PNGLoader.cpp 22 KB

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