PNGLoader.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. ASSERT(context.width >= 0);
  677. ASSERT(context.height >= 0);
  678. unsigned long srclen = context.compressed_data.size() - 6;
  679. unsigned long destlen = 0;
  680. int ret = puff(nullptr, &destlen, context.compressed_data.data() + 2, &srclen);
  681. if (ret != 0) {
  682. context.state = PNGLoadingContext::State::Error;
  683. return false;
  684. }
  685. context.decompression_buffer_size = destlen;
  686. #ifdef __serenity__
  687. 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");
  688. #else
  689. context.decompression_buffer = (u8*)mmap(nullptr, context.decompression_buffer_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
  690. #endif
  691. ret = puff(context.decompression_buffer, &destlen, context.compressed_data.data() + 2, &srclen);
  692. if (ret != 0) {
  693. context.state = PNGLoadingContext::State::Error;
  694. return false;
  695. }
  696. context.compressed_data.clear();
  697. context.scanlines.ensure_capacity(context.height);
  698. switch (context.interlace_method) {
  699. case PngInterlaceMethod::Null:
  700. if (!decode_png_bitmap_simple(context))
  701. return false;
  702. break;
  703. case PngInterlaceMethod::Adam7:
  704. if (!decode_png_adam7(context))
  705. return false;
  706. break;
  707. default:
  708. ASSERT_NOT_REACHED();
  709. }
  710. munmap(context.decompression_buffer, context.decompression_buffer_size);
  711. context.decompression_buffer = nullptr;
  712. context.decompression_buffer_size = 0;
  713. context.state = PNGLoadingContext::State::BitmapDecoded;
  714. return true;
  715. }
  716. static RefPtr<Gfx::Bitmap> load_png_impl(const u8* data, size_t data_size)
  717. {
  718. PNGLoadingContext context;
  719. context.data = data;
  720. context.data_size = data_size;
  721. if (!decode_png_chunks(context))
  722. return nullptr;
  723. if (!decode_png_bitmap(context))
  724. return nullptr;
  725. return context.bitmap;
  726. }
  727. static bool process_IHDR(const ByteBuffer& data, PNGLoadingContext& context)
  728. {
  729. if (data.size() < (int)sizeof(PNG_IHDR))
  730. return false;
  731. auto& ihdr = *(const PNG_IHDR*)data.data();
  732. if (ihdr.width > NumericLimits<i32>::max() || ihdr.height > NumericLimits<i32>::max()) {
  733. dbgln("PNG has invalid geometry {}x{}", (u32)ihdr.width, (u32)ihdr.height);
  734. return false;
  735. }
  736. context.width = ihdr.width;
  737. context.height = ihdr.height;
  738. context.bit_depth = ihdr.bit_depth;
  739. context.color_type = ihdr.color_type;
  740. context.compression_method = ihdr.compression_method;
  741. context.filter_method = ihdr.filter_method;
  742. context.interlace_method = ihdr.interlace_method;
  743. #ifdef PNG_DEBUG
  744. printf("PNG: %dx%d (%d bpp)\n", context.width, context.height, context.bit_depth);
  745. printf(" Color type: %d\n", context.color_type);
  746. printf("Compress Method: %d\n", context.compression_method);
  747. printf(" Filter Method: %d\n", context.filter_method);
  748. printf(" Interlace type: %d\n", context.interlace_method);
  749. #endif
  750. if (context.interlace_method != PngInterlaceMethod::Null && context.interlace_method != PngInterlaceMethod::Adam7) {
  751. dbgprintf("PNGLoader::process_IHDR: unknown interlace method: %d\n", context.interlace_method);
  752. return false;
  753. }
  754. switch (context.color_type) {
  755. case 0: // Each pixel is a grayscale sample.
  756. context.channels = 1;
  757. break;
  758. case 4: // Each pixel is a grayscale sample, followed by an alpha sample.
  759. context.channels = 2;
  760. break;
  761. case 2: // Each pixel is an RGB sample
  762. context.channels = 3;
  763. break;
  764. case 3: // Each pixel is a palette index; a PLTE chunk must appear.
  765. context.channels = 1;
  766. break;
  767. case 6: // Each pixel is an RGB sample, followed by an alpha sample.
  768. context.channels = 4;
  769. break;
  770. default:
  771. ASSERT_NOT_REACHED();
  772. }
  773. return true;
  774. }
  775. static bool process_IDAT(const ByteBuffer& data, PNGLoadingContext& context)
  776. {
  777. context.compressed_data.append(data.data(), data.size());
  778. return true;
  779. }
  780. static bool process_PLTE(const ByteBuffer& data, PNGLoadingContext& context)
  781. {
  782. context.palette_data.append((const PaletteEntry*)data.data(), data.size() / 3);
  783. return true;
  784. }
  785. static bool process_tRNS(const ByteBuffer& data, PNGLoadingContext& context)
  786. {
  787. switch (context.color_type) {
  788. case 3:
  789. context.palette_transparency_data.append(data.data(), data.size());
  790. break;
  791. }
  792. return true;
  793. }
  794. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  795. {
  796. u32 chunk_size;
  797. if (!streamer.read(chunk_size)) {
  798. printf("Bail at chunk_size\n");
  799. return false;
  800. }
  801. u8 chunk_type[5];
  802. chunk_type[4] = '\0';
  803. if (!streamer.read_bytes(chunk_type, 4)) {
  804. printf("Bail at chunk_type\n");
  805. return false;
  806. }
  807. ByteBuffer chunk_data;
  808. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  809. printf("Bail at chunk_data\n");
  810. return false;
  811. }
  812. u32 chunk_crc;
  813. if (!streamer.read(chunk_crc)) {
  814. printf("Bail at chunk_crc\n");
  815. return false;
  816. }
  817. #ifdef PNG_DEBUG
  818. printf("Chunk type: '%s', size: %u, crc: %x\n", chunk_type, chunk_size, chunk_crc);
  819. #endif
  820. if (!strcmp((const char*)chunk_type, "IHDR"))
  821. return process_IHDR(chunk_data, context);
  822. if (!strcmp((const char*)chunk_type, "IDAT"))
  823. return process_IDAT(chunk_data, context);
  824. if (!strcmp((const char*)chunk_type, "PLTE"))
  825. return process_PLTE(chunk_data, context);
  826. if (!strcmp((const char*)chunk_type, "tRNS"))
  827. return process_tRNS(chunk_data, context);
  828. return true;
  829. }
  830. PNGImageDecoderPlugin::PNGImageDecoderPlugin(const u8* data, size_t size)
  831. {
  832. m_context = make<PNGLoadingContext>();
  833. m_context->data = data;
  834. m_context->data_size = size;
  835. }
  836. PNGImageDecoderPlugin::~PNGImageDecoderPlugin()
  837. {
  838. }
  839. IntSize PNGImageDecoderPlugin::size()
  840. {
  841. if (m_context->state == PNGLoadingContext::State::Error)
  842. return {};
  843. if (m_context->state < PNGLoadingContext::State::SizeDecoded) {
  844. bool success = decode_png_size(*m_context);
  845. if (!success)
  846. return {};
  847. }
  848. return { m_context->width, m_context->height };
  849. }
  850. RefPtr<Gfx::Bitmap> PNGImageDecoderPlugin::bitmap()
  851. {
  852. if (m_context->state == PNGLoadingContext::State::Error)
  853. return nullptr;
  854. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  855. // NOTE: This forces the chunk decoding to happen.
  856. bool success = decode_png_bitmap(*m_context);
  857. if (!success)
  858. return nullptr;
  859. }
  860. ASSERT(m_context->bitmap);
  861. return m_context->bitmap;
  862. }
  863. void PNGImageDecoderPlugin::set_volatile()
  864. {
  865. if (m_context->bitmap)
  866. m_context->bitmap->set_volatile();
  867. }
  868. bool PNGImageDecoderPlugin::set_nonvolatile()
  869. {
  870. if (!m_context->bitmap)
  871. return false;
  872. return m_context->bitmap->set_nonvolatile();
  873. }
  874. bool PNGImageDecoderPlugin::sniff()
  875. {
  876. return decode_png_header(*m_context);
  877. }
  878. bool PNGImageDecoderPlugin::is_animated()
  879. {
  880. return false;
  881. }
  882. size_t PNGImageDecoderPlugin::loop_count()
  883. {
  884. return 0;
  885. }
  886. size_t PNGImageDecoderPlugin::frame_count()
  887. {
  888. return 1;
  889. }
  890. ImageFrameDescriptor PNGImageDecoderPlugin::frame(size_t i)
  891. {
  892. if (i > 0) {
  893. return { bitmap(), 0 };
  894. }
  895. return {};
  896. }
  897. }