PNGLoader.cpp 22 KB

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