| 1 |
/* |
| 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 |
|
| 8 |
#include "src/codec/SkWebpCodec.h" |
| 9 |
|
| 10 |
#include "include/codec/SkCodec.h" |
| 11 |
#include "include/codec/SkCodecAnimation.h" |
| 12 |
#include "include/codec/SkWebpDecoder.h" |
| 13 |
#include "include/core/SkAlphaType.h" |
| 14 |
#include "include/core/SkBitmap.h" |
| 15 |
#include "include/core/SkColorType.h" |
| 16 |
#include "include/core/SkImageInfo.h" |
| 17 |
#include "include/core/SkRect.h" |
| 18 |
#include "include/core/SkSize.h" |
| 19 |
#include "include/core/SkStream.h" |
| 20 |
#include "include/private/base/SkAlign.h" |
| 21 |
#include "include/private/base/SkMath.h" |
| 22 |
#include "include/private/base/SkNoncopyable.h" |
| 23 |
#include "include/private/base/SkTFitsIn.h" |
| 24 |
#include "include/private/base/SkTemplates.h" |
| 25 |
#include "include/private/base/SkTo.h" |
| 26 |
#include "modules/skcms/skcms.h" |
| 27 |
#include "src/codec/SkParseEncodedOrigin.h" |
| 28 |
#include "src/codec/SkSampler.h" |
| 29 |
#include "src/core/SkRasterPipeline.h" |
| 30 |
#include "src/core/SkRasterPipelineOpContexts.h" |
| 31 |
#include "src/core/SkRasterPipelineOpList.h" |
| 32 |
#include "src/core/SkStreamPriv.h" |
| 33 |
|
| 34 |
#include <algorithm> |
| 35 |
#include <cstdint> |
| 36 |
#include <cstring> |
| 37 |
#include <optional> |
| 38 |
#include <tuple> |
| 39 |
#include <utility> |
| 40 |
|
| 41 |
// A WebP decoder on top of (subset of) libwebp |
| 42 |
// For more information on WebP image format, and libwebp library, see: |
| 43 |
// https://code.google.com/speed/webp/ |
| 44 |
// http://www.webmproject.org/code/#libwebp-webp-image-library |
| 45 |
// https://chromium.googlesource.com/webm/libwebp |
| 46 |
|
| 47 |
// If moving libwebp out of skia source tree, path for webp headers must be |
| 48 |
// updated accordingly. Here, we enforce using local copy in webp sub-directory. |
| 49 |
#include "webp/decode.h" // NO_G3_REWRITE |
| 50 |
#include "webp/demux.h" // NO_G3_REWRITE |
| 51 |
#include "webp/mux_types.h" // NO_G3_REWRITE |
| 52 |
|
| 53 |
bool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) { |
| 54 |
// WEBP starts with the following: |
| 55 |
// RIFFXXXXWEBPVP |
| 56 |
// Where XXXX is unspecified. |
| 57 |
const char* bytes = static_cast<const char*>(buf); |
| 58 |
return bytesRead >= 14 && !memcmp(bytes, "RIFF", 4) && !memcmp(&bytes[8], "WEBPVP", 6); |
| 59 |
} |
| 60 |
|
| 61 |
// This gives the optimal amount of the stream as SkData to a WebPDemux object for |
| 62 |
// decoding so that an SkCodec object can be made. |
| 63 |
// Exif data is at the end so we will end up reading the whole stream in that case. |
| 64 |
// Otherwise we stop until we reach the header bytes for VP8(L) data, and the first |
| 65 |
// frame for animated data. |
| 66 |
// Returns a bool indicating if only the header has been read and the data read from |
| 67 |
// the stream as SkData. If incomplete/invalid data, return nullptr and ignore the boolean |
| 68 |
// value. |
| 69 |
static std::pair<bool, sk_sp<SkData>> get_header_from_stream(SkStream* stream) { |
| 70 |
const size_t kBufferSize = 4096; |
| 71 |
char buffer[kBufferSize]; |
| 72 |
// "RIFF" (4) + file size (4) + "WEBP" (4) = 12 |
| 73 |
const size_t kInitialHeaderSize = 12; |
| 74 |
|
| 75 |
SkDynamicMemoryWStream tempStream; |
| 76 |
size_t bytes_read = stream->read(buffer, kInitialHeaderSize); |
| 77 |
if (bytes_read < kInitialHeaderSize || |
| 78 |
memcmp(buffer, "RIFF", 4) != 0 || |
| 79 |
memcmp(&buffer[8], "WEBP", 4) != 0) { |
| 80 |
// Fail if we don't have valid webp data |
| 81 |
return {false, nullptr}; |
| 82 |
} |
| 83 |
tempStream.write(buffer, bytes_read); |
| 84 |
bool isAnimated = false; |
| 85 |
bool firstChunkRead = false; |
| 86 |
|
| 87 |
while (!stream->isAtEnd()) { |
| 88 |
// Read the chunk's FourCC and payload size |
| 89 |
const size_t kChunkSizeHeader = 8; |
| 90 |
bytes_read = stream->read(buffer, kChunkSizeHeader); |
| 91 |
if (bytes_read < kChunkSizeHeader) { |
| 92 |
return {false, nullptr}; |
| 93 |
} |
| 94 |
tempStream.write(buffer, bytes_read); |
| 95 |
|
| 96 |
// Return upon VP8 or VP8L chunk, keep reading and writing otherwise |
| 97 |
// Handle ANMF subchunks, if animated image read the first frame and return |
| 98 |
if (!memcmp(buffer, "VP8 ", 4)) { |
| 99 |
const size_t kVP8UncompressedChunkMinSize = 3; |
| 100 |
const size_t kVP8UncompressedChunkMaxSize = 10; |
| 101 |
bytes_read = stream->read(buffer, kVP8UncompressedChunkMaxSize); |
| 102 |
if (bytes_read < kVP8UncompressedChunkMinSize) { |
| 103 |
// Invalid webp |
| 104 |
return {false, nullptr}; |
| 105 |
} |
| 106 |
tempStream.write(buffer, bytes_read); |
| 107 |
return {true, tempStream.detachAsData()}; |
| 108 |
} else if (!memcmp(buffer, "VP8L", 4)) { |
| 109 |
const size_t kImageHeaderSize = 5; |
| 110 |
bytes_read = stream->read(buffer, kImageHeaderSize); |
| 111 |
if (bytes_read < kImageHeaderSize) { |
| 112 |
// Invalid webp |
| 113 |
return {false, nullptr}; |
| 114 |
} |
| 115 |
tempStream.write(buffer, bytes_read); |
| 116 |
return {true, tempStream.detachAsData()}; |
| 117 |
} else if (!memcmp(buffer, "VP8X", 4)) { |
| 118 |
if (firstChunkRead) { |
| 119 |
return {false, nullptr}; |
| 120 |
} else { |
| 121 |
firstChunkRead = true; |
| 122 |
} |
| 123 |
// VP8X payload should always be 10 |
| 124 |
uint32_t payloadSize; |
| 125 |
const size_t kVP8XPayloadSize = 10; |
| 126 |
memcpy(&payloadSize, &buffer[4], 4); |
| 127 |
if (payloadSize != kVP8XPayloadSize) { |
| 128 |
return {false, nullptr}; |
| 129 |
} |
| 130 |
|
| 131 |
bytes_read = stream->read(buffer, payloadSize); |
| 132 |
if (bytes_read < payloadSize) { |
| 133 |
// Invalid webp |
| 134 |
return {false, nullptr}; |
| 135 |
} |
| 136 |
tempStream.write(buffer, bytes_read); |
| 137 |
|
| 138 |
uint8_t vp8xFeatureFlags; |
| 139 |
memcpy(&vp8xFeatureFlags, buffer, 1); |
| 140 |
const bool hasExif = vp8xFeatureFlags & EXIF_FLAG; |
| 141 |
isAnimated = vp8xFeatureFlags & ANIMATION_FLAG; |
| 142 |
if (hasExif) { |
| 143 |
// If exif data, we have to read the whole stream because exif data |
| 144 |
// is at the end of the file and we want that in order to create |
| 145 |
// the SkCodec |
| 146 |
do { |
| 147 |
bytes_read = stream->read(buffer, kBufferSize); |
| 148 |
tempStream.write(buffer, bytes_read); |
| 149 |
} while (!stream->isAtEnd()); |
| 150 |
return {false, tempStream.detachAsData()}; |
| 151 |
} |
| 152 |
} else { |
| 153 |
if (!firstChunkRead) { |
| 154 |
// We only expect VP8, VP8L, or VP8X chunks to be the first. |
| 155 |
return {false, nullptr}; |
| 156 |
} |
| 157 |
const bool animatedFrame = !memcmp(buffer, "ANMF", 4); |
| 158 |
|
| 159 |
// According to the RIFF document format, if 'payloadSize' is odd a single |
| 160 |
// padding byte -- which must be 0 to conform with RIFF -- is added. |
| 161 |
uint32_t payloadSize; |
| 162 |
memcpy(&payloadSize, &buffer[4], 4); |
| 163 |
if (payloadSize % 2 != 0) { |
| 164 |
payloadSize += 1; |
| 165 |
} |
| 166 |
|
| 167 |
// Read 'payload size' bytes ahead to get to the next chunk |
| 168 |
while (payloadSize) { |
| 169 |
bytes_read = stream->read(buffer, std::min((size_t)payloadSize, kBufferSize)); |
| 170 |
if (!bytes_read) { |
| 171 |
break; |
| 172 |
} |
| 173 |
tempStream.write(buffer, bytes_read); |
| 174 |
payloadSize -= bytes_read; |
| 175 |
} |
| 176 |
if (payloadSize) { |
| 177 |
SkASSERT(stream->isAtEnd()); |
| 178 |
// Invalid webp |
| 179 |
return {false, nullptr}; |
| 180 |
} |
| 181 |
|
| 182 |
if (animatedFrame && isAnimated) { |
| 183 |
// If this is an animated frame and we are expecting it, return |
| 184 |
// the whole frame (this is the first frame which we want in order to |
| 185 |
// create the SkCodec) |
| 186 |
return {true, tempStream.detachAsData()}; |
| 187 |
} |
| 188 |
} |
| 189 |
} |
| 190 |
// We never reached image data but read the whole stream |
| 191 |
return {true, tempStream.detachAsData()}; |
| 192 |
} |
| 193 |
|
| 194 |
bool SkWebpCodec::ensureAllData() { |
| 195 |
if (fOnlyHeaderParsed) { |
| 196 |
SkDynamicMemoryWStream newData; |
| 197 |
newData.write(fData->data(), fData->size()); |
| 198 |
SkStreamPriv::Copy(&newData, this->stream()); |
| 199 |
fData = newData.detachAsData(); |
| 200 |
fOnlyHeaderParsed = false; |
| 201 |
|
| 202 |
WebPData webpData = { fData->bytes(), fData->size() }; |
| 203 |
WebPDemuxState state; |
| 204 |
fDemux.reset(WebPDemuxPartial(&webpData, &state)); |
| 205 |
// We know fDemux state is at least WEBP_DEMUX_PARSED_HEADER already which we allow |
| 206 |
if (state == WEBP_DEMUX_PARSE_ERROR) { |
| 207 |
return false; |
| 208 |
} |
| 209 |
} |
| 210 |
return true; |
| 211 |
} |
| 212 |
|
| 213 |
// Parse headers of RIFF container, and check for valid Webp (VP8) content. |
| 214 |
// Returns an SkWebpCodec on success |
| 215 |
std::unique_ptr<SkCodec> SkWebpCodec::MakeFromStream(std::unique_ptr<SkStream> stream, |
| 216 |
Result* result) { |
| 217 |
SkASSERT(result); |
| 218 |
if (!stream) { |
| 219 |
*result = SkCodec::kInvalidInput; |
| 220 |
return nullptr; |
| 221 |
} |
| 222 |
// Webp demux needs a contiguous data buffer. |
| 223 |
sk_sp<SkData> data = nullptr; |
| 224 |
// If there is no memory base for the stream, we will attempt to only read necessary portions, |
| 225 |
// which we will read the rest later. |
| 226 |
bool onlyHeaderParsed = false; |
| 227 |
if (stream->getMemoryBase()) { |
| 228 |
// It is safe to make without copy because we'll hold onto the stream. |
| 229 |
data = SkData::MakeWithoutCopy(stream->getMemoryBase(), stream->getLength()); |
| 230 |
} else { |
| 231 |
std::tie(onlyHeaderParsed, data) = get_header_from_stream(stream.get()); |
| 232 |
if (!data) { |
| 233 |
*result = kIncompleteInput; |
| 234 |
return nullptr; |
| 235 |
} |
| 236 |
|
| 237 |
// If we are forced to copy the stream to a data, we can go ahead and delete the stream. |
| 238 |
if (!onlyHeaderParsed) { |
| 239 |
stream.reset(nullptr); |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
// It's a little strange that the |demux| will outlive |webpData|, though it needs the |
| 244 |
// pointer in |webpData| to remain valid. This works because the pointer remains valid |
| 245 |
// until the SkData is freed. |
| 246 |
WebPData webpData = { data->bytes(), data->size() }; |
| 247 |
WebPDemuxState state; |
| 248 |
SkAutoTCallVProc<WebPDemuxer, WebPDemuxDelete> demux(WebPDemuxPartial(&webpData, &state)); |
| 249 |
switch (state) { |
| 250 |
case WEBP_DEMUX_PARSE_ERROR: |
| 251 |
*result = kInvalidInput; |
| 252 |
return nullptr; |
| 253 |
case WEBP_DEMUX_PARSING_HEADER: |
| 254 |
*result = kIncompleteInput; |
| 255 |
return nullptr; |
| 256 |
case WEBP_DEMUX_PARSED_HEADER: |
| 257 |
case WEBP_DEMUX_DONE: |
| 258 |
SkASSERT(demux); |
| 259 |
break; |
| 260 |
} |
| 261 |
|
| 262 |
const int width = WebPDemuxGetI(demux, WEBP_FF_CANVAS_WIDTH); |
| 263 |
const int height = WebPDemuxGetI(demux, WEBP_FF_CANVAS_HEIGHT); |
| 264 |
|
| 265 |
// Validate the image size that's about to be decoded. |
| 266 |
{ |
| 267 |
const int64_t size = sk_64_mul(width, height); |
| 268 |
// now check that if we are 4-bytes per pixel, we also don't overflow |
| 269 |
if (!SkTFitsIn<int32_t>(size) || SkTo<int32_t>(size) > (0x7FFFFFFF >> 2)) { |
| 270 |
*result = kInvalidInput; |
| 271 |
return nullptr; |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
std::unique_ptr<SkCodecs::ColorProfile> profile = nullptr; |
| 276 |
{ |
| 277 |
WebPChunkIterator chunkIterator; |
| 278 |
SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator); |
| 279 |
if (WebPDemuxGetChunk(demux, "ICCP", 1, &chunkIterator)) { |
| 280 |
// FIXME: I think this could be MakeWithoutCopy |
| 281 |
auto chunk = SkData::MakeWithCopy(chunkIterator.chunk.bytes, chunkIterator.chunk.size); |
| 282 |
profile = SkCodecs::ColorProfile::MakeICCProfile(std::move(chunk)); |
| 283 |
} |
| 284 |
if (profile && profile->dataSpace() != SkCodecs::ColorProfile::DataSpace::kRGB) { |
| 285 |
profile = nullptr; |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
SkEncodedOrigin origin = kDefault_SkEncodedOrigin; |
| 290 |
{ |
| 291 |
WebPChunkIterator chunkIterator; |
| 292 |
SkAutoTCallVProc<WebPChunkIterator, WebPDemuxReleaseChunkIterator> autoCI(&chunkIterator); |
| 293 |
if (WebPDemuxGetChunk(demux, "EXIF", 1, &chunkIterator)) { |
| 294 |
SkParseEncodedOrigin(chunkIterator.chunk.bytes, chunkIterator.chunk.size, &origin); |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
// Get the first frame and its "features" to determine the color and alpha types. |
| 299 |
WebPIterator frame; |
| 300 |
SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame); |
| 301 |
if (!WebPDemuxGetFrame(demux, 1, &frame)) { |
| 302 |
*result = kIncompleteInput; |
| 303 |
return nullptr; |
| 304 |
} |
| 305 |
|
| 306 |
WebPBitstreamFeatures features; |
| 307 |
switch (WebPGetFeatures(frame.fragment.bytes, frame.fragment.size, &features)) { |
| 308 |
case VP8_STATUS_OK: |
| 309 |
break; |
| 310 |
case VP8_STATUS_SUSPENDED: |
| 311 |
case VP8_STATUS_NOT_ENOUGH_DATA: |
| 312 |
*result = kIncompleteInput; |
| 313 |
return nullptr; |
| 314 |
default: |
| 315 |
*result = kInvalidInput; |
| 316 |
return nullptr; |
| 317 |
} |
| 318 |
|
| 319 |
const bool hasAlpha = SkToBool(frame.has_alpha) |
| 320 |
|| frame.width != width || frame.height != height; |
| 321 |
SkEncodedInfo::Color color; |
| 322 |
SkEncodedInfo::Alpha alpha; |
| 323 |
switch (features.format) { |
| 324 |
case 0: |
| 325 |
// This indicates a "mixed" format. We could see this for |
| 326 |
// animated webps (multiple fragments). |
| 327 |
// We could also guess kYUV here, but I think it makes more |
| 328 |
// sense to guess kBGRA which is likely closer to the final |
| 329 |
// output. Otherwise, we might end up converting |
| 330 |
// BGRA->YUVA->BGRA. |
| 331 |
[[fallthrough]]; |
| 332 |
case 2: |
| 333 |
// This is the lossless format (BGRA). |
| 334 |
if (hasAlpha) { |
| 335 |
color = SkEncodedInfo::kBGRA_Color; |
| 336 |
alpha = SkEncodedInfo::kUnpremul_Alpha; |
| 337 |
} else { |
| 338 |
color = SkEncodedInfo::kBGRX_Color; |
| 339 |
alpha = SkEncodedInfo::kOpaque_Alpha; |
| 340 |
} |
| 341 |
break; |
| 342 |
case 1: |
| 343 |
// This is the lossy format (YUV). |
| 344 |
if (hasAlpha) { |
| 345 |
color = SkEncodedInfo::kYUVA_Color; |
| 346 |
alpha = SkEncodedInfo::kUnpremul_Alpha; |
| 347 |
} else { |
| 348 |
color = SkEncodedInfo::kYUV_Color; |
| 349 |
alpha = SkEncodedInfo::kOpaque_Alpha; |
| 350 |
} |
| 351 |
break; |
| 352 |
default: |
| 353 |
*result = kInvalidInput; |
| 354 |
return nullptr; |
| 355 |
} |
| 356 |
|
| 357 |
|
| 358 |
*result = kSuccess; |
| 359 |
SkEncodedInfo info = SkEncodedInfo::Make(width, height, color, alpha, 8, std::move(profile)); |
| 360 |
return std::unique_ptr<SkCodec>(new SkWebpCodec(std::move(info), std::move(stream), |
| 361 |
demux.release(), std::move(data), origin, |
| 362 |
onlyHeaderParsed)); |
| 363 |
} |
| 364 |
|
| 365 |
static WEBP_CSP_MODE webp_decode_mode(SkColorType dstCT, bool premultiply) { |
| 366 |
switch (dstCT) { |
| 367 |
case kBGRA_8888_SkColorType: |
| 368 |
return premultiply ? MODE_bgrA : MODE_BGRA; |
| 369 |
case kRGBA_8888_SkColorType: |
| 370 |
return premultiply ? MODE_rgbA : MODE_RGBA; |
| 371 |
case kRGB_565_SkColorType: |
| 372 |
return MODE_RGB_565; |
| 373 |
default: |
| 374 |
return MODE_LAST; |
| 375 |
} |
| 376 |
} |
| 377 |
|
| 378 |
SkWebpCodec::Frame* SkWebpCodec::FrameHolder::appendNewFrame(bool hasAlpha) { |
| 379 |
const int i = this->size(); |
| 380 |
fFrames.emplace_back(i, hasAlpha ? SkEncodedInfo::kUnpremul_Alpha |
| 381 |
: SkEncodedInfo::kOpaque_Alpha); |
| 382 |
return &fFrames[i]; |
| 383 |
} |
| 384 |
|
| 385 |
bool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const { |
| 386 |
if (!desiredSubset) { |
| 387 |
return false; |
| 388 |
} |
| 389 |
|
| 390 |
if (!this->bounds().contains(*desiredSubset)) { |
| 391 |
return false; |
| 392 |
} |
| 393 |
|
| 394 |
// As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we |
| 395 |
// decode this exact subset. |
| 396 |
// Leave right and bottom unmodified, so we suggest a slightly larger subset than requested. |
| 397 |
desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1; |
| 398 |
desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1; |
| 399 |
return true; |
| 400 |
} |
| 401 |
|
| 402 |
int SkWebpCodec::onGetRepetitionCount() { |
| 403 |
auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS); |
| 404 |
if (!(flags & ANIMATION_FLAG)) { |
| 405 |
return 0; |
| 406 |
} |
| 407 |
|
| 408 |
int loopCount = WebPDemuxGetI(fDemux.get(), WEBP_FF_LOOP_COUNT); |
| 409 |
if (0 == loopCount) { |
| 410 |
return kRepetitionCountInfinite; |
| 411 |
} |
| 412 |
|
| 413 |
loopCount--; |
| 414 |
return loopCount; |
| 415 |
} |
| 416 |
|
| 417 |
SkCodec::IsAnimated SkWebpCodec::onIsAnimated() { |
| 418 |
auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS); |
| 419 |
return (flags & ANIMATION_FLAG) != 0 ? IsAnimated::kYes : IsAnimated::kNo; |
| 420 |
} |
| 421 |
|
| 422 |
bool SkWebpCodec::onRewind() { |
| 423 |
// We may have a stream, but we never need to rewind it because we hold our own |
| 424 |
// SkData copy. |
| 425 |
return true; |
| 426 |
} |
| 427 |
|
| 428 |
int SkWebpCodec::onGetFrameCount() { |
| 429 |
auto flags = WebPDemuxGetI(fDemux.get(), WEBP_FF_FORMAT_FLAGS); |
| 430 |
if (!(flags & ANIMATION_FLAG)) { |
| 431 |
return 1; |
| 432 |
} |
| 433 |
|
| 434 |
const uint32_t oldFrameCount = fFrameHolder.size(); |
| 435 |
if (fFailed) { |
| 436 |
return oldFrameCount; |
| 437 |
} |
| 438 |
|
| 439 |
if (!ensureAllData()) { |
| 440 |
return 0; |
| 441 |
} |
| 442 |
|
| 443 |
const uint32_t frameCount = WebPDemuxGetI(fDemux, WEBP_FF_FRAME_COUNT); |
| 444 |
if (oldFrameCount == frameCount) { |
| 445 |
// We have already parsed this. |
| 446 |
return frameCount; |
| 447 |
} |
| 448 |
|
| 449 |
fFrameHolder.reserve(frameCount); |
| 450 |
|
| 451 |
for (uint32_t i = oldFrameCount; i < frameCount; i++) { |
| 452 |
WebPIterator iter; |
| 453 |
SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoIter(&iter); |
| 454 |
|
| 455 |
if (!WebPDemuxGetFrame(fDemux.get(), i + 1, &iter)) { |
| 456 |
fFailed = true; |
| 457 |
break; |
| 458 |
} |
| 459 |
|
| 460 |
// libwebp only reports complete frames of an animated image. |
| 461 |
SkASSERT(iter.complete); |
| 462 |
|
| 463 |
Frame* frame = fFrameHolder.appendNewFrame(iter.has_alpha); |
| 464 |
frame->setXYWH(iter.x_offset, iter.y_offset, iter.width, iter.height); |
| 465 |
frame->setDisposalMethod(iter.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND ? |
| 466 |
SkCodecAnimation::DisposalMethod::kRestoreBGColor : |
| 467 |
SkCodecAnimation::DisposalMethod::kKeep); |
| 468 |
frame->setDuration(iter.duration); |
| 469 |
if (WEBP_MUX_BLEND != iter.blend_method) { |
| 470 |
frame->setBlend(SkCodecAnimation::Blend::kSrc); |
| 471 |
} |
| 472 |
fFrameHolder.setAlphaAndRequiredFrame(frame); |
| 473 |
} |
| 474 |
|
| 475 |
return fFrameHolder.size(); |
| 476 |
|
| 477 |
} |
| 478 |
|
| 479 |
const SkFrame* SkWebpCodec::FrameHolder::onGetFrame(int i) const { |
| 480 |
return static_cast<const SkFrame*>(this->frame(i)); |
| 481 |
} |
| 482 |
|
| 483 |
const SkWebpCodec::Frame* SkWebpCodec::FrameHolder::frame(int i) const { |
| 484 |
SkASSERT(i >= 0 && i < this->size()); |
| 485 |
return &fFrames[i]; |
| 486 |
} |
| 487 |
|
| 488 |
bool SkWebpCodec::onGetFrameInfo(int i, FrameInfo* frameInfo) const { |
| 489 |
if (i >= fFrameHolder.size()) { |
| 490 |
return false; |
| 491 |
} |
| 492 |
|
| 493 |
const Frame* frame = fFrameHolder.frame(i); |
| 494 |
if (!frame) { |
| 495 |
return false; |
| 496 |
} |
| 497 |
|
| 498 |
if (frameInfo) { |
| 499 |
// libwebp only reports fully received frames for an |
| 500 |
// animated image. |
| 501 |
frame->fillIn(frameInfo, true); |
| 502 |
} |
| 503 |
|
| 504 |
return true; |
| 505 |
} |
| 506 |
|
| 507 |
static bool is_8888(SkColorType colorType) { |
| 508 |
switch (colorType) { |
| 509 |
case kRGBA_8888_SkColorType: |
| 510 |
case kBGRA_8888_SkColorType: |
| 511 |
return true; |
| 512 |
default: |
| 513 |
return false; |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
namespace { |
| 518 |
|
| 519 |
// Requires that the src input be unpremultiplied (or opaque). |
| 520 |
class RPBlender final : SkNoncopyable { |
| 521 |
public: |
| 522 |
RPBlender(SkColorType dstCT, SkColorType srcCT, SkAlphaType dstAt, bool srcHasAlpha) |
| 523 |
{ |
| 524 |
fRP.appendLoadDst(dstCT, &fDstCtx); |
| 525 |
if (kUnpremul_SkAlphaType == dstAt) { |
| 526 |
fRP.append(SkRasterPipelineOp::premul_dst); |
| 527 |
} |
| 528 |
|
| 529 |
fRP.appendLoad(srcCT, &fSrcCtx); |
| 530 |
if (srcHasAlpha) { |
| 531 |
fRP.append(SkRasterPipelineOp::premul); |
| 532 |
} |
| 533 |
|
| 534 |
fRP.append(SkRasterPipelineOp::srcover); |
| 535 |
|
| 536 |
if (kUnpremul_SkAlphaType == dstAt) { |
| 537 |
fRP.append(SkRasterPipelineOp::unpremul); |
| 538 |
} |
| 539 |
fRP.appendStore(dstCT, &fDstCtx); |
| 540 |
} |
| 541 |
|
| 542 |
void blendLine(void* dst, const void* src, int width) { |
| 543 |
fDstCtx = { dst, 0 }; |
| 544 |
fSrcCtx = { const_cast<void*>(src), 0 }; |
| 545 |
|
| 546 |
fRP.run(0, 0, width, 1); |
| 547 |
} |
| 548 |
|
| 549 |
private: |
| 550 |
SkRasterPipelineContexts::MemoryCtx fDstCtx, fSrcCtx; |
| 551 |
|
| 552 |
SkRasterPipeline_<256> fRP; |
| 553 |
}; |
| 554 |
|
| 555 |
} // namespace |
| 556 |
|
| 557 |
SkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, |
| 558 |
const Options& options, int* rowsDecodedPtr) { |
| 559 |
const int index = options.fFrameIndex; |
| 560 |
SkASSERT(0 == index || index < fFrameHolder.size()); |
| 561 |
SkASSERT(0 == index || !options.fSubset); |
| 562 |
|
| 563 |
WebPDecoderConfig config; |
| 564 |
if (0 == WebPInitDecoderConfig(&config)) { |
| 565 |
// ABI mismatch. |
| 566 |
// FIXME: New enum for this? |
| 567 |
return kInvalidInput; |
| 568 |
} |
| 569 |
|
| 570 |
// Free any memory associated with the buffer. Must be called last, so we declare it first. |
| 571 |
SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output)); |
| 572 |
|
| 573 |
WebPIterator frame; |
| 574 |
SkAutoTCallVProc<WebPIterator, WebPDemuxReleaseIterator> autoFrame(&frame); |
| 575 |
// If this succeeded in onGetFrameCount(), it should succeed again here. |
| 576 |
if (!ensureAllData()) { |
| 577 |
return kInvalidInput; |
| 578 |
} |
| 579 |
SkAssertResult(WebPDemuxGetFrame(fDemux, index + 1, &frame)); |
| 580 |
|
| 581 |
const bool independent = index == 0 ? true : |
| 582 |
(fFrameHolder.frame(index)->getRequiredFrame() == kNoFrame); |
| 583 |
// Get the frameRect. libwebp will have already signaled an error if this is not fully |
| 584 |
// contained by the canvas. |
| 585 |
auto frameRect = SkIRect::MakeXYWH(frame.x_offset, frame.y_offset, frame.width, frame.height); |
| 586 |
SkASSERT(this->bounds().contains(frameRect)); |
| 587 |
const bool frameIsSubset = frameRect != this->bounds(); |
| 588 |
if (independent && frameIsSubset) { |
| 589 |
SkSampler::Fill(dstInfo, dst, rowBytes, options.fZeroInitialized); |
| 590 |
} |
| 591 |
|
| 592 |
int dstX = frameRect.x(); |
| 593 |
int dstY = frameRect.y(); |
| 594 |
int subsetWidth = frameRect.width(); |
| 595 |
int subsetHeight = frameRect.height(); |
| 596 |
if (options.fSubset) { |
| 597 |
SkIRect subset = *options.fSubset; |
| 598 |
SkASSERT(this->bounds().contains(subset)); |
| 599 |
SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop)); |
| 600 |
SkASSERT(this->getValidSubset(&subset) && subset == *options.fSubset); |
| 601 |
|
| 602 |
if (!SkIRect::Intersects(subset, frameRect)) { |
| 603 |
return kSuccess; |
| 604 |
} |
| 605 |
|
| 606 |
int minXOffset = std::min(dstX, subset.x()); |
| 607 |
int minYOffset = std::min(dstY, subset.y()); |
| 608 |
dstX -= minXOffset; |
| 609 |
dstY -= minYOffset; |
| 610 |
frameRect.offset(-minXOffset, -minYOffset); |
| 611 |
subset.offset(-minXOffset, -minYOffset); |
| 612 |
|
| 613 |
// Just like we require that the requested subset x and y offset are even, libwebp |
| 614 |
// guarantees that the frame x and y offset are even (it's actually impossible to specify |
| 615 |
// an odd frame offset). So we can still guarantee that the adjusted offsets are even. |
| 616 |
SkASSERT(SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop)); |
| 617 |
|
| 618 |
SkIRect intersection; |
| 619 |
SkAssertResult(intersection.intersect(frameRect, subset)); |
| 620 |
subsetWidth = intersection.width(); |
| 621 |
subsetHeight = intersection.height(); |
| 622 |
|
| 623 |
config.options.use_cropping = 1; |
| 624 |
config.options.crop_left = subset.x(); |
| 625 |
config.options.crop_top = subset.y(); |
| 626 |
config.options.crop_width = subsetWidth; |
| 627 |
config.options.crop_height = subsetHeight; |
| 628 |
} |
| 629 |
|
| 630 |
// Ignore the frame size and offset when determining if scaling is necessary. |
| 631 |
int scaledWidth = subsetWidth; |
| 632 |
int scaledHeight = subsetHeight; |
| 633 |
SkISize srcSize = options.fSubset ? options.fSubset->size() : this->dimensions(); |
| 634 |
if (srcSize != dstInfo.dimensions()) { |
| 635 |
config.options.use_scaling = 1; |
| 636 |
|
| 637 |
if (frameIsSubset) { |
| 638 |
float scaleX = ((float) dstInfo.width()) / srcSize.width(); |
| 639 |
float scaleY = ((float) dstInfo.height()) / srcSize.height(); |
| 640 |
|
| 641 |
// We need to be conservative here and floor rather than round. |
| 642 |
// Otherwise, we may find ourselves decoding off the end of memory. |
| 643 |
dstX = scaleX * dstX; |
| 644 |
scaledWidth = scaleX * scaledWidth; |
| 645 |
dstY = scaleY * dstY; |
| 646 |
scaledHeight = scaleY * scaledHeight; |
| 647 |
if (0 == scaledWidth || 0 == scaledHeight) { |
| 648 |
return kSuccess; |
| 649 |
} |
| 650 |
} else { |
| 651 |
scaledWidth = dstInfo.width(); |
| 652 |
scaledHeight = dstInfo.height(); |
| 653 |
} |
| 654 |
|
| 655 |
config.options.scaled_width = scaledWidth; |
| 656 |
config.options.scaled_height = scaledHeight; |
| 657 |
} |
| 658 |
|
| 659 |
const bool blendWithPrevFrame = !independent && frame.blend_method == WEBP_MUX_BLEND |
| 660 |
&& frame.has_alpha; |
| 661 |
|
| 662 |
auto webpInfo = dstInfo; |
| 663 |
if (!frame.has_alpha) { |
| 664 |
webpInfo = webpInfo.makeAlphaType(kOpaque_SkAlphaType); |
| 665 |
} else if (this->colorXform() || blendWithPrevFrame) { |
| 666 |
// the colorXform and blend_line expect unpremul. |
| 667 |
webpInfo = webpInfo.makeAlphaType(kUnpremul_SkAlphaType); |
| 668 |
} |
| 669 |
if (this->colorXform()) { |
| 670 |
// Swizzling between RGBA and BGRA is zero cost in a color transform. So when we have a |
| 671 |
// color transform, we should decode to whatever is easiest for libwebp, and then let the |
| 672 |
// color transform swizzle if necessary. |
| 673 |
// Lossy webp is encoded as YUV (so RGBA and BGRA are the same cost). Lossless webp is |
| 674 |
// encoded as BGRA. This means decoding to BGRA is either faster or the same cost as RGBA. |
| 675 |
webpInfo = webpInfo.makeColorType(kBGRA_8888_SkColorType); |
| 676 |
} |
| 677 |
|
| 678 |
SkBitmap webpDst; |
| 679 |
if ((this->colorXform() && !is_8888(dstInfo.colorType())) || blendWithPrevFrame) { |
| 680 |
// We will decode the entire image and then perform the color transform. libwebp |
| 681 |
// does not provide a row-by-row API. This is a shame particularly when we do not want |
| 682 |
// 8888, since we will need to create another image sized buffer. |
| 683 |
webpDst.allocPixels(webpInfo); |
| 684 |
} else { |
| 685 |
// libwebp can decode directly into the output memory. |
| 686 |
webpDst.installPixels(webpInfo, dst, rowBytes); |
| 687 |
} |
| 688 |
|
| 689 |
config.output.colorspace = webp_decode_mode(webpInfo.colorType(), |
| 690 |
webpInfo.alphaType() == kPremul_SkAlphaType); |
| 691 |
config.output.is_external_memory = 1; |
| 692 |
|
| 693 |
config.output.u.RGBA.rgba = reinterpret_cast<uint8_t*>(webpDst.getAddr(dstX, dstY)); |
| 694 |
config.output.u.RGBA.stride = static_cast<int>(webpDst.rowBytes()); |
| 695 |
config.output.u.RGBA.size = webpDst.computeByteSize(); |
| 696 |
|
| 697 |
SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config)); |
| 698 |
if (!idec) { |
| 699 |
return kInvalidInput; |
| 700 |
} |
| 701 |
|
| 702 |
int rowsDecoded = 0; |
| 703 |
SkCodec::Result result; |
| 704 |
switch (WebPIUpdate(idec, frame.fragment.bytes, frame.fragment.size)) { |
| 705 |
case VP8_STATUS_OK: |
| 706 |
rowsDecoded = scaledHeight; |
| 707 |
result = kSuccess; |
| 708 |
break; |
| 709 |
case VP8_STATUS_SUSPENDED: |
| 710 |
if (!WebPIDecGetRGB(idec, &rowsDecoded, nullptr, nullptr, nullptr) |
| 711 |
|| rowsDecoded <= 0) { |
| 712 |
return kInvalidInput; |
| 713 |
} |
| 714 |
*rowsDecodedPtr = rowsDecoded + dstY; |
| 715 |
result = kIncompleteInput; |
| 716 |
break; |
| 717 |
default: |
| 718 |
return kInvalidInput; |
| 719 |
} |
| 720 |
|
| 721 |
const size_t dstBpp = dstInfo.bytesPerPixel(); |
| 722 |
dst = SkTAddOffset<void>(dst, dstBpp * dstX + rowBytes * dstY); |
| 723 |
const size_t srcRowBytes = config.output.u.RGBA.stride; |
| 724 |
|
| 725 |
const auto dstCT = dstInfo.colorType(); |
| 726 |
if (this->colorXform()) { |
| 727 |
uint32_t* xformSrc = (uint32_t*) config.output.u.RGBA.rgba; |
| 728 |
SkBitmap tmp; |
| 729 |
void* xformDst; |
| 730 |
|
| 731 |
if (blendWithPrevFrame) { |
| 732 |
// Xform into temporary bitmap big enough for one row. |
| 733 |
tmp.allocPixels(dstInfo.makeWH(scaledWidth, 1)); |
| 734 |
xformDst = tmp.getPixels(); |
| 735 |
} else { |
| 736 |
xformDst = dst; |
| 737 |
} |
| 738 |
|
| 739 |
std::optional<RPBlender> blender; |
| 740 |
if (blendWithPrevFrame) { |
| 741 |
blender.emplace(dstCT, dstCT, dstInfo.alphaType(), frame.has_alpha); |
| 742 |
} |
| 743 |
|
| 744 |
for (int y = 0; y < rowsDecoded; y++) { |
| 745 |
this->applyColorXform(xformDst, xformSrc, scaledWidth); |
| 746 |
if (blendWithPrevFrame) { |
| 747 |
blender->blendLine(dst, xformDst, scaledWidth); |
| 748 |
dst = SkTAddOffset<void>(dst, rowBytes); |
| 749 |
} else { |
| 750 |
xformDst = SkTAddOffset<void>(xformDst, rowBytes); |
| 751 |
} |
| 752 |
xformSrc = SkTAddOffset<uint32_t>(xformSrc, srcRowBytes); |
| 753 |
} |
| 754 |
} else if (blendWithPrevFrame) { |
| 755 |
RPBlender blender(dstCT, webpDst.colorType(), dstInfo.alphaType(), frame.has_alpha); |
| 756 |
|
| 757 |
const uint8_t* src = config.output.u.RGBA.rgba; |
| 758 |
|
| 759 |
for (int y = 0; y < rowsDecoded; y++) { |
| 760 |
blender.blendLine(dst, src, scaledWidth); |
| 761 |
src = SkTAddOffset<const uint8_t>(src, srcRowBytes); |
| 762 |
dst = SkTAddOffset<void>(dst, rowBytes); |
| 763 |
} |
| 764 |
} |
| 765 |
|
| 766 |
return result; |
| 767 |
} |
| 768 |
|
| 769 |
SkWebpCodec::SkWebpCodec(SkEncodedInfo&& info, std::unique_ptr<SkStream> stream, |
| 770 |
WebPDemuxer* demux, sk_sp<SkData> data, SkEncodedOrigin origin, |
| 771 |
bool onlyHeaderParsed) |
| 772 |
: INHERITED(std::move(info), skcms_PixelFormat_BGRA_8888, std::move(stream), |
| 773 |
origin) |
| 774 |
, fDemux(demux) |
| 775 |
, fData(std::move(data)) |
| 776 |
, fFailed(false) |
| 777 |
, fOnlyHeaderParsed(onlyHeaderParsed) |
| 778 |
{ |
| 779 |
const auto& eInfo = this->getEncodedInfo(); |
| 780 |
fFrameHolder.setScreenSize(eInfo.width(), eInfo.height()); |
| 781 |
} |
| 782 |
|
| 783 |
namespace SkWebpDecoder { |
| 784 |
bool IsWebp(const void* data, size_t len) { |
| 785 |
return SkWebpCodec::IsWebp(data, len); |
| 786 |
} |
| 787 |
|
| 788 |
std::unique_ptr<SkCodec> Decode(std::unique_ptr<SkStream> stream, |
| 789 |
SkCodec::Result* outResult, |
| 790 |
SkCodecs::DecodeContext) { |
| 791 |
SkCodec::Result resultStorage; |
| 792 |
if (!outResult) { |
| 793 |
outResult = &resultStorage; |
| 794 |
} |
| 795 |
return SkWebpCodec::MakeFromStream(std::move(stream), outResult); |
| 796 |
} |
| 797 |
|
| 798 |
std::unique_ptr<SkCodec> Decode(sk_sp<const SkData> data, |
| 799 |
SkCodec::Result* outResult, |
| 800 |
SkCodecs::DecodeContext) { |
| 801 |
if (!data) { |
| 802 |
if (outResult) { |
| 803 |
*outResult = SkCodec::kInvalidInput; |
| 804 |
} |
| 805 |
return nullptr; |
| 806 |
} |
| 807 |
return Decode(SkMemoryStream::Make(std::move(data)), outResult, nullptr); |
| 808 |
} |
| 809 |
} // namespace SkWebpDecoder |