blob: 59b53a5de7955fe803e4c8468500ca2492741315 [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;
Nigel Tao0185b952018-11-08 10:47:24 +1100201 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),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400321 fIncrDecRowBytes(0),
Nigel Tao0185b952018-11-08 10:47:24 +1100322 fSwizzler(nullptr),
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400323 fNumFullyReceivedFrames(0),
324 fFramesComplete(false),
325 fDecoderIsSuspended(false) {
326 fFrameHolder.init(this, imgcfg.pixcfg.width(), imgcfg.pixcfg.height());
Nigel Tao0185b952018-11-08 10:47:24 +1100327 sk_memset32(fColorTable, 0, SK_ARRAY_COUNT(fColorTable));
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400328
329 // Initialize fIOBuffer's fields, copying any outstanding data from iobuf to
330 // fIOBuffer, as iobuf's backing array may not be valid for the lifetime of
331 // this SkWuffsCodec object, but fIOBuffer's backing array (fBuffer) is.
332 SkASSERT(iobuf.data.len == SK_WUFFS_CODEC_BUFFER_SIZE);
333 memmove(fBuffer, iobuf.data.ptr, iobuf.meta.wi);
334 fIOBuffer = ((wuffs_base__io_buffer){
335 .data = ((wuffs_base__slice_u8){
336 .ptr = fBuffer,
337 .len = SK_WUFFS_CODEC_BUFFER_SIZE,
338 }),
339 .meta = iobuf.meta,
340 });
341}
342
343const SkWuffsFrame* SkWuffsCodec::frame(int i) const {
344 if ((0 <= i) && (static_cast<size_t>(i) < fFrames.size())) {
345 return &fFrames[i];
346 }
347 return nullptr;
348}
349
350SkEncodedImageFormat SkWuffsCodec::onGetEncodedFormat() const {
351 return SkEncodedImageFormat::kGIF;
352}
353
354SkCodec::Result SkWuffsCodec::onGetPixels(const SkImageInfo& dstInfo,
355 void* dst,
356 size_t rowBytes,
357 const Options& options,
358 int* rowsDecoded) {
359 SkCodec::Result result = this->onStartIncrementalDecode(dstInfo, dst, rowBytes, options);
360 if (result != kSuccess) {
361 return result;
362 }
363 return this->onIncrementalDecode(rowsDecoded);
364}
365
366const SkFrameHolder* SkWuffsCodec::getFrameHolder() const {
367 return &fFrameHolder;
368}
369
370SkCodec::Result SkWuffsCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
371 void* dst,
372 size_t rowBytes,
373 const SkCodec::Options& options) {
374 if (options.fSubset) {
375 return SkCodec::kUnimplemented;
376 }
377 SkCodec::Result result = this->seekFrame(options.fFrameIndex);
378 if (result != SkCodec::kSuccess) {
379 return result;
380 }
381
Nigel Tao0185b952018-11-08 10:47:24 +1100382 fSpySampler.reset();
Nigel Tao0185b952018-11-08 10:47:24 +1100383 fSwizzler = nullptr;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400384
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500385 const char* status = this->decodeFrameConfig();
386 if (status == nullptr) {
387 fIncrDecDst = static_cast<uint8_t*>(dst);
388 fIncrDecRowBytes = rowBytes;
389 return SkCodec::kSuccess;
390 } else if (status == wuffs_base__suspension__short_read) {
391 return SkCodec::kIncompleteInput;
392 } else {
393 SkCodecPrintf("decodeFrameConfig: %s", status);
394 return SkCodec::kErrorInInput;
395 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400396}
397
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500398static bool independent_frame(SkCodec* codec, int frameIndex) {
399 if (frameIndex == 0) {
400 return true;
401 }
402
403 SkCodec::FrameInfo frameInfo;
404 SkAssertResult(codec->getFrameInfo(frameIndex, &frameInfo));
405 return frameInfo.fRequiredFrame == SkCodec::kNoFrame;
406}
407
408static void blend(uint32_t* dst, const uint32_t* src, int width) {
409 while (width --> 0) {
410 if (*src != 0) {
411 *dst = *src;
412 }
413 src++;
414 dst++;
415 }
416}
417
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400418SkCodec::Result SkWuffsCodec::onIncrementalDecode(int* rowsDecoded) {
419 if (!fIncrDecDst) {
420 return SkCodec::kInternalError;
421 }
422
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500423 // In Wuffs, a paletted image is always 1 byte per pixel.
424 static constexpr size_t src_bpp = 1;
425 wuffs_base__table_u8 pixels = fPixelBuffer.plane(0);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400426
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500427 const bool independent = independent_frame(this, options().fFrameIndex);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400428 wuffs_base__rect_ie_u32 r = fFrameConfig.bounds();
Nigel Tao0185b952018-11-08 10:47:24 +1100429 if (!fSwizzler) {
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500430 auto bounds = SkIRect::MakeLTRB(r.min_incl_x, r.min_incl_y, r.max_excl_x, r.max_excl_y);
431 fSwizzler = SkSwizzler::Make(this->getEncodedInfo(), fColorTable, dstInfo(),
432 this->options(), &bounds);
Nigel Tao0185b952018-11-08 10:47:24 +1100433 fSwizzler->setSampleX(fSpySampler.sampleX());
434 fSwizzler->setSampleY(fSpySampler.sampleY());
435
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500436 // Zero-initialize wuffs' buffer covering the frame rect. This will later be used to
437 // determine how we write to the output, even if the image was incomplete. This ensures
438 // that we do not swizzle uninitialized memory.
439 for (uint32_t y = r.min_incl_y; y < r.max_excl_y; y++) {
440 uint8_t* s = pixels.ptr + (y * pixels.stride) + (r.min_incl_x * src_bpp);
441 sk_bzero(s, r.width() * src_bpp);
442 }
443
444 // If the frame rect does not fill the output, ensure that those pixels are not
445 // left uninitialized either.
446 if (independent && bounds != this->bounds()) {
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500447 auto fillInfo = dstInfo().makeWH(fSwizzler->fillWidth(),
448 get_scaled_dimension(this->dstInfo().height(),
449 fSwizzler->sampleY()));
450 SkSampler::Fill(fillInfo, fIncrDecDst, fIncrDecRowBytes, options().fZeroInitialized);
451 }
Nigel Tao0185b952018-11-08 10:47:24 +1100452 }
453
Leon Scroggins IIIcb6b8842018-12-04 13:55:13 -0500454 SkCodec::Result result = SkCodec::kSuccess;
455 const char* status = this->decodeFrame();
456 if (status != nullptr) {
457 if (status == wuffs_base__suspension__short_read) {
458 result = SkCodec::kIncompleteInput;
459 } else {
460 SkCodecPrintf("decodeFrame: %s", status);
461 result = SkCodec::kErrorInInput;
462 }
463
464 if (!independent) {
465 if (rowsDecoded) {
466 // Though no rows were written by this call, the prior frame
467 // initialized all the rows.
468 *rowsDecoded = get_scaled_dimension(this->dstInfo().height(),
469 fSwizzler->sampleY());
470 }
471 // For a dependent frame, we cannot blend the partial result, since
472 // that will overwrite the contribution from prior frames with all
473 // zeroes that were written to |pixels| above.
474 return result;
475 }
476 }
477
Nigel Tao0185b952018-11-08 10:47:24 +1100478 wuffs_base__slice_u8 palette = fPixelBuffer.palette();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400479 SkASSERT(palette.len == 4 * 256);
Nigel Tao0185b952018-11-08 10:47:24 +1100480 auto proc = choose_pack_color_proc(false, dstInfo().colorType());
481 for (int i = 0; i < 256; i++) {
482 uint8_t* p = palette.ptr + 4 * i;
483 fColorTable[i] = proc(p[3], p[2], p[1], p[0]);
484 }
485
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500486 std::unique_ptr<uint8_t[]> tmpBuffer;
487 if (!independent) {
488 tmpBuffer.reset(new uint8_t[dstInfo().minRowBytes()]);
489 }
Nigel Tao0185b952018-11-08 10:47:24 +1100490 const int sampleY = fSwizzler->sampleY();
491 const int scaledHeight = get_scaled_dimension(dstInfo().height(), sampleY);
492 for (uint32_t y = r.min_incl_y; y < r.max_excl_y; y++) {
Nigel Tao0185b952018-11-08 10:47:24 +1100493 int dstY = y;
494 if (sampleY != 1) {
495 if (!fSwizzler->rowNeeded(y)) {
496 continue;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400497 }
Nigel Tao0185b952018-11-08 10:47:24 +1100498 dstY /= sampleY;
499 if (dstY >= scaledHeight) {
500 break;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400501 }
Nigel Tao0185b952018-11-08 10:47:24 +1100502 }
503
504 // We don't adjust d by (r.min_incl_x * dst_bpp) as we have already
505 // accounted for that in swizzleRect, above.
506 uint8_t* d = fIncrDecDst + (dstY * fIncrDecRowBytes);
507
508 // The Wuffs model is that the dst buffer is the image, not the frame.
509 // The expectation is that you allocate the buffer once, but re-use it
510 // for the N frames, regardless of each frame's top-left co-ordinate.
511 //
512 // To get from the start (in the X-direction) of the image to the start
513 // of the frame, we adjust s by (r.min_incl_x * src_bpp).
514 uint8_t* s = pixels.ptr + (y * pixels.stride) + (r.min_incl_x * src_bpp);
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500515 if (independent) {
516 fSwizzler->swizzle(d, s);
517 } else {
518 SkASSERT(tmpBuffer.get());
519 fSwizzler->swizzle(tmpBuffer.get(), s);
520 d = SkTAddOffset<uint8_t>(d, fSwizzler->swizzleOffsetBytes());
521 const auto* swizzled = SkTAddOffset<uint32_t>(tmpBuffer.get(),
522 fSwizzler->swizzleOffsetBytes());
523 blend(reinterpret_cast<uint32_t*>(d), swizzled, fSwizzler->swizzleWidth());
524 }
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400525 }
526
527 // The semantics of *rowsDecoded is: say you have a 10 pixel high image
528 // (both the frame and the image). If you only decoded the first 3 rows,
529 // set this to 3, and then SkCodec (or the caller of incrementalDecode)
530 // would zero-initialize the remaining 7 (unless the memory was already
531 // zero-initialized).
532 //
533 // Now let's say that the image is still 10 pixels high, but the frame is
534 // from row 5 to 9. If you only decoded 3 rows, but you initialized the
535 // first 5, you could return 8, and the caller would zero-initialize the
536 // final 2. For GIF (where a frame can be smaller than the image and can be
537 // interlaced), we just zero-initialize all 10 rows ahead of time and
538 // return the height of the image, so the caller knows it doesn't need to
539 // do anything.
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500540 //
541 // Similarly, if the output is scaled, we zero-initialized all
542 // |scaledHeight| rows (the scaled image height), so we inform the caller
543 // that it doesn't need to do anything.
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400544 if (rowsDecoded) {
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500545 *rowsDecoded = scaledHeight;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400546 }
547
548 if (result == SkCodec::kSuccess) {
Nigel Tao0185b952018-11-08 10:47:24 +1100549 fSpySampler.reset();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400550 fIncrDecDst = nullptr;
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400551 fIncrDecRowBytes = 0;
Nigel Tao0185b952018-11-08 10:47:24 +1100552 fSwizzler = nullptr;
553 } else {
554 // Make fSpySampler return whatever fSwizzler would have for fillWidth.
555 fSpySampler.fFillWidth = fSwizzler->fillWidth();
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400556 }
557 return result;
558}
559
560int SkWuffsCodec::onGetFrameCount() {
561 if (!fFramesComplete) {
562 this->readFrames();
563 this->updateNumFullyReceivedFrames();
564 }
565 return fFrames.size();
566}
567
568bool SkWuffsCodec::onGetFrameInfo(int i, SkCodec::FrameInfo* frameInfo) const {
569 const SkWuffsFrame* f = this->frame(i);
570 if (!f) {
571 return false;
572 }
573 if (frameInfo) {
574 *frameInfo = f->frameInfo(static_cast<uint64_t>(i) < this->fNumFullyReceivedFrames);
575 }
576 return true;
577}
578
579int SkWuffsCodec::onGetRepetitionCount() {
580 // Convert from Wuffs's loop count to Skia's repeat count. Wuffs' uint32_t
581 // number is how many times to play the loop. Skia's int number is how many
582 // times to play the loop *after the first play*. Wuffs and Skia use 0 and
583 // kRepetitionCountInfinite respectively to mean loop forever.
584 uint32_t n = wuffs_gif__decoder__num_animation_loops(fDecoder.get());
585 if (n == 0) {
586 return SkCodec::kRepetitionCountInfinite;
587 }
588 n--;
589 return n < INT_MAX ? n : INT_MAX;
590}
591
Nigel Tao0185b952018-11-08 10:47:24 +1100592SkSampler* SkWuffsCodec::getSampler(bool createIfNecessary) {
593 // fIncrDst being non-nullptr means that we are between an
594 // onStartIncrementalDecode call and the matching final (successful)
595 // onIncrementalDecode call.
596 if (createIfNecessary || fIncrDecDst) {
597 return &fSpySampler;
598 }
599 return nullptr;
600}
601
Leon Scroggins III9b0ba2c2018-11-19 14:52:37 -0500602bool SkWuffsCodec::conversionSupported(const SkImageInfo& dst, bool srcIsOpaque, bool needsColorXform) {
603 if (!this->INHERITED::conversionSupported(dst, srcIsOpaque, needsColorXform)) {
604 return false;
605 }
606
607 switch (dst.colorType()) {
608 case kRGBA_8888_SkColorType:
609 case kBGRA_8888_SkColorType:
610 return true;
611 default:
612 // FIXME: Add skcms to support F16
613 // FIXME: Add support for 565 on the first frame
614 return false;
615 }
616}
617
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -0400618void SkWuffsCodec::readFrames() {
619 size_t n = fFrames.size();
620 int i = n ? n - 1 : 0;
621 if (this->seekFrame(i) != SkCodec::kSuccess) {
622 return;
623 }
624
625 // Iterate through the frames, converting from Wuffs'
626 // wuffs_base__frame_config type to Skia's SkWuffsFrame type.
627 for (; i < INT_MAX; i++) {
628 const char* status = this->decodeFrameConfig();
629 if (status == nullptr) {
630 // No-op.
631 } else if (status == wuffs_base__warning__end_of_data) {
632 break;
633 } else {
634 return;
635 }
636
637 if (static_cast<size_t>(i) < fFrames.size()) {
638 continue;
639 }
640 fFrames.emplace_back(&fFrameConfig);
641 SkWuffsFrame* f = &fFrames[fFrames.size() - 1];
642 fFrameHolder.setAlphaAndRequiredFrame(f);
643 }
644
645 fFramesComplete = true;
646}
647
648SkCodec::Result SkWuffsCodec::seekFrame(int frameIndex) {
649 if (fDecoderIsSuspended) {
650 SkCodec::Result res = this->resetDecoder();
651 if (res != SkCodec::kSuccess) {
652 return res;
653 }
654 }
655
656 uint64_t pos = 0;
657 if (frameIndex < 0) {
658 return SkCodec::kInternalError;
659 } else if (frameIndex == 0) {
660 pos = fFirstFrameIOPosition;
661 } else if (static_cast<size_t>(frameIndex) < fFrames.size()) {
662 pos = fFrames[frameIndex].ioPosition();
663 } else {
664 return SkCodec::kInternalError;
665 }
666
667 if (!seek_buffer(&fIOBuffer, fStream.get(), pos)) {
668 return SkCodec::kInternalError;
669 }
670 const char* status = wuffs_gif__decoder__restart_frame(fDecoder.get(), frameIndex,
671 fIOBuffer.reader_io_position());
672 if (status != nullptr) {
673 return SkCodec::kInternalError;
674 }
675 return SkCodec::kSuccess;
676}
677
678// An overview of the Wuffs decoding API:
679//
680// An animated image (such as GIF) has an image header and then N frames. The
681// image header gives e.g. the overall image's width and height. Each frame
682// consists of a frame header (e.g. frame rectangle bounds, display duration)
683// and a payload (the pixels).
684//
685// In Wuffs terminology, there is one image config and then N pairs of
686// (frame_config, frame). To decode everything (without knowing N in advance)
687// sequentially:
688// - call wuffs_gif__decoder::decode_image_config
689// - while (true) {
690// - call wuffs_gif__decoder::decode_frame_config
691// - if that returned wuffs_base__warning__end_of_data, break
692// - call wuffs_gif__decoder::decode_frame
693// - }
694//
695// The first argument to each decode_foo method is the destination struct to
696// store the decoded information.
697//
698// For random (instead of sequential) access to an image's frames, call
699// wuffs_gif__decoder::restart_frame to prepare to decode the i'th frame.
700// Essentially, it restores the state to be at the top of the while loop above.
701// The wuffs_base__io_buffer's reader position will also need to be set at the
702// right point in the source data stream. The position for the i'th frame is
703// calculated by the i'th decode_frame_config call. You can only call
704// restart_frame after decode_image_config is called, explicitly or implicitly
705// (see below), as decoding a single frame might require for-all-frames
706// information like the overall image dimensions and the global palette.
707//
708// All of those decode_xxx calls are optional. For example, if
709// decode_image_config is not called, then the first decode_frame_config call
710// will implicitly parse and verify the image header, before parsing the first
711// frame's header. Similarly, you can call only decode_frame N times, without
712// calling decode_image_config or decode_frame_config, if you already know
713// metadata like N and each frame's rectangle bounds by some other means (e.g.
714// this is a first party, statically known image).
715//
716// Specifically, starting with an unknown (but re-windable) GIF image, if you
717// want to just find N (i.e. count the number of frames), you can loop calling
718// only the decode_frame_config method and avoid calling the more expensive
719// decode_frame method. In terms of the underlying GIF image format, this will
720// skip over the LZW-encoded pixel data, avoiding the costly LZW decompression.
721//
722// Those decode_xxx methods are also suspendible. They will return early (with
723// a status code that is_suspendible and therefore isn't is_complete) if there
724// isn't enough source data to complete the operation: an incremental decode.
725// Calling decode_xxx again with additional source data will resume the
726// previous operation, instead of starting a new operation. Calling decode_yyy
727// whilst decode_xxx is suspended will result in an error.
728//
729// Once an error is encountered, whether from invalid source data or from a
730// programming error such as calling decode_yyy while suspended in decode_xxx,
731// all subsequent calls will be no-ops that return an error. To reset the
732// decoder into something that does productive work, memset the entire struct
733// to zero, check the Wuffs version and then, in order to be able to call
734// restart_frame, call decode_image_config. The io_buffer and its associated
735// stream will also need to be rewound.
736
737static SkCodec::Result reset_and_decode_image_config(wuffs_gif__decoder* decoder,
738 wuffs_base__image_config* imgcfg,
739 wuffs_base__io_buffer* b,
740 SkStream* s) {
741 memset(decoder, 0, sizeof__wuffs_gif__decoder());
742 const char* status = wuffs_gif__decoder__check_wuffs_version(
743 decoder, sizeof__wuffs_gif__decoder(), WUFFS_VERSION);
744 if (status != nullptr) {
745 SkCodecPrintf("check_wuffs_version: %s", status);
746 return SkCodec::kInternalError;
747 }
748 while (true) {
749 status = wuffs_gif__decoder__decode_image_config(decoder, imgcfg, b->reader());
750 if (status == nullptr) {
751 return SkCodec::kSuccess;
752 } else if (status != wuffs_base__suspension__short_read) {
753 SkCodecPrintf("decode_image_config: %s", status);
754 return SkCodec::kErrorInInput;
755 } else if (!fill_buffer(b, s)) {
756 return SkCodec::kIncompleteInput;
757 }
758 }
759}
760
761SkCodec::Result SkWuffsCodec::resetDecoder() {
762 if (!fStream->rewind()) {
763 return SkCodec::kInternalError;
764 }
765 fIOBuffer.meta = ((wuffs_base__io_buffer_meta){});
766
767 SkCodec::Result result =
768 reset_and_decode_image_config(fDecoder.get(), nullptr, &fIOBuffer, fStream.get());
769 if (result == SkCodec::kIncompleteInput) {
770 return SkCodec::kInternalError;
771 } else if (result != SkCodec::kSuccess) {
772 return result;
773 }
774
775 fDecoderIsSuspended = false;
776 return SkCodec::kSuccess;
777}
778
779const char* SkWuffsCodec::decodeFrameConfig() {
780 while (true) {
781 const char* status = wuffs_gif__decoder__decode_frame_config(fDecoder.get(), &fFrameConfig,
782 fIOBuffer.reader());
783 if ((status == wuffs_base__suspension__short_read) &&
784 fill_buffer(&fIOBuffer, fStream.get())) {
785 continue;
786 }
787 fDecoderIsSuspended = !wuffs_base__status__is_complete(status);
788 this->updateNumFullyReceivedFrames();
789 return status;
790 }
791}
792
793const char* SkWuffsCodec::decodeFrame() {
794 while (true) {
795 const char* status =
796 wuffs_gif__decoder__decode_frame(fDecoder.get(), &fPixelBuffer, fIOBuffer.reader(),
797 ((wuffs_base__slice_u8){
798 .ptr = fWorkbufPtr.get(),
799 .len = fWorkbufLen,
800 }),
801 NULL);
802 if ((status == wuffs_base__suspension__short_read) &&
803 fill_buffer(&fIOBuffer, fStream.get())) {
804 continue;
805 }
806 fDecoderIsSuspended = !wuffs_base__status__is_complete(status);
807 this->updateNumFullyReceivedFrames();
808 return status;
809 }
810}
811
812void SkWuffsCodec::updateNumFullyReceivedFrames() {
813 // wuffs_gif__decoder__num_decoded_frames's return value, n, can change
814 // over time, both up and down, as we seek back and forth in the underlying
815 // stream. fNumFullyReceivedFrames is the highest n we've seen.
816 uint64_t n = wuffs_gif__decoder__num_decoded_frames(fDecoder.get());
817 if (fNumFullyReceivedFrames < n) {
818 fNumFullyReceivedFrames = n;
819 }
820}
821
822// -------------------------------- SkWuffsCodec.h functions
823
824bool SkWuffsCodec_IsFormat(const void* buf, size_t bytesRead) {
825 constexpr const char* gif_ptr = "GIF8";
826 constexpr size_t gif_len = 4;
827 return (bytesRead >= gif_len) && (memcmp(buf, gif_ptr, gif_len) == 0);
828}
829
830std::unique_ptr<SkCodec> SkWuffsCodec_MakeFromStream(std::unique_ptr<SkStream> stream,
831 SkCodec::Result* result) {
832 uint8_t buffer[SK_WUFFS_CODEC_BUFFER_SIZE];
833 wuffs_base__io_buffer iobuf = ((wuffs_base__io_buffer){
834 .data = ((wuffs_base__slice_u8){
835 .ptr = buffer,
836 .len = SK_WUFFS_CODEC_BUFFER_SIZE,
837 }),
838 .meta = ((wuffs_base__io_buffer_meta){}),
839 });
840 wuffs_base__image_config imgcfg = ((wuffs_base__image_config){});
841
842 // Wuffs is primarily a C library, not a C++ one. Furthermore, outside of
843 // the wuffs_base__etc types, the sizeof a file format specific type like
844 // GIF's wuffs_gif__decoder can vary between Wuffs versions. If p is of
845 // type wuffs_gif__decoder*, then the supported API treats p as a pointer
846 // to an opaque type: a private implementation detail. The API is always
847 // "set_foo(p, etc)" and not "p->foo = etc".
848 //
849 // See https://en.wikipedia.org/wiki/Opaque_pointer#C
850 //
851 // Thus, we don't use C++'s new operator (which requires knowing the sizeof
852 // the struct at compile time). Instead, we use sk_malloc_canfail, with
853 // sizeof__wuffs_gif__decoder returning the appropriate value for the
854 // (statically or dynamically) linked version of the Wuffs library.
855 //
856 // As a C (not C++) library, none of the Wuffs types have constructors or
857 // destructors.
858 //
859 // In RAII style, we can still use std::unique_ptr with these pointers, but
860 // we pair the pointer with sk_free instead of C++'s delete.
861 void* decoder_raw = sk_malloc_canfail(sizeof__wuffs_gif__decoder());
862 if (!decoder_raw) {
863 *result = SkCodec::kInternalError;
864 return nullptr;
865 }
866 std::unique_ptr<wuffs_gif__decoder, decltype(&sk_free)> decoder(
867 reinterpret_cast<wuffs_gif__decoder*>(decoder_raw), &sk_free);
868
869 SkCodec::Result reset_result =
870 reset_and_decode_image_config(decoder.get(), &imgcfg, &iobuf, stream.get());
871 if (reset_result != SkCodec::kSuccess) {
872 *result = reset_result;
873 return nullptr;
874 }
875
876 uint32_t width = imgcfg.pixcfg.width();
877 uint32_t height = imgcfg.pixcfg.height();
878 if ((width == 0) || (width > INT_MAX) || (height == 0) || (height > INT_MAX)) {
879 *result = SkCodec::kInvalidInput;
880 return nullptr;
881 }
882
883 uint64_t workbuf_len = imgcfg.workbuf_len().max_incl;
884 void* workbuf_ptr_raw = workbuf_len <= SIZE_MAX ? sk_malloc_canfail(workbuf_len) : nullptr;
885 if (!workbuf_ptr_raw) {
886 *result = SkCodec::kInternalError;
887 return nullptr;
888 }
889 std::unique_ptr<uint8_t, decltype(&sk_free)> workbuf_ptr(
890 reinterpret_cast<uint8_t*>(workbuf_ptr_raw), &sk_free);
891
892 uint64_t pixbuf_len = imgcfg.pixcfg.pixbuf_len();
893 void* pixbuf_ptr_raw = pixbuf_len <= SIZE_MAX ? sk_malloc_canfail(pixbuf_len) : nullptr;
894 if (!pixbuf_ptr_raw) {
895 *result = SkCodec::kInternalError;
896 return nullptr;
897 }
898 std::unique_ptr<uint8_t, decltype(&sk_free)> pixbuf_ptr(
899 reinterpret_cast<uint8_t*>(pixbuf_ptr_raw), &sk_free);
900 wuffs_base__pixel_buffer pixbuf = ((wuffs_base__pixel_buffer){});
901
902 const char* status = pixbuf.set_from_slice(&imgcfg.pixcfg, ((wuffs_base__slice_u8){
903 .ptr = pixbuf_ptr.get(),
904 .len = pixbuf_len,
905 }));
906 if (status != nullptr) {
907 SkCodecPrintf("set_from_slice: %s", status);
908 *result = SkCodec::kInternalError;
909 return nullptr;
910 }
911
912 // In Skia's API, the alpha we calculate here and return is only for the
913 // first frame.
914 SkEncodedInfo::Alpha alpha = imgcfg.first_frame_is_opaque() ? SkEncodedInfo::kOpaque_Alpha
915 : SkEncodedInfo::kBinary_Alpha;
916
917 SkEncodedInfo encodedInfo =
918 SkEncodedInfo::Make(width, height, SkEncodedInfo::kPalette_Color, alpha, 8);
919
920 *result = SkCodec::kSuccess;
921 return std::unique_ptr<SkCodec>(new SkWuffsCodec(
922 std::move(encodedInfo), std::move(stream), std::move(decoder), std::move(pixbuf_ptr),
923 std::move(workbuf_ptr), workbuf_len, imgcfg, pixbuf, iobuf));
924}