golang/src/image/jpeg
Nigel Tao e7aeeae0c8 image/jpeg: ignore garbage bytes before a RST marker
Well-formed JPEG images will not have garbage bytes. However, for
corrupted JPEG images, the RST (restart) mechanism is specifically
designed so that a decoder can re-synchronize to an upcoming restartable
MCU (Minimum Coded Unit, e.g. 16x16 block of pixels) boundary and resume
decoding. Even if the resultant image isn't perfect, a 98%-good image is
better than a fatal error.

Every JPEG marker is encoded in two bytes, the first of which is 0xFF.
There are 8 possible RST markers, cycling as "0xFF 0xD0", "0xFF 0xD1",
..., "0xFF 0xD7". Suppose that, our decoder is expecting "0xFF 0xD1".

Before this commit, Go's image/jpeg package would accept only two
possible inputs: a well-formed "0xFF 0xD1" or one very specific pattern
of spec non-compliance, "0xFF 0x00 0xFF 0xD1".

After this commit, it is more lenient, similar to libjpeg's jdmarker.c's
next_marker function.
2dfe6c0fe9/jdmarker.c (L892-L935)

The new testdata file was created by:

$ convert video-001.png a.ppm
$ cjpeg -restart 2 a.ppm > video-001.restart2.jpeg
$ rm a.ppm

Fixes #40130

Change-Id: Ic598a5f489f110d6bd63e0735200fb6acac3aca3
Reviewed-on: https://go-review.googlesource.com/c/go/+/580755
Reviewed-by: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Joedian Reid <joedian@google.com>
2024-04-25 00:46:29 +00:00
..
dct_test.go image/jpeg: use strings.Builder 2022-09-06 15:49:30 +00:00
fdct.go image/jpeg: reduce bound checks from idct and fdct 2019-04-02 23:18:37 +00:00
fuzz_test.go image/jpeg, image/png: replace Fatal with Error in tests 2023-08-03 15:56:27 +00:00
huffman.go image: use built-in clear to simplify code 2024-03-11 17:08:05 +00:00
idct.go image/jpeg: reduce bound checks from idct and fdct 2019-04-02 23:18:37 +00:00
reader.go image: add available godoc link 2023-10-19 12:02:45 +00:00
reader_test.go image/jpeg: ignore garbage bytes before a RST marker 2024-04-25 00:46:29 +00:00
scan.go image/jpeg: ignore garbage bytes before a RST marker 2024-04-25 00:46:29 +00:00
writer.go image: add available godoc link 2023-10-19 12:02:45 +00:00
writer_test.go image/jpeg: use strings.Builder 2022-09-06 15:49:30 +00:00