PNGLoader.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  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/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/Vector.h>
  10. #include <LibCompress/Zlib.h>
  11. #include <LibGfx/ImageFormats/PNGLoader.h>
  12. #include <LibGfx/ImageFormats/PNGShared.h>
  13. #include <LibGfx/Painter.h>
  14. namespace Gfx {
  15. struct PNG_IHDR {
  16. NetworkOrdered<u32> width;
  17. NetworkOrdered<u32> height;
  18. u8 bit_depth { 0 };
  19. PNG::ColorType color_type { 0 };
  20. u8 compression_method { 0 };
  21. u8 filter_method { 0 };
  22. u8 interlace_method { 0 };
  23. };
  24. static_assert(AssertSize<PNG_IHDR, 13>());
  25. struct acTL_Chunk {
  26. NetworkOrdered<u32> num_frames;
  27. NetworkOrdered<u32> num_plays;
  28. };
  29. static_assert(AssertSize<acTL_Chunk, 8>());
  30. struct fcTL_Chunk {
  31. enum class DisposeOp : u8 {
  32. APNG_DISPOSE_OP_NONE = 0,
  33. APNG_DISPOSE_OP_BACKGROUND,
  34. APNG_DISPOSE_OP_PREVIOUS
  35. };
  36. enum class BlendOp : u8 {
  37. APNG_BLEND_OP_SOURCE = 0,
  38. APNG_BLEND_OP_OVER
  39. };
  40. NetworkOrdered<u32> sequence_number;
  41. NetworkOrdered<u32> width;
  42. NetworkOrdered<u32> height;
  43. NetworkOrdered<u32> x_offset;
  44. NetworkOrdered<u32> y_offset;
  45. NetworkOrdered<u16> delay_num;
  46. NetworkOrdered<u16> delay_den;
  47. DisposeOp dispose_op { DisposeOp::APNG_DISPOSE_OP_NONE };
  48. BlendOp blend_op { BlendOp::APNG_BLEND_OP_SOURCE };
  49. };
  50. static_assert(AssertSize<fcTL_Chunk, 26>());
  51. struct ChromaticitiesAndWhitepoint {
  52. NetworkOrdered<u32> white_point_x;
  53. NetworkOrdered<u32> white_point_y;
  54. NetworkOrdered<u32> red_x;
  55. NetworkOrdered<u32> red_y;
  56. NetworkOrdered<u32> green_x;
  57. NetworkOrdered<u32> green_y;
  58. NetworkOrdered<u32> blue_x;
  59. NetworkOrdered<u32> blue_y;
  60. };
  61. static_assert(AssertSize<ChromaticitiesAndWhitepoint, 32>());
  62. struct CodingIndependentCodePoints {
  63. u8 color_primaries;
  64. u8 transfer_function;
  65. u8 matrix_coefficients;
  66. u8 video_full_range_flag;
  67. };
  68. static_assert(AssertSize<CodingIndependentCodePoints, 4>());
  69. struct EmbeddedICCProfile {
  70. StringView profile_name;
  71. ReadonlyBytes compressed_data;
  72. };
  73. struct Scanline {
  74. PNG::FilterType filter;
  75. ReadonlyBytes data {};
  76. };
  77. struct [[gnu::packed]] PaletteEntry {
  78. u8 r;
  79. u8 g;
  80. u8 b;
  81. // u8 a;
  82. };
  83. template<typename T>
  84. struct [[gnu::packed]] Tuple {
  85. T gray;
  86. T a;
  87. };
  88. template<typename T>
  89. struct [[gnu::packed]] Triplet {
  90. T r;
  91. T g;
  92. T b;
  93. bool operator==(Triplet const& other) const = default;
  94. };
  95. template<typename T>
  96. struct [[gnu::packed]] Quartet {
  97. T r;
  98. T g;
  99. T b;
  100. T a;
  101. };
  102. enum PngInterlaceMethod {
  103. Null = 0,
  104. Adam7 = 1
  105. };
  106. enum RenderingIntent {
  107. Perceptual = 0,
  108. RelativeColorimetric = 1,
  109. Saturation = 2,
  110. AbsoluteColorimetric = 3,
  111. };
  112. struct AnimationFrame {
  113. fcTL_Chunk const& fcTL;
  114. RefPtr<Bitmap> bitmap;
  115. Vector<u8> compressed_data;
  116. AnimationFrame(fcTL_Chunk const& fcTL)
  117. : fcTL(fcTL)
  118. {
  119. }
  120. u32 duration_ms() const
  121. {
  122. u32 num = fcTL.delay_num;
  123. if (num == 0)
  124. return 1;
  125. u32 denom = fcTL.delay_den != 0 ? static_cast<u32>(fcTL.delay_den) : 100u;
  126. return (num * 1000) / denom;
  127. }
  128. IntRect rect() const
  129. {
  130. return { fcTL.x_offset, fcTL.y_offset, fcTL.width, fcTL.height };
  131. }
  132. };
  133. struct PNGLoadingContext {
  134. enum State {
  135. NotDecoded = 0,
  136. Error,
  137. HeaderDecoded,
  138. SizeDecoded,
  139. ImageDataChunkDecoded,
  140. ChunksDecoded,
  141. BitmapDecoded,
  142. };
  143. State state { State::NotDecoded };
  144. u8 const* data { nullptr };
  145. u8 const* data_current_ptr { nullptr };
  146. size_t data_size { 0 };
  147. int width { -1 };
  148. int height { -1 };
  149. u8 bit_depth { 0 };
  150. PNG::ColorType color_type { 0 };
  151. u8 compression_method { 0 };
  152. u8 filter_method { 0 };
  153. u8 interlace_method { 0 };
  154. u8 channels { 0 };
  155. u32 animation_next_expected_seq { 0 };
  156. u32 animation_next_frame_to_render { 0 };
  157. u32 animation_frame_count { 0 };
  158. u32 animation_loop_count { 0 };
  159. Optional<u32> last_completed_animation_frame_index;
  160. bool is_first_idat_part_of_animation { false };
  161. bool has_seen_zlib_header { false };
  162. bool has_seen_iend { false };
  163. bool has_seen_idat_chunk { false };
  164. bool has_seen_actl_chunk_before_idat { false };
  165. bool has_alpha() const { return to_underlying(color_type) & 4 || palette_transparency_data.size() > 0; }
  166. Vector<Scanline> scanlines;
  167. ByteBuffer unfiltered_data;
  168. RefPtr<Gfx::Bitmap> bitmap;
  169. Vector<u8> compressed_data;
  170. Vector<PaletteEntry> palette_data;
  171. Vector<u8> palette_transparency_data;
  172. Vector<AnimationFrame> animation_frames;
  173. Optional<ChromaticitiesAndWhitepoint> chromaticities_and_whitepoint;
  174. Optional<CodingIndependentCodePoints> coding_independent_code_points;
  175. Optional<u32> gamma;
  176. Optional<EmbeddedICCProfile> embedded_icc_profile;
  177. Optional<ByteBuffer> decompressed_icc_profile;
  178. Optional<RenderingIntent> sRGB_rendering_intent;
  179. Checked<int> compute_row_size_for_width(int width)
  180. {
  181. Checked<int> row_size = width;
  182. row_size *= channels;
  183. row_size *= bit_depth;
  184. row_size += 7;
  185. row_size /= 8;
  186. if (row_size.has_overflow()) {
  187. dbgln("PNG too large, integer overflow while computing row size");
  188. state = State::Error;
  189. }
  190. return row_size;
  191. }
  192. PNGLoadingContext create_subimage_context(int width, int height)
  193. {
  194. PNGLoadingContext subimage_context;
  195. subimage_context.state = State::ChunksDecoded;
  196. subimage_context.width = width;
  197. subimage_context.height = height;
  198. subimage_context.channels = channels;
  199. subimage_context.color_type = color_type;
  200. subimage_context.palette_data = palette_data;
  201. subimage_context.palette_transparency_data = palette_transparency_data;
  202. subimage_context.bit_depth = bit_depth;
  203. subimage_context.filter_method = filter_method;
  204. return subimage_context;
  205. }
  206. };
  207. class Streamer {
  208. public:
  209. Streamer(u8 const* data, size_t size)
  210. : m_data_ptr(data)
  211. , m_size_remaining(size)
  212. {
  213. }
  214. template<typename T>
  215. bool read(T& value)
  216. {
  217. if (m_size_remaining < sizeof(T))
  218. return false;
  219. value = *((NetworkOrdered<T> const*)m_data_ptr);
  220. m_data_ptr += sizeof(T);
  221. m_size_remaining -= sizeof(T);
  222. return true;
  223. }
  224. bool read_bytes(u8* buffer, size_t count)
  225. {
  226. if (m_size_remaining < count)
  227. return false;
  228. memcpy(buffer, m_data_ptr, count);
  229. m_data_ptr += count;
  230. m_size_remaining -= count;
  231. return true;
  232. }
  233. bool wrap_bytes(ReadonlyBytes& buffer, size_t count)
  234. {
  235. if (m_size_remaining < count)
  236. return false;
  237. buffer = ReadonlyBytes { m_data_ptr, count };
  238. m_data_ptr += count;
  239. m_size_remaining -= count;
  240. return true;
  241. }
  242. u8 const* current_data_ptr() const { return m_data_ptr; }
  243. bool at_end() const { return !m_size_remaining; }
  244. private:
  245. u8 const* m_data_ptr { nullptr };
  246. size_t m_size_remaining { 0 };
  247. };
  248. static bool process_chunk(Streamer&, PNGLoadingContext& context);
  249. union [[gnu::packed]] Pixel {
  250. ARGB32 rgba { 0 };
  251. u8 v[4];
  252. struct {
  253. u8 r;
  254. u8 g;
  255. u8 b;
  256. u8 a;
  257. };
  258. };
  259. static_assert(AssertSize<Pixel, 4>());
  260. static void unfilter_scanline(PNG::FilterType filter, Bytes scanline_data, ReadonlyBytes previous_scanlines_data, u8 bytes_per_complete_pixel)
  261. {
  262. VERIFY(filter != PNG::FilterType::None);
  263. switch (filter) {
  264. case PNG::FilterType::Sub:
  265. // This loop starts at bytes_per_complete_pixel because all bytes before that are
  266. // guaranteed to have no valid byte at index (i - bytes_per_complete pixel).
  267. // All such invalid byte indexes should be treated as 0, and adding 0 to the current
  268. // byte would do nothing, so the first bytes_per_complete_pixel bytes can instead
  269. // just be skipped.
  270. for (size_t i = bytes_per_complete_pixel; i < scanline_data.size(); ++i) {
  271. u8 left = scanline_data[i - bytes_per_complete_pixel];
  272. scanline_data[i] += left;
  273. }
  274. break;
  275. case PNG::FilterType::Up:
  276. for (size_t i = 0; i < scanline_data.size(); ++i) {
  277. u8 above = previous_scanlines_data[i];
  278. scanline_data[i] += above;
  279. }
  280. break;
  281. case PNG::FilterType::Average:
  282. for (size_t i = 0; i < scanline_data.size(); ++i) {
  283. u32 left = (i < bytes_per_complete_pixel) ? 0 : scanline_data[i - bytes_per_complete_pixel];
  284. u32 above = previous_scanlines_data[i];
  285. u8 average = (left + above) / 2;
  286. scanline_data[i] += average;
  287. }
  288. break;
  289. case PNG::FilterType::Paeth:
  290. for (size_t i = 0; i < scanline_data.size(); ++i) {
  291. u8 left = (i < bytes_per_complete_pixel) ? 0 : scanline_data[i - bytes_per_complete_pixel];
  292. u8 above = previous_scanlines_data[i];
  293. u8 upper_left = (i < bytes_per_complete_pixel) ? 0 : previous_scanlines_data[i - bytes_per_complete_pixel];
  294. i32 predictor = left + above - upper_left;
  295. u32 predictor_left = abs(predictor - left);
  296. u32 predictor_above = abs(predictor - above);
  297. u32 predictor_upper_left = abs(predictor - upper_left);
  298. u8 nearest;
  299. if (predictor_left <= predictor_above && predictor_left <= predictor_upper_left) {
  300. nearest = left;
  301. } else if (predictor_above <= predictor_upper_left) {
  302. nearest = above;
  303. } else {
  304. nearest = upper_left;
  305. }
  306. scanline_data[i] += nearest;
  307. }
  308. break;
  309. default:
  310. VERIFY_NOT_REACHED();
  311. }
  312. }
  313. template<typename T>
  314. ALWAYS_INLINE static void unpack_grayscale_without_alpha(PNGLoadingContext& context)
  315. {
  316. for (int y = 0; y < context.height; ++y) {
  317. auto* gray_values = reinterpret_cast<T const*>(context.scanlines[y].data.data());
  318. for (int i = 0; i < context.width; ++i) {
  319. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  320. pixel.r = gray_values[i];
  321. pixel.g = gray_values[i];
  322. pixel.b = gray_values[i];
  323. pixel.a = 0xff;
  324. }
  325. }
  326. }
  327. template<typename T>
  328. ALWAYS_INLINE static void unpack_grayscale_with_alpha(PNGLoadingContext& context)
  329. {
  330. for (int y = 0; y < context.height; ++y) {
  331. auto* tuples = reinterpret_cast<Tuple<T> const*>(context.scanlines[y].data.data());
  332. for (int i = 0; i < context.width; ++i) {
  333. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  334. pixel.r = tuples[i].gray;
  335. pixel.g = tuples[i].gray;
  336. pixel.b = tuples[i].gray;
  337. pixel.a = tuples[i].a;
  338. }
  339. }
  340. }
  341. template<typename T>
  342. ALWAYS_INLINE static void unpack_triplets_without_alpha(PNGLoadingContext& context)
  343. {
  344. for (int y = 0; y < context.height; ++y) {
  345. auto* triplets = reinterpret_cast<Triplet<T> const*>(context.scanlines[y].data.data());
  346. for (int i = 0; i < context.width; ++i) {
  347. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  348. pixel.r = triplets[i].r;
  349. pixel.g = triplets[i].g;
  350. pixel.b = triplets[i].b;
  351. pixel.a = 0xff;
  352. }
  353. }
  354. }
  355. template<typename T>
  356. ALWAYS_INLINE static void unpack_triplets_with_transparency_value(PNGLoadingContext& context, Triplet<T> transparency_value)
  357. {
  358. for (int y = 0; y < context.height; ++y) {
  359. auto* triplets = reinterpret_cast<Triplet<T> const*>(context.scanlines[y].data.data());
  360. for (int i = 0; i < context.width; ++i) {
  361. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  362. pixel.r = triplets[i].r;
  363. pixel.g = triplets[i].g;
  364. pixel.b = triplets[i].b;
  365. if (triplets[i] == transparency_value)
  366. pixel.a = 0x00;
  367. else
  368. pixel.a = 0xff;
  369. }
  370. }
  371. }
  372. NEVER_INLINE FLATTEN static ErrorOr<void> unfilter(PNGLoadingContext& context)
  373. {
  374. // First unfilter the scanlines:
  375. // FIXME: Instead of creating a separate buffer for the scanlines that need to be
  376. // mutated, the mutation could be done in place (if the data was non-const).
  377. size_t bytes_per_scanline = context.scanlines[0].data.size();
  378. size_t bytes_needed_for_all_unfiltered_scanlines = 0;
  379. for (int y = 0; y < context.height; ++y) {
  380. if (context.scanlines[y].filter != PNG::FilterType::None) {
  381. bytes_needed_for_all_unfiltered_scanlines += bytes_per_scanline;
  382. }
  383. }
  384. context.unfiltered_data = TRY(ByteBuffer::create_uninitialized(bytes_needed_for_all_unfiltered_scanlines));
  385. // From section 6.3 of http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html
  386. // "bpp is defined as the number of bytes per complete pixel, rounding up to one.
  387. // For example, for color type 2 with a bit depth of 16, bpp is equal to 6
  388. // (three samples, two bytes per sample); for color type 0 with a bit depth of 2,
  389. // bpp is equal to 1 (rounding up); for color type 4 with a bit depth of 16, bpp
  390. // is equal to 4 (two-byte grayscale sample, plus two-byte alpha sample)."
  391. u8 bytes_per_complete_pixel = (context.bit_depth + 7) / 8 * context.channels;
  392. u8 dummy_scanline_bytes[bytes_per_scanline];
  393. memset(dummy_scanline_bytes, 0, sizeof(dummy_scanline_bytes));
  394. auto previous_scanlines_data = ReadonlyBytes { dummy_scanline_bytes, sizeof(dummy_scanline_bytes) };
  395. for (int y = 0, data_start = 0; y < context.height; ++y) {
  396. if (context.scanlines[y].filter != PNG::FilterType::None) {
  397. auto scanline_data_slice = context.unfiltered_data.bytes().slice(data_start, bytes_per_scanline);
  398. // Copy the current values over and set the scanline's data to the to-be-mutated slice
  399. context.scanlines[y].data.copy_to(scanline_data_slice);
  400. context.scanlines[y].data = scanline_data_slice;
  401. unfilter_scanline(context.scanlines[y].filter, scanline_data_slice, previous_scanlines_data, bytes_per_complete_pixel);
  402. data_start += bytes_per_scanline;
  403. }
  404. previous_scanlines_data = context.scanlines[y].data;
  405. }
  406. // Now unpack the scanlines to RGBA:
  407. switch (context.color_type) {
  408. case PNG::ColorType::Greyscale:
  409. if (context.bit_depth == 8) {
  410. unpack_grayscale_without_alpha<u8>(context);
  411. } else if (context.bit_depth == 16) {
  412. unpack_grayscale_without_alpha<u16>(context);
  413. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  414. auto bit_depth_squared = context.bit_depth * context.bit_depth;
  415. auto pixels_per_byte = 8 / context.bit_depth;
  416. auto mask = (1 << context.bit_depth) - 1;
  417. for (int y = 0; y < context.height; ++y) {
  418. auto* gray_values = context.scanlines[y].data.data();
  419. for (int x = 0; x < context.width; ++x) {
  420. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (x % pixels_per_byte));
  421. auto value = (gray_values[x / pixels_per_byte] >> bit_offset) & mask;
  422. auto& pixel = (Pixel&)context.bitmap->scanline(y)[x];
  423. pixel.r = value * (0xff / bit_depth_squared);
  424. pixel.g = value * (0xff / bit_depth_squared);
  425. pixel.b = value * (0xff / bit_depth_squared);
  426. pixel.a = 0xff;
  427. }
  428. }
  429. } else {
  430. VERIFY_NOT_REACHED();
  431. }
  432. break;
  433. case PNG::ColorType::GreyscaleWithAlpha:
  434. if (context.bit_depth == 8) {
  435. unpack_grayscale_with_alpha<u8>(context);
  436. } else if (context.bit_depth == 16) {
  437. unpack_grayscale_with_alpha<u16>(context);
  438. } else {
  439. VERIFY_NOT_REACHED();
  440. }
  441. break;
  442. case PNG::ColorType::Truecolor:
  443. if (context.palette_transparency_data.size() == 6) {
  444. if (context.bit_depth == 8) {
  445. unpack_triplets_with_transparency_value<u8>(context, Triplet<u8> { context.palette_transparency_data[0], context.palette_transparency_data[2], context.palette_transparency_data[4] });
  446. } else if (context.bit_depth == 16) {
  447. u16 tr = context.palette_transparency_data[0] | context.palette_transparency_data[1] << 8;
  448. u16 tg = context.palette_transparency_data[2] | context.palette_transparency_data[3] << 8;
  449. u16 tb = context.palette_transparency_data[4] | context.palette_transparency_data[5] << 8;
  450. unpack_triplets_with_transparency_value<u16>(context, Triplet<u16> { tr, tg, tb });
  451. } else {
  452. VERIFY_NOT_REACHED();
  453. }
  454. } else {
  455. if (context.bit_depth == 8)
  456. unpack_triplets_without_alpha<u8>(context);
  457. else if (context.bit_depth == 16)
  458. unpack_triplets_without_alpha<u16>(context);
  459. else
  460. VERIFY_NOT_REACHED();
  461. }
  462. break;
  463. case PNG::ColorType::TruecolorWithAlpha:
  464. if (context.bit_depth == 8) {
  465. for (int y = 0; y < context.height; ++y) {
  466. memcpy(context.bitmap->scanline(y), context.scanlines[y].data.data(), context.scanlines[y].data.size());
  467. }
  468. } else if (context.bit_depth == 16) {
  469. for (int y = 0; y < context.height; ++y) {
  470. auto* quartets = reinterpret_cast<Quartet<u16> const*>(context.scanlines[y].data.data());
  471. for (int i = 0; i < context.width; ++i) {
  472. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  473. pixel.r = quartets[i].r & 0xFF;
  474. pixel.g = quartets[i].g & 0xFF;
  475. pixel.b = quartets[i].b & 0xFF;
  476. pixel.a = quartets[i].a & 0xFF;
  477. }
  478. }
  479. } else {
  480. VERIFY_NOT_REACHED();
  481. }
  482. break;
  483. case PNG::ColorType::IndexedColor:
  484. if (context.bit_depth == 8) {
  485. for (int y = 0; y < context.height; ++y) {
  486. auto* palette_index = context.scanlines[y].data.data();
  487. for (int i = 0; i < context.width; ++i) {
  488. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  489. if (palette_index[i] >= context.palette_data.size())
  490. return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range");
  491. auto& color = context.palette_data.at((int)palette_index[i]);
  492. auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u
  493. ? context.palette_transparency_data.data()[palette_index[i]]
  494. : 0xff;
  495. pixel.r = color.r;
  496. pixel.g = color.g;
  497. pixel.b = color.b;
  498. pixel.a = transparency;
  499. }
  500. }
  501. } else if (context.bit_depth == 1 || context.bit_depth == 2 || context.bit_depth == 4) {
  502. auto pixels_per_byte = 8 / context.bit_depth;
  503. auto mask = (1 << context.bit_depth) - 1;
  504. for (int y = 0; y < context.height; ++y) {
  505. auto* palette_indices = context.scanlines[y].data.data();
  506. for (int i = 0; i < context.width; ++i) {
  507. auto bit_offset = (8 - context.bit_depth) - (context.bit_depth * (i % pixels_per_byte));
  508. auto palette_index = (palette_indices[i / pixels_per_byte] >> bit_offset) & mask;
  509. auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
  510. if ((size_t)palette_index >= context.palette_data.size())
  511. return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range");
  512. auto& color = context.palette_data.at(palette_index);
  513. auto transparency = context.palette_transparency_data.size() >= palette_index + 1u
  514. ? context.palette_transparency_data.data()[palette_index]
  515. : 0xff;
  516. pixel.r = color.r;
  517. pixel.g = color.g;
  518. pixel.b = color.b;
  519. pixel.a = transparency;
  520. }
  521. }
  522. } else {
  523. VERIFY_NOT_REACHED();
  524. }
  525. break;
  526. default:
  527. VERIFY_NOT_REACHED();
  528. break;
  529. }
  530. // Swap r and b values:
  531. for (int y = 0; y < context.height; ++y) {
  532. auto* pixels = (Pixel*)context.bitmap->scanline(y);
  533. for (int i = 0; i < context.bitmap->width(); ++i) {
  534. auto& x = pixels[i];
  535. swap(x.r, x.b);
  536. }
  537. }
  538. return {};
  539. }
  540. static bool decode_png_header(PNGLoadingContext& context)
  541. {
  542. if (context.state >= PNGLoadingContext::HeaderDecoded)
  543. return true;
  544. if (!context.data || context.data_size < sizeof(PNG::header)) {
  545. dbgln_if(PNG_DEBUG, "Missing PNG header");
  546. context.state = PNGLoadingContext::State::Error;
  547. return false;
  548. }
  549. if (memcmp(context.data, PNG::header.span().data(), sizeof(PNG::header)) != 0) {
  550. dbgln_if(PNG_DEBUG, "Invalid PNG header");
  551. context.state = PNGLoadingContext::State::Error;
  552. return false;
  553. }
  554. context.data_current_ptr = context.data + sizeof(PNG::header);
  555. context.state = PNGLoadingContext::HeaderDecoded;
  556. return true;
  557. }
  558. static bool decode_png_size(PNGLoadingContext& context)
  559. {
  560. if (context.state >= PNGLoadingContext::SizeDecoded)
  561. return true;
  562. if (context.state < PNGLoadingContext::HeaderDecoded) {
  563. if (!decode_png_header(context))
  564. return false;
  565. }
  566. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  567. Streamer streamer(context.data_current_ptr, data_remaining);
  568. while (!streamer.at_end() && !context.has_seen_iend) {
  569. if (!process_chunk(streamer, context)) {
  570. context.state = PNGLoadingContext::State::Error;
  571. return false;
  572. }
  573. context.data_current_ptr = streamer.current_data_ptr();
  574. if (context.width && context.height) {
  575. context.state = PNGLoadingContext::State::SizeDecoded;
  576. return true;
  577. }
  578. }
  579. return false;
  580. }
  581. static bool decode_png_image_data_chunk(PNGLoadingContext& context)
  582. {
  583. if (context.state >= PNGLoadingContext::ImageDataChunkDecoded)
  584. return true;
  585. if (context.state < PNGLoadingContext::SizeDecoded) {
  586. if (!decode_png_size(context))
  587. return false;
  588. }
  589. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  590. Streamer streamer(context.data_current_ptr, data_remaining);
  591. while (!streamer.at_end() && !context.has_seen_iend) {
  592. if (!process_chunk(streamer, context)) {
  593. context.state = PNGLoadingContext::State::Error;
  594. return false;
  595. }
  596. context.data_current_ptr = streamer.current_data_ptr();
  597. if (context.state >= PNGLoadingContext::State::ImageDataChunkDecoded)
  598. return true;
  599. }
  600. return false;
  601. }
  602. static bool decode_png_animation_data_chunks(PNGLoadingContext& context, u32 requested_animation_frame_index)
  603. {
  604. if (context.state >= PNGLoadingContext::ImageDataChunkDecoded) {
  605. if (context.last_completed_animation_frame_index.has_value()) {
  606. if (requested_animation_frame_index <= context.last_completed_animation_frame_index.value())
  607. return true;
  608. }
  609. } else if (!decode_png_image_data_chunk(context)) {
  610. return false;
  611. }
  612. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  613. Streamer streamer(context.data_current_ptr, data_remaining);
  614. while (!streamer.at_end() && !context.has_seen_iend) {
  615. if (!process_chunk(streamer, context)) {
  616. context.state = PNGLoadingContext::State::Error;
  617. return false;
  618. }
  619. context.data_current_ptr = streamer.current_data_ptr();
  620. if (context.last_completed_animation_frame_index.has_value()) {
  621. if (requested_animation_frame_index <= context.last_completed_animation_frame_index.value())
  622. break;
  623. }
  624. }
  625. if (!context.last_completed_animation_frame_index.has_value())
  626. return false;
  627. return requested_animation_frame_index <= context.last_completed_animation_frame_index.value();
  628. }
  629. static bool decode_png_chunks(PNGLoadingContext& context)
  630. {
  631. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  632. return true;
  633. if (context.state < PNGLoadingContext::HeaderDecoded) {
  634. if (!decode_png_header(context))
  635. return false;
  636. }
  637. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  638. context.compressed_data.ensure_capacity(context.data_size);
  639. Streamer streamer(context.data_current_ptr, data_remaining);
  640. while (!streamer.at_end() && !context.has_seen_iend) {
  641. if (!process_chunk(streamer, context)) {
  642. // Ignore failed chunk and just consider chunk decoding being done.
  643. // decode_png_bitmap() will check whether we got all required ones anyway.
  644. break;
  645. }
  646. context.data_current_ptr = streamer.current_data_ptr();
  647. }
  648. context.state = PNGLoadingContext::State::ChunksDecoded;
  649. return true;
  650. }
  651. static ErrorOr<void> decode_png_bitmap_simple(PNGLoadingContext& context, ByteBuffer& decompression_buffer)
  652. {
  653. Streamer streamer(decompression_buffer.data(), decompression_buffer.size());
  654. for (int y = 0; y < context.height; ++y) {
  655. PNG::FilterType filter;
  656. if (!streamer.read(filter)) {
  657. context.state = PNGLoadingContext::State::Error;
  658. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  659. }
  660. if (to_underlying(filter) > 4) {
  661. context.state = PNGLoadingContext::State::Error;
  662. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
  663. }
  664. context.scanlines.append({ filter });
  665. auto& scanline_buffer = context.scanlines.last().data;
  666. auto row_size = context.compute_row_size_for_width(context.width);
  667. if (row_size.has_overflow())
  668. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
  669. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  670. context.state = PNGLoadingContext::State::Error;
  671. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  672. }
  673. }
  674. context.bitmap = TRY(Bitmap::create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  675. return unfilter(context);
  676. }
  677. static int adam7_height(PNGLoadingContext& context, int pass)
  678. {
  679. switch (pass) {
  680. case 1:
  681. return (context.height + 7) / 8;
  682. case 2:
  683. return (context.height + 7) / 8;
  684. case 3:
  685. return (context.height + 3) / 8;
  686. case 4:
  687. return (context.height + 3) / 4;
  688. case 5:
  689. return (context.height + 1) / 4;
  690. case 6:
  691. return (context.height + 1) / 2;
  692. case 7:
  693. return context.height / 2;
  694. default:
  695. VERIFY_NOT_REACHED();
  696. }
  697. }
  698. static int adam7_width(PNGLoadingContext& context, int pass)
  699. {
  700. switch (pass) {
  701. case 1:
  702. return (context.width + 7) / 8;
  703. case 2:
  704. return (context.width + 3) / 8;
  705. case 3:
  706. return (context.width + 3) / 4;
  707. case 4:
  708. return (context.width + 1) / 4;
  709. case 5:
  710. return (context.width + 1) / 2;
  711. case 6:
  712. return context.width / 2;
  713. case 7:
  714. return context.width;
  715. default:
  716. VERIFY_NOT_REACHED();
  717. }
  718. }
  719. // Index 0 unused (non-interlaced case)
  720. static int adam7_starty[8] = { 0, 0, 0, 4, 0, 2, 0, 1 };
  721. static int adam7_startx[8] = { 0, 0, 4, 0, 2, 0, 1, 0 };
  722. static int adam7_stepy[8] = { 1, 8, 8, 8, 4, 4, 2, 2 };
  723. static int adam7_stepx[8] = { 1, 8, 8, 4, 4, 2, 2, 1 };
  724. static ErrorOr<void> decode_adam7_pass(PNGLoadingContext& context, Streamer& streamer, int pass)
  725. {
  726. auto subimage_context = context.create_subimage_context(adam7_width(context, pass), adam7_height(context, pass));
  727. // For small images, some passes might be empty
  728. if (!subimage_context.width || !subimage_context.height)
  729. return {};
  730. for (int y = 0; y < subimage_context.height; ++y) {
  731. PNG::FilterType filter;
  732. if (!streamer.read(filter)) {
  733. context.state = PNGLoadingContext::State::Error;
  734. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  735. }
  736. if (to_underlying(filter) > 4) {
  737. context.state = PNGLoadingContext::State::Error;
  738. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
  739. }
  740. subimage_context.scanlines.append({ filter });
  741. auto& scanline_buffer = subimage_context.scanlines.last().data;
  742. auto row_size = context.compute_row_size_for_width(subimage_context.width);
  743. if (row_size.has_overflow())
  744. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
  745. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  746. context.state = PNGLoadingContext::State::Error;
  747. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  748. }
  749. }
  750. subimage_context.bitmap = TRY(Bitmap::create(context.bitmap->format(), { subimage_context.width, subimage_context.height }));
  751. TRY(unfilter(subimage_context));
  752. // Copy the subimage data into the main image according to the pass pattern
  753. for (int y = 0, dy = adam7_starty[pass]; y < subimage_context.height && dy < context.height; ++y, dy += adam7_stepy[pass]) {
  754. for (int x = 0, dx = adam7_startx[pass]; x < subimage_context.width && dx < context.width; ++x, dx += adam7_stepx[pass]) {
  755. context.bitmap->set_pixel(dx, dy, subimage_context.bitmap->get_pixel(x, y));
  756. }
  757. }
  758. return {};
  759. }
  760. static ErrorOr<void> decode_png_adam7(PNGLoadingContext& context, ByteBuffer& decompression_buffer)
  761. {
  762. Streamer streamer(decompression_buffer.data(), decompression_buffer.size());
  763. context.bitmap = TRY(Bitmap::create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  764. for (int pass = 1; pass <= 7; ++pass)
  765. TRY(decode_adam7_pass(context, streamer, pass));
  766. return {};
  767. }
  768. static ErrorOr<void> decode_png_bitmap(PNGLoadingContext& context)
  769. {
  770. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  771. if (!decode_png_chunks(context))
  772. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  773. }
  774. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  775. return {};
  776. if (context.width == -1 || context.height == -1)
  777. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see an IHDR chunk.");
  778. if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty())
  779. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty.");
  780. auto result = Compress::ZlibDecompressor::decompress_all(context.compressed_data.span());
  781. if (!result.has_value()) {
  782. context.state = PNGLoadingContext::State::Error;
  783. return Error::from_string_literal("PNGImageDecoderPlugin: Decompression failed");
  784. }
  785. auto& decompression_buffer = result.value();
  786. context.compressed_data.clear();
  787. context.scanlines.ensure_capacity(context.height);
  788. switch (context.interlace_method) {
  789. case PngInterlaceMethod::Null:
  790. TRY(decode_png_bitmap_simple(context, decompression_buffer));
  791. break;
  792. case PngInterlaceMethod::Adam7:
  793. TRY(decode_png_adam7(context, decompression_buffer));
  794. break;
  795. default:
  796. context.state = PNGLoadingContext::State::Error;
  797. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method");
  798. }
  799. context.state = PNGLoadingContext::State::BitmapDecoded;
  800. return {};
  801. }
  802. static ErrorOr<RefPtr<Bitmap>> decode_png_animation_frame_bitmap(PNGLoadingContext& context, AnimationFrame& animation_frame)
  803. {
  804. if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty())
  805. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty.");
  806. VERIFY(!animation_frame.bitmap);
  807. auto frame_rect = animation_frame.rect();
  808. auto frame_context = context.create_subimage_context(frame_rect.width(), frame_rect.height());
  809. auto result = Compress::ZlibDecompressor::decompress_all(animation_frame.compressed_data.span());
  810. if (!result.has_value())
  811. return Error::from_string_literal("PNGImageDecoderPlugin: Decompression of animation frame failed");
  812. auto& decompression_buffer = result.value();
  813. frame_context.compressed_data.clear();
  814. frame_context.scanlines.ensure_capacity(frame_context.height);
  815. switch (context.interlace_method) {
  816. case PngInterlaceMethod::Null:
  817. TRY(decode_png_bitmap_simple(frame_context, decompression_buffer));
  818. break;
  819. case PngInterlaceMethod::Adam7:
  820. TRY(decode_png_adam7(frame_context, decompression_buffer));
  821. break;
  822. default:
  823. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method");
  824. }
  825. context.state = PNGLoadingContext::State::BitmapDecoded;
  826. return move(frame_context.bitmap);
  827. }
  828. static bool is_valid_compression_method(u8 compression_method)
  829. {
  830. return compression_method == 0;
  831. }
  832. static bool is_valid_filter_method(u8 filter_method)
  833. {
  834. return filter_method == 0;
  835. }
  836. static bool process_IHDR(ReadonlyBytes data, PNGLoadingContext& context)
  837. {
  838. if (data.size() < (int)sizeof(PNG_IHDR))
  839. return false;
  840. auto& ihdr = *(const PNG_IHDR*)data.data();
  841. if (ihdr.width > maximum_width_for_decoded_images || ihdr.height > maximum_height_for_decoded_images) {
  842. dbgln("This PNG is too large for comfort: {}x{}", (u32)ihdr.width, (u32)ihdr.height);
  843. return false;
  844. }
  845. if (!is_valid_compression_method(ihdr.compression_method)) {
  846. dbgln("PNG has invalid compression method {}", ihdr.compression_method);
  847. return false;
  848. }
  849. if (!is_valid_filter_method(ihdr.filter_method)) {
  850. dbgln("PNG has invalid filter method {}", ihdr.filter_method);
  851. return false;
  852. }
  853. context.width = ihdr.width;
  854. context.height = ihdr.height;
  855. context.bit_depth = ihdr.bit_depth;
  856. context.color_type = ihdr.color_type;
  857. context.compression_method = ihdr.compression_method;
  858. context.filter_method = ihdr.filter_method;
  859. context.interlace_method = ihdr.interlace_method;
  860. dbgln_if(PNG_DEBUG, "PNG: {}x{} ({} bpp)", context.width, context.height, context.bit_depth);
  861. dbgln_if(PNG_DEBUG, " Color type: {}", to_underlying(context.color_type));
  862. dbgln_if(PNG_DEBUG, "Compress Method: {}", context.compression_method);
  863. dbgln_if(PNG_DEBUG, " Filter Method: {}", context.filter_method);
  864. dbgln_if(PNG_DEBUG, " Interlace type: {}", context.interlace_method);
  865. if (context.interlace_method != PngInterlaceMethod::Null && context.interlace_method != PngInterlaceMethod::Adam7) {
  866. dbgln_if(PNG_DEBUG, "PNGLoader::process_IHDR: unknown interlace method: {}", context.interlace_method);
  867. return false;
  868. }
  869. switch (context.color_type) {
  870. case PNG::ColorType::Greyscale:
  871. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8 && context.bit_depth != 16)
  872. return false;
  873. context.channels = 1;
  874. break;
  875. case PNG::ColorType::GreyscaleWithAlpha:
  876. if (context.bit_depth != 8 && context.bit_depth != 16)
  877. return false;
  878. context.channels = 2;
  879. break;
  880. case PNG::ColorType::Truecolor:
  881. if (context.bit_depth != 8 && context.bit_depth != 16)
  882. return false;
  883. context.channels = 3;
  884. break;
  885. case PNG::ColorType::IndexedColor:
  886. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8)
  887. return false;
  888. context.channels = 1;
  889. break;
  890. case PNG::ColorType::TruecolorWithAlpha:
  891. if (context.bit_depth != 8 && context.bit_depth != 16)
  892. return false;
  893. context.channels = 4;
  894. break;
  895. default:
  896. return false;
  897. }
  898. return true;
  899. }
  900. static bool process_IDAT(ReadonlyBytes data, PNGLoadingContext& context)
  901. {
  902. context.compressed_data.append(data.data(), data.size());
  903. if (context.state < PNGLoadingContext::State::ImageDataChunkDecoded)
  904. context.state = PNGLoadingContext::State::ImageDataChunkDecoded;
  905. return true;
  906. }
  907. static bool process_PLTE(ReadonlyBytes data, PNGLoadingContext& context)
  908. {
  909. context.palette_data.append((PaletteEntry const*)data.data(), data.size() / 3);
  910. return true;
  911. }
  912. static bool process_tRNS(ReadonlyBytes data, PNGLoadingContext& context)
  913. {
  914. switch (context.color_type) {
  915. case PNG::ColorType::Greyscale:
  916. case PNG::ColorType::Truecolor:
  917. case PNG::ColorType::IndexedColor:
  918. context.palette_transparency_data.append(data.data(), data.size());
  919. break;
  920. default:
  921. break;
  922. }
  923. return true;
  924. }
  925. static bool process_cHRM(ReadonlyBytes data, PNGLoadingContext& context)
  926. {
  927. // https://www.w3.org/TR/png/#11cHRM
  928. if (data.size() != 32)
  929. return false;
  930. context.chromaticities_and_whitepoint = *bit_cast<ChromaticitiesAndWhitepoint* const>(data.data());
  931. return true;
  932. }
  933. static bool process_cICP(ReadonlyBytes data, PNGLoadingContext& context)
  934. {
  935. // https://www.w3.org/TR/png/#cICP-chunk
  936. if (data.size() != 4)
  937. return false;
  938. context.coding_independent_code_points = *bit_cast<CodingIndependentCodePoints* const>(data.data());
  939. return true;
  940. }
  941. static bool process_iCCP(ReadonlyBytes data, PNGLoadingContext& context)
  942. {
  943. // https://www.w3.org/TR/png/#11iCCP
  944. size_t profile_name_length_max = min(80u, data.size());
  945. size_t profile_name_length = strnlen((char const*)data.data(), profile_name_length_max);
  946. if (profile_name_length == 0 || profile_name_length == profile_name_length_max)
  947. return false;
  948. if (data.size() < profile_name_length + 2)
  949. return false;
  950. u8 compression_method = data[profile_name_length + 1];
  951. if (compression_method != 0)
  952. return false;
  953. context.embedded_icc_profile = EmbeddedICCProfile { { data.data(), profile_name_length }, data.slice(profile_name_length + 2) };
  954. return true;
  955. }
  956. static bool process_gAMA(ReadonlyBytes data, PNGLoadingContext& context)
  957. {
  958. // https://www.w3.org/TR/png/#11gAMA
  959. if (data.size() != 4)
  960. return false;
  961. u32 gamma = *bit_cast<NetworkOrdered<u32> const*>(data.data());
  962. if (gamma & 0x8000'0000)
  963. return false;
  964. context.gamma = gamma;
  965. return true;
  966. }
  967. static bool process_sRGB(ReadonlyBytes data, PNGLoadingContext& context)
  968. {
  969. // https://www.w3.org/TR/png/#srgb-standard-colour-space
  970. if (data.size() != 1)
  971. return false;
  972. u8 rendering_intent = data[0];
  973. if (rendering_intent > 3)
  974. return false;
  975. context.sRGB_rendering_intent = (RenderingIntent)rendering_intent;
  976. return true;
  977. }
  978. static bool process_acTL(ReadonlyBytes data, PNGLoadingContext& context)
  979. {
  980. // https://www.w3.org/TR/png/#acTL-chunk
  981. if (context.has_seen_idat_chunk)
  982. return true; // Ignore if we encounter it after the first idat
  983. if (data.size() != sizeof(acTL_Chunk))
  984. return false;
  985. auto const& acTL = *bit_cast<acTL_Chunk* const>(data.data());
  986. context.animation_frame_count = acTL.num_frames;
  987. context.animation_loop_count = acTL.num_plays;
  988. context.has_seen_actl_chunk_before_idat = true;
  989. context.animation_frames.ensure_capacity(context.animation_frame_count);
  990. return true;
  991. }
  992. static bool process_fcTL(ReadonlyBytes data, PNGLoadingContext& context)
  993. {
  994. // https://www.w3.org/TR/png/#fcTL-chunk
  995. if (!context.has_seen_actl_chunk_before_idat)
  996. return true; // Ignore if it's not a valid animated png
  997. if (data.size() != sizeof(fcTL_Chunk))
  998. return false;
  999. auto const& fcTL = *bit_cast<fcTL_Chunk* const>(data.data());
  1000. if (fcTL.sequence_number != context.animation_next_expected_seq)
  1001. return false;
  1002. context.animation_next_expected_seq++;
  1003. if (fcTL.width == 0 || fcTL.height == 0)
  1004. return false;
  1005. Checked<int> left { static_cast<int>(fcTL.x_offset) };
  1006. Checked<int> top { static_cast<int>(fcTL.y_offset) };
  1007. Checked<int> width { static_cast<int>(fcTL.width) };
  1008. Checked<int> height { static_cast<int>(fcTL.height) };
  1009. auto right = left + width;
  1010. auto bottom = top + height;
  1011. if (left < 0 || width <= 0 || right.has_overflow() || right > context.width)
  1012. return false;
  1013. if (top < 0 || height <= 0 || bottom.has_overflow() || bottom > context.height)
  1014. return false;
  1015. bool is_first_animation_frame = context.animation_frames.is_empty();
  1016. if (!is_first_animation_frame)
  1017. context.last_completed_animation_frame_index = context.animation_frames.size() - 1;
  1018. context.animation_frames.append({ fcTL });
  1019. if (!context.has_seen_idat_chunk && is_first_animation_frame)
  1020. context.is_first_idat_part_of_animation = true;
  1021. return true;
  1022. }
  1023. static bool process_fdAT(ReadonlyBytes data, PNGLoadingContext& context)
  1024. {
  1025. // https://www.w3.org/TR/png/#fdAT-chunk
  1026. if (data.size() <= 4)
  1027. return false;
  1028. u32 sequence_number = *bit_cast<NetworkOrdered<u32> const*>(data.data());
  1029. if (sequence_number != context.animation_next_expected_seq)
  1030. return false;
  1031. context.animation_next_expected_seq++;
  1032. if (context.animation_frames.is_empty())
  1033. return false;
  1034. auto& current_animation_frame = context.animation_frames[context.animation_frames.size() - 1];
  1035. auto compressed_data = data.slice(4);
  1036. current_animation_frame.compressed_data.append(compressed_data.data(), compressed_data.size());
  1037. return true;
  1038. }
  1039. static bool process_IEND(ReadonlyBytes, PNGLoadingContext& context)
  1040. {
  1041. // https://www.w3.org/TR/png/#11IEND
  1042. if (context.has_seen_actl_chunk_before_idat)
  1043. context.last_completed_animation_frame_index = context.animation_frames.size();
  1044. context.has_seen_iend = true;
  1045. return true;
  1046. }
  1047. static bool process_chunk(Streamer& streamer, PNGLoadingContext& context)
  1048. {
  1049. u32 chunk_size;
  1050. if (!streamer.read(chunk_size)) {
  1051. dbgln_if(PNG_DEBUG, "Bail at chunk_size");
  1052. return false;
  1053. }
  1054. Array<u8, 4> chunk_type_buffer;
  1055. StringView const chunk_type { chunk_type_buffer.span() };
  1056. if (!streamer.read_bytes(chunk_type_buffer.data(), chunk_type_buffer.size())) {
  1057. dbgln_if(PNG_DEBUG, "Bail at chunk_type");
  1058. return false;
  1059. }
  1060. ReadonlyBytes chunk_data;
  1061. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  1062. dbgln_if(PNG_DEBUG, "Bail at chunk_data");
  1063. return false;
  1064. }
  1065. u32 chunk_crc;
  1066. if (!streamer.read(chunk_crc)) {
  1067. dbgln_if(PNG_DEBUG, "Bail at chunk_crc");
  1068. return false;
  1069. }
  1070. dbgln_if(PNG_DEBUG, "Chunk type: '{}', size: {}, crc: {:x}", chunk_type, chunk_size, chunk_crc);
  1071. if (chunk_type == "IHDR"sv)
  1072. return process_IHDR(chunk_data, context);
  1073. if (chunk_type == "IDAT"sv)
  1074. return process_IDAT(chunk_data, context);
  1075. if (chunk_type == "PLTE"sv)
  1076. return process_PLTE(chunk_data, context);
  1077. if (chunk_type == "cHRM"sv)
  1078. return process_cHRM(chunk_data, context);
  1079. if (chunk_type == "cICP"sv)
  1080. return process_cICP(chunk_data, context);
  1081. if (chunk_type == "iCCP"sv)
  1082. return process_iCCP(chunk_data, context);
  1083. if (chunk_type == "gAMA"sv)
  1084. return process_gAMA(chunk_data, context);
  1085. if (chunk_type == "sRGB"sv)
  1086. return process_sRGB(chunk_data, context);
  1087. if (chunk_type == "tRNS"sv)
  1088. return process_tRNS(chunk_data, context);
  1089. if (chunk_type == "acTL"sv)
  1090. return process_acTL(chunk_data, context);
  1091. if (chunk_type == "fcTL"sv)
  1092. return process_fcTL(chunk_data, context);
  1093. if (chunk_type == "fdAT"sv)
  1094. return process_fdAT(chunk_data, context);
  1095. if (chunk_type == "IEND"sv)
  1096. return process_IEND(chunk_data, context);
  1097. return true;
  1098. }
  1099. PNGImageDecoderPlugin::PNGImageDecoderPlugin(u8 const* data, size_t size)
  1100. {
  1101. m_context = make<PNGLoadingContext>();
  1102. m_context->data = m_context->data_current_ptr = data;
  1103. m_context->data_size = size;
  1104. }
  1105. PNGImageDecoderPlugin::~PNGImageDecoderPlugin() = default;
  1106. bool PNGImageDecoderPlugin::ensure_image_data_chunk_was_decoded()
  1107. {
  1108. if (m_context->state == PNGLoadingContext::State::Error)
  1109. return false;
  1110. if (m_context->state < PNGLoadingContext::State::ImageDataChunkDecoded) {
  1111. if (!decode_png_image_data_chunk(*m_context))
  1112. return false;
  1113. }
  1114. return true;
  1115. }
  1116. bool PNGImageDecoderPlugin::ensure_animation_frame_was_decoded(u32 animation_frame_index)
  1117. {
  1118. if (m_context->state == PNGLoadingContext::State::Error)
  1119. return false;
  1120. if (m_context->state < PNGLoadingContext::State::ImageDataChunkDecoded) {
  1121. if (!decode_png_image_data_chunk(*m_context))
  1122. return false;
  1123. }
  1124. if (m_context->last_completed_animation_frame_index.has_value()) {
  1125. if (m_context->last_completed_animation_frame_index.value() >= animation_frame_index)
  1126. return true;
  1127. }
  1128. return decode_png_animation_data_chunks(*m_context, animation_frame_index);
  1129. }
  1130. IntSize PNGImageDecoderPlugin::size()
  1131. {
  1132. if (m_context->state == PNGLoadingContext::State::Error)
  1133. return {};
  1134. if (m_context->state < PNGLoadingContext::State::SizeDecoded) {
  1135. bool success = decode_png_size(*m_context);
  1136. if (!success)
  1137. return {};
  1138. }
  1139. return { m_context->width, m_context->height };
  1140. }
  1141. void PNGImageDecoderPlugin::set_volatile()
  1142. {
  1143. if (m_context->bitmap)
  1144. m_context->bitmap->set_volatile();
  1145. }
  1146. bool PNGImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  1147. {
  1148. if (!m_context->bitmap)
  1149. return false;
  1150. return m_context->bitmap->set_nonvolatile(was_purged);
  1151. }
  1152. ErrorOr<void> PNGImageDecoderPlugin::initialize()
  1153. {
  1154. if (decode_png_header(*m_context))
  1155. return {};
  1156. return Error::from_string_literal("bad image header");
  1157. }
  1158. bool PNGImageDecoderPlugin::sniff(ReadonlyBytes data)
  1159. {
  1160. PNGLoadingContext context;
  1161. context.data = context.data_current_ptr = data.data();
  1162. context.data_size = data.size();
  1163. return decode_png_header(context);
  1164. }
  1165. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> PNGImageDecoderPlugin::create(ReadonlyBytes data)
  1166. {
  1167. return adopt_nonnull_own_or_enomem(new (nothrow) PNGImageDecoderPlugin(data.data(), data.size()));
  1168. }
  1169. bool PNGImageDecoderPlugin::is_animated()
  1170. {
  1171. if (!ensure_image_data_chunk_was_decoded())
  1172. return false;
  1173. return m_context->has_seen_actl_chunk_before_idat;
  1174. }
  1175. size_t PNGImageDecoderPlugin::loop_count()
  1176. {
  1177. if (!ensure_image_data_chunk_was_decoded())
  1178. return 0;
  1179. return m_context->animation_loop_count;
  1180. }
  1181. size_t PNGImageDecoderPlugin::frame_count()
  1182. {
  1183. if (!ensure_image_data_chunk_was_decoded())
  1184. return 0;
  1185. if (!m_context->has_seen_actl_chunk_before_idat)
  1186. return 1;
  1187. auto total_frames = m_context->animation_frame_count;
  1188. if (!m_context->is_first_idat_part_of_animation)
  1189. total_frames++;
  1190. return total_frames;
  1191. }
  1192. size_t PNGImageDecoderPlugin::first_animated_frame_index()
  1193. {
  1194. if (!ensure_image_data_chunk_was_decoded())
  1195. return 0;
  1196. if (!m_context->has_seen_actl_chunk_before_idat)
  1197. return 0;
  1198. return m_context->is_first_idat_part_of_animation ? 0 : 1;
  1199. }
  1200. static ErrorOr<RefPtr<Bitmap>> render_animation_frame(AnimationFrame const& prev_animation_frame, AnimationFrame& animation_frame, Bitmap const& decoded_frame_bitmap)
  1201. {
  1202. auto rendered_bitmap = TRY(prev_animation_frame.bitmap->clone());
  1203. Painter painter(rendered_bitmap);
  1204. static constexpr Color transparent_black = { 0, 0, 0, 0 };
  1205. auto frame_rect = animation_frame.rect();
  1206. switch (prev_animation_frame.fcTL.dispose_op) {
  1207. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_NONE:
  1208. break;
  1209. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_BACKGROUND:
  1210. painter.clear_rect(rendered_bitmap->rect(), transparent_black);
  1211. break;
  1212. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_PREVIOUS: {
  1213. painter.blit(frame_rect.location(), *prev_animation_frame.bitmap, frame_rect, 1.0f, false);
  1214. break;
  1215. }
  1216. }
  1217. switch (animation_frame.fcTL.blend_op) {
  1218. case fcTL_Chunk::BlendOp::APNG_BLEND_OP_SOURCE:
  1219. painter.blit(frame_rect.location(), decoded_frame_bitmap, decoded_frame_bitmap.rect(), 1.0f, false);
  1220. break;
  1221. case fcTL_Chunk::BlendOp::APNG_BLEND_OP_OVER:
  1222. painter.blit(frame_rect.location(), decoded_frame_bitmap, decoded_frame_bitmap.rect(), 1.0f, true);
  1223. break;
  1224. }
  1225. return rendered_bitmap;
  1226. }
  1227. ErrorOr<ImageFrameDescriptor> PNGImageDecoderPlugin::frame(size_t index)
  1228. {
  1229. if (m_context->state == PNGLoadingContext::State::Error)
  1230. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  1231. if (!ensure_image_data_chunk_was_decoded())
  1232. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding image data chunk");
  1233. auto set_descriptor_duration = [](ImageFrameDescriptor& descriptor, AnimationFrame const& animation_frame) {
  1234. descriptor.duration = static_cast<int>(animation_frame.duration_ms());
  1235. if (descriptor.duration < 0)
  1236. descriptor.duration = NumericLimits<int>::min();
  1237. };
  1238. auto load_default_image = [&]() -> ErrorOr<void> {
  1239. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  1240. // NOTE: This forces the chunk decoding to happen.
  1241. TRY(decode_png_bitmap(*m_context));
  1242. }
  1243. VERIFY(m_context->bitmap);
  1244. return {};
  1245. };
  1246. if (index == 0) {
  1247. TRY(load_default_image());
  1248. ImageFrameDescriptor descriptor { m_context->bitmap };
  1249. if (m_context->has_seen_actl_chunk_before_idat && m_context->is_first_idat_part_of_animation)
  1250. set_descriptor_duration(descriptor, m_context->animation_frames[0]);
  1251. return descriptor;
  1252. }
  1253. if (!m_context->has_seen_actl_chunk_before_idat)
  1254. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid frame index");
  1255. if (!ensure_animation_frame_was_decoded(index))
  1256. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding image data chunk");
  1257. if (index >= m_context->animation_frames.size())
  1258. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid animation frame index");
  1259. // We need to assemble each frame up until the one requested,
  1260. // so decode all bitmaps that haven't been decoded yet.
  1261. for (size_t i = m_context->animation_next_frame_to_render; i <= index; i++) {
  1262. if (i == 0) {
  1263. // If the default image hasn't been loaded, load it now
  1264. TRY(load_default_image()); // May modify animation_frames!
  1265. auto& animation_frame = m_context->animation_frames[i];
  1266. animation_frame.bitmap = m_context->bitmap;
  1267. } else {
  1268. auto& animation_frame = m_context->animation_frames[i];
  1269. VERIFY(!animation_frame.bitmap);
  1270. auto decoded_bitmap = TRY(decode_png_animation_frame_bitmap(*m_context, animation_frame));
  1271. auto prev_animation_frame = m_context->animation_frames[i - 1];
  1272. animation_frame.bitmap = TRY(render_animation_frame(prev_animation_frame, animation_frame, *decoded_bitmap));
  1273. }
  1274. m_context->animation_next_frame_to_render = i + 1;
  1275. }
  1276. auto const& animation_frame = m_context->animation_frames[index];
  1277. VERIFY(animation_frame.bitmap);
  1278. ImageFrameDescriptor descriptor { animation_frame.bitmap };
  1279. set_descriptor_duration(descriptor, animation_frame);
  1280. return descriptor;
  1281. }
  1282. ErrorOr<Optional<ReadonlyBytes>> PNGImageDecoderPlugin::icc_data()
  1283. {
  1284. if (!decode_png_chunks(*m_context))
  1285. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding chunks failed");
  1286. if (m_context->embedded_icc_profile.has_value()) {
  1287. if (!m_context->decompressed_icc_profile.has_value()) {
  1288. auto result = Compress::ZlibDecompressor::decompress_all(m_context->embedded_icc_profile->compressed_data);
  1289. if (!result.has_value()) {
  1290. m_context->embedded_icc_profile.clear();
  1291. return Error::from_string_literal("PNGImageDecoderPlugin: Decompression of ICC profile failed");
  1292. }
  1293. m_context->decompressed_icc_profile = move(*result);
  1294. }
  1295. return m_context->decompressed_icc_profile.value();
  1296. }
  1297. // FIXME: Eventually, look at coding_independent_code_points, chromaticities_and_whitepoint, gamma, sRGB_rendering_intent too.
  1298. // The order is:
  1299. // 1. Use coding_independent_code_points if it exists, ignore the rest.
  1300. // 2. Use embedded_icc_profile if it exists, ignore the rest.
  1301. // 3. Use sRGB_rendering_intent if it exists, ignore the rest.
  1302. // 4. Use gamma to adjust gamma and chromaticities_and_whitepoint to adjust color.
  1303. // (Order between 2 and 3 isn't fully clear, but "It is recommended that the sRGB and iCCP chunks do not appear simultaneously in a PNG datastream."
  1304. return OptionalNone {};
  1305. }
  1306. }