PNGLoader.cpp 27 KB

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