Debian Codegraph @

src/codec/SkCodec.cpp

raw
1 /*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "include/codec/SkCodec.h"
9
10 #include "include/codec/SkCodecAnimation.h"
11 #include "include/codec/SkPixmapUtils.h"
12 #include "include/core/SkAlphaType.h"
13 #include "include/core/SkBitmap.h"
14 #include "include/core/SkColorSpace.h"
15 #include "include/core/SkColorType.h"
16 #include "include/core/SkData.h"
17 #include "include/core/SkImage.h" // IWYU pragma: keep
18 #include "include/core/SkImageInfo.h"
19 #include "include/core/SkMatrix.h"
20 #include "include/core/SkStream.h"
21 #include "include/private/base/SkTemplates.h"
22 #include "modules/skcms/skcms.h"
23 #include "src/base/SkNoDestructor.h"
24 #include "src/codec/SkCodecPriv.h"
25 #include "src/codec/SkFrameHolder.h"
26 #include "src/codec/SkPixmapUtilsPriv.h"
27 #include "src/codec/SkSampler.h"
28 #include "src/core/SkColorPriv.h"
29
30 #include <string>
31 #include <string_view>
32 #include <utility>
33
34 #if !defined(SK_DISABLE_LEGACY_INIT_DECODERS)
35 #include "include/private/base/SkOnce.h"
36
37 #if defined(SK_CODEC_DECODES_AVIF)
38 #include "include/codec/SkAvifDecoder.h"
39 #endif
40
41 #if defined(SK_CODEC_DECODES_BMP_WITH_RUST)
42 #include "experimental/rust_bmp/decoder/SkBmpRustDecoder.h"
43 #elif defined(SK_CODEC_DECODES_BMP)
44 #include "include/codec/SkBmpDecoder.h"
45 #endif
46
47 #if defined(SK_CODEC_DECODES_GIF) || defined(SK_HAS_WUFFS_LIBRARY)
48 #include "include/codec/SkGifDecoder.h"
49 #endif
50
51 #if defined(SK_CODEC_DECODES_ICO)
52 #include "include/codec/SkIcoDecoder.h"
53 #endif
54
55 #if defined(SK_CODEC_DECODES_JPEG)
56 #include "include/codec/SkJpegDecoder.h"
57 #endif
58
59 #if defined(SK_CODEC_DECODES_JPEGXL)
60 #include "include/codec/SkJpegxlDecoder.h"
61 #endif
62
63 #if defined(SK_CODEC_DECODES_PNG_WITH_LIBPNG)
64 #include "include/codec/SkPngDecoder.h"
65 #elif defined(SK_CODEC_DECODES_PNG_WITH_RUST)
66 #include "include/codec/SkPngRustDecoder.h"
67 #endif
68
69 #if defined(SK_CODEC_DECODES_RAW)
70 #include "include/codec/SkRawDecoder.h"
71 #endif
72
73 #if defined(SK_CODEC_DECODES_WBMP)
74 #include "include/codec/SkWbmpDecoder.h"
75 #endif
76
77 #if defined(SK_CODEC_DECODES_WEBP)
78 #include "include/codec/SkWebpDecoder.h"
79 #endif
80 #endif // !defined(SK_DISABLE_LEGACY_INIT_DECODERS)
81
82 namespace SkCodecs {
83 // A static variable inside a function avoids a static initializer.
84 // https://chromium.googlesource.com/chromium/src/+/HEAD/docs/static_initializers.md#removing-static-initializers
85 static std::vector<Decoder>* get_decoders_for_editing() {
86 static SkNoDestructor<std::vector<Decoder>> decoders;
87 #if !defined(SK_DISABLE_LEGACY_INIT_DECODERS)
88 static SkOnce once;
89 once([] {
90 if (decoders->empty()) {
91 #if defined(SK_CODEC_DECODES_PNG_WITH_LIBPNG)
92 decoders->push_back(SkPngDecoder::Decoder());
93 #elif defined(SK_CODEC_DECODES_PNG_WITH_RUST)
94 decoders->push_back(SkPngRustDecoder::Decoder());
95 #endif
96 #if defined(SK_CODEC_DECODES_JPEG)
97 decoders->push_back(SkJpegDecoder::Decoder());
98 #endif
99 #if defined(SK_CODEC_DECODES_WEBP)
100 decoders->push_back(SkWebpDecoder::Decoder());
101 #endif
102 #if defined(SK_CODEC_DECODES_GIF) || defined(SK_HAS_WUFFS_LIBRARY)
103 decoders->push_back(SkGifDecoder::Decoder());
104 #endif
105 #if defined(SK_CODEC_DECODES_ICO)
106 decoders->push_back(SkIcoDecoder::Decoder());
107 #endif
108
109 #if defined(SK_CODEC_DECODES_BMP_WITH_RUST)
110 decoders->push_back(SkBmpRustDecoder::Decoder());
111 #elif defined(SK_CODEC_DECODES_BMP)
112 decoders->push_back(SkBmpDecoder::Decoder());
113 #endif
114 #if defined(SK_CODEC_DECODES_WBMP)
115 decoders->push_back(SkWbmpDecoder::Decoder());
116 #endif
117 #if defined(SK_CODEC_DECODES_AVIF)
118 #if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK)
119 decoders->push_back(SkAvifDecoder::CrabbyAvif::Decoder());
120 #else
121 decoders->push_back(SkAvifDecoder::LibAvif::Decoder());
122 #endif
123 #endif
124 #if defined(SK_CODEC_DECODES_JPEGXL)
125 decoders->push_back(SkJpegxlDecoder::Decoder());
126 #endif
127 #if defined(SK_CODEC_DECODES_RAW)
128 decoders->push_back(SkRawDecoder::Decoder());
129 #endif
130 }
131 });
132 #endif // !defined(SK_DISABLE_LEGACY_INIT_DECODERS)
133 return decoders.get();
134 }
135
136 const std::vector<Decoder>& get_decoders() {
137 auto decoders = get_decoders_for_editing();
138 return *decoders;
139 }
140
141 void Register(Decoder d) {
142 auto decoders = get_decoders_for_editing();
143 for (size_t i = 0; i < decoders->size(); i++) {
144 if ((*decoders)[i].id == d.id) {
145 (*decoders)[i] = d;
146 return;
147 }
148 }
149 decoders->push_back(d);
150 }
151
152 bool HasDecoder(std::string_view id) {
153 for (const SkCodecs::Decoder& decoder : get_decoders()) {
154 if (decoder.id == id) {
155 return true;
156 }
157 }
158 return false;
159 }
160
161 } // namespace SkCodecs
162
163 std::unique_ptr<SkCodec> SkCodec::MakeFromStream(
164 std::unique_ptr<SkStream> stream, Result* outResult,
165 SkPngChunkReader* chunkReader, SelectionPolicy selectionPolicy) {
166 return MakeFromStream(std::move(stream), SkCodecs::get_decoders(), outResult,
167 chunkReader, selectionPolicy);
168 }
169 std::unique_ptr<SkCodec> SkCodec::MakeFromStream(
170 std::unique_ptr<SkStream> stream, SkSpan<const SkCodecs::Decoder> decoders,
171 Result* outResult, SkPngChunkReader* chunkReader, SelectionPolicy selectionPolicy) {
172 Result resultStorage;
173 if (!outResult) {
174 outResult = &resultStorage;
175 }
176
177 if (!stream) {
178 *outResult = kInvalidInput;
179 return nullptr;
180 }
181
182 if (selectionPolicy != SelectionPolicy::kPreferStillImage
183 && selectionPolicy != SelectionPolicy::kPreferAnimation) {
184 *outResult = kInvalidParameters;
185 return nullptr;
186 }
187
188 constexpr size_t bytesToRead = MinBufferedBytesNeeded();
189
190 char buffer[bytesToRead];
191 size_t bytesRead = stream->peek(buffer, bytesToRead);
192
193 // It is also possible to have a complete image less than bytesToRead bytes
194 // (e.g. a 1 x 1 wbmp), meaning peek() would return less than bytesToRead.
195 // Assume that if bytesRead < bytesToRead, but > 0, the stream is shorter
196 // than bytesToRead, so pass that directly to the decoder.
197 // It also is possible the stream uses too small a buffer for peeking, but
198 // we trust the caller to use a large enough buffer.
199
200 if (0 == bytesRead) {
201 // TODO: After implementing peek in CreateJavaOutputStreamAdaptor.cpp, this
202 // printf could be useful to notice failures.
203 // SkCodecPrintf("Encoded image data failed to peek!\n");
204
205 // It is possible the stream does not support peeking, but does support
206 // rewinding.
207 // Attempt to read() and pass the actual amount read to the decoder.
208 bytesRead = stream->read(buffer, bytesToRead);
209 if (!stream->rewind()) {
210 SkCodecPrintf("Encoded image data could not peek or rewind to determine format!\n");
211 *outResult = kCouldNotRewind;
212 return nullptr;
213 }
214 }
215
216 SkCodecs::MakeFromStreamCallback rawFallback = nullptr;
217 for (const SkCodecs::Decoder& proc : decoders) {
218 if (proc.isFormat(buffer, bytesRead)) {
219 // Some formats are special, since we want to be able to provide an extra parameter.
220 if (proc.id == "png") {
221 return proc.makeFromStream(std::move(stream), outResult, chunkReader);
222 } else if (proc.id == "heif" || proc.id == "gif") {
223 return proc.makeFromStream(std::move(stream), outResult, &selectionPolicy);
224 } else if (proc.id == "raw") {
225 rawFallback = proc.makeFromStream;
226 continue;
227 }
228 return proc.makeFromStream(std::move(stream), outResult, nullptr);
229 }
230 }
231 if (rawFallback != nullptr) {
232 // Fallback to raw.
233 return rawFallback(std::move(stream), outResult, nullptr);
234 }
235
236 if (bytesRead < bytesToRead) {
237 *outResult = kIncompleteInput;
238 } else {
239 *outResult = kUnimplemented;
240 }
241 return nullptr;
242 }
243
244 std::unique_ptr<SkCodec> SkCodec::MakeFromData(sk_sp<const SkData> data, SkPngChunkReader* reader) {
245 return MakeFromData(std::move(data), SkCodecs::get_decoders(), reader);
246 }
247 std::unique_ptr<SkCodec> SkCodec::MakeFromData(sk_sp<const SkData> data,
248 SkSpan<const SkCodecs::Decoder> decoders,
249 SkPngChunkReader* reader) {
250 if (!data) {
251 return nullptr;
252 }
253 return MakeFromStream(SkMemoryStream::Make(std::move(data)), decoders, nullptr, reader);
254 }
255
256 SkCodec::SkCodec(SkEncodedInfo&& info,
257 XformFormat srcFormat,
258 std::unique_ptr<SkStream> stream,
259 SkEncodedOrigin origin)
260 : fEncodedInfo(std::move(info))
261 , fSrcXformFormat(srcFormat)
262 , fStream(std::move(stream))
263 , fOrigin(origin)
264 , fDstInfo()
265 , fOptions() {}
266
267 SkCodec::~SkCodec() {}
268
269 bool SkCodec::queryYUVAInfo(const SkYUVAPixmapInfo::SupportedDataTypes& supportedDataTypes,
270 SkYUVAPixmapInfo* yuvaPixmapInfo) const {
271 if (!yuvaPixmapInfo) {
272 return false;
273 }
274 return this->onQueryYUVAInfo(supportedDataTypes, yuvaPixmapInfo) &&
275 yuvaPixmapInfo->isSupported(supportedDataTypes);
276 }
277
278 SkCodec::Result SkCodec::getYUVAPlanes(const SkYUVAPixmaps& yuvaPixmaps) {
279 if (!yuvaPixmaps.isValid()) {
280 return kInvalidInput;
281 }
282 if (!this->rewindIfNeeded()) {
283 return kCouldNotRewind;
284 }
285 return this->onGetYUVAPlanes(yuvaPixmaps);
286 }
287
288 bool SkCodec::conversionSupported(const SkImageInfo& dst, bool srcIsOpaque, bool needsColorXform) {
289 if (!SkCodecPriv::ValidAlpha(dst.alphaType(), srcIsOpaque)) {
290 return false;
291 }
292
293 switch (dst.colorType()) {
294 case kRGBA_8888_SkColorType:
295 case kBGRA_8888_SkColorType:
296 case kRGBA_F16_SkColorType:
297 case kBGRA_10101010_XR_SkColorType:
298 return true;
299 case kBGR_101010x_XR_SkColorType:
300 case kRGB_565_SkColorType:
301 return srcIsOpaque;
302 case kGray_8_SkColorType:
303 return SkEncodedInfo::kGray_Color == fEncodedInfo.color() && srcIsOpaque;
304 case kAlpha_8_SkColorType:
305 // conceptually we can convert anything into alpha_8, but we haven't actually coded
306 // all of those other conversions yet.
307 return SkEncodedInfo::kXAlpha_Color == fEncodedInfo.color();
308 default:
309 return false;
310 }
311 }
312
313 bool SkCodec::rewindStream() {
314 // Some codecs do not have a stream. They may hold onto their own data or another codec.
315 // They must handle rewinding themselves.
316 if (fStream && !fStream->rewind()) {
317 return false;
318 }
319 return true;
320 }
321
322 bool SkCodec::rewindIfNeeded() {
323 // Store the value of fNeedsRewind so we can update it. Next read will
324 // require a rewind.
325 const bool needsRewind = fNeedsRewind;
326 fNeedsRewind = true;
327 if (!needsRewind) {
328 return true;
329 }
330
331 // startScanlineDecode will need to be called before decoding scanlines.
332 fCurrScanline = -1;
333 // startIncrementalDecode will need to be called before incrementalDecode.
334 fStartedIncrementalDecode = false;
335
336 return this->onRewind();
337 }
338
339 static SkIRect frame_rect_on_screen(SkIRect frameRect,
340 const SkIRect& screenRect) {
341 if (!frameRect.intersect(screenRect)) {
342 return SkIRect::MakeEmpty();
343 }
344
345 return frameRect;
346 }
347
348 bool zero_rect(const SkImageInfo& dstInfo, void* pixels, size_t rowBytes,
349 SkISize srcDimensions, SkIRect prevRect) {
350 const auto dimensions = dstInfo.dimensions();
351 if (dimensions != srcDimensions) {
352 SkRect src = SkRect::Make(srcDimensions);
353 SkRect dst = SkRect::Make(dimensions);
354 auto map = SkMatrix::Rect2Rect(src, dst);
355 if (!map) {
356 return false;
357 }
358 SkRect asRect = SkRect::Make(prevRect);
359 if (!map->mapRect(&asRect)) {
360 return false;
361 }
362 asRect.roundOut(&prevRect);
363 }
364
365 if (!prevRect.intersect(SkIRect::MakeSize(dimensions))) {
366 // Nothing to zero, due to scaling or bad frame rect.
367 return true;
368 }
369
370 const SkImageInfo info = dstInfo.makeDimensions(prevRect.size());
371 const size_t bpp = dstInfo.bytesPerPixel();
372 const size_t offset = prevRect.x() * bpp + prevRect.y() * rowBytes;
373 void* eraseDst = SkTAddOffset<void>(pixels, offset);
374 SkSampler::Fill(info, eraseDst, rowBytes, SkCodec::kNo_ZeroInitialized);
375 return true;
376 }
377
378 SkCodec::Result SkCodec::handleFrameIndex(const SkImageInfo& info, void* pixels, size_t rowBytes,
379 const Options& options, GetPixelsCallback getPixelsFn) {
380 if (getPixelsFn) {
381 // If a callback is used, it handles the frame index, so calls from this SkCodec
382 // should always short-circuit in the else case below.
383 fUsingCallbackForHandleFrameIndex = true;
384 } else if (fUsingCallbackForHandleFrameIndex) {
385 return kSuccess;
386 }
387
388 if (!this->rewindIfNeeded()) {
389 return kCouldNotRewind;
390 }
391
392 const int index = options.fFrameIndex;
393 if (0 == index) {
394 return this->initializeColorXform(info, fEncodedInfo.alpha(), fEncodedInfo.opaque())
395 ? kSuccess : kInvalidConversion;
396 }
397
398 if (index < 0) {
399 return kInvalidParameters;
400 }
401
402 if (options.fSubset) {
403 // If we add support for this, we need to update the code that zeroes
404 // a kRestoreBGColor frame.
405 return kInvalidParameters;
406 }
407
408 if (index >= this->onGetFrameCount()) {
409 return kIncompleteInput;
410 }
411
412 const auto* frameHolder = this->getFrameHolder();
413 SkASSERT(frameHolder);
414
415 const auto* frame = frameHolder->getFrame(index);
416 SkASSERT(frame);
417
418 const int requiredFrame = frame->getRequiredFrame();
419 if (requiredFrame != kNoFrame) {
420 // Decode earlier frame if necessary
421 const SkFrame* preppedFrame = nullptr;
422 if (options.fPriorFrame == kNoFrame) {
423 Result result = kInternalError;
424 // getPixelsFn will be set when things like SkAndroidCodec are calling this function.
425 // Thus, we call the provided function when recursively decoding previous frames,
426 // but only when necessary (i.e. there is a required frame).
427 if (getPixelsFn) {
428 result = getPixelsFn(info, pixels, rowBytes, options, requiredFrame);
429 } else {
430 Options prevFrameOptions(options);
431 prevFrameOptions.fFrameIndex = requiredFrame;
432 result = this->getPixels(info, pixels, rowBytes, &prevFrameOptions);
433 }
434 if (result != kSuccess) {
435 return result;
436 }
437 preppedFrame = frameHolder->getFrame(requiredFrame);
438 } else {
439 // Check for a valid frame as a starting point. Alternatively, we could
440 // treat an invalid frame as not providing one, but rejecting it will
441 // make it easier to catch the mistake.
442 if (options.fPriorFrame < requiredFrame || options.fPriorFrame >= index) {
443 return kInvalidParameters;
444 }
445 preppedFrame = frameHolder->getFrame(options.fPriorFrame);
446 }
447
448 SkASSERT(preppedFrame);
449 switch (preppedFrame->getDisposalMethod()) {
450 case SkCodecAnimation::DisposalMethod::kRestorePrevious:
451 SkASSERT(options.fPriorFrame != kNoFrame);
452 return kInvalidParameters;
453 case SkCodecAnimation::DisposalMethod::kRestoreBGColor:
454 // If a frame after the required frame is provided, there is no
455 // need to clear, since it must be covered by the desired frame.
456 // FIXME: If the required frame is kRestoreBGColor, we don't actually need to decode
457 // it, since we'll just clear it to transparent. Instead, we could decode *its*
458 // required frame and then clear.
459 if (preppedFrame->frameId() == requiredFrame) {
460 SkIRect preppedRect = preppedFrame->frameRect();
461 if (!zero_rect(info, pixels, rowBytes, this->dimensions(), preppedRect)) {
462 return kInternalError;
463 }
464 }
465 break;
466 default:
467 break;
468 }
469 }
470
471 return this->initializeColorXform(info, frame->reportedAlpha(), !frame->hasAlpha())
472 ? kSuccess : kInvalidConversion;
473 }
474
475 bool SkCodec::allocateFromBudget(size_t numBytes) {
476 if (numBytes > fDecodeBudget) SK_UNLIKELY {
477 return false;
478 }
479 fDecodeBudget -= numBytes;
480 return true;
481 }
482
483 SkCodec::Result SkCodec::getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes,
484 const Options* options) {
485 Options optsStorage;
486 if (!options) {
487 options = &optsStorage;
488 }
489
490 fDecodeBudget = options->fMaxDecodeMemory ? options->fMaxDecodeMemory : SIZE_MAX;
491 return this->getPixelsBudgeted(info, pixels, rowBytes, options);
492 }
493
494 SkCodec::Result SkCodec::getPixelsBudgeted(const SkImageInfo& info,
495 void* pixels,
496 size_t rowBytes,
497 const Options* options) {
498 if (kUnknown_SkColorType == info.colorType()) {
499 return kInvalidConversion;
500 }
501 if (nullptr == pixels) {
502 return kInvalidParameters;
503 }
504 if (rowBytes < info.minRowBytes()) {
505 return kInvalidParameters;
506 }
507 SkASSERT(options);
508 SkASSERT(fDecodeBudget > 0);
509
510 if (options->fSubset) {
511 SkIRect subset(*options->fSubset);
512 if (!this->onGetValidSubset(&subset) || subset != *options->fSubset) {
513 // FIXME: How to differentiate between not supporting subset at all
514 // and not supporting this particular subset?
515 return kUnimplemented;
516 }
517 }
518
519 const Result frameIndexResult = this->handleFrameIndex(info, pixels, rowBytes,
520 *options);
521 if (frameIndexResult != kSuccess) {
522 return frameIndexResult;
523 }
524
525 // FIXME: Support subsets somehow? Note that this works for SkWebpCodec
526 // because it supports arbitrary scaling/subset combinations.
527 if (!this->dimensionsSupported(info.dimensions())) {
528 return kInvalidScale;
529 }
530
531 fDstInfo = info;
532 fOptions = *options;
533
534 // On an incomplete decode, the subclass will specify the number of scanlines that it decoded
535 // successfully.
536 int rowsDecoded = 0;
537 const Result result = this->onGetPixels(info, pixels, rowBytes, *options, &rowsDecoded);
538
539 // A return value of kIncompleteInput indicates a truncated image stream.
540 // In this case, we will fill any uninitialized memory with a default value.
541 // Some subclasses will take care of filling any uninitialized memory on
542 // their own. They indicate that all of the memory has been filled by
543 // setting rowsDecoded equal to the height.
544 if ((kIncompleteInput == result || kErrorInInput == result) && rowsDecoded != info.height()) {
545 // FIXME: (skbug.com/40036982) fillIncompleteImage will fill using the swizzler's width, unless
546 // there is a subset. In that case, it will use the width of the subset. From here, the
547 // subset will only be non-null in the case of SkWebpCodec, but it treats the subset
548 // differenty from the other codecs, and it needs to use the width specified by the info.
549 // Set the subset to null so SkWebpCodec uses the correct width.
550 fOptions.fSubset = nullptr;
551 this->fillIncompleteImage(info, pixels, rowBytes, options->fZeroInitialized, info.height(),
552 rowsDecoded);
553 }
554
555 return result;
556 }
557
558 std::tuple<sk_sp<SkImage>, SkCodec::Result> SkCodec::getImage(const SkImageInfo& info,
559 const Options* options) {
560 Options optsStorage;
561 if (!options) {
562 options = &optsStorage;
563 }
564 fDecodeBudget = options->fMaxDecodeMemory ? options->fMaxDecodeMemory : SIZE_MAX;
565
566 if (size_t size = info.computeByteSize(info.minRowBytes()); !this->allocateFromBudget(size)) {
567 return {nullptr, kOutOfMemory};
568 }
569
570 SkBitmap bm;
571 if (!bm.tryAllocPixels(info)) {
572 return {nullptr, kInternalError};
573 }
574
575 Result result;
576 auto decode = [this, options, &result](const SkPixmap& pm) {
577 result = this->getPixelsBudgeted(pm.info(), pm.writable_addr(), pm.rowBytes(), options);
578 switch (result) {
579 case SkCodec::kSuccess:
580 case SkCodec::kIncompleteInput:
581 case SkCodec::kErrorInInput:
582 return true;
583 default:
584 return false;
585 }
586 };
587
588 // If the codec reports this image is rotated, we will decode it into
589 // a temporary buffer, then copy it (rotated) into the pixmap belonging
590 // to bm that we allocated above. If the image is not rotated, we will
591 // decode straight into that allocated pixmap.
592 if (!SkPixmapUtils::Orient(bm.pixmap(), this->getOrigin(), decode)) {
593 return {nullptr, result};
594 }
595 // Setting the bitmap to be immutable saves us from having to copy it.
596 bm.setImmutable();
597 return {SkImages::RasterFromBitmap(bm), kSuccess};
598 }
599
600 std::tuple<sk_sp<SkImage>, SkCodec::Result> SkCodec::getImage() {
601 // If the codec reports that it is rotated, we need to rotate the image info
602 // it says it is, so the output is what the user wants.
603 SkImageInfo info = this->getInfo();
604 if (SkEncodedOriginSwapsWidthHeight(this->getOrigin())) {
605 info = SkPixmapUtils::SwapWidthHeight(info);
606 }
607 return this->getImage(info, nullptr);
608 }
609
610 SkCodec::Result SkCodec::startIncrementalDecode(const SkImageInfo& info, void* pixels,
611 size_t rowBytes, const SkCodec::Options* options) {
612 fStartedIncrementalDecode = false;
613
614 if (!this->onSupportsIncrementalDecode(info)) {
615 return kUnimplemented;
616 }
617 if (kUnknown_SkColorType == info.colorType()) {
618 return kInvalidConversion;
619 }
620 if (nullptr == pixels) {
621 return kInvalidParameters;
622 }
623
624 // Set options.
625 Options optsStorage;
626 if (nullptr == options) {
627 options = &optsStorage;
628 } else {
629 if (options->fSubset) {
630 SkIRect size = SkIRect::MakeSize(info.dimensions());
631 if (!size.contains(*options->fSubset)) {
632 return kInvalidParameters;
633 }
634
635 const int top = options->fSubset->top();
636 const int bottom = options->fSubset->bottom();
637 if (top < 0 || top >= info.height() || top >= bottom || bottom > info.height()) {
638 return kInvalidParameters;
639 }
640 }
641 }
642
643 const Result frameIndexResult = this->handleFrameIndex(info, pixels, rowBytes,
644 *options);
645 if (frameIndexResult != kSuccess) {
646 return frameIndexResult;
647 }
648
649 if (!this->dimensionsSupported(info.dimensions())) {
650 return kInvalidScale;
651 }
652
653 fDstInfo = info;
654 fOptions = *options;
655
656 const Result result = this->onStartIncrementalDecode(info, pixels, rowBytes, fOptions);
657 if (kSuccess == result) {
658 fStartedIncrementalDecode = true;
659 }
660 SkASSERT(result != kUnimplemented);
661 return result;
662 }
663
664
665 SkCodec::Result SkCodec::startScanlineDecode(const SkImageInfo& info,
666 const SkCodec::Options* options) {
667 // Reset fCurrScanline in case of failure.
668 fCurrScanline = -1;
669
670 // Set options.
671 Options optsStorage;
672 if (!options) {
673 options = &optsStorage;
674 }
675 fDecodeBudget = options->fMaxDecodeMemory ? options->fMaxDecodeMemory : SIZE_MAX;
676
677 if (options->fSubset) {
678 SkIRect size = SkIRect::MakeSize(info.dimensions());
679 if (!size.contains(*options->fSubset)) {
680 return kInvalidInput;
681 }
682
683 // We only support subsetting in the x-dimension for scanline decoder.
684 // Subsetting in the y-dimension can be accomplished using skipScanlines().
685 if (options->fSubset->top() != 0 || options->fSubset->height() != info.height()) {
686 return kInvalidInput;
687 }
688 }
689
690 // Scanline decoding only supports decoding the first frame.
691 if (options->fFrameIndex != 0) {
692 return kUnimplemented;
693 }
694
695 // The void* dst and rowbytes in handleFrameIndex or only used for decoding prior
696 // frames, which is not supported here anyway, so it is safe to pass nullptr/0.
697 const Result frameIndexResult = this->handleFrameIndex(info, nullptr, 0, *options);
698 if (frameIndexResult != kSuccess) {
699 return frameIndexResult;
700 }
701
702 // FIXME: Support subsets somehow?
703 if (!this->dimensionsSupported(info.dimensions())) {
704 return kInvalidScale;
705 }
706
707 const Result result = this->onStartScanlineDecode(info, *options);
708 if (result != SkCodec::kSuccess) {
709 return result;
710 }
711
712 fCurrScanline = 0;
713 fDstInfo = info;
714 fOptions = *options;
715 return kSuccess;
716 }
717
718 int SkCodec::getScanlines(void* dst, int countLines, size_t rowBytes) {
719 if (fCurrScanline < 0) {
720 return 0;
721 }
722
723 SkASSERT(!fDstInfo.isEmpty());
724 if (countLines <= 0 || fCurrScanline + countLines > fDstInfo.height()) {
725 return 0;
726 }
727
728 const int linesDecoded = this->onGetScanlines(dst, countLines, rowBytes);
729 if (linesDecoded < countLines) {
730 this->fillIncompleteImage(this->dstInfo(), dst, rowBytes, this->options().fZeroInitialized,
731 countLines, linesDecoded);
732 }
733 fCurrScanline += countLines;
734 return linesDecoded;
735 }
736
737 bool SkCodec::skipScanlines(int countLines) {
738 if (fCurrScanline < 0) {
739 return false;
740 }
741
742 SkASSERT(!fDstInfo.isEmpty());
743 if (countLines < 0 || fCurrScanline + countLines > fDstInfo.height()) {
744 // Arguably, we could just skip the scanlines which are remaining,
745 // and return true. We choose to return false so the client
746 // can catch their bug.
747 return false;
748 }
749
750 bool result = this->onSkipScanlines(countLines);
751 fCurrScanline += countLines;
752 return result;
753 }
754
755 int SkCodec::outputScanline(int inputScanline) const {
756 SkASSERT(0 <= inputScanline && inputScanline < fEncodedInfo.height());
757 return this->onOutputScanline(inputScanline);
758 }
759
760 int SkCodec::onOutputScanline(int inputScanline) const {
761 switch (this->getScanlineOrder()) {
762 case kTopDown_SkScanlineOrder:
763 return inputScanline;
764 case kBottomUp_SkScanlineOrder:
765 return fEncodedInfo.height() - inputScanline - 1;
766 default:
767 // This case indicates an interlaced gif and is implemented by SkGifCodec.
768 SkASSERT(false);
769 return 0;
770 }
771 }
772
773 void SkCodec::fillIncompleteImage(const SkImageInfo& info, void* dst, size_t rowBytes,
774 ZeroInitialized zeroInit, int linesRequested, int linesDecoded) {
775 if (kYes_ZeroInitialized == zeroInit) {
776 return;
777 }
778
779 const int linesRemaining = linesRequested - linesDecoded;
780 SkSampler* sampler = this->getSampler(false);
781
782 const int fillWidth = sampler ? sampler->fillWidth() :
783 fOptions.fSubset ? fOptions.fSubset->width() :
784 info.width() ;
785 void* fillDst = this->getScanlineOrder() == kBottomUp_SkScanlineOrder ? dst :
786 SkTAddOffset<void>(dst, linesDecoded * rowBytes);
787 const auto fillInfo = info.makeWH(fillWidth, linesRemaining);
788 SkSampler::Fill(fillInfo, fillDst, rowBytes, kNo_ZeroInitialized);
789 }
790
791 bool SkCodecPriv::SelectXformFormat(SkColorType colorType,
792 bool forColorTable,
793 skcms_PixelFormat* outFormat) {
794 SkASSERT(outFormat);
795
796 switch (colorType) {
797 case kRGBA_8888_SkColorType:
798 *outFormat = skcms_PixelFormat_RGBA_8888;
799 break;
800 case kBGRA_8888_SkColorType:
801 *outFormat = skcms_PixelFormat_BGRA_8888;
802 break;
803 case kRGB_565_SkColorType:
804 if (forColorTable) {
805 #if defined(SK_PMCOLOR_IS_RGBA)
806 *outFormat = skcms_PixelFormat_RGBA_8888;
807 #else
808 *outFormat = skcms_PixelFormat_BGRA_8888;
809 #endif
810 break;
811 }
812 *outFormat = skcms_PixelFormat_BGR_565;
813 break;
814 case kRGBA_F16_SkColorType:
815 *outFormat = skcms_PixelFormat_RGBA_hhhh;
816 break;
817 case kRGBA_1010102_SkColorType:
818 *outFormat = skcms_PixelFormat_RGBA_1010102;
819 break;
820 case kBGR_101010x_XR_SkColorType:
821 *outFormat = skcms_PixelFormat_BGR_101010x_XR;
822 break;
823 case kGray_8_SkColorType:
824 *outFormat = skcms_PixelFormat_G_8;
825 break;
826 default:
827 return false;
828 }
829 return true;
830 }
831
832 bool SkCodec::initializeColorXform(const SkImageInfo& dstInfo, SkEncodedInfo::Alpha encodedAlpha,
833 bool srcIsOpaque) {
834 fXformTime = kNo_XformTime;
835 bool needsColorXform = false;
836 if (this->usesColorXform()) {
837 if (kRGBA_F16_SkColorType == dstInfo.colorType() ||
838 kRGBA_1010102_SkColorType == dstInfo.colorType() ||
839 kBGR_101010x_XR_SkColorType == dstInfo.colorType()) {
840 needsColorXform = true;
841 if (dstInfo.colorSpace()) {
842 dstInfo.colorSpace()->toProfile(&fDstProfileStorage);
843 fDstProfile = &fDstProfileStorage;
844 } else {
845 // Use the srcProfile to avoid conversion.
846 const auto* srcProfile = fEncodedInfo.profile();
847 fDstProfile = srcProfile ? srcProfile : skcms_sRGB_profile();
848 }
849 } else if (dstInfo.colorSpace()) {
850 dstInfo.colorSpace()->toProfile(&fDstProfileStorage);
851 fDstProfile = &fDstProfileStorage;
852 const auto* srcProfile = fEncodedInfo.profile();
853 if (!srcProfile) {
854 srcProfile = skcms_sRGB_profile();
855 }
856 if (!skcms_ApproximatelyEqualProfiles(srcProfile, fDstProfile) ) {
857 needsColorXform = true;
858 }
859 }
860 }
861
862 if (!this->conversionSupported(dstInfo, srcIsOpaque, needsColorXform)) {
863 return false;
864 }
865
866 if (needsColorXform) {
867 fXformTime = SkEncodedInfo::kPalette_Color != fEncodedInfo.color()
868 || kRGBA_F16_SkColorType == dstInfo.colorType()
869 ? kDecodeRow_XformTime : kPalette_XformTime;
870 if (!SkCodecPriv::SelectXformFormat(
871 dstInfo.colorType(), fXformTime == kPalette_XformTime, &fDstXformFormat)) {
872 return false;
873 }
874 if (encodedAlpha == SkEncodedInfo::kUnpremul_Alpha
875 && dstInfo.alphaType() == kPremul_SkAlphaType) {
876 fDstXformAlphaFormat = skcms_AlphaFormat_PremulAsEncoded;
877 } else {
878 fDstXformAlphaFormat = skcms_AlphaFormat_Unpremul;
879 }
880 }
881 return true;
882 }
883
884 void SkCodec::applyColorXform(void* dst, const void* src, int count) const {
885 // It is okay for srcProfile to be null. This will use sRGB.
886 const auto* srcProfile = fEncodedInfo.profile();
887 SkAssertResult(skcms_Transform(src, fSrcXformFormat, skcms_AlphaFormat_Unpremul, srcProfile,
888 dst, fDstXformFormat, fDstXformAlphaFormat, fDstProfile,
889 count));
890 }
891
892 std::vector<SkCodec::FrameInfo> SkCodec::getFrameInfo() {
893 const int frameCount = this->getFrameCount();
894 SkASSERT(frameCount >= 0);
895 if (frameCount <= 0) {
896 return std::vector<FrameInfo>{};
897 }
898
899 if (frameCount == 1 && !this->onGetFrameInfo(0, nullptr)) {
900 // Not animated.
901 return std::vector<FrameInfo>{};
902 }
903
904 std::vector<FrameInfo> result(frameCount);
905 for (int i = 0; i < frameCount; ++i) {
906 SkAssertResult(this->onGetFrameInfo(i, &result[i]));
907 }
908 return result;
909 }
910
911 const char* SkCodec::ResultToString(Result result) {
912 switch (result) {
913 case kSuccess:
914 return "success";
915 case kIncompleteInput:
916 return "incomplete input";
917 case kErrorInInput:
918 return "error in input";
919 case kInvalidConversion:
920 return "invalid conversion";
921 case kInvalidScale:
922 return "invalid scale";
923 case kInvalidParameters:
924 return "invalid parameters";
925 case kInvalidInput:
926 return "invalid input";
927 case kCouldNotRewind:
928 return "could not rewind";
929 case kInternalError:
930 return "internal error";
931 case kUnimplemented:
932 return "unimplemented";
933 case kOutOfMemory:
934 return "out of memory";
935 default:
936 SkASSERT(false);
937 return "bogus result value";
938 }
939 }
940
941 void SkFrame::fillIn(SkCodec::FrameInfo* frameInfo, bool fullyReceived) const {
942 SkASSERT(frameInfo);
943
944 frameInfo->fRequiredFrame = fRequiredFrame;
945 frameInfo->fDuration = fDuration;
946 frameInfo->fFullyReceived = fullyReceived;
947 frameInfo->fAlphaType = fHasAlpha ? kUnpremul_SkAlphaType
948 : kOpaque_SkAlphaType;
949 frameInfo->fHasAlphaWithinBounds = this->reportedAlpha() != SkEncodedInfo::kOpaque_Alpha;
950 frameInfo->fDisposalMethod = fDisposalMethod;
951 frameInfo->fBlend = fBlend;
952 frameInfo->fFrameRect = fRect;
953 }
954
955 static bool independent(const SkFrame& frame) {
956 return frame.getRequiredFrame() == SkCodec::kNoFrame;
957 }
958
959 static bool restore_bg(const SkFrame& frame) {
960 return frame.getDisposalMethod() == SkCodecAnimation::DisposalMethod::kRestoreBGColor;
961 }
962
963 // As its name suggests, this method computes a frame's alpha (e.g. completely
964 // opaque, unpremul, binary) and its required frame (a preceding frame that
965 // this frame depends on, to draw the complete image at this frame's point in
966 // the animation stream), and calls this frame's setter methods with that
967 // computed information.
968 //
969 // A required frame of kNoFrame means that this frame is independent: drawing
970 // the complete image at this frame's point in the animation stream does not
971 // require first preparing the pixel buffer based on another frame. Instead,
972 // drawing can start from an uninitialized pixel buffer.
973 //
974 // "Uninitialized" is from the SkCodec's caller's point of view. In the SkCodec
975 // implementation, for independent frames, first party Skia code (in src/codec)
976 // will typically fill the buffer with a uniform background color (e.g.
977 // transparent black) before calling into third party codec-specific code (e.g.
978 // libjpeg or libpng). Pixels outside of the frame's rect will remain this
979 // background color after drawing this frame. For incomplete decodes, pixels
980 // inside that rect may be (at least temporarily) set to that background color.
981 // In an incremental decode, later passes may then overwrite that background
982 // color.
983 //
984 // Determining kNoFrame or otherwise involves testing a number of conditions
985 // sequentially. The first satisfied condition results in setting the required
986 // frame to kNoFrame (an "INDx" condition) or to a non-negative frame number (a
987 // "DEPx" condition), and the function returning early. Those "INDx" and "DEPx"
988 // labels also map to comments in the function body.
989 //
990 // - IND1: this frame is the first frame.
991 // - IND2: this frame fills out the whole image, and it is completely opaque
992 // or it overwrites (not blends with) the previous frame.
993 // - IND3: all preceding frames' disposals are kRestorePrevious.
994 // - IND4: the prevFrame's disposal is kRestoreBGColor, and it fills out the
995 // whole image or it is itself otherwise independent.
996 // - DEP5: this frame reports alpha (it is not completely opaque) and it
997 // blends with (not overwrites) the previous frame.
998 // - IND6: this frame's rect covers the rects of all preceding frames back to
999 // and including the most recent independent frame before this frame.
1000 // - DEP7: unconditional.
1001 //
1002 // The "prevFrame" variable initially points to the previous frame (also known
1003 // as the prior frame), but that variable may iterate further backwards over
1004 // the course of this computation.
1005 void SkFrameHolder::setAlphaAndRequiredFrame(SkFrame* frame) {
1006 const bool reportsAlpha = frame->reportedAlpha() != SkEncodedInfo::kOpaque_Alpha;
1007 const auto screenRect = SkIRect::MakeWH(fScreenWidth, fScreenHeight);
1008 const auto frameRect = frame_rect_on_screen(frame->frameRect(), screenRect);
1009
1010 const int i = frame->frameId();
1011 if (0 == i) {
1012 frame->setHasAlpha(reportsAlpha || frameRect != screenRect);
1013 frame->setRequiredFrame(SkCodec::kNoFrame); // IND1
1014 return;
1015 }
1016
1017
1018 const bool blendWithPrevFrame = frame->getBlend() == SkCodecAnimation::Blend::kSrcOver;
1019 if ((!reportsAlpha || !blendWithPrevFrame) && frameRect == screenRect) {
1020 frame->setHasAlpha(reportsAlpha);
1021 frame->setRequiredFrame(SkCodec::kNoFrame); // IND2
1022 return;
1023 }
1024
1025 const SkFrame* prevFrame = this->getFrame(i-1);
1026 while (prevFrame->getDisposalMethod() == SkCodecAnimation::DisposalMethod::kRestorePrevious) {
1027 const int prevId = prevFrame->frameId();
1028 if (0 == prevId) {
1029 frame->setHasAlpha(true);
1030 frame->setRequiredFrame(SkCodec::kNoFrame); // IND3
1031 return;
1032 }
1033
1034 prevFrame = this->getFrame(prevId - 1);
1035 }
1036
1037 const bool clearPrevFrame = restore_bg(*prevFrame);
1038 auto prevFrameRect = frame_rect_on_screen(prevFrame->frameRect(), screenRect);
1039
1040 if (clearPrevFrame) {
1041 if (prevFrameRect == screenRect || independent(*prevFrame)) {
1042 frame->setHasAlpha(true);
1043 frame->setRequiredFrame(SkCodec::kNoFrame); // IND4
1044 return;
1045 }
1046 }
1047
1048 if (reportsAlpha && blendWithPrevFrame) {
1049 // Note: We could be more aggressive here. If prevFrame clears
1050 // to background color and covers its required frame (and that
1051 // frame is independent), prevFrame could be marked independent.
1052 // Would this extra complexity be worth it?
1053 frame->setRequiredFrame(prevFrame->frameId()); // DEP5
1054 frame->setHasAlpha(prevFrame->hasAlpha() || clearPrevFrame);
1055 return;
1056 }
1057
1058 while (frameRect.contains(prevFrameRect)) {
1059 const int prevRequiredFrame = prevFrame->getRequiredFrame();
1060 if (prevRequiredFrame == SkCodec::kNoFrame) {
1061 frame->setRequiredFrame(SkCodec::kNoFrame); // IND6
1062 frame->setHasAlpha(true);
1063 return;
1064 }
1065
1066 prevFrame = this->getFrame(prevRequiredFrame);
1067 prevFrameRect = frame_rect_on_screen(prevFrame->frameRect(), screenRect);
1068 }
1069
1070 frame->setRequiredFrame(prevFrame->frameId()); // DEP7
1071 if (restore_bg(*prevFrame)) {
1072 frame->setHasAlpha(true);
1073 return;
1074 }
1075 SkASSERT(prevFrame->getDisposalMethod() == SkCodecAnimation::DisposalMethod::kKeep);
1076 frame->setHasAlpha(prevFrame->hasAlpha() || (reportsAlpha && !blendWithPrevFrame));
1077 }
1078
1079 std::unique_ptr<SkStream> SkCodec::getEncodedData() const {
1080 SkASSERT(fStream);
1081 if (!fStream) {
1082 return nullptr;
1083 }
1084 return fStream->duplicate();
1085 }