PNGLoader.cpp 31 KB

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