PNGLoader.cpp 54 KB

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