blob: 4d2bbe7e7a5bb62e0758470f358a29ee9a98d803 [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 IIIe93ec682018-10-26 09:25:51 -0400176
177 void readFrames();
178 Result seekFrame(int frameIndex);
179
180 Result resetDecoder();
181 const char* decodeFrameConfig();
182 const char* decodeFrame();
183 void updateNumFullyReceivedFrames();
184
Nigel Tao0185b952018-11-08 10:47:24 +1100185 SkWuffsSpySampler fSpySampler;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400186 SkWuffsFrameHolder fFrameHolder;
187 std::unique_ptr<SkStream> fStream;
188 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> fDecoder;
189 std::unique_ptr<uint8_t, decltype(&sk_free)> fPixbufPtr;
190 std::unique_ptr<uint8_t, decltype(&sk_free)> fWorkbufPtr;
191 size_t fWorkbufLen;
192
193 const uint64_t fFirstFrameIOPosition;
194 wuffs_base__frame_config fFrameConfig;
195 wuffs_base__pixel_buffer fPixelBuffer;
196 wuffs_base__io_buffer fIOBuffer;
197
198 // Incremental decoding state.
Nigel Tao0185b952018-11-08 10:47:24 +1100199 uint8_t* fIncrDecDst;
200 bool fIncrDecHaveFrameConfig;
201 size_t fIncrDecRowBytes;
202
203 std::unique_ptr<SkSwizzler> fSwizzler;
204 SkPMColor fColorTable[256];
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400205
206 uint64_t fNumFullyReceivedFrames;
207 std::vector<SkWuffsFrame> fFrames;
208 bool fFramesComplete;
209
210 // If calling an fDecoder method returns an incomplete status, then
211 // fDecoder is suspended in a coroutine (i.e. waiting on I/O or halted on a
212 // non-recoverable error). To keep its internal proof-of-safety invariants
213 // consistent, there's only two things you can safely do with a suspended
214 // Wuffs object: resume the coroutine, or reset all state (memset to zero
215 // and start again).
216 //
217 // If fDecoderIsSuspended, and we aren't sure that we're going to resume
218 // the coroutine, then we will need to call this->resetDecoder before
219 // calling other fDecoder methods.
220 bool fDecoderIsSuspended;
221
222 uint8_t fBuffer[SK_WUFFS_CODEC_BUFFER_SIZE];
223
224 typedef SkCodec INHERITED;
225};
226
227// -------------------------------- SkWuffsFrame implementation
228
229SkWuffsFrame::SkWuffsFrame(wuffs_base__frame_config* fc)
230 : INHERITED(fc->index()),
231 fIOPosition(fc->io_position()),
232 fReportedAlpha(wuffs_blend_to_skia_alpha(fc->blend())) {
233 wuffs_base__rect_ie_u32 r = fc->bounds();
234 this->setXYWH(r.min_incl_x, r.min_incl_y, r.width(), r.height());
235 this->setDisposalMethod(wuffs_disposal_to_skia_disposal(fc->disposal()));
236 this->setDuration(fc->duration() / WUFFS_BASE__FLICKS_PER_MILLISECOND);
237 this->setBlend(wuffs_blend_to_skia_blend(fc->blend()));
238}
239
240SkCodec::FrameInfo SkWuffsFrame::frameInfo(bool fullyReceived) const {
241 return ((SkCodec::FrameInfo){
242 .fRequiredFrame = getRequiredFrame(),
243 .fDuration = getDuration(),
244 .fFullyReceived = fullyReceived,
245 .fAlphaType = hasAlpha() ? kUnpremul_SkAlphaType : kOpaque_SkAlphaType,
246 .fDisposalMethod = getDisposalMethod(),
247 });
248}
249
250uint64_t SkWuffsFrame::ioPosition() const {
251 return fIOPosition;
252}
253
254SkEncodedInfo::Alpha SkWuffsFrame::onReportedAlpha() const {
255 return fReportedAlpha;
256}
257
258// -------------------------------- SkWuffsFrameHolder implementation
259
260void SkWuffsFrameHolder::init(SkWuffsCodec* codec, int width, int height) {
261 fCodec = codec;
262 // Initialize SkFrameHolder's (the superclass) fields.
263 fScreenWidth = width;
264 fScreenHeight = height;
265}
266
267const SkFrame* SkWuffsFrameHolder::onGetFrame(int i) const {
268 return fCodec->frame(i);
269};
270
Nigel Tao0185b952018-11-08 10:47:24 +1100271// -------------------------------- SkWuffsSpySampler implementation
272
273void SkWuffsSpySampler::reset() {
274 fFillWidth = 0;
275 fSampleX = 1;
276 this->setSampleY(1);
277}
278
279int SkWuffsSpySampler::sampleX() const {
280 return fSampleX;
281}
282
283int SkWuffsSpySampler::fillWidth() const {
284 return fFillWidth;
285}
286
287int SkWuffsSpySampler::onSetSampleX(int sampleX) {
288 fSampleX = sampleX;
289 return get_scaled_dimension(fImageWidth, sampleX);
290}
291
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400292// -------------------------------- SkWuffsCodec implementation
293
294SkWuffsCodec::SkWuffsCodec(SkEncodedInfo&& encodedInfo,
295 std::unique_ptr<SkStream> stream,
296 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> dec,
297 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr,
298 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr,
299 size_t workbuf_len,
300 wuffs_base__image_config imgcfg,
301 wuffs_base__pixel_buffer pixbuf,
302 wuffs_base__io_buffer iobuf)
303 : INHERITED(std::move(encodedInfo),
304 skcms_PixelFormat_RGBA_8888,
305 // Pass a nullptr SkStream to the SkCodec constructor. We
306 // manage the stream ourselves, as the default SkCodec behavior
307 // is too trigger-happy on rewinding the stream.
308 nullptr),
Nigel Tao0185b952018-11-08 10:47:24 +1100309 fSpySampler(imgcfg.pixcfg.width()),
310 fFrameHolder(),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400311 fStream(std::move(stream)),
312 fDecoder(std::move(dec)),
313 fPixbufPtr(std::move(pixbuf_ptr)),
314 fWorkbufPtr(std::move(workbuf_ptr)),
315 fWorkbufLen(workbuf_len),
316 fFirstFrameIOPosition(imgcfg.first_frame_io_position()),
317 fFrameConfig((wuffs_base__frame_config){}),
318 fPixelBuffer(pixbuf),
319 fIOBuffer((wuffs_base__io_buffer){}),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400320 fIncrDecDst(nullptr),
321 fIncrDecHaveFrameConfig(false),
322 fIncrDecRowBytes(0),
Nigel Tao0185b952018-11-08 10:47:24 +1100323 fSwizzler(nullptr),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400324 fNumFullyReceivedFrames(0),
325 fFramesComplete(false),
326 fDecoderIsSuspended(false) {
327 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
Nigel Tao0185b952018-11-08 10:47:24 +1100328 sk_memset32(fColorTable, 0, SK_ARRAY_COUNT(fColorTable));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400329
330 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
331 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
332 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
333 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
334 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
335 fIOBuffer = ((wuffs_base__io_buffer){
336 .data = ((wuffs_base__slice_u8){
337 .ptr = fBuffer,
338 .len = SK_WUFFS_CODEC_BUFFER_SIZE,
339 }),
340 .meta = iobuf.meta,
341 });
342}
343
344const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
345 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
346 return &fFrames[i];
347 }
348 return nullptr;
349}
350
351SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
352 return SkEncodedImageFormat::kGIF;
353}
354
355SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
356 void* dst,
357 size_t rowBytes,
358 const Options& options,
359 int* rowsDecoded) {
360 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
361 if (result != kSuccess) {
362 return result;
363 }
364 return this->onIncrementalDecode(rowsDecoded);
365}
366
367const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
368 return &fFrameHolder;
369}
370
371SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
372 void* dst,
373 size_t rowBytes,
374 const SkCodec::Options& options) {
375 if (options.fSubset) {
376 return SkCodec::kUnimplemented;
377 }
378 SkCodec::Result result = this->seekFrame(options.fFrameIndex);
379 if (result != SkCodec::kSuccess) {
380 return result;
381 }
382
Nigel Tao0185b952018-11-08 10:47:24 +1100383 fSpySampler.reset();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400384 fIncrDecDst = static_cast<uint8_t*>(dst);
385 fIncrDecHaveFrameConfig = false;
386 fIncrDecRowBytes = rowBytes;
Nigel Tao0185b952018-11-08 10:47:24 +1100387 fSwizzler = nullptr;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400388
389 return SkCodec::kSuccess;
390}
391
392SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
393 if (!fIncrDecDst) {
394 return SkCodec::kInternalError;
395 }
396
397 if (!fIncrDecHaveFrameConfig) {
398 const char* status = this->decodeFrameConfig();
399 if (status == nullptr) {
400 // No-op.
401 } else if (status == wuffs_base__suspension__short_read) {
402 return SkCodec::kIncompleteInput;
403 } else {
404 SkCodecPrintf("decodeFrameConfig: %s", status);
405 return SkCodec::kErrorInInput;
406 }
407 fIncrDecHaveFrameConfig = true;
408 }
409
410 SkCodec::Result result = SkCodec::kSuccess;
411 const char* status = this->decodeFrame();
412 if (status == nullptr) {
413 // No-op.
414 } else if (status == wuffs_base__suspension__short_read) {
415 result = SkCodec::kIncompleteInput;
416 } else {
417 SkCodecPrintf("decodeFrame: %s", status);
418 return SkCodec::kErrorInInput;
419 }
420
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400421 wuffs_base__rect_ie_u32 r = fFrameConfig.bounds();
Nigel Tao0185b952018-11-08 10:47:24 +1100422 if (!fSwizzler) {
423 SkIRect swizzleRect = SkIRect::MakeLTRB(r.min_incl_x, 0, r.max_excl_x, 1);
424 fSwizzler = SkSwizzler::Make(this->getEncodedInfo(), fColorTable, dstInfo(), Options(),
425 &swizzleRect);
426 fSwizzler->setSampleX(fSpySampler.sampleX());
427 fSwizzler->setSampleY(fSpySampler.sampleY());
428
429 auto fillInfo = dstInfo().makeWH(
430 fSwizzler->fillWidth(), get_scaled_dimension(dstInfo().height(), fSwizzler->sampleY()));
431 SkSampler::Fill(fillInfo, fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
432 }
433
434 wuffs_base__slice_u8 palette = fPixelBuffer.palette();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400435 SkASSERT(palette.len == 4 * 256);
Nigel Tao0185b952018-11-08 10:47:24 +1100436 auto proc = choose_pack_color_proc(false, dstInfo().colorType());
437 for (int i = 0; i < 256; i++) {
438 uint8_t* p = palette.ptr + 4 * i;
439 fColorTable[i] = proc(p[3], p[2], p[1], p[0]);
440 }
441
442 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
443 const int sampleY = fSwizzler->sampleY();
444 const int scaledHeight = get_scaled_dimension(dstInfo().height(), sampleY);
445 for (uint32_t y = r.min_incl_y; y < r.max_excl_y; y++) {
446 // In Wuffs, a paletted image is always 1 byte per pixel.
447 static constexpr size_t src_bpp = 1;
448
449 int dstY = y;
450 if (sampleY != 1) {
451 if (!fSwizzler->rowNeeded(y)) {
452 continue;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400453 }
Nigel Tao0185b952018-11-08 10:47:24 +1100454 dstY /= sampleY;
455 if (dstY >= scaledHeight) {
456 break;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400457 }
Nigel Tao0185b952018-11-08 10:47:24 +1100458 }
459
460 // We don't adjust d by (r.min_incl_x * dst_bpp) as we have already
461 // accounted for that in swizzleRect, above.
462 uint8_t* d = fIncrDecDst + (dstY * fIncrDecRowBytes);
463
464 // The Wuffs model is that the dst buffer is the image, not the frame.
465 // The expectation is that you allocate the buffer once, but re-use it
466 // for the N frames, regardless of each frame's top-left co-ordinate.
467 //
468 // To get from the start (in the X-direction) of the image to the start
469 // of the frame, we adjust s by (r.min_incl_x * src_bpp).
470 uint8_t* s = pixels.ptr + (y * pixels.stride) + (r.min_incl_x * src_bpp);
471 fSwizzler->swizzle(d, s);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400472 }
473
474 // The semantics of *rowsDecoded is: say you have a 10 pixel high image
475 // (both the frame and the image). If you only decoded the first 3 rows,
476 // set this to 3, and then SkCodec (or the caller of incrementalDecode)
477 // would zero-initialize the remaining 7 (unless the memory was already
478 // zero-initialized).
479 //
480 // Now let's say that the image is still 10 pixels high, but the frame is
481 // from row 5 to 9. If you only decoded 3 rows, but you initialized the
482 // first 5, you could return 8, and the caller would zero-initialize the
483 // final 2. For GIF (where a frame can be smaller than the image and can be
484 // interlaced), we just zero-initialize all 10 rows ahead of time and
485 // return the height of the image, so the caller knows it doesn't need to
486 // do anything.
487 if (rowsDecoded) {
488 *rowsDecoded = static_cast<int>(fPixelBuffer.pixcfg.height());
489 }
490
491 if (result == SkCodec::kSuccess) {
Nigel Tao0185b952018-11-08 10:47:24 +1100492 fSpySampler.reset();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400493 fIncrDecDst = nullptr;
494 fIncrDecHaveFrameConfig = false;
495 fIncrDecRowBytes = 0;
Nigel Tao0185b952018-11-08 10:47:24 +1100496 fSwizzler = nullptr;
497 } else {
498 // Make fSpySampler return whatever fSwizzler would have for fillWidth.
499 fSpySampler.fFillWidth = fSwizzler->fillWidth();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400500 }
501 return result;
502}
503
504int SkWuffsCodec::onGetFrameCount() {
505 if (!fFramesComplete) {
506 this->readFrames();
507 this->updateNumFullyReceivedFrames();
508 }
509 return fFrames.size();
510}
511
512bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
513 const SkWuffsFrame* f = this->frame(i);
514 if (!f) {
515 return false;
516 }
517 if (frameInfo) {
518 *frameInfo = f->frameInfo(static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
519 }
520 return true;
521}
522
523int SkWuffsCodec::onGetRepetitionCount() {
524 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
525 // number is how many times to play the loop. Skia's int number is how many
526 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
527 // kRepetitionCountInfinite respectively to mean loop forever.
528 uint32_t n = wuffs_gif__decoder__num_animation_loops(fDecoder.get());
529 if (n == 0) {
530 return SkCodec::kRepetitionCountInfinite;
531 }
532 n--;
533 return n < INT_MAX ? n : INT_MAX;
534}
535
Nigel Tao0185b952018-11-08 10:47:24 +1100536SkSampler* SkWuffsCodec::getSampler(bool createIfNecessary) {
537 // fIncrDst being non-nullptr means that we are between an
538 // onStartIncrementalDecode call and the matching final (successful)
539 // onIncrementalDecode call.
540 if (createIfNecessary || fIncrDecDst) {
541 return &fSpySampler;
542 }
543 return nullptr;
544}
545
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400546void SkWuffsCodec::readFrames() {
547 size_t n = fFrames.size();
548 int i = n ? n - 1 : 0;
549 if (this->seekFrame(i) != SkCodec::kSuccess) {
550 return;
551 }
552
553 // Iterate through the frames, converting from Wuffs'
554 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
555 for (; i < INT_MAX; i++) {
556 const char* status = this->decodeFrameConfig();
557 if (status == nullptr) {
558 // No-op.
559 } else if (status == wuffs_base__warning__end_of_data) {
560 break;
561 } else {
562 return;
563 }
564
565 if (static_cast<size_t>(i) < fFrames.size()) {
566 continue;
567 }
568 fFrames.emplace_back(&fFrameConfig);
569 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
570 fFrameHolder.setAlphaAndRequiredFrame(f);
571 }
572
573 fFramesComplete = true;
574}
575
576SkCodec::Result SkWuffsCodec::seekFrame(int frameIndex) {
577 if (fDecoderIsSuspended) {
578 SkCodec::Result res = this->resetDecoder();
579 if (res != SkCodec::kSuccess) {
580 return res;
581 }
582 }
583
584 uint64_t pos = 0;
585 if (frameIndex < 0) {
586 return SkCodec::kInternalError;
587 } else if (frameIndex == 0) {
588 pos = fFirstFrameIOPosition;
589 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
590 pos = fFrames[frameIndex].ioPosition();
591 } else {
592 return SkCodec::kInternalError;
593 }
594
595 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
596 return SkCodec::kInternalError;
597 }
598 const char* status = wuffs_gif__decoder__restart_frame(fDecoder.get(), frameIndex,
599 fIOBuffer.reader_io_position());
600 if (status != nullptr) {
601 return SkCodec::kInternalError;
602 }
603 return SkCodec::kSuccess;
604}
605
606// An overview of the Wuffs decoding API:
607//
608// An animated image (such as GIF) has an image header and then N frames. The
609// image header gives e.g. the overall image's width and height. Each frame
610// consists of a frame header (e.g. frame rectangle bounds, display duration)
611// and a payload (the pixels).
612//
613// In Wuffs terminology, there is one image config and then N pairs of
614// (frame_config, frame). To decode everything (without knowing N in advance)
615// sequentially:
616// - call wuffs_gif__decoder::decode_image_config
617// - while (true) {
618// - call wuffs_gif__decoder::decode_frame_config
619// - if that returned wuffs_base__warning__end_of_data, break
620// - call wuffs_gif__decoder::decode_frame
621// - }
622//
623// The first argument to each decode_foo method is the destination struct to
624// store the decoded information.
625//
626// For random (instead of sequential) access to an image's frames, call
627// wuffs_gif__decoder::restart_frame to prepare to decode the i'th frame.
628// Essentially, it restores the state to be at the top of the while loop above.
629// The wuffs_base__io_buffer's reader position will also need to be set at the
630// right point in the source data stream. The position for the i'th frame is
631// calculated by the i'th decode_frame_config call. You can only call
632// restart_frame after decode_image_config is called, explicitly or implicitly
633// (see below), as decoding a single frame might require for-all-frames
634// information like the overall image dimensions and the global palette.
635//
636// All of those decode_xxx calls are optional. For example, if
637// decode_image_config is not called, then the first decode_frame_config call
638// will implicitly parse and verify the image header, before parsing the first
639// frame's header. Similarly, you can call only decode_frame N times, without
640// calling decode_image_config or decode_frame_config, if you already know
641// metadata like N and each frame's rectangle bounds by some other means (e.g.
642// this is a first party, statically known image).
643//
644// Specifically, starting with an unknown (but re-windable) GIF image, if you
645// want to just find N (i.e. count the number of frames), you can loop calling
646// only the decode_frame_config method and avoid calling the more expensive
647// decode_frame method. In terms of the underlying GIF image format, this will
648// skip over the LZW-encoded pixel data, avoiding the costly LZW decompression.
649//
650// Those decode_xxx methods are also suspendible. They will return early (with
651// a status code that is_suspendible and therefore isn't is_complete) if there
652// isn't enough source data to complete the operation: an incremental decode.
653// Calling decode_xxx again with additional source data will resume the
654// previous operation, instead of starting a new operation. Calling decode_yyy
655// whilst decode_xxx is suspended will result in an error.
656//
657// Once an error is encountered, whether from invalid source data or from a
658// programming error such as calling decode_yyy while suspended in decode_xxx,
659// all subsequent calls will be no-ops that return an error. To reset the
660// decoder into something that does productive work, memset the entire struct
661// to zero, check the Wuffs version and then, in order to be able to call
662// restart_frame, call decode_image_config. The io_buffer and its associated
663// stream will also need to be rewound.
664
665static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
666 wuffs_base__image_config* imgcfg,
667 wuffs_base__io_buffer* b,
668 SkStream* s) {
669 memset(decoder, 0, sizeof__wuffs_gif__decoder());
670 const char* status = wuffs_gif__decoder__check_wuffs_version(
671 decoder, sizeof__wuffs_gif__decoder(), WUFFS_VERSION);
672 if (status != nullptr) {
673 SkCodecPrintf("check_wuffs_version: %s", status);
674 return SkCodec::kInternalError;
675 }
676 while (true) {
677 status = wuffs_gif__decoder__decode_image_config(decoder, imgcfg, b->reader());
678 if (status == nullptr) {
679 return SkCodec::kSuccess;
680 } else if (status != wuffs_base__suspension__short_read) {
681 SkCodecPrintf("decode_image_config: %s", status);
682 return SkCodec::kErrorInInput;
683 } else if (!fill_buffer(b, s)) {
684 return SkCodec::kIncompleteInput;
685 }
686 }
687}
688
689SkCodec::Result SkWuffsCodec::resetDecoder() {
690 if (!fStream->rewind()) {
691 return SkCodec::kInternalError;
692 }
693 fIOBuffer.meta = ((wuffs_base__io_buffer_meta){});
694
695 SkCodec::Result result =
696 reset_and_decode_image_config(fDecoder.get(), nullptr, &fIOBuffer, fStream.get());
697 if (result == SkCodec::kIncompleteInput) {
698 return SkCodec::kInternalError;
699 } else if (result != SkCodec::kSuccess) {
700 return result;
701 }
702
703 fDecoderIsSuspended = false;
704 return SkCodec::kSuccess;
705}
706
707const char* SkWuffsCodec::decodeFrameConfig() {
708 while (true) {
709 const char* status = wuffs_gif__decoder__decode_frame_config(fDecoder.get(), &fFrameConfig,
710 fIOBuffer.reader());
711 if ((status == wuffs_base__suspension__short_read) &&
712 fill_buffer(&fIOBuffer, fStream.get())) {
713 continue;
714 }
715 fDecoderIsSuspended = !wuffs_base__status__is_complete(status);
716 this->updateNumFullyReceivedFrames();
717 return status;
718 }
719}
720
721const char* SkWuffsCodec::decodeFrame() {
722 while (true) {
723 const char* status =
724 wuffs_gif__decoder__decode_frame(fDecoder.get(), &fPixelBuffer, fIOBuffer.reader(),
725 ((wuffs_base__slice_u8){
726 .ptr = fWorkbufPtr.get(),
727 .len = fWorkbufLen,
728 }),
729 NULL);
730 if ((status == wuffs_base__suspension__short_read) &&
731 fill_buffer(&fIOBuffer, fStream.get())) {
732 continue;
733 }
734 fDecoderIsSuspended = !wuffs_base__status__is_complete(status);
735 this->updateNumFullyReceivedFrames();
736 return status;
737 }
738}
739
740void SkWuffsCodec::updateNumFullyReceivedFrames() {
741 // wuffs_gif__decoder__num_decoded_frames's return value, n, can change
742 // over time, both up and down, as we seek back and forth in the underlying
743 // stream. fNumFullyReceivedFrames is the highest n we've seen.
744 uint64_t n = wuffs_gif__decoder__num_decoded_frames(fDecoder.get());
745 if (fNumFullyReceivedFrames < n) {
746 fNumFullyReceivedFrames = n;
747 }
748}
749
750// -------------------------------- SkWuffsCodec.h functions
751
752bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
753 constexpr const char* gif_ptr = "GIF8";
754 constexpr size_t gif_len = 4;
755 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
756}
757
758std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
759 SkCodec::Result* result) {
760 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
761 wuffs_base__io_buffer iobuf = ((wuffs_base__io_buffer){
762 .data = ((wuffs_base__slice_u8){
763 .ptr = buffer,
764 .len = SK_WUFFS_CODEC_BUFFER_SIZE,
765 }),
766 .meta = ((wuffs_base__io_buffer_meta){}),
767 });
768 wuffs_base__image_config imgcfg = ((wuffs_base__image_config){});
769
770 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
771 // the wuffs_base__etc types, the sizeof a file format specific type like
772 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
773 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
774 // to an opaque type: a private implementation detail. The API is always
775 // "set_foo(p, etc)" and not "p->foo = etc".
776 //
777 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
778 //
779 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
780 // the struct at compile time). Instead, we use sk_malloc_canfail, with
781 // sizeof__wuffs_gif__decoder returning the appropriate value for the
782 // (statically or dynamically) linked version of the Wuffs library.
783 //
784 // As a C (not C++) library, none of the Wuffs types have constructors or
785 // destructors.
786 //
787 // In RAII style, we can still use std::unique_ptr with these pointers, but
788 // we pair the pointer with sk_free instead of C++'s delete.
789 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
790 if (!decoder_raw) {
791 *result = SkCodec::kInternalError;
792 return nullptr;
793 }
794 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
795 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
796
797 SkCodec::Result reset_result =
798 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
799 if (reset_result != SkCodec::kSuccess) {
800 *result = reset_result;
801 return nullptr;
802 }
803
804 uint32_t width = imgcfg.pixcfg.width();
805 uint32_t height = imgcfg.pixcfg.height();
806 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
807 *result = SkCodec::kInvalidInput;
808 return nullptr;
809 }
810
811 uint64_t workbuf_len = imgcfg.workbuf_len().max_incl;
812 void* workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
813 if (!workbuf_ptr_raw) {
814 *result = SkCodec::kInternalError;
815 return nullptr;
816 }
817 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
818 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
819
820 uint64_t pixbuf_len = imgcfg.pixcfg.pixbuf_len();
821 void* pixbuf_ptr_raw = pixbuf_len <= SIZE_MAX ? sk_malloc_canfail(pixbuf_len) : nullptr;
822 if (!pixbuf_ptr_raw) {
823 *result = SkCodec::kInternalError;
824 return nullptr;
825 }
826 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr(
827 reinterpret_cast<uint8_t*>(pixbuf_ptr_raw), &sk_free);
828 wuffs_base__pixel_buffer pixbuf = ((wuffs_base__pixel_buffer){});
829
830 const char* status = pixbuf.set_from_slice(&imgcfg.pixcfg, ((wuffs_base__slice_u8){
831 .ptr = pixbuf_ptr.get(),
832 .len = pixbuf_len,
833 }));
834 if (status != nullptr) {
835 SkCodecPrintf("set_from_slice: %s", status);
836 *result = SkCodec::kInternalError;
837 return nullptr;
838 }
839
840 // In Skia's API, the alpha we calculate here and return is only for the
841 // first frame.
842 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
843 : SkEncodedInfo::kBinary_Alpha;
844
845 SkEncodedInfo encodedInfo =
846 SkEncodedInfo::Make(width, height, SkEncodedInfo::kPalette_Color, alpha, 8);
847
848 *result = SkCodec::kSuccess;
849 return std::unique_ptr<SkCodec>(new SkWuffsCodec(
850 std::move(encodedInfo), std::move(stream), std::move(decoder), std::move(pixbuf_ptr),
851 std::move(workbuf_ptr), workbuf_len, imgcfg, pixbuf, iobuf));
852}