blob: a6c254914103f57062cc49c40b2dbdf71e38c0e1 [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"
9#include "SkJpegCodec.h"
10#include "SkJpegDecoderMgr.h"
msarette16b04a2015-04-15 07:32:19 -070011#include "SkCodecPriv.h"
Cary Clarka4083c92017-09-15 11:59:23 -040012#include "SkColorData.h"
raftias54761282016-12-01 13:44:07 -050013#include "SkColorSpace_Base.h"
msarette16b04a2015-04-15 07:32:19 -070014#include "SkStream.h"
15#include "SkTemplates.h"
16#include "SkTypes.h"
17
msarett1c8a5872015-07-07 08:50:01 -070018// stdio is needed for libjpeg-turbo
msarette16b04a2015-04-15 07:32:19 -070019#include <stdio.h>
msarettc1d03122016-03-25 08:58:55 -070020#include "SkJpegUtility.h"
msarette16b04a2015-04-15 07:32:19 -070021
mtkleindc90b532016-07-28 14:45:28 -070022// This warning triggers false postives way too often in here.
23#if defined(__GNUC__) && !defined(__clang__)
24 #pragma GCC diagnostic ignored "-Wclobbered"
25#endif
26
msarette16b04a2015-04-15 07:32:19 -070027extern "C" {
28 #include "jerror.h"
msarette16b04a2015-04-15 07:32:19 -070029 #include "jpeglib.h"
30}
31
scroggodb30be22015-12-08 18:54:13 -080032bool SkJpegCodec::IsJpeg(const void* buffer, size_t bytesRead) {
Leon Scroggins III862c1962017-10-02 16:28:49 -040033 constexpr uint8_t jpegSig[] = { 0xFF, 0xD8, 0xFF };
scroggodb30be22015-12-08 18:54:13 -080034 return bytesRead >= 3 && !memcmp(buffer, jpegSig, sizeof(jpegSig));
msarette16b04a2015-04-15 07:32:19 -070035}
36
msarett0e6274f2016-03-21 08:04:40 -070037static uint32_t get_endian_int(const uint8_t* data, bool littleEndian) {
38 if (littleEndian) {
39 return (data[3] << 24) | (data[2] << 16) | (data[1] << 8) | (data[0]);
40 }
41
42 return (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | (data[3]);
43}
44
45const uint32_t kExifHeaderSize = 14;
msarett0e6274f2016-03-21 08:04:40 -070046const uint32_t kExifMarker = JPEG_APP0 + 1;
msarett0e6274f2016-03-21 08:04:40 -070047
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -040048static bool is_orientation_marker(jpeg_marker_struct* marker, SkEncodedOrigin* orientation) {
msarett0e6274f2016-03-21 08:04:40 -070049 if (kExifMarker != marker->marker || marker->data_length < kExifHeaderSize) {
50 return false;
51 }
52
53 const uint8_t* data = marker->data;
Leon Scroggins III862c1962017-10-02 16:28:49 -040054 constexpr uint8_t kExifSig[] { 'E', 'x', 'i', 'f', '\0' };
msarett0e6274f2016-03-21 08:04:40 -070055 if (memcmp(data, kExifSig, sizeof(kExifSig))) {
56 return false;
57 }
58
59 bool littleEndian;
60 if (!is_valid_endian_marker(data + 6, &littleEndian)) {
61 return false;
62 }
63
64 // Get the offset from the start of the marker.
65 // Account for 'E', 'x', 'i', 'f', '\0', '<fill byte>'.
66 uint32_t offset = get_endian_int(data + 10, littleEndian);
67 offset += sizeof(kExifSig) + 1;
68
69 // Require that the marker is at least large enough to contain the number of entries.
70 if (marker->data_length < offset + 2) {
71 return false;
72 }
73 uint32_t numEntries = get_endian_short(data + offset, littleEndian);
74
75 // Tag (2 bytes), Datatype (2 bytes), Number of elements (4 bytes), Data (4 bytes)
76 const uint32_t kEntrySize = 12;
77 numEntries = SkTMin(numEntries, (marker->data_length - offset - 2) / kEntrySize);
78
79 // Advance the data to the start of the entries.
80 data += offset + 2;
81
82 const uint16_t kOriginTag = 0x112;
83 const uint16_t kOriginType = 3;
84 for (uint32_t i = 0; i < numEntries; i++, data += kEntrySize) {
85 uint16_t tag = get_endian_short(data, littleEndian);
86 uint16_t type = get_endian_short(data + 2, littleEndian);
87 uint32_t count = get_endian_int(data + 4, littleEndian);
88 if (kOriginTag == tag && kOriginType == type && 1 == count) {
89 uint16_t val = get_endian_short(data + 8, littleEndian);
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -040090 if (0 < val && val <= kLast_SkEncodedOrigin) {
91 *orientation = (SkEncodedOrigin) val;
msarett0e6274f2016-03-21 08:04:40 -070092 return true;
93 }
94 }
95 }
96
97 return false;
98}
99
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -0400100static SkEncodedOrigin get_exif_orientation(jpeg_decompress_struct* dinfo) {
101 SkEncodedOrigin orientation;
msarett0e6274f2016-03-21 08:04:40 -0700102 for (jpeg_marker_struct* marker = dinfo->marker_list; marker; marker = marker->next) {
103 if (is_orientation_marker(marker, &orientation)) {
104 return orientation;
105 }
106 }
107
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -0400108 return kDefault_SkEncodedOrigin;
msarett0e6274f2016-03-21 08:04:40 -0700109}
110
111static bool is_icc_marker(jpeg_marker_struct* marker) {
Matt Sarett5df93de2017-03-22 21:52:47 +0000112 if (kICCMarker != marker->marker || marker->data_length < kICCMarkerHeaderSize) {
msarett0e6274f2016-03-21 08:04:40 -0700113 return false;
114 }
115
msarett0e6274f2016-03-21 08:04:40 -0700116 return !memcmp(marker->data, kICCSig, sizeof(kICCSig));
117}
118
119/*
120 * ICC profiles may be stored using a sequence of multiple markers. We obtain the ICC profile
121 * in two steps:
122 * (1) Discover all ICC profile markers and verify that they are numbered properly.
123 * (2) Copy the data from each marker into a contiguous ICC profile.
124 */
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400125static sk_sp<SkColorSpace> read_color_space(jpeg_decompress_struct* dinfo) {
msarett0e6274f2016-03-21 08:04:40 -0700126 // Note that 256 will be enough storage space since each markerIndex is stored in 8-bits.
127 jpeg_marker_struct* markerSequence[256];
128 memset(markerSequence, 0, sizeof(markerSequence));
129 uint8_t numMarkers = 0;
130 size_t totalBytes = 0;
131
132 // Discover any ICC markers and verify that they are numbered properly.
133 for (jpeg_marker_struct* marker = dinfo->marker_list; marker; marker = marker->next) {
134 if (is_icc_marker(marker)) {
135 // Verify that numMarkers is valid and consistent.
136 if (0 == numMarkers) {
137 numMarkers = marker->data[13];
138 if (0 == numMarkers) {
139 SkCodecPrintf("ICC Profile Error: numMarkers must be greater than zero.\n");
140 return nullptr;
141 }
142 } else if (numMarkers != marker->data[13]) {
143 SkCodecPrintf("ICC Profile Error: numMarkers must be consistent.\n");
144 return nullptr;
145 }
146
147 // Verify that the markerIndex is valid and unique. Note that zero is not
148 // a valid index.
149 uint8_t markerIndex = marker->data[12];
150 if (markerIndex == 0 || markerIndex > numMarkers) {
151 SkCodecPrintf("ICC Profile Error: markerIndex is invalid.\n");
152 return nullptr;
153 }
154 if (markerSequence[markerIndex]) {
155 SkCodecPrintf("ICC Profile Error: Duplicate value of markerIndex.\n");
156 return nullptr;
157 }
158 markerSequence[markerIndex] = marker;
Matt Sarett5df93de2017-03-22 21:52:47 +0000159 SkASSERT(marker->data_length >= kICCMarkerHeaderSize);
160 totalBytes += marker->data_length - kICCMarkerHeaderSize;
msarett0e6274f2016-03-21 08:04:40 -0700161 }
162 }
163
164 if (0 == totalBytes) {
165 // No non-empty ICC profile markers were found.
166 return nullptr;
167 }
168
169 // Combine the ICC marker data into a contiguous profile.
msarett9876ac52016-06-01 14:47:18 -0700170 sk_sp<SkData> iccData = SkData::MakeUninitialized(totalBytes);
171 void* dst = iccData->writable_data();
msarett0e6274f2016-03-21 08:04:40 -0700172 for (uint32_t i = 1; i <= numMarkers; i++) {
173 jpeg_marker_struct* marker = markerSequence[i];
174 if (!marker) {
175 SkCodecPrintf("ICC Profile Error: Missing marker %d of %d.\n", i, numMarkers);
176 return nullptr;
177 }
178
Matt Sarett5df93de2017-03-22 21:52:47 +0000179 void* src = SkTAddOffset<void>(marker->data, kICCMarkerHeaderSize);
180 size_t bytes = marker->data_length - kICCMarkerHeaderSize;
msarett0e6274f2016-03-21 08:04:40 -0700181 memcpy(dst, src, bytes);
182 dst = SkTAddOffset<void>(dst, bytes);
183 }
184
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400185 return SkColorSpace::MakeICC(iccData->data(), iccData->size());
msarett0e6274f2016-03-21 08:04:40 -0700186}
187
Leon Scroggins III588fb042017-07-14 16:32:31 -0400188SkCodec::Result SkJpegCodec::ReadHeader(SkStream* stream, SkCodec** codecOut,
189 JpegDecoderMgr** decoderMgrOut, sk_sp<SkColorSpace> defaultColorSpace) {
msarette16b04a2015-04-15 07:32:19 -0700190
191 // Create a JpegDecoderMgr to own all of the decompress information
Ben Wagner145dbcd2016-11-03 14:40:50 -0400192 std::unique_ptr<JpegDecoderMgr> decoderMgr(new JpegDecoderMgr(stream));
msarette16b04a2015-04-15 07:32:19 -0700193
194 // libjpeg errors will be caught and reported here
mtklein2f428962016-07-28 13:59:59 -0700195 if (setjmp(decoderMgr->getJmpBuf())) {
Leon Scroggins III588fb042017-07-14 16:32:31 -0400196 return decoderMgr->returnFailure("ReadHeader", kInvalidInput);
msarette16b04a2015-04-15 07:32:19 -0700197 }
198
199 // Initialize the decompress info and the source manager
200 decoderMgr->init();
201
msarett0e6274f2016-03-21 08:04:40 -0700202 // Instruct jpeg library to save the markers that we care about. Since
203 // the orientation and color profile will not change, we can skip this
204 // step on rewinds.
205 if (codecOut) {
206 jpeg_save_markers(decoderMgr->dinfo(), kExifMarker, 0xFFFF);
207 jpeg_save_markers(decoderMgr->dinfo(), kICCMarker, 0xFFFF);
208 }
209
msarette16b04a2015-04-15 07:32:19 -0700210 // Read the jpeg header
Leon Scroggins III588fb042017-07-14 16:32:31 -0400211 switch (jpeg_read_header(decoderMgr->dinfo(), true)) {
212 case JPEG_HEADER_OK:
213 break;
214 case JPEG_SUSPENDED:
215 return decoderMgr->returnFailure("ReadHeader", kIncompleteInput);
216 default:
217 return decoderMgr->returnFailure("ReadHeader", kInvalidInput);
msarette16b04a2015-04-15 07:32:19 -0700218 }
219
msarett0e6274f2016-03-21 08:04:40 -0700220 if (codecOut) {
msarettc30c4182016-04-20 11:53:35 -0700221 // Get the encoded color type
msarettac6c7502016-04-25 09:30:24 -0700222 SkEncodedInfo::Color color;
223 if (!decoderMgr->getEncodedColor(&color)) {
Leon Scroggins III588fb042017-07-14 16:32:31 -0400224 return kInvalidInput;
msarettc30c4182016-04-20 11:53:35 -0700225 }
msarette16b04a2015-04-15 07:32:19 -0700226
227 // Create image info object and the codec
msarettc30c4182016-04-20 11:53:35 -0700228 SkEncodedInfo info = SkEncodedInfo::Make(color, SkEncodedInfo::kOpaque_Alpha, 8);
msarett0e6274f2016-03-21 08:04:40 -0700229
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -0400230 SkEncodedOrigin orientation = get_exif_orientation(decoderMgr->dinfo());
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400231 sk_sp<SkColorSpace> colorSpace = read_color_space(decoderMgr->dinfo());
232 if (colorSpace) {
raftias54761282016-12-01 13:44:07 -0500233 switch (decoderMgr->dinfo()->jpeg_color_space) {
234 case JCS_CMYK:
235 case JCS_YCCK:
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400236 if (colorSpace->type() != SkColorSpace::kCMYK_Type) {
237 colorSpace = nullptr;
238 }
raftias54761282016-12-01 13:44:07 -0500239 break;
raftias91db12d2016-12-02 11:56:59 -0500240 case JCS_GRAYSCALE:
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400241 if (colorSpace->type() != SkColorSpace::kGray_Type &&
242 colorSpace->type() != SkColorSpace::kRGB_Type)
243 {
244 colorSpace = nullptr;
245 }
raftias54761282016-12-01 13:44:07 -0500246 default:
Leon Scroggins IIIf78b55c2017-10-31 13:49:14 -0400247 if (colorSpace->type() != SkColorSpace::kRGB_Type) {
248 colorSpace = nullptr;
249 }
raftias54761282016-12-01 13:44:07 -0500250 break;
251 }
msarett9876ac52016-06-01 14:47:18 -0700252 }
msarettf34cd632016-05-25 10:13:53 -0700253 if (!colorSpace) {
Matt Sarettc5eabe72017-02-24 14:51:08 -0500254 colorSpace = defaultColorSpace;
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;
Mike Reedede7bac2017-07-23 15:30:02 -0400259 SkJpegCodec* codec = new SkJpegCodec(width, height, info, std::unique_ptr<SkStream>(stream),
260 decoderMgr.release(), std::move(colorSpace),
261 orientation);
raftiasd737bee2016-12-08 10:53:24 -0500262 *codecOut = codec;
msarette16b04a2015-04-15 07:32:19 -0700263 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700264 SkASSERT(nullptr != decoderMgrOut);
mtklein18300a32016-03-16 13:53:35 -0700265 *decoderMgrOut = decoderMgr.release();
msarette16b04a2015-04-15 07:32:19 -0700266 }
Leon Scroggins III588fb042017-07-14 16:32:31 -0400267 return kSuccess;
msarette16b04a2015-04-15 07:32:19 -0700268}
269
Mike Reedede7bac2017-07-23 15:30:02 -0400270std::unique_ptr<SkCodec> SkJpegCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
271 Result* result) {
272 return SkJpegCodec::MakeFromStream(std::move(stream), result, SkColorSpace::MakeSRGB());
Matt Sarettc5eabe72017-02-24 14:51:08 -0500273}
274
Mike Reedede7bac2017-07-23 15:30:02 -0400275std::unique_ptr<SkCodec> SkJpegCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
276 Result* result,
Leon Scroggins III588fb042017-07-14 16:32:31 -0400277 sk_sp<SkColorSpace> defaultColorSpace) {
halcanary96fcdcc2015-08-27 07:41:13 -0700278 SkCodec* codec = nullptr;
Mike Reedede7bac2017-07-23 15:30:02 -0400279 *result = ReadHeader(stream.get(), &codec, nullptr, std::move(defaultColorSpace));
Leon Scroggins III588fb042017-07-14 16:32:31 -0400280 if (kSuccess == *result) {
msarette16b04a2015-04-15 07:32:19 -0700281 // Codec has taken ownership of the stream, we do not need to delete it
282 SkASSERT(codec);
Mike Reedede7bac2017-07-23 15:30:02 -0400283 stream.release();
284 return std::unique_ptr<SkCodec>(codec);
msarette16b04a2015-04-15 07:32:19 -0700285 }
halcanary96fcdcc2015-08-27 07:41:13 -0700286 return nullptr;
msarette16b04a2015-04-15 07:32:19 -0700287}
288
Mike Reedede7bac2017-07-23 15:30:02 -0400289SkJpegCodec::SkJpegCodec(int width, int height, const SkEncodedInfo& info,
290 std::unique_ptr<SkStream> stream, JpegDecoderMgr* decoderMgr,
Leon Scroggins IIIb6ab10f2017-10-18 14:42:43 -0400291 sk_sp<SkColorSpace> colorSpace, SkEncodedOrigin origin)
Mike Reedede7bac2017-07-23 15:30:02 -0400292 : INHERITED(width, height, info, SkColorSpaceXform::kRGBA_8888_ColorFormat, std::move(stream),
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400293 std::move(colorSpace), origin)
msarette16b04a2015-04-15 07:32:19 -0700294 , fDecoderMgr(decoderMgr)
msarettfbccb592015-09-01 06:43:41 -0700295 , fReadyState(decoderMgr->dinfo()->global_state)
msarett50ce1f22016-07-29 06:23:33 -0700296 , fSwizzleSrcRow(nullptr)
297 , fColorXformSrcRow(nullptr)
msarett91c22b22016-02-22 12:27:46 -0800298 , fSwizzlerSubset(SkIRect::MakeEmpty())
msarette16b04a2015-04-15 07:32:19 -0700299{}
300
301/*
emmaleer8f4ba762015-08-14 07:44:46 -0700302 * Return the row bytes of a particular image type and width
303 */
msarett23e78d32016-02-06 15:58:50 -0800304static size_t get_row_bytes(const j_decompress_ptr dinfo) {
msarett70e418b2016-02-12 12:35:48 -0800305 const size_t colorBytes = (dinfo->out_color_space == JCS_RGB565) ? 2 :
306 dinfo->out_color_components;
emmaleer8f4ba762015-08-14 07:44:46 -0700307 return dinfo->output_width * colorBytes;
308
309}
scroggoe7fc14b2015-10-02 13:14:46 -0700310
311/*
312 * Calculate output dimensions based on the provided factors.
313 *
314 * Not to be used on the actual jpeg_decompress_struct used for decoding, since it will
315 * incorrectly modify num_components.
316 */
317void calc_output_dimensions(jpeg_decompress_struct* dinfo, unsigned int num, unsigned int denom) {
318 dinfo->num_components = 0;
319 dinfo->scale_num = num;
320 dinfo->scale_denom = denom;
321 jpeg_calc_output_dimensions(dinfo);
322}
323
emmaleer8f4ba762015-08-14 07:44:46 -0700324/*
msarette16b04a2015-04-15 07:32:19 -0700325 * Return a valid set of output dimensions for this decoder, given an input scale
326 */
327SkISize SkJpegCodec::onGetScaledDimensions(float desiredScale) const {
msarett1c8a5872015-07-07 08:50:01 -0700328 // 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
329 // support these as well
scroggoe7fc14b2015-10-02 13:14:46 -0700330 unsigned int num;
331 unsigned int denom = 8;
msarettfdb47572015-10-13 12:50:14 -0700332 if (desiredScale >= 0.9375) {
msarett1c8a5872015-07-07 08:50:01 -0700333 num = 8;
msarettfdb47572015-10-13 12:50:14 -0700334 } else if (desiredScale >= 0.8125) {
msarett1c8a5872015-07-07 08:50:01 -0700335 num = 7;
msarettfdb47572015-10-13 12:50:14 -0700336 } else if (desiredScale >= 0.6875f) {
msarett1c8a5872015-07-07 08:50:01 -0700337 num = 6;
msarettfdb47572015-10-13 12:50:14 -0700338 } else if (desiredScale >= 0.5625f) {
msarett1c8a5872015-07-07 08:50:01 -0700339 num = 5;
msarettfdb47572015-10-13 12:50:14 -0700340 } else if (desiredScale >= 0.4375f) {
msarett1c8a5872015-07-07 08:50:01 -0700341 num = 4;
msarettfdb47572015-10-13 12:50:14 -0700342 } else if (desiredScale >= 0.3125f) {
msarett1c8a5872015-07-07 08:50:01 -0700343 num = 3;
msarettfdb47572015-10-13 12:50:14 -0700344 } else if (desiredScale >= 0.1875f) {
msarett1c8a5872015-07-07 08:50:01 -0700345 num = 2;
msarette16b04a2015-04-15 07:32:19 -0700346 } else {
msarett1c8a5872015-07-07 08:50:01 -0700347 num = 1;
msarette16b04a2015-04-15 07:32:19 -0700348 }
349
350 // Set up a fake decompress struct in order to use libjpeg to calculate output dimensions
351 jpeg_decompress_struct dinfo;
mtkleinf7aaadb2015-04-16 06:09:27 -0700352 sk_bzero(&dinfo, sizeof(dinfo));
msarette16b04a2015-04-15 07:32:19 -0700353 dinfo.image_width = this->getInfo().width();
354 dinfo.image_height = this->getInfo().height();
msarettfbccb592015-09-01 06:43:41 -0700355 dinfo.global_state = fReadyState;
scroggoe7fc14b2015-10-02 13:14:46 -0700356 calc_output_dimensions(&dinfo, num, denom);
msarette16b04a2015-04-15 07:32:19 -0700357
358 // Return the calculated output dimensions for the given scale
359 return SkISize::Make(dinfo.output_width, dinfo.output_height);
360}
361
scroggob427db12015-08-12 07:24:13 -0700362bool SkJpegCodec::onRewind() {
halcanary96fcdcc2015-08-27 07:41:13 -0700363 JpegDecoderMgr* decoderMgr = nullptr;
Leon Scroggins III588fb042017-07-14 16:32:31 -0400364 if (kSuccess != ReadHeader(this->stream(), nullptr, &decoderMgr, nullptr)) {
msarett50ce1f22016-07-29 06:23:33 -0700365 return fDecoderMgr->returnFalse("onRewind");
msarett97fdea62015-04-29 08:17:15 -0700366 }
halcanary96fcdcc2015-08-27 07:41:13 -0700367 SkASSERT(nullptr != decoderMgr);
scroggob427db12015-08-12 07:24:13 -0700368 fDecoderMgr.reset(decoderMgr);
msarett2812f032016-07-18 15:56:08 -0700369
370 fSwizzler.reset(nullptr);
msarett50ce1f22016-07-29 06:23:33 -0700371 fSwizzleSrcRow = nullptr;
372 fColorXformSrcRow = nullptr;
msarett2812f032016-07-18 15:56:08 -0700373 fStorage.reset();
374
scroggob427db12015-08-12 07:24:13 -0700375 return true;
msarett97fdea62015-04-29 08:17:15 -0700376}
377
378/*
msarett1c8a5872015-07-07 08:50:01 -0700379 * Checks if the conversion between the input image and the requested output
380 * image has been implemented
381 * Sets the output color space
382 */
msarett2ecc35f2016-09-08 11:55:16 -0700383bool SkJpegCodec::setOutputColorSpace(const SkImageInfo& dstInfo) {
msarett50ce1f22016-07-29 06:23:33 -0700384 if (kUnknown_SkAlphaType == dstInfo.alphaType()) {
msarett1c8a5872015-07-07 08:50:01 -0700385 return false;
386 }
387
msarett50ce1f22016-07-29 06:23:33 -0700388 if (kOpaque_SkAlphaType != dstInfo.alphaType()) {
scroggoc5560be2016-02-03 09:42:42 -0800389 SkCodecPrintf("Warning: an opaque image should be decoded as opaque "
390 "- it is being decoded as non-opaque, which will draw slower\n");
391 }
392
msarett50ce1f22016-07-29 06:23:33 -0700393 J_COLOR_SPACE encodedColorType = fDecoderMgr->dinfo()->jpeg_color_space;
msarett1c8a5872015-07-07 08:50:01 -0700394
395 // Check for valid color types and set the output color space
msarett50ce1f22016-07-29 06:23:33 -0700396 switch (dstInfo.colorType()) {
msarett34e0ec42016-04-22 16:27:24 -0700397 case kRGBA_8888_SkColorType:
nagarajan.n08cda142017-09-07 20:03:29 +0530398 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
399 break;
msarett34e0ec42016-04-22 16:27:24 -0700400 case kBGRA_8888_SkColorType:
nagarajan.n08cda142017-09-07 20:03:29 +0530401 if (this->colorXform()) {
Matt Sarett562e6812016-11-08 16:13:43 -0500402 // Always using RGBA as the input format for color xforms makes the
403 // implementation a little simpler.
msarett50ce1f22016-07-29 06:23:33 -0700404 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
msarett34e0ec42016-04-22 16:27:24 -0700405 } else {
msarettf25bff92016-07-21 12:00:24 -0700406 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_BGRA;
msarett1c8a5872015-07-07 08:50:01 -0700407 }
nagarajan.n08cda142017-09-07 20:03:29 +0530408 break;
msarett1c8a5872015-07-07 08:50:01 -0700409 case kRGB_565_SkColorType:
nagarajan.n08cda142017-09-07 20:03:29 +0530410 if (this->colorXform()) {
Matt Sarett3725f0a2017-03-28 14:34:20 -0400411 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
msarett1c8a5872015-07-07 08:50:01 -0700412 } else {
msarett8ff6ca62015-09-18 12:06:04 -0700413 fDecoderMgr->dinfo()->dither_mode = JDITHER_NONE;
msarett1c8a5872015-07-07 08:50:01 -0700414 fDecoderMgr->dinfo()->out_color_space = JCS_RGB565;
415 }
nagarajan.n08cda142017-09-07 20:03:29 +0530416 break;
msarett1c8a5872015-07-07 08:50:01 -0700417 case kGray_8_SkColorType:
Matt Sarett313c4632016-10-20 12:35:23 -0400418 if (this->colorXform() || JCS_GRAYSCALE != encodedColorType) {
msarett39979d82016-07-28 17:11:18 -0700419 return false;
msarett50ce1f22016-07-29 06:23:33 -0700420 }
421
422 fDecoderMgr->dinfo()->out_color_space = JCS_GRAYSCALE;
nagarajan.n08cda142017-09-07 20:03:29 +0530423 break;
msarett50ce1f22016-07-29 06:23:33 -0700424 case kRGBA_F16_SkColorType:
Matt Sarett313c4632016-10-20 12:35:23 -0400425 SkASSERT(this->colorXform());
426
msarett2ecc35f2016-09-08 11:55:16 -0700427 if (!dstInfo.colorSpace()->gammaIsLinear()) {
428 return false;
429 }
msarett50ce1f22016-07-29 06:23:33 -0700430
nagarajan.n08cda142017-09-07 20:03:29 +0530431 fDecoderMgr->dinfo()->out_color_space = JCS_EXT_RGBA;
432 break;
msarett1c8a5872015-07-07 08:50:01 -0700433 default:
434 return false;
435 }
nagarajan.n08cda142017-09-07 20:03:29 +0530436
437 // Check if we will decode to CMYK. libjpeg-turbo does not convert CMYK to RGBA, so
438 // we must do it ourselves.
439 if (JCS_CMYK == encodedColorType || JCS_YCCK == encodedColorType) {
440 fDecoderMgr->dinfo()->out_color_space = JCS_CMYK;
441 }
442
443 return true;
msarett1c8a5872015-07-07 08:50:01 -0700444}
445
446/*
mtkleine721a8e2016-02-06 19:12:23 -0800447 * Checks if we can natively scale to the requested dimensions and natively scales the
emmaleer8f4ba762015-08-14 07:44:46 -0700448 * dimensions if possible
msarett97fdea62015-04-29 08:17:15 -0700449 */
scroggoe7fc14b2015-10-02 13:14:46 -0700450bool SkJpegCodec::onDimensionsSupported(const SkISize& size) {
mtklein2f428962016-07-28 13:59:59 -0700451 if (setjmp(fDecoderMgr->getJmpBuf())) {
msarett50ce1f22016-07-29 06:23:33 -0700452 return fDecoderMgr->returnFalse("onDimensionsSupported");
scroggoe7fc14b2015-10-02 13:14:46 -0700453 }
454
455 const unsigned int dstWidth = size.width();
456 const unsigned int dstHeight = size.height();
457
458 // Set up a fake decompress struct in order to use libjpeg to calculate output dimensions
459 // FIXME: Why is this necessary?
460 jpeg_decompress_struct dinfo;
461 sk_bzero(&dinfo, sizeof(dinfo));
462 dinfo.image_width = this->getInfo().width();
463 dinfo.image_height = this->getInfo().height();
464 dinfo.global_state = fReadyState;
465
msarett1c8a5872015-07-07 08:50:01 -0700466 // 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 -0700467 unsigned int num = 8;
468 const unsigned int denom = 8;
469 calc_output_dimensions(&dinfo, num, denom);
470 while (dinfo.output_width != dstWidth || dinfo.output_height != dstHeight) {
msarett97fdea62015-04-29 08:17:15 -0700471
472 // Return a failure if we have tried all of the possible scales
scroggoe7fc14b2015-10-02 13:14:46 -0700473 if (1 == num || dstWidth > dinfo.output_width || dstHeight > dinfo.output_height) {
emmaleer8f4ba762015-08-14 07:44:46 -0700474 return false;
msarett97fdea62015-04-29 08:17:15 -0700475 }
476
477 // Try the next scale
scroggoe7fc14b2015-10-02 13:14:46 -0700478 num -= 1;
479 calc_output_dimensions(&dinfo, num, denom);
msarett97fdea62015-04-29 08:17:15 -0700480 }
scroggoe7fc14b2015-10-02 13:14:46 -0700481
482 fDecoderMgr->dinfo()->scale_num = num;
483 fDecoderMgr->dinfo()->scale_denom = denom;
msarett97fdea62015-04-29 08:17:15 -0700484 return true;
485}
486
Matt Sarettc8c901f2017-01-24 16:16:33 -0500487int SkJpegCodec::readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count,
488 const Options& opts) {
msarett50ce1f22016-07-29 06:23:33 -0700489 // Set the jump location for libjpeg-turbo errors
490 if (setjmp(fDecoderMgr->getJmpBuf())) {
491 return 0;
492 }
493
494 // When fSwizzleSrcRow is non-null, it means that we need to swizzle. In this case,
495 // we will always decode into fSwizzlerSrcRow before swizzling into the next buffer.
496 // We can never swizzle "in place" because the swizzler may perform sampling and/or
497 // subsetting.
498 // When fColorXformSrcRow is non-null, it means that we need to color xform and that
499 // we cannot color xform "in place" (many times we can, but not when the dst is F16).
Matt Sarett313c4632016-10-20 12:35:23 -0400500 // In this case, we will color xform from fColorXformSrcRow into the dst.
msarett50ce1f22016-07-29 06:23:33 -0700501 JSAMPLE* decodeDst = (JSAMPLE*) dst;
502 uint32_t* swizzleDst = (uint32_t*) dst;
503 size_t decodeDstRowBytes = rowBytes;
504 size_t swizzleDstRowBytes = rowBytes;
Matt Sarettc8c901f2017-01-24 16:16:33 -0500505 int dstWidth = opts.fSubset ? opts.fSubset->width() : dstInfo.width();
msarett50ce1f22016-07-29 06:23:33 -0700506 if (fSwizzleSrcRow && fColorXformSrcRow) {
507 decodeDst = (JSAMPLE*) fSwizzleSrcRow;
508 swizzleDst = fColorXformSrcRow;
509 decodeDstRowBytes = 0;
510 swizzleDstRowBytes = 0;
msarett35bb74b2016-08-22 07:41:28 -0700511 dstWidth = fSwizzler->swizzleWidth();
msarett50ce1f22016-07-29 06:23:33 -0700512 } else if (fColorXformSrcRow) {
513 decodeDst = (JSAMPLE*) fColorXformSrcRow;
514 swizzleDst = fColorXformSrcRow;
515 decodeDstRowBytes = 0;
516 swizzleDstRowBytes = 0;
517 } else if (fSwizzleSrcRow) {
518 decodeDst = (JSAMPLE*) fSwizzleSrcRow;
519 decodeDstRowBytes = 0;
msarett35bb74b2016-08-22 07:41:28 -0700520 dstWidth = fSwizzler->swizzleWidth();
msarett50ce1f22016-07-29 06:23:33 -0700521 }
522
523 for (int y = 0; y < count; y++) {
524 uint32_t lines = jpeg_read_scanlines(fDecoderMgr->dinfo(), &decodeDst, 1);
msarett50ce1f22016-07-29 06:23:33 -0700525 if (0 == lines) {
526 return y;
527 }
528
529 if (fSwizzler) {
530 fSwizzler->swizzle(swizzleDst, decodeDst);
531 }
532
Matt Sarett313c4632016-10-20 12:35:23 -0400533 if (this->colorXform()) {
Leon Scroggins IIIc6e6a5f2017-06-05 15:53:38 -0400534 this->applyColorXform(dst, swizzleDst, dstWidth, kOpaque_SkAlphaType);
msarett50ce1f22016-07-29 06:23:33 -0700535 dst = SkTAddOffset<void>(dst, rowBytes);
536 }
537
538 decodeDst = SkTAddOffset<JSAMPLE>(decodeDst, decodeDstRowBytes);
539 swizzleDst = SkTAddOffset<uint32_t>(swizzleDst, swizzleDstRowBytes);
540 }
541
542 return count;
543}
544
msarett97fdea62015-04-29 08:17:15 -0700545/*
Matt Sarett7f15b682017-02-24 17:22:09 -0500546 * This is a bit tricky. We only need the swizzler to do format conversion if the jpeg is
547 * encoded as CMYK.
548 * And even then we still may not need it. If the jpeg has a CMYK color space and a color
549 * xform, the color xform will handle the CMYK->RGB conversion.
550 */
551static inline bool needs_swizzler_to_convert_from_cmyk(J_COLOR_SPACE jpegColorType,
552 const SkImageInfo& srcInfo, bool hasColorSpaceXform) {
553 if (JCS_CMYK != jpegColorType) {
554 return false;
555 }
556
557 bool hasCMYKColorSpace = as_CSB(srcInfo.colorSpace())->onIsCMYK();
558 return !hasCMYKColorSpace || !hasColorSpaceXform;
559}
560
561/*
msarette16b04a2015-04-15 07:32:19 -0700562 * Performs the jpeg decode
563 */
564SkCodec::Result SkJpegCodec::onGetPixels(const SkImageInfo& dstInfo,
565 void* dst, size_t dstRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000566 const Options& options,
msarette6dd0042015-10-09 11:07:34 -0700567 int* rowsDecoded) {
scroggob636b452015-07-22 07:16:20 -0700568 if (options.fSubset) {
569 // Subsets are not supported.
570 return kUnimplemented;
571 }
572
msarette16b04a2015-04-15 07:32:19 -0700573 // Get a pointer to the decompress info since we will use it quite frequently
574 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
575
576 // Set the jump location for libjpeg errors
mtklein2f428962016-07-28 13:59:59 -0700577 if (setjmp(fDecoderMgr->getJmpBuf())) {
msarette16b04a2015-04-15 07:32:19 -0700578 return fDecoderMgr->returnFailure("setjmp", kInvalidInput);
579 }
580
msarett2ecc35f2016-09-08 11:55:16 -0700581 // Check if we can decode to the requested destination and set the output color space
582 if (!this->setOutputColorSpace(dstInfo)) {
583 return fDecoderMgr->returnFailure("setOutputColorSpace", kInvalidConversion);
msarett85c922a2016-09-08 10:54:34 -0700584 }
585
msarettfbccb592015-09-01 06:43:41 -0700586 if (!jpeg_start_decompress(dinfo)) {
msarette16b04a2015-04-15 07:32:19 -0700587 return fDecoderMgr->returnFailure("startDecompress", kInvalidInput);
588 }
589
msarett1c8a5872015-07-07 08:50:01 -0700590 // The recommended output buffer height should always be 1 in high quality modes.
591 // If it's not, we want to know because it means our strategy is not optimal.
592 SkASSERT(1 == dinfo->rec_outbuf_height);
msarette16b04a2015-04-15 07:32:19 -0700593
Matt Sarett7f15b682017-02-24 17:22:09 -0500594 if (needs_swizzler_to_convert_from_cmyk(dinfo->out_color_space, this->getInfo(),
595 this->colorXform())) {
596 this->initializeSwizzler(dstInfo, options, true);
scroggoef27d892015-10-23 09:29:22 -0700597 }
598
msarett50ce1f22016-07-29 06:23:33 -0700599 this->allocateStorage(dstInfo);
scroggoef27d892015-10-23 09:29:22 -0700600
Matt Sarettc8c901f2017-01-24 16:16:33 -0500601 int rows = this->readRows(dstInfo, dst, dstRowBytes, dstInfo.height(), options);
msarett50ce1f22016-07-29 06:23:33 -0700602 if (rows < dstInfo.height()) {
603 *rowsDecoded = rows;
604 return fDecoderMgr->returnFailure("Incomplete image data", kIncompleteInput);
msarette16b04a2015-04-15 07:32:19 -0700605 }
msarette16b04a2015-04-15 07:32:19 -0700606
607 return kSuccess;
608}
msarett97fdea62015-04-29 08:17:15 -0700609
msarett50ce1f22016-07-29 06:23:33 -0700610void SkJpegCodec::allocateStorage(const SkImageInfo& dstInfo) {
msarett35bb74b2016-08-22 07:41:28 -0700611 int dstWidth = dstInfo.width();
612
msarett50ce1f22016-07-29 06:23:33 -0700613 size_t swizzleBytes = 0;
614 if (fSwizzler) {
615 swizzleBytes = get_row_bytes(fDecoderMgr->dinfo());
msarett35bb74b2016-08-22 07:41:28 -0700616 dstWidth = fSwizzler->swizzleWidth();
Matt Sarett313c4632016-10-20 12:35:23 -0400617 SkASSERT(!this->colorXform() || SkIsAlign4(swizzleBytes));
msarett50ce1f22016-07-29 06:23:33 -0700618 }
619
620 size_t xformBytes = 0;
Matt Sarett3725f0a2017-03-28 14:34:20 -0400621 if (this->colorXform() && (kRGBA_F16_SkColorType == dstInfo.colorType() ||
622 kRGB_565_SkColorType == dstInfo.colorType())) {
msarett35bb74b2016-08-22 07:41:28 -0700623 xformBytes = dstWidth * sizeof(uint32_t);
msarett50ce1f22016-07-29 06:23:33 -0700624 }
625
626 size_t totalBytes = swizzleBytes + xformBytes;
627 if (totalBytes > 0) {
628 fStorage.reset(totalBytes);
629 fSwizzleSrcRow = (swizzleBytes > 0) ? fStorage.get() : nullptr;
630 fColorXformSrcRow = (xformBytes > 0) ?
631 SkTAddOffset<uint32_t>(fStorage.get(), swizzleBytes) : nullptr;
632 }
633}
634
Matt Sarett7f15b682017-02-24 17:22:09 -0500635void SkJpegCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& options,
636 bool needsCMYKToRGB) {
msaretta45a6682016-04-22 13:18:37 -0700637 SkEncodedInfo swizzlerInfo = this->getEncodedInfo();
Matt Sarett7f15b682017-02-24 17:22:09 -0500638 if (needsCMYKToRGB) {
mtkleinda19f6f2016-08-23 11:49:29 -0700639 swizzlerInfo = SkEncodedInfo::Make(SkEncodedInfo::kInvertedCMYK_Color,
640 swizzlerInfo.alpha(),
641 swizzlerInfo.bitsPerComponent());
msarett70e418b2016-02-12 12:35:48 -0800642 }
643
msarett91c22b22016-02-22 12:27:46 -0800644 Options swizzlerOptions = options;
645 if (options.fSubset) {
646 // Use fSwizzlerSubset if this is a subset decode. This is necessary in the case
647 // where libjpeg-turbo provides a subset and then we need to subset it further.
648 // Also, verify that fSwizzlerSubset is initialized and valid.
649 SkASSERT(!fSwizzlerSubset.isEmpty() && fSwizzlerSubset.x() <= options.fSubset->x() &&
650 fSwizzlerSubset.width() == options.fSubset->width());
651 swizzlerOptions.fSubset = &fSwizzlerSubset;
652 }
Matt Sarett09a1c082017-02-01 15:34:22 -0800653
654 SkImageInfo swizzlerDstInfo = dstInfo;
Matt Sarett7f15b682017-02-24 17:22:09 -0500655 if (this->colorXform()) {
656 // The color xform will be expecting RGBA 8888 input.
Matt Sarett09a1c082017-02-01 15:34:22 -0800657 swizzlerDstInfo = swizzlerDstInfo.makeColorType(kRGBA_8888_SkColorType);
658 }
659
660 fSwizzler.reset(SkSwizzler::CreateSwizzler(swizzlerInfo, nullptr, swizzlerDstInfo,
Matt Sarett7f15b682017-02-24 17:22:09 -0500661 swizzlerOptions, nullptr, !needsCMYKToRGB));
msarettb30d6982016-02-15 10:18:45 -0800662 SkASSERT(fSwizzler);
msarett50ce1f22016-07-29 06:23:33 -0700663}
664
msarettfdb47572015-10-13 12:50:14 -0700665SkSampler* SkJpegCodec::getSampler(bool createIfNecessary) {
666 if (!createIfNecessary || fSwizzler) {
msarett50ce1f22016-07-29 06:23:33 -0700667 SkASSERT(!fSwizzler || (fSwizzleSrcRow && fStorage.get() == fSwizzleSrcRow));
Ben Wagner145dbcd2016-11-03 14:40:50 -0400668 return fSwizzler.get();
msarettfdb47572015-10-13 12:50:14 -0700669 }
670
Matt Sarett7f15b682017-02-24 17:22:09 -0500671 bool needsCMYKToRGB = needs_swizzler_to_convert_from_cmyk(
672 fDecoderMgr->dinfo()->out_color_space, this->getInfo(), this->colorXform());
673 this->initializeSwizzler(this->dstInfo(), this->options(), needsCMYKToRGB);
msarett50ce1f22016-07-29 06:23:33 -0700674 this->allocateStorage(this->dstInfo());
Ben Wagner145dbcd2016-11-03 14:40:50 -0400675 return fSwizzler.get();
scroggo46c57472015-09-30 08:57:13 -0700676}
scroggo1c005e42015-08-04 09:24:45 -0700677
scroggo46c57472015-09-30 08:57:13 -0700678SkCodec::Result SkJpegCodec::onStartScanlineDecode(const SkImageInfo& dstInfo,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000679 const Options& options) {
scroggo46c57472015-09-30 08:57:13 -0700680 // Set the jump location for libjpeg errors
mtklein2f428962016-07-28 13:59:59 -0700681 if (setjmp(fDecoderMgr->getJmpBuf())) {
scroggo46c57472015-09-30 08:57:13 -0700682 SkCodecPrintf("setjmp: Error from libjpeg\n");
683 return kInvalidInput;
684 }
685
msarett2ecc35f2016-09-08 11:55:16 -0700686 // Check if we can decode to the requested destination and set the output color space
687 if (!this->setOutputColorSpace(dstInfo)) {
688 return fDecoderMgr->returnFailure("setOutputColorSpace", kInvalidConversion);
msarett50ce1f22016-07-29 06:23:33 -0700689 }
690
scroggo46c57472015-09-30 08:57:13 -0700691 if (!jpeg_start_decompress(fDecoderMgr->dinfo())) {
692 SkCodecPrintf("start decompress failed\n");
693 return kInvalidInput;
694 }
695
Matt Sarett7f15b682017-02-24 17:22:09 -0500696 bool needsCMYKToRGB = needs_swizzler_to_convert_from_cmyk(
697 fDecoderMgr->dinfo()->out_color_space, this->getInfo(), this->colorXform());
msarett91c22b22016-02-22 12:27:46 -0800698 if (options.fSubset) {
699 uint32_t startX = options.fSubset->x();
700 uint32_t width = options.fSubset->width();
701
702 // libjpeg-turbo may need to align startX to a multiple of the IDCT
703 // block size. If this is the case, it will decrease the value of
704 // startX to the appropriate alignment and also increase the value
705 // of width so that the right edge of the requested subset remains
706 // the same.
707 jpeg_crop_scanline(fDecoderMgr->dinfo(), &startX, &width);
708
709 SkASSERT(startX <= (uint32_t) options.fSubset->x());
710 SkASSERT(width >= (uint32_t) options.fSubset->width());
711 SkASSERT(startX + width >= (uint32_t) options.fSubset->right());
712
713 // Instruct the swizzler (if it is necessary) to further subset the
714 // output provided by libjpeg-turbo.
715 //
716 // We set this here (rather than in the if statement below), so that
717 // if (1) we don't need a swizzler for the subset, and (2) we need a
718 // swizzler for CMYK, the swizzler will still use the proper subset
719 // dimensions.
720 //
721 // Note that the swizzler will ignore the y and height parameters of
722 // the subset. Since the scanline decoder (and the swizzler) handle
723 // one row at a time, only the subsetting in the x-dimension matters.
724 fSwizzlerSubset.setXYWH(options.fSubset->x() - startX, 0,
725 options.fSubset->width(), options.fSubset->height());
726
727 // We will need a swizzler if libjpeg-turbo cannot provide the exact
728 // subset that we request.
729 if (startX != (uint32_t) options.fSubset->x() ||
730 width != (uint32_t) options.fSubset->width()) {
Matt Sarett7f15b682017-02-24 17:22:09 -0500731 this->initializeSwizzler(dstInfo, options, needsCMYKToRGB);
msarett91c22b22016-02-22 12:27:46 -0800732 }
733 }
734
735 // Make sure we have a swizzler if we are converting from CMYK.
Matt Sarett7f15b682017-02-24 17:22:09 -0500736 if (!fSwizzler && needsCMYKToRGB) {
737 this->initializeSwizzler(dstInfo, options, true);
msarett91c22b22016-02-22 12:27:46 -0800738 }
msarettfdb47572015-10-13 12:50:14 -0700739
msarett50ce1f22016-07-29 06:23:33 -0700740 this->allocateStorage(dstInfo);
741
scroggo46c57472015-09-30 08:57:13 -0700742 return kSuccess;
743}
744
mtkleine721a8e2016-02-06 19:12:23 -0800745int SkJpegCodec::onGetScanlines(void* dst, int count, size_t dstRowBytes) {
Matt Sarettc8c901f2017-01-24 16:16:33 -0500746 int rows = this->readRows(this->dstInfo(), dst, dstRowBytes, count, this->options());
msarett50ce1f22016-07-29 06:23:33 -0700747 if (rows < count) {
748 // This allows us to skip calling jpeg_finish_decompress().
749 fDecoderMgr->dinfo()->output_scanline = this->dstInfo().height();
scroggo46c57472015-09-30 08:57:13 -0700750 }
751
msarett50ce1f22016-07-29 06:23:33 -0700752 return rows;
scroggo46c57472015-09-30 08:57:13 -0700753}
msarett97fdea62015-04-29 08:17:15 -0700754
msarette6dd0042015-10-09 11:07:34 -0700755bool SkJpegCodec::onSkipScanlines(int count) {
scroggo46c57472015-09-30 08:57:13 -0700756 // Set the jump location for libjpeg errors
mtklein2f428962016-07-28 13:59:59 -0700757 if (setjmp(fDecoderMgr->getJmpBuf())) {
msarett50ce1f22016-07-29 06:23:33 -0700758 return fDecoderMgr->returnFalse("onSkipScanlines");
msarett97fdea62015-04-29 08:17:15 -0700759 }
760
msarettf724b992015-10-15 06:41:06 -0700761 return (uint32_t) count == jpeg_skip_scanlines(fDecoderMgr->dinfo(), count);
msarett97fdea62015-04-29 08:17:15 -0700762}
msarettb714fb02016-01-22 14:46:42 -0800763
764static bool is_yuv_supported(jpeg_decompress_struct* dinfo) {
765 // Scaling is not supported in raw data mode.
766 SkASSERT(dinfo->scale_num == dinfo->scale_denom);
767
768 // I can't imagine that this would ever change, but we do depend on it.
769 static_assert(8 == DCTSIZE, "DCTSIZE (defined in jpeg library) should always be 8.");
770
771 if (JCS_YCbCr != dinfo->jpeg_color_space) {
772 return false;
773 }
774
775 SkASSERT(3 == dinfo->num_components);
776 SkASSERT(dinfo->comp_info);
777
778 // It is possible to perform a YUV decode for any combination of
779 // horizontal and vertical sampling that is supported by
780 // libjpeg/libjpeg-turbo. However, we will start by supporting only the
781 // common cases (where U and V have samp_factors of one).
782 //
783 // The definition of samp_factor is kind of the opposite of what SkCodec
784 // thinks of as a sampling factor. samp_factor is essentially a
785 // multiplier, and the larger the samp_factor is, the more samples that
786 // there will be. Ex:
787 // U_plane_width = image_width * (U_h_samp_factor / max_h_samp_factor)
788 //
789 // Supporting cases where the samp_factors for U or V were larger than
790 // that of Y would be an extremely difficult change, given that clients
791 // allocate memory as if the size of the Y plane is always the size of the
792 // image. However, this case is very, very rare.
msarett7c87cf42016-03-04 06:23:20 -0800793 if ((1 != dinfo->comp_info[1].h_samp_factor) ||
794 (1 != dinfo->comp_info[1].v_samp_factor) ||
795 (1 != dinfo->comp_info[2].h_samp_factor) ||
796 (1 != dinfo->comp_info[2].v_samp_factor))
797 {
msarettb714fb02016-01-22 14:46:42 -0800798 return false;
799 }
800
801 // Support all common cases of Y samp_factors.
802 // TODO (msarett): As mentioned above, it would be possible to support
803 // more combinations of samp_factors. The issues are:
804 // (1) Are there actually any images that are not covered
805 // by these cases?
806 // (2) How much complexity would be added to the
807 // implementation in order to support these rare
808 // cases?
809 int hSampY = dinfo->comp_info[0].h_samp_factor;
810 int vSampY = dinfo->comp_info[0].v_samp_factor;
811 return (1 == hSampY && 1 == vSampY) ||
812 (2 == hSampY && 1 == vSampY) ||
813 (2 == hSampY && 2 == vSampY) ||
814 (1 == hSampY && 2 == vSampY) ||
815 (4 == hSampY && 1 == vSampY) ||
816 (4 == hSampY && 2 == vSampY);
817}
818
msarett4984c3c2016-03-10 05:44:43 -0800819bool SkJpegCodec::onQueryYUV8(SkYUVSizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const {
msarettb714fb02016-01-22 14:46:42 -0800820 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
821 if (!is_yuv_supported(dinfo)) {
822 return false;
823 }
824
nagarajan.nb1854fa2017-07-19 19:53:21 +0530825 jpeg_component_info * comp_info = dinfo->comp_info;
826 for (auto i : { SkYUVSizeInfo::kY, SkYUVSizeInfo::kU, SkYUVSizeInfo::kV }) {
827 sizeInfo->fSizes[i].set(comp_info[i].downsampled_width, comp_info[i].downsampled_height);
828 sizeInfo->fWidthBytes[i] = comp_info[i].width_in_blocks * DCTSIZE;
829 }
msarettb714fb02016-01-22 14:46:42 -0800830
831 if (colorSpace) {
832 *colorSpace = kJPEG_SkYUVColorSpace;
833 }
834
835 return true;
836}
837
msarett4984c3c2016-03-10 05:44:43 -0800838SkCodec::Result SkJpegCodec::onGetYUV8Planes(const SkYUVSizeInfo& sizeInfo, void* planes[3]) {
839 SkYUVSizeInfo defaultInfo;
msarettb714fb02016-01-22 14:46:42 -0800840
841 // This will check is_yuv_supported(), so we don't need to here.
842 bool supportsYUV = this->onQueryYUV8(&defaultInfo, nullptr);
msarett4984c3c2016-03-10 05:44:43 -0800843 if (!supportsYUV ||
844 sizeInfo.fSizes[SkYUVSizeInfo::kY] != defaultInfo.fSizes[SkYUVSizeInfo::kY] ||
845 sizeInfo.fSizes[SkYUVSizeInfo::kU] != defaultInfo.fSizes[SkYUVSizeInfo::kU] ||
846 sizeInfo.fSizes[SkYUVSizeInfo::kV] != defaultInfo.fSizes[SkYUVSizeInfo::kV] ||
847 sizeInfo.fWidthBytes[SkYUVSizeInfo::kY] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kY] ||
848 sizeInfo.fWidthBytes[SkYUVSizeInfo::kU] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kU] ||
849 sizeInfo.fWidthBytes[SkYUVSizeInfo::kV] < defaultInfo.fWidthBytes[SkYUVSizeInfo::kV]) {
msarettb714fb02016-01-22 14:46:42 -0800850 return fDecoderMgr->returnFailure("onGetYUV8Planes", kInvalidInput);
851 }
852
853 // Set the jump location for libjpeg errors
mtklein2f428962016-07-28 13:59:59 -0700854 if (setjmp(fDecoderMgr->getJmpBuf())) {
msarettb714fb02016-01-22 14:46:42 -0800855 return fDecoderMgr->returnFailure("setjmp", kInvalidInput);
856 }
857
858 // Get a pointer to the decompress info since we will use it quite frequently
859 jpeg_decompress_struct* dinfo = fDecoderMgr->dinfo();
860
861 dinfo->raw_data_out = TRUE;
862 if (!jpeg_start_decompress(dinfo)) {
863 return fDecoderMgr->returnFailure("startDecompress", kInvalidInput);
864 }
865
866 // A previous implementation claims that the return value of is_yuv_supported()
867 // may change after calling jpeg_start_decompress(). It looks to me like this
868 // was caused by a bug in the old code, but we'll be safe and check here.
869 SkASSERT(is_yuv_supported(dinfo));
870
871 // Currently, we require that the Y plane dimensions match the image dimensions
872 // and that the U and V planes are the same dimensions.
msarett4984c3c2016-03-10 05:44:43 -0800873 SkASSERT(sizeInfo.fSizes[SkYUVSizeInfo::kU] == sizeInfo.fSizes[SkYUVSizeInfo::kV]);
874 SkASSERT((uint32_t) sizeInfo.fSizes[SkYUVSizeInfo::kY].width() == dinfo->output_width &&
875 (uint32_t) sizeInfo.fSizes[SkYUVSizeInfo::kY].height() == dinfo->output_height);
msarettb714fb02016-01-22 14:46:42 -0800876
877 // Build a JSAMPIMAGE to handle output from libjpeg-turbo. A JSAMPIMAGE has
878 // a 2-D array of pixels for each of the components (Y, U, V) in the image.
879 // Cheat Sheet:
880 // JSAMPIMAGE == JSAMPLEARRAY* == JSAMPROW** == JSAMPLE***
881 JSAMPARRAY yuv[3];
882
883 // Set aside enough space for pointers to rows of Y, U, and V.
884 JSAMPROW rowptrs[2 * DCTSIZE + DCTSIZE + DCTSIZE];
885 yuv[0] = &rowptrs[0]; // Y rows (DCTSIZE or 2 * DCTSIZE)
886 yuv[1] = &rowptrs[2 * DCTSIZE]; // U rows (DCTSIZE)
887 yuv[2] = &rowptrs[3 * DCTSIZE]; // V rows (DCTSIZE)
888
889 // Initialize rowptrs.
890 int numYRowsPerBlock = DCTSIZE * dinfo->comp_info[0].v_samp_factor;
891 for (int i = 0; i < numYRowsPerBlock; i++) {
msarett4984c3c2016-03-10 05:44:43 -0800892 rowptrs[i] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kY],
893 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kY]);
msarettb714fb02016-01-22 14:46:42 -0800894 }
895 for (int i = 0; i < DCTSIZE; i++) {
msarett4984c3c2016-03-10 05:44:43 -0800896 rowptrs[i + 2 * DCTSIZE] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kU],
897 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kU]);
898 rowptrs[i + 3 * DCTSIZE] = SkTAddOffset<JSAMPLE>(planes[SkYUVSizeInfo::kV],
899 i * sizeInfo.fWidthBytes[SkYUVSizeInfo::kV]);
msarettb714fb02016-01-22 14:46:42 -0800900 }
901
902 // After each loop iteration, we will increment pointers to Y, U, and V.
msarett4984c3c2016-03-10 05:44:43 -0800903 size_t blockIncrementY = numYRowsPerBlock * sizeInfo.fWidthBytes[SkYUVSizeInfo::kY];
904 size_t blockIncrementU = DCTSIZE * sizeInfo.fWidthBytes[SkYUVSizeInfo::kU];
905 size_t blockIncrementV = DCTSIZE * sizeInfo.fWidthBytes[SkYUVSizeInfo::kV];
msarettb714fb02016-01-22 14:46:42 -0800906
907 uint32_t numRowsPerBlock = numYRowsPerBlock;
908
909 // We intentionally round down here, as this first loop will only handle
910 // full block rows. As a special case at the end, we will handle any
911 // remaining rows that do not make up a full block.
912 const int numIters = dinfo->output_height / numRowsPerBlock;
913 for (int i = 0; i < numIters; i++) {
914 JDIMENSION linesRead = jpeg_read_raw_data(dinfo, yuv, numRowsPerBlock);
915 if (linesRead < numRowsPerBlock) {
916 // FIXME: Handle incomplete YUV decodes without signalling an error.
917 return kInvalidInput;
918 }
919
920 // Update rowptrs.
921 for (int i = 0; i < numYRowsPerBlock; i++) {
922 rowptrs[i] += blockIncrementY;
923 }
924 for (int i = 0; i < DCTSIZE; i++) {
925 rowptrs[i + 2 * DCTSIZE] += blockIncrementU;
926 rowptrs[i + 3 * DCTSIZE] += blockIncrementV;
927 }
928 }
929
930 uint32_t remainingRows = dinfo->output_height - dinfo->output_scanline;
931 SkASSERT(remainingRows == dinfo->output_height % numRowsPerBlock);
932 SkASSERT(dinfo->output_scanline == numIters * numRowsPerBlock);
933 if (remainingRows > 0) {
934 // libjpeg-turbo needs memory to be padded by the block sizes. We will fulfill
935 // this requirement using a dummy row buffer.
936 // FIXME: Should SkCodec have an extra memory buffer that can be shared among
937 // all of the implementations that use temporary/garbage memory?
msarett4984c3c2016-03-10 05:44:43 -0800938 SkAutoTMalloc<JSAMPLE> dummyRow(sizeInfo.fWidthBytes[SkYUVSizeInfo::kY]);
msarettb714fb02016-01-22 14:46:42 -0800939 for (int i = remainingRows; i < numYRowsPerBlock; i++) {
940 rowptrs[i] = dummyRow.get();
941 }
942 int remainingUVRows = dinfo->comp_info[1].downsampled_height - DCTSIZE * numIters;
943 for (int i = remainingUVRows; i < DCTSIZE; i++) {
944 rowptrs[i + 2 * DCTSIZE] = dummyRow.get();
945 rowptrs[i + 3 * DCTSIZE] = dummyRow.get();
946 }
947
948 JDIMENSION linesRead = jpeg_read_raw_data(dinfo, yuv, numRowsPerBlock);
949 if (linesRead < remainingRows) {
950 // FIXME: Handle incomplete YUV decodes without signalling an error.
951 return kInvalidInput;
952 }
953 }
954
955 return kSuccess;
956}