nsPNGDecoder.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  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/. */
  6. #include "ImageLogging.h" // Must appear first
  7. #include "nsPNGDecoder.h"
  8. #include <algorithm>
  9. #include <cstdint>
  10. #include "gfxColor.h"
  11. #include "gfxPlatform.h"
  12. #include "imgFrame.h"
  13. #include "nsColor.h"
  14. #include "nsIInputStream.h"
  15. #include "nsMemory.h"
  16. #include "nsRect.h"
  17. #include "nspr.h"
  18. #include "png.h"
  19. #include "RasterImage.h"
  20. #include "SurfacePipeFactory.h"
  21. #include "mozilla/DebugOnly.h"
  22. #include "mozilla/Telemetry.h"
  23. using namespace mozilla::gfx;
  24. using std::min;
  25. namespace mozilla {
  26. namespace image {
  27. static LazyLogModule sPNGLog("PNGDecoder");
  28. static LazyLogModule sPNGDecoderAccountingLog("PNGDecoderAccounting");
  29. // Limit image dimensions.
  30. #ifndef MOZ_PNG_MAX_WIDTH
  31. # define MOZ_PNG_MAX_WIDTH 65535
  32. #endif
  33. #ifndef MOZ_PNG_MAX_HEIGHT
  34. # define MOZ_PNG_MAX_HEIGHT 65535
  35. #endif
  36. // Maximum area supported in pixels (W*H)
  37. #ifndef MOZ_PNG_MAX_PIX
  38. # define MOZ_PNG_MAX_PIX 268435456 // 256 Mpix = 16Ki x 16Ki
  39. #endif
  40. nsPNGDecoder::AnimFrameInfo::AnimFrameInfo()
  41. : mDispose(DisposalMethod::KEEP)
  42. , mBlend(BlendMethod::OVER)
  43. , mTimeout(0)
  44. { }
  45. #ifdef PNG_APNG_SUPPORTED
  46. int32_t GetNextFrameDelay(png_structp aPNG, png_infop aInfo)
  47. {
  48. // Delay, in seconds, is delayNum / delayDen.
  49. png_uint_16 delayNum = png_get_next_frame_delay_num(aPNG, aInfo);
  50. png_uint_16 delayDen = png_get_next_frame_delay_den(aPNG, aInfo);
  51. if (delayNum == 0) {
  52. return 0; // SetFrameTimeout() will set to a minimum.
  53. }
  54. if (delayDen == 0) {
  55. delayDen = 100; // So says the APNG spec.
  56. }
  57. // Need to cast delay_num to float to have a proper division and
  58. // the result to int to avoid a compiler warning.
  59. return static_cast<int32_t>(static_cast<double>(delayNum) * 1000 / delayDen);
  60. }
  61. nsPNGDecoder::AnimFrameInfo::AnimFrameInfo(png_structp aPNG, png_infop aInfo)
  62. : mDispose(DisposalMethod::KEEP)
  63. , mBlend(BlendMethod::OVER)
  64. , mTimeout(0)
  65. {
  66. png_byte dispose_op = png_get_next_frame_dispose_op(aPNG, aInfo);
  67. png_byte blend_op = png_get_next_frame_blend_op(aPNG, aInfo);
  68. if (dispose_op == PNG_DISPOSE_OP_PREVIOUS) {
  69. mDispose = DisposalMethod::RESTORE_PREVIOUS;
  70. } else if (dispose_op == PNG_DISPOSE_OP_BACKGROUND) {
  71. mDispose = DisposalMethod::CLEAR;
  72. } else {
  73. mDispose = DisposalMethod::KEEP;
  74. }
  75. if (blend_op == PNG_BLEND_OP_SOURCE) {
  76. mBlend = BlendMethod::SOURCE;
  77. } else {
  78. mBlend = BlendMethod::OVER;
  79. }
  80. mTimeout = GetNextFrameDelay(aPNG, aInfo);
  81. }
  82. #endif
  83. // First 8 bytes of a PNG file
  84. const uint8_t
  85. nsPNGDecoder::pngSignatureBytes[] = { 137, 80, 78, 71, 13, 10, 26, 10 };
  86. nsPNGDecoder::nsPNGDecoder(RasterImage* aImage)
  87. : Decoder(aImage)
  88. , mLexer(Transition::ToUnbuffered(State::FINISHED_PNG_DATA,
  89. State::PNG_DATA,
  90. SIZE_MAX),
  91. Transition::TerminateSuccess())
  92. , mNextTransition(Transition::ContinueUnbuffered(State::PNG_DATA))
  93. , mLastChunkLength(0)
  94. , mPNG(nullptr)
  95. , mInfo(nullptr)
  96. , mCMSLine(nullptr)
  97. , interlacebuf(nullptr)
  98. , mInProfile(nullptr)
  99. , mTransform(nullptr)
  100. , format(gfx::SurfaceFormat::UNKNOWN)
  101. , mCMSMode(0)
  102. , mChannels(0)
  103. , mPass(0)
  104. , mFrameIsHidden(false)
  105. , mDisablePremultipliedAlpha(false)
  106. , mNumFrames(0)
  107. { }
  108. nsPNGDecoder::~nsPNGDecoder()
  109. {
  110. if (mPNG) {
  111. png_destroy_read_struct(&mPNG, mInfo ? &mInfo : nullptr, nullptr);
  112. }
  113. if (mCMSLine) {
  114. free(mCMSLine);
  115. }
  116. if (interlacebuf) {
  117. free(interlacebuf);
  118. }
  119. if (mInProfile) {
  120. qcms_profile_release(mInProfile);
  121. // mTransform belongs to us only if mInProfile is non-null
  122. if (mTransform) {
  123. qcms_transform_release(mTransform);
  124. }
  125. }
  126. }
  127. nsPNGDecoder::TransparencyType
  128. nsPNGDecoder::GetTransparencyType(SurfaceFormat aFormat,
  129. const IntRect& aFrameRect)
  130. {
  131. // Check if the image has a transparent color in its palette.
  132. if (aFormat == SurfaceFormat::B8G8R8A8) {
  133. return TransparencyType::eAlpha;
  134. }
  135. if (!aFrameRect.IsEqualEdges(FullFrame())) {
  136. MOZ_ASSERT(HasAnimation());
  137. return TransparencyType::eFrameRect;
  138. }
  139. return TransparencyType::eNone;
  140. }
  141. void
  142. nsPNGDecoder::PostHasTransparencyIfNeeded(TransparencyType aTransparencyType)
  143. {
  144. switch (aTransparencyType) {
  145. case TransparencyType::eNone:
  146. return;
  147. case TransparencyType::eAlpha:
  148. PostHasTransparency();
  149. return;
  150. case TransparencyType::eFrameRect:
  151. // If the first frame of animated image doesn't draw into the whole image,
  152. // then record that it is transparent. For subsequent frames, this doesn't
  153. // affect transparency, because they're composited on top of all previous
  154. // frames.
  155. if (mNumFrames == 0) {
  156. PostHasTransparency();
  157. }
  158. return;
  159. }
  160. }
  161. // CreateFrame() is used for both simple and animated images.
  162. nsresult
  163. nsPNGDecoder::CreateFrame(const FrameInfo& aFrameInfo)
  164. {
  165. MOZ_ASSERT(HasSize());
  166. MOZ_ASSERT(!IsMetadataDecode());
  167. // Check if we have transparency, and send notifications if needed.
  168. auto transparency = GetTransparencyType(aFrameInfo.mFormat,
  169. aFrameInfo.mFrameRect);
  170. PostHasTransparencyIfNeeded(transparency);
  171. SurfaceFormat format = transparency == TransparencyType::eNone
  172. ? SurfaceFormat::B8G8R8X8
  173. : SurfaceFormat::B8G8R8A8;
  174. // Make sure there's no animation or padding if we're downscaling.
  175. MOZ_ASSERT_IF(Size() != OutputSize(), mNumFrames == 0);
  176. MOZ_ASSERT_IF(Size() != OutputSize(), !GetImageMetadata().HasAnimation());
  177. MOZ_ASSERT_IF(Size() != OutputSize(),
  178. transparency != TransparencyType::eFrameRect);
  179. Maybe<AnimationParams> animParams;
  180. #ifdef PNG_APNG_SUPPORTED
  181. if (png_get_valid(mPNG, mInfo, PNG_INFO_acTL)) {
  182. mAnimInfo = AnimFrameInfo(mPNG, mInfo);
  183. if (mAnimInfo.mDispose == DisposalMethod::CLEAR) {
  184. // We may have to display the background under this image during
  185. // animation playback, so we regard it as transparent.
  186. PostHasTransparency();
  187. }
  188. animParams.emplace(AnimationParams {
  189. aFrameInfo.mFrameRect,
  190. FrameTimeout::FromRawMilliseconds(mAnimInfo.mTimeout),
  191. mNumFrames, mAnimInfo.mBlend, mAnimInfo.mDispose
  192. });
  193. }
  194. #endif
  195. // If this image is interlaced, we can display better quality intermediate
  196. // results to the user by post processing them with ADAM7InterpolatingFilter.
  197. SurfacePipeFlags pipeFlags = aFrameInfo.mIsInterlaced
  198. ? SurfacePipeFlags::ADAM7_INTERPOLATE
  199. : SurfacePipeFlags();
  200. if (mNumFrames == 0) {
  201. // The first frame may be displayed progressively.
  202. pipeFlags |= SurfacePipeFlags::PROGRESSIVE_DISPLAY;
  203. }
  204. Maybe<SurfacePipe> pipe =
  205. SurfacePipeFactory::CreateSurfacePipe(this, Size(), OutputSize(),
  206. aFrameInfo.mFrameRect, format,
  207. animParams, pipeFlags);
  208. if (!pipe) {
  209. mPipe = SurfacePipe();
  210. return NS_ERROR_FAILURE;
  211. }
  212. mPipe = Move(*pipe);
  213. mFrameRect = aFrameInfo.mFrameRect;
  214. mPass = 0;
  215. MOZ_LOG(sPNGDecoderAccountingLog, LogLevel::Debug,
  216. ("PNGDecoderAccounting: nsPNGDecoder::CreateFrame -- created "
  217. "image frame with %dx%d pixels for decoder %p",
  218. mFrameRect.width, mFrameRect.height, this));
  219. return NS_OK;
  220. }
  221. // set timeout and frame disposal method for the current frame
  222. void
  223. nsPNGDecoder::EndImageFrame()
  224. {
  225. if (mFrameIsHidden) {
  226. return;
  227. }
  228. mNumFrames++;
  229. Opacity opacity = Opacity::SOME_TRANSPARENCY;
  230. if (format == gfx::SurfaceFormat::B8G8R8X8) {
  231. opacity = Opacity::FULLY_OPAQUE;
  232. }
  233. PostFrameStop(opacity);
  234. }
  235. nsresult
  236. nsPNGDecoder::InitInternal()
  237. {
  238. mCMSMode = gfxPlatform::GetCMSMode();
  239. if (GetSurfaceFlags() & SurfaceFlags::NO_COLORSPACE_CONVERSION) {
  240. mCMSMode = eCMSMode_Off;
  241. }
  242. mDisablePremultipliedAlpha =
  243. bool(GetSurfaceFlags() & SurfaceFlags::NO_PREMULTIPLY_ALPHA);
  244. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  245. static png_byte color_chunks[]=
  246. { 99, 72, 82, 77, '\0', // cHRM
  247. 105, 67, 67, 80, '\0'}; // iCCP
  248. static png_byte unused_chunks[]=
  249. { 98, 75, 71, 68, '\0', // bKGD
  250. 104, 73, 83, 84, '\0', // hIST
  251. 105, 84, 88, 116, '\0', // iTXt
  252. 111, 70, 70, 115, '\0', // oFFs
  253. 112, 67, 65, 76, '\0', // pCAL
  254. 115, 67, 65, 76, '\0', // sCAL
  255. 112, 72, 89, 115, '\0', // pHYs
  256. 115, 66, 73, 84, '\0', // sBIT
  257. 115, 80, 76, 84, '\0', // sPLT
  258. 116, 69, 88, 116, '\0', // tEXt
  259. 116, 73, 77, 69, '\0', // tIME
  260. 122, 84, 88, 116, '\0'}; // zTXt
  261. #endif
  262. // Initialize the container's source image header
  263. // Always decode to 24 bit pixdepth
  264. mPNG = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  265. nullptr, nsPNGDecoder::error_callback,
  266. nsPNGDecoder::warning_callback);
  267. if (!mPNG) {
  268. return NS_ERROR_OUT_OF_MEMORY;
  269. }
  270. mInfo = png_create_info_struct(mPNG);
  271. if (!mInfo) {
  272. png_destroy_read_struct(&mPNG, nullptr, nullptr);
  273. return NS_ERROR_OUT_OF_MEMORY;
  274. }
  275. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  276. // Ignore unused chunks
  277. if (mCMSMode == eCMSMode_Off || IsMetadataDecode()) {
  278. png_set_keep_unknown_chunks(mPNG, 1, color_chunks, 2);
  279. }
  280. png_set_keep_unknown_chunks(mPNG, 1, unused_chunks,
  281. (int)sizeof(unused_chunks)/5);
  282. #endif
  283. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  284. png_set_user_limits(mPNG, MOZ_PNG_MAX_WIDTH, MOZ_PNG_MAX_HEIGHT);
  285. if (mCMSMode != eCMSMode_Off) {
  286. png_set_chunk_malloc_max(mPNG, 4000000L);
  287. }
  288. #endif
  289. #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED
  290. // Disallow palette-index checking, for speed; we would ignore the warning
  291. // anyhow. This feature was added at libpng version 1.5.10 and is disabled
  292. // in the embedded libpng but enabled by default in the system libpng. This
  293. // call also disables it in the system libpng, for decoding speed.
  294. // Bug #745202.
  295. png_set_check_for_invalid_index(mPNG, 0);
  296. #endif
  297. #ifdef PNG_SET_OPTION_SUPPORTED
  298. #if defined(PNG_sRGB_PROFILE_CHECKS) && PNG_sRGB_PROFILE_CHECKS >= 0
  299. // Skip checking of sRGB ICC profiles
  300. png_set_option(mPNG, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);
  301. #endif
  302. #ifdef PNG_MAXIMUM_INFLATE_WINDOW
  303. // Force a larger zlib inflate window as some images in the wild have
  304. // incorrectly set metadata (specifically CMF bits) which prevent us from
  305. // decoding them otherwise.
  306. png_set_option(mPNG, PNG_MAXIMUM_INFLATE_WINDOW, PNG_OPTION_ON);
  307. #endif
  308. #endif
  309. // use this as libpng "progressive pointer" (retrieve in callbacks)
  310. png_set_progressive_read_fn(mPNG, static_cast<png_voidp>(this),
  311. nsPNGDecoder::info_callback,
  312. nsPNGDecoder::row_callback,
  313. nsPNGDecoder::end_callback);
  314. return NS_OK;
  315. }
  316. LexerResult
  317. nsPNGDecoder::DoDecode(SourceBufferIterator& aIterator, IResumable* aOnResume)
  318. {
  319. MOZ_ASSERT(!HasError(), "Shouldn't call DoDecode after error!");
  320. return mLexer.Lex(aIterator, aOnResume,
  321. [=](State aState, const char* aData, size_t aLength) {
  322. switch (aState) {
  323. case State::PNG_DATA:
  324. return ReadPNGData(aData, aLength);
  325. case State::FINISHED_PNG_DATA:
  326. return FinishedPNGData();
  327. }
  328. MOZ_CRASH("Unknown State");
  329. });
  330. }
  331. LexerTransition<nsPNGDecoder::State>
  332. nsPNGDecoder::ReadPNGData(const char* aData, size_t aLength)
  333. {
  334. // If we were waiting until after returning from a yield to call
  335. // CreateFrame(), call it now.
  336. if (mNextFrameInfo) {
  337. if (NS_FAILED(CreateFrame(*mNextFrameInfo))) {
  338. return Transition::TerminateFailure();
  339. }
  340. MOZ_ASSERT(mImageData, "Should have a buffer now");
  341. mNextFrameInfo = Nothing();
  342. }
  343. // libpng uses setjmp/longjmp for error handling.
  344. if (setjmp(png_jmpbuf(mPNG))) {
  345. return Transition::TerminateFailure();
  346. }
  347. // Pass the data off to libpng.
  348. mLastChunkLength = aLength;
  349. mNextTransition = Transition::ContinueUnbuffered(State::PNG_DATA);
  350. png_process_data(mPNG, mInfo,
  351. reinterpret_cast<unsigned char*>(const_cast<char*>((aData))),
  352. aLength);
  353. // Make sure that we've reached a terminal state if decoding is done.
  354. MOZ_ASSERT_IF(GetDecodeDone(), mNextTransition.NextStateIsTerminal());
  355. MOZ_ASSERT_IF(HasError(), mNextTransition.NextStateIsTerminal());
  356. // Continue with whatever transition the callback code requested. We
  357. // initialized this to Transition::ContinueUnbuffered(State::PNG_DATA) above,
  358. // so by default we just continue the unbuffered read.
  359. return mNextTransition;
  360. }
  361. LexerTransition<nsPNGDecoder::State>
  362. nsPNGDecoder::FinishedPNGData()
  363. {
  364. // Since we set up an unbuffered read for SIZE_MAX bytes, if we actually read
  365. // all that data something is really wrong.
  366. MOZ_ASSERT_UNREACHABLE("Read the entire address space?");
  367. return Transition::TerminateFailure();
  368. }
  369. // Sets up gamma pre-correction in libpng before our callback gets called.
  370. // We need to do this if we don't end up with a CMS profile.
  371. static void
  372. PNGDoGammaCorrection(png_structp png_ptr, png_infop info_ptr)
  373. {
  374. double aGamma;
  375. if (png_get_gAMA(png_ptr, info_ptr, &aGamma)) {
  376. if ((aGamma <= 0.0) || (aGamma > 21474.83)) {
  377. aGamma = 0.45455;
  378. png_set_gAMA(png_ptr, info_ptr, aGamma);
  379. }
  380. png_set_gamma(png_ptr, 2.2, aGamma);
  381. } else {
  382. png_set_gamma(png_ptr, 2.2, 0.45455);
  383. }
  384. }
  385. // Adapted from http://www.littlecms.com/pngchrm.c example code
  386. static qcms_profile*
  387. PNGGetColorProfile(png_structp png_ptr, png_infop info_ptr,
  388. int color_type, qcms_data_type* inType, uint32_t* intent)
  389. {
  390. qcms_profile* profile = nullptr;
  391. *intent = QCMS_INTENT_PERCEPTUAL; // Our default
  392. // First try to see if iCCP chunk is present
  393. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP)) {
  394. png_uint_32 profileLen;
  395. png_bytep profileData;
  396. png_charp profileName;
  397. int compression;
  398. png_get_iCCP(png_ptr, info_ptr, &profileName, &compression,
  399. &profileData, &profileLen);
  400. profile = qcms_profile_from_memory((char*)profileData, profileLen);
  401. if (profile) {
  402. uint32_t profileSpace = qcms_profile_get_color_space(profile);
  403. bool mismatch = false;
  404. if (color_type & PNG_COLOR_MASK_COLOR) {
  405. if (profileSpace != icSigRgbData) {
  406. mismatch = true;
  407. }
  408. } else {
  409. if (profileSpace == icSigRgbData) {
  410. png_set_gray_to_rgb(png_ptr);
  411. } else if (profileSpace != icSigGrayData) {
  412. mismatch = true;
  413. }
  414. }
  415. if (mismatch) {
  416. qcms_profile_release(profile);
  417. profile = nullptr;
  418. } else {
  419. *intent = qcms_profile_get_rendering_intent(profile);
  420. }
  421. }
  422. }
  423. // Check sRGB chunk
  424. if (!profile && png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
  425. profile = qcms_profile_sRGB();
  426. if (profile) {
  427. int fileIntent;
  428. png_set_gray_to_rgb(png_ptr);
  429. png_get_sRGB(png_ptr, info_ptr, &fileIntent);
  430. uint32_t map[] = { QCMS_INTENT_PERCEPTUAL,
  431. QCMS_INTENT_RELATIVE_COLORIMETRIC,
  432. QCMS_INTENT_SATURATION,
  433. QCMS_INTENT_ABSOLUTE_COLORIMETRIC };
  434. *intent = map[fileIntent];
  435. }
  436. }
  437. // Check gAMA/cHRM chunks
  438. if (!profile &&
  439. png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) &&
  440. png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) {
  441. qcms_CIE_xyYTRIPLE primaries;
  442. qcms_CIE_xyY whitePoint;
  443. png_get_cHRM(png_ptr, info_ptr,
  444. &whitePoint.x, &whitePoint.y,
  445. &primaries.red.x, &primaries.red.y,
  446. &primaries.green.x, &primaries.green.y,
  447. &primaries.blue.x, &primaries.blue.y);
  448. whitePoint.Y =
  449. primaries.red.Y = primaries.green.Y = primaries.blue.Y = 1.0;
  450. double gammaOfFile;
  451. png_get_gAMA(png_ptr, info_ptr, &gammaOfFile);
  452. profile = qcms_profile_create_rgb_with_gamma(whitePoint, primaries,
  453. 1.0/gammaOfFile);
  454. if (profile) {
  455. png_set_gray_to_rgb(png_ptr);
  456. }
  457. }
  458. if (profile) {
  459. uint32_t profileSpace = qcms_profile_get_color_space(profile);
  460. if (profileSpace == icSigGrayData) {
  461. if (color_type & PNG_COLOR_MASK_ALPHA) {
  462. *inType = QCMS_DATA_GRAYA_8;
  463. } else {
  464. *inType = QCMS_DATA_GRAY_8;
  465. }
  466. } else {
  467. if (color_type & PNG_COLOR_MASK_ALPHA ||
  468. png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
  469. *inType = QCMS_DATA_RGBA_8;
  470. } else {
  471. *inType = QCMS_DATA_RGB_8;
  472. }
  473. }
  474. }
  475. return profile;
  476. }
  477. void
  478. nsPNGDecoder::info_callback(png_structp png_ptr, png_infop info_ptr)
  479. {
  480. png_uint_32 width, height;
  481. int bit_depth, color_type, interlace_type, compression_type, filter_type;
  482. unsigned int channels;
  483. png_bytep trans = nullptr;
  484. int num_trans = 0;
  485. nsPNGDecoder* decoder =
  486. static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
  487. // Always decode to 24-bit RGB or 32-bit RGBA
  488. png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
  489. &interlace_type, &compression_type, &filter_type);
  490. // Check sizes against cap limits and W*H
  491. if ((width > MOZ_PNG_MAX_WIDTH) ||
  492. (height > MOZ_PNG_MAX_HEIGHT) ||
  493. (width * height > MOZ_PNG_MAX_PIX)) {
  494. png_error(decoder->mPNG, "Image too large");
  495. }
  496. const IntRect frameRect(0, 0, width, height);
  497. // Post our size to the superclass
  498. decoder->PostSize(frameRect.width, frameRect.height);
  499. if (decoder->HasError()) {
  500. // Setting the size led to an error.
  501. png_error(decoder->mPNG, "Sizing error");
  502. }
  503. if (color_type == PNG_COLOR_TYPE_PALETTE) {
  504. png_set_expand(png_ptr);
  505. }
  506. if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
  507. png_set_expand(png_ptr);
  508. }
  509. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
  510. png_color_16p trans_values;
  511. png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &trans_values);
  512. // libpng doesn't reject a tRNS chunk with out-of-range samples
  513. // so we check it here to avoid setting up a useless opacity
  514. // channel or producing unexpected transparent pixels (bug #428045)
  515. if (bit_depth < 16) {
  516. png_uint_16 sample_max = (1 << bit_depth) - 1;
  517. if ((color_type == PNG_COLOR_TYPE_GRAY &&
  518. trans_values->gray > sample_max) ||
  519. (color_type == PNG_COLOR_TYPE_RGB &&
  520. (trans_values->red > sample_max ||
  521. trans_values->green > sample_max ||
  522. trans_values->blue > sample_max))) {
  523. // clear the tRNS valid flag and release tRNS memory
  524. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  525. num_trans = 0;
  526. }
  527. }
  528. if (num_trans != 0) {
  529. png_set_expand(png_ptr);
  530. }
  531. }
  532. if (bit_depth == 16) {
  533. png_set_scale_16(png_ptr);
  534. }
  535. qcms_data_type inType = QCMS_DATA_RGBA_8;
  536. uint32_t intent = -1;
  537. uint32_t pIntent;
  538. if (decoder->mCMSMode != eCMSMode_Off) {
  539. intent = gfxPlatform::GetRenderingIntent();
  540. decoder->mInProfile = PNGGetColorProfile(png_ptr, info_ptr,
  541. color_type, &inType, &pIntent);
  542. // If we're not mandating an intent, use the one from the image.
  543. if (intent == uint32_t(-1)) {
  544. intent = pIntent;
  545. }
  546. }
  547. if (decoder->mInProfile && gfxPlatform::GetCMSOutputProfile()) {
  548. qcms_data_type outType;
  549. if (color_type & PNG_COLOR_MASK_ALPHA || num_trans) {
  550. outType = QCMS_DATA_RGBA_8;
  551. } else {
  552. outType = QCMS_DATA_RGB_8;
  553. }
  554. decoder->mTransform = qcms_transform_create(decoder->mInProfile,
  555. inType,
  556. gfxPlatform::GetCMSOutputProfile(),
  557. outType,
  558. (qcms_intent)intent);
  559. } else {
  560. png_set_gray_to_rgb(png_ptr);
  561. // only do gamma correction if CMS isn't entirely disabled
  562. if (decoder->mCMSMode != eCMSMode_Off) {
  563. PNGDoGammaCorrection(png_ptr, info_ptr);
  564. }
  565. if (decoder->mCMSMode == eCMSMode_All) {
  566. if (color_type & PNG_COLOR_MASK_ALPHA || num_trans) {
  567. decoder->mTransform = gfxPlatform::GetCMSRGBATransform();
  568. } else {
  569. decoder->mTransform = gfxPlatform::GetCMSRGBTransform();
  570. }
  571. }
  572. }
  573. // Let libpng expand interlaced images.
  574. const bool isInterlaced = interlace_type == PNG_INTERLACE_ADAM7;
  575. if (isInterlaced) {
  576. png_set_interlace_handling(png_ptr);
  577. }
  578. // now all of those things we set above are used to update various struct
  579. // members and whatnot, after which we can get channels, rowbytes, etc.
  580. png_read_update_info(png_ptr, info_ptr);
  581. decoder->mChannels = channels = png_get_channels(png_ptr, info_ptr);
  582. //---------------------------------------------------------------//
  583. // copy PNG info into imagelib structs (formerly png_set_dims()) //
  584. //---------------------------------------------------------------//
  585. if (channels == 1 || channels == 3) {
  586. decoder->format = gfx::SurfaceFormat::B8G8R8X8;
  587. } else if (channels == 2 || channels == 4) {
  588. decoder->format = gfx::SurfaceFormat::B8G8R8A8;
  589. } else {
  590. png_error(decoder->mPNG, "Invalid number of channels");
  591. }
  592. #ifdef PNG_APNG_SUPPORTED
  593. bool isAnimated = png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL);
  594. if (isAnimated) {
  595. int32_t rawTimeout = GetNextFrameDelay(png_ptr, info_ptr);
  596. decoder->PostIsAnimated(FrameTimeout::FromRawMilliseconds(rawTimeout));
  597. if (decoder->Size() != decoder->OutputSize() &&
  598. !decoder->IsFirstFrameDecode()) {
  599. MOZ_ASSERT_UNREACHABLE("Doing downscale-during-decode "
  600. "for an animated image?");
  601. png_error(decoder->mPNG, "Invalid downscale attempt"); // Abort decode.
  602. }
  603. }
  604. #endif
  605. if (decoder->IsMetadataDecode()) {
  606. // If we are animated then the first frame rect is either:
  607. // 1) the whole image if the IDAT chunk is part of the animation
  608. // 2) the frame rect of the first fDAT chunk otherwise.
  609. // If we are not animated then we want to make sure to call
  610. // PostHasTransparency in the metadata decode if we need to. So it's
  611. // okay to pass IntRect(0, 0, width, height) here for animated images;
  612. // they will call with the proper first frame rect in the full decode.
  613. auto transparency = decoder->GetTransparencyType(decoder->format,
  614. frameRect);
  615. decoder->PostHasTransparencyIfNeeded(transparency);
  616. // We have the metadata we're looking for, so stop here, before we allocate
  617. // buffers below.
  618. return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
  619. }
  620. #ifdef PNG_APNG_SUPPORTED
  621. if (isAnimated) {
  622. png_set_progressive_frame_fn(png_ptr, nsPNGDecoder::frame_info_callback,
  623. nullptr);
  624. }
  625. if (png_get_first_frame_is_hidden(png_ptr, info_ptr)) {
  626. decoder->mFrameIsHidden = true;
  627. } else {
  628. #endif
  629. nsresult rv = decoder->CreateFrame(FrameInfo{ decoder->format,
  630. frameRect,
  631. isInterlaced });
  632. if (NS_FAILED(rv)) {
  633. png_error(decoder->mPNG, "CreateFrame failed");
  634. }
  635. MOZ_ASSERT(decoder->mImageData, "Should have a buffer now");
  636. #ifdef PNG_APNG_SUPPORTED
  637. }
  638. #endif
  639. if (decoder->mTransform && (channels <= 2 || isInterlaced)) {
  640. uint32_t bpp[] = { 0, 3, 4, 3, 4 };
  641. decoder->mCMSLine =
  642. static_cast<uint8_t*>(malloc(bpp[channels] * frameRect.width));
  643. if (!decoder->mCMSLine) {
  644. png_error(decoder->mPNG, "malloc of mCMSLine failed");
  645. }
  646. }
  647. if (interlace_type == PNG_INTERLACE_ADAM7) {
  648. if (frameRect.height < INT32_MAX / (frameRect.width * int32_t(channels))) {
  649. const size_t bufferSize = channels * frameRect.width * frameRect.height;
  650. decoder->interlacebuf = static_cast<uint8_t*>(malloc(bufferSize));
  651. }
  652. if (!decoder->interlacebuf) {
  653. png_error(decoder->mPNG, "malloc of interlacebuf failed");
  654. }
  655. }
  656. }
  657. void
  658. nsPNGDecoder::PostInvalidationIfNeeded()
  659. {
  660. Maybe<SurfaceInvalidRect> invalidRect = mPipe.TakeInvalidRect();
  661. if (!invalidRect) {
  662. return;
  663. }
  664. PostInvalidation(invalidRect->mInputSpaceRect,
  665. Some(invalidRect->mOutputSpaceRect));
  666. }
  667. static NextPixel<uint32_t>
  668. PackRGBPixelAndAdvance(uint8_t*& aRawPixelInOut)
  669. {
  670. const uint32_t pixel =
  671. gfxPackedPixel(0xFF, aRawPixelInOut[0], aRawPixelInOut[1],
  672. aRawPixelInOut[2]);
  673. aRawPixelInOut += 3;
  674. return AsVariant(pixel);
  675. }
  676. static NextPixel<uint32_t>
  677. PackRGBAPixelAndAdvance(uint8_t*& aRawPixelInOut)
  678. {
  679. const uint32_t pixel =
  680. gfxPackedPixel(aRawPixelInOut[3], aRawPixelInOut[0],
  681. aRawPixelInOut[1], aRawPixelInOut[2]);
  682. aRawPixelInOut += 4;
  683. return AsVariant(pixel);
  684. }
  685. static NextPixel<uint32_t>
  686. PackUnpremultipliedRGBAPixelAndAdvance(uint8_t*& aRawPixelInOut)
  687. {
  688. const uint32_t pixel =
  689. gfxPackedPixelNoPreMultiply(aRawPixelInOut[3], aRawPixelInOut[0],
  690. aRawPixelInOut[1], aRawPixelInOut[2]);
  691. aRawPixelInOut += 4;
  692. return AsVariant(pixel);
  693. }
  694. void
  695. nsPNGDecoder::row_callback(png_structp png_ptr, png_bytep new_row,
  696. png_uint_32 row_num, int pass)
  697. {
  698. /* libpng comments:
  699. *
  700. * This function is called for every row in the image. If the
  701. * image is interlacing, and you turned on the interlace handler,
  702. * this function will be called for every row in every pass.
  703. * Some of these rows will not be changed from the previous pass.
  704. * When the row is not changed, the new_row variable will be
  705. * nullptr. The rows and passes are called in order, so you don't
  706. * really need the row_num and pass, but I'm supplying them
  707. * because it may make your life easier.
  708. *
  709. * For the non-nullptr rows of interlaced images, you must call
  710. * png_progressive_combine_row() passing in the row and the
  711. * old row. You can call this function for nullptr rows (it will
  712. * just return) and for non-interlaced images (it just does the
  713. * memcpy for you) if it will make the code easier. Thus, you
  714. * can just do this for all cases:
  715. *
  716. * png_progressive_combine_row(png_ptr, old_row, new_row);
  717. *
  718. * where old_row is what was displayed for previous rows. Note
  719. * that the first pass (pass == 0 really) will completely cover
  720. * the old row, so the rows do not have to be initialized. After
  721. * the first pass (and only for interlaced images), you will have
  722. * to pass the current row, and the function will combine the
  723. * old row and the new row.
  724. */
  725. nsPNGDecoder* decoder =
  726. static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
  727. if (decoder->mFrameIsHidden) {
  728. return; // Skip this frame.
  729. }
  730. MOZ_ASSERT_IF(decoder->IsFirstFrameDecode(), decoder->mNumFrames == 0);
  731. while (pass > decoder->mPass) {
  732. // Advance to the next pass. We may have to do this multiple times because
  733. // libpng will skip passes if the image is so small that no pixels have
  734. // changed on a given pass, but ADAM7InterpolatingFilter needs to be reset
  735. // once for every pass to perform interpolation properly.
  736. decoder->mPipe.ResetToFirstRow();
  737. decoder->mPass++;
  738. }
  739. const png_uint_32 height =
  740. static_cast<png_uint_32>(decoder->mFrameRect.height);
  741. if (row_num >= height) {
  742. // Bail if we receive extra rows. This is especially important because if we
  743. // didn't, we might overflow the deinterlacing buffer.
  744. MOZ_ASSERT_UNREACHABLE("libpng producing extra rows?");
  745. return;
  746. }
  747. // Note that |new_row| may be null here, indicating that this is an interlaced
  748. // image and |row_callback| is being called for a row that hasn't changed.
  749. MOZ_ASSERT_IF(!new_row, decoder->interlacebuf);
  750. uint8_t* rowToWrite = new_row;
  751. if (decoder->interlacebuf) {
  752. uint32_t width = uint32_t(decoder->mFrameRect.width);
  753. // We'll output the deinterlaced version of the row.
  754. rowToWrite = decoder->interlacebuf + (row_num * decoder->mChannels * width);
  755. // Update the deinterlaced version of this row with the new data.
  756. png_progressive_combine_row(png_ptr, rowToWrite, new_row);
  757. }
  758. decoder->WriteRow(rowToWrite);
  759. }
  760. void
  761. nsPNGDecoder::WriteRow(uint8_t* aRow)
  762. {
  763. MOZ_ASSERT(aRow);
  764. uint8_t* rowToWrite = aRow;
  765. uint32_t width = uint32_t(mFrameRect.width);
  766. // Apply color management to the row, if necessary, before writing it out.
  767. if (mTransform) {
  768. if (mCMSLine) {
  769. qcms_transform_data(mTransform, rowToWrite, mCMSLine, width);
  770. // Copy alpha over.
  771. if (mChannels == 2 || mChannels == 4) {
  772. for (uint32_t i = 0; i < width; ++i) {
  773. mCMSLine[4 * i + 3] = rowToWrite[mChannels * i + mChannels - 1];
  774. }
  775. }
  776. rowToWrite = mCMSLine;
  777. } else {
  778. qcms_transform_data(mTransform, rowToWrite, rowToWrite, width);
  779. }
  780. }
  781. // Write this row to the SurfacePipe.
  782. DebugOnly<WriteState> result = WriteState::FAILURE;
  783. switch (format) {
  784. case SurfaceFormat::B8G8R8X8:
  785. result = mPipe.WritePixelsToRow<uint32_t>([&]{
  786. return PackRGBPixelAndAdvance(rowToWrite);
  787. });
  788. break;
  789. case SurfaceFormat::B8G8R8A8:
  790. if (mDisablePremultipliedAlpha) {
  791. result = mPipe.WritePixelsToRow<uint32_t>([&]{
  792. return PackUnpremultipliedRGBAPixelAndAdvance(rowToWrite);
  793. });
  794. } else {
  795. result = mPipe.WritePixelsToRow<uint32_t>([&]{
  796. return PackRGBAPixelAndAdvance(rowToWrite);
  797. });
  798. }
  799. break;
  800. default:
  801. png_error(mPNG, "Invalid SurfaceFormat");
  802. }
  803. MOZ_ASSERT(WriteState(result) != WriteState::FAILURE);
  804. PostInvalidationIfNeeded();
  805. }
  806. void
  807. nsPNGDecoder::DoTerminate(png_structp aPNGStruct, TerminalState aState)
  808. {
  809. // Stop processing data. Note that we intentionally ignore the return value of
  810. // png_process_data_pause(), which tells us how many bytes of the data that
  811. // was passed to png_process_data() have not been consumed yet, because now
  812. // that we've reached a terminal state, we won't do any more decoding or call
  813. // back into libpng anymore.
  814. png_process_data_pause(aPNGStruct, /* save = */ false);
  815. mNextTransition = aState == TerminalState::SUCCESS
  816. ? Transition::TerminateSuccess()
  817. : Transition::TerminateFailure();
  818. }
  819. void
  820. nsPNGDecoder::DoYield(png_structp aPNGStruct)
  821. {
  822. // Pause data processing. png_process_data_pause() returns how many bytes of
  823. // the data that was passed to png_process_data() have not been consumed yet.
  824. // We use this information to tell StreamingLexer where to place us in the
  825. // input stream when we come back from the yield.
  826. png_size_t pendingBytes = png_process_data_pause(aPNGStruct,
  827. /* save = */ false);
  828. MOZ_ASSERT(pendingBytes < mLastChunkLength);
  829. size_t consumedBytes = mLastChunkLength - min(pendingBytes, mLastChunkLength);
  830. mNextTransition =
  831. Transition::ContinueUnbufferedAfterYield(State::PNG_DATA, consumedBytes);
  832. }
  833. #ifdef PNG_APNG_SUPPORTED
  834. // got the header of a new frame that's coming
  835. void
  836. nsPNGDecoder::frame_info_callback(png_structp png_ptr, png_uint_32 frame_num)
  837. {
  838. nsPNGDecoder* decoder =
  839. static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
  840. // old frame is done
  841. decoder->EndImageFrame();
  842. const bool previousFrameWasHidden = decoder->mFrameIsHidden;
  843. if (!previousFrameWasHidden && decoder->IsFirstFrameDecode()) {
  844. // We're about to get a second non-hidden frame, but we only want the first.
  845. // Stop decoding now. (And avoid allocating the unnecessary buffers below.)
  846. decoder->PostDecodeDone();
  847. return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
  848. }
  849. // Only the first frame can be hidden, so unhide unconditionally here.
  850. decoder->mFrameIsHidden = false;
  851. // Save the information necessary to create the frame; we'll actually create
  852. // it when we return from the yield.
  853. const IntRect frameRect(png_get_next_frame_x_offset(png_ptr, decoder->mInfo),
  854. png_get_next_frame_y_offset(png_ptr, decoder->mInfo),
  855. png_get_next_frame_width(png_ptr, decoder->mInfo),
  856. png_get_next_frame_height(png_ptr, decoder->mInfo));
  857. const bool isInterlaced = bool(decoder->interlacebuf);
  858. #ifndef MOZ_EMBEDDED_LIBPNG
  859. // if using system library, check frame_width and height against 0
  860. if (frameRect.width == 0) {
  861. png_error(png_ptr, "Frame width must not be 0");
  862. }
  863. if (frameRect.height == 0) {
  864. png_error(png_ptr, "Frame height must not be 0");
  865. }
  866. #endif
  867. const FrameInfo info { decoder->format, frameRect, isInterlaced };
  868. // If the previous frame was hidden, skip the yield (which will mislead the
  869. // caller, who will think the previous frame was real) and just allocate the
  870. // new frame here.
  871. if (previousFrameWasHidden) {
  872. if (NS_FAILED(decoder->CreateFrame(info))) {
  873. return decoder->DoTerminate(png_ptr, TerminalState::FAILURE);
  874. }
  875. MOZ_ASSERT(decoder->mImageData, "Should have a buffer now");
  876. return; // No yield, so we'll just keep decoding.
  877. }
  878. // Yield to the caller to notify them that the previous frame is now complete.
  879. decoder->mNextFrameInfo = Some(info);
  880. return decoder->DoYield(png_ptr);
  881. }
  882. #endif
  883. void
  884. nsPNGDecoder::end_callback(png_structp png_ptr, png_infop info_ptr)
  885. {
  886. /* libpng comments:
  887. *
  888. * this function is called when the whole image has been read,
  889. * including any chunks after the image (up to and including
  890. * the IEND). You will usually have the same info chunk as you
  891. * had in the header, although some data may have been added
  892. * to the comments and time fields.
  893. *
  894. * Most people won't do much here, perhaps setting a flag that
  895. * marks the image as finished.
  896. */
  897. nsPNGDecoder* decoder =
  898. static_cast<nsPNGDecoder*>(png_get_progressive_ptr(png_ptr));
  899. // We shouldn't get here if we've hit an error
  900. MOZ_ASSERT(!decoder->HasError(), "Finishing up PNG but hit error!");
  901. int32_t loop_count = 0;
  902. #ifdef PNG_APNG_SUPPORTED
  903. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL)) {
  904. int32_t num_plays = png_get_num_plays(png_ptr, info_ptr);
  905. loop_count = num_plays - 1;
  906. }
  907. #endif
  908. // Send final notifications.
  909. decoder->EndImageFrame();
  910. decoder->PostDecodeDone(loop_count);
  911. return decoder->DoTerminate(png_ptr, TerminalState::SUCCESS);
  912. }
  913. void
  914. nsPNGDecoder::error_callback(png_structp png_ptr, png_const_charp error_msg)
  915. {
  916. MOZ_LOG(sPNGLog, LogLevel::Error, ("libpng error: %s\n", error_msg));
  917. png_longjmp(png_ptr, 1);
  918. }
  919. void
  920. nsPNGDecoder::warning_callback(png_structp png_ptr, png_const_charp warning_msg)
  921. {
  922. MOZ_LOG(sPNGLog, LogLevel::Warning, ("libpng warning: %s\n", warning_msg));
  923. }
  924. Maybe<Telemetry::ID>
  925. nsPNGDecoder::SpeedHistogram() const
  926. {
  927. return Some(Telemetry::IMAGE_DECODE_SPEED_PNG);
  928. }
  929. bool
  930. nsPNGDecoder::IsValidICO() const
  931. {
  932. // Only 32-bit RGBA PNGs are valid ICO resources; see here:
  933. // http://blogs.msdn.com/b/oldnewthing/archive/2010/10/22/10079192.aspx
  934. // If there are errors in the call to png_get_IHDR, the error_callback in
  935. // nsPNGDecoder.cpp is called. In this error callback we do a longjmp, so
  936. // we need to save the jump buffer here. Otherwise we'll end up without a
  937. // proper callstack.
  938. if (setjmp(png_jmpbuf(mPNG))) {
  939. // We got here from a longjmp call indirectly from png_get_IHDR
  940. return false;
  941. }
  942. png_uint_32
  943. png_width, // Unused
  944. png_height; // Unused
  945. int png_bit_depth,
  946. png_color_type;
  947. if (png_get_IHDR(mPNG, mInfo, &png_width, &png_height, &png_bit_depth,
  948. &png_color_type, nullptr, nullptr, nullptr)) {
  949. return ((png_color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
  950. png_color_type == PNG_COLOR_TYPE_RGB) &&
  951. png_bit_depth == 8);
  952. } else {
  953. return false;
  954. }
  955. }
  956. } // namespace image
  957. } // namespace mozilla