blob: d44258f9b0d623f17c54b4b04428c8d9759d1dbb [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
msarette16b04a2015-04-15 07:32:19 -07008#include "SkJpegCodec.h"
Hal Canary83e0f1b2018-04-05 16:58:41 -04009
10#include "SkCodec.h"
msarette16b04a2015-04-15 07:32:19 -070011#include "SkCodecPriv.h"
Cary Clarka4083c92017-09-15 11:59:23 -040012#include "SkColorData.h"
Hal Canary83e0f1b2018-04-05 16:58:41 -040013#include "SkJpegDecoderMgr.h"
14#include "SkJpegInfo.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) {
Leon Scroggins III862c1962017-10-02 16:28:49 -040034 constexpr 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;
msarett0e6274f2016-03-21 08:04:40 -070047const uint32_t kExifMarker = JPEG_APP0 + 1;
msarett0e6274f2016-03-21 08:04:40 -070048
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -040049static bool is_orientation_marker(jpeg_marker_struct* marker, SkEncodedOrigin* orientation) {
msarett0e6274f2016-03-21 08:04:40 -070050 if (kExifMarker != marker->marker || marker->data_length < kExifHeaderSize) {
51 return false;
52 }
53
Leon Scroggins III862c1962017-10-02 16:28:49 -040054 constexpr uint8_t kExifSig[] { 'E', 'x', 'i', 'f', '\0' };
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -050055 if (memcmp(marker->data, kExifSig, sizeof(kExifSig))) {
msarett0e6274f2016-03-21 08:04:40 -070056 return false;
57 }
58
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -050059 // Account for 'E', 'x', 'i', 'f', '\0', '<fill byte>'.
60 constexpr size_t kOffset = 6;
61 return is_orientation_marker(marker->data + kOffset, marker->data_length - kOffset,
62 orientation);
63}
64
65bool is_orientation_marker(const uint8_t* data, size_t data_length, SkEncodedOrigin* orientation) {
msarett0e6274f2016-03-21 08:04:40 -070066 bool littleEndian;
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -050067 // We need eight bytes to read the endian marker and the offset, below.
68 if (data_length < 8 || !is_valid_endian_marker(data, &littleEndian)) {
msarett0e6274f2016-03-21 08:04:40 -070069 return false;
70 }
71
72 // Get the offset from the start of the marker.
Leon Scroggins III71d8a572017-12-19 10:14:43 -050073 // Though this only reads four bytes, use a larger int in case it overflows.
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -050074 uint64_t offset = get_endian_int(data + 4, littleEndian);
msarett0e6274f2016-03-21 08:04:40 -070075
76 // Require that the marker is at least large enough to contain the number of entries.
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -050077 if (data_length < offset + 2) {
msarett0e6274f2016-03-21 08:04:40 -070078 return false;
79 }
80 uint32_t numEntries = get_endian_short(data + offset, littleEndian);
81
82 // Tag (2 bytes), Datatype (2 bytes), Number of elements (4 bytes), Data (4 bytes)
83 const uint32_t kEntrySize = 12;
Leon Scroggins IIIda3e9ad2018-01-26 15:48:26 -050084 const auto max = SkTo<uint32_t>((data_length - offset - 2) / kEntrySize);
Leon Scroggins III71d8a572017-12-19 10:14:43 -050085 numEntries = SkTMin(numEntries, max);
msarett0e6274f2016-03-21 08:04:40 -070086
87 // Advance the data to the start of the entries.
88 data += offset + 2;
89
90 const uint16_t kOriginTag = 0x112;
91 const uint16_t kOriginType = 3;
92 for (uint32_t i = 0; i < numEntries; i++, data += kEntrySize) {
93 uint16_t tag = get_endian_short(data, littleEndian);
94 uint16_t type = get_endian_short(data + 2, littleEndian);
95 uint32_t count = get_endian_int(data + 4, littleEndian);
96 if (kOriginTag == tag && kOriginType == type && 1 == count) {
97 uint16_t val = get_endian_short(data + 8, littleEndian);
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -040098 if (0 < val && val <= kLast_SkEncodedOrigin) {
99 *orientation = (SkEncodedOrigin) val;
msarett0e6274f2016-03-21 08:04:40 -0700100 return true;
101 }
102 }
103 }
104
105 return false;
106}
107
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -0400108static SkEncodedOrigin get_exif_orientation(jpeg_decompress_struct* dinfo) {
109 SkEncodedOrigin orientation;
msarett0e6274f2016-03-21 08:04:40 -0700110 for (jpeg_marker_struct* marker = dinfo->marker_list; marker; marker = marker->next) {
111 if (is_orientation_marker(marker, &orientation)) {
112 return orientation;
113 }
114 }
115
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -0400116 return kDefault_SkEncodedOrigin;
msarett0e6274f2016-03-21 08:04:40 -0700117}
118
119static bool is_icc_marker(jpeg_marker_struct* marker) {
Matt Sarett5df93de2017-03-22 21:52:47 +0000120 if (kICCMarker != marker->marker || marker->data_length < kICCMarkerHeaderSize) {
msarett0e6274f2016-03-21 08:04:40 -0700121 return false;
122 }
123
msarett0e6274f2016-03-21 08:04:40 -0700124 return !memcmp(marker->data, kICCSig, sizeof(kICCSig));
125}
126
127/*
128 * ICC profiles may be stored using a sequence of multiple markers. We obtain the ICC profile
129 * in two steps:
130 * (1) Discover all ICC profile markers and verify that they are numbered properly.
131 * (2) Copy the data from each marker into a contiguous ICC profile.
132 */
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400133static sk_sp<SkColorSpace> read_color_space(jpeg_decompress_struct* dinfo) {
msarett0e6274f2016-03-21 08:04:40 -0700134 // Note that 256 will be enough storage space since each markerIndex is stored in 8-bits.
135 jpeg_marker_struct* markerSequence[256];
136 memset(markerSequence, 0, sizeof(markerSequence));
137 uint8_t numMarkers = 0;
138 size_t totalBytes = 0;
139
140 // Discover any ICC markers and verify that they are numbered properly.
141 for (jpeg_marker_struct* marker = dinfo->marker_list; marker; marker = marker->next) {
142 if (is_icc_marker(marker)) {
143 // Verify that numMarkers is valid and consistent.
144 if (0 == numMarkers) {
145 numMarkers = marker->data[13];
146 if (0 == numMarkers) {
147 SkCodecPrintf("ICC Profile Error: numMarkers must be greater than zero.\n");
148 return nullptr;
149 }
150 } else if (numMarkers != marker->data[13]) {
151 SkCodecPrintf("ICC Profile Error: numMarkers must be consistent.\n");
152 return nullptr;
153 }
154
155 // Verify that the markerIndex is valid and unique. Note that zero is not
156 // a valid index.
157 uint8_t markerIndex = marker->data[12];
158 if (markerIndex == 0 || markerIndex > numMarkers) {
159 SkCodecPrintf("ICC Profile Error: markerIndex is invalid.\n");
160 return nullptr;
161 }
162 if (markerSequence[markerIndex]) {
163 SkCodecPrintf("ICC Profile Error: Duplicate value of markerIndex.\n");
164 return nullptr;
165 }
166 markerSequence[markerIndex] = marker;
Matt Sarett5df93de2017-03-22 21:52:47 +0000167 SkASSERT(marker->data_length >= kICCMarkerHeaderSize);
168 totalBytes += marker->data_length - kICCMarkerHeaderSize;
msarett0e6274f2016-03-21 08:04:40 -0700169 }
170 }
171
172 if (0 == totalBytes) {
173 // No non-empty ICC profile markers were found.
174 return nullptr;
175 }
176
177 // Combine the ICC marker data into a contiguous profile.
msarett9876ac52016-06-01 14:47:18 -0700178 sk_sp<SkData> iccData = SkData::MakeUninitialized(totalBytes);
179 void* dst = iccData->writable_data();
msarett0e6274f2016-03-21 08:04:40 -0700180 for (uint32_t i = 1; i <= numMarkers; i++) {
181 jpeg_marker_struct* marker = markerSequence[i];
182 if (!marker) {
183 SkCodecPrintf("ICC Profile Error: Missing marker %d of %d.\n", i, numMarkers);
184 return nullptr;
185 }
186
Matt Sarett5df93de2017-03-22 21:52:47 +0000187 void* src = SkTAddOffset<void>(marker->data, kICCMarkerHeaderSize);
188 size_t bytes = marker->data_length - kICCMarkerHeaderSize;
msarett0e6274f2016-03-21 08:04:40 -0700189 memcpy(dst, src, bytes);
190 dst = SkTAddOffset<void>(dst, bytes);
191 }
192
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400193 return SkColorSpace::MakeICC(iccData->data(), iccData->size());
msarett0e6274f2016-03-21 08:04:40 -0700194}
195
Leon Scroggins III588fb042017-07-14 16:32:31 -0400196SkCodec::Result SkJpegCodec::ReadHeader(SkStream* stream, SkCodec** codecOut,
197 JpegDecoderMgr** decoderMgrOut, sk_sp<SkColorSpace> defaultColorSpace) {
msarette16b04a2015-04-15 07:32:19 -0700198
199 // Create a JpegDecoderMgr to own all of the decompress information
Ben Wagner145dbcd2016-11-03 14:40:50 -0400200 std::unique_ptr<JpegDecoderMgr> decoderMgr(new JpegDecoderMgr(stream));
msarette16b04a2015-04-15 07:32:19 -0700201
202 // libjpeg errors will be caught and reported here
Chris Dalton3e794592017-12-01 13:11:09 -0700203 skjpeg_error_mgr::AutoPushJmpBuf jmp(decoderMgr->errorMgr());
204 if (setjmp(jmp)) {
Leon Scroggins III588fb042017-07-14 16:32:31 -0400205 return decoderMgr->returnFailure("ReadHeader", kInvalidInput);
msarette16b04a2015-04-15 07:32:19 -0700206 }
207
208 // Initialize the decompress info and the source manager
209 decoderMgr->init();
210
msarett0e6274f2016-03-21 08:04:40 -0700211 // Instruct jpeg library to save the markers that we care about. Since
212 // the orientation and color profile will not change, we can skip this
213 // step on rewinds.
214 if (codecOut) {
215 jpeg_save_markers(decoderMgr->dinfo(), kExifMarker, 0xFFFF);
216 jpeg_save_markers(decoderMgr->dinfo(), kICCMarker, 0xFFFF);
217 }
218
msarette16b04a2015-04-15 07:32:19 -0700219 // Read the jpeg header
Leon Scroggins III588fb042017-07-14 16:32:31 -0400220 switch (jpeg_read_header(decoderMgr->dinfo(), true)) {
221 case JPEG_HEADER_OK:
222 break;
223 case JPEG_SUSPENDED:
224 return decoderMgr->returnFailure("ReadHeader", kIncompleteInput);
225 default:
226 return decoderMgr->returnFailure("ReadHeader", kInvalidInput);
msarette16b04a2015-04-15 07:32:19 -0700227 }
228
msarett0e6274f2016-03-21 08:04:40 -0700229 if (codecOut) {
msarettc30c4182016-04-20 11:53:35 -0700230 // Get the encoded color type
msarettac6c7502016-04-25 09:30:24 -0700231 SkEncodedInfo::Color color;
232 if (!decoderMgr->getEncodedColor(&color)) {
Leon Scroggins III588fb042017-07-14 16:32:31 -0400233 return kInvalidInput;
msarettc30c4182016-04-20 11:53:35 -0700234 }
msarette16b04a2015-04-15 07:32:19 -0700235
236 // Create image info object and the codec
msarettc30c4182016-04-20 11:53:35 -0700237 SkEncodedInfo info = SkEncodedInfo::Make(color, SkEncodedInfo::kOpaque_Alpha, 8);
msarett0e6274f2016-03-21 08:04:40 -0700238
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -0400239 SkEncodedOrigin orientation = get_exif_orientation(decoderMgr->dinfo());
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400240 sk_sp<SkColorSpace> colorSpace = read_color_space(decoderMgr->dinfo());
241 if (colorSpace) {
raftias54761282016-12-01 13:44:07 -0500242 switch (decoderMgr->dinfo()->jpeg_color_space) {
243 case JCS_CMYK:
244 case JCS_YCCK:
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400245 if (colorSpace->type() != SkColorSpace::kCMYK_Type) {
246 colorSpace = nullptr;
247 }
raftias54761282016-12-01 13:44:07 -0500248 break;
raftias91db12d2016-12-02 11:56:59 -0500249 case JCS_GRAYSCALE:
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400250 if (colorSpace->type() != SkColorSpace::kGray_Type &&
251 colorSpace->type() != SkColorSpace::kRGB_Type)
252 {
253 colorSpace = nullptr;
254 }
Mike Klein503bdcd2017-11-01 08:34:15 -0400255 break;
raftias54761282016-12-01 13:44:07 -0500256 default:
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400257 if (colorSpace->type() != SkColorSpace::kRGB_Type) {
258 colorSpace = nullptr;
259 }
raftias54761282016-12-01 13:44:07 -0500260 break;
261 }
msarett9876ac52016-06-01 14:47:18 -0700262 }
msarettf34cd632016-05-25 10:13:53 -0700263 if (!colorSpace) {
Matt Sarettc5eabe72017-02-24 14:51:08 -0500264 colorSpace = defaultColorSpace;
msarettf34cd632016-05-25 10:13:53 -0700265 }
msarett0e6274f2016-03-21 08:04:40 -0700266
msarettc30c4182016-04-20 11:53:35 -0700267 const int width = decoderMgr->dinfo()->image_width;
268 const int height = decoderMgr->dinfo()->image_height;
Mike Reedede7bac2017-07-23 15:30:02 -0400269 SkJpegCodec* codec = new SkJpegCodec(width, height, info, std::unique_ptr<SkStream>(stream),
270 decoderMgr.release(), std::move(colorSpace),
271 orientation);
raftiasd737bee2016-12-08 10:53:24 -0500272 *codecOut = codec;
msarette16b04a2015-04-15 07:32:19 -0700273 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700274 SkASSERT(nullptr != decoderMgrOut);
mtklein18300a32016-03-16 13:53:35 -0700275 *decoderMgrOut = decoderMgr.release();
msarette16b04a2015-04-15 07:32:19 -0700276 }
Leon Scroggins III588fb042017-07-14 16:32:31 -0400277 return kSuccess;
msarette16b04a2015-04-15 07:32:19 -0700278}
279
Mike Reedede7bac2017-07-23 15:30:02 -0400280std::unique_ptr<SkCodec> SkJpegCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
281 Result* result) {
282 return SkJpegCodec::MakeFromStream(std::move(stream), result, SkColorSpace::MakeSRGB());
Matt Sarettc5eabe72017-02-24 14:51:08 -0500283}
284
Mike Reedede7bac2017-07-23 15:30:02 -0400285std::unique_ptr<SkCodec> SkJpegCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
286 Result* result,
Leon Scroggins III588fb042017-07-14 16:32:31 -0400287 sk_sp<SkColorSpace> defaultColorSpace) {
halcanary96fcdcc2015-08-27 07:41:13 -0700288 SkCodec* codec = nullptr;
Mike Reedede7bac2017-07-23 15:30:02 -0400289 *result = ReadHeader(stream.get(), &codec, nullptr, std::move(defaultColorSpace));
Leon Scroggins III588fb042017-07-14 16:32:31 -0400290 if (kSuccess == *result) {
msarette16b04a2015-04-15 07:32:19 -0700291 // Codec has taken ownership of the stream, we do not need to delete it
292 SkASSERT(codec);
Mike Reedede7bac2017-07-23 15:30:02 -0400293 stream.release();
294 return std::unique_ptr<SkCodec>(codec);
msarette16b04a2015-04-15 07:32:19 -0700295 }
halcanary96fcdcc2015-08-27 07:41:13 -0700296 return nullptr;
msarette16b04a2015-04-15 07:32:19 -0700297}
298
Mike Reedede7bac2017-07-23 15:30:02 -0400299SkJpegCodec::SkJpegCodec(int width, int height, const SkEncodedInfo& info,
300 std::unique_ptr<SkStream> stream, JpegDecoderMgr* decoderMgr,
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -0400301 sk_sp<SkColorSpace> colorSpace, SkEncodedOrigin origin)
Mike Reedede7bac2017-07-23 15:30:02 -0400302 : INHERITED(width, height, info, SkColorSpaceXform::kRGBA_8888_ColorFormat, std::move(stream),
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400303 std::move(colorSpace), origin)
msarette16b04a2015-04-15 07:32:19 -0700304 , fDecoderMgr(decoderMgr)
msarettfbccb592015-09-01 06:43:41 -0700305 , fReadyState(decoderMgr->dinfo()->global_state)
msarett50ce1f22016-07-29 06:23:33 -0700306 , fSwizzleSrcRow(nullptr)
307 , fColorXformSrcRow(nullptr)
msarett91c22b22016-02-22 12:27:46 -0800308 , fSwizzlerSubset(SkIRect::MakeEmpty())
msarette16b04a2015-04-15 07:32:19 -0700309{}
310
311/*
emmaleer8f4ba762015-08-14 07:44:46 -0700312 * Return the row bytes of a particular image type and width
313 */
msarett23e78d32016-02-06 15:58:50 -0800314static size_t get_row_bytes(const j_decompress_ptr dinfo) {
msarett70e418b2016-02-12 12:35:48 -0800315 const size_t colorBytes = (dinfo->out_color_space == JCS_RGB565) ? 2 :
316 dinfo->out_color_components;
emmaleer8f4ba762015-08-14 07:44:46 -0700317 return dinfo->output_width * colorBytes;
318
319}
scroggoe7fc14b2015-10-02 13:14:46 -0700320
321/*
322 * Calculate output dimensions based on the provided factors.
323 *
324 * Not to be used on the actual jpeg_decompress_struct used for decoding, since it will
325 * incorrectly modify num_components.
326 */
327void calc_output_dimensions(jpeg_decompress_struct* dinfo, unsigned int num, unsigned int denom) {
328 dinfo->num_components = 0;
329 dinfo->scale_num = num;
330 dinfo->scale_denom = denom;
331 jpeg_calc_output_dimensions(dinfo);
332}
333
emmaleer8f4ba762015-08-14 07:44:46 -0700334/*
msarette16b04a2015-04-15 07:32:19 -0700335 * Return a valid set of output dimensions for this decoder, given an input scale
336 */
337SkISize SkJpegCodec::onGetScaledDimensions(float desiredScale) const {
msarett1c8a5872015-07-07 08:50:01 -0700338 // 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
339 // support these as well
scroggoe7fc14b2015-10-02 13:14:46 -0700340 unsigned int num;
341 unsigned int denom = 8;
msarettfdb47572015-10-13 12:50:14 -0700342 if (desiredScale >= 0.9375) {
msarett1c8a5872015-07-07 08:50:01 -0700343 num = 8;
msarettfdb47572015-10-13 12:50:14 -0700344 } else if (desiredScale >= 0.8125) {
msarett1c8a5872015-07-07 08:50:01 -0700345 num = 7;
msarettfdb47572015-10-13 12:50:14 -0700346 } else if (desiredScale >= 0.6875f) {
msarett1c8a5872015-07-07 08:50:01 -0700347 num = 6;
msarettfdb47572015-10-13 12:50:14 -0700348 } else if (desiredScale >= 0.5625f) {
msarett1c8a5872015-07-07 08:50:01 -0700349 num = 5;
msarettfdb47572015-10-13 12:50:14 -0700350 } else if (desiredScale >= 0.4375f) {
msarett1c8a5872015-07-07 08:50:01 -0700351 num = 4;
msarettfdb47572015-10-13 12:50:14 -0700352 } else if (desiredScale >= 0.3125f) {
msarett1c8a5872015-07-07 08:50:01 -0700353 num = 3;
msarettfdb47572015-10-13 12:50:14 -0700354 } else if (desiredScale >= 0.1875f) {
msarett1c8a5872015-07-07 08:50:01 -0700355 num = 2;
msarette16b04a2015-04-15 07:32:19 -0700356 } else {
msarett1c8a5872015-07-07 08:50:01 -0700357 num = 1;
msarette16b04a2015-04-15 07:32:19 -0700358 }
359
360 // Set up a fake decompress struct in order to use libjpeg to calculate output dimensions
361 jpeg_decompress_struct dinfo;
mtkleinf7aaadb2015-04-16 06:09:27 -0700362 sk_bzero(&dinfo, sizeof(dinfo));
msarette16b04a2015-04-15 07:32:19 -0700363 dinfo.image_width = this->getInfo().width();
364 dinfo.image_height = this->getInfo().height();
msarettfbccb592015-09-01 06:43:41 -0700365 dinfo.global_state = fReadyState;
scroggoe7fc14b2015-10-02 13:14:46 -0700366 calc_output_dimensions(&dinfo, num, denom);
msarette16b04a2015-04-15 07:32:19 -0700367
368 // Return the calculated output dimensions for the given scale
369 return SkISize::Make(dinfo.output_width, dinfo.output_height);
370}
371
scroggob427db12015-08-12 07:24:13 -0700372bool SkJpegCodec::onRewind() {
halcanary96fcdcc2015-08-27 07:41:13 -0700373 JpegDecoderMgr* decoderMgr = nullptr;
Leon Scroggins III588fb042017-07-14 16:32:31 -0400374 if (kSuccess != ReadHeader(this->stream(), nullptr, &decoderMgr, nullptr)) {
msarett50ce1f22016-07-29 06:23:33 -0700375 return fDecoderMgr->returnFalse("onRewind");
msarett97fdea62015-04-29 08:17:15 -0700376 }
halcanary96fcdcc2015-08-27 07:41:13 -0700377 SkASSERT(nullptr != decoderMgr);
scroggob427db12015-08-12 07:24:13 -0700378 fDecoderMgr.reset(decoderMgr);
msarett2812f032016-07-18 15:56:08 -0700379
380 fSwizzler.reset(nullptr);
msarett50ce1f22016-07-29 06:23:33 -0700381 fSwizzleSrcRow = nullptr;
382 fColorXformSrcRow = nullptr;
msarett2812f032016-07-18 15:56:08 -0700383 fStorage.reset();
384
scroggob427db12015-08-12 07:24:13 -0700385 return true;
msarett97fdea62015-04-29 08:17:15 -0700386}
387
388/*
msarett1c8a5872015-07-07 08:50:01 -0700389 * Checks if the conversion between the input image and the requested output
390 * image has been implemented
391 * Sets the output color space
392 */
msarett2ecc35f2016-09-08 11:55:16 -0700393bool SkJpegCodec::setOutputColorSpace(const SkImageInfo& dstInfo) {
msarett50ce1f22016-07-29 06:23:33 -0700394 if (kUnknown_SkAlphaType == dstInfo.alphaType()) {
msarett1c8a5872015-07-07 08:50:01 -0700395 return false;
396 }
397
msarett50ce1f22016-07-29 06:23:33 -0700398 if (kOpaque_SkAlphaType != dstInfo.alphaType()) {
scroggoc5560be2016-02-03 09:42:42 -0800399 SkCodecPrintf("Warning: an opaque image should be decoded as opaque "
400 "- it is being decoded as non-opaque, which will draw slower\n");
401 }
402
msarett50ce1f22016-07-29 06:23:33 -0700403 J_COLOR_SPACE encodedColorType = fDecoderMgr->dinfo()->jpeg_color_space;
msarett1c8a5872015-07-07 08:50:01 -0700404
405 // Check for valid color types and set the output color space
msarett50ce1f22016-07-29 06:23:33 -0700406 switch (dstInfo.colorType()) {
msarett34e0ec42016-04-22 16:27:24 -0700407 case kRGBA_8888_SkColorType:
nagarajan.n08cda142017-09-07 20:03:29 +0530408 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
409 break;
msarett34e0ec42016-04-22 16:27:24 -0700410 case kBGRA_8888_SkColorType:
nagarajan.n08cda142017-09-07 20:03:29 +0530411 if (this->colorXform()) {
Matt Sarett562e6812016-11-08 16:13:43 -0500412 // Always using RGBA as the input format for color xforms makes the
413 // implementation a little simpler.
msarett50ce1f22016-07-29 06:23:33 -0700414 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
msarett34e0ec42016-04-22 16:27:24 -0700415 } else {
msarettf25bff92016-07-21 12:00:24 -0700416 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_BGRA;
msarett1c8a5872015-07-07 08:50:01 -0700417 }
nagarajan.n08cda142017-09-07 20:03:29 +0530418 break;
msarett1c8a5872015-07-07 08:50:01 -0700419 case kRGB_565_SkColorType:
nagarajan.n08cda142017-09-07 20:03:29 +0530420 if (this->colorXform()) {
Matt Sarett3725f0a2017-03-28 14:34:20 -0400421 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
msarett1c8a5872015-07-07 08:50:01 -0700422 } else {
msarett8ff6ca62015-09-18 12:06:04 -0700423 fDecoderMgr->dinfo()->dither_mode = JDITHER_NONE;
msarett1c8a5872015-07-07 08:50:01 -0700424 fDecoderMgr->dinfo()->out_color_space = JCS_RGB565;
425 }
nagarajan.n08cda142017-09-07 20:03:29 +0530426 break;
msarett1c8a5872015-07-07 08:50:01 -0700427 case kGray_8_SkColorType:
Matt Sarett313c4632016-10-20 12:35:23 -0400428 if (this->colorXform() || JCS_GRAYSCALE != encodedColorType) {
msarett39979d82016-07-28 17:11:18 -0700429 return false;
msarett50ce1f22016-07-29 06:23:33 -0700430 }
431
432 fDecoderMgr->dinfo()->out_color_space = JCS_GRAYSCALE;
nagarajan.n08cda142017-09-07 20:03:29 +0530433 break;
msarett50ce1f22016-07-29 06:23:33 -0700434 case kRGBA_F16_SkColorType:
Matt Sarett313c4632016-10-20 12:35:23 -0400435 SkASSERT(this->colorXform());
nagarajan.n08cda142017-09-07 20:03:29 +0530436 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
437 break;
msarett1c8a5872015-07-07 08:50:01 -0700438 default:
439 return false;
440 }
nagarajan.n08cda142017-09-07 20:03:29 +0530441
442 // Check if we will decode to CMYK. libjpeg-turbo does not convert CMYK to RGBA, so
443 // we must do it ourselves.
444 if (JCS_CMYK == encodedColorType || JCS_YCCK == encodedColorType) {
445 fDecoderMgr->dinfo()->out_color_space = JCS_CMYK;
446 }
447
448 return true;
msarett1c8a5872015-07-07 08:50:01 -0700449}
450
451/*
mtkleine721a8e2016-02-06 19:12:23 -0800452 * Checks if we can natively scale to the requested dimensions and natively scales the
emmaleer8f4ba762015-08-14 07:44:46 -0700453 * dimensions if possible
msarett97fdea62015-04-29 08:17:15 -0700454 */
scroggoe7fc14b2015-10-02 13:14:46 -0700455bool SkJpegCodec::onDimensionsSupported(const SkISize& size) {
Chris Dalton3e794592017-12-01 13:11:09 -0700456 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
457 if (setjmp(jmp)) {
msarett50ce1f22016-07-29 06:23:33 -0700458 return fDecoderMgr->returnFalse("onDimensionsSupported");
scroggoe7fc14b2015-10-02 13:14:46 -0700459 }
460
461 const unsigned int dstWidth = size.width();
462 const unsigned int dstHeight = size.height();
463
464 // Set up a fake decompress struct in order to use libjpeg to calculate output dimensions
465 // FIXME: Why is this necessary?
466 jpeg_decompress_struct dinfo;
467 sk_bzero(&dinfo, sizeof(dinfo));
468 dinfo.image_width = this->getInfo().width();
469 dinfo.image_height = this->getInfo().height();
470 dinfo.global_state = fReadyState;
471
msarett1c8a5872015-07-07 08:50:01 -0700472 // 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 -0700473 unsigned int num = 8;
474 const unsigned int denom = 8;
475 calc_output_dimensions(&dinfo, num, denom);
476 while (dinfo.output_width != dstWidth || dinfo.output_height != dstHeight) {
msarett97fdea62015-04-29 08:17:15 -0700477
478 // Return a failure if we have tried all of the possible scales
scroggoe7fc14b2015-10-02 13:14:46 -0700479 if (1 == num || dstWidth > dinfo.output_width || dstHeight > dinfo.output_height) {
emmaleer8f4ba762015-08-14 07:44:46 -0700480 return false;
msarett97fdea62015-04-29 08:17:15 -0700481 }
482
483 // Try the next scale
scroggoe7fc14b2015-10-02 13:14:46 -0700484 num -= 1;
485 calc_output_dimensions(&dinfo, num, denom);
msarett97fdea62015-04-29 08:17:15 -0700486 }
scroggoe7fc14b2015-10-02 13:14:46 -0700487
488 fDecoderMgr->dinfo()->scale_num = num;
489 fDecoderMgr->dinfo()->scale_denom = denom;
msarett97fdea62015-04-29 08:17:15 -0700490 return true;
491}
492
Matt Sarettc8c901f2017-01-24 16:16:33 -0500493int SkJpegCodec::readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count,
494 const Options& opts) {
msarett50ce1f22016-07-29 06:23:33 -0700495 // Set the jump location for libjpeg-turbo errors
Chris Dalton3e794592017-12-01 13:11:09 -0700496 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
497 if (setjmp(jmp)) {
msarett50ce1f22016-07-29 06:23:33 -0700498 return 0;
499 }
500
501 // When fSwizzleSrcRow is non-null, it means that we need to swizzle. In this case,
502 // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer.
503 // We can never swizzle "in place" because the swizzler may perform sampling and/or
504 // subsetting.
505 // When fColorXformSrcRow is non-null, it means that we need to color xform and that
506 // we cannot color xform "in place" (many times we can, but not when the dst is F16).
Matt Sarett313c4632016-10-20 12:35:23 -0400507 // In this case, we will color xform from fColorXformSrcRow into the dst.
msarett50ce1f22016-07-29 06:23:33 -0700508 JSAMPLE* decodeDst = (JSAMPLE*) dst;
509 uint32_t* swizzleDst = (uint32_t*) dst;
510 size_t decodeDstRowBytes = rowBytes;
511 size_t swizzleDstRowBytes = rowBytes;
Matt Sarettc8c901f2017-01-24 16:16:33 -0500512 int dstWidth = opts.fSubset ? opts.fSubset->width() : dstInfo.width();
msarett50ce1f22016-07-29 06:23:33 -0700513 if (fSwizzleSrcRow && fColorXformSrcRow) {
514 decodeDst = (JSAMPLE*) fSwizzleSrcRow;
515 swizzleDst = fColorXformSrcRow;
516 decodeDstRowBytes = 0;
517 swizzleDstRowBytes = 0;
msarett35bb74b2016-08-22 07:41:28 -0700518 dstWidth = fSwizzler->swizzleWidth();
msarett50ce1f22016-07-29 06:23:33 -0700519 } else if (fColorXformSrcRow) {
520 decodeDst = (JSAMPLE*) fColorXformSrcRow;
521 swizzleDst = fColorXformSrcRow;
522 decodeDstRowBytes = 0;
523 swizzleDstRowBytes = 0;
524 } else if (fSwizzleSrcRow) {
525 decodeDst = (JSAMPLE*) fSwizzleSrcRow;
526 decodeDstRowBytes = 0;
msarett35bb74b2016-08-22 07:41:28 -0700527 dstWidth = fSwizzler->swizzleWidth();
msarett50ce1f22016-07-29 06:23:33 -0700528 }
529
530 for (int y = 0; y < count; y++) {
531 uint32_t lines = jpeg_read_scanlines(fDecoderMgr->dinfo(), &decodeDst, 1);
msarett50ce1f22016-07-29 06:23:33 -0700532 if (0 == lines) {
533 return y;
534 }
535
536 if (fSwizzler) {
537 fSwizzler->swizzle(swizzleDst, decodeDst);
538 }
539
Matt Sarett313c4632016-10-20 12:35:23 -0400540 if (this->colorXform()) {
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400541 this->applyColorXform(dst, swizzleDst, dstWidth, kOpaque_SkAlphaType);
msarett50ce1f22016-07-29 06:23:33 -0700542 dst = SkTAddOffset<void>(dst, rowBytes);
543 }
544
545 decodeDst = SkTAddOffset<JSAMPLE>(decodeDst, decodeDstRowBytes);
546 swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes);
547 }
548
549 return count;
550}
551
msarett97fdea62015-04-29 08:17:15 -0700552/*
Matt Sarett7f15b682017-02-24 17:22:09 -0500553 * This is a bit tricky. We only need the swizzler to do format conversion if the jpeg is
554 * encoded as CMYK.
555 * And even then we still may not need it. If the jpeg has a CMYK color space and a color
556 * xform, the color xform will handle the CMYK->RGB conversion.
557 */
558static inline bool needs_swizzler_to_convert_from_cmyk(J_COLOR_SPACE jpegColorType,
559 const SkImageInfo& srcInfo, bool hasColorSpaceXform) {
560 if (JCS_CMYK != jpegColorType) {
561 return false;
562 }
563
Brian Osman36703d92017-12-12 14:09:31 -0500564 bool hasCMYKColorSpace = SkColorSpace::kCMYK_Type == srcInfo.colorSpace()->type();
Matt Sarett7f15b682017-02-24 17:22:09 -0500565 return !hasCMYKColorSpace || !hasColorSpaceXform;
566}
567
568/*
msarette16b04a2015-04-15 07:32:19 -0700569 * Performs the jpeg decode
570 */
571SkCodec::Result SkJpegCodec::onGetPixels(const SkImageInfo& dstInfo,
572 void* dst, size_t dstRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000573 const Options& options,
msarette6dd0042015-10-09 11:07:34 -0700574 int* rowsDecoded) {
scroggob636b452015-07-22 07:16:20 -0700575 if (options.fSubset) {
576 // Subsets are not supported.
577 return kUnimplemented;
578 }
579
msarette16b04a2015-04-15 07:32:19 -0700580 // Get a pointer to the decompress info since we will use it quite frequently
581 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
582
583 // Set the jump location for libjpeg errors
Chris Dalton3e794592017-12-01 13:11:09 -0700584 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
585 if (setjmp(jmp)) {
msarette16b04a2015-04-15 07:32:19 -0700586 return fDecoderMgr->returnFailure("setjmp", kInvalidInput);
587 }
588
msarett2ecc35f2016-09-08 11:55:16 -0700589 // Check if we can decode to the requested destination and set the output color space
590 if (!this->setOutputColorSpace(dstInfo)) {
591 return fDecoderMgr->returnFailure("setOutputColorSpace", kInvalidConversion);
msarett85c922a2016-09-08 10:54:34 -0700592 }
593
msarettfbccb592015-09-01 06:43:41 -0700594 if (!jpeg_start_decompress(dinfo)) {
msarette16b04a2015-04-15 07:32:19 -0700595 return fDecoderMgr->returnFailure("startDecompress", kInvalidInput);
596 }
597
msarett1c8a5872015-07-07 08:50:01 -0700598 // The recommended output buffer height should always be 1 in high quality modes.
599 // If it's not, we want to know because it means our strategy is not optimal.
600 SkASSERT(1 == dinfo->rec_outbuf_height);
msarette16b04a2015-04-15 07:32:19 -0700601
Matt Sarett7f15b682017-02-24 17:22:09 -0500602 if (needs_swizzler_to_convert_from_cmyk(dinfo->out_color_space, this->getInfo(),
603 this->colorXform())) {
604 this->initializeSwizzler(dstInfo, options, true);
scroggoef27d892015-10-23 09:29:22 -0700605 }
606
msarett50ce1f22016-07-29 06:23:33 -0700607 this->allocateStorage(dstInfo);
scroggoef27d892015-10-23 09:29:22 -0700608
Matt Sarettc8c901f2017-01-24 16:16:33 -0500609 int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options);
msarett50ce1f22016-07-29 06:23:33 -0700610 if (rows < dstInfo.height()) {
611 *rowsDecoded = rows;
612 return fDecoderMgr->returnFailure("Incomplete image data", kIncompleteInput);
msarette16b04a2015-04-15 07:32:19 -0700613 }
msarette16b04a2015-04-15 07:32:19 -0700614
615 return kSuccess;
616}
msarett97fdea62015-04-29 08:17:15 -0700617
msarett50ce1f22016-07-29 06:23:33 -0700618void SkJpegCodec::allocateStorage(const SkImageInfo& dstInfo) {
msarett35bb74b2016-08-22 07:41:28 -0700619 int dstWidth = dstInfo.width();
620
msarett50ce1f22016-07-29 06:23:33 -0700621 size_t swizzleBytes = 0;
622 if (fSwizzler) {
623 swizzleBytes = get_row_bytes(fDecoderMgr->dinfo());
msarett35bb74b2016-08-22 07:41:28 -0700624 dstWidth = fSwizzler->swizzleWidth();
Matt Sarett313c4632016-10-20 12:35:23 -0400625 SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes));
msarett50ce1f22016-07-29 06:23:33 -0700626 }
627
628 size_t xformBytes = 0;
Matt Sarett3725f0a2017-03-28 14:34:20 -0400629 if (this->colorXform() && (kRGBA_F16_SkColorType == dstInfo.colorType() ||
630 kRGB_565_SkColorType == dstInfo.colorType())) {
msarett35bb74b2016-08-22 07:41:28 -0700631 xformBytes = dstWidth * sizeof(uint32_t);
msarett50ce1f22016-07-29 06:23:33 -0700632 }
633
634 size_t totalBytes = swizzleBytes + xformBytes;
635 if (totalBytes > 0) {
636 fStorage.reset(totalBytes);
637 fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr;
638 fColorXformSrcRow = (xformBytes > 0) ?
639 SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr;
640 }
641}
642
Matt Sarett7f15b682017-02-24 17:22:09 -0500643void SkJpegCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& options,
644 bool needsCMYKToRGB) {
msaretta45a6682016-04-22 13:18:37 -0700645 SkEncodedInfo swizzlerInfo = this->getEncodedInfo();
Matt Sarett7f15b682017-02-24 17:22:09 -0500646 if (needsCMYKToRGB) {
mtkleinda19f6f2016-08-23 11:49:29 -0700647 swizzlerInfo = SkEncodedInfo::Make(SkEncodedInfo::kInvertedCMYK_Color,
648 swizzlerInfo.alpha(),
649 swizzlerInfo.bitsPerComponent());
msarett70e418b2016-02-12 12:35:48 -0800650 }
651
msarett91c22b22016-02-22 12:27:46 -0800652 Options swizzlerOptions = options;
653 if (options.fSubset) {
654 // Use fSwizzlerSubset if this is a subset decode. This is necessary in the case
655 // where libjpeg-turbo provides a subset and then we need to subset it further.
656 // Also, verify that fSwizzlerSubset is initialized and valid.
657 SkASSERT(!fSwizzlerSubset.isEmpty() && fSwizzlerSubset.x() <= options.fSubset->x() &&
658 fSwizzlerSubset.width() == options.fSubset->width());
659 swizzlerOptions.fSubset = &fSwizzlerSubset;
660 }
Matt Sarett09a1c082017-02-01 15:34:22 -0800661
662 SkImageInfo swizzlerDstInfo = dstInfo;
Matt Sarett7f15b682017-02-24 17:22:09 -0500663 if (this->colorXform()) {
664 // The color xform will be expecting RGBA 8888 input.
Matt Sarett09a1c082017-02-01 15:34:22 -0800665 swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType);
666 }
667
668 fSwizzler.reset(SkSwizzler::CreateSwizzler(swizzlerInfo, nullptr, swizzlerDstInfo,
Matt Sarett7f15b682017-02-24 17:22:09 -0500669 swizzlerOptions, nullptr, !needsCMYKToRGB));
msarettb30d6982016-02-15 10:18:45 -0800670 SkASSERT(fSwizzler);
msarett50ce1f22016-07-29 06:23:33 -0700671}
672
msarettfdb47572015-10-13 12:50:14 -0700673SkSampler* SkJpegCodec::getSampler(bool createIfNecessary) {
674 if (!createIfNecessary || fSwizzler) {
msarett50ce1f22016-07-29 06:23:33 -0700675 SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow));
Ben Wagner145dbcd2016-11-03 14:40:50 -0400676 return fSwizzler.get();
msarettfdb47572015-10-13 12:50:14 -0700677 }
678
Matt Sarett7f15b682017-02-24 17:22:09 -0500679 bool needsCMYKToRGB = needs_swizzler_to_convert_from_cmyk(
680 fDecoderMgr->dinfo()->out_color_space, this->getInfo(), this->colorXform());
681 this->initializeSwizzler(this->dstInfo(), this->options(), needsCMYKToRGB);
msarett50ce1f22016-07-29 06:23:33 -0700682 this->allocateStorage(this->dstInfo());
Ben Wagner145dbcd2016-11-03 14:40:50 -0400683 return fSwizzler.get();
scroggo46c57472015-09-30 08:57:13 -0700684}
scroggo1c005e42015-08-04 09:24:45 -0700685
scroggo46c57472015-09-30 08:57:13 -0700686SkCodec::Result SkJpegCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000687 const Options& options) {
scroggo46c57472015-09-30 08:57:13 -0700688 // Set the jump location for libjpeg errors
Chris Dalton3e794592017-12-01 13:11:09 -0700689 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
690 if (setjmp(jmp)) {
scroggo46c57472015-09-30 08:57:13 -0700691 SkCodecPrintf("setjmp: Error from libjpeg\n");
692 return kInvalidInput;
693 }
694
msarett2ecc35f2016-09-08 11:55:16 -0700695 // Check if we can decode to the requested destination and set the output color space
696 if (!this->setOutputColorSpace(dstInfo)) {
697 return fDecoderMgr->returnFailure("setOutputColorSpace", kInvalidConversion);
msarett50ce1f22016-07-29 06:23:33 -0700698 }
699
scroggo46c57472015-09-30 08:57:13 -0700700 if (!jpeg_start_decompress(fDecoderMgr->dinfo())) {
701 SkCodecPrintf("start decompress failed\n");
702 return kInvalidInput;
703 }
704
Matt Sarett7f15b682017-02-24 17:22:09 -0500705 bool needsCMYKToRGB = needs_swizzler_to_convert_from_cmyk(
706 fDecoderMgr->dinfo()->out_color_space, this->getInfo(), this->colorXform());
msarett91c22b22016-02-22 12:27:46 -0800707 if (options.fSubset) {
708 uint32_t startX = options.fSubset->x();
709 uint32_t width = options.fSubset->width();
710
711 // libjpeg-turbo may need to align startX to a multiple of the IDCT
712 // block size. If this is the case, it will decrease the value of
713 // startX to the appropriate alignment and also increase the value
714 // of width so that the right edge of the requested subset remains
715 // the same.
716 jpeg_crop_scanline(fDecoderMgr->dinfo(), &startX, &width);
717
718 SkASSERT(startX <= (uint32_t) options.fSubset->x());
719 SkASSERT(width >= (uint32_t) options.fSubset->width());
720 SkASSERT(startX + width >= (uint32_t) options.fSubset->right());
721
722 // Instruct the swizzler (if it is necessary) to further subset the
723 // output provided by libjpeg-turbo.
724 //
725 // We set this here (rather than in the if statement below), so that
726 // if (1) we don't need a swizzler for the subset, and (2) we need a
727 // swizzler for CMYK, the swizzler will still use the proper subset
728 // dimensions.
729 //
730 // Note that the swizzler will ignore the y and height parameters of
731 // the subset. Since the scanline decoder (and the swizzler) handle
732 // one row at a time, only the subsetting in the x-dimension matters.
733 fSwizzlerSubset.setXYWH(options.fSubset->x() - startX, 0,
734 options.fSubset->width(), options.fSubset->height());
735
736 // We will need a swizzler if libjpeg-turbo cannot provide the exact
737 // subset that we request.
738 if (startX != (uint32_t) options.fSubset->x() ||
739 width != (uint32_t) options.fSubset->width()) {
Matt Sarett7f15b682017-02-24 17:22:09 -0500740 this->initializeSwizzler(dstInfo, options, needsCMYKToRGB);
msarett91c22b22016-02-22 12:27:46 -0800741 }
742 }
743
744 // Make sure we have a swizzler if we are converting from CMYK.
Matt Sarett7f15b682017-02-24 17:22:09 -0500745 if (!fSwizzler && needsCMYKToRGB) {
746 this->initializeSwizzler(dstInfo, options, true);
msarett91c22b22016-02-22 12:27:46 -0800747 }
msarettfdb47572015-10-13 12:50:14 -0700748
msarett50ce1f22016-07-29 06:23:33 -0700749 this->allocateStorage(dstInfo);
750
scroggo46c57472015-09-30 08:57:13 -0700751 return kSuccess;
752}
753
mtkleine721a8e2016-02-06 19:12:23 -0800754int SkJpegCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) {
Matt Sarettc8c901f2017-01-24 16:16:33 -0500755 int rows = this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options());
msarett50ce1f22016-07-29 06:23:33 -0700756 if (rows < count) {
757 // This allows us to skip calling jpeg_finish_decompress().
758 fDecoderMgr->dinfo()->output_scanline = this->dstInfo().height();
scroggo46c57472015-09-30 08:57:13 -0700759 }
760
msarett50ce1f22016-07-29 06:23:33 -0700761 return rows;
scroggo46c57472015-09-30 08:57:13 -0700762}
msarett97fdea62015-04-29 08:17:15 -0700763
msarette6dd0042015-10-09 11:07:34 -0700764bool SkJpegCodec::onSkipScanlines(int count) {
scroggo46c57472015-09-30 08:57:13 -0700765 // Set the jump location for libjpeg errors
Chris Dalton3e794592017-12-01 13:11:09 -0700766 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
767 if (setjmp(jmp)) {
msarett50ce1f22016-07-29 06:23:33 -0700768 return fDecoderMgr->returnFalse("onSkipScanlines");
msarett97fdea62015-04-29 08:17:15 -0700769 }
770
msarettf724b992015-10-15 06:41:06 -0700771 return (uint32_t) count == jpeg_skip_scanlines(fDecoderMgr->dinfo(), count);
msarett97fdea62015-04-29 08:17:15 -0700772}
msarettb714fb02016-01-22 14:46:42 -0800773
774static bool is_yuv_supported(jpeg_decompress_struct* dinfo) {
775 // Scaling is not supported in raw data mode.
776 SkASSERT(dinfo->scale_num == dinfo->scale_denom);
777
778 // I can't imagine that this would ever change, but we do depend on it.
779 static_assert(8 == DCTSIZE, "DCTSIZE (defined in jpeg library) should always be 8.");
780
781 if (JCS_YCbCr != dinfo->jpeg_color_space) {
782 return false;
783 }
784
785 SkASSERT(3 == dinfo->num_components);
786 SkASSERT(dinfo->comp_info);
787
788 // It is possible to perform a YUV decode for any combination of
789 // horizontal and vertical sampling that is supported by
790 // libjpeg/libjpeg-turbo. However, we will start by supporting only the
791 // common cases (where U and V have samp_factors of one).
792 //
793 // The definition of samp_factor is kind of the opposite of what SkCodec
794 // thinks of as a sampling factor. samp_factor is essentially a
795 // multiplier, and the larger the samp_factor is, the more samples that
796 // there will be. Ex:
797 // U_plane_width = image_width * (U_h_samp_factor / max_h_samp_factor)
798 //
799 // Supporting cases where the samp_factors for U or V were larger than
800 // that of Y would be an extremely difficult change, given that clients
801 // allocate memory as if the size of the Y plane is always the size of the
802 // image. However, this case is very, very rare.
msarett7c87cf42016-03-04 06:23:20 -0800803 if ((1 != dinfo->comp_info[1].h_samp_factor) ||
804 (1 != dinfo->comp_info[1].v_samp_factor) ||
805 (1 != dinfo->comp_info[2].h_samp_factor) ||
806 (1 != dinfo->comp_info[2].v_samp_factor))
807 {
msarettb714fb02016-01-22 14:46:42 -0800808 return false;
809 }
810
811 // Support all common cases of Y samp_factors.
812 // TODO (msarett): As mentioned above, it would be possible to support
813 // more combinations of samp_factors. The issues are:
814 // (1) Are there actually any images that are not covered
815 // by these cases?
816 // (2) How much complexity would be added to the
817 // implementation in order to support these rare
818 // cases?
819 int hSampY = dinfo->comp_info[0].h_samp_factor;
820 int vSampY = dinfo->comp_info[0].v_samp_factor;
821 return (1 == hSampY && 1 == vSampY) ||
822 (2 == hSampY && 1 == vSampY) ||
823 (2 == hSampY && 2 == vSampY) ||
824 (1 == hSampY && 2 == vSampY) ||
825 (4 == hSampY && 1 == vSampY) ||
826 (4 == hSampY && 2 == vSampY);
827}
828
msarett4984c3c2016-03-10 05:44:43 -0800829bool SkJpegCodec::onQueryYUV8(SkYUVSizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const {
msarettb714fb02016-01-22 14:46:42 -0800830 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
831 if (!is_yuv_supported(dinfo)) {
832 return false;
833 }
834
nagarajan.nb1854fa2017-07-19 19:53:21 +0530835 jpeg_component_info * comp_info = dinfo->comp_info;
836 for (auto i : { SkYUVSizeInfo::kY, SkYUVSizeInfo::kU, SkYUVSizeInfo::kV }) {
837 sizeInfo->fSizes[i].set(comp_info[i].downsampled_width, comp_info[i].downsampled_height);
838 sizeInfo->fWidthBytes[i] = comp_info[i].width_in_blocks * DCTSIZE;
839 }
msarettb714fb02016-01-22 14:46:42 -0800840
841 if (colorSpace) {
842 *colorSpace = kJPEG_SkYUVColorSpace;
843 }
844
845 return true;
846}
847
msarett4984c3c2016-03-10 05:44:43 -0800848SkCodec::Result SkJpegCodec::onGetYUV8Planes(const SkYUVSizeInfo& sizeInfo, void* planes[3]) {
849 SkYUVSizeInfo defaultInfo;
msarettb714fb02016-01-22 14:46:42 -0800850
851 // This will check is_yuv_supported(), so we don't need to here.
852 bool supportsYUV = this->onQueryYUV8(&defaultInfo, nullptr);
msarett4984c3c2016-03-10 05:44:43 -0800853 if (!supportsYUV ||
854 sizeInfo.fSizes[SkYUVSizeInfo::kY] != defaultInfo.fSizes[SkYUVSizeInfo::kY] ||
855 sizeInfo.fSizes[SkYUVSizeInfo::kU] != defaultInfo.fSizes[SkYUVSizeInfo::kU] ||
856 sizeInfo.fSizes[SkYUVSizeInfo::kV] != defaultInfo.fSizes[SkYUVSizeInfo::kV] ||
857 sizeInfo.fWidthBytes[SkYUVSizeInfo::kY] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kY] ||
858 sizeInfo.fWidthBytes[SkYUVSizeInfo::kU] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kU] ||
859 sizeInfo.fWidthBytes[SkYUVSizeInfo::kV] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kV]) {
msarettb714fb02016-01-22 14:46:42 -0800860 return fDecoderMgr->returnFailure("onGetYUV8Planes", kInvalidInput);
861 }
862
863 // Set the jump location for libjpeg errors
Chris Dalton3e794592017-12-01 13:11:09 -0700864 skjpeg_error_mgr::AutoPushJmpBuf jmp(fDecoderMgr->errorMgr());
865 if (setjmp(jmp)) {
msarettb714fb02016-01-22 14:46:42 -0800866 return fDecoderMgr->returnFailure("setjmp", kInvalidInput);
867 }
868
869 // Get a pointer to the decompress info since we will use it quite frequently
870 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
871
872 dinfo->raw_data_out = TRUE;
873 if (!jpeg_start_decompress(dinfo)) {
874 return fDecoderMgr->returnFailure("startDecompress", kInvalidInput);
875 }
876
877 // A previous implementation claims that the return value of is_yuv_supported()
878 // may change after calling jpeg_start_decompress(). It looks to me like this
879 // was caused by a bug in the old code, but we'll be safe and check here.
880 SkASSERT(is_yuv_supported(dinfo));
881
882 // Currently, we require that the Y plane dimensions match the image dimensions
883 // and that the U and V planes are the same dimensions.
msarett4984c3c2016-03-10 05:44:43 -0800884 SkASSERT(sizeInfo.fSizes[SkYUVSizeInfo::kU] == sizeInfo.fSizes[SkYUVSizeInfo::kV]);
885 SkASSERT((uint32_t) sizeInfo.fSizes[SkYUVSizeInfo::kY].width() == dinfo->output_width &&
886 (uint32_t) sizeInfo.fSizes[SkYUVSizeInfo::kY].height() == dinfo->output_height);
msarettb714fb02016-01-22 14:46:42 -0800887
888 // Build a JSAMPIMAGE to handle output from libjpeg-turbo. A JSAMPIMAGE has
889 // a 2-D array of pixels for each of the components (Y, U, V) in the image.
890 // Cheat Sheet:
891 // JSAMPIMAGE == JSAMPLEARRAY* == JSAMPROW** == JSAMPLE***
892 JSAMPARRAY yuv[3];
893
894 // Set aside enough space for pointers to rows of Y, U, and V.
895 JSAMPROW rowptrs[2 * DCTSIZE + DCTSIZE + DCTSIZE];
896 yuv[0] = &rowptrs[0]; // Y rows (DCTSIZE or 2 * DCTSIZE)
897 yuv[1] = &rowptrs[2 * DCTSIZE]; // U rows (DCTSIZE)
898 yuv[2] = &rowptrs[3 * DCTSIZE]; // V rows (DCTSIZE)
899
900 // Initialize rowptrs.
901 int numYRowsPerBlock = DCTSIZE * dinfo->comp_info[0].v_samp_factor;
902 for (int i = 0; i < numYRowsPerBlock; i++) {
msarett4984c3c2016-03-10 05:44:43 -0800903 rowptrs[i] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kY],
904 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kY]);
msarettb714fb02016-01-22 14:46:42 -0800905 }
906 for (int i = 0; i < DCTSIZE; i++) {
msarett4984c3c2016-03-10 05:44:43 -0800907 rowptrs[i + 2 * DCTSIZE] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kU],
908 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kU]);
909 rowptrs[i + 3 * DCTSIZE] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kV],
910 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kV]);
msarettb714fb02016-01-22 14:46:42 -0800911 }
912
913 // After each loop iteration, we will increment pointers to Y, U, and V.
msarett4984c3c2016-03-10 05:44:43 -0800914 size_t blockIncrementY = numYRowsPerBlock * sizeInfo.fWidthBytes[SkYUVSizeInfo::kY];
915 size_t blockIncrementU = DCTSIZE * sizeInfo.fWidthBytes[SkYUVSizeInfo::kU];
916 size_t blockIncrementV = DCTSIZE * sizeInfo.fWidthBytes[SkYUVSizeInfo::kV];
msarettb714fb02016-01-22 14:46:42 -0800917
918 uint32_t numRowsPerBlock = numYRowsPerBlock;
919
920 // We intentionally round down here, as this first loop will only handle
921 // full block rows. As a special case at the end, we will handle any
922 // remaining rows that do not make up a full block.
923 const int numIters = dinfo->output_height / numRowsPerBlock;
924 for (int i = 0; i < numIters; i++) {
925 JDIMENSION linesRead = jpeg_read_raw_data(dinfo, yuv, numRowsPerBlock);
926 if (linesRead < numRowsPerBlock) {
927 // FIXME: Handle incomplete YUV decodes without signalling an error.
928 return kInvalidInput;
929 }
930
931 // Update rowptrs.
932 for (int i = 0; i < numYRowsPerBlock; i++) {
933 rowptrs[i] += blockIncrementY;
934 }
935 for (int i = 0; i < DCTSIZE; i++) {
936 rowptrs[i + 2 * DCTSIZE] += blockIncrementU;
937 rowptrs[i + 3 * DCTSIZE] += blockIncrementV;
938 }
939 }
940
941 uint32_t remainingRows = dinfo->output_height - dinfo->output_scanline;
942 SkASSERT(remainingRows == dinfo->output_height % numRowsPerBlock);
943 SkASSERT(dinfo->output_scanline == numIters * numRowsPerBlock);
944 if (remainingRows > 0) {
945 // libjpeg-turbo needs memory to be padded by the block sizes. We will fulfill
946 // this requirement using a dummy row buffer.
947 // FIXME: Should SkCodec have an extra memory buffer that can be shared among
948 // all of the implementations that use temporary/garbage memory?
msarett4984c3c2016-03-10 05:44:43 -0800949 SkAutoTMalloc<JSAMPLE> dummyRow(sizeInfo.fWidthBytes[SkYUVSizeInfo::kY]);
msarettb714fb02016-01-22 14:46:42 -0800950 for (int i = remainingRows; i < numYRowsPerBlock; i++) {
951 rowptrs[i] = dummyRow.get();
952 }
953 int remainingUVRows = dinfo->comp_info[1].downsampled_height - DCTSIZE * numIters;
954 for (int i = remainingUVRows; i < DCTSIZE; i++) {
955 rowptrs[i + 2 * DCTSIZE] = dummyRow.get();
956 rowptrs[i + 3 * DCTSIZE] = dummyRow.get();
957 }
958
959 JDIMENSION linesRead = jpeg_read_raw_data(dinfo, yuv, numRowsPerBlock);
960 if (linesRead < remainingRows) {
961 // FIXME: Handle incomplete YUV decodes without signalling an error.
962 return kInvalidInput;
963 }
964 }
965
966 return kSuccess;
967}
Hal Canary83e0f1b2018-04-05 16:58:41 -0400968
969// This function is declared in SkJpegInfo.h, used by SkPDF.
970bool SkGetJpegInfo(const void* data, size_t len,
971 SkISize* size,
972 SkEncodedInfo::Color* colorType,
973 SkEncodedOrigin* orientation) {
974 if (!SkJpegCodec::IsJpeg(data, len)) {
975 return false;
976 }
977
978 SkMemoryStream stream(data, len);
979 JpegDecoderMgr decoderMgr(&stream);
980 // libjpeg errors will be caught and reported here
981 skjpeg_error_mgr::AutoPushJmpBuf jmp(decoderMgr.errorMgr());
982 if (setjmp(jmp)) {
983 return false;
984 }
985 decoderMgr.init();
986 jpeg_decompress_struct* dinfo = decoderMgr.dinfo();
987 jpeg_save_markers(dinfo, kExifMarker, 0xFFFF);
988 jpeg_save_markers(dinfo, kICCMarker, 0xFFFF);
989 if (JPEG_HEADER_OK != jpeg_read_header(dinfo, true)) {
990 return false;
991 }
992 SkEncodedInfo::Color encodedColorType;
993 if (!decoderMgr.getEncodedColor(&encodedColorType)) {
994 return false; // Unable to interpret the color channels as colors.
995 }
996 if (colorType) {
997 *colorType = encodedColorType;
998 }
999 if (orientation) {
1000 *orientation = get_exif_orientation(dinfo);
1001 }
1002 if (size) {
1003 *size = {SkToS32(dinfo->image_width), SkToS32(dinfo->image_height)};
1004 }
1005 return true;
1006}