WebPWriter.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. #include <AK/BitStream.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Endian.h>
  10. #include <AK/MemoryStream.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. namespace Gfx {
  16. // https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
  17. static ErrorOr<void> write_webp_header(Stream& stream, unsigned data_size)
  18. {
  19. TRY(stream.write_until_depleted("RIFF"sv));
  20. TRY(stream.write_value<LittleEndian<u32>>("WEBP"sv.length() + data_size));
  21. TRY(stream.write_until_depleted("WEBP"sv));
  22. return {};
  23. }
  24. static ErrorOr<void> write_chunk_header(Stream& stream, StringView chunk_fourcc, unsigned data_size)
  25. {
  26. TRY(stream.write_until_depleted(chunk_fourcc));
  27. TRY(stream.write_value<LittleEndian<u32>>(data_size));
  28. return {};
  29. }
  30. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
  31. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#7_overall_structure_of_the_format
  32. static ErrorOr<void> write_VP8L_header(Stream& stream, unsigned width, unsigned height, bool alpha_is_used_hint)
  33. {
  34. // "The 14-bit precision for image width and height limits the maximum size of a WebP lossless image to 16384✕16384 pixels."
  35. if (width > 16384 || height > 16384)
  36. return Error::from_string_literal("WebP lossless images can't be larger than 16384x16384 pixels");
  37. if (width == 0 || height == 0)
  38. return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
  39. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  40. // Signature byte.
  41. TRY(bit_stream.write_bits(0x2fu, 8u)); // Signature byte
  42. // 14 bits width-1, 14 bits height-1, 1 bit alpha hint, 3 bit version_number.
  43. TRY(bit_stream.write_bits(width - 1, 14u));
  44. TRY(bit_stream.write_bits(height - 1, 14u));
  45. // "The alpha_is_used bit is a hint only, and should not impact decoding.
  46. // It should be set to 0 when all alpha values are 255 in the picture, and 1 otherwise."
  47. TRY(bit_stream.write_bits(alpha_is_used_hint, 1u));
  48. // "The version_number is a 3 bit code that must be set to 0."
  49. TRY(bit_stream.write_bits(0u, 3u));
  50. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  51. TRY(bit_stream.flush_buffer_to_stream());
  52. return {};
  53. }
  54. // FIXME: Consider using LibRIFF for RIFF writing details. (It currently has no writing support.)
  55. static ErrorOr<void> align_to_two(Stream& stream, size_t number_of_bytes_written)
  56. {
  57. // https://developers.google.com/speed/webp/docs/riff_container
  58. // "If Chunk Size is odd, a single padding byte -- which MUST be 0 to conform with RIFF -- is added."
  59. if (number_of_bytes_written % 2 != 0)
  60. TRY(stream.write_value<u8>(0));
  61. return {};
  62. }
  63. constexpr size_t vp8l_header_size = 5; // 1 byte signature + (2 * 14 bits width and height + 1 bit alpha hint + 3 bit version_number)
  64. static size_t compute_VP8L_chunk_size(ByteBuffer const& data)
  65. {
  66. constexpr size_t chunk_header_size = 8; // "VP8L" + size
  67. return chunk_header_size + align_up_to(vp8l_header_size + data.size(), 2);
  68. }
  69. static ErrorOr<void> write_VP8L_chunk(Stream& stream, unsigned width, unsigned height, bool alpha_is_used_hint, ByteBuffer const& data)
  70. {
  71. size_t const number_of_bytes_written = vp8l_header_size + data.size();
  72. TRY(write_chunk_header(stream, "VP8L"sv, number_of_bytes_written));
  73. TRY(write_VP8L_header(stream, width, height, alpha_is_used_hint));
  74. TRY(stream.write_until_depleted(data));
  75. TRY(align_to_two(stream, number_of_bytes_written));
  76. return {};
  77. }
  78. static u8 vp8x_flags_from_header(VP8XHeader const& header)
  79. {
  80. u8 flags = 0;
  81. // "Reserved (Rsv): 2 bits
  82. // MUST be 0. Readers MUST ignore this field."
  83. // "ICC profile (I): 1 bit
  84. // Set if the file contains an 'ICCP' Chunk."
  85. if (header.has_icc)
  86. flags |= 0x20;
  87. // "Alpha (L): 1 bit
  88. // Set if any of the frames of the image contain transparency information ("alpha")."
  89. if (header.has_alpha)
  90. flags |= 0x10;
  91. // "Exif metadata (E): 1 bit
  92. // Set if the file contains Exif metadata."
  93. if (header.has_exif)
  94. flags |= 0x8;
  95. // "XMP metadata (X): 1 bit
  96. // Set if the file contains XMP metadata."
  97. if (header.has_xmp)
  98. flags |= 0x4;
  99. // "Animation (A): 1 bit
  100. // Set if this is an animated image. Data in 'ANIM' and 'ANMF' Chunks should be used to control the animation."
  101. if (header.has_animation)
  102. flags |= 0x2;
  103. // "Reserved (R): 1 bit
  104. // MUST be 0. Readers MUST ignore this field."
  105. return flags;
  106. }
  107. // https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
  108. static ErrorOr<void> write_VP8X_chunk(Stream& stream, VP8XHeader const& header)
  109. {
  110. if (header.width > (1 << 24) || header.height > (1 << 24))
  111. return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
  112. if (header.width == 0 || header.height == 0)
  113. return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
  114. // "The product of Canvas Width and Canvas Height MUST be at most 2^32 - 1."
  115. u64 product = static_cast<u64>(header.width) * static_cast<u64>(header.height);
  116. if (product >= (1ull << 32))
  117. return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
  118. TRY(write_chunk_header(stream, "VP8X"sv, 10));
  119. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  120. // Don't use bit_stream.write_bits() to write individual flags here:
  121. // The spec describes bit flags in MSB to LSB order, but write_bits() writes LSB to MSB.
  122. TRY(bit_stream.write_bits(vp8x_flags_from_header(header), 8u));
  123. // "Reserved: 24 bits
  124. // MUST be 0. Readers MUST ignore this field."
  125. TRY(bit_stream.write_bits(0u, 24u));
  126. // "Canvas Width Minus One: 24 bits
  127. // 1-based width of the canvas in pixels. The actual canvas width is 1 + Canvas Width Minus One."
  128. TRY(bit_stream.write_bits(header.width - 1, 24u));
  129. // "Canvas Height Minus One: 24 bits
  130. // 1-based height of the canvas in pixels. The actual canvas height is 1 + Canvas Height Minus One."
  131. TRY(bit_stream.write_bits(header.height - 1, 24u));
  132. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  133. TRY(bit_stream.flush_buffer_to_stream());
  134. return {};
  135. }
  136. // FIXME: Consider using LibRIFF for RIFF writing details. (It currently has no writing support.)
  137. static ErrorOr<void> align_to_two(AllocatingMemoryStream& stream)
  138. {
  139. return align_to_two(stream, stream.used_buffer_size());
  140. }
  141. ErrorOr<void> WebPWriter::encode(Stream& stream, Bitmap const& bitmap, Options const& options)
  142. {
  143. // 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.
  144. bool is_fully_opaque;
  145. auto vp8l_data_bytes = TRY(compress_VP8L_image_data(bitmap, options.vp8l_options, is_fully_opaque));
  146. bool alpha_is_used_hint = !is_fully_opaque;
  147. dbgln_if(WEBP_DEBUG, "Writing WebP of size {} with alpha hint: {}", bitmap.size(), alpha_is_used_hint);
  148. ByteBuffer vp8x_chunk_bytes;
  149. ByteBuffer iccp_chunk_bytes;
  150. if (options.icc_data.has_value()) {
  151. // FIXME: The whole writing-and-reading-into-buffer over-and-over is awkward and inefficient.
  152. // Maybe add an abstraction that knows its size and can write its data later. This would
  153. // allow saving a few copies.
  154. dbgln_if(WEBP_DEBUG, "Writing VP8X and ICCP chunks.");
  155. AllocatingMemoryStream iccp_chunk_stream;
  156. TRY(write_chunk_header(iccp_chunk_stream, "ICCP"sv, options.icc_data.value().size()));
  157. TRY(iccp_chunk_stream.write_until_depleted(options.icc_data.value()));
  158. TRY(align_to_two(iccp_chunk_stream));
  159. iccp_chunk_bytes = TRY(iccp_chunk_stream.read_until_eof());
  160. AllocatingMemoryStream vp8x_chunk_stream;
  161. TRY(write_VP8X_chunk(vp8x_chunk_stream, { .has_icc = true, .has_alpha = alpha_is_used_hint, .width = (u32)bitmap.width(), .height = (u32)bitmap.height() }));
  162. VERIFY(vp8x_chunk_stream.used_buffer_size() % 2 == 0);
  163. vp8x_chunk_bytes = TRY(vp8x_chunk_stream.read_until_eof());
  164. }
  165. u32 total_size = vp8x_chunk_bytes.size() + iccp_chunk_bytes.size() + compute_VP8L_chunk_size(vp8l_data_bytes);
  166. TRY(write_webp_header(stream, total_size));
  167. TRY(stream.write_until_depleted(vp8x_chunk_bytes));
  168. TRY(stream.write_until_depleted(iccp_chunk_bytes));
  169. TRY(write_VP8L_chunk(stream, bitmap.width(), bitmap.height(), alpha_is_used_hint, vp8l_data_bytes));
  170. return {};
  171. }
  172. class WebPAnimationWriter : public AnimationWriter {
  173. public:
  174. WebPAnimationWriter(SeekableStream& stream, IntSize dimensions, u8 original_vp8x_flags, VP8LEncoderOptions vp8l_options)
  175. : m_stream(stream)
  176. , m_dimensions(dimensions)
  177. , m_vp8x_flags(original_vp8x_flags)
  178. , m_vp8l_options(vp8l_options)
  179. {
  180. }
  181. virtual ErrorOr<void> add_frame(Bitmap&, int, IntPoint) override;
  182. ErrorOr<void> update_size_in_header();
  183. ErrorOr<void> set_alpha_bit_in_header();
  184. private:
  185. SeekableStream& m_stream;
  186. IntSize m_dimensions;
  187. u8 m_vp8x_flags { 0 };
  188. VP8LEncoderOptions m_vp8l_options;
  189. };
  190. static ErrorOr<void> align_to_two(SeekableStream& stream)
  191. {
  192. return align_to_two(stream, TRY(stream.tell()));
  193. }
  194. static ErrorOr<void> write_ANMF_chunk_header(Stream& stream, ANMFChunkHeader const& chunk, size_t payload_size)
  195. {
  196. if (chunk.frame_width > (1 << 24) || chunk.frame_height > (1 << 24))
  197. return Error::from_string_literal("WebP dimensions too large for ANMF chunk");
  198. if (chunk.frame_width == 0 || chunk.frame_height == 0)
  199. return Error::from_string_literal("WebP lossless animation frames must be at least one pixel wide and tall");
  200. if (chunk.frame_x % 2 != 0 || chunk.frame_y % 2 != 0)
  201. return Error::from_string_literal("WebP lossless animation frames must be at at even coordinates");
  202. dbgln_if(WEBP_DEBUG, "writing ANMF frame_x {} frame_y {} frame_width {} frame_height {} frame_duration {} blending_method {} disposal_method {}",
  203. 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);
  204. TRY(write_chunk_header(stream, "ANMF"sv, 16 + payload_size));
  205. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  206. // "Frame X: 24 bits (uint24)
  207. // The X coordinate of the upper left corner of the frame is Frame X * 2."
  208. TRY(bit_stream.write_bits(chunk.frame_x / 2, 24u));
  209. // "Frame Y: 24 bits (uint24)
  210. // The Y coordinate of the upper left corner of the frame is Frame Y * 2."
  211. TRY(bit_stream.write_bits(chunk.frame_y / 2, 24u));
  212. // "Frame Width: 24 bits (uint24)
  213. // The 1-based width of the frame. The frame width is 1 + Frame Width Minus One."
  214. TRY(bit_stream.write_bits(chunk.frame_width - 1, 24u));
  215. // "Frame Height: 24 bits (uint24)
  216. // The 1-based height of the frame. The frame height is 1 + Frame Height Minus One."
  217. TRY(bit_stream.write_bits(chunk.frame_height - 1, 24u));
  218. // "Frame Duration: 24 bits (uint24)"
  219. TRY(bit_stream.write_bits(chunk.frame_duration_in_milliseconds, 24u));
  220. // Don't use bit_stream.write_bits() to write individual flags here:
  221. // The spec describes bit flags in MSB to LSB order, but write_bits() writes LSB to MSB.
  222. u8 flags = 0;
  223. // "Reserved: 6 bits
  224. // MUST be 0. Readers MUST ignore this field."
  225. // "Blending method (B): 1 bit"
  226. if (chunk.blending_method == ANMFChunkHeader::BlendingMethod::DoNotBlend)
  227. flags |= 0x2;
  228. // "Disposal method (D): 1 bit"
  229. if (chunk.disposal_method == ANMFChunkHeader::DisposalMethod::DisposeToBackgroundColor)
  230. flags |= 0x1;
  231. TRY(bit_stream.write_bits(flags, 8u));
  232. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  233. TRY(bit_stream.flush_buffer_to_stream());
  234. return {};
  235. }
  236. ErrorOr<void> WebPAnimationWriter::add_frame(Bitmap& bitmap, int duration_ms, IntPoint at)
  237. {
  238. if (at.x() < 0 || at.y() < 0 || at.x() + bitmap.width() > m_dimensions.width() || at.y() + bitmap.height() > m_dimensions.height())
  239. return Error::from_string_literal("Frame does not fit in animation dimensions");
  240. // Since we have a SeekableStream, we could write both the VP8L chunk header and the ANMF chunk header with a placeholder size,
  241. // compress the frame data directly to the stream, and then go back and update the two sizes.
  242. // That's pretty messy though, and the compressed image data is smaller than the uncompressed bitmap passed in. So we'll buffer it.
  243. bool is_fully_opaque;
  244. auto vp8l_data_bytes = TRY(compress_VP8L_image_data(bitmap, m_vp8l_options, is_fully_opaque));
  245. ANMFChunkHeader chunk;
  246. chunk.frame_x = static_cast<u32>(at.x());
  247. chunk.frame_y = static_cast<u32>(at.y());
  248. chunk.frame_width = static_cast<u32>(bitmap.width());
  249. chunk.frame_height = static_cast<u32>(bitmap.height());
  250. chunk.frame_duration_in_milliseconds = static_cast<u32>(duration_ms);
  251. chunk.blending_method = ANMFChunkHeader::BlendingMethod::DoNotBlend;
  252. chunk.disposal_method = ANMFChunkHeader::DisposalMethod::DoNotDispose;
  253. TRY(write_ANMF_chunk_header(m_stream, chunk, compute_VP8L_chunk_size(vp8l_data_bytes)));
  254. bool alpha_is_used_hint = !is_fully_opaque;
  255. TRY(write_VP8L_chunk(m_stream, bitmap.width(), bitmap.height(), alpha_is_used_hint, vp8l_data_bytes));
  256. TRY(update_size_in_header());
  257. if (!(m_vp8x_flags & 0x10) && !is_fully_opaque)
  258. TRY(set_alpha_bit_in_header());
  259. return {};
  260. }
  261. ErrorOr<void> WebPAnimationWriter::update_size_in_header()
  262. {
  263. auto current_offset = TRY(m_stream.tell());
  264. TRY(m_stream.seek(4, SeekMode::SetPosition));
  265. VERIFY(current_offset > 8);
  266. TRY(m_stream.write_value<LittleEndian<u32>>(current_offset - 8));
  267. TRY(m_stream.seek(current_offset, SeekMode::SetPosition));
  268. return {};
  269. }
  270. ErrorOr<void> WebPAnimationWriter::set_alpha_bit_in_header()
  271. {
  272. m_vp8x_flags |= 0x10;
  273. auto current_offset = TRY(m_stream.tell());
  274. // 4 bytes for "RIFF",
  275. // 4 bytes RIFF chunk size (i.e. file size - 8),
  276. // 4 bytes for "WEBP",
  277. // 4 bytes for "VP8X",
  278. // 4 bytes for VP8X chunk size,
  279. // followed by VP8X flags in the first byte of the VP8X chunk data.
  280. TRY(m_stream.seek(20, SeekMode::SetPosition));
  281. TRY(m_stream.write_value<u8>(m_vp8x_flags));
  282. TRY(m_stream.seek(current_offset, SeekMode::SetPosition));
  283. return {};
  284. }
  285. static ErrorOr<void> write_ANIM_chunk(Stream& stream, ANIMChunk const& chunk)
  286. {
  287. TRY(write_chunk_header(stream, "ANIM"sv, 6)); // Size of the ANIM chunk.
  288. TRY(stream.write_value<LittleEndian<u32>>(chunk.background_color));
  289. TRY(stream.write_value<LittleEndian<u16>>(chunk.loop_count));
  290. return {};
  291. }
  292. ErrorOr<NonnullOwnPtr<AnimationWriter>> WebPWriter::start_encoding_animation(SeekableStream& stream, IntSize dimensions, int loop_count, Color background_color, Options const& options)
  293. {
  294. // We'll update the stream with the actual size later.
  295. TRY(write_webp_header(stream, 0));
  296. VP8XHeader vp8x_header;
  297. vp8x_header.has_icc = options.icc_data.has_value();
  298. vp8x_header.width = dimensions.width();
  299. vp8x_header.height = dimensions.height();
  300. vp8x_header.has_animation = true;
  301. TRY(write_VP8X_chunk(stream, vp8x_header));
  302. VERIFY(TRY(stream.tell()) % 2 == 0);
  303. ByteBuffer iccp_chunk_bytes;
  304. if (options.icc_data.has_value()) {
  305. TRY(write_chunk_header(stream, "ICCP"sv, options.icc_data.value().size()));
  306. TRY(stream.write_until_depleted(options.icc_data.value()));
  307. TRY(align_to_two(stream));
  308. }
  309. TRY(write_ANIM_chunk(stream, { .background_color = background_color.value(), .loop_count = static_cast<u16>(loop_count) }));
  310. auto writer = make<WebPAnimationWriter>(stream, dimensions, vp8x_flags_from_header(vp8x_header), options.vp8l_options);
  311. TRY(writer->update_size_in_header());
  312. return writer;
  313. }
  314. }