PNGLoader.cpp 27 KB

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