WebPWriter.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. static u8 vp8x_flags_from_header(VP8XHeader const& header)
  160. {
  161. u8 flags = 0;
  162. // "Reserved (Rsv): 2 bits
  163. // MUST be 0. Readers MUST ignore this field."
  164. // "ICC profile (I): 1 bit
  165. // Set if the file contains an 'ICCP' Chunk."
  166. if (header.has_icc)
  167. flags |= 0x20;
  168. // "Alpha (L): 1 bit
  169. // Set if any of the frames of the image contain transparency information ("alpha")."
  170. if (header.has_alpha)
  171. flags |= 0x10;
  172. // "Exif metadata (E): 1 bit
  173. // Set if the file contains Exif metadata."
  174. if (header.has_exif)
  175. flags |= 0x8;
  176. // "XMP metadata (X): 1 bit
  177. // Set if the file contains XMP metadata."
  178. if (header.has_xmp)
  179. flags |= 0x4;
  180. // "Animation (A): 1 bit
  181. // Set if this is an animated image. Data in 'ANIM' and 'ANMF' Chunks should be used to control the animation."
  182. if (header.has_animation)
  183. flags |= 0x2;
  184. // "Reserved (R): 1 bit
  185. // MUST be 0. Readers MUST ignore this field."
  186. return flags;
  187. }
  188. // https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
  189. static ErrorOr<void> write_VP8X_chunk(Stream& stream, VP8XHeader const& header)
  190. {
  191. if (header.width > (1 << 24) || header.height > (1 << 24))
  192. return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
  193. if (header.width == 0 || header.height == 0)
  194. return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
  195. // "The product of Canvas Width and Canvas Height MUST be at most 2^32 - 1."
  196. u64 product = static_cast<u64>(header.width) * static_cast<u64>(header.height);
  197. if (product >= (1ull << 32))
  198. return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
  199. TRY(write_chunk_header(stream, "VP8X"sv, 10));
  200. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  201. // Don't use bit_stream.write_bits() to write individual flags here:
  202. // The spec describes bit flags in MSB to LSB order, but write_bits() writes LSB to MSB.
  203. TRY(bit_stream.write_bits(vp8x_flags_from_header(header), 8u));
  204. // "Reserved: 24 bits
  205. // MUST be 0. Readers MUST ignore this field."
  206. TRY(bit_stream.write_bits(0u, 24u));
  207. // "Canvas Width Minus One: 24 bits
  208. // 1-based width of the canvas in pixels. The actual canvas width is 1 + Canvas Width Minus One."
  209. TRY(bit_stream.write_bits(header.width - 1, 24u));
  210. // "Canvas Height Minus One: 24 bits
  211. // 1-based height of the canvas in pixels. The actual canvas height is 1 + Canvas Height Minus One."
  212. TRY(bit_stream.write_bits(header.height - 1, 24u));
  213. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  214. TRY(bit_stream.flush_buffer_to_stream());
  215. return {};
  216. }
  217. // FIXME: Consider using LibRIFF for RIFF writing details. (It currently has no writing support.)
  218. static ErrorOr<void> align_to_two(AllocatingMemoryStream& stream)
  219. {
  220. // https://developers.google.com/speed/webp/docs/riff_container
  221. // "If Chunk Size is odd, a single padding byte -- which MUST be 0 to conform with RIFF -- is added."
  222. if (stream.used_buffer_size() % 2 != 0)
  223. TRY(stream.write_value<u8>(0));
  224. return {};
  225. }
  226. ErrorOr<void> WebPWriter::encode(Stream& stream, Bitmap const& bitmap, Options const& options)
  227. {
  228. bool alpha_is_used_hint = !are_all_pixels_opaque(bitmap);
  229. dbgln_if(WEBP_DEBUG, "Writing WebP of size {} with alpha hint: {}", bitmap.size(), alpha_is_used_hint);
  230. // 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.
  231. // FIXME: The whole writing-and-reading-into-buffer over-and-over is awkward and inefficient.
  232. AllocatingMemoryStream vp8l_header_stream;
  233. TRY(write_VP8L_header(vp8l_header_stream, bitmap.width(), bitmap.height(), alpha_is_used_hint));
  234. auto vp8l_header_bytes = TRY(vp8l_header_stream.read_until_eof());
  235. auto vp8l_data_bytes = TRY(compress_VP8L_image_data(bitmap));
  236. AllocatingMemoryStream vp8l_chunk_stream;
  237. TRY(write_chunk_header(vp8l_chunk_stream, "VP8L"sv, vp8l_header_bytes.size() + vp8l_data_bytes.size()));
  238. TRY(vp8l_chunk_stream.write_until_depleted(vp8l_header_bytes));
  239. TRY(vp8l_chunk_stream.write_until_depleted(vp8l_data_bytes));
  240. TRY(align_to_two(vp8l_chunk_stream));
  241. auto vp8l_chunk_bytes = TRY(vp8l_chunk_stream.read_until_eof());
  242. ByteBuffer vp8x_chunk_bytes;
  243. ByteBuffer iccp_chunk_bytes;
  244. if (options.icc_data.has_value()) {
  245. dbgln_if(WEBP_DEBUG, "Writing VP8X and ICCP chunks.");
  246. AllocatingMemoryStream iccp_chunk_stream;
  247. TRY(write_chunk_header(iccp_chunk_stream, "ICCP"sv, options.icc_data.value().size()));
  248. TRY(iccp_chunk_stream.write_until_depleted(options.icc_data.value()));
  249. TRY(align_to_two(iccp_chunk_stream));
  250. iccp_chunk_bytes = TRY(iccp_chunk_stream.read_until_eof());
  251. AllocatingMemoryStream vp8x_chunk_stream;
  252. TRY(write_VP8X_chunk(vp8x_chunk_stream, { .has_icc = true, .has_alpha = alpha_is_used_hint, .width = (u32)bitmap.width(), .height = (u32)bitmap.height() }));
  253. VERIFY(vp8x_chunk_stream.used_buffer_size() % 2 == 0);
  254. vp8x_chunk_bytes = TRY(vp8x_chunk_stream.read_until_eof());
  255. }
  256. u32 total_size = vp8x_chunk_bytes.size() + iccp_chunk_bytes.size() + vp8l_chunk_bytes.size();
  257. TRY(write_webp_header(stream, total_size));
  258. TRY(stream.write_until_depleted(vp8x_chunk_bytes));
  259. TRY(stream.write_until_depleted(iccp_chunk_bytes));
  260. TRY(stream.write_until_depleted(vp8l_chunk_bytes));
  261. return {};
  262. }
  263. class WebPAnimationWriter : public AnimationWriter {
  264. public:
  265. WebPAnimationWriter(SeekableStream& stream, IntSize dimensions, u8 original_vp8x_flags)
  266. : m_stream(stream)
  267. , m_dimensions(dimensions)
  268. , m_vp8x_flags(original_vp8x_flags)
  269. {
  270. }
  271. virtual ErrorOr<void> add_frame(Bitmap&, int, IntPoint) override;
  272. ErrorOr<void> update_size_in_header();
  273. ErrorOr<void> set_alpha_bit_in_header();
  274. private:
  275. SeekableStream& m_stream;
  276. IntSize m_dimensions;
  277. u8 m_vp8x_flags { 0 };
  278. };
  279. static ErrorOr<void> align_to_two(SeekableStream& stream)
  280. {
  281. // https://developers.google.com/speed/webp/docs/riff_container
  282. // "If Chunk Size is odd, a single padding byte -- which MUST be 0 to conform with RIFF -- is added."
  283. if (TRY(stream.tell()) % 2 != 0)
  284. TRY(stream.write_value<u8>(0));
  285. return {};
  286. }
  287. static ErrorOr<void> write_ANMF_chunk(Stream& stream, ANMFChunk const& chunk)
  288. {
  289. if (chunk.frame_width > (1 << 24) || chunk.frame_height > (1 << 24))
  290. return Error::from_string_literal("WebP dimensions too large for ANMF chunk");
  291. if (chunk.frame_width == 0 || chunk.frame_height == 0)
  292. return Error::from_string_literal("WebP lossless animation frames must be at least one pixel wide and tall");
  293. if (chunk.frame_x % 2 != 0 || chunk.frame_y % 2 != 0)
  294. return Error::from_string_literal("WebP lossless animation frames must be at at even coordinates");
  295. dbgln_if(WEBP_DEBUG, "writing ANMF frame_x {} frame_y {} frame_width {} frame_height {} frame_duration {} blending_method {} disposal_method {}",
  296. 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);
  297. TRY(write_chunk_header(stream, "ANMF"sv, 16 + chunk.frame_data.size()));
  298. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  299. // "Frame X: 24 bits (uint24)
  300. // The X coordinate of the upper left corner of the frame is Frame X * 2."
  301. TRY(bit_stream.write_bits(chunk.frame_x / 2, 24u));
  302. // "Frame Y: 24 bits (uint24)
  303. // The Y coordinate of the upper left corner of the frame is Frame Y * 2."
  304. TRY(bit_stream.write_bits(chunk.frame_y / 2, 24u));
  305. // "Frame Width: 24 bits (uint24)
  306. // The 1-based width of the frame. The frame width is 1 + Frame Width Minus One."
  307. TRY(bit_stream.write_bits(chunk.frame_width - 1, 24u));
  308. // "Frame Height: 24 bits (uint24)
  309. // The 1-based height of the frame. The frame height is 1 + Frame Height Minus One."
  310. TRY(bit_stream.write_bits(chunk.frame_height - 1, 24u));
  311. // "Frame Duration: 24 bits (uint24)"
  312. TRY(bit_stream.write_bits(chunk.frame_duration_in_milliseconds, 24u));
  313. // Don't use bit_stream.write_bits() to write individual flags here:
  314. // The spec describes bit flags in MSB to LSB order, but write_bits() writes LSB to MSB.
  315. u8 flags = 0;
  316. // "Reserved: 6 bits
  317. // MUST be 0. Readers MUST ignore this field."
  318. // "Blending method (B): 1 bit"
  319. if (chunk.blending_method == ANMFChunk::BlendingMethod::DoNotBlend)
  320. flags |= 0x2;
  321. // "Disposal method (D): 1 bit"
  322. if (chunk.disposal_method == ANMFChunk::DisposalMethod::DisposeToBackgroundColor)
  323. flags |= 0x1;
  324. TRY(bit_stream.write_bits(flags, 8u));
  325. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  326. TRY(bit_stream.flush_buffer_to_stream());
  327. TRY(stream.write_until_depleted(chunk.frame_data));
  328. if (chunk.frame_data.size() % 2 != 0)
  329. TRY(stream.write_value<u8>(0));
  330. return {};
  331. }
  332. ErrorOr<void> WebPAnimationWriter::add_frame(Bitmap& bitmap, int duration_ms, IntPoint at)
  333. {
  334. if (at.x() < 0 || at.y() < 0 || at.x() + bitmap.width() > m_dimensions.width() || at.y() + bitmap.height() > m_dimensions.height())
  335. return Error::from_string_literal("Frame does not fit in animation dimensions");
  336. // FIXME: The whole writing-and-reading-into-buffer over-and-over is awkward and inefficient.
  337. AllocatingMemoryStream vp8l_header_stream;
  338. TRY(write_VP8L_header(vp8l_header_stream, bitmap.width(), bitmap.height(), true));
  339. auto vp8l_header_bytes = TRY(vp8l_header_stream.read_until_eof());
  340. auto vp8l_data_bytes = TRY(compress_VP8L_image_data(bitmap));
  341. AllocatingMemoryStream vp8l_chunk_stream;
  342. TRY(write_chunk_header(vp8l_chunk_stream, "VP8L"sv, vp8l_header_bytes.size() + vp8l_data_bytes.size()));
  343. TRY(vp8l_chunk_stream.write_until_depleted(vp8l_header_bytes));
  344. TRY(vp8l_chunk_stream.write_until_depleted(vp8l_data_bytes));
  345. TRY(align_to_two(vp8l_chunk_stream));
  346. auto vp8l_chunk_bytes = TRY(vp8l_chunk_stream.read_until_eof());
  347. ANMFChunk chunk;
  348. chunk.frame_x = static_cast<u32>(at.x());
  349. chunk.frame_y = static_cast<u32>(at.y());
  350. chunk.frame_width = static_cast<u32>(bitmap.width());
  351. chunk.frame_height = static_cast<u32>(bitmap.height());
  352. chunk.frame_duration_in_milliseconds = static_cast<u32>(duration_ms);
  353. chunk.blending_method = ANMFChunk::BlendingMethod::DoNotBlend;
  354. chunk.disposal_method = ANMFChunk::DisposalMethod::DoNotDispose;
  355. chunk.frame_data = vp8l_chunk_bytes;
  356. TRY(write_ANMF_chunk(m_stream, chunk));
  357. TRY(update_size_in_header());
  358. if (!(m_vp8x_flags & 0x10) && !are_all_pixels_opaque(bitmap))
  359. TRY(set_alpha_bit_in_header());
  360. return {};
  361. }
  362. ErrorOr<void> WebPAnimationWriter::update_size_in_header()
  363. {
  364. auto current_offset = TRY(m_stream.tell());
  365. TRY(m_stream.seek(4, SeekMode::SetPosition));
  366. VERIFY(current_offset > 8);
  367. TRY(m_stream.write_value<LittleEndian<u32>>(current_offset - 8));
  368. TRY(m_stream.seek(current_offset, SeekMode::SetPosition));
  369. return {};
  370. }
  371. ErrorOr<void> WebPAnimationWriter::set_alpha_bit_in_header()
  372. {
  373. m_vp8x_flags |= 0x10;
  374. auto current_offset = TRY(m_stream.tell());
  375. TRY(m_stream.seek(20, SeekMode::SetPosition));
  376. TRY(m_stream.write_value<u8>(m_vp8x_flags));
  377. TRY(m_stream.seek(current_offset, SeekMode::SetPosition));
  378. return {};
  379. }
  380. static ErrorOr<void> write_ANIM_chunk(Stream& stream, ANIMChunk const& chunk)
  381. {
  382. TRY(write_chunk_header(stream, "ANIM"sv, 6)); // Size of the ANIM chunk.
  383. TRY(stream.write_value<LittleEndian<u32>>(chunk.background_color));
  384. TRY(stream.write_value<LittleEndian<u16>>(chunk.loop_count));
  385. return {};
  386. }
  387. ErrorOr<NonnullOwnPtr<AnimationWriter>> WebPWriter::start_encoding_animation(SeekableStream& stream, IntSize dimensions, int loop_count, Color background_color, Options const& options)
  388. {
  389. // We'll update the stream with the actual size later.
  390. TRY(write_webp_header(stream, 0));
  391. VP8XHeader vp8x_header;
  392. vp8x_header.has_icc = options.icc_data.has_value();
  393. vp8x_header.width = dimensions.width();
  394. vp8x_header.height = dimensions.height();
  395. vp8x_header.has_animation = true;
  396. TRY(write_VP8X_chunk(stream, vp8x_header));
  397. VERIFY(TRY(stream.tell()) % 2 == 0);
  398. ByteBuffer iccp_chunk_bytes;
  399. if (options.icc_data.has_value()) {
  400. TRY(write_chunk_header(stream, "ICCP"sv, options.icc_data.value().size()));
  401. TRY(stream.write_until_depleted(options.icc_data.value()));
  402. TRY(align_to_two(stream));
  403. }
  404. TRY(write_ANIM_chunk(stream, { .background_color = background_color.value(), .loop_count = static_cast<u16>(loop_count) }));
  405. auto writer = make<WebPAnimationWriter>(stream, dimensions, vp8x_flags_from_header(vp8x_header));
  406. TRY(writer->update_size_in_header());
  407. return writer;
  408. }
  409. }