WebPWriter.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. * Copyright (c) 2024, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. // Container: https://developers.google.com/speed/webp/docs/riff_container
  7. // Lossless format: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification
  8. #include <AK/BitStream.h>
  9. #include <AK/Debug.h>
  10. #include <LibCompress/DeflateTables.h>
  11. #include <LibGfx/Bitmap.h>
  12. #include <LibGfx/ImageFormats/AnimationWriter.h>
  13. #include <LibGfx/ImageFormats/WebPShared.h>
  14. #include <LibGfx/ImageFormats/WebPWriter.h>
  15. #include <LibRIFF/RIFF.h>
  16. namespace Gfx {
  17. // https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
  18. static ErrorOr<void> write_webp_header(Stream& stream, unsigned data_size)
  19. {
  20. TRY(stream.write_until_depleted("RIFF"sv));
  21. TRY(stream.write_value<LittleEndian<u32>>(4 + data_size)); // Including size of "WEBP" and the data size itself.
  22. TRY(stream.write_until_depleted("WEBP"sv));
  23. return {};
  24. }
  25. static ErrorOr<void> write_chunk_header(Stream& stream, StringView chunk_fourcc, unsigned vp8l_data_size)
  26. {
  27. TRY(stream.write_until_depleted(chunk_fourcc));
  28. TRY(stream.write_value<LittleEndian<u32>>(vp8l_data_size));
  29. return {};
  30. }
  31. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
  32. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#7_overall_structure_of_the_format
  33. static ErrorOr<void> write_VP8L_header(Stream& stream, unsigned width, unsigned height, bool alpha_is_used_hint)
  34. {
  35. // "The 14-bit precision for image width and height limits the maximum size of a WebP lossless image to 16384✕16384 pixels."
  36. if (width > 16384 || height > 16384)
  37. return Error::from_string_literal("WebP lossless images can't be larger than 16384x16384 pixels");
  38. if (width == 0 || height == 0)
  39. return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
  40. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  41. // Signature byte.
  42. TRY(bit_stream.write_bits(0x2fu, 8u)); // Signature byte
  43. // 14 bits width-1, 14 bits height-1, 1 bit alpha hint, 3 bit version_number.
  44. TRY(bit_stream.write_bits(width - 1, 14u));
  45. TRY(bit_stream.write_bits(height - 1, 14u));
  46. // "The alpha_is_used bit is a hint only, and should not impact decoding.
  47. // It should be set to 0 when all alpha values are 255 in the picture, and 1 otherwise."
  48. TRY(bit_stream.write_bits(alpha_is_used_hint, 1u));
  49. // "The version_number is a 3 bit code that must be set to 0."
  50. TRY(bit_stream.write_bits(0u, 3u));
  51. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  52. TRY(bit_stream.flush_buffer_to_stream());
  53. return {};
  54. }
  55. static bool are_all_pixels_opaque(Bitmap const& bitmap)
  56. {
  57. for (ARGB32 pixel : bitmap) {
  58. if ((pixel >> 24) != 0xff)
  59. return false;
  60. }
  61. return true;
  62. }
  63. static ErrorOr<void> write_VP8L_image_data(Stream& stream, Bitmap const& bitmap)
  64. {
  65. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  66. // optional-transform = (%b1 transform optional-transform) / %b0
  67. TRY(bit_stream.write_bits(0u, 1u)); // No transform for now.
  68. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#5_image_data
  69. // spatially-coded-image = color-cache-info meta-prefix data
  70. // color-cache-info = %b0
  71. // color-cache-info =/ (%b1 4BIT) ; 1 followed by color cache size
  72. TRY(bit_stream.write_bits(0u, 1u)); // No color cache for now.
  73. // meta-prefix = %b0 / (%b1 entropy-image)
  74. TRY(bit_stream.write_bits(0u, 1u)); // No meta prefix for now.
  75. // data = prefix-codes lz77-coded-image
  76. // prefix-codes = prefix-code-group *prefix-codes
  77. // prefix-code-group =
  78. // 5prefix-code ; See "Interpretation of Meta Prefix Codes" to
  79. // ; understand what each of these five prefix
  80. // ; codes are for.
  81. // We're writing a single prefix-code-group.
  82. // "These codes are (in bitstream order):
  83. // Prefix code #1: Used for green channel, backward-reference length, and color cache.
  84. // Prefix code #2, #3, and #4: Used for red, blue, and alpha channels, respectively.
  85. // Prefix code #5: Used for backward-reference distance."
  86. // We use neither back-references not color cache entries yet.
  87. // We write prefix trees for 256 literals all of length 8, which means each byte is encoded as itself.
  88. // That doesn't give any compression, but is a valid bit stream.
  89. // We can make this smarter later on.
  90. size_t const color_cache_size = 0;
  91. constexpr Array alphabet_sizes = to_array<size_t>({ 256 + 24 + static_cast<size_t>(color_cache_size), 256, 256, 256, 40 }); // XXX Shared?
  92. // If you add support for color cache: At the moment, CanonicalCodes does not support writing more than 288 symbols.
  93. if (alphabet_sizes[0] > 288)
  94. return Error::from_string_literal("Invalid alphabet size");
  95. bool all_pixels_are_opaque = are_all_pixels_opaque(bitmap);
  96. int number_of_full_channels = all_pixels_are_opaque ? 3 : 4;
  97. for (int i = 0; i < number_of_full_channels; ++i) {
  98. TRY(bit_stream.write_bits(0u, 1u)); // Normal code length code.
  99. // Write code length codes.
  100. constexpr int kCodeLengthCodes = 19;
  101. Array<int, kCodeLengthCodes> kCodeLengthCodeOrder = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
  102. int num_code_lengths = max(4u, find_index(kCodeLengthCodeOrder.begin(), kCodeLengthCodeOrder.end(), 8) + 1);
  103. // "int num_code_lengths = 4 + ReadBits(4);"
  104. TRY(bit_stream.write_bits(num_code_lengths - 4u, 4u));
  105. for (int i = 0; i < num_code_lengths - 1; ++i)
  106. TRY(bit_stream.write_bits(0u, 3u));
  107. TRY(bit_stream.write_bits(1u, 3u));
  108. // Write code lengths.
  109. if (alphabet_sizes[i] == 256) {
  110. TRY(bit_stream.write_bits(0u, 1u)); // max_symbol is alphabet_size
  111. } else {
  112. TRY(bit_stream.write_bits(1u, 1u)); // max_symbol is explicitly coded
  113. // "int length_nbits = 2 + 2 * ReadBits(3);
  114. // int max_symbol = 2 + ReadBits(length_nbits);"
  115. TRY(bit_stream.write_bits(3u, 3u)); // length_nbits = 2 + 2 * 3
  116. TRY(bit_stream.write_bits(254u, 8u)); // max_symbol = 2 + 254
  117. }
  118. // The code length codes only contain a single entry for '8'. WebP streams with a single element store 0 bits per element.
  119. // (This is different from deflate, which needs 1 bit per element.)
  120. }
  121. if (all_pixels_are_opaque) {
  122. // Use a simple 1-element code.
  123. TRY(bit_stream.write_bits(1u, 1u)); // Simple code length code.
  124. TRY(bit_stream.write_bits(0u, 1u)); // num_symbols - 1
  125. TRY(bit_stream.write_bits(1u, 1u)); // is_first_8bits
  126. TRY(bit_stream.write_bits(255u, 8u)); // symbol0
  127. }
  128. // For code #5, use a simple empty code, since we don't use this yet.
  129. TRY(bit_stream.write_bits(1u, 1u)); // Simple code length code.
  130. TRY(bit_stream.write_bits(0u, 1u)); // num_symbols - 1
  131. TRY(bit_stream.write_bits(0u, 1u)); // is_first_8bits
  132. TRY(bit_stream.write_bits(0u, 1u)); // symbol0
  133. // Image data.
  134. for (ARGB32 pixel : bitmap) {
  135. u8 a = pixel >> 24;
  136. u8 r = pixel >> 16;
  137. u8 g = pixel >> 8;
  138. u8 b = pixel;
  139. // We wrote a huffman table that gives every symbol 8 bits. That means we can write the image data
  140. // out uncompressed –- but we do need to reverse the bit order of the bytes.
  141. TRY(bit_stream.write_bits(Compress::reverse8_lookup_table[g], 8u));
  142. TRY(bit_stream.write_bits(Compress::reverse8_lookup_table[r], 8u));
  143. TRY(bit_stream.write_bits(Compress::reverse8_lookup_table[b], 8u));
  144. // If all pixels are opaque, we wrote a one-element huffman table for alpha, which needs 0 bits per element.
  145. if (!all_pixels_are_opaque)
  146. TRY(bit_stream.write_bits(Compress::reverse8_lookup_table[a], 8u));
  147. }
  148. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  149. TRY(bit_stream.align_to_byte_boundary());
  150. TRY(bit_stream.flush_buffer_to_stream());
  151. return {};
  152. }
  153. static ErrorOr<ByteBuffer> compress_VP8L_image_data(Bitmap const& bitmap)
  154. {
  155. AllocatingMemoryStream vp8l_data_stream;
  156. TRY(write_VP8L_image_data(vp8l_data_stream, bitmap));
  157. return vp8l_data_stream.read_until_eof();
  158. }
  159. // FIXME: Consider using LibRIFF for RIFF writing details. (It currently has no writing support.)
  160. static ErrorOr<void> align_to_two(Stream& stream, size_t number_of_bytes_written)
  161. {
  162. // https://developers.google.com/speed/webp/docs/riff_container
  163. // "If Chunk Size is odd, a single padding byte -- which MUST be 0 to conform with RIFF -- is added."
  164. if (number_of_bytes_written % 2 != 0)
  165. TRY(stream.write_value<u8>(0));
  166. return {};
  167. }
  168. constexpr size_t vp8l_header_size = 5; // 1 byte signature + (2 * 14 bits width and height + 1 bit alpha hint + 3 bit version_number)
  169. static size_t compute_VP8L_chunk_size(ByteBuffer const& data)
  170. {
  171. constexpr size_t chunk_header_size = 8; // "VP8L" + size
  172. return chunk_header_size + align_up_to(vp8l_header_size + data.size(), 2);
  173. }
  174. static ErrorOr<void> write_VP8L_chunk(Stream& stream, unsigned width, unsigned height, bool alpha_is_used_hint, ByteBuffer const& data)
  175. {
  176. size_t const number_of_bytes_written = vp8l_header_size + data.size();
  177. TRY(write_chunk_header(stream, "VP8L"sv, number_of_bytes_written));
  178. TRY(write_VP8L_header(stream, width, height, alpha_is_used_hint));
  179. TRY(stream.write_until_depleted(data));
  180. TRY(align_to_two(stream, number_of_bytes_written));
  181. return {};
  182. }
  183. static u8 vp8x_flags_from_header(VP8XHeader const& header)
  184. {
  185. u8 flags = 0;
  186. // "Reserved (Rsv): 2 bits
  187. // MUST be 0. Readers MUST ignore this field."
  188. // "ICC profile (I): 1 bit
  189. // Set if the file contains an 'ICCP' Chunk."
  190. if (header.has_icc)
  191. flags |= 0x20;
  192. // "Alpha (L): 1 bit
  193. // Set if any of the frames of the image contain transparency information ("alpha")."
  194. if (header.has_alpha)
  195. flags |= 0x10;
  196. // "Exif metadata (E): 1 bit
  197. // Set if the file contains Exif metadata."
  198. if (header.has_exif)
  199. flags |= 0x8;
  200. // "XMP metadata (X): 1 bit
  201. // Set if the file contains XMP metadata."
  202. if (header.has_xmp)
  203. flags |= 0x4;
  204. // "Animation (A): 1 bit
  205. // Set if this is an animated image. Data in 'ANIM' and 'ANMF' Chunks should be used to control the animation."
  206. if (header.has_animation)
  207. flags |= 0x2;
  208. // "Reserved (R): 1 bit
  209. // MUST be 0. Readers MUST ignore this field."
  210. return flags;
  211. }
  212. // https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
  213. static ErrorOr<void> write_VP8X_chunk(Stream& stream, VP8XHeader const& header)
  214. {
  215. if (header.width > (1 << 24) || header.height > (1 << 24))
  216. return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
  217. if (header.width == 0 || header.height == 0)
  218. return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
  219. // "The product of Canvas Width and Canvas Height MUST be at most 2^32 - 1."
  220. u64 product = static_cast<u64>(header.width) * static_cast<u64>(header.height);
  221. if (product >= (1ull << 32))
  222. return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
  223. TRY(write_chunk_header(stream, "VP8X"sv, 10));
  224. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  225. // Don't use bit_stream.write_bits() to write individual flags here:
  226. // The spec describes bit flags in MSB to LSB order, but write_bits() writes LSB to MSB.
  227. TRY(bit_stream.write_bits(vp8x_flags_from_header(header), 8u));
  228. // "Reserved: 24 bits
  229. // MUST be 0. Readers MUST ignore this field."
  230. TRY(bit_stream.write_bits(0u, 24u));
  231. // "Canvas Width Minus One: 24 bits
  232. // 1-based width of the canvas in pixels. The actual canvas width is 1 + Canvas Width Minus One."
  233. TRY(bit_stream.write_bits(header.width - 1, 24u));
  234. // "Canvas Height Minus One: 24 bits
  235. // 1-based height of the canvas in pixels. The actual canvas height is 1 + Canvas Height Minus One."
  236. TRY(bit_stream.write_bits(header.height - 1, 24u));
  237. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  238. TRY(bit_stream.flush_buffer_to_stream());
  239. return {};
  240. }
  241. // FIXME: Consider using LibRIFF for RIFF writing details. (It currently has no writing support.)
  242. static ErrorOr<void> align_to_two(AllocatingMemoryStream& stream)
  243. {
  244. return align_to_two(stream, stream.used_buffer_size());
  245. }
  246. ErrorOr<void> WebPWriter::encode(Stream& stream, Bitmap const& bitmap, Options const& options)
  247. {
  248. bool alpha_is_used_hint = !are_all_pixels_opaque(bitmap);
  249. dbgln_if(WEBP_DEBUG, "Writing WebP of size {} with alpha hint: {}", bitmap.size(), alpha_is_used_hint);
  250. // The chunk headers need to know their size, so we either need a SeekableStream or need to buffer the data. We're doing the latter.
  251. auto vp8l_data_bytes = TRY(compress_VP8L_image_data(bitmap));
  252. ByteBuffer vp8x_chunk_bytes;
  253. ByteBuffer iccp_chunk_bytes;
  254. if (options.icc_data.has_value()) {
  255. // FIXME: The whole writing-and-reading-into-buffer over-and-over is awkward and inefficient.
  256. // Maybe add an abstraction that knows its size and can write its data later. This would
  257. // allow saving a few copies.
  258. dbgln_if(WEBP_DEBUG, "Writing VP8X and ICCP chunks.");
  259. AllocatingMemoryStream iccp_chunk_stream;
  260. TRY(write_chunk_header(iccp_chunk_stream, "ICCP"sv, options.icc_data.value().size()));
  261. TRY(iccp_chunk_stream.write_until_depleted(options.icc_data.value()));
  262. TRY(align_to_two(iccp_chunk_stream));
  263. iccp_chunk_bytes = TRY(iccp_chunk_stream.read_until_eof());
  264. AllocatingMemoryStream vp8x_chunk_stream;
  265. TRY(write_VP8X_chunk(vp8x_chunk_stream, { .has_icc = true, .has_alpha = alpha_is_used_hint, .width = (u32)bitmap.width(), .height = (u32)bitmap.height() }));
  266. VERIFY(vp8x_chunk_stream.used_buffer_size() % 2 == 0);
  267. vp8x_chunk_bytes = TRY(vp8x_chunk_stream.read_until_eof());
  268. }
  269. u32 total_size = vp8x_chunk_bytes.size() + iccp_chunk_bytes.size() + compute_VP8L_chunk_size(vp8l_data_bytes);
  270. TRY(write_webp_header(stream, total_size));
  271. TRY(stream.write_until_depleted(vp8x_chunk_bytes));
  272. TRY(stream.write_until_depleted(iccp_chunk_bytes));
  273. TRY(write_VP8L_chunk(stream, bitmap.width(), bitmap.height(), alpha_is_used_hint, vp8l_data_bytes));
  274. return {};
  275. }
  276. class WebPAnimationWriter : public AnimationWriter {
  277. public:
  278. WebPAnimationWriter(SeekableStream& stream, IntSize dimensions, u8 original_vp8x_flags)
  279. : m_stream(stream)
  280. , m_dimensions(dimensions)
  281. , m_vp8x_flags(original_vp8x_flags)
  282. {
  283. }
  284. virtual ErrorOr<void> add_frame(Bitmap&, int, IntPoint) override;
  285. ErrorOr<void> update_size_in_header();
  286. ErrorOr<void> set_alpha_bit_in_header();
  287. private:
  288. SeekableStream& m_stream;
  289. IntSize m_dimensions;
  290. u8 m_vp8x_flags { 0 };
  291. };
  292. static ErrorOr<void> align_to_two(SeekableStream& stream)
  293. {
  294. return align_to_two(stream, TRY(stream.tell()));
  295. }
  296. static ErrorOr<void> write_ANMF_chunk_header(Stream& stream, ANMFChunkHeader const& chunk, size_t payload_size)
  297. {
  298. if (chunk.frame_width > (1 << 24) || chunk.frame_height > (1 << 24))
  299. return Error::from_string_literal("WebP dimensions too large for ANMF chunk");
  300. if (chunk.frame_width == 0 || chunk.frame_height == 0)
  301. return Error::from_string_literal("WebP lossless animation frames must be at least one pixel wide and tall");
  302. if (chunk.frame_x % 2 != 0 || chunk.frame_y % 2 != 0)
  303. return Error::from_string_literal("WebP lossless animation frames must be at at even coordinates");
  304. dbgln_if(WEBP_DEBUG, "writing ANMF frame_x {} frame_y {} frame_width {} frame_height {} frame_duration {} blending_method {} disposal_method {}",
  305. chunk.frame_x, chunk.frame_y, chunk.frame_width, chunk.frame_height, chunk.frame_duration_in_milliseconds, (int)chunk.blending_method, (int)chunk.disposal_method);
  306. TRY(write_chunk_header(stream, "ANMF"sv, 16 + payload_size));
  307. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  308. // "Frame X: 24 bits (uint24)
  309. // The X coordinate of the upper left corner of the frame is Frame X * 2."
  310. TRY(bit_stream.write_bits(chunk.frame_x / 2, 24u));
  311. // "Frame Y: 24 bits (uint24)
  312. // The Y coordinate of the upper left corner of the frame is Frame Y * 2."
  313. TRY(bit_stream.write_bits(chunk.frame_y / 2, 24u));
  314. // "Frame Width: 24 bits (uint24)
  315. // The 1-based width of the frame. The frame width is 1 + Frame Width Minus One."
  316. TRY(bit_stream.write_bits(chunk.frame_width - 1, 24u));
  317. // "Frame Height: 24 bits (uint24)
  318. // The 1-based height of the frame. The frame height is 1 + Frame Height Minus One."
  319. TRY(bit_stream.write_bits(chunk.frame_height - 1, 24u));
  320. // "Frame Duration: 24 bits (uint24)"
  321. TRY(bit_stream.write_bits(chunk.frame_duration_in_milliseconds, 24u));
  322. // Don't use bit_stream.write_bits() to write individual flags here:
  323. // The spec describes bit flags in MSB to LSB order, but write_bits() writes LSB to MSB.
  324. u8 flags = 0;
  325. // "Reserved: 6 bits
  326. // MUST be 0. Readers MUST ignore this field."
  327. // "Blending method (B): 1 bit"
  328. if (chunk.blending_method == ANMFChunkHeader::BlendingMethod::DoNotBlend)
  329. flags |= 0x2;
  330. // "Disposal method (D): 1 bit"
  331. if (chunk.disposal_method == ANMFChunkHeader::DisposalMethod::DisposeToBackgroundColor)
  332. flags |= 0x1;
  333. TRY(bit_stream.write_bits(flags, 8u));
  334. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  335. TRY(bit_stream.flush_buffer_to_stream());
  336. return {};
  337. }
  338. ErrorOr<void> WebPAnimationWriter::add_frame(Bitmap& bitmap, int duration_ms, IntPoint at)
  339. {
  340. if (at.x() < 0 || at.y() < 0 || at.x() + bitmap.width() > m_dimensions.width() || at.y() + bitmap.height() > m_dimensions.height())
  341. return Error::from_string_literal("Frame does not fit in animation dimensions");
  342. // Since we have a SeekableStream, we could write both the VP8L chunk header and the ANMF chunk header with a placeholder size,
  343. // compress the frame data directly to the stream, and then go back and update the two sizes.
  344. // That's pretty messy though, and the compressed image data is smaller than the uncompressed bitmap passed in. So we'll buffer it.
  345. auto vp8l_data_bytes = TRY(compress_VP8L_image_data(bitmap));
  346. ANMFChunkHeader chunk;
  347. chunk.frame_x = static_cast<u32>(at.x());
  348. chunk.frame_y = static_cast<u32>(at.y());
  349. chunk.frame_width = static_cast<u32>(bitmap.width());
  350. chunk.frame_height = static_cast<u32>(bitmap.height());
  351. chunk.frame_duration_in_milliseconds = static_cast<u32>(duration_ms);
  352. chunk.blending_method = ANMFChunkHeader::BlendingMethod::DoNotBlend;
  353. chunk.disposal_method = ANMFChunkHeader::DisposalMethod::DoNotDispose;
  354. TRY(write_ANMF_chunk_header(m_stream, chunk, compute_VP8L_chunk_size(vp8l_data_bytes)));
  355. TRY(write_VP8L_chunk(m_stream, bitmap.width(), bitmap.height(), true, vp8l_data_bytes));
  356. TRY(update_size_in_header());
  357. if (!(m_vp8x_flags & 0x10) && !are_all_pixels_opaque(bitmap))
  358. TRY(set_alpha_bit_in_header());
  359. return {};
  360. }
  361. ErrorOr<void> WebPAnimationWriter::update_size_in_header()
  362. {
  363. auto current_offset = TRY(m_stream.tell());
  364. TRY(m_stream.seek(4, SeekMode::SetPosition));
  365. VERIFY(current_offset > 8);
  366. TRY(m_stream.write_value<LittleEndian<u32>>(current_offset - 8));
  367. TRY(m_stream.seek(current_offset, SeekMode::SetPosition));
  368. return {};
  369. }
  370. ErrorOr<void> WebPAnimationWriter::set_alpha_bit_in_header()
  371. {
  372. m_vp8x_flags |= 0x10;
  373. auto current_offset = TRY(m_stream.tell());
  374. TRY(m_stream.seek(20, SeekMode::SetPosition));
  375. TRY(m_stream.write_value<u8>(m_vp8x_flags));
  376. TRY(m_stream.seek(current_offset, SeekMode::SetPosition));
  377. return {};
  378. }
  379. static ErrorOr<void> write_ANIM_chunk(Stream& stream, ANIMChunk const& chunk)
  380. {
  381. TRY(write_chunk_header(stream, "ANIM"sv, 6)); // Size of the ANIM chunk.
  382. TRY(stream.write_value<LittleEndian<u32>>(chunk.background_color));
  383. TRY(stream.write_value<LittleEndian<u16>>(chunk.loop_count));
  384. return {};
  385. }
  386. ErrorOr<NonnullOwnPtr<AnimationWriter>> WebPWriter::start_encoding_animation(SeekableStream& stream, IntSize dimensions, int loop_count, Color background_color, Options const& options)
  387. {
  388. // We'll update the stream with the actual size later.
  389. TRY(write_webp_header(stream, 0));
  390. VP8XHeader vp8x_header;
  391. vp8x_header.has_icc = options.icc_data.has_value();
  392. vp8x_header.width = dimensions.width();
  393. vp8x_header.height = dimensions.height();
  394. vp8x_header.has_animation = true;
  395. TRY(write_VP8X_chunk(stream, vp8x_header));
  396. VERIFY(TRY(stream.tell()) % 2 == 0);
  397. ByteBuffer iccp_chunk_bytes;
  398. if (options.icc_data.has_value()) {
  399. TRY(write_chunk_header(stream, "ICCP"sv, options.icc_data.value().size()));
  400. TRY(stream.write_until_depleted(options.icc_data.value()));
  401. TRY(align_to_two(stream));
  402. }
  403. TRY(write_ANIM_chunk(stream, { .background_color = background_color.value(), .loop_count = static_cast<u16>(loop_count) }));
  404. auto writer = make<WebPAnimationWriter>(stream, dimensions, vp8x_flags_from_header(vp8x_header));
  405. TRY(writer->update_size_in_header());
  406. return writer;
  407. }
  408. }