WebPWriter.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. // https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
  161. static ErrorOr<void> write_VP8X_header(Stream& stream, VP8XHeader const& header)
  162. {
  163. if (header.width > (1 << 24) || header.height > (1 << 24))
  164. return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
  165. if (header.width == 0 || header.height == 0)
  166. return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
  167. // "The product of Canvas Width and Canvas Height MUST be at most 2^32 - 1."
  168. u64 product = static_cast<u64>(header.width) * static_cast<u64>(header.height);
  169. if (product >= (1ull << 32))
  170. return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
  171. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  172. // "Reserved (Rsv): 2 bits
  173. // MUST be 0. Readers MUST ignore this field."
  174. TRY(bit_stream.write_bits(0u, 2u));
  175. // "ICC profile (I): 1 bit
  176. // Set if the file contains an 'ICCP' Chunk."
  177. TRY(bit_stream.write_bits(header.has_icc, 1u));
  178. // "Alpha (L): 1 bit
  179. // Set if any of the frames of the image contain transparency information ("alpha")."
  180. TRY(bit_stream.write_bits(header.has_alpha, 1u));
  181. // "Exif metadata (E): 1 bit
  182. // Set if the file contains Exif metadata."
  183. TRY(bit_stream.write_bits(header.has_exif, 1u));
  184. // "XMP metadata (X): 1 bit
  185. // Set if the file contains XMP metadata."
  186. TRY(bit_stream.write_bits(header.has_xmp, 1u));
  187. // "Animation (A): 1 bit
  188. // Set if this is an animated image. Data in 'ANIM' and 'ANMF' Chunks should be used to control the animation."
  189. TRY(bit_stream.write_bits(header.has_animation, 1u));
  190. // "Reserved (R): 1 bit
  191. // MUST be 0. Readers MUST ignore this field."
  192. TRY(bit_stream.write_bits(0u, 1u));
  193. // "Reserved: 24 bits
  194. // MUST be 0. Readers MUST ignore this field."
  195. TRY(bit_stream.write_bits(0u, 24u));
  196. // "Canvas Width Minus One: 24 bits
  197. // 1-based width of the canvas in pixels. The actual canvas width is 1 + Canvas Width Minus One."
  198. TRY(bit_stream.write_bits(header.width - 1, 24u));
  199. // "Canvas Height Minus One: 24 bits
  200. // 1-based height of the canvas in pixels. The actual canvas height is 1 + Canvas Height Minus One."
  201. TRY(bit_stream.write_bits(header.height - 1, 24u));
  202. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  203. TRY(bit_stream.flush_buffer_to_stream());
  204. return {};
  205. }
  206. // FIXME: Consider using LibRIFF for RIFF writing details. (It currently has no writing support.)
  207. static ErrorOr<void> align_to_two(AllocatingMemoryStream& stream)
  208. {
  209. // https://developers.google.com/speed/webp/docs/riff_container
  210. // "If Chunk Size is odd, a single padding byte -- which MUST be 0 to conform with RIFF -- is added."
  211. if (stream.used_buffer_size() % 2 != 0)
  212. TRY(stream.write_value<u8>(0));
  213. return {};
  214. }
  215. ErrorOr<void> WebPWriter::encode(Stream& stream, Bitmap const& bitmap, Options const& options)
  216. {
  217. bool alpha_is_used_hint = !are_all_pixels_opaque(bitmap);
  218. dbgln_if(WEBP_DEBUG, "Writing WebP of size {} with alpha hint: {}", bitmap.size(), alpha_is_used_hint);
  219. // 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.
  220. // FIXME: The whole writing-and-reading-into-buffer over-and-over is awkward and inefficient.
  221. AllocatingMemoryStream vp8l_header_stream;
  222. TRY(write_VP8L_header(vp8l_header_stream, bitmap.width(), bitmap.height(), alpha_is_used_hint));
  223. auto vp8l_header_bytes = TRY(vp8l_header_stream.read_until_eof());
  224. AllocatingMemoryStream vp8l_data_stream;
  225. TRY(write_VP8L_image_data(vp8l_data_stream, bitmap));
  226. auto vp8l_data_bytes = TRY(vp8l_data_stream.read_until_eof());
  227. AllocatingMemoryStream vp8l_chunk_stream;
  228. TRY(write_chunk_header(vp8l_chunk_stream, "VP8L"sv, vp8l_header_bytes.size() + vp8l_data_bytes.size()));
  229. TRY(vp8l_chunk_stream.write_until_depleted(vp8l_header_bytes));
  230. TRY(vp8l_chunk_stream.write_until_depleted(vp8l_data_bytes));
  231. TRY(align_to_two(vp8l_chunk_stream));
  232. auto vp8l_chunk_bytes = TRY(vp8l_chunk_stream.read_until_eof());
  233. ByteBuffer vp8x_chunk_bytes;
  234. ByteBuffer iccp_chunk_bytes;
  235. if (options.icc_data.has_value()) {
  236. dbgln_if(WEBP_DEBUG, "Writing VP8X and ICCP chunks.");
  237. AllocatingMemoryStream iccp_chunk_stream;
  238. TRY(write_chunk_header(iccp_chunk_stream, "ICCP"sv, options.icc_data.value().size()));
  239. TRY(iccp_chunk_stream.write_until_depleted(options.icc_data.value()));
  240. TRY(align_to_two(iccp_chunk_stream));
  241. iccp_chunk_bytes = TRY(iccp_chunk_stream.read_until_eof());
  242. AllocatingMemoryStream vp8x_header_stream;
  243. TRY(write_VP8X_header(vp8x_header_stream, { .has_icc = true, .width = (u32)bitmap.width(), .height = (u32)bitmap.height() }));
  244. auto vp8x_header_bytes = TRY(vp8x_header_stream.read_until_eof());
  245. AllocatingMemoryStream vp8x_chunk_stream;
  246. TRY(write_chunk_header(vp8x_chunk_stream, "VP8X"sv, vp8x_header_bytes.size()));
  247. TRY(vp8x_chunk_stream.write_until_depleted(vp8x_header_bytes));
  248. VERIFY(vp8x_chunk_stream.used_buffer_size() % 2 == 0);
  249. vp8x_chunk_bytes = TRY(vp8x_chunk_stream.read_until_eof());
  250. }
  251. u32 total_size = vp8x_chunk_bytes.size() + iccp_chunk_bytes.size() + vp8l_chunk_bytes.size();
  252. TRY(write_webp_header(stream, total_size));
  253. TRY(stream.write_until_depleted(vp8x_chunk_bytes));
  254. TRY(stream.write_until_depleted(iccp_chunk_bytes));
  255. TRY(stream.write_until_depleted(vp8l_chunk_bytes));
  256. return {};
  257. }
  258. }