| 1 |
/* |
| 2 |
* Copyright 2024 Google LLC. |
| 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/SkPngRustCodec.h" |
| 9 |
|
| 10 |
#include <limits> |
| 11 |
#include <memory> |
| 12 |
#include <utility> |
| 13 |
|
| 14 |
#include "include/core/SkColorSpace.h" |
| 15 |
#include "include/core/SkStream.h" |
| 16 |
#include "include/private/SkEncodedInfo.h" |
| 17 |
#include "include/private/SkHdrMetadata.h" |
| 18 |
#include "include/private/base/SkAssert.h" |
| 19 |
#include "include/private/base/SkSafe32.h" |
| 20 |
#include "include/private/base/SkTemplates.h" |
| 21 |
#include "modules/skcms/skcms.h" |
| 22 |
#include "rust/png/FFI.rs.h" |
| 23 |
#include "rust/common/SpanUtils.h" |
| 24 |
#include "src/base/SkAutoMalloc.h" |
| 25 |
#include "src/base/SkSafeMath.h" |
| 26 |
#include "src/codec/SkFrameHolder.h" |
| 27 |
#include "src/codec/SkParseEncodedOrigin.h" |
| 28 |
#include "src/codec/SkPngPriv.h" |
| 29 |
#include "src/codec/SkSwizzler.h" |
| 30 |
#include "src/core/SkRasterPipeline.h" |
| 31 |
#include "src/core/SkRasterPipelineOpList.h" |
| 32 |
#include "third_party/rust/cxx/v1/cxx.h" |
| 33 |
|
| 34 |
#ifdef __clang__ |
| 35 |
#pragma clang diagnostic error "-Wconversion" |
| 36 |
#endif |
| 37 |
|
| 38 |
namespace { |
| 39 |
|
| 40 |
SkEncodedInfo::Color ToColor(rust_png::ColorType colorType, const rust_png::Reader& reader) { |
| 41 |
switch (colorType) { |
| 42 |
case rust_png::ColorType::Grayscale: |
| 43 |
return SkEncodedInfo::kGray_Color; |
| 44 |
case rust_png::ColorType::Rgb: |
| 45 |
if (reader.has_sbit_chunk()) { |
| 46 |
SkSpan<const uint8_t> sBit = ToSkSpan(reader.get_sbit_chunk()); |
| 47 |
|
| 48 |
// Restricting to 8-bit images, because of `SkEncodedInfo` |
| 49 |
// asserts. See also https://crbug.com/458852444. |
| 50 |
if (sBit.size() == 3 && reader.output_bits_per_component() == 8) { |
| 51 |
if (sBit[0] == 5 && sBit[1] == 6 && sBit[2] == 5) { |
| 52 |
return SkEncodedInfo::k565_Color; |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
return SkEncodedInfo::kRGB_Color; |
| 57 |
case rust_png::ColorType::GrayscaleAlpha: |
| 58 |
if (reader.has_sbit_chunk()) { |
| 59 |
SkSpan<const uint8_t> sBit = ToSkSpan(reader.get_sbit_chunk()); |
| 60 |
|
| 61 |
// Restricting to 8-bit images, because of `SkEncodedInfo` |
| 62 |
// asserts. See also https://crbug.com/458852444. |
| 63 |
if (sBit.size() == 2 && reader.output_bits_per_component() == 8) { |
| 64 |
if (sBit[0] == kGraySigBit_GrayAlphaIsJustAlpha && sBit[1] == 8) { |
| 65 |
return SkEncodedInfo::kXAlpha_Color; |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
return SkEncodedInfo::kGrayAlpha_Color; |
| 70 |
case rust_png::ColorType::Rgba: |
| 71 |
return SkEncodedInfo::kRGBA_Color; |
| 72 |
case rust_png::ColorType::Indexed: |
| 73 |
return SkEncodedInfo::kPalette_Color; |
| 74 |
} |
| 75 |
SK_ABORT("Unexpected `rust_png::ColorType`: %d", static_cast<int>(colorType)); |
| 76 |
} |
| 77 |
|
| 78 |
SkEncodedInfo::Alpha ToAlpha(rust_png::ColorType colorType, const rust_png::Reader& reader) { |
| 79 |
switch (colorType) { |
| 80 |
case rust_png::ColorType::Grayscale: |
| 81 |
case rust_png::ColorType::Rgb: |
| 82 |
return SkEncodedInfo::kOpaque_Alpha; |
| 83 |
case rust_png::ColorType::GrayscaleAlpha: |
| 84 |
case rust_png::ColorType::Rgba: |
| 85 |
return SkEncodedInfo::kUnpremul_Alpha; |
| 86 |
case rust_png::ColorType::Indexed: |
| 87 |
if (reader.has_trns_chunk()) { |
| 88 |
return SkEncodedInfo::kUnpremul_Alpha; |
| 89 |
} else { |
| 90 |
return SkEncodedInfo::kOpaque_Alpha; |
| 91 |
} |
| 92 |
} |
| 93 |
SK_ABORT("Unexpected `rust_png::ColorType`: %d", static_cast<int>(colorType)); |
| 94 |
} |
| 95 |
|
| 96 |
SkCodecAnimation::DisposalMethod ToDisposalMethod(rust_png::DisposeOp op) { |
| 97 |
switch (op) { |
| 98 |
case rust_png::DisposeOp::None: |
| 99 |
return SkCodecAnimation::DisposalMethod::kKeep; |
| 100 |
case rust_png::DisposeOp::Background: |
| 101 |
return SkCodecAnimation::DisposalMethod::kRestoreBGColor; |
| 102 |
case rust_png::DisposeOp::Previous: |
| 103 |
return SkCodecAnimation::DisposalMethod::kRestorePrevious; |
| 104 |
} |
| 105 |
SK_ABORT("Unexpected `rust_png::DisposeOp`: %d", static_cast<int>(op)); |
| 106 |
} |
| 107 |
|
| 108 |
SkCodecAnimation::Blend ToBlend(rust_png::BlendOp op) { |
| 109 |
switch (op) { |
| 110 |
case rust_png::BlendOp::Source: |
| 111 |
return SkCodecAnimation::Blend::kSrc; |
| 112 |
case rust_png::BlendOp::Over: |
| 113 |
return SkCodecAnimation::Blend::kSrcOver; |
| 114 |
} |
| 115 |
SK_ABORT("Unexpected `rust_png::BlendOp`: %d", static_cast<int>(op)); |
| 116 |
} |
| 117 |
|
| 118 |
SkColorSpacePrimaries ToSkColorSpacePrimaries(const rust_png::ColorSpacePrimaries& p) { |
| 119 |
return SkColorSpacePrimaries({p.fRX, p.fRY, p.fGX, p.fGY, p.fBX, p.fBY, p.fWX, p.fWY}); |
| 120 |
} |
| 121 |
|
| 122 |
skhdr::MasteringDisplayColorVolume ToSkMDCV(const rust_png::MasteringDisplayColorVolume& mdcv) { |
| 123 |
return skhdr::MasteringDisplayColorVolume({ |
| 124 |
ToSkColorSpacePrimaries(mdcv.fDisplayPrimaries), |
| 125 |
mdcv.fMaximumDisplayMasteringLuminance, |
| 126 |
mdcv.fMinimumDisplayMasteringLuminance}); |
| 127 |
} |
| 128 |
|
| 129 |
skhdr::ContentLightLevelInformation ToSkCLLI(const rust_png::ContentLightLevelInfo& clli) { |
| 130 |
return skhdr::ContentLightLevelInformation({clli.fMaxCLL, clli.fMaxFALL}); |
| 131 |
} |
| 132 |
|
| 133 |
std::unique_ptr<SkCodecs::ColorProfile> CreateColorProfile(const rust_png::Reader& reader) { |
| 134 |
// NOTE: This method is based on `read_color_profile` in |
| 135 |
// `src/codec/SkPngCodec.cpp` but has been refactored to use Rust inputs |
| 136 |
// instead of `libpng`. |
| 137 |
|
| 138 |
// Considering the `cICP` chunk first, because the spec at |
| 139 |
// https://www.w3.org/TR/png-3/#cICP-chunk says: "This chunk, if understood |
| 140 |
// by the decoder, is the highest-precedence color chunk." |
| 141 |
uint8_t cicpPrimariesId = 0; |
| 142 |
uint8_t cicpTransferId = 0; |
| 143 |
uint8_t cicpMatrixId = 0; |
| 144 |
bool cicpIsFullRange = false; |
| 145 |
if (reader.try_get_cicp_chunk(cicpPrimariesId, cicpTransferId, cicpMatrixId, cicpIsFullRange)) { |
| 146 |
// https://www.w3.org/TR/png-3/#cICP-chunk says "RGB is currently the |
| 147 |
// only supported color model in PNG, and as such Matrix Coefficients |
| 148 |
// shall be set to 0." |
| 149 |
// |
| 150 |
// According to SkColorSpace::MakeCICP narrow range images are rare and |
| 151 |
// therefore not supported. |
| 152 |
if (cicpMatrixId == 0 && cicpIsFullRange) { |
| 153 |
sk_sp<SkColorSpace> colorSpace = |
| 154 |
SkColorSpace::MakeCICP(static_cast<SkNamedPrimaries::CicpId>(cicpPrimariesId), |
| 155 |
static_cast<SkNamedTransferFn::CicpId>(cicpTransferId)); |
| 156 |
if (colorSpace) { |
| 157 |
return SkCodecs::ColorProfile::Make(colorSpace); |
| 158 |
} |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
if (reader.has_iccp_chunk()) { |
| 163 |
// `SkData::MakeWithCopy` is resilient against 0-sized inputs, so |
| 164 |
// no need to check `rust_slice.empty()` here. |
| 165 |
rust::Slice<const uint8_t> rust_slice = reader.get_iccp_chunk(); |
| 166 |
sk_sp<SkData> owned_data = SkData::MakeWithCopy(rust_slice.data(), rust_slice.size()); |
| 167 |
std::unique_ptr<SkCodecs::ColorProfile> parsed_data = |
| 168 |
SkCodecs::ColorProfile::MakeICCProfile(std::move(owned_data)); |
| 169 |
if (parsed_data) { |
| 170 |
return parsed_data; |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
if (reader.is_srgb()) { |
| 175 |
// TODO(https://crbug.com/362304558): Consider the intent field from the |
| 176 |
// `sRGB` chunk. |
| 177 |
return nullptr; |
| 178 |
} |
| 179 |
|
| 180 |
// Next, check for presence of `gAMA` and `cHRM` chunks. |
| 181 |
float gamma = 0; |
| 182 |
// Unlike libpng, image-rs does not seem to validate the gamma value. |
| 183 |
// So we check explicitly for zero, which is an invalid value encountered in the wild. |
| 184 |
// TODO: upstream? |
| 185 |
if (!reader.try_get_gama(gamma) || gamma <= 0) { |
| 186 |
// We ignore whether `chRM` is present or not. |
| 187 |
// |
| 188 |
// This preserves the behavior decided in Chromium's 83587041dc5f1428c09 |
| 189 |
// (https://codereview.chromium.org/2469473002). The PNG spec states |
| 190 |
// that cHRM is valid even without gAMA but we cannot apply the cHRM |
| 191 |
// without guessing a gAMA. Color correction is not a guessing game, |
| 192 |
// so we match the behavior of Safari and Firefox instead (compat). |
| 193 |
return nullptr; |
| 194 |
} |
| 195 |
rust_png::ColorSpacePrimaries chrm; |
| 196 |
const bool got_chrm = reader.try_get_chrm(chrm); |
| 197 |
if (!got_chrm) { |
| 198 |
// If there is no `cHRM` chunk then check if `gamma` is neutral (in PNG |
| 199 |
// / `SkNamedTransferFn::k2Dot2` sense). `kPngGammaThreshold` mimics |
| 200 |
// `PNG_GAMMA_THRESHOLD_FIXED` from `libpng`. |
| 201 |
constexpr float kPngGammaThreshold = 0.05f; |
| 202 |
constexpr float kMinNeutralValue = 1.0f - kPngGammaThreshold; |
| 203 |
constexpr float kMaxNeutralValue = 1.0f + kPngGammaThreshold; |
| 204 |
float tmp = gamma * 2.2f; |
| 205 |
bool is_neutral = kMinNeutralValue < tmp && tmp < kMaxNeutralValue; |
| 206 |
if (is_neutral) { |
| 207 |
// Don't construct a custom color profile if the only encoded color |
| 208 |
// space information is a "neutral" gamma. This is primarily needed |
| 209 |
// for correctness (see // https://crbug.com/388025081), but may |
| 210 |
// also help with performance (using a slightly more direct |
| 211 |
// `SkSwizzler` instead of `skcms_Transform`). |
| 212 |
return nullptr; |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
// Construct a color profile based on `cHRM` and `gAMA` chunks. |
| 217 |
skcms_Matrix3x3 toXYZD50; |
| 218 |
if (got_chrm) { |
| 219 |
if (!ToSkColorSpacePrimaries(chrm).toXYZD50(&toXYZD50)) { |
| 220 |
return nullptr; |
| 221 |
} |
| 222 |
} else { |
| 223 |
// `blink::PNGImageDecoder` returns a null color profile when `gAMA` is |
| 224 |
// present without `cHRM`. We fall back to the sRGB profile instead |
| 225 |
// because we do gamma correction via `skcms_Transform` (rather than |
| 226 |
// relying on `libpng` gamma correction as the legacy Blink decoder does |
| 227 |
// in this scenario). |
| 228 |
toXYZD50 = SkNamedGamut::kSRGB; |
| 229 |
} |
| 230 |
|
| 231 |
skcms_TransferFunction fn; |
| 232 |
fn.a = 1.0f; |
| 233 |
fn.b = fn.c = fn.d = fn.e = fn.f = 0.0f; |
| 234 |
fn.g = 1.0f / gamma; |
| 235 |
|
| 236 |
return SkCodecs::ColorProfile::Make(fn, toXYZD50); |
| 237 |
} |
| 238 |
|
| 239 |
// Returns `nullopt` when input errors are encountered. |
| 240 |
std::optional<SkEncodedInfo> CreateEncodedInfo(const rust_png::Reader& reader) { |
| 241 |
rust_png::ColorType rustColor = reader.output_color_type(); |
| 242 |
SkEncodedInfo::Color skColor = ToColor(rustColor, reader); |
| 243 |
|
| 244 |
std::unique_ptr<SkCodecs::ColorProfile> profile = CreateColorProfile(reader); |
| 245 |
if (!SkPngCodecBase::isCompatibleColorProfileAndType(profile.get(), skColor)) { |
| 246 |
profile = nullptr; |
| 247 |
} |
| 248 |
|
| 249 |
skhdr::Metadata hdrMetadata; |
| 250 |
{ |
| 251 |
rust_png::MasteringDisplayColorVolume rust_mdcv; |
| 252 |
if (reader.try_get_mdcv_chunk(rust_mdcv)) { |
| 253 |
hdrMetadata.setMasteringDisplayColorVolume(ToSkMDCV(rust_mdcv)); |
| 254 |
} |
| 255 |
rust_png::ContentLightLevelInfo rust_clli; |
| 256 |
if (reader.try_get_clli_chunk(rust_clli)) { |
| 257 |
hdrMetadata.setContentLightLevelInformation(ToSkCLLI(rust_clli)); |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
// Protect against large PNGs. See http://bugzil.la/251381 for more details. |
| 262 |
constexpr uint32_t kMaxPNGSize = 1000000; |
| 263 |
if ((reader.width() > kMaxPNGSize) || (reader.height() > kMaxPNGSize)) { |
| 264 |
return std::nullopt; |
| 265 |
} |
| 266 |
// We checked image dimensions above, so here we can just assert that casts |
| 267 |
// from `uint32_t` to `int` work ok. |
| 268 |
// |
| 269 |
// We don't use a saturating cast, because this could invalidate `fcTL` |
| 270 |
// checks done within the `png` crate. For example, the new / truncated |
| 271 |
// image width could end up smaller than `fcTL.frameWidth`. |
| 272 |
SkSafeMath safe; |
| 273 |
int width = safe.castTo<int>(reader.width()); |
| 274 |
int height = safe.castTo<int>(reader.height()); |
| 275 |
SkASSERT_RELEASE(safe.ok()); |
| 276 |
|
| 277 |
return SkEncodedInfo::Make(width, |
| 278 |
height, |
| 279 |
skColor, |
| 280 |
ToAlpha(rustColor, reader), |
| 281 |
reader.output_bits_per_component(), // bitsPerComponent |
| 282 |
reader.output_bits_per_component(), // colorDepth |
| 283 |
std::move(profile), |
| 284 |
hdrMetadata); |
| 285 |
} |
| 286 |
|
| 287 |
SkCodec::Result ToSkCodecResult(rust_png::DecodingResult rustResult) { |
| 288 |
switch (rustResult) { |
| 289 |
case rust_png::DecodingResult::Success: |
| 290 |
case rust_png::DecodingResult::EndOfFrame: |
| 291 |
return SkCodec::kSuccess; |
| 292 |
case rust_png::DecodingResult::FormatError: |
| 293 |
return SkCodec::kErrorInInput; |
| 294 |
case rust_png::DecodingResult::ParameterError: |
| 295 |
return SkCodec::kInvalidParameters; |
| 296 |
case rust_png::DecodingResult::OtherIoError: |
| 297 |
case rust_png::DecodingResult::LimitsExceededError: |
| 298 |
return SkCodec::kInternalError; |
| 299 |
case rust_png::DecodingResult::IncompleteInput: |
| 300 |
return SkCodec::kIncompleteInput; |
| 301 |
} |
| 302 |
SK_ABORT("Unexpected `rust_png::DecodingResult`: %d", static_cast<int>(rustResult)); |
| 303 |
} |
| 304 |
|
| 305 |
void blendRow(SkSpan<uint8_t> dstRow, |
| 306 |
SkSpan<const uint8_t> srcRow, |
| 307 |
SkColorType color, |
| 308 |
SkAlphaType alpha) { |
| 309 |
SkASSERT_RELEASE(dstRow.size() >= srcRow.size()); |
| 310 |
SkRasterPipeline_<256> p; |
| 311 |
|
| 312 |
SkRasterPipelineContexts::MemoryCtx dstCtx = {dstRow.data(), 0}; |
| 313 |
p.appendLoadDst(color, &dstCtx); |
| 314 |
if (kUnpremul_SkAlphaType == alpha) { |
| 315 |
p.append(SkRasterPipelineOp::premul_dst); |
| 316 |
} |
| 317 |
|
| 318 |
SkRasterPipelineContexts::MemoryCtx srcCtx = { |
| 319 |
const_cast<void*>(static_cast<const void*>(srcRow.data())), |
| 320 |
0, |
| 321 |
}; |
| 322 |
p.appendLoad(color, &srcCtx); |
| 323 |
if (kUnpremul_SkAlphaType == alpha) { |
| 324 |
p.append(SkRasterPipelineOp::premul); |
| 325 |
} |
| 326 |
|
| 327 |
p.append(SkRasterPipelineOp::srcover); |
| 328 |
|
| 329 |
if (kUnpremul_SkAlphaType == alpha) { |
| 330 |
p.append(SkRasterPipelineOp::unpremul); |
| 331 |
} |
| 332 |
p.appendStore(color, &dstCtx); |
| 333 |
|
| 334 |
SkSafeMath safe; |
| 335 |
size_t bpp = safe.castTo<size_t>(SkColorTypeBytesPerPixel(color)); |
| 336 |
SkASSERT_RELEASE(safe.ok()); |
| 337 |
|
| 338 |
size_t width = srcRow.size() / bpp; |
| 339 |
p.run(0, 0, width, 1); |
| 340 |
} |
| 341 |
|
| 342 |
void blendAllRows(SkSpan<uint8_t> dstFrame, |
| 343 |
SkSpan<const uint8_t> srcFrame, |
| 344 |
size_t rowSize, |
| 345 |
size_t rowStride, |
| 346 |
SkColorType color, |
| 347 |
SkAlphaType alpha) { |
| 348 |
while (srcFrame.size() >= rowSize) { |
| 349 |
blendRow(dstFrame, srcFrame.first(rowSize), color, alpha); |
| 350 |
|
| 351 |
srcFrame = srcFrame.subspan(std::min(rowStride, srcFrame.size())); |
| 352 |
dstFrame = dstFrame.subspan(std::min(rowStride, dstFrame.size())); |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
SkEncodedOrigin GetEncodedOrigin(const rust_png::Reader& reader) { |
| 357 |
if (reader.has_exif_chunk()) { |
| 358 |
rust::Slice<const uint8_t> rust_slice = reader.get_exif_chunk(); |
| 359 |
SkEncodedOrigin origin; |
| 360 |
if (SkParseEncodedOrigin(rust_slice.data(), rust_slice.size(), &origin)) { |
| 361 |
return origin; |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
return kTopLeft_SkEncodedOrigin; |
| 366 |
} |
| 367 |
|
| 368 |
bool IsValidFctlIfAny(const SkEncodedInfo& imageInfo, |
| 369 |
const rust_png::Reader& reader) { |
| 370 |
// Enforce that if an `fcTL` appears before an `IDAT` chunk, then it has the |
| 371 |
// same dimensions as the ones in the earlier `IHDR` chunk. This |
| 372 |
// corresponds to the restrictions that the spec at |
| 373 |
// https://www.w3.org/TR/png-3/#fcTL-chunk places on "fcTL chunk |
| 374 |
// corresponding to the default image". |
| 375 |
// |
| 376 |
// Doing this check here is more robust than doing it inside |
| 377 |
// `setFrameInfoFromCurrentFctlChunk`, because the code elsewhere in |
| 378 |
// `SkPngRustCodec` may ignore the `fcTL` chunk (e.g. if |
| 379 |
// `idatIsNotPartOfAnimation` and/or if `acTL` chunk is missing). |
| 380 |
// |
| 381 |
// Reporting a hard error is more robust than trying to ignore the `fcTL` |
| 382 |
// chunk and falling back to decoding a static image, because such a |
| 383 |
// fallback would risk discrepancies between dimensions used in different |
| 384 |
// layers of the software stack (see https://crbug.com/428205250). |
| 385 |
// |
| 386 |
// This check is kind of a defense-in-depth - in the long-term the |
| 387 |
// dimensions should be checked in the Rust `png` crate itself |
| 388 |
// (see https://github.com/image-rs/image-png/pull/614 which hasn't yet been |
| 389 |
// released in a new crates.io version). |
| 390 |
if (reader.has_fctl_chunk()) { |
| 391 |
uint32_t width = 0; |
| 392 |
uint32_t height = 0; |
| 393 |
uint32_t xOffset = 0; |
| 394 |
uint32_t yOffset = 0; |
| 395 |
auto ignoredDisposeOp = rust_png::DisposeOp::None; |
| 396 |
auto ignoredBlendOp = rust_png::BlendOp::Source; |
| 397 |
uint32_t ignoredDurationMs = 0; |
| 398 |
reader.get_fctl_info(width, height, xOffset, yOffset, |
| 399 |
ignoredDisposeOp, ignoredBlendOp, ignoredDurationMs); |
| 400 |
|
| 401 |
SkSafeMath safe; |
| 402 |
int frameWidth = safe.castTo<int>(width); |
| 403 |
int frameHeight = safe.castTo<int>(height); |
| 404 |
if (!safe.ok()) { |
| 405 |
return false; |
| 406 |
} |
| 407 |
|
| 408 |
if (xOffset != 0 || frameWidth != imageInfo.width() || |
| 409 |
yOffset != 0 || frameHeight != imageInfo.height()) { |
| 410 |
return false; |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
return true; |
| 415 |
} |
| 416 |
|
| 417 |
} // namespace |
| 418 |
|
| 419 |
// static |
| 420 |
std::unique_ptr<SkPngRustCodec> SkPngRustCodec::MakeFromStream(std::unique_ptr<SkStream> stream, |
| 421 |
Result* result) { |
| 422 |
SkASSERT_RELEASE(stream); |
| 423 |
SkASSERT_RELEASE(result); |
| 424 |
|
| 425 |
auto inputAdapter = std::make_unique<rust::stream::SkStreamAdapter>(stream.get()); |
| 426 |
rust::Box<rust_png::ResultOfReader> resultOfReader = |
| 427 |
rust_png::new_reader(std::move(inputAdapter)); |
| 428 |
*result = ToSkCodecResult(resultOfReader->err()); |
| 429 |
if (*result != kSuccess) { |
| 430 |
return nullptr; |
| 431 |
} |
| 432 |
rust::Box<rust_png::Reader> reader = resultOfReader->unwrap(); |
| 433 |
|
| 434 |
std::optional<SkEncodedInfo> maybeImageInfo = CreateEncodedInfo(*reader); |
| 435 |
if (!maybeImageInfo.has_value()) { |
| 436 |
*result = kErrorInInput; |
| 437 |
return nullptr; |
| 438 |
} |
| 439 |
SkEncodedInfo& imageInfo = *maybeImageInfo; |
| 440 |
|
| 441 |
if (!IsValidFctlIfAny(imageInfo, *reader)) { |
| 442 |
*result = kErrorInInput; |
| 443 |
return nullptr; |
| 444 |
} |
| 445 |
|
| 446 |
return std::make_unique<SkPngRustCodec>( |
| 447 |
std::move(imageInfo), std::move(stream), std::move(reader)); |
| 448 |
} |
| 449 |
|
| 450 |
SkPngRustCodec::SkPngRustCodec(SkEncodedInfo&& encodedInfo, |
| 451 |
std::unique_ptr<SkStream> stream, |
| 452 |
rust::Box<rust_png::Reader> reader) |
| 453 |
: SkPngCodecBase(std::move(encodedInfo), |
| 454 |
// TODO(https://crbug.com/370522089): If/when `SkCodec` can |
| 455 |
// avoid unnecessary rewinding, then stop "hiding" our stream |
| 456 |
// from it. |
| 457 |
/* stream = */ nullptr, |
| 458 |
GetEncodedOrigin(*reader)) |
| 459 |
, fReader(std::move(reader)) |
| 460 |
, fPrivStream(std::move(stream)) |
| 461 |
, fFrameHolder(encodedInfo.width(), encodedInfo.height()) { |
| 462 |
SkASSERT_RELEASE(fPrivStream); |
| 463 |
|
| 464 |
bool idatIsNotPartOfAnimation = fReader->has_actl_chunk() && !fReader->has_fctl_chunk(); |
| 465 |
fFrameAtCurrentStreamPosition = idatIsNotPartOfAnimation ? -1 : 0; |
| 466 |
fStreamIsPositionedAtStartOfFrameData = true; |
| 467 |
if (!idatIsNotPartOfAnimation) { |
| 468 |
// This `appendNewFrame` call should always succeed because: |
| 469 |
// * `fFrameHolder.size()` is 0 at this point |
| 470 |
// * Width and height are already capped when calling `SkEncodedInfo::Make` |
| 471 |
// * `!fReader->has_fctl_chunk()` means that we don't need to worry |
| 472 |
// about validating other frame metadata. |
| 473 |
Result result = fFrameHolder.appendNewFrame(*fReader, this->getEncodedInfo()); |
| 474 |
SkASSERT_RELEASE(result == kSuccess); |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
SkPngRustCodec::~SkPngRustCodec() = default; |
| 479 |
|
| 480 |
SkCodec::Result SkPngRustCodec::readToStartOfNextFrame() { |
| 481 |
SkASSERT_RELEASE(fFrameAtCurrentStreamPosition < this->getRawFrameCount()); |
| 482 |
Result result = ToSkCodecResult(fReader->next_frame_info()); |
| 483 |
if (result != kSuccess) { |
| 484 |
fStreamIsPositionedAtStartOfFrameData = false; |
| 485 |
return result; |
| 486 |
} |
| 487 |
|
| 488 |
fStreamIsPositionedAtStartOfFrameData = true; |
| 489 |
fFrameAtCurrentStreamPosition++; |
| 490 |
if (fFrameAtCurrentStreamPosition == fFrameHolder.size()) { |
| 491 |
result = fFrameHolder.appendNewFrame(*fReader, this->getEncodedInfo()); |
| 492 |
} |
| 493 |
|
| 494 |
return result; |
| 495 |
} |
| 496 |
|
| 497 |
SkCodec::Result SkPngRustCodec::seekToStartOfFrame(int index) { |
| 498 |
// Callers of this `private` method should provide a valid `index`. |
| 499 |
// |
| 500 |
// `index == fFrameHolder.size()` means that we are seeking to the next |
| 501 |
// frame (i.e. to the first frame for which an `fcTL` chunk wasn't parsed |
| 502 |
// yet). |
| 503 |
SkASSERT_RELEASE((0 <= index) && (index <= fFrameHolder.size())); |
| 504 |
|
| 505 |
// TODO(https://crbug.com/371060427): Improve runtime performance by seeking |
| 506 |
// directly to the right offset in the stream, rather than calling `rewind` |
| 507 |
// here and moving one-frame-at-a-time via `readToStartOfNextFrame` below. |
| 508 |
if ((index < fFrameAtCurrentStreamPosition) || |
| 509 |
(index == fFrameAtCurrentStreamPosition && !fStreamIsPositionedAtStartOfFrameData)) { |
| 510 |
if (!fPrivStream->rewind()) { |
| 511 |
return kCouldNotRewind; |
| 512 |
} |
| 513 |
|
| 514 |
auto inputAdapter = |
| 515 |
std::make_unique<rust::stream::SkStreamAdapter>(fPrivStream.get()); |
| 516 |
rust::Box<rust_png::ResultOfReader> resultOfReader = |
| 517 |
rust_png::new_reader(std::move(inputAdapter)); |
| 518 |
|
| 519 |
// `SkPngRustCodec` constructor must have run before, and the |
| 520 |
// constructor got a successfully created reader - we therefore also |
| 521 |
// expect success here. |
| 522 |
SkASSERT_RELEASE(kSuccess == ToSkCodecResult(resultOfReader->err())); |
| 523 |
fReader = resultOfReader->unwrap(); |
| 524 |
|
| 525 |
bool idatIsNotPartOfAnimation = fReader->has_actl_chunk() && !fReader->has_fctl_chunk(); |
| 526 |
fFrameAtCurrentStreamPosition = idatIsNotPartOfAnimation ? -1 : 0; |
| 527 |
fStreamIsPositionedAtStartOfFrameData = true; |
| 528 |
} |
| 529 |
while (fFrameAtCurrentStreamPosition < index) { |
| 530 |
Result result = this->readToStartOfNextFrame(); |
| 531 |
if (result != kSuccess) { |
| 532 |
return result; |
| 533 |
} |
| 534 |
} |
| 535 |
|
| 536 |
return kSuccess; |
| 537 |
} |
| 538 |
|
| 539 |
int SkPngRustCodec::getRawFrameCount() const { |
| 540 |
if (!fReader->has_actl_chunk()) { |
| 541 |
return 1; |
| 542 |
} |
| 543 |
|
| 544 |
static_assert(sizeof(int) >= sizeof(int32_t), "Is it ok to use Sk64_pin_to_s32 below?"); |
| 545 |
uint32_t num_frames = fReader->get_actl_num_frames(); |
| 546 |
return Sk64_pin_to_s32(num_frames); |
| 547 |
} |
| 548 |
|
| 549 |
SkCodec::Result SkPngRustCodec::parseAdditionalFrameInfos() { |
| 550 |
while (fFrameHolder.size() < this->getRawFrameCount()) { |
| 551 |
int oldFrameCount = fFrameHolder.size(); |
| 552 |
|
| 553 |
Result result = this->seekToStartOfFrame(fFrameHolder.size()); |
| 554 |
if (result != kSuccess) { |
| 555 |
return result; |
| 556 |
} |
| 557 |
SkASSERT_RELEASE(fFrameHolder.size() == (oldFrameCount + 1)); |
| 558 |
} |
| 559 |
return kSuccess; |
| 560 |
} |
| 561 |
|
| 562 |
void SkPngRustCodec::getSubsetFromFullImage(SkSpan<const uint8_t> fullImageBuffer, |
| 563 |
SkSpan<uint8_t> dst, |
| 564 |
size_t dstRowStride, |
| 565 |
size_t offset) { |
| 566 |
// This only needs to be used in the case of interlaced images that need a subset, |
| 567 |
// otherwise we can decode row by row. |
| 568 |
SkASSERT_RELEASE(fReader->interlaced()); |
| 569 |
SkASSERT_RELEASE(this->options().fSubset); |
| 570 |
SkASSERT_RELEASE(fullImageBuffer.size() >= dst.size()); |
| 571 |
// We want the whole row and applyXformRow does the rest, so only offset to correct y value. |
| 572 |
fullImageBuffer = fullImageBuffer.subspan(offset); |
| 573 |
const size_t encodedRowBytes = this->getEncodedRowBytes(); |
| 574 |
|
| 575 |
for (int i = 0; i < this->options().fSubset->height(); ++i) { |
| 576 |
SkSpan<const uint8_t> srcRow = fullImageBuffer.first(encodedRowBytes); |
| 577 |
fullImageBuffer = fullImageBuffer.subspan(encodedRowBytes); |
| 578 |
|
| 579 |
SkSpan<uint8_t> dstRow = dst.first(dstRowStride); |
| 580 |
dst = dst.subspan(dstRowStride); |
| 581 |
|
| 582 |
// Copy the source row into the correct position in the destination. |
| 583 |
this->applyXformRow(dstRow, srcRow); |
| 584 |
} |
| 585 |
} |
| 586 |
|
| 587 |
SkCodec::Result SkPngRustCodec::startDecoding(const SkImageInfo& dstInfo, |
| 588 |
void* pixels, |
| 589 |
size_t rowBytes, |
| 590 |
const Options& options, |
| 591 |
DecodingState* decodingState) { |
| 592 |
// TODO(https://crbug.com/362830091): Consider handling `fSubset` for APNG. |
| 593 |
if (options.fSubset && this->isAnimated() != IsAnimated::kNo) { |
| 594 |
return kUnimplemented; |
| 595 |
} |
| 596 |
|
| 597 |
if (options.fFrameIndex < 0 || options.fFrameIndex >= fFrameHolder.size()) { |
| 598 |
return kInvalidParameters; |
| 599 |
} |
| 600 |
const SkFrame* frame = fFrameHolder.getFrame(options.fFrameIndex); |
| 601 |
SkASSERT_RELEASE(frame); |
| 602 |
|
| 603 |
Result result = this->seekToStartOfFrame(options.fFrameIndex); |
| 604 |
if (result != kSuccess) { |
| 605 |
return result; |
| 606 |
} |
| 607 |
|
| 608 |
// https://www.w3.org/TR/png-3/#11PLTE says that for color type 3 |
| 609 |
// (indexed-color), the PLTE chunk is required. OTOH, `Codec_InvalidImages` |
| 610 |
// expects that we will succeed in this case and produce *some* output. |
| 611 |
// |
| 612 |
// This check needs to happen after `seekToStartOfFrame`, because the act |
| 613 |
// of seeking-and/or-rewinding may reset whether `fReader` has encountered |
| 614 |
// an PLTE chunk yet or not. |
| 615 |
if (this->getEncodedInfo().color() == SkEncodedInfo::kPalette_Color && |
| 616 |
!fReader->has_plte_chunk()) { |
| 617 |
return kInvalidInput; |
| 618 |
} |
| 619 |
|
| 620 |
result = this->initializeXforms(dstInfo, options, frame->width()); |
| 621 |
if (result != kSuccess) { |
| 622 |
return result; |
| 623 |
} |
| 624 |
|
| 625 |
{ |
| 626 |
DecodingDstInfo& decodingDst = decodingState->fDecodingDstInfo; |
| 627 |
|
| 628 |
SkSafeMath safe; |
| 629 |
decodingDst.fDstRowStride = rowBytes; |
| 630 |
|
| 631 |
uint8_t dstBytesPerPixel = safe.castTo<uint8_t>(dstInfo.bytesPerPixel()); |
| 632 |
if (dstBytesPerPixel >= 32u) { |
| 633 |
return kInvalidParameters; |
| 634 |
} |
| 635 |
decodingDst.fDstBytesPerPixel = dstBytesPerPixel; |
| 636 |
|
| 637 |
size_t imageHeight = safe.castTo<size_t>(dstInfo.height()); |
| 638 |
size_t imageSize = safe.mul(rowBytes, imageHeight); |
| 639 |
|
| 640 |
size_t xPixelOffset = safe.castTo<size_t>(frame->xOffset()); |
| 641 |
size_t xByteOffsetFrame = safe.mul(dstBytesPerPixel, xPixelOffset); |
| 642 |
|
| 643 |
size_t yPixelOffset = safe.castTo<size_t>(frame->yOffset()); |
| 644 |
size_t yByteOffsetFrame = safe.mul(rowBytes, yPixelOffset); |
| 645 |
|
| 646 |
if (options.fSubset) { |
| 647 |
decodingState->fYByteOffset = safe.mul(safe.castTo<size_t>(this->getEncodedRowBytes()), |
| 648 |
safe.castTo<size_t>(options.fSubset->top())); |
| 649 |
decodingState->fFirstRow = options.fSubset->top(); |
| 650 |
decodingState->fLastRow = options.fSubset->bottom() - 1; |
| 651 |
} else { |
| 652 |
decodingState->fYByteOffset = 0; |
| 653 |
decodingState->fFirstRow = 0; |
| 654 |
decodingState->fLastRow = frame->yOffset() + frame->height() - 1; |
| 655 |
} |
| 656 |
|
| 657 |
size_t frameWidth = safe.castTo<size_t>(frame->width()); |
| 658 |
size_t rowSize = safe.mul(dstBytesPerPixel, frameWidth); |
| 659 |
size_t frameHeight = safe.castTo<size_t>(frame->height()); |
| 660 |
size_t frameHeightTimesRowStride = safe.mul(frameHeight, rowBytes); |
| 661 |
decodingDst.fDstRowSize = rowSize; |
| 662 |
|
| 663 |
size_t encodedImageSize = safe.mul(this->getEncodedRowBytes(), |
| 664 |
safe.castTo<size_t>(this->getEncodedInfo().height())); |
| 665 |
|
| 666 |
if (!safe.ok()) { |
| 667 |
return kErrorInInput; |
| 668 |
} |
| 669 |
|
| 670 |
decodingDst.fDst = SkSpan(static_cast<uint8_t*>(pixels), imageSize) |
| 671 |
.subspan(xByteOffsetFrame) |
| 672 |
.subspan(yByteOffsetFrame); |
| 673 |
if (frameHeightTimesRowStride < decodingDst.fDst.size()) { |
| 674 |
decodingDst.fDst = decodingDst.fDst.first(frameHeightTimesRowStride); |
| 675 |
} |
| 676 |
|
| 677 |
if (fReader->interlaced()) { |
| 678 |
// Use fPreblendBuffer to decode whole image untransformed, then truncate/xform later. |
| 679 |
if (options.fSubset) { |
| 680 |
decodingState->fPreblendBuffer.resize(encodedImageSize, 0x00); |
| 681 |
} else if (frame->getBlend() == SkCodecAnimation::Blend::kSrcOver) { |
| 682 |
decodingState->fPreblendBuffer.resize(decodingDst.fDst.size(), 0x00); |
| 683 |
} |
| 684 |
} else if (frame->getBlend() == SkCodecAnimation::Blend::kSrcOver) { |
| 685 |
decodingState->fPreblendBuffer.resize(rowSize, 0x00); |
| 686 |
} |
| 687 |
} |
| 688 |
|
| 689 |
return kSuccess; |
| 690 |
} |
| 691 |
|
| 692 |
void SkPngRustCodec::expandDecodedInterlacedRow(SkSpan<uint8_t> dstFrame, |
| 693 |
SkSpan<const uint8_t> srcRow, |
| 694 |
const DecodingDstInfo& decodingDst, |
| 695 |
bool xFormNeeded) { |
| 696 |
SkASSERT_RELEASE(fReader->interlaced()); |
| 697 |
std::vector<uint8_t> decodedInterlacedFullWidthRow; |
| 698 |
std::vector<uint8_t> xformedInterlacedRow; |
| 699 |
const size_t dstRowStride = decodingDst.fDstRowStride; |
| 700 |
if (xFormNeeded) { |
| 701 |
// Copy (potentially shorter for initial Adam7 passes) `srcRow` into a |
| 702 |
// full-frame-width `decodedInterlacedFullWidthRow`. This is needed because |
| 703 |
// `applyXformRow` requires full-width rows as input (can't change |
| 704 |
// `SkSwizzler::fSrcWidth` after `initializeXforms`). |
| 705 |
decodedInterlacedFullWidthRow.resize(this->getEncodedRowBytes(), 0x00); |
| 706 |
SkASSERT_RELEASE(decodedInterlacedFullWidthRow.size() >= srcRow.size()); |
| 707 |
memcpy(decodedInterlacedFullWidthRow.data(), srcRow.data(), srcRow.size()); |
| 708 |
|
| 709 |
xformedInterlacedRow.resize(decodingDst.fDstRowSize, 0x00); |
| 710 |
this->applyXformRow(xformedInterlacedRow, decodedInterlacedFullWidthRow); |
| 711 |
|
| 712 |
} |
| 713 |
|
| 714 |
const uint8_t dstBytesPerPixel = decodingDst.fDstBytesPerPixel; |
| 715 |
SkASSERT_RELEASE(dstBytesPerPixel < 32u); // Checked in `startDecoding`. |
| 716 |
if (xFormNeeded) { |
| 717 |
fReader->expand_last_interlaced_row(rust::Slice<uint8_t>(dstFrame), |
| 718 |
dstRowStride, |
| 719 |
rust::Slice<const uint8_t>(xformedInterlacedRow), |
| 720 |
dstBytesPerPixel * 8u); |
| 721 |
} else { |
| 722 |
fReader->expand_last_interlaced_row(rust::Slice<uint8_t>(dstFrame), |
| 723 |
dstRowStride, |
| 724 |
rust::Slice<const uint8_t>(srcRow), |
| 725 |
dstBytesPerPixel * 8u); |
| 726 |
} |
| 727 |
} |
| 728 |
|
| 729 |
// Given the dstInfo and the rust colortype/bits per component, determines if we |
| 730 |
// can use rust_png::Reader::read_row to decode directly into dst. |
| 731 |
bool SkPngRustCodec::canReadRow() { |
| 732 |
// Check alpha types |
| 733 |
if (this->dstInfo().alphaType() != kUnpremul_SkAlphaType) { |
| 734 |
return false; |
| 735 |
} |
| 736 |
// We use temporary buffer to read the full image for subsets. |
| 737 |
if (this->options().fSubset) { |
| 738 |
return false; |
| 739 |
} |
| 740 |
|
| 741 |
// Check color types |
| 742 |
rust_png::ColorType color_type = fReader->output_color_type(); |
| 743 |
uint8_t bits_per_component = fReader->output_bits_per_component(); |
| 744 |
switch (this->dstInfo().colorType()) { |
| 745 |
case kRGBA_8888_SkColorType: |
| 746 |
if (color_type != rust_png::ColorType::Rgba |
| 747 |
|| bits_per_component != 8) { |
| 748 |
return false; |
| 749 |
} |
| 750 |
break; |
| 751 |
case kGray_8_SkColorType: |
| 752 |
if (color_type != rust_png::ColorType::Grayscale |
| 753 |
|| bits_per_component != 8) { |
| 754 |
return false; |
| 755 |
} |
| 756 |
break; |
| 757 |
default: |
| 758 |
return false; |
| 759 |
} |
| 760 |
|
| 761 |
// Check profiles |
| 762 |
if (!!this->getEncodedInfo().profile() != !!this->dstInfo().colorSpace()) { |
| 763 |
return false; |
| 764 |
} |
| 765 |
if (this->getEncodedInfo().profile()) { |
| 766 |
SkASSERT_RELEASE(this->dstInfo().colorSpace()); |
| 767 |
skcms_ICCProfile dstProfile; |
| 768 |
this->dstInfo().colorSpace()->toProfile(&dstProfile); |
| 769 |
if (!skcms_ApproximatelyEqualProfiles(this->getEncodedInfo().profile(), &dstProfile)) { |
| 770 |
return false; |
| 771 |
} |
| 772 |
} |
| 773 |
|
| 774 |
return true; |
| 775 |
} |
| 776 |
|
| 777 |
SkCodec::Result SkPngRustCodec::incrementalDecodeXForm(DecodingState& decodingState, |
| 778 |
int* rowsDecodedPtr) { |
| 779 |
SkASSERT_RELEASE(!this->canReadRow()); |
| 780 |
this->initializeXformParams(); |
| 781 |
|
| 782 |
int rowsDecoded = 0; |
| 783 |
const bool interlaced = fReader->interlaced(); |
| 784 |
const bool subset = this->options().fSubset; |
| 785 |
DecodingDstInfo& decodingDst = decodingState.fDecodingDstInfo; |
| 786 |
|
| 787 |
int rowNum = 0; |
| 788 |
while (true) { |
| 789 |
rust::Slice<const uint8_t> decodedRow; |
| 790 |
fStreamIsPositionedAtStartOfFrameData = false; |
| 791 |
Result result = ToSkCodecResult(fReader->next_interlaced_row(decodedRow)); |
| 792 |
if (result != kSuccess) { |
| 793 |
if (result == kIncompleteInput && rowsDecodedPtr) { |
| 794 |
*rowsDecodedPtr = rowsDecoded; |
| 795 |
} |
| 796 |
return result; |
| 797 |
} |
| 798 |
|
| 799 |
// This is how FFI layer says "no more rows". We also want to stop reading rows |
| 800 |
// if we are at the end of our subset. |
| 801 |
if (decodedRow.empty() || rowNum > decodingState.fLastRow) { |
| 802 |
if (interlaced && !decodingState.fPreblendBuffer.empty()) { |
| 803 |
if (subset) { |
| 804 |
this->getSubsetFromFullImage(SkSpan<uint8_t>(decodingState.fPreblendBuffer), |
| 805 |
decodingDst.fDst, |
| 806 |
decodingDst.fDstRowStride, |
| 807 |
decodingState.fYByteOffset); |
| 808 |
} else { |
| 809 |
blendAllRows(decodingDst.fDst, |
| 810 |
decodingState.fPreblendBuffer, |
| 811 |
decodingDst.fDstRowSize, |
| 812 |
decodingDst.fDstRowStride, |
| 813 |
this->dstInfo().colorType(), |
| 814 |
this->dstInfo().alphaType()); |
| 815 |
} |
| 816 |
} |
| 817 |
if (!interlaced && !subset) { |
| 818 |
// All of the original `fDst` should be filled out at this point. |
| 819 |
SkASSERT_RELEASE(decodingDst.fDst.empty()); |
| 820 |
} |
| 821 |
|
| 822 |
// `static_cast` is ok, because `startDecoding` already validated `fFrameIndex`. |
| 823 |
fFrameHolder.markFrameAsFullyReceived(static_cast<size_t>(this->options().fFrameIndex)); |
| 824 |
return kSuccess; |
| 825 |
} |
| 826 |
|
| 827 |
if (interlaced) { |
| 828 |
if (decodingState.fPreblendBuffer.empty()) { |
| 829 |
this->expandDecodedInterlacedRow( |
| 830 |
decodingDst.fDst, decodedRow, decodingDst, /*xFormNeeded=*/true); |
| 831 |
} else { |
| 832 |
if (subset) { |
| 833 |
SkSafeMath safe; |
| 834 |
uint8_t encodedBytesPerPixel = safe.castTo<uint8_t>(this->getEncodedInfo() |
| 835 |
.makeImageInfo() |
| 836 |
.bytesPerPixel()); |
| 837 |
SkASSERT_RELEASE(safe.ok()); // Checked in `startDecoding`. |
| 838 |
DecodingDstInfo fullImageDecodingDst = |
| 839 |
{.fDst = decodingState.fPreblendBuffer, |
| 840 |
.fDstRowStride = this->getEncodedRowBytes(), |
| 841 |
.fDstRowSize = this->getEncodedRowBytes(), |
| 842 |
.fDstBytesPerPixel = encodedBytesPerPixel}; |
| 843 |
this->expandDecodedInterlacedRow(decodingState.fPreblendBuffer, |
| 844 |
decodedRow, |
| 845 |
fullImageDecodingDst, |
| 846 |
/*xFormNeeded=*/false); |
| 847 |
} else { |
| 848 |
this->expandDecodedInterlacedRow(decodingState.fPreblendBuffer, |
| 849 |
decodedRow, |
| 850 |
decodingDst, |
| 851 |
/*xFormNeeded=*/true); |
| 852 |
} |
| 853 |
} |
| 854 |
// `rowsDecoded` is not incremented, because full, contiguous rows |
| 855 |
// are not decoded until pass 6 (or 7 depending on how you look) of |
| 856 |
// Adam7 interlacing scheme. |
| 857 |
} else { |
| 858 |
if (rowNum++ < decodingState.fFirstRow) { |
| 859 |
continue; |
| 860 |
} |
| 861 |
if (decodingState.fPreblendBuffer.empty()) { |
| 862 |
this->applyXformRow(decodingDst.fDst, decodedRow); |
| 863 |
} else { |
| 864 |
this->applyXformRow(decodingState.fPreblendBuffer, decodedRow); |
| 865 |
blendRow(decodingDst.fDst, |
| 866 |
decodingState.fPreblendBuffer, |
| 867 |
this->dstInfo().colorType(), |
| 868 |
this->dstInfo().alphaType()); |
| 869 |
} |
| 870 |
|
| 871 |
decodingDst.fDst = decodingDst.fDst.subspan( |
| 872 |
std::min(decodingDst.fDstRowStride, decodingDst.fDst.size())); |
| 873 |
rowsDecoded++; |
| 874 |
} |
| 875 |
} |
| 876 |
} |
| 877 |
|
| 878 |
SkCodec::Result SkPngRustCodec::incrementalDecode(DecodingState& decodingState, |
| 879 |
int* rowsDecodedPtr) { |
| 880 |
SkASSERT_RELEASE(this->canReadRow()); |
| 881 |
int rowsDecoded = 0; |
| 882 |
const bool interlaced = fReader->interlaced(); |
| 883 |
rust::Slice<uint8_t> dstSlice; |
| 884 |
// If we have interlaced rows we have to copy into a temp buffer. |
| 885 |
std::vector<uint8_t> fullWidthRow; |
| 886 |
if (interlaced) { |
| 887 |
fullWidthRow.resize(this->getEncodedRowBytes()); |
| 888 |
dstSlice = rust::Slice<uint8_t>(fullWidthRow); |
| 889 |
} |
| 890 |
DecodingDstInfo& decodingDst = decodingState.fDecodingDstInfo; |
| 891 |
|
| 892 |
while (true) { |
| 893 |
if (!interlaced) { |
| 894 |
dstSlice = decodingState.fPreblendBuffer.empty() |
| 895 |
? rust::Slice<uint8_t>(decodingDst.fDst) |
| 896 |
: rust::Slice<uint8_t>(decodingState.fPreblendBuffer); |
| 897 |
} |
| 898 |
fStreamIsPositionedAtStartOfFrameData = false; |
| 899 |
|
| 900 |
rust_png::DecodingResult rustResult = fReader->read_row(dstSlice); |
| 901 |
Result result = ToSkCodecResult(rustResult); |
| 902 |
|
| 903 |
if (result != kSuccess) { |
| 904 |
if (result == kIncompleteInput && rowsDecodedPtr) { |
| 905 |
*rowsDecodedPtr = rowsDecoded; |
| 906 |
} |
| 907 |
return result; |
| 908 |
} |
| 909 |
|
| 910 |
// No more rows. |
| 911 |
if (rustResult == rust_png::DecodingResult::EndOfFrame) { |
| 912 |
if (interlaced && !decodingState.fPreblendBuffer.empty()) { |
| 913 |
blendAllRows(decodingDst.fDst, |
| 914 |
decodingState.fPreblendBuffer, |
| 915 |
decodingDst.fDstRowSize, |
| 916 |
decodingDst.fDstRowStride, |
| 917 |
this->dstInfo().colorType(), |
| 918 |
this->dstInfo().alphaType()); |
| 919 |
} |
| 920 |
|
| 921 |
if (!interlaced) { |
| 922 |
// All of the original `fDst` should be filled out at this point. |
| 923 |
SkASSERT_RELEASE(decodingDst.fDst.empty()); |
| 924 |
} |
| 925 |
// `static_cast` is ok, because `startDecoding` already validated `fFrameIndex`. |
| 926 |
fFrameHolder.markFrameAsFullyReceived(static_cast<size_t>(this->options().fFrameIndex)); |
| 927 |
return kSuccess; |
| 928 |
} |
| 929 |
|
| 930 |
// Expand interlaced rows or blend into previous frame if needed. |
| 931 |
if (interlaced) { |
| 932 |
if (decodingState.fPreblendBuffer.empty()) { |
| 933 |
this->expandDecodedInterlacedRow(decodingDst.fDst, |
| 934 |
dstSlice, |
| 935 |
decodingDst, |
| 936 |
/*xFormNeeded=*/false); |
| 937 |
} else { |
| 938 |
this->expandDecodedInterlacedRow(decodingState.fPreblendBuffer, |
| 939 |
dstSlice, |
| 940 |
decodingDst, |
| 941 |
/*xFormNeeded=*/false); |
| 942 |
} |
| 943 |
// `rowsDecoded` is not incremented, because full, contiguous rows |
| 944 |
// are not decoded until pass 6 (or 7 depending on how you look) of |
| 945 |
// Adam7 interlacing scheme. |
| 946 |
} else { |
| 947 |
if (!decodingState.fPreblendBuffer.empty()) { |
| 948 |
blendRow(decodingDst.fDst, |
| 949 |
decodingState.fPreblendBuffer, |
| 950 |
this->dstInfo().colorType(), |
| 951 |
this->dstInfo().alphaType()); |
| 952 |
} |
| 953 |
// Increment our pointer to dst memory. |
| 954 |
decodingDst.fDst = decodingDst.fDst.subspan( |
| 955 |
std::min(decodingDst.fDstRowStride, decodingDst.fDst.size())); |
| 956 |
rowsDecoded++; |
| 957 |
} |
| 958 |
} |
| 959 |
} |
| 960 |
|
| 961 |
SkCodec::Result SkPngRustCodec::onGetPixels(const SkImageInfo& dstInfo, |
| 962 |
void* pixels, |
| 963 |
size_t rowBytes, |
| 964 |
const Options& options, |
| 965 |
int* rowsDecoded) { |
| 966 |
DecodingState decodingState; |
| 967 |
Result result = this->startDecoding(dstInfo, pixels, rowBytes, options, &decodingState); |
| 968 |
if (result != kSuccess) { |
| 969 |
return result; |
| 970 |
} |
| 971 |
|
| 972 |
if (this->canReadRow()) { |
| 973 |
result = this->incrementalDecode(decodingState, rowsDecoded); |
| 974 |
} else { |
| 975 |
result = this->incrementalDecodeXForm(decodingState, rowsDecoded); |
| 976 |
} |
| 977 |
return result; |
| 978 |
} |
| 979 |
|
| 980 |
SkCodec::Result SkPngRustCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo, |
| 981 |
void* pixels, |
| 982 |
size_t rowBytes, |
| 983 |
const Options& options) { |
| 984 |
DecodingState decodingState; |
| 985 |
Result result = this->startDecoding(dstInfo, pixels, rowBytes, options, &decodingState); |
| 986 |
if (result != kSuccess) { |
| 987 |
return result; |
| 988 |
} |
| 989 |
|
| 990 |
// It is okay if `fIncrementalDecodingState` contains state of another, |
| 991 |
// partially decoded frame - in this case we want to clobber |
| 992 |
fIncrementalDecodingState = decodingState; |
| 993 |
return kSuccess; |
| 994 |
} |
| 995 |
|
| 996 |
SkCodec::Result SkPngRustCodec::onIncrementalDecode(int* rowsDecoded) { |
| 997 |
if (!fIncrementalDecodingState.has_value()) { |
| 998 |
return kInvalidParameters; |
| 999 |
} |
| 1000 |
|
| 1001 |
Result result; |
| 1002 |
if (this->canReadRow()) { |
| 1003 |
result = this->incrementalDecode(*fIncrementalDecodingState, rowsDecoded); |
| 1004 |
} else { |
| 1005 |
result = this->incrementalDecodeXForm(*fIncrementalDecodingState, rowsDecoded); |
| 1006 |
} |
| 1007 |
if (result != kIncompleteInput) { |
| 1008 |
// After successfully reading the whole row (`kSuccess`), and after a |
| 1009 |
// fatal error (only recoverable error is `kIncompleteInput`) our client |
| 1010 |
// should not call `onIncrementalDecode` again. This means that the |
| 1011 |
// incremental decoding state can be discarded at this point. |
| 1012 |
fIncrementalDecodingState.reset(); |
| 1013 |
} |
| 1014 |
return result; |
| 1015 |
} |
| 1016 |
|
| 1017 |
int SkPngRustCodec::onGetFrameCount() { |
| 1018 |
do { |
| 1019 |
if (!fCanParseAdditionalFrameInfos || fIncrementalDecodingState.has_value()) { |
| 1020 |
break; |
| 1021 |
} |
| 1022 |
|
| 1023 |
if (fPrivStream->hasLength()) { |
| 1024 |
size_t currentLength = fPrivStream->getLength(); |
| 1025 |
if (fMaxStreamLengthSeenWhenParsingAdditionalFrameInfos.has_value()) { |
| 1026 |
size_t oldLength = *fMaxStreamLengthSeenWhenParsingAdditionalFrameInfos; |
| 1027 |
// We use `>=` instead of `==`, because the underlying stream |
| 1028 |
// can be "cleared" - see https://crbug.com/431273809#comment4. |
| 1029 |
if (oldLength >= currentLength) { |
| 1030 |
// Don't retry `parseAdditionalFrameInfos` if the input |
| 1031 |
// didn't change (or is smaller than last time). |
| 1032 |
break; |
| 1033 |
} |
| 1034 |
} |
| 1035 |
fMaxStreamLengthSeenWhenParsingAdditionalFrameInfos = currentLength; |
| 1036 |
} |
| 1037 |
|
| 1038 |
switch (this->parseAdditionalFrameInfos()) { |
| 1039 |
case kIncompleteInput: |
| 1040 |
fCanParseAdditionalFrameInfos = true; |
| 1041 |
break; |
| 1042 |
case kSuccess: |
| 1043 |
SkASSERT_RELEASE(fFrameHolder.size() == this->getRawFrameCount()); |
| 1044 |
fCanParseAdditionalFrameInfos = false; |
| 1045 |
break; |
| 1046 |
default: |
| 1047 |
fCanParseAdditionalFrameInfos = false; |
| 1048 |
break; |
| 1049 |
} |
| 1050 |
} while (false); |
| 1051 |
|
| 1052 |
return fFrameHolder.size(); |
| 1053 |
} |
| 1054 |
|
| 1055 |
bool SkPngRustCodec::onGetFrameInfo(int index, FrameInfo* info) const { |
| 1056 |
return fFrameHolder.getFrameInfo(index, info); |
| 1057 |
} |
| 1058 |
|
| 1059 |
int SkPngRustCodec::onGetRepetitionCount() { |
| 1060 |
if (!fReader->has_actl_chunk()) { |
| 1061 |
return 0; |
| 1062 |
} |
| 1063 |
|
| 1064 |
uint32_t numFrames = fReader->get_actl_num_frames(); |
| 1065 |
if (numFrames <= 1) { |
| 1066 |
return 0; |
| 1067 |
} |
| 1068 |
|
| 1069 |
// APNG spec says that "`num_plays` indicates the number of times that this |
| 1070 |
// animation should play; if it is 0, the animation should play |
| 1071 |
// indefinitely." |
| 1072 |
SkSafeMath safe; |
| 1073 |
int numPlays = safe.castTo<int>(fReader->get_actl_num_plays()); |
| 1074 |
if ((numPlays == 0) || !safe.ok()) { |
| 1075 |
return kRepetitionCountInfinite; |
| 1076 |
} |
| 1077 |
|
| 1078 |
// Subtracting 1, because `SkCodec::onGetRepetitionCount` doc comment says |
| 1079 |
// that "This number does not include the first play through of each frame. |
| 1080 |
// For example, a repetition count of 4 means that each frame is played 5 |
| 1081 |
// times and then the animation stops." |
| 1082 |
return numPlays - 1; |
| 1083 |
} |
| 1084 |
|
| 1085 |
SkCodec::IsAnimated SkPngRustCodec::onIsAnimated() { |
| 1086 |
if (fReader->has_actl_chunk() && fReader->get_actl_num_frames() > 1) { |
| 1087 |
return IsAnimated::kYes; |
| 1088 |
} |
| 1089 |
return IsAnimated::kNo; |
| 1090 |
} |
| 1091 |
|
| 1092 |
std::optional<SkSpan<const SkPngCodecBase::PaletteColorEntry>> SkPngRustCodec::onTryGetPlteChunk() { |
| 1093 |
if (fReader->output_color_type() != rust_png::ColorType::Indexed) { |
| 1094 |
return std::nullopt; |
| 1095 |
} |
| 1096 |
|
| 1097 |
SkASSERT_RELEASE(fReader->has_plte_chunk()); // Checked in `startDecoding`. |
| 1098 |
SkSpan<const uint8_t> bytes = ToSkSpan(fReader->get_plte_chunk()); |
| 1099 |
|
| 1100 |
// Make sure that `bytes.size()` is a multiple of |
| 1101 |
// `sizeof(PaletteColorEntry)`. |
| 1102 |
constexpr size_t kEntrySize = sizeof(PaletteColorEntry); |
| 1103 |
bytes = bytes.first((bytes.size() / kEntrySize) * kEntrySize); |
| 1104 |
|
| 1105 |
// Alignment of `PaletteColorEntry` is 1, because its size is 3, and size |
| 1106 |
// has to be a multiple of alignment (every element of an array has to be |
| 1107 |
// aligned) + alignment is always a power of 2. And this means that |
| 1108 |
// `bytes.data()` is already aligned. |
| 1109 |
static_assert(kEntrySize == 3, ""); |
| 1110 |
static_assert(std::alignment_of<PaletteColorEntry>::value == 1, ""); |
| 1111 |
static_assert(std::alignment_of<uint8_t>::value == 1, ""); |
| 1112 |
SkSpan<const PaletteColorEntry> palette = SkSpan( |
| 1113 |
reinterpret_cast<const PaletteColorEntry*>(bytes.data()), bytes.size() / kEntrySize); |
| 1114 |
|
| 1115 |
return palette; |
| 1116 |
} |
| 1117 |
|
| 1118 |
std::optional<SkSpan<const uint8_t>> SkPngRustCodec::onTryGetTrnsChunk() { |
| 1119 |
if (fReader->output_color_type() != rust_png::ColorType::Indexed) { |
| 1120 |
return std::nullopt; |
| 1121 |
} |
| 1122 |
|
| 1123 |
if (!fReader->has_trns_chunk()) { |
| 1124 |
return std::nullopt; |
| 1125 |
} |
| 1126 |
|
| 1127 |
return ToSkSpan(fReader->get_trns_chunk()); |
| 1128 |
} |
| 1129 |
|
| 1130 |
class SkPngRustCodec::FrameHolder::PngFrame final : public SkFrame { |
| 1131 |
public: |
| 1132 |
PngFrame(int id, SkEncodedInfo::Alpha alpha) : SkFrame(id), fReportedAlpha(alpha) {} |
| 1133 |
|
| 1134 |
bool isFullyReceived() const { return fFullyReceived; } |
| 1135 |
void markAsFullyReceived() { fFullyReceived = true; } |
| 1136 |
|
| 1137 |
private: |
| 1138 |
SkEncodedInfo::Alpha onReportedAlpha() const override { return fReportedAlpha; } |
| 1139 |
|
| 1140 |
const SkEncodedInfo::Alpha fReportedAlpha; |
| 1141 |
bool fFullyReceived = false; |
| 1142 |
}; |
| 1143 |
|
| 1144 |
SkPngRustCodec::FrameHolder::FrameHolder(int width, int height) : SkFrameHolder() { |
| 1145 |
fScreenWidth = width; |
| 1146 |
fScreenHeight = height; |
| 1147 |
} |
| 1148 |
|
| 1149 |
const SkFrameHolder* SkPngRustCodec::getFrameHolder() const { return &fFrameHolder; } |
| 1150 |
|
| 1151 |
// We cannot use the SkCodec implementation since we pass nullptr to the superclass out of |
| 1152 |
// an abundance of caution w/r to rewinding the stream. |
| 1153 |
// |
| 1154 |
// TODO(https://crbug.com/370522089): See if `SkCodec` can be tweaked to avoid |
| 1155 |
// the need to hide the stream from it. |
| 1156 |
std::unique_ptr<SkStream> SkPngRustCodec::getEncodedData() const { |
| 1157 |
SkASSERT_RELEASE(fPrivStream); |
| 1158 |
return fPrivStream->duplicate(); |
| 1159 |
} |
| 1160 |
|
| 1161 |
SkPngRustCodec::FrameHolder::~FrameHolder() = default; |
| 1162 |
|
| 1163 |
const SkFrame* SkPngRustCodec::FrameHolder::onGetFrame(int unverifiedIndex) const { |
| 1164 |
SkSafeMath safe; |
| 1165 |
size_t index = safe.castTo<size_t>(unverifiedIndex); |
| 1166 |
if (safe.ok() && (index < fFrames.size())) { |
| 1167 |
return &fFrames[index]; |
| 1168 |
} |
| 1169 |
return nullptr; |
| 1170 |
} |
| 1171 |
|
| 1172 |
int SkPngRustCodec::FrameHolder::size() const { |
| 1173 |
// This invariant is maintained in `appendNewFrame`. |
| 1174 |
SkASSERT_RELEASE(SkTFitsIn<int>(fFrames.size())); |
| 1175 |
return static_cast<int>(fFrames.size()); |
| 1176 |
} |
| 1177 |
|
| 1178 |
void SkPngRustCodec::FrameHolder::markFrameAsFullyReceived(size_t index) { |
| 1179 |
SkASSERT_RELEASE(index < fFrames.size()); |
| 1180 |
fFrames[index].markAsFullyReceived(); |
| 1181 |
} |
| 1182 |
|
| 1183 |
bool SkPngRustCodec::FrameHolder::getFrameInfo(int index, FrameInfo* info) const { |
| 1184 |
const SkFrame* frame = this->getFrame(index); |
| 1185 |
if (frame && info) { |
| 1186 |
bool isFullyReceived = static_cast<const PngFrame*>(frame)->isFullyReceived(); |
| 1187 |
frame->fillIn(info, isFullyReceived); |
| 1188 |
} |
| 1189 |
return !!frame; |
| 1190 |
} |
| 1191 |
|
| 1192 |
SkCodec::Result SkPngRustCodec::FrameHolder::appendNewFrame(const rust_png::Reader& reader, |
| 1193 |
const SkEncodedInfo& info) { |
| 1194 |
// Ensure that `this->size()` fits into an `int`. `+ 1u` is used to account |
| 1195 |
// for `push_back` / `emplace_back` below. |
| 1196 |
if (!SkTFitsIn<int>(fFrames.size() + 1u)) { |
| 1197 |
return kErrorInInput; |
| 1198 |
} |
| 1199 |
int id = static_cast<int>(fFrames.size()); |
| 1200 |
|
| 1201 |
if (reader.has_actl_chunk() && reader.has_fctl_chunk()) { |
| 1202 |
if (!fFrames.empty()) { |
| 1203 |
// Having `fcTL` for a new frame means that the previous frame has been |
| 1204 |
// fully received (since all of the previous frame's `fdAT` / `IDAT` |
| 1205 |
// chunks must have come before the new frame's `fcTL` chunk). |
| 1206 |
fFrames.back().markAsFullyReceived(); |
| 1207 |
} |
| 1208 |
|
| 1209 |
PngFrame frame(id, info.alpha()); |
| 1210 |
SkCodec::Result result = this->setFrameInfoFromCurrentFctlChunk(reader, &frame); |
| 1211 |
if (result == SkCodec::kSuccess) { |
| 1212 |
fFrames.push_back(std::move(frame)); |
| 1213 |
} |
| 1214 |
return result; |
| 1215 |
} |
| 1216 |
|
| 1217 |
SkASSERT_RELEASE(!reader.has_actl_chunk() || !reader.has_fctl_chunk()); |
| 1218 |
SkASSERT_RELEASE(id == 0); |
| 1219 |
fFrames.emplace_back(id, info.alpha()); |
| 1220 |
SkFrame& frame = fFrames.back(); |
| 1221 |
frame.setXYWH(0, 0, info.width(), info.height()); |
| 1222 |
frame.setBlend(SkCodecAnimation::Blend::kSrc); |
| 1223 |
this->setAlphaAndRequiredFrame(&frame); |
| 1224 |
return kSuccess; |
| 1225 |
} |
| 1226 |
|
| 1227 |
SkCodec::Result SkPngRustCodec::FrameHolder::setFrameInfoFromCurrentFctlChunk( |
| 1228 |
const rust_png::Reader& reader, PngFrame* frame) { |
| 1229 |
SkASSERT_RELEASE(reader.has_fctl_chunk()); // Caller should guarantee this |
| 1230 |
SkASSERT_RELEASE(frame); |
| 1231 |
|
| 1232 |
uint32_t width = 0; |
| 1233 |
uint32_t height = 0; |
| 1234 |
uint32_t xOffset = 0; |
| 1235 |
uint32_t yOffset = 0; |
| 1236 |
auto disposeOp = rust_png::DisposeOp::None; |
| 1237 |
auto blendOp = rust_png::BlendOp::Source; |
| 1238 |
uint32_t durationMs = 0; |
| 1239 |
reader.get_fctl_info(width, height, xOffset, yOffset, disposeOp, blendOp, durationMs); |
| 1240 |
|
| 1241 |
{ |
| 1242 |
SkSafeMath safe; |
| 1243 |
frame->setXYWH(safe.castTo<int>(xOffset), |
| 1244 |
safe.castTo<int>(yOffset), |
| 1245 |
safe.castTo<int>(width), |
| 1246 |
safe.castTo<int>(height)); |
| 1247 |
frame->setDuration(safe.castTo<int>(durationMs)); |
| 1248 |
if (!safe.ok()) { |
| 1249 |
return kErrorInInput; |
| 1250 |
} |
| 1251 |
} |
| 1252 |
|
| 1253 |
frame->setDisposalMethod(ToDisposalMethod(disposeOp)); |
| 1254 |
|
| 1255 |
// https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chunk |
| 1256 |
// points out that "for the first frame the two blend modes are functionally |
| 1257 |
// equivalent" so we use `BlendOp::Source` because it has better performance |
| 1258 |
// characteristics. |
| 1259 |
if (frame->frameId() == 0) { |
| 1260 |
blendOp = rust_png::BlendOp::Source; |
| 1261 |
} |
| 1262 |
frame->setBlend(ToBlend(blendOp)); |
| 1263 |
|
| 1264 |
// Note: `setAlphaAndRequiredFrame` needs to be called last, because it |
| 1265 |
// depends on the other properties set above. |
| 1266 |
this->setAlphaAndRequiredFrame(frame); |
| 1267 |
return kSuccess; |
| 1268 |
} |