PNGLoader.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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/LexicalPath.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. template<typename T>
  64. struct [[gnu::packed]] Tuple
  65. {
  66. T gray;
  67. T a;
  68. };
  69. template<typename T>
  70. struct [[gnu::packed]] Triplet
  71. {
  72. T r;
  73. T g;
  74. T b;
  75. };
  76. template<typename T>
  77. struct [[gnu::packed]] Quad
  78. {
  79. T r;
  80. T g;
  81. T b;
  82. T a;
  83. };
  84. struct PNGLoadingContext {
  85. enum State {
  86. NotDecoded = 0,
  87. Error,
  88. HeaderDecoded,
  89. SizeDecoded,
  90. ChunksDecoded,
  91. BitmapDecoded,
  92. };
  93. State state { State::NotDecoded };
  94. const u8* data { nullptr };
  95. size_t data_size { 0 };
  96. int width { -1 };
  97. int height { -1 };
  98. u8 bit_depth { 0 };
  99. u8 color_type { 0 };
  100. u8 compression_method { 0 };
  101. u8 filter_method { 0 };
  102. u8 interlace_method { 0 };
  103. u8 channels { 0 };
  104. bool has_seen_zlib_header { false };
  105. bool has_alpha() const { return color_type & 4 || palette_transparency_data.size() > 0; }
  106. Vector<Scanline> scanlines;
  107. RefPtr<Gfx::Bitmap> bitmap;
  108. u8* decompression_buffer { nullptr };
  109. int decompression_buffer_size { 0 };
  110. Vector<u8> compressed_data;
  111. Vector<PaletteEntry> palette_data;
  112. Vector<u8> palette_transparency_data;
  113. };
  114. class Streamer {
  115. public:
  116. Streamer(const u8* data, int size)
  117. : m_data_ptr(data)
  118. , m_size_remaining(size)
  119. {
  120. }
  121. template<typename T>
  122. bool read(T& value)
  123. {
  124. if (m_size_remaining < (int)sizeof(T))
  125. return false;
  126. value = *((const NetworkOrdered<T>*)m_data_ptr);
  127. m_data_ptr += sizeof(T);
  128. m_size_remaining -= sizeof(T);
  129. return true;
  130. }
  131. bool read_bytes(u8* buffer, int count)
  132. {
  133. if (m_size_remaining < count)
  134. return false;
  135. memcpy(buffer, m_data_ptr, count);
  136. m_data_ptr += count;
  137. m_size_remaining -= count;
  138. return true;
  139. }
  140. bool wrap_bytes(ByteBuffer& buffer, int count)
  141. {
  142. if (m_size_remaining < count)
  143. return false;
  144. buffer = ByteBuffer::wrap(m_data_ptr, count);
  145. m_data_ptr += count;
  146. m_size_remaining -= count;
  147. return true;
  148. }
  149. bool at_end() const { return !m_size_remaining; }
  150. private:
  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(), LexicalPath::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. ALWAYS_INLINE static 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. ALWAYS_INLINE static 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. NEVER_INLINE FLATTEN static void unfilter(PNGLoadingContext& context)
  278. {
  279. // First unpack the scanlines to RGBA:
  280. switch (context.color_type) {
  281. case 0:
  282. if (context.bit_depth == 8) {
  283. for (int y = 0; y < context.height; ++y) {
  284. auto* gray_values = (u8*)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 = gray_values[i];
  288. pixel.g = gray_values[i];
  289. pixel.b = gray_values[i];
  290. pixel.a = 0xff;
  291. }
  292. }
  293. } else if (context.bit_depth == 16) {
  294. for (int y = 0; y < context.height; ++y) {
  295. auto* gray_values = (u16*)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 = gray_values[i] & 0xFF;
  299. pixel.g = gray_values[i] & 0xFF;
  300. pixel.b = gray_values[i] & 0xFF;
  301. pixel.a = 0xff;
  302. }
  303. }
  304. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  305. auto pixels_per_byte = 8 / context.bit_depth;
  306. auto mask = (1 << context.bit_depth) - 1;
  307. for (int y = 0; y < context.height; ++y) {
  308. auto* gray_values = (u8*)context.scanlines[y].data.data();
  309. for (int i = 0; i < context.width; ++i) {
  310. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (i % pixels_per_byte));
  311. auto value = (gray_values[i / pixels_per_byte] >> bit_offset) & mask;
  312. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  313. pixel.r = value * (0xff / pow(context.bit_depth, 2));
  314. pixel.g = value * (0xff / pow(context.bit_depth, 2));
  315. pixel.b = value * (0xff / pow(context.bit_depth, 2));
  316. pixel.a = 0xff;
  317. }
  318. }
  319. } else {
  320. ASSERT_NOT_REACHED();
  321. }
  322. break;
  323. case 4:
  324. if (context.bit_depth == 8) {
  325. for (int y = 0; y < context.height; ++y) {
  326. auto* tuples = (Tuple<u8>*)context.scanlines[y].data.data();
  327. for (int i = 0; i < context.width; ++i) {
  328. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  329. pixel.r = tuples[i].gray;
  330. pixel.g = tuples[i].gray;
  331. pixel.b = tuples[i].gray;
  332. pixel.a = tuples[i].a;
  333. }
  334. }
  335. } else if (context.bit_depth == 16) {
  336. for (int y = 0; y < context.height; ++y) {
  337. auto* tuples = (Tuple<u16>*)context.scanlines[y].data.data();
  338. for (int i = 0; i < context.width; ++i) {
  339. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  340. pixel.r = tuples[i].gray & 0xFF;
  341. pixel.g = tuples[i].gray & 0xFF;
  342. pixel.b = tuples[i].gray & 0xFF;
  343. pixel.a = tuples[i].a & 0xFF;
  344. }
  345. }
  346. } else {
  347. ASSERT_NOT_REACHED();
  348. }
  349. break;
  350. case 2:
  351. if (context.bit_depth == 8) {
  352. for (int y = 0; y < context.height; ++y) {
  353. auto* triplets = (Triplet<u8>*)context.scanlines[y].data.data();
  354. for (int i = 0; i < context.width; ++i) {
  355. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  356. pixel.r = triplets[i].r;
  357. pixel.g = triplets[i].g;
  358. pixel.b = triplets[i].b;
  359. pixel.a = 0xff;
  360. }
  361. }
  362. } else if (context.bit_depth == 16) {
  363. for (int y = 0; y < context.height; ++y) {
  364. auto* triplets = (Triplet<u16>*)context.scanlines[y].data.data();
  365. for (int i = 0; i < context.width; ++i) {
  366. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  367. pixel.r = triplets[i].r & 0xFF;
  368. pixel.g = triplets[i].g & 0xFF;
  369. pixel.b = triplets[i].b & 0xFF;
  370. pixel.a = 0xff;
  371. }
  372. }
  373. } else {
  374. ASSERT_NOT_REACHED();
  375. }
  376. break;
  377. case 6:
  378. if (context.bit_depth == 8) {
  379. for (int y = 0; y < context.height; ++y) {
  380. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  381. }
  382. } else if (context.bit_depth == 16) {
  383. for (int y = 0; y < context.height; ++y) {
  384. auto* triplets = (Quad<u16>*)context.scanlines[y].data.data();
  385. for (int i = 0; i < context.width; ++i) {
  386. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  387. pixel.r = triplets[i].r & 0xFF;
  388. pixel.g = triplets[i].g & 0xFF;
  389. pixel.b = triplets[i].b & 0xFF;
  390. pixel.a = triplets[i].a & 0xFF;
  391. }
  392. }
  393. } else {
  394. ASSERT_NOT_REACHED();
  395. }
  396. break;
  397. case 3:
  398. if (context.bit_depth == 8) {
  399. for (int y = 0; y < context.height; ++y) {
  400. auto* palette_index = (u8*)context.scanlines[y].data.data();
  401. for (int i = 0; i < context.width; ++i) {
  402. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  403. auto& color = context.palette_data.at((int)palette_index[i]);
  404. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u
  405. ? context.palette_transparency_data.data()[palette_index[i]]
  406. : 0xff;
  407. pixel.r = color.r;
  408. pixel.g = color.g;
  409. pixel.b = color.b;
  410. pixel.a = transparency;
  411. }
  412. }
  413. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  414. auto pixels_per_byte = 8 / context.bit_depth;
  415. auto mask = (1 << context.bit_depth) - 1;
  416. for (int y = 0; y < context.height; ++y) {
  417. auto* palette_indexes = (u8*)context.scanlines[y].data.data();
  418. for (int i = 0; i < context.width; ++i) {
  419. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (i % pixels_per_byte));
  420. auto palette_index = (palette_indexes[i / pixels_per_byte] >> bit_offset) & mask;
  421. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  422. auto& color = context.palette_data.at(palette_index);
  423. auto transparency = context.palette_transparency_data.size() >= palette_index + 1u
  424. ? context.palette_transparency_data.data()[palette_index]
  425. : 0xff;
  426. pixel.r = color.r;
  427. pixel.g = color.g;
  428. pixel.b = color.b;
  429. pixel.a = transparency;
  430. }
  431. }
  432. } else {
  433. ASSERT_NOT_REACHED();
  434. }
  435. break;
  436. default:
  437. ASSERT_NOT_REACHED();
  438. break;
  439. }
  440. auto dummy_scanline = ByteBuffer::create_zeroed(context.width * sizeof(RGBA32));
  441. for (int y = 0; y < context.height; ++y) {
  442. auto filter = context.scanlines[y].filter;
  443. if (filter == 0) {
  444. if (context.has_alpha())
  445. unfilter_impl<true, 0>(*context.bitmap, y, dummy_scanline.data());
  446. else
  447. unfilter_impl<false, 0>(*context.bitmap, y, dummy_scanline.data());
  448. continue;
  449. }
  450. if (filter == 1) {
  451. if (context.has_alpha())
  452. unfilter_impl<true, 1>(*context.bitmap, y, dummy_scanline.data());
  453. else
  454. unfilter_impl<false, 1>(*context.bitmap, y, dummy_scanline.data());
  455. continue;
  456. }
  457. if (filter == 2) {
  458. if (context.has_alpha())
  459. unfilter_impl<true, 2>(*context.bitmap, y, dummy_scanline.data());
  460. else
  461. unfilter_impl<false, 2>(*context.bitmap, y, dummy_scanline.data());
  462. continue;
  463. }
  464. if (filter == 3) {
  465. if (context.has_alpha())
  466. unfilter_impl<true, 3>(*context.bitmap, y, dummy_scanline.data());
  467. else
  468. unfilter_impl<false, 3>(*context.bitmap, y, dummy_scanline.data());
  469. continue;
  470. }
  471. if (filter == 4) {
  472. if (context.has_alpha())
  473. unfilter_impl<true, 4>(*context.bitmap, y, dummy_scanline.data());
  474. else
  475. unfilter_impl<false, 4>(*context.bitmap, y, dummy_scanline.data());
  476. continue;
  477. }
  478. }
  479. }
  480. static bool decode_png_header(PNGLoadingContext& context)
  481. {
  482. if (context.state >= PNGLoadingContext::HeaderDecoded)
  483. return true;
  484. if (!context.data || context.data_size < sizeof(png_header)) {
  485. dbg() << "Missing PNG header";
  486. context.state = PNGLoadingContext::State::Error;
  487. return false;
  488. }
  489. if (memcmp(context.data, png_header, sizeof(png_header)) != 0) {
  490. dbg() << "Invalid PNG header";
  491. context.state = PNGLoadingContext::State::Error;
  492. return false;
  493. }
  494. context.state = PNGLoadingContext::HeaderDecoded;
  495. return true;
  496. }
  497. static bool decode_png_size(PNGLoadingContext& context)
  498. {
  499. if (context.state >= PNGLoadingContext::SizeDecoded)
  500. return true;
  501. if (context.state < PNGLoadingContext::HeaderDecoded) {
  502. if (!decode_png_header(context))
  503. return false;
  504. }
  505. const u8* data_ptr = context.data + sizeof(png_header);
  506. size_t data_remaining = context.data_size - sizeof(png_header);
  507. Streamer streamer(data_ptr, data_remaining);
  508. while (!streamer.at_end()) {
  509. if (!process_chunk(streamer, context, true)) {
  510. context.state = PNGLoadingContext::State::Error;
  511. return false;
  512. }
  513. if (context.width && context.height) {
  514. context.state = PNGLoadingContext::State::SizeDecoded;
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. static bool decode_png_chunks(PNGLoadingContext& context)
  521. {
  522. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  523. return true;
  524. if (context.state < PNGLoadingContext::HeaderDecoded) {
  525. if (!decode_png_header(context))
  526. return false;
  527. }
  528. const u8* data_ptr = context.data + sizeof(png_header);
  529. int data_remaining = context.data_size - sizeof(png_header);
  530. context.compressed_data.ensure_capacity(context.data_size);
  531. Streamer streamer(data_ptr, data_remaining);
  532. while (!streamer.at_end()) {
  533. if (!process_chunk(streamer, context, false)) {
  534. context.state = PNGLoadingContext::State::Error;
  535. return false;
  536. }
  537. }
  538. context.state = PNGLoadingContext::State::ChunksDecoded;
  539. return true;
  540. }
  541. static bool decode_png_bitmap(PNGLoadingContext& context)
  542. {
  543. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  544. if (!decode_png_chunks(context))
  545. return false;
  546. }
  547. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  548. return true;
  549. unsigned long srclen = context.compressed_data.size() - 6;
  550. unsigned long destlen = context.decompression_buffer_size;
  551. int ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen);
  552. if (ret < 0) {
  553. context.state = PNGLoadingContext::State::Error;
  554. return false;
  555. }
  556. context.compressed_data.clear();
  557. context.scanlines.ensure_capacity(context.height);
  558. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  559. for (int y = 0; y < context.height; ++y) {
  560. u8 filter;
  561. if (!streamer.read(filter)) {
  562. context.state = PNGLoadingContext::State::Error;
  563. return false;
  564. }
  565. context.scanlines.append({ filter });
  566. auto& scanline_buffer = context.scanlines.last().data;
  567. auto row_size = ((context.width * context.channels * context.bit_depth) + 7) / 8;
  568. if (!streamer.wrap_bytes(scanline_buffer, row_size)) {
  569. context.state = PNGLoadingContext::State::Error;
  570. return false;
  571. }
  572. }
  573. context.bitmap = Bitmap::create_purgeable(context.has_alpha() ? BitmapFormat::RGBA32 : BitmapFormat::RGB32, { context.width, context.height });
  574. unfilter(context);
  575. munmap(context.decompression_buffer, context.decompression_buffer_size);
  576. context.decompression_buffer = nullptr;
  577. context.decompression_buffer_size = 0;
  578. context.state = PNGLoadingContext::State::BitmapDecoded;
  579. return true;
  580. }
  581. static RefPtr<Gfx::Bitmap> load_png_impl(const u8* data, int data_size)
  582. {
  583. PNGLoadingContext context;
  584. context.data = data;
  585. context.data_size = data_size;
  586. if (!decode_png_chunks(context))
  587. return nullptr;
  588. if (!decode_png_bitmap(context))
  589. return nullptr;
  590. return context.bitmap;
  591. }
  592. static bool process_IHDR(const ByteBuffer& data, PNGLoadingContext& context, bool decode_size_only = false)
  593. {
  594. if (data.size() < (int)sizeof(PNG_IHDR))
  595. return false;
  596. auto& ihdr = *(const PNG_IHDR*)data.data();
  597. context.width = ihdr.width;
  598. context.height = ihdr.height;
  599. context.bit_depth = ihdr.bit_depth;
  600. context.color_type = ihdr.color_type;
  601. context.compression_method = ihdr.compression_method;
  602. context.filter_method = ihdr.filter_method;
  603. context.interlace_method = ihdr.interlace_method;
  604. #ifdef PNG_DEBUG
  605. printf("PNG: %dx%d (%d bpp)\n", context.width, context.height, context.bit_depth);
  606. printf(" Color type: %d\n", context.color_type);
  607. printf("Compress Method: %d\n", context.compression_method);
  608. printf(" Filter Method: %d\n", context.filter_method);
  609. printf(" Interlace type: %d\n", context.interlace_method);
  610. #endif
  611. // FIXME: Implement Adam7 deinterlacing
  612. if (context.interlace_method != 0) {
  613. dbgprintf("PNGLoader::process_IHDR: Interlaced PNGs not currently supported.\n");
  614. return false;
  615. }
  616. switch (context.color_type) {
  617. case 0: // Each pixel is a grayscale sample.
  618. context.channels = 1;
  619. break;
  620. case 4: // Each pixel is a grayscale sample, followed by an alpha sample.
  621. context.channels = 2;
  622. break;
  623. case 2: // Each pixel is an RGB sample
  624. context.channels = 3;
  625. break;
  626. case 3: // Each pixel is a palette index; a PLTE chunk must appear.
  627. context.channels = 1;
  628. break;
  629. case 6: // Each pixel is an RGB sample, followed by an alpha sample.
  630. context.channels = 4;
  631. break;
  632. default:
  633. ASSERT_NOT_REACHED();
  634. }
  635. if (!decode_size_only) {
  636. // Calculate number of bytes per row (+1 for filter)
  637. auto row_size = ((context.width * context.channels * context.bit_depth) + 7) / 8 + 1;
  638. context.decompression_buffer_size = row_size * context.height;
  639. 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");
  640. }
  641. return true;
  642. }
  643. static bool process_IDAT(const ByteBuffer& data, PNGLoadingContext& context)
  644. {
  645. context.compressed_data.append(data.data(), data.size());
  646. return true;
  647. }
  648. static bool process_PLTE(const ByteBuffer& data, PNGLoadingContext& context)
  649. {
  650. context.palette_data.append((const PaletteEntry*)data.data(), data.size() / 3);
  651. return true;
  652. }
  653. static bool process_tRNS(const ByteBuffer& data, PNGLoadingContext& context)
  654. {
  655. switch (context.color_type) {
  656. case 3:
  657. context.palette_transparency_data.append(data.data(), data.size());
  658. break;
  659. }
  660. return true;
  661. }
  662. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context, bool decode_size_only)
  663. {
  664. u32 chunk_size;
  665. if (!streamer.read(chunk_size)) {
  666. printf("Bail at chunk_size\n");
  667. return false;
  668. }
  669. u8 chunk_type[5];
  670. chunk_type[4] = '\0';
  671. if (!streamer.read_bytes(chunk_type, 4)) {
  672. printf("Bail at chunk_type\n");
  673. return false;
  674. }
  675. ByteBuffer chunk_data;
  676. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  677. printf("Bail at chunk_data\n");
  678. return false;
  679. }
  680. u32 chunk_crc;
  681. if (!streamer.read(chunk_crc)) {
  682. printf("Bail at chunk_crc\n");
  683. return false;
  684. }
  685. #ifdef PNG_DEBUG
  686. printf("Chunk type: '%s', size: %u, crc: %x\n", chunk_type, chunk_size, chunk_crc);
  687. #endif
  688. if (!strcmp((const char*)chunk_type, "IHDR"))
  689. return process_IHDR(chunk_data, context, decode_size_only);
  690. if (!strcmp((const char*)chunk_type, "IDAT"))
  691. return process_IDAT(chunk_data, context);
  692. if (!strcmp((const char*)chunk_type, "PLTE"))
  693. return process_PLTE(chunk_data, context);
  694. if (!strcmp((const char*)chunk_type, "tRNS"))
  695. return process_tRNS(chunk_data, context);
  696. return true;
  697. }
  698. PNGImageDecoderPlugin::PNGImageDecoderPlugin(const u8* data, size_t size)
  699. {
  700. m_context = make<PNGLoadingContext>();
  701. m_context->data = data;
  702. m_context->data_size = size;
  703. }
  704. PNGImageDecoderPlugin::~PNGImageDecoderPlugin()
  705. {
  706. }
  707. Size PNGImageDecoderPlugin::size()
  708. {
  709. if (m_context->state == PNGLoadingContext::State::Error)
  710. return {};
  711. if (m_context->state < PNGLoadingContext::State::SizeDecoded) {
  712. bool success = decode_png_size(*m_context);
  713. if (!success)
  714. return {};
  715. }
  716. return { m_context->width, m_context->height };
  717. }
  718. RefPtr<Gfx::Bitmap> PNGImageDecoderPlugin::bitmap()
  719. {
  720. if (m_context->state == PNGLoadingContext::State::Error)
  721. return nullptr;
  722. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  723. // NOTE: This forces the chunk decoding to happen.
  724. bool success = decode_png_bitmap(*m_context);
  725. if (!success)
  726. return nullptr;
  727. }
  728. ASSERT(m_context->bitmap);
  729. return m_context->bitmap;
  730. }
  731. void PNGImageDecoderPlugin::set_volatile()
  732. {
  733. if (m_context->bitmap)
  734. m_context->bitmap->set_volatile();
  735. }
  736. bool PNGImageDecoderPlugin::set_nonvolatile()
  737. {
  738. if (!m_context->bitmap)
  739. return false;
  740. return m_context->bitmap->set_nonvolatile();
  741. }
  742. bool PNGImageDecoderPlugin::sniff()
  743. {
  744. return decode_png_header(*m_context);
  745. }
  746. bool PNGImageDecoderPlugin::is_animated()
  747. {
  748. return false;
  749. }
  750. size_t PNGImageDecoderPlugin::loop_count()
  751. {
  752. return 0;
  753. }
  754. size_t PNGImageDecoderPlugin::frame_count()
  755. {
  756. return 1;
  757. }
  758. ImageFrameDescriptor PNGImageDecoderPlugin::frame(size_t i)
  759. {
  760. if (i > 0) {
  761. return { bitmap(), 0 };
  762. }
  763. return {};
  764. }
  765. }