ladybird/Userland/Libraries/LibGfx/ImageFormats/WebPSharedLossless.h
Nico Weber 7aa61ca49b LibGfx/WebP: Add CanonicalCode::write_symbol(), use it in writer
We still construct the code length codes manually, and now we also
construct a PrefixCodeGroup manually that assigns 8 bits to all
symbols (except for fully-opaque alpha channels, and for the
unused distance codes, like before). But now we use the CanonicalCodes
from that PrefixCodeGroup for writing.

No behavior change at all, the output is bit-for-bit identical to
before. But this is a step towards actually huffman-coding symbols.

This is however a pretty big perf regression. For
`image -o test.webp test.bmp` (where test.bmp is retro-sunset.png
re-encoded as bmp), time goes from 23.7 ms to 33.2 ms.

`animation -o wow.webp giphy.gif` goes from 85.5 ms to 127.7 ms.

`animation -o wow.webp 7z7c.gif` goes from 12.6 ms to 16.5 ms.
2024-05-20 13:17:34 -04:00

57 lines
1.6 KiB
C++

/*
* Copyright (c) 2024, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <LibCompress/Deflate.h>
namespace Gfx {
// 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()
: m_code(0)
{
}
static ErrorOr<CanonicalCode> from_bytes(ReadonlyBytes);
ErrorOr<u32> read_symbol(LittleEndianInputBitStream&) const;
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;
};
// 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;
};
}