blob: 9a08755b644e25d44948955e7e40fa6a5ee6b9ad [file] [log] [blame]
msarette16b04a2015-04-15 07:32:19 -07001/*
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 "SkCodec.h"
mtkleine721a8e2016-02-06 19:12:23 -08009#include "SkMSAN.h"
msarette16b04a2015-04-15 07:32:19 -070010#include "SkJpegCodec.h"
11#include "SkJpegDecoderMgr.h"
msarette16b04a2015-04-15 07:32:19 -070012#include "SkCodecPriv.h"
13#include "SkColorPriv.h"
raftias54761282016-12-01 13:44:07 -050014#include "SkColorSpace_Base.h"
msarette16b04a2015-04-15 07:32:19 -070015#include "SkStream.h"
16#include "SkTemplates.h"
17#include "SkTypes.h"
18
msarett1c8a5872015-07-07 08:50:01 -070019// stdio is needed for libjpeg-turbo
msarette16b04a2015-04-15 07:32:19 -070020#include <stdio.h>
msarettc1d03122016-03-25 08:58:55 -070021#include "SkJpegUtility.h"
msarette16b04a2015-04-15 07:32:19 -070022
mtkleindc90b532016-07-28 14:45:28 -070023// This warning triggers false postives way too often in here.
24#if defined(__GNUC__) && !defined(__clang__)
25 #pragma GCC diagnostic ignored "-Wclobbered"
26#endif
27
msarette16b04a2015-04-15 07:32:19 -070028extern "C" {
29 #include "jerror.h"
msarette16b04a2015-04-15 07:32:19 -070030 #include "jpeglib.h"
31}
32
scroggodb30be22015-12-08 18:54:13 -080033bool SkJpegCodec::IsJpeg(const void* buffer, size_t bytesRead) {
msarette16b04a2015-04-15 07:32:19 -070034 static const uint8_t jpegSig[] = { 0xFF, 0xD8, 0xFF };
scroggodb30be22015-12-08 18:54:13 -080035 return bytesRead >= 3 && !memcmp(buffer, jpegSig, sizeof(jpegSig));
msarette16b04a2015-04-15 07:32:19 -070036}
37
msarett0e6274f2016-03-21 08:04:40 -070038static uint32_t get_endian_int(const uint8_t* data, bool littleEndian) {
39 if (littleEndian) {
40 return (data[3] << 24) | (data[2] << 16) | (data[1] << 8) | (data[0]);
41 }
42
43 return (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | (data[3]);
44}
45
46const uint32_t kExifHeaderSize = 14;
47const uint32_t kICCHeaderSize = 14;
48const uint32_t kExifMarker = JPEG_APP0 + 1;
49const uint32_t kICCMarker = JPEG_APP0 + 2;
50
51static bool is_orientation_marker(jpeg_marker_struct* marker, SkCodec::Origin* orientation) {
52 if (kExifMarker != marker->marker || marker->data_length < kExifHeaderSize) {
53 return false;
54 }
55
56 const uint8_t* data = marker->data;
57 static const uint8_t kExifSig[] { 'E', 'x', 'i', 'f', '\0' };
58 if (memcmp(data, kExifSig, sizeof(kExifSig))) {
59 return false;
60 }
61
62 bool littleEndian;
63 if (!is_valid_endian_marker(data + 6, &littleEndian)) {
64 return false;
65 }
66
67 // Get the offset from the start of the marker.
68 // Account for 'E', 'x', 'i', 'f', '\0', '<fill byte>'.
69 uint32_t offset = get_endian_int(data + 10, littleEndian);
70 offset += sizeof(kExifSig) + 1;
71
72 // Require that the marker is at least large enough to contain the number of entries.
73 if (marker->data_length < offset + 2) {
74 return false;
75 }
76 uint32_t numEntries = get_endian_short(data + offset, littleEndian);
77
78 // Tag (2 bytes), Datatype (2 bytes), Number of elements (4 bytes), Data (4 bytes)
79 const uint32_t kEntrySize = 12;
80 numEntries = SkTMin(numEntries, (marker->data_length - offset - 2) / kEntrySize);
81
82 // Advance the data to the start of the entries.
83 data += offset + 2;
84
85 const uint16_t kOriginTag = 0x112;
86 const uint16_t kOriginType = 3;
87 for (uint32_t i = 0; i < numEntries; i++, data += kEntrySize) {
88 uint16_t tag = get_endian_short(data, littleEndian);
89 uint16_t type = get_endian_short(data + 2, littleEndian);
90 uint32_t count = get_endian_int(data + 4, littleEndian);
91 if (kOriginTag == tag && kOriginType == type && 1 == count) {
92 uint16_t val = get_endian_short(data + 8, littleEndian);
93 if (0 < val && val <= SkCodec::kLast_Origin) {
94 *orientation = (SkCodec::Origin) val;
95 return true;
96 }
97 }
98 }
99
100 return false;
101}
102
103static SkCodec::Origin get_exif_orientation(jpeg_decompress_struct* dinfo) {
104 SkCodec::Origin orientation;
105 for (jpeg_marker_struct* marker = dinfo->marker_list; marker; marker = marker->next) {
106 if (is_orientation_marker(marker, &orientation)) {
107 return orientation;
108 }
109 }
110
111 return SkCodec::kDefault_Origin;
112}
113
114static bool is_icc_marker(jpeg_marker_struct* marker) {
115 if (kICCMarker != marker->marker || marker->data_length < kICCHeaderSize) {
116 return false;
117 }
118
119 static const uint8_t kICCSig[] { 'I', 'C', 'C', '_', 'P', 'R', 'O', 'F', 'I', 'L', 'E', '\0' };
120 return !memcmp(marker->data, kICCSig, sizeof(kICCSig));
121}
122
123/*
124 * ICC profiles may be stored using a sequence of multiple markers. We obtain the ICC profile
125 * in two steps:
126 * (1) Discover all ICC profile markers and verify that they are numbered properly.
127 * (2) Copy the data from each marker into a contiguous ICC profile.
128 */
msarett9876ac52016-06-01 14:47:18 -0700129static sk_sp<SkData> get_icc_profile(jpeg_decompress_struct* dinfo) {
msarett0e6274f2016-03-21 08:04:40 -0700130 // Note that 256 will be enough storage space since each markerIndex is stored in 8-bits.
131 jpeg_marker_struct* markerSequence[256];
132 memset(markerSequence, 0, sizeof(markerSequence));
133 uint8_t numMarkers = 0;
134 size_t totalBytes = 0;
135
136 // Discover any ICC markers and verify that they are numbered properly.
137 for (jpeg_marker_struct* marker = dinfo->marker_list; marker; marker = marker->next) {
138 if (is_icc_marker(marker)) {
139 // Verify that numMarkers is valid and consistent.
140 if (0 == numMarkers) {
141 numMarkers = marker->data[13];
142 if (0 == numMarkers) {
143 SkCodecPrintf("ICC Profile Error: numMarkers must be greater than zero.\n");
144 return nullptr;
145 }
146 } else if (numMarkers != marker->data[13]) {
147 SkCodecPrintf("ICC Profile Error: numMarkers must be consistent.\n");
148 return nullptr;
149 }
150
151 // Verify that the markerIndex is valid and unique. Note that zero is not
152 // a valid index.
153 uint8_t markerIndex = marker->data[12];
154 if (markerIndex == 0 || markerIndex > numMarkers) {
155 SkCodecPrintf("ICC Profile Error: markerIndex is invalid.\n");
156 return nullptr;
157 }
158 if (markerSequence[markerIndex]) {
159 SkCodecPrintf("ICC Profile Error: Duplicate value of markerIndex.\n");
160 return nullptr;
161 }
162 markerSequence[markerIndex] = marker;
163 SkASSERT(marker->data_length >= kICCHeaderSize);
164 totalBytes += marker->data_length - kICCHeaderSize;
165 }
166 }
167
168 if (0 == totalBytes) {
169 // No non-empty ICC profile markers were found.
170 return nullptr;
171 }
172
173 // Combine the ICC marker data into a contiguous profile.
msarett9876ac52016-06-01 14:47:18 -0700174 sk_sp<SkData> iccData = SkData::MakeUninitialized(totalBytes);
175 void* dst = iccData->writable_data();
msarett0e6274f2016-03-21 08:04:40 -0700176 for (uint32_t i = 1; i <= numMarkers; i++) {
177 jpeg_marker_struct* marker = markerSequence[i];
178 if (!marker) {
179 SkCodecPrintf("ICC Profile Error: Missing marker %d of %d.\n", i, numMarkers);
180 return nullptr;
181 }
182
183 void* src = SkTAddOffset<void>(marker->data, kICCHeaderSize);
184 size_t bytes = marker->data_length - kICCHeaderSize;
185 memcpy(dst, src, bytes);
186 dst = SkTAddOffset<void>(dst, bytes);
187 }
188
msarett9876ac52016-06-01 14:47:18 -0700189 return iccData;
msarett0e6274f2016-03-21 08:04:40 -0700190}
191
msarette16b04a2015-04-15 07:32:19 -0700192bool SkJpegCodec::ReadHeader(SkStream* stream, SkCodec** codecOut,
193 JpegDecoderMgr** decoderMgrOut) {
194
195 // Create a JpegDecoderMgr to own all of the decompress information
Ben Wagner145dbcd2016-11-03 14:40:50 -0400196 std::unique_ptr<JpegDecoderMgr> decoderMgr(new JpegDecoderMgr(stream));
msarette16b04a2015-04-15 07:32:19 -0700197
198 // libjpeg errors will be caught and reported here
mtklein2f428962016-07-28 13:59:59 -0700199 if (setjmp(decoderMgr->getJmpBuf())) {
msarett50ce1f22016-07-29 06:23:33 -0700200 return decoderMgr->returnFalse("ReadHeader");
msarette16b04a2015-04-15 07:32:19 -0700201 }
202
203 // Initialize the decompress info and the source manager
204 decoderMgr->init();
205
msarett0e6274f2016-03-21 08:04:40 -0700206 // Instruct jpeg library to save the markers that we care about. Since
207 // the orientation and color profile will not change, we can skip this
208 // step on rewinds.
209 if (codecOut) {
210 jpeg_save_markers(decoderMgr->dinfo(), kExifMarker, 0xFFFF);
211 jpeg_save_markers(decoderMgr->dinfo(), kICCMarker, 0xFFFF);
212 }
213
msarette16b04a2015-04-15 07:32:19 -0700214 // Read the jpeg header
msarettfbccb592015-09-01 06:43:41 -0700215 if (JPEG_HEADER_OK != jpeg_read_header(decoderMgr->dinfo(), true)) {
msarett50ce1f22016-07-29 06:23:33 -0700216 return decoderMgr->returnFalse("ReadHeader");
msarette16b04a2015-04-15 07:32:19 -0700217 }
218
msarett0e6274f2016-03-21 08:04:40 -0700219 if (codecOut) {
msarettc30c4182016-04-20 11:53:35 -0700220 // Get the encoded color type
msarettac6c7502016-04-25 09:30:24 -0700221 SkEncodedInfo::Color color;
222 if (!decoderMgr->getEncodedColor(&color)) {
msarettc30c4182016-04-20 11:53:35 -0700223 return false;
224 }
msarette16b04a2015-04-15 07:32:19 -0700225
226 // Create image info object and the codec
msarettc30c4182016-04-20 11:53:35 -0700227 SkEncodedInfo info = SkEncodedInfo::Make(color, SkEncodedInfo::kOpaque_Alpha, 8);
msarett0e6274f2016-03-21 08:04:40 -0700228
229 Origin orientation = get_exif_orientation(decoderMgr->dinfo());
msarett9876ac52016-06-01 14:47:18 -0700230 sk_sp<SkData> iccData = get_icc_profile(decoderMgr->dinfo());
231 sk_sp<SkColorSpace> colorSpace = nullptr;
232 if (iccData) {
raftias54761282016-12-01 13:44:07 -0500233 SkColorSpace_Base::InputColorFormat inputColorFormat =
234 SkColorSpace_Base::InputColorFormat::kRGB;
235 switch (decoderMgr->dinfo()->jpeg_color_space) {
236 case JCS_CMYK:
237 case JCS_YCCK:
238 inputColorFormat = SkColorSpace_Base::InputColorFormat::kCMYK;
239 break;
raftias91db12d2016-12-02 11:56:59 -0500240 case JCS_GRAYSCALE:
241 inputColorFormat = SkColorSpace_Base::InputColorFormat::kGray;
242 break;
raftias54761282016-12-01 13:44:07 -0500243 default:
244 break;
245 }
246 colorSpace = SkColorSpace_Base::MakeICC(iccData->data(), iccData->size(),
247 inputColorFormat);
msarett9876ac52016-06-01 14:47:18 -0700248 if (!colorSpace) {
249 SkCodecPrintf("Could not create SkColorSpace from ICC data.\n");
250 }
251 }
msarettf34cd632016-05-25 10:13:53 -0700252 if (!colorSpace) {
253 // Treat unmarked jpegs as sRGB.
Brian Osman526972e2016-10-24 09:24:02 -0400254 colorSpace = SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named);
msarettf34cd632016-05-25 10:13:53 -0700255 }
msarett0e6274f2016-03-21 08:04:40 -0700256
msarettc30c4182016-04-20 11:53:35 -0700257 const int width = decoderMgr->dinfo()->image_width;
258 const int height = decoderMgr->dinfo()->image_height;
msarettf34cd632016-05-25 10:13:53 -0700259 *codecOut = new SkJpegCodec(width, height, info, stream, decoderMgr.release(),
Matt Saretta9e9bfc2016-11-01 12:19:50 -0400260 std::move(colorSpace), orientation);
msarette16b04a2015-04-15 07:32:19 -0700261 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700262 SkASSERT(nullptr != decoderMgrOut);
mtklein18300a32016-03-16 13:53:35 -0700263 *decoderMgrOut = decoderMgr.release();
msarette16b04a2015-04-15 07:32:19 -0700264 }
265 return true;
266}
267
268SkCodec* SkJpegCodec::NewFromStream(SkStream* stream) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400269 std::unique_ptr<SkStream> streamDeleter(stream);
halcanary96fcdcc2015-08-27 07:41:13 -0700270 SkCodec* codec = nullptr;
271 if (ReadHeader(stream, &codec, nullptr)) {
msarette16b04a2015-04-15 07:32:19 -0700272 // Codec has taken ownership of the stream, we do not need to delete it
273 SkASSERT(codec);
mtklein18300a32016-03-16 13:53:35 -0700274 streamDeleter.release();
msarette16b04a2015-04-15 07:32:19 -0700275 return codec;
276 }
halcanary96fcdcc2015-08-27 07:41:13 -0700277 return nullptr;
msarette16b04a2015-04-15 07:32:19 -0700278}
279
msarettc30c4182016-04-20 11:53:35 -0700280SkJpegCodec::SkJpegCodec(int width, int height, const SkEncodedInfo& info, SkStream* stream,
Matt Saretta9e9bfc2016-11-01 12:19:50 -0400281 JpegDecoderMgr* decoderMgr, sk_sp<SkColorSpace> colorSpace, Origin origin)
msarettf34cd632016-05-25 10:13:53 -0700282 : INHERITED(width, height, info, stream, std::move(colorSpace), origin)
msarette16b04a2015-04-15 07:32:19 -0700283 , fDecoderMgr(decoderMgr)
msarettfbccb592015-09-01 06:43:41 -0700284 , fReadyState(decoderMgr->dinfo()->global_state)
msarett50ce1f22016-07-29 06:23:33 -0700285 , fSwizzleSrcRow(nullptr)
286 , fColorXformSrcRow(nullptr)
msarett91c22b22016-02-22 12:27:46 -0800287 , fSwizzlerSubset(SkIRect::MakeEmpty())
msarette16b04a2015-04-15 07:32:19 -0700288{}
289
290/*
emmaleer8f4ba762015-08-14 07:44:46 -0700291 * Return the row bytes of a particular image type and width
292 */
msarett23e78d32016-02-06 15:58:50 -0800293static size_t get_row_bytes(const j_decompress_ptr dinfo) {
msarett70e418b2016-02-12 12:35:48 -0800294 const size_t colorBytes = (dinfo->out_color_space == JCS_RGB565) ? 2 :
295 dinfo->out_color_components;
emmaleer8f4ba762015-08-14 07:44:46 -0700296 return dinfo->output_width * colorBytes;
297
298}
scroggoe7fc14b2015-10-02 13:14:46 -0700299
300/*
301 * Calculate output dimensions based on the provided factors.
302 *
303 * Not to be used on the actual jpeg_decompress_struct used for decoding, since it will
304 * incorrectly modify num_components.
305 */
306void calc_output_dimensions(jpeg_decompress_struct* dinfo, unsigned int num, unsigned int denom) {
307 dinfo->num_components = 0;
308 dinfo->scale_num = num;
309 dinfo->scale_denom = denom;
310 jpeg_calc_output_dimensions(dinfo);
311}
312
emmaleer8f4ba762015-08-14 07:44:46 -0700313/*
msarette16b04a2015-04-15 07:32:19 -0700314 * Return a valid set of output dimensions for this decoder, given an input scale
315 */
316SkISize SkJpegCodec::onGetScaledDimensions(float desiredScale) const {
msarett1c8a5872015-07-07 08:50:01 -0700317 // 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
318 // support these as well
scroggoe7fc14b2015-10-02 13:14:46 -0700319 unsigned int num;
320 unsigned int denom = 8;
msarettfdb47572015-10-13 12:50:14 -0700321 if (desiredScale >= 0.9375) {
msarett1c8a5872015-07-07 08:50:01 -0700322 num = 8;
msarettfdb47572015-10-13 12:50:14 -0700323 } else if (desiredScale >= 0.8125) {
msarett1c8a5872015-07-07 08:50:01 -0700324 num = 7;
msarettfdb47572015-10-13 12:50:14 -0700325 } else if (desiredScale >= 0.6875f) {
msarett1c8a5872015-07-07 08:50:01 -0700326 num = 6;
msarettfdb47572015-10-13 12:50:14 -0700327 } else if (desiredScale >= 0.5625f) {
msarett1c8a5872015-07-07 08:50:01 -0700328 num = 5;
msarettfdb47572015-10-13 12:50:14 -0700329 } else if (desiredScale >= 0.4375f) {
msarett1c8a5872015-07-07 08:50:01 -0700330 num = 4;
msarettfdb47572015-10-13 12:50:14 -0700331 } else if (desiredScale >= 0.3125f) {
msarett1c8a5872015-07-07 08:50:01 -0700332 num = 3;
msarettfdb47572015-10-13 12:50:14 -0700333 } else if (desiredScale >= 0.1875f) {
msarett1c8a5872015-07-07 08:50:01 -0700334 num = 2;
msarette16b04a2015-04-15 07:32:19 -0700335 } else {
msarett1c8a5872015-07-07 08:50:01 -0700336 num = 1;
msarette16b04a2015-04-15 07:32:19 -0700337 }
338
339 // Set up a fake decompress struct in order to use libjpeg to calculate output dimensions
340 jpeg_decompress_struct dinfo;
mtkleinf7aaadb2015-04-16 06:09:27 -0700341 sk_bzero(&dinfo, sizeof(dinfo));
msarette16b04a2015-04-15 07:32:19 -0700342 dinfo.image_width = this->getInfo().width();
343 dinfo.image_height = this->getInfo().height();
msarettfbccb592015-09-01 06:43:41 -0700344 dinfo.global_state = fReadyState;
scroggoe7fc14b2015-10-02 13:14:46 -0700345 calc_output_dimensions(&dinfo, num, denom);
msarette16b04a2015-04-15 07:32:19 -0700346
347 // Return the calculated output dimensions for the given scale
348 return SkISize::Make(dinfo.output_width, dinfo.output_height);
349}
350
scroggob427db12015-08-12 07:24:13 -0700351bool SkJpegCodec::onRewind() {
halcanary96fcdcc2015-08-27 07:41:13 -0700352 JpegDecoderMgr* decoderMgr = nullptr;
353 if (!ReadHeader(this->stream(), nullptr, &decoderMgr)) {
msarett50ce1f22016-07-29 06:23:33 -0700354 return fDecoderMgr->returnFalse("onRewind");
msarett97fdea62015-04-29 08:17:15 -0700355 }
halcanary96fcdcc2015-08-27 07:41:13 -0700356 SkASSERT(nullptr != decoderMgr);
scroggob427db12015-08-12 07:24:13 -0700357 fDecoderMgr.reset(decoderMgr);
msarett2812f032016-07-18 15:56:08 -0700358
359 fSwizzler.reset(nullptr);
msarett50ce1f22016-07-29 06:23:33 -0700360 fSwizzleSrcRow = nullptr;
361 fColorXformSrcRow = nullptr;
msarett2812f032016-07-18 15:56:08 -0700362 fStorage.reset();
363
scroggob427db12015-08-12 07:24:13 -0700364 return true;
msarett97fdea62015-04-29 08:17:15 -0700365}
366
367/*
msarett1c8a5872015-07-07 08:50:01 -0700368 * Checks if the conversion between the input image and the requested output
369 * image has been implemented
370 * Sets the output color space
371 */
msarett2ecc35f2016-09-08 11:55:16 -0700372bool SkJpegCodec::setOutputColorSpace(const SkImageInfo& dstInfo) {
msarett50ce1f22016-07-29 06:23:33 -0700373 if (kUnknown_SkAlphaType == dstInfo.alphaType()) {
msarett1c8a5872015-07-07 08:50:01 -0700374 return false;
375 }
376
msarett50ce1f22016-07-29 06:23:33 -0700377 if (kOpaque_SkAlphaType != dstInfo.alphaType()) {
scroggoc5560be2016-02-03 09:42:42 -0800378 SkCodecPrintf("Warning: an opaque image should be decoded as opaque "
379 "- it is being decoded as non-opaque, which will draw slower\n");
380 }
381
msarett50ce1f22016-07-29 06:23:33 -0700382 // Check if we will decode to CMYK. libjpeg-turbo does not convert CMYK to RGBA, so
383 // we must do it ourselves.
384 J_COLOR_SPACE encodedColorType = fDecoderMgr->dinfo()->jpeg_color_space;
385 bool isCMYK = (JCS_CMYK == encodedColorType || JCS_YCCK == encodedColorType);
msarett1c8a5872015-07-07 08:50:01 -0700386
387 // Check for valid color types and set the output color space
msarett50ce1f22016-07-29 06:23:33 -0700388 switch (dstInfo.colorType()) {
msarett34e0ec42016-04-22 16:27:24 -0700389 case kRGBA_8888_SkColorType:
msarett1c8a5872015-07-07 08:50:01 -0700390 if (isCMYK) {
391 fDecoderMgr->dinfo()->out_color_space = JCS_CMYK;
392 } else {
msarettf25bff92016-07-21 12:00:24 -0700393 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
msarett34e0ec42016-04-22 16:27:24 -0700394 }
395 return true;
396 case kBGRA_8888_SkColorType:
397 if (isCMYK) {
398 fDecoderMgr->dinfo()->out_color_space = JCS_CMYK;
Matt Sarett313c4632016-10-20 12:35:23 -0400399 } else if (this->colorXform()) {
Matt Sarett562e6812016-11-08 16:13:43 -0500400 // Always using RGBA as the input format for color xforms makes the
401 // implementation a little simpler.
msarett50ce1f22016-07-29 06:23:33 -0700402 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
msarett34e0ec42016-04-22 16:27:24 -0700403 } else {
msarettf25bff92016-07-21 12:00:24 -0700404 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_BGRA;
msarett1c8a5872015-07-07 08:50:01 -0700405 }
406 return true;
407 case kRGB_565_SkColorType:
Matt Sarett313c4632016-10-20 12:35:23 -0400408 if (this->colorXform()) {
msarett50ce1f22016-07-29 06:23:33 -0700409 return false;
410 }
411
msarett1c8a5872015-07-07 08:50:01 -0700412 if (isCMYK) {
scroggoef27d892015-10-23 09:29:22 -0700413 fDecoderMgr->dinfo()->out_color_space = JCS_CMYK;
msarett1c8a5872015-07-07 08:50:01 -0700414 } else {
msarett8ff6ca62015-09-18 12:06:04 -0700415 fDecoderMgr->dinfo()->dither_mode = JDITHER_NONE;
msarett1c8a5872015-07-07 08:50:01 -0700416 fDecoderMgr->dinfo()->out_color_space = JCS_RGB565;
417 }
418 return true;
419 case kGray_8_SkColorType:
Matt Sarett313c4632016-10-20 12:35:23 -0400420 if (this->colorXform() || JCS_GRAYSCALE != encodedColorType) {
msarett39979d82016-07-28 17:11:18 -0700421 return false;
msarett50ce1f22016-07-29 06:23:33 -0700422 }
423
424 fDecoderMgr->dinfo()->out_color_space = JCS_GRAYSCALE;
425 return true;
426 case kRGBA_F16_SkColorType:
Matt Sarett313c4632016-10-20 12:35:23 -0400427 SkASSERT(this->colorXform());
428
msarett2ecc35f2016-09-08 11:55:16 -0700429 if (!dstInfo.colorSpace()->gammaIsLinear()) {
430 return false;
431 }
msarett50ce1f22016-07-29 06:23:33 -0700432
433 if (isCMYK) {
434 fDecoderMgr->dinfo()->out_color_space = JCS_CMYK;
msarett1c8a5872015-07-07 08:50:01 -0700435 } else {
msarett50ce1f22016-07-29 06:23:33 -0700436 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
msarett1c8a5872015-07-07 08:50:01 -0700437 }
438 return true;
439 default:
440 return false;
441 }
442}
443
444/*
mtkleine721a8e2016-02-06 19:12:23 -0800445 * Checks if we can natively scale to the requested dimensions and natively scales the
emmaleer8f4ba762015-08-14 07:44:46 -0700446 * dimensions if possible
msarett97fdea62015-04-29 08:17:15 -0700447 */
scroggoe7fc14b2015-10-02 13:14:46 -0700448bool SkJpegCodec::onDimensionsSupported(const SkISize& size) {
mtklein2f428962016-07-28 13:59:59 -0700449 if (setjmp(fDecoderMgr->getJmpBuf())) {
msarett50ce1f22016-07-29 06:23:33 -0700450 return fDecoderMgr->returnFalse("onDimensionsSupported");
scroggoe7fc14b2015-10-02 13:14:46 -0700451 }
452
453 const unsigned int dstWidth = size.width();
454 const unsigned int dstHeight = size.height();
455
456 // Set up a fake decompress struct in order to use libjpeg to calculate output dimensions
457 // FIXME: Why is this necessary?
458 jpeg_decompress_struct dinfo;
459 sk_bzero(&dinfo, sizeof(dinfo));
460 dinfo.image_width = this->getInfo().width();
461 dinfo.image_height = this->getInfo().height();
462 dinfo.global_state = fReadyState;
463
msarett1c8a5872015-07-07 08:50:01 -0700464 // libjpeg-turbo can scale to 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8, and 1/1
scroggoe7fc14b2015-10-02 13:14:46 -0700465 unsigned int num = 8;
466 const unsigned int denom = 8;
467 calc_output_dimensions(&dinfo, num, denom);
468 while (dinfo.output_width != dstWidth || dinfo.output_height != dstHeight) {
msarett97fdea62015-04-29 08:17:15 -0700469
470 // Return a failure if we have tried all of the possible scales
scroggoe7fc14b2015-10-02 13:14:46 -0700471 if (1 == num || dstWidth > dinfo.output_width || dstHeight > dinfo.output_height) {
emmaleer8f4ba762015-08-14 07:44:46 -0700472 return false;
msarett97fdea62015-04-29 08:17:15 -0700473 }
474
475 // Try the next scale
scroggoe7fc14b2015-10-02 13:14:46 -0700476 num -= 1;
477 calc_output_dimensions(&dinfo, num, denom);
msarett97fdea62015-04-29 08:17:15 -0700478 }
scroggoe7fc14b2015-10-02 13:14:46 -0700479
480 fDecoderMgr->dinfo()->scale_num = num;
481 fDecoderMgr->dinfo()->scale_denom = denom;
msarett97fdea62015-04-29 08:17:15 -0700482 return true;
483}
484
msarett50ce1f22016-07-29 06:23:33 -0700485int SkJpegCodec::readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count) {
486 // Set the jump location for libjpeg-turbo errors
487 if (setjmp(fDecoderMgr->getJmpBuf())) {
488 return 0;
489 }
490
491 // When fSwizzleSrcRow is non-null, it means that we need to swizzle. In this case,
492 // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer.
493 // We can never swizzle "in place" because the swizzler may perform sampling and/or
494 // subsetting.
495 // When fColorXformSrcRow is non-null, it means that we need to color xform and that
496 // we cannot color xform "in place" (many times we can, but not when the dst is F16).
Matt Sarett313c4632016-10-20 12:35:23 -0400497 // In this case, we will color xform from fColorXformSrcRow into the dst.
msarett50ce1f22016-07-29 06:23:33 -0700498 JSAMPLE* decodeDst = (JSAMPLE*) dst;
499 uint32_t* swizzleDst = (uint32_t*) dst;
500 size_t decodeDstRowBytes = rowBytes;
501 size_t swizzleDstRowBytes = rowBytes;
msarett35bb74b2016-08-22 07:41:28 -0700502 int dstWidth = dstInfo.width();
msarett50ce1f22016-07-29 06:23:33 -0700503 if (fSwizzleSrcRow && fColorXformSrcRow) {
504 decodeDst = (JSAMPLE*) fSwizzleSrcRow;
505 swizzleDst = fColorXformSrcRow;
506 decodeDstRowBytes = 0;
507 swizzleDstRowBytes = 0;
msarett35bb74b2016-08-22 07:41:28 -0700508 dstWidth = fSwizzler->swizzleWidth();
msarett50ce1f22016-07-29 06:23:33 -0700509 } else if (fColorXformSrcRow) {
510 decodeDst = (JSAMPLE*) fColorXformSrcRow;
511 swizzleDst = fColorXformSrcRow;
512 decodeDstRowBytes = 0;
513 swizzleDstRowBytes = 0;
514 } else if (fSwizzleSrcRow) {
515 decodeDst = (JSAMPLE*) fSwizzleSrcRow;
516 decodeDstRowBytes = 0;
msarett35bb74b2016-08-22 07:41:28 -0700517 dstWidth = fSwizzler->swizzleWidth();
msarett50ce1f22016-07-29 06:23:33 -0700518 }
519
520 for (int y = 0; y < count; y++) {
521 uint32_t lines = jpeg_read_scanlines(fDecoderMgr->dinfo(), &decodeDst, 1);
522 size_t srcRowBytes = get_row_bytes(fDecoderMgr->dinfo());
523 sk_msan_mark_initialized(decodeDst, decodeDst + srcRowBytes, "skbug.com/4550");
524 if (0 == lines) {
525 return y;
526 }
527
528 if (fSwizzler) {
529 fSwizzler->swizzle(swizzleDst, decodeDst);
530 }
531
Matt Sarett313c4632016-10-20 12:35:23 -0400532 if (this->colorXform()) {
533 SkAssertResult(this->colorXform()->apply(select_xform_format(dstInfo.colorType()), dst,
534 SkColorSpaceXform::kRGBA_8888_ColorFormat, swizzleDst, dstWidth,
535 kOpaque_SkAlphaType));
msarett50ce1f22016-07-29 06:23:33 -0700536 dst = SkTAddOffset<void>(dst, rowBytes);
537 }
538
539 decodeDst = SkTAddOffset<JSAMPLE>(decodeDst, decodeDstRowBytes);
540 swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes);
541 }
542
543 return count;
544}
545
msarett97fdea62015-04-29 08:17:15 -0700546/*
msarette16b04a2015-04-15 07:32:19 -0700547 * Performs the jpeg decode
548 */
549SkCodec::Result SkJpegCodec::onGetPixels(const SkImageInfo& dstInfo,
550 void* dst, size_t dstRowBytes,
msarette6dd0042015-10-09 11:07:34 -0700551 const Options& options, SkPMColor*, int*,
552 int* rowsDecoded) {
scroggob636b452015-07-22 07:16:20 -0700553 if (options.fSubset) {
554 // Subsets are not supported.
555 return kUnimplemented;
556 }
557
msarette16b04a2015-04-15 07:32:19 -0700558 // Get a pointer to the decompress info since we will use it quite frequently
559 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
560
561 // Set the jump location for libjpeg errors
mtklein2f428962016-07-28 13:59:59 -0700562 if (setjmp(fDecoderMgr->getJmpBuf())) {
msarette16b04a2015-04-15 07:32:19 -0700563 return fDecoderMgr->returnFailure("setjmp", kInvalidInput);
564 }
565
Matt Sarett313c4632016-10-20 12:35:23 -0400566 if (!this->initializeColorXform(dstInfo)) {
567 return kInvalidConversion;
568 }
msarett50ce1f22016-07-29 06:23:33 -0700569
msarett2ecc35f2016-09-08 11:55:16 -0700570 // Check if we can decode to the requested destination and set the output color space
571 if (!this->setOutputColorSpace(dstInfo)) {
572 return fDecoderMgr->returnFailure("setOutputColorSpace", kInvalidConversion);
msarett85c922a2016-09-08 10:54:34 -0700573 }
574
msarettfbccb592015-09-01 06:43:41 -0700575 if (!jpeg_start_decompress(dinfo)) {
msarette16b04a2015-04-15 07:32:19 -0700576 return fDecoderMgr->returnFailure("startDecompress", kInvalidInput);
577 }
578
msarett1c8a5872015-07-07 08:50:01 -0700579 // The recommended output buffer height should always be 1 in high quality modes.
580 // If it's not, we want to know because it means our strategy is not optimal.
581 SkASSERT(1 == dinfo->rec_outbuf_height);
msarette16b04a2015-04-15 07:32:19 -0700582
msarett70e418b2016-02-12 12:35:48 -0800583 J_COLOR_SPACE colorSpace = dinfo->out_color_space;
raftias54761282016-12-01 13:44:07 -0500584 if (JCS_CMYK == colorSpace && nullptr == this->colorXform()) {
scroggoef27d892015-10-23 09:29:22 -0700585 this->initializeSwizzler(dstInfo, options);
586 }
587
msarett50ce1f22016-07-29 06:23:33 -0700588 this->allocateStorage(dstInfo);
scroggoef27d892015-10-23 09:29:22 -0700589
msarett50ce1f22016-07-29 06:23:33 -0700590 int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height());
591 if (rows < dstInfo.height()) {
592 *rowsDecoded = rows;
593 return fDecoderMgr->returnFailure("Incomplete image data", kIncompleteInput);
msarette16b04a2015-04-15 07:32:19 -0700594 }
msarette16b04a2015-04-15 07:32:19 -0700595
596 return kSuccess;
597}
msarett97fdea62015-04-29 08:17:15 -0700598
msarett50ce1f22016-07-29 06:23:33 -0700599void SkJpegCodec::allocateStorage(const SkImageInfo& dstInfo) {
msarett35bb74b2016-08-22 07:41:28 -0700600 int dstWidth = dstInfo.width();
601
msarett50ce1f22016-07-29 06:23:33 -0700602 size_t swizzleBytes = 0;
603 if (fSwizzler) {
604 swizzleBytes = get_row_bytes(fDecoderMgr->dinfo());
msarett35bb74b2016-08-22 07:41:28 -0700605 dstWidth = fSwizzler->swizzleWidth();
Matt Sarett313c4632016-10-20 12:35:23 -0400606 SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes));
msarett50ce1f22016-07-29 06:23:33 -0700607 }
608
609 size_t xformBytes = 0;
610 if (kRGBA_F16_SkColorType == dstInfo.colorType()) {
Matt Sarett313c4632016-10-20 12:35:23 -0400611 SkASSERT(this->colorXform());
msarett35bb74b2016-08-22 07:41:28 -0700612 xformBytes = dstWidth * sizeof(uint32_t);
msarett50ce1f22016-07-29 06:23:33 -0700613 }
614
615 size_t totalBytes = swizzleBytes + xformBytes;
616 if (totalBytes > 0) {
617 fStorage.reset(totalBytes);
618 fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr;
619 fColorXformSrcRow = (xformBytes > 0) ?
620 SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr;
621 }
622}
623
msarettfdb47572015-10-13 12:50:14 -0700624void SkJpegCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& options) {
msaretta45a6682016-04-22 13:18:37 -0700625 // libjpeg-turbo may have already performed color conversion. We must indicate the
626 // appropriate format to the swizzler.
627 SkEncodedInfo swizzlerInfo = this->getEncodedInfo();
msarett68758ae2016-04-25 11:41:15 -0700628 bool preSwizzled = true;
mtkleinda19f6f2016-08-23 11:49:29 -0700629 if (JCS_CMYK == fDecoderMgr->dinfo()->out_color_space) {
630 preSwizzled = false;
631 swizzlerInfo = SkEncodedInfo::Make(SkEncodedInfo::kInvertedCMYK_Color,
632 swizzlerInfo.alpha(),
633 swizzlerInfo.bitsPerComponent());
msarett70e418b2016-02-12 12:35:48 -0800634 }
635
msarett91c22b22016-02-22 12:27:46 -0800636 Options swizzlerOptions = options;
637 if (options.fSubset) {
638 // Use fSwizzlerSubset if this is a subset decode. This is necessary in the case
639 // where libjpeg-turbo provides a subset and then we need to subset it further.
640 // Also, verify that fSwizzlerSubset is initialized and valid.
641 SkASSERT(!fSwizzlerSubset.isEmpty() && fSwizzlerSubset.x() <= options.fSubset->x() &&
642 fSwizzlerSubset.width() == options.fSubset->width());
643 swizzlerOptions.fSubset = &fSwizzlerSubset;
644 }
msarett68758ae2016-04-25 11:41:15 -0700645 fSwizzler.reset(SkSwizzler::CreateSwizzler(swizzlerInfo, nullptr, dstInfo, swizzlerOptions,
646 nullptr, preSwizzled));
msarettb30d6982016-02-15 10:18:45 -0800647 SkASSERT(fSwizzler);
msarett50ce1f22016-07-29 06:23:33 -0700648}
649
msarettfdb47572015-10-13 12:50:14 -0700650SkSampler* SkJpegCodec::getSampler(bool createIfNecessary) {
651 if (!createIfNecessary || fSwizzler) {
msarett50ce1f22016-07-29 06:23:33 -0700652 SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow));
Ben Wagner145dbcd2016-11-03 14:40:50 -0400653 return fSwizzler.get();
msarettfdb47572015-10-13 12:50:14 -0700654 }
655
656 this->initializeSwizzler(this->dstInfo(), this->options());
msarett50ce1f22016-07-29 06:23:33 -0700657 this->allocateStorage(this->dstInfo());
Ben Wagner145dbcd2016-11-03 14:40:50 -0400658 return fSwizzler.get();
scroggo46c57472015-09-30 08:57:13 -0700659}
scroggo1c005e42015-08-04 09:24:45 -0700660
scroggo46c57472015-09-30 08:57:13 -0700661SkCodec::Result SkJpegCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
662 const Options& options, SkPMColor ctable[], int* ctableCount) {
scroggo46c57472015-09-30 08:57:13 -0700663 // Set the jump location for libjpeg errors
mtklein2f428962016-07-28 13:59:59 -0700664 if (setjmp(fDecoderMgr->getJmpBuf())) {
scroggo46c57472015-09-30 08:57:13 -0700665 SkCodecPrintf("setjmp: Error from libjpeg\n");
666 return kInvalidInput;
667 }
668
Matt Sarett313c4632016-10-20 12:35:23 -0400669 if (!this->initializeColorXform(dstInfo)) {
670 return kInvalidConversion;
671 }
msarett85c922a2016-09-08 10:54:34 -0700672
msarett2ecc35f2016-09-08 11:55:16 -0700673 // Check if we can decode to the requested destination and set the output color space
674 if (!this->setOutputColorSpace(dstInfo)) {
675 return fDecoderMgr->returnFailure("setOutputColorSpace", kInvalidConversion);
msarett50ce1f22016-07-29 06:23:33 -0700676 }
677
scroggo46c57472015-09-30 08:57:13 -0700678 if (!jpeg_start_decompress(fDecoderMgr->dinfo())) {
679 SkCodecPrintf("start decompress failed\n");
680 return kInvalidInput;
681 }
682
msarett91c22b22016-02-22 12:27:46 -0800683 if (options.fSubset) {
684 uint32_t startX = options.fSubset->x();
685 uint32_t width = options.fSubset->width();
686
687 // libjpeg-turbo may need to align startX to a multiple of the IDCT
688 // block size. If this is the case, it will decrease the value of
689 // startX to the appropriate alignment and also increase the value
690 // of width so that the right edge of the requested subset remains
691 // the same.
692 jpeg_crop_scanline(fDecoderMgr->dinfo(), &startX, &width);
693
694 SkASSERT(startX <= (uint32_t) options.fSubset->x());
695 SkASSERT(width >= (uint32_t) options.fSubset->width());
696 SkASSERT(startX + width >= (uint32_t) options.fSubset->right());
697
698 // Instruct the swizzler (if it is necessary) to further subset the
699 // output provided by libjpeg-turbo.
700 //
701 // We set this here (rather than in the if statement below), so that
702 // if (1) we don't need a swizzler for the subset, and (2) we need a
703 // swizzler for CMYK, the swizzler will still use the proper subset
704 // dimensions.
705 //
706 // Note that the swizzler will ignore the y and height parameters of
707 // the subset. Since the scanline decoder (and the swizzler) handle
708 // one row at a time, only the subsetting in the x-dimension matters.
709 fSwizzlerSubset.setXYWH(options.fSubset->x() - startX, 0,
710 options.fSubset->width(), options.fSubset->height());
711
712 // We will need a swizzler if libjpeg-turbo cannot provide the exact
713 // subset that we request.
714 if (startX != (uint32_t) options.fSubset->x() ||
715 width != (uint32_t) options.fSubset->width()) {
716 this->initializeSwizzler(dstInfo, options);
717 }
718 }
719
720 // Make sure we have a swizzler if we are converting from CMYK.
721 if (!fSwizzler && JCS_CMYK == fDecoderMgr->dinfo()->out_color_space) {
722 this->initializeSwizzler(dstInfo, options);
723 }
msarettfdb47572015-10-13 12:50:14 -0700724
msarett50ce1f22016-07-29 06:23:33 -0700725 this->allocateStorage(dstInfo);
726
scroggo46c57472015-09-30 08:57:13 -0700727 return kSuccess;
728}
729
mtkleine721a8e2016-02-06 19:12:23 -0800730int SkJpegCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) {
msarett50ce1f22016-07-29 06:23:33 -0700731 int rows = this->readRows(this->dstInfo(), dst, dstRowBytes, count);
732 if (rows < count) {
733 // This allows us to skip calling jpeg_finish_decompress().
734 fDecoderMgr->dinfo()->output_scanline = this->dstInfo().height();
scroggo46c57472015-09-30 08:57:13 -0700735 }
736
msarett50ce1f22016-07-29 06:23:33 -0700737 return rows;
scroggo46c57472015-09-30 08:57:13 -0700738}
msarett97fdea62015-04-29 08:17:15 -0700739
msarette6dd0042015-10-09 11:07:34 -0700740bool SkJpegCodec::onSkipScanlines(int count) {
scroggo46c57472015-09-30 08:57:13 -0700741 // Set the jump location for libjpeg errors
mtklein2f428962016-07-28 13:59:59 -0700742 if (setjmp(fDecoderMgr->getJmpBuf())) {
msarett50ce1f22016-07-29 06:23:33 -0700743 return fDecoderMgr->returnFalse("onSkipScanlines");
msarett97fdea62015-04-29 08:17:15 -0700744 }
745
msarettf724b992015-10-15 06:41:06 -0700746 return (uint32_t) count == jpeg_skip_scanlines(fDecoderMgr->dinfo(), count);
msarett97fdea62015-04-29 08:17:15 -0700747}
msarettb714fb02016-01-22 14:46:42 -0800748
749static bool is_yuv_supported(jpeg_decompress_struct* dinfo) {
750 // Scaling is not supported in raw data mode.
751 SkASSERT(dinfo->scale_num == dinfo->scale_denom);
752
753 // I can't imagine that this would ever change, but we do depend on it.
754 static_assert(8 == DCTSIZE, "DCTSIZE (defined in jpeg library) should always be 8.");
755
756 if (JCS_YCbCr != dinfo->jpeg_color_space) {
757 return false;
758 }
759
760 SkASSERT(3 == dinfo->num_components);
761 SkASSERT(dinfo->comp_info);
762
763 // It is possible to perform a YUV decode for any combination of
764 // horizontal and vertical sampling that is supported by
765 // libjpeg/libjpeg-turbo. However, we will start by supporting only the
766 // common cases (where U and V have samp_factors of one).
767 //
768 // The definition of samp_factor is kind of the opposite of what SkCodec
769 // thinks of as a sampling factor. samp_factor is essentially a
770 // multiplier, and the larger the samp_factor is, the more samples that
771 // there will be. Ex:
772 // U_plane_width = image_width * (U_h_samp_factor / max_h_samp_factor)
773 //
774 // Supporting cases where the samp_factors for U or V were larger than
775 // that of Y would be an extremely difficult change, given that clients
776 // allocate memory as if the size of the Y plane is always the size of the
777 // image. However, this case is very, very rare.
msarett7c87cf42016-03-04 06:23:20 -0800778 if ((1 != dinfo->comp_info[1].h_samp_factor) ||
779 (1 != dinfo->comp_info[1].v_samp_factor) ||
780 (1 != dinfo->comp_info[2].h_samp_factor) ||
781 (1 != dinfo->comp_info[2].v_samp_factor))
782 {
msarettb714fb02016-01-22 14:46:42 -0800783 return false;
784 }
785
786 // Support all common cases of Y samp_factors.
787 // TODO (msarett): As mentioned above, it would be possible to support
788 // more combinations of samp_factors. The issues are:
789 // (1) Are there actually any images that are not covered
790 // by these cases?
791 // (2) How much complexity would be added to the
792 // implementation in order to support these rare
793 // cases?
794 int hSampY = dinfo->comp_info[0].h_samp_factor;
795 int vSampY = dinfo->comp_info[0].v_samp_factor;
796 return (1 == hSampY && 1 == vSampY) ||
797 (2 == hSampY && 1 == vSampY) ||
798 (2 == hSampY && 2 == vSampY) ||
799 (1 == hSampY && 2 == vSampY) ||
800 (4 == hSampY && 1 == vSampY) ||
801 (4 == hSampY && 2 == vSampY);
802}
803
msarett4984c3c2016-03-10 05:44:43 -0800804bool SkJpegCodec::onQueryYUV8(SkYUVSizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const {
msarettb714fb02016-01-22 14:46:42 -0800805 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
806 if (!is_yuv_supported(dinfo)) {
807 return false;
808 }
809
msarett4984c3c2016-03-10 05:44:43 -0800810 sizeInfo->fSizes[SkYUVSizeInfo::kY].set(dinfo->comp_info[0].downsampled_width,
811 dinfo->comp_info[0].downsampled_height);
812 sizeInfo->fSizes[SkYUVSizeInfo::kU].set(dinfo->comp_info[1].downsampled_width,
813 dinfo->comp_info[1].downsampled_height);
814 sizeInfo->fSizes[SkYUVSizeInfo::kV].set(dinfo->comp_info[2].downsampled_width,
815 dinfo->comp_info[2].downsampled_height);
816 sizeInfo->fWidthBytes[SkYUVSizeInfo::kY] = dinfo->comp_info[0].width_in_blocks * DCTSIZE;
817 sizeInfo->fWidthBytes[SkYUVSizeInfo::kU] = dinfo->comp_info[1].width_in_blocks * DCTSIZE;
818 sizeInfo->fWidthBytes[SkYUVSizeInfo::kV] = dinfo->comp_info[2].width_in_blocks * DCTSIZE;
msarettb714fb02016-01-22 14:46:42 -0800819
820 if (colorSpace) {
821 *colorSpace = kJPEG_SkYUVColorSpace;
822 }
823
824 return true;
825}
826
msarett4984c3c2016-03-10 05:44:43 -0800827SkCodec::Result SkJpegCodec::onGetYUV8Planes(const SkYUVSizeInfo& sizeInfo, void* planes[3]) {
828 SkYUVSizeInfo defaultInfo;
msarettb714fb02016-01-22 14:46:42 -0800829
830 // This will check is_yuv_supported(), so we don't need to here.
831 bool supportsYUV = this->onQueryYUV8(&defaultInfo, nullptr);
msarett4984c3c2016-03-10 05:44:43 -0800832 if (!supportsYUV ||
833 sizeInfo.fSizes[SkYUVSizeInfo::kY] != defaultInfo.fSizes[SkYUVSizeInfo::kY] ||
834 sizeInfo.fSizes[SkYUVSizeInfo::kU] != defaultInfo.fSizes[SkYUVSizeInfo::kU] ||
835 sizeInfo.fSizes[SkYUVSizeInfo::kV] != defaultInfo.fSizes[SkYUVSizeInfo::kV] ||
836 sizeInfo.fWidthBytes[SkYUVSizeInfo::kY] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kY] ||
837 sizeInfo.fWidthBytes[SkYUVSizeInfo::kU] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kU] ||
838 sizeInfo.fWidthBytes[SkYUVSizeInfo::kV] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kV]) {
msarettb714fb02016-01-22 14:46:42 -0800839 return fDecoderMgr->returnFailure("onGetYUV8Planes", kInvalidInput);
840 }
841
842 // Set the jump location for libjpeg errors
mtklein2f428962016-07-28 13:59:59 -0700843 if (setjmp(fDecoderMgr->getJmpBuf())) {
msarettb714fb02016-01-22 14:46:42 -0800844 return fDecoderMgr->returnFailure("setjmp", kInvalidInput);
845 }
846
847 // Get a pointer to the decompress info since we will use it quite frequently
848 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
849
850 dinfo->raw_data_out = TRUE;
851 if (!jpeg_start_decompress(dinfo)) {
852 return fDecoderMgr->returnFailure("startDecompress", kInvalidInput);
853 }
854
855 // A previous implementation claims that the return value of is_yuv_supported()
856 // may change after calling jpeg_start_decompress(). It looks to me like this
857 // was caused by a bug in the old code, but we'll be safe and check here.
858 SkASSERT(is_yuv_supported(dinfo));
859
860 // Currently, we require that the Y plane dimensions match the image dimensions
861 // and that the U and V planes are the same dimensions.
msarett4984c3c2016-03-10 05:44:43 -0800862 SkASSERT(sizeInfo.fSizes[SkYUVSizeInfo::kU] == sizeInfo.fSizes[SkYUVSizeInfo::kV]);
863 SkASSERT((uint32_t) sizeInfo.fSizes[SkYUVSizeInfo::kY].width() == dinfo->output_width &&
864 (uint32_t) sizeInfo.fSizes[SkYUVSizeInfo::kY].height() == dinfo->output_height);
msarettb714fb02016-01-22 14:46:42 -0800865
866 // Build a JSAMPIMAGE to handle output from libjpeg-turbo. A JSAMPIMAGE has
867 // a 2-D array of pixels for each of the components (Y, U, V) in the image.
868 // Cheat Sheet:
869 // JSAMPIMAGE == JSAMPLEARRAY* == JSAMPROW** == JSAMPLE***
870 JSAMPARRAY yuv[3];
871
872 // Set aside enough space for pointers to rows of Y, U, and V.
873 JSAMPROW rowptrs[2 * DCTSIZE + DCTSIZE + DCTSIZE];
874 yuv[0] = &rowptrs[0]; // Y rows (DCTSIZE or 2 * DCTSIZE)
875 yuv[1] = &rowptrs[2 * DCTSIZE]; // U rows (DCTSIZE)
876 yuv[2] = &rowptrs[3 * DCTSIZE]; // V rows (DCTSIZE)
877
878 // Initialize rowptrs.
879 int numYRowsPerBlock = DCTSIZE * dinfo->comp_info[0].v_samp_factor;
880 for (int i = 0; i < numYRowsPerBlock; i++) {
msarett4984c3c2016-03-10 05:44:43 -0800881 rowptrs[i] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kY],
882 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kY]);
msarettb714fb02016-01-22 14:46:42 -0800883 }
884 for (int i = 0; i < DCTSIZE; i++) {
msarett4984c3c2016-03-10 05:44:43 -0800885 rowptrs[i + 2 * DCTSIZE] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kU],
886 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kU]);
887 rowptrs[i + 3 * DCTSIZE] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kV],
888 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kV]);
msarettb714fb02016-01-22 14:46:42 -0800889 }
890
891 // After each loop iteration, we will increment pointers to Y, U, and V.
msarett4984c3c2016-03-10 05:44:43 -0800892 size_t blockIncrementY = numYRowsPerBlock * sizeInfo.fWidthBytes[SkYUVSizeInfo::kY];
893 size_t blockIncrementU = DCTSIZE * sizeInfo.fWidthBytes[SkYUVSizeInfo::kU];
894 size_t blockIncrementV = DCTSIZE * sizeInfo.fWidthBytes[SkYUVSizeInfo::kV];
msarettb714fb02016-01-22 14:46:42 -0800895
896 uint32_t numRowsPerBlock = numYRowsPerBlock;
897
898 // We intentionally round down here, as this first loop will only handle
899 // full block rows. As a special case at the end, we will handle any
900 // remaining rows that do not make up a full block.
901 const int numIters = dinfo->output_height / numRowsPerBlock;
902 for (int i = 0; i < numIters; i++) {
903 JDIMENSION linesRead = jpeg_read_raw_data(dinfo, yuv, numRowsPerBlock);
904 if (linesRead < numRowsPerBlock) {
905 // FIXME: Handle incomplete YUV decodes without signalling an error.
906 return kInvalidInput;
907 }
908
909 // Update rowptrs.
910 for (int i = 0; i < numYRowsPerBlock; i++) {
911 rowptrs[i] += blockIncrementY;
912 }
913 for (int i = 0; i < DCTSIZE; i++) {
914 rowptrs[i + 2 * DCTSIZE] += blockIncrementU;
915 rowptrs[i + 3 * DCTSIZE] += blockIncrementV;
916 }
917 }
918
919 uint32_t remainingRows = dinfo->output_height - dinfo->output_scanline;
920 SkASSERT(remainingRows == dinfo->output_height % numRowsPerBlock);
921 SkASSERT(dinfo->output_scanline == numIters * numRowsPerBlock);
922 if (remainingRows > 0) {
923 // libjpeg-turbo needs memory to be padded by the block sizes. We will fulfill
924 // this requirement using a dummy row buffer.
925 // FIXME: Should SkCodec have an extra memory buffer that can be shared among
926 // all of the implementations that use temporary/garbage memory?
msarett4984c3c2016-03-10 05:44:43 -0800927 SkAutoTMalloc<JSAMPLE> dummyRow(sizeInfo.fWidthBytes[SkYUVSizeInfo::kY]);
msarettb714fb02016-01-22 14:46:42 -0800928 for (int i = remainingRows; i < numYRowsPerBlock; i++) {
929 rowptrs[i] = dummyRow.get();
930 }
931 int remainingUVRows = dinfo->comp_info[1].downsampled_height - DCTSIZE * numIters;
932 for (int i = remainingUVRows; i < DCTSIZE; i++) {
933 rowptrs[i + 2 * DCTSIZE] = dummyRow.get();
934 rowptrs[i + 3 * DCTSIZE] = dummyRow.get();
935 }
936
937 JDIMENSION linesRead = jpeg_read_raw_data(dinfo, yuv, numRowsPerBlock);
938 if (linesRead < remainingRows) {
939 // FIXME: Handle incomplete YUV decodes without signalling an error.
940 return kInvalidInput;
941 }
942 }
943
944 return kSuccess;
945}