Debian Codegraph @

src/codec/SkJpegCodec.cpp

raw
1 /*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/codec/SkJpegCodec.h"
9
10 #include "include/codec/SkCodec.h"
11 #include "include/codec/SkJpegDecoder.h"
12 #include "include/core/SkAlphaType.h"
13 #include "include/core/SkColorType.h"
14 #include "include/core/SkData.h"
15 #include "include/core/SkImageInfo.h"
16 #include "include/core/SkPixmap.h"
17 #include "include/core/SkRefCnt.h"
18 #include "include/core/SkStream.h"
19 #include "include/core/SkTypes.h"
20 #include "include/core/SkYUVAInfo.h"
21 #include "include/private/base/SkAlign.h"
22 #include "include/private/base/SkTemplates.h"
23 #include "modules/skcms/skcms.h"
24 #include "src/codec/SkCodecPriv.h"
25 #include "src/codec/SkJpegConstants.h"
26 #include "src/codec/SkJpegDecoderMgr.h"
27 #include "src/codec/SkJpegMetadataDecoderImpl.h"
28 #include "src/codec/SkJpegPriv.h"
29 #include "src/codec/SkParseEncodedOrigin.h"
30 #include "src/codec/SkSwizzler.h"
31
32 #ifdef SK_CODEC_DECODES_JPEG_GAINMAPS
33 #include "include/private/SkGainmapInfo.h"
34 #endif // SK_CODEC_DECODES_JPEG_GAINMAPS
35
36 #include <array>
37 #include <csetjmp>
38 #include <cstring>
39 #include <utility>
40
41 using namespace skia_private;
42
43 class SkSampler;
44 struct SkGainmapInfo;
45
46 // This warning triggers false postives way too often in here.
47 #if defined(__GNUC__) && !defined(__clang__)
48 #pragma GCC diagnostic ignored "-Wclobbered"
49 #endif
50
51 extern "C" {
52 #include "jpeglib.h" // NO_G3_REWRITE
53 }
54
55 bool SkJpegCodec::IsJpeg(const void* buffer, size_t bytesRead) {
56 return bytesRead >= sizeof(kJpegSig) && !memcmp(buffer, kJpegSig, sizeof(kJpegSig));
57 }
58
59 static SkJpegMarkerList get_sk_marker_list(jpeg_decompress_struct* dinfo) {
60 SkJpegMarkerList markerList;
61 for (auto* marker = dinfo->marker_list; marker; marker = marker->next) {
62 markerList.emplace_back(marker->marker,
63 SkData::MakeWithoutCopy(marker->data, marker->data_length));
64 }
65 return markerList;
66 }
67
68 static SkEncodedOrigin get_exif_orientation(sk_sp<const SkData> exifData) {
69 SkEncodedOrigin origin = kDefault_SkEncodedOrigin;
70 if (exifData && SkParseEncodedOrigin(exifData->bytes(), exifData->size(), &origin)) {
71 return origin;
72 }
73 return kDefault_SkEncodedOrigin;
74 }
75
76 enum class SaveMarkers : bool {
77 kNo = false,
78 kYes = true,
79 };
80
81 // Initializes the decoder manager and read just the header to get relevent metadata.
82 static std::tuple<SkCodec::Result, std::unique_ptr<JpegDecoderMgr>> read_header(
83 SkStream* stream, SaveMarkers saveMarkers) {
84 // Create a JpegDecoderMgr to own all of the decompress information
85 std::unique_ptr<JpegDecoderMgr> decoderMgr(new JpegDecoderMgr(stream));
86
87 // libjpeg errors will be caught and reported here
88 skjpeg_error_mgr::AutoPushJmpBuf jmp(decoderMgr->errorMgr());
89 if (setjmp(jmp)) {
90 return {decoderMgr->returnFailure("ReadHeader", SkCodec::kInvalidInput), nullptr};
91 }
92
93 // Initialize the decompress info and the source manager
94 decoderMgr->init();
95 auto* dinfo = decoderMgr->dinfo();
96
97 // Instruct jpeg library to save the markers that we care about. Since
98 // the orientation and color profile will not change, we can skip this
99 // step on rewinds.
100 if (saveMarkers == SaveMarkers::kYes) {
101 jpeg_save_markers(dinfo, kExifMarker, 0xFFFF);
102 jpeg_save_markers(dinfo, kICCMarker, 0xFFFF);
103 jpeg_save_markers(dinfo, kMpfMarker, 0xFFFF);
104 }
105
106 // Read the jpeg header
107 switch (jpeg_read_header(dinfo, TRUE)) {
108 case JPEG_HEADER_OK:
109 break;
110 case JPEG_SUSPENDED:
111 return {decoderMgr->returnFailure("ReadHeader", SkCodec::kIncompleteInput), nullptr};
112 default:
113 return {decoderMgr->returnFailure("ReadHeader", SkCodec::kInvalidInput), nullptr};
114 }
115
116 return {SkCodec::kSuccess, std::move(decoderMgr)};
117 }
118
119 std::unique_ptr<SkCodec> SkJpegCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
120 Result* result) {
121 return SkJpegCodec::MakeFromStream(std::move(stream), result, nullptr);
122 }
123
124 std::unique_ptr<SkCodec> SkJpegCodec::MakeFromStream(
125 std::unique_ptr<SkStream> stream,
126 Result* result, std::unique_ptr<SkCodecs::ColorProfile> defaultColorProfile) {
127 SkASSERT(result);
128 if (!stream) {
129 *result = SkCodec::kInvalidInput;
130 return nullptr;
131 }
132
133 auto [r, decoderMgr] = read_header(stream.get(), SaveMarkers::kYes);
134 if (r != SkCodec::kSuccess) {
135 *result = r;
136 return nullptr;
137 }
138 // Get the encoded color type
139 SkEncodedInfo::Color color;
140 if (!decoderMgr->getEncodedColor(&color)) {
141 *result = SkCodec::kInvalidInput;
142 return nullptr;
143 }
144
145 auto* dinfo = decoderMgr->dinfo();
146 auto metadataDecoder = std::make_unique<SkJpegMetadataDecoderImpl>(get_sk_marker_list(dinfo));
147
148 SkEncodedOrigin orientation =
149 get_exif_orientation(metadataDecoder->getExifMetadata(/*copyData=*/false));
150
151 std::unique_ptr<SkCodecs::ColorProfile> profile;
152 if (auto iccProfileData = metadataDecoder->getICCProfileData(/*copyData=*/true)) {
153 profile = SkCodecs::ColorProfile::MakeICCProfile(std::move(iccProfileData));
154 }
155 if (profile) {
156 const auto colorDataSpace = profile->dataSpace();
157 switch (decoderMgr->dinfo()->jpeg_color_space) {
158 case JCS_CMYK:
159 case JCS_YCCK:
160 if (colorDataSpace != SkCodecs::ColorProfile::DataSpace::kCMYK) {
161 profile = nullptr;
162 }
163 break;
164 case JCS_GRAYSCALE:
165 if (colorDataSpace != SkCodecs::ColorProfile::DataSpace::kGray &&
166 colorDataSpace != SkCodecs::ColorProfile::DataSpace::kRGB) {
167 profile = nullptr;
168 }
169 break;
170 default:
171 if (colorDataSpace != SkCodecs::ColorProfile::DataSpace::kRGB) {
172 profile = nullptr;
173 }
174 break;
175 }
176 }
177 if (!profile) {
178 profile = std::move(defaultColorProfile);
179 }
180
181 SkEncodedInfo info = SkEncodedInfo::Make(dinfo->image_width,
182 dinfo->image_height,
183 color,
184 SkEncodedInfo::kOpaque_Alpha,
185 8,
186 std::move(profile));
187
188 *result = SkCodec::kSuccess;
189 return std::unique_ptr<SkJpegCodec>(
190 new SkJpegCodec(std::move(info), std::move(stream), decoderMgr.release(), orientation));
191 }
192
193 SkJpegCodec::SkJpegCodec(SkEncodedInfo&& info,
194 std::unique_ptr<SkStream> stream,
195 JpegDecoderMgr* decoderMgr,
196 SkEncodedOrigin origin)
197 : SkCodec(std::move(info), skcms_PixelFormat_RGBA_8888, std::move(stream), origin)
198 , fDecoderMgr(decoderMgr)
199 , fReadyState(decoderMgr->dinfo()->global_state) {}
200 SkJpegCodec::~SkJpegCodec() = default;
201
202 /*
203 * Return the row bytes of a particular image type and width
204 */
205 static size_t get_row_bytes(const j_decompress_ptr dinfo) {
206 const size_t colorBytes = (dinfo->out_color_space == JCS_RGB565) ? 2 :
207 dinfo->out_color_components;
208 return dinfo->output_width * colorBytes;
209
210 }
211
212 /*
213 * Calculate output dimensions based on the provided factors.
214 *
215 * Not to be used on the actual jpeg_decompress_struct used for decoding, since it will
216 * incorrectly modify num_components.
217 */
218 static void calc_output_dimensions(jpeg_decompress_struct* dinfo,
219 unsigned int num,
220 unsigned int denom) {
221 dinfo->num_components = 0;
222 dinfo->scale_num = num;
223 dinfo->scale_denom = denom;
224 jpeg_calc_output_dimensions(dinfo);
225 }
226
227 /*
228 * Return a valid set of output dimensions for this decoder, given an input scale
229 */
230 SkISize SkJpegCodec::onGetScaledDimensions(float desiredScale) const {
231 // libjpeg-turbo supports scaling by 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, and 1/1, so we will
232 // support these as well
233 unsigned int num;
234 unsigned int denom = 8;
235 if (desiredScale >= 0.9375) {
236 num = 8;
237 } else if (desiredScale >= 0.8125) {
238 num = 7;
239 } else if (desiredScale >= 0.6875f) {
240 num = 6;
241 } else if (desiredScale >= 0.5625f) {
242 num = 5;
243 } else if (desiredScale >= 0.4375f) {
244 num = 4;
245 } else if (desiredScale >= 0.3125f) {
246 num = 3;
247 } else if (desiredScale >= 0.1875f) {
248 num = 2;
249 } else {
250 num = 1;
251 }
252
253 // Set up a fake decompress struct in order to use libjpeg to calculate output dimensions.
254 // This isn't conventional use of libjpeg-turbo but initializing the decompress struct with
255 // jpeg_create_decompress allows for less violation of the API regardless of the version.
256 jpeg_decompress_struct dinfo;
257 jpeg_create_decompress(&dinfo);
258 dinfo.image_width = this->dimensions().width();
259 dinfo.image_height = this->dimensions().height();
260 dinfo.global_state = fReadyState;
261 calc_output_dimensions(&dinfo, num, denom);
262 SkISize outputDimensions = SkISize::Make(dinfo.output_width, dinfo.output_height);
263 jpeg_destroy_decompress(&dinfo);
264
265 return outputDimensions;
266 }
267
268 bool SkJpegCodec::onRewind() {
269 if (!this->rewindStream()) {
270 return false;
271 }
272 auto [result, decoderMgr] = read_header(this->stream(), SaveMarkers::kNo);
273 if (result != kSuccess) {
274 return fDecoderMgr->returnFalse("onRewind");
275 }
276 SkASSERT(decoderMgr);
277
278 if ((int) decoderMgr->dinfo()->image_width != this->getEncodedInfo().width() ||
279 (int) decoderMgr->dinfo()->image_height != this->getEncodedInfo().height()) {
280 return fDecoderMgr->returnFailure("onRewind: dimensions changed", kInternalError);
281 }
282
283 fDecoderMgr = std::move(decoderMgr);
284
285 fSwizzler.reset(nullptr);
286 fSwizzleSrcRow = nullptr;
287 fColorXformSrcRow = nullptr;
288 fStorage.reset();
289
290 return true;
291 }
292
293 bool SkJpegCodec::conversionSupported(const SkImageInfo& dstInfo, bool srcIsOpaque,
294 bool needsColorXform) {
295 SkASSERT(srcIsOpaque);
296
297 if (kUnknown_SkAlphaType == dstInfo.alphaType()) {
298 return false;
299 }
300
301 if (kOpaque_SkAlphaType != dstInfo.alphaType()) {
302 SkCodecPrintf("Warning: an opaque image should be decoded as opaque "
303 "- it is being decoded as non-opaque, which will draw slower\n");
304 }
305
306 J_COLOR_SPACE encodedColorType = fDecoderMgr->dinfo()->jpeg_color_space;
307
308 // Check for valid color types and set the output color space
309 switch (dstInfo.colorType()) {
310 case kRGBA_8888_SkColorType:
311 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
312 break;
313 case kBGRA_8888_SkColorType:
314 if (needsColorXform) {
315 // Always using RGBA as the input format for color xforms makes the
316 // implementation a little simpler.
317 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
318 } else {
319 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_BGRA;
320 }
321 break;
322 case kRGB_565_SkColorType:
323 if (needsColorXform) {
324 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
325 } else {
326 fDecoderMgr->dinfo()->dither_mode = JDITHER_NONE;
327 fDecoderMgr->dinfo()->out_color_space = JCS_RGB565;
328 }
329 break;
330 case kGray_8_SkColorType:
331 if (JCS_GRAYSCALE != encodedColorType) {
332 return false;
333 }
334
335 if (needsColorXform) {
336 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
337 } else {
338 fDecoderMgr->dinfo()->out_color_space = JCS_GRAYSCALE;
339 }
340 break;
341 case kBGRA_10101010_XR_SkColorType:
342 case kBGR_101010x_XR_SkColorType:
343 case kRGBA_F16_SkColorType:
344 SkASSERT(needsColorXform);
345 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
346 break;
347 default:
348 return false;
349 }
350
351 // Check if we will decode to CMYK. libjpeg-turbo does not convert CMYK to RGBA, so
352 // we must do it ourselves.
353 if (JCS_CMYK == encodedColorType || JCS_YCCK == encodedColorType) {
354 fDecoderMgr->dinfo()->out_color_space = JCS_CMYK;
355 }
356
357 return true;
358 }
359
360 /*
361 * Checks if we can natively scale to the requested dimensions and natively scales the
362 * dimensions if possible
363 */
364 bool SkJpegCodec::onDimensionsSupported(const SkISize& size) {
365 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
366 if (setjmp(jmp)) {
367 return fDecoderMgr->returnFalse("onDimensionsSupported");
368 }
369
370 const unsigned int dstWidth = size.width();
371 const unsigned int dstHeight = size.height();
372
373 // Set up a fake decompress struct in order to use libjpeg to calculate output dimensions
374 // This isn't conventional use of libjpeg-turbo but initializing the decompress struct with
375 // jpeg_create_decompress allows for less violation of the API regardless of the version.
376 // FIXME: Why is this necessary?
377 jpeg_decompress_struct dinfo;
378 jpeg_create_decompress(&dinfo);
379 dinfo.image_width = this->dimensions().width();
380 dinfo.image_height = this->dimensions().height();
381 dinfo.global_state = fReadyState;
382
383 // libjpeg-turbo can scale to 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, and 1/1
384 unsigned num = 8;
385 constexpr unsigned denom = 8;
386 calc_output_dimensions(&dinfo, num, denom);
387 while (dinfo.output_width != dstWidth || dinfo.output_height != dstHeight) {
388
389 // Return a failure if we have tried all of the possible scales
390 if (1 == num || dstWidth > dinfo.output_width || dstHeight > dinfo.output_height) {
391 jpeg_destroy_decompress(&dinfo);
392 return false;
393 }
394
395 // Try the next scale
396 num -= 1;
397 calc_output_dimensions(&dinfo, num, denom);
398 }
399 jpeg_destroy_decompress(&dinfo);
400
401 fDecoderMgr->dinfo()->scale_num = num;
402 fDecoderMgr->dinfo()->scale_denom = denom;
403 return true;
404 }
405
406 SkCodec::Result SkJpegCodec::readRows(const SkImageInfo& dstInfo,
407 void* dst,
408 size_t rowBytes,
409 int count,
410 const Options& opts,
411 int* rowsDecoded) {
412 // Set the jump location for libjpeg-turbo errors
413 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
414 if (setjmp(jmp)) {
415 *rowsDecoded = 0;
416 return kInvalidInput;
417 }
418
419 // When fSwizzleSrcRow is non-null, it means that we need to swizzle. In this case,
420 // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer.
421 // We can never swizzle "in place" because the swizzler may perform sampling and/or
422 // subsetting.
423 // When fColorXformSrcRow is non-null, it means that we need to color xform and that
424 // we cannot color xform "in place" (many times we can, but not when the src and dst
425 // are different sizes).
426 // In this case, we will color xform from fColorXformSrcRow into the dst.
427 JSAMPLE* decodeDst = (JSAMPLE*) dst;
428 uint32_t* swizzleDst = (uint32_t*) dst;
429 size_t decodeDstRowBytes = rowBytes;
430 size_t swizzleDstRowBytes = rowBytes;
431 int dstWidth = opts.fSubset ? opts.fSubset->width() : dstInfo.width();
432 if (fSwizzleSrcRow && fColorXformSrcRow) {
433 decodeDst = (JSAMPLE*) fSwizzleSrcRow;
434 swizzleDst = fColorXformSrcRow;
435 decodeDstRowBytes = 0;
436 swizzleDstRowBytes = 0;
437 dstWidth = fSwizzler->swizzleWidth();
438 } else if (fColorXformSrcRow) {
439 decodeDst = (JSAMPLE*) fColorXformSrcRow;
440 swizzleDst = fColorXformSrcRow;
441 decodeDstRowBytes = 0;
442 swizzleDstRowBytes = 0;
443 } else if (fSwizzleSrcRow) {
444 decodeDst = (JSAMPLE*) fSwizzleSrcRow;
445 decodeDstRowBytes = 0;
446 dstWidth = fSwizzler->swizzleWidth();
447 }
448
449 for (int y = 0; y < count; y++) {
450 uint32_t lines = jpeg_read_scanlines(fDecoderMgr->dinfo(), &decodeDst, 1);
451 if (0 == lines) {
452 *rowsDecoded = y;
453 return kSuccess;
454 }
455
456 if (fSwizzler) {
457 fSwizzler->swizzle(swizzleDst, decodeDst);
458 }
459
460 if (this->colorXform()) {
461 this->applyColorXform(dst, swizzleDst, dstWidth);
462 dst = SkTAddOffset<void>(dst, rowBytes);
463 }
464
465 decodeDst = SkTAddOffset<JSAMPLE>(decodeDst, decodeDstRowBytes);
466 swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes);
467 }
468
469 *rowsDecoded = count;
470 return kSuccess;
471 }
472
473 /*
474 * This is a bit tricky. We only need the swizzler to do format conversion if the jpeg is
475 * encoded as CMYK.
476 * And even then we still may not need it. If the jpeg has a CMYK color profile and a color
477 * xform, the color xform will handle the CMYK->RGB conversion.
478 */
479 static inline bool needs_swizzler_to_convert_from_cmyk(J_COLOR_SPACE jpegColorType,
480 const SkCodecs::ColorProfile* srcProfile,
481 bool hasColorSpaceXform) {
482 if (JCS_CMYK != jpegColorType) {
483 return false;
484 }
485
486 bool hasCMYKColorSpace = srcProfile &&
487 srcProfile->dataSpace() == SkCodecs::ColorProfile::DataSpace::kCMYK;
488 return !hasCMYKColorSpace || !hasColorSpaceXform;
489 }
490
491 /*
492 * Performs the jpeg decode
493 */
494 SkCodec::Result SkJpegCodec::onGetPixels(const SkImageInfo& dstInfo,
495 void* dst, size_t dstRowBytes,
496 const Options& options,
497 int* rowsDecoded) {
498 if (options.fSubset) {
499 // Subsets are not supported.
500 return kUnimplemented;
501 }
502
503 // Get a pointer to the decompress info since we will use it quite frequently
504 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
505
506 // Set the jump location for libjpeg errors
507 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
508 if (setjmp(jmp)) {
509 return fDecoderMgr->returnFailure("setjmp", kInvalidInput);
510 }
511
512 const bool isProgressive = dinfo->progressive_mode;
513 if (isProgressive) {
514 dinfo->buffered_image = TRUE;
515 jpeg_start_decompress(dinfo);
516 } else if (!jpeg_start_decompress(dinfo)) {
517 return fDecoderMgr->returnFailure("startDecompress", kInvalidInput);
518 }
519
520 // The recommended output buffer height should always be 1 in high quality modes.
521 // If it's not, we want to know because it means our strategy is not optimal.
522 SkASSERT(1 == dinfo->rec_outbuf_height);
523
524 if (needs_swizzler_to_convert_from_cmyk(dinfo->out_color_space,
525 this->getEncodedInfo().colorProfile(),
526 this->colorXform())) {
527 this->initializeSwizzler(dstInfo, options, true);
528 }
529
530 if (!this->allocateStorage(dstInfo)) {
531 return kOutOfMemory;
532 }
533
534 if (isProgressive) {
535 // https://github.com/libjpeg-turbo/libjpeg-turbo/blob/af9c1c268520a29adf98cad5138dafe612b3d318/doc/libjpeg.txt
536 // "Worst case (1x1 sampling) [for a progressive JPEG] requires 6 bytes/pixel."
537 const size_t estimatedLibJpegMemory = 6 * this->dimensions().area();
538 if (!this->allocateFromBudget(estimatedLibJpegMemory)) {
539 return kOutOfMemory;
540 }
541 // Keep consuming input until we can't anymore, and only output/read scanlines
542 // if there is at least one valid output.
543 int last_scan_completed = 0;
544 while (!jpeg_input_complete(dinfo)) {
545 // Call the progress monitor hook if present, to prevent decoder from hanging.
546 if (dinfo->progress) {
547 dinfo->progress->progress_monitor((j_common_ptr)dinfo);
548 }
549 const int res = jpeg_consume_input(dinfo);
550 if (res == JPEG_SUSPENDED) {
551 break;
552 }
553 if (res == JPEG_SCAN_COMPLETED) {
554 last_scan_completed = dinfo->input_scan_number;
555 }
556 }
557 if (last_scan_completed <= 0) {
558 return fDecoderMgr->returnFailure("Incomplete image data", kIncompleteInput);
559 }
560 jpeg_start_output(dinfo, last_scan_completed);
561 int rows = 0;
562 SkCodec::Result readResult =
563 this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options, &rows);
564 // Checks if scan was called too many times to not stall the decoder.
565 jpeg_finish_output(dinfo);
566 if (readResult != kSuccess) {
567 return fDecoderMgr->returnFailure("readRows", readResult);
568 }
569 if (rows < dstInfo.height()) {
570 *rowsDecoded = rows;
571 return fDecoderMgr->returnFailure("Incomplete image data", kIncompleteInput);
572 }
573 return kSuccess;
574 }
575 // Baseline image
576 // https://github.com/libjpeg-turbo/libjpeg-turbo/blob/af9c1c268520a29adf98cad5138dafe612b3d318/doc/libjpeg.txt
577 // "The worst case for commonly used sampling factors is about 34 bytes * width in pixels for a
578 // color image."
579 const size_t estimatedLibJpegMemory = 34 * this->dimensions().width();
580 if (!this->allocateFromBudget(estimatedLibJpegMemory)) {
581 return kOutOfMemory;
582 }
583 int rows = 0;
584 this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options, &rows);
585 if (rows < dstInfo.height()) {
586 *rowsDecoded = rows;
587 return fDecoderMgr->returnFailure("Incomplete image data", kIncompleteInput);
588 }
589 return kSuccess;
590 }
591
592 bool SkJpegCodec::allocateStorage(const SkImageInfo& dstInfo) {
593 int dstWidth = dstInfo.width();
594
595 size_t swizzleBytes = 0;
596 if (fSwizzler) {
597 swizzleBytes = get_row_bytes(fDecoderMgr->dinfo());
598 dstWidth = fSwizzler->swizzleWidth();
599 SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes));
600 }
601
602 size_t xformBytes = 0;
603
604 if (this->colorXform() && sizeof(uint32_t) != dstInfo.bytesPerPixel()) {
605 xformBytes = dstWidth * sizeof(uint32_t);
606 }
607
608 size_t totalBytes = swizzleBytes + xformBytes;
609 if (totalBytes > 0) {
610 if (!this->allocateFromBudget(totalBytes)) {
611 return false;
612 }
613 if (!fStorage.reset(totalBytes)) {
614 return false;
615 }
616 fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr;
617 fColorXformSrcRow = (xformBytes > 0) ?
618 SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr;
619 }
620 return true;
621 }
622
623 void SkJpegCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& options,
624 bool needsCMYKToRGB) {
625 Options swizzlerOptions = options;
626 if (options.fSubset) {
627 // Use fSwizzlerSubset if this is a subset decode. This is necessary in the case
628 // where libjpeg-turbo provides a subset and then we need to subset it further.
629 // Also, verify that fSwizzlerSubset is initialized and valid.
630 SkASSERT(!fSwizzlerSubset.isEmpty() && fSwizzlerSubset.x() <= options.fSubset->x() &&
631 fSwizzlerSubset.width() == options.fSubset->width());
632 swizzlerOptions.fSubset = &fSwizzlerSubset;
633 }
634
635 SkImageInfo swizzlerDstInfo = dstInfo;
636 if (this->colorXform()) {
637 // The color xform will be expecting RGBA 8888 input.
638 swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType);
639 }
640
641 if (needsCMYKToRGB) {
642 // The swizzler is used to convert to from CMYK.
643 // The swizzler does not use the width or height on SkEncodedInfo.
644 auto swizzlerInfo = SkEncodedInfo::Make(0, 0, SkEncodedInfo::kInvertedCMYK_Color,
645 SkEncodedInfo::kOpaque_Alpha, 8);
646 fSwizzler = SkSwizzler::Make(swizzlerInfo, nullptr, swizzlerDstInfo, swizzlerOptions);
647 } else {
648 int srcBPP = 0;
649 switch (fDecoderMgr->dinfo()->out_color_space) {
650 case JCS_EXT_RGBA:
651 case JCS_EXT_BGRA:
652 case JCS_CMYK:
653 srcBPP = 4;
654 break;
655 case JCS_RGB565:
656 srcBPP = 2;
657 break;
658 case JCS_GRAYSCALE:
659 srcBPP = 1;
660 break;
661 default:
662 SkASSERT(false);
663 break;
664 }
665 fSwizzler = SkSwizzler::MakeSimple(srcBPP, swizzlerDstInfo, swizzlerOptions);
666 }
667 SkASSERT(fSwizzler);
668 }
669
670 SkSampler* SkJpegCodec::getSampler(bool createIfNecessary) {
671 if (!createIfNecessary || fSwizzler) {
672 SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow));
673 return fSwizzler.get();
674 }
675
676 bool needsCMYKToRGB = needs_swizzler_to_convert_from_cmyk(
677 fDecoderMgr->dinfo()->out_color_space, this->getEncodedInfo().colorProfile(),
678 this->colorXform());
679 this->initializeSwizzler(this->dstInfo(), this->options(), needsCMYKToRGB);
680 if (!this->allocateStorage(this->dstInfo())) {
681 return nullptr;
682 }
683 return fSwizzler.get();
684 }
685
686 SkCodec::Result SkJpegCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
687 const Options& options) {
688 // Set the jump location for libjpeg errors
689 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
690 if (setjmp(jmp)) {
691 SkCodecPrintf("setjmp: Error from libjpeg\n");
692 return kInvalidInput;
693 }
694
695 if (!jpeg_start_decompress(fDecoderMgr->dinfo())) {
696 SkCodecPrintf("start decompress failed\n");
697 return kInvalidInput;
698 }
699
700 bool needsCMYKToRGB = needs_swizzler_to_convert_from_cmyk(
701 fDecoderMgr->dinfo()->out_color_space, this->getEncodedInfo().colorProfile(),
702 this->colorXform());
703 if (options.fSubset) {
704 uint32_t startX = options.fSubset->x();
705 uint32_t width = options.fSubset->width();
706
707 // libjpeg-turbo may need to align startX to a multiple of the IDCT
708 // block size. If this is the case, it will decrease the value of
709 // startX to the appropriate alignment and also increase the value
710 // of width so that the right edge of the requested subset remains
711 // the same.
712 jpeg_crop_scanline(fDecoderMgr->dinfo(), &startX, &width);
713
714 SkASSERT(startX <= (uint32_t) options.fSubset->x());
715 SkASSERT(width >= (uint32_t) options.fSubset->width());
716 SkASSERT(startX + width >= (uint32_t) options.fSubset->right());
717
718 // Instruct the swizzler (if it is necessary) to further subset the
719 // output provided by libjpeg-turbo.
720 //
721 // We set this here (rather than in the if statement below), so that
722 // if (1) we don't need a swizzler for the subset, and (2) we need a
723 // swizzler for CMYK, the swizzler will still use the proper subset
724 // dimensions.
725 //
726 // Note that the swizzler will ignore the y and height parameters of
727 // the subset. Since the scanline decoder (and the swizzler) handle
728 // one row at a time, only the subsetting in the x-dimension matters.
729 fSwizzlerSubset.setXYWH(options.fSubset->x() - startX, 0,
730 options.fSubset->width(), options.fSubset->height());
731
732 // We will need a swizzler if libjpeg-turbo cannot provide the exact
733 // subset that we request.
734 if (startX != (uint32_t) options.fSubset->x() ||
735 width != (uint32_t) options.fSubset->width()) {
736 this->initializeSwizzler(dstInfo, options, needsCMYKToRGB);
737 }
738 }
739
740 // Make sure we have a swizzler if we are converting from CMYK.
741 if (!fSwizzler && needsCMYKToRGB) {
742 this->initializeSwizzler(dstInfo, options, true);
743 }
744
745 if (!this->allocateStorage(dstInfo)) {
746 return kOutOfMemory;
747 }
748
749 return kSuccess;
750 }
751
752 int SkJpegCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) {
753 int rows = 0;
754 this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options(), &rows);
755 if (rows < count) {
756 // This allows us to skip calling jpeg_finish_decompress().
757 fDecoderMgr->dinfo()->output_scanline = this->dstInfo().height();
758 }
759
760 return rows;
761 }
762
763 bool SkJpegCodec::onSkipScanlines(int count) {
764 // Set the jump location for libjpeg errors
765 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
766 if (setjmp(jmp)) {
767 return fDecoderMgr->returnFalse("onSkipScanlines");
768 }
769
770 return (uint32_t) count == jpeg_skip_scanlines(fDecoderMgr->dinfo(), count);
771 }
772
773 static bool is_yuv_supported(const jpeg_decompress_struct* dinfo,
774 const SkJpegCodec& codec,
775 const SkYUVAPixmapInfo::SupportedDataTypes* supportedDataTypes,
776 SkYUVAPixmapInfo* yuvaPixmapInfo) {
777 // Scaling is not supported in raw data mode.
778 SkASSERT(dinfo->scale_num == dinfo->scale_denom);
779
780 // I can't imagine that this would ever change, but we do depend on it.
781 static_assert(8 == DCTSIZE, "DCTSIZE (defined in jpeg library) should always be 8.");
782
783 if (JCS_YCbCr != dinfo->jpeg_color_space) {
784 return false;
785 }
786
787 SkASSERT(3 == dinfo->num_components);
788 SkASSERT(dinfo->comp_info);
789
790 // It is possible to perform a YUV decode for any combination of
791 // horizontal and vertical sampling that is supported by
792 // libjpeg/libjpeg-turbo. However, we will start by supporting only the
793 // common cases (where U and V have samp_factors of one).
794 //
795 // The definition of samp_factor is kind of the opposite of what SkCodec
796 // thinks of as a sampling factor. samp_factor is essentially a
797 // multiplier, and the larger the samp_factor is, the more samples that
798 // there will be. Ex:
799 // U_plane_width = image_width * (U_h_samp_factor / max_h_samp_factor)
800 //
801 // Supporting cases where the samp_factors for U or V were larger than
802 // that of Y would be an extremely difficult change, given that clients
803 // allocate memory as if the size of the Y plane is always the size of the
804 // image. However, this case is very, very rare.
805 if ((1 != dinfo->comp_info[1].h_samp_factor) ||
806 (1 != dinfo->comp_info[1].v_samp_factor) ||
807 (1 != dinfo->comp_info[2].h_samp_factor) ||
808 (1 != dinfo->comp_info[2].v_samp_factor))
809 {
810 return false;
811 }
812
813 // Support all common cases of Y samp_factors.
814 // TODO (msarett): As mentioned above, it would be possible to support
815 // more combinations of samp_factors. The issues are:
816 // (1) Are there actually any images that are not covered
817 // by these cases?
818 // (2) How much complexity would be added to the
819 // implementation in order to support these rare
820 // cases?
821 int hSampY = dinfo->comp_info[0].h_samp_factor;
822 int vSampY = dinfo->comp_info[0].v_samp_factor;
823 SkASSERT(hSampY == dinfo->max_h_samp_factor);
824 SkASSERT(vSampY == dinfo->max_v_samp_factor);
825
826 SkYUVAInfo::Subsampling tempSubsampling;
827 if (1 == hSampY && 1 == vSampY) {
828 tempSubsampling = SkYUVAInfo::Subsampling::k444;
829 } else if (2 == hSampY && 1 == vSampY) {
830 tempSubsampling = SkYUVAInfo::Subsampling::k422;
831 } else if (2 == hSampY && 2 == vSampY) {
832 tempSubsampling = SkYUVAInfo::Subsampling::k420;
833 } else if (1 == hSampY && 2 == vSampY) {
834 tempSubsampling = SkYUVAInfo::Subsampling::k440;
835 } else if (4 == hSampY && 1 == vSampY) {
836 tempSubsampling = SkYUVAInfo::Subsampling::k411;
837 } else if (4 == hSampY && 2 == vSampY) {
838 tempSubsampling = SkYUVAInfo::Subsampling::k410;
839 } else {
840 return false;
841 }
842 if (supportedDataTypes &&
843 !supportedDataTypes->supported(SkYUVAInfo::PlaneConfig::kY_U_V,
844 SkYUVAPixmapInfo::DataType::kUnorm8)) {
845 return false;
846 }
847 if (yuvaPixmapInfo) {
848 SkColorType colorTypes[SkYUVAPixmapInfo::kMaxPlanes];
849 size_t rowBytes[SkYUVAPixmapInfo::kMaxPlanes];
850 for (int i = 0; i < 3; ++i) {
851 colorTypes[i] = kAlpha_8_SkColorType;
852 rowBytes[i] = dinfo->comp_info[i].width_in_blocks * DCTSIZE;
853 }
854 SkYUVAInfo yuvaInfo(codec.dimensions(),
855 SkYUVAInfo::PlaneConfig::kY_U_V,
856 tempSubsampling,
857 kJPEG_Full_SkYUVColorSpace,
858 codec.getOrigin(),
859 SkYUVAInfo::Siting::kCentered,
860 SkYUVAInfo::Siting::kCentered);
861 *yuvaPixmapInfo = SkYUVAPixmapInfo(yuvaInfo, colorTypes, rowBytes);
862 }
863 return true;
864 }
865
866 bool SkJpegCodec::onQueryYUVAInfo(const SkYUVAPixmapInfo::SupportedDataTypes& supportedDataTypes,
867 SkYUVAPixmapInfo* yuvaPixmapInfo) const {
868 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
869 return is_yuv_supported(dinfo, *this, &supportedDataTypes, yuvaPixmapInfo);
870 }
871
872 SkCodec::Result SkJpegCodec::onGetYUVAPlanes(const SkYUVAPixmaps& yuvaPixmaps) {
873 // Get a pointer to the decompress info since we will use it quite frequently
874 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
875 if (!is_yuv_supported(dinfo, *this, nullptr, nullptr)) {
876 return fDecoderMgr->returnFailure("onGetYUVAPlanes", kInvalidInput);
877 }
878 // Set the jump location for libjpeg errors
879 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
880 if (setjmp(jmp)) {
881 return fDecoderMgr->returnFailure("setjmp", kInvalidInput);
882 }
883
884 dinfo->raw_data_out = TRUE;
885 if (!jpeg_start_decompress(dinfo)) {
886 return fDecoderMgr->returnFailure("startDecompress", kInvalidInput);
887 }
888
889 const std::array<SkPixmap, SkYUVAPixmaps::kMaxPlanes>& planes = yuvaPixmaps.planes();
890
891 #ifdef SK_DEBUG
892 {
893 // A previous implementation claims that the return value of is_yuv_supported()
894 // may change after calling jpeg_start_decompress(). It looks to me like this
895 // was caused by a bug in the old code, but we'll be safe and check here.
896 // Also check that pixmap properties agree with expectations.
897 SkYUVAPixmapInfo info;
898 SkASSERT(is_yuv_supported(dinfo, *this, nullptr, &info));
899 SkASSERT(info.yuvaInfo() == yuvaPixmaps.yuvaInfo());
900 for (int i = 0; i < info.numPlanes(); ++i) {
901 SkASSERT(planes[i].colorType() == kAlpha_8_SkColorType);
902 SkASSERT(info.planeInfo(i) == planes[i].info());
903 }
904 }
905 #endif
906
907 // Build a JSAMPIMAGE to handle output from libjpeg-turbo. A JSAMPIMAGE has
908 // a 2-D array of pixels for each of the components (Y, U, V) in the image.
909 // Cheat Sheet:
910 // JSAMPIMAGE == JSAMPLEARRAY* == JSAMPROW** == JSAMPLE***
911 JSAMPARRAY yuv[3];
912
913 // Set aside enough space for pointers to rows of Y, U, and V.
914 JSAMPROW rowptrs[2 * DCTSIZE + DCTSIZE + DCTSIZE];
915 yuv[0] = &rowptrs[0]; // Y rows (DCTSIZE or 2 * DCTSIZE)
916 yuv[1] = &rowptrs[2 * DCTSIZE]; // U rows (DCTSIZE)
917 yuv[2] = &rowptrs[3 * DCTSIZE]; // V rows (DCTSIZE)
918
919 // Initialize rowptrs.
920 int numYRowsPerBlock = DCTSIZE * dinfo->comp_info[0].v_samp_factor;
921 static_assert(sizeof(JSAMPLE) == 1);
922 for (int i = 0; i < numYRowsPerBlock; i++) {
923 rowptrs[i] = static_cast<JSAMPLE*>(planes[0].writable_addr()) + i* planes[0].rowBytes();
924 }
925 for (int i = 0; i < DCTSIZE; i++) {
926 rowptrs[i + 2 * DCTSIZE] =
927 static_cast<JSAMPLE*>(planes[1].writable_addr()) + i* planes[1].rowBytes();
928 rowptrs[i + 3 * DCTSIZE] =
929 static_cast<JSAMPLE*>(planes[2].writable_addr()) + i* planes[2].rowBytes();
930 }
931
932 // After each loop iteration, we will increment pointers to Y, U, and V.
933 size_t blockIncrementY = numYRowsPerBlock * planes[0].rowBytes();
934 size_t blockIncrementU = DCTSIZE * planes[1].rowBytes();
935 size_t blockIncrementV = DCTSIZE * planes[2].rowBytes();
936
937 uint32_t numRowsPerBlock = numYRowsPerBlock;
938
939 // We intentionally round down here, as this first loop will only handle
940 // full block rows. As a special case at the end, we will handle any
941 // remaining rows that do not make up a full block.
942 const int numIters = dinfo->output_height / numRowsPerBlock;
943 for (int i = 0; i < numIters; i++) {
944 JDIMENSION linesRead = jpeg_read_raw_data(dinfo, yuv, numRowsPerBlock);
945 if (linesRead < numRowsPerBlock) {
946 // FIXME: Handle incomplete YUV decodes without signalling an error.
947 return kInvalidInput;
948 }
949
950 // Update rowptrs.
951 for (int j = 0; j < numYRowsPerBlock; j++) {
952 rowptrs[j] += blockIncrementY;
953 }
954 for (int j = 0; j < DCTSIZE; j++) {
955 rowptrs[j + 2 * DCTSIZE] += blockIncrementU;
956 rowptrs[j + 3 * DCTSIZE] += blockIncrementV;
957 }
958 }
959
960 uint32_t remainingRows = dinfo->output_height - dinfo->output_scanline;
961 SkASSERT(remainingRows == dinfo->output_height % numRowsPerBlock);
962 SkASSERT(dinfo->output_scanline == numIters * numRowsPerBlock);
963 if (remainingRows > 0) {
964 // libjpeg-turbo needs memory to be padded by the block sizes. We will fulfill
965 // this requirement using an extra row buffer.
966 // FIXME: Should SkCodec have an extra memory buffer that can be shared among
967 // all of the implementations that use temporary/garbage memory?
968 AutoTMalloc<JSAMPLE> extraRow(planes[0].rowBytes());
969 for (int i = remainingRows; i < numYRowsPerBlock; i++) {
970 rowptrs[i] = extraRow.get();
971 }
972 int remainingUVRows = dinfo->comp_info[1].downsampled_height - DCTSIZE * numIters;
973 for (int i = remainingUVRows; i < DCTSIZE; i++) {
974 rowptrs[i + 2 * DCTSIZE] = extraRow.get();
975 rowptrs[i + 3 * DCTSIZE] = extraRow.get();
976 }
977
978 JDIMENSION linesRead = jpeg_read_raw_data(dinfo, yuv, numRowsPerBlock);
979 if (linesRead < remainingRows) {
980 // FIXME: Handle incomplete YUV decodes without signalling an error.
981 return kInvalidInput;
982 }
983 }
984
985 return kSuccess;
986 }
987
988 bool SkJpegCodec::onGetGainmapCodec(SkGainmapInfo* info, std::unique_ptr<SkCodec>* gainmapCodec) {
989 std::unique_ptr<SkStream> stream;
990 if (!this->onGetGainmapInfo(info, &stream)) {
991 return false;
992 }
993 if (gainmapCodec) {
994 Result result;
995 *gainmapCodec = MakeFromStream(std::move(stream), &result);
996 if (!*gainmapCodec) {
997 return false;
998 }
999 }
1000 return true;
1001 }
1002
1003 bool SkJpegCodec::onGetGainmapInfo(SkGainmapInfo* info,
1004 std::unique_ptr<SkStream>* gainmapImageStream) {
1005 #ifdef SK_CODEC_DECODES_JPEG_GAINMAPS
1006 auto metadataDecoder =
1007 std::make_unique<SkJpegMetadataDecoderImpl>(get_sk_marker_list(fDecoderMgr->dinfo()));
1008 if (auto [data, gInfo] = metadataDecoder->findGainmapImage(fDecoderMgr->getSourceMgr()); data) {
1009 *info = gInfo;
1010 *gainmapImageStream = SkMemoryStream::Make(data);
1011 return true;
1012 }
1013 #endif // SK_CODEC_DECODES_JPEG_GAINMAPS
1014 return false;
1015 }
1016
1017 namespace SkJpegDecoder {
1018 bool IsJpeg(const void* data, size_t len) {
1019 return SkJpegCodec::IsJpeg(data, len);
1020 }
1021
1022 std::unique_ptr<SkCodec> Decode(std::unique_ptr<SkStream> stream,
1023 SkCodec::Result* outResult,
1024 SkCodecs::DecodeContext) {
1025 SkCodec::Result resultStorage;
1026 if (!outResult) {
1027 outResult = &resultStorage;
1028 }
1029 return SkJpegCodec::MakeFromStream(std::move(stream), outResult);
1030 }
1031
1032 std::unique_ptr<SkCodec> Decode(sk_sp<const SkData> data,
1033 SkCodec::Result* outResult,
1034 SkCodecs::DecodeContext) {
1035 if (!data) {
1036 if (outResult) {
1037 *outResult = SkCodec::kInvalidInput;
1038 }
1039 return nullptr;
1040 }
1041 return Decode(SkMemoryStream::Make(std::move(data)), outResult, nullptr);
1042 }
1043
1044 } // namespace SkJpegDecoder