PNGLoader.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Array.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Endian.h>
  10. #include <AK/Vector.h>
  11. #include <LibCompress/Zlib.h>
  12. #include <LibGfx/PNGLoader.h>
  13. #include <LibGfx/PNGShared.h>
  14. #include <string.h>
  15. namespace Gfx {
  16. struct PNG_IHDR {
  17. NetworkOrdered<u32> width;
  18. NetworkOrdered<u32> height;
  19. u8 bit_depth { 0 };
  20. PNG::ColorType color_type { 0 };
  21. u8 compression_method { 0 };
  22. u8 filter_method { 0 };
  23. u8 interlace_method { 0 };
  24. };
  25. static_assert(AssertSize<PNG_IHDR, 13>());
  26. struct Scanline {
  27. PNG::FilterType filter;
  28. ReadonlyBytes data {};
  29. };
  30. struct [[gnu::packed]] PaletteEntry {
  31. u8 r;
  32. u8 g;
  33. u8 b;
  34. // u8 a;
  35. };
  36. template<typename T>
  37. struct [[gnu::packed]] Tuple {
  38. T gray;
  39. T a;
  40. };
  41. template<typename T>
  42. struct [[gnu::packed]] Triplet {
  43. T r;
  44. T g;
  45. T b;
  46. bool operator==(Triplet const& other) const = default;
  47. };
  48. template<typename T>
  49. struct [[gnu::packed]] Quartet {
  50. T r;
  51. T g;
  52. T b;
  53. T a;
  54. };
  55. enum PngInterlaceMethod {
  56. Null = 0,
  57. Adam7 = 1
  58. };
  59. struct PNGLoadingContext {
  60. enum State {
  61. NotDecoded = 0,
  62. Error,
  63. HeaderDecoded,
  64. SizeDecoded,
  65. ChunksDecoded,
  66. BitmapDecoded,
  67. };
  68. State state { State::NotDecoded };
  69. u8 const* data { nullptr };
  70. size_t data_size { 0 };
  71. int width { -1 };
  72. int height { -1 };
  73. u8 bit_depth { 0 };
  74. PNG::ColorType color_type { 0 };
  75. u8 compression_method { 0 };
  76. u8 filter_method { 0 };
  77. u8 interlace_method { 0 };
  78. u8 channels { 0 };
  79. bool has_seen_zlib_header { false };
  80. bool has_alpha() const { return to_underlying(color_type) & 4 || palette_transparency_data.size() > 0; }
  81. Vector<Scanline> scanlines;
  82. ByteBuffer unfiltered_data;
  83. RefPtr<Gfx::Bitmap> bitmap;
  84. ByteBuffer* decompression_buffer { nullptr };
  85. Vector<u8> compressed_data;
  86. Vector<PaletteEntry> palette_data;
  87. Vector<u8> palette_transparency_data;
  88. Checked<int> compute_row_size_for_width(int width)
  89. {
  90. Checked<int> row_size = width;
  91. row_size *= channels;
  92. row_size *= bit_depth;
  93. row_size += 7;
  94. row_size /= 8;
  95. if (row_size.has_overflow()) {
  96. dbgln("PNG too large, integer overflow while computing row size");
  97. state = State::Error;
  98. }
  99. return row_size;
  100. }
  101. };
  102. class Streamer {
  103. public:
  104. Streamer(u8 const* data, size_t size)
  105. : m_data_ptr(data)
  106. , m_size_remaining(size)
  107. {
  108. }
  109. template<typename T>
  110. bool read(T& value)
  111. {
  112. if (m_size_remaining < sizeof(T))
  113. return false;
  114. value = *((NetworkOrdered<T> const*)m_data_ptr);
  115. m_data_ptr += sizeof(T);
  116. m_size_remaining -= sizeof(T);
  117. return true;
  118. }
  119. bool read_bytes(u8* buffer, size_t count)
  120. {
  121. if (m_size_remaining < count)
  122. return false;
  123. memcpy(buffer, m_data_ptr, count);
  124. m_data_ptr += count;
  125. m_size_remaining -= count;
  126. return true;
  127. }
  128. bool wrap_bytes(ReadonlyBytes& buffer, size_t count)
  129. {
  130. if (m_size_remaining < count)
  131. return false;
  132. buffer = ReadonlyBytes { m_data_ptr, count };
  133. m_data_ptr += count;
  134. m_size_remaining -= count;
  135. return true;
  136. }
  137. bool at_end() const { return !m_size_remaining; }
  138. private:
  139. u8 const* m_data_ptr { nullptr };
  140. size_t m_size_remaining { 0 };
  141. };
  142. static bool process_chunk(Streamer&, PNGLoadingContext& context);
  143. union [[gnu::packed]] Pixel {
  144. ARGB32 rgba { 0 };
  145. u8 v[4];
  146. struct {
  147. u8 r;
  148. u8 g;
  149. u8 b;
  150. u8 a;
  151. };
  152. };
  153. static_assert(AssertSize<Pixel, 4>());
  154. static void unfilter_scanline(PNG::FilterType filter, Bytes scanline_data, ReadonlyBytes previous_scanlines_data, u8 bytes_per_complete_pixel)
  155. {
  156. VERIFY(filter != PNG::FilterType::None);
  157. switch (filter) {
  158. case PNG::FilterType::Sub:
  159. // This loop starts at bytes_per_complete_pixel because all bytes before that are
  160. // guaranteed to have no valid byte at index (i - bytes_per_complete pixel).
  161. // All such invalid byte indexes should be treated as 0, and adding 0 to the current
  162. // byte would do nothing, so the first bytes_per_complete_pixel bytes can instead
  163. // just be skipped.
  164. for (size_t i = bytes_per_complete_pixel; i < scanline_data.size(); ++i) {
  165. u8 left = scanline_data[i - bytes_per_complete_pixel];
  166. scanline_data[i] += left;
  167. }
  168. break;
  169. case PNG::FilterType::Up:
  170. for (size_t i = 0; i < scanline_data.size(); ++i) {
  171. u8 above = previous_scanlines_data[i];
  172. scanline_data[i] += above;
  173. }
  174. break;
  175. case PNG::FilterType::Average:
  176. for (size_t i = 0; i < scanline_data.size(); ++i) {
  177. u32 left = (i < bytes_per_complete_pixel) ? 0 : scanline_data[i - bytes_per_complete_pixel];
  178. u32 above = previous_scanlines_data[i];
  179. u8 average = (left + above) / 2;
  180. scanline_data[i] += average;
  181. }
  182. break;
  183. case PNG::FilterType::Paeth:
  184. for (size_t i = 0; i < scanline_data.size(); ++i) {
  185. u8 left = (i < bytes_per_complete_pixel) ? 0 : scanline_data[i - bytes_per_complete_pixel];
  186. u8 above = previous_scanlines_data[i];
  187. u8 upper_left = (i < bytes_per_complete_pixel) ? 0 : previous_scanlines_data[i - bytes_per_complete_pixel];
  188. i32 predictor = left + above - upper_left;
  189. u32 predictor_left = abs(predictor - left);
  190. u32 predictor_above = abs(predictor - above);
  191. u32 predictor_upper_left = abs(predictor - upper_left);
  192. u8 nearest;
  193. if (predictor_left <= predictor_above && predictor_left <= predictor_upper_left) {
  194. nearest = left;
  195. } else if (predictor_above <= predictor_upper_left) {
  196. nearest = above;
  197. } else {
  198. nearest = upper_left;
  199. }
  200. scanline_data[i] += nearest;
  201. }
  202. break;
  203. default:
  204. VERIFY_NOT_REACHED();
  205. }
  206. }
  207. template<typename T>
  208. ALWAYS_INLINE static void unpack_grayscale_without_alpha(PNGLoadingContext& context)
  209. {
  210. for (int y = 0; y < context.height; ++y) {
  211. auto* gray_values = reinterpret_cast<const T*>(context.scanlines[y].data.data());
  212. for (int i = 0; i < context.width; ++i) {
  213. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  214. pixel.r = gray_values[i];
  215. pixel.g = gray_values[i];
  216. pixel.b = gray_values[i];
  217. pixel.a = 0xff;
  218. }
  219. }
  220. }
  221. template<typename T>
  222. ALWAYS_INLINE static void unpack_grayscale_with_alpha(PNGLoadingContext& context)
  223. {
  224. for (int y = 0; y < context.height; ++y) {
  225. auto* tuples = reinterpret_cast<Tuple<T> const*>(context.scanlines[y].data.data());
  226. for (int i = 0; i < context.width; ++i) {
  227. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  228. pixel.r = tuples[i].gray;
  229. pixel.g = tuples[i].gray;
  230. pixel.b = tuples[i].gray;
  231. pixel.a = tuples[i].a;
  232. }
  233. }
  234. }
  235. template<typename T>
  236. ALWAYS_INLINE static void unpack_triplets_without_alpha(PNGLoadingContext& context)
  237. {
  238. for (int y = 0; y < context.height; ++y) {
  239. auto* triplets = reinterpret_cast<Triplet<T> const*>(context.scanlines[y].data.data());
  240. for (int i = 0; i < context.width; ++i) {
  241. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  242. pixel.r = triplets[i].r;
  243. pixel.g = triplets[i].g;
  244. pixel.b = triplets[i].b;
  245. pixel.a = 0xff;
  246. }
  247. }
  248. }
  249. template<typename T>
  250. ALWAYS_INLINE static void unpack_triplets_with_transparency_value(PNGLoadingContext& context, Triplet<T> transparency_value)
  251. {
  252. for (int y = 0; y < context.height; ++y) {
  253. auto* triplets = reinterpret_cast<Triplet<T> const*>(context.scanlines[y].data.data());
  254. for (int i = 0; i < context.width; ++i) {
  255. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  256. pixel.r = triplets[i].r;
  257. pixel.g = triplets[i].g;
  258. pixel.b = triplets[i].b;
  259. if (triplets[i] == transparency_value)
  260. pixel.a = 0x00;
  261. else
  262. pixel.a = 0xff;
  263. }
  264. }
  265. }
  266. NEVER_INLINE FLATTEN static ErrorOr<void> unfilter(PNGLoadingContext& context)
  267. {
  268. // First unfilter the scanlines:
  269. // FIXME: Instead of creating a separate buffer for the scanlines that need to be
  270. // mutated, the mutation could be done in place (if the data was non-const).
  271. size_t bytes_per_scanline = context.scanlines[0].data.size();
  272. size_t bytes_needed_for_all_unfiltered_scanlines = 0;
  273. for (int y = 0; y < context.height; ++y) {
  274. if (context.scanlines[y].filter != PNG::FilterType::None) {
  275. bytes_needed_for_all_unfiltered_scanlines += bytes_per_scanline;
  276. }
  277. }
  278. context.unfiltered_data = TRY(ByteBuffer::create_uninitialized(bytes_needed_for_all_unfiltered_scanlines));
  279. // From section 6.3 of http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html
  280. // "bpp is defined as the number of bytes per complete pixel, rounding up to one.
  281. // For example, for color type 2 with a bit depth of 16, bpp is equal to 6
  282. // (three samples, two bytes per sample); for color type 0 with a bit depth of 2,
  283. // bpp is equal to 1 (rounding up); for color type 4 with a bit depth of 16, bpp
  284. // is equal to 4 (two-byte grayscale sample, plus two-byte alpha sample)."
  285. u8 bytes_per_complete_pixel = (context.bit_depth + 7) / 8 * context.channels;
  286. u8 dummy_scanline_bytes[bytes_per_scanline];
  287. memset(dummy_scanline_bytes, 0, sizeof(dummy_scanline_bytes));
  288. auto previous_scanlines_data = ReadonlyBytes { dummy_scanline_bytes, sizeof(dummy_scanline_bytes) };
  289. for (int y = 0, data_start = 0; y < context.height; ++y) {
  290. if (context.scanlines[y].filter != PNG::FilterType::None) {
  291. auto scanline_data_slice = context.unfiltered_data.bytes().slice(data_start, bytes_per_scanline);
  292. // Copy the current values over and set the scanline's data to the to-be-mutated slice
  293. context.scanlines[y].data.copy_to(scanline_data_slice);
  294. context.scanlines[y].data = scanline_data_slice;
  295. unfilter_scanline(context.scanlines[y].filter, scanline_data_slice, previous_scanlines_data, bytes_per_complete_pixel);
  296. data_start += bytes_per_scanline;
  297. }
  298. previous_scanlines_data = context.scanlines[y].data;
  299. }
  300. // Now unpack the scanlines to RGBA:
  301. switch (context.color_type) {
  302. case PNG::ColorType::Greyscale:
  303. if (context.bit_depth == 8) {
  304. unpack_grayscale_without_alpha<u8>(context);
  305. } else if (context.bit_depth == 16) {
  306. unpack_grayscale_without_alpha<u16>(context);
  307. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  308. auto bit_depth_squared = context.bit_depth * context.bit_depth;
  309. auto pixels_per_byte = 8 / context.bit_depth;
  310. auto mask = (1 << context.bit_depth) - 1;
  311. for (int y = 0; y < context.height; ++y) {
  312. auto* gray_values = context.scanlines[y].data.data();
  313. for (int x = 0; x < context.width; ++x) {
  314. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (x % pixels_per_byte));
  315. auto value = (gray_values[x / pixels_per_byte] >> bit_offset) & mask;
  316. auto& pixel = (Pixel&)context.bitmap->scanline(y)[x];
  317. pixel.r = value * (0xff / bit_depth_squared);
  318. pixel.g = value * (0xff / bit_depth_squared);
  319. pixel.b = value * (0xff / bit_depth_squared);
  320. pixel.a = 0xff;
  321. }
  322. }
  323. } else {
  324. VERIFY_NOT_REACHED();
  325. }
  326. break;
  327. case PNG::ColorType::GreyscaleWithAlpha:
  328. if (context.bit_depth == 8) {
  329. unpack_grayscale_with_alpha<u8>(context);
  330. } else if (context.bit_depth == 16) {
  331. unpack_grayscale_with_alpha<u16>(context);
  332. } else {
  333. VERIFY_NOT_REACHED();
  334. }
  335. break;
  336. case PNG::ColorType::Truecolor:
  337. if (context.palette_transparency_data.size() == 6) {
  338. if (context.bit_depth == 8) {
  339. unpack_triplets_with_transparency_value<u8>(context, Triplet<u8> { context.palette_transparency_data[0], context.palette_transparency_data[2], context.palette_transparency_data[4] });
  340. } else if (context.bit_depth == 16) {
  341. u16 tr = context.palette_transparency_data[0] | context.palette_transparency_data[1] << 8;
  342. u16 tg = context.palette_transparency_data[2] | context.palette_transparency_data[3] << 8;
  343. u16 tb = context.palette_transparency_data[4] | context.palette_transparency_data[5] << 8;
  344. unpack_triplets_with_transparency_value<u16>(context, Triplet<u16> { tr, tg, tb });
  345. } else {
  346. VERIFY_NOT_REACHED();
  347. }
  348. } else {
  349. if (context.bit_depth == 8)
  350. unpack_triplets_without_alpha<u8>(context);
  351. else if (context.bit_depth == 16)
  352. unpack_triplets_without_alpha<u16>(context);
  353. else
  354. VERIFY_NOT_REACHED();
  355. }
  356. break;
  357. case PNG::ColorType::TruecolorWithAlpha:
  358. if (context.bit_depth == 8) {
  359. for (int y = 0; y < context.height; ++y) {
  360. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  361. }
  362. } else if (context.bit_depth == 16) {
  363. for (int y = 0; y < context.height; ++y) {
  364. auto* quartets = reinterpret_cast<Quartet<u16> const*>(context.scanlines[y].data.data());
  365. for (int i = 0; i < context.width; ++i) {
  366. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  367. pixel.r = quartets[i].r & 0xFF;
  368. pixel.g = quartets[i].g & 0xFF;
  369. pixel.b = quartets[i].b & 0xFF;
  370. pixel.a = quartets[i].a & 0xFF;
  371. }
  372. }
  373. } else {
  374. VERIFY_NOT_REACHED();
  375. }
  376. break;
  377. case PNG::ColorType::IndexedColor:
  378. if (context.bit_depth == 8) {
  379. for (int y = 0; y < context.height; ++y) {
  380. auto* palette_index = context.scanlines[y].data.data();
  381. for (int i = 0; i < context.width; ++i) {
  382. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  383. if (palette_index[i] >= context.palette_data.size())
  384. return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range");
  385. auto& color = context.palette_data.at((int)palette_index[i]);
  386. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u
  387. ? context.palette_transparency_data.data()[palette_index[i]]
  388. : 0xff;
  389. pixel.r = color.r;
  390. pixel.g = color.g;
  391. pixel.b = color.b;
  392. pixel.a = transparency;
  393. }
  394. }
  395. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  396. auto pixels_per_byte = 8 / context.bit_depth;
  397. auto mask = (1 << context.bit_depth) - 1;
  398. for (int y = 0; y < context.height; ++y) {
  399. auto* palette_indices = context.scanlines[y].data.data();
  400. for (int i = 0; i < context.width; ++i) {
  401. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (i % pixels_per_byte));
  402. auto palette_index = (palette_indices[i / pixels_per_byte] >> bit_offset) & mask;
  403. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  404. if ((size_t)palette_index >= context.palette_data.size())
  405. return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range");
  406. auto& color = context.palette_data.at(palette_index);
  407. auto transparency = context.palette_transparency_data.size() >= palette_index + 1u
  408. ? context.palette_transparency_data.data()[palette_index]
  409. : 0xff;
  410. pixel.r = color.r;
  411. pixel.g = color.g;
  412. pixel.b = color.b;
  413. pixel.a = transparency;
  414. }
  415. }
  416. } else {
  417. VERIFY_NOT_REACHED();
  418. }
  419. break;
  420. default:
  421. VERIFY_NOT_REACHED();
  422. break;
  423. }
  424. // Swap r and b values:
  425. for (int y = 0; y < context.height; ++y) {
  426. auto* pixels = (Pixel*)context.bitmap->scanline(y);
  427. for (int i = 0; i < context.bitmap->width(); ++i) {
  428. auto& x = pixels[i];
  429. swap(x.r, x.b);
  430. }
  431. }
  432. return {};
  433. }
  434. static bool decode_png_header(PNGLoadingContext& context)
  435. {
  436. if (context.state >= PNGLoadingContext::HeaderDecoded)
  437. return true;
  438. if (!context.data || context.data_size < sizeof(PNG::header)) {
  439. dbgln_if(PNG_DEBUG, "Missing PNG header");
  440. context.state = PNGLoadingContext::State::Error;
  441. return false;
  442. }
  443. if (memcmp(context.data, PNG::header.span().data(), sizeof(PNG::header)) != 0) {
  444. dbgln_if(PNG_DEBUG, "Invalid PNG header");
  445. context.state = PNGLoadingContext::State::Error;
  446. return false;
  447. }
  448. context.state = PNGLoadingContext::HeaderDecoded;
  449. return true;
  450. }
  451. static bool decode_png_size(PNGLoadingContext& context)
  452. {
  453. if (context.state >= PNGLoadingContext::SizeDecoded)
  454. return true;
  455. if (context.state < PNGLoadingContext::HeaderDecoded) {
  456. if (!decode_png_header(context))
  457. return false;
  458. }
  459. u8 const* data_ptr = context.data + sizeof(PNG::header);
  460. size_t data_remaining = context.data_size - sizeof(PNG::header);
  461. Streamer streamer(data_ptr, data_remaining);
  462. while (!streamer.at_end()) {
  463. if (!process_chunk(streamer, context)) {
  464. context.state = PNGLoadingContext::State::Error;
  465. return false;
  466. }
  467. if (context.width && context.height) {
  468. context.state = PNGLoadingContext::State::SizeDecoded;
  469. return true;
  470. }
  471. }
  472. return false;
  473. }
  474. static bool decode_png_chunks(PNGLoadingContext& context)
  475. {
  476. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  477. return true;
  478. if (context.state < PNGLoadingContext::HeaderDecoded) {
  479. if (!decode_png_header(context))
  480. return false;
  481. }
  482. u8 const* data_ptr = context.data + sizeof(PNG::header);
  483. int data_remaining = context.data_size - sizeof(PNG::header);
  484. context.compressed_data.ensure_capacity(context.data_size);
  485. Streamer streamer(data_ptr, data_remaining);
  486. while (!streamer.at_end()) {
  487. if (!process_chunk(streamer, context)) {
  488. // Ignore failed chunk and just consider chunk decoding being done.
  489. // decode_png_bitmap() will check whether we got all required ones anyway.
  490. break;
  491. }
  492. }
  493. context.state = PNGLoadingContext::State::ChunksDecoded;
  494. return true;
  495. }
  496. static ErrorOr<void> decode_png_bitmap_simple(PNGLoadingContext& context)
  497. {
  498. Streamer streamer(context.decompression_buffer->data(), context.decompression_buffer->size());
  499. for (int y = 0; y < context.height; ++y) {
  500. PNG::FilterType filter;
  501. if (!streamer.read(filter)) {
  502. context.state = PNGLoadingContext::State::Error;
  503. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  504. }
  505. if (to_underlying(filter) > 4) {
  506. context.state = PNGLoadingContext::State::Error;
  507. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
  508. }
  509. context.scanlines.append({ filter });
  510. auto& scanline_buffer = context.scanlines.last().data;
  511. auto row_size = context.compute_row_size_for_width(context.width);
  512. if (row_size.has_overflow())
  513. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
  514. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  515. context.state = PNGLoadingContext::State::Error;
  516. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  517. }
  518. }
  519. context.bitmap = TRY(Bitmap::try_create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  520. return unfilter(context);
  521. }
  522. static int adam7_height(PNGLoadingContext& context, int pass)
  523. {
  524. switch (pass) {
  525. case 1:
  526. return (context.height + 7) / 8;
  527. case 2:
  528. return (context.height + 7) / 8;
  529. case 3:
  530. return (context.height + 3) / 8;
  531. case 4:
  532. return (context.height + 3) / 4;
  533. case 5:
  534. return (context.height + 1) / 4;
  535. case 6:
  536. return (context.height + 1) / 2;
  537. case 7:
  538. return context.height / 2;
  539. default:
  540. VERIFY_NOT_REACHED();
  541. }
  542. }
  543. static int adam7_width(PNGLoadingContext& context, int pass)
  544. {
  545. switch (pass) {
  546. case 1:
  547. return (context.width + 7) / 8;
  548. case 2:
  549. return (context.width + 3) / 8;
  550. case 3:
  551. return (context.width + 3) / 4;
  552. case 4:
  553. return (context.width + 1) / 4;
  554. case 5:
  555. return (context.width + 1) / 2;
  556. case 6:
  557. return context.width / 2;
  558. case 7:
  559. return context.width;
  560. default:
  561. VERIFY_NOT_REACHED();
  562. }
  563. }
  564. // Index 0 unused (non-interlaced case)
  565. static int adam7_starty[8] = { 0, 0, 0, 4, 0, 2, 0, 1 };
  566. static int adam7_startx[8] = { 0, 0, 4, 0, 2, 0, 1, 0 };
  567. static int adam7_stepy[8] = { 1, 8, 8, 8, 4, 4, 2, 2 };
  568. static int adam7_stepx[8] = { 1, 8, 8, 4, 4, 2, 2, 1 };
  569. static ErrorOr<void> decode_adam7_pass(PNGLoadingContext& context, Streamer& streamer, int pass)
  570. {
  571. PNGLoadingContext subimage_context;
  572. subimage_context.width = adam7_width(context, pass);
  573. subimage_context.height = adam7_height(context, pass);
  574. subimage_context.channels = context.channels;
  575. subimage_context.color_type = context.color_type;
  576. subimage_context.palette_data = context.palette_data;
  577. subimage_context.palette_transparency_data = context.palette_transparency_data;
  578. subimage_context.bit_depth = context.bit_depth;
  579. subimage_context.filter_method = context.filter_method;
  580. // For small images, some passes might be empty
  581. if (!subimage_context.width || !subimage_context.height)
  582. return {};
  583. subimage_context.scanlines.clear_with_capacity();
  584. for (int y = 0; y < subimage_context.height; ++y) {
  585. PNG::FilterType filter;
  586. if (!streamer.read(filter)) {
  587. context.state = PNGLoadingContext::State::Error;
  588. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  589. }
  590. if (to_underlying(filter) > 4) {
  591. context.state = PNGLoadingContext::State::Error;
  592. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
  593. }
  594. subimage_context.scanlines.append({ filter });
  595. auto& scanline_buffer = subimage_context.scanlines.last().data;
  596. auto row_size = context.compute_row_size_for_width(subimage_context.width);
  597. if (row_size.has_overflow())
  598. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
  599. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  600. context.state = PNGLoadingContext::State::Error;
  601. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  602. }
  603. }
  604. subimage_context.bitmap = TRY(Bitmap::try_create(context.bitmap->format(), { subimage_context.width, subimage_context.height }));
  605. TRY(unfilter(subimage_context));
  606. // Copy the subimage data into the main image according to the pass pattern
  607. for (int y = 0, dy = adam7_starty[pass]; y < subimage_context.height && dy < context.height; ++y, dy += adam7_stepy[pass]) {
  608. for (int x = 0, dx = adam7_startx[pass]; x < subimage_context.width && dy < context.width; ++x, dx += adam7_stepx[pass]) {
  609. context.bitmap->set_pixel(dx, dy, subimage_context.bitmap->get_pixel(x, y));
  610. }
  611. }
  612. return {};
  613. }
  614. static ErrorOr<void> decode_png_adam7(PNGLoadingContext& context)
  615. {
  616. Streamer streamer(context.decompression_buffer->data(), context.decompression_buffer->size());
  617. context.bitmap = TRY(Bitmap::try_create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  618. for (int pass = 1; pass <= 7; ++pass)
  619. TRY(decode_adam7_pass(context, streamer, pass));
  620. return {};
  621. }
  622. static ErrorOr<void> decode_png_bitmap(PNGLoadingContext& context)
  623. {
  624. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  625. if (!decode_png_chunks(context))
  626. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  627. }
  628. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  629. return {};
  630. if (context.width == -1 || context.height == -1)
  631. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see an IHDR chunk.");
  632. if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty())
  633. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty.");
  634. auto result = Compress::Zlib::decompress_all(context.compressed_data.span());
  635. if (!result.has_value()) {
  636. context.state = PNGLoadingContext::State::Error;
  637. return Error::from_string_literal("PNGImageDecoderPlugin: Decompression failed");
  638. }
  639. context.decompression_buffer = &result.value();
  640. context.compressed_data.clear();
  641. context.scanlines.ensure_capacity(context.height);
  642. switch (context.interlace_method) {
  643. case PngInterlaceMethod::Null:
  644. TRY(decode_png_bitmap_simple(context));
  645. break;
  646. case PngInterlaceMethod::Adam7:
  647. TRY(decode_png_adam7(context));
  648. break;
  649. default:
  650. context.state = PNGLoadingContext::State::Error;
  651. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method");
  652. }
  653. context.decompression_buffer = nullptr;
  654. context.state = PNGLoadingContext::State::BitmapDecoded;
  655. return {};
  656. }
  657. static bool is_valid_compression_method(u8 compression_method)
  658. {
  659. return compression_method == 0;
  660. }
  661. static bool is_valid_filter_method(u8 filter_method)
  662. {
  663. return filter_method == 0;
  664. }
  665. static bool process_IHDR(ReadonlyBytes data, PNGLoadingContext& context)
  666. {
  667. if (data.size() < (int)sizeof(PNG_IHDR))
  668. return false;
  669. auto& ihdr = *(const PNG_IHDR*)data.data();
  670. if (ihdr.width > maximum_width_for_decoded_images || ihdr.height > maximum_height_for_decoded_images) {
  671. dbgln("This PNG is too large for comfort: {}x{}", (u32)ihdr.width, (u32)ihdr.height);
  672. return false;
  673. }
  674. if (!is_valid_compression_method(ihdr.compression_method)) {
  675. dbgln("PNG has invalid compression method {}", ihdr.compression_method);
  676. return false;
  677. }
  678. if (!is_valid_filter_method(ihdr.filter_method)) {
  679. dbgln("PNG has invalid filter method {}", ihdr.filter_method);
  680. return false;
  681. }
  682. context.width = ihdr.width;
  683. context.height = ihdr.height;
  684. context.bit_depth = ihdr.bit_depth;
  685. context.color_type = ihdr.color_type;
  686. context.compression_method = ihdr.compression_method;
  687. context.filter_method = ihdr.filter_method;
  688. context.interlace_method = ihdr.interlace_method;
  689. dbgln_if(PNG_DEBUG, "PNG: {}x{} ({} bpp)", context.width, context.height, context.bit_depth);
  690. dbgln_if(PNG_DEBUG, " Color type: {}", to_underlying(context.color_type));
  691. dbgln_if(PNG_DEBUG, "Compress Method: {}", context.compression_method);
  692. dbgln_if(PNG_DEBUG, " Filter Method: {}", context.filter_method);
  693. dbgln_if(PNG_DEBUG, " Interlace type: {}", context.interlace_method);
  694. if (context.interlace_method != PngInterlaceMethod::Null && context.interlace_method != PngInterlaceMethod::Adam7) {
  695. dbgln_if(PNG_DEBUG, "PNGLoader::process_IHDR: unknown interlace method: {}", context.interlace_method);
  696. return false;
  697. }
  698. switch (context.color_type) {
  699. case PNG::ColorType::Greyscale:
  700. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8 && context.bit_depth != 16)
  701. return false;
  702. context.channels = 1;
  703. break;
  704. case PNG::ColorType::GreyscaleWithAlpha:
  705. if (context.bit_depth != 8 && context.bit_depth != 16)
  706. return false;
  707. context.channels = 2;
  708. break;
  709. case PNG::ColorType::Truecolor:
  710. if (context.bit_depth != 8 && context.bit_depth != 16)
  711. return false;
  712. context.channels = 3;
  713. break;
  714. case PNG::ColorType::IndexedColor:
  715. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8)
  716. return false;
  717. context.channels = 1;
  718. break;
  719. case PNG::ColorType::TruecolorWithAlpha:
  720. if (context.bit_depth != 8 && context.bit_depth != 16)
  721. return false;
  722. context.channels = 4;
  723. break;
  724. default:
  725. return false;
  726. }
  727. return true;
  728. }
  729. static bool process_IDAT(ReadonlyBytes data, PNGLoadingContext& context)
  730. {
  731. context.compressed_data.append(data.data(), data.size());
  732. return true;
  733. }
  734. static bool process_PLTE(ReadonlyBytes data, PNGLoadingContext& context)
  735. {
  736. context.palette_data.append((PaletteEntry const*)data.data(), data.size() / 3);
  737. return true;
  738. }
  739. static bool process_tRNS(ReadonlyBytes data, PNGLoadingContext& context)
  740. {
  741. switch (context.color_type) {
  742. case PNG::ColorType::Greyscale:
  743. case PNG::ColorType::Truecolor:
  744. case PNG::ColorType::IndexedColor:
  745. context.palette_transparency_data.append(data.data(), data.size());
  746. break;
  747. default:
  748. break;
  749. }
  750. return true;
  751. }
  752. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  753. {
  754. u32 chunk_size;
  755. if (!streamer.read(chunk_size)) {
  756. dbgln_if(PNG_DEBUG, "Bail at chunk_size");
  757. return false;
  758. }
  759. u8 chunk_type[5];
  760. chunk_type[4] = '\0';
  761. if (!streamer.read_bytes(chunk_type, 4)) {
  762. dbgln_if(PNG_DEBUG, "Bail at chunk_type");
  763. return false;
  764. }
  765. ReadonlyBytes chunk_data;
  766. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  767. dbgln_if(PNG_DEBUG, "Bail at chunk_data");
  768. return false;
  769. }
  770. u32 chunk_crc;
  771. if (!streamer.read(chunk_crc)) {
  772. dbgln_if(PNG_DEBUG, "Bail at chunk_crc");
  773. return false;
  774. }
  775. dbgln_if(PNG_DEBUG, "Chunk type: '{}', size: {}, crc: {:x}", chunk_type, chunk_size, chunk_crc);
  776. if (!strcmp((char const*)chunk_type, "IHDR"))
  777. return process_IHDR(chunk_data, context);
  778. if (!strcmp((char const*)chunk_type, "IDAT"))
  779. return process_IDAT(chunk_data, context);
  780. if (!strcmp((char const*)chunk_type, "PLTE"))
  781. return process_PLTE(chunk_data, context);
  782. if (!strcmp((char const*)chunk_type, "tRNS"))
  783. return process_tRNS(chunk_data, context);
  784. return true;
  785. }
  786. PNGImageDecoderPlugin::PNGImageDecoderPlugin(u8 const* data, size_t size)
  787. {
  788. m_context = make<PNGLoadingContext>();
  789. m_context->data = data;
  790. m_context->data_size = size;
  791. }
  792. PNGImageDecoderPlugin::~PNGImageDecoderPlugin() = default;
  793. IntSize PNGImageDecoderPlugin::size()
  794. {
  795. if (m_context->state == PNGLoadingContext::State::Error)
  796. return {};
  797. if (m_context->state < PNGLoadingContext::State::SizeDecoded) {
  798. bool success = decode_png_size(*m_context);
  799. if (!success)
  800. return {};
  801. }
  802. return { m_context->width, m_context->height };
  803. }
  804. void PNGImageDecoderPlugin::set_volatile()
  805. {
  806. if (m_context->bitmap)
  807. m_context->bitmap->set_volatile();
  808. }
  809. bool PNGImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  810. {
  811. if (!m_context->bitmap)
  812. return false;
  813. return m_context->bitmap->set_nonvolatile(was_purged);
  814. }
  815. bool PNGImageDecoderPlugin::sniff()
  816. {
  817. return decode_png_header(*m_context);
  818. }
  819. bool PNGImageDecoderPlugin::is_animated()
  820. {
  821. return false;
  822. }
  823. size_t PNGImageDecoderPlugin::loop_count()
  824. {
  825. return 0;
  826. }
  827. size_t PNGImageDecoderPlugin::frame_count()
  828. {
  829. return 1;
  830. }
  831. ErrorOr<ImageFrameDescriptor> PNGImageDecoderPlugin::frame(size_t index)
  832. {
  833. if (index > 0)
  834. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid frame index");
  835. if (m_context->state == PNGLoadingContext::State::Error)
  836. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  837. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  838. // NOTE: This forces the chunk decoding to happen.
  839. TRY(decode_png_bitmap(*m_context));
  840. }
  841. VERIFY(m_context->bitmap);
  842. return ImageFrameDescriptor { m_context->bitmap, 0 };
  843. }
  844. }