WebPLoader.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. /*
  2. * Copyright (c) 2023, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/BitStream.h>
  7. #include <AK/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/Format.h>
  10. #include <AK/MemoryStream.h>
  11. #include <AK/Vector.h>
  12. #include <LibCompress/Deflate.h>
  13. #include <LibGfx/ImageFormats/WebPLoader.h>
  14. // Overview: https://developers.google.com/speed/webp/docs/compression
  15. // Container: https://developers.google.com/speed/webp/docs/riff_container
  16. // Lossless format: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification
  17. // Lossy format: https://datatracker.ietf.org/doc/html/rfc6386
  18. namespace Gfx {
  19. namespace {
  20. struct FourCC {
  21. constexpr FourCC(char const* name)
  22. {
  23. cc[0] = name[0];
  24. cc[1] = name[1];
  25. cc[2] = name[2];
  26. cc[3] = name[3];
  27. }
  28. bool operator==(FourCC const&) const = default;
  29. bool operator!=(FourCC const&) const = default;
  30. char cc[4];
  31. };
  32. // https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
  33. struct WebPFileHeader {
  34. FourCC riff;
  35. LittleEndian<u32> file_size;
  36. FourCC webp;
  37. };
  38. static_assert(AssertSize<WebPFileHeader, 12>());
  39. struct ChunkHeader {
  40. FourCC chunk_type;
  41. LittleEndian<u32> chunk_size;
  42. };
  43. static_assert(AssertSize<ChunkHeader, 8>());
  44. struct Chunk {
  45. FourCC type;
  46. ReadonlyBytes data;
  47. };
  48. struct VP8Header {
  49. u8 version;
  50. bool show_frame;
  51. u32 size_of_first_partition;
  52. u32 width;
  53. u8 horizontal_scale;
  54. u32 height;
  55. u8 vertical_scale;
  56. };
  57. struct VP8LHeader {
  58. u16 width;
  59. u16 height;
  60. bool is_alpha_used;
  61. };
  62. struct VP8XHeader {
  63. bool has_icc;
  64. bool has_alpha;
  65. bool has_exif;
  66. bool has_xmp;
  67. bool has_animation;
  68. u32 width;
  69. u32 height;
  70. };
  71. struct ANIMChunk {
  72. u32 background_color;
  73. u16 loop_count;
  74. };
  75. }
  76. struct WebPLoadingContext {
  77. enum State {
  78. NotDecoded = 0,
  79. Error,
  80. HeaderDecoded,
  81. FirstChunkRead,
  82. FirstChunkDecoded,
  83. ChunksDecoded,
  84. BitmapDecoded,
  85. };
  86. State state { State::NotDecoded };
  87. ReadonlyBytes data;
  88. ReadonlyBytes chunks_cursor;
  89. Optional<IntSize> size;
  90. RefPtr<Gfx::Bitmap> bitmap;
  91. // Either 'VP8 ' (simple lossy file), 'VP8L' (simple lossless file), or 'VP8X' (extended file).
  92. Optional<Chunk> first_chunk;
  93. union {
  94. VP8Header vp8_header;
  95. VP8LHeader vp8l_header;
  96. VP8XHeader vp8x_header;
  97. };
  98. // If first_chunk is not a VP8X chunk, then only image_data_chunk is set and all the other Chunks are not set.
  99. // "For a still image, the image data consists of a single frame, which is made up of:
  100. // An optional alpha subchunk.
  101. // A bitstream subchunk."
  102. Optional<Chunk> alpha_chunk; // 'ALPH'
  103. Optional<Chunk> image_data_chunk; // Either 'VP8 ' or 'VP8L'.
  104. Optional<Chunk> animation_header_chunk; // 'ANIM'
  105. Vector<Chunk> animation_frame_chunks; // 'ANMF'
  106. Optional<Chunk> iccp_chunk; // 'ICCP'
  107. Optional<Chunk> exif_chunk; // 'EXIF'
  108. Optional<Chunk> xmp_chunk; // 'XMP '
  109. template<size_t N>
  110. [[nodiscard]] class Error error(char const (&string_literal)[N])
  111. {
  112. state = WebPLoadingContext::State::Error;
  113. return Error::from_string_literal(string_literal);
  114. }
  115. };
  116. // https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
  117. static ErrorOr<void> decode_webp_header(WebPLoadingContext& context)
  118. {
  119. if (context.state >= WebPLoadingContext::HeaderDecoded)
  120. return {};
  121. if (context.data.size() < sizeof(WebPFileHeader))
  122. return context.error("Missing WebP header");
  123. auto& header = *bit_cast<WebPFileHeader const*>(context.data.data());
  124. if (header.riff != FourCC("RIFF") || header.webp != FourCC("WEBP"))
  125. return context.error("Invalid WebP header");
  126. // "File Size: [...] The size of the file in bytes starting at offset 8. The maximum value of this field is 2^32 minus 10 bytes."
  127. u32 const maximum_webp_file_size = 0xffff'ffff - 9;
  128. if (header.file_size > maximum_webp_file_size)
  129. return context.error("WebP header file size over maximum");
  130. // "The file size in the header is the total size of the chunks that follow plus 4 bytes for the 'WEBP' FourCC.
  131. // The file SHOULD NOT contain any data after the data specified by File Size.
  132. // Readers MAY parse such files, ignoring the trailing data."
  133. if (context.data.size() - 8 < header.file_size)
  134. return context.error("WebP data too small for size in header");
  135. if (context.data.size() - 8 > header.file_size) {
  136. dbgln_if(WEBP_DEBUG, "WebP has {} bytes of data, but header needs only {}. Trimming.", context.data.size(), header.file_size + 8);
  137. context.data = context.data.trim(header.file_size + 8);
  138. }
  139. context.state = WebPLoadingContext::HeaderDecoded;
  140. return {};
  141. }
  142. // https://developers.google.com/speed/webp/docs/riff_container#riff_file_format
  143. static ErrorOr<Chunk> decode_webp_chunk_header(WebPLoadingContext& context, ReadonlyBytes chunks)
  144. {
  145. if (chunks.size() < sizeof(ChunkHeader))
  146. return context.error("Not enough data for WebP chunk header");
  147. auto const& header = *bit_cast<ChunkHeader const*>(chunks.data());
  148. dbgln_if(WEBP_DEBUG, "chunk {} size {}", header.chunk_type, header.chunk_size);
  149. if (chunks.size() < sizeof(ChunkHeader) + header.chunk_size)
  150. return context.error("Not enough data for WebP chunk");
  151. return Chunk { header.chunk_type, { chunks.data() + sizeof(ChunkHeader), header.chunk_size } };
  152. }
  153. // https://developers.google.com/speed/webp/docs/riff_container#riff_file_format
  154. static ErrorOr<Chunk> decode_webp_advance_chunk(WebPLoadingContext& context, ReadonlyBytes& chunks)
  155. {
  156. auto chunk = TRY(decode_webp_chunk_header(context, chunks));
  157. // "Chunk Size: 32 bits (uint32)
  158. // The size of the chunk in bytes, not including this field, the chunk identifier or padding.
  159. // Chunk Payload: Chunk Size bytes
  160. // The data payload. If Chunk Size is odd, a single padding byte -- that MUST be 0 to conform with RIFF -- is added."
  161. chunks = chunks.slice(sizeof(ChunkHeader) + chunk.data.size());
  162. if (chunk.data.size() % 2 != 0) {
  163. if (chunks.is_empty())
  164. return context.error("Missing data for padding byte");
  165. if (*chunks.data() != 0)
  166. return context.error("Padding byte is not 0");
  167. chunks = chunks.slice(1);
  168. }
  169. return chunk;
  170. }
  171. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossy
  172. // https://datatracker.ietf.org/doc/html/rfc6386#section-19 "Annex A: Bitstream Syntax"
  173. static ErrorOr<VP8Header> decode_webp_chunk_VP8_header(WebPLoadingContext& context, Chunk const& vp8_chunk)
  174. {
  175. VERIFY(vp8_chunk.type == FourCC("VP8 "));
  176. if (vp8_chunk.data.size() < 10)
  177. return context.error("WebPImageDecoderPlugin: 'VP8 ' chunk too small");
  178. // FIXME: Eventually, this should probably call into LibVideo/VP8,
  179. // and image decoders should move into LibImageDecoders which depends on both LibGfx and LibVideo.
  180. // (LibVideo depends on LibGfx, so LibGfx can't depend on LibVideo itself.)
  181. // https://datatracker.ietf.org/doc/html/rfc6386#section-4 "Overview of Compressed Data Format"
  182. // "The decoder is simply presented with a sequence of compressed frames [...]
  183. // The first frame presented to the decompressor is [...] a key frame. [...]
  184. // [E]very compressed frame has three or more pieces. It begins with an uncompressed data chunk comprising 10 bytes in the case of key frames
  185. u8 const* data = vp8_chunk.data.data();
  186. // https://datatracker.ietf.org/doc/html/rfc6386#section-9.1 "Uncompressed Data Chunk"
  187. u32 frame_tag = data[0] | (data[1] << 8) | (data[2] << 16);
  188. bool is_key_frame = (frame_tag & 1) == 0; // https://www.rfc-editor.org/errata/eid5534
  189. u8 version = (frame_tag & 0xe) >> 1;
  190. bool show_frame = (frame_tag & 0x10) != 0;
  191. u32 size_of_first_partition = frame_tag >> 5;
  192. if (!is_key_frame)
  193. return context.error("WebPImageDecoderPlugin: 'VP8 ' chunk not a key frame");
  194. // FIXME: !show_frame does not make sense in a webp file either, probably?
  195. u32 start_code = data[3] | (data[4] << 8) | (data[5] << 16);
  196. if (start_code != 0x2a019d) // https://www.rfc-editor.org/errata/eid7370
  197. return context.error("WebPImageDecoderPlugin: 'VP8 ' chunk invalid start_code");
  198. // "The scaling specifications for each dimension are encoded as follows.
  199. // 0 | No upscaling (the most common case).
  200. // 1 | Upscale by 5/4.
  201. // 2 | Upscale by 5/3.
  202. // 3 | Upscale by 2."
  203. // This is a display-time operation and doesn't affect decoding.
  204. u16 width_and_horizontal_scale = data[6] | (data[7] << 8);
  205. u16 width = width_and_horizontal_scale & 0x3fff;
  206. u8 horizontal_scale = width_and_horizontal_scale >> 14;
  207. u16 heigth_and_vertical_scale = data[8] | (data[9] << 8);
  208. u16 height = heigth_and_vertical_scale & 0x3fff;
  209. u8 vertical_scale = heigth_and_vertical_scale >> 14;
  210. dbgln_if(WEBP_DEBUG, "version {}, show_frame {}, size_of_first_partition {}, width {}, horizontal_scale {}, height {}, vertical_scale {}",
  211. version, show_frame, size_of_first_partition, width, horizontal_scale, height, vertical_scale);
  212. return VP8Header { version, show_frame, size_of_first_partition, width, horizontal_scale, height, vertical_scale };
  213. }
  214. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
  215. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#7_overall_structure_of_the_format
  216. static ErrorOr<VP8LHeader> decode_webp_chunk_VP8L_header(WebPLoadingContext& context, Chunk const& vp8l_chunk)
  217. {
  218. VERIFY(vp8l_chunk.type == FourCC("VP8L"));
  219. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#3_riff_header
  220. if (vp8l_chunk.data.size() < 5)
  221. return context.error("WebPImageDecoderPlugin: VP8L chunk too small");
  222. FixedMemoryStream memory_stream { vp8l_chunk.data.trim(5) };
  223. LittleEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream) };
  224. u8 signature = TRY(bit_stream.read_bits(8));
  225. if (signature != 0x2f)
  226. return context.error("WebPImageDecoderPlugin: VP8L chunk invalid signature");
  227. // 14 bits width-1, 14 bits height-1, 1 bit alpha hint, 3 bit version_number.
  228. u16 width = TRY(bit_stream.read_bits(14)) + 1;
  229. u16 height = TRY(bit_stream.read_bits(14)) + 1;
  230. bool is_alpha_used = TRY(bit_stream.read_bits(1)) != 0;
  231. u8 version_number = TRY(bit_stream.read_bits(3));
  232. VERIFY(bit_stream.is_eof());
  233. dbgln_if(WEBP_DEBUG, "width {}, height {}, is_alpha_used {}, version_number {}",
  234. width, height, is_alpha_used, version_number);
  235. // "The version_number is a 3 bit code that must be set to 0. Any other value should be treated as an error. [AMENDED]"
  236. if (version_number != 0)
  237. return context.error("WebPImageDecoderPlugin: VP8L chunk invalid version_number");
  238. return VP8LHeader { width, height, is_alpha_used };
  239. }
  240. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#61_overview
  241. // "From here on, we refer to this set as a prefix code group."
  242. class PrefixCodeGroup {
  243. public:
  244. Compress::CanonicalCode& operator[](int i) { return m_codes[i]; }
  245. Compress::CanonicalCode const& operator[](int i) const { return m_codes[i]; }
  246. private:
  247. Array<Compress::CanonicalCode, 5> m_codes;
  248. };
  249. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#621_decoding_and_building_the_prefix_codes
  250. static ErrorOr<Compress::CanonicalCode> decode_webp_chunk_VP8L_prefix_code(WebPLoadingContext& context, LittleEndianInputBitStream& bit_stream, size_t alphabet_size)
  251. {
  252. // prefix-code = simple-prefix-code / normal-prefix-code
  253. bool is_simple_code_length_code = TRY(bit_stream.read_bits(1));
  254. dbgln_if(WEBP_DEBUG, "is_simple_code_length_code {}", is_simple_code_length_code);
  255. Vector<u8, 286> code_lengths;
  256. if (is_simple_code_length_code) {
  257. TRY(code_lengths.try_resize(alphabet_size));
  258. int num_symbols = TRY(bit_stream.read_bits(1)) + 1;
  259. int is_first_8bits = TRY(bit_stream.read_bits(1));
  260. u8 symbol0 = TRY(bit_stream.read_bits(1 + 7 * is_first_8bits));
  261. dbgln_if(WEBP_DEBUG, " symbol0 {}", symbol0);
  262. if (symbol0 >= code_lengths.size())
  263. return Error::from_string_literal("symbol0 out of bounds");
  264. code_lengths[symbol0] = 1;
  265. if (num_symbols == 2) {
  266. u8 symbol1 = TRY(bit_stream.read_bits(8));
  267. dbgln_if(WEBP_DEBUG, " symbol1 {}", symbol1);
  268. if (symbol1 >= code_lengths.size())
  269. return Error::from_string_literal("symbol1 out of bounds");
  270. code_lengths[symbol1] = 1;
  271. }
  272. return Compress::CanonicalCode::from_bytes(code_lengths);
  273. }
  274. // This has plenty in common with deflate (cf DeflateDecompressor::decode_codes() in Deflate.cpp in LibCompress)
  275. // Symbol 16 has different semantics, and kCodeLengthCodeOrder is different. Other than that, this is virtually deflate.
  276. // (...but webp uses 5 different prefix codes, while deflate doesn't.)
  277. int num_code_lengths = 4 + TRY(bit_stream.read_bits(4));
  278. dbgln_if(WEBP_DEBUG, " num_code_lengths {}", num_code_lengths);
  279. // "If num_code_lengths is > 19, the bit_stream is invalid. [AMENDED3]"
  280. if (num_code_lengths > 19)
  281. return context.error("WebPImageDecoderPlugin: invalid num_code_lengths");
  282. constexpr int kCodeLengthCodes = 19;
  283. int kCodeLengthCodeOrder[kCodeLengthCodes] = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
  284. u8 code_length_code_lengths[kCodeLengthCodes] = { 0 }; // "All zeros" [sic]
  285. for (int i = 0; i < num_code_lengths; ++i) {
  286. code_length_code_lengths[kCodeLengthCodeOrder[i]] = TRY(bit_stream.read_bits(3));
  287. dbgln_if(WEBP_DEBUG, " code_length_code_lengths[{}] = {}", kCodeLengthCodeOrder[i], code_length_code_lengths[kCodeLengthCodeOrder[i]]);
  288. }
  289. int max_symbol = num_code_lengths;
  290. if (TRY(bit_stream.read_bits(1))) {
  291. int length_nbits = 2 + 2 * TRY(bit_stream.read_bits(3));
  292. max_symbol = 2 + TRY(bit_stream.read_bits(length_nbits));
  293. dbgln_if(WEBP_DEBUG, " extended, length_nbits {} max_symbol {}", length_nbits, max_symbol);
  294. }
  295. auto const code_length_code = TRY(Compress::CanonicalCode::from_bytes({ code_length_code_lengths, sizeof(code_length_code_lengths) }));
  296. // Next we extract the code lengths of the code that was used to encode the block.
  297. u8 last_non_zero = 8; // "If code 16 is used before a non-zero value has been emitted, a value of 8 is repeated."
  298. // "A prefix table is then built from code_length_code_lengths and used to read up to max_symbol code lengths."
  299. // FIXME: what's max_symbol good for? (seems to work with alphabet_size)
  300. while (code_lengths.size() < alphabet_size) {
  301. auto symbol = TRY(code_length_code.read_symbol(bit_stream));
  302. if (symbol < 16) {
  303. // "Code [0..15] indicates literal code lengths."
  304. dbgln_if(WEBP_DEBUG, " append {}", symbol);
  305. code_lengths.append(static_cast<u8>(symbol));
  306. if (symbol != 0)
  307. last_non_zero = symbol;
  308. } else if (symbol == 16) {
  309. // "Code 16 repeats the previous non-zero value [3..6] times, i.e., 3 + ReadBits(2) times."
  310. auto nrepeat = 3 + TRY(bit_stream.read_bits(2));
  311. dbgln_if(WEBP_DEBUG, " repeat {} {}s", nrepeat, last_non_zero);
  312. // This is different from deflate.
  313. for (size_t j = 0; j < nrepeat; ++j)
  314. code_lengths.append(last_non_zero);
  315. } else if (symbol == 17) {
  316. // "Code 17 emits a streak of zeros [3..10], i.e., 3 + ReadBits(3) times."
  317. auto nrepeat = 3 + TRY(bit_stream.read_bits(3));
  318. dbgln_if(WEBP_DEBUG, " repeat {} zeroes", nrepeat);
  319. for (size_t j = 0; j < nrepeat; ++j)
  320. code_lengths.append(0);
  321. } else {
  322. VERIFY(symbol == 18);
  323. // "Code 18 emits a streak of zeros of length [11..138], i.e., 11 + ReadBits(7) times."
  324. auto nrepeat = 11 + TRY(bit_stream.read_bits(7));
  325. dbgln_if(WEBP_DEBUG, " Repeat {} zeroes", nrepeat);
  326. for (size_t j = 0; j < nrepeat; ++j)
  327. code_lengths.append(0);
  328. }
  329. }
  330. if (code_lengths.size() != alphabet_size)
  331. return Error::from_string_literal("Number of code lengths does not match the sum of codes");
  332. return Compress::CanonicalCode::from_bytes(code_lengths);
  333. }
  334. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#622_decoding_of_meta_prefix_codes
  335. // The description of prefix code groups is in "Decoding of Meta Prefix Codes", even though prefix code groups are used
  336. // in regular images without meta prefix code as well ¯\_(ツ)_/¯.
  337. static ErrorOr<PrefixCodeGroup> decode_webp_chunk_VP8L_prefix_code_group(WebPLoadingContext& context, u16 color_cache_size, LittleEndianInputBitStream& bit_stream)
  338. {
  339. // prefix-code-group =
  340. // 5prefix-code ; See "Interpretation of Meta Prefix Codes" to
  341. // ; understand what each of these five prefix
  342. // ; codes are for.
  343. // "Once code lengths are read, a prefix code for each symbol type (A, R, G, B, distance) is formed using their respective alphabet sizes:
  344. // * G channel: 256 + 24 + color_cache_size
  345. // * other literals (A,R,B): 256
  346. // * distance code: 40"
  347. static Array<size_t, 5> const alphabet_sizes { 256 + 24 + static_cast<size_t>(color_cache_size), 256, 256, 256, 40 };
  348. PrefixCodeGroup group;
  349. for (size_t i = 0; i < alphabet_sizes.size(); ++i)
  350. group[i] = TRY(decode_webp_chunk_VP8L_prefix_code(context, bit_stream, alphabet_sizes[i]));
  351. return group;
  352. }
  353. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
  354. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#7_overall_structure_of_the_format
  355. static ErrorOr<void> decode_webp_chunk_VP8L(WebPLoadingContext& context, Chunk const& vp8l_chunk)
  356. {
  357. VERIFY(context.first_chunk->type == FourCC("VP8L") || context.first_chunk->type == FourCC("VP8X"));
  358. VERIFY(vp8l_chunk.type == FourCC("VP8L"));
  359. auto vp8l_header = TRY(decode_webp_chunk_VP8L_header(context, vp8l_chunk));
  360. // Check that size in VP8X chunk matches dimensions in VP8L chunk if both are present.
  361. if (context.first_chunk->type == FourCC("VP8X")) {
  362. if (vp8l_header.width != context.vp8x_header.width)
  363. return context.error("WebPImageDecoderPlugin: VP8X and VP8L chunks store different widths");
  364. if (vp8l_header.height != context.vp8x_header.height)
  365. return context.error("WebPImageDecoderPlugin: VP8X and VP8L chunks store different heights");
  366. if (vp8l_header.is_alpha_used != context.vp8x_header.has_alpha)
  367. return context.error("WebPImageDecoderPlugin: VP8X and VP8L chunks store different alpha");
  368. }
  369. FixedMemoryStream memory_stream { vp8l_chunk.data.slice(5) };
  370. LittleEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream) };
  371. // image-stream = optional-transform spatially-coded-image
  372. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#4_transformations
  373. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#72_structure_of_transforms
  374. // optional-transform = (%b1 transform optional-transform) / %b0
  375. while (TRY(bit_stream.read_bits(1))) {
  376. // transform = predictor-tx / color-tx / subtract-green-tx
  377. // transform =/ color-indexing-tx
  378. enum TransformType {
  379. // predictor-tx = %b00 predictor-image
  380. PREDICTOR_TRANSFORM = 0,
  381. // color-tx = %b01 color-image
  382. COLOR_TRANSFORM = 1,
  383. // subtract-green-tx = %b10
  384. SUBTRACT_GREEN_TRANSFORM = 2,
  385. // color-indexing-tx = %b11 color-indexing-image
  386. COLOR_INDEXING_TRANSFORM = 3,
  387. };
  388. TransformType transform_type = static_cast<TransformType>(TRY(bit_stream.read_bits(2)));
  389. dbgln_if(WEBP_DEBUG, "transform type {}", (int)transform_type);
  390. switch (transform_type) {
  391. case PREDICTOR_TRANSFORM:
  392. return context.error("WebPImageDecoderPlugin: VP8L PREDICTOR_TRANSFORM handling not yet implemented");
  393. case COLOR_TRANSFORM:
  394. return context.error("WebPImageDecoderPlugin: VP8L COLOR_TRANSFORM handling not yet implemented");
  395. case SUBTRACT_GREEN_TRANSFORM:
  396. return context.error("WebPImageDecoderPlugin: VP8L SUBTRACT_GREEN_TRANSFORM handling not yet implemented");
  397. case COLOR_INDEXING_TRANSFORM:
  398. return context.error("WebPImageDecoderPlugin: VP8L COLOR_INDEXING_TRANSFORM handling not yet implemented");
  399. }
  400. }
  401. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#623_decoding_entropy-coded_image_data
  402. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#523_color_cache_coding
  403. // spatially-coded-image = color-cache-info meta-prefix data
  404. // color-cache-info = %b0
  405. // color-cache-info =/ (%b1 4BIT) ; 1 followed by color cache size
  406. bool has_color_cache_info = TRY(bit_stream.read_bits(1));
  407. u16 color_cache_size = 0;
  408. u8 color_cache_code_bits;
  409. dbgln_if(WEBP_DEBUG, "has_color_cache_info {}", has_color_cache_info);
  410. Vector<ARGB32, 32> color_cache;
  411. if (has_color_cache_info) {
  412. color_cache_code_bits = TRY(bit_stream.read_bits(4));
  413. // "The range of allowed values for color_cache_code_bits is [1..11]. Compliant decoders must indicate a corrupted bitstream for other values."
  414. if (color_cache_code_bits < 1 || color_cache_code_bits > 11)
  415. return context.error("WebPImageDecoderPlugin: VP8L invalid color_cache_code_bits");
  416. color_cache_size = 1 << color_cache_code_bits;
  417. dbgln_if(WEBP_DEBUG, "color_cache_size {}", color_cache_size);
  418. TRY(color_cache.try_resize(color_cache_size));
  419. }
  420. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#622_decoding_of_meta_prefix_codes
  421. // "Meta prefix codes may be used only when the image is being used in the role of an ARGB image."
  422. // meta-prefix = %b0 / (%b1 entropy-image)
  423. bool has_meta_prefix = TRY(bit_stream.read_bits(1));
  424. dbgln_if(WEBP_DEBUG, "has_meta_prefix {}", has_meta_prefix);
  425. if (has_meta_prefix)
  426. return context.error("WebPImageDecoderPlugin: VP8L meta_prefix not yet implemented");
  427. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#52_encoding_of_image_data
  428. // "The encoded image data consists of several parts:
  429. // 1. Decoding and building the prefix codes [AMENDED2]
  430. // 2. Meta prefix codes
  431. // 3. Entropy-coded image data"
  432. // data = prefix-codes lz77-coded-image
  433. // prefix-codes = prefix-code-group *prefix-codes
  434. PrefixCodeGroup group = TRY(decode_webp_chunk_VP8L_prefix_code_group(context, color_cache_size, bit_stream));
  435. context.bitmap = TRY(Bitmap::create(vp8l_header.is_alpha_used ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888, context.size.value()));
  436. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
  437. struct Offset {
  438. i8 x, y;
  439. };
  440. // clang-format off
  441. Array<Offset, 120> distance_map { {
  442. {0, 1}, {1, 0},
  443. {1, 1}, {-1, 1}, {0, 2}, { 2, 0},
  444. {1, 2}, {-1, 2}, {2, 1}, {-2, 1},
  445. {2, 2}, {-2, 2}, {0, 3}, { 3, 0}, { 1, 3}, {-1, 3}, { 3, 1}, {-3, 1},
  446. {2, 3}, {-2, 3}, {3, 2}, {-3, 2}, { 0, 4}, { 4, 0}, { 1, 4}, {-1, 4}, { 4, 1}, {-4, 1},
  447. {3, 3}, {-3, 3}, {2, 4}, {-2, 4}, { 4, 2}, {-4, 2}, { 0, 5},
  448. {3, 4}, {-3, 4}, {4, 3}, {-4, 3}, { 5, 0}, { 1, 5}, {-1, 5}, { 5, 1}, {-5, 1}, { 2, 5}, {-2, 5}, { 5, 2}, {-5, 2},
  449. {4, 4}, {-4, 4}, {3, 5}, {-3, 5}, { 5, 3}, {-5, 3}, { 0, 6}, { 6, 0}, { 1, 6}, {-1, 6}, { 6, 1}, {-6, 1}, { 2, 6}, {-2, 6}, {6, 2}, {-6, 2},
  450. {4, 5}, {-4, 5}, {5, 4}, {-5, 4}, { 3, 6}, {-3, 6}, { 6, 3}, {-6, 3}, { 0, 7}, { 7, 0}, { 1, 7}, {-1, 7},
  451. {5, 5}, {-5, 5}, {7, 1}, {-7, 1}, { 4, 6}, {-4, 6}, { 6, 4}, {-6, 4}, { 2, 7}, {-2, 7}, { 7, 2}, {-7, 2}, { 3, 7}, {-3, 7}, {7, 3}, {-7, 3},
  452. {5, 6}, {-5, 6}, {6, 5}, {-6, 5}, { 8, 0}, { 4, 7}, {-4, 7}, { 7, 4}, {-7, 4}, { 8, 1}, { 8, 2},
  453. {6, 6}, {-6, 6}, {8, 3}, { 5, 7}, {-5, 7}, { 7, 5}, {-7, 5}, { 8, 4},
  454. {6, 7}, {-6, 7}, {7, 6}, {-7, 6}, { 8, 5},
  455. {7, 7}, {-7, 7}, {8, 6},
  456. {8, 7},
  457. } };
  458. // clang-format on
  459. // lz77-coded-image =
  460. // *((argb-pixel / lz77-copy / color-cache-code) lz77-coded-image)
  461. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#623_decoding_entropy-coded_image_data
  462. ARGB32* pixel = context.bitmap->begin();
  463. ARGB32* end = context.bitmap->end();
  464. auto emit_pixel = [&pixel, &color_cache, color_cache_size, color_cache_code_bits](ARGB32 color) {
  465. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#523_color_cache_coding
  466. // "The state of the color cache is maintained by inserting every pixel, be it produced by backward referencing or as literals, into the cache in the order they appear in the stream."
  467. *pixel++ = color;
  468. if (color_cache_size)
  469. color_cache[(0x1e35a7bd * color) >> (32 - color_cache_code_bits)] = color;
  470. };
  471. while (pixel < end) {
  472. auto symbol = TRY(group[0].read_symbol(bit_stream));
  473. if (symbol >= 256u + 24u + color_cache_size)
  474. return context.error("WebPImageDecoderPlugin: Symbol out of bounds");
  475. // "1. if S < 256"
  476. if (symbol < 256u) {
  477. // "a. Use S as the green component."
  478. u8 g = symbol;
  479. // "b. Read red from the bitstream using prefix code #2."
  480. u8 r = TRY(group[1].read_symbol(bit_stream));
  481. // "c. Read blue from the bitstream using prefix code #3."
  482. u8 b = TRY(group[2].read_symbol(bit_stream));
  483. // "d. Read alpha from the bitstream using prefix code #4."
  484. u8 a = TRY(group[3].read_symbol(bit_stream));
  485. emit_pixel(Color(r, g, b, a).value());
  486. }
  487. // "2. if S >= 256 && S < 256 + 24"
  488. else if (symbol < 256u + 24u) {
  489. auto prefix_value = [&bit_stream](u8 prefix_code) -> ErrorOr<u32> {
  490. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
  491. if (prefix_code < 4)
  492. return prefix_code + 1;
  493. int extra_bits = (prefix_code - 2) >> 1;
  494. int offset = (2 + (prefix_code & 1)) << extra_bits;
  495. return offset + TRY(bit_stream.read_bits(extra_bits)) + 1;
  496. };
  497. // "a. Use S - 256 as a length prefix code."
  498. u8 length_prefix_code = symbol - 256;
  499. // "b. Read extra bits for length from the bitstream."
  500. // "c. Determine backward-reference length L from length prefix code and the extra bits read."
  501. u32 length = TRY(prefix_value(length_prefix_code));
  502. // "d. Read distance prefix code from the bitstream using prefix code #5."
  503. u8 distance_prefix_code = TRY(group[4].read_symbol(bit_stream));
  504. // "e. Read extra bits for distance from the bitstream."
  505. // "f. Determine backward-reference distance D from distance prefix code and the extra bits read."
  506. i32 distance = TRY(prefix_value(distance_prefix_code));
  507. // "g. Copy the L pixels (in scan-line order) from the sequence of pixels prior to them by D pixels."
  508. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
  509. // "Distance codes larger than 120 denote the pixel-distance in scan-line order, offset by 120."
  510. // "The smallest distance codes [1..120] are special, and are reserved for a close neighborhood of the current pixel."
  511. if (distance <= 120) {
  512. auto offset = distance_map[distance - 1];
  513. distance = offset.x + offset.y * context.size->width();
  514. if (distance < 1)
  515. distance = 1;
  516. } else {
  517. distance = distance - 120;
  518. }
  519. if (pixel - context.bitmap->begin() < distance)
  520. return context.error("WebPImageDecoderPlugin: Backward reference distance out of bounds");
  521. if (context.bitmap->end() - pixel < length)
  522. return context.error("WebPImageDecoderPlugin: Backward reference length out of bounds");
  523. ARGB32* src = pixel - distance;
  524. for (u32 i = 0; i < length; ++i)
  525. emit_pixel(src[i]);
  526. }
  527. // "3. if S >= 256 + 24"
  528. else {
  529. // "a. Use S - (256 + 24) as the index into the color cache."
  530. unsigned index = symbol - (256 + 24);
  531. // "b. Get ARGB color from the color cache at that index."
  532. if (index >= color_cache_size)
  533. return context.error("WebPImageDecoderPlugin: Color cache index out of bounds");
  534. *pixel++ = color_cache[index];
  535. }
  536. }
  537. return {};
  538. }
  539. static ErrorOr<VP8XHeader> decode_webp_chunk_VP8X(WebPLoadingContext& context, Chunk const& vp8x_chunk)
  540. {
  541. VERIFY(vp8x_chunk.type == FourCC("VP8X"));
  542. // The VP8X chunk is documented at "Extended WebP file header:" at the end of
  543. // https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
  544. if (vp8x_chunk.data.size() < 10)
  545. return context.error("WebPImageDecoderPlugin: VP8X chunk too small");
  546. u8 const* data = vp8x_chunk.data.data();
  547. // 1 byte flags
  548. // "Reserved (Rsv): 2 bits MUST be 0. Readers MUST ignore this field.
  549. // ICC profile (I): 1 bit Set if the file contains an ICC profile.
  550. // Alpha (L): 1 bit Set if any of the frames of the image contain transparency information ("alpha").
  551. // Exif metadata (E): 1 bit Set if the file contains Exif metadata.
  552. // XMP metadata (X): 1 bit Set if the file contains XMP metadata.
  553. // Animation (A): 1 bit Set if this is an animated image. Data in 'ANIM' and 'ANMF' chunks should be used to control the animation.
  554. // Reserved (R): 1 bit MUST be 0. Readers MUST ignore this field."
  555. u8 flags = data[0];
  556. bool has_icc = flags & 0x20;
  557. bool has_alpha = flags & 0x10;
  558. bool has_exif = flags & 0x8;
  559. bool has_xmp = flags & 0x4;
  560. bool has_animation = flags & 0x2;
  561. // 3 bytes reserved
  562. // 3 bytes width minus one
  563. u32 width = (data[4] | (data[5] << 8) | (data[6] << 16)) + 1;
  564. // 3 bytes height minus one
  565. u32 height = (data[7] | (data[8] << 8) | (data[9] << 16)) + 1;
  566. dbgln_if(WEBP_DEBUG, "flags 0x{:x} --{}{}{}{}{}{}, width {}, height {}",
  567. flags,
  568. has_icc ? " icc" : "",
  569. has_alpha ? " alpha" : "",
  570. has_exif ? " exif" : "",
  571. has_xmp ? " xmp" : "",
  572. has_animation ? " anim" : "",
  573. (flags & 0x3e) == 0 ? " none" : "",
  574. width, height);
  575. return VP8XHeader { has_icc, has_alpha, has_exif, has_xmp, has_animation, width, height };
  576. }
  577. // https://developers.google.com/speed/webp/docs/riff_container#animation
  578. static ErrorOr<ANIMChunk> decode_webp_chunk_ANIM(WebPLoadingContext& context, Chunk const& anim_chunk)
  579. {
  580. VERIFY(anim_chunk.type == FourCC("ANIM"));
  581. if (anim_chunk.data.size() < 6)
  582. return context.error("WebPImageDecoderPlugin: ANIM chunk too small");
  583. u8 const* data = anim_chunk.data.data();
  584. u32 background_color = (u32)data[0] | ((u32)data[1] << 8) | ((u32)data[2] << 16) | ((u32)data[3] << 24);
  585. u16 loop_count = data[4] | (data[5] << 8);
  586. return ANIMChunk { background_color, loop_count };
  587. }
  588. // https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
  589. static ErrorOr<void> decode_webp_extended(WebPLoadingContext& context, ReadonlyBytes chunks)
  590. {
  591. VERIFY(context.first_chunk->type == FourCC("VP8X"));
  592. // FIXME: This isn't quite to spec, which says
  593. // "All chunks SHOULD be placed in the same order as listed above.
  594. // If a chunk appears in the wrong place, the file is invalid, but readers MAY parse the file, ignoring the chunks that are out of order."
  595. auto store = [](auto& field, Chunk const& chunk) {
  596. if (!field.has_value())
  597. field = chunk;
  598. };
  599. while (!chunks.is_empty()) {
  600. auto chunk = TRY(decode_webp_advance_chunk(context, chunks));
  601. if (chunk.type == FourCC("ICCP"))
  602. store(context.iccp_chunk, chunk);
  603. else if (chunk.type == FourCC("ALPH"))
  604. store(context.alpha_chunk, chunk);
  605. else if (chunk.type == FourCC("ANIM"))
  606. store(context.animation_header_chunk, chunk);
  607. else if (chunk.type == FourCC("ANMF"))
  608. TRY(context.animation_frame_chunks.try_append(chunk));
  609. else if (chunk.type == FourCC("EXIF"))
  610. store(context.exif_chunk, chunk);
  611. else if (chunk.type == FourCC("XMP "))
  612. store(context.xmp_chunk, chunk);
  613. else if (chunk.type == FourCC("VP8 ") || chunk.type == FourCC("VP8L"))
  614. store(context.image_data_chunk, chunk);
  615. }
  616. // Validate chunks.
  617. // https://developers.google.com/speed/webp/docs/riff_container#animation
  618. // "ANIM Chunk: [...] This chunk MUST appear if the Animation flag in the VP8X chunk is set. If the Animation flag is not set and this chunk is present, it MUST be ignored."
  619. if (context.vp8x_header.has_animation && !context.animation_header_chunk.has_value())
  620. return context.error("WebPImageDecoderPlugin: Header claims animation, but no ANIM chunk");
  621. if (!context.vp8x_header.has_animation && context.animation_header_chunk.has_value()) {
  622. dbgln_if(WEBP_DEBUG, "WebPImageDecoderPlugin: Header claims no animation, but ANIM chunk present. Ignoring ANIM chunk.");
  623. context.animation_header_chunk.clear();
  624. }
  625. // "ANMF Chunk: [...] If the Animation flag is not set, then this chunk SHOULD NOT be present."
  626. if (!context.vp8x_header.has_animation && context.animation_header_chunk.has_value()) {
  627. dbgln_if(WEBP_DEBUG, "WebPImageDecoderPlugin: Header claims no animation, but ANMF chunks present. Ignoring ANMF chunks.");
  628. context.animation_frame_chunks.clear();
  629. }
  630. // https://developers.google.com/speed/webp/docs/riff_container#alpha
  631. // "A frame containing a 'VP8L' chunk SHOULD NOT contain this chunk."
  632. // FIXME: Also check in ANMF chunks.
  633. if (context.alpha_chunk.has_value() && context.image_data_chunk.has_value() && context.image_data_chunk->type == FourCC("VP8L")) {
  634. dbgln_if(WEBP_DEBUG, "WebPImageDecoderPlugin: VP8L frames should not have ALPH chunks. Ignoring ALPH chunk.");
  635. context.alpha_chunk.clear();
  636. }
  637. // https://developers.google.com/speed/webp/docs/riff_container#color_profile
  638. // "This chunk MUST appear before the image data."
  639. // FIXME: Doesn't check animated files.
  640. if (context.iccp_chunk.has_value() && context.image_data_chunk.has_value() && context.iccp_chunk->data.data() > context.image_data_chunk->data.data())
  641. return context.error("WebPImageDecoderPlugin: ICCP chunk is after image data");
  642. context.state = WebPLoadingContext::State::ChunksDecoded;
  643. return {};
  644. }
  645. static ErrorOr<void> read_webp_first_chunk(WebPLoadingContext& context)
  646. {
  647. if (context.state >= WebPLoadingContext::State::FirstChunkRead)
  648. return {};
  649. if (context.state < WebPLoadingContext::HeaderDecoded)
  650. TRY(decode_webp_header(context));
  651. context.chunks_cursor = context.data.slice(sizeof(WebPFileHeader));
  652. auto first_chunk = TRY(decode_webp_advance_chunk(context, context.chunks_cursor));
  653. if (first_chunk.type != FourCC("VP8 ") && first_chunk.type != FourCC("VP8L") && first_chunk.type != FourCC("VP8X"))
  654. return context.error("WebPImageDecoderPlugin: Invalid first chunk type");
  655. context.first_chunk = first_chunk;
  656. context.state = WebPLoadingContext::State::FirstChunkRead;
  657. if (first_chunk.type == FourCC("VP8 ") || first_chunk.type == FourCC("VP8L"))
  658. context.image_data_chunk = first_chunk;
  659. return {};
  660. }
  661. static ErrorOr<void> decode_webp_first_chunk(WebPLoadingContext& context)
  662. {
  663. if (context.state >= WebPLoadingContext::State::FirstChunkDecoded)
  664. return {};
  665. if (context.state < WebPLoadingContext::FirstChunkRead)
  666. TRY(read_webp_first_chunk(context));
  667. if (context.first_chunk->type == FourCC("VP8 ")) {
  668. context.vp8_header = TRY(decode_webp_chunk_VP8_header(context, context.first_chunk.value()));
  669. context.size = IntSize { context.vp8_header.width, context.vp8_header.height };
  670. context.state = WebPLoadingContext::State::FirstChunkDecoded;
  671. return {};
  672. }
  673. if (context.first_chunk->type == FourCC("VP8L")) {
  674. context.vp8l_header = TRY(decode_webp_chunk_VP8L_header(context, context.first_chunk.value()));
  675. context.size = IntSize { context.vp8l_header.width, context.vp8l_header.height };
  676. context.state = WebPLoadingContext::State::FirstChunkDecoded;
  677. return {};
  678. }
  679. VERIFY(context.first_chunk->type == FourCC("VP8X"));
  680. context.vp8x_header = TRY(decode_webp_chunk_VP8X(context, context.first_chunk.value()));
  681. context.size = IntSize { context.vp8x_header.width, context.vp8x_header.height };
  682. context.state = WebPLoadingContext::State::FirstChunkDecoded;
  683. return {};
  684. }
  685. static ErrorOr<void> decode_webp_chunks(WebPLoadingContext& context)
  686. {
  687. if (context.state >= WebPLoadingContext::State::ChunksDecoded)
  688. return {};
  689. if (context.state < WebPLoadingContext::FirstChunkDecoded)
  690. TRY(decode_webp_first_chunk(context));
  691. if (context.first_chunk->type == FourCC("VP8X"))
  692. return decode_webp_extended(context, context.chunks_cursor);
  693. context.state = WebPLoadingContext::State::ChunksDecoded;
  694. return {};
  695. }
  696. WebPImageDecoderPlugin::WebPImageDecoderPlugin(ReadonlyBytes data, OwnPtr<WebPLoadingContext> context)
  697. : m_context(move(context))
  698. {
  699. m_context->data = data;
  700. }
  701. WebPImageDecoderPlugin::~WebPImageDecoderPlugin() = default;
  702. IntSize WebPImageDecoderPlugin::size()
  703. {
  704. if (m_context->state == WebPLoadingContext::State::Error)
  705. return {};
  706. if (m_context->state < WebPLoadingContext::State::FirstChunkDecoded) {
  707. if (decode_webp_first_chunk(*m_context).is_error())
  708. return {};
  709. }
  710. return m_context->size.value();
  711. }
  712. void WebPImageDecoderPlugin::set_volatile()
  713. {
  714. if (m_context->bitmap)
  715. m_context->bitmap->set_volatile();
  716. }
  717. bool WebPImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  718. {
  719. if (!m_context->bitmap)
  720. return false;
  721. return m_context->bitmap->set_nonvolatile(was_purged);
  722. }
  723. bool WebPImageDecoderPlugin::initialize()
  724. {
  725. return !decode_webp_header(*m_context).is_error();
  726. }
  727. bool WebPImageDecoderPlugin::sniff(ReadonlyBytes data)
  728. {
  729. WebPLoadingContext context;
  730. context.data = data;
  731. return !decode_webp_header(context).is_error();
  732. }
  733. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> WebPImageDecoderPlugin::create(ReadonlyBytes data)
  734. {
  735. auto context = TRY(try_make<WebPLoadingContext>());
  736. return adopt_nonnull_own_or_enomem(new (nothrow) WebPImageDecoderPlugin(data, move(context)));
  737. }
  738. bool WebPImageDecoderPlugin::is_animated()
  739. {
  740. if (m_context->state == WebPLoadingContext::State::Error)
  741. return false;
  742. if (m_context->state < WebPLoadingContext::State::FirstChunkDecoded) {
  743. if (decode_webp_first_chunk(*m_context).is_error())
  744. return false;
  745. }
  746. return m_context->first_chunk->type == FourCC("VP8X") && m_context->vp8x_header.has_animation;
  747. }
  748. size_t WebPImageDecoderPlugin::loop_count()
  749. {
  750. if (!is_animated())
  751. return 0;
  752. if (m_context->state < WebPLoadingContext::State::ChunksDecoded) {
  753. if (decode_webp_chunks(*m_context).is_error())
  754. return 0;
  755. }
  756. auto anim_or_error = decode_webp_chunk_ANIM(*m_context, m_context->animation_header_chunk.value());
  757. if (decode_webp_chunks(*m_context).is_error())
  758. return 0;
  759. return anim_or_error.value().loop_count;
  760. }
  761. size_t WebPImageDecoderPlugin::frame_count()
  762. {
  763. if (!is_animated())
  764. return 1;
  765. if (m_context->state < WebPLoadingContext::State::ChunksDecoded) {
  766. if (decode_webp_chunks(*m_context).is_error())
  767. return 1;
  768. }
  769. return m_context->animation_frame_chunks.size();
  770. }
  771. ErrorOr<ImageFrameDescriptor> WebPImageDecoderPlugin::frame(size_t index)
  772. {
  773. if (index >= frame_count())
  774. return Error::from_string_literal("WebPImageDecoderPlugin: Invalid frame index");
  775. if (m_context->state == WebPLoadingContext::State::Error)
  776. return Error::from_string_literal("WebPImageDecoderPlugin: Decoding failed");
  777. if (m_context->state < WebPLoadingContext::State::ChunksDecoded)
  778. TRY(decode_webp_chunks(*m_context));
  779. if (is_animated())
  780. return Error::from_string_literal("WebPImageDecoderPlugin: decoding of animated files not yet implemented");
  781. if (m_context->image_data_chunk.has_value() && m_context->image_data_chunk->type == FourCC("VP8L")) {
  782. if (m_context->state < WebPLoadingContext::State::BitmapDecoded) {
  783. TRY(decode_webp_chunk_VP8L(*m_context, m_context->image_data_chunk.value()));
  784. m_context->state = WebPLoadingContext::State::BitmapDecoded;
  785. }
  786. VERIFY(m_context->bitmap);
  787. return ImageFrameDescriptor { m_context->bitmap, 0 };
  788. }
  789. return Error::from_string_literal("WebPImageDecoderPlugin: decoding not yet implemented");
  790. }
  791. ErrorOr<Optional<ReadonlyBytes>> WebPImageDecoderPlugin::icc_data()
  792. {
  793. TRY(decode_webp_chunks(*m_context));
  794. // FIXME: "If this chunk is not present, sRGB SHOULD be assumed."
  795. return m_context->iccp_chunk.map([](auto iccp_chunk) { return iccp_chunk.data; });
  796. }
  797. }
  798. template<>
  799. struct AK::Formatter<Gfx::FourCC> : StandardFormatter {
  800. ErrorOr<void> format(FormatBuilder& builder, Gfx::FourCC const& four_cc)
  801. {
  802. TRY(builder.put_padding('\'', 1));
  803. TRY(builder.put_padding(four_cc.cc[0], 1));
  804. TRY(builder.put_padding(four_cc.cc[1], 1));
  805. TRY(builder.put_padding(four_cc.cc[2], 1));
  806. TRY(builder.put_padding(four_cc.cc[3], 1));
  807. TRY(builder.put_padding('\'', 1));
  808. return {};
  809. }
  810. };