PNGLoader.cpp 54 KB

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