PNGLoader.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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/Endian.h>
  28. #include <AK/LexicalPath.h>
  29. #include <AK/MappedFile.h>
  30. #include <LibCore/puff.h>
  31. #include <LibGfx/PNGLoader.h>
  32. #include <fcntl.h>
  33. #include <math.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(const_cast<u8*>(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 bit_depth_squared = context.bit_depth * context.bit_depth;
  337. auto pixels_per_byte = 8 / context.bit_depth;
  338. auto mask = (1 << context.bit_depth) - 1;
  339. for (int y = 0; y < context.height; ++y) {
  340. auto* gray_values = (u8*)context.scanlines[y].data.data();
  341. for (int x = 0; x < context.width; ++x) {
  342. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (x % pixels_per_byte));
  343. auto value = (gray_values[x / pixels_per_byte] >> bit_offset) & mask;
  344. auto& pixel = (Pixel&)context.bitmap->scanline(y)[x];
  345. pixel.r = value * (0xff / bit_depth_squared);
  346. pixel.g = value * (0xff / bit_depth_squared);
  347. pixel.b = value * (0xff / bit_depth_squared);
  348. pixel.a = 0xff;
  349. }
  350. }
  351. } else {
  352. ASSERT_NOT_REACHED();
  353. }
  354. break;
  355. case 4:
  356. if (context.bit_depth == 8) {
  357. unpack_grayscale_with_alpha<u8>(context);
  358. } else if (context.bit_depth == 16) {
  359. unpack_grayscale_with_alpha<u16>(context);
  360. } else {
  361. ASSERT_NOT_REACHED();
  362. }
  363. break;
  364. case 2:
  365. if (context.bit_depth == 8) {
  366. unpack_triplets_without_alpha<u8>(context);
  367. } else if (context.bit_depth == 16) {
  368. unpack_triplets_without_alpha<u16>(context);
  369. } else {
  370. ASSERT_NOT_REACHED();
  371. }
  372. break;
  373. case 6:
  374. if (context.bit_depth == 8) {
  375. for (int y = 0; y < context.height; ++y) {
  376. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  377. }
  378. } else if (context.bit_depth == 16) {
  379. for (int y = 0; y < context.height; ++y) {
  380. auto* triplets = reinterpret_cast<const Quad<u16>*>(context.scanlines[y].data.data());
  381. for (int i = 0; i < context.width; ++i) {
  382. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  383. pixel.r = triplets[i].r & 0xFF;
  384. pixel.g = triplets[i].g & 0xFF;
  385. pixel.b = triplets[i].b & 0xFF;
  386. pixel.a = triplets[i].a & 0xFF;
  387. }
  388. }
  389. } else {
  390. ASSERT_NOT_REACHED();
  391. }
  392. break;
  393. case 3:
  394. if (context.bit_depth == 8) {
  395. for (int y = 0; y < context.height; ++y) {
  396. auto* palette_index = (u8*)context.scanlines[y].data.data();
  397. for (int i = 0; i < context.width; ++i) {
  398. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  399. auto& color = context.palette_data.at((int)palette_index[i]);
  400. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u
  401. ? context.palette_transparency_data.data()[palette_index[i]]
  402. : 0xff;
  403. pixel.r = color.r;
  404. pixel.g = color.g;
  405. pixel.b = color.b;
  406. pixel.a = transparency;
  407. }
  408. }
  409. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  410. auto pixels_per_byte = 8 / context.bit_depth;
  411. auto mask = (1 << context.bit_depth) - 1;
  412. for (int y = 0; y < context.height; ++y) {
  413. auto* palette_indexes = (u8*)context.scanlines[y].data.data();
  414. for (int i = 0; i < context.width; ++i) {
  415. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (i % pixels_per_byte));
  416. auto palette_index = (palette_indexes[i / pixels_per_byte] >> bit_offset) & mask;
  417. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  418. auto& color = context.palette_data.at(palette_index);
  419. auto transparency = context.palette_transparency_data.size() >= palette_index + 1u
  420. ? context.palette_transparency_data.data()[palette_index]
  421. : 0xff;
  422. pixel.r = color.r;
  423. pixel.g = color.g;
  424. pixel.b = color.b;
  425. pixel.a = transparency;
  426. }
  427. }
  428. } else {
  429. ASSERT_NOT_REACHED();
  430. }
  431. break;
  432. default:
  433. ASSERT_NOT_REACHED();
  434. break;
  435. }
  436. auto dummy_scanline = ByteBuffer::create_zeroed(context.width * sizeof(RGBA32));
  437. for (int y = 0; y < context.height; ++y) {
  438. auto filter = context.scanlines[y].filter;
  439. if (filter == 0) {
  440. if (context.has_alpha())
  441. unfilter_impl<true, 0>(*context.bitmap, y, dummy_scanline.data());
  442. else
  443. unfilter_impl<false, 0>(*context.bitmap, y, dummy_scanline.data());
  444. continue;
  445. }
  446. if (filter == 1) {
  447. if (context.has_alpha())
  448. unfilter_impl<true, 1>(*context.bitmap, y, dummy_scanline.data());
  449. else
  450. unfilter_impl<false, 1>(*context.bitmap, y, dummy_scanline.data());
  451. continue;
  452. }
  453. if (filter == 2) {
  454. if (context.has_alpha())
  455. unfilter_impl<true, 2>(*context.bitmap, y, dummy_scanline.data());
  456. else
  457. unfilter_impl<false, 2>(*context.bitmap, y, dummy_scanline.data());
  458. continue;
  459. }
  460. if (filter == 3) {
  461. if (context.has_alpha())
  462. unfilter_impl<true, 3>(*context.bitmap, y, dummy_scanline.data());
  463. else
  464. unfilter_impl<false, 3>(*context.bitmap, y, dummy_scanline.data());
  465. continue;
  466. }
  467. if (filter == 4) {
  468. if (context.has_alpha())
  469. unfilter_impl<true, 4>(*context.bitmap, y, dummy_scanline.data());
  470. else
  471. unfilter_impl<false, 4>(*context.bitmap, y, dummy_scanline.data());
  472. continue;
  473. }
  474. }
  475. }
  476. static bool decode_png_header(PNGLoadingContext& context)
  477. {
  478. if (context.state >= PNGLoadingContext::HeaderDecoded)
  479. return true;
  480. if (!context.data || context.data_size < sizeof(png_header)) {
  481. #ifdef PNG_DEBUG
  482. dbg() << "Missing PNG header";
  483. #endif
  484. context.state = PNGLoadingContext::State::Error;
  485. return false;
  486. }
  487. if (memcmp(context.data, png_header, sizeof(png_header)) != 0) {
  488. #ifdef PNG_DEBUG
  489. dbg() << "Invalid PNG header";
  490. #endif
  491. context.state = PNGLoadingContext::State::Error;
  492. return false;
  493. }
  494. context.state = PNGLoadingContext::HeaderDecoded;
  495. return true;
  496. }
  497. static bool decode_png_size(PNGLoadingContext& context)
  498. {
  499. if (context.state >= PNGLoadingContext::SizeDecoded)
  500. return true;
  501. if (context.state < PNGLoadingContext::HeaderDecoded) {
  502. if (!decode_png_header(context))
  503. return false;
  504. }
  505. const u8* data_ptr = context.data + sizeof(png_header);
  506. size_t data_remaining = context.data_size - sizeof(png_header);
  507. Streamer streamer(data_ptr, data_remaining);
  508. while (!streamer.at_end()) {
  509. if (!process_chunk(streamer, context)) {
  510. context.state = PNGLoadingContext::State::Error;
  511. return false;
  512. }
  513. if (context.width && context.height) {
  514. context.state = PNGLoadingContext::State::SizeDecoded;
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. static bool decode_png_chunks(PNGLoadingContext& context)
  521. {
  522. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  523. return true;
  524. if (context.state < PNGLoadingContext::HeaderDecoded) {
  525. if (!decode_png_header(context))
  526. return false;
  527. }
  528. const u8* data_ptr = context.data + sizeof(png_header);
  529. int data_remaining = context.data_size - sizeof(png_header);
  530. context.compressed_data.ensure_capacity(context.data_size);
  531. Streamer streamer(data_ptr, data_remaining);
  532. while (!streamer.at_end()) {
  533. if (!process_chunk(streamer, context)) {
  534. context.state = PNGLoadingContext::State::Error;
  535. return false;
  536. }
  537. }
  538. context.state = PNGLoadingContext::State::ChunksDecoded;
  539. return true;
  540. }
  541. static bool decode_png_bitmap_simple(PNGLoadingContext& context)
  542. {
  543. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  544. for (int y = 0; y < context.height; ++y) {
  545. u8 filter;
  546. if (!streamer.read(filter)) {
  547. context.state = PNGLoadingContext::State::Error;
  548. return false;
  549. }
  550. if (filter > 4) {
  551. dbg() << "Invalid PNG filter: " << filter;
  552. context.state = PNGLoadingContext::State::Error;
  553. return false;
  554. }
  555. context.scanlines.append({ filter });
  556. auto& scanline_buffer = context.scanlines.last().data;
  557. auto row_size = ((context.width * context.channels * context.bit_depth) + 7) / 8;
  558. if (!streamer.wrap_bytes(scanline_buffer, row_size)) {
  559. context.state = PNGLoadingContext::State::Error;
  560. return false;
  561. }
  562. }
  563. context.bitmap = Bitmap::create_purgeable(context.has_alpha() ? BitmapFormat::RGBA32 : BitmapFormat::RGB32, { context.width, context.height });
  564. unfilter(context);
  565. return true;
  566. }
  567. static int adam7_height(PNGLoadingContext& context, int pass)
  568. {
  569. switch (pass) {
  570. case 1:
  571. return (context.height + 7) / 8;
  572. case 2:
  573. return (context.height + 7) / 8;
  574. case 3:
  575. return (context.height + 3) / 8;
  576. case 4:
  577. return (context.height + 3) / 4;
  578. case 5:
  579. return (context.height + 1) / 4;
  580. case 6:
  581. return (context.height + 1) / 2;
  582. case 7:
  583. return context.height / 2;
  584. default:
  585. ASSERT_NOT_REACHED();
  586. }
  587. }
  588. static int adam7_width(PNGLoadingContext& context, int pass)
  589. {
  590. switch (pass) {
  591. case 1:
  592. return (context.width + 7) / 8;
  593. case 2:
  594. return (context.width + 3) / 8;
  595. case 3:
  596. return (context.width + 3) / 4;
  597. case 4:
  598. return (context.width + 1) / 4;
  599. case 5:
  600. return (context.width + 1) / 2;
  601. case 6:
  602. return context.width / 2;
  603. case 7:
  604. return context.width;
  605. default:
  606. ASSERT_NOT_REACHED();
  607. }
  608. }
  609. // Index 0 unused (non-interlaced case)
  610. static int adam7_starty[8] = { 0, 0, 0, 4, 0, 2, 0, 1 };
  611. static int adam7_startx[8] = { 0, 0, 4, 0, 2, 0, 1, 0 };
  612. static int adam7_stepy[8] = { 1, 8, 8, 8, 4, 4, 2, 2 };
  613. static int adam7_stepx[8] = { 1, 8, 8, 4, 4, 2, 2, 1 };
  614. static bool decode_adam7_pass(PNGLoadingContext& context, Streamer& streamer, int pass)
  615. {
  616. PNGLoadingContext subimage_context;
  617. subimage_context.width = adam7_width(context, pass);
  618. subimage_context.height = adam7_height(context, pass);
  619. subimage_context.channels = context.channels;
  620. subimage_context.color_type = context.color_type;
  621. subimage_context.palette_data = context.palette_data;
  622. subimage_context.palette_transparency_data = context.palette_transparency_data;
  623. subimage_context.bit_depth = context.bit_depth;
  624. subimage_context.filter_method = context.filter_method;
  625. // For small images, some passes might be empty
  626. if (!subimage_context.width || !subimage_context.height)
  627. return true;
  628. subimage_context.scanlines.clear_with_capacity();
  629. for (int y = 0; y < subimage_context.height; ++y) {
  630. u8 filter;
  631. if (!streamer.read(filter)) {
  632. context.state = PNGLoadingContext::State::Error;
  633. return false;
  634. }
  635. if (filter > 4) {
  636. dbg() << "Invalid PNG filter: " << filter;
  637. context.state = PNGLoadingContext::State::Error;
  638. return false;
  639. }
  640. subimage_context.scanlines.append({ filter });
  641. auto& scanline_buffer = subimage_context.scanlines.last().data;
  642. auto row_size = ((subimage_context.width * context.channels * context.bit_depth) + 7) / 8;
  643. if (!streamer.wrap_bytes(scanline_buffer, row_size)) {
  644. context.state = PNGLoadingContext::State::Error;
  645. return false;
  646. }
  647. }
  648. subimage_context.bitmap = Bitmap::create(context.bitmap->format(), { subimage_context.width, subimage_context.height });
  649. unfilter(subimage_context);
  650. // Copy the subimage data into the main image according to the pass pattern
  651. for (int y = 0, dy = adam7_starty[pass]; y < subimage_context.height && dy < context.height; ++y, dy += adam7_stepy[pass]) {
  652. for (int x = 0, dx = adam7_startx[pass]; x < subimage_context.width && dy < context.width; ++x, dx += adam7_stepx[pass]) {
  653. context.bitmap->set_pixel(dx, dy, subimage_context.bitmap->get_pixel(x, y));
  654. }
  655. }
  656. return true;
  657. }
  658. static bool decode_png_adam7(PNGLoadingContext& context)
  659. {
  660. Streamer streamer(context.decompression_buffer, context.decompression_buffer_size);
  661. context.bitmap = Bitmap::create_purgeable(context.has_alpha() ? BitmapFormat::RGBA32 : BitmapFormat::RGB32, { context.width, context.height });
  662. for (int pass = 1; pass <= 7; ++pass) {
  663. if (!decode_adam7_pass(context, streamer, pass))
  664. return false;
  665. }
  666. return true;
  667. }
  668. static bool decode_png_bitmap(PNGLoadingContext& context)
  669. {
  670. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  671. if (!decode_png_chunks(context))
  672. return false;
  673. }
  674. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  675. return true;
  676. unsigned long srclen = context.compressed_data.size() - 6;
  677. unsigned long destlen = 0;
  678. int ret = puff(NULL, &destlen, context.compressed_data.data() + 2, &srclen);
  679. if (ret != 0) {
  680. context.state = PNGLoadingContext::State::Error;
  681. return false;
  682. }
  683. context.decompression_buffer_size = destlen;
  684. #ifdef __serenity__
  685. 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");
  686. #else
  687. context.decompression_buffer = (u8*)mmap(nullptr, context.decompression_buffer_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
  688. #endif
  689. ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen);
  690. if (ret != 0) {
  691. context.state = PNGLoadingContext::State::Error;
  692. return false;
  693. }
  694. context.compressed_data.clear();
  695. context.scanlines.ensure_capacity(context.height);
  696. switch (context.interlace_method) {
  697. case PngInterlaceMethod::Null:
  698. if (!decode_png_bitmap_simple(context))
  699. return false;
  700. break;
  701. case PngInterlaceMethod::Adam7:
  702. if (!decode_png_adam7(context))
  703. return false;
  704. break;
  705. default:
  706. ASSERT_NOT_REACHED();
  707. }
  708. munmap(context.decompression_buffer, context.decompression_buffer_size);
  709. context.decompression_buffer = nullptr;
  710. context.decompression_buffer_size = 0;
  711. context.state = PNGLoadingContext::State::BitmapDecoded;
  712. return true;
  713. }
  714. static RefPtr<Gfx::Bitmap> load_png_impl(const u8* data, size_t data_size)
  715. {
  716. PNGLoadingContext context;
  717. context.data = data;
  718. context.data_size = data_size;
  719. if (!decode_png_chunks(context))
  720. return nullptr;
  721. if (!decode_png_bitmap(context))
  722. return nullptr;
  723. return context.bitmap;
  724. }
  725. static bool process_IHDR(const ByteBuffer& data, PNGLoadingContext& context)
  726. {
  727. if (data.size() < (int)sizeof(PNG_IHDR))
  728. return false;
  729. auto& ihdr = *(const PNG_IHDR*)data.data();
  730. context.width = ihdr.width;
  731. context.height = ihdr.height;
  732. context.bit_depth = ihdr.bit_depth;
  733. context.color_type = ihdr.color_type;
  734. context.compression_method = ihdr.compression_method;
  735. context.filter_method = ihdr.filter_method;
  736. context.interlace_method = ihdr.interlace_method;
  737. #ifdef PNG_DEBUG
  738. printf("PNG: %dx%d (%d bpp)\n", context.width, context.height, context.bit_depth);
  739. printf(" Color type: %d\n", context.color_type);
  740. printf("Compress Method: %d\n", context.compression_method);
  741. printf(" Filter Method: %d\n", context.filter_method);
  742. printf(" Interlace type: %d\n", context.interlace_method);
  743. #endif
  744. if (context.interlace_method != PngInterlaceMethod::Null && context.interlace_method != PngInterlaceMethod::Adam7) {
  745. dbgprintf("PNGLoader::process_IHDR: unknown interlace method: %d\n", context.interlace_method);
  746. return false;
  747. }
  748. switch (context.color_type) {
  749. case 0: // Each pixel is a grayscale sample.
  750. context.channels = 1;
  751. break;
  752. case 4: // Each pixel is a grayscale sample, followed by an alpha sample.
  753. context.channels = 2;
  754. break;
  755. case 2: // Each pixel is an RGB sample
  756. context.channels = 3;
  757. break;
  758. case 3: // Each pixel is a palette index; a PLTE chunk must appear.
  759. context.channels = 1;
  760. break;
  761. case 6: // Each pixel is an RGB sample, followed by an alpha sample.
  762. context.channels = 4;
  763. break;
  764. default:
  765. ASSERT_NOT_REACHED();
  766. }
  767. return true;
  768. }
  769. static bool process_IDAT(const ByteBuffer& data, PNGLoadingContext& context)
  770. {
  771. context.compressed_data.append(data.data(), data.size());
  772. return true;
  773. }
  774. static bool process_PLTE(const ByteBuffer& data, PNGLoadingContext& context)
  775. {
  776. context.palette_data.append((const PaletteEntry*)data.data(), data.size() / 3);
  777. return true;
  778. }
  779. static bool process_tRNS(const ByteBuffer& data, PNGLoadingContext& context)
  780. {
  781. switch (context.color_type) {
  782. case 3:
  783. context.palette_transparency_data.append(data.data(), data.size());
  784. break;
  785. }
  786. return true;
  787. }
  788. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  789. {
  790. u32 chunk_size;
  791. if (!streamer.read(chunk_size)) {
  792. printf("Bail at chunk_size\n");
  793. return false;
  794. }
  795. u8 chunk_type[5];
  796. chunk_type[4] = '\0';
  797. if (!streamer.read_bytes(chunk_type, 4)) {
  798. printf("Bail at chunk_type\n");
  799. return false;
  800. }
  801. ByteBuffer chunk_data;
  802. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  803. printf("Bail at chunk_data\n");
  804. return false;
  805. }
  806. u32 chunk_crc;
  807. if (!streamer.read(chunk_crc)) {
  808. printf("Bail at chunk_crc\n");
  809. return false;
  810. }
  811. #ifdef PNG_DEBUG
  812. printf("Chunk type: '%s', size: %u, crc: %x\n", chunk_type, chunk_size, chunk_crc);
  813. #endif
  814. if (!strcmp((const char*)chunk_type, "IHDR"))
  815. return process_IHDR(chunk_data, context);
  816. if (!strcmp((const char*)chunk_type, "IDAT"))
  817. return process_IDAT(chunk_data, context);
  818. if (!strcmp((const char*)chunk_type, "PLTE"))
  819. return process_PLTE(chunk_data, context);
  820. if (!strcmp((const char*)chunk_type, "tRNS"))
  821. return process_tRNS(chunk_data, context);
  822. return true;
  823. }
  824. PNGImageDecoderPlugin::PNGImageDecoderPlugin(const u8* data, size_t size)
  825. {
  826. m_context = make<PNGLoadingContext>();
  827. m_context->data = data;
  828. m_context->data_size = size;
  829. }
  830. PNGImageDecoderPlugin::~PNGImageDecoderPlugin()
  831. {
  832. }
  833. IntSize PNGImageDecoderPlugin::size()
  834. {
  835. if (m_context->state == PNGLoadingContext::State::Error)
  836. return {};
  837. if (m_context->state < PNGLoadingContext::State::SizeDecoded) {
  838. bool success = decode_png_size(*m_context);
  839. if (!success)
  840. return {};
  841. }
  842. return { m_context->width, m_context->height };
  843. }
  844. RefPtr<Gfx::Bitmap> PNGImageDecoderPlugin::bitmap()
  845. {
  846. if (m_context->state == PNGLoadingContext::State::Error)
  847. return nullptr;
  848. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  849. // NOTE: This forces the chunk decoding to happen.
  850. bool success = decode_png_bitmap(*m_context);
  851. if (!success)
  852. return nullptr;
  853. }
  854. ASSERT(m_context->bitmap);
  855. return m_context->bitmap;
  856. }
  857. void PNGImageDecoderPlugin::set_volatile()
  858. {
  859. if (m_context->bitmap)
  860. m_context->bitmap->set_volatile();
  861. }
  862. bool PNGImageDecoderPlugin::set_nonvolatile()
  863. {
  864. if (!m_context->bitmap)
  865. return false;
  866. return m_context->bitmap->set_nonvolatile();
  867. }
  868. bool PNGImageDecoderPlugin::sniff()
  869. {
  870. return decode_png_header(*m_context);
  871. }
  872. bool PNGImageDecoderPlugin::is_animated()
  873. {
  874. return false;
  875. }
  876. size_t PNGImageDecoderPlugin::loop_count()
  877. {
  878. return 0;
  879. }
  880. size_t PNGImageDecoderPlugin::frame_count()
  881. {
  882. return 1;
  883. }
  884. ImageFrameDescriptor PNGImageDecoderPlugin::frame(size_t i)
  885. {
  886. if (i > 0) {
  887. return { bitmap(), 0 };
  888. }
  889. return {};
  890. }
  891. }