PNGLoader.cpp 31 KB

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