blob: c602fcd7843eb0a63317b5a3b448fbf12461624f [file] [log] [blame]
scroggo6f5e6192015-06-18 12:53:43 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
scroggocc2feb12015-08-14 08:32:46 -07008#include "SkCodecPriv.h"
msarette99883f2016-09-08 06:05:35 -07009#include "SkColorSpaceXform.h"
Matt Sarett5c496172017-02-07 17:01:16 -050010#include "SkSampler.h"
msarettff2a6c82016-09-07 11:23:28 -070011#include "SkStreamPriv.h"
scroggo6f5e6192015-06-18 12:53:43 -070012#include "SkTemplates.h"
Matt Sarett5c496172017-02-07 17:01:16 -050013#include "SkWebpCodec.h"
scroggo6f5e6192015-06-18 12:53:43 -070014
15// A WebP decoder on top of (subset of) libwebp
16// For more information on WebP image format, and libwebp library, see:
17// https://code.google.com/speed/webp/
18// http://www.webmproject.org/code/#libwebp-webp-image-library
19// https://chromium.googlesource.com/webm/libwebp
20
21// If moving libwebp out of skia source tree, path for webp headers must be
22// updated accordingly. Here, we enforce using local copy in webp sub-directory.
23#include "webp/decode.h"
msarett9d15dab2016-08-24 07:36:06 -070024#include "webp/demux.h"
scroggo6f5e6192015-06-18 12:53:43 -070025#include "webp/encode.h"
26
scroggodb30be22015-12-08 18:54:13 -080027bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {
scroggo6f5e6192015-06-18 12:53:43 -070028 // WEBP starts with the following:
29 // RIFFXXXXWEBPVP
30 // Where XXXX is unspecified.
scroggodb30be22015-12-08 18:54:13 -080031 const char* bytes = static_cast<const char*>(buf);
32 return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6);
scroggo6f5e6192015-06-18 12:53:43 -070033}
34
scroggo6f5e6192015-06-18 12:53:43 -070035// Parse headers of RIFF container, and check for valid Webp (VP8) content.
36// NOTE: This calls peek instead of read, since onGetPixels will need these
37// bytes again.
msarettac6c7502016-04-25 09:30:24 -070038// Returns an SkWebpCodec on success;
39SkCodec* SkWebpCodec::NewFromStream(SkStream* stream) {
Ben Wagner145dbcd2016-11-03 14:40:50 -040040 std::unique_ptr<SkStream> streamDeleter(stream);
msarettac6c7502016-04-25 09:30:24 -070041
msarettff2a6c82016-09-07 11:23:28 -070042 // Webp demux needs a contiguous data buffer.
43 sk_sp<SkData> data = nullptr;
44 if (stream->getMemoryBase()) {
45 // It is safe to make without copy because we'll hold onto the stream.
46 data = SkData::MakeWithoutCopy(stream->getMemoryBase(), stream->getLength());
47 } else {
48 data = SkCopyStreamToData(stream);
scroggodb30be22015-12-08 18:54:13 -080049
msarettff2a6c82016-09-07 11:23:28 -070050 // If we are forced to copy the stream to a data, we can go ahead and delete the stream.
51 streamDeleter.reset(nullptr);
52 }
53
54 // It's a little strange that the |demux| will outlive |webpData|, though it needs the
55 // pointer in |webpData| to remain valid. This works because the pointer remains valid
56 // until the SkData is freed.
57 WebPData webpData = { data->bytes(), data->size() };
58 SkAutoTCallVProc<WebPDemuxer, WebPDemuxDelete> demux(WebPDemuxPartial(&webpData, nullptr));
59 if (nullptr == demux) {
msarettac6c7502016-04-25 09:30:24 -070060 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -070061 }
62
Matt Sarett5c496172017-02-07 17:01:16 -050063 const int width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH);
64 const int height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT);
65
66 // Sanity check for image size that's about to be decoded.
67 {
68 const int64_t size = sk_64_mul(width, height);
69 if (!sk_64_isS32(size)) {
70 return nullptr;
71 }
72 // now check that if we are 4-bytes per pixel, we also don't overflow
73 if (sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {
74 return nullptr;
75 }
76 }
77
msarettff2a6c82016-09-07 11:23:28 -070078 WebPChunkIterator chunkIterator;
79 SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator);
80 sk_sp<SkColorSpace> colorSpace = nullptr;
raftiasd737bee2016-12-08 10:53:24 -050081 bool unsupportedICC = false;
msarettff2a6c82016-09-07 11:23:28 -070082 if (WebPDemuxGetChunk(demux, "ICCP", 1, &chunkIterator)) {
Brian Osman526972e2016-10-24 09:24:02 -040083 colorSpace = SkColorSpace::MakeICC(chunkIterator.chunk.bytes, chunkIterator.chunk.size);
raftiasd737bee2016-12-08 10:53:24 -050084 if (!colorSpace) {
85 unsupportedICC = true;
86 }
scroggo6f5e6192015-06-18 12:53:43 -070087 }
msarettff2a6c82016-09-07 11:23:28 -070088 if (!colorSpace) {
Matt Sarett77a7a1b2017-02-07 13:56:11 -050089 colorSpace = SkColorSpace::MakeSRGB();
msarettff2a6c82016-09-07 11:23:28 -070090 }
91
Matt Sarett5c496172017-02-07 17:01:16 -050092 // Get the first frame and its "features" to determine the color and alpha types.
93 // Since we do not yet support animated webp, this is the only frame that we will
94 // decode.
msarettff2a6c82016-09-07 11:23:28 -070095 WebPIterator frame;
96 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
97 if (!WebPDemuxGetFrame(demux, 1, &frame)) {
98 return nullptr;
99 }
100
msarettff2a6c82016-09-07 11:23:28 -0700101 WebPBitstreamFeatures features;
102 VP8StatusCode status = WebPGetFeatures(frame.fragment.bytes, frame.fragment.size, &features);
103 if (VP8_STATUS_OK != status) {
104 return nullptr;
105 }
106
msarettac6c7502016-04-25 09:30:24 -0700107 SkEncodedInfo::Color color;
108 SkEncodedInfo::Alpha alpha;
109 switch (features.format) {
110 case 0:
Matt Sarett5c496172017-02-07 17:01:16 -0500111 // This indicates a "mixed" format. We could see this for
112 // animated webps (multiple fragments).
msarettac6c7502016-04-25 09:30:24 -0700113 // I believe that this is a rare case.
114 // We could also guess kYUV here, but I think it makes more
115 // sense to guess kBGRA which is likely closer to the final
116 // output. Otherwise, we might end up converting
117 // BGRA->YUVA->BGRA.
118 color = SkEncodedInfo::kBGRA_Color;
119 alpha = SkEncodedInfo::kUnpremul_Alpha;
120 break;
121 case 1:
122 // This is the lossy format (YUV).
Matt Sarett5c496172017-02-07 17:01:16 -0500123 if (SkToBool(features.has_alpha) || frame.width != width || frame.height != height) {
msarettac6c7502016-04-25 09:30:24 -0700124 color = SkEncodedInfo::kYUVA_Color;
msarettc30c4182016-04-20 11:53:35 -0700125 alpha = SkEncodedInfo::kUnpremul_Alpha;
msarettac6c7502016-04-25 09:30:24 -0700126 } else {
127 color = SkEncodedInfo::kYUV_Color;
128 alpha = SkEncodedInfo::kOpaque_Alpha;
129 }
130 break;
131 case 2:
132 // This is the lossless format (BGRA).
msarettac6c7502016-04-25 09:30:24 -0700133 color = SkEncodedInfo::kBGRA_Color;
134 alpha = SkEncodedInfo::kUnpremul_Alpha;
135 break;
136 default:
137 return nullptr;
scroggo6f5e6192015-06-18 12:53:43 -0700138 }
scroggo6f5e6192015-06-18 12:53:43 -0700139
msarettac6c7502016-04-25 09:30:24 -0700140 SkEncodedInfo info = SkEncodedInfo::Make(color, alpha, 8);
Matt Sarett5c496172017-02-07 17:01:16 -0500141 SkWebpCodec* codecOut = new SkWebpCodec(width, height, info, std::move(colorSpace),
142 streamDeleter.release(), demux.release(),
143 std::move(data));
raftiasd737bee2016-12-08 10:53:24 -0500144 codecOut->setUnsupportedICC(unsupportedICC);
145 return codecOut;
scroggo6f5e6192015-06-18 12:53:43 -0700146}
147
scroggo6f5e6192015-06-18 12:53:43 -0700148SkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {
149 SkISize dim = this->getInfo().dimensions();
msaretta0c414d2015-06-19 07:34:30 -0700150 // SkCodec treats zero dimensional images as errors, so the minimum size
151 // that we will recommend is 1x1.
152 dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));
153 dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));
scroggo6f5e6192015-06-18 12:53:43 -0700154 return dim;
155}
156
scroggoe7fc14b2015-10-02 13:14:46 -0700157bool SkWebpCodec::onDimensionsSupported(const SkISize& dim) {
158 const SkImageInfo& info = this->getInfo();
159 return dim.width() >= 1 && dim.width() <= info.width()
160 && dim.height() >= 1 && dim.height() <= info.height();
161}
162
scroggo6f5e6192015-06-18 12:53:43 -0700163static WEBP_CSP_MODE webp_decode_mode(SkColorType ct, bool premultiply) {
164 switch (ct) {
165 case kBGRA_8888_SkColorType:
166 return premultiply ? MODE_bgrA : MODE_BGRA;
167 case kRGBA_8888_SkColorType:
168 return premultiply ? MODE_rgbA : MODE_RGBA;
scroggo74992b52015-08-06 13:50:15 -0700169 case kRGB_565_SkColorType:
170 return MODE_RGB_565;
scroggo6f5e6192015-06-18 12:53:43 -0700171 default:
172 return MODE_LAST;
173 }
174}
175
scroggob636b452015-07-22 07:16:20 -0700176bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {
177 if (!desiredSubset) {
178 return false;
179 }
180
msarettfdb47572015-10-13 12:50:14 -0700181 SkIRect dimensions = SkIRect::MakeSize(this->getInfo().dimensions());
182 if (!dimensions.contains(*desiredSubset)) {
scroggob636b452015-07-22 07:16:20 -0700183 return false;
184 }
185
186 // As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we
187 // decode this exact subset.
188 // Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.
189 desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;
190 desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;
191 return true;
192}
193
scroggoeb602a52015-07-09 08:16:03 -0700194SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
msarette6dd0042015-10-09 11:07:34 -0700195 const Options& options, SkPMColor*, int*,
msarette99883f2016-09-08 06:05:35 -0700196 int* rowsDecodedPtr) {
msarett2ecc35f2016-09-08 11:55:16 -0700197 if (!conversion_possible(dstInfo, this->getInfo())) {
198 return kInvalidConversion;
199 }
msarette99883f2016-09-08 06:05:35 -0700200
Matt Sarett313c4632016-10-20 12:35:23 -0400201 if (!this->initializeColorXform(dstInfo)) {
202 return kInvalidConversion;
scroggo6f5e6192015-06-18 12:53:43 -0700203 }
204
205 WebPDecoderConfig config;
206 if (0 == WebPInitDecoderConfig(&config)) {
207 // ABI mismatch.
208 // FIXME: New enum for this?
209 return kInvalidInput;
210 }
211
212 // Free any memory associated with the buffer. Must be called last, so we declare it first.
213 SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));
214
Matt Sarett5c496172017-02-07 17:01:16 -0500215 WebPIterator frame;
216 SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame);
217 // If this succeeded in NewFromStream(), it should succeed again here.
218 SkAssertResult(WebPDemuxGetFrame(fDemux, 1, &frame));
Matt Sarett604971e2017-02-06 09:51:48 -0500219
Matt Sarett5c496172017-02-07 17:01:16 -0500220 // Get the frameRect. libwebp will have already signaled an error if this is not fully
221 // contained by the canvas.
222 auto frameRect = SkIRect::MakeXYWH(frame.x_offset, frame.y_offset, frame.width, frame.height);
223 SkASSERT(this->getInfo().bounds().contains(frameRect));
224 bool frameIsSubset = frameRect.size() != this->getInfo().dimensions();
225 if (frameIsSubset) {
226 SkSampler::Fill(dstInfo, dst, rowBytes, 0, options.fZeroInitialized);
Matt Sarett604971e2017-02-06 09:51:48 -0500227 }
228
Matt Sarett5c496172017-02-07 17:01:16 -0500229 int dstX = frameRect.x();
230 int dstY = frameRect.y();
231 int subsetWidth = frameRect.width();
232 int subsetHeight = frameRect.height();
233 if (options.fSubset) {
234 SkIRect subset = *options.fSubset;
235 SkASSERT(this->getInfo().bounds().contains(subset));
236 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
237 SkASSERT(this->getValidSubset(&subset) && subset == *options.fSubset);
238
239 if (!SkIRect::IntersectsNoEmptyCheck(subset, frameRect)) {
240 return kSuccess;
241 }
242
243 int minXOffset = SkTMin(dstX, subset.x());
244 int minYOffset = SkTMin(dstY, subset.y());
245 dstX -= minXOffset;
246 dstY -= minYOffset;
247 frameRect.offset(-minXOffset, -minYOffset);
248 subset.offset(-minXOffset, -minYOffset);
249
250 // Just like we require that the requested subset x and y offset are even, libwebp
251 // guarantees that the frame x and y offset are even (it's actually impossible to specify
252 // an odd frame offset). So we can still guarantee that the adjusted offsets are even.
253 SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
254
255 SkIRect intersection;
256 SkAssertResult(intersection.intersect(frameRect, subset));
257 subsetWidth = intersection.width();
258 subsetHeight = intersection.height();
259
260 config.options.use_cropping = 1;
261 config.options.crop_left = subset.x();
262 config.options.crop_top = subset.y();
263 config.options.crop_width = subsetWidth;
264 config.options.crop_height = subsetHeight;
265 }
266
267 // Ignore the frame size and offset when determining if scaling is necessary.
268 int scaledWidth = subsetWidth;
269 int scaledHeight = subsetHeight;
270 SkISize srcSize = options.fSubset ? options.fSubset->size() : this->getInfo().dimensions();
271 if (srcSize != dstInfo.dimensions()) {
scroggo6f5e6192015-06-18 12:53:43 -0700272 config.options.use_scaling = 1;
Matt Sarett5c496172017-02-07 17:01:16 -0500273
274 if (frameIsSubset) {
275 float scaleX = ((float) dstInfo.width()) / srcSize.width();
276 float scaleY = ((float) dstInfo.height()) / srcSize.height();
277
278 // We need to be conservative here and floor rather than round.
279 // Otherwise, we may find ourselves decoding off the end of memory.
280 dstX = scaleX * dstX;
281 scaledWidth = scaleX * scaledWidth;
282 dstY = scaleY * dstY;
283 scaledHeight = scaleY * scaledHeight;
284 if (0 == scaledWidth || 0 == scaledHeight) {
285 return kSuccess;
286 }
287 } else {
288 scaledWidth = dstInfo.width();
289 scaledHeight = dstInfo.height();
290 }
291
292 config.options.scaled_width = scaledWidth;
293 config.options.scaled_height = scaledHeight;
scroggo6f5e6192015-06-18 12:53:43 -0700294 }
295
msarettcf7b8772016-09-22 12:37:04 -0700296 // Swizzling between RGBA and BGRA is zero cost in a color transform. So when we have a
297 // color transform, we should decode to whatever is easiest for libwebp, and then let the
298 // color transform swizzle if necessary.
299 // Lossy webp is encoded as YUV (so RGBA and BGRA are the same cost). Lossless webp is
300 // encoded as BGRA. This means decoding to BGRA is either faster or the same cost as RGBA.
Matt Sarett313c4632016-10-20 12:35:23 -0400301 config.output.colorspace = this->colorXform() ? MODE_BGRA :
msarette99883f2016-09-08 06:05:35 -0700302 webp_decode_mode(dstInfo.colorType(), dstInfo.alphaType() == kPremul_SkAlphaType);
scroggo6f5e6192015-06-18 12:53:43 -0700303 config.output.is_external_memory = 1;
304
msarette99883f2016-09-08 06:05:35 -0700305 // We will decode the entire image and then perform the color transform. libwebp
306 // does not provide a row-by-row API. This is a shame particularly in the F16 case,
307 // where we need to allocate an extra image-sized buffer.
308 SkAutoTMalloc<uint32_t> pixels;
Matt Sarett5c496172017-02-07 17:01:16 -0500309 bool isF16 = kRGBA_F16_SkColorType == dstInfo.colorType();
310 void* webpDst = isF16 ? pixels.reset(dstInfo.width() * dstInfo.height()) : dst;
311 size_t webpRowBytes = isF16 ? dstInfo.width() * sizeof(uint32_t) : rowBytes;
312 size_t totalBytes = isF16 ? webpRowBytes * dstInfo.height() : dstInfo.getSafeSize(webpRowBytes);
313 size_t dstBpp = SkColorTypeBytesPerPixel(dstInfo.colorType());
314 size_t webpBpp = isF16 ? sizeof(uint32_t) : dstBpp;
msarette99883f2016-09-08 06:05:35 -0700315
Matt Sarett5c496172017-02-07 17:01:16 -0500316 size_t offset = dstX * webpBpp + dstY * webpRowBytes;
317 config.output.u.RGBA.rgba = SkTAddOffset<uint8_t>(webpDst, offset);
318 config.output.u.RGBA.stride = (int) webpRowBytes;
319 config.output.u.RGBA.size = totalBytes - offset;
msarettff2a6c82016-09-07 11:23:28 -0700320
halcanary96fcdcc2015-08-27 07:41:13 -0700321 SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));
scroggo6f5e6192015-06-18 12:53:43 -0700322 if (!idec) {
323 return kInvalidInput;
324 }
325
msarette99883f2016-09-08 06:05:35 -0700326 int rowsDecoded;
327 SkCodec::Result result;
msarettff2a6c82016-09-07 11:23:28 -0700328 switch (WebPIUpdate(idec, frame.fragment.bytes, frame.fragment.size)) {
329 case VP8_STATUS_OK:
Matt Sarett5c496172017-02-07 17:01:16 -0500330 rowsDecoded = scaledHeight;
msarette99883f2016-09-08 06:05:35 -0700331 result = kSuccess;
332 break;
msarettff2a6c82016-09-07 11:23:28 -0700333 case VP8_STATUS_SUSPENDED:
Matt Sarett5c496172017-02-07 17:01:16 -0500334 WebPIDecGetRGB(idec, &rowsDecoded, nullptr, nullptr, nullptr);
335 *rowsDecodedPtr = rowsDecoded + dstY;
msarette99883f2016-09-08 06:05:35 -0700336 result = kIncompleteInput;
337 break;
msarettff2a6c82016-09-07 11:23:28 -0700338 default:
339 return kInvalidInput;
scroggo6f5e6192015-06-18 12:53:43 -0700340 }
msarette99883f2016-09-08 06:05:35 -0700341
Matt Sarett313c4632016-10-20 12:35:23 -0400342 if (this->colorXform()) {
msarettcf7b8772016-09-22 12:37:04 -0700343 SkColorSpaceXform::ColorFormat dstColorFormat = select_xform_format(dstInfo.colorType());
msarettc0444612016-09-16 11:45:58 -0700344 SkAlphaType xformAlphaType = select_xform_alpha(dstInfo.alphaType(),
msarette99883f2016-09-08 06:05:35 -0700345 this->getInfo().alphaType());
346
Matt Sarett5c496172017-02-07 17:01:16 -0500347 uint32_t* xformSrc = (uint32_t*) config.output.u.RGBA.rgba;
348 void* xformDst = SkTAddOffset<void>(dst, dstBpp * dstX + rowBytes * dstY);
msarette99883f2016-09-08 06:05:35 -0700349 size_t srcRowBytes = config.output.u.RGBA.stride;
Robert Phillipsb3050b92017-02-06 13:12:18 +0000350 for (int y = 0; y < rowsDecoded; y++) {
Matt Sarett5c496172017-02-07 17:01:16 -0500351 SkAssertResult(this->colorXform()->apply(dstColorFormat, xformDst,
352 SkColorSpaceXform::kBGRA_8888_ColorFormat, xformSrc, scaledWidth,
Matt Sarett313c4632016-10-20 12:35:23 -0400353 xformAlphaType));
Matt Sarett5c496172017-02-07 17:01:16 -0500354 xformDst = SkTAddOffset<void>(xformDst, rowBytes);
355 xformSrc = SkTAddOffset<uint32_t>(xformSrc, srcRowBytes);
msarette99883f2016-09-08 06:05:35 -0700356 }
357 }
358
359 return result;
scroggo6f5e6192015-06-18 12:53:43 -0700360}
361
msarett9d15dab2016-08-24 07:36:06 -0700362SkWebpCodec::SkWebpCodec(int width, int height, const SkEncodedInfo& info,
msarettff2a6c82016-09-07 11:23:28 -0700363 sk_sp<SkColorSpace> colorSpace, SkStream* stream, WebPDemuxer* demux,
364 sk_sp<SkData> data)
365 : INHERITED(width, height, info, stream, std::move(colorSpace))
366 , fDemux(demux)
367 , fData(std::move(data))
msarett9d15dab2016-08-24 07:36:06 -0700368{}