PNGLoader.cpp 31 KB

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