blob: 090c2341cc53bbdceb10ed35ad7bc19d64159195 [file] [log] [blame]
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001/*
2 * Copyright 2018 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 "SkWuffsCodec.h"
9
10#include "../private/SkMalloc.h"
11#include "SkFrameHolder.h"
12#include "SkSampler.h"
Nigel Tao0185b952018-11-08 10:47:24 +110013#include "SkSwizzler.h"
14#include "SkUtils.h"
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040015#include "wuffs-v0.2.h"
16
17#define SK_WUFFS_CODEC_BUFFER_SIZE 4096
18
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -040019static bool fill_buffer(wuffs_base__io_buffer* b, SkStream* s) {
20 b->compact();
21 size_t num_read = s->read(b->data.ptr + b->meta.wi, b->data.len - b->meta.wi);
22 b->meta.wi += num_read;
23 b->meta.closed = s->isAtEnd();
24 return num_read > 0;
25}
26
27static bool seek_buffer(wuffs_base__io_buffer* b, SkStream* s, uint64_t pos) {
28 // Try to re-position the io_buffer's meta.ri read-index first, which is
29 // cheaper than seeking in the backing SkStream.
30 if ((pos >= b->meta.pos) && (pos - b->meta.pos <= b->meta.wi)) {
31 b->meta.ri = pos - b->meta.pos;
32 return true;
33 }
34 // Seek in the backing SkStream.
35 if ((pos > SIZE_MAX) || (!s->seek(pos))) {
36 return false;
37 }
38 b->meta.wi = 0;
39 b->meta.ri = 0;
40 b->meta.pos = pos;
41 b->meta.closed = false;
42 return true;
43}
44
45static SkEncodedInfo::Alpha wuffs_blend_to_skia_alpha(wuffs_base__animation_blend w) {
46 return (w == WUFFS_BASE__ANIMATION_BLEND__OPAQUE) ? SkEncodedInfo::kOpaque_Alpha
47 : SkEncodedInfo::kUnpremul_Alpha;
48}
49
50static SkCodecAnimation::Blend wuffs_blend_to_skia_blend(wuffs_base__animation_blend w) {
51 return (w == WUFFS_BASE__ANIMATION_BLEND__SRC) ? SkCodecAnimation::Blend::kBG
52 : SkCodecAnimation::Blend::kPriorFrame;
53}
54
55static SkCodecAnimation::DisposalMethod wuffs_disposal_to_skia_disposal(
56 wuffs_base__animation_disposal w) {
57 switch (w) {
58 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND:
59 return SkCodecAnimation::DisposalMethod::kRestoreBGColor;
60 case WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS:
61 return SkCodecAnimation::DisposalMethod::kRestorePrevious;
62 default:
63 return SkCodecAnimation::DisposalMethod::kKeep;
64 }
65}
66
67// -------------------------------- Class definitions
68
69class SkWuffsCodec;
70
71class SkWuffsFrame final : public SkFrame {
72public:
73 SkWuffsFrame(wuffs_base__frame_config* fc);
74
75 SkCodec::FrameInfo frameInfo(bool fullyReceived) const;
76 uint64_t ioPosition() const;
77
78 // SkFrame overrides.
79 SkEncodedInfo::Alpha onReportedAlpha() const override;
80
81private:
82 uint64_t fIOPosition;
83 SkEncodedInfo::Alpha fReportedAlpha;
84
85 typedef SkFrame INHERITED;
86};
87
88// SkWuffsFrameHolder is a trivial indirector that forwards its calls onto a
89// SkWuffsCodec. It is a separate class as SkWuffsCodec would otherwise
90// inherit from both SkCodec and SkFrameHolder, and Skia style discourages
91// multiple inheritance (e.g. with its "typedef Foo INHERITED" convention).
92class SkWuffsFrameHolder final : public SkFrameHolder {
93public:
94 SkWuffsFrameHolder() : INHERITED() {}
95
96 void init(SkWuffsCodec* codec, int width, int height);
97
98 // SkFrameHolder overrides.
99 const SkFrame* onGetFrame(int i) const override;
100
101private:
102 const SkWuffsCodec* fCodec;
103
104 typedef SkFrameHolder INHERITED;
105};
106
Nigel Tao0185b952018-11-08 10:47:24 +1100107// SkWuffsSpySampler is a placeholder SkSampler implementation. The Skia API
108// expects to manipulate the codec's sampler (i.e. call setSampleX and
109// setSampleY) in between the startIncrementalDecode (SID) and
110// incrementalDecode (ID) calls. But creating the SkSwizzler (the real sampler)
111// requires knowing the destination buffer's dimensions, i.e. the animation
112// frame's width and height. That width and height are decoded in ID, not SID.
113//
114// To break that circle, the SkWuffsSpySampler always exists, so its methods
115// can be called between SID and ID. It doesn't actually do any sampling, it
116// merely records the arguments given to setSampleX (explicitly) and setSampleY
117// (implicitly, via the superclass' implementation). Inside ID, those recorded
118// arguments are forwarded on to the SkSwizzler (the real sampler) when that
119// SkSwizzler is created, after the frame width and height are known.
120//
121// Roughly speaking, the SkWuffsSpySampler is an eager proxy for the lazily
122// constructed real sampler. But that laziness is out of necessity.
123//
124// The "Spy" name is because it records its arguments. See
125// https://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs
126class SkWuffsSpySampler final : public SkSampler {
127public:
128 SkWuffsSpySampler(int imageWidth)
129 : INHERITED(), fFillWidth(0), fImageWidth(imageWidth), fSampleX(1) {}
130
131 void reset();
132 int sampleX() const;
133
134 int fFillWidth;
135
136private:
137 // SkSampler overrides.
138 int fillWidth() const override;
139 int onSetSampleX(int sampleX) override;
140
141 const int fImageWidth;
142
143 int fSampleX;
144
145 typedef SkSampler INHERITED;
146};
147
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400148class SkWuffsCodec final : public SkCodec {
149public:
150 SkWuffsCodec(SkEncodedInfo&& encodedInfo,
151 std::unique_ptr<SkStream> stream,
152 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
153 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr,
154 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
155 size_t workbuf_len,
156 wuffs_base__image_config imgcfg,
157 wuffs_base__pixel_buffer pixbuf,
158 wuffs_base__io_buffer iobuf);
159
160 const SkWuffsFrame* frame(int i) const;
161
162private:
163 // SkCodec overrides.
164 SkEncodedImageFormat onGetEncodedFormat() const override;
165 Result onGetPixels(const SkImageInfo&, void*, size_t, const Options&, int*) override;
166 const SkFrameHolder* getFrameHolder() const override;
167 Result onStartIncrementalDecode(const SkImageInfo& dstInfo,
168 void* dst,
169 size_t rowBytes,
170 const SkCodec::Options& options) override;
171 Result onIncrementalDecode(int* rowsDecoded) override;
172 int onGetFrameCount() override;
173 bool onGetFrameInfo(int, FrameInfo*) const override;
174 int onGetRepetitionCount() override;
Nigel Tao0185b952018-11-08 10:47:24 +1100175 SkSampler* getSampler(bool createIfNecessary) override;
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500176 bool conversionSupported(const SkImageInfo& dst, bool, bool) override;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400177
178 void readFrames();
179 Result seekFrame(int frameIndex);
180
181 Result resetDecoder();
182 const char* decodeFrameConfig();
183 const char* decodeFrame();
184 void updateNumFullyReceivedFrames();
185
Nigel Tao0185b952018-11-08 10:47:24 +1100186 SkWuffsSpySampler fSpySampler;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400187 SkWuffsFrameHolder fFrameHolder;
188 std::unique_ptr<SkStream> fStream;
189 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoder;
190 std::unique_ptr<uint8_t, decltype(&sk_free)> fPixbufPtr;
191 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
192 size_t fWorkbufLen;
193
194 const uint64_t fFirstFrameIOPosition;
195 wuffs_base__frame_config fFrameConfig;
196 wuffs_base__pixel_buffer fPixelBuffer;
197 wuffs_base__io_buffer fIOBuffer;
198
199 // Incremental decoding state.
Nigel Tao0185b952018-11-08 10:47:24 +1100200 uint8_t* fIncrDecDst;
201 bool fIncrDecHaveFrameConfig;
202 size_t fIncrDecRowBytes;
203
204 std::unique_ptr<SkSwizzler> fSwizzler;
205 SkPMColor fColorTable[256];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400206
207 uint64_t fNumFullyReceivedFrames;
208 std::vector<SkWuffsFrame> fFrames;
209 bool fFramesComplete;
210
211 // If calling an fDecoder method returns an incomplete status, then
212 // fDecoder is suspended in a coroutine (i.e. waiting on I/O or halted on a
213 // non-recoverable error). To keep its internal proof-of-safety invariants
214 // consistent, there's only two things you can safely do with a suspended
215 // Wuffs object: resume the coroutine, or reset all state (memset to zero
216 // and start again).
217 //
218 // If fDecoderIsSuspended, and we aren't sure that we're going to resume
219 // the coroutine, then we will need to call this->resetDecoder before
220 // calling other fDecoder methods.
221 bool fDecoderIsSuspended;
222
223 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
224
225 typedef SkCodec INHERITED;
226};
227
228// -------------------------------- SkWuffsFrame implementation
229
230SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
231 : INHERITED(fc->index()),
232 fIOPosition(fc->io_position()),
233 fReportedAlpha(wuffs_blend_to_skia_alpha(fc->blend())) {
234 wuffs_base__rect_ie_u32 r = fc->bounds();
235 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
236 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
237 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
238 this->setBlend(wuffs_blend_to_skia_blend(fc->blend()));
239}
240
241SkCodec::FrameInfo SkWuffsFrame::frameInfo(bool fullyReceived) const {
242 return ((SkCodec::FrameInfo){
243 .fRequiredFrame = getRequiredFrame(),
244 .fDuration = getDuration(),
245 .fFullyReceived = fullyReceived,
246 .fAlphaType = hasAlpha() ? kUnpremul_SkAlphaType : kOpaque_SkAlphaType,
247 .fDisposalMethod = getDisposalMethod(),
248 });
249}
250
251uint64_t SkWuffsFrame::ioPosition() const {
252 return fIOPosition;
253}
254
255SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
256 return fReportedAlpha;
257}
258
259// -------------------------------- SkWuffsFrameHolder implementation
260
261void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
262 fCodec = codec;
263 // Initialize SkFrameHolder's (the superclass) fields.
264 fScreenWidth = width;
265 fScreenHeight = height;
266}
267
268const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
269 return fCodec->frame(i);
270};
271
Nigel Tao0185b952018-11-08 10:47:24 +1100272// -------------------------------- SkWuffsSpySampler implementation
273
274void SkWuffsSpySampler::reset() {
275 fFillWidth = 0;
276 fSampleX = 1;
277 this->setSampleY(1);
278}
279
280int SkWuffsSpySampler::sampleX() const {
281 return fSampleX;
282}
283
284int SkWuffsSpySampler::fillWidth() const {
285 return fFillWidth;
286}
287
288int SkWuffsSpySampler::onSetSampleX(int sampleX) {
289 fSampleX = sampleX;
290 return get_scaled_dimension(fImageWidth, sampleX);
291}
292
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400293// -------------------------------- SkWuffsCodec implementation
294
295SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
296 std::unique_ptr<SkStream> stream,
297 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
298 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr,
299 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
300 size_t workbuf_len,
301 wuffs_base__image_config imgcfg,
302 wuffs_base__pixel_buffer pixbuf,
303 wuffs_base__io_buffer iobuf)
304 : INHERITED(std::move(encodedInfo),
305 skcms_PixelFormat_RGBA_8888,
306 // Pass a nullptr SkStream to the SkCodec constructor. We
307 // manage the stream ourselves, as the default SkCodec behavior
308 // is too trigger-happy on rewinding the stream.
309 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100310 fSpySampler(imgcfg.pixcfg.width()),
311 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400312 fStream(std::move(stream)),
313 fDecoder(std::move(dec)),
314 fPixbufPtr(std::move(pixbuf_ptr)),
315 fWorkbufPtr(std::move(workbuf_ptr)),
316 fWorkbufLen(workbuf_len),
317 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
318 fFrameConfig((wuffs_base__frame_config){}),
319 fPixelBuffer(pixbuf),
320 fIOBuffer((wuffs_base__io_buffer){}),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400321 fIncrDecDst(nullptr),
322 fIncrDecHaveFrameConfig(false),
323 fIncrDecRowBytes(0),
Nigel Tao0185b952018-11-08 10:47:24 +1100324 fSwizzler(nullptr),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400325 fNumFullyReceivedFrames(0),
326 fFramesComplete(false),
327 fDecoderIsSuspended(false) {
328 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
Nigel Tao0185b952018-11-08 10:47:24 +1100329 sk_memset32(fColorTable, 0, SK_ARRAY_COUNT(fColorTable));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400330
331 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
332 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
333 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
334 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
335 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
336 fIOBuffer = ((wuffs_base__io_buffer){
337 .data = ((wuffs_base__slice_u8){
338 .ptr = fBuffer,
339 .len = SK_WUFFS_CODEC_BUFFER_SIZE,
340 }),
341 .meta = iobuf.meta,
342 });
343}
344
345const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
346 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
347 return &fFrames[i];
348 }
349 return nullptr;
350}
351
352SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
353 return SkEncodedImageFormat::kGIF;
354}
355
356SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
357 void* dst,
358 size_t rowBytes,
359 const Options& options,
360 int* rowsDecoded) {
361 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
362 if (result != kSuccess) {
363 return result;
364 }
365 return this->onIncrementalDecode(rowsDecoded);
366}
367
368const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
369 return &fFrameHolder;
370}
371
372SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
373 void* dst,
374 size_t rowBytes,
375 const SkCodec::Options& options) {
376 if (options.fSubset) {
377 return SkCodec::kUnimplemented;
378 }
379 SkCodec::Result result = this->seekFrame(options.fFrameIndex);
380 if (result != SkCodec::kSuccess) {
381 return result;
382 }
383
Nigel Tao0185b952018-11-08 10:47:24 +1100384 fSpySampler.reset();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400385 fIncrDecDst = static_cast<uint8_t*>(dst);
386 fIncrDecHaveFrameConfig = false;
387 fIncrDecRowBytes = rowBytes;
Nigel Tao0185b952018-11-08 10:47:24 +1100388 fSwizzler = nullptr;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400389
390 return SkCodec::kSuccess;
391}
392
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500393static bool independent_frame(SkCodec* codec, int frameIndex) {
394 if (frameIndex == 0) {
395 return true;
396 }
397
398 SkCodec::FrameInfo frameInfo;
399 SkAssertResult(codec->getFrameInfo(frameIndex, &frameInfo));
400 return frameInfo.fRequiredFrame == SkCodec::kNoFrame;
401}
402
403static void blend(uint32_t* dst, const uint32_t* src, int width) {
404 while (width --> 0) {
405 if (*src != 0) {
406 *dst = *src;
407 }
408 src++;
409 dst++;
410 }
411}
412
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400413SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
414 if (!fIncrDecDst) {
415 return SkCodec::kInternalError;
416 }
417
418 if (!fIncrDecHaveFrameConfig) {
419 const char* status = this->decodeFrameConfig();
420 if (status == nullptr) {
421 // No-op.
422 } else if (status == wuffs_base__suspension__short_read) {
423 return SkCodec::kIncompleteInput;
424 } else {
425 SkCodecPrintf("decodeFrameConfig: %s", status);
426 return SkCodec::kErrorInInput;
427 }
428 fIncrDecHaveFrameConfig = true;
429 }
430
431 SkCodec::Result result = SkCodec::kSuccess;
432 const char* status = this->decodeFrame();
433 if (status == nullptr) {
434 // No-op.
435 } else if (status == wuffs_base__suspension__short_read) {
436 result = SkCodec::kIncompleteInput;
437 } else {
438 SkCodecPrintf("decodeFrame: %s", status);
439 return SkCodec::kErrorInInput;
440 }
441
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500442 const bool independent = independent_frame(this, options().fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400443 wuffs_base__rect_ie_u32 r = fFrameConfig.bounds();
Nigel Tao0185b952018-11-08 10:47:24 +1100444 if (!fSwizzler) {
445 SkIRect swizzleRect = SkIRect::MakeLTRB(r.min_incl_x, 0, r.max_excl_x, 1);
446 fSwizzler = SkSwizzler::Make(this->getEncodedInfo(), fColorTable, dstInfo(), Options(),
447 &swizzleRect);
448 fSwizzler->setSampleX(fSpySampler.sampleX());
449 fSwizzler->setSampleY(fSpySampler.sampleY());
450
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500451 if (independent) {
452 auto fillInfo = dstInfo().makeWH(fSwizzler->fillWidth(),
453 get_scaled_dimension(this->dstInfo().height(),
454 fSwizzler->sampleY()));
455 SkSampler::Fill(fillInfo, fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
456 }
Nigel Tao0185b952018-11-08 10:47:24 +1100457 }
458
459 wuffs_base__slice_u8 palette = fPixelBuffer.palette();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400460 SkASSERT(palette.len == 4 * 256);
Nigel Tao0185b952018-11-08 10:47:24 +1100461 auto proc = choose_pack_color_proc(false, dstInfo().colorType());
462 for (int i = 0; i < 256; i++) {
463 uint8_t* p = palette.ptr + 4 * i;
464 fColorTable[i] = proc(p[3], p[2], p[1], p[0]);
465 }
466
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500467 std::unique_ptr<uint8_t[]> tmpBuffer;
468 if (!independent) {
469 tmpBuffer.reset(new uint8_t[dstInfo().minRowBytes()]);
470 }
Nigel Tao0185b952018-11-08 10:47:24 +1100471 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
472 const int sampleY = fSwizzler->sampleY();
473 const int scaledHeight = get_scaled_dimension(dstInfo().height(), sampleY);
474 for (uint32_t y = r.min_incl_y; y < r.max_excl_y; y++) {
475 // In Wuffs, a paletted image is always 1 byte per pixel.
476 static constexpr size_t src_bpp = 1;
477
478 int dstY = y;
479 if (sampleY != 1) {
480 if (!fSwizzler->rowNeeded(y)) {
481 continue;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400482 }
Nigel Tao0185b952018-11-08 10:47:24 +1100483 dstY /= sampleY;
484 if (dstY >= scaledHeight) {
485 break;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400486 }
Nigel Tao0185b952018-11-08 10:47:24 +1100487 }
488
489 // We don't adjust d by (r.min_incl_x * dst_bpp) as we have already
490 // accounted for that in swizzleRect, above.
491 uint8_t* d = fIncrDecDst + (dstY * fIncrDecRowBytes);
492
493 // The Wuffs model is that the dst buffer is the image, not the frame.
494 // The expectation is that you allocate the buffer once, but re-use it
495 // for the N frames, regardless of each frame's top-left co-ordinate.
496 //
497 // To get from the start (in the X-direction) of the image to the start
498 // of the frame, we adjust s by (r.min_incl_x * src_bpp).
499 uint8_t* s = pixels.ptr + (y * pixels.stride) + (r.min_incl_x * src_bpp);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500500 if (independent) {
501 fSwizzler->swizzle(d, s);
502 } else {
503 SkASSERT(tmpBuffer.get());
504 fSwizzler->swizzle(tmpBuffer.get(), s);
505 d = SkTAddOffset<uint8_t>(d, fSwizzler->swizzleOffsetBytes());
506 const auto* swizzled = SkTAddOffset<uint32_t>(tmpBuffer.get(),
507 fSwizzler->swizzleOffsetBytes());
508 blend(reinterpret_cast<uint32_t*>(d), swizzled, fSwizzler->swizzleWidth());
509 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400510 }
511
512 // The semantics of *rowsDecoded is: say you have a 10 pixel high image
513 // (both the frame and the image). If you only decoded the first 3 rows,
514 // set this to 3, and then SkCodec (or the caller of incrementalDecode)
515 // would zero-initialize the remaining 7 (unless the memory was already
516 // zero-initialized).
517 //
518 // Now let's say that the image is still 10 pixels high, but the frame is
519 // from row 5 to 9. If you only decoded 3 rows, but you initialized the
520 // first 5, you could return 8, and the caller would zero-initialize the
521 // final 2. For GIF (where a frame can be smaller than the image and can be
522 // interlaced), we just zero-initialize all 10 rows ahead of time and
523 // return the height of the image, so the caller knows it doesn't need to
524 // do anything.
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500525 //
526 // Similarly, if the output is scaled, we zero-initialized all
527 // |scaledHeight| rows (the scaled image height), so we inform the caller
528 // that it doesn't need to do anything.
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400529 if (rowsDecoded) {
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500530 *rowsDecoded = scaledHeight;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400531 }
532
533 if (result == SkCodec::kSuccess) {
Nigel Tao0185b952018-11-08 10:47:24 +1100534 fSpySampler.reset();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400535 fIncrDecDst = nullptr;
536 fIncrDecHaveFrameConfig = false;
537 fIncrDecRowBytes = 0;
Nigel Tao0185b952018-11-08 10:47:24 +1100538 fSwizzler = nullptr;
539 } else {
540 // Make fSpySampler return whatever fSwizzler would have for fillWidth.
541 fSpySampler.fFillWidth = fSwizzler->fillWidth();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400542 }
543 return result;
544}
545
546int SkWuffsCodec::onGetFrameCount() {
547 if (!fFramesComplete) {
548 this->readFrames();
549 this->updateNumFullyReceivedFrames();
550 }
551 return fFrames.size();
552}
553
554bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
555 const SkWuffsFrame* f = this->frame(i);
556 if (!f) {
557 return false;
558 }
559 if (frameInfo) {
560 *frameInfo = f->frameInfo(static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
561 }
562 return true;
563}
564
565int SkWuffsCodec::onGetRepetitionCount() {
566 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
567 // number is how many times to play the loop. Skia's int number is how many
568 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
569 // kRepetitionCountInfinite respectively to mean loop forever.
570 uint32_t n = wuffs_gif__decoder__num_animation_loops(fDecoder.get());
571 if (n == 0) {
572 return SkCodec::kRepetitionCountInfinite;
573 }
574 n--;
575 return n < INT_MAX ? n : INT_MAX;
576}
577
Nigel Tao0185b952018-11-08 10:47:24 +1100578SkSampler* SkWuffsCodec::getSampler(bool createIfNecessary) {
579 // fIncrDst being non-nullptr means that we are between an
580 // onStartIncrementalDecode call and the matching final (successful)
581 // onIncrementalDecode call.
582 if (createIfNecessary || fIncrDecDst) {
583 return &fSpySampler;
584 }
585 return nullptr;
586}
587
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500588bool SkWuffsCodec::conversionSupported(const SkImageInfo& dst, bool srcIsOpaque, bool needsColorXform) {
589 if (!this->INHERITED::conversionSupported(dst, srcIsOpaque, needsColorXform)) {
590 return false;
591 }
592
593 switch (dst.colorType()) {
594 case kRGBA_8888_SkColorType:
595 case kBGRA_8888_SkColorType:
596 return true;
597 default:
598 // FIXME: Add skcms to support F16
599 // FIXME: Add support for 565 on the first frame
600 return false;
601 }
602}
603
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400604void SkWuffsCodec::readFrames() {
605 size_t n = fFrames.size();
606 int i = n ? n - 1 : 0;
607 if (this->seekFrame(i) != SkCodec::kSuccess) {
608 return;
609 }
610
611 // Iterate through the frames, converting from Wuffs'
612 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
613 for (; i < INT_MAX; i++) {
614 const char* status = this->decodeFrameConfig();
615 if (status == nullptr) {
616 // No-op.
617 } else if (status == wuffs_base__warning__end_of_data) {
618 break;
619 } else {
620 return;
621 }
622
623 if (static_cast<size_t>(i) < fFrames.size()) {
624 continue;
625 }
626 fFrames.emplace_back(&fFrameConfig);
627 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
628 fFrameHolder.setAlphaAndRequiredFrame(f);
629 }
630
631 fFramesComplete = true;
632}
633
634SkCodec::Result SkWuffsCodec::seekFrame(int frameIndex) {
635 if (fDecoderIsSuspended) {
636 SkCodec::Result res = this->resetDecoder();
637 if (res != SkCodec::kSuccess) {
638 return res;
639 }
640 }
641
642 uint64_t pos = 0;
643 if (frameIndex < 0) {
644 return SkCodec::kInternalError;
645 } else if (frameIndex == 0) {
646 pos = fFirstFrameIOPosition;
647 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
648 pos = fFrames[frameIndex].ioPosition();
649 } else {
650 return SkCodec::kInternalError;
651 }
652
653 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
654 return SkCodec::kInternalError;
655 }
656 const char* status = wuffs_gif__decoder__restart_frame(fDecoder.get(), frameIndex,
657 fIOBuffer.reader_io_position());
658 if (status != nullptr) {
659 return SkCodec::kInternalError;
660 }
661 return SkCodec::kSuccess;
662}
663
664// An overview of the Wuffs decoding API:
665//
666// An animated image (such as GIF) has an image header and then N frames. The
667// image header gives e.g. the overall image's width and height. Each frame
668// consists of a frame header (e.g. frame rectangle bounds, display duration)
669// and a payload (the pixels).
670//
671// In Wuffs terminology, there is one image config and then N pairs of
672// (frame_config, frame). To decode everything (without knowing N in advance)
673// sequentially:
674// - call wuffs_gif__decoder::decode_image_config
675// - while (true) {
676// - call wuffs_gif__decoder::decode_frame_config
677// - if that returned wuffs_base__warning__end_of_data, break
678// - call wuffs_gif__decoder::decode_frame
679// - }
680//
681// The first argument to each decode_foo method is the destination struct to
682// store the decoded information.
683//
684// For random (instead of sequential) access to an image's frames, call
685// wuffs_gif__decoder::restart_frame to prepare to decode the i'th frame.
686// Essentially, it restores the state to be at the top of the while loop above.
687// The wuffs_base__io_buffer's reader position will also need to be set at the
688// right point in the source data stream. The position for the i'th frame is
689// calculated by the i'th decode_frame_config call. You can only call
690// restart_frame after decode_image_config is called, explicitly or implicitly
691// (see below), as decoding a single frame might require for-all-frames
692// information like the overall image dimensions and the global palette.
693//
694// All of those decode_xxx calls are optional. For example, if
695// decode_image_config is not called, then the first decode_frame_config call
696// will implicitly parse and verify the image header, before parsing the first
697// frame's header. Similarly, you can call only decode_frame N times, without
698// calling decode_image_config or decode_frame_config, if you already know
699// metadata like N and each frame's rectangle bounds by some other means (e.g.
700// this is a first party, statically known image).
701//
702// Specifically, starting with an unknown (but re-windable) GIF image, if you
703// want to just find N (i.e. count the number of frames), you can loop calling
704// only the decode_frame_config method and avoid calling the more expensive
705// decode_frame method. In terms of the underlying GIF image format, this will
706// skip over the LZW-encoded pixel data, avoiding the costly LZW decompression.
707//
708// Those decode_xxx methods are also suspendible. They will return early (with
709// a status code that is_suspendible and therefore isn't is_complete) if there
710// isn't enough source data to complete the operation: an incremental decode.
711// Calling decode_xxx again with additional source data will resume the
712// previous operation, instead of starting a new operation. Calling decode_yyy
713// whilst decode_xxx is suspended will result in an error.
714//
715// Once an error is encountered, whether from invalid source data or from a
716// programming error such as calling decode_yyy while suspended in decode_xxx,
717// all subsequent calls will be no-ops that return an error. To reset the
718// decoder into something that does productive work, memset the entire struct
719// to zero, check the Wuffs version and then, in order to be able to call
720// restart_frame, call decode_image_config. The io_buffer and its associated
721// stream will also need to be rewound.
722
723static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
724 wuffs_base__image_config* imgcfg,
725 wuffs_base__io_buffer* b,
726 SkStream* s) {
727 memset(decoder, 0, sizeof__wuffs_gif__decoder());
728 const char* status = wuffs_gif__decoder__check_wuffs_version(
729 decoder, sizeof__wuffs_gif__decoder(), WUFFS_VERSION);
730 if (status != nullptr) {
731 SkCodecPrintf("check_wuffs_version: %s", status);
732 return SkCodec::kInternalError;
733 }
734 while (true) {
735 status = wuffs_gif__decoder__decode_image_config(decoder, imgcfg, b->reader());
736 if (status == nullptr) {
737 return SkCodec::kSuccess;
738 } else if (status != wuffs_base__suspension__short_read) {
739 SkCodecPrintf("decode_image_config: %s", status);
740 return SkCodec::kErrorInInput;
741 } else if (!fill_buffer(b, s)) {
742 return SkCodec::kIncompleteInput;
743 }
744 }
745}
746
747SkCodec::Result SkWuffsCodec::resetDecoder() {
748 if (!fStream->rewind()) {
749 return SkCodec::kInternalError;
750 }
751 fIOBuffer.meta = ((wuffs_base__io_buffer_meta){});
752
753 SkCodec::Result result =
754 reset_and_decode_image_config(fDecoder.get(), nullptr, &fIOBuffer, fStream.get());
755 if (result == SkCodec::kIncompleteInput) {
756 return SkCodec::kInternalError;
757 } else if (result != SkCodec::kSuccess) {
758 return result;
759 }
760
761 fDecoderIsSuspended = false;
762 return SkCodec::kSuccess;
763}
764
765const char* SkWuffsCodec::decodeFrameConfig() {
766 while (true) {
767 const char* status = wuffs_gif__decoder__decode_frame_config(fDecoder.get(), &fFrameConfig,
768 fIOBuffer.reader());
769 if ((status == wuffs_base__suspension__short_read) &&
770 fill_buffer(&fIOBuffer, fStream.get())) {
771 continue;
772 }
773 fDecoderIsSuspended = !wuffs_base__status__is_complete(status);
774 this->updateNumFullyReceivedFrames();
775 return status;
776 }
777}
778
779const char* SkWuffsCodec::decodeFrame() {
780 while (true) {
781 const char* status =
782 wuffs_gif__decoder__decode_frame(fDecoder.get(), &fPixelBuffer, fIOBuffer.reader(),
783 ((wuffs_base__slice_u8){
784 .ptr = fWorkbufPtr.get(),
785 .len = fWorkbufLen,
786 }),
787 NULL);
788 if ((status == wuffs_base__suspension__short_read) &&
789 fill_buffer(&fIOBuffer, fStream.get())) {
790 continue;
791 }
792 fDecoderIsSuspended = !wuffs_base__status__is_complete(status);
793 this->updateNumFullyReceivedFrames();
794 return status;
795 }
796}
797
798void SkWuffsCodec::updateNumFullyReceivedFrames() {
799 // wuffs_gif__decoder__num_decoded_frames's return value, n, can change
800 // over time, both up and down, as we seek back and forth in the underlying
801 // stream. fNumFullyReceivedFrames is the highest n we've seen.
802 uint64_t n = wuffs_gif__decoder__num_decoded_frames(fDecoder.get());
803 if (fNumFullyReceivedFrames < n) {
804 fNumFullyReceivedFrames = n;
805 }
806}
807
808// -------------------------------- SkWuffsCodec.h functions
809
810bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
811 constexpr const char* gif_ptr = "GIF8";
812 constexpr size_t gif_len = 4;
813 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
814}
815
816std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
817 SkCodec::Result* result) {
818 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
819 wuffs_base__io_buffer iobuf = ((wuffs_base__io_buffer){
820 .data = ((wuffs_base__slice_u8){
821 .ptr = buffer,
822 .len = SK_WUFFS_CODEC_BUFFER_SIZE,
823 }),
824 .meta = ((wuffs_base__io_buffer_meta){}),
825 });
826 wuffs_base__image_config imgcfg = ((wuffs_base__image_config){});
827
828 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
829 // the wuffs_base__etc types, the sizeof a file format specific type like
830 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
831 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
832 // to an opaque type: a private implementation detail. The API is always
833 // "set_foo(p, etc)" and not "p->foo = etc".
834 //
835 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
836 //
837 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
838 // the struct at compile time). Instead, we use sk_malloc_canfail, with
839 // sizeof__wuffs_gif__decoder returning the appropriate value for the
840 // (statically or dynamically) linked version of the Wuffs library.
841 //
842 // As a C (not C++) library, none of the Wuffs types have constructors or
843 // destructors.
844 //
845 // In RAII style, we can still use std::unique_ptr with these pointers, but
846 // we pair the pointer with sk_free instead of C++'s delete.
847 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
848 if (!decoder_raw) {
849 *result = SkCodec::kInternalError;
850 return nullptr;
851 }
852 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
853 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
854
855 SkCodec::Result reset_result =
856 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
857 if (reset_result != SkCodec::kSuccess) {
858 *result = reset_result;
859 return nullptr;
860 }
861
862 uint32_t width = imgcfg.pixcfg.width();
863 uint32_t height = imgcfg.pixcfg.height();
864 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
865 *result = SkCodec::kInvalidInput;
866 return nullptr;
867 }
868
869 uint64_t workbuf_len = imgcfg.workbuf_len().max_incl;
870 void* workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
871 if (!workbuf_ptr_raw) {
872 *result = SkCodec::kInternalError;
873 return nullptr;
874 }
875 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
876 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
877
878 uint64_t pixbuf_len = imgcfg.pixcfg.pixbuf_len();
879 void* pixbuf_ptr_raw = pixbuf_len <= SIZE_MAX ? sk_malloc_canfail(pixbuf_len) : nullptr;
880 if (!pixbuf_ptr_raw) {
881 *result = SkCodec::kInternalError;
882 return nullptr;
883 }
884 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr(
885 reinterpret_cast<uint8_t*>(pixbuf_ptr_raw), &sk_free);
886 wuffs_base__pixel_buffer pixbuf = ((wuffs_base__pixel_buffer){});
887
888 const char* status = pixbuf.set_from_slice(&imgcfg.pixcfg, ((wuffs_base__slice_u8){
889 .ptr = pixbuf_ptr.get(),
890 .len = pixbuf_len,
891 }));
892 if (status != nullptr) {
893 SkCodecPrintf("set_from_slice: %s", status);
894 *result = SkCodec::kInternalError;
895 return nullptr;
896 }
897
898 // In Skia's API, the alpha we calculate here and return is only for the
899 // first frame.
900 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
901 : SkEncodedInfo::kBinary_Alpha;
902
903 SkEncodedInfo encodedInfo =
904 SkEncodedInfo::Make(width, height, SkEncodedInfo::kPalette_Color, alpha, 8);
905
906 *result = SkCodec::kSuccess;
907 return std::unique_ptr<SkCodec>(new SkWuffsCodec(
908 std::move(encodedInfo), std::move(stream), std::move(decoder), std::move(pixbuf_ptr),
909 std::move(workbuf_ptr), workbuf_len, imgcfg, pixbuf, iobuf));
910}