Skip to content

Truly independent web browser

LibGfx: Remove the WebP writer

Shannon Booth51eb854f66a5
diff --git a/AK/Debug.h.in b/AK/Debug.h.in
index 3a1fad512e6..7ebf8d043ec 100644
--- a/AK/Debug.h.in
+++ b/AK/Debug.h.in
@@ -274,10 +274,6 @@
# cmakedefine01 WEB_WORKER_DEBUG
#endif
-#ifndef WEBP_DEBUG
-# cmakedefine01 WEBP_DEBUG
-#endif
-
#ifndef XML_PARSER_DEBUG
# cmakedefine01 XML_PARSER_DEBUG
#endif
diff --git a/Libraries/LibGfx/CMakeLists.txt b/Libraries/LibGfx/CMakeLists.txt
index cc4f4298ead..70a06646b53 100644
--- a/Libraries/LibGfx/CMakeLists.txt
+++ b/Libraries/LibGfx/CMakeLists.txt
@@ -28,9 +28,6 @@ set(SOURCES
RustProcessState.cpp
ImageFormats/JPEGWriter.cpp
ImageFormats/PNGWriter.cpp
- ImageFormats/WebPSharedLossless.cpp
- ImageFormats/WebPWriter.cpp
- ImageFormats/WebPWriterLossless.cpp
PaintStyle.cpp
Palette.cpp
Path.cpp
diff --git a/Libraries/LibGfx/ImageFormats/WebPShared.h b/Libraries/LibGfx/ImageFormats/WebPShared.h
deleted file mode 100644
index 603b561e663..00000000000
--- a/Libraries/LibGfx/ImageFormats/WebPShared.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2024, Nico Weber <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Span.h>
-#include <AK/Types.h>
-
-namespace Gfx {
-
-struct VP8XHeader {
- bool has_icc { false };
- bool has_alpha { false };
- bool has_exif { false };
- bool has_xmp { false };
- bool has_animation { false };
- u32 width { 0 };
- u32 height { 0 };
-};
-
-struct ANIMChunk {
- u32 background_color { 0 };
- u16 loop_count { 0 };
-};
-
-struct ANMFChunkHeader {
- u32 frame_x { 0 };
- u32 frame_y { 0 };
- u32 frame_width { 0 };
- u32 frame_height { 0 };
- u32 frame_duration_in_milliseconds { 0 };
-
- enum class BlendingMethod {
- UseAlphaBlending = 0,
- DoNotBlend = 1,
- };
- BlendingMethod blending_method { BlendingMethod::UseAlphaBlending };
-
- enum class DisposalMethod {
- DoNotDispose = 0,
- DisposeToBackgroundColor = 1,
- };
- DisposalMethod disposal_method { DisposalMethod::DoNotDispose };
-};
-
-struct ANMFChunk {
- ANMFChunkHeader header;
- ReadonlyBytes frame_data;
-};
-
-}
diff --git a/Libraries/LibGfx/ImageFormats/WebPSharedLossless.cpp b/Libraries/LibGfx/ImageFormats/WebPSharedLossless.cpp
deleted file mode 100644
index 331b4202cfe..00000000000
--- a/Libraries/LibGfx/ImageFormats/WebPSharedLossless.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2024, Nico Weber <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGfx/ImageFormats/WebPSharedLossless.h>
-
-namespace Gfx {
-
-ErrorOr<CanonicalCode> CanonicalCode::from_bytes(ReadonlyBytes bytes)
-{
- auto non_zero_symbol_count = 0;
- auto last_non_zero_symbol = -1;
- for (size_t i = 0; i < bytes.size(); i++) {
- if (bytes[i] != 0) {
- non_zero_symbol_count++;
- last_non_zero_symbol = i;
- }
- }
-
- if (non_zero_symbol_count == 1)
- return CanonicalCode(last_non_zero_symbol);
-
- return CanonicalCode(TRY(Compress::CanonicalCode::from_bytes(bytes)));
-}
-
-}
diff --git a/Libraries/LibGfx/ImageFormats/WebPSharedLossless.h b/Libraries/LibGfx/ImageFormats/WebPSharedLossless.h
deleted file mode 100644
index 4bf88874ec1..00000000000
--- a/Libraries/LibGfx/ImageFormats/WebPSharedLossless.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2024, Nico Weber <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibCompress/Deflate.h>
-
-namespace Gfx {
-
-constexpr Array kCodeLengthCodeOrder = { 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
-
-// WebP-lossless's CanonicalCodes are almost identical to deflate's.
-// One difference is that codes with a single element in webp-lossless consume 0 bits to produce that single element,
-// while they consume 1 bit in Compress::CanonicalCode. This class wraps Compress::CanonicalCode to handle the case
-// where the codes contain just a single element, and dispatches to Compress::CanonicalCode else.
-class CanonicalCode {
-public:
- CanonicalCode() = default;
-
- static ErrorOr<CanonicalCode> from_bytes(ReadonlyBytes);
- ErrorOr<void> write_symbol(LittleEndianOutputBitStream&, u32) const;
-
-private:
- explicit CanonicalCode(u32 single_symbol)
- : m_code(single_symbol)
- {
- }
-
- explicit CanonicalCode(Compress::CanonicalCode code)
- : m_code(move(code))
- {
- }
-
- Variant<u32, Compress::CanonicalCode> m_code { 0 };
-};
-
-ALWAYS_INLINE ErrorOr<void> CanonicalCode::write_symbol(LittleEndianOutputBitStream& bit_stream, u32 symbol) const
-{
- TRY(m_code.visit(
- [&](u32 single_code) __attribute__((always_inline)) -> ErrorOr<void> { VERIFY(symbol == single_code); return {}; },
- [&](Compress::CanonicalCode const& code) __attribute__((always_inline)) { return code.write_symbol(bit_stream, symbol); }));
- return {};
-}
-
-// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#61_overview
-// "From here on, we refer to this set as a prefix code group."
-class PrefixCodeGroup {
-public:
- PrefixCodeGroup() = default;
- PrefixCodeGroup(PrefixCodeGroup&&) = default;
- PrefixCodeGroup(PrefixCodeGroup const&) = delete;
-
- CanonicalCode& operator[](int i) { return m_codes[i]; }
- CanonicalCode const& operator[](int i) const { return m_codes[i]; }
-
-private:
- Array<CanonicalCode, 5> m_codes;
-};
-
-enum class ImageKind {
- SpatiallyCoded,
- EntropyCoded,
-};
-
-enum TransformType {
- // predictor-tx = %b00 predictor-image
- PREDICTOR_TRANSFORM = 0,
-
- // color-tx = %b01 color-image
- COLOR_TRANSFORM = 1,
-
- // subtract-green-tx = %b10
- SUBTRACT_GREEN_TRANSFORM = 2,
-
- // color-indexing-tx = %b11 color-indexing-image
- COLOR_INDEXING_TRANSFORM = 3,
-};
-
-}
diff --git a/Libraries/LibGfx/ImageFormats/WebPWriter.cpp b/Libraries/LibGfx/ImageFormats/WebPWriter.cpp
deleted file mode 100644
index df5fc1f5f72..00000000000
--- a/Libraries/LibGfx/ImageFormats/WebPWriter.cpp
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Copyright (c) 2024, Nico Weber <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-// Container: https://developers.google.com/speed/webp/docs/riff_container
-
-#include <AK/BitStream.h>
-#include <AK/ByteBuffer.h>
-#include <AK/Debug.h>
-#include <AK/Endian.h>
-#include <AK/MemoryStream.h>
-#include <LibGfx/Bitmap.h>
-#include <LibGfx/ImageFormats/WebPShared.h>
-#include <LibGfx/ImageFormats/WebPWriter.h>
-#include <LibGfx/ImageFormats/WebPWriterLossless.h>
-
-namespace Gfx {
-
-// https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
-static ErrorOr<void> write_webp_header(Stream& stream, unsigned data_size)
-{
- TRY(stream.write_until_depleted("RIFF"sv));
- TRY(stream.write_value<LittleEndian<u32>>("WEBP"sv.length() + data_size));
- TRY(stream.write_until_depleted("WEBP"sv));
- return {};
-}
-
-static ErrorOr<void> write_chunk_header(Stream& stream, StringView chunk_fourcc, unsigned data_size)
-{
- TRY(stream.write_until_depleted(chunk_fourcc));
- TRY(stream.write_value<LittleEndian<u32>>(data_size));
- return {};
-}
-
-// https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
-// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#7_overall_structure_of_the_format
-static ErrorOr<void> write_VP8L_header(Stream& stream, unsigned width, unsigned height, bool alpha_is_used_hint)
-{
- // "The 14-bit precision for image width and height limits the maximum size of a WebP lossless image to 16384✕16384 pixels."
- if (width > 16384 || height > 16384)
- return Error::from_string_literal("WebP lossless images can't be larger than 16384x16384 pixels");
-
- if (width == 0 || height == 0)
- return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
-
- LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
-
- // Signature byte.
- TRY(bit_stream.write_bits(0x2fu, 8u)); // Signature byte
-
- // 14 bits width-1, 14 bits height-1, 1 bit alpha hint, 3 bit version_number.
- TRY(bit_stream.write_bits(width - 1, 14u));
- TRY(bit_stream.write_bits(height - 1, 14u));
-
- // "The alpha_is_used bit is a hint only, and should not impact decoding.
- // It should be set to 0 when all alpha values are 255 in the picture, and 1 otherwise."
- TRY(bit_stream.write_bits(alpha_is_used_hint, 1u));
-
- // "The version_number is a 3 bit code that must be set to 0."
- TRY(bit_stream.write_bits(0u, 3u));
-
- // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
- TRY(bit_stream.flush_buffer_to_stream());
-
- return {};
-}
-
-static ErrorOr<void> align_to_two(Stream& stream, size_t number_of_bytes_written)
-{
- // https://developers.google.com/speed/webp/docs/riff_container
- // "If Chunk Size is odd, a single padding byte -- which MUST be 0 to conform with RIFF -- is added."
- if (number_of_bytes_written % 2 != 0)
- TRY(stream.write_value<u8>(0));
- return {};
-}
-
-constexpr size_t vp8l_header_size = 5; // 1 byte signature + (2 * 14 bits width and height + 1 bit alpha hint + 3 bit version_number)
-
-static size_t compute_VP8L_chunk_size(ByteBuffer const& data)
-{
- constexpr size_t chunk_header_size = 8; // "VP8L" + size
- return chunk_header_size + align_up_to(vp8l_header_size + data.size(), 2);
-}
-
-static ErrorOr<void> write_VP8L_chunk(Stream& stream, unsigned width, unsigned height, bool alpha_is_used_hint, ByteBuffer const& data)
-{
- size_t const number_of_bytes_written = vp8l_header_size + data.size();
- TRY(write_chunk_header(stream, "VP8L"sv, number_of_bytes_written));
- TRY(write_VP8L_header(stream, width, height, alpha_is_used_hint));
- TRY(stream.write_until_depleted(data));
- TRY(align_to_two(stream, number_of_bytes_written));
- return {};
-}
-
-static u8 vp8x_flags_from_header(VP8XHeader const& header)
-{
- u8 flags = 0;
-
- // "Reserved (Rsv): 2 bits
- // MUST be 0. Readers MUST ignore this field."
-
- // "ICC profile (I): 1 bit
- // Set if the file contains an 'ICCP' Chunk."
- if (header.has_icc)
- flags |= 0x20;
-
- // "Alpha (L): 1 bit
- // Set if any of the frames of the image contain transparency information ("alpha")."
- if (header.has_alpha)
- flags |= 0x10;
-
- // "Exif metadata (E): 1 bit
- // Set if the file contains Exif metadata."
- if (header.has_exif)
- flags |= 0x8;
-
- // "XMP metadata (X): 1 bit
- // Set if the file contains XMP metadata."
- if (header.has_xmp)
- flags |= 0x4;
-
- // "Animation (A): 1 bit
- // Set if this is an animated image. Data in 'ANIM' and 'ANMF' Chunks should be used to control the animation."
- if (header.has_animation)
- flags |= 0x2;
-
- // "Reserved (R): 1 bit
- // MUST be 0. Readers MUST ignore this field."
-
- return flags;
-}
-
-// https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
-static ErrorOr<void> write_VP8X_chunk(Stream& stream, VP8XHeader const& header)
-{
- if (header.width > (1 << 24) || header.height > (1 << 24))
- return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
-
- if (header.width == 0 || header.height == 0)
- return Error::from_string_literal("WebP lossless images must be at least one pixel wide and tall");
-
- // "The product of Canvas Width and Canvas Height MUST be at most 2^32 - 1."
- u64 product = static_cast<u64>(header.width) * static_cast<u64>(header.height);
- if (product >= (1ull << 32))
- return Error::from_string_literal("WebP dimensions too large for VP8X chunk");
-
- TRY(write_chunk_header(stream, "VP8X"sv, 10));
-
- LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
-
- // Don't use bit_stream.write_bits() to write individual flags here:
- // The spec describes bit flags in MSB to LSB order, but write_bits() writes LSB to MSB.
- TRY(bit_stream.write_bits(vp8x_flags_from_header(header), 8u));
-
- // "Reserved: 24 bits
- // MUST be 0. Readers MUST ignore this field."
- TRY(bit_stream.write_bits(0u, 24u));
-
- // "Canvas Width Minus One: 24 bits
- // 1-based width of the canvas in pixels. The actual canvas width is 1 + Canvas Width Minus One."
- TRY(bit_stream.write_bits(header.width - 1, 24u));
-
- // "Canvas Height Minus One: 24 bits
- // 1-based height of the canvas in pixels. The actual canvas height is 1 + Canvas Height Minus One."
- TRY(bit_stream.write_bits(header.height - 1, 24u));
-
- // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
- TRY(bit_stream.flush_buffer_to_stream());
-
- return {};
-}
-
-static ErrorOr<void> align_to_two(AllocatingMemoryStream& stream)
-{
- return align_to_two(stream, stream.used_buffer_size());
-}
-
-ErrorOr<void> WebPWriter::encode(Stream& stream, Bitmap const& bitmap, Options const& options)
-{
- // 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.
- bool is_fully_opaque;
- auto vp8l_data_bytes = TRY(compress_VP8L_image_data(bitmap, options.vp8l_options, is_fully_opaque));
- bool alpha_is_used_hint = !is_fully_opaque;
- dbgln_if(WEBP_DEBUG, "Writing WebP of size {} with alpha hint: {}", bitmap.size(), alpha_is_used_hint);
-
- ByteBuffer vp8x_chunk_bytes;
- ByteBuffer iccp_chunk_bytes;
- if (options.icc_data.has_value()) {
- // FIXME: The whole writing-and-reading-into-buffer over-and-over is awkward and inefficient.
- // Maybe add an abstraction that knows its size and can write its data later. This would
- // allow saving a few copies.
- dbgln_if(WEBP_DEBUG, "Writing VP8X and ICCP chunks.");
- AllocatingMemoryStream iccp_chunk_stream;
- TRY(write_chunk_header(iccp_chunk_stream, "ICCP"sv, options.icc_data.value().size()));
- TRY(iccp_chunk_stream.write_until_depleted(options.icc_data.value()));
- TRY(align_to_two(iccp_chunk_stream));
- iccp_chunk_bytes = TRY(iccp_chunk_stream.read_until_eof());
-
- AllocatingMemoryStream vp8x_chunk_stream;
- TRY(write_VP8X_chunk(vp8x_chunk_stream, { .has_icc = true, .has_alpha = alpha_is_used_hint, .width = (u32)bitmap.width(), .height = (u32)bitmap.height() }));
- VERIFY(vp8x_chunk_stream.used_buffer_size() % 2 == 0);
- vp8x_chunk_bytes = TRY(vp8x_chunk_stream.read_until_eof());
- }
-
- u32 total_size = vp8x_chunk_bytes.size() + iccp_chunk_bytes.size() + compute_VP8L_chunk_size(vp8l_data_bytes);
- TRY(write_webp_header(stream, total_size));
- TRY(stream.write_until_depleted(vp8x_chunk_bytes));
- TRY(stream.write_until_depleted(iccp_chunk_bytes));
- TRY(write_VP8L_chunk(stream, bitmap.width(), bitmap.height(), alpha_is_used_hint, vp8l_data_bytes));
- return {};
-}
-
-}
diff --git a/Libraries/LibGfx/ImageFormats/WebPWriter.h b/Libraries/LibGfx/ImageFormats/WebPWriter.h
deleted file mode 100644
index a984f30165b..00000000000
--- a/Libraries/LibGfx/ImageFormats/WebPWriter.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2024, Nico Weber <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Error.h>
-#include <LibGfx/Forward.h>
-#include <LibGfx/ImageFormats/WebPWriterLossless.h>
-
-namespace Gfx {
-
-struct WebPEncoderOptions {
- VP8LEncoderOptions vp8l_options;
- Optional<ReadonlyBytes> icc_data;
-};
-
-class WebPWriter {
-public:
- using Options = WebPEncoderOptions;
-
- // Always lossless at the moment.
- static ErrorOr<void> encode(Stream&, Bitmap const&, Options const& = {});
-
-private:
- WebPWriter() = delete;
-};
-
-}
diff --git a/Libraries/LibGfx/ImageFormats/WebPWriterLossless.cpp b/Libraries/LibGfx/ImageFormats/WebPWriterLossless.cpp
deleted file mode 100644
index acd05c97aa7..00000000000
--- a/Libraries/LibGfx/ImageFormats/WebPWriterLossless.cpp
+++ /dev/null
@@ -1,460 +0,0 @@
-/*
- * Copyright (c) 2024, Nico Weber <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-// Lossless format: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification
-
-#include <AK/BitStream.h>
-#include <AK/ByteBuffer.h>
-#include <AK/Debug.h>
-#include <AK/HashMap.h>
-#include <AK/HashTable.h>
-#include <AK/MemoryStream.h>
-#include <AK/QuickSort.h>
-#include <LibCompress/Huffman.h>
-#include <LibGfx/Bitmap.h>
-#include <LibGfx/ImageFormats/WebPSharedLossless.h>
-#include <LibGfx/ImageFormats/WebPWriterLossless.h>
-
-namespace Gfx {
-
-namespace {
-
-struct IsOpaque {
- bool is_fully_opaque { false };
- bool is_opacity_known { false };
-
- void set_is_fully_opaque_if_not_yet_known(bool is_fully_opaque)
- {
- if (is_opacity_known)
- return;
- this->is_fully_opaque = is_fully_opaque;
- is_opacity_known = true;
- }
-};
-
-}
-
-NEVER_INLINE static ErrorOr<void> write_image_data(LittleEndianOutputBitStream& bit_stream, Bitmap const& bitmap, PrefixCodeGroup const& prefix_code_group)
-{
- // This is currently the hot loop. Keep performance in mind when you change it.
- for (RawPixel pixel : bitmap) {
- u8 a = pixel >> 24;
- u8 r = pixel >> 16;
- u8 g = pixel >> 8;
- u8 b = pixel;
-
- TRY(prefix_code_group[0].write_symbol(bit_stream, g));
- TRY(prefix_code_group[1].write_symbol(bit_stream, r));
- TRY(prefix_code_group[2].write_symbol(bit_stream, b));
- TRY(prefix_code_group[3].write_symbol(bit_stream, a));
- }
- return {};
-}
-
-struct CodeLengthSymbol {
- u8 symbol { 0 };
- u8 count { 0 }; // used for special symbols 16-18
-};
-
-// This is very similar to DeflateCompressor::encode_huffman_lengths().
-// But:
-// * size can be larger than 288 for green, is always 256 for r, b, a, and is always 40 for distance codes
-// * code 16 has different semantics, requires last_non_zero_symbol
-static size_t encode_huffman_lengths(ReadonlyBytes lengths, Array<CodeLengthSymbol, 256>& encoded_lengths)
-{
- size_t encoded_count = 0;
- size_t i = 0;
- u8 last_non_zero_symbol = 8; // "If code 16 is used before a non-zero value has been emitted, a value of 8 is repeated."
- while (i < lengths.size()) {
- if (lengths[i] == 0) {
- auto zero_count = 0;
- for (size_t j = i; j < min(lengths.size(), i + 138) && lengths[j] == 0; j++)
- zero_count++;
-
- if (zero_count < 3) { // below minimum repeated zero count
- encoded_lengths[encoded_count++].symbol = 0;
- i++;
- continue;
- }
-
- if (zero_count <= 10) {
- // "Code 17 emits a streak of zeros [3..10], i.e., 3 + ReadBits(3) times."
- encoded_lengths[encoded_count].symbol = 17;
- encoded_lengths[encoded_count++].count = zero_count;
- } else {
- // "Code 18 emits a streak of zeros of length [11..138], i.e., 11 + ReadBits(7) times."
- encoded_lengths[encoded_count].symbol = 18;
- encoded_lengths[encoded_count++].count = zero_count;
- }
- i += zero_count;
- continue;
- }
-
- VERIFY(lengths[i] != 0);
- last_non_zero_symbol = lengths[i];
- encoded_lengths[encoded_count++].symbol = lengths[i++];
-
- // "Code 16 repeats the previous non-zero value [3..6] times, i.e., 3 + ReadBits(2) times."
- // This is different from deflate.
- auto copy_count = 0;
- for (size_t j = i; j < min(lengths.size(), i + 6) && lengths[j] == last_non_zero_symbol; j++)
- copy_count++;
-
- if (copy_count >= 3) {
- encoded_lengths[encoded_count].symbol = 16;
- encoded_lengths[encoded_count++].count = copy_count;
- i += copy_count;
- continue;
- }
- }
- return encoded_count;
-}
-
-static ErrorOr<CanonicalCode> write_simple_code_lengths(LittleEndianOutputBitStream& bit_stream, ReadonlyBytes symbols)
-{
- VERIFY(symbols.size() <= 2);
-
- static constexpr Array<u8, 1> empty { 0 };
- if (symbols.size() == 0) {
- // "Another special case is when all prefix code lengths are zeros (an empty prefix code). [...]
- // empty prefix codes can be coded as those containing a single symbol 0."
- symbols = empty;
- }
-
- unsigned non_zero_symbol_count = symbols.size();
-
- TRY(bit_stream.write_bits(1u, 1u)); // Simple code length code.
- TRY(bit_stream.write_bits(non_zero_symbol_count - 1, 1u)); // num_symbols - 1
- if (symbols[0] <= 1) {
- TRY(bit_stream.write_bits(0u, 1u)); // is_first_8bits: no
- TRY(bit_stream.write_bits(symbols[0], 1u)); // symbol0
- } else {
- TRY(bit_stream.write_bits(1u, 1u)); // is_first_8bits: yes
- TRY(bit_stream.write_bits(symbols[0], 8u)); // symbol0
- }
- if (non_zero_symbol_count > 1)
- TRY(bit_stream.write_bits(symbols[1], 8u)); // symbol1
-
- Array<u8, 256> bits_per_symbol {};
- // "When coding a single leaf node [...], all but one code length are zeros, and the single leaf node value
- // is marked with the length of 1 -- even when no bits are consumed when that single leaf node tree is used."
- // CanonicalCode follows that convention too, even when describing simple code lengths.
- bits_per_symbol[symbols[0]] = 1;
- if (non_zero_symbol_count > 1)
- bits_per_symbol[symbols[1]] = 1;
-
- return MUST(CanonicalCode::from_bytes(bits_per_symbol));
-}
-
-static ErrorOr<CanonicalCode> write_normal_code_lengths(LittleEndianOutputBitStream& bit_stream, Array<u8, 256> const& bit_lengths, size_t alphabet_size)
-{
- // bit_lengths stores how many bits each symbol is encoded with.
-
- // Drop trailing zero lengths.
- // This will keep at least three symbols; else we would've called write_simple_code_lengths() instead.
- // This is similar to the loops in Deflate::encode_block_lengths().
- size_t code_count = bit_lengths.size();
- while (bit_lengths[code_count - 1] == 0) {
- code_count--;
- VERIFY(code_count > 2);
- }
-
- Array<CodeLengthSymbol, 256> encoded_lengths {};
- auto encoded_lengths_count = encode_huffman_lengths(bit_lengths.span().trim(code_count), encoded_lengths);
-
- // The code to compute code length code lengths is very similar to some of the code in DeflateCompressor::flush().
- // count code length frequencies
- Array<u16, 19> code_lengths_frequencies { 0 };
- for (size_t i = 0; i < encoded_lengths_count; i++) {
- VERIFY(code_lengths_frequencies[encoded_lengths[i].symbol] < UINT16_MAX);
- code_lengths_frequencies[encoded_lengths[i].symbol]++;
- }
-
- // generate optimal huffman code lengths code lengths
- Array<u8, 19> code_lengths_bit_lengths {};
- Compress::generate_huffman_lengths(code_lengths_bit_lengths, code_lengths_frequencies, 7); // deflate code length huffman can use up to 7 bits per symbol
- // calculate actual code length code lengths count (without trailing zeros)
- auto code_lengths_count = code_lengths_bit_lengths.size();
- while (code_lengths_bit_lengths[kCodeLengthCodeOrder[code_lengths_count - 1]] == 0)
- code_lengths_count--;
-
- TRY(bit_stream.write_bits(0u, 1u)); // Normal code length code.
-
- // This here isn't needed in Deflate because it always writes EndOfBlock. WebP does not have an EndOfBlock marker, so it needs this check.
- if (code_lengths_count < 4)
- code_lengths_count = 4;
- dbgln_if(WEBP_DEBUG, "writing code_lengths_count: {}", code_lengths_count);
-
- // WebP uses a different kCodeLengthCodeOrder than deflate. Other than that, the following is similar to a loop in Compress::write_dynamic_huffman().
- // "int num_code_lengths = 4 + ReadBits(4);"
- TRY(bit_stream.write_bits(code_lengths_count - 4u, 4u));
-
- for (size_t i = 0; i < code_lengths_count; i++) {
- TRY(bit_stream.write_bits(code_lengths_bit_lengths[kCodeLengthCodeOrder[i]], 3));
- }
-
- // Write code lengths. This is slightly different from deflate too -- deflate writes literal and distance lengths here,
- // while WebP writes one of these codes each for g, r, b, a, and distance.
- if (alphabet_size == encoded_lengths_count) {
- TRY(bit_stream.write_bits(0u, 1u)); // max_symbol is alphabet_size
- } else {
- dbgln_if(WEBP_DEBUG, "writing max_symbol: {}", encoded_lengths_count);
- TRY(bit_stream.write_bits(1u, 1u)); // max_symbol is explicitly coded
- // "int length_nbits = 2 + 2 * ReadBits(3);
- // int max_symbol = 2 + ReadBits(length_nbits);"
- // => length_nbits is at most 2 + 2*7 == 16
- unsigned needed_length_nbits = encoded_lengths_count > 2 ? floor(log2(encoded_lengths_count - 2) + 1) : 2;
- VERIFY(needed_length_nbits <= 16);
- needed_length_nbits = ceil_div(needed_length_nbits, 2) * 2;
- TRY(bit_stream.write_bits((needed_length_nbits - 2) / 2, 3u));
- TRY(bit_stream.write_bits(encoded_lengths_count - 2, needed_length_nbits));
- }
-
- // The rest is identical to write_dynamic_huffman() again. (Code 16 has different semantics, but that doesn't matter here.)
- auto code_lengths_code = MUST(CanonicalCode::from_bytes(code_lengths_bit_lengths));
- for (size_t i = 0; i < encoded_lengths_count; i++) {
- auto encoded_length = encoded_lengths[i];
- TRY(code_lengths_code.write_symbol(bit_stream, encoded_length.symbol));
- if (encoded_length.symbol == 16) {
- // "Code 16 repeats the previous non-zero value [3..6] times, i.e., 3 + ReadBits(2) times."
- TRY(bit_stream.write_bits<u8>(encoded_length.count - 3, 2));
- } else if (encoded_length.symbol == 17) {
- // "Code 17 emits a streak of zeros [3..10], i.e., 3 + ReadBits(3) times."
- TRY(bit_stream.write_bits<u8>(encoded_length.count - 3, 3));
- } else if (encoded_length.symbol == 18) {
- // "Code 18 emits a streak of zeros of length [11..138], i.e., 11 + ReadBits(7) times."
- TRY(bit_stream.write_bits<u8>(encoded_length.count - 11, 7));
- }
- }
-
- return CanonicalCode::from_bytes(bit_lengths.span().trim(code_count));
-}
-
-static ErrorOr<void> write_VP8L_coded_image(ImageKind image_kind, LittleEndianOutputBitStream& bit_stream, Bitmap const& bitmap, IsOpaque& is_fully_opaque)
-{
- // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#5_image_data
- // spatially-coded-image = color-cache-info meta-prefix data
- // entropy-coded-image = color-cache-info data
-
- // color-cache-info = %b0
- // color-cache-info =/ (%b1 4BIT) ; 1 followed by color cache size
- TRY(bit_stream.write_bits(0u, 1u)); // No color cache for now.
-
- if (image_kind == ImageKind::SpatiallyCoded) {
- // meta-prefix = %b0 / (%b1 entropy-image)
- TRY(bit_stream.write_bits(0u, 1u)); // No meta prefix for now.
- }
-
- // data = prefix-codes lz77-coded-image
- // prefix-codes = prefix-code-group *prefix-codes
- // prefix-code-group =
- // 5prefix-code ; See "Interpretation of Meta Prefix Codes" to
- // ; understand what each of these five prefix
- // ; codes are for.
-
- // We're writing a single prefix-code-group.
- // "These codes are (in bitstream order):
-
- // Prefix code #1: Used for green channel, backward-reference length, and color cache.
- // Prefix code #2, #3, and #4: Used for red, blue, and alpha channels, respectively.
- // Prefix code #5: Used for backward-reference distance."
-
- // We use neither back-references not color cache entries yet.
- // We can make this smarter later on.
-
- size_t const color_cache_size = 0;
- constexpr Array alphabet_sizes = to_array<size_t>({ 256 + 24 + static_cast<size_t>(color_cache_size), 256, 256, 256, 40 });
-
- // If you add support for color cache: At the moment, CanonicalCodes does not support writing more than 288 symbols.
- if (alphabet_sizes[0] > 288)
- return Error::from_string_literal("Invalid alphabet size");
-
- // We do use huffman coding by writing a single prefix-code-group for the entire image.
- // FIXME: Consider using a meta-prefix image and using one prefix-code-group per tile.
-
- Array<Array<u16, 256>, 4> symbol_frequencies {};
- for (RawPixel pixel : bitmap) {
- static constexpr auto saturating_increment = [](u16& value) {
- if (value < UINT16_MAX)
- value++;
- };
- saturating_increment(symbol_frequencies[0][(pixel >> 8) & 0xff]); // green
- saturating_increment(symbol_frequencies[1][(pixel >> 16) & 0xff]); // red
- saturating_increment(symbol_frequencies[2][pixel & 0xff]); // blue
- saturating_increment(symbol_frequencies[3][pixel >> 24]); // alpha
- }
-
- Array<Array<u8, 256>, 4> code_lengths {};
- for (int i = 0; i < 4; ++i) {
- // "Code [0..15] indicates literal code lengths." => the maximum bit length is 15.
- Compress::generate_huffman_lengths(code_lengths[i], symbol_frequencies[i], 15);
- }
-
- PrefixCodeGroup prefix_code_group;
- for (int i = 0; i < 4; ++i) {
- u8 symbols[2];
- unsigned non_zero_symbol_count = 0;
- for (int j = 0; j < 256; ++j) {
- if (code_lengths[i][j] != 0) {
- if (non_zero_symbol_count < 2)
- symbols[non_zero_symbol_count] = j;
- non_zero_symbol_count++;
- }
- }
-
- if (non_zero_symbol_count <= 2)
- prefix_code_group[i] = TRY(write_simple_code_lengths(bit_stream, { symbols, non_zero_symbol_count }));
- else
- prefix_code_group[i] = TRY(write_normal_code_lengths(bit_stream, code_lengths[i], alphabet_sizes[i]));
-
- if (i == 3)
- is_fully_opaque.set_is_fully_opaque_if_not_yet_known(non_zero_symbol_count == 1 && symbols[0] == 0xff);
- }
-
- // For code #5, use a simple empty code, since we don't use this yet.
- prefix_code_group[4] = TRY(write_simple_code_lengths(bit_stream, {}));
-
- // Image data.
- TRY(write_image_data(bit_stream, bitmap, prefix_code_group));
-
- return {};
-}
-
-static RawPixel sub_pixel(RawPixel a, RawPixel b)
-{
- auto a_color = Color::from_bgra(a);
- auto b_color = Color::from_bgra(b);
- return Color(a_color.red() - b_color.red(),
- a_color.green() - b_color.green(),
- a_color.blue() - b_color.blue(),
- a_color.alpha() - b_color.alpha())
- .value();
-}
-
-static ErrorOr<NonnullRefPtr<Bitmap const>> maybe_write_color_indexing_transform(LittleEndianOutputBitStream& bit_stream, NonnullRefPtr<Bitmap const> bitmap, IsOpaque& is_fully_opaque)
-{
- // https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#44_color_indexing_transform
- unsigned color_table_size = 0;
- HashTable<RawPixel> seen_colors;
- RawPixel channels = 0;
- RawPixel first_pixel = bitmap->get_pixel(0, 0).value();
- for (RawPixel pixel : *bitmap) {
- auto result = seen_colors.set(pixel);
- if (result == HashSetResult::InsertedNewEntry) {
- ++color_table_size;
- channels |= pixel ^ first_pixel;
- if (color_table_size > 256)
- break;
- }
- }
- dbgln_if(WEBP_DEBUG, "WebP: Image has {}{} colors; all pixels or'd is {:#08x}", color_table_size > 256 ? ">= " : "", color_table_size, channels);
-
- // If the image has a single color, the huffman table can encode it in 0 bits and color indexing does not help.
- if (color_table_size <= 1 || color_table_size > 256)
- return bitmap;
-
- // If all colors use just a single channel, color indexing does not help either,
- // except if there are <= 16 colors and we can do pixel bundling.
- // FIXME: Once we support color cache, maybe that helps for single-channel pixels with fewer than 16 colors
- // and we don't need to write a color index then?
- if (color_table_size > 16) {
- int number_of_non_constant_channels = 0;
- for (int i = 0; i < 4; ++i) {
- if (channels & (0xff << (i * 8)))
- number_of_non_constant_channels++;
- }
- if (number_of_non_constant_channels <= 1)
- return bitmap;
- }
-
- dbgln_if(WEBP_DEBUG, "WebP: Writing color index transform");
- TRY(bit_stream.write_bits(1u, 1u)); // Transform present.
- TRY(bit_stream.write_bits(static_cast<unsigned>(COLOR_INDEXING_TRANSFORM), 2u));
-
- // "int color_table_size = ReadBits(8) + 1;"
- TRY(bit_stream.write_bits(color_table_size - 1, 8u));
-
- // Store color index to bit stream.
- Vector<RawPixel, 256> colors;
- for (RawPixel color : seen_colors)
- colors.append(color);
- quick_sort(colors.begin(), colors.end());
-
- // "The color table is stored using the image storage format itself." [...]
- // "The color table is always subtraction-coded to reduce image entropy."
- auto color_index_bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, { static_cast<int>(color_table_size), 1 }));
- color_index_bitmap->set_pixel(0, 0, Color::from_bgra(colors[0]));
- for (unsigned i = 1; i < color_table_size; ++i)
- color_index_bitmap->set_pixel(i, 0, Color::from_bgra(sub_pixel(colors[i], colors[i - 1])));
- TRY(write_VP8L_coded_image(ImageKind::EntropyCoded, bit_stream, *color_index_bitmap, is_fully_opaque));
-
- // Return a new bitmap with the color indexing transform applied.
- HashMap<RawPixel, u8> color_index_map;
- for (unsigned i = 0; i < color_table_size; ++i)
- color_index_map.set(colors[i], i);
-
- // "When the color table is small (equal to or less than 16 colors), several pixels are bundled into a single pixel.
- // The pixel bundling packs several (2, 4, or 8) pixels into a single pixel, reducing the image width respectively."
- int width_bits;
- if (color_table_size <= 2)
- width_bits = 3;
- else if (color_table_size <= 4)
- width_bits = 2;
- else if (color_table_size <= 16)
- width_bits = 1;
- else
- width_bits = 0;
- int pixels_per_pixel = 1 << width_bits;
- int image_width = ceil_div(bitmap->width(), pixels_per_pixel);
- auto new_bitmap = TRY(Bitmap::create(BitmapFormat::BGRx8888, { image_width, bitmap->height() }));
-
- unsigned bits_per_pixel = 8 / pixels_per_pixel;
- for (int y = 0; y < bitmap->height(); ++y) {
- for (int x = 0, new_x = 0; x < bitmap->width(); x += pixels_per_pixel, ++new_x) {
- u8 indexes = 0;
- for (int i = 0; i < pixels_per_pixel && x + i < bitmap->width(); ++i) {
- auto pixel = bitmap->get_pixel(x + i, y);
- auto result = color_index_map.get(pixel.value());
- VERIFY(result.has_value());
- indexes |= result.value() << (i * bits_per_pixel);
- }
- new_bitmap->set_pixel(new_x, y, Color(0, indexes, 0, 0));
- }
- }
-
- return new_bitmap;
-}
-
-static ErrorOr<void> write_VP8L_image_data(Stream& stream, NonnullRefPtr<Bitmap const> bitmap, VP8LEncoderOptions const& options, IsOpaque& is_fully_opaque)
-{
- LittleEndianOutputBitStream bit_stream { MaybeOwned<Stream>(stream) };
-
- // image-stream = optional-transform spatially-coded-image
- // optional-transform = (%b1 transform optional-transform) / %b0
- if (options.allowed_transforms & (1u << COLOR_INDEXING_TRANSFORM))
- bitmap = TRY(maybe_write_color_indexing_transform(bit_stream, bitmap, is_fully_opaque));
- TRY(bit_stream.write_bits(0u, 1u)); // No further transforms for now.
-
- TRY(write_VP8L_coded_image(ImageKind::SpatiallyCoded, bit_stream, *bitmap, is_fully_opaque));
-
- // FIXME: Make ~LittleEndianOutputBitStream do this, or make it VERIFY() that it has happened at least.
- TRY(bit_stream.align_to_byte_boundary());
- TRY(bit_stream.flush_buffer_to_stream());
-
- return {};
-}
-
-ErrorOr<ByteBuffer> compress_VP8L_image_data(Bitmap const& bitmap, VP8LEncoderOptions const& options, bool& is_fully_opaque)
-{
- AllocatingMemoryStream vp8l_data_stream;
- IsOpaque is_opaque_struct;
- TRY(write_VP8L_image_data(vp8l_data_stream, bitmap, options, is_opaque_struct));
- VERIFY(is_opaque_struct.is_opacity_known);
- is_fully_opaque = is_opaque_struct.is_fully_opaque;
- return vp8l_data_stream.read_until_eof();
-}
-
-}
diff --git a/Libraries/LibGfx/ImageFormats/WebPWriterLossless.h b/Libraries/LibGfx/ImageFormats/WebPWriterLossless.h
deleted file mode 100644
index 035765696bc..00000000000
--- a/Libraries/LibGfx/ImageFormats/WebPWriterLossless.h
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (c) 2024, Nico Weber <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Error.h>
-#include <LibGfx/Forward.h>
-
-namespace Gfx {
-
-struct VP8LEncoderOptions {
- // For each TransformType, set bit `1 << transform_type` if that transform type is allowed.
- unsigned allowed_transforms { 0xf };
-};
-
-ErrorOr<ByteBuffer> compress_VP8L_image_data(Bitmap const&, VP8LEncoderOptions const&, bool& is_fully_opaque);
-
-}
diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmake
index 0daa5c4c6a3..e0c88d8dd0d 100644
--- a/Meta/CMake/all_the_debug_macros.cmake
+++ b/Meta/CMake/all_the_debug_macros.cmake
@@ -66,7 +66,6 @@ set(VIDEO_PRESENTATION_CHANNEL_DEBUG ON)
set(WEBVIEW_PROCESS_DEBUG ON)
set(WEB_FETCH_DEBUG ON)
set(WEB_WORKER_DEBUG ON)
-set(WEBP_DEBUG ON)
set(XML_PARSER_DEBUG ON)
# False positive: ANDROID_LOG_DEBUG is a log level, not a debug flag
diff --git a/Tests/LibGfx/TestImageWriter.cpp b/Tests/LibGfx/TestImageWriter.cpp
index e6150502626..1ef5b82db5d 100644
--- a/Tests/LibGfx/TestImageWriter.cpp
+++ b/Tests/LibGfx/TestImageWriter.cpp
@@ -11,8 +11,6 @@
#include <LibGfx/ImageFormats/JPEGWriter.h>
#include <LibGfx/ImageFormats/PNGLoader.h>
#include <LibGfx/ImageFormats/PNGWriter.h>
-#include <LibGfx/ImageFormats/WebPLoader.h>
-#include <LibGfx/ImageFormats/WebPWriter.h>
#include <LibTest/TestCase.h>
static ErrorOr<NonnullRefPtr<Gfx::Bitmap>> expect_single_frame(Gfx::ImageDecoderPlugin& plugin_decoder)
@@ -159,72 +157,3 @@ TEST_CASE(test_png)
TRY_OR_FAIL((test_roundtrip<Gfx::PNGWriter, Gfx::PNGImageDecoderPlugin>(TRY_OR_FAIL(create_test_rgb_bitmap()))));
TRY_OR_FAIL((test_roundtrip<Gfx::PNGWriter, Gfx::PNGImageDecoderPlugin>(TRY_OR_FAIL(create_test_rgba_bitmap()))));
}
-
-TEST_CASE(test_webp)
-{
- TRY_OR_FAIL((test_roundtrip<Gfx::WebPWriter, Gfx::WebPImageDecoderPlugin>(TRY_OR_FAIL(create_test_rgb_bitmap()))));
- TRY_OR_FAIL((test_roundtrip<Gfx::WebPWriter, Gfx::WebPImageDecoderPlugin>(TRY_OR_FAIL(create_test_rgba_bitmap()))));
-}
-
-TEST_CASE(test_webp_color_indexing_transform)
-{
- Array<Color, 256> colors;
- for (size_t i = 0; i < colors.size(); ++i) {
- colors[i].set_red(i);
- colors[i].set_green(255 - i);
- colors[i].set_blue(128);
- colors[i].set_alpha(255 - i / 16);
- }
- for (int bits_per_pixel : { 1, 2, 4, 8 }) {
- int number_of_colors = 1 << bits_per_pixel;
-
- auto bitmap = TRY_OR_FAIL(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 47, 33 }));
- for (int y = 0; y < bitmap->height(); ++y)
- for (int x = 0; x < bitmap->width(); ++x)
- bitmap->set_pixel(x, y, colors[(x * bitmap->width() + y) % number_of_colors]);
-
- auto encoded_data = TRY_OR_FAIL(encode_bitmap<Gfx::WebPWriter>(bitmap));
- auto decoded_bitmap = TRY_OR_FAIL(expect_single_frame_of_size(*TRY_OR_FAIL(Gfx::WebPImageDecoderPlugin::create(encoded_data)), bitmap->size()));
- expect_bitmaps_equal(*decoded_bitmap, *bitmap);
-
- Gfx::WebPEncoderOptions options;
- options.vp8l_options.allowed_transforms = 0;
- auto encoded_data_without_color_indexing = TRY_OR_FAIL(encode_bitmap<Gfx::WebPWriter>(bitmap, options));
- EXPECT(encoded_data.size() < encoded_data_without_color_indexing.size());
- auto decoded_bitmap_without_color_indexing = TRY_OR_FAIL(expect_single_frame_of_size(*TRY_OR_FAIL(Gfx::WebPImageDecoderPlugin::create(encoded_data)), bitmap->size()));
- expect_bitmaps_equal(*decoded_bitmap_without_color_indexing, *decoded_bitmap);
- }
-}
-
-TEST_CASE(test_webp_color_indexing_transform_single_channel)
-{
- Array<Color, 256> colors;
- for (size_t i = 0; i < colors.size(); ++i) {
- colors[i].set_red(0);
- colors[i].set_green(255 - i);
- colors[i].set_blue(128);
- colors[i].set_alpha(255);
- }
- for (int bits_per_pixel : { 1, 2, 4, 8 }) {
- int number_of_colors = 1 << bits_per_pixel;
-
- auto bitmap = TRY_OR_FAIL(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 47, 33 }));
- for (int y = 0; y < bitmap->height(); ++y)
- for (int x = 0; x < bitmap->width(); ++x)
- bitmap->set_pixel(x, y, colors[(x * bitmap->width() + y) % number_of_colors]);
-
- auto encoded_data = TRY_OR_FAIL(encode_bitmap<Gfx::WebPWriter>(bitmap));
- auto decoded_bitmap = TRY_OR_FAIL(expect_single_frame_of_size(*TRY_OR_FAIL(Gfx::WebPImageDecoderPlugin::create(encoded_data)), bitmap->size()));
- expect_bitmaps_equal(*decoded_bitmap, *bitmap);
-
- Gfx::WebPEncoderOptions options;
- options.vp8l_options.allowed_transforms = 0;
- auto encoded_data_without_color_indexing = TRY_OR_FAIL(encode_bitmap<Gfx::WebPWriter>(bitmap, options));
- if (bits_per_pixel == 8)
- EXPECT(encoded_data.size() <= encoded_data_without_color_indexing.size());
- else
- EXPECT(encoded_data.size() < encoded_data_without_color_indexing.size());
- auto decoded_bitmap_without_color_indexing = TRY_OR_FAIL(expect_single_frame_of_size(*TRY_OR_FAIL(Gfx::WebPImageDecoderPlugin::create(encoded_data)), bitmap->size()));
- expect_bitmaps_equal(*decoded_bitmap_without_color_indexing, *decoded_bitmap);
- }
-}