Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

thumbnail: Show the first few frames of large animated images.

Alex Vandiver8bd8a33dd27c
diff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.py
index 52aba7dcf88..52a42fd0331 100644
--- a/zerver/lib/thumbnail.py
+++ b/zerver/lib/thumbnail.py
@@ -22,8 +22,11 @@ DEFAULT_AVATAR_SIZE = 100
MEDIUM_AVATAR_SIZE = 500
DEFAULT_EMOJI_SIZE = 64
-# We refuse to deal with any image whose total pixelcount exceeds this.
+# We refuse to deal with any image whose total pixelcount exceeds
+# this. This is chosen to be around a quarter of a gigabyte for a
+# 24-bit (3bpp) image.
IMAGE_BOMB_TOTAL_PIXELS = 90000000
+IMAGE_MAX_ANIMATED_PIXELS = IMAGE_BOMB_TOTAL_PIXELS / 3
# Reject emoji which, after resizing, have stills larger than this
MAX_EMOJI_GIF_FILE_SIZE_BYTES = 128 * 1024 # 128 kb
@@ -146,7 +149,9 @@ class BadImageError(JsonableError):
@contextmanager
-def libvips_check_image(image_data: bytes | pyvips.Source) -> Iterator[pyvips.Image]:
+def libvips_check_image(
+ image_data: bytes | pyvips.Source, truncated_animation: bool = False
+) -> Iterator[pyvips.Image]:
# The primary goal of this is to verify that the image is valid,
# and raise BadImageError otherwise. The yielded `source_image`
# may be ignored, since calling `thumbnail_buffer` is faster than
@@ -161,11 +166,34 @@ def libvips_check_image(image_data: bytes | pyvips.Source) -> Iterator[pyvips.Im
except pyvips.Error:
raise BadImageError(_("Could not decode image; did you upload an image file?"))
- if (
- source_image.width * source_image.height * source_image.get_n_pages()
- > IMAGE_BOMB_TOTAL_PIXELS
- ):
- raise BadImageError(_("Image size exceeds limit."))
+ if not truncated_animation:
+ # For places where we do not truncate animations (e.g. emoji,
+ # where the original is never served to clients, so we must
+ # preserve the full animation) we count total pixels across
+ # all frames for the limit.
+ if (
+ source_image.width * source_image.height * source_image.get_n_pages()
+ > IMAGE_BOMB_TOTAL_PIXELS
+ ):
+ raise BadImageError(_("Image size exceeds limit."))
+ else:
+ # When thumbnailing image uploads, we truncate thumbnailed
+ # animations, so we have different checks for animated vs
+ # still images.
+ if source_image.get_n_pages() == 1:
+ if source_image.width * source_image.height > IMAGE_BOMB_TOTAL_PIXELS:
+ raise BadImageError(_("Image size exceeds limit."))
+
+ else:
+ # For animated images, we have an additional limit -- we
+ # want to be able to render at least 3 frames, and spend
+ # no more than 1/3 of that IMAGE_BOMB_TOTAL_PIXELS budget
+ # in doing so.
+ if (
+ source_image.width * source_image.height * min(3, source_image.get_n_pages())
+ > IMAGE_MAX_ANIMATED_PIXELS
+ ):
+ raise BadImageError(_("Image size exceeds limit."))
try:
yield source_image
@@ -320,7 +348,7 @@ def maybe_thumbnail(
return None
try:
# This only attempts to read the header, not the full image content
- with libvips_check_image(content) as image:
+ with libvips_check_image(content, truncated_animation=True) as image:
# "original_width_px" and "original_height_px" here are
# _as rendered_, after applying the orientation
# information which the image may contain.
@@ -548,8 +576,9 @@ def rewrite_thumbnailed_images(
image_tag["data-transcoded-image"] = str(image_data.transcoded_image)
if changed:
- return parsed_message.encode(
- formatter=html_formatter
- ).decode().strip(), remaining_thumbnails
+ return (
+ parsed_message.encode(formatter=html_formatter).decode().strip(),
+ remaining_thumbnails,
+ )
else:
return None, remaining_thumbnails
diff --git a/zerver/tests/images/animated_many_frames.gif b/zerver/tests/images/animated_many_frames.gif
new file mode 100644
index 00000000000..45c8f1a90aa
Binary files /dev/null and b/zerver/tests/images/animated_many_frames.gif differ
diff --git a/zerver/tests/test_thumbnail.py b/zerver/tests/test_thumbnail.py
index c8ff92c25c2..165df764970 100644
--- a/zerver/tests/test_thumbnail.py
+++ b/zerver/tests/test_thumbnail.py
@@ -167,15 +167,19 @@ class ThumbnailEmojiTest(ZulipTestCase):
def test_resize_too_many_pixels(self) -> None:
"""An image file with too many pixels is not resized"""
- with patch("zerver.lib.thumbnail.IMAGE_BOMB_TOTAL_PIXELS", 100):
+ bomb_img_data = read_test_image_file("bomb.png")
+ with self.assertRaises(BadImageError):
+ resize_emoji(bomb_img_data, "bomb.png", size=50)
+
+ def test_animated_resize_too_many_pixels(self) -> None:
+ with patch("zerver.lib.thumbnail.IMAGE_BOMB_TOTAL_PIXELS", 100000):
+ # This image is 256 * 256 with 3 frames, so 196k pixels.
+ # When resizing emoji, we want to show the whole
+ # animation, so every pixel on every frame counts
animated_large_img_data = read_test_image_file("animated_large_img.gif")
with self.assertRaises(BadImageError):
resize_emoji(animated_large_img_data, "animated_large_img.gif", size=50)
- bomb_img_data = read_test_image_file("bomb.png")
- with self.assertRaises(BadImageError):
- resize_emoji(bomb_img_data, "bomb.png", size=50)
-
def test_resize_still_gif(self) -> None:
"""A non-animated square emoji resize"""
still_large_img_data = read_test_image_file("still_large_img.gif")
@@ -365,6 +369,7 @@ class TestStoreThumbnail(ZulipTestCase):
with self.thumbnail_formats(ThumbnailFormat("webp", 100, 75, animated=True)):
self.assertEqual(ensure_thumbnails(image_attachment, "image/webp"), 0)
+ self.assert_length(image_attachment.thumbnail_metadata, 1)
with self.thumbnail_formats(ThumbnailFormat("webp", 150, 100, opts="Q=90", animated=False)):
self.assertEqual(ensure_thumbnails(image_attachment, "image/webp"), 1)
@@ -401,6 +406,72 @@ class TestStoreThumbnail(ZulipTestCase):
),
)
+ def test_animated_resize_partial_frames(self) -> None:
+ self.login_user(self.example_user("hamlet"))
+ with self.thumbnail_formats(ThumbnailFormat("webp", 100, 75, animated=True)):
+ with (
+ patch("zerver.lib.thumbnail.IMAGE_MAX_ANIMATED_PIXELS", 100000),
+ patch("zerver.worker.thumbnail.IMAGE_MAX_ANIMATED_PIXELS", 100000),
+ get_test_image_file("animated_many_frames.gif") as image_file,
+ ):
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.assert_json_success(
+ self.client_post("/json/user_uploads", {"file": image_file})
+ )
+ path_id = re.sub(r"/user_uploads/", "", response["url"])
+ self.assertEqual(Attachment.objects.filter(path_id=path_id).count(), 1)
+
+ image_attachment = ImageAttachment.objects.get(path_id=path_id)
+ self.assertEqual(image_attachment.original_height_px, 100)
+ self.assertEqual(image_attachment.original_width_px, 200)
+ # Metadata shows the total frame count
+ self.assertEqual(image_attachment.frames, 69)
+ # Exit the captureOnCommitCallbacks block and run thumbnailing
+ with BytesIO() as fh:
+ save_attachment_contents(f"thumbnail/{path_id}/100x75-anim.webp", fh)
+ thumbnailed_bytes = fh.getvalue()
+ with pyvips.Image.new_from_buffer(thumbnailed_bytes, "") as thumbnailed_image:
+ self.assertEqual(thumbnailed_image.get("vips-loader"), "webpload_buffer")
+ self.assertEqual(thumbnailed_image.width, 100)
+ self.assertEqual(thumbnailed_image.height, 50)
+ # IMAGE_MAX_ANIMATED_PIXELS means that we only
+ # thumbnail the first 5 frames (100k / (100 * 200))
+ self.assertEqual(thumbnailed_image.get_n_pages(), 5)
+
+ # If we have higher IMAGE_MAX_ANIMATED_PIXELS then we thumbnail all frames
+ with (
+ patch("zerver.lib.thumbnail.IMAGE_MAX_ANIMATED_PIXELS", 100 * 200 * 70),
+ patch("zerver.worker.thumbnail.IMAGE_MAX_ANIMATED_PIXELS", 100 * 200 * 70),
+ get_test_image_file("animated_many_frames.gif") as image_file,
+ ):
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.assert_json_success(
+ self.client_post("/json/user_uploads", {"file": image_file})
+ )
+ path_id = re.sub(r"/user_uploads/", "", response["url"])
+ self.assertEqual(Attachment.objects.filter(path_id=path_id).count(), 1)
+ self.assertEqual(ImageAttachment.objects.filter(path_id=path_id).count(), 1)
+ with BytesIO() as fh:
+ save_attachment_contents(f"thumbnail/{path_id}/100x75-anim.webp", fh)
+ thumbnailed_bytes = fh.getvalue()
+ with pyvips.Image.new_from_buffer(thumbnailed_bytes, "") as thumbnailed_image:
+ self.assertEqual(thumbnailed_image.get_n_pages(), 69)
+
+ # If IMAGE_MAX_ANIMATED_PIXELS isn't enough to be able to
+ # fit 3 frames in, then we don't display a thumbnail at
+ # all.
+ with (
+ patch("zerver.lib.thumbnail.IMAGE_MAX_ANIMATED_PIXELS", 100 * 200),
+ patch("zerver.worker.thumbnail.IMAGE_MAX_ANIMATED_PIXELS", 100 * 200),
+ get_test_image_file("animated_many_frames.gif") as image_file,
+ ):
+ response = self.assert_json_success(
+ self.client_post("/json/user_uploads", {"file": image_file})
+ )
+ path_id = re.sub(r"/user_uploads/", "", response["url"])
+ self.assertEqual(Attachment.objects.filter(path_id=path_id).count(), 1)
+ self.assertEqual(ImageAttachment.objects.filter(path_id=path_id).count(), 0)
+
def test_image_orientation(self) -> None:
self.login_user(self.example_user("hamlet"))
@@ -468,20 +539,37 @@ class TestStoreThumbnail(ZulipTestCase):
self.assertFalse(ImageAttachment.objects.filter(path_id=path_id).exists())
def test_big_animated_upload(self) -> None:
- # We also decline to process a small but many-frame image
+ # We support uploads of very large frame-count animations --
+ # we just do not include all of their frames in the thumbnail
+ # preview
self.login_user(self.example_user("hamlet"))
- with get_test_image_file("img.gif") as image_file:
- with patch.object(pyvips.Image, "new_from_buffer") as mock_from_buffer:
- mock_from_buffer.return_value.width = 100
- mock_from_buffer.return_value.height = 100
- mock_from_buffer.return_value.get_n_pages.return_value = 1000000
- response = self.assert_json_success(
- self.client_post("/json/user_uploads", {"file": image_file})
- )
+ with (
+ get_test_image_file("img.gif") as image_file,
+ patch.object(pyvips.Image, "new_from_buffer") as mock_from_buffer,
+ patch("zerver.lib.thumbnail.IMAGE_MAX_ANIMATED_PIXELS", 100000),
+ ):
+ # A 1000x1000 image has too many pixels to show three frames, so we don't include it
+ mock_from_buffer.return_value.width = 1000
+ mock_from_buffer.return_value.height = 1000
+ mock_from_buffer.return_value.get_n_pages.return_value = 1000000
+ response = self.assert_json_success(
+ self.client_post("/json/user_uploads", {"file": image_file})
+ )
path_id = re.sub(r"/user_uploads/", "", response["url"])
self.assertTrue(Attachment.objects.filter(path_id=path_id).exists())
self.assertFalse(ImageAttachment.objects.filter(path_id=path_id).exists())
+ # A 100x100 image, we'll thumbnail the first few frames of.
+ mock_from_buffer.return_value.width = 100
+ mock_from_buffer.return_value.height = 100
+ mock_from_buffer.return_value.get_n_pages.return_value = 1000000
+ response = self.assert_json_success(
+ self.client_post("/json/user_uploads", {"file": image_file})
+ )
+ path_id = re.sub(r"/user_uploads/", "", response["url"])
+ self.assertTrue(Attachment.objects.filter(path_id=path_id).exists())
+ self.assertTrue(ImageAttachment.objects.filter(path_id=path_id).exists())
+
def test_bad_upload(self) -> None:
assert settings.LOCAL_FILES_DIR
hamlet = self.example_user("hamlet")
diff --git a/zerver/worker/thumbnail.py b/zerver/worker/thumbnail.py
index aae4efde7ee..2b216eee5a9 100644
--- a/zerver/worker/thumbnail.py
+++ b/zerver/worker/thumbnail.py
@@ -12,6 +12,7 @@ from typing_extensions import override
from zerver.actions.message_edit import do_update_embedded_data
from zerver.lib.mime_types import guess_type
from zerver.lib.thumbnail import (
+ IMAGE_MAX_ANIMATED_PIXELS,
MarkdownImageMetadata,
StoredThumbnailFormat,
get_default_thumbnail_url,
@@ -95,7 +96,16 @@ def ensure_thumbnails(
# one of them if we're outputting to a static format,
# otherwise we load them all.
if thumbnail_format.animated:
- load_opts = "n=-1"
+ # We compute how many frames to thumbnail based on
+ # how many frames it will take us to get to
+ # IMAGE_MAX_ANIMATED_PIXELS
+ pixels_per_frame = (
+ image_attachment.original_width_px * image_attachment.original_height_px
+ )
+ if pixels_per_frame * image_attachment.frames < IMAGE_MAX_ANIMATED_PIXELS:
+ load_opts = "n=-1"
+ else:
+ load_opts = f"n={IMAGE_MAX_ANIMATED_PIXELS // pixels_per_frame}"
else:
load_opts = "n=1"
resized = pyvips.Image.thumbnail_buffer(