PNGLoader.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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. enum PngInterlaceMethod {
  86. Null = 0,
  87. Adam7 = 1
  88. };
  89. struct PNGLoadingContext {
  90. enum State {
  91. NotDecoded = 0,
  92. Error,
  93. HeaderDecoded,
  94. SizeDecoded,
  95. ChunksDecoded,
  96. BitmapDecoded,
  97. };
  98. State state { State::NotDecoded };
  99. const u8* data { nullptr };
  100. size_t data_size { 0 };
  101. int width { -1 };
  102. int height { -1 };
  103. u8 bit_depth { 0 };
  104. u8 color_type { 0 };
  105. u8 compression_method { 0 };
  106. u8 filter_method { 0 };
  107. u8 interlace_method { 0 };
  108. u8 channels { 0 };
  109. bool has_seen_zlib_header { false };
  110. bool has_alpha() const { return color_type & 4 || palette_transparency_data.size() > 0; }
  111. Vector<Scanline> scanlines;
  112. RefPtr<Gfx::Bitmap> bitmap;
  113. u8* decompression_buffer { nullptr };
  114. size_t decompression_buffer_size { 0 };
  115. Vector<u8> compressed_data;
  116. Vector<PaletteEntry> palette_data;
  117. Vector<u8> palette_transparency_data;
  118. };
  119. class Streamer {
  120. public:
  121. Streamer(const u8* data, size_t size)
  122. : m_data_ptr(data)
  123. , m_size_remaining(size)
  124. {
  125. }
  126. template<typename T>
  127. bool read(T& value)
  128. {
  129. if (m_size_remaining < sizeof(T))
  130. return false;
  131. value = *((const NetworkOrdered<T>*)m_data_ptr);
  132. m_data_ptr += sizeof(T);
  133. m_size_remaining -= sizeof(T);
  134. return true;
  135. }
  136. bool read_bytes(u8* buffer, size_t count)
  137. {
  138. if (m_size_remaining < count)
  139. return false;
  140. memcpy(buffer, m_data_ptr, count);
  141. m_data_ptr += count;
  142. m_size_remaining -= count;
  143. return true;
  144. }
  145. bool wrap_bytes(ByteBuffer& buffer, size_t count)
  146. {
  147. if (m_size_remaining < count)
  148. return false;
  149. buffer = ByteBuffer::wrap(m_data_ptr, count);
  150. m_data_ptr += count;
  151. m_size_remaining -= count;
  152. return true;
  153. }
  154. bool at_end() const { return !m_size_remaining; }
  155. private:
  156. const u8* m_data_ptr { nullptr };
  157. size_t m_size_remaining { 0 };
  158. };
  159. static RefPtr<Gfx::Bitmap> load_png_impl(const u8*, size_t);
  160. static bool process_chunk(Streamer&, PNGLoadingContext& context);
  161. RefPtr<Gfx::Bitmap> load_png(const StringView& path)
  162. {
  163. MappedFile mapped_file(path);
  164. if (!mapped_file.is_valid())
  165. return nullptr;
  166. auto bitmap = load_png_impl((const u8*)mapped_file.data(), mapped_file.size());
  167. if (bitmap)
  168. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded PNG: %s", bitmap->width(), bitmap->height(), LexicalPath::canonicalized_path(path).characters()));
  169. return bitmap;
  170. }
  171. RefPtr<Gfx::Bitmap> load_png_from_memory(const u8* data, size_t length)
  172. {
  173. auto bitmap = load_png_impl(data, length);
  174. if (bitmap)
  175. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded PNG: <memory>", bitmap->width(), bitmap->height()));
  176. return bitmap;
  177. }
  178. ALWAYS_INLINE static u8 paeth_predictor(int a, int b, int c)
  179. {
  180. int p = a + b - c;
  181. int pa = abs(p - a);
  182. int pb = abs(p - b);
  183. int pc = abs(p - c);
  184. if (pa <= pb && pa <= pc)
  185. return a;
  186. if (pb <= pc)
  187. return b;
  188. return c;
  189. }
  190. union [[gnu::packed]] Pixel
  191. {
  192. RGBA32 rgba { 0 };
  193. u8 v[4];
  194. struct {
  195. u8 r;
  196. u8 g;
  197. u8 b;
  198. u8 a;
  199. };
  200. };
  201. static_assert(sizeof(Pixel) == 4);
  202. template<bool has_alpha, u8 filter_type>
  203. ALWAYS_INLINE static void unfilter_impl(Gfx::Bitmap& bitmap, int y, const void* dummy_scanline_data)
  204. {
  205. auto* dummy_scanline = (const Pixel*)dummy_scanline_data;
  206. if constexpr (filter_type == 0) {
  207. auto* pixels = (Pixel*)bitmap.scanline(y);
  208. for (int i = 0; i < bitmap.width(); ++i) {
  209. auto& x = pixels[i];
  210. swap(x.r, x.b);
  211. }
  212. }
  213. if constexpr (filter_type == 1) {
  214. auto* pixels = (Pixel*)bitmap.scanline(y);
  215. swap(pixels[0].r, pixels[0].b);
  216. for (int i = 1; i < bitmap.width(); ++i) {
  217. auto& x = pixels[i];
  218. swap(x.r, x.b);
  219. auto& a = (const Pixel&)pixels[i - 1];
  220. x.v[0] += a.v[0];
  221. x.v[1] += a.v[1];
  222. x.v[2] += a.v[2];
  223. if constexpr (has_alpha)
  224. x.v[3] += a.v[3];
  225. }
  226. return;
  227. }
  228. if constexpr (filter_type == 2) {
  229. auto* pixels = (Pixel*)bitmap.scanline(y);
  230. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (const Pixel*)bitmap.scanline(y - 1);
  231. for (int i = 0; i < bitmap.width(); ++i) {
  232. auto& x = pixels[i];
  233. swap(x.r, x.b);
  234. const Pixel& b = pixels_y_minus_1[i];
  235. x.v[0] += b.v[0];
  236. x.v[1] += b.v[1];
  237. x.v[2] += b.v[2];
  238. if constexpr (has_alpha)
  239. x.v[3] += b.v[3];
  240. }
  241. return;
  242. }
  243. if constexpr (filter_type == 3) {
  244. auto* pixels = (Pixel*)bitmap.scanline(y);
  245. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (const Pixel*)bitmap.scanline(y - 1);
  246. for (int i = 0; i < bitmap.width(); ++i) {
  247. auto& x = pixels[i];
  248. swap(x.r, x.b);
  249. Pixel a;
  250. if (i != 0)
  251. a = pixels[i - 1];
  252. const Pixel& b = pixels_y_minus_1[i];
  253. x.v[0] = x.v[0] + ((a.v[0] + b.v[0]) / 2);
  254. x.v[1] = x.v[1] + ((a.v[1] + b.v[1]) / 2);
  255. x.v[2] = x.v[2] + ((a.v[2] + b.v[2]) / 2);
  256. if constexpr (has_alpha)
  257. x.v[3] = x.v[3] + ((a.v[3] + b.v[3]) / 2);
  258. }
  259. return;
  260. }
  261. if constexpr (filter_type == 4) {
  262. auto* pixels = (Pixel*)bitmap.scanline(y);
  263. auto* pixels_y_minus_1 = y == 0 ? dummy_scanline : (Pixel*)bitmap.scanline(y - 1);
  264. for (int i = 0; i < bitmap.width(); ++i) {
  265. auto& x = pixels[i];
  266. swap(x.r, x.b);
  267. Pixel a;
  268. const Pixel& b = pixels_y_minus_1[i];
  269. Pixel c;
  270. if (i != 0) {
  271. a = pixels[i - 1];
  272. c = pixels_y_minus_1[i - 1];
  273. }
  274. x.v[0] += paeth_predictor(a.v[0], b.v[0], c.v[0]);
  275. x.v[1] += paeth_predictor(a.v[1], b.v[1], c.v[1]);
  276. x.v[2] += paeth_predictor(a.v[2], b.v[2], c.v[2]);
  277. if constexpr (has_alpha)
  278. x.v[3] += paeth_predictor(a.v[3], b.v[3], c.v[3]);
  279. }
  280. }
  281. }
  282. template<typename T>
  283. ALWAYS_INLINE static void unpack_grayscale_without_alpha(PNGLoadingContext& context)
  284. {
  285. for (int y = 0; y < context.height; ++y) {
  286. auto* gray_values = reinterpret_cast<const T*>(context.scanlines[y].data.data());
  287. for (int i = 0; i < context.width; ++i) {
  288. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  289. pixel.r = gray_values[i];
  290. pixel.g = gray_values[i];
  291. pixel.b = gray_values[i];
  292. pixel.a = 0xff;
  293. }
  294. }
  295. }
  296. template<typename T>
  297. ALWAYS_INLINE static void unpack_grayscale_with_alpha(PNGLoadingContext& context)
  298. {
  299. for (int y = 0; y < context.height; ++y) {
  300. auto* tuples = reinterpret_cast<const Tuple<T>*>(context.scanlines[y].data.data());
  301. for (int i = 0; i < context.width; ++i) {
  302. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  303. pixel.r = tuples[i].gray;
  304. pixel.g = tuples[i].gray;
  305. pixel.b = tuples[i].gray;
  306. pixel.a = tuples[i].a;
  307. }
  308. }
  309. }
  310. template<typename T>
  311. ALWAYS_INLINE static void unpack_triplets_without_alpha(PNGLoadingContext& context)
  312. {
  313. for (int y = 0; y < context.height; ++y) {
  314. auto* triplets = reinterpret_cast<const Triplet<T>*>(context.scanlines[y].data.data());
  315. for (int i = 0; i < context.width; ++i) {
  316. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  317. pixel.r = triplets[i].r;
  318. pixel.g = triplets[i].g;
  319. pixel.b = triplets[i].b;
  320. pixel.a = 0xff;
  321. }
  322. }
  323. }
  324. NEVER_INLINE FLATTEN static void unfilter(PNGLoadingContext& context)
  325. {
  326. // First unpack the scanlines to RGBA:
  327. switch (context.color_type) {
  328. case 0:
  329. if (context.bit_depth == 8) {
  330. unpack_grayscale_without_alpha<u8>(context);
  331. } else if (context.bit_depth == 16) {
  332. unpack_grayscale_without_alpha<u16>(context);
  333. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  334. auto pixels_per_byte = 8 / context.bit_depth;
  335. auto mask = (1 << context.bit_depth) - 1;
  336. for (int y = 0; y < context.height; ++y) {
  337. auto* gray_values = (u8*)context.scanlines[y].data.data();
  338. for (int x = 0; x < context.width; ++x) {
  339. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (x % pixels_per_byte));
  340. auto value = (gray_values[x / pixels_per_byte] >> bit_offset) & mask;
  341. auto& pixel = (Pixel&)context.bitmap->scanline(y)[x];
  342. pixel.r = value * (0xff / pow(context.bit_depth, 2));
  343. pixel.g = value * (0xff / pow(context.bit_depth, 2));
  344. pixel.b = value * (0xff / pow(context.bit_depth, 2));
  345. pixel.a = 0xff;
  346. }
  347. }
  348. } else {
  349. ASSERT_NOT_REACHED();
  350. }
  351. break;
  352. case 4:
  353. if (context.bit_depth == 8) {
  354. unpack_grayscale_with_alpha<u8>(context);
  355. } else if (context.bit_depth == 16) {
  356. unpack_grayscale_with_alpha<u16>(context);
  357. } else {
  358. ASSERT_NOT_REACHED();
  359. }
  360. break;
  361. case 2:
  362. if (context.bit_depth == 8) {
  363. unpack_triplets_without_alpha<u8>(context);
  364. } else if (context.bit_depth == 16) {
  365. unpack_triplets_without_alpha<u16>(context);
  366. } else {
  367. ASSERT_NOT_REACHED();
  368. }
  369. break;
  370. case 6:
  371. if (context.bit_depth == 8) {
  372. for (int y = 0; y < context.height; ++y) {
  373. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  374. }
  375. } else if (context.bit_depth == 16) {
  376. for (int y = 0; y < context.height; ++y) {
  377. auto* triplets = reinterpret_cast<const Quad<u16>*>(context.scanlines[y].data.data());
  378. for (int i = 0; i < context.width; ++i) {
  379. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  380. pixel.r = triplets[i].r & 0xFF;
  381. pixel.g = triplets[i].g & 0xFF;
  382. pixel.b = triplets[i].b & 0xFF;
  383. pixel.a = triplets[i].a & 0xFF;
  384. }
  385. }
  386. } else {
  387. ASSERT_NOT_REACHED();
  388. }
  389. break;
  390. case 3:
  391. if (context.bit_depth == 8) {
  392. for (int y = 0; y < context.height; ++y) {
  393. auto* palette_index = (u8*)context.scanlines[y].data.data();
  394. for (int i = 0; i < context.width; ++i) {
  395. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  396. auto& color = context.palette_data.at((int)palette_index[i]);
  397. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u
  398. ? context.palette_transparency_data.data()[palette_index[i]]
  399. : 0xff;
  400. pixel.r = color.r;
  401. pixel.g = color.g;
  402. pixel.b = color.b;
  403. pixel.a = transparency;
  404. }
  405. }
  406. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  407. auto pixels_per_byte = 8 / context.bit_depth;
  408. auto mask = (1 << context.bit_depth) - 1;
  409. for (int y = 0; y < context.height; ++y) {
  410. auto* palette_indexes = (u8*)context.scanlines[y].data.data();
  411. for (int i = 0; i < context.width; ++i) {
  412. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (i % pixels_per_byte));
  413. auto palette_index = (palette_indexes[i / pixels_per_byte] >> bit_offset) & mask;
  414. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  415. auto& color = context.palette_data.at(palette_index);
  416. auto transparency = context.palette_transparency_data.size() >= palette_index + 1u
  417. ? context.palette_transparency_data.data()[palette_index]
  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 {
  426. ASSERT_NOT_REACHED();
  427. }
  428. break;
  429. default:
  430. ASSERT_NOT_REACHED();
  431. break;
  432. }
  433. auto dummy_scanline = ByteBuffer::create_zeroed(context.width * sizeof(RGBA32));
  434. for (int y = 0; y < context.height; ++y) {
  435. auto filter = context.scanlines[y].filter;
  436. if (filter == 0) {
  437. if (context.has_alpha())
  438. unfilter_impl<true, 0>(*context.bitmap, y, dummy_scanline.data());
  439. else
  440. unfilter_impl<false, 0>(*context.bitmap, y, dummy_scanline.data());
  441. continue;
  442. }
  443. if (filter == 1) {
  444. if (context.has_alpha())
  445. unfilter_impl<true, 1>(*context.bitmap, y, dummy_scanline.data());
  446. else
  447. unfilter_impl<false, 1>(*context.bitmap, y, dummy_scanline.data());
  448. continue;
  449. }
  450. if (filter == 2) {
  451. if (context.has_alpha())
  452. unfilter_impl<true, 2>(*context.bitmap, y, dummy_scanline.data());
  453. else
  454. unfilter_impl<false, 2>(*context.bitmap, y, dummy_scanline.data());
  455. continue;
  456. }
  457. if (filter == 3) {
  458. if (context.has_alpha())
  459. unfilter_impl<true, 3>(*context.bitmap, y, dummy_scanline.data());
  460. else
  461. unfilter_impl<false, 3>(*context.bitmap, y, dummy_scanline.data());
  462. continue;
  463. }
  464. if (filter == 4) {
  465. if (context.has_alpha())
  466. unfilter_impl<true, 4>(*context.bitmap, y, dummy_scanline.data());
  467. else
  468. unfilter_impl<false, 4>(*context.bitmap, y, dummy_scanline.data());
  469. continue;
  470. }
  471. }
  472. }
  473. static bool decode_png_header(PNGLoadingContext& context)
  474. {
  475. if (context.state >= PNGLoadingContext::HeaderDecoded)
  476. return true;
  477. if (!context.data || context.data_size < sizeof(png_header)) {
  478. #ifdef PNG_DEBUG
  479. dbg() << "Missing PNG header";
  480. #endif
  481. context.state = PNGLoadingContext::State::Error;
  482. return false;
  483. }
  484. if (memcmp(context.data, png_header, sizeof(png_header)) != 0) {
  485. #ifdef PNG_DEBUG
  486. dbg() << "Invalid PNG header";
  487. #endif
  488. context.state = PNGLoadingContext::State::Error;
  489. return false;
  490. }
  491. context.state = PNGLoadingContext::HeaderDecoded;
  492. return true;
  493. }
  494. static bool decode_png_size(PNGLoadingContext& context)
  495. {
  496. if (context.state >= PNGLoadingContext::SizeDecoded)
  497. return true;
  498. if (context.state < PNGLoadingContext::HeaderDecoded) {
  499. if (!decode_png_header(context))
  500. return false;
  501. }
  502. const u8* data_ptr = context.data + sizeof(png_header);
  503. size_t data_remaining = context.data_size - sizeof(png_header);
  504. Streamer streamer(data_ptr, data_remaining);
  505. while (!streamer.at_end()) {
  506. if (!process_chunk(streamer, context)) {
  507. context.state = PNGLoadingContext::State::Error;
  508. return false;
  509. }
  510. if (context.width && context.height) {
  511. context.state = PNGLoadingContext::State::SizeDecoded;
  512. return true;
  513. }
  514. }
  515. return false;
  516. }
  517. static bool decode_png_chunks(PNGLoadingContext& context)
  518. {
  519. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  520. return true;
  521. if (context.state < PNGLoadingContext::HeaderDecoded) {
  522. if (!decode_png_header(context))
  523. return false;
  524. }
  525. const u8* data_ptr = context.data + sizeof(png_header);
  526. int data_remaining = context.data_size - sizeof(png_header);
  527. context.compressed_data.ensure_capacity(context.data_size);
  528. Streamer streamer(data_ptr, data_remaining);
  529. while (!streamer.at_end()) {
  530. if (!process_chunk(streamer, context)) {
  531. context.state = PNGLoadingContext::State::Error;
  532. return false;
  533. }
  534. }
  535. context.state = PNGLoadingContext::State::ChunksDecoded;
  536. return true;
  537. }
  538. static bool decode_png_bitmap_simple(PNGLoadingContext& context)
  539. {
  540. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  541. for (int y = 0; y < context.height; ++y) {
  542. u8 filter;
  543. if (!streamer.read(filter)) {
  544. context.state = PNGLoadingContext::State::Error;
  545. return false;
  546. }
  547. if (filter > 4) {
  548. dbg() << "Invalid PNG filter: " << filter;
  549. context.state = PNGLoadingContext::State::Error;
  550. return false;
  551. }
  552. context.scanlines.append({ filter });
  553. auto& scanline_buffer = context.scanlines.last().data;
  554. auto row_size = ((context.width * context.channels * context.bit_depth) + 7) / 8;
  555. if (!streamer.wrap_bytes(scanline_buffer, row_size)) {
  556. context.state = PNGLoadingContext::State::Error;
  557. return false;
  558. }
  559. }
  560. context.bitmap = Bitmap::create_purgeable(context.has_alpha() ? BitmapFormat::RGBA32 : BitmapFormat::RGB32, { context.width, context.height });
  561. unfilter(context);
  562. return true;
  563. }
  564. static int adam7_height(PNGLoadingContext& context, int pass)
  565. {
  566. switch (pass) {
  567. case 1:
  568. return (context.height + 7) / 8;
  569. case 2:
  570. return (context.height + 7) / 8;
  571. case 3:
  572. return (context.height + 3) / 8;
  573. case 4:
  574. return (context.height + 3) / 4;
  575. case 5:
  576. return (context.height + 1) / 4;
  577. case 6:
  578. return (context.height + 1) / 2;
  579. case 7:
  580. return context.height / 2;
  581. default:
  582. ASSERT_NOT_REACHED();
  583. }
  584. }
  585. static int adam7_width(PNGLoadingContext& context, int pass)
  586. {
  587. switch (pass) {
  588. case 1:
  589. return (context.width + 7) / 8;
  590. case 2:
  591. return (context.width + 3) / 8;
  592. case 3:
  593. return (context.width + 3) / 4;
  594. case 4:
  595. return (context.width + 1) / 4;
  596. case 5:
  597. return (context.width + 1) / 2;
  598. case 6:
  599. return context.width / 2;
  600. case 7:
  601. return context.width;
  602. default:
  603. ASSERT_NOT_REACHED();
  604. }
  605. }
  606. // Index 0 unused (non-interlaced case)
  607. static int adam7_starty[8] = { 0, 0, 0, 4, 0, 2, 0, 1 };
  608. static int adam7_startx[8] = { 0, 0, 4, 0, 2, 0, 1, 0 };
  609. static int adam7_stepy[8] = { 1, 8, 8, 8, 4, 4, 2, 2 };
  610. static int adam7_stepx[8] = { 1, 8, 8, 4, 4, 2, 2, 1 };
  611. static bool decode_adam7_pass(PNGLoadingContext& context, Streamer& streamer, int pass)
  612. {
  613. PNGLoadingContext subimage_context;
  614. subimage_context.width = adam7_width(context, pass);
  615. subimage_context.height = adam7_height(context, pass);
  616. subimage_context.channels = context.channels;
  617. subimage_context.color_type = context.color_type;
  618. subimage_context.palette_data = context.palette_data;
  619. subimage_context.palette_transparency_data = context.palette_transparency_data;
  620. subimage_context.bit_depth = context.bit_depth;
  621. subimage_context.filter_method = context.filter_method;
  622. // For small images, some passes might be empty
  623. if (!subimage_context.width || !subimage_context.height)
  624. return true;
  625. subimage_context.scanlines.clear_with_capacity();
  626. for (int y = 0; y < subimage_context.height; ++y) {
  627. u8 filter;
  628. if (!streamer.read(filter)) {
  629. context.state = PNGLoadingContext::State::Error;
  630. return false;
  631. }
  632. if (filter > 4) {
  633. dbg() << "Invalid PNG filter: " << filter;
  634. context.state = PNGLoadingContext::State::Error;
  635. return false;
  636. }
  637. subimage_context.scanlines.append({ filter });
  638. auto& scanline_buffer = subimage_context.scanlines.last().data;
  639. auto row_size = ((subimage_context.width * context.channels * context.bit_depth) + 7) / 8;
  640. if (!streamer.wrap_bytes(scanline_buffer, row_size)) {
  641. context.state = PNGLoadingContext::State::Error;
  642. return false;
  643. }
  644. }
  645. subimage_context.bitmap = Bitmap::create(context.bitmap->format(), { subimage_context.width, subimage_context.height });
  646. unfilter(subimage_context);
  647. // Copy the subimage data into the main image according to the pass pattern
  648. for (int y = 0, dy = adam7_starty[pass]; y < subimage_context.height && dy < context.height; ++y, dy += adam7_stepy[pass]) {
  649. for (int x = 0, dx = adam7_startx[pass]; x < subimage_context.width && dy < context.width; ++x, dx += adam7_stepx[pass]) {
  650. context.bitmap->set_pixel(dx, dy, subimage_context.bitmap->get_pixel(x, y));
  651. }
  652. }
  653. return true;
  654. }
  655. static bool decode_png_adam7(PNGLoadingContext& context)
  656. {
  657. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  658. context.bitmap = Bitmap::create_purgeable(context.has_alpha() ? BitmapFormat::RGBA32 : BitmapFormat::RGB32, { context.width, context.height });
  659. for (int pass = 1; pass <= 7; ++pass) {
  660. if (!decode_adam7_pass(context, streamer, pass))
  661. return false;
  662. }
  663. return true;
  664. }
  665. static bool decode_png_bitmap(PNGLoadingContext& context)
  666. {
  667. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  668. if (!decode_png_chunks(context))
  669. return false;
  670. }
  671. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  672. return true;
  673. unsigned long srclen = context.compressed_data.size() - 6;
  674. unsigned long destlen = 0;
  675. int ret = puff(NULL, &destlen, context.compressed_data.data() + 2, &srclen);
  676. if (ret != 0) {
  677. context.state = PNGLoadingContext::State::Error;
  678. return false;
  679. }
  680. context.decompression_buffer_size = destlen;
  681. 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");
  682. ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen);
  683. if (ret != 0) {
  684. context.state = PNGLoadingContext::State::Error;
  685. return false;
  686. }
  687. context.compressed_data.clear();
  688. context.scanlines.ensure_capacity(context.height);
  689. switch (context.interlace_method) {
  690. case PngInterlaceMethod::Null:
  691. if (!decode_png_bitmap_simple(context))
  692. return false;
  693. break;
  694. case PngInterlaceMethod::Adam7:
  695. if (!decode_png_adam7(context))
  696. return false;
  697. break;
  698. default:
  699. ASSERT_NOT_REACHED();
  700. }
  701. munmap(context.decompression_buffer, context.decompression_buffer_size);
  702. context.decompression_buffer = nullptr;
  703. context.decompression_buffer_size = 0;
  704. context.state = PNGLoadingContext::State::BitmapDecoded;
  705. return true;
  706. }
  707. static RefPtr<Gfx::Bitmap> load_png_impl(const u8* data, size_t data_size)
  708. {
  709. PNGLoadingContext context;
  710. context.data = data;
  711. context.data_size = data_size;
  712. if (!decode_png_chunks(context))
  713. return nullptr;
  714. if (!decode_png_bitmap(context))
  715. return nullptr;
  716. return context.bitmap;
  717. }
  718. static bool process_IHDR(const ByteBuffer& data, PNGLoadingContext& context)
  719. {
  720. if (data.size() < (int)sizeof(PNG_IHDR))
  721. return false;
  722. auto& ihdr = *(const PNG_IHDR*)data.data();
  723. context.width = ihdr.width;
  724. context.height = ihdr.height;
  725. context.bit_depth = ihdr.bit_depth;
  726. context.color_type = ihdr.color_type;
  727. context.compression_method = ihdr.compression_method;
  728. context.filter_method = ihdr.filter_method;
  729. context.interlace_method = ihdr.interlace_method;
  730. #ifdef PNG_DEBUG
  731. printf("PNG: %dx%d (%d bpp)\n", context.width, context.height, context.bit_depth);
  732. printf(" Color type: %d\n", context.color_type);
  733. printf("Compress Method: %d\n", context.compression_method);
  734. printf(" Filter Method: %d\n", context.filter_method);
  735. printf(" Interlace type: %d\n", context.interlace_method);
  736. #endif
  737. if (context.interlace_method != PngInterlaceMethod::Null && context.interlace_method != PngInterlaceMethod::Adam7) {
  738. dbgprintf("PNGLoader::process_IHDR: unknown interlace method: %d\n", context.interlace_method);
  739. return false;
  740. }
  741. switch (context.color_type) {
  742. case 0: // Each pixel is a grayscale sample.
  743. context.channels = 1;
  744. break;
  745. case 4: // Each pixel is a grayscale sample, followed by an alpha sample.
  746. context.channels = 2;
  747. break;
  748. case 2: // Each pixel is an RGB sample
  749. context.channels = 3;
  750. break;
  751. case 3: // Each pixel is a palette index; a PLTE chunk must appear.
  752. context.channels = 1;
  753. break;
  754. case 6: // Each pixel is an RGB sample, followed by an alpha sample.
  755. context.channels = 4;
  756. break;
  757. default:
  758. ASSERT_NOT_REACHED();
  759. }
  760. return true;
  761. }
  762. static bool process_IDAT(const ByteBuffer& data, PNGLoadingContext& context)
  763. {
  764. context.compressed_data.append(data.data(), data.size());
  765. return true;
  766. }
  767. static bool process_PLTE(const ByteBuffer& data, PNGLoadingContext& context)
  768. {
  769. context.palette_data.append((const PaletteEntry*)data.data(), data.size() / 3);
  770. return true;
  771. }
  772. static bool process_tRNS(const ByteBuffer& data, PNGLoadingContext& context)
  773. {
  774. switch (context.color_type) {
  775. case 3:
  776. context.palette_transparency_data.append(data.data(), data.size());
  777. break;
  778. }
  779. return true;
  780. }
  781. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  782. {
  783. u32 chunk_size;
  784. if (!streamer.read(chunk_size)) {
  785. printf("Bail at chunk_size\n");
  786. return false;
  787. }
  788. u8 chunk_type[5];
  789. chunk_type[4] = '\0';
  790. if (!streamer.read_bytes(chunk_type, 4)) {
  791. printf("Bail at chunk_type\n");
  792. return false;
  793. }
  794. ByteBuffer chunk_data;
  795. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  796. printf("Bail at chunk_data\n");
  797. return false;
  798. }
  799. u32 chunk_crc;
  800. if (!streamer.read(chunk_crc)) {
  801. printf("Bail at chunk_crc\n");
  802. return false;
  803. }
  804. #ifdef PNG_DEBUG
  805. printf("Chunk type: '%s', size: %u, crc: %x\n", chunk_type, chunk_size, chunk_crc);
  806. #endif
  807. if (!strcmp((const char*)chunk_type, "IHDR"))
  808. return process_IHDR(chunk_data, context);
  809. if (!strcmp((const char*)chunk_type, "IDAT"))
  810. return process_IDAT(chunk_data, context);
  811. if (!strcmp((const char*)chunk_type, "PLTE"))
  812. return process_PLTE(chunk_data, context);
  813. if (!strcmp((const char*)chunk_type, "tRNS"))
  814. return process_tRNS(chunk_data, context);
  815. return true;
  816. }
  817. PNGImageDecoderPlugin::PNGImageDecoderPlugin(const u8* data, size_t size)
  818. {
  819. m_context = make<PNGLoadingContext>();
  820. m_context->data = data;
  821. m_context->data_size = size;
  822. }
  823. PNGImageDecoderPlugin::~PNGImageDecoderPlugin()
  824. {
  825. }
  826. IntSize PNGImageDecoderPlugin::size()
  827. {
  828. if (m_context->state == PNGLoadingContext::State::Error)
  829. return {};
  830. if (m_context->state < PNGLoadingContext::State::SizeDecoded) {
  831. bool success = decode_png_size(*m_context);
  832. if (!success)
  833. return {};
  834. }
  835. return { m_context->width, m_context->height };
  836. }
  837. RefPtr<Gfx::Bitmap> PNGImageDecoderPlugin::bitmap()
  838. {
  839. if (m_context->state == PNGLoadingContext::State::Error)
  840. return nullptr;
  841. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  842. // NOTE: This forces the chunk decoding to happen.
  843. bool success = decode_png_bitmap(*m_context);
  844. if (!success)
  845. return nullptr;
  846. }
  847. ASSERT(m_context->bitmap);
  848. return m_context->bitmap;
  849. }
  850. void PNGImageDecoderPlugin::set_volatile()
  851. {
  852. if (m_context->bitmap)
  853. m_context->bitmap->set_volatile();
  854. }
  855. bool PNGImageDecoderPlugin::set_nonvolatile()
  856. {
  857. if (!m_context->bitmap)
  858. return false;
  859. return m_context->bitmap->set_nonvolatile();
  860. }
  861. bool PNGImageDecoderPlugin::sniff()
  862. {
  863. return decode_png_header(*m_context);
  864. }
  865. bool PNGImageDecoderPlugin::is_animated()
  866. {
  867. return false;
  868. }
  869. size_t PNGImageDecoderPlugin::loop_count()
  870. {
  871. return 0;
  872. }
  873. size_t PNGImageDecoderPlugin::frame_count()
  874. {
  875. return 1;
  876. }
  877. ImageFrameDescriptor PNGImageDecoderPlugin::frame(size_t i)
  878. {
  879. if (i > 0) {
  880. return { bitmap(), 0 };
  881. }
  882. return {};
  883. }
  884. }