1 /*
2  * Copyright (C) 2006 Apple Computer, Inc.
3  *
4  * Portions are Copyright (C) 2001-6 mozilla.org
5  *
6  * Other contributors:
7  *   Stuart Parmenter <stuart@mozilla.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  *
23  * Alternatively, the contents of this file may be used under the terms
24  * of either the Mozilla Public License Version 1.1, found at
25  * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
26  * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
27  * (the "GPL"), in which case the provisions of the MPL or the GPL are
28  * applicable instead of those above.  If you wish to allow use of your
29  * version of this file only under the terms of one of those two
30  * licenses (the MPL or the GPL) and not to allow others to use your
31  * version of this file under the LGPL, indicate your decision by
32  * deletingthe provisions above and replace them with the notice and
33  * other provisions required by the MPL or the GPL, as the case may be.
34  * If you do not delete the provisions above, a recipient may use your
35  * version of this file under any of the LGPL, the MPL or the GPL.
36  */
37 
38 #include "third_party/blink/renderer/platform/image-decoders/jpeg/jpeg_image_decoder.h"
39 
40 #include <limits>
41 #include <memory>
42 
43 #include "base/numerics/checked_math.h"
44 #include "build/build_config.h"
45 #include "third_party/blink/renderer/platform/graphics/bitmap_image_metrics.h"
46 #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
47 #include "third_party/blink/renderer/platform/runtime_enabled_features.h"
48 
49 extern "C" {
50 #include <stdio.h>  // jpeglib.h needs stdio FILE.
51 #include "jpeglib.h"
52 #include "iccjpeg.h"
53 #include <setjmp.h>
54 }
55 
56 #if defined(JCS_ALPHA_EXTENSIONS)
57 #define TURBO_JPEG_RGB_SWIZZLE
58 #if SK_PMCOLOR_BYTE_ORDER(R, G, B, A)
rgbOutputColorSpace()59 inline J_COLOR_SPACE rgbOutputColorSpace() {
60   return JCS_EXT_RGBA;
61 }
62 #elif SK_PMCOLOR_BYTE_ORDER(B, G, R, A)
rgbOutputColorSpace()63 inline J_COLOR_SPACE rgbOutputColorSpace() {
64   return JCS_EXT_BGRA;
65 }
66 #elif SK_PMCOLOR_BYTE_ORDER(A, R, G, B)
rgbOutputColorSpace()67 inline J_COLOR_SPACE rgbOutputColorSpace() {
68   return JCS_EXT_ARGB;
69 }
70 #elif SK_PMCOLOR_BYTE_ORDER(A, B, G, R)
rgbOutputColorSpace()71 inline J_COLOR_SPACE rgbOutputColorSpace() {
72   return JCS_EXT_ABGR;
73 }
74 #else
75 #error Component order not supported by libjpeg_turbo
76 #endif
turboSwizzled(J_COLOR_SPACE colorSpace)77 inline bool turboSwizzled(J_COLOR_SPACE colorSpace) {
78   return colorSpace == JCS_EXT_RGBA || colorSpace == JCS_EXT_BGRA ||
79     colorSpace == JCS_EXT_ABGR || colorSpace == JCS_EXT_ARGB;
80 }
81 #else
rgbOutputColorSpace()82 inline J_COLOR_SPACE rgbOutputColorSpace() {
83   return JCS_RGB;
84 }
85 #endif
86 
87 namespace {
88 
89 const int exifMarker = JPEG_APP0 + 1;
90 
91 // JPEG only supports a denominator of 8.
92 const unsigned g_scale_denominator = 8;
93 
94 // Extracts the YUV subsampling format of an image given |info| which is assumed
95 // to have gone through a jpeg_read_header() call.
YuvSubsampling(const jpeg_decompress_struct & info)96 cc::YUVSubsampling YuvSubsampling(const jpeg_decompress_struct& info) {
97   if (info.jpeg_color_space == JCS_YCbCr && info.num_components == 3 &&
98       info.comp_info && info.comp_info[1].h_samp_factor == 1 &&
99       info.comp_info[1].v_samp_factor == 1 &&
100       info.comp_info[2].h_samp_factor == 1 &&
101       info.comp_info[2].v_samp_factor == 1) {
102     const int h = info.comp_info[0].h_samp_factor;
103     const int v = info.comp_info[0].v_samp_factor;
104     if (v == 1) {
105       switch (h) {
106         case 1:
107           return cc::YUVSubsampling::k444;
108         case 2:
109           return cc::YUVSubsampling::k422;
110         case 4:
111           return cc::YUVSubsampling::k411;
112       }
113     } else if (v == 2) {
114       switch (h) {
115         case 1:
116           return cc::YUVSubsampling::k440;
117         case 2:
118           return cc::YUVSubsampling::k420;
119         case 4:
120           return cc::YUVSubsampling::k410;
121       }
122     }
123   }
124   return cc::YUVSubsampling::kUnknown;
125 }
126 
127 // Extracts the JPEG color space of an image for UMA purposes given |info| which
128 // is assumed to have gone through a jpeg_read_header(). When the color space is
129 // YCbCr, we also extract the chroma subsampling. The caveat is that the
130 // extracted color space is really libjpeg_turbo's guess. According to
131 // libjpeg.txt, "[t]he JPEG color space, unfortunately, is something of a guess
132 // since the JPEG standard proper does not provide a way to record it. In
133 // practice most files adhere to the JFIF or Adobe conventions, and the decoder
134 // will recognize these correctly."
ExtractUMAJpegColorSpace(const jpeg_decompress_struct & info)135 blink::BitmapImageMetrics::JpegColorSpace ExtractUMAJpegColorSpace(
136     const jpeg_decompress_struct& info) {
137   switch (info.jpeg_color_space) {
138     case JCS_GRAYSCALE:
139       return blink::BitmapImageMetrics::JpegColorSpace::kGrayscale;
140     case JCS_RGB:
141       return blink::BitmapImageMetrics::JpegColorSpace::kRGB;
142     case JCS_CMYK:
143       return blink::BitmapImageMetrics::JpegColorSpace::kCMYK;
144     case JCS_YCCK:
145       return blink::BitmapImageMetrics::JpegColorSpace::kYCCK;
146     case JCS_YCbCr:
147       switch (YuvSubsampling(info)) {
148         case cc::YUVSubsampling::k444:
149           return blink::BitmapImageMetrics::JpegColorSpace::kYCbCr444;
150         case cc::YUVSubsampling::k422:
151           return blink::BitmapImageMetrics::JpegColorSpace::kYCbCr422;
152         case cc::YUVSubsampling::k411:
153           return blink::BitmapImageMetrics::JpegColorSpace::kYCbCr411;
154         case cc::YUVSubsampling::k440:
155           return blink::BitmapImageMetrics::JpegColorSpace::kYCbCr440;
156         case cc::YUVSubsampling::k420:
157           return blink::BitmapImageMetrics::JpegColorSpace::kYCbCr420;
158         case cc::YUVSubsampling::k410:
159           return blink::BitmapImageMetrics::JpegColorSpace::kYCbCr410;
160         case cc::YUVSubsampling::kUnknown:
161           return blink::BitmapImageMetrics::JpegColorSpace::kYCbCrOther;
162       }
163       NOTREACHED();
164     default:
165       return blink::BitmapImageMetrics::JpegColorSpace::kUnknown;
166   }
167 }
168 
169 // Rounds |size| to the smallest multiple of |alignment| that is greater than or
170 // equal to |size|.
171 // Note that base::bits::Align is not used here because the alignment is not
172 // guaranteed to be a power of two.
Align(int size,int alignment)173 int Align(int size, int alignment) {
174   // Width and height are 16 bits for a JPEG (i.e. < 65536) and the maximum
175   // size of a JPEG MCU in either dimension is 8 * 4 == 32.
176   DCHECK_GE(size, 0);
177   DCHECK_LT(size, 1 << 16);
178   DCHECK_GT(alignment, 0);
179   DCHECK_LE(alignment, 32);
180 
181   if (size % alignment == 0)
182     return size;
183 
184   return ((size + alignment) / alignment) * alignment;
185 }
186 
187 }  // namespace
188 
189 namespace blink {
190 
191 struct decoder_error_mgr {
192   DISALLOW_NEW();
193   struct jpeg_error_mgr pub;  // "public" fields for IJG library
194   int num_corrupt_warnings;   // Counts corrupt warning messages
195   jmp_buf setjmp_buffer;      // For handling catastropic errors
196 };
197 
198 struct decoder_source_mgr {
199   DISALLOW_NEW();
200   struct jpeg_source_mgr pub;  // "public" fields for IJG library
201   JPEGImageReader* reader;
202 };
203 
204 enum jstate {
205   JPEG_HEADER,  // Reading JFIF headers
206   JPEG_START_DECOMPRESS,
207   JPEG_DECOMPRESS_PROGRESSIVE,  // Output progressive pixels
208   JPEG_DECOMPRESS_SEQUENTIAL,   // Output sequential pixels
209   JPEG_DONE
210 };
211 
212 void init_source(j_decompress_ptr jd);
213 boolean fill_input_buffer(j_decompress_ptr jd);
214 void skip_input_data(j_decompress_ptr jd, long num_bytes);
215 void term_source(j_decompress_ptr jd);
216 void error_exit(j_common_ptr cinfo);
217 void emit_message(j_common_ptr cinfo, int msg_level);
218 
ReadUint16(JOCTET * data,bool is_big_endian)219 static unsigned ReadUint16(JOCTET* data, bool is_big_endian) {
220   if (is_big_endian)
221     return (GETJOCTET(data[0]) << 8) | GETJOCTET(data[1]);
222   return (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
223 }
224 
ReadUint32(JOCTET * data,bool is_big_endian)225 static unsigned ReadUint32(JOCTET* data, bool is_big_endian) {
226   if (is_big_endian)
227     return (GETJOCTET(data[0]) << 24) | (GETJOCTET(data[1]) << 16) |
228            (GETJOCTET(data[2]) << 8) | GETJOCTET(data[3]);
229   return (GETJOCTET(data[3]) << 24) | (GETJOCTET(data[2]) << 16) |
230          (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
231 }
232 
CheckExifHeader(jpeg_saved_marker_ptr marker,bool & is_big_endian,unsigned & ifd_offset)233 static bool CheckExifHeader(jpeg_saved_marker_ptr marker,
234                             bool& is_big_endian,
235                             unsigned& ifd_offset) {
236   // For exif data, the APP1 block is followed by 'E', 'x', 'i', 'f', '\0',
237   // then a fill byte, and then a tiff file that contains the metadata.
238   // A tiff file starts with 'I', 'I' (intel / little endian byte order) or
239   // 'M', 'M' (motorola / big endian byte order), followed by (uint16_t)42,
240   // followed by an uint32_t with the offset to the tag block, relative to the
241   // tiff file start.
242   const unsigned kExifHeaderSize = 14;
243   if (!(marker->marker == exifMarker &&
244         marker->data_length >= kExifHeaderSize && marker->data[0] == 'E' &&
245         marker->data[1] == 'x' && marker->data[2] == 'i' &&
246         marker->data[3] == 'f' &&
247         marker->data[4] == '\0'
248         // data[5] is a fill byte
249         && ((marker->data[6] == 'I' && marker->data[7] == 'I') ||
250             (marker->data[6] == 'M' && marker->data[7] == 'M'))))
251     return false;
252 
253   is_big_endian = marker->data[6] == 'M';
254   if (ReadUint16(marker->data + 8, is_big_endian) != 42)
255     return false;
256 
257   ifd_offset = ReadUint32(marker->data + 10, is_big_endian);
258   return true;
259 }
260 
ReadImageOrientation(jpeg_decompress_struct * info)261 static ImageOrientation ReadImageOrientation(jpeg_decompress_struct* info) {
262   // The JPEG decoder looks at EXIF metadata.
263   // FIXME: Possibly implement XMP and IPTC support.
264   const unsigned kOrientationTag = 0x112;
265   const unsigned kShortType = 3;
266   for (jpeg_saved_marker_ptr marker = info->marker_list; marker;
267        marker = marker->next) {
268     bool is_big_endian;
269     unsigned ifd_offset;
270     if (!CheckExifHeader(marker, is_big_endian, ifd_offset))
271       continue;
272     const unsigned kOffsetToTiffData =
273         6;  // Account for 'Exif\0<fill byte>' header.
274     if (marker->data_length < kOffsetToTiffData ||
275         ifd_offset >= marker->data_length - kOffsetToTiffData)
276       continue;
277     ifd_offset += kOffsetToTiffData;
278 
279     // The jpeg exif container format contains a tiff block for metadata.
280     // A tiff image file directory (ifd) consists of a uint16_t describing
281     // the number of ifd entries, followed by that many entries.
282     // When touching this code, it's useful to look at the tiff spec:
283     // http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
284     JOCTET* ifd = marker->data + ifd_offset;
285     JOCTET* end = marker->data + marker->data_length;
286     if (end - ifd < 2)
287       continue;
288     unsigned tag_count = ReadUint16(ifd, is_big_endian);
289     ifd += 2;  // Skip over the uint16 that was just read.
290 
291     // Every ifd entry is 2 bytes of tag, 2 bytes of contents datatype,
292     // 4 bytes of number-of-elements, and 4 bytes of either offset to the
293     // tag data, or if the data is small enough, the inlined data itself.
294     const int kIfdEntrySize = 12;
295     for (unsigned i = 0; i < tag_count && end - ifd >= kIfdEntrySize;
296          ++i, ifd += kIfdEntrySize) {
297       unsigned tag = ReadUint16(ifd, is_big_endian);
298       unsigned type = ReadUint16(ifd + 2, is_big_endian);
299       unsigned count = ReadUint32(ifd + 4, is_big_endian);
300       if (tag == kOrientationTag && type == kShortType && count == 1)
301         return ImageOrientation::FromEXIFValue(
302             ReadUint16(ifd + 8, is_big_endian));
303     }
304   }
305 
306   return ImageOrientation();
307 }
308 
ComputeYUVSize(const jpeg_decompress_struct * info,int component)309 static IntSize ComputeYUVSize(const jpeg_decompress_struct* info,
310                               int component) {
311   return IntSize(info->comp_info[component].downsampled_width,
312                  info->comp_info[component].downsampled_height);
313 }
314 
ComputeYUVWidthBytes(const jpeg_decompress_struct * info,int component)315 static size_t ComputeYUVWidthBytes(const jpeg_decompress_struct* info,
316                                    int component) {
317   return info->comp_info[component].width_in_blocks * DCTSIZE;
318 }
319 
ProgressMonitor(j_common_ptr info)320 static void ProgressMonitor(j_common_ptr info) {
321   int scan = ((j_decompress_ptr)info)->input_scan_number;
322   // Progressive images with a very large number of scans can cause the
323   // decoder to hang.  Here we use the progress monitor to abort on
324   // a very large number of scans.  100 is arbitrary, but much larger
325   // than the number of scans we might expect in a normal image.
326   if (scan >= 100) {
327     error_exit(info);
328   }
329 }
330 
331 class JPEGImageReader final {
332   USING_FAST_MALLOC(JPEGImageReader);
333 
334  public:
JPEGImageReader(JPEGImageDecoder * decoder,size_t initial_offset)335   JPEGImageReader(JPEGImageDecoder* decoder, size_t initial_offset)
336       : decoder_(decoder),
337         needs_restart_(false),
338         restart_position_(initial_offset),
339         next_read_position_(initial_offset),
340         last_set_byte_(nullptr),
341         state_(JPEG_HEADER),
342         samples_(nullptr) {
343     memset(&info_, 0, sizeof(jpeg_decompress_struct));
344 
345     // Set up the normal JPEG error routines, then override error_exit.
346     info_.err = jpeg_std_error(&err_.pub);
347     err_.pub.error_exit = error_exit;
348 
349     // Allocate and initialize JPEG decompression object.
350     jpeg_create_decompress(&info_);
351 
352     // Initialize source manager.
353     memset(&src_, 0, sizeof(decoder_source_mgr));
354     info_.src = reinterpret_cast_ptr<jpeg_source_mgr*>(&src_);
355 
356     // Set up callback functions.
357     src_.pub.init_source = init_source;
358     src_.pub.fill_input_buffer = fill_input_buffer;
359     src_.pub.skip_input_data = skip_input_data;
360     src_.pub.resync_to_restart = jpeg_resync_to_restart;
361     src_.pub.term_source = term_source;
362     src_.reader = this;
363 
364     // Set up a progress monitor.
365     info_.progress = &progress_mgr_;
366     progress_mgr_.progress_monitor = ProgressMonitor;
367 
368     // Retain ICC color profile markers for color management.
369     setup_read_icc_profile(&info_);
370 
371     // Keep APP1 blocks, for obtaining exif data.
372     jpeg_save_markers(&info_, exifMarker, 0xFFFF);
373   }
374 
~JPEGImageReader()375   ~JPEGImageReader() { jpeg_destroy_decompress(&info_); }
376 
SkipBytes(long num_bytes)377   void SkipBytes(long num_bytes) {
378     if (num_bytes <= 0)
379       return;
380 
381     size_t bytes_to_skip = static_cast<size_t>(num_bytes);
382 
383     if (bytes_to_skip < info_.src->bytes_in_buffer) {
384       // The next byte needed is in the buffer. Move to it.
385       info_.src->bytes_in_buffer -= bytes_to_skip;
386       info_.src->next_input_byte += bytes_to_skip;
387     } else {
388       // Move beyond the buffer and empty it.
389       next_read_position_ =
390           next_read_position_ + bytes_to_skip - info_.src->bytes_in_buffer;
391       info_.src->bytes_in_buffer = 0;
392       info_.src->next_input_byte = nullptr;
393     }
394 
395     // This is a valid restart position.
396     restart_position_ = next_read_position_ - info_.src->bytes_in_buffer;
397     // We updated |next_input_byte|, so we need to update |last_byte_set_|
398     // so we know not to update |restart_position_| again.
399     last_set_byte_ = info_.src->next_input_byte;
400   }
401 
FillBuffer()402   bool FillBuffer() {
403     if (needs_restart_) {
404       needs_restart_ = false;
405       next_read_position_ = restart_position_;
406     } else {
407       UpdateRestartPosition();
408     }
409 
410     const char* segment;
411     const size_t bytes = data_->GetSomeData(segment, next_read_position_);
412     if (bytes == 0) {
413       // We had to suspend. When we resume, we will need to start from the
414       // restart position.
415       needs_restart_ = true;
416       ClearBuffer();
417       return false;
418     }
419 
420     next_read_position_ += bytes;
421     info_.src->bytes_in_buffer = bytes;
422     const JOCTET* next_byte = reinterpret_cast_ptr<const JOCTET*>(segment);
423     info_.src->next_input_byte = next_byte;
424     last_set_byte_ = next_byte;
425     return true;
426   }
427 
SetData(SegmentReader * data)428   void SetData(SegmentReader* data) {
429     if (data_.get() == data)
430       return;
431 
432     data_ = data;
433 
434     // If a restart is needed, the next call to fillBuffer will read from the
435     // new SegmentReader.
436     if (needs_restart_)
437       return;
438 
439     // Otherwise, empty the buffer, and leave the position the same, so
440     // FillBuffer continues reading from the same position in the new
441     // SegmentReader.
442     next_read_position_ -= info_.src->bytes_in_buffer;
443     ClearBuffer();
444   }
445 
ShouldDecodeToOriginalSize() const446   bool ShouldDecodeToOriginalSize() const {
447     // We should decode only to original size if either dimension cannot fit a
448     // whole number of MCUs.
449     const int max_h_samp_factor = info_.max_h_samp_factor;
450     const int max_v_samp_factor = info_.max_v_samp_factor;
451     DCHECK_GE(max_h_samp_factor, 1);
452     DCHECK_GE(max_v_samp_factor, 1);
453     DCHECK_LE(max_h_samp_factor, 4);
454     DCHECK_LE(max_v_samp_factor, 4);
455     const int mcu_width = info_.max_h_samp_factor * DCTSIZE;
456     const int mcu_height = info_.max_v_samp_factor * DCTSIZE;
457     return info_.image_width % mcu_width != 0 ||
458            info_.image_height % mcu_height != 0;
459   }
460 
461   // Whether or not the horizontal and vertical sample factors of all components
462   // hold valid values (i.e. 1, 2, 3, or 4). It also returns the maximal
463   // horizontal and vertical sample factors via |max_h| and |max_v|.
AreValidSampleFactorsAvailable(int * max_h,int * max_v) const464   bool AreValidSampleFactorsAvailable(int* max_h, int* max_v) const {
465     if (!info_.num_components)
466       return false;
467 
468     const jpeg_component_info* comp_info = info_.comp_info;
469     if (!comp_info)
470       return false;
471 
472     *max_h = 0;
473     *max_v = 0;
474     for (int i = 0; i < info_.num_components; ++i) {
475       if (comp_info[i].h_samp_factor < 1 || comp_info[i].h_samp_factor > 4 ||
476           comp_info[i].v_samp_factor < 1 || comp_info[i].v_samp_factor > 4) {
477         return false;
478       }
479 
480       *max_h = std::max(*max_h, comp_info[i].h_samp_factor);
481       *max_v = std::max(*max_v, comp_info[i].v_samp_factor);
482     }
483     return true;
484   }
485 
486   // Decode the JPEG data. If |only_size| is specified, then only the size
487   // information will be decoded.
Decode(bool only_size)488   bool Decode(bool only_size) {
489     // We need to do the setjmp here. Otherwise bad things will happen
490     if (setjmp(err_.setjmp_buffer))
491       return decoder_->SetFailed();
492 
493     J_COLOR_SPACE override_color_space = JCS_UNKNOWN;
494     switch (state_) {
495       case JPEG_HEADER: {
496         // Read file parameters with jpeg_read_header().
497         if (jpeg_read_header(&info_, true) == JPEG_SUSPENDED)
498           return false;  // I/O suspension.
499 
500         switch (info_.jpeg_color_space) {
501           case JCS_YCbCr:
502             if (decoder_->CanDecodeToYUV() &&
503                 YuvSubsampling(info_) == cc::YUVSubsampling::k420)
504               override_color_space = JCS_YCbCr;
505             FALLTHROUGH;  // libjpeg can convert YCbCr image pixels to RGB.
506           case JCS_GRAYSCALE:
507             FALLTHROUGH;  // libjpeg can convert GRAYSCALE image pixels to RGB.
508           case JCS_RGB:
509             info_.out_color_space = rgbOutputColorSpace();
510             break;
511           case JCS_CMYK:
512           case JCS_YCCK:
513             // libjpeg can convert YCCK to CMYK, but neither to RGB, so we
514             // manually convert CMKY to RGB.
515             info_.out_color_space = JCS_CMYK;
516             break;
517           default:
518             return decoder_->SetFailed();
519         }
520 
521         state_ = JPEG_START_DECOMPRESS;
522 
523         // We can fill in the size now that the header is available.
524         if (!decoder_->SetSize(info_.image_width, info_.image_height))
525           return false;
526 
527         // Calculate and set decoded size.
528         int max_numerator = decoder_->DesiredScaleNumerator();
529         info_.scale_denom = g_scale_denominator;
530 
531         if (decoder_->ShouldGenerateAllSizes()) {
532           // Some images should not be scaled down by libjpeg_turbo because
533           // doing so may cause artifacts. Specifically, if the image contains a
534           // non-whole number of MCUs in either dimension, it's possible that
535           // the encoder used bogus data to create the last row or column of
536           // MCUs. This data may manifest when downscaling using libjpeg_turbo.
537           // See https://crbug.com/890745 and
538           // https://github.com/libjpeg-turbo/libjpeg-turbo/issues/297. Hence,
539           // we'll only allow downscaling an image if both dimensions fit a
540           // whole number of MCUs or if decoding to the original size would
541           // cause us to exceed memory limits. The latter case is detected by
542           // checking the |max_numerator| returned by DesiredScaleNumerator():
543           // this method will return either |g_scale_denominator| if decoding to
544           // the original size won't exceed the memory limit (see
545           // |max_decoded_bytes_| in ImageDecoder) or something less than
546           // |g_scale_denominator| otherwise to ensure the image is downscaled.
547           Vector<SkISize> sizes;
548           if (max_numerator == g_scale_denominator &&
549               ShouldDecodeToOriginalSize()) {
550             sizes.push_back(
551                 SkISize::Make(info_.image_width, info_.image_height));
552           } else {
553             sizes.ReserveCapacity(max_numerator);
554             for (int numerator = 1; numerator <= max_numerator; ++numerator) {
555               info_.scale_num = numerator;
556               jpeg_calc_output_dimensions(&info_);
557               sizes.push_back(
558                   SkISize::Make(info_.output_width, info_.output_height));
559             }
560           }
561           decoder_->SetSupportedDecodeSizes(std::move(sizes));
562         }
563 
564         info_.scale_num = max_numerator;
565         // Scaling caused by running low on memory isn't supported by YUV
566         // decoding since YUV decoding is performed on full sized images. At
567         // this point, buffers and various image info structs have already been
568         // set up for the scaled size after reading the image header using this
569         // decoder, so using the full size is no longer possible.
570         if (info_.scale_num != info_.scale_denom)
571           override_color_space = JCS_UNKNOWN;
572         jpeg_calc_output_dimensions(&info_);
573         decoder_->SetDecodedSize(info_.output_width, info_.output_height);
574 
575         decoder_->SetOrientation(ReadImageOrientation(Info()));
576 
577         // Allow color management of the decoded RGBA pixels if possible.
578         if (!decoder_->IgnoresColorSpace()) {
579           JOCTET* profile_buf = nullptr;
580           unsigned profile_length = 0;
581           if (read_icc_profile(Info(), &profile_buf, &profile_length)) {
582             std::unique_ptr<ColorProfile> profile =
583                 ColorProfile::Create(profile_buf, profile_length);
584             if (profile) {
585               uint32_t data_color_space =
586                   profile->GetProfile()->data_color_space;
587               switch (info_.jpeg_color_space) {
588                 case JCS_CMYK:
589                 case JCS_YCCK:
590                   if (data_color_space != skcms_Signature_CMYK)
591                     profile = nullptr;
592                   break;
593                 case JCS_GRAYSCALE:
594                   if (data_color_space != skcms_Signature_Gray &&
595                       data_color_space != skcms_Signature_RGB)
596                     profile = nullptr;
597                   break;
598                 default:
599                   if (data_color_space != skcms_Signature_RGB)
600                     profile = nullptr;
601                   break;
602               }
603               Decoder()->SetEmbeddedColorProfile(std::move(profile));
604             } else {
605               DLOG(ERROR) << "Failed to parse image ICC profile";
606             }
607             free(profile_buf);
608           }
609           if (Decoder()->ColorTransform()) {
610             override_color_space = JCS_UNKNOWN;
611           }
612         }
613         if (override_color_space == JCS_YCbCr) {
614           info_.out_color_space = JCS_YCbCr;
615           info_.raw_data_out = TRUE;
616           uv_size_ = ComputeYUVSize(
617               &info_,
618               1);  // U size and V size have to be the same if we got here
619         }
620 
621         // Don't allocate a giant and superfluous memory buffer when the
622         // image is a sequential JPEG.
623         info_.buffered_image = jpeg_has_multiple_scans(&info_);
624         if (info_.buffered_image) {
625           err_.pub.emit_message = emit_message;
626           err_.num_corrupt_warnings = 0;
627         }
628 
629         if (only_size) {
630           // This exits the function while there is still potentially
631           // data in the buffer. Before this function is called again,
632           // the SharedBuffer may be collapsed (by a call to
633           // MergeSegmentsIntoBuffer), invalidating the "buffer" (which
634           // in reality is a pointer into the SharedBuffer's data).
635           // Defensively empty the buffer, but first find the latest
636           // restart position and signal to restart, so the next call to
637           // FillBuffer will resume from the correct point.
638           needs_restart_ = true;
639           UpdateRestartPosition();
640           ClearBuffer();
641           return true;
642         }
643       }
644       FALLTHROUGH;
645       case JPEG_START_DECOMPRESS:
646         if (info_.out_color_space == JCS_YCbCr)
647           DCHECK(decoder_->HasImagePlanes());
648 
649         // Set parameters for decompression.
650         // FIXME -- Should reset dct_method and dither mode for final pass
651         // of progressive JPEG.
652         info_.dct_method = JDCT_ISLOW;
653         info_.dither_mode = JDITHER_FS;
654         info_.do_fancy_upsampling = true;
655         info_.do_block_smoothing = true;
656         info_.enable_2pass_quant = false;
657         // FIXME: should we just assert these?
658         info_.enable_external_quant = false;
659         info_.enable_1pass_quant = false;
660         info_.quantize_colors = false;
661         info_.colormap = nullptr;
662 
663         // Make a one-row-high sample array that will go away when done with
664         // image. Always make it big enough to hold one RGBA row. Since this
665         // uses the IJG memory manager, it must be allocated before the call
666         // to jpeg_start_decompress().
667         samples_ = AllocateSampleArray();
668 
669         // Start decompressor.
670         if (!jpeg_start_decompress(&info_))
671           return false;  // I/O suspension.
672 
673         // If this is a progressive JPEG ...
674         state_ = (info_.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE
675                                         : JPEG_DECOMPRESS_SEQUENTIAL;
676         FALLTHROUGH;
677 
678       case JPEG_DECOMPRESS_SEQUENTIAL:
679         if (state_ == JPEG_DECOMPRESS_SEQUENTIAL) {
680           if (!decoder_->OutputScanlines())
681             return false;  // I/O suspension.
682 
683           // If we've completed image output...
684           DCHECK_EQ(info_.output_scanline, info_.output_height);
685           state_ = JPEG_DONE;
686         }
687         FALLTHROUGH;
688 
689       case JPEG_DECOMPRESS_PROGRESSIVE:
690         if (state_ == JPEG_DECOMPRESS_PROGRESSIVE) {
691           int status = 0;
692           do {
693             decoder_error_mgr* err =
694                 reinterpret_cast_ptr<decoder_error_mgr*>(info_.err);
695             if (err->num_corrupt_warnings)
696               break;
697             status = jpeg_consume_input(&info_);
698           } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI));
699 
700           for (;;) {
701             if (!info_.output_scanline) {
702               int scan = info_.input_scan_number;
703 
704               // If we haven't displayed anything yet
705               // (output_scan_number == 0) and we have enough data for
706               // a complete scan, force output of the last full scan.
707               if (!info_.output_scan_number && (scan > 1) &&
708                   (status != JPEG_REACHED_EOI))
709                 --scan;
710 
711               if (!jpeg_start_output(&info_, scan))
712                 return false;  // I/O suspension.
713             }
714 
715             if (info_.output_scanline == 0xffffff)
716               info_.output_scanline = 0;
717 
718             if (!decoder_->OutputScanlines()) {
719               if (decoder_->Failed())
720                 return false;
721               // If no scan lines were read, flag it so we don't call
722               // jpeg_start_output() multiple times for the same scan.
723               if (!info_.output_scanline)
724                 info_.output_scanline = 0xffffff;
725 
726               return false;  // I/O suspension.
727             }
728 
729             if (info_.output_scanline == info_.output_height) {
730               if (!jpeg_finish_output(&info_))
731                 return false;  // I/O suspension.
732 
733               if (jpeg_input_complete(&info_) &&
734                   (info_.input_scan_number == info_.output_scan_number))
735                 break;
736 
737               info_.output_scanline = 0;
738             }
739           }
740 
741           state_ = JPEG_DONE;
742         }
743         FALLTHROUGH;
744 
745       case JPEG_DONE:
746         // Finish decompression.
747         BitmapImageMetrics::CountJpegArea(decoder_->Size());
748         BitmapImageMetrics::CountJpegColorSpace(
749             ExtractUMAJpegColorSpace(info_));
750         return jpeg_finish_decompress(&info_);
751     }
752 
753     return true;
754   }
755 
Info()756   jpeg_decompress_struct* Info() { return &info_; }
Samples() const757   JSAMPARRAY Samples() const { return samples_; }
Decoder()758   JPEGImageDecoder* Decoder() { return decoder_; }
UvSize() const759   IntSize UvSize() const { return uv_size_; }
760 
761  private:
762 #if defined(USE_SYSTEM_LIBJPEG)
763   NO_SANITIZE_CFI_ICALL
764 #endif
AllocateSampleArray()765   JSAMPARRAY AllocateSampleArray() {
766 // Some output color spaces don't need the sample array: don't allocate in that
767 // case.
768 #if defined(TURBO_JPEG_RGB_SWIZZLE)
769     if (turboSwizzled(info_.out_color_space))
770       return nullptr;
771 #endif
772 
773     if (info_.out_color_space != JCS_YCbCr)
774       return (*info_.mem->alloc_sarray)(
775           reinterpret_cast_ptr<j_common_ptr>(&info_), JPOOL_IMAGE,
776           4 * info_.output_width, 1);
777 
778     // Compute the width of the Y plane in bytes.  This may be larger than the
779     // output width, since the jpeg library requires that the allocated width be
780     // a multiple of DCTSIZE.  Note that this buffer will be used as garbage
781     // memory for rows that extend below the actual height of the image.  We can
782     // reuse the same memory for the U and V planes, since we are guaranteed
783     // that the Y plane width is at least as large as the U and V plane widths.
784     int width_bytes = ComputeYUVWidthBytes(&info_, 0);
785     return (*info_.mem->alloc_sarray)(
786         reinterpret_cast_ptr<j_common_ptr>(&info_), JPOOL_IMAGE, width_bytes,
787         1);
788   }
789 
UpdateRestartPosition()790   void UpdateRestartPosition() {
791     if (last_set_byte_ != info_.src->next_input_byte) {
792       // next_input_byte was updated by jpeg, meaning that it found a restart
793       // position.
794       restart_position_ = next_read_position_ - info_.src->bytes_in_buffer;
795     }
796   }
797 
ClearBuffer()798   void ClearBuffer() {
799     // Let libjpeg know that the buffer needs to be refilled.
800     info_.src->bytes_in_buffer = 0;
801     info_.src->next_input_byte = nullptr;
802     last_set_byte_ = nullptr;
803   }
804 
805   scoped_refptr<SegmentReader> data_;
806   JPEGImageDecoder* decoder_;
807 
808   // Input reading: True if we need to back up to restart_position_.
809   bool needs_restart_;
810   // If libjpeg needed to restart, this is the position to restart from.
811   size_t restart_position_;
812   // This is the position where we will read from, unless there is a restart.
813   size_t next_read_position_;
814   // This is how we know to update the restart position. It is the last value
815   // we set to next_input_byte. libjpeg will update next_input_byte when it
816   // has found the next restart position, so if it no longer matches this
817   // value, we know we've reached the next restart position.
818   const JOCTET* last_set_byte_;
819 
820   jpeg_decompress_struct info_;
821   decoder_error_mgr err_;
822   decoder_source_mgr src_;
823   jpeg_progress_mgr progress_mgr_;
824   jstate state_;
825 
826   JSAMPARRAY samples_;
827   IntSize uv_size_;
828 
829   DISALLOW_COPY_AND_ASSIGN(JPEGImageReader);
830 };
831 
error_exit(j_common_ptr cinfo)832 void error_exit(
833     j_common_ptr cinfo)  // Decoding failed: return control to the setjmp point.
834 {
835   longjmp(reinterpret_cast_ptr<decoder_error_mgr*>(cinfo->err)->setjmp_buffer,
836           -1);
837 }
838 
emit_message(j_common_ptr cinfo,int msg_level)839 void emit_message(j_common_ptr cinfo, int msg_level) {
840   if (msg_level >= 0)
841     return;
842 
843   decoder_error_mgr* err = reinterpret_cast_ptr<decoder_error_mgr*>(cinfo->err);
844   err->pub.num_warnings++;
845 
846   // Detect and count corrupt JPEG warning messages.
847   const char* warning = nullptr;
848   int code = err->pub.msg_code;
849   if (code > 0 && code <= err->pub.last_jpeg_message)
850     warning = err->pub.jpeg_message_table[code];
851   if (warning && !strncmp("Corrupt JPEG", warning, 12))
852     err->num_corrupt_warnings++;
853 }
854 
init_source(j_decompress_ptr)855 void init_source(j_decompress_ptr) {}
856 
skip_input_data(j_decompress_ptr jd,long num_bytes)857 void skip_input_data(j_decompress_ptr jd, long num_bytes) {
858   reinterpret_cast_ptr<decoder_source_mgr*>(jd->src)->reader->SkipBytes(
859       num_bytes);
860 }
861 
fill_input_buffer(j_decompress_ptr jd)862 boolean fill_input_buffer(j_decompress_ptr jd) {
863   return reinterpret_cast_ptr<decoder_source_mgr*>(jd->src)
864       ->reader->FillBuffer();
865 }
866 
term_source(j_decompress_ptr jd)867 void term_source(j_decompress_ptr jd) {
868   reinterpret_cast_ptr<decoder_source_mgr*>(jd->src)
869       ->reader->Decoder()
870       ->Complete();
871 }
872 
JPEGImageDecoder(AlphaOption alpha_option,const ColorBehavior & color_behavior,size_t max_decoded_bytes,const OverrideAllowDecodeToYuv allow_decode_to_yuv,size_t offset)873 JPEGImageDecoder::JPEGImageDecoder(
874     AlphaOption alpha_option,
875     const ColorBehavior& color_behavior,
876     size_t max_decoded_bytes,
877     const OverrideAllowDecodeToYuv allow_decode_to_yuv,
878     size_t offset)
879     : ImageDecoder(
880           alpha_option,
881           ImageDecoder::kDefaultBitDepth,
882           color_behavior,
883           max_decoded_bytes,
884           allow_decode_to_yuv == OverrideAllowDecodeToYuv::kDefault &&
885               RuntimeEnabledFeatures::DecodeJpeg420ImagesToYUVEnabled()),
886       offset_(offset) {}
887 
888 JPEGImageDecoder::~JPEGImageDecoder() = default;
889 
SetSize(unsigned width,unsigned height)890 bool JPEGImageDecoder::SetSize(unsigned width, unsigned height) {
891   if (!ImageDecoder::SetSize(width, height))
892     return false;
893 
894   if (!DesiredScaleNumerator())
895     return SetFailed();
896 
897   SetDecodedSize(width, height);
898   return true;
899 }
900 
OnSetData(SegmentReader * data)901 void JPEGImageDecoder::OnSetData(SegmentReader* data) {
902   if (reader_)
903     reader_->SetData(data);
904   // TODO(crbug.com/943519): Incremental YUV decoding is not currently
905   // supported.
906   if (IsAllDataReceived()) {
907     // TODO(crbug.com/919627): Right now |allow_decode_to_yuv_| is false by
908     // default and is set by the blink feature DecodeJpeg420ImagesToYUV.
909     //
910     // Calling IsSizeAvailable() ensures the reader is created and the output
911     // color space is set.
912     allow_decode_to_yuv_ &=
913         IsSizeAvailable() && reader_->Info()->out_color_space == JCS_YCbCr;
914   }
915 }
916 
SetDecodedSize(unsigned width,unsigned height)917 void JPEGImageDecoder::SetDecodedSize(unsigned width, unsigned height) {
918   decoded_size_ = IntSize(width, height);
919 }
920 
DecodedYUVSize(int component) const921 IntSize JPEGImageDecoder::DecodedYUVSize(int component) const {
922   DCHECK_GE(component, 0);
923   DCHECK_LE(component, 2);
924   DCHECK(reader_);
925   const jpeg_decompress_struct* info = reader_->Info();
926 
927   DCHECK_EQ(info->out_color_space, JCS_YCbCr);
928   return ComputeYUVSize(info, component);
929 }
930 
DecodedYUVWidthBytes(int component) const931 size_t JPEGImageDecoder::DecodedYUVWidthBytes(int component) const {
932   DCHECK_GE(component, 0);
933   DCHECK_LE(component, 2);
934   DCHECK(reader_);
935   const jpeg_decompress_struct* info = reader_->Info();
936 
937   DCHECK_EQ(info->out_color_space, JCS_YCbCr);
938   return ComputeYUVWidthBytes(info, component);
939 }
940 
DesiredScaleNumerator() const941 unsigned JPEGImageDecoder::DesiredScaleNumerator() const {
942   size_t original_bytes = Size().Width() * Size().Height() * 4;
943 
944   if (original_bytes <= max_decoded_bytes_)
945     return g_scale_denominator;
946 
947   // Downsample according to the maximum decoded size.
948   unsigned scale_numerator = static_cast<unsigned>(floor(sqrt(
949       // MSVC needs explicit parameter type for sqrt().
950       static_cast<float>(max_decoded_bytes_ * g_scale_denominator *
951                          g_scale_denominator / original_bytes))));
952 
953   return scale_numerator;
954 }
955 
ShouldGenerateAllSizes() const956 bool JPEGImageDecoder::ShouldGenerateAllSizes() const {
957   return supported_decode_sizes_.IsEmpty();
958 }
959 
DecodeToYUV()960 void JPEGImageDecoder::DecodeToYUV() {
961   DCHECK(HasImagePlanes());
962   DCHECK(CanDecodeToYUV());
963 
964   {
965     TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "Decode Image",
966                  "imageType", "JPEG");
967     Decode(false);
968   }
969 }
970 
971 // TODO(crbug.com/919627): Confirm that this is correct for all cases.
GetYUVColorSpace() const972 SkYUVColorSpace JPEGImageDecoder::GetYUVColorSpace() const {
973   return SkYUVColorSpace::kJPEG_SkYUVColorSpace;
974 }
975 
SetSupportedDecodeSizes(Vector<SkISize> sizes)976 void JPEGImageDecoder::SetSupportedDecodeSizes(Vector<SkISize> sizes) {
977   supported_decode_sizes_ = std::move(sizes);
978 }
979 
GetSupportedDecodeSizes() const980 Vector<SkISize> JPEGImageDecoder::GetSupportedDecodeSizes() const {
981   // DCHECK IsDecodedSizeAvailable instead of IsSizeAvailable, since the latter
982   // has side effects of actually doing the decode.
983   DCHECK(IsDecodedSizeAvailable());
984   return supported_decode_sizes_;
985 }
986 
GetImageCodedSize() const987 gfx::Size JPEGImageDecoder::GetImageCodedSize() const {
988   // We use the |max_{h,v}_samp_factor|s returned by
989   // AreValidSampleFactorsAvailable() since the ones available via
990   // Info()->max_{h,v}_samp_factor are not updated until the image is actually
991   // being decoded.
992   int max_h_samp_factor;
993   int max_v_samp_factor;
994   if (!reader_->AreValidSampleFactorsAvailable(&max_h_samp_factor,
995                                                &max_v_samp_factor)) {
996     return gfx::Size();
997   }
998 
999   const int coded_width = Align(Size().Width(), max_h_samp_factor * 8);
1000   const int coded_height = Align(Size().Height(), max_v_samp_factor * 8);
1001 
1002   return gfx::Size(coded_width, coded_height);
1003 }
1004 
MakeMetadataForDecodeAcceleration() const1005 cc::ImageHeaderMetadata JPEGImageDecoder::MakeMetadataForDecodeAcceleration()
1006     const {
1007   cc::ImageHeaderMetadata image_metadata =
1008       ImageDecoder::MakeMetadataForDecodeAcceleration();
1009   image_metadata.jpeg_is_progressive = reader_->Info()->buffered_image;
1010   image_metadata.coded_size = GetImageCodedSize();
1011   return image_metadata;
1012 }
1013 
1014 // At the moment we support only JCS_RGB and JCS_CMYK values of the
1015 // J_COLOR_SPACE enum.
1016 // If you need a specific implementation for other J_COLOR_SPACE values,
1017 // please add a full template specialization for this function below.
1018 template <J_COLOR_SPACE colorSpace>
1019 void SetPixel(ImageFrame::PixelData*, JSAMPARRAY samples, int column);
1020 
1021 // Used only for debugging with libjpeg (instead of libjpeg-turbo).
1022 template <>
SetPixel(ImageFrame::PixelData * pixel,JSAMPARRAY samples,int column)1023 void SetPixel<JCS_RGB>(ImageFrame::PixelData* pixel,
1024                        JSAMPARRAY samples,
1025                        int column) {
1026   JSAMPLE* jsample = *samples + column * 3;
1027   ImageFrame::SetRGBARaw(pixel, jsample[0], jsample[1], jsample[2], 255);
1028 }
1029 
1030 template <>
SetPixel(ImageFrame::PixelData * pixel,JSAMPARRAY samples,int column)1031 void SetPixel<JCS_CMYK>(ImageFrame::PixelData* pixel,
1032                         JSAMPARRAY samples,
1033                         int column) {
1034   JSAMPLE* jsample = *samples + column * 4;
1035 
1036   // Source is 'Inverted CMYK', output is RGB.
1037   // See: http://www.easyrgb.com/math.php?MATH=M12#text12
1038   // Or: http://www.ilkeratalay.com/colorspacesfaq.php#rgb
1039   // From CMYK to CMY:
1040   // X =   X    * (1 -   K   ) +   K  [for X = C, M, or Y]
1041   // Thus, from Inverted CMYK to CMY is:
1042   // X = (1-iX) * (1 - (1-iK)) + (1-iK) => 1 - iX*iK
1043   // From CMY (0..1) to RGB (0..1):
1044   // R = 1 - C => 1 - (1 - iC*iK) => iC*iK  [G and B similar]
1045   unsigned k = jsample[3];
1046   ImageFrame::SetRGBARaw(pixel, jsample[0] * k / 255, jsample[1] * k / 255,
1047                          jsample[2] * k / 255, 255);
1048 }
1049 
1050 // Used only for JCS_CMYK and JCS_RGB output.  Note that JCS_RGB is used only
1051 // for debugging with libjpeg (instead of libjpeg-turbo).
1052 template <J_COLOR_SPACE colorSpace>
OutputRows(JPEGImageReader * reader,ImageFrame & buffer)1053 bool OutputRows(JPEGImageReader* reader, ImageFrame& buffer) {
1054   JSAMPARRAY samples = reader->Samples();
1055   jpeg_decompress_struct* info = reader->Info();
1056   int width = info->output_width;
1057 
1058   while (info->output_scanline < info->output_height) {
1059     // jpeg_read_scanlines will increase the scanline counter, so we
1060     // save the scanline before calling it.
1061     int y = info->output_scanline;
1062     // Request one scanline: returns 0 or 1 scanlines.
1063     if (jpeg_read_scanlines(info, samples, 1) != 1)
1064       return false;
1065 
1066     ImageFrame::PixelData* pixel = buffer.GetAddr(0, y);
1067     for (int x = 0; x < width; ++pixel, ++x)
1068       SetPixel<colorSpace>(pixel, samples, x);
1069 
1070     ColorProfileTransform* xform = reader->Decoder()->ColorTransform();
1071     if (xform) {
1072       ImageFrame::PixelData* row = buffer.GetAddr(0, y);
1073       skcms_AlphaFormat alpha_format = skcms_AlphaFormat_Unpremul;
1074       bool color_conversion_successful = skcms_Transform(
1075           row, XformColorFormat(), alpha_format, xform->SrcProfile(), row,
1076           XformColorFormat(), alpha_format, xform->DstProfile(), width);
1077       DCHECK(color_conversion_successful);
1078     }
1079   }
1080 
1081   buffer.SetPixelsChanged(true);
1082   return true;
1083 }
1084 
OutputRawData(JPEGImageReader * reader,ImagePlanes * image_planes)1085 static bool OutputRawData(JPEGImageReader* reader, ImagePlanes* image_planes) {
1086   JSAMPARRAY samples = reader->Samples();
1087   jpeg_decompress_struct* info = reader->Info();
1088 
1089   DCHECK_EQ(info->out_color_space, JCS_YCbCr);
1090 
1091   JSAMPARRAY bufferraw[3];
1092   JSAMPROW bufferraw2[32];
1093   bufferraw[0] = &bufferraw2[0];   // Y channel rows (8 or 16)
1094   bufferraw[1] = &bufferraw2[16];  // U channel rows (8)
1095   bufferraw[2] = &bufferraw2[24];  // V channel rows (8)
1096   int y_height = info->output_height;
1097   int v = info->comp_info[0].v_samp_factor;
1098   IntSize uv_size = reader->UvSize();
1099   int uv_height = uv_size.Height();
1100   JSAMPROW output_y = static_cast<JSAMPROW>(image_planes->Plane(0));
1101   JSAMPROW output_u = static_cast<JSAMPROW>(image_planes->Plane(1));
1102   JSAMPROW output_v = static_cast<JSAMPROW>(image_planes->Plane(2));
1103   size_t row_bytes_y = image_planes->RowBytes(0);
1104   size_t row_bytes_u = image_planes->RowBytes(1);
1105   size_t row_bytes_v = image_planes->RowBytes(2);
1106 
1107   // Request 8 or 16 scanlines: returns 0 or more scanlines.
1108   int y_scanlines_to_read = DCTSIZE * v;
1109   JSAMPROW dummy_row = *samples;
1110   while (info->output_scanline < info->output_height) {
1111     // Assign 8 or 16 rows of memory to read the Y channel.
1112     for (int i = 0; i < y_scanlines_to_read; ++i) {
1113       int scanline = info->output_scanline + i;
1114       if (scanline < y_height) {
1115         bufferraw2[i] = &output_y[scanline * row_bytes_y];
1116       } else {
1117         bufferraw2[i] = dummy_row;
1118       }
1119     }
1120 
1121     // Assign 8 rows of memory to read the U and V channels.
1122     int scaled_scanline = info->output_scanline / v;
1123     for (int i = 0; i < 8; ++i) {
1124       int scanline = scaled_scanline + i;
1125       if (scanline < uv_height) {
1126         bufferraw2[16 + i] = &output_u[scanline * row_bytes_u];
1127         bufferraw2[24 + i] = &output_v[scanline * row_bytes_v];
1128       } else {
1129         bufferraw2[16 + i] = dummy_row;
1130         bufferraw2[24 + i] = dummy_row;
1131       }
1132     }
1133 
1134     JDIMENSION scanlines_read =
1135         jpeg_read_raw_data(info, bufferraw, y_scanlines_to_read);
1136     if (!scanlines_read)
1137       return false;
1138   }
1139 
1140   info->output_scanline = std::min(info->output_scanline, info->output_height);
1141   return true;
1142 }
1143 
OutputScanlines()1144 bool JPEGImageDecoder::OutputScanlines() {
1145   if (HasImagePlanes())
1146     return OutputRawData(reader_.get(), image_planes_.get());
1147 
1148   if (frame_buffer_cache_.IsEmpty())
1149     return false;
1150 
1151   jpeg_decompress_struct* info = reader_->Info();
1152 
1153   // Initialize the framebuffer if needed.
1154   ImageFrame& buffer = frame_buffer_cache_[0];
1155   if (buffer.GetStatus() == ImageFrame::kFrameEmpty) {
1156     DCHECK_EQ(info->output_width,
1157               static_cast<JDIMENSION>(decoded_size_.Width()));
1158     DCHECK_EQ(info->output_height,
1159               static_cast<JDIMENSION>(decoded_size_.Height()));
1160 
1161     if (!buffer.AllocatePixelData(info->output_width, info->output_height,
1162                                   ColorSpaceForSkImages()))
1163       return SetFailed();
1164 
1165     buffer.ZeroFillPixelData();
1166     // The buffer is transparent outside the decoded area while the image is
1167     // loading. The image will be marked fully opaque in Complete().
1168     buffer.SetStatus(ImageFrame::kFramePartial);
1169     buffer.SetHasAlpha(true);
1170 
1171     // For JPEGs, the frame always fills the entire image.
1172     buffer.SetOriginalFrameRect(IntRect(IntPoint(), Size()));
1173   }
1174 
1175 #if defined(TURBO_JPEG_RGB_SWIZZLE)
1176   if (turboSwizzled(info->out_color_space)) {
1177     while (info->output_scanline < info->output_height) {
1178       unsigned char* row = reinterpret_cast_ptr<unsigned char*>(
1179           buffer.GetAddr(0, info->output_scanline));
1180       if (jpeg_read_scanlines(info, &row, 1) != 1)
1181         return false;
1182 
1183       ColorProfileTransform* xform = ColorTransform();
1184       if (xform) {
1185         skcms_AlphaFormat alpha_format = skcms_AlphaFormat_Unpremul;
1186         bool color_conversion_successful = skcms_Transform(
1187             row, XformColorFormat(), alpha_format, xform->SrcProfile(), row,
1188             XformColorFormat(), alpha_format, xform->DstProfile(),
1189             info->output_width);
1190         DCHECK(color_conversion_successful);
1191       }
1192     }
1193     buffer.SetPixelsChanged(true);
1194     return true;
1195   }
1196 #endif
1197 
1198   switch (info->out_color_space) {
1199     case JCS_RGB:
1200       return OutputRows<JCS_RGB>(reader_.get(), buffer);
1201     case JCS_CMYK:
1202       return OutputRows<JCS_CMYK>(reader_.get(), buffer);
1203     default:
1204       NOTREACHED();
1205   }
1206 
1207   return SetFailed();
1208 }
1209 
Complete()1210 void JPEGImageDecoder::Complete() {
1211   if (frame_buffer_cache_.IsEmpty())
1212     return;
1213 
1214   frame_buffer_cache_[0].SetHasAlpha(false);
1215   frame_buffer_cache_[0].SetStatus(ImageFrame::kFrameComplete);
1216 }
1217 
IsComplete(const JPEGImageDecoder * decoder,bool only_size)1218 inline bool IsComplete(const JPEGImageDecoder* decoder, bool only_size) {
1219   if (decoder->HasImagePlanes() && !only_size)
1220     return true;
1221 
1222   return decoder->FrameIsDecodedAtIndex(0);
1223 }
1224 
GetYUVSubsampling() const1225 cc::YUVSubsampling JPEGImageDecoder::GetYUVSubsampling() const {
1226   DCHECK(reader_->Info());
1227   // reader_->Info() should have gone through a jpeg_read_header() call.
1228   DCHECK(IsDecodedSizeAvailable());
1229   return YuvSubsampling(*reader_->Info());
1230 }
1231 
Decode(bool only_size)1232 void JPEGImageDecoder::Decode(bool only_size) {
1233   if (Failed())
1234     return;
1235 
1236   if (!reader_) {
1237     reader_ = std::make_unique<JPEGImageReader>(this, offset_);
1238     reader_->SetData(data_.get());
1239   }
1240 
1241   // If we couldn't decode the image but have received all the data, decoding
1242   // has failed.
1243   if (!reader_->Decode(only_size) && IsAllDataReceived())
1244     SetFailed();
1245 
1246   // If decoding is done or failed, we don't need the JPEGImageReader anymore.
1247   if (IsComplete(this, only_size) || Failed())
1248     reader_.reset();
1249 }
1250 
1251 }  // namespace blink
1252