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