Bug 1803984 - Add tests for the interaction between speculative preloading and module...
[gecko.git] / image / decoders / nsPNGDecoder.cpp
blobafc2762515dec5c477b4e50a1ed25c6b7acac562
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 mNumFrames(0) {}
119 nsPNGDecoder::~nsPNGDecoder() {
120 if (mPNG) {
121 png_destroy_read_struct(&mPNG, mInfo ? &mInfo : nullptr, nullptr);
123 if (mCMSLine) {
124 free(mCMSLine);
126 if (interlacebuf) {
127 free(interlacebuf);
131 nsPNGDecoder::TransparencyType nsPNGDecoder::GetTransparencyType(
132 const OrientedIntRect& aFrameRect) {
133 // Check if the image has a transparent color in its palette.
134 if (HasAlphaChannel()) {
135 return TransparencyType::eAlpha;
137 if (!aFrameRect.IsEqualEdges(FullFrame())) {
138 MOZ_ASSERT(HasAnimation());
139 return TransparencyType::eFrameRect;
142 return TransparencyType::eNone;
145 void nsPNGDecoder::PostHasTransparencyIfNeeded(
146 TransparencyType aTransparencyType) {
147 switch (aTransparencyType) {
148 case TransparencyType::eNone:
149 return;
151 case TransparencyType::eAlpha:
152 PostHasTransparency();
153 return;
155 case TransparencyType::eFrameRect:
156 // If the first frame of animated image doesn't draw into the whole image,
157 // then record that it is transparent. For subsequent frames, this doesn't
158 // affect transparency, because they're composited on top of all previous
159 // frames.
160 if (mNumFrames == 0) {
161 PostHasTransparency();
163 return;
167 // CreateFrame() is used for both simple and animated images.
168 nsresult nsPNGDecoder::CreateFrame(const FrameInfo& aFrameInfo) {
169 MOZ_ASSERT(HasSize());
170 MOZ_ASSERT(!IsMetadataDecode());
172 // Check if we have transparency, and send notifications if needed.
173 auto transparency = GetTransparencyType(aFrameInfo.mFrameRect);
174 PostHasTransparencyIfNeeded(transparency);
175 mFormat = transparency == TransparencyType::eNone ? SurfaceFormat::OS_RGBX
176 : SurfaceFormat::OS_RGBA;
178 // Make sure there's no animation or padding if we're downscaling.
179 MOZ_ASSERT_IF(Size() != OutputSize(), mNumFrames == 0);
180 MOZ_ASSERT_IF(Size() != OutputSize(), !GetImageMetadata().HasAnimation());
181 MOZ_ASSERT_IF(Size() != OutputSize(),
182 transparency != TransparencyType::eFrameRect);
184 Maybe<AnimationParams> animParams;
185 #ifdef PNG_APNG_SUPPORTED
186 if (!IsFirstFrameDecode() && png_get_valid(mPNG, mInfo, PNG_INFO_acTL)) {
187 mAnimInfo = AnimFrameInfo(mPNG, mInfo);
189 if (mAnimInfo.mDispose == DisposalMethod::CLEAR) {
190 // We may have to display the background under this image during
191 // animation playback, so we regard it as transparent.
192 PostHasTransparency();
195 animParams.emplace(
196 AnimationParams{aFrameInfo.mFrameRect.ToUnknownRect(),
197 FrameTimeout::FromRawMilliseconds(mAnimInfo.mTimeout),
198 mNumFrames, mAnimInfo.mBlend, mAnimInfo.mDispose});
200 #endif
202 // If this image is interlaced, we can display better quality intermediate
203 // results to the user by post processing them with ADAM7InterpolatingFilter.
204 SurfacePipeFlags pipeFlags = aFrameInfo.mIsInterlaced
205 ? SurfacePipeFlags::ADAM7_INTERPOLATE
206 : SurfacePipeFlags();
208 if (mNumFrames == 0) {
209 // The first frame may be displayed progressively.
210 pipeFlags |= SurfacePipeFlags::PROGRESSIVE_DISPLAY;
213 SurfaceFormat inFormat;
214 if (mTransform && !mUsePipeTransform) {
215 // QCMS will output in the correct format.
216 inFormat = mFormat;
217 } else if (transparency == TransparencyType::eAlpha) {
218 // We are outputting directly as RGBA, so we need to swap at this step.
219 inFormat = SurfaceFormat::R8G8B8A8;
220 } else {
221 // We have no alpha channel, so we need to unpack from RGB to BGRA.
222 inFormat = SurfaceFormat::R8G8B8;
225 // Only apply premultiplication if the frame has true alpha. If we ever
226 // support downscaling animated images, we will need to premultiply for frame
227 // rect transparency when downscaling as well.
228 if (transparency == TransparencyType::eAlpha && !mDisablePremultipliedAlpha) {
229 pipeFlags |= SurfacePipeFlags::PREMULTIPLY_ALPHA;
232 qcms_transform* pipeTransform = mUsePipeTransform ? mTransform : nullptr;
233 Maybe<SurfacePipe> pipe = SurfacePipeFactory::CreateSurfacePipe(
234 this, Size(), OutputSize(), aFrameInfo.mFrameRect, inFormat, mFormat,
235 animParams, pipeTransform, pipeFlags);
237 if (!pipe) {
238 mPipe = SurfacePipe();
239 return NS_ERROR_FAILURE;
242 mPipe = std::move(*pipe);
244 mFrameRect = aFrameInfo.mFrameRect;
245 mPass = 0;
247 MOZ_LOG(sPNGDecoderAccountingLog, LogLevel::Debug,
248 ("PNGDecoderAccounting: nsPNGDecoder::CreateFrame -- created "
249 "image frame with %dx%d pixels for decoder %p",
250 mFrameRect.Width(), mFrameRect.Height(), this));
252 return NS_OK;
255 // set timeout and frame disposal method for the current frame
256 void nsPNGDecoder::EndImageFrame() {
257 if (mFrameIsHidden) {
258 return;
261 mNumFrames++;
263 Opacity opacity = mFormat == SurfaceFormat::OS_RGBX
264 ? Opacity::FULLY_OPAQUE
265 : Opacity::SOME_TRANSPARENCY;
267 PostFrameStop(opacity);
270 nsresult nsPNGDecoder::InitInternal() {
271 mDisablePremultipliedAlpha =
272 bool(GetSurfaceFlags() & SurfaceFlags::NO_PREMULTIPLY_ALPHA);
274 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
275 static png_byte color_chunks[] = {99, 72, 82, 77, '\0', // cHRM
276 105, 67, 67, 80, '\0'}; // iCCP
277 static png_byte unused_chunks[] = {98, 75, 71, 68, '\0', // bKGD
278 101, 88, 73, 102, '\0', // eXIf
279 104, 73, 83, 84, '\0', // hIST
280 105, 84, 88, 116, '\0', // iTXt
281 111, 70, 70, 115, '\0', // oFFs
282 112, 67, 65, 76, '\0', // pCAL
283 115, 67, 65, 76, '\0', // sCAL
284 112, 72, 89, 115, '\0', // pHYs
285 115, 66, 73, 84, '\0', // sBIT
286 115, 80, 76, 84, '\0', // sPLT
287 116, 69, 88, 116, '\0', // tEXt
288 116, 73, 77, 69, '\0', // tIME
289 122, 84, 88, 116, '\0'}; // zTXt
290 #endif
292 // Initialize the container's source image header
293 // Always decode to 24 bit pixdepth
295 mPNG = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
296 nsPNGDecoder::error_callback,
297 nsPNGDecoder::warning_callback);
298 if (!mPNG) {
299 return NS_ERROR_OUT_OF_MEMORY;
302 mInfo = png_create_info_struct(mPNG);
303 if (!mInfo) {
304 png_destroy_read_struct(&mPNG, nullptr, nullptr);
305 return NS_ERROR_OUT_OF_MEMORY;
308 #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
309 // Ignore unused chunks
310 if (mCMSMode == CMSMode::Off || IsMetadataDecode()) {
311 png_set_keep_unknown_chunks(mPNG, 1, color_chunks, 2);
314 png_set_keep_unknown_chunks(mPNG, 1, unused_chunks,
315 (int)sizeof(unused_chunks) / 5);
316 #endif
318 #ifdef PNG_SET_USER_LIMITS_SUPPORTED
319 png_set_user_limits(mPNG, MOZ_PNG_MAX_WIDTH, MOZ_PNG_MAX_HEIGHT);
320 png_set_chunk_malloc_max(mPNG, kPngMaxChunkSize);
321 #endif
323 #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
324 // Disallow palette-index checking, for speed; we would ignore the warning
325 // anyhow. This feature was added at libpng version 1.5.10 and is disabled
326 // in the embedded libpng but enabled by default in the system libpng. This
327 // call also disables it in the system libpng, for decoding speed.
328 // Bug #745202.
329 png_set_check_for_invalid_index(mPNG, 0);
330 #endif
332 #ifdef PNG_SET_OPTION_SUPPORTED
333 # if defined(PNG_sRGB_PROFILE_CHECKS) && PNG_sRGB_PROFILE_CHECKS >= 0
334 // Skip checking of sRGB ICC profiles
335 png_set_option(mPNG, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);
336 # endif
338 # ifdef PNG_MAXIMUM_INFLATE_WINDOW
339 // Force a larger zlib inflate window as some images in the wild have
340 // incorrectly set metadata (specifically CMF bits) which prevent us from
341 // decoding them otherwise.
342 png_set_option(mPNG, PNG_MAXIMUM_INFLATE_WINDOW, PNG_OPTION_ON);
343 # endif
344 #endif
346 // use this as libpng "progressive pointer" (retrieve in callbacks)
347 png_set_progressive_read_fn(
348 mPNG, static_cast<png_voidp>(this), nsPNGDecoder::info_callback,
349 nsPNGDecoder::row_callback, nsPNGDecoder::end_callback);
351 return NS_OK;
354 LexerResult nsPNGDecoder::DoDecode(SourceBufferIterator& aIterator,
355 IResumable* aOnResume) {
356 MOZ_ASSERT(!HasError(), "Shouldn't call DoDecode after error!");
358 return mLexer.Lex(aIterator, aOnResume,
359 [=](State aState, const char* aData, size_t aLength) {
360 switch (aState) {
361 case State::PNG_DATA:
362 return ReadPNGData(aData, aLength);
363 case State::FINISHED_PNG_DATA:
364 return FinishedPNGData();
366 MOZ_CRASH("Unknown State");
370 LexerTransition<nsPNGDecoder::State> nsPNGDecoder::ReadPNGData(
371 const char* aData, size_t aLength) {
372 // If we were waiting until after returning from a yield to call
373 // CreateFrame(), call it now.
374 if (mNextFrameInfo) {
375 if (NS_FAILED(CreateFrame(*mNextFrameInfo))) {
376 return Transition::TerminateFailure();
379 MOZ_ASSERT(mImageData, "Should have a buffer now");
380 mNextFrameInfo = Nothing();
383 // libpng uses setjmp/longjmp for error handling.
384 if (setjmp(png_jmpbuf(mPNG))) {
385 return Transition::TerminateFailure();
388 // Pass the data off to libpng.
389 mLastChunkLength = aLength;
390 mNextTransition = Transition::ContinueUnbuffered(State::PNG_DATA);
391 png_process_data(mPNG, mInfo,
392 reinterpret_cast<unsigned char*>(const_cast<char*>((aData))),
393 aLength);
395 // Make sure that we've reached a terminal state if decoding is done.
396 MOZ_ASSERT_IF(GetDecodeDone(), mNextTransition.NextStateIsTerminal());
397 MOZ_ASSERT_IF(HasError(), mNextTransition.NextStateIsTerminal());
399 // Continue with whatever transition the callback code requested. We
400 // initialized this to Transition::ContinueUnbuffered(State::PNG_DATA) above,
401 // so by default we just continue the unbuffered read.
402 return mNextTransition;
405 LexerTransition<nsPNGDecoder::State> nsPNGDecoder::FinishedPNGData() {
406 // Since we set up an unbuffered read for SIZE_MAX bytes, if we actually read
407 // all that data something is really wrong.
408 MOZ_ASSERT_UNREACHABLE("Read the entire address space?");
409 return Transition::TerminateFailure();
412 // Sets up gamma pre-correction in libpng before our callback gets called.
413 // We need to do this if we don't end up with a CMS profile.
414 static void PNGDoGammaCorrection(png_structp png_ptr, png_infop info_ptr) {
415 double aGamma;
417 if (png_get_gAMA(png_ptr, info_ptr, &aGamma)) {
418 if ((aGamma <= 0.0) || (aGamma > 21474.83)) {
419 aGamma = 0.45455;
420 png_set_gAMA(png_ptr, info_ptr, aGamma);
422 png_set_gamma(png_ptr, 2.2, aGamma);
423 } else {
424 png_set_gamma(png_ptr, 2.2, 0.45455);
428 // Adapted from http://www.littlecms.com/pngchrm.c example code
429 uint32_t nsPNGDecoder::ReadColorProfile(png_structp png_ptr, png_infop info_ptr,
430 int color_type, bool* sRGBTag) {
431 // First try to see if iCCP chunk is present
432 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP)) {
433 png_uint_32 profileLen;
434 png_bytep profileData;
435 png_charp profileName;
436 int compression;
438 png_get_iCCP(png_ptr, info_ptr, &profileName, &compression, &profileData,
439 &profileLen);
441 mInProfile = qcms_profile_from_memory((char*)profileData, profileLen);
442 if (mInProfile) {
443 uint32_t profileSpace = qcms_profile_get_color_space(mInProfile);
445 bool mismatch = false;
446 if (color_type & PNG_COLOR_MASK_COLOR) {
447 if (profileSpace != icSigRgbData) {
448 mismatch = true;
450 } else {
451 if (profileSpace == icSigRgbData) {
452 png_set_gray_to_rgb(png_ptr);
453 } else if (profileSpace != icSigGrayData) {
454 mismatch = true;
458 if (mismatch) {
459 qcms_profile_release(mInProfile);
460 mInProfile = nullptr;
461 } else {
462 return qcms_profile_get_rendering_intent(mInProfile);
467 // Check sRGB chunk
468 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
469 *sRGBTag = true;
471 int fileIntent;
472 png_set_gray_to_rgb(png_ptr);
473 png_get_sRGB(png_ptr, info_ptr, &fileIntent);
474 uint32_t map[] = {QCMS_INTENT_PERCEPTUAL, QCMS_INTENT_RELATIVE_COLORIMETRIC,
475 QCMS_INTENT_SATURATION,
476 QCMS_INTENT_ABSOLUTE_COLORIMETRIC};
477 return map[fileIntent];
480 // Check gAMA/cHRM chunks
481 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) &&
482 png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) {
483 qcms_CIE_xyYTRIPLE primaries;
484 qcms_CIE_xyY whitePoint;
486 png_get_cHRM(png_ptr, info_ptr, &whitePoint.x, &whitePoint.y,
487 &primaries.red.x, &primaries.red.y, &primaries.green.x,
488 &primaries.green.y, &primaries.blue.x, &primaries.blue.y);
489 whitePoint.Y = primaries.red.Y = primaries.green.Y = primaries.blue.Y = 1.0;
491 double gammaOfFile;
493 png_get_gAMA(png_ptr, info_ptr, &gammaOfFile);
495 mInProfile = qcms_profile_create_rgb_with_gamma(whitePoint, primaries,
496 1.0 / gammaOfFile);
498 if (mInProfile) {
499 png_set_gray_to_rgb(png_ptr);
503 return QCMS_INTENT_PERCEPTUAL; // Our default
506 void nsPNGDecoder::info_callback(png_structp png_ptr, png_infop info_ptr) {
507 png_uint_32 width, height;
508 int bit_depth, color_type, interlace_type, compression_type, filter_type;
509 unsigned int channels;
511 png_bytep trans = nullptr;
512 int num_trans = 0;
514 nsPNGDecoder* decoder =
515 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
517 if (decoder->mGotInfoCallback) {
518 MOZ_LOG(sPNGLog, LogLevel::Warning,
519 ("libpng called info_callback more than once\n"));
520 return;
523 decoder->mGotInfoCallback = true;
525 // Always decode to 24-bit RGB or 32-bit RGBA
526 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
527 &interlace_type, &compression_type, &filter_type);
529 const OrientedIntRect frameRect(0, 0, width, height);
531 // Post our size to the superclass
532 decoder->PostSize(frameRect.Width(), frameRect.Height());
534 if (width > SurfaceCache::MaximumCapacity() / (bit_depth > 8 ? 16 : 8)) {
535 // libpng needs space to allocate two row buffers
536 png_error(decoder->mPNG, "Image is too wide");
539 if (decoder->HasError()) {
540 // Setting the size led to an error.
541 png_error(decoder->mPNG, "Sizing error");
544 if (color_type == PNG_COLOR_TYPE_PALETTE) {
545 png_set_expand(png_ptr);
548 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
549 png_set_expand(png_ptr);
552 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
553 png_color_16p trans_values;
554 png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &trans_values);
555 // libpng doesn't reject a tRNS chunk with out-of-range samples
556 // so we check it here to avoid setting up a useless opacity
557 // channel or producing unexpected transparent pixels (bug #428045)
558 if (bit_depth < 16) {
559 png_uint_16 sample_max = (1 << bit_depth) - 1;
560 if ((color_type == PNG_COLOR_TYPE_GRAY &&
561 trans_values->gray > sample_max) ||
562 (color_type == PNG_COLOR_TYPE_RGB &&
563 (trans_values->red > sample_max ||
564 trans_values->green > sample_max ||
565 trans_values->blue > sample_max))) {
566 // clear the tRNS valid flag and release tRNS memory
567 png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
568 num_trans = 0;
571 if (num_trans != 0) {
572 png_set_expand(png_ptr);
576 if (bit_depth == 16) {
577 png_set_scale_16(png_ptr);
580 // We only need to extract the color profile for non-metadata decodes. It is
581 // fairly expensive to read the profile and create the transform so we should
582 // avoid it if not necessary.
583 uint32_t intent = -1;
584 bool sRGBTag = false;
585 if (!decoder->IsMetadataDecode()) {
586 if (decoder->mCMSMode != CMSMode::Off) {
587 intent = gfxPlatform::GetRenderingIntent();
588 uint32_t pIntent =
589 decoder->ReadColorProfile(png_ptr, info_ptr, color_type, &sRGBTag);
590 // If we're not mandating an intent, use the one from the image.
591 if (intent == uint32_t(-1)) {
592 intent = pIntent;
595 if (!decoder->mInProfile || !decoder->GetCMSOutputProfile()) {
596 png_set_gray_to_rgb(png_ptr);
598 // only do gamma correction if CMS isn't entirely disabled
599 if (decoder->mCMSMode != CMSMode::Off) {
600 PNGDoGammaCorrection(png_ptr, info_ptr);
605 // Let libpng expand interlaced images.
606 const bool isInterlaced = interlace_type == PNG_INTERLACE_ADAM7;
607 if (isInterlaced) {
608 png_set_interlace_handling(png_ptr);
611 // now all of those things we set above are used to update various struct
612 // members and whatnot, after which we can get channels, rowbytes, etc.
613 png_read_update_info(png_ptr, info_ptr);
614 decoder->mChannels = channels = png_get_channels(png_ptr, info_ptr);
616 //---------------------------------------------------------------//
617 // copy PNG info into imagelib structs (formerly png_set_dims()) //
618 //---------------------------------------------------------------//
620 if (channels < 1 || channels > 4) {
621 png_error(decoder->mPNG, "Invalid number of channels");
624 #ifdef PNG_APNG_SUPPORTED
625 bool isAnimated = png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL);
626 if (isAnimated) {
627 int32_t rawTimeout = GetNextFrameDelay(png_ptr, info_ptr);
628 decoder->PostIsAnimated(FrameTimeout::FromRawMilliseconds(rawTimeout));
630 if (decoder->Size() != decoder->OutputSize() &&
631 !decoder->IsFirstFrameDecode()) {
632 MOZ_ASSERT_UNREACHABLE(
633 "Doing downscale-during-decode "
634 "for an animated image?");
635 png_error(decoder->mPNG, "Invalid downscale attempt"); // Abort decode.
638 #endif
640 auto transparency = decoder->GetTransparencyType(frameRect);
641 if (decoder->IsMetadataDecode()) {
642 // If we are animated then the first frame rect is either:
643 // 1) the whole image if the IDAT chunk is part of the animation
644 // 2) the frame rect of the first fDAT chunk otherwise.
645 // If we are not animated then we want to make sure to call
646 // PostHasTransparency in the metadata decode if we need to. So it's
647 // okay to pass IntRect(0, 0, width, height) here for animated images;
648 // they will call with the proper first frame rect in the full decode.
649 decoder->PostHasTransparencyIfNeeded(transparency);
651 // We have the metadata we're looking for, so stop here, before we allocate
652 // buffers below.
653 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
656 if (decoder->mInProfile && decoder->GetCMSOutputProfile()) {
657 qcms_data_type inType;
658 qcms_data_type outType;
660 uint32_t profileSpace = qcms_profile_get_color_space(decoder->mInProfile);
661 decoder->mUsePipeTransform = profileSpace != icSigGrayData;
662 if (decoder->mUsePipeTransform) {
663 // If the transform happens with SurfacePipe, it will be in RGBA if we
664 // have an alpha channel, because the swizzle and premultiplication
665 // happens after color management. Otherwise it will be in BGRA because
666 // the swizzle happens at the start.
667 if (transparency == TransparencyType::eAlpha) {
668 inType = QCMS_DATA_RGBA_8;
669 outType = QCMS_DATA_RGBA_8;
670 } else {
671 inType = gfxPlatform::GetCMSOSRGBAType();
672 outType = inType;
674 } else {
675 if (color_type & PNG_COLOR_MASK_ALPHA) {
676 inType = QCMS_DATA_GRAYA_8;
677 outType = gfxPlatform::GetCMSOSRGBAType();
678 } else {
679 inType = QCMS_DATA_GRAY_8;
680 outType = gfxPlatform::GetCMSOSRGBAType();
684 decoder->mTransform = qcms_transform_create(decoder->mInProfile, inType,
685 decoder->GetCMSOutputProfile(),
686 outType, (qcms_intent)intent);
687 } else if ((sRGBTag && decoder->mCMSMode == CMSMode::TaggedOnly) ||
688 decoder->mCMSMode == CMSMode::All) {
689 // If the transform happens with SurfacePipe, it will be in RGBA if we
690 // have an alpha channel, because the swizzle and premultiplication
691 // happens after color management. Otherwise it will be in OS_RGBA because
692 // the swizzle happens at the start.
693 if (transparency == TransparencyType::eAlpha) {
694 decoder->mTransform =
695 decoder->GetCMSsRGBTransform(SurfaceFormat::R8G8B8A8);
696 } else {
697 decoder->mTransform =
698 decoder->GetCMSsRGBTransform(SurfaceFormat::OS_RGBA);
700 decoder->mUsePipeTransform = true;
703 #ifdef PNG_APNG_SUPPORTED
704 if (isAnimated) {
705 png_set_progressive_frame_fn(png_ptr, nsPNGDecoder::frame_info_callback,
706 nullptr);
709 if (png_get_first_frame_is_hidden(png_ptr, info_ptr)) {
710 decoder->mFrameIsHidden = true;
711 } else {
712 #endif
713 nsresult rv = decoder->CreateFrame(FrameInfo{frameRect, isInterlaced});
714 if (NS_FAILED(rv)) {
715 png_error(decoder->mPNG, "CreateFrame failed");
717 MOZ_ASSERT(decoder->mImageData, "Should have a buffer now");
718 #ifdef PNG_APNG_SUPPORTED
720 #endif
722 if (decoder->mTransform && !decoder->mUsePipeTransform) {
723 decoder->mCMSLine =
724 static_cast<uint8_t*>(malloc(sizeof(uint32_t) * frameRect.Width()));
725 if (!decoder->mCMSLine) {
726 png_error(decoder->mPNG, "malloc of mCMSLine failed");
730 if (interlace_type == PNG_INTERLACE_ADAM7) {
731 if (frameRect.Height() <
732 INT32_MAX / (frameRect.Width() * int32_t(channels))) {
733 const size_t bufferSize =
734 channels * frameRect.Width() * frameRect.Height();
736 if (bufferSize > SurfaceCache::MaximumCapacity()) {
737 png_error(decoder->mPNG, "Insufficient memory to deinterlace image");
740 decoder->interlacebuf = static_cast<uint8_t*>(malloc(bufferSize));
742 if (!decoder->interlacebuf) {
743 png_error(decoder->mPNG, "malloc of interlacebuf failed");
748 void nsPNGDecoder::PostInvalidationIfNeeded() {
749 Maybe<SurfaceInvalidRect> invalidRect = mPipe.TakeInvalidRect();
750 if (!invalidRect) {
751 return;
754 PostInvalidation(invalidRect->mInputSpaceRect,
755 Some(invalidRect->mOutputSpaceRect));
758 void nsPNGDecoder::row_callback(png_structp png_ptr, png_bytep new_row,
759 png_uint_32 row_num, int pass) {
760 /* libpng comments:
762 * This function is called for every row in the image. If the
763 * image is interlacing, and you turned on the interlace handler,
764 * this function will be called for every row in every pass.
765 * Some of these rows will not be changed from the previous pass.
766 * When the row is not changed, the new_row variable will be
767 * nullptr. The rows and passes are called in order, so you don't
768 * really need the row_num and pass, but I'm supplying them
769 * because it may make your life easier.
771 * For the non-nullptr rows of interlaced images, you must call
772 * png_progressive_combine_row() passing in the row and the
773 * old row. You can call this function for nullptr rows (it will
774 * just return) and for non-interlaced images (it just does the
775 * memcpy for you) if it will make the code easier. Thus, you
776 * can just do this for all cases:
778 * png_progressive_combine_row(png_ptr, old_row, new_row);
780 * where old_row is what was displayed for previous rows. Note
781 * that the first pass (pass == 0 really) will completely cover
782 * the old row, so the rows do not have to be initialized. After
783 * the first pass (and only for interlaced images), you will have
784 * to pass the current row, and the function will combine the
785 * old row and the new row.
787 nsPNGDecoder* decoder =
788 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
790 if (decoder->mFrameIsHidden) {
791 return; // Skip this frame.
794 MOZ_ASSERT_IF(decoder->IsFirstFrameDecode(), decoder->mNumFrames == 0);
796 while (pass > decoder->mPass) {
797 // Advance to the next pass. We may have to do this multiple times because
798 // libpng will skip passes if the image is so small that no pixels have
799 // changed on a given pass, but ADAM7InterpolatingFilter needs to be reset
800 // once for every pass to perform interpolation properly.
801 decoder->mPipe.ResetToFirstRow();
802 decoder->mPass++;
805 const png_uint_32 height =
806 static_cast<png_uint_32>(decoder->mFrameRect.Height());
808 if (row_num >= height) {
809 // Bail if we receive extra rows. This is especially important because if we
810 // didn't, we might overflow the deinterlacing buffer.
811 MOZ_ASSERT_UNREACHABLE("libpng producing extra rows?");
812 return;
815 // Note that |new_row| may be null here, indicating that this is an interlaced
816 // image and |row_callback| is being called for a row that hasn't changed.
817 MOZ_ASSERT_IF(!new_row, decoder->interlacebuf);
819 if (decoder->interlacebuf) {
820 uint32_t width = uint32_t(decoder->mFrameRect.Width());
822 // We'll output the deinterlaced version of the row.
823 uint8_t* rowToWrite =
824 decoder->interlacebuf + (row_num * decoder->mChannels * width);
826 // Update the deinterlaced version of this row with the new data.
827 png_progressive_combine_row(png_ptr, rowToWrite, new_row);
829 decoder->WriteRow(rowToWrite);
830 } else {
831 decoder->WriteRow(new_row);
835 void nsPNGDecoder::WriteRow(uint8_t* aRow) {
836 MOZ_ASSERT(aRow);
838 uint8_t* rowToWrite = aRow;
839 uint32_t width = uint32_t(mFrameRect.Width());
841 // Apply color management to the row, if necessary, before writing it out.
842 // This is only needed for grayscale images.
843 if (mTransform && !mUsePipeTransform) {
844 MOZ_ASSERT(mCMSLine);
845 qcms_transform_data(mTransform, rowToWrite, mCMSLine, width);
846 rowToWrite = mCMSLine;
849 // Write this row to the SurfacePipe.
850 DebugOnly<WriteState> result =
851 mPipe.WriteBuffer(reinterpret_cast<uint32_t*>(rowToWrite));
852 MOZ_ASSERT(WriteState(result) != WriteState::FAILURE);
854 PostInvalidationIfNeeded();
857 void nsPNGDecoder::DoTerminate(png_structp aPNGStruct, TerminalState aState) {
858 // Stop processing data. Note that we intentionally ignore the return value of
859 // png_process_data_pause(), which tells us how many bytes of the data that
860 // was passed to png_process_data() have not been consumed yet, because now
861 // that we've reached a terminal state, we won't do any more decoding or call
862 // back into libpng anymore.
863 png_process_data_pause(aPNGStruct, /* save = */ false);
865 mNextTransition = aState == TerminalState::SUCCESS
866 ? Transition::TerminateSuccess()
867 : Transition::TerminateFailure();
870 void nsPNGDecoder::DoYield(png_structp aPNGStruct) {
871 // Pause data processing. png_process_data_pause() returns how many bytes of
872 // the data that was passed to png_process_data() have not been consumed yet.
873 // We use this information to tell StreamingLexer where to place us in the
874 // input stream when we come back from the yield.
875 png_size_t pendingBytes = png_process_data_pause(aPNGStruct,
876 /* save = */ false);
878 MOZ_ASSERT(pendingBytes < mLastChunkLength);
879 size_t consumedBytes = mLastChunkLength - min(pendingBytes, mLastChunkLength);
881 mNextTransition =
882 Transition::ContinueUnbufferedAfterYield(State::PNG_DATA, consumedBytes);
885 nsresult nsPNGDecoder::FinishInternal() {
886 // We shouldn't be called in error cases.
887 MOZ_ASSERT(!HasError(), "Can't call FinishInternal on error!");
889 if (IsMetadataDecode()) {
890 return NS_OK;
893 int32_t loop_count = 0;
894 #ifdef PNG_APNG_SUPPORTED
895 if (png_get_valid(mPNG, mInfo, PNG_INFO_acTL)) {
896 int32_t num_plays = png_get_num_plays(mPNG, mInfo);
897 loop_count = num_plays - 1;
899 #endif
901 if (InFrame()) {
902 EndImageFrame();
904 PostDecodeDone(loop_count);
906 return NS_OK;
909 #ifdef PNG_APNG_SUPPORTED
910 // got the header of a new frame that's coming
911 void nsPNGDecoder::frame_info_callback(png_structp png_ptr,
912 png_uint_32 frame_num) {
913 nsPNGDecoder* decoder =
914 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
916 // old frame is done
917 decoder->EndImageFrame();
919 const bool previousFrameWasHidden = decoder->mFrameIsHidden;
921 if (!previousFrameWasHidden && decoder->IsFirstFrameDecode()) {
922 // We're about to get a second non-hidden frame, but we only want the first.
923 // Stop decoding now. (And avoid allocating the unnecessary buffers below.)
924 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
927 // Only the first frame can be hidden, so unhide unconditionally here.
928 decoder->mFrameIsHidden = false;
930 // Save the information necessary to create the frame; we'll actually create
931 // it when we return from the yield.
932 const OrientedIntRect frameRect(
933 png_get_next_frame_x_offset(png_ptr, decoder->mInfo),
934 png_get_next_frame_y_offset(png_ptr, decoder->mInfo),
935 png_get_next_frame_width(png_ptr, decoder->mInfo),
936 png_get_next_frame_height(png_ptr, decoder->mInfo));
937 const bool isInterlaced = bool(decoder->interlacebuf);
939 # ifndef MOZ_EMBEDDED_LIBPNG
940 // if using system library, check frame_width and height against 0
941 if (frameRect.width == 0) {
942 png_error(png_ptr, "Frame width must not be 0");
944 if (frameRect.height == 0) {
945 png_error(png_ptr, "Frame height must not be 0");
947 # endif
949 const FrameInfo info{frameRect, isInterlaced};
951 // If the previous frame was hidden, skip the yield (which will mislead the
952 // caller, who will think the previous frame was real) and just allocate the
953 // new frame here.
954 if (previousFrameWasHidden) {
955 if (NS_FAILED(decoder->CreateFrame(info))) {
956 return decoder->DoTerminate(png_ptr, TerminalState::FAILURE);
959 MOZ_ASSERT(decoder->mImageData, "Should have a buffer now");
960 return; // No yield, so we'll just keep decoding.
963 // Yield to the caller to notify them that the previous frame is now complete.
964 decoder->mNextFrameInfo = Some(info);
965 return decoder->DoYield(png_ptr);
967 #endif
969 void nsPNGDecoder::end_callback(png_structp png_ptr, png_infop info_ptr) {
970 /* libpng comments:
972 * this function is called when the whole image has been read,
973 * including any chunks after the image (up to and including
974 * the IEND). You will usually have the same info chunk as you
975 * had in the header, although some data may have been added
976 * to the comments and time fields.
978 * Most people won't do much here, perhaps setting a flag that
979 * marks the image as finished.
982 nsPNGDecoder* decoder =
983 static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
985 // We shouldn't get here if we've hit an error
986 MOZ_ASSERT(!decoder->HasError(), "Finishing up PNG but hit error!");
988 return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
991 void nsPNGDecoder::error_callback(png_structp png_ptr,
992 png_const_charp error_msg) {
993 MOZ_LOG(sPNGLog, LogLevel::Error, ("libpng error: %s\n", error_msg));
994 png_longjmp(png_ptr, 1);
997 void nsPNGDecoder::warning_callback(png_structp png_ptr,
998 png_const_charp warning_msg) {
999 MOZ_LOG(sPNGLog, LogLevel::Warning, ("libpng warning: %s\n", warning_msg));
1002 Maybe<Telemetry::HistogramID> nsPNGDecoder::SpeedHistogram() const {
1003 return Some(Telemetry::IMAGE_DECODE_SPEED_PNG);
1006 bool nsPNGDecoder::IsValidICOResource() const {
1007 // Only 32-bit RGBA PNGs are valid ICO resources; see here:
1008 // http://blogs.msdn.com/b/oldnewthing/archive/2010/10/22/10079192.aspx
1010 // If there are errors in the call to png_get_IHDR, the error_callback in
1011 // nsPNGDecoder.cpp is called. In this error callback we do a longjmp, so
1012 // we need to save the jump buffer here. Otherwise we'll end up without a
1013 // proper callstack.
1014 if (setjmp(png_jmpbuf(mPNG))) {
1015 // We got here from a longjmp call indirectly from png_get_IHDR
1016 return false;
1019 png_uint_32 png_width, // Unused
1020 png_height; // Unused
1022 int png_bit_depth, png_color_type;
1024 if (png_get_IHDR(mPNG, mInfo, &png_width, &png_height, &png_bit_depth,
1025 &png_color_type, nullptr, nullptr, nullptr)) {
1026 return ((png_color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
1027 png_color_type == PNG_COLOR_TYPE_RGB) &&
1028 png_bit_depth == 8);
1029 } else {
1030 return false;
1034 } // namespace image
1035 } // namespace mozilla