PNGLoader.cpp 55 KB

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