WebPWriter.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 <LibCompress/DeflateTables.h>
  10. #include <LibGfx/Bitmap.h>
  11. #include <LibGfx/ImageFormats/WebPWriter.h>
  12. #include <LibRIFF/RIFF.h>
  13. namespace Gfx {
  14. // https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
  15. static ErrorOr<void> write_webp_header(Stream& stream, unsigned data_size)
  16. {
  17. TRY(stream.write_until_depleted("RIFF"sv));
  18. TRY(stream.write_value<LittleEndian<u32>>(4 + data_size)); // Including size of "WEBP" and the data size itself.
  19. TRY(stream.write_until_depleted("WEBP"sv));
  20. return {};
  21. }
  22. static ErrorOr<void> write_chunk_header(Stream& stream, StringView chunk_fourcc, unsigned vp8l_data_size)
  23. {
  24. TRY(stream.write_until_depleted(chunk_fourcc));
  25. TRY(stream.write_value<LittleEndian<u32>>(vp8l_data_size));
  26. return {};
  27. }
  28. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
  29. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#7_overall_structure_of_the_format
  30. static ErrorOr<void> write_VP8L_header(Stream& stream, unsigned width, unsigned height, bool alpha_hint)
  31. {
  32. // "The 14-bit precision for image width and height limits the maximum size of a WebP lossless image to 16384✕16384 pixels."
  33. if (width > 16384 || height > 16384)
  34. return Error::from_string_literal("WebP lossless images can't be larger than 16384x16384 pixels");
  35. if (width == 0 || height == 0)
  36. return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
  37. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  38. // Signature byte.
  39. TRY(bit_stream.write_bits(0x2fu, 8u)); // Signature byte
  40. // 14 bits width-1, 14 bits height-1, 1 bit alpha hint, 3 bit version_number.
  41. TRY(bit_stream.write_bits(width - 1, 14u));
  42. TRY(bit_stream.write_bits(height - 1, 14u));
  43. // "The alpha_is_used bit is a hint only, and should not impact decoding.
  44. // It should be set to 0 when all alpha values are 255 in the picture, and 1 otherwise."
  45. TRY(bit_stream.write_bits(alpha_hint, 1u));
  46. // "The version_number is a 3 bit code that must be set to 0."
  47. TRY(bit_stream.write_bits(0u, 3u));
  48. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  49. TRY(bit_stream.flush_buffer_to_stream());
  50. return {};
  51. }
  52. static ErrorOr<void> write_VP8L_image_data(Stream& stream, Bitmap const& bitmap)
  53. {
  54. LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
  55. // optional-transform = (%b1 transform optional-transform) / %b0
  56. TRY(bit_stream.write_bits(0u, 1u)); // No transform for now.
  57. // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#5_image_data
  58. // spatially-coded-image = color-cache-info meta-prefix data
  59. // color-cache-info = %b0
  60. // color-cache-info =/ (%b1 4BIT) ; 1 followed by color cache size
  61. TRY(bit_stream.write_bits(0u, 1u)); // No color cache for now.
  62. // meta-prefix = %b0 / (%b1 entropy-image)
  63. TRY(bit_stream.write_bits(0u, 1u)); // No meta prefix for now.
  64. // data = prefix-codes lz77-coded-image
  65. // prefix-codes = prefix-code-group *prefix-codes
  66. // prefix-code-group =
  67. // 5prefix-code ; See "Interpretation of Meta Prefix Codes" to
  68. // ; understand what each of these five prefix
  69. // ; codes are for.
  70. // We're writing a single prefix-code-group.
  71. // "These codes are (in bitstream order):
  72. // Prefix code #1: Used for green channel, backward-reference length, and color cache.
  73. // Prefix code #2, #3, and #4: Used for red, blue, and alpha channels, respectively.
  74. // Prefix code #5: Used for backward-reference distance."
  75. // We use neither back-references not color cache entries yet.
  76. // We write prefix trees for 256 literals all of length 8, which means each byte is encoded as itself.
  77. // That doesn't give any compression, but is a valid bit stream.
  78. // We can make this smarter later on.
  79. size_t const color_cache_size = 0;
  80. constexpr Array alphabet_sizes = to_array<size_t>({ 256 + 24 + static_cast<size_t>(color_cache_size), 256, 256, 256, 40 }); // XXX Shared?
  81. // If you add support for color cache: At the moment, CanonicalCodes does not support writing more than 288 symbols.
  82. if (alphabet_sizes[0] > 288)
  83. return Error::from_string_literal("Invalid alphabet size");
  84. for (int i = 0; i < 4; ++i) {
  85. TRY(bit_stream.write_bits(0u, 1u)); // Normal code length code.
  86. // Write code length codes.
  87. constexpr int kCodeLengthCodes = 19;
  88. Array<int, kCodeLengthCodes> kCodeLengthCodeOrder = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
  89. int num_code_lengths = max(4u, find_index(kCodeLengthCodeOrder.begin(), kCodeLengthCodeOrder.end(), 8) + 1);
  90. // "int num_code_lengths = 4 + ReadBits(4);"
  91. TRY(bit_stream.write_bits(num_code_lengths - 4u, 4u));
  92. for (int i = 0; i < num_code_lengths - 1; ++i)
  93. TRY(bit_stream.write_bits(0u, 3u));
  94. TRY(bit_stream.write_bits(1u, 3u));
  95. // Write code lengths.
  96. if (alphabet_sizes[i] == 256) {
  97. TRY(bit_stream.write_bits(0u, 1u)); // max_symbol is alphabet_size
  98. } else {
  99. TRY(bit_stream.write_bits(1u, 1u)); // max_symbol is explicitly coded
  100. // "int length_nbits = 2 + 2 * ReadBits(3);
  101. // int max_symbol = 2 + ReadBits(length_nbits);"
  102. TRY(bit_stream.write_bits(3u, 3u)); // length_nbits = 2 + 2 * 3
  103. TRY(bit_stream.write_bits(254u, 8u)); // max_symbol = 2 + 254
  104. }
  105. // The code length codes only contain a single entry for '8'. WebP streams with a single element store 0 bits per element.
  106. // (This is different from deflate, which needs 1 bit per element.)
  107. }
  108. // For code #5, use a simple empty code, since we don't use this yet.
  109. TRY(bit_stream.write_bits(1u, 1u)); // Simple code length code.
  110. TRY(bit_stream.write_bits(0u, 1u)); // num_symbols - 1
  111. TRY(bit_stream.write_bits(0u, 1u)); // is_first_8bits
  112. TRY(bit_stream.write_bits(0u, 1u)); // symbol0
  113. // Image data.
  114. for (ARGB32 pixel : bitmap) {
  115. u8 a = pixel >> 24;
  116. u8 r = pixel >> 16;
  117. u8 g = pixel >> 8;
  118. u8 b = pixel;
  119. // We wrote a huffman table that gives every symbol 8 bits. That means we can write the image data
  120. // out uncompressed –- but we do need to reverse the bit order of the bytes.
  121. TRY(bit_stream.write_bits(Compress::reverse8_lookup_table[g], 8u));
  122. TRY(bit_stream.write_bits(Compress::reverse8_lookup_table[r], 8u));
  123. TRY(bit_stream.write_bits(Compress::reverse8_lookup_table[b], 8u));
  124. TRY(bit_stream.write_bits(Compress::reverse8_lookup_table[a], 8u));
  125. }
  126. // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
  127. TRY(bit_stream.align_to_byte_boundary());
  128. TRY(bit_stream.flush_buffer_to_stream());
  129. return {};
  130. }
  131. // FIXME: Consider using LibRIFF for RIFF writing details. (It currently has no writing support.)
  132. static ErrorOr<void> align_to_two(AllocatingMemoryStream& stream)
  133. {
  134. // https://developers.google.com/speed/webp/docs/riff_container
  135. // "If Chunk Size is odd, a single padding byte -- which MUST be 0 to conform with RIFF -- is added."
  136. if (stream.used_buffer_size() % 2 != 0)
  137. TRY(stream.write_value<u8>(0));
  138. return {};
  139. }
  140. ErrorOr<void> WebPWriter::encode(Stream& stream, Bitmap const& bitmap, Options const& options)
  141. {
  142. // 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.
  143. // FIXME: The whole writing-and-reading-into-buffer over-and-over is awkward and inefficient.
  144. AllocatingMemoryStream vp8l_header_stream;
  145. TRY(write_VP8L_header(vp8l_header_stream, bitmap.width(), bitmap.height(), true));
  146. auto vp8l_header_bytes = TRY(vp8l_header_stream.read_until_eof());
  147. AllocatingMemoryStream vp8l_data_stream;
  148. TRY(write_VP8L_image_data(vp8l_data_stream, bitmap));
  149. auto vp8l_data_bytes = TRY(vp8l_data_stream.read_until_eof());
  150. AllocatingMemoryStream vp8l_chunk_stream;
  151. TRY(write_chunk_header(vp8l_chunk_stream, "VP8L"sv, vp8l_header_bytes.size() + vp8l_data_bytes.size()));
  152. TRY(vp8l_chunk_stream.write_until_depleted(vp8l_header_bytes));
  153. TRY(vp8l_chunk_stream.write_until_depleted(vp8l_data_bytes));
  154. TRY(align_to_two(vp8l_chunk_stream));
  155. auto vp8l_chunk_bytes = TRY(vp8l_chunk_stream.read_until_eof());
  156. if (options.icc_data.has_value()) {
  157. // FIXME: Write VP8X, ICCP chunks.
  158. dbgln("WebPWriter: Can't write ICC data to webp files yet, dropping it for now");
  159. }
  160. TRY(write_webp_header(stream, vp8l_chunk_bytes.size()));
  161. TRY(stream.write_until_depleted(vp8l_chunk_bytes));
  162. return {};
  163. }
  164. }