PNGLoader.cpp 56 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/MemoryStream.h>
  10. #include <AK/Vector.h>
  11. #include <LibCompress/Zlib.h>
  12. #include <LibGfx/ImageFormats/PNGLoader.h>
  13. #include <LibGfx/ImageFormats/PNGShared.h>
  14. #include <LibGfx/Painter.h>
  15. namespace Gfx {
  16. struct PNG_IHDR {
  17. NetworkOrdered<u32> width;
  18. NetworkOrdered<u32> height;
  19. u8 bit_depth { 0 };
  20. PNG::ColorType color_type { 0 };
  21. u8 compression_method { 0 };
  22. u8 filter_method { 0 };
  23. u8 interlace_method { 0 };
  24. };
  25. static_assert(AssertSize<PNG_IHDR, 13>());
  26. struct acTL_Chunk {
  27. NetworkOrdered<u32> num_frames;
  28. NetworkOrdered<u32> num_plays;
  29. };
  30. static_assert(AssertSize<acTL_Chunk, 8>());
  31. struct fcTL_Chunk {
  32. enum class DisposeOp : u8 {
  33. APNG_DISPOSE_OP_NONE = 0,
  34. APNG_DISPOSE_OP_BACKGROUND,
  35. APNG_DISPOSE_OP_PREVIOUS
  36. };
  37. enum class BlendOp : u8 {
  38. APNG_BLEND_OP_SOURCE = 0,
  39. APNG_BLEND_OP_OVER
  40. };
  41. NetworkOrdered<u32> sequence_number;
  42. NetworkOrdered<u32> width;
  43. NetworkOrdered<u32> height;
  44. NetworkOrdered<u32> x_offset;
  45. NetworkOrdered<u32> y_offset;
  46. NetworkOrdered<u16> delay_num;
  47. NetworkOrdered<u16> delay_den;
  48. DisposeOp dispose_op { DisposeOp::APNG_DISPOSE_OP_NONE };
  49. BlendOp blend_op { BlendOp::APNG_BLEND_OP_SOURCE };
  50. };
  51. static_assert(AssertSize<fcTL_Chunk, 26>());
  52. struct ChromaticitiesAndWhitepoint {
  53. NetworkOrdered<u32> white_point_x;
  54. NetworkOrdered<u32> white_point_y;
  55. NetworkOrdered<u32> red_x;
  56. NetworkOrdered<u32> red_y;
  57. NetworkOrdered<u32> green_x;
  58. NetworkOrdered<u32> green_y;
  59. NetworkOrdered<u32> blue_x;
  60. NetworkOrdered<u32> blue_y;
  61. };
  62. static_assert(AssertSize<ChromaticitiesAndWhitepoint, 32>());
  63. struct CodingIndependentCodePoints {
  64. u8 color_primaries;
  65. u8 transfer_function;
  66. u8 matrix_coefficients;
  67. u8 video_full_range_flag;
  68. };
  69. static_assert(AssertSize<CodingIndependentCodePoints, 4>());
  70. struct EmbeddedICCProfile {
  71. StringView profile_name;
  72. ReadonlyBytes compressed_data;
  73. };
  74. struct Scanline {
  75. PNG::FilterType filter;
  76. ReadonlyBytes data {};
  77. };
  78. struct [[gnu::packed]] PaletteEntry {
  79. u8 r;
  80. u8 g;
  81. u8 b;
  82. // u8 a;
  83. };
  84. template<typename T>
  85. struct [[gnu::packed]] Tuple {
  86. T gray;
  87. T a;
  88. };
  89. template<typename T>
  90. struct [[gnu::packed]] Triplet {
  91. T r;
  92. T g;
  93. T b;
  94. bool operator==(Triplet const& other) const = default;
  95. };
  96. template<typename T>
  97. struct [[gnu::packed]] Quartet {
  98. T r;
  99. T g;
  100. T b;
  101. T a;
  102. };
  103. enum PngInterlaceMethod {
  104. Null = 0,
  105. Adam7 = 1
  106. };
  107. enum RenderingIntent {
  108. Perceptual = 0,
  109. RelativeColorimetric = 1,
  110. Saturation = 2,
  111. AbsoluteColorimetric = 3,
  112. };
  113. struct AnimationFrame {
  114. fcTL_Chunk const& fcTL;
  115. RefPtr<Bitmap> bitmap;
  116. ByteBuffer compressed_data;
  117. AnimationFrame(fcTL_Chunk const& fcTL)
  118. : fcTL(fcTL)
  119. {
  120. }
  121. u32 duration_ms() const
  122. {
  123. u32 num = fcTL.delay_num;
  124. if (num == 0)
  125. return 1;
  126. u32 denom = fcTL.delay_den != 0 ? static_cast<u32>(fcTL.delay_den) : 100u;
  127. return (num * 1000) / denom;
  128. }
  129. IntRect rect() const
  130. {
  131. return { fcTL.x_offset, fcTL.y_offset, fcTL.width, fcTL.height };
  132. }
  133. };
  134. struct PNGLoadingContext {
  135. enum State {
  136. NotDecoded = 0,
  137. Error,
  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. i32 width { -1 };
  148. i32 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.data || context.data_size < sizeof(PNG::header)) {
  542. dbgln_if(PNG_DEBUG, "Missing PNG header");
  543. context.state = PNGLoadingContext::State::Error;
  544. return false;
  545. }
  546. if (memcmp(context.data, PNG::header.span().data(), sizeof(PNG::header)) != 0) {
  547. dbgln_if(PNG_DEBUG, "Invalid PNG header");
  548. context.state = PNGLoadingContext::State::Error;
  549. return false;
  550. }
  551. context.data_current_ptr = context.data + sizeof(PNG::header);
  552. return true;
  553. }
  554. static ErrorOr<void> decode_png_ihdr(PNGLoadingContext& context)
  555. {
  556. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  557. Streamer streamer(context.data_current_ptr, data_remaining);
  558. // https://www.w3.org/TR/png/#11IHDR
  559. // The IHDR chunk shall be the first chunk in the PNG datastream.
  560. TRY(process_chunk(streamer, context));
  561. context.data_current_ptr = streamer.current_data_ptr();
  562. VERIFY(context.state == PNGLoadingContext::State::IHDRDecoded);
  563. return {};
  564. }
  565. static bool decode_png_image_data_chunk(PNGLoadingContext& context)
  566. {
  567. VERIFY(context.state >= PNGLoadingContext::IHDRDecoded);
  568. if (context.state >= PNGLoadingContext::ImageDataChunkDecoded)
  569. return true;
  570. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  571. Streamer streamer(context.data_current_ptr, data_remaining);
  572. while (!streamer.at_end() && !context.has_seen_iend) {
  573. if (auto result = process_chunk(streamer, context); result.is_error()) {
  574. context.state = PNGLoadingContext::State::Error;
  575. return false;
  576. }
  577. context.data_current_ptr = streamer.current_data_ptr();
  578. if (context.state >= PNGLoadingContext::State::ImageDataChunkDecoded)
  579. return true;
  580. }
  581. return false;
  582. }
  583. static bool decode_png_animation_data_chunks(PNGLoadingContext& context, u32 requested_animation_frame_index)
  584. {
  585. if (context.state >= PNGLoadingContext::ImageDataChunkDecoded) {
  586. if (context.last_completed_animation_frame_index.has_value()) {
  587. if (requested_animation_frame_index <= context.last_completed_animation_frame_index.value())
  588. return true;
  589. }
  590. } else if (!decode_png_image_data_chunk(context)) {
  591. return false;
  592. }
  593. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  594. Streamer streamer(context.data_current_ptr, data_remaining);
  595. while (!streamer.at_end() && !context.has_seen_iend) {
  596. if (auto result = process_chunk(streamer, context); result.is_error()) {
  597. context.state = PNGLoadingContext::State::Error;
  598. return false;
  599. }
  600. context.data_current_ptr = streamer.current_data_ptr();
  601. if (context.last_completed_animation_frame_index.has_value()) {
  602. if (requested_animation_frame_index <= context.last_completed_animation_frame_index.value())
  603. break;
  604. }
  605. }
  606. if (!context.last_completed_animation_frame_index.has_value())
  607. return false;
  608. return requested_animation_frame_index <= context.last_completed_animation_frame_index.value();
  609. }
  610. static bool decode_png_chunks(PNGLoadingContext& context)
  611. {
  612. VERIFY(context.state >= PNGLoadingContext::IHDRDecoded);
  613. if (context.state >= PNGLoadingContext::State::ChunksDecoded)
  614. return true;
  615. size_t data_remaining = context.data_size - (context.data_current_ptr - context.data);
  616. context.compressed_data.ensure_capacity(context.data_size);
  617. Streamer streamer(context.data_current_ptr, data_remaining);
  618. while (!streamer.at_end() && !context.has_seen_iend) {
  619. if (auto result = process_chunk(streamer, context); result.is_error()) {
  620. // Ignore failed chunk and just consider chunk decoding being done.
  621. // decode_png_bitmap() will check whether we got all required ones anyway.
  622. break;
  623. }
  624. context.data_current_ptr = streamer.current_data_ptr();
  625. }
  626. context.state = PNGLoadingContext::State::ChunksDecoded;
  627. return true;
  628. }
  629. static ErrorOr<void> decode_png_bitmap_simple(PNGLoadingContext& context, ByteBuffer& decompression_buffer)
  630. {
  631. Streamer streamer(decompression_buffer.data(), decompression_buffer.size());
  632. for (int y = 0; y < context.height; ++y) {
  633. PNG::FilterType filter;
  634. if (!streamer.read(filter)) {
  635. context.state = PNGLoadingContext::State::Error;
  636. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  637. }
  638. if (to_underlying(filter) > 4) {
  639. context.state = PNGLoadingContext::State::Error;
  640. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
  641. }
  642. context.scanlines.append({ filter });
  643. auto& scanline_buffer = context.scanlines.last().data;
  644. auto row_size = context.compute_row_size_for_width(context.width);
  645. if (row_size.has_overflow())
  646. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
  647. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  648. context.state = PNGLoadingContext::State::Error;
  649. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  650. }
  651. }
  652. context.bitmap = TRY(Bitmap::create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  653. return unfilter(context);
  654. }
  655. static int adam7_height(PNGLoadingContext& context, int pass)
  656. {
  657. switch (pass) {
  658. case 1:
  659. return (context.height + 7) / 8;
  660. case 2:
  661. return (context.height + 7) / 8;
  662. case 3:
  663. return (context.height + 3) / 8;
  664. case 4:
  665. return (context.height + 3) / 4;
  666. case 5:
  667. return (context.height + 1) / 4;
  668. case 6:
  669. return (context.height + 1) / 2;
  670. case 7:
  671. return context.height / 2;
  672. default:
  673. VERIFY_NOT_REACHED();
  674. }
  675. }
  676. static int adam7_width(PNGLoadingContext& context, int pass)
  677. {
  678. switch (pass) {
  679. case 1:
  680. return (context.width + 7) / 8;
  681. case 2:
  682. return (context.width + 3) / 8;
  683. case 3:
  684. return (context.width + 3) / 4;
  685. case 4:
  686. return (context.width + 1) / 4;
  687. case 5:
  688. return (context.width + 1) / 2;
  689. case 6:
  690. return context.width / 2;
  691. case 7:
  692. return context.width;
  693. default:
  694. VERIFY_NOT_REACHED();
  695. }
  696. }
  697. // Index 0 unused (non-interlaced case)
  698. static int adam7_starty[8] = { 0, 0, 0, 4, 0, 2, 0, 1 };
  699. static int adam7_startx[8] = { 0, 0, 4, 0, 2, 0, 1, 0 };
  700. static int adam7_stepy[8] = { 1, 8, 8, 8, 4, 4, 2, 2 };
  701. static int adam7_stepx[8] = { 1, 8, 8, 4, 4, 2, 2, 1 };
  702. static ErrorOr<void> decode_adam7_pass(PNGLoadingContext& context, Streamer& streamer, int pass)
  703. {
  704. auto subimage_context = context.create_subimage_context(adam7_width(context, pass), adam7_height(context, pass));
  705. // For small images, some passes might be empty
  706. if (!subimage_context.width || !subimage_context.height)
  707. return {};
  708. for (int y = 0; y < subimage_context.height; ++y) {
  709. PNG::FilterType filter;
  710. if (!streamer.read(filter)) {
  711. context.state = PNGLoadingContext::State::Error;
  712. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  713. }
  714. if (to_underlying(filter) > 4) {
  715. context.state = PNGLoadingContext::State::Error;
  716. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
  717. }
  718. subimage_context.scanlines.append({ filter });
  719. auto& scanline_buffer = subimage_context.scanlines.last().data;
  720. auto row_size = context.compute_row_size_for_width(subimage_context.width);
  721. if (row_size.has_overflow())
  722. return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
  723. if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
  724. context.state = PNGLoadingContext::State::Error;
  725. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  726. }
  727. }
  728. subimage_context.bitmap = TRY(Bitmap::create(context.bitmap->format(), { subimage_context.width, subimage_context.height }));
  729. TRY(unfilter(subimage_context));
  730. // Copy the subimage data into the main image according to the pass pattern
  731. for (int y = 0, dy = adam7_starty[pass]; y < subimage_context.height && dy < context.height; ++y, dy += adam7_stepy[pass]) {
  732. for (int x = 0, dx = adam7_startx[pass]; x < subimage_context.width && dx < context.width; ++x, dx += adam7_stepx[pass]) {
  733. context.bitmap->set_pixel(dx, dy, subimage_context.bitmap->get_pixel(x, y));
  734. }
  735. }
  736. return {};
  737. }
  738. static ErrorOr<void> decode_png_adam7(PNGLoadingContext& context, ByteBuffer& decompression_buffer)
  739. {
  740. Streamer streamer(decompression_buffer.data(), decompression_buffer.size());
  741. context.bitmap = TRY(Bitmap::create(context.has_alpha() ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, { context.width, context.height }));
  742. for (int pass = 1; pass <= 7; ++pass)
  743. TRY(decode_adam7_pass(context, streamer, pass));
  744. return {};
  745. }
  746. static ErrorOr<void> decode_png_bitmap(PNGLoadingContext& context)
  747. {
  748. if (context.state < PNGLoadingContext::State::ChunksDecoded) {
  749. if (!decode_png_chunks(context))
  750. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  751. }
  752. if (context.state >= PNGLoadingContext::State::BitmapDecoded)
  753. return {};
  754. if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty())
  755. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty.");
  756. auto compressed_data_stream = make<FixedMemoryStream>(context.compressed_data.span());
  757. auto decompressor_or_error = Compress::ZlibDecompressor::create(move(compressed_data_stream));
  758. if (decompressor_or_error.is_error()) {
  759. context.state = PNGLoadingContext::State::Error;
  760. return decompressor_or_error.release_error();
  761. }
  762. auto decompressor = decompressor_or_error.release_value();
  763. auto result_or_error = decompressor->read_until_eof();
  764. if (result_or_error.is_error()) {
  765. context.state = PNGLoadingContext::State::Error;
  766. return result_or_error.release_error();
  767. }
  768. auto decompression_buffer = result_or_error.release_value();
  769. context.compressed_data.clear();
  770. context.scanlines.ensure_capacity(context.height);
  771. switch (context.interlace_method) {
  772. case PngInterlaceMethod::Null:
  773. TRY(decode_png_bitmap_simple(context, decompression_buffer));
  774. break;
  775. case PngInterlaceMethod::Adam7:
  776. TRY(decode_png_adam7(context, decompression_buffer));
  777. break;
  778. default:
  779. context.state = PNGLoadingContext::State::Error;
  780. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method");
  781. }
  782. context.state = PNGLoadingContext::State::BitmapDecoded;
  783. return {};
  784. }
  785. static ErrorOr<RefPtr<Bitmap>> decode_png_animation_frame_bitmap(PNGLoadingContext& context, AnimationFrame& animation_frame)
  786. {
  787. if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty())
  788. return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty.");
  789. VERIFY(!animation_frame.bitmap);
  790. auto frame_rect = animation_frame.rect();
  791. auto frame_context = context.create_subimage_context(frame_rect.width(), frame_rect.height());
  792. auto compressed_data_stream = make<FixedMemoryStream>(animation_frame.compressed_data.span());
  793. auto decompressor = TRY(Compress::ZlibDecompressor::create(move(compressed_data_stream)));
  794. auto decompression_buffer = TRY(decompressor->read_until_eof());
  795. frame_context.compressed_data.clear();
  796. frame_context.scanlines.ensure_capacity(frame_context.height);
  797. switch (context.interlace_method) {
  798. case PngInterlaceMethod::Null:
  799. TRY(decode_png_bitmap_simple(frame_context, decompression_buffer));
  800. break;
  801. case PngInterlaceMethod::Adam7:
  802. TRY(decode_png_adam7(frame_context, decompression_buffer));
  803. break;
  804. default:
  805. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method");
  806. }
  807. context.state = PNGLoadingContext::State::BitmapDecoded;
  808. return move(frame_context.bitmap);
  809. }
  810. static bool is_valid_compression_method(u8 compression_method)
  811. {
  812. return compression_method == 0;
  813. }
  814. static bool is_valid_filter_method(u8 filter_method)
  815. {
  816. return filter_method == 0;
  817. }
  818. static bool is_valid_bit_depth(u8 bit_depth, PNG::ColorType color_type)
  819. {
  820. switch (bit_depth) {
  821. case 1:
  822. case 2:
  823. case 4:
  824. return color_type == PNG::ColorType::Greyscale || color_type == PNG::ColorType::IndexedColor;
  825. case 8:
  826. return true;
  827. case 16:
  828. return color_type != PNG::ColorType::IndexedColor;
  829. default:
  830. return false;
  831. }
  832. }
  833. static ErrorOr<void> process_IHDR(ReadonlyBytes data, PNGLoadingContext& context)
  834. {
  835. if (data.size() < (int)sizeof(PNG_IHDR))
  836. return Error::from_string_literal("IHDR chunk has an abnormal size");
  837. auto const& ihdr = *(const PNG_IHDR*)data.data();
  838. if (ihdr.width == 0 || ihdr.width > NumericLimits<i32>::max()) {
  839. dbgln("PNG has invalid width {}", ihdr.width);
  840. return Error::from_string_literal("Invalid width");
  841. }
  842. if (ihdr.height == 0 || ihdr.height > NumericLimits<i32>::max()) {
  843. dbgln("PNG has invalid height {}", ihdr.height);
  844. return Error::from_string_literal("Invalid height");
  845. }
  846. if (!is_valid_bit_depth(ihdr.bit_depth, ihdr.color_type)) {
  847. dbgln("PNG has invalid bit depth {} for color type {}", ihdr.bit_depth, to_underlying(ihdr.color_type));
  848. return Error::from_string_literal("Invalid bit depth");
  849. }
  850. if (!is_valid_compression_method(ihdr.compression_method)) {
  851. dbgln("PNG has invalid compression method {}", ihdr.compression_method);
  852. return Error::from_string_literal("Unsupported compression method");
  853. }
  854. if (!is_valid_filter_method(ihdr.filter_method)) {
  855. dbgln("PNG has invalid filter method {}", ihdr.filter_method);
  856. return Error::from_string_literal("Unsupported filter method");
  857. }
  858. context.width = ihdr.width;
  859. context.height = ihdr.height;
  860. context.bit_depth = ihdr.bit_depth;
  861. context.color_type = ihdr.color_type;
  862. context.compression_method = ihdr.compression_method;
  863. context.filter_method = ihdr.filter_method;
  864. context.interlace_method = ihdr.interlace_method;
  865. dbgln_if(PNG_DEBUG, "PNG: {}x{} ({} bpp)", context.width, context.height, context.bit_depth);
  866. dbgln_if(PNG_DEBUG, " Color type: {}", to_underlying(context.color_type));
  867. dbgln_if(PNG_DEBUG, "Compress Method: {}", context.compression_method);
  868. dbgln_if(PNG_DEBUG, " Filter Method: {}", context.filter_method);
  869. dbgln_if(PNG_DEBUG, " Interlace type: {}", context.interlace_method);
  870. if (context.interlace_method != PngInterlaceMethod::Null && context.interlace_method != PngInterlaceMethod::Adam7) {
  871. dbgln_if(PNG_DEBUG, "PNGLoader::process_IHDR: unknown interlace method: {}", context.interlace_method);
  872. return Error::from_string_literal("Unsupported interlacing method");
  873. }
  874. switch (context.color_type) {
  875. case PNG::ColorType::Greyscale:
  876. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8 && context.bit_depth != 16)
  877. return Error::from_string_literal("Unsupported bit depth for a greyscale image");
  878. context.channels = 1;
  879. break;
  880. case PNG::ColorType::GreyscaleWithAlpha:
  881. if (context.bit_depth != 8 && context.bit_depth != 16)
  882. return Error::from_string_literal("Unsupported bit depth for a greyscale image with alpha");
  883. context.channels = 2;
  884. break;
  885. case PNG::ColorType::Truecolor:
  886. if (context.bit_depth != 8 && context.bit_depth != 16)
  887. return Error::from_string_literal("Unsupported bit depth for a true color image");
  888. context.channels = 3;
  889. break;
  890. case PNG::ColorType::IndexedColor:
  891. if (context.bit_depth != 1 && context.bit_depth != 2 && context.bit_depth != 4 && context.bit_depth != 8)
  892. return Error::from_string_literal("Unsupported bit depth for a indexed color image");
  893. context.channels = 1;
  894. break;
  895. case PNG::ColorType::TruecolorWithAlpha:
  896. if (context.bit_depth != 8 && context.bit_depth != 16)
  897. return Error::from_string_literal("Unsupported bit depth for a true color image with alpha");
  898. context.channels = 4;
  899. break;
  900. default:
  901. return Error::from_string_literal("Unsupported color type");
  902. }
  903. context.state = PNGLoadingContext::IHDRDecoded;
  904. return {};
  905. }
  906. static ErrorOr<void> process_IDAT(ReadonlyBytes data, PNGLoadingContext& context)
  907. {
  908. context.compressed_data.append(data);
  909. if (context.state < PNGLoadingContext::State::ImageDataChunkDecoded)
  910. context.state = PNGLoadingContext::State::ImageDataChunkDecoded;
  911. return {};
  912. }
  913. static ErrorOr<void> process_PLTE(ReadonlyBytes data, PNGLoadingContext& context)
  914. {
  915. TRY(context.palette_data.try_append((PaletteEntry const*)data.data(), data.size() / 3));
  916. return {};
  917. }
  918. static ErrorOr<void> process_tRNS(ReadonlyBytes data, PNGLoadingContext& context)
  919. {
  920. switch (context.color_type) {
  921. case PNG::ColorType::Greyscale:
  922. case PNG::ColorType::Truecolor:
  923. case PNG::ColorType::IndexedColor:
  924. TRY(context.palette_transparency_data.try_append(data));
  925. break;
  926. default:
  927. break;
  928. }
  929. return {};
  930. }
  931. static ErrorOr<void> process_cHRM(ReadonlyBytes data, PNGLoadingContext& context)
  932. {
  933. // https://www.w3.org/TR/png/#11cHRM
  934. if (data.size() != 32)
  935. return Error::from_string_literal("cHRM chunk has an abnormal size");
  936. context.chromaticities_and_whitepoint = *bit_cast<ChromaticitiesAndWhitepoint* const>(data.data());
  937. return {};
  938. }
  939. static ErrorOr<void> process_cICP(ReadonlyBytes data, PNGLoadingContext& context)
  940. {
  941. // https://www.w3.org/TR/png/#cICP-chunk
  942. if (data.size() != 4)
  943. return Error::from_string_literal("cICP chunk has an abnormal size");
  944. context.coding_independent_code_points = *bit_cast<CodingIndependentCodePoints* const>(data.data());
  945. return {};
  946. }
  947. static ErrorOr<void> process_iCCP(ReadonlyBytes data, PNGLoadingContext& context)
  948. {
  949. // https://www.w3.org/TR/png/#11iCCP
  950. size_t profile_name_length_max = min(80u, data.size());
  951. size_t profile_name_length = strnlen((char const*)data.data(), profile_name_length_max);
  952. if (profile_name_length == 0 || profile_name_length == profile_name_length_max)
  953. return Error::from_string_literal("iCCP chunk does not contain a profile name");
  954. if (data.size() < profile_name_length + 2)
  955. return Error::from_string_literal("iCCP chunk is too small");
  956. u8 compression_method = data[profile_name_length + 1];
  957. if (compression_method != 0)
  958. return Error::from_string_literal("Unsupported compression method in the iCCP chunk");
  959. context.embedded_icc_profile = EmbeddedICCProfile { { data.data(), profile_name_length }, data.slice(profile_name_length + 2) };
  960. return {};
  961. }
  962. static ErrorOr<void> process_gAMA(ReadonlyBytes data, PNGLoadingContext& context)
  963. {
  964. // https://www.w3.org/TR/png/#11gAMA
  965. if (data.size() != 4)
  966. return Error::from_string_literal("gAMA chunk has an abnormal size");
  967. u32 gamma = *bit_cast<NetworkOrdered<u32> const*>(data.data());
  968. if (gamma & 0x8000'0000)
  969. return Error::from_string_literal("Gamma value is too high");
  970. context.gamma = gamma;
  971. return {};
  972. }
  973. static ErrorOr<void> process_sRGB(ReadonlyBytes data, PNGLoadingContext& context)
  974. {
  975. // https://www.w3.org/TR/png/#srgb-standard-colour-space
  976. if (data.size() != 1) {
  977. // Invalid per spec, but (rarely) happens in the wild. Log and ignore.
  978. warnln("warning: PNG sRGB chunk has an abnormal size; ignoring");
  979. return {};
  980. }
  981. u8 rendering_intent = data[0];
  982. if (rendering_intent > 3)
  983. return Error::from_string_literal("Unsupported rendering intent");
  984. context.sRGB_rendering_intent = (RenderingIntent)rendering_intent;
  985. return {};
  986. }
  987. static ErrorOr<void> process_acTL(ReadonlyBytes data, PNGLoadingContext& context)
  988. {
  989. // https://www.w3.org/TR/png/#acTL-chunk
  990. if (context.has_seen_idat_chunk)
  991. return {}; // Ignore if we encounter it after the first idat
  992. if (data.size() != sizeof(acTL_Chunk))
  993. return Error::from_string_literal("acTL chunk has an abnormal size");
  994. auto const& acTL = *bit_cast<acTL_Chunk* const>(data.data());
  995. context.animation_frame_count = acTL.num_frames;
  996. context.animation_loop_count = acTL.num_plays;
  997. context.has_seen_actl_chunk_before_idat = true;
  998. TRY(context.animation_frames.try_ensure_capacity(context.animation_frame_count));
  999. return {};
  1000. }
  1001. static ErrorOr<void> process_fcTL(ReadonlyBytes data, PNGLoadingContext& context)
  1002. {
  1003. // https://www.w3.org/TR/png/#fcTL-chunk
  1004. if (!context.has_seen_actl_chunk_before_idat)
  1005. return {}; // Ignore if it's not a valid animated png
  1006. if (data.size() != sizeof(fcTL_Chunk))
  1007. return Error::from_string_literal("fcTL chunk has an abnormal size");
  1008. auto const& fcTL = *bit_cast<fcTL_Chunk* const>(data.data());
  1009. if (fcTL.sequence_number != context.animation_next_expected_seq)
  1010. return Error::from_string_literal("Unexpected sequence number");
  1011. context.animation_next_expected_seq++;
  1012. if (fcTL.width == 0 || fcTL.height == 0)
  1013. return Error::from_string_literal("width and height must be greater than zero in fcTL chunk");
  1014. Checked<int> left { static_cast<int>(fcTL.x_offset) };
  1015. Checked<int> top { static_cast<int>(fcTL.y_offset) };
  1016. Checked<int> width { static_cast<int>(fcTL.width) };
  1017. Checked<int> height { static_cast<int>(fcTL.height) };
  1018. auto right = left + width;
  1019. auto bottom = top + height;
  1020. if (left < 0 || width <= 0 || right.has_overflow() || right > context.width)
  1021. return Error::from_string_literal("Invalid x_offset value in fcTL chunk");
  1022. if (top < 0 || height <= 0 || bottom.has_overflow() || bottom > context.height)
  1023. return Error::from_string_literal("Invalid y_offset value in fcTL chunk");
  1024. bool is_first_animation_frame = context.animation_frames.is_empty();
  1025. if (!is_first_animation_frame)
  1026. context.last_completed_animation_frame_index = context.animation_frames.size() - 1;
  1027. context.animation_frames.append({ fcTL });
  1028. if (!context.has_seen_idat_chunk && is_first_animation_frame)
  1029. context.is_first_idat_part_of_animation = true;
  1030. return {};
  1031. }
  1032. static ErrorOr<void> process_fdAT(ReadonlyBytes data, PNGLoadingContext& context)
  1033. {
  1034. // https://www.w3.org/TR/png/#fdAT-chunk
  1035. if (data.size() <= 4)
  1036. return Error::from_string_literal("fdAT chunk has an abnormal size");
  1037. u32 sequence_number = *bit_cast<NetworkOrdered<u32> const*>(data.data());
  1038. if (sequence_number != context.animation_next_expected_seq)
  1039. return Error::from_string_literal("Unexpected sequence number");
  1040. context.animation_next_expected_seq++;
  1041. if (context.animation_frames.is_empty())
  1042. return Error::from_string_literal("No frame available");
  1043. auto& current_animation_frame = context.animation_frames[context.animation_frames.size() - 1];
  1044. auto compressed_data = data.slice(4);
  1045. current_animation_frame.compressed_data.append(compressed_data.data(), compressed_data.size());
  1046. return {};
  1047. }
  1048. static void process_IEND(ReadonlyBytes, PNGLoadingContext& context)
  1049. {
  1050. // https://www.w3.org/TR/png/#11IEND
  1051. if (context.has_seen_actl_chunk_before_idat)
  1052. context.last_completed_animation_frame_index = context.animation_frames.size();
  1053. context.has_seen_iend = true;
  1054. }
  1055. static ErrorOr<void> process_chunk(Streamer& streamer, PNGLoadingContext& context)
  1056. {
  1057. u32 chunk_size;
  1058. if (!streamer.read(chunk_size)) {
  1059. dbgln_if(PNG_DEBUG, "Bail at chunk_size");
  1060. return Error::from_string_literal("Error while reading from Streamer");
  1061. }
  1062. Array<u8, 4> chunk_type_buffer;
  1063. StringView const chunk_type { chunk_type_buffer.span() };
  1064. if (!streamer.read_bytes(chunk_type_buffer.data(), chunk_type_buffer.size())) {
  1065. dbgln_if(PNG_DEBUG, "Bail at chunk_type");
  1066. return Error::from_string_literal("Error while reading from Streamer");
  1067. }
  1068. ReadonlyBytes chunk_data;
  1069. if (!streamer.wrap_bytes(chunk_data, chunk_size)) {
  1070. dbgln_if(PNG_DEBUG, "Bail at chunk_data");
  1071. return Error::from_string_literal("Error while reading from Streamer");
  1072. }
  1073. u32 chunk_crc;
  1074. if (!streamer.read(chunk_crc)) {
  1075. dbgln_if(PNG_DEBUG, "Bail at chunk_crc");
  1076. return Error::from_string_literal("Error while reading from Streamer");
  1077. }
  1078. dbgln_if(PNG_DEBUG, "Chunk type: '{}', size: {}, crc: {:x}", chunk_type, chunk_size, chunk_crc);
  1079. if (chunk_type == "IHDR"sv) {
  1080. if (context.state >= PNGLoadingContext::IHDRDecoded)
  1081. return Error::from_string_literal("Multiple IHDR chunks");
  1082. return process_IHDR(chunk_data, context);
  1083. }
  1084. if (context.state < PNGLoadingContext::IHDRDecoded)
  1085. return Error::from_string_literal("IHDR is not the first chunk of the file");
  1086. if (chunk_type == "IDAT"sv)
  1087. return process_IDAT(chunk_data, context);
  1088. if (chunk_type == "PLTE"sv)
  1089. return process_PLTE(chunk_data, context);
  1090. if (chunk_type == "cHRM"sv)
  1091. return process_cHRM(chunk_data, context);
  1092. if (chunk_type == "cICP"sv)
  1093. return process_cICP(chunk_data, context);
  1094. if (chunk_type == "iCCP"sv)
  1095. return process_iCCP(chunk_data, context);
  1096. if (chunk_type == "gAMA"sv)
  1097. return process_gAMA(chunk_data, context);
  1098. if (chunk_type == "sRGB"sv)
  1099. return process_sRGB(chunk_data, context);
  1100. if (chunk_type == "tRNS"sv)
  1101. return process_tRNS(chunk_data, context);
  1102. if (chunk_type == "acTL"sv)
  1103. return process_acTL(chunk_data, context);
  1104. if (chunk_type == "fcTL"sv)
  1105. return process_fcTL(chunk_data, context);
  1106. if (chunk_type == "fdAT"sv)
  1107. return process_fdAT(chunk_data, context);
  1108. if (chunk_type == "IEND"sv)
  1109. process_IEND(chunk_data, context);
  1110. return {};
  1111. }
  1112. PNGImageDecoderPlugin::PNGImageDecoderPlugin(u8 const* data, size_t size)
  1113. {
  1114. m_context = make<PNGLoadingContext>();
  1115. m_context->data = m_context->data_current_ptr = data;
  1116. m_context->data_size = size;
  1117. }
  1118. PNGImageDecoderPlugin::~PNGImageDecoderPlugin() = default;
  1119. bool PNGImageDecoderPlugin::ensure_image_data_chunk_was_decoded()
  1120. {
  1121. if (m_context->state == PNGLoadingContext::State::Error)
  1122. return false;
  1123. if (m_context->state < PNGLoadingContext::State::ImageDataChunkDecoded) {
  1124. if (!decode_png_image_data_chunk(*m_context))
  1125. return false;
  1126. }
  1127. return true;
  1128. }
  1129. bool PNGImageDecoderPlugin::ensure_animation_frame_was_decoded(u32 animation_frame_index)
  1130. {
  1131. if (m_context->state == PNGLoadingContext::State::Error)
  1132. return false;
  1133. if (m_context->state < PNGLoadingContext::State::ImageDataChunkDecoded) {
  1134. if (!decode_png_image_data_chunk(*m_context))
  1135. return false;
  1136. }
  1137. if (m_context->last_completed_animation_frame_index.has_value()) {
  1138. if (m_context->last_completed_animation_frame_index.value() >= animation_frame_index)
  1139. return true;
  1140. }
  1141. return decode_png_animation_data_chunks(*m_context, animation_frame_index);
  1142. }
  1143. IntSize PNGImageDecoderPlugin::size()
  1144. {
  1145. return { m_context->width, m_context->height };
  1146. }
  1147. bool PNGImageDecoderPlugin::sniff(ReadonlyBytes data)
  1148. {
  1149. PNGLoadingContext context;
  1150. context.data = context.data_current_ptr = data.data();
  1151. context.data_size = data.size();
  1152. return decode_png_header(context);
  1153. }
  1154. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> PNGImageDecoderPlugin::create(ReadonlyBytes data)
  1155. {
  1156. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) PNGImageDecoderPlugin(data.data(), data.size())));
  1157. if (!decode_png_header(*plugin->m_context))
  1158. return Error::from_string_literal("Invalid header for a PNG file");
  1159. TRY(decode_png_ihdr(*plugin->m_context));
  1160. return plugin;
  1161. }
  1162. bool PNGImageDecoderPlugin::is_animated()
  1163. {
  1164. if (!ensure_image_data_chunk_was_decoded())
  1165. return false;
  1166. return m_context->has_seen_actl_chunk_before_idat;
  1167. }
  1168. size_t PNGImageDecoderPlugin::loop_count()
  1169. {
  1170. if (!ensure_image_data_chunk_was_decoded())
  1171. return 0;
  1172. return m_context->animation_loop_count;
  1173. }
  1174. size_t PNGImageDecoderPlugin::frame_count()
  1175. {
  1176. if (!ensure_image_data_chunk_was_decoded())
  1177. return 0;
  1178. if (!m_context->has_seen_actl_chunk_before_idat)
  1179. return 1;
  1180. auto total_frames = m_context->animation_frame_count;
  1181. if (!m_context->is_first_idat_part_of_animation)
  1182. total_frames++;
  1183. return total_frames;
  1184. }
  1185. size_t PNGImageDecoderPlugin::first_animated_frame_index()
  1186. {
  1187. if (!ensure_image_data_chunk_was_decoded())
  1188. return 0;
  1189. if (!m_context->has_seen_actl_chunk_before_idat)
  1190. return 0;
  1191. return m_context->is_first_idat_part_of_animation ? 0 : 1;
  1192. }
  1193. static ErrorOr<RefPtr<Bitmap>> render_animation_frame(AnimationFrame const& prev_animation_frame, AnimationFrame& animation_frame, Bitmap const& decoded_frame_bitmap)
  1194. {
  1195. auto rendered_bitmap = TRY(prev_animation_frame.bitmap->clone());
  1196. Painter painter(rendered_bitmap);
  1197. static constexpr Color transparent_black = { 0, 0, 0, 0 };
  1198. auto frame_rect = animation_frame.rect();
  1199. switch (prev_animation_frame.fcTL.dispose_op) {
  1200. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_NONE:
  1201. break;
  1202. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_BACKGROUND:
  1203. painter.clear_rect(rendered_bitmap->rect(), transparent_black);
  1204. break;
  1205. case fcTL_Chunk::DisposeOp::APNG_DISPOSE_OP_PREVIOUS: {
  1206. painter.blit(frame_rect.location(), *prev_animation_frame.bitmap, frame_rect, 1.0f, false);
  1207. break;
  1208. }
  1209. }
  1210. switch (animation_frame.fcTL.blend_op) {
  1211. case fcTL_Chunk::BlendOp::APNG_BLEND_OP_SOURCE:
  1212. painter.blit(frame_rect.location(), decoded_frame_bitmap, decoded_frame_bitmap.rect(), 1.0f, false);
  1213. break;
  1214. case fcTL_Chunk::BlendOp::APNG_BLEND_OP_OVER:
  1215. painter.blit(frame_rect.location(), decoded_frame_bitmap, decoded_frame_bitmap.rect(), 1.0f, true);
  1216. break;
  1217. }
  1218. return rendered_bitmap;
  1219. }
  1220. ErrorOr<ImageFrameDescriptor> PNGImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1221. {
  1222. if (m_context->state == PNGLoadingContext::State::Error)
  1223. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
  1224. if (!ensure_image_data_chunk_was_decoded())
  1225. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding image data chunk");
  1226. auto set_descriptor_duration = [](ImageFrameDescriptor& descriptor, AnimationFrame const& animation_frame) {
  1227. descriptor.duration = static_cast<int>(animation_frame.duration_ms());
  1228. if (descriptor.duration < 0)
  1229. descriptor.duration = NumericLimits<int>::min();
  1230. };
  1231. auto load_default_image = [&]() -> ErrorOr<void> {
  1232. if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
  1233. // NOTE: This forces the chunk decoding to happen.
  1234. TRY(decode_png_bitmap(*m_context));
  1235. }
  1236. VERIFY(m_context->bitmap);
  1237. return {};
  1238. };
  1239. if (index == 0) {
  1240. TRY(load_default_image());
  1241. ImageFrameDescriptor descriptor { m_context->bitmap };
  1242. if (m_context->has_seen_actl_chunk_before_idat && m_context->is_first_idat_part_of_animation)
  1243. set_descriptor_duration(descriptor, m_context->animation_frames[0]);
  1244. return descriptor;
  1245. }
  1246. if (!m_context->has_seen_actl_chunk_before_idat)
  1247. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid frame index");
  1248. if (!ensure_animation_frame_was_decoded(index))
  1249. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding image data chunk");
  1250. if (index >= m_context->animation_frames.size())
  1251. return Error::from_string_literal("PNGImageDecoderPlugin: Invalid animation frame index");
  1252. // We need to assemble each frame up until the one requested,
  1253. // so decode all bitmaps that haven't been decoded yet.
  1254. for (size_t i = m_context->animation_next_frame_to_render; i <= index; i++) {
  1255. if (i == 0) {
  1256. // If the default image hasn't been loaded, load it now
  1257. TRY(load_default_image()); // May modify animation_frames!
  1258. auto& animation_frame = m_context->animation_frames[i];
  1259. animation_frame.bitmap = m_context->bitmap;
  1260. } else {
  1261. auto& animation_frame = m_context->animation_frames[i];
  1262. VERIFY(!animation_frame.bitmap);
  1263. auto decoded_bitmap = TRY(decode_png_animation_frame_bitmap(*m_context, animation_frame));
  1264. auto prev_animation_frame = m_context->animation_frames[i - 1];
  1265. animation_frame.bitmap = TRY(render_animation_frame(prev_animation_frame, animation_frame, *decoded_bitmap));
  1266. }
  1267. m_context->animation_next_frame_to_render = i + 1;
  1268. }
  1269. auto const& animation_frame = m_context->animation_frames[index];
  1270. VERIFY(animation_frame.bitmap);
  1271. ImageFrameDescriptor descriptor { animation_frame.bitmap };
  1272. set_descriptor_duration(descriptor, animation_frame);
  1273. return descriptor;
  1274. }
  1275. ErrorOr<Optional<ReadonlyBytes>> PNGImageDecoderPlugin::icc_data()
  1276. {
  1277. if (!decode_png_chunks(*m_context))
  1278. return Error::from_string_literal("PNGImageDecoderPlugin: Decoding chunks failed");
  1279. if (m_context->embedded_icc_profile.has_value()) {
  1280. if (!m_context->decompressed_icc_profile.has_value()) {
  1281. auto compressed_data_stream = make<FixedMemoryStream>(m_context->embedded_icc_profile->compressed_data);
  1282. auto decompressor_or_error = Compress::ZlibDecompressor::create(move(compressed_data_stream));
  1283. if (decompressor_or_error.is_error()) {
  1284. m_context->embedded_icc_profile.clear();
  1285. return decompressor_or_error.release_error();
  1286. }
  1287. auto decompressor = decompressor_or_error.release_value();
  1288. auto result_or_error = decompressor->read_until_eof();
  1289. if (result_or_error.is_error()) {
  1290. m_context->embedded_icc_profile.clear();
  1291. return result_or_error.release_error();
  1292. }
  1293. m_context->decompressed_icc_profile = result_or_error.release_value();
  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. }