PNGLoader.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/FileSystemPath.h>
  27. #include <AK/MappedFile.h>
  28. #include <AK/NetworkOrdered.h>
  29. #include <LibCore/puff.h>
  30. #include <LibDraw/PNGLoader.h>
  31. #include <fcntl.h>
  32. #include <serenity.h>
  33. #include <stdio.h>
  34. #include <string.h>
  35. #include <sys/mman.h>
  36. #include <sys/stat.h>
  37. #include <unistd.h>
  38. static const u8 png_header[8] = { 0x89, 'P', 'N', 'G', 13, 10, 26, 10 };
  39. struct PNG_IHDR {
  40. NetworkOrdered<u32> width;
  41. NetworkOrdered<u32> height;
  42. u8 bit_depth { 0 };
  43. u8 color_type { 0 };
  44. u8 compression_method { 0 };
  45. u8 filter_method { 0 };
  46. u8 interlace_method { 0 };
  47. };
  48. static_assert(sizeof(PNG_IHDR) == 13);
  49. struct Scanline {
  50. u8 filter { 0 };
  51. ByteBuffer data {};
  52. };
  53. struct [[gnu::packed]] PaletteEntry
  54. {
  55. u8 r;
  56. u8 g;
  57. u8 b;
  58. //u8 a;
  59. };
  60. struct [[gnu::packed]] Triplet
  61. {
  62. u8 r;
  63. u8 g;
  64. u8 b;
  65. };
  66. struct [[gnu::packed]] Triplet16
  67. {
  68. u16 r;
  69. u16 g;
  70. u16 b;
  71. };
  72. struct [[gnu::packed]] Quad16
  73. {
  74. u16 r;
  75. u16 g;
  76. u16 b;
  77. u16 a;
  78. };
  79. struct PNGLoadingContext {
  80. enum State {
  81. NotDecoded = 0,
  82. Error,
  83. HeaderDecoded,
  84. SizeDecoded,
  85. ChunksDecoded,
  86. BitmapDecoded,
  87. };
  88. State state { State::NotDecoded };
  89. const u8* data { nullptr };
  90. size_t data_size { 0 };
  91. int width { -1 };
  92. int height { -1 };
  93. u8 bit_depth { 0 };
  94. u8 color_type { 0 };
  95. u8 compression_method { 0 };
  96. u8 filter_method { 0 };
  97. u8 interlace_method { 0 };
  98. u8 bytes_per_pixel { 0 };
  99. bool has_seen_zlib_header { false };
  100. bool has_alpha() const { return color_type & 4 || palette_transparency_data.size() > 0; }
  101. Vector<Scanline> scanlines;
  102. RefPtr<GraphicsBitmap> bitmap;
  103. u8* decompression_buffer { nullptr };
  104. int decompression_buffer_size { 0 };
  105. Vector<u8> compressed_data;
  106. Vector<PaletteEntry> palette_data;
  107. Vector<u8> palette_transparency_data;
  108. };
  109. class Streamer {
  110. public:
  111. Streamer(const u8* data, int size)
  112. : m_original_data(data)
  113. , m_original_size(size)
  114. , m_data_ptr(data)
  115. , m_size_remaining(size)
  116. {
  117. }
  118. template<typename T>
  119. bool read(T& value)
  120. {
  121. if (m_size_remaining < (int)sizeof(T))
  122. return false;
  123. value = *((const NetworkOrdered<T>*)m_data_ptr);
  124. m_data_ptr += sizeof(T);
  125. m_size_remaining -= sizeof(T);
  126. return true;
  127. }
  128. bool read_bytes(u8* buffer, int count)
  129. {
  130. if (m_size_remaining < count)
  131. return false;
  132. memcpy(buffer, m_data_ptr, count);
  133. m_data_ptr += count;
  134. m_size_remaining -= count;
  135. return true;
  136. }
  137. bool wrap_bytes(ByteBuffer& buffer, int count)
  138. {
  139. if (m_size_remaining < count)
  140. return false;
  141. buffer = ByteBuffer::wrap(m_data_ptr, count);
  142. m_data_ptr += count;
  143. m_size_remaining -= count;
  144. return true;
  145. }
  146. bool at_end() const { return !m_size_remaining; }
  147. private:
  148. const u8* m_original_data;
  149. int m_original_size;
  150. const u8* m_data_ptr;
  151. int m_size_remaining;
  152. };
  153. static RefPtr<GraphicsBitmap> load_png_impl(const u8*, int);
  154. static bool process_chunk(Streamer&, PNGLoadingContext& context, bool decode_size_only);
  155. RefPtr<GraphicsBitmap> load_png(const StringView& path)
  156. {
  157. MappedFile mapped_file(path);
  158. if (!mapped_file.is_valid())
  159. return nullptr;
  160. auto bitmap = load_png_impl((const u8*)mapped_file.data(), mapped_file.size());
  161. if (bitmap)
  162. bitmap->set_mmap_name(String::format("GraphicsBitmap [%dx%d] - Decoded PNG: %s", bitmap->width(), bitmap->height(), canonicalized_path(path).characters()));
  163. return bitmap;
  164. }
  165. RefPtr<GraphicsBitmap> load_png_from_memory(const u8* data, size_t length)
  166. {
  167. auto bitmap = load_png_impl(data, length);
  168. if (bitmap)
  169. bitmap->set_mmap_name(String::format("GraphicsBitmap [%dx%d] - Decoded PNG: <memory>", bitmap->width(), bitmap->height()));
  170. return bitmap;
  171. }
  172. [[gnu::always_inline]] static inline u8 paeth_predictor(int a, int b, int c)
  173. {
  174. int p = a + b - c;
  175. int pa = abs(p - a);
  176. int pb = abs(p - b);
  177. int pc = abs(p - c);
  178. if (pa <= pb && pa <= pc)
  179. return a;
  180. if (pb <= pc)
  181. return b;
  182. return c;
  183. }
  184. union [[gnu::packed]] Pixel
  185. {
  186. RGBA32 rgba { 0 };
  187. u8 v[4];
  188. struct {
  189. u8 r;
  190. u8 g;
  191. u8 b;
  192. u8 a;
  193. };
  194. };
  195. static_assert(sizeof(Pixel) == 4);
  196. template<bool has_alpha, u8 filter_type>
  197. [[gnu::always_inline]] static inline void unfilter_impl(GraphicsBitmap& bitmap, int y, const void* dummy_scanline_data)
  198. {
  199. auto* dummy_scanline = (const Pixel*)dummy_scanline_data;
  200. if constexpr (filter_type == 0) {
  201. auto* pixels = (Pixel*)bitmap.scanline(y);
  202. for (int i = 0; i < bitmap.width(); ++i) {
  203. auto& x = pixels[i];
  204. swap(x.r, x.b);
  205. }
  206. }
  207. if constexpr (filter_type == 1) {
  208. auto* pixels = (Pixel*)bitmap.scanline(y);
  209. swap(pixels[0].r, pixels[0].b);
  210. for (int i = 1; i < bitmap.width(); ++i) {
  211. auto& x = pixels[i];
  212. swap(x.r, x.b);
  213. auto& a = (const Pixel&)pixels[i - 1];
  214. x.v[0] += a.v[0];
  215. x.v[1] += a.v[1];
  216. x.v[2] += a.v[2];
  217. if constexpr (has_alpha)
  218. x.v[3] += a.v[3];
  219. }
  220. return;
  221. }
  222. if constexpr (filter_type == 2) {
  223. auto* pixels = (Pixel*)bitmap.scanline(y);
  224. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  225. for (int i = 0; i < bitmap.width(); ++i) {
  226. auto& x = pixels[i];
  227. swap(x.r, x.b);
  228. const Pixel& b = pixels_y_minus_1[i];
  229. x.v[0] += b.v[0];
  230. x.v[1] += b.v[1];
  231. x.v[2] += b.v[2];
  232. if constexpr (has_alpha)
  233. x.v[3] += b.v[3];
  234. }
  235. return;
  236. }
  237. if constexpr (filter_type == 3) {
  238. auto* pixels = (Pixel*)bitmap.scanline(y);
  239. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  240. for (int i = 0; i < bitmap.width(); ++i) {
  241. auto& x = pixels[i];
  242. swap(x.r, x.b);
  243. Pixel a;
  244. if (i != 0)
  245. a = pixels[i - 1];
  246. const Pixel& b = pixels_y_minus_1[i];
  247. x.v[0] = x.v[0] + ((a.v[0] + b.v[0]) / 2);
  248. x.v[1] = x.v[1] + ((a.v[1] + b.v[1]) / 2);
  249. x.v[2] = x.v[2] + ((a.v[2] + b.v[2]) / 2);
  250. if constexpr (has_alpha)
  251. x.v[3] = x.v[3] + ((a.v[3] + b.v[3]) / 2);
  252. }
  253. return;
  254. }
  255. if constexpr (filter_type == 4) {
  256. auto* pixels = (Pixel*)bitmap.scanline(y);
  257. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  258. for (int i = 0; i < bitmap.width(); ++i) {
  259. auto& x = pixels[i];
  260. swap(x.r, x.b);
  261. Pixel a;
  262. const Pixel& b = pixels_y_minus_1[i];
  263. Pixel c;
  264. if (i != 0) {
  265. a = pixels[i - 1];
  266. c = pixels_y_minus_1[i - 1];
  267. }
  268. x.v[0] += paeth_predictor(a.v[0], b.v[0], c.v[0]);
  269. x.v[1] += paeth_predictor(a.v[1], b.v[1], c.v[1]);
  270. x.v[2] += paeth_predictor(a.v[2], b.v[2], c.v[2]);
  271. if constexpr (has_alpha)
  272. x.v[3] += paeth_predictor(a.v[3], b.v[3], c.v[3]);
  273. }
  274. }
  275. }
  276. [[gnu::noinline]] static void unfilter(PNGLoadingContext& context)
  277. {
  278. // First unpack the scanlines to RGBA:
  279. switch (context.color_type) {
  280. case 2:
  281. if (context.bit_depth == 8) {
  282. for (int y = 0; y < context.height; ++y) {
  283. auto* triplets = (Triplet*)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. } else if (context.bit_depth == 16) {
  293. for (int y = 0; y < context.height; ++y) {
  294. auto* triplets = (Triplet16*)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 & 0xFF;
  298. pixel.g = triplets[i].g & 0xFF;
  299. pixel.b = triplets[i].b & 0xFF;
  300. pixel.a = 0xff;
  301. }
  302. }
  303. } else {
  304. ASSERT_NOT_REACHED();
  305. }
  306. break;
  307. case 6:
  308. if (context.bit_depth == 8) {
  309. for (int y = 0; y < context.height; ++y) {
  310. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  311. }
  312. } else if (context.bit_depth == 16) {
  313. for (int y = 0; y < context.height; ++y) {
  314. auto* triplets = (Quad16*)context.scanlines[y].data.data();
  315. for (int i = 0; i < context.width; ++i) {
  316. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  317. pixel.r = triplets[i].r & 0xFF;
  318. pixel.g = triplets[i].g & 0xFF;
  319. pixel.b = triplets[i].b & 0xFF;
  320. pixel.a = triplets[i].a & 0xFF;
  321. }
  322. }
  323. } else {
  324. ASSERT_NOT_REACHED();
  325. }
  326. break;
  327. case 3:
  328. for (int y = 0; y < context.height; ++y) {
  329. auto* palette_index = (u8*)context.scanlines[y].data.data();
  330. for (int i = 0; i < context.width; ++i) {
  331. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  332. auto& color = context.palette_data.at((int)palette_index[i]);
  333. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1
  334. ? (int)context.palette_transparency_data.data()[palette_index[i]]
  335. : 0xFF;
  336. pixel.r = color.r;
  337. pixel.g = color.g;
  338. pixel.b = color.b;
  339. pixel.a = transparency;
  340. }
  341. }
  342. break;
  343. default:
  344. ASSERT_NOT_REACHED();
  345. break;
  346. }
  347. auto dummy_scanline = ByteBuffer::create_zeroed(context.width * sizeof(RGBA32));
  348. for (int y = 0; y < context.height; ++y) {
  349. auto filter = context.scanlines[y].filter;
  350. if (filter == 0) {
  351. if (context.has_alpha())
  352. unfilter_impl<true, 0>(*context.bitmap, y, dummy_scanline.data());
  353. else
  354. unfilter_impl<false, 0>(*context.bitmap, y, dummy_scanline.data());
  355. continue;
  356. }
  357. if (filter == 1) {
  358. if (context.has_alpha())
  359. unfilter_impl<true, 1>(*context.bitmap, y, dummy_scanline.data());
  360. else
  361. unfilter_impl<false, 1>(*context.bitmap, y, dummy_scanline.data());
  362. continue;
  363. }
  364. if (filter == 2) {
  365. if (context.has_alpha())
  366. unfilter_impl<true, 2>(*context.bitmap, y, dummy_scanline.data());
  367. else
  368. unfilter_impl<false, 2>(*context.bitmap, y, dummy_scanline.data());
  369. continue;
  370. }
  371. if (filter == 3) {
  372. if (context.has_alpha())
  373. unfilter_impl<true, 3>(*context.bitmap, y, dummy_scanline.data());
  374. else
  375. unfilter_impl<false, 3>(*context.bitmap, y, dummy_scanline.data());
  376. continue;
  377. }
  378. if (filter == 4) {
  379. if (context.has_alpha())
  380. unfilter_impl<true, 4>(*context.bitmap, y, dummy_scanline.data());
  381. else
  382. unfilter_impl<false, 4>(*context.bitmap, y, dummy_scanline.data());
  383. continue;
  384. }
  385. }
  386. }
  387. static bool decode_png_header(PNGLoadingContext& context)
  388. {
  389. if (context.state >= PNGLoadingContext::HeaderDecoded)
  390. return true;
  391. if (memcmp(context.data, png_header, sizeof(png_header)) != 0) {
  392. dbg() << "Invalid PNG header";
  393. context.state = PNGLoadingContext::State::Error;
  394. return false;
  395. }
  396. context.state = PNGLoadingContext::HeaderDecoded;
  397. return true;
  398. }
  399. static bool decode_png_size(PNGLoadingContext& context)
  400. {
  401. if (context.state >= PNGLoadingContext::SizeDecoded)
  402. return true;
  403. if (context.state < PNGLoadingContext::HeaderDecoded) {
  404. if (!decode_png_header(context))
  405. return false;
  406. }
  407. const u8* data_ptr = context.data + sizeof(png_header);
  408. size_t data_remaining = context.data_size - sizeof(png_header);
  409. Streamer streamer(data_ptr, data_remaining);
  410. while (!streamer.at_end()) {
  411. if (!process_chunk(streamer, context, true)) {
  412. context.state = PNGLoadingContext::State::Error;
  413. return false;
  414. }
  415. if (context.width && context.height) {
  416. context.state = PNGLoadingContext::State::SizeDecoded;
  417. return true;
  418. }
  419. }
  420. return false;
  421. }
  422. static bool decode_png_chunks(PNGLoadingContext& context)
  423. {
  424. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  425. return true;
  426. if (context.state < PNGLoadingContext::HeaderDecoded) {
  427. if (!decode_png_header(context))
  428. return false;
  429. }
  430. const u8* data_ptr = context.data + sizeof(png_header);
  431. int data_remaining = context.data_size - sizeof(png_header);
  432. context.compressed_data.ensure_capacity(context.data_size);
  433. Streamer streamer(data_ptr, data_remaining);
  434. while (!streamer.at_end()) {
  435. if (!process_chunk(streamer, context, false)) {
  436. context.state = PNGLoadingContext::State::Error;
  437. return false;
  438. }
  439. }
  440. context.state = PNGLoadingContext::State::ChunksDecoded;
  441. return true;
  442. }
  443. static bool decode_png_bitmap(PNGLoadingContext& context)
  444. {
  445. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  446. if (!decode_png_chunks(context))
  447. return false;
  448. }
  449. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  450. return true;
  451. unsigned long srclen = context.compressed_data.size() - 6;
  452. unsigned long destlen = context.decompression_buffer_size;
  453. int ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen);
  454. if (ret < 0) {
  455. context.state = PNGLoadingContext::State::Error;
  456. return false;
  457. }
  458. context.compressed_data.clear();
  459. context.scanlines.ensure_capacity(context.height);
  460. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  461. for (int y = 0; y < context.height; ++y) {
  462. u8 filter;
  463. if (!streamer.read(filter)) {
  464. context.state = PNGLoadingContext::State::Error;
  465. return false;
  466. }
  467. context.scanlines.append({ filter });
  468. auto& scanline_buffer = context.scanlines.last().data;
  469. if (!streamer.wrap_bytes(scanline_buffer, context.width * context.bytes_per_pixel)) {
  470. context.state = PNGLoadingContext::State::Error;
  471. return false;
  472. }
  473. }
  474. context.bitmap = GraphicsBitmap::create_purgeable(context.has_alpha() ? GraphicsBitmap::Format::RGBA32 : GraphicsBitmap::Format::RGB32, { context.width, context.height });
  475. unfilter(context);
  476. munmap(context.decompression_buffer, context.decompression_buffer_size);
  477. context.decompression_buffer = nullptr;
  478. context.decompression_buffer_size = 0;
  479. context.state = PNGLoadingContext::State::BitmapDecoded;
  480. return true;
  481. }
  482. static RefPtr<GraphicsBitmap> load_png_impl(const u8* data, int data_size)
  483. {
  484. PNGLoadingContext context;
  485. context.data = data;
  486. context.data_size = data_size;
  487. if (!decode_png_chunks(context))
  488. return nullptr;
  489. if (!decode_png_bitmap(context))
  490. return nullptr;
  491. return context.bitmap;
  492. }
  493. static bool process_IHDR(const ByteBuffer& data, PNGLoadingContext& context, bool decode_size_only = false)
  494. {
  495. if (data.size() < (int)sizeof(PNG_IHDR))
  496. return false;
  497. auto& ihdr = *(const PNG_IHDR*)data.data();
  498. context.width = ihdr.width;
  499. context.height = ihdr.height;
  500. context.bit_depth = ihdr.bit_depth;
  501. context.color_type = ihdr.color_type;
  502. context.compression_method = ihdr.compression_method;
  503. context.filter_method = ihdr.filter_method;
  504. context.interlace_method = ihdr.interlace_method;
  505. #ifdef PNG_DEBUG
  506. printf("PNG: %dx%d (%d bpp)\n", context.width, context.height, context.bit_depth);
  507. printf(" Color type: %d\n", context.color_type);
  508. printf("Compress Method: %d\n", context.compression_method);
  509. printf(" Filter Method: %d\n", context.filter_method);
  510. printf(" Interlace type: %d\n", context.interlace_method);
  511. #endif
  512. // FIXME: Implement Adam7 deinterlacing
  513. if (context.interlace_method != 0) {
  514. dbgprintf("PNGLoader::process_IHDR: Interlaced PNGs not currently supported.\n");
  515. return false;
  516. }
  517. switch (context.color_type) {
  518. case 0: // Each pixel is a grayscale sample.
  519. case 4: // Each pixel is a grayscale sample, followed by an alpha sample.
  520. // FIXME: Implement grayscale PNG support.
  521. dbgprintf("PNGLoader::process_IHDR: Unsupported grayscale format.\n");
  522. return false;
  523. case 2:
  524. context.bytes_per_pixel = 3 * (ihdr.bit_depth / 8);
  525. break;
  526. case 3: // Each pixel is a palette index; a PLTE chunk must appear.
  527. // FIXME: Implement support for 1/2/4 bit palette based images.
  528. if (ihdr.bit_depth != 8) {
  529. dbgprintf("PNGLoader::process_IHDR: Unsupported index-based format (%d bpp).\n", context.bit_depth);
  530. return false;
  531. }
  532. context.bytes_per_pixel = 1;
  533. break;
  534. case 6:
  535. context.bytes_per_pixel = 4 * (ihdr.bit_depth / 8);
  536. break;
  537. default:
  538. ASSERT_NOT_REACHED();
  539. }
  540. if (!decode_size_only) {
  541. context.decompression_buffer_size = (context.width * context.height * context.bytes_per_pixel + context.height);
  542. context.decompression_buffer = (u8*)mmap_with_name(nullptr, context.decompression_buffer_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0, "PNG decompression buffer");
  543. }
  544. return true;
  545. }
  546. static bool process_IDAT(const ByteBuffer& data, PNGLoadingContext& context)
  547. {
  548. context.compressed_data.append(data.data(), data.size());
  549. return true;
  550. }
  551. static bool process_PLTE(const ByteBuffer& data, PNGLoadingContext& context)
  552. {
  553. context.palette_data.append((const PaletteEntry*)data.data(), data.size() / 3);
  554. return true;
  555. }
  556. static bool process_tRNS(const ByteBuffer& data, PNGLoadingContext& context)
  557. {
  558. switch (context.color_type) {
  559. case 3:
  560. context.palette_transparency_data.append(data.data(), data.size());
  561. break;
  562. }
  563. return true;
  564. }
  565. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context, bool decode_size_only)
  566. {
  567. u32 chunk_size;
  568. if (!streamer.read(chunk_size)) {
  569. printf("Bail at chunk_size\n");
  570. return false;
  571. }
  572. u8 chunk_type[5];
  573. chunk_type[4] = '\0';
  574. if (!streamer.read_bytes(chunk_type, 4)) {
  575. printf("Bail at chunk_type\n");
  576. return false;
  577. }
  578. ByteBuffer chunk_data;
  579. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  580. printf("Bail at chunk_data\n");
  581. return false;
  582. }
  583. u32 chunk_crc;
  584. if (!streamer.read(chunk_crc)) {
  585. printf("Bail at chunk_crc\n");
  586. return false;
  587. }
  588. #ifdef PNG_DEBUG
  589. printf("Chunk type: '%s', size: %u, crc: %x\n", chunk_type, chunk_size, chunk_crc);
  590. #endif
  591. if (!strcmp((const char*)chunk_type, "IHDR"))
  592. return process_IHDR(chunk_data, context, decode_size_only);
  593. if (!strcmp((const char*)chunk_type, "IDAT"))
  594. return process_IDAT(chunk_data, context);
  595. if (!strcmp((const char*)chunk_type, "PLTE"))
  596. return process_PLTE(chunk_data, context);
  597. if (!strcmp((const char*)chunk_type, "tRNS"))
  598. return process_tRNS(chunk_data, context);
  599. return true;
  600. }
  601. PNGImageDecoderPlugin::PNGImageDecoderPlugin(const u8* data, size_t size)
  602. {
  603. m_context = make<PNGLoadingContext>();
  604. m_context->data = data;
  605. m_context->data_size = size;
  606. }
  607. PNGImageDecoderPlugin::~PNGImageDecoderPlugin()
  608. {
  609. }
  610. Size PNGImageDecoderPlugin::size()
  611. {
  612. if (m_context->state == PNGLoadingContext::State::Error)
  613. return {};
  614. if (m_context->state < PNGLoadingContext::State::SizeDecoded) {
  615. bool success = decode_png_size(*m_context);
  616. if (!success)
  617. return {};
  618. }
  619. return { m_context->width, m_context->height };
  620. }
  621. RefPtr<GraphicsBitmap> PNGImageDecoderPlugin::bitmap()
  622. {
  623. if (m_context->state == PNGLoadingContext::State::Error)
  624. return nullptr;
  625. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  626. // NOTE: This forces the chunk decoding to happen.
  627. bool success = decode_png_bitmap(*m_context);
  628. if (!success)
  629. return nullptr;
  630. }
  631. ASSERT(m_context->bitmap);
  632. return m_context->bitmap;
  633. }
  634. void PNGImageDecoderPlugin::set_volatile()
  635. {
  636. if (m_context->bitmap)
  637. m_context->bitmap->set_volatile();
  638. }
  639. bool PNGImageDecoderPlugin::set_nonvolatile()
  640. {
  641. if (!m_context->bitmap)
  642. return false;
  643. return m_context->bitmap->set_nonvolatile();
  644. }