PNGLoader.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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/Array.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Endian.h>
  10. #include <AK/Vector.h>
  11. #include <LibCompress/Zlib.h>
  12. #include <LibGfx/PNGLoader.h>
  13. #include <string.h>
  14. #ifdef __serenity__
  15. # include <LibCompress/Deflate.h>
  16. #endif
  17. namespace Gfx {
  18. static constexpr Array<u8, 8> png_header = { 0x89, 'P', 'N', 'G', 13, 10, 26, 10 };
  19. struct PNG_IHDR {
  20. NetworkOrdered<u32> width;
  21. NetworkOrdered<u32> height;
  22. u8 bit_depth { 0 };
  23. u8 color_type { 0 };
  24. u8 compression_method { 0 };
  25. u8 filter_method { 0 };
  26. u8 interlace_method { 0 };
  27. };
  28. static_assert(AssertSize<PNG_IHDR, 13>());
  29. struct Scanline {
  30. u8 filter { 0 };
  31. ReadonlyBytes data {};
  32. };
  33. struct [[gnu::packed]] PaletteEntry {
  34. u8 r;
  35. u8 g;
  36. u8 b;
  37. // u8 a;
  38. };
  39. template<typename T>
  40. struct [[gnu::packed]] Tuple {
  41. T gray;
  42. T a;
  43. };
  44. template<typename T>
  45. struct [[gnu::packed]] Triplet {
  46. T r;
  47. T g;
  48. T b;
  49. bool operator==(Triplet const& other) const = default;
  50. };
  51. template<typename T>
  52. struct [[gnu::packed]] Quartet {
  53. T r;
  54. T g;
  55. T b;
  56. T a;
  57. };
  58. enum PngInterlaceMethod {
  59. Null = 0,
  60. Adam7 = 1
  61. };
  62. struct PNGLoadingContext {
  63. enum State {
  64. NotDecoded = 0,
  65. Error,
  66. HeaderDecoded,
  67. SizeDecoded,
  68. ChunksDecoded,
  69. BitmapDecoded,
  70. };
  71. State state { State::NotDecoded };
  72. u8 const* data { nullptr };
  73. size_t data_size { 0 };
  74. int width { -1 };
  75. int height { -1 };
  76. u8 bit_depth { 0 };
  77. u8 color_type { 0 };
  78. u8 compression_method { 0 };
  79. u8 filter_method { 0 };
  80. u8 interlace_method { 0 };
  81. u8 channels { 0 };
  82. bool has_seen_zlib_header { false };
  83. bool has_alpha() const { return color_type & 4 || palette_transparency_data.size() > 0; }
  84. Vector<Scanline> scanlines;
  85. RefPtr<Gfx::Bitmap> bitmap;
  86. ByteBuffer* decompression_buffer { nullptr };
  87. Vector<u8> compressed_data;
  88. Vector<PaletteEntry> palette_data;
  89. Vector<u8> palette_transparency_data;
  90. Checked<int> compute_row_size_for_width(int width)
  91. {
  92. Checked<int> row_size = width;
  93. row_size *= channels;
  94. row_size *= bit_depth;
  95. row_size += 7;
  96. row_size /= 8;
  97. if (row_size.has_overflow()) {
  98. dbgln("PNG too large, integer overflow while computing row size");
  99. state = State::Error;
  100. }
  101. return row_size;
  102. }
  103. };
  104. class Streamer {
  105. public:
  106. Streamer(u8 const* data, size_t size)
  107. : m_data_ptr(data)
  108. , m_size_remaining(size)
  109. {
  110. }
  111. template<typename T>
  112. bool read(T& value)
  113. {
  114. if (m_size_remaining < sizeof(T))
  115. return false;
  116. value = *((NetworkOrdered<T> const*)m_data_ptr);
  117. m_data_ptr += sizeof(T);
  118. m_size_remaining -= sizeof(T);
  119. return true;
  120. }
  121. bool read_bytes(u8* buffer, size_t count)
  122. {
  123. if (m_size_remaining < count)
  124. return false;
  125. memcpy(buffer, m_data_ptr, count);
  126. m_data_ptr += count;
  127. m_size_remaining -= count;
  128. return true;
  129. }
  130. bool wrap_bytes(ReadonlyBytes& buffer, size_t count)
  131. {
  132. if (m_size_remaining < count)
  133. return false;
  134. buffer = ReadonlyBytes { m_data_ptr, count };
  135. m_data_ptr += count;
  136. m_size_remaining -= count;
  137. return true;
  138. }
  139. bool at_end() const { return !m_size_remaining; }
  140. private:
  141. u8 const* m_data_ptr { nullptr };
  142. size_t m_size_remaining { 0 };
  143. };
  144. static bool process_chunk(Streamer&, PNGLoadingContext& context);
  145. ALWAYS_INLINE static u8 paeth_predictor(int a, int b, int c)
  146. {
  147. int p = a + b - c;
  148. int pa = abs(p - a);
  149. int pb = abs(p - b);
  150. int pc = abs(p - c);
  151. if (pa <= pb && pa <= pc)
  152. return a;
  153. if (pb <= pc)
  154. return b;
  155. return c;
  156. }
  157. union [[gnu::packed]] Pixel {
  158. ARGB32 rgba { 0 };
  159. u8 v[4];
  160. struct {
  161. u8 r;
  162. u8 g;
  163. u8 b;
  164. u8 a;
  165. };
  166. };
  167. static_assert(AssertSize<Pixel, 4>());
  168. template<bool has_alpha, u8 filter_type>
  169. ALWAYS_INLINE static void unfilter_impl(Gfx::Bitmap& bitmap, int y, void const* dummy_scanline_data)
  170. {
  171. auto* dummy_scanline = (Pixel const*)dummy_scanline_data;
  172. if constexpr (filter_type == 0) {
  173. auto* pixels = (Pixel*)bitmap.scanline(y);
  174. for (int i = 0; i < bitmap.width(); ++i) {
  175. auto& x = pixels[i];
  176. swap(x.r, x.b);
  177. }
  178. }
  179. if constexpr (filter_type == 1) {
  180. auto* pixels = (Pixel*)bitmap.scanline(y);
  181. swap(pixels[0].r, pixels[0].b);
  182. for (int i = 1; i < bitmap.width(); ++i) {
  183. auto& x = pixels[i];
  184. swap(x.r, x.b);
  185. auto& a = (Pixel const&)pixels[i - 1];
  186. x.v[0] += a.v[0];
  187. x.v[1] += a.v[1];
  188. x.v[2] += a.v[2];
  189. if constexpr (has_alpha)
  190. x.v[3] += a.v[3];
  191. }
  192. return;
  193. }
  194. if constexpr (filter_type == 2) {
  195. auto* pixels = (Pixel*)bitmap.scanline(y);
  196. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel const*)bitmap.scanline(y - 1);
  197. for (int i = 0; i < bitmap.width(); ++i) {
  198. auto& x = pixels[i];
  199. swap(x.r, x.b);
  200. Pixel const& b = pixels_y_minus_1[i];
  201. x.v[0] += b.v[0];
  202. x.v[1] += b.v[1];
  203. x.v[2] += b.v[2];
  204. if constexpr (has_alpha)
  205. x.v[3] += b.v[3];
  206. }
  207. return;
  208. }
  209. if constexpr (filter_type == 3) {
  210. auto* pixels = (Pixel*)bitmap.scanline(y);
  211. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel const*)bitmap.scanline(y - 1);
  212. for (int i = 0; i < bitmap.width(); ++i) {
  213. auto& x = pixels[i];
  214. swap(x.r, x.b);
  215. Pixel a;
  216. if (i != 0)
  217. a = pixels[i - 1];
  218. Pixel const& b = pixels_y_minus_1[i];
  219. x.v[0] = x.v[0] + ((a.v[0] + b.v[0]) / 2);
  220. x.v[1] = x.v[1] + ((a.v[1] + b.v[1]) / 2);
  221. x.v[2] = x.v[2] + ((a.v[2] + b.v[2]) / 2);
  222. if constexpr (has_alpha)
  223. x.v[3] = x.v[3] + ((a.v[3] + b.v[3]) / 2);
  224. }
  225. return;
  226. }
  227. if constexpr (filter_type == 4) {
  228. auto* pixels = (Pixel*)bitmap.scanline(y);
  229. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  230. for (int i = 0; i < bitmap.width(); ++i) {
  231. auto& x = pixels[i];
  232. swap(x.r, x.b);
  233. Pixel a;
  234. Pixel const& b = pixels_y_minus_1[i];
  235. Pixel c;
  236. if (i != 0) {
  237. a = pixels[i - 1];
  238. c = pixels_y_minus_1[i - 1];
  239. }
  240. x.v[0] += paeth_predictor(a.v[0], b.v[0], c.v[0]);
  241. x.v[1] += paeth_predictor(a.v[1], b.v[1], c.v[1]);
  242. x.v[2] += paeth_predictor(a.v[2], b.v[2], c.v[2]);
  243. if constexpr (has_alpha)
  244. x.v[3] += paeth_predictor(a.v[3], b.v[3], c.v[3]);
  245. }
  246. }
  247. }
  248. template<typename T>
  249. ALWAYS_INLINE static void unpack_grayscale_without_alpha(PNGLoadingContext& context)
  250. {
  251. for (int y = 0; y < context.height; ++y) {
  252. auto* gray_values = reinterpret_cast<const T*>(context.scanlines[y].data.data());
  253. for (int i = 0; i < context.width; ++i) {
  254. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  255. pixel.r = gray_values[i];
  256. pixel.g = gray_values[i];
  257. pixel.b = gray_values[i];
  258. pixel.a = 0xff;
  259. }
  260. }
  261. }
  262. template<typename T>
  263. ALWAYS_INLINE static void unpack_grayscale_with_alpha(PNGLoadingContext& context)
  264. {
  265. for (int y = 0; y < context.height; ++y) {
  266. auto* tuples = reinterpret_cast<Tuple<T> const*>(context.scanlines[y].data.data());
  267. for (int i = 0; i < context.width; ++i) {
  268. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  269. pixel.r = tuples[i].gray;
  270. pixel.g = tuples[i].gray;
  271. pixel.b = tuples[i].gray;
  272. pixel.a = tuples[i].a;
  273. }
  274. }
  275. }
  276. template<typename T>
  277. ALWAYS_INLINE static void unpack_triplets_without_alpha(PNGLoadingContext& context)
  278. {
  279. for (int y = 0; y < context.height; ++y) {
  280. auto* triplets = reinterpret_cast<Triplet<T> const*>(context.scanlines[y].data.data());
  281. for (int i = 0; i < context.width; ++i) {
  282. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  283. pixel.r = triplets[i].r;
  284. pixel.g = triplets[i].g;
  285. pixel.b = triplets[i].b;
  286. pixel.a = 0xff;
  287. }
  288. }
  289. }
  290. template<typename T>
  291. ALWAYS_INLINE static void unpack_triplets_with_transparency_value(PNGLoadingContext& context, Triplet<T> transparency_value)
  292. {
  293. for (int y = 0; y < context.height; ++y) {
  294. auto* triplets = reinterpret_cast<Triplet<T> const*>(context.scanlines[y].data.data());
  295. for (int i = 0; i < context.width; ++i) {
  296. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  297. pixel.r = triplets[i].r;
  298. pixel.g = triplets[i].g;
  299. pixel.b = triplets[i].b;
  300. if (triplets[i] == transparency_value)
  301. pixel.a = 0x00;
  302. else
  303. pixel.a = 0xff;
  304. }
  305. }
  306. }
  307. NEVER_INLINE FLATTEN static ErrorOr<void> unfilter(PNGLoadingContext& context)
  308. {
  309. // First unpack the scanlines to RGBA:
  310. switch (context.color_type) {
  311. case 0:
  312. if (context.bit_depth == 8) {
  313. unpack_grayscale_without_alpha<u8>(context);
  314. } else if (context.bit_depth == 16) {
  315. unpack_grayscale_without_alpha<u16>(context);
  316. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  317. auto bit_depth_squared = context.bit_depth * context.bit_depth;
  318. auto pixels_per_byte = 8 / context.bit_depth;
  319. auto mask = (1 << context.bit_depth) - 1;
  320. for (int y = 0; y < context.height; ++y) {
  321. auto* gray_values = context.scanlines[y].data.data();
  322. for (int x = 0; x < context.width; ++x) {
  323. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (x % pixels_per_byte));
  324. auto value = (gray_values[x / pixels_per_byte] >> bit_offset) & mask;
  325. auto& pixel = (Pixel&)context.bitmap->scanline(y)[x];
  326. pixel.r = value * (0xff / bit_depth_squared);
  327. pixel.g = value * (0xff / bit_depth_squared);
  328. pixel.b = value * (0xff / bit_depth_squared);
  329. pixel.a = 0xff;
  330. }
  331. }
  332. } else {
  333. VERIFY_NOT_REACHED();
  334. }
  335. break;
  336. case 4:
  337. if (context.bit_depth == 8) {
  338. unpack_grayscale_with_alpha<u8>(context);
  339. } else if (context.bit_depth == 16) {
  340. unpack_grayscale_with_alpha<u16>(context);
  341. } else {
  342. VERIFY_NOT_REACHED();
  343. }
  344. break;
  345. case 2:
  346. if (context.palette_transparency_data.size() == 6) {
  347. if (context.bit_depth == 8) {
  348. unpack_triplets_with_transparency_value<u8>(context, Triplet<u8> { context.palette_transparency_data[0], context.palette_transparency_data[2], context.palette_transparency_data[4] });
  349. } else if (context.bit_depth == 16) {
  350. u16 tr = context.palette_transparency_data[0] | context.palette_transparency_data[1] << 8;
  351. u16 tg = context.palette_transparency_data[2] | context.palette_transparency_data[3] << 8;
  352. u16 tb = context.palette_transparency_data[4] | context.palette_transparency_data[5] << 8;
  353. unpack_triplets_with_transparency_value<u16>(context, Triplet<u16> { tr, tg, tb });
  354. } else {
  355. VERIFY_NOT_REACHED();
  356. }
  357. } else {
  358. if (context.bit_depth == 8)
  359. unpack_triplets_without_alpha<u8>(context);
  360. else if (context.bit_depth == 16)
  361. unpack_triplets_without_alpha<u16>(context);
  362. else
  363. VERIFY_NOT_REACHED();
  364. }
  365. break;
  366. case 6:
  367. if (context.bit_depth == 8) {
  368. for (int y = 0; y < context.height; ++y) {
  369. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  370. }
  371. } else if (context.bit_depth == 16) {
  372. for (int y = 0; y < context.height; ++y) {
  373. auto* quartets = reinterpret_cast<Quartet<u16> const*>(context.scanlines[y].data.data());
  374. for (int i = 0; i < context.width; ++i) {
  375. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  376. pixel.r = quartets[i].r & 0xFF;
  377. pixel.g = quartets[i].g & 0xFF;
  378. pixel.b = quartets[i].b & 0xFF;
  379. pixel.a = quartets[i].a & 0xFF;
  380. }
  381. }
  382. } else {
  383. VERIFY_NOT_REACHED();
  384. }
  385. break;
  386. case 3:
  387. if (context.bit_depth == 8) {
  388. for (int y = 0; y < context.height; ++y) {
  389. auto* palette_index = context.scanlines[y].data.data();
  390. for (int i = 0; i < context.width; ++i) {
  391. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  392. if (palette_index[i] >= context.palette_data.size())
  393. return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range"sv);
  394. auto& color = context.palette_data.at((int)palette_index[i]);
  395. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u
  396. ? context.palette_transparency_data.data()[palette_index[i]]
  397. : 0xff;
  398. pixel.r = color.r;
  399. pixel.g = color.g;
  400. pixel.b = color.b;
  401. pixel.a = transparency;
  402. }
  403. }
  404. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  405. auto pixels_per_byte = 8 / context.bit_depth;
  406. auto mask = (1 << context.bit_depth) - 1;
  407. for (int y = 0; y < context.height; ++y) {
  408. auto* palette_indices = context.scanlines[y].data.data();
  409. for (int i = 0; i < context.width; ++i) {
  410. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (i % pixels_per_byte));
  411. auto palette_index = (palette_indices[i / pixels_per_byte] >> bit_offset) & mask;
  412. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  413. if ((size_t)palette_index >= context.palette_data.size())
  414. return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range"sv);
  415. auto& color = context.palette_data.at(palette_index);
  416. auto transparency = context.palette_transparency_data.size() >= palette_index + 1u
  417. ? context.palette_transparency_data.data()[palette_index]
  418. : 0xff;
  419. pixel.r = color.r;
  420. pixel.g = color.g;
  421. pixel.b = color.b;
  422. pixel.a = transparency;
  423. }
  424. }
  425. } else {
  426. VERIFY_NOT_REACHED();
  427. }
  428. break;
  429. default:
  430. VERIFY_NOT_REACHED();
  431. break;
  432. }
  433. u8 dummy_scanline[context.width * sizeof(ARGB32)];
  434. memset(dummy_scanline, 0, sizeof(dummy_scanline));
  435. for (int y = 0; y < context.height; ++y) {
  436. auto filter = context.scanlines[y].filter;
  437. if (filter == 0) {
  438. if (context.has_alpha())
  439. unfilter_impl<true, 0>(*context.bitmap, y, dummy_scanline);
  440. else
  441. unfilter_impl<false, 0>(*context.bitmap, y, dummy_scanline);
  442. continue;
  443. }
  444. if (filter == 1) {
  445. if (context.has_alpha())
  446. unfilter_impl<true, 1>(*context.bitmap, y, dummy_scanline);
  447. else
  448. unfilter_impl<false, 1>(*context.bitmap, y, dummy_scanline);
  449. continue;
  450. }
  451. if (filter == 2) {
  452. if (context.has_alpha())
  453. unfilter_impl<true, 2>(*context.bitmap, y, dummy_scanline);
  454. else
  455. unfilter_impl<false, 2>(*context.bitmap, y, dummy_scanline);
  456. continue;
  457. }
  458. if (filter == 3) {
  459. if (context.has_alpha())
  460. unfilter_impl<true, 3>(*context.bitmap, y, dummy_scanline);
  461. else
  462. unfilter_impl<false, 3>(*context.bitmap, y, dummy_scanline);
  463. continue;
  464. }
  465. if (filter == 4) {
  466. if (context.has_alpha())
  467. unfilter_impl<true, 4>(*context.bitmap, y, dummy_scanline);
  468. else
  469. unfilter_impl<false, 4>(*context.bitmap, y, dummy_scanline);
  470. continue;
  471. }
  472. }
  473. return {};
  474. }
  475. static bool decode_png_header(PNGLoadingContext& context)
  476. {
  477. if (context.state >= PNGLoadingContext::HeaderDecoded)
  478. return true;
  479. if (!context.data || context.data_size < sizeof(png_header)) {
  480. dbgln_if(PNG_DEBUG, "Missing PNG header");
  481. context.state = PNGLoadingContext::State::Error;
  482. return false;
  483. }
  484. if (memcmp(context.data, png_header.span().data(), sizeof(png_header)) != 0) {
  485. dbgln_if(PNG_DEBUG, "Invalid PNG header");
  486. context.state = PNGLoadingContext::State::Error;
  487. return false;
  488. }
  489. context.state = PNGLoadingContext::HeaderDecoded;
  490. return true;
  491. }
  492. static bool decode_png_size(PNGLoadingContext& context)
  493. {
  494. if (context.state >= PNGLoadingContext::SizeDecoded)
  495. return true;
  496. if (context.state < PNGLoadingContext::HeaderDecoded) {
  497. if (!decode_png_header(context))
  498. return false;
  499. }
  500. u8 const* data_ptr = context.data + sizeof(png_header);
  501. size_t data_remaining = context.data_size - sizeof(png_header);
  502. Streamer streamer(data_ptr, data_remaining);
  503. while (!streamer.at_end()) {
  504. if (!process_chunk(streamer, context)) {
  505. context.state = PNGLoadingContext::State::Error;
  506. return false;
  507. }
  508. if (context.width && context.height) {
  509. context.state = PNGLoadingContext::State::SizeDecoded;
  510. return true;
  511. }
  512. }
  513. return false;
  514. }
  515. static bool decode_png_chunks(PNGLoadingContext& context)
  516. {
  517. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  518. return true;
  519. if (context.state < PNGLoadingContext::HeaderDecoded) {
  520. if (!decode_png_header(context))
  521. return false;
  522. }
  523. u8 const* data_ptr = context.data + sizeof(png_header);
  524. int data_remaining = context.data_size - sizeof(png_header);
  525. context.compressed_data.ensure_capacity(context.data_size);
  526. Streamer streamer(data_ptr, data_remaining);
  527. while (!streamer.at_end()) {
  528. if (!process_chunk(streamer, context)) {
  529. // Ignore failed chunk and just consider chunk decoding being done.
  530. // decode_png_bitmap() will check whether we got all required ones anyway.
  531. break;
  532. }
  533. }
  534. context.state = PNGLoadingContext::State::ChunksDecoded;
  535. return true;
  536. }
  537. static ErrorOr<void> decode_png_bitmap_simple(PNGLoadingContext& context)
  538. {
  539. Streamer streamer(context.decompression_buffer->data(), context.decompression_buffer->size());
  540. for (int y = 0; y < context.height; ++y) {
  541. u8 filter;
  542. if (!streamer.read(filter)) {
  543. context.state = PNGLoadingContext::State::Error;
  544. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv);
  545. }
  546. if (filter > 4) {
  547. context.state = PNGLoadingContext::State::Error;
  548. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter"sv);
  549. }
  550. context.scanlines.append({ filter });
  551. auto& scanline_buffer = context.scanlines.last().data;
  552. auto row_size = context.compute_row_size_for_width(context.width);
  553. if (row_size.has_overflow())
  554. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow"sv);
  555. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  556. context.state = PNGLoadingContext::State::Error;
  557. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv);
  558. }
  559. }
  560. context.bitmap = TRY(Bitmap::try_create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  561. return unfilter(context);
  562. }
  563. static int adam7_height(PNGLoadingContext& context, int pass)
  564. {
  565. switch (pass) {
  566. case 1:
  567. return (context.height + 7) / 8;
  568. case 2:
  569. return (context.height + 7) / 8;
  570. case 3:
  571. return (context.height + 3) / 8;
  572. case 4:
  573. return (context.height + 3) / 4;
  574. case 5:
  575. return (context.height + 1) / 4;
  576. case 6:
  577. return (context.height + 1) / 2;
  578. case 7:
  579. return context.height / 2;
  580. default:
  581. VERIFY_NOT_REACHED();
  582. }
  583. }
  584. static int adam7_width(PNGLoadingContext& context, int pass)
  585. {
  586. switch (pass) {
  587. case 1:
  588. return (context.width + 7) / 8;
  589. case 2:
  590. return (context.width + 3) / 8;
  591. case 3:
  592. return (context.width + 3) / 4;
  593. case 4:
  594. return (context.width + 1) / 4;
  595. case 5:
  596. return (context.width + 1) / 2;
  597. case 6:
  598. return context.width / 2;
  599. case 7:
  600. return context.width;
  601. default:
  602. VERIFY_NOT_REACHED();
  603. }
  604. }
  605. // Index 0 unused (non-interlaced case)
  606. static int adam7_starty[8] = { 0, 0, 0, 4, 0, 2, 0, 1 };
  607. static int adam7_startx[8] = { 0, 0, 4, 0, 2, 0, 1, 0 };
  608. static int adam7_stepy[8] = { 1, 8, 8, 8, 4, 4, 2, 2 };
  609. static int adam7_stepx[8] = { 1, 8, 8, 4, 4, 2, 2, 1 };
  610. static ErrorOr<void> decode_adam7_pass(PNGLoadingContext& context, Streamer& streamer, int pass)
  611. {
  612. PNGLoadingContext subimage_context;
  613. subimage_context.width = adam7_width(context, pass);
  614. subimage_context.height = adam7_height(context, pass);
  615. subimage_context.channels = context.channels;
  616. subimage_context.color_type = context.color_type;
  617. subimage_context.palette_data = context.palette_data;
  618. subimage_context.palette_transparency_data = context.palette_transparency_data;
  619. subimage_context.bit_depth = context.bit_depth;
  620. subimage_context.filter_method = context.filter_method;
  621. // For small images, some passes might be empty
  622. if (!subimage_context.width || !subimage_context.height)
  623. return {};
  624. subimage_context.scanlines.clear_with_capacity();
  625. for (int y = 0; y < subimage_context.height; ++y) {
  626. u8 filter;
  627. if (!streamer.read(filter)) {
  628. context.state = PNGLoadingContext::State::Error;
  629. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv);
  630. }
  631. if (filter > 4) {
  632. context.state = PNGLoadingContext::State::Error;
  633. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter"sv);
  634. }
  635. subimage_context.scanlines.append({ filter });
  636. auto& scanline_buffer = subimage_context.scanlines.last().data;
  637. auto row_size = context.compute_row_size_for_width(subimage_context.width);
  638. if (row_size.has_overflow())
  639. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow"sv);
  640. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  641. context.state = PNGLoadingContext::State::Error;
  642. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv);
  643. }
  644. }
  645. subimage_context.bitmap = TRY(Bitmap::try_create(context.bitmap->format(), { subimage_context.width, subimage_context.height }));
  646. TRY(unfilter(subimage_context));
  647. // Copy the subimage data into the main image according to the pass pattern
  648. for (int y = 0, dy = adam7_starty[pass]; y < subimage_context.height && dy < context.height; ++y, dy += adam7_stepy[pass]) {
  649. for (int x = 0, dx = adam7_startx[pass]; x < subimage_context.width && dy < context.width; ++x, dx += adam7_stepx[pass]) {
  650. context.bitmap->set_pixel(dx, dy, subimage_context.bitmap->get_pixel(x, y));
  651. }
  652. }
  653. return {};
  654. }
  655. static ErrorOr<void> decode_png_adam7(PNGLoadingContext& context)
  656. {
  657. Streamer streamer(context.decompression_buffer->data(), context.decompression_buffer->size());
  658. context.bitmap = TRY(Bitmap::try_create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  659. for (int pass = 1; pass <= 7; ++pass)
  660. TRY(decode_adam7_pass(context, streamer, pass));
  661. return {};
  662. }
  663. static ErrorOr<void> decode_png_bitmap(PNGLoadingContext& context)
  664. {
  665. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  666. if (!decode_png_chunks(context))
  667. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv);
  668. }
  669. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  670. return {};
  671. if (context.width == -1 || context.height == -1)
  672. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see an IHDR chunk."sv);
  673. if (context.color_type == 3 && context.palette_data.is_empty())
  674. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty."sv);
  675. auto result = Compress::Zlib::decompress_all(context.compressed_data.span());
  676. if (!result.has_value()) {
  677. context.state = PNGLoadingContext::State::Error;
  678. return Error::from_string_literal("PNGImageDecoderPlugin: Decompression failed"sv);
  679. }
  680. context.decompression_buffer = &result.value();
  681. context.compressed_data.clear();
  682. context.scanlines.ensure_capacity(context.height);
  683. switch (context.interlace_method) {
  684. case PngInterlaceMethod::Null:
  685. TRY(decode_png_bitmap_simple(context));
  686. break;
  687. case PngInterlaceMethod::Adam7:
  688. TRY(decode_png_adam7(context));
  689. break;
  690. default:
  691. context.state = PNGLoadingContext::State::Error;
  692. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method"sv);
  693. }
  694. context.decompression_buffer = nullptr;
  695. context.state = PNGLoadingContext::State::BitmapDecoded;
  696. return {};
  697. }
  698. static bool is_valid_compression_method(u8 compression_method)
  699. {
  700. return compression_method == 0;
  701. }
  702. static bool is_valid_filter_method(u8 filter_method)
  703. {
  704. return filter_method == 0;
  705. }
  706. static bool process_IHDR(ReadonlyBytes data, PNGLoadingContext& context)
  707. {
  708. if (data.size() < (int)sizeof(PNG_IHDR))
  709. return false;
  710. auto& ihdr = *(const PNG_IHDR*)data.data();
  711. if (ihdr.width > maximum_width_for_decoded_images || ihdr.height > maximum_height_for_decoded_images) {
  712. dbgln("This PNG is too large for comfort: {}x{}", (u32)ihdr.width, (u32)ihdr.height);
  713. return false;
  714. }
  715. if (!is_valid_compression_method(ihdr.compression_method)) {
  716. dbgln("PNG has invalid compression method {}", ihdr.compression_method);
  717. return false;
  718. }
  719. if (!is_valid_filter_method(ihdr.filter_method)) {
  720. dbgln("PNG has invalid filter method {}", ihdr.filter_method);
  721. return false;
  722. }
  723. context.width = ihdr.width;
  724. context.height = ihdr.height;
  725. context.bit_depth = ihdr.bit_depth;
  726. context.color_type = ihdr.color_type;
  727. context.compression_method = ihdr.compression_method;
  728. context.filter_method = ihdr.filter_method;
  729. context.interlace_method = ihdr.interlace_method;
  730. dbgln_if(PNG_DEBUG, "PNG: {}x{} ({} bpp)", context.width, context.height, context.bit_depth);
  731. dbgln_if(PNG_DEBUG, " Color type: {}", context.color_type);
  732. dbgln_if(PNG_DEBUG, "Compress Method: {}", context.compression_method);
  733. dbgln_if(PNG_DEBUG, " Filter Method: {}", context.filter_method);
  734. dbgln_if(PNG_DEBUG, " Interlace type: {}", context.interlace_method);
  735. if (context.interlace_method != PngInterlaceMethod::Null && context.interlace_method != PngInterlaceMethod::Adam7) {
  736. dbgln_if(PNG_DEBUG, "PNGLoader::process_IHDR: unknown interlace method: {}", context.interlace_method);
  737. return false;
  738. }
  739. switch (context.color_type) {
  740. case 0: // Each pixel is a grayscale sample.
  741. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8 && context.bit_depth != 16)
  742. return false;
  743. context.channels = 1;
  744. break;
  745. case 4: // Each pixel is a grayscale sample, followed by an alpha sample.
  746. if (context.bit_depth != 8 && context.bit_depth != 16)
  747. return false;
  748. context.channels = 2;
  749. break;
  750. case 2: // Each pixel is an RGB sample
  751. if (context.bit_depth != 8 && context.bit_depth != 16)
  752. return false;
  753. context.channels = 3;
  754. break;
  755. case 3: // Each pixel is a palette index; a PLTE chunk must appear.
  756. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8)
  757. return false;
  758. context.channels = 1;
  759. break;
  760. case 6: // Each pixel is an RGB sample, followed by an alpha sample.
  761. if (context.bit_depth != 8 && context.bit_depth != 16)
  762. return false;
  763. context.channels = 4;
  764. break;
  765. default:
  766. return false;
  767. }
  768. return true;
  769. }
  770. static bool process_IDAT(ReadonlyBytes data, PNGLoadingContext& context)
  771. {
  772. context.compressed_data.append(data.data(), data.size());
  773. return true;
  774. }
  775. static bool process_PLTE(ReadonlyBytes data, PNGLoadingContext& context)
  776. {
  777. context.palette_data.append((PaletteEntry const*)data.data(), data.size() / 3);
  778. return true;
  779. }
  780. static bool process_tRNS(ReadonlyBytes data, PNGLoadingContext& context)
  781. {
  782. switch (context.color_type) {
  783. case 0:
  784. case 2:
  785. case 3:
  786. context.palette_transparency_data.append(data.data(), data.size());
  787. break;
  788. }
  789. return true;
  790. }
  791. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  792. {
  793. u32 chunk_size;
  794. if (!streamer.read(chunk_size)) {
  795. dbgln_if(PNG_DEBUG, "Bail at chunk_size");
  796. return false;
  797. }
  798. u8 chunk_type[5];
  799. chunk_type[4] = '\0';
  800. if (!streamer.read_bytes(chunk_type, 4)) {
  801. dbgln_if(PNG_DEBUG, "Bail at chunk_type");
  802. return false;
  803. }
  804. ReadonlyBytes chunk_data;
  805. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  806. dbgln_if(PNG_DEBUG, "Bail at chunk_data");
  807. return false;
  808. }
  809. u32 chunk_crc;
  810. if (!streamer.read(chunk_crc)) {
  811. dbgln_if(PNG_DEBUG, "Bail at chunk_crc");
  812. return false;
  813. }
  814. dbgln_if(PNG_DEBUG, "Chunk type: '{}', size: {}, crc: {:x}", chunk_type, chunk_size, chunk_crc);
  815. if (!strcmp((char const*)chunk_type, "IHDR"))
  816. return process_IHDR(chunk_data, context);
  817. if (!strcmp((char const*)chunk_type, "IDAT"))
  818. return process_IDAT(chunk_data, context);
  819. if (!strcmp((char const*)chunk_type, "PLTE"))
  820. return process_PLTE(chunk_data, context);
  821. if (!strcmp((char const*)chunk_type, "tRNS"))
  822. return process_tRNS(chunk_data, context);
  823. return true;
  824. }
  825. PNGImageDecoderPlugin::PNGImageDecoderPlugin(u8 const* data, size_t size)
  826. {
  827. m_context = make<PNGLoadingContext>();
  828. m_context->data = data;
  829. m_context->data_size = size;
  830. }
  831. PNGImageDecoderPlugin::~PNGImageDecoderPlugin() = default;
  832. IntSize PNGImageDecoderPlugin::size()
  833. {
  834. if (m_context->state == PNGLoadingContext::State::Error)
  835. return {};
  836. if (m_context->state < PNGLoadingContext::State::SizeDecoded) {
  837. bool success = decode_png_size(*m_context);
  838. if (!success)
  839. return {};
  840. }
  841. return { m_context->width, m_context->height };
  842. }
  843. void PNGImageDecoderPlugin::set_volatile()
  844. {
  845. if (m_context->bitmap)
  846. m_context->bitmap->set_volatile();
  847. }
  848. bool PNGImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  849. {
  850. if (!m_context->bitmap)
  851. return false;
  852. return m_context->bitmap->set_nonvolatile(was_purged);
  853. }
  854. bool PNGImageDecoderPlugin::sniff()
  855. {
  856. return decode_png_header(*m_context);
  857. }
  858. bool PNGImageDecoderPlugin::is_animated()
  859. {
  860. return false;
  861. }
  862. size_t PNGImageDecoderPlugin::loop_count()
  863. {
  864. return 0;
  865. }
  866. size_t PNGImageDecoderPlugin::frame_count()
  867. {
  868. return 1;
  869. }
  870. ErrorOr<ImageFrameDescriptor> PNGImageDecoderPlugin::frame(size_t index)
  871. {
  872. if (index > 0)
  873. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid frame index"sv);
  874. if (m_context->state == PNGLoadingContext::State::Error)
  875. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv);
  876. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  877. // NOTE: This forces the chunk decoding to happen.
  878. TRY(decode_png_bitmap(*m_context));
  879. }
  880. VERIFY(m_context->bitmap);
  881. return ImageFrameDescriptor { m_context->bitmap, 0 };
  882. }
  883. }