Coverage Report

Created: 2021-08-22 09:07

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