Bug 1891340 - Part 1: Add parameters to customize the before and after icon tints...
[gecko.git] / image / decoders / nsPNGDecoder.cpp
blob324c7613cad7d2f6672d2f76fee2d49402fdb730
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "ImageLogging.h" // Must appear first
8 #include "nsPNGDecoder.h"
10 #include <algorithm>
11 #include <cstdint>
13 #include "gfxColor.h"
14 #include "gfxPlatform.h"
15 #include "imgFrame.h"
16 #include "nsColor.h"
17 #include "nsRect.h"
18 #include "nspr.h"
19 #include "png.h"
21 #include "RasterImage.h"
22 #include "SurfaceCache.h"
23 #include "SurfacePipeFactory.h"
24 #include "mozilla/DebugOnly.h"
25 #include "mozilla/Telemetry.h"
27 using namespace mozilla::gfx;
29 using std::min;
31 namespace mozilla {
32 namespace image {
34 static LazyLogModule sPNGLog("PNGDecoder");
35 static LazyLogModule sPNGDecoderAccountingLog("PNGDecoderAccounting");
37 // limit image dimensions (bug #251381, #591822, #967656, and #1283961)
38 #ifndef MOZ_PNG_MAX_WIDTH
39 # define MOZ_PNG_MAX_WIDTH 0x7fffffff // Unlimited
40 #endif
41 #ifndef MOZ_PNG_MAX_HEIGHT
42 # define MOZ_PNG_MAX_HEIGHT 0x7fffffff // Unlimited
43 #endif
45 /* Controls the maximum chunk size configuration for libpng. We set this to a
46 * very large number, 256MB specifically. */
47 static constexpr png_alloc_size_t kPngMaxChunkSize = 0x10000000;
49 nsPNGDecoder::AnimFrameInfo::AnimFrameInfo()
50 : mDispose(DisposalMethod::KEEP), mBlend(BlendMethod::OVER), mTimeout(0) {}
52 #ifdef PNG_APNG_SUPPORTED
54 int32_t GetNextFrameDelay(png_structp aPNG, png_infop aInfo) {
55 // Delay, in seconds, is delayNum / delayDen.
56 png_uint_16 delayNum = png_get_next_frame_delay_num(aPNG, aInfo);
57 png_uint_16 delayDen = png_get_next_frame_delay_den(aPNG, aInfo);
59 if (delayNum == 0) {
60 return 0; // SetFrameTimeout() will set to a minimum.
63 if (delayDen == 0) {
64 delayDen = 100; // So says the APNG spec.
67 // Need to cast delay_num to float to have a proper division and
68 // the result to int to avoid a compiler warning.
69 return static_cast<int32_t>(static_cast<double>(delayNum) * 1000 / delayDen);
72 nsPNGDecoder::AnimFrameInfo::AnimFrameInfo(png_structp aPNG, png_infop aInfo)
73 : mDispose(DisposalMethod::KEEP), mBlend(BlendMethod::OVER), mTimeout(0) {
74 png_byte dispose_op = png_get_next_frame_dispose_op(aPNG, aInfo);
75 png_byte blend_op = png_get_next_frame_blend_op(aPNG, aInfo);
77 if (dispose_op == PNG_DISPOSE_OP_PREVIOUS) {
78 mDispose = DisposalMethod::RESTORE_PREVIOUS;
79 } else if (dispose_op == PNG_DISPOSE_OP_BACKGROUND) {
80 mDispose = DisposalMethod::CLEAR;
81 } else {
82 mDispose = DisposalMethod::KEEP;
85 if (blend_op == PNG_BLEND_OP_SOURCE) {
86 mBlend = BlendMethod::SOURCE;
87 } else {
88 mBlend = BlendMethod::OVER;
91 mTimeout = GetNextFrameDelay(aPNG, aInfo);
93 #endif
95 // First 8 bytes of a PNG file
96 const uint8_t nsPNGDecoder::pngSignatureBytes[] = {137, 80, 78, 71,
97 13, 10, 26, 10};
99 nsPNGDecoder::nsPNGDecoder(RasterImage* aImage)
100 : Decoder(aImage),
101 mLexer(Transition::ToUnbuffered(State::FINISHED_PNG_DATA, State::PNG_DATA,
102 SIZE_MAX),
103 Transition::TerminateSuccess()),
104 mNextTransition(Transition::ContinueUnbuffered(State::PNG_DATA)),
105 mLastChunkLength(0),
106 mPNG(nullptr),
107 mInfo(nullptr),
108 mCMSLine(nullptr),
109 interlacebuf(nullptr),
110 mFormat(SurfaceFormat::UNKNOWN),
111 mChannels(0),
112 mPass(0),
113 mFrameIsHidden(false),
114 mDisablePremultipliedAlpha(false),
115 mGotInfoCallback(false),
116 mUsePipeTransform(false),
117 mErrorIsRecoverable(false),
118 mNumFrames(0) {}
120 nsPNGDecoder::~nsPNGDecoder() {
121 if (mPNG) {
122 png_destroy_read_struct(&mPNG, mInfo ? &mInfo : nullptr, nullptr);
124 if (mCMSLine) {
125 free(mCMSLine);
127 if (interlacebuf) {
128 free(interlacebuf);
132 nsPNGDecoder::TransparencyType nsPNGDecoder::GetTransparencyType(
133 const OrientedIntRect& aFrameRect) {
134 // Check if the image has a transparent color in its palette.
135 if (HasAlphaChannel()) {
136 return TransparencyType::eAlpha;
138 if (!aFrameRect.IsEqualEdges(FullFrame())) {
139 MOZ_ASSERT(HasAnimation());
140 return TransparencyType::eFrameRect;
143 return TransparencyType::eNone;
146 void nsPNGDecoder::PostHasTransparencyIfNeeded(
147 TransparencyType aTransparencyType) {
148 switch (aTransparencyType) {
149 case TransparencyType::eNone:
150 return;
152 case TransparencyType::eAlpha:
153 PostHasTransparency();
154 return;
156 case TransparencyType::eFrameRect:
157 // If the first frame of animated image doesn't draw into the whole image,
158 // then record that it is transparent. For subsequent frames, this doesn't
159 // affect transparency, because they're composited on top of all previous
160 // frames.
161 if (mNumFrames == 0) {
162 PostHasTransparency();
164 return;
168 // CreateFrame() is used for both simple and animated images.
169 nsresult nsPNGDecoder::CreateFrame(const FrameInfo& aFrameInfo) {
170 MOZ_ASSERT(HasSize());
171 MOZ_ASSERT(!IsMetadataDecode());
173 // Check if we have transparency, and send notifications if needed.
174 auto transparency = GetTransparencyType(aFrameInfo.mFrameRect);
175 PostHasTransparencyIfNeeded(transparency);
176 mFormat = transparency == TransparencyType::eNone ? SurfaceFormat::OS_RGBX
177 : SurfaceFormat::OS_RGBA;
179 // Make sure there's no animation or padding if we're downscaling.
180 MOZ_ASSERT_IF(Size() != OutputSize(), mNumFrames == 0);
181 MOZ_ASSERT_IF(Size() != OutputSize(), !GetImageMetadata().HasAnimation());
182 MOZ_ASSERT_IF(Size() != OutputSize(),
183 transparency != TransparencyType::eFrameRect);
185 Maybe<AnimationParams> animParams;
186 #ifdef PNG_APNG_SUPPORTED
187 if (!IsFirstFrameDecode() && png_get_valid(mPNG, mInfo, PNG_INFO_acTL)) {
188 mAnimInfo = AnimFrameInfo(mPNG, mInfo);
190 if (mAnimInfo.mDispose == DisposalMethod::CLEAR) {
191 // We may have to display the background under this image during
192 // animation playback, so we regard it as transparent.
193 PostHasTransparency();
196 animParams.emplace(
197 AnimationParams{aFrameInfo.mFrameRect.ToUnknownRect(),
198 FrameTimeout::FromRawMilliseconds(mAnimInfo.mTimeout),
199 mNumFrames, mAnimInfo.mBlend, mAnimInfo.mDispose});
201 #endif
203 // If this image is interlaced, we can display better quality intermediate
204 // results to the user by post processing them with ADAM7InterpolatingFilter.
205 SurfacePipeFlags pipeFlags = aFrameInfo.mIsInterlaced
206 ? SurfacePipeFlags::ADAM7_INTERPOLATE
207 : SurfacePipeFlags();
209 if (mNumFrames == 0) {
210 // The first frame may be displayed progressively.
211 pipeFlags |= SurfacePipeFlags::PROGRESSIVE_DISPLAY;
214 SurfaceFormat inFormat;
215 if (mTransform && !mUsePipeTransform) {
216 // QCMS will output in the correct format.
217 inFormat = mFormat;
218 } else if (transparency == TransparencyType::eAlpha) {
219 // We are outputting directly as RGBA, so we need to swap at this step.
220 inFormat = SurfaceFormat::R8G8B8A8;
221 } else {
222 // We have no alpha channel, so we need to unpack from RGB to BGRA.
223 inFormat = SurfaceFormat::R8G8B8;
226 // Only apply premultiplication if the frame has true alpha. If we ever
227 // support downscaling animated images, we will need to premultiply for frame
228 // rect transparency when downscaling as well.
229 if (transparency == TransparencyType::eAlpha && !mDisablePremultipliedAlpha) {
230 pipeFlags |= SurfacePipeFlags::PREMULTIPLY_ALPHA;
233 qcms_transform* pipeTransform = mUsePipeTransform ? mTransform : nullptr;
234 Maybe<SurfacePipe> pipe = SurfacePipeFactory::CreateSurfacePipe(
235 this, Size(), OutputSize(), aFrameInfo.mFrameRect, inFormat, mFormat,
236 animParams, pipeTransform, pipeFlags);
238 if (!pipe) {
239 mPipe = SurfacePipe();
240 return NS_ERROR_FAILURE;
243 mPipe = std::move(*pipe);
245 mFrameRect = aFrameInfo.mFrameRect;
246 mPass = 0;
248 MOZ_LOG(sPNGDecoderAccountingLog, LogLevel::Debug,
249 ("PNGDecoderAccounting: nsPNGDecoder::CreateFrame -- created "
250 "image frame with %dx%d pixels for decoder %p",
251 mFrameRect.Width(), mFrameRect.Height(), this));
253 return NS_OK;
256 // set timeout and frame disposal method for the current frame
257 void nsPNGDecoder::EndImageFrame() {
258 if (mFrameIsHidden) {
259 return;
262 mNumFrames++;
264 Opacity opacity = mFormat == SurfaceFormat::OS_RGBX
265 ? Opacity::FULLY_OPAQUE
266 : Opacity::SOME_TRANSPARENCY;
268 PostFrameStop(opacity);
271 nsresult nsPNGDecoder::InitInternal() {
272 mDisablePremultipliedAlpha =
273 bool(GetSurfaceFlags() & SurfaceFlags::NO_PREMULTIPLY_ALPHA);
275 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
276 static png_byte color_chunks[] = {99, 72, 82, 77, '\0', // cHRM
277 105, 67, 67, 80, '\0'}; // iCCP
278 static png_byte unused_chunks[] = {98, 75, 71, 68, '\0', // bKGD
279 101, 88, 73, 102, '\0', // eXIf
280 104, 73, 83, 84, '\0', // hIST
281 105, 84, 88, 116, '\0', // iTXt
282 111, 70, 70, 115, '\0', // oFFs
283 112, 67, 65, 76, '\0', // pCAL
284 115, 67, 65, 76, '\0', // sCAL
285 112, 72, 89, 115, '\0', // pHYs
286 115, 66, 73, 84, '\0', // sBIT
287 115, 80, 76, 84, '\0', // sPLT
288 116, 69, 88, 116, '\0', // tEXt
289 116, 73, 77, 69, '\0', // tIME
290 122, 84, 88, 116, '\0'}; // zTXt
291 #endif
293 // Initialize the container's source image header
294 // Always decode to 24 bit pixdepth
296 mPNG = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
297 nsPNGDecoder::error_callback,
298 nsPNGDecoder::warning_callback);
299 if (!mPNG) {
300 return NS_ERROR_OUT_OF_MEMORY;
303 mInfo = png_create_info_struct(mPNG);
304 if (!mInfo) {
305 png_destroy_read_struct(&mPNG, nullptr, nullptr);
306 return NS_ERROR_OUT_OF_MEMORY;
309 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
310 // Ignore unused chunks
311 if (mCMSMode == CMSMode::Off || IsMetadataDecode()) {
312 png_set_keep_unknown_chunks(mPNG, 1, color_chunks, 2);
315 png_set_keep_unknown_chunks(mPNG, 1, unused_chunks,
316 (int)sizeof(unused_chunks) / 5);
317 #endif
319 #ifdef PNG_SET_USER_LIMITS_SUPPORTED
320 png_set_user_limits(mPNG, MOZ_PNG_MAX_WIDTH, MOZ_PNG_MAX_HEIGHT);
321 png_set_chunk_malloc_max(mPNG, kPngMaxChunkSize);
322 #endif
324 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
325 // Disallow palette-index checking, for speed; we would ignore the warning
326 // anyhow. This feature was added at libpng version 1.5.10 and is disabled
327 // in the embedded libpng but enabled by default in the system libpng. This
328 // call also disables it in the system libpng, for decoding speed.
329 // Bug #745202.
330 png_set_check_for_invalid_index(mPNG, 0);
331 #endif
333 #ifdef PNG_SET_OPTION_SUPPORTED
334 # if defined(PNG_sRGB_PROFILE_CHECKS) && PNG_sRGB_PROFILE_CHECKS >= 0
335 // Skip checking of sRGB ICC profiles
336 png_set_option(mPNG, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);
337 # endif
339 # ifdef PNG_MAXIMUM_INFLATE_WINDOW
340 // Force a larger zlib inflate window as some images in the wild have
341 // incorrectly set metadata (specifically CMF bits) which prevent us from
342 // decoding them otherwise.
343 png_set_option(mPNG, PNG_MAXIMUM_INFLATE_WINDOW, PNG_OPTION_ON);
344 # endif
345 #endif
347 // use this as libpng "progressive pointer" (retrieve in callbacks)
348 png_set_progressive_read_fn(
349 mPNG, static_cast<png_voidp>(this), nsPNGDecoder::info_callback,
350 nsPNGDecoder::row_callback, nsPNGDecoder::end_callback);
352 return NS_OK;
355 LexerResult nsPNGDecoder::DoDecode(SourceBufferIterator& aIterator,
356 IResumable* aOnResume) {
357 MOZ_ASSERT(!HasError(), "Shouldn't call DoDecode after error!");
359 return mLexer.Lex(aIterator, aOnResume,
360 [=](State aState, const char* aData, size_t aLength) {
361 switch (aState) {
362 case State::PNG_DATA:
363 return ReadPNGData(aData, aLength);
364 case State::FINISHED_PNG_DATA:
365 return FinishedPNGData();
367 MOZ_CRASH("Unknown State");
371 LexerTransition<nsPNGDecoder::State> nsPNGDecoder::ReadPNGData(
372 const char* aData, size_t aLength) {
373 // If we were waiting until after returning from a yield to call
374 // CreateFrame(), call it now.
375 if (mNextFrameInfo) {
376 if (NS_FAILED(CreateFrame(*mNextFrameInfo))) {
377 return Transition::TerminateFailure();
380 MOZ_ASSERT(mImageData, "Should have a buffer now");
381 mNextFrameInfo = Nothing();
384 // libpng uses setjmp/longjmp for error handling.
385 if (setjmp(png_jmpbuf(mPNG))) {
386 return (GetFrameCount() > 0 && mErrorIsRecoverable)
387 ? Transition::TerminateSuccess()
388 : Transition::TerminateFailure();
391 // Pass the data off to libpng.
392 mLastChunkLength = aLength;
393 mNextTransition = Transition::ContinueUnbuffered(State::PNG_DATA);
394 png_process_data(mPNG, mInfo,
395 reinterpret_cast<unsigned char*>(const_cast<char*>((aData))),
396 aLength);
398 // Make sure that we've reached a terminal state if decoding is done.
399 MOZ_ASSERT_IF(GetDecodeDone(), mNextTransition.NextStateIsTerminal());
400 MOZ_ASSERT_IF(HasError(), mNextTransition.NextStateIsTerminal());
402 // Continue with whatever transition the callback code requested. We
403 // initialized this to Transition::ContinueUnbuffered(State::PNG_DATA) above,
404 // so by default we just continue the unbuffered read.
405 return mNextTransition;
408 LexerTransition<nsPNGDecoder::State> nsPNGDecoder::FinishedPNGData() {
409 // Since we set up an unbuffered read for SIZE_MAX bytes, if we actually read
410 // all that data something is really wrong.
411 MOZ_ASSERT_UNREACHABLE("Read the entire address space?");
412 return Transition::TerminateFailure();
415 // Sets up gamma pre-correction in libpng before our callback gets called.
416 // We need to do this if we don't end up with a CMS profile.
417 static void PNGDoGammaCorrection(png_structp png_ptr, png_infop info_ptr) {
418 double aGamma;
420 if (png_get_gAMA(png_ptr, info_ptr, &aGamma)) {
421 if ((aGamma <= 0.0) || (aGamma > 21474.83)) {
422 aGamma = 0.45455;
423 png_set_gAMA(png_ptr, info_ptr, aGamma);
425 png_set_gamma(png_ptr, 2.2, aGamma);
426 } else {
427 png_set_gamma(png_ptr, 2.2, 0.45455);
431 // Adapted from http://www.littlecms.com/pngchrm.c example code
432 uint32_t nsPNGDecoder::ReadColorProfile(png_structp png_ptr, png_infop info_ptr,
433 int color_type, bool* sRGBTag) {
434 // First try to see if iCCP chunk is present
435 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP)) {
436 png_uint_32 profileLen;
437 png_bytep profileData;
438 png_charp profileName;
439 int compression;
441 png_get_iCCP(png_ptr, info_ptr, &profileName, &compression, &profileData,
442 &profileLen);
444 mInProfile = qcms_profile_from_memory((char*)profileData, profileLen);
445 if (mInProfile) {
446 uint32_t profileSpace = qcms_profile_get_color_space(mInProfile);
448 bool mismatch = false;
449 if (color_type & PNG_COLOR_MASK_COLOR) {
450 if (profileSpace != icSigRgbData) {
451 mismatch = true;
453 } else {
454 if (profileSpace == icSigRgbData) {
455 png_set_gray_to_rgb(png_ptr);
456 } else if (profileSpace != icSigGrayData) {
457 mismatch = true;
461 if (mismatch) {
462 qcms_profile_release(mInProfile);
463 mInProfile = nullptr;
464 } else {
465 return qcms_profile_get_rendering_intent(mInProfile);
470 // Check sRGB chunk
471 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
472 *sRGBTag = true;
474 int fileIntent;
475 png_set_gray_to_rgb(png_ptr);
476 png_get_sRGB(png_ptr, info_ptr, &fileIntent);
477 uint32_t map[] = {QCMS_INTENT_PERCEPTUAL, QCMS_INTENT_RELATIVE_COLORIMETRIC,
478 QCMS_INTENT_SATURATION,
479 QCMS_INTENT_ABSOLUTE_COLORIMETRIC};
480 return map[fileIntent];
483 // Check gAMA/cHRM chunks
484 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) &&
485 png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) {
486 qcms_CIE_xyYTRIPLE primaries;
487 qcms_CIE_xyY whitePoint;
489 png_get_cHRM(png_ptr, info_ptr, &whitePoint.x, &whitePoint.y,
490 &primaries.red.x, &primaries.red.y, &primaries.green.x,
491 &primaries.green.y, &primaries.blue.x, &primaries.blue.y);
492 whitePoint.Y = primaries.red.Y = primaries.green.Y = primaries.blue.Y = 1.0;
494 double gammaOfFile;
496 png_get_gAMA(png_ptr, info_ptr, &gammaOfFile);
498 mInProfile = qcms_profile_create_rgb_with_gamma(whitePoint, primaries,
499 1.0 / gammaOfFile);
501 if (mInProfile) {
502 png_set_gray_to_rgb(png_ptr);
506 return QCMS_INTENT_PERCEPTUAL; // Our default
509 void nsPNGDecoder::info_callback(png_structp png_ptr, png_infop info_ptr) {
510 png_uint_32 width, height;
511 int bit_depth, color_type, interlace_type, compression_type, filter_type;
512 unsigned int channels;
514 png_bytep trans = nullptr;
515 int num_trans = 0;
517 nsPNGDecoder* decoder =
518 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
520 if (decoder->mGotInfoCallback) {
521 MOZ_LOG(sPNGLog, LogLevel::Warning,
522 ("libpng called info_callback more than once\n"));
523 return;
526 decoder->mGotInfoCallback = true;
528 // Always decode to 24-bit RGB or 32-bit RGBA
529 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
530 &interlace_type, &compression_type, &filter_type);
532 const OrientedIntRect frameRect(0, 0, width, height);
534 // Post our size to the superclass
535 decoder->PostSize(frameRect.Width(), frameRect.Height());
537 if (width > SurfaceCache::MaximumCapacity() / (bit_depth > 8 ? 16 : 8)) {
538 // libpng needs space to allocate two row buffers
539 png_error(decoder->mPNG, "Image is too wide");
542 if (decoder->HasError()) {
543 // Setting the size led to an error.
544 png_error(decoder->mPNG, "Sizing error");
547 if (color_type == PNG_COLOR_TYPE_PALETTE) {
548 png_set_expand(png_ptr);
551 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
552 png_set_expand(png_ptr);
555 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
556 png_color_16p trans_values;
557 png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &trans_values);
558 // libpng doesn't reject a tRNS chunk with out-of-range samples
559 // so we check it here to avoid setting up a useless opacity
560 // channel or producing unexpected transparent pixels (bug #428045)
561 if (bit_depth < 16) {
562 png_uint_16 sample_max = (1 << bit_depth) - 1;
563 if ((color_type == PNG_COLOR_TYPE_GRAY &&
564 trans_values->gray > sample_max) ||
565 (color_type == PNG_COLOR_TYPE_RGB &&
566 (trans_values->red > sample_max ||
567 trans_values->green > sample_max ||
568 trans_values->blue > sample_max))) {
569 // clear the tRNS valid flag and release tRNS memory
570 png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
571 num_trans = 0;
574 if (num_trans != 0) {
575 png_set_expand(png_ptr);
579 if (bit_depth == 16) {
580 png_set_scale_16(png_ptr);
583 // We only need to extract the color profile for non-metadata decodes. It is
584 // fairly expensive to read the profile and create the transform so we should
585 // avoid it if not necessary.
586 uint32_t intent = -1;
587 bool sRGBTag = false;
588 if (!decoder->IsMetadataDecode()) {
589 if (decoder->mCMSMode != CMSMode::Off) {
590 intent = gfxPlatform::GetRenderingIntent();
591 uint32_t pIntent =
592 decoder->ReadColorProfile(png_ptr, info_ptr, color_type, &sRGBTag);
593 // If we're not mandating an intent, use the one from the image.
594 if (intent == uint32_t(-1)) {
595 intent = pIntent;
598 if (!decoder->mInProfile || !decoder->GetCMSOutputProfile()) {
599 png_set_gray_to_rgb(png_ptr);
601 // only do gamma correction if CMS isn't entirely disabled
602 if (decoder->mCMSMode != CMSMode::Off) {
603 PNGDoGammaCorrection(png_ptr, info_ptr);
608 // Let libpng expand interlaced images.
609 const bool isInterlaced = interlace_type == PNG_INTERLACE_ADAM7;
610 if (isInterlaced) {
611 png_set_interlace_handling(png_ptr);
614 // now all of those things we set above are used to update various struct
615 // members and whatnot, after which we can get channels, rowbytes, etc.
616 png_read_update_info(png_ptr, info_ptr);
617 decoder->mChannels = channels = png_get_channels(png_ptr, info_ptr);
619 //---------------------------------------------------------------//
620 // copy PNG info into imagelib structs (formerly png_set_dims()) //
621 //---------------------------------------------------------------//
623 if (channels < 1 || channels > 4) {
624 png_error(decoder->mPNG, "Invalid number of channels");
627 #ifdef PNG_APNG_SUPPORTED
628 bool isAnimated = png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL);
629 if (isAnimated) {
630 int32_t rawTimeout = GetNextFrameDelay(png_ptr, info_ptr);
631 decoder->PostIsAnimated(FrameTimeout::FromRawMilliseconds(rawTimeout));
633 if (decoder->Size() != decoder->OutputSize() &&
634 !decoder->IsFirstFrameDecode()) {
635 MOZ_ASSERT_UNREACHABLE(
636 "Doing downscale-during-decode "
637 "for an animated image?");
638 png_error(decoder->mPNG, "Invalid downscale attempt"); // Abort decode.
641 #endif
643 auto transparency = decoder->GetTransparencyType(frameRect);
644 if (decoder->IsMetadataDecode()) {
645 // If we are animated then the first frame rect is either:
646 // 1) the whole image if the IDAT chunk is part of the animation
647 // 2) the frame rect of the first fDAT chunk otherwise.
648 // If we are not animated then we want to make sure to call
649 // PostHasTransparency in the metadata decode if we need to. So it's
650 // okay to pass IntRect(0, 0, width, height) here for animated images;
651 // they will call with the proper first frame rect in the full decode.
652 decoder->PostHasTransparencyIfNeeded(transparency);
654 // We have the metadata we're looking for, so stop here, before we allocate
655 // buffers below.
656 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
659 if (decoder->mInProfile && decoder->GetCMSOutputProfile()) {
660 qcms_data_type inType;
661 qcms_data_type outType;
663 uint32_t profileSpace = qcms_profile_get_color_space(decoder->mInProfile);
664 decoder->mUsePipeTransform = profileSpace != icSigGrayData;
665 if (decoder->mUsePipeTransform) {
666 // If the transform happens with SurfacePipe, it will be in RGBA if we
667 // have an alpha channel, because the swizzle and premultiplication
668 // happens after color management. Otherwise it will be in BGRA because
669 // the swizzle happens at the start.
670 if (transparency == TransparencyType::eAlpha) {
671 inType = QCMS_DATA_RGBA_8;
672 outType = QCMS_DATA_RGBA_8;
673 } else {
674 inType = gfxPlatform::GetCMSOSRGBAType();
675 outType = inType;
677 } else {
678 if (color_type & PNG_COLOR_MASK_ALPHA) {
679 inType = QCMS_DATA_GRAYA_8;
680 outType = gfxPlatform::GetCMSOSRGBAType();
681 } else {
682 inType = QCMS_DATA_GRAY_8;
683 outType = gfxPlatform::GetCMSOSRGBAType();
687 decoder->mTransform = qcms_transform_create(decoder->mInProfile, inType,
688 decoder->GetCMSOutputProfile(),
689 outType, (qcms_intent)intent);
690 } else if ((sRGBTag && decoder->mCMSMode == CMSMode::TaggedOnly) ||
691 decoder->mCMSMode == CMSMode::All) {
692 // If the transform happens with SurfacePipe, it will be in RGBA if we
693 // have an alpha channel, because the swizzle and premultiplication
694 // happens after color management. Otherwise it will be in OS_RGBA because
695 // the swizzle happens at the start.
696 if (transparency == TransparencyType::eAlpha) {
697 decoder->mTransform =
698 decoder->GetCMSsRGBTransform(SurfaceFormat::R8G8B8A8);
699 } else {
700 decoder->mTransform =
701 decoder->GetCMSsRGBTransform(SurfaceFormat::OS_RGBA);
703 decoder->mUsePipeTransform = true;
706 #ifdef PNG_APNG_SUPPORTED
707 if (isAnimated) {
708 png_set_progressive_frame_fn(png_ptr, nsPNGDecoder::frame_info_callback,
709 nullptr);
712 if (png_get_first_frame_is_hidden(png_ptr, info_ptr)) {
713 decoder->mFrameIsHidden = true;
714 } else {
715 #endif
716 nsresult rv = decoder->CreateFrame(FrameInfo{frameRect, isInterlaced});
717 if (NS_FAILED(rv)) {
718 png_error(decoder->mPNG, "CreateFrame failed");
720 MOZ_ASSERT(decoder->mImageData, "Should have a buffer now");
721 #ifdef PNG_APNG_SUPPORTED
723 #endif
725 if (decoder->mTransform && !decoder->mUsePipeTransform) {
726 decoder->mCMSLine =
727 static_cast<uint8_t*>(malloc(sizeof(uint32_t) * frameRect.Width()));
728 if (!decoder->mCMSLine) {
729 png_error(decoder->mPNG, "malloc of mCMSLine failed");
733 if (interlace_type == PNG_INTERLACE_ADAM7) {
734 if (frameRect.Height() <
735 INT32_MAX / (frameRect.Width() * int32_t(channels))) {
736 const size_t bufferSize =
737 channels * frameRect.Width() * frameRect.Height();
739 if (bufferSize > SurfaceCache::MaximumCapacity()) {
740 png_error(decoder->mPNG, "Insufficient memory to deinterlace image");
743 decoder->interlacebuf = static_cast<uint8_t*>(malloc(bufferSize));
745 if (!decoder->interlacebuf) {
746 png_error(decoder->mPNG, "malloc of interlacebuf failed");
751 void nsPNGDecoder::PostInvalidationIfNeeded() {
752 Maybe<SurfaceInvalidRect> invalidRect = mPipe.TakeInvalidRect();
753 if (!invalidRect) {
754 return;
757 PostInvalidation(invalidRect->mInputSpaceRect,
758 Some(invalidRect->mOutputSpaceRect));
761 void nsPNGDecoder::row_callback(png_structp png_ptr, png_bytep new_row,
762 png_uint_32 row_num, int pass) {
763 /* libpng comments:
765 * This function is called for every row in the image. If the
766 * image is interlacing, and you turned on the interlace handler,
767 * this function will be called for every row in every pass.
768 * Some of these rows will not be changed from the previous pass.
769 * When the row is not changed, the new_row variable will be
770 * nullptr. The rows and passes are called in order, so you don't
771 * really need the row_num and pass, but I'm supplying them
772 * because it may make your life easier.
774 * For the non-nullptr rows of interlaced images, you must call
775 * png_progressive_combine_row() passing in the row and the
776 * old row. You can call this function for nullptr rows (it will
777 * just return) and for non-interlaced images (it just does the
778 * memcpy for you) if it will make the code easier. Thus, you
779 * can just do this for all cases:
781 * png_progressive_combine_row(png_ptr, old_row, new_row);
783 * where old_row is what was displayed for previous rows. Note
784 * that the first pass (pass == 0 really) will completely cover
785 * the old row, so the rows do not have to be initialized. After
786 * the first pass (and only for interlaced images), you will have
787 * to pass the current row, and the function will combine the
788 * old row and the new row.
790 nsPNGDecoder* decoder =
791 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
793 if (decoder->mFrameIsHidden) {
794 return; // Skip this frame.
797 MOZ_ASSERT_IF(decoder->IsFirstFrameDecode(), decoder->mNumFrames == 0);
799 while (pass > decoder->mPass) {
800 // Advance to the next pass. We may have to do this multiple times because
801 // libpng will skip passes if the image is so small that no pixels have
802 // changed on a given pass, but ADAM7InterpolatingFilter needs to be reset
803 // once for every pass to perform interpolation properly.
804 decoder->mPipe.ResetToFirstRow();
805 decoder->mPass++;
808 const png_uint_32 height =
809 static_cast<png_uint_32>(decoder->mFrameRect.Height());
811 if (row_num >= height) {
812 // Bail if we receive extra rows. This is especially important because if we
813 // didn't, we might overflow the deinterlacing buffer.
814 MOZ_ASSERT_UNREACHABLE("libpng producing extra rows?");
815 return;
818 // Note that |new_row| may be null here, indicating that this is an interlaced
819 // image and |row_callback| is being called for a row that hasn't changed.
820 MOZ_ASSERT_IF(!new_row, decoder->interlacebuf);
822 if (decoder->interlacebuf) {
823 uint32_t width = uint32_t(decoder->mFrameRect.Width());
825 // We'll output the deinterlaced version of the row.
826 uint8_t* rowToWrite =
827 decoder->interlacebuf + (row_num * decoder->mChannels * width);
829 // Update the deinterlaced version of this row with the new data.
830 png_progressive_combine_row(png_ptr, rowToWrite, new_row);
832 decoder->WriteRow(rowToWrite);
833 } else {
834 decoder->WriteRow(new_row);
838 void nsPNGDecoder::WriteRow(uint8_t* aRow) {
839 MOZ_ASSERT(aRow);
841 uint8_t* rowToWrite = aRow;
842 uint32_t width = uint32_t(mFrameRect.Width());
844 // Apply color management to the row, if necessary, before writing it out.
845 // This is only needed for grayscale images.
846 if (mTransform && !mUsePipeTransform) {
847 MOZ_ASSERT(mCMSLine);
848 qcms_transform_data(mTransform, rowToWrite, mCMSLine, width);
849 rowToWrite = mCMSLine;
852 // Write this row to the SurfacePipe.
853 DebugOnly<WriteState> result =
854 mPipe.WriteBuffer(reinterpret_cast<uint32_t*>(rowToWrite));
855 MOZ_ASSERT(WriteState(result) != WriteState::FAILURE);
857 PostInvalidationIfNeeded();
860 void nsPNGDecoder::DoTerminate(png_structp aPNGStruct, TerminalState aState) {
861 // Stop processing data. Note that we intentionally ignore the return value of
862 // png_process_data_pause(), which tells us how many bytes of the data that
863 // was passed to png_process_data() have not been consumed yet, because now
864 // that we've reached a terminal state, we won't do any more decoding or call
865 // back into libpng anymore.
866 png_process_data_pause(aPNGStruct, /* save = */ false);
868 mNextTransition = aState == TerminalState::SUCCESS
869 ? Transition::TerminateSuccess()
870 : Transition::TerminateFailure();
873 void nsPNGDecoder::DoYield(png_structp aPNGStruct) {
874 // Pause data processing. png_process_data_pause() returns how many bytes of
875 // the data that was passed to png_process_data() have not been consumed yet.
876 // We use this information to tell StreamingLexer where to place us in the
877 // input stream when we come back from the yield.
878 png_size_t pendingBytes = png_process_data_pause(aPNGStruct,
879 /* save = */ false);
881 MOZ_ASSERT(pendingBytes < mLastChunkLength);
882 size_t consumedBytes = mLastChunkLength - min(pendingBytes, mLastChunkLength);
884 mNextTransition =
885 Transition::ContinueUnbufferedAfterYield(State::PNG_DATA, consumedBytes);
888 nsresult nsPNGDecoder::FinishInternal() {
889 // We shouldn't be called in error cases.
890 MOZ_ASSERT(!HasError(), "Can't call FinishInternal on error!");
892 if (IsMetadataDecode()) {
893 return NS_OK;
896 int32_t loop_count = 0;
897 #ifdef PNG_APNG_SUPPORTED
898 if (png_get_valid(mPNG, mInfo, PNG_INFO_acTL)) {
899 int32_t num_plays = png_get_num_plays(mPNG, mInfo);
900 loop_count = num_plays - 1;
902 #endif
904 if (InFrame()) {
905 EndImageFrame();
907 PostDecodeDone(loop_count);
909 return NS_OK;
912 #ifdef PNG_APNG_SUPPORTED
913 // got the header of a new frame that's coming
914 void nsPNGDecoder::frame_info_callback(png_structp png_ptr,
915 png_uint_32 frame_num) {
916 nsPNGDecoder* decoder =
917 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
919 // old frame is done
920 decoder->EndImageFrame();
922 const bool previousFrameWasHidden = decoder->mFrameIsHidden;
924 if (!previousFrameWasHidden && decoder->IsFirstFrameDecode()) {
925 // We're about to get a second non-hidden frame, but we only want the first.
926 // Stop decoding now. (And avoid allocating the unnecessary buffers below.)
927 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
930 // Only the first frame can be hidden, so unhide unconditionally here.
931 decoder->mFrameIsHidden = false;
933 // Save the information necessary to create the frame; we'll actually create
934 // it when we return from the yield.
935 const OrientedIntRect frameRect(
936 png_get_next_frame_x_offset(png_ptr, decoder->mInfo),
937 png_get_next_frame_y_offset(png_ptr, decoder->mInfo),
938 png_get_next_frame_width(png_ptr, decoder->mInfo),
939 png_get_next_frame_height(png_ptr, decoder->mInfo));
940 const bool isInterlaced = bool(decoder->interlacebuf);
942 # ifndef MOZ_EMBEDDED_LIBPNG
943 // if using system library, check frame_width and height against 0
944 if (frameRect.width == 0) {
945 png_error(png_ptr, "Frame width must not be 0");
947 if (frameRect.height == 0) {
948 png_error(png_ptr, "Frame height must not be 0");
950 # endif
952 const FrameInfo info{frameRect, isInterlaced};
954 // If the previous frame was hidden, skip the yield (which will mislead the
955 // caller, who will think the previous frame was real) and just allocate the
956 // new frame here.
957 if (previousFrameWasHidden) {
958 if (NS_FAILED(decoder->CreateFrame(info))) {
959 return decoder->DoTerminate(png_ptr, TerminalState::FAILURE);
962 MOZ_ASSERT(decoder->mImageData, "Should have a buffer now");
963 return; // No yield, so we'll just keep decoding.
966 // Yield to the caller to notify them that the previous frame is now complete.
967 decoder->mNextFrameInfo = Some(info);
968 return decoder->DoYield(png_ptr);
970 #endif
972 void nsPNGDecoder::end_callback(png_structp png_ptr, png_infop info_ptr) {
973 /* libpng comments:
975 * this function is called when the whole image has been read,
976 * including any chunks after the image (up to and including
977 * the IEND). You will usually have the same info chunk as you
978 * had in the header, although some data may have been added
979 * to the comments and time fields.
981 * Most people won't do much here, perhaps setting a flag that
982 * marks the image as finished.
985 nsPNGDecoder* decoder =
986 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
988 // We shouldn't get here if we've hit an error
989 MOZ_ASSERT(!decoder->HasError(), "Finishing up PNG but hit error!");
991 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
994 void nsPNGDecoder::error_callback(png_structp png_ptr,
995 png_const_charp error_msg) {
996 MOZ_LOG(sPNGLog, LogLevel::Error, ("libpng error: %s\n", error_msg));
998 nsPNGDecoder* decoder =
999 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
1001 if (strstr(error_msg, "invalid chunk type")) {
1002 decoder->mErrorIsRecoverable = true;
1003 } else {
1004 decoder->mErrorIsRecoverable = false;
1007 png_longjmp(png_ptr, 1);
1010 void nsPNGDecoder::warning_callback(png_structp png_ptr,
1011 png_const_charp warning_msg) {
1012 MOZ_LOG(sPNGLog, LogLevel::Warning, ("libpng warning: %s\n", warning_msg));
1015 Maybe<Telemetry::HistogramID> nsPNGDecoder::SpeedHistogram() const {
1016 return Some(Telemetry::IMAGE_DECODE_SPEED_PNG);
1019 bool nsPNGDecoder::IsValidICOResource() const {
1020 // Only 32-bit RGBA PNGs are valid ICO resources; see here:
1021 // http://blogs.msdn.com/b/oldnewthing/archive/2010/10/22/10079192.aspx
1023 // If there are errors in the call to png_get_IHDR, the error_callback in
1024 // nsPNGDecoder.cpp is called. In this error callback we do a longjmp, so
1025 // we need to save the jump buffer here. Otherwise we'll end up without a
1026 // proper callstack.
1027 if (setjmp(png_jmpbuf(mPNG))) {
1028 // We got here from a longjmp call indirectly from png_get_IHDR via
1029 // error_callback. Ignore mErrorIsRecoverable: if we got an invalid chunk
1030 // error before even reading the IHDR we can't recover from that.
1031 return false;
1034 png_uint_32 png_width, // Unused
1035 png_height; // Unused
1037 int png_bit_depth, png_color_type;
1039 if (png_get_IHDR(mPNG, mInfo, &png_width, &png_height, &png_bit_depth,
1040 &png_color_type, nullptr, nullptr, nullptr)) {
1041 return ((png_color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
1042 png_color_type == PNG_COLOR_TYPE_RGB) &&
1043 png_bit_depth == 8);
1044 } else {
1045 return false;
1049 } // namespace image
1050 } // namespace mozilla