WebPWriter.cpp 22 KB

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