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