From 24155efd3427ac6a0baa6efb16d1dfa34ecaeec9 Mon Sep 17 00:00:00 2001 From: shrey kharbanda Date: Wed, 23 Sep 2026 15:47:11 +0000 Subject: [PATCH] fix(images): keep JPEG marker alignment after a fill byte before a large segment --- litellm/images/utils.py | 5 ++++- tests/test_litellm/images/test_image_edit_utils.py | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/litellm/images/utils.py b/litellm/images/utils.py index 613020de899..b5e415dd409 100644 --- a/litellm/images/utils.py +++ b/litellm/images/utils.py @@ -85,7 +85,10 @@ def _jpeg_sof_dimensions(stream: IO[bytes], start: int, offset: int, segments_le if len(marker) < 4 or marker[0] != 0xFF: return None if marker[1] == 0xFF: - segment_offset += 1 + int(marker[2] == 0xFF) + int(marker[3] == 0xFF) + run = 1 # rebind-ok: consecutive fill bytes in this window + while run < 3 and marker[run + 1] == 0xFF: + run += 1 + segment_offset += run continue if marker[1] in _JPEG_SOF_MARKERS: sof = stream.read(_JPEG_SOF_PAYLOAD_SIZE) diff --git a/tests/test_litellm/images/test_image_edit_utils.py b/tests/test_litellm/images/test_image_edit_utils.py index a97766d34d3..802b9b9b0e1 100644 --- a/tests/test_litellm/images/test_image_edit_utils.py +++ b/tests/test_litellm/images/test_image_edit_utils.py @@ -102,6 +102,9 @@ SEGMENTS_1030_JPEG: Final = ( JPEG_SOI + _jpeg_segment(JPEG_APP0, bytes(4)) * 1030 + _jpeg_sof_segment(JPEG_SOF0_MARKER, 320, 200) ) FILL_BYTES_JPEG: Final = JPEG_SOI + b"\xff" * 1100 + _jpeg_sof_segment(JPEG_SOF0_MARKER, 320, 200) +FILL_BEFORE_LARGE_SEGMENT_JPEG: Final = ( + JPEG_SOI + b"\xff" + _jpeg_segment(JPEG_APP2_MARKER, bytes(0xFEFE)) + _jpeg_sof_segment(JPEG_SOF0_MARKER, 640, 480) +) OVERSIZED_HEADER_JPEG: Final = ( JPEG_SOI + _jpeg_segment(JPEG_APP0, bytes(65533)) * 260 + _jpeg_sof_segment(JPEG_SOF0_MARKER, 320, 200) ) @@ -133,6 +136,7 @@ def _bmp(width: int, height: int) -> bytes: pytest.param(SEGMENTS_300_JPEG, (320, 200), id="jpeg-300-app2-segments"), pytest.param(SEGMENTS_1030_JPEG, None, id="jpeg-more-than-1024-segments"), pytest.param(FILL_BYTES_JPEG, (320, 200), id="jpeg-1100-fill-bytes-before-sof"), + pytest.param(FILL_BEFORE_LARGE_SEGMENT_JPEG, (640, 480), id="jpeg-fill-before-large-segment"), pytest.param(OVERSIZED_HEADER_JPEG, None, id="jpeg-sof-beyond-16mib"), pytest.param(PROGRESSIVE_JPEG, (111, 55), id="jpeg-sof2-progressive"), pytest.param(DHT_JPEG, (400, 300), id="jpeg-dht-skipped-before-sof0"),