PNGLoader.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/MemoryStream.h>
  10. #include <AK/Vector.h>
  11. #include <LibCompress/Zlib.h>
  12. #include <LibGfx/ImageFormats/PNGLoader.h>
  13. #include <LibGfx/Painter.h>
  14. namespace Gfx {
  15. struct PNG_IHDR {
  16. NetworkOrdered<u32> width;
  17. NetworkOrdered<u32> height;
  18. u8 bit_depth { 0 };
  19. PNG::ColorType color_type { 0 };
  20. u8 compression_method { 0 };
  21. u8 filter_method { 0 };
  22. u8 interlace_method { 0 };
  23. };
  24. static_assert(AssertSize<PNG_IHDR, 13>());
  25. struct acTL_Chunk {
  26. NetworkOrdered<u32> num_frames;
  27. NetworkOrdered<u32> num_plays;
  28. };
  29. static_assert(AssertSize<acTL_Chunk, 8>());
  30. struct fcTL_Chunk {
  31. enum class DisposeOp : u8 {
  32. APNG_DISPOSE_OP_NONE = 0,
  33. APNG_DISPOSE_OP_BACKGROUND,
  34. APNG_DISPOSE_OP_PREVIOUS
  35. };
  36. enum class BlendOp : u8 {
  37. APNG_BLEND_OP_SOURCE = 0,
  38. APNG_BLEND_OP_OVER
  39. };
  40. NetworkOrdered<u32> sequence_number;
  41. NetworkOrdered<u32> width;
  42. NetworkOrdered<u32> height;
  43. NetworkOrdered<u32> x_offset;
  44. NetworkOrdered<u32> y_offset;
  45. NetworkOrdered<u16> delay_num;
  46. NetworkOrdered<u16> delay_den;
  47. DisposeOp dispose_op { DisposeOp::APNG_DISPOSE_OP_NONE };
  48. BlendOp blend_op { BlendOp::APNG_BLEND_OP_SOURCE };
  49. };
  50. static_assert(AssertSize<fcTL_Chunk, 26>());
  51. struct ChromaticitiesAndWhitepoint {
  52. NetworkOrdered<u32> white_point_x;
  53. NetworkOrdered<u32> white_point_y;
  54. NetworkOrdered<u32> red_x;
  55. NetworkOrdered<u32> red_y;
  56. NetworkOrdered<u32> green_x;
  57. NetworkOrdered<u32> green_y;
  58. NetworkOrdered<u32> blue_x;
  59. NetworkOrdered<u32> blue_y;
  60. };
  61. static_assert(AssertSize<ChromaticitiesAndWhitepoint, 32>());
  62. struct CodingIndependentCodePoints {
  63. u8 color_primaries;
  64. u8 transfer_function;
  65. u8 matrix_coefficients;
  66. u8 video_full_range_flag;
  67. };
  68. static_assert(AssertSize<CodingIndependentCodePoints, 4>());
  69. struct EmbeddedICCProfile {
  70. StringView profile_name;
  71. ReadonlyBytes compressed_data;
  72. };
  73. struct Scanline {
  74. PNG::FilterType filter;
  75. ReadonlyBytes data {};
  76. };
  77. struct [[gnu::packed]] PaletteEntry {
  78. u8 r;
  79. u8 g;
  80. u8 b;
  81. // u8 a;
  82. };
  83. template<typename T>
  84. struct [[gnu::packed]] Tuple {
  85. T gray;
  86. T a;
  87. };
  88. template<typename T>
  89. struct [[gnu::packed]] Triplet {
  90. T r;
  91. T g;
  92. T b;
  93. bool operator==(Triplet const& other) const = default;
  94. };
  95. template<typename T>
  96. struct [[gnu::packed]] Quartet {
  97. T r;
  98. T g;
  99. T b;
  100. T a;
  101. };
  102. enum PngInterlaceMethod {
  103. Null = 0,
  104. Adam7 = 1
  105. };
  106. enum RenderingIntent {
  107. Perceptual = 0,
  108. RelativeColorimetric = 1,
  109. Saturation = 2,
  110. AbsoluteColorimetric = 3,
  111. };
  112. struct AnimationFrame {
  113. fcTL_Chunk const& fcTL;
  114. RefPtr<Bitmap> bitmap;
  115. ByteBuffer compressed_data;
  116. AnimationFrame(fcTL_Chunk const& fcTL)
  117. : fcTL(fcTL)
  118. {
  119. }
  120. u32 duration_ms() const
  121. {
  122. u32 num = fcTL.delay_num;
  123. if (num == 0)
  124. return 1;
  125. u32 denom = fcTL.delay_den != 0 ? static_cast<u32>(fcTL.delay_den) : 100u;
  126. return (num * 1000) / denom;
  127. }
  128. IntRect rect() const
  129. {
  130. return { fcTL.x_offset, fcTL.y_offset, fcTL.width, fcTL.height };
  131. }
  132. };
  133. struct PNGLoadingContext {
  134. enum State {
  135. NotDecoded = 0,
  136. Error,
  137. IHDRDecoded,
  138. ImageDataChunkDecoded,
  139. ChunksDecoded,
  140. BitmapDecoded,
  141. };
  142. State state { State::NotDecoded };
  143. u8 const* data { nullptr };
  144. u8 const* data_current_ptr { nullptr };
  145. size_t data_size { 0 };
  146. i32 width { -1 };
  147. i32 height { -1 };
  148. u8 bit_depth { 0 };
  149. PNG::ColorType color_type { 0 };
  150. u8 compression_method { 0 };
  151. u8 filter_method { 0 };
  152. u8 interlace_method { 0 };
  153. u8 channels { 0 };
  154. u32 animation_next_expected_seq { 0 };
  155. u32 animation_next_frame_to_render { 0 };
  156. u32 animation_frame_count { 0 };
  157. u32 animation_loop_count { 0 };
  158. Optional<u32> last_completed_animation_frame_index;
  159. bool is_first_idat_part_of_animation { false };
  160. bool has_seen_iend { false };
  161. bool has_seen_idat_chunk { false };
  162. bool has_seen_actl_chunk_before_idat { false };
  163. bool has_alpha() const { return to_underlying(color_type) & 4 || palette_transparency_data.size() > 0; }
  164. Vector<Scanline> scanlines;
  165. ByteBuffer unfiltered_data;
  166. RefPtr<Gfx::Bitmap> bitmap;
  167. ByteBuffer compressed_data;
  168. Vector<PaletteEntry> palette_data;
  169. ByteBuffer palette_transparency_data;
  170. Vector<AnimationFrame> animation_frames;
  171. Optional<ChromaticitiesAndWhitepoint> chromaticities_and_whitepoint;
  172. Optional<CodingIndependentCodePoints> coding_independent_code_points;
  173. Optional<u32> gamma;
  174. Optional<EmbeddedICCProfile> embedded_icc_profile;
  175. Optional<ByteBuffer> decompressed_icc_profile;
  176. Optional<RenderingIntent> sRGB_rendering_intent;
  177. Checked<int> compute_row_size_for_width(int width)
  178. {
  179. Checked<int> row_size = width;
  180. row_size *= channels;
  181. row_size *= bit_depth;
  182. row_size += 7;
  183. row_size /= 8;
  184. if (row_size.has_overflow()) {
  185. dbgln("PNG too large, integer overflow while computing row size");
  186. state = State::Error;
  187. }
  188. return row_size;
  189. }
  190. PNGLoadingContext create_subimage_context(int width, int height)
  191. {
  192. PNGLoadingContext subimage_context;
  193. subimage_context.state = State::ChunksDecoded;
  194. subimage_context.width = width;
  195. subimage_context.height = height;
  196. subimage_context.channels = channels;
  197. subimage_context.color_type = color_type;
  198. subimage_context.palette_data = palette_data;
  199. subimage_context.palette_transparency_data = palette_transparency_data;
  200. subimage_context.bit_depth = bit_depth;
  201. subimage_context.filter_method = filter_method;
  202. return subimage_context;
  203. }
  204. };
  205. class Streamer {
  206. public:
  207. Streamer(u8 const* data, size_t size)
  208. : m_data_ptr(data)
  209. , m_size_remaining(size)
  210. {
  211. }
  212. template<typename T>
  213. bool read(T& value)
  214. {
  215. if (m_size_remaining < sizeof(T))
  216. return false;
  217. value = *((NetworkOrdered<T> const*)m_data_ptr);
  218. m_data_ptr += sizeof(T);
  219. m_size_remaining -= sizeof(T);
  220. return true;
  221. }
  222. bool read_bytes(u8* buffer, size_t count)
  223. {
  224. if (m_size_remaining < count)
  225. return false;
  226. memcpy(buffer, m_data_ptr, count);
  227. m_data_ptr += count;
  228. m_size_remaining -= count;
  229. return true;
  230. }
  231. bool wrap_bytes(ReadonlyBytes& buffer, size_t count)
  232. {
  233. if (m_size_remaining < count)
  234. return false;
  235. buffer = ReadonlyBytes { m_data_ptr, count };
  236. m_data_ptr += count;
  237. m_size_remaining -= count;
  238. return true;
  239. }
  240. u8 const* current_data_ptr() const { return m_data_ptr; }
  241. bool at_end() const { return !m_size_remaining; }
  242. private:
  243. u8 const* m_data_ptr { nullptr };
  244. size_t m_size_remaining { 0 };
  245. };
  246. static ErrorOr<void> process_chunk(Streamer&, PNGLoadingContext& context);
  247. union [[gnu::packed]] Pixel {
  248. ARGB32 rgba { 0 };
  249. u8 v[4];
  250. struct {
  251. u8 r;
  252. u8 g;
  253. u8 b;
  254. u8 a;
  255. };
  256. };
  257. static_assert(AssertSize<Pixel, 4>());
  258. void PNGImageDecoderPlugin::unfilter_scanline(PNG::FilterType filter, Bytes scanline_data, ReadonlyBytes previous_scanlines_data, u8 bytes_per_complete_pixel)
  259. {
  260. // https://www.w3.org/TR/png-3/#9Filter-types
  261. // "Filters are applied to bytes, not to pixels, regardless of the bit depth or colour type of the image."
  262. switch (filter) {
  263. case PNG::FilterType::None:
  264. break;
  265. case PNG::FilterType::Sub:
  266. // This loop starts at bytes_per_complete_pixel because all bytes before that are
  267. // guaranteed to have no valid byte at index (i - bytes_per_complete pixel).
  268. // All such invalid byte indexes should be treated as 0, and adding 0 to the current
  269. // byte would do nothing, so the first bytes_per_complete_pixel bytes can instead
  270. // just be skipped.
  271. for (size_t i = bytes_per_complete_pixel; i < scanline_data.size(); ++i) {
  272. u8 left = scanline_data[i - bytes_per_complete_pixel];
  273. scanline_data[i] += left;
  274. }
  275. break;
  276. case PNG::FilterType::Up:
  277. for (size_t i = 0; i < scanline_data.size(); ++i) {
  278. u8 above = previous_scanlines_data[i];
  279. scanline_data[i] += above;
  280. }
  281. break;
  282. case PNG::FilterType::Average:
  283. for (size_t i = 0; i < scanline_data.size(); ++i) {
  284. u32 left = (i < bytes_per_complete_pixel) ? 0 : scanline_data[i - bytes_per_complete_pixel];
  285. u32 above = previous_scanlines_data[i];
  286. u8 average = (left + above) / 2;
  287. scanline_data[i] += average;
  288. }
  289. break;
  290. case PNG::FilterType::Paeth:
  291. for (size_t i = 0; i < scanline_data.size(); ++i) {
  292. u8 left = (i < bytes_per_complete_pixel) ? 0 : scanline_data[i - bytes_per_complete_pixel];
  293. u8 above = previous_scanlines_data[i];
  294. u8 upper_left = (i < bytes_per_complete_pixel) ? 0 : previous_scanlines_data[i - bytes_per_complete_pixel];
  295. scanline_data[i] += PNG::paeth_predictor(left, above, upper_left);
  296. }
  297. break;
  298. }
  299. }
  300. template<typename T>
  301. ALWAYS_INLINE static void unpack_grayscale_without_alpha(PNGLoadingContext& context)
  302. {
  303. for (int y = 0; y < context.height; ++y) {
  304. auto* gray_values = reinterpret_cast<T const*>(context.scanlines[y].data.data());
  305. for (int i = 0; i < context.width; ++i) {
  306. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  307. pixel.r = gray_values[i];
  308. pixel.g = gray_values[i];
  309. pixel.b = gray_values[i];
  310. pixel.a = 0xff;
  311. }
  312. }
  313. }
  314. template<typename T>
  315. ALWAYS_INLINE static void unpack_grayscale_with_alpha(PNGLoadingContext& context)
  316. {
  317. for (int y = 0; y < context.height; ++y) {
  318. auto* tuples = reinterpret_cast<Tuple<T> const*>(context.scanlines[y].data.data());
  319. for (int i = 0; i < context.width; ++i) {
  320. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  321. pixel.r = tuples[i].gray;
  322. pixel.g = tuples[i].gray;
  323. pixel.b = tuples[i].gray;
  324. pixel.a = tuples[i].a;
  325. }
  326. }
  327. }
  328. template<typename T>
  329. ALWAYS_INLINE static void unpack_triplets_without_alpha(PNGLoadingContext& context)
  330. {
  331. for (int y = 0; y < context.height; ++y) {
  332. auto* triplets = reinterpret_cast<Triplet<T> const*>(context.scanlines[y].data.data());
  333. for (int i = 0; i < context.width; ++i) {
  334. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  335. pixel.r = triplets[i].r;
  336. pixel.g = triplets[i].g;
  337. pixel.b = triplets[i].b;
  338. pixel.a = 0xff;
  339. }
  340. }
  341. }
  342. template<typename T>
  343. ALWAYS_INLINE static void unpack_triplets_with_transparency_value(PNGLoadingContext& context, Triplet<T> transparency_value)
  344. {
  345. for (int y = 0; y < context.height; ++y) {
  346. auto* triplets = reinterpret_cast<Triplet<T> const*>(context.scanlines[y].data.data());
  347. for (int i = 0; i < context.width; ++i) {
  348. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  349. pixel.r = triplets[i].r;
  350. pixel.g = triplets[i].g;
  351. pixel.b = triplets[i].b;
  352. if (triplets[i] == transparency_value)
  353. pixel.a = 0x00;
  354. else
  355. pixel.a = 0xff;
  356. }
  357. }
  358. }
  359. NEVER_INLINE FLATTEN static ErrorOr<void> unfilter(PNGLoadingContext& context)
  360. {
  361. // First unfilter the scanlines:
  362. // FIXME: Instead of creating a separate buffer for the scanlines that need to be
  363. // mutated, the mutation could be done in place (if the data was non-const).
  364. size_t bytes_per_scanline = context.scanlines[0].data.size();
  365. size_t bytes_needed_for_all_unfiltered_scanlines = 0;
  366. for (int y = 0; y < context.height; ++y) {
  367. if (context.scanlines[y].filter != PNG::FilterType::None) {
  368. bytes_needed_for_all_unfiltered_scanlines += bytes_per_scanline;
  369. }
  370. }
  371. context.unfiltered_data = TRY(ByteBuffer::create_uninitialized(bytes_needed_for_all_unfiltered_scanlines));
  372. // From section 6.3 of http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html
  373. // "bpp is defined as the number of bytes per complete pixel, rounding up to one.
  374. // For example, for color type 2 with a bit depth of 16, bpp is equal to 6
  375. // (three samples, two bytes per sample); for color type 0 with a bit depth of 2,
  376. // bpp is equal to 1 (rounding up); for color type 4 with a bit depth of 16, bpp
  377. // is equal to 4 (two-byte grayscale sample, plus two-byte alpha sample)."
  378. u8 bytes_per_complete_pixel = ceil_div(context.bit_depth, (u8)8) * context.channels;
  379. u8 dummy_scanline_bytes[bytes_per_scanline];
  380. memset(dummy_scanline_bytes, 0, sizeof(dummy_scanline_bytes));
  381. auto previous_scanlines_data = ReadonlyBytes { dummy_scanline_bytes, sizeof(dummy_scanline_bytes) };
  382. for (int y = 0, data_start = 0; y < context.height; ++y) {
  383. if (context.scanlines[y].filter != PNG::FilterType::None) {
  384. auto scanline_data_slice = context.unfiltered_data.bytes().slice(data_start, bytes_per_scanline);
  385. // Copy the current values over and set the scanline's data to the to-be-mutated slice
  386. context.scanlines[y].data.copy_to(scanline_data_slice);
  387. context.scanlines[y].data = scanline_data_slice;
  388. PNGImageDecoderPlugin::unfilter_scanline(context.scanlines[y].filter, scanline_data_slice, previous_scanlines_data, bytes_per_complete_pixel);
  389. data_start += bytes_per_scanline;
  390. }
  391. previous_scanlines_data = context.scanlines[y].data;
  392. }
  393. // Now unpack the scanlines to RGBA:
  394. switch (context.color_type) {
  395. case PNG::ColorType::Greyscale:
  396. if (context.bit_depth == 8) {
  397. unpack_grayscale_without_alpha<u8>(context);
  398. } else if (context.bit_depth == 16) {
  399. unpack_grayscale_without_alpha<u16>(context);
  400. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  401. auto bit_depth_squared = context.bit_depth * context.bit_depth;
  402. auto pixels_per_byte = 8 / context.bit_depth;
  403. auto mask = (1 << context.bit_depth) - 1;
  404. for (int y = 0; y < context.height; ++y) {
  405. auto* gray_values = context.scanlines[y].data.data();
  406. for (int x = 0; x < context.width; ++x) {
  407. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (x % pixels_per_byte));
  408. auto value = (gray_values[x / pixels_per_byte] >> bit_offset) & mask;
  409. auto& pixel = (Pixel&)context.bitmap->scanline(y)[x];
  410. pixel.r = value * (0xff / bit_depth_squared);
  411. pixel.g = value * (0xff / bit_depth_squared);
  412. pixel.b = value * (0xff / bit_depth_squared);
  413. pixel.a = 0xff;
  414. }
  415. }
  416. } else {
  417. VERIFY_NOT_REACHED();
  418. }
  419. break;
  420. case PNG::ColorType::GreyscaleWithAlpha:
  421. if (context.bit_depth == 8) {
  422. unpack_grayscale_with_alpha<u8>(context);
  423. } else if (context.bit_depth == 16) {
  424. unpack_grayscale_with_alpha<u16>(context);
  425. } else {
  426. VERIFY_NOT_REACHED();
  427. }
  428. break;
  429. case PNG::ColorType::Truecolor:
  430. if (context.palette_transparency_data.size() == 6) {
  431. if (context.bit_depth == 8) {
  432. unpack_triplets_with_transparency_value<u8>(context, Triplet<u8> { context.palette_transparency_data[0], context.palette_transparency_data[2], context.palette_transparency_data[4] });
  433. } else if (context.bit_depth == 16) {
  434. u16 tr = context.palette_transparency_data[0] | context.palette_transparency_data[1] << 8;
  435. u16 tg = context.palette_transparency_data[2] | context.palette_transparency_data[3] << 8;
  436. u16 tb = context.palette_transparency_data[4] | context.palette_transparency_data[5] << 8;
  437. unpack_triplets_with_transparency_value<u16>(context, Triplet<u16> { tr, tg, tb });
  438. } else {
  439. VERIFY_NOT_REACHED();
  440. }
  441. } else {
  442. if (context.bit_depth == 8)
  443. unpack_triplets_without_alpha<u8>(context);
  444. else if (context.bit_depth == 16)
  445. unpack_triplets_without_alpha<u16>(context);
  446. else
  447. VERIFY_NOT_REACHED();
  448. }
  449. break;
  450. case PNG::ColorType::TruecolorWithAlpha:
  451. if (context.bit_depth == 8) {
  452. for (int y = 0; y < context.height; ++y) {
  453. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  454. }
  455. } else if (context.bit_depth == 16) {
  456. for (int y = 0; y < context.height; ++y) {
  457. auto* quartets = reinterpret_cast<Quartet<u16> const*>(context.scanlines[y].data.data());
  458. for (int i = 0; i < context.width; ++i) {
  459. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  460. pixel.r = quartets[i].r & 0xFF;
  461. pixel.g = quartets[i].g & 0xFF;
  462. pixel.b = quartets[i].b & 0xFF;
  463. pixel.a = quartets[i].a & 0xFF;
  464. }
  465. }
  466. } else {
  467. VERIFY_NOT_REACHED();
  468. }
  469. break;
  470. case PNG::ColorType::IndexedColor:
  471. if (context.bit_depth == 8) {
  472. for (int y = 0; y < context.height; ++y) {
  473. auto* palette_index = context.scanlines[y].data.data();
  474. for (int i = 0; i < context.width; ++i) {
  475. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  476. if (palette_index[i] >= context.palette_data.size())
  477. return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range");
  478. auto& color = context.palette_data.at((int)palette_index[i]);
  479. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u
  480. ? context.palette_transparency_data[palette_index[i]]
  481. : 0xff;
  482. pixel.r = color.r;
  483. pixel.g = color.g;
  484. pixel.b = color.b;
  485. pixel.a = transparency;
  486. }
  487. }
  488. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  489. auto pixels_per_byte = 8 / context.bit_depth;
  490. auto mask = (1 << context.bit_depth) - 1;
  491. for (int y = 0; y < context.height; ++y) {
  492. auto* palette_indices = context.scanlines[y].data.data();
  493. for (int i = 0; i < context.width; ++i) {
  494. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (i % pixels_per_byte));
  495. auto palette_index = (palette_indices[i / pixels_per_byte] >> bit_offset) & mask;
  496. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  497. if ((size_t)palette_index >= context.palette_data.size())
  498. return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range");
  499. auto& color = context.palette_data.at(palette_index);
  500. auto transparency = context.palette_transparency_data.size() >= palette_index + 1u
  501. ? context.palette_transparency_data[palette_index]
  502. : 0xff;
  503. pixel.r = color.r;
  504. pixel.g = color.g;
  505. pixel.b = color.b;
  506. pixel.a = transparency;
  507. }
  508. }
  509. } else {
  510. VERIFY_NOT_REACHED();
  511. }
  512. break;
  513. default:
  514. VERIFY_NOT_REACHED();
  515. break;
  516. }
  517. // Swap r and b values:
  518. for (int y = 0; y < context.height; ++y) {
  519. auto* pixels = (Pixel*)context.bitmap->scanline(y);
  520. for (int i = 0; i < context.bitmap->width(); ++i) {
  521. auto& x = pixels[i];
  522. swap(x.r, x.b);
  523. }
  524. }
  525. return {};
  526. }
  527. static bool decode_png_header(PNGLoadingContext& context)
  528. {
  529. if (!context.data || context.data_size < sizeof(PNG::header)) {
  530. dbgln_if(PNG_DEBUG, "Missing PNG header");
  531. context.state = PNGLoadingContext::State::Error;
  532. return false;
  533. }
  534. if (memcmp(context.data, PNG::header.span().data(), sizeof(PNG::header)) != 0) {
  535. dbgln_if(PNG_DEBUG, "Invalid PNG header");
  536. context.state = PNGLoadingContext::State::Error;
  537. return false;
  538. }
  539. context.data_current_ptr = context.data + sizeof(PNG::header);
  540. return true;
  541. }
  542. static ErrorOr<void> decode_png_ihdr(PNGLoadingContext& context)
  543. {
  544. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  545. Streamer streamer(context.data_current_ptr, data_remaining);
  546. // https://www.w3.org/TR/png/#11IHDR
  547. // The IHDR chunk shall be the first chunk in the PNG datastream.
  548. TRY(process_chunk(streamer, context));
  549. context.data_current_ptr = streamer.current_data_ptr();
  550. VERIFY(context.state == PNGLoadingContext::State::IHDRDecoded);
  551. return {};
  552. }
  553. static bool decode_png_image_data_chunk(PNGLoadingContext& context)
  554. {
  555. VERIFY(context.state >= PNGLoadingContext::IHDRDecoded);
  556. if (context.state >= PNGLoadingContext::ImageDataChunkDecoded)
  557. return true;
  558. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  559. Streamer streamer(context.data_current_ptr, data_remaining);
  560. while (!streamer.at_end() && !context.has_seen_iend) {
  561. if (auto result = process_chunk(streamer, context); result.is_error()) {
  562. context.state = PNGLoadingContext::State::Error;
  563. return false;
  564. }
  565. context.data_current_ptr = streamer.current_data_ptr();
  566. if (context.state >= PNGLoadingContext::State::ImageDataChunkDecoded)
  567. return true;
  568. }
  569. return false;
  570. }
  571. static bool decode_png_animation_data_chunks(PNGLoadingContext& context, u32 requested_animation_frame_index)
  572. {
  573. if (context.state >= PNGLoadingContext::ImageDataChunkDecoded) {
  574. if (context.last_completed_animation_frame_index.has_value()) {
  575. if (requested_animation_frame_index <= context.last_completed_animation_frame_index.value())
  576. return true;
  577. }
  578. } else if (!decode_png_image_data_chunk(context)) {
  579. return false;
  580. }
  581. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  582. Streamer streamer(context.data_current_ptr, data_remaining);
  583. while (!streamer.at_end() && !context.has_seen_iend) {
  584. if (auto result = process_chunk(streamer, context); result.is_error()) {
  585. context.state = PNGLoadingContext::State::Error;
  586. return false;
  587. }
  588. context.data_current_ptr = streamer.current_data_ptr();
  589. if (context.last_completed_animation_frame_index.has_value()) {
  590. if (requested_animation_frame_index <= context.last_completed_animation_frame_index.value())
  591. break;
  592. }
  593. }
  594. if (!context.last_completed_animation_frame_index.has_value())
  595. return false;
  596. return requested_animation_frame_index <= context.last_completed_animation_frame_index.value();
  597. }
  598. static bool decode_png_chunks(PNGLoadingContext& context)
  599. {
  600. VERIFY(context.state >= PNGLoadingContext::IHDRDecoded);
  601. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  602. return true;
  603. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  604. context.compressed_data.ensure_capacity(context.data_size);
  605. Streamer streamer(context.data_current_ptr, data_remaining);
  606. while (!streamer.at_end() && !context.has_seen_iend) {
  607. if (auto result = process_chunk(streamer, context); result.is_error()) {
  608. // Ignore failed chunk and just consider chunk decoding being done.
  609. // decode_png_bitmap() will check whether we got all required ones anyway.
  610. break;
  611. }
  612. context.data_current_ptr = streamer.current_data_ptr();
  613. }
  614. context.state = PNGLoadingContext::State::ChunksDecoded;
  615. return true;
  616. }
  617. static ErrorOr<void> decode_png_bitmap_simple(PNGLoadingContext& context, ByteBuffer& decompression_buffer)
  618. {
  619. Streamer streamer(decompression_buffer.data(), decompression_buffer.size());
  620. for (int y = 0; y < context.height; ++y) {
  621. u8 filter_byte;
  622. if (!streamer.read(filter_byte)) {
  623. context.state = PNGLoadingContext::State::Error;
  624. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  625. }
  626. if (filter_byte > 4) {
  627. context.state = PNGLoadingContext::State::Error;
  628. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
  629. }
  630. context.scanlines.append({ MUST(PNG::filter_type(filter_byte)) });
  631. auto& scanline_buffer = context.scanlines.last().data;
  632. auto row_size = context.compute_row_size_for_width(context.width);
  633. if (row_size.has_overflow())
  634. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
  635. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  636. context.state = PNGLoadingContext::State::Error;
  637. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  638. }
  639. }
  640. context.bitmap = TRY(Bitmap::create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  641. return unfilter(context);
  642. }
  643. static int adam7_height(PNGLoadingContext& context, int pass)
  644. {
  645. switch (pass) {
  646. case 1:
  647. return (context.height + 7) / 8;
  648. case 2:
  649. return (context.height + 7) / 8;
  650. case 3:
  651. return (context.height + 3) / 8;
  652. case 4:
  653. return (context.height + 3) / 4;
  654. case 5:
  655. return (context.height + 1) / 4;
  656. case 6:
  657. return (context.height + 1) / 2;
  658. case 7:
  659. return context.height / 2;
  660. default:
  661. VERIFY_NOT_REACHED();
  662. }
  663. }
  664. static int adam7_width(PNGLoadingContext& context, int pass)
  665. {
  666. switch (pass) {
  667. case 1:
  668. return (context.width + 7) / 8;
  669. case 2:
  670. return (context.width + 3) / 8;
  671. case 3:
  672. return (context.width + 3) / 4;
  673. case 4:
  674. return (context.width + 1) / 4;
  675. case 5:
  676. return (context.width + 1) / 2;
  677. case 6:
  678. return context.width / 2;
  679. case 7:
  680. return context.width;
  681. default:
  682. VERIFY_NOT_REACHED();
  683. }
  684. }
  685. // Index 0 unused (non-interlaced case)
  686. static int adam7_starty[8] = { 0, 0, 0, 4, 0, 2, 0, 1 };
  687. static int adam7_startx[8] = { 0, 0, 4, 0, 2, 0, 1, 0 };
  688. static int adam7_stepy[8] = { 1, 8, 8, 8, 4, 4, 2, 2 };
  689. static int adam7_stepx[8] = { 1, 8, 8, 4, 4, 2, 2, 1 };
  690. static ErrorOr<void> decode_adam7_pass(PNGLoadingContext& context, Streamer& streamer, int pass)
  691. {
  692. auto subimage_context = context.create_subimage_context(adam7_width(context, pass), adam7_height(context, pass));
  693. // For small images, some passes might be empty
  694. if (!subimage_context.width || !subimage_context.height)
  695. return {};
  696. for (int y = 0; y < subimage_context.height; ++y) {
  697. u8 filter_byte;
  698. if (!streamer.read(filter_byte)) {
  699. context.state = PNGLoadingContext::State::Error;
  700. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  701. }
  702. if (filter_byte > 4) {
  703. context.state = PNGLoadingContext::State::Error;
  704. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
  705. }
  706. subimage_context.scanlines.append({ MUST(PNG::filter_type(filter_byte)) });
  707. auto& scanline_buffer = subimage_context.scanlines.last().data;
  708. auto row_size = context.compute_row_size_for_width(subimage_context.width);
  709. if (row_size.has_overflow())
  710. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
  711. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  712. context.state = PNGLoadingContext::State::Error;
  713. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  714. }
  715. }
  716. subimage_context.bitmap = TRY(Bitmap::create(context.bitmap->format(), { subimage_context.width, subimage_context.height }));
  717. TRY(unfilter(subimage_context));
  718. // Copy the subimage data into the main image according to the pass pattern
  719. for (int y = 0, dy = adam7_starty[pass]; y < subimage_context.height && dy < context.height; ++y, dy += adam7_stepy[pass]) {
  720. for (int x = 0, dx = adam7_startx[pass]; x < subimage_context.width && dx < context.width; ++x, dx += adam7_stepx[pass]) {
  721. context.bitmap->set_pixel(dx, dy, subimage_context.bitmap->get_pixel(x, y));
  722. }
  723. }
  724. return {};
  725. }
  726. static ErrorOr<void> decode_png_adam7(PNGLoadingContext& context, ByteBuffer& decompression_buffer)
  727. {
  728. Streamer streamer(decompression_buffer.data(), decompression_buffer.size());
  729. context.bitmap = TRY(Bitmap::create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  730. for (int pass = 1; pass <= 7; ++pass)
  731. TRY(decode_adam7_pass(context, streamer, pass));
  732. return {};
  733. }
  734. static ErrorOr<void> decode_png_bitmap(PNGLoadingContext& context)
  735. {
  736. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  737. if (!decode_png_chunks(context))
  738. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  739. }
  740. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  741. return {};
  742. if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty())
  743. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty.");
  744. auto compressed_data_stream = make<FixedMemoryStream>(context.compressed_data.span());
  745. auto decompressor_or_error = Compress::ZlibDecompressor::create(move(compressed_data_stream));
  746. if (decompressor_or_error.is_error()) {
  747. context.state = PNGLoadingContext::State::Error;
  748. return decompressor_or_error.release_error();
  749. }
  750. auto decompressor = decompressor_or_error.release_value();
  751. auto result_or_error = decompressor->read_until_eof();
  752. if (result_or_error.is_error()) {
  753. context.state = PNGLoadingContext::State::Error;
  754. return result_or_error.release_error();
  755. }
  756. auto decompression_buffer = result_or_error.release_value();
  757. context.compressed_data.clear();
  758. context.scanlines.ensure_capacity(context.height);
  759. switch (context.interlace_method) {
  760. case PngInterlaceMethod::Null:
  761. TRY(decode_png_bitmap_simple(context, decompression_buffer));
  762. break;
  763. case PngInterlaceMethod::Adam7:
  764. TRY(decode_png_adam7(context, decompression_buffer));
  765. break;
  766. default:
  767. context.state = PNGLoadingContext::State::Error;
  768. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method");
  769. }
  770. context.state = PNGLoadingContext::State::BitmapDecoded;
  771. return {};
  772. }
  773. static ErrorOr<RefPtr<Bitmap>> decode_png_animation_frame_bitmap(PNGLoadingContext& context, AnimationFrame& animation_frame)
  774. {
  775. if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty())
  776. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty.");
  777. VERIFY(!animation_frame.bitmap);
  778. auto frame_rect = animation_frame.rect();
  779. auto frame_context = context.create_subimage_context(frame_rect.width(), frame_rect.height());
  780. auto compressed_data_stream = make<FixedMemoryStream>(animation_frame.compressed_data.span());
  781. auto decompressor = TRY(Compress::ZlibDecompressor::create(move(compressed_data_stream)));
  782. auto decompression_buffer = TRY(decompressor->read_until_eof());
  783. frame_context.compressed_data.clear();
  784. frame_context.scanlines.ensure_capacity(frame_context.height);
  785. switch (context.interlace_method) {
  786. case PngInterlaceMethod::Null:
  787. TRY(decode_png_bitmap_simple(frame_context, decompression_buffer));
  788. break;
  789. case PngInterlaceMethod::Adam7:
  790. TRY(decode_png_adam7(frame_context, decompression_buffer));
  791. break;
  792. default:
  793. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method");
  794. }
  795. context.state = PNGLoadingContext::State::BitmapDecoded;
  796. return move(frame_context.bitmap);
  797. }
  798. static bool is_valid_compression_method(u8 compression_method)
  799. {
  800. return compression_method == 0;
  801. }
  802. static bool is_valid_filter_method(u8 filter_method)
  803. {
  804. return filter_method == 0;
  805. }
  806. static ErrorOr<void> process_IHDR(ReadonlyBytes data, PNGLoadingContext& context)
  807. {
  808. if (data.size() < (int)sizeof(PNG_IHDR))
  809. return Error::from_string_literal("IHDR chunk has an abnormal size");
  810. auto const& ihdr = *(const PNG_IHDR*)data.data();
  811. if (ihdr.width == 0 || ihdr.width > NumericLimits<i32>::max()) {
  812. dbgln("PNG has invalid width {}", ihdr.width);
  813. return Error::from_string_literal("Invalid width");
  814. }
  815. if (ihdr.height == 0 || ihdr.height > NumericLimits<i32>::max()) {
  816. dbgln("PNG has invalid height {}", ihdr.height);
  817. return Error::from_string_literal("Invalid height");
  818. }
  819. if (!is_valid_compression_method(ihdr.compression_method)) {
  820. dbgln("PNG has invalid compression method {}", ihdr.compression_method);
  821. return Error::from_string_literal("Unsupported compression method");
  822. }
  823. if (!is_valid_filter_method(ihdr.filter_method)) {
  824. dbgln("PNG has invalid filter method {}", ihdr.filter_method);
  825. return Error::from_string_literal("Unsupported filter method");
  826. }
  827. context.width = ihdr.width;
  828. context.height = ihdr.height;
  829. context.bit_depth = ihdr.bit_depth;
  830. context.color_type = ihdr.color_type;
  831. context.compression_method = ihdr.compression_method;
  832. context.filter_method = ihdr.filter_method;
  833. context.interlace_method = ihdr.interlace_method;
  834. dbgln_if(PNG_DEBUG, "PNG: {}x{} ({} bpp)", context.width, context.height, context.bit_depth);
  835. dbgln_if(PNG_DEBUG, " Color type: {}", to_underlying(context.color_type));
  836. dbgln_if(PNG_DEBUG, "Compress Method: {}", context.compression_method);
  837. dbgln_if(PNG_DEBUG, " Filter Method: {}", context.filter_method);
  838. dbgln_if(PNG_DEBUG, " Interlace type: {}", context.interlace_method);
  839. if (context.interlace_method != PngInterlaceMethod::Null && context.interlace_method != PngInterlaceMethod::Adam7) {
  840. dbgln_if(PNG_DEBUG, "PNGLoader::process_IHDR: unknown interlace method: {}", context.interlace_method);
  841. return Error::from_string_literal("Unsupported interlacing method");
  842. }
  843. switch (context.color_type) {
  844. case PNG::ColorType::Greyscale:
  845. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8 && context.bit_depth != 16)
  846. return Error::from_string_literal("Unsupported bit depth for a greyscale image");
  847. context.channels = 1;
  848. break;
  849. case PNG::ColorType::GreyscaleWithAlpha:
  850. if (context.bit_depth != 8 && context.bit_depth != 16)
  851. return Error::from_string_literal("Unsupported bit depth for a greyscale image with alpha");
  852. context.channels = 2;
  853. break;
  854. case PNG::ColorType::Truecolor:
  855. if (context.bit_depth != 8 && context.bit_depth != 16)
  856. return Error::from_string_literal("Unsupported bit depth for a true color image");
  857. context.channels = 3;
  858. break;
  859. case PNG::ColorType::IndexedColor:
  860. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8)
  861. return Error::from_string_literal("Unsupported bit depth for a indexed color image");
  862. context.channels = 1;
  863. break;
  864. case PNG::ColorType::TruecolorWithAlpha:
  865. if (context.bit_depth != 8 && context.bit_depth != 16)
  866. return Error::from_string_literal("Unsupported bit depth for a true color image with alpha");
  867. context.channels = 4;
  868. break;
  869. default:
  870. return Error::from_string_literal("Unsupported color type");
  871. }
  872. context.state = PNGLoadingContext::IHDRDecoded;
  873. return {};
  874. }
  875. static ErrorOr<void> process_IDAT(ReadonlyBytes data, PNGLoadingContext& context)
  876. {
  877. context.compressed_data.append(data);
  878. if (context.state < PNGLoadingContext::State::ImageDataChunkDecoded)
  879. context.state = PNGLoadingContext::State::ImageDataChunkDecoded;
  880. return {};
  881. }
  882. static ErrorOr<void> process_PLTE(ReadonlyBytes data, PNGLoadingContext& context)
  883. {
  884. TRY(context.palette_data.try_append((PaletteEntry const*)data.data(), data.size() / 3));
  885. return {};
  886. }
  887. static ErrorOr<void> process_tRNS(ReadonlyBytes data, PNGLoadingContext& context)
  888. {
  889. switch (context.color_type) {
  890. case PNG::ColorType::Greyscale:
  891. case PNG::ColorType::Truecolor:
  892. case PNG::ColorType::IndexedColor:
  893. TRY(context.palette_transparency_data.try_append(data));
  894. break;
  895. default:
  896. break;
  897. }
  898. return {};
  899. }
  900. static ErrorOr<void> process_cHRM(ReadonlyBytes data, PNGLoadingContext& context)
  901. {
  902. // https://www.w3.org/TR/png/#11cHRM
  903. if (data.size() != 32)
  904. return Error::from_string_literal("cHRM chunk has an abnormal size");
  905. context.chromaticities_and_whitepoint = *bit_cast<ChromaticitiesAndWhitepoint* const>(data.data());
  906. return {};
  907. }
  908. static ErrorOr<void> process_cICP(ReadonlyBytes data, PNGLoadingContext& context)
  909. {
  910. // https://www.w3.org/TR/png/#cICP-chunk
  911. if (data.size() != 4)
  912. return Error::from_string_literal("cICP chunk has an abnormal size");
  913. context.coding_independent_code_points = *bit_cast<CodingIndependentCodePoints* const>(data.data());
  914. return {};
  915. }
  916. static ErrorOr<void> process_iCCP(ReadonlyBytes data, PNGLoadingContext& context)
  917. {
  918. // https://www.w3.org/TR/png/#11iCCP
  919. size_t profile_name_length_max = min(80u, data.size());
  920. size_t profile_name_length = strnlen((char const*)data.data(), profile_name_length_max);
  921. if (profile_name_length == 0 || profile_name_length == profile_name_length_max)
  922. return Error::from_string_literal("iCCP chunk does not contain a profile name");
  923. if (data.size() < profile_name_length + 2)
  924. return Error::from_string_literal("iCCP chunk is too small");
  925. u8 compression_method = data[profile_name_length + 1];
  926. if (compression_method != 0)
  927. return Error::from_string_literal("Unsupported compression method in the iCCP chunk");
  928. context.embedded_icc_profile = EmbeddedICCProfile { { data.data(), profile_name_length }, data.slice(profile_name_length + 2) };
  929. return {};
  930. }
  931. static ErrorOr<void> process_gAMA(ReadonlyBytes data, PNGLoadingContext& context)
  932. {
  933. // https://www.w3.org/TR/png/#11gAMA
  934. if (data.size() != 4)
  935. return Error::from_string_literal("gAMA chunk has an abnormal size");
  936. u32 gamma = *bit_cast<NetworkOrdered<u32> const*>(data.data());
  937. if (gamma & 0x8000'0000)
  938. return Error::from_string_literal("Gamma value is too high");
  939. context.gamma = gamma;
  940. return {};
  941. }
  942. static ErrorOr<void> process_sRGB(ReadonlyBytes data, PNGLoadingContext& context)
  943. {
  944. // https://www.w3.org/TR/png/#srgb-standard-colour-space
  945. if (data.size() != 1) {
  946. // Invalid per spec, but (rarely) happens in the wild. Log and ignore.
  947. warnln("warning: PNG sRGB chunk has an abnormal size; ignoring");
  948. return {};
  949. }
  950. u8 rendering_intent = data[0];
  951. if (rendering_intent > 3)
  952. return Error::from_string_literal("Unsupported rendering intent");
  953. context.sRGB_rendering_intent = (RenderingIntent)rendering_intent;
  954. return {};
  955. }
  956. static ErrorOr<void> process_acTL(ReadonlyBytes data, PNGLoadingContext& context)
  957. {
  958. // https://www.w3.org/TR/png/#acTL-chunk
  959. if (context.has_seen_idat_chunk)
  960. return {}; // Ignore if we encounter it after the first idat
  961. if (data.size() != sizeof(acTL_Chunk))
  962. return Error::from_string_literal("acTL chunk has an abnormal size");
  963. auto const& acTL = *bit_cast<acTL_Chunk* const>(data.data());
  964. context.animation_frame_count = acTL.num_frames;
  965. context.animation_loop_count = acTL.num_plays;
  966. context.has_seen_actl_chunk_before_idat = true;
  967. TRY(context.animation_frames.try_ensure_capacity(context.animation_frame_count));
  968. return {};
  969. }
  970. static ErrorOr<void> process_fcTL(ReadonlyBytes data, PNGLoadingContext& context)
  971. {
  972. // https://www.w3.org/TR/png/#fcTL-chunk
  973. if (!context.has_seen_actl_chunk_before_idat)
  974. return {}; // Ignore if it's not a valid animated png
  975. if (data.size() != sizeof(fcTL_Chunk))
  976. return Error::from_string_literal("fcTL chunk has an abnormal size");
  977. auto const& fcTL = *bit_cast<fcTL_Chunk* const>(data.data());
  978. if (fcTL.sequence_number != context.animation_next_expected_seq)
  979. return Error::from_string_literal("Unexpected sequence number");
  980. context.animation_next_expected_seq++;
  981. if (fcTL.width == 0 || fcTL.height == 0)
  982. return Error::from_string_literal("width and height must be greater than zero in fcTL chunk");
  983. Checked<int> left { static_cast<int>(fcTL.x_offset) };
  984. Checked<int> top { static_cast<int>(fcTL.y_offset) };
  985. Checked<int> width { static_cast<int>(fcTL.width) };
  986. Checked<int> height { static_cast<int>(fcTL.height) };
  987. auto right = left + width;
  988. auto bottom = top + height;
  989. if (left < 0 || width <= 0 || right.has_overflow() || right > context.width)
  990. return Error::from_string_literal("Invalid x_offset value in fcTL chunk");
  991. if (top < 0 || height <= 0 || bottom.has_overflow() || bottom > context.height)
  992. return Error::from_string_literal("Invalid y_offset value in fcTL chunk");
  993. bool is_first_animation_frame = context.animation_frames.is_empty();
  994. if (!is_first_animation_frame)
  995. context.last_completed_animation_frame_index = context.animation_frames.size() - 1;
  996. context.animation_frames.append({ fcTL });
  997. if (!context.has_seen_idat_chunk && is_first_animation_frame)
  998. context.is_first_idat_part_of_animation = true;
  999. return {};
  1000. }
  1001. static ErrorOr<void> process_fdAT(ReadonlyBytes data, PNGLoadingContext& context)
  1002. {
  1003. // https://www.w3.org/TR/png/#fdAT-chunk
  1004. if (data.size() <= 4)
  1005. return Error::from_string_literal("fdAT chunk has an abnormal size");
  1006. u32 sequence_number = *bit_cast<NetworkOrdered<u32> const*>(data.data());
  1007. if (sequence_number != context.animation_next_expected_seq)
  1008. return Error::from_string_literal("Unexpected sequence number");
  1009. context.animation_next_expected_seq++;
  1010. if (context.animation_frames.is_empty())
  1011. return Error::from_string_literal("No frame available");
  1012. auto& current_animation_frame = context.animation_frames[context.animation_frames.size() - 1];
  1013. auto compressed_data = data.slice(4);
  1014. current_animation_frame.compressed_data.append(compressed_data.data(), compressed_data.size());
  1015. return {};
  1016. }
  1017. static void process_IEND(ReadonlyBytes, PNGLoadingContext& context)
  1018. {
  1019. // https://www.w3.org/TR/png/#11IEND
  1020. if (context.has_seen_actl_chunk_before_idat)
  1021. context.last_completed_animation_frame_index = context.animation_frames.size();
  1022. context.has_seen_iend = true;
  1023. }
  1024. static ErrorOr<void> process_chunk(Streamer& streamer, PNGLoadingContext& context)
  1025. {
  1026. u32 chunk_size;
  1027. if (!streamer.read(chunk_size)) {
  1028. dbgln_if(PNG_DEBUG, "Bail at chunk_size");
  1029. return Error::from_string_literal("Error while reading from Streamer");
  1030. }
  1031. Array<u8, 4> chunk_type_buffer;
  1032. StringView const chunk_type { chunk_type_buffer.span() };
  1033. if (!streamer.read_bytes(chunk_type_buffer.data(), chunk_type_buffer.size())) {
  1034. dbgln_if(PNG_DEBUG, "Bail at chunk_type");
  1035. return Error::from_string_literal("Error while reading from Streamer");
  1036. }
  1037. ReadonlyBytes chunk_data;
  1038. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  1039. dbgln_if(PNG_DEBUG, "Bail at chunk_data");
  1040. return Error::from_string_literal("Error while reading from Streamer");
  1041. }
  1042. u32 chunk_crc;
  1043. if (!streamer.read(chunk_crc)) {
  1044. dbgln_if(PNG_DEBUG, "Bail at chunk_crc");
  1045. return Error::from_string_literal("Error while reading from Streamer");
  1046. }
  1047. dbgln_if(PNG_DEBUG, "Chunk type: '{}', size: {}, crc: {:x}", chunk_type, chunk_size, chunk_crc);
  1048. if (chunk_type == "IHDR"sv) {
  1049. if (context.state >= PNGLoadingContext::IHDRDecoded)
  1050. return Error::from_string_literal("Multiple IHDR chunks");
  1051. return process_IHDR(chunk_data, context);
  1052. }
  1053. if (context.state < PNGLoadingContext::IHDRDecoded)
  1054. return Error::from_string_literal("IHDR is not the first chunk of the file");
  1055. if (chunk_type == "IDAT"sv)
  1056. return process_IDAT(chunk_data, context);
  1057. if (chunk_type == "PLTE"sv)
  1058. return process_PLTE(chunk_data, context);
  1059. if (chunk_type == "cHRM"sv)
  1060. return process_cHRM(chunk_data, context);
  1061. if (chunk_type == "cICP"sv)
  1062. return process_cICP(chunk_data, context);
  1063. if (chunk_type == "iCCP"sv)
  1064. return process_iCCP(chunk_data, context);
  1065. if (chunk_type == "gAMA"sv)
  1066. return process_gAMA(chunk_data, context);
  1067. if (chunk_type == "sRGB"sv)
  1068. return process_sRGB(chunk_data, context);
  1069. if (chunk_type == "tRNS"sv)
  1070. return process_tRNS(chunk_data, context);
  1071. if (chunk_type == "acTL"sv)
  1072. return process_acTL(chunk_data, context);
  1073. if (chunk_type == "fcTL"sv)
  1074. return process_fcTL(chunk_data, context);
  1075. if (chunk_type == "fdAT"sv)
  1076. return process_fdAT(chunk_data, context);
  1077. if (chunk_type == "IEND"sv)
  1078. process_IEND(chunk_data, context);
  1079. return {};
  1080. }
  1081. PNGImageDecoderPlugin::PNGImageDecoderPlugin(u8 const* data, size_t size)
  1082. {
  1083. m_context = make<PNGLoadingContext>();
  1084. m_context->data = m_context->data_current_ptr = data;
  1085. m_context->data_size = size;
  1086. }
  1087. PNGImageDecoderPlugin::~PNGImageDecoderPlugin() = default;
  1088. bool PNGImageDecoderPlugin::ensure_image_data_chunk_was_decoded()
  1089. {
  1090. if (m_context->state == PNGLoadingContext::State::Error)
  1091. return false;
  1092. if (m_context->state < PNGLoadingContext::State::ImageDataChunkDecoded) {
  1093. if (!decode_png_image_data_chunk(*m_context))
  1094. return false;
  1095. }
  1096. return true;
  1097. }
  1098. bool PNGImageDecoderPlugin::ensure_animation_frame_was_decoded(u32 animation_frame_index)
  1099. {
  1100. if (m_context->state == PNGLoadingContext::State::Error)
  1101. return false;
  1102. if (m_context->state < PNGLoadingContext::State::ImageDataChunkDecoded) {
  1103. if (!decode_png_image_data_chunk(*m_context))
  1104. return false;
  1105. }
  1106. if (m_context->last_completed_animation_frame_index.has_value()) {
  1107. if (m_context->last_completed_animation_frame_index.value() >= animation_frame_index)
  1108. return true;
  1109. }
  1110. return decode_png_animation_data_chunks(*m_context, animation_frame_index);
  1111. }
  1112. IntSize PNGImageDecoderPlugin::size()
  1113. {
  1114. return { m_context->width, m_context->height };
  1115. }
  1116. bool PNGImageDecoderPlugin::sniff(ReadonlyBytes data)
  1117. {
  1118. PNGLoadingContext context;
  1119. context.data = context.data_current_ptr = data.data();
  1120. context.data_size = data.size();
  1121. return decode_png_header(context);
  1122. }
  1123. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> PNGImageDecoderPlugin::create(ReadonlyBytes data)
  1124. {
  1125. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) PNGImageDecoderPlugin(data.data(), data.size())));
  1126. if (!decode_png_header(*plugin->m_context))
  1127. return Error::from_string_literal("Invalid header for a PNG file");
  1128. TRY(decode_png_ihdr(*plugin->m_context));
  1129. return plugin;
  1130. }
  1131. bool PNGImageDecoderPlugin::is_animated()
  1132. {
  1133. if (!ensure_image_data_chunk_was_decoded())
  1134. return false;
  1135. return m_context->has_seen_actl_chunk_before_idat;
  1136. }
  1137. size_t PNGImageDecoderPlugin::loop_count()
  1138. {
  1139. if (!ensure_image_data_chunk_was_decoded())
  1140. return 0;
  1141. return m_context->animation_loop_count;
  1142. }
  1143. size_t PNGImageDecoderPlugin::frame_count()
  1144. {
  1145. if (!ensure_image_data_chunk_was_decoded())
  1146. return 0;
  1147. if (!m_context->has_seen_actl_chunk_before_idat)
  1148. return 1;
  1149. auto total_frames = m_context->animation_frame_count;
  1150. if (!m_context->is_first_idat_part_of_animation)
  1151. total_frames++;
  1152. return total_frames;
  1153. }
  1154. size_t PNGImageDecoderPlugin::first_animated_frame_index()
  1155. {
  1156. if (!ensure_image_data_chunk_was_decoded())
  1157. return 0;
  1158. if (!m_context->has_seen_actl_chunk_before_idat)
  1159. return 0;
  1160. return m_context->is_first_idat_part_of_animation ? 0 : 1;
  1161. }
  1162. static ErrorOr<RefPtr<Bitmap>> render_animation_frame(AnimationFrame const& prev_animation_frame, AnimationFrame& animation_frame, Bitmap const& decoded_frame_bitmap)
  1163. {
  1164. auto rendered_bitmap = TRY(prev_animation_frame.bitmap->clone());
  1165. Painter painter(rendered_bitmap);
  1166. static constexpr Color transparent_black = { 0, 0, 0, 0 };
  1167. auto frame_rect = animation_frame.rect();
  1168. switch (prev_animation_frame.fcTL.dispose_op) {
  1169. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_NONE:
  1170. break;
  1171. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_BACKGROUND:
  1172. painter.clear_rect(rendered_bitmap->rect(), transparent_black);
  1173. break;
  1174. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_PREVIOUS: {
  1175. painter.blit(frame_rect.location(), *prev_animation_frame.bitmap, frame_rect, 1.0f, false);
  1176. break;
  1177. }
  1178. }
  1179. switch (animation_frame.fcTL.blend_op) {
  1180. case fcTL_Chunk::BlendOp::APNG_BLEND_OP_SOURCE:
  1181. painter.blit(frame_rect.location(), decoded_frame_bitmap, decoded_frame_bitmap.rect(), 1.0f, false);
  1182. break;
  1183. case fcTL_Chunk::BlendOp::APNG_BLEND_OP_OVER:
  1184. painter.blit(frame_rect.location(), decoded_frame_bitmap, decoded_frame_bitmap.rect(), 1.0f, true);
  1185. break;
  1186. }
  1187. return rendered_bitmap;
  1188. }
  1189. ErrorOr<ImageFrameDescriptor> PNGImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1190. {
  1191. if (m_context->state == PNGLoadingContext::State::Error)
  1192. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  1193. if (!ensure_image_data_chunk_was_decoded())
  1194. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding image data chunk");
  1195. auto set_descriptor_duration = [](ImageFrameDescriptor& descriptor, AnimationFrame const& animation_frame) {
  1196. descriptor.duration = static_cast<int>(animation_frame.duration_ms());
  1197. if (descriptor.duration < 0)
  1198. descriptor.duration = NumericLimits<int>::min();
  1199. };
  1200. auto load_default_image = [&]() -> ErrorOr<void> {
  1201. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  1202. // NOTE: This forces the chunk decoding to happen.
  1203. TRY(decode_png_bitmap(*m_context));
  1204. }
  1205. VERIFY(m_context->bitmap);
  1206. return {};
  1207. };
  1208. if (index == 0) {
  1209. TRY(load_default_image());
  1210. ImageFrameDescriptor descriptor { m_context->bitmap };
  1211. if (m_context->has_seen_actl_chunk_before_idat && m_context->is_first_idat_part_of_animation)
  1212. set_descriptor_duration(descriptor, m_context->animation_frames[0]);
  1213. return descriptor;
  1214. }
  1215. if (!m_context->has_seen_actl_chunk_before_idat)
  1216. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid frame index");
  1217. if (!ensure_animation_frame_was_decoded(index))
  1218. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding image data chunk");
  1219. if (index >= m_context->animation_frames.size())
  1220. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid animation frame index");
  1221. // We need to assemble each frame up until the one requested,
  1222. // so decode all bitmaps that haven't been decoded yet.
  1223. for (size_t i = m_context->animation_next_frame_to_render; i <= index; i++) {
  1224. if (i == 0) {
  1225. // If the default image hasn't been loaded, load it now
  1226. TRY(load_default_image()); // May modify animation_frames!
  1227. auto& animation_frame = m_context->animation_frames[i];
  1228. animation_frame.bitmap = m_context->bitmap;
  1229. } else {
  1230. auto& animation_frame = m_context->animation_frames[i];
  1231. VERIFY(!animation_frame.bitmap);
  1232. auto decoded_bitmap = TRY(decode_png_animation_frame_bitmap(*m_context, animation_frame));
  1233. auto prev_animation_frame = m_context->animation_frames[i - 1];
  1234. animation_frame.bitmap = TRY(render_animation_frame(prev_animation_frame, animation_frame, *decoded_bitmap));
  1235. }
  1236. m_context->animation_next_frame_to_render = i + 1;
  1237. }
  1238. auto const& animation_frame = m_context->animation_frames[index];
  1239. VERIFY(animation_frame.bitmap);
  1240. ImageFrameDescriptor descriptor { animation_frame.bitmap };
  1241. set_descriptor_duration(descriptor, animation_frame);
  1242. return descriptor;
  1243. }
  1244. ErrorOr<Optional<ReadonlyBytes>> PNGImageDecoderPlugin::icc_data()
  1245. {
  1246. if (!decode_png_chunks(*m_context))
  1247. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding chunks failed");
  1248. if (m_context->embedded_icc_profile.has_value()) {
  1249. if (!m_context->decompressed_icc_profile.has_value()) {
  1250. auto compressed_data_stream = make<FixedMemoryStream>(m_context->embedded_icc_profile->compressed_data);
  1251. auto decompressor_or_error = Compress::ZlibDecompressor::create(move(compressed_data_stream));
  1252. if (decompressor_or_error.is_error()) {
  1253. m_context->embedded_icc_profile.clear();
  1254. return decompressor_or_error.release_error();
  1255. }
  1256. auto decompressor = decompressor_or_error.release_value();
  1257. auto result_or_error = decompressor->read_until_eof();
  1258. if (result_or_error.is_error()) {
  1259. m_context->embedded_icc_profile.clear();
  1260. return result_or_error.release_error();
  1261. }
  1262. m_context->decompressed_icc_profile = result_or_error.release_value();
  1263. }
  1264. return m_context->decompressed_icc_profile.value();
  1265. }
  1266. // FIXME: Eventually, look at coding_independent_code_points, chromaticities_and_whitepoint, gamma, sRGB_rendering_intent too.
  1267. // The order is:
  1268. // 1. Use coding_independent_code_points if it exists, ignore the rest.
  1269. // 2. Use embedded_icc_profile if it exists, ignore the rest.
  1270. // 3. Use sRGB_rendering_intent if it exists, ignore the rest.
  1271. // 4. Use gamma to adjust gamma and chromaticities_and_whitepoint to adjust color.
  1272. // (Order between 2 and 3 isn't fully clear, but "It is recommended that the sRGB and iCCP chunks do not appear simultaneously in a PNG datastream."
  1273. return OptionalNone {};
  1274. }
  1275. }