LibGfx: Decode WebP images with libwebp

This commit is contained in:
doctortheemh 2024-07-12 01:08:39 -07:00 committed by Andrew Kaster
parent 83d0452e69
commit 0140e5e9cc
Notes: sideshowbarker 2024-07-18 16:49:41 +09:00
10 changed files with 168 additions and 3663 deletions

View file

@ -649,8 +649,8 @@ TEST_CASE(test_webp_simple_lossy)
// While VP8 YUV contents are defined bit-exact, the YUV->RGB conversion isn't.
// So pixels changing by 1 or so below is fine if you change code.
EXPECT_EQ(frame.image->get_pixel(120, 232), Gfx::Color(0xf2, 0xef, 0xf0, 255));
EXPECT_EQ(frame.image->get_pixel(198, 202), Gfx::Color(0x7b, 0xaa, 0xd5, 255));
EXPECT_EQ(frame.image->get_pixel(120, 232), Gfx::Color(0xf1, 0xef, 0xf0, 255));
EXPECT_EQ(frame.image->get_pixel(198, 202), Gfx::Color(0x7a, 0xaa, 0xd5, 255));
}
TEST_CASE(test_webp_simple_lossless)
@ -723,7 +723,7 @@ TEST_CASE(test_webp_extended_lossy_alpha_horizontal_filter)
// While VP8 YUV contents are defined bit-exact, the YUV->RGB conversion isn't.
// So pixels changing by 1 or so below is fine if you change code.
// The important component in this test is alpha, and that shouldn't change even by 1 as it's losslessly compressed and doesn't use YUV.
EXPECT_EQ(frame.image->get_pixel(131, 131), Gfx::Color(0x8f, 0x51, 0x2f, 0x4b));
EXPECT_EQ(frame.image->get_pixel(131, 131), Gfx::Color(0x8f, 0x50, 0x33, 0x4b));
}
TEST_CASE(test_webp_extended_lossy_alpha_vertical_filter)
@ -739,7 +739,7 @@ TEST_CASE(test_webp_extended_lossy_alpha_vertical_filter)
// While VP8 YUV contents are defined bit-exact, the YUV->RGB conversion isn't.
// So pixels changing by 1 or so below is fine if you change code.
// The important component in this test is alpha, and that shouldn't change even by 1 as it's losslessly compressed and doesn't use YUV.
EXPECT_EQ(frame.image->get_pixel(131, 131), Gfx::Color(0x94, 0x50, 0x32, 0x4c));
EXPECT_EQ(frame.image->get_pixel(131, 131), Gfx::Color(0x92, 0x50, 0x32, 0x4c));
}
TEST_CASE(test_webp_extended_lossy_alpha_gradient_filter)
@ -756,7 +756,7 @@ TEST_CASE(test_webp_extended_lossy_alpha_gradient_filter)
// So pixels changing by 1 or so below is fine if you change code.
// The important component in this test is alpha, and that shouldn't change even by 1 as it's losslessly compressed and doesn't use YUV.
// In particular, the center of the image should be fully opaque, not fully transparent.
EXPECT_EQ(frame.image->get_pixel(131, 131), Gfx::Color(0x8c, 0x47, 0x2e, 255));
EXPECT_EQ(frame.image->get_pixel(131, 131), Gfx::Color(0x8a, 0x48, 0x2e, 255));
}
TEST_CASE(test_webp_extended_lossy_uncompressed_alpha)
@ -769,8 +769,8 @@ TEST_CASE(test_webp_extended_lossy_uncompressed_alpha)
// While VP8 YUV contents are defined bit-exact, the YUV->RGB conversion isn't.
// So pixels changing by 1 or so below is fine if you change code.
EXPECT_EQ(frame.image->get_pixel(89, 72), Gfx::Color(255, 0, 4, 255));
EXPECT_EQ(frame.image->get_pixel(174, 69), Gfx::Color(4, 255, 0, 255));
EXPECT_EQ(frame.image->get_pixel(89, 72), Gfx::Color(254, 0, 6, 255));
EXPECT_EQ(frame.image->get_pixel(174, 69), Gfx::Color(0, 255, 0, 255));
EXPECT_EQ(frame.image->get_pixel(245, 84), Gfx::Color(0, 0, 255, 255));
EXPECT_EQ(frame.image->get_pixel(352, 125), Gfx::Color(0, 0, 0, 128));
EXPECT_EQ(frame.image->get_pixel(355, 106), Gfx::Color(0, 0, 0, 0));
@ -786,7 +786,7 @@ TEST_CASE(test_webp_extended_lossy_negative_quantization_offset)
// While VP8 YUV contents are defined bit-exact, the YUV->RGB conversion isn't.
// So pixels changing by 1 or so below is fine if you change code.
EXPECT_EQ(frame.image->get_pixel(16, 16), Gfx::Color(0x3c, 0x24, 0x1a, 255));
EXPECT_EQ(frame.image->get_pixel(16, 16), Gfx::Color(0x3b, 0x25, 0x18, 255));
}
TEST_CASE(test_webp_lossy_4)
@ -813,7 +813,7 @@ TEST_CASE(test_webp_lossy_4_with_partitions)
auto plugin_decoder = TRY_OR_FAIL(Gfx::WebPImageDecoderPlugin::create(file->bytes()));
auto frame = TRY_OR_FAIL(expect_single_frame_of_size(*plugin_decoder, { 1024, 772 }));
EXPECT_EQ(frame.image->get_pixel(780, 570), Gfx::Color(0x73, 0xc9, 0xf9, 255));
EXPECT_EQ(frame.image->get_pixel(780, 570), Gfx::Color(0x72, 0xc7, 0xf8, 255));
}
TEST_CASE(test_webp_extended_lossless)

View file

@ -47,8 +47,6 @@ set(SOURCES
ImageFormats/TIFFLoader.cpp
ImageFormats/TinyVGLoader.cpp
ImageFormats/WebPLoader.cpp
ImageFormats/WebPLoaderLossless.cpp
ImageFormats/WebPLoaderLossy.cpp
ImageFormats/WebPSharedLossless.cpp
ImageFormats/WebPWriter.cpp
ImageFormats/WebPWriterLossless.cpp
@ -98,5 +96,7 @@ pkg_check_modules(WOFF2 REQUIRED IMPORTED_TARGET libwoff2dec)
find_package(JPEG REQUIRED)
find_package(PNG REQUIRED)
find_package(LIBAVIF REQUIRED)
find_package(WebP REQUIRED)
target_link_libraries(LibGfx PRIVATE PkgConfig::WOFF2 JPEG::JPEG PNG::PNG avif)
target_link_libraries(LibGfx PRIVATE PkgConfig::WOFF2 JPEG::JPEG PNG::PNG avif WebP::webp WebP::webpdecoder
WebP::webpdemux WebP::libwebpmux)

View file

@ -1,595 +1,41 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
* Copyright (c) 2024, doctortheemh <doctortheemh@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Debug.h>
#include <AK/Endian.h>
#include <AK/Format.h>
#include <AK/MemoryStream.h>
#include <AK/Vector.h>
#include <LibGfx/FourCC.h>
#include <AK/Error.h>
#include <LibGfx/ImageFormats/WebPLoader.h>
#include <LibGfx/ImageFormats/WebPLoaderLossless.h>
#include <LibGfx/ImageFormats/WebPLoaderLossy.h>
#include <LibGfx/ImageFormats/WebPShared.h>
#include <LibGfx/Painter.h>
#include <LibRIFF/ChunkID.h>
#include <LibRIFF/RIFF.h>
// Overview: https://developers.google.com/speed/webp/docs/compression
// Container: https://developers.google.com/speed/webp/docs/riff_container
#include <webp/decode.h>
#include <webp/demux.h>
#include <webp/mux.h>
namespace Gfx {
namespace {
// "For a still image, the image data consists of a single frame, which is made up of:
// An optional alpha subchunk.
// A bitstream subchunk."
struct ImageData {
// "This optional chunk contains encoded alpha data for this frame. A frame containing a 'VP8L' chunk SHOULD NOT contain this chunk."
Optional<RIFF::Chunk> alpha_chunk; // 'ALPH'
RIFF::Chunk image_data_chunk; // Either 'VP8 ' or 'VP8L'. For 'VP8L', alpha_chunk will not have a value.
};
}
struct WebPLoadingContext {
enum State {
NotDecoded = 0,
Error,
HeaderDecoded,
FirstChunkRead,
FirstChunkDecoded,
ChunksDecoded,
AnimationFrameChunksDecoded,
BitmapDecoded,
};
State state { State::NotDecoded };
ReadonlyBytes data;
ReadonlyBytes chunks_cursor;
// Image properties
IntSize size;
bool has_alpha;
bool has_animation;
size_t frame_count;
size_t loop_count;
ByteBuffer icc_data;
Optional<IntSize> size;
RefPtr<Gfx::Bitmap> bitmap;
// Either 'VP8 ' (simple lossy file), 'VP8L' (simple lossless file), or 'VP8X' (extended file).
Optional<RIFF::Chunk> first_chunk;
// Only valid if first_chunk->type == 'VP8X'.
VP8XHeader vp8x_header;
// If first_chunk is not a VP8X chunk, then only image_data.image_data_chunk is set and all the other Chunks are not set.
// Once state is >= ChunksDecoded, for non-animated images, this will have a value, or decoding will have failed.
Optional<ImageData> image_data;
Optional<RIFF::Chunk> animation_header_chunk; // 'ANIM'
Vector<RIFF::Chunk> animation_frame_chunks; // 'ANMF'
// These are set in state >= AnimationFrameChunksDecoded, if first_chunk.type == 'VP8X' && vp8x_header.has_animation.
Optional<ANIMChunk> animation_header_chunk_data;
Optional<Vector<ANMFChunk>> animation_frame_chunks_data;
size_t current_frame { 0 };
Optional<RIFF::Chunk> iccp_chunk; // 'ICCP'
Optional<RIFF::Chunk> exif_chunk; // 'EXIF'
Optional<RIFF::Chunk> xmp_chunk; // 'XMP '
Vector<ImageFrameDescriptor> frame_descriptors;
};
// https://developers.google.com/speed/webp/docs/riff_container#webp_file_header
static ErrorOr<void> decode_webp_header(WebPLoadingContext& context)
{
if (context.state >= WebPLoadingContext::HeaderDecoded)
return {};
FixedMemoryStream header_stream { context.data };
auto header = TRY(header_stream.read_value<RIFF::FileHeader>());
if (header.magic() != RIFF::riff_magic || header.subformat != "WEBP"sv)
return Error::from_string_literal("Invalid WebP header");
// "File Size: [...] The size of the file in bytes starting at offset 8. The maximum value of this field is 2^32 minus 10 bytes."
u32 const maximum_webp_file_size = 0xffff'ffff - 9;
if (header.file_size() > maximum_webp_file_size)
return Error::from_string_literal("WebP header file size over maximum");
// "The file size in the header is the total size of the chunks that follow plus 4 bytes for the 'WEBP' RIFF::ChunkID.
// The file SHOULD NOT contain any data after the data specified by File Size.
// Readers MAY parse such files, ignoring the trailing data."
if (context.data.size() - 8 < header.file_size())
return Error::from_string_literal("WebP data too small for size in header");
if (header.file_size() < 4) // Need at least 4 bytes for 'WEBP', else we'll trim to less than the header size below.
return Error::from_string_literal("WebP stored file size too small for header it's stored in");
if (context.data.size() - 8 > header.file_size()) {
dbgln_if(WEBP_DEBUG, "WebP has {} bytes of data, but header needs only {}. Trimming.", context.data.size(), header.file_size() + 8);
context.data = context.data.trim(header.file_size() + 8);
}
context.state = WebPLoadingContext::HeaderDecoded;
return {};
}
// https://developers.google.com/speed/webp/docs/riff_container#alpha
static ErrorOr<void> decode_webp_chunk_ALPH(RIFF::Chunk const& alph_chunk, Bitmap& bitmap)
{
VERIFY(alph_chunk.id() == "ALPH"sv);
if (alph_chunk.size() < 1)
return Error::from_string_literal("WebPImageDecoderPlugin: ALPH chunk too small");
u8 flags = alph_chunk[0];
u8 preprocessing = (flags >> 4) & 3;
u8 filtering_method = (flags >> 2) & 3;
u8 compression_method = flags & 3;
dbgln_if(WEBP_DEBUG, "ALPH: preprocessing {} filtering_method {} compression_method {}", preprocessing, filtering_method, compression_method);
ReadonlyBytes alpha_data = alph_chunk.data().slice(1);
size_t pixel_count = bitmap.width() * bitmap.height();
auto alpha = TRY(ByteBuffer::create_uninitialized(pixel_count));
if (compression_method == 0) {
// "Raw data: consists of a byte sequence of length width * height, containing all the 8-bit transparency values in scan order."
if (alpha_data.size() < pixel_count)
return Error::from_string_literal("WebPImageDecoderPlugin: uncompressed ALPH data too small");
memcpy(alpha.data(), alpha_data.data(), pixel_count);
} else {
// "Lossless format compression: the byte sequence is a compressed image-stream (as described in the WebP Lossless Bitstream Format)
// of implicit dimension width x height. That is, this image-stream does NOT contain any headers describing the image dimension.
// Once the image-stream is decoded into ARGB color values, following the process described in the lossless format specification,
// the transparency information must be extracted from the green channel of the ARGB quadruplet."
VP8LHeader vp8l_header { static_cast<u16>(bitmap.width()), static_cast<u16>(bitmap.height()), /*is_alpha_used=*/false, alpha_data };
auto lossless_bitmap = TRY(decode_webp_chunk_VP8L_contents(vp8l_header));
if (pixel_count != static_cast<size_t>(lossless_bitmap->width() * lossless_bitmap->height()))
return Error::from_string_literal("WebPImageDecoderPlugin: decompressed ALPH dimensions don't match VP8 dimensions");
for (size_t i = 0; i < pixel_count; ++i)
alpha[i] = (lossless_bitmap->begin()[i] & 0xff00) >> 8;
}
// "For each pixel, filtering is performed using the following calculations. Assume the alpha values surrounding the current X position are labeled as:
//
// C | B |
// ---+---+
// A | X |
// [...]
//
// The final value is derived by adding the decompressed value X to the predictor and using modulo-256 arithmetic"
switch (filtering_method) {
case 0:
// "Method 0: predictor = 0"
// Nothing to do.
break;
case 1:
// "Method 1: predictor = A"
// "The top-left value at location (0, 0) uses 0 as predictor value. Otherwise,
// For horizontal or gradient filtering methods, the left-most pixels at location (0, y) are predicted using the location (0, y-1) just above."
for (int y = 1; y < bitmap.height(); ++y)
alpha[y * bitmap.width()] += alpha[(y - 1) * bitmap.width()];
for (int y = 0; y < bitmap.height(); ++y) {
for (int x = 1; x < bitmap.width(); ++x) {
u8 A = alpha[y * bitmap.width() + (x - 1)];
alpha[y * bitmap.width() + x] += A;
}
}
break;
case 2:
// "Method 2: predictor = B"
// "The top-left value at location (0, 0) uses 0 as predictor value. Otherwise,
// For vertical or gradient filtering methods, the top-most pixels at location (x, 0) are predicted using the location (x-1, 0) on the left."
for (int x = 1; x < bitmap.width(); ++x)
alpha[x] += alpha[x - 1];
for (int y = 1; y < bitmap.height(); ++y) {
for (int x = 0; x < bitmap.width(); ++x) {
u8 B = alpha[(y - 1) * bitmap.width() + x];
alpha[y * bitmap.width() + x] += B;
}
}
break;
case 3:
// "Method 3: predictor = clip(A + B - C)"
// where clip(v) is equal to:
// * 0 if v < 0
// * 255 if v > 255
// * v otherwise"
// "The top-left value at location (0, 0) uses 0 as predictor value. Otherwise,
// For horizontal or gradient filtering methods, the left-most pixels at location (0, y) are predicted using the location (0, y-1) just above.
// For vertical or gradient filtering methods, the top-most pixels at location (x, 0) are predicted using the location (x-1, 0) on the left."
for (int x = 1; x < bitmap.width(); ++x)
alpha[x] += alpha[x - 1];
for (int y = 1; y < bitmap.height(); ++y)
alpha[y * bitmap.width()] += alpha[(y - 1) * bitmap.width()];
for (int y = 1; y < bitmap.height(); ++y) {
for (int x = 1; x < bitmap.width(); ++x) {
u8 A = alpha[y * bitmap.width() + (x - 1)];
u8 B = alpha[(y - 1) * bitmap.width() + x];
u8 C = alpha[(y - 1) * bitmap.width() + (x - 1)];
alpha[y * bitmap.width() + x] += clamp(A + B - C, 0, 255);
}
}
break;
default:
return Error::from_string_literal("WebPImageDecoderPlugin: uncompressed ALPH invalid filtering method");
}
for (size_t i = 0; i < pixel_count; ++i)
bitmap.begin()[i] = alpha[i] << 24 | (bitmap.begin()[i] & 0xffffff);
return {};
}
static ErrorOr<VP8XHeader> decode_webp_chunk_VP8X(RIFF::Chunk const& vp8x_chunk)
{
VERIFY(vp8x_chunk.id() == "VP8X"sv);
// The VP8X chunk is documented at "Extended WebP file header:" at the end of
// https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
if (vp8x_chunk.size() < 10)
return Error::from_string_literal("WebPImageDecoderPlugin: VP8X chunk too small");
// 1 byte flags
// "Reserved (Rsv): 2 bits MUST be 0. Readers MUST ignore this field.
// ICC profile (I): 1 bit Set if the file contains an ICC profile.
// Alpha (L): 1 bit Set if any of the frames of the image contain transparency information ("alpha").
// Exif metadata (E): 1 bit Set if the file contains Exif metadata.
// XMP metadata (X): 1 bit Set if the file contains XMP metadata.
// Animation (A): 1 bit Set if this is an animated image. Data in 'ANIM' and 'ANMF' chunks should be used to control the animation.
// Reserved (R): 1 bit MUST be 0. Readers MUST ignore this field."
u8 flags = vp8x_chunk[0];
bool has_icc = flags & 0x20;
bool has_alpha = flags & 0x10;
bool has_exif = flags & 0x8;
bool has_xmp = flags & 0x4;
bool has_animation = flags & 0x2;
// 3 bytes reserved
// 3 bytes width minus one
u32 width = (vp8x_chunk[4] | (vp8x_chunk[5] << 8) | (vp8x_chunk[6] << 16)) + 1;
// 3 bytes height minus one
u32 height = (vp8x_chunk[7] | (vp8x_chunk[8] << 8) | (vp8x_chunk[9] << 16)) + 1;
dbgln_if(WEBP_DEBUG, "VP8X: flags {:#x} --{}{}{}{}{}{}, width {}, height {}",
flags,
has_icc ? " icc" : "",
has_alpha ? " alpha" : "",
has_exif ? " exif" : "",
has_xmp ? " xmp" : "",
has_animation ? " anim" : "",
(flags & 0x3e) == 0 ? " none" : "",
width, height);
return VP8XHeader { has_icc, has_alpha, has_exif, has_xmp, has_animation, width, height };
}
// https://developers.google.com/speed/webp/docs/riff_container#animation
static ErrorOr<ANIMChunk> decode_webp_chunk_ANIM(RIFF::Chunk const& anim_chunk)
{
VERIFY(anim_chunk.id() == "ANIM"sv);
if (anim_chunk.size() < 6)
return Error::from_string_literal("WebPImageDecoderPlugin: ANIM chunk too small");
u32 background_color = (u32)anim_chunk[0] | ((u32)anim_chunk[1] << 8) | ((u32)anim_chunk[2] << 16) | ((u32)anim_chunk[3] << 24);
u16 loop_count = anim_chunk[4] | (anim_chunk[5] << 8);
dbgln_if(WEBP_DEBUG, "ANIM: background_color {:x} loop_count {}", background_color, loop_count);
return ANIMChunk { background_color, loop_count };
}
// https://developers.google.com/speed/webp/docs/riff_container#animation
static ErrorOr<ANMFChunk> decode_webp_chunk_ANMF(WebPLoadingContext& context, RIFF::Chunk const& anmf_chunk)
{
VERIFY(anmf_chunk.id() == "ANMF"sv);
if (anmf_chunk.size() < 16)
return Error::from_string_literal("WebPImageDecoderPlugin: ANMF chunk too small");
// "The X coordinate of the upper left corner of the frame is Frame X * 2."
u32 frame_x = ((u32)anmf_chunk[0] | ((u32)anmf_chunk[1] << 8) | ((u32)anmf_chunk[2] << 16)) * 2;
// "The Y coordinate of the upper left corner of the frame is Frame Y * 2."
u32 frame_y = ((u32)anmf_chunk[3] | ((u32)anmf_chunk[4] << 8) | ((u32)anmf_chunk[5] << 16)) * 2;
// "The frame width is 1 + Frame Width Minus One."
u32 frame_width = ((u32)anmf_chunk[6] | ((u32)anmf_chunk[7] << 8) | ((u32)anmf_chunk[8] << 16)) + 1;
// "The frame height is 1 + Frame Height Minus One."
u32 frame_height = ((u32)anmf_chunk[9] | ((u32)anmf_chunk[10] << 8) | ((u32)anmf_chunk[11] << 16)) + 1;
// "The time to wait before displaying the next frame, in 1 millisecond units.
// Note the interpretation of frame duration of 0 (and often <= 10) is implementation defined.
// Many tools and browsers assign a minimum duration similar to GIF."
u32 frame_duration = (u32)anmf_chunk[12] | ((u32)anmf_chunk[13] << 8) | ((u32)anmf_chunk[14] << 16);
u8 flags = anmf_chunk[15];
auto blending_method = static_cast<ANMFChunkHeader::BlendingMethod>((flags >> 1) & 1);
auto disposal_method = static_cast<ANMFChunkHeader::DisposalMethod>(flags & 1);
dbgln_if(WEBP_DEBUG, "ANMF: frame_x {} frame_y {} frame_width {} frame_height {} frame_duration {} blending_method {} disposal_method {}",
frame_x, frame_y, frame_width, frame_height, frame_duration, (int)blending_method, (int)disposal_method);
// https://developers.google.com/speed/webp/docs/riff_container#assembling_the_canvas_from_frames
// "assert VP8X.canvasWidth >= frame_right
// assert VP8X.canvasHeight >= frame_bottom"
VERIFY(context.first_chunk->id() == "VP8X"sv);
if (frame_x + frame_width > context.vp8x_header.width || frame_y + frame_height > context.vp8x_header.height)
return Error::from_string_literal("WebPImageDecoderPlugin: ANMF dimensions out of bounds");
auto header = ANMFChunkHeader { frame_x, frame_y, frame_width, frame_height, frame_duration, blending_method, disposal_method };
ReadonlyBytes frame_data = anmf_chunk.data().slice(16);
return ANMFChunk { header, frame_data };
}
static ErrorOr<ImageData> decode_webp_set_image_data(Optional<RIFF::Chunk> alpha, Optional<RIFF::Chunk> image_data)
{
if (!image_data.has_value())
return Error::from_string_literal("WebPImageDecoderPlugin: missing image data");
// https://developers.google.com/speed/webp/docs/riff_container#alpha
// "A frame containing a 'VP8L' chunk SHOULD NOT contain this chunk."
if (alpha.has_value() && image_data->id() == "VP8L"sv) {
dbgln_if(WEBP_DEBUG, "WebPImageDecoderPlugin: VP8L frames should not have ALPH chunks. Ignoring ALPH chunk.");
alpha.clear();
}
return ImageData { move(alpha), image_data.value() };
}
// https://developers.google.com/speed/webp/docs/riff_container#extended_file_format
static ErrorOr<void> decode_webp_extended(WebPLoadingContext& context, ReadonlyBytes chunks)
{
VERIFY(context.first_chunk->id() == "VP8X"sv);
Optional<RIFF::Chunk> alpha, image_data;
// FIXME: This isn't quite to spec, which says
// "All chunks SHOULD be placed in the same order as listed above.
// If a chunk appears in the wrong place, the file is invalid, but readers MAY parse the file, ignoring the chunks that are out of order."
auto store = [](auto& field, RIFF::Chunk const& chunk) {
if (!field.has_value())
field = chunk;
};
while (!chunks.is_empty()) {
auto chunk = TRY(RIFF::Chunk::decode_and_advance(chunks));
if (chunk.id() == "ICCP"sv)
store(context.iccp_chunk, chunk);
else if (chunk.id() == "ALPH"sv)
store(alpha, chunk);
else if (chunk.id() == "ANIM"sv)
store(context.animation_header_chunk, chunk);
else if (chunk.id() == "ANMF"sv)
TRY(context.animation_frame_chunks.try_append(chunk));
else if (chunk.id() == "EXIF"sv)
store(context.exif_chunk, chunk);
else if (chunk.id() == "XMP "sv)
store(context.xmp_chunk, chunk);
else if (chunk.id() == "VP8 "sv || chunk.id() == "VP8L"sv)
store(image_data, chunk);
}
// Validate chunks.
// https://developers.google.com/speed/webp/docs/riff_container#animation
// "ANIM Chunk: [...] This chunk MUST appear if the Animation flag in the VP8X chunk is set. If the Animation flag is not set and this chunk is present, it MUST be ignored."
if (context.vp8x_header.has_animation && !context.animation_header_chunk.has_value())
return Error::from_string_literal("WebPImageDecoderPlugin: Header claims animation, but no ANIM chunk");
if (!context.vp8x_header.has_animation && context.animation_header_chunk.has_value()) {
dbgln_if(WEBP_DEBUG, "WebPImageDecoderPlugin: Header claims no animation, but ANIM chunk present. Ignoring ANIM chunk.");
context.animation_header_chunk.clear();
}
// "ANMF Chunk: [...] If the Animation flag is not set, then this chunk SHOULD NOT be present."
if (!context.vp8x_header.has_animation && !context.animation_frame_chunks.is_empty()) {
dbgln_if(WEBP_DEBUG, "WebPImageDecoderPlugin: Header claims no animation, but ANMF chunks present. Ignoring ANMF chunks.");
context.animation_frame_chunks.clear();
}
// Image data is not optional -- but the spec doesn't explicitly say that an animated image must have more than 0 frames.
// The spec also doesn't say that animated images must not contain a regular image data segment.
if (!context.vp8x_header.has_animation || image_data.has_value())
context.image_data = TRY(decode_webp_set_image_data(move(alpha), move(image_data)));
// https://developers.google.com/speed/webp/docs/riff_container#color_profile
// "This chunk MUST appear before the image data."
if (context.iccp_chunk.has_value()
&& ((context.image_data.has_value()
&& (context.iccp_chunk->data().data() > context.image_data->image_data_chunk.data().data()
|| (context.image_data->alpha_chunk.has_value() && context.iccp_chunk->data().data() > context.image_data->alpha_chunk->data().data())))
|| (!context.animation_frame_chunks.is_empty() && context.iccp_chunk->data().data() > context.animation_frame_chunks[0].data().data()))) {
return Error::from_string_literal("WebPImageDecoderPlugin: ICCP chunk is after image data");
}
if (context.iccp_chunk.has_value() && !context.vp8x_header.has_icc)
return Error::from_string_literal("WebPImageDecoderPlugin: ICCP chunk present, but VP8X header claims no ICC profile");
if (!context.iccp_chunk.has_value() && context.vp8x_header.has_icc)
return Error::from_string_literal("WebPImageDecoderPlugin: VP8X header claims ICC profile, but no ICCP chunk present");
context.state = WebPLoadingContext::State::ChunksDecoded;
return {};
}
static ErrorOr<void> read_webp_first_chunk(WebPLoadingContext& context)
{
if (context.state >= WebPLoadingContext::State::FirstChunkRead)
return {};
context.chunks_cursor = context.data.slice(sizeof(RIFF::FileHeader));
auto first_chunk = TRY(RIFF::Chunk::decode_and_advance(context.chunks_cursor));
if (first_chunk.id() != "VP8 "sv && first_chunk.id() != "VP8L"sv && first_chunk.id() != "VP8X"sv)
return Error::from_string_literal("WebPImageDecoderPlugin: Invalid first chunk type");
context.first_chunk = first_chunk;
context.state = WebPLoadingContext::State::FirstChunkRead;
if (first_chunk.id() == "VP8 "sv || first_chunk.id() == "VP8L"sv)
context.image_data = TRY(decode_webp_set_image_data(OptionalNone {}, first_chunk));
return {};
}
static ErrorOr<void> decode_webp_first_chunk(WebPLoadingContext& context)
{
if (context.state >= WebPLoadingContext::State::FirstChunkDecoded)
return {};
if (context.state < WebPLoadingContext::FirstChunkRead)
TRY(read_webp_first_chunk(context));
if (context.first_chunk->id() == "VP8 "sv) {
auto vp8_header = TRY(decode_webp_chunk_VP8_header(context.first_chunk->data()));
context.size = IntSize { vp8_header.width, vp8_header.height };
context.state = WebPLoadingContext::State::FirstChunkDecoded;
return {};
}
if (context.first_chunk->id() == "VP8L"sv) {
auto vp8l_header = TRY(decode_webp_chunk_VP8L_header(context.first_chunk->data()));
context.size = IntSize { vp8l_header.width, vp8l_header.height };
context.state = WebPLoadingContext::State::FirstChunkDecoded;
return {};
}
VERIFY(context.first_chunk->id() == "VP8X"sv);
context.vp8x_header = TRY(decode_webp_chunk_VP8X(context.first_chunk.value()));
context.size = IntSize { context.vp8x_header.width, context.vp8x_header.height };
context.state = WebPLoadingContext::State::FirstChunkDecoded;
return {};
}
static ErrorOr<void> decode_webp_chunks(WebPLoadingContext& context)
{
if (context.state >= WebPLoadingContext::State::ChunksDecoded)
return {};
VERIFY(context.state >= WebPLoadingContext::FirstChunkDecoded);
if (context.first_chunk->id() == "VP8X"sv)
return decode_webp_extended(context, context.chunks_cursor);
context.state = WebPLoadingContext::State::ChunksDecoded;
return {};
}
static ErrorOr<void> decode_webp_animation_frame_chunks(WebPLoadingContext& context)
{
if (context.state >= WebPLoadingContext::State::AnimationFrameChunksDecoded)
return {};
VERIFY(context.state == WebPLoadingContext::State::ChunksDecoded);
context.animation_header_chunk_data = TRY(decode_webp_chunk_ANIM(context.animation_header_chunk.value()));
Vector<ANMFChunk> decoded_chunks;
TRY(decoded_chunks.try_ensure_capacity(context.animation_frame_chunks.size()));
for (auto const& chunk : context.animation_frame_chunks)
TRY(decoded_chunks.try_append(TRY(decode_webp_chunk_ANMF(context, chunk))));
context.animation_frame_chunks_data = move(decoded_chunks);
context.state = WebPLoadingContext::State::AnimationFrameChunksDecoded;
return {};
}
static ErrorOr<ImageData> decode_webp_animation_frame_image_data(ANMFChunk const& frame)
{
ReadonlyBytes chunks = frame.frame_data;
auto chunk = TRY(RIFF::Chunk::decode_and_advance(chunks));
Optional<RIFF::Chunk> alpha, image_data;
if (chunk.id() == "ALPH"sv) {
alpha = chunk;
chunk = TRY(RIFF::Chunk::decode_and_advance(chunks));
}
if (chunk.id() == "VP8 "sv || chunk.id() == "VP8L"sv)
image_data = chunk;
return decode_webp_set_image_data(move(alpha), move(image_data));
}
static ErrorOr<NonnullRefPtr<Bitmap>> decode_webp_image_data(WebPLoadingContext& context, ImageData const& image_data)
{
if (image_data.image_data_chunk.id() == "VP8L"sv) {
VERIFY(!image_data.alpha_chunk.has_value());
auto vp8l_header = TRY(decode_webp_chunk_VP8L_header(image_data.image_data_chunk.data()));
// Check that the VP8X header alpha flag matches the VP8L header alpha flag.
// FIXME: For animated images, if VP8X has alpha then at least one frame should have alpha. But we currently don't check this for animations.
if (context.first_chunk->id() == "VP8X" && !context.animation_frame_chunks_data.has_value() && context.vp8x_header.has_alpha != vp8l_header.is_alpha_used)
return Error::from_string_literal("WebPImageDecoderPlugin: VP8X header alpha flag doesn't match VP8L header");
return decode_webp_chunk_VP8L_contents(vp8l_header);
}
VERIFY(image_data.image_data_chunk.id() == "VP8 "sv);
auto vp8_header = TRY(decode_webp_chunk_VP8_header(image_data.image_data_chunk.data()));
auto bitmap = TRY(decode_webp_chunk_VP8_contents(vp8_header, image_data.alpha_chunk.has_value()));
if (image_data.alpha_chunk.has_value())
TRY(decode_webp_chunk_ALPH(image_data.alpha_chunk.value(), *bitmap));
return bitmap;
}
// https://developers.google.com/speed/webp/docs/riff_container#assembling_the_canvas_from_frames
static ErrorOr<ImageFrameDescriptor> decode_webp_animation_frame(WebPLoadingContext& context, size_t frame_index)
{
if (frame_index >= context.animation_frame_chunks_data->size())
return Error::from_string_literal("frame_index size too high");
VERIFY(context.first_chunk->id() == "VP8X"sv);
VERIFY(context.vp8x_header.has_animation);
Color clear_color = Color::from_argb(context.animation_header_chunk_data->background_color);
size_t start_frame = context.current_frame + 1;
dbgln_if(WEBP_DEBUG, "start_frame {} context.current_frame {}", start_frame, context.current_frame);
if (context.state < WebPLoadingContext::State::BitmapDecoded) {
start_frame = 0;
auto format = context.vp8x_header.has_alpha ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888;
context.bitmap = TRY(Bitmap::create(format, { context.vp8x_header.width, context.vp8x_header.height }));
context.bitmap->fill(clear_color);
} else if (frame_index < context.current_frame) {
start_frame = 0;
}
Painter painter(*context.bitmap);
for (size_t i = start_frame; i <= frame_index; ++i) {
dbgln_if(WEBP_DEBUG, "drawing frame {} to produce frame {}", i, frame_index);
auto const& frame = context.animation_frame_chunks_data.value()[i];
auto const& frame_description = frame.header;
if (i > 0) {
auto const& previous_frame = context.animation_frame_chunks_data.value()[i - 1].header;
if (previous_frame.disposal_method == ANMFChunkHeader::DisposalMethod::DisposeToBackgroundColor)
painter.clear_rect({ previous_frame.frame_x, previous_frame.frame_y, previous_frame.frame_width, previous_frame.frame_height }, clear_color);
}
auto frame_image_data = TRY(decode_webp_animation_frame_image_data(frame));
auto frame_bitmap = TRY(decode_webp_image_data(context, frame_image_data));
if (static_cast<u32>(frame_bitmap->width()) != frame_description.frame_width || static_cast<u32>(frame_bitmap->height()) != frame_description.frame_height)
return Error::from_string_literal("WebPImageDecoderPlugin: decoded frame bitmap size doesn't match frame description size");
// FIXME: "Alpha-blending SHOULD be done in linear color space..."
bool apply_alpha = frame_description.blending_method == ANMFChunkHeader::BlendingMethod::UseAlphaBlending;
painter.blit({ frame_description.frame_x, frame_description.frame_y }, *frame_bitmap, { {}, frame_bitmap->size() }, /*opacity=*/1.0, apply_alpha);
context.current_frame = i;
context.state = WebPLoadingContext::State::BitmapDecoded;
}
return ImageFrameDescriptor { context.bitmap, static_cast<int>(context.animation_frame_chunks_data.value()[frame_index].header.frame_duration_in_milliseconds) };
}
WebPImageDecoderPlugin::WebPImageDecoderPlugin(ReadonlyBytes data, OwnPtr<WebPLoadingContext> context)
: m_context(move(context))
{
@ -598,27 +44,129 @@ WebPImageDecoderPlugin::WebPImageDecoderPlugin(ReadonlyBytes data, OwnPtr<WebPLo
WebPImageDecoderPlugin::~WebPImageDecoderPlugin() = default;
bool WebPImageDecoderPlugin::set_error(ErrorOr<void> const& error_or)
{
if (error_or.is_error()) {
dbgln("WebPLoadingContext error: {}", error_or.error());
m_context->state = WebPLoadingContext::State::Error;
return true;
}
return false;
}
IntSize WebPImageDecoderPlugin::size()
{
return m_context->size.value();
return m_context->size;
}
static ErrorOr<void> decode_webp_header(WebPLoadingContext& context)
{
if (context.state >= WebPLoadingContext::HeaderDecoded)
return {};
int width = 0;
int height = 0;
int getinfo_result = WebPGetInfo(context.data.data(), context.data.size(), &width, &height);
if (getinfo_result != 1)
return Error::from_string_literal("Failed to decode webp image data");
WebPBitstreamFeatures webp_bitstream_features {};
VP8StatusCode vp8_result = WebPGetFeatures(context.data.data(), context.data.size(), &webp_bitstream_features);
if (vp8_result != VP8_STATUS_OK)
return Error::from_string_literal("Failed to get WebP bitstream features");
// Image header now decoded, save some results for fast access in other parts of the plugin.
context.size = IntSize { width, height };
context.has_animation = webp_bitstream_features.has_animation;
context.has_alpha = webp_bitstream_features.has_alpha;
context.frame_count = 1;
context.loop_count = 0;
if (webp_bitstream_features.has_animation == 1) {
WebPAnimDecoderOptions anim_decoder_options {};
WebPAnimDecoderOptionsInit(&anim_decoder_options);
anim_decoder_options.color_mode = MODE_BGRA;
anim_decoder_options.use_threads = 1;
WebPData webp_data { .bytes = context.data.data(), .size = context.data.size() };
auto* anim_decoder = WebPAnimDecoderNew(&webp_data, &anim_decoder_options);
if (anim_decoder == nullptr)
return Error::from_string_literal("Failed to allocate WebPAnimDecoderNew failed");
ScopeGuard guard { [=]() { WebPAnimDecoderDelete(anim_decoder); } };
WebPAnimInfo anim_info {};
int anim_getinfo_result = WebPAnimDecoderGetInfo(anim_decoder, &anim_info);
if (anim_getinfo_result != 1)
return Error::from_string_literal("Failed to get WebP animation info");
context.frame_count = anim_info.frame_count;
context.loop_count = anim_info.loop_count;
}
WebPData webp_data { .bytes = context.data.data(), .size = context.data.size() };
WebPMux* mux = WebPMuxCreate(&webp_data, 0);
ScopeGuard guard { [=]() { WebPMuxDelete(mux); } };
uint32_t flag = 0;
WebPMuxError err = WebPMuxGetFeatures(mux, &flag);
if (err != WEBP_MUX_OK)
return Error::from_string_literal("Failed to get webp features");
if (flag & ICCP_FLAG) {
WebPData icc_profile;
err = WebPMuxGetChunk(mux, "ICCP", &icc_profile);
if (err != WEBP_MUX_OK)
return Error::from_string_literal("Failed to get ICCP chunk of webp");
context.icc_data = TRY(context.icc_data.copy(icc_profile.bytes, icc_profile.size));
}
context.state = WebPLoadingContext::State::HeaderDecoded;
return {};
}
static ErrorOr<void> decode_webp_image(WebPLoadingContext& context)
{
VERIFY(context.state >= WebPLoadingContext::State::HeaderDecoded);
if (context.has_animation) {
WebPAnimDecoderOptions anim_decoder_options {};
WebPAnimDecoderOptionsInit(&anim_decoder_options);
anim_decoder_options.color_mode = MODE_BGRA;
anim_decoder_options.use_threads = 1;
WebPData webp_data { .bytes = context.data.data(), .size = context.data.size() };
auto* anim_decoder = WebPAnimDecoderNew(&webp_data, &anim_decoder_options);
if (anim_decoder == nullptr)
return Error::from_string_literal("Failed to allocate WebPAnimDecoderNew failed");
ScopeGuard guard { [=]() { WebPAnimDecoderDelete(anim_decoder); } };
int old_timestamp = 0;
while (WebPAnimDecoderHasMoreFrames(anim_decoder)) {
uint8_t* frame_data = nullptr;
int timestamp = 0;
if (!WebPAnimDecoderGetNext(anim_decoder, &frame_data, &timestamp))
return Error::from_string_literal("Failed to decode animated frame");
auto bitmap_format = context.has_alpha ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888;
auto bitmap = TRY(Bitmap::create(bitmap_format, context.size));
memcpy(bitmap->scanline_u8(0), frame_data, context.size.width() * context.size.height() * 4);
auto duration = timestamp - old_timestamp;
old_timestamp = timestamp;
context.frame_descriptors.append(ImageFrameDescriptor { bitmap, duration });
}
} else {
auto bitmap_format = context.has_alpha ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888;
auto bitmap = TRY(Bitmap::create(bitmap_format, context.size));
auto image_data = WebPDecodeBGRAInto(context.data.data(), context.data.size(), bitmap->scanline_u8(0), bitmap->data_size(), bitmap->pitch());
if (image_data == nullptr)
return Error::from_string_literal("Failed to decode webp image into bitmap");
auto duration = 0;
context.frame_descriptors.append(ImageFrameDescriptor { bitmap, duration });
}
return {};
}
bool WebPImageDecoderPlugin::sniff(ReadonlyBytes data)
{
WebPLoadingContext context;
context.data = data;
// Intentionally no set_error() call: We're just sniffing `data` passed to the function, not reading m_context->data.
return !decode_webp_header(context).is_error();
}
@ -627,13 +175,12 @@ ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> WebPImageDecoderPlugin::create(Readon
auto context = TRY(try_make<WebPLoadingContext>());
auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) WebPImageDecoderPlugin(data, move(context))));
TRY(decode_webp_header(*plugin->m_context));
TRY(decode_webp_first_chunk(*plugin->m_context));
return plugin;
}
bool WebPImageDecoderPlugin::is_animated()
{
return m_context->first_chunk->id() == "VP8X"sv && m_context->vp8x_header.has_animation;
return m_context->has_animation;
}
size_t WebPImageDecoderPlugin::loop_count()
@ -641,17 +188,7 @@ size_t WebPImageDecoderPlugin::loop_count()
if (!is_animated())
return 0;
if (m_context->state < WebPLoadingContext::State::ChunksDecoded) {
if (set_error(decode_webp_chunks(*m_context)))
return 0;
}
if (m_context->state < WebPLoadingContext::State::AnimationFrameChunksDecoded) {
if (set_error(decode_webp_animation_frame_chunks(*m_context)))
return 0;
}
return m_context->animation_header_chunk_data->loop_count;
return m_context->loop_count;
}
size_t WebPImageDecoderPlugin::frame_count()
@ -659,12 +196,7 @@ size_t WebPImageDecoderPlugin::frame_count()
if (!is_animated())
return 1;
if (m_context->state < WebPLoadingContext::State::ChunksDecoded) {
if (set_error(decode_webp_chunks(*m_context)))
return 1;
}
return m_context->animation_frame_chunks.size();
return m_context->frame_count;
}
size_t WebPImageDecoderPlugin::first_animated_frame_index()
@ -680,52 +212,24 @@ ErrorOr<ImageFrameDescriptor> WebPImageDecoderPlugin::frame(size_t index, Option
if (m_context->state == WebPLoadingContext::State::Error)
return Error::from_string_literal("WebPImageDecoderPlugin: Decoding failed");
// In a lambda so that only one check to set State::Error is needed, instead of one per TRY.
auto decode_frame = [this](size_t index) -> ErrorOr<ImageFrameDescriptor> {
if (m_context->state < WebPLoadingContext::State::ChunksDecoded)
TRY(decode_webp_chunks(*m_context));
if (is_animated()) {
if (m_context->state < WebPLoadingContext::State::AnimationFrameChunksDecoded)
TRY(decode_webp_animation_frame_chunks(*m_context));
return decode_webp_animation_frame(*m_context, index);
}
if (m_context->state < WebPLoadingContext::State::BitmapDecoded) {
auto bitmap = TRY(decode_webp_image_data(*m_context, m_context->image_data.value()));
// Check that size in VP8X chunk matches dimensions in VP8 or VP8L chunk if both are present.
if (m_context->first_chunk->id() == "VP8X") {
if (static_cast<u32>(bitmap->width()) != m_context->vp8x_header.width || static_cast<u32>(bitmap->height()) != m_context->vp8x_header.height)
return Error::from_string_literal("WebPImageDecoderPlugin: VP8X and VP8/VP8L chunks store different dimensions");
}
m_context->bitmap = move(bitmap);
m_context->state = WebPLoadingContext::State::BitmapDecoded;
}
VERIFY(m_context->bitmap);
return ImageFrameDescriptor { m_context->bitmap, 0 };
};
auto result = decode_frame(index);
if (result.is_error()) {
m_context->state = WebPLoadingContext::State::Error;
return result.release_error();
if (m_context->state < WebPLoadingContext::State::BitmapDecoded) {
TRY(decode_webp_image(*m_context));
m_context->state = WebPLoadingContext::State::BitmapDecoded;
}
return result.release_value();
if (index >= m_context->frame_descriptors.size())
return Error::from_string_literal("WebPImageDecoderPlugin: Invalid frame index");
return m_context->frame_descriptors[index];
}
ErrorOr<Optional<ReadonlyBytes>> WebPImageDecoderPlugin::icc_data()
{
if (auto result = decode_webp_chunks(*m_context); result.is_error()) {
m_context->state = WebPLoadingContext::State::Error;
return result.release_error();
}
if (m_context->state < WebPLoadingContext::State::HeaderDecoded)
(void)frame(0);
// FIXME: "If this chunk is not present, sRGB SHOULD be assumed."
return m_context->iccp_chunk.map([](auto iccp_chunk) { return iccp_chunk.data(); });
if (!m_context->icc_data.is_empty())
return m_context->icc_data;
return OptionalNone {};
}
}

View file

@ -29,8 +29,6 @@ public:
virtual ErrorOr<Optional<ReadonlyBytes>> icc_data() override;
private:
bool set_error(ErrorOr<void> const&);
WebPImageDecoderPlugin(ReadonlyBytes, OwnPtr<WebPLoadingContext>);
OwnPtr<WebPLoadingContext> m_context;

View file

@ -1,923 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/BitStream.h>
#include <AK/Debug.h>
#include <AK/Endian.h>
#include <AK/Format.h>
#include <AK/MemoryStream.h>
#include <AK/Vector.h>
#include <LibCompress/Deflate.h>
#include <LibGfx/ImageFormats/WebPLoaderLossless.h>
#include <LibGfx/ImageFormats/WebPSharedLossless.h>
// Lossless format: https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification
namespace Gfx {
// 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
ErrorOr<VP8LHeader> decode_webp_chunk_VP8L_header(ReadonlyBytes vp8l_data)
{
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#3_riff_header
if (vp8l_data.size() < 5)
return Error::from_string_literal("WebPImageDecoderPlugin: VP8L chunk too small");
FixedMemoryStream memory_stream { vp8l_data.trim(5) };
LittleEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream), LittleEndianInputBitStream::UnsatisfiableReadBehavior::FillWithZero };
u8 signature = TRY(bit_stream.read_bits(8));
if (signature != 0x2f)
return Error::from_string_literal("WebPImageDecoderPlugin: VP8L chunk invalid signature");
// 14 bits width-1, 14 bits height-1, 1 bit alpha hint, 3 bit version_number.
u16 width = TRY(bit_stream.read_bits(14)) + 1;
u16 height = TRY(bit_stream.read_bits(14)) + 1;
bool is_alpha_used = TRY(bit_stream.read_bits(1)) != 0;
u8 version_number = TRY(bit_stream.read_bits(3));
VERIFY(bit_stream.is_eof());
dbgln_if(WEBP_DEBUG, "VP8L: width {}, height {}, is_alpha_used {}, version_number {}",
width, height, is_alpha_used, version_number);
// "The version_number is a 3 bit code that must be set to 0. Any other value should be treated as an error."
if (version_number != 0)
return Error::from_string_literal("WebPImageDecoderPlugin: VP8L chunk invalid version_number");
return VP8LHeader { width, height, is_alpha_used, vp8l_data.slice(5) };
}
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#621_decoding_and_building_the_prefix_codes
static ErrorOr<CanonicalCode> decode_webp_chunk_VP8L_prefix_code(LittleEndianInputBitStream& bit_stream, size_t alphabet_size)
{
// prefix-code = simple-prefix-code / normal-prefix-code
bool is_simple_code_length_code = TRY(bit_stream.read_bits(1));
dbgln_if(WEBP_DEBUG, "is_simple_code_length_code {}", is_simple_code_length_code);
Vector<u8, 286> code_lengths;
if (is_simple_code_length_code) {
TRY(code_lengths.try_resize(alphabet_size));
int num_symbols = TRY(bit_stream.read_bits(1)) + 1;
int is_first_8bits = TRY(bit_stream.read_bits(1));
u8 symbol0 = TRY(bit_stream.read_bits(1 + 7 * is_first_8bits));
dbgln_if(WEBP_DEBUG, " symbol0 {}", symbol0);
if (symbol0 >= code_lengths.size())
return Error::from_string_literal("symbol0 out of bounds");
code_lengths[symbol0] = 1;
if (num_symbols == 2) {
u8 symbol1 = TRY(bit_stream.read_bits(8));
dbgln_if(WEBP_DEBUG, " symbol1 {}", symbol1);
if (symbol1 >= code_lengths.size())
return Error::from_string_literal("symbol1 out of bounds");
code_lengths[symbol1] = 1;
}
return CanonicalCode::from_bytes(code_lengths);
}
// This has plenty in common with deflate (cf DeflateDecompressor::decode_codes() in Deflate.cpp in LibCompress)
// Symbol 16 has different semantics, and kCodeLengthCodeOrder is different. Other than that, this is virtually deflate.
// (...but webp uses 5 different prefix codes, while deflate doesn't.)
int num_code_lengths = 4 + TRY(bit_stream.read_bits(4));
dbgln_if(WEBP_DEBUG, " num_code_lengths {}", num_code_lengths);
VERIFY(num_code_lengths <= 19);
u8 code_length_code_lengths[kCodeLengthCodeOrder.size()] = { 0 }; // "All zeros" [sic]
for (int i = 0; i < num_code_lengths; ++i)
code_length_code_lengths[kCodeLengthCodeOrder[i]] = TRY(bit_stream.read_bits(3));
// "Next, if `ReadBits(1) == 0`, the maximum number of different read symbols
// (`max_symbol`) for each symbol type (A, R, G, B, and distance) is set to its
// alphabet size:"
unsigned max_symbol;
if (TRY(bit_stream.read_bits(1)) == 0) {
max_symbol = alphabet_size;
}
// "Otherwise, it is defined as:"
else {
// "int length_nbits = 2 + 2 * ReadBits(3);"
int length_nbits = 2 + 2 * TRY(bit_stream.read_bits(3));
// "int max_symbol = 2 + ReadBits(length_nbits);"
max_symbol = 2 + TRY(bit_stream.read_bits(length_nbits));
dbgln_if(WEBP_DEBUG, " extended, length_nbits {} max_symbol {}", length_nbits, max_symbol);
// "If `max_symbol` is larger than the size of the alphabet for the symbol type, the bitstream is invalid."
if (max_symbol > alphabet_size)
return Error::from_string_literal("WebPImageDecoderPlugin: invalid max_symbol");
}
// "A prefix table is then built from code_length_code_lengths and used to read up to max_symbol code lengths."
dbgln_if(WEBP_DEBUG, " reading {} symbols from at most {} codes", alphabet_size, max_symbol);
auto const code_length_code = TRY(CanonicalCode::from_bytes({ code_length_code_lengths, sizeof(code_length_code_lengths) }));
u8 last_non_zero = 8; // "If code 16 is used before a non-zero value has been emitted, a value of 8 is repeated."
while (code_lengths.size() < alphabet_size) {
if (max_symbol == 0)
break;
--max_symbol;
auto symbol = TRY(code_length_code.read_symbol(bit_stream));
if (symbol < 16) {
// "Code [0..15] indicates literal code lengths."
code_lengths.append(static_cast<u8>(symbol));
if (symbol != 0)
last_non_zero = symbol;
} else if (symbol == 16) {
// "Code 16 repeats the previous non-zero value [3..6] times, i.e., 3 + ReadBits(2) times."
auto nrepeat = 3 + TRY(bit_stream.read_bits(2));
// This is different from deflate.
for (size_t j = 0; j < nrepeat; ++j)
code_lengths.append(last_non_zero);
} else if (symbol == 17) {
// "Code 17 emits a streak of zeros [3..10], i.e., 3 + ReadBits(3) times."
auto nrepeat = 3 + TRY(bit_stream.read_bits(3));
for (size_t j = 0; j < nrepeat; ++j)
code_lengths.append(0);
} else {
VERIFY(symbol == 18);
// "Code 18 emits a streak of zeros of length [11..138], i.e., 11 + ReadBits(7) times."
auto nrepeat = 11 + TRY(bit_stream.read_bits(7));
for (size_t j = 0; j < nrepeat; ++j)
code_lengths.append(0);
}
}
if (code_lengths.size() > alphabet_size)
return Error::from_string_literal("Number of code lengths is larger than the alphabet size");
return CanonicalCode::from_bytes(code_lengths);
}
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#622_decoding_of_meta_prefix_codes
// The description of prefix code groups is in "Decoding of Meta Prefix Codes", even though prefix code groups are used
// in regular images without meta prefix code as well ¯\_(ツ)_/¯.
static ErrorOr<PrefixCodeGroup> decode_webp_chunk_VP8L_prefix_code_group(u16 color_cache_size, LittleEndianInputBitStream& bit_stream)
{
// prefix-code-group =
// 5prefix-code ; See "Interpretation of Meta Prefix Codes" to
// ; understand what each of these five prefix
// ; codes are for.
// "Once code lengths are read, a prefix code for each symbol type (A, R, G, B, distance) is formed using their respective alphabet sizes."
// ...
// "* G channel: 256 + 24 + color_cache_size
// * other literals (A,R,B): 256
// * distance code: 40"
Array<size_t, 5> const alphabet_sizes { 256 + 24 + static_cast<size_t>(color_cache_size), 256, 256, 256, 40 };
PrefixCodeGroup group;
for (size_t i = 0; i < alphabet_sizes.size(); ++i)
group[i] = TRY(decode_webp_chunk_VP8L_prefix_code(bit_stream, alphabet_sizes[i]));
return group;
}
static ErrorOr<NonnullRefPtr<Bitmap>> decode_webp_chunk_VP8L_image(ImageKind image_kind, BitmapFormat format, IntSize const& size, LittleEndianInputBitStream& bit_stream)
{
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#623_decoding_entropy-coded_image_data
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#523_color_cache_coding
// 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
bool has_color_cache_info = TRY(bit_stream.read_bits(1));
u16 color_cache_size = 0;
u8 color_cache_code_bits;
dbgln_if(WEBP_DEBUG, "has_color_cache_info {}", has_color_cache_info);
Vector<ARGB32, 32> color_cache;
if (has_color_cache_info) {
color_cache_code_bits = TRY(bit_stream.read_bits(4));
// "The range of allowed values for color_cache_code_bits is [1..11]. Compliant decoders must indicate a corrupted bitstream for other values."
if (color_cache_code_bits < 1 || color_cache_code_bits > 11)
return Error::from_string_literal("WebPImageDecoderPlugin: VP8L invalid color_cache_code_bits");
color_cache_size = 1 << color_cache_code_bits;
dbgln_if(WEBP_DEBUG, "color_cache_size {}", color_cache_size);
TRY(color_cache.try_resize(color_cache_size));
}
int num_prefix_groups = 1;
RefPtr<Gfx::Bitmap> entropy_image;
int prefix_bits = 0;
if (image_kind == ImageKind::SpatiallyCoded) {
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#622_decoding_of_meta_prefix_codes
// In particular, the "Entropy image" subsection.
// "Meta prefix codes may be used only when the image is being used in the role of an ARGB image."
// meta-prefix = %b0 / (%b1 entropy-image)
bool has_meta_prefix = TRY(bit_stream.read_bits(1));
dbgln_if(WEBP_DEBUG, "has_meta_prefix {}", has_meta_prefix);
if (has_meta_prefix) {
prefix_bits = TRY(bit_stream.read_bits(3)) + 2;
dbgln_if(WEBP_DEBUG, "prefix_bits {}", prefix_bits);
int block_size = 1 << prefix_bits;
IntSize prefix_size { ceil_div(size.width(), block_size), ceil_div(size.height(), block_size) };
entropy_image = TRY(decode_webp_chunk_VP8L_image(ImageKind::EntropyCoded, BitmapFormat::BGRx8888, prefix_size, bit_stream));
// A "meta prefix image" or "entropy image" can tell the decoder to use different PrefixCodeGroup for
// tiles of the main, spatially coded, image. It's a bit hidden in the spec:
// "The red and green components of a pixel define the meta prefix code used in a particular block of the ARGB image."
// ...
// "The number of prefix code groups in the ARGB image can be obtained by finding the largest meta prefix code from the entropy image"
// That is, if a meta prefix image is present, the main image has more than one PrefixCodeGroup,
// and the highest value in the meta prefix image determines how many exactly.
u16 largest_meta_prefix_code = 0;
for (ARGB32& pixel : *entropy_image) {
u16 meta_prefix_code = (pixel >> 8) & 0xffff;
if (meta_prefix_code > largest_meta_prefix_code)
largest_meta_prefix_code = meta_prefix_code;
}
dbgln_if(WEBP_DEBUG, "largest meta prefix code {}", largest_meta_prefix_code);
num_prefix_groups = largest_meta_prefix_code + 1;
}
}
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#52_encoding_of_image_data
// "The encoded image data consists of several parts:
// 1. Decoding and building the prefix codes
// 2. Meta prefix codes
// 3. Entropy-coded image data"
// data = prefix-codes lz77-coded-image
// prefix-codes = prefix-code-group *prefix-codes
Vector<PrefixCodeGroup, 1> groups;
for (int i = 0; i < num_prefix_groups; ++i)
TRY(groups.try_append(TRY(decode_webp_chunk_VP8L_prefix_code_group(color_cache_size, bit_stream))));
auto bitmap = TRY(Bitmap::create(format, size));
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
struct Offset {
i8 x, y;
};
// clang-format off
Array<Offset, 120> distance_map { {
{0, 1}, {1, 0},
{1, 1}, {-1, 1}, {0, 2}, { 2, 0},
{1, 2}, {-1, 2}, {2, 1}, {-2, 1},
{2, 2}, {-2, 2}, {0, 3}, { 3, 0}, { 1, 3}, {-1, 3}, { 3, 1}, {-3, 1},
{2, 3}, {-2, 3}, {3, 2}, {-3, 2}, { 0, 4}, { 4, 0}, { 1, 4}, {-1, 4}, { 4, 1}, {-4, 1},
{3, 3}, {-3, 3}, {2, 4}, {-2, 4}, { 4, 2}, {-4, 2}, { 0, 5},
{3, 4}, {-3, 4}, {4, 3}, {-4, 3}, { 5, 0}, { 1, 5}, {-1, 5}, { 5, 1}, {-5, 1}, { 2, 5}, {-2, 5}, { 5, 2}, {-5, 2},
{4, 4}, {-4, 4}, {3, 5}, {-3, 5}, { 5, 3}, {-5, 3}, { 0, 6}, { 6, 0}, { 1, 6}, {-1, 6}, { 6, 1}, {-6, 1}, { 2, 6}, {-2, 6}, {6, 2}, {-6, 2},
{4, 5}, {-4, 5}, {5, 4}, {-5, 4}, { 3, 6}, {-3, 6}, { 6, 3}, {-6, 3}, { 0, 7}, { 7, 0}, { 1, 7}, {-1, 7},
{5, 5}, {-5, 5}, {7, 1}, {-7, 1}, { 4, 6}, {-4, 6}, { 6, 4}, {-6, 4}, { 2, 7}, {-2, 7}, { 7, 2}, {-7, 2}, { 3, 7}, {-3, 7}, {7, 3}, {-7, 3},
{5, 6}, {-5, 6}, {6, 5}, {-6, 5}, { 8, 0}, { 4, 7}, {-4, 7}, { 7, 4}, {-7, 4}, { 8, 1}, { 8, 2},
{6, 6}, {-6, 6}, {8, 3}, { 5, 7}, {-5, 7}, { 7, 5}, {-7, 5}, { 8, 4},
{6, 7}, {-6, 7}, {7, 6}, {-7, 6}, { 8, 5},
{7, 7}, {-7, 7}, {8, 6},
{8, 7},
} };
// clang-format on
// lz77-coded-image =
// *((argb-pixel / lz77-copy / color-cache-code) lz77-coded-image)
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#623_decoding_entropy-coded_image_data
ARGB32* begin = bitmap->begin();
ARGB32* end = bitmap->end();
ARGB32* pixel = begin;
auto prefix_group = [prefix_bits, begin, &groups, size, &entropy_image](ARGB32* pixel) -> PrefixCodeGroup const& {
if (!prefix_bits)
return groups[0];
size_t offset = pixel - begin;
int x = offset % size.width();
int y = offset / size.width();
int meta_prefix_code = (entropy_image->scanline(y >> prefix_bits)[x >> prefix_bits] >> 8) & 0xffff;
return groups[meta_prefix_code];
};
auto emit_pixel = [&pixel, &color_cache, color_cache_size, color_cache_code_bits](ARGB32 color) {
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#523_color_cache_coding
// "The state of the color cache is maintained by inserting every pixel, be it produced by backward referencing or as literals, into the cache in the order they appear in the stream."
*pixel++ = color;
if (color_cache_size)
color_cache[(0x1e35a7bd * color) >> (32 - color_cache_code_bits)] = color;
};
while (pixel < end) {
// "For the current position (x, y) in the image, the decoder first identifies the corresponding prefix code group"
auto const& group = prefix_group(pixel);
// "Next, read the symbol S from the bitstream using prefix code #1.
// Note that S is any integer in the range 0 to (256 + 24 + color_cache_size - 1)."
auto symbol = TRY(group[0].read_symbol(bit_stream));
if (symbol >= 256u + 24u + color_cache_size)
return Error::from_string_literal("WebPImageDecoderPlugin: Symbol out of bounds");
// "1. if S < 256"
if (symbol < 256u) {
// "a. Use S as the green component."
u8 g = symbol;
// "b. Read red from the bitstream using prefix code #2."
u8 r = TRY(group[1].read_symbol(bit_stream));
// "c. Read blue from the bitstream using prefix code #3."
u8 b = TRY(group[2].read_symbol(bit_stream));
// "d. Read alpha from the bitstream using prefix code #4."
u8 a = TRY(group[3].read_symbol(bit_stream));
emit_pixel(Color(r, g, b, a).value());
}
// "2. if S >= 256 && S < 256 + 24"
else if (symbol < 256u + 24u) {
auto prefix_value = [&bit_stream](u8 prefix_code) -> ErrorOr<u32> {
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
if (prefix_code < 4)
return prefix_code + 1;
int extra_bits = (prefix_code - 2) >> 1;
int offset = (2 + (prefix_code & 1)) << extra_bits;
return offset + TRY(bit_stream.read_bits(extra_bits)) + 1;
};
// "a. Use S - 256 as a length prefix code."
u8 length_prefix_code = symbol - 256;
// "b. Read extra bits for length from the bitstream."
// "c. Determine backward-reference length L from length prefix code and the extra bits read."
u32 length = TRY(prefix_value(length_prefix_code));
// "d. Read distance prefix code from the bitstream using prefix code #5."
u8 distance_prefix_code = TRY(group[4].read_symbol(bit_stream));
// "e. Read extra bits for distance from the bitstream."
// "f. Determine backward-reference distance D from distance prefix code and the extra bits read."
i32 distance = TRY(prefix_value(distance_prefix_code));
// "g. Copy the L pixels (in scan-line order) from the sequence of pixels prior to them by D pixels."
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#522_lz77_backward_reference
// "Distance codes larger than 120 denote the pixel-distance in scan-line order, offset by 120."
// "The smallest distance codes [1..120] are special, and are reserved for a close neighborhood of the current pixel."
if (distance <= 120) {
auto offset = distance_map[distance - 1];
distance = offset.x + offset.y * bitmap->width();
if (distance < 1)
distance = 1;
} else {
distance = distance - 120;
}
if (pixel - begin < distance) {
dbgln_if(WEBP_DEBUG, "invalid backref, {} < {}", pixel - begin, distance);
return Error::from_string_literal("WebPImageDecoderPlugin: Backward reference distance out of bounds");
}
if (end - pixel < static_cast<ptrdiff_t>(length)) {
dbgln_if(WEBP_DEBUG, "invalid length, {} < {}", end - pixel, length);
return Error::from_string_literal("WebPImageDecoderPlugin: Backward reference length out of bounds");
}
ARGB32* src = pixel - distance;
for (u32 i = 0; i < length; ++i)
emit_pixel(src[i]);
}
// "3. if S >= 256 + 24"
else {
// "a. Use S - (256 + 24) as the index into the color cache."
unsigned index = symbol - (256 + 24);
// "b. Get ARGB color from the color cache at that index."
// `symbol` is bounds-checked at the start of the loop.
*pixel++ = color_cache[index];
}
}
return bitmap;
}
namespace {
static ARGB32 add_argb32(ARGB32 a, ARGB32 b)
{
auto a_color = Color::from_argb(a);
auto b_color = Color::from_argb(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();
}
class Transform {
public:
virtual ~Transform();
// Could modify the input bitmap and return it, or could return a new bitmap.
virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) = 0;
};
Transform::~Transform() = default;
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#41_predictor_transform
class PredictorTransform : public Transform {
public:
static ErrorOr<NonnullOwnPtr<PredictorTransform>> read(LittleEndianInputBitStream&, IntSize const& image_size);
virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) override;
private:
PredictorTransform(int size_bits, NonnullRefPtr<Bitmap> predictor_bitmap)
: m_size_bits(size_bits)
, m_predictor_bitmap(move(predictor_bitmap))
{
}
// These capitalized functions are all from the spec:
static u8 Average2(u8 a, u8 b)
{
return (a + b) / 2;
}
static u32 Select(u32 L, u32 T, u32 TL)
{
// "L = left pixel, T = top pixel, TL = top left pixel."
#define ALPHA(x) ((x >> 24) & 0xff)
#define RED(x) ((x >> 16) & 0xff)
#define GREEN(x) ((x >> 8) & 0xff)
#define BLUE(x) (x & 0xff)
// "ARGB component estimates for prediction."
int pAlpha = ALPHA(L) + ALPHA(T) - ALPHA(TL);
int pRed = RED(L) + RED(T) - RED(TL);
int pGreen = GREEN(L) + GREEN(T) - GREEN(TL);
int pBlue = BLUE(L) + BLUE(T) - BLUE(TL);
// "Manhattan distances to estimates for left and top pixels."
int pL = abs(pAlpha - (int)ALPHA(L)) + abs(pRed - (int)RED(L)) + abs(pGreen - (int)GREEN(L)) + abs(pBlue - (int)BLUE(L));
int pT = abs(pAlpha - (int)ALPHA(T)) + abs(pRed - (int)RED(T)) + abs(pGreen - (int)GREEN(T)) + abs(pBlue - (int)BLUE(T));
// "Return either left or top, the one closer to the prediction."
if (pL < pT) {
return L;
} else {
return T;
}
#undef BLUE
#undef GREEN
#undef RED
#undef ALPHA
}
// "Clamp the input value between 0 and 255."
static int Clamp(int a)
{
return clamp(a, 0, 255);
}
static int ClampAddSubtractFull(int a, int b, int c)
{
return Clamp(a + b - c);
}
static int ClampAddSubtractHalf(int a, int b)
{
return Clamp(a + (a - b) / 2);
}
// ...and we're back from the spec!
static Color average2(Color a, Color b)
{
return Color(Average2(a.red(), b.red()),
Average2(a.green(), b.green()),
Average2(a.blue(), b.blue()),
Average2(a.alpha(), b.alpha()));
}
static ARGB32 average2(ARGB32 a, ARGB32 b)
{
return average2(Color::from_argb(a), Color::from_argb(b)).value();
}
static ErrorOr<ARGB32> predict(u8 predictor, ARGB32 TL, ARGB32 T, ARGB32 TR, ARGB32 L);
int m_size_bits;
NonnullRefPtr<Bitmap> m_predictor_bitmap;
};
ErrorOr<NonnullOwnPtr<PredictorTransform>> PredictorTransform::read(LittleEndianInputBitStream& bit_stream, IntSize const& image_size)
{
// predictor-image = 3BIT ; sub-pixel code
// entropy-coded-image
int size_bits = TRY(bit_stream.read_bits(3)) + 2;
dbgln_if(WEBP_DEBUG, "predictor size_bits {}", size_bits);
int block_size = 1 << size_bits;
IntSize predictor_image_size { ceil_div(image_size.width(), block_size), ceil_div(image_size.height(), block_size) };
auto predictor_bitmap = TRY(decode_webp_chunk_VP8L_image(ImageKind::EntropyCoded, BitmapFormat::BGRx8888, predictor_image_size, bit_stream));
return adopt_nonnull_own_or_enomem(new (nothrow) PredictorTransform(size_bits, move(predictor_bitmap)));
}
ErrorOr<NonnullRefPtr<Bitmap>> PredictorTransform::transform(NonnullRefPtr<Bitmap> bitmap_ref)
{
Bitmap& bitmap = *bitmap_ref;
// "There are special handling rules for some border pixels.
// If there is a prediction transform, regardless of the mode [0..13] for these pixels,
// the predicted value for the left-topmost pixel of the image is 0xff000000,
bitmap.scanline(0)[0] = add_argb32(bitmap.scanline(0)[0], 0xff000000);
// L-pixel for all pixels on the top row,
for (int x = 1; x < bitmap.width(); ++x)
bitmap.scanline(0)[x] = add_argb32(bitmap.scanline(0)[x], bitmap.scanline(0)[x - 1]);
// and T-pixel for all pixels on the leftmost column."
for (int y = 1; y < bitmap.height(); ++y)
bitmap.scanline(y)[0] = add_argb32(bitmap.scanline(y)[0], bitmap.scanline(y - 1)[0]);
ARGB32* bitmap_previous_scanline = bitmap.scanline(0);
for (int y = 1; y < bitmap.height(); ++y) {
ARGB32* bitmap_scanline = bitmap.scanline(y);
ARGB32 TL = bitmap_previous_scanline[0];
ARGB32 T = bitmap_previous_scanline[1];
ARGB32 TR = 2 < bitmap.width() ? bitmap_previous_scanline[2] : bitmap_previous_scanline[0];
ARGB32 L = bitmap_scanline[0];
int predictor_y = y >> m_size_bits;
ARGB32* predictor_scanline = m_predictor_bitmap->scanline(predictor_y);
for (int x = 1; x < bitmap.width(); ++x) {
int predictor_x = x >> m_size_bits;
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#51_roles_of_image_data
// "The green component of a pixel defines which of the 14 predictors is used within a particular block of the ARGB image."
u8 predictor = Color::from_argb(predictor_scanline[predictor_x]).green();
ARGB32 predicted = TRY(predict(predictor, TL, T, TR, L));
// "The final pixel value is obtained by adding each channel of the predicted value to the encoded residual value."
bitmap_scanline[x] = add_argb32(bitmap_scanline[x], predicted);
TL = T;
T = TR;
// "Addressing the TR-pixel for pixels on the rightmost column is exceptional.
// The pixels on the rightmost column are predicted by using the modes [0..13] just like pixels not on the border,
// but the leftmost pixel on the same row as the current pixel is instead used as the TR-pixel."
TR = x + 2 < bitmap.width() ? bitmap_previous_scanline[x + 2] : bitmap_previous_scanline[0];
L = bitmap_scanline[x];
}
bitmap_previous_scanline = bitmap_scanline;
}
return bitmap_ref;
}
ErrorOr<ARGB32> PredictorTransform::predict(u8 predictor, ARGB32 TL, ARGB32 T, ARGB32 TR, ARGB32 L)
{
switch (predictor) {
case 0:
// "0xff000000 (represents solid black color in ARGB)"
return 0xff000000;
case 1:
// "L"
return L;
case 2:
// "T"
return T;
case 3:
// "TR"
return TR;
case 4:
// "TL"
return TL;
case 5:
// "Average2(Average2(L, TR), T)"
return average2(average2(L, TR), T);
case 6:
// "Average2(L, TL)"
return average2(L, TL);
case 7:
// "Average2(L, T)"
return average2(L, T);
case 8:
// "Average2(TL, T)"
return average2(TL, T);
case 9:
// "Average2(T, TR)"
return average2(T, TR);
case 10:
// "Average2(Average2(L, TL), Average2(T, TR))"
return average2(average2(L, TL), average2(T, TR));
case 11:
// "Select(L, T, TL)"
return Select(L, T, TL);
case 12: {
// "ClampAddSubtractFull(L, T, TL)"
auto color_L = Color::from_argb(L);
auto color_T = Color::from_argb(T);
auto color_TL = Color::from_argb(TL);
return Color(ClampAddSubtractFull(color_L.red(), color_T.red(), color_TL.red()),
ClampAddSubtractFull(color_L.green(), color_T.green(), color_TL.green()),
ClampAddSubtractFull(color_L.blue(), color_T.blue(), color_TL.blue()),
ClampAddSubtractFull(color_L.alpha(), color_T.alpha(), color_TL.alpha()))
.value();
}
case 13: {
// "ClampAddSubtractHalf(Average2(L, T), TL)"
auto color_L = Color::from_argb(L);
auto color_T = Color::from_argb(T);
auto color_TL = Color::from_argb(TL);
return Color(ClampAddSubtractHalf(Average2(color_L.red(), color_T.red()), color_TL.red()),
ClampAddSubtractHalf(Average2(color_L.green(), color_T.green()), color_TL.green()),
ClampAddSubtractHalf(Average2(color_L.blue(), color_T.blue()), color_TL.blue()),
ClampAddSubtractHalf(Average2(color_L.alpha(), color_T.alpha()), color_TL.alpha()))
.value();
}
}
return Error::from_string_literal("WebPImageDecoderPlugin: invalid predictor");
}
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#42_color_transform
class ColorTransform : public Transform {
public:
static ErrorOr<NonnullOwnPtr<ColorTransform>> read(LittleEndianInputBitStream&, IntSize const& image_size);
virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) override;
private:
ColorTransform(int size_bits, NonnullRefPtr<Bitmap> color_bitmap)
: m_size_bits(size_bits)
, m_color_bitmap(move(color_bitmap))
{
}
static i8 ColorTransformDelta(i8 transform, i8 color)
{
return (transform * color) >> 5;
}
static ARGB32 inverse_transform(ARGB32 pixel, ARGB32 transform);
int m_size_bits;
NonnullRefPtr<Bitmap> m_color_bitmap;
};
ErrorOr<NonnullOwnPtr<ColorTransform>> ColorTransform::read(LittleEndianInputBitStream& bit_stream, IntSize const& image_size)
{
// color-image = 3BIT ; sub-pixel code
// entropy-coded-image
int size_bits = TRY(bit_stream.read_bits(3)) + 2;
dbgln_if(WEBP_DEBUG, "color size_bits {}", size_bits);
int block_size = 1 << size_bits;
IntSize color_image_size { ceil_div(image_size.width(), block_size), ceil_div(image_size.height(), block_size) };
auto color_bitmap = TRY(decode_webp_chunk_VP8L_image(ImageKind::EntropyCoded, BitmapFormat::BGRx8888, color_image_size, bit_stream));
return adopt_nonnull_own_or_enomem(new (nothrow) ColorTransform(size_bits, move(color_bitmap)));
}
ErrorOr<NonnullRefPtr<Bitmap>> ColorTransform::transform(NonnullRefPtr<Bitmap> bitmap_ref)
{
Bitmap& bitmap = *bitmap_ref;
for (int y = 0; y < bitmap.height(); ++y) {
ARGB32* bitmap_scanline = bitmap.scanline(y);
int color_y = y >> m_size_bits;
ARGB32* color_scanline = m_color_bitmap->scanline(color_y);
for (int x = 0; x < bitmap.width(); ++x) {
int color_x = x >> m_size_bits;
bitmap_scanline[x] = inverse_transform(bitmap_scanline[x], color_scanline[color_x]);
}
}
return bitmap_ref;
}
ARGB32 ColorTransform::inverse_transform(ARGB32 pixel, ARGB32 transform)
{
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#51_roles_of_image_data
// "Each ColorTransformElement 'cte' is treated as a pixel whose alpha component is 255,
// red component is cte.red_to_blue, green component is cte.green_to_blue
// and blue component is cte.green_to_red."
auto transform_color = Color::from_argb(transform);
i8 red_to_blue = static_cast<i8>(transform_color.red());
i8 green_to_blue = static_cast<i8>(transform_color.green());
i8 green_to_red = static_cast<i8>(transform_color.blue());
auto pixel_color = Color::from_argb(pixel);
// "Transformed values of red and blue components"
int tmp_red = pixel_color.red();
int green = pixel_color.green();
int tmp_blue = pixel_color.blue();
// "Applying the inverse transform is just adding the color transform deltas"
tmp_red += ColorTransformDelta(green_to_red, green);
tmp_blue += ColorTransformDelta(green_to_blue, green);
tmp_blue += ColorTransformDelta(red_to_blue, tmp_red & 0xff);
return Color(tmp_red & 0xff, green, tmp_blue & 0xff, pixel_color.alpha()).value();
}
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#43_subtract_green_transform
class SubtractGreenTransform : public Transform {
public:
virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) override;
};
ErrorOr<NonnullRefPtr<Bitmap>> SubtractGreenTransform::transform(NonnullRefPtr<Bitmap> bitmap)
{
for (ARGB32& pixel : *bitmap) {
Color color = Color::from_argb(pixel);
u8 red = (color.red() + color.green()) & 0xff;
u8 blue = (color.blue() + color.green()) & 0xff;
pixel = Color(red, color.green(), blue, color.alpha()).value();
}
return bitmap;
}
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#44_color_indexing_transform
class ColorIndexingTransform : public Transform {
public:
static ErrorOr<NonnullOwnPtr<ColorIndexingTransform>> read(LittleEndianInputBitStream&, int original_width);
virtual ErrorOr<NonnullRefPtr<Bitmap>> transform(NonnullRefPtr<Bitmap>) override;
// For a color indexing transform, the green channel of the source image is used as the index into a palette to produce an output color.
// If the palette is small enough, several output pixels are bundled into a single input pixel.
// If the palette has just 2 colors, every index needs just a single bit, and the 8 bits of the green channel of one input pixel can encode 8 output pixels.
// If the palette has 3 or 4 colors, every index needs 2 bits and every pixel can encode 4 output pixels.
// If the palette has 5 to 16 colors, every index needs 4 bits and every pixel can encode 2 output pixels.
// This returns how many output pixels one input pixel can encode after the color indexing transform.
//
// This affects all images after the color indexing transform:
// If a webp file contains a 29x32 image and it contains a color indexing transform with a 4-color palette, then the in-memory size of all images
// after the color indexing transform assume a bitmap size of ceil_div(29, 4)x32 = 8x32.
// That is, the sizes of transforms after the color indexing transform are computed relative to the size 8x32,
// the main image's meta prefix image's size (if present) is computed relative to the size 8x32,
// the main image is 8x32, and only applying the color indexing transform resizes the image back to 29x32.
int pixels_per_pixel() const { return m_pixels_per_pixel; }
private:
ColorIndexingTransform(int pixels_per_pixel, int original_width, NonnullRefPtr<Bitmap> palette_bitmap)
: m_pixels_per_pixel(pixels_per_pixel)
, m_original_width(original_width)
, m_palette_bitmap(palette_bitmap)
{
}
int m_pixels_per_pixel;
int m_original_width;
NonnullRefPtr<Bitmap> m_palette_bitmap;
};
ErrorOr<NonnullOwnPtr<ColorIndexingTransform>> ColorIndexingTransform::read(LittleEndianInputBitStream& bit_stream, int original_width)
{
// color-indexing-image = 8BIT ; color count
// entropy-coded-image
int color_table_size = TRY(bit_stream.read_bits(8)) + 1;
dbgln_if(WEBP_DEBUG, "colorindexing color_table_size {}", color_table_size);
IntSize palette_image_size { color_table_size, 1 };
auto palette_bitmap = TRY(decode_webp_chunk_VP8L_image(ImageKind::EntropyCoded, BitmapFormat::BGRA8888, palette_image_size, bit_stream));
// "When the color table is small (equal to or less than 16 colors), several pixels are bundled into a single pixel..."
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;
// "The color table is always subtraction-coded to reduce image entropy. [...] In decoding, every final color in the color table
// can be obtained by adding the previous color component values by each ARGB component separately,
// and storing the least significant 8 bits of the result."
for (ARGB32* pixel = palette_bitmap->begin() + 1; pixel != palette_bitmap->end(); ++pixel)
*pixel = add_argb32(*pixel, pixel[-1]);
return adopt_nonnull_own_or_enomem(new (nothrow) ColorIndexingTransform(pixels_per_pixel, original_width, move(palette_bitmap)));
}
ErrorOr<NonnullRefPtr<Bitmap>> ColorIndexingTransform::transform(NonnullRefPtr<Bitmap> bitmap)
{
if (pixels_per_pixel() == 1) {
for (ARGB32& pixel : *bitmap) {
// "The inverse transform for the image is simply replacing the pixel values (which are indices to the color table)
// with the actual color table values. The indexing is done based on the green component of the ARGB color. [...]
// If the index is equal or larger than color_table_size, the argb color value should be set to 0x00000000 (transparent black)."
u8 index = Color::from_argb(pixel).green();
pixel = index < m_palette_bitmap->width() ? m_palette_bitmap->scanline(0)[index] : 0;
}
return bitmap;
}
// Pixel bundling case.
VERIFY(ceil_div(m_original_width, pixels_per_pixel()) == bitmap->size().width());
IntSize unbundled_size = { m_original_width, bitmap->size().height() };
auto new_bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, unbundled_size));
unsigned bits_per_pixel = 8 / pixels_per_pixel();
unsigned pixel_mask = (1 << bits_per_pixel) - 1;
for (int y = 0; y < bitmap->height(); ++y) {
ARGB32* bitmap_scanline = bitmap->scanline(y);
ARGB32* new_bitmap_scanline = new_bitmap->scanline(y);
for (int x = 0, new_x = 0; x < bitmap->width(); ++x, new_x += pixels_per_pixel()) {
u8 indexes = Color::from_argb(bitmap_scanline[x]).green();
for (int i = 0; i < pixels_per_pixel() && new_x + i < new_bitmap->width(); ++i) {
u8 index = indexes & pixel_mask;
new_bitmap_scanline[new_x + i] = index < m_palette_bitmap->width() ? m_palette_bitmap->scanline(0)[index] : 0;
indexes >>= bits_per_pixel;
}
}
}
return new_bitmap;
}
}
// 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
ErrorOr<NonnullRefPtr<Bitmap>> decode_webp_chunk_VP8L_contents(VP8LHeader const& vp8l_header)
{
FixedMemoryStream memory_stream { vp8l_header.lossless_data };
LittleEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream), LittleEndianInputBitStream::UnsatisfiableReadBehavior::FillWithZero };
// image-stream = optional-transform spatially-coded-image
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#4_transformations
// https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification#72_structure_of_transforms
auto stored_size = IntSize { vp8l_header.width, vp8l_header.height };
// optional-transform = (%b1 transform optional-transform) / %b0
u8 seen_transforms = 0;
Vector<NonnullOwnPtr<Transform>, 4> transforms;
while (TRY(bit_stream.read_bits(1))) {
// transform = predictor-tx / color-tx / subtract-green-tx
// transform =/ color-indexing-tx
TransformType transform_type = static_cast<TransformType>(TRY(bit_stream.read_bits(2)));
dbgln_if(WEBP_DEBUG, "transform type {}", (int)transform_type);
// "Each transform is allowed to be used only once."
u8 mask = 1 << (int)transform_type;
if (seen_transforms & mask)
return Error::from_string_literal("WebPImageDecoderPlugin: transform type used multiple times");
seen_transforms |= mask;
// "Transform data contains the information required to apply the inverse transform and depends on the transform type."
switch (transform_type) {
case PREDICTOR_TRANSFORM:
TRY(transforms.try_append(TRY(PredictorTransform::read(bit_stream, stored_size))));
break;
case COLOR_TRANSFORM:
TRY(transforms.try_append(TRY(ColorTransform::read(bit_stream, stored_size))));
break;
case SUBTRACT_GREEN_TRANSFORM:
TRY(transforms.try_append(TRY(try_make<SubtractGreenTransform>())));
break;
case COLOR_INDEXING_TRANSFORM: {
auto color_indexing_transform = TRY(ColorIndexingTransform::read(bit_stream, stored_size.width()));
// "After reading this transform, image_width is subsampled by width_bits. This affects the size of subsequent transforms."
stored_size.set_width(ceil_div(stored_size.width(), color_indexing_transform->pixels_per_pixel()));
TRY(transforms.try_append(move(color_indexing_transform)));
break;
}
}
}
auto format = vp8l_header.is_alpha_used ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888;
auto bitmap = TRY(decode_webp_chunk_VP8L_image(ImageKind::SpatiallyCoded, format, stored_size, bit_stream));
// "The inverse transforms are applied in the reverse order that they are read from the bitstream, that is, last one first."
for (auto const& transform : transforms.in_reverse())
bitmap = TRY(transform->transform(bitmap));
if (!vp8l_header.is_alpha_used)
bitmap->strip_alpha_channel();
return bitmap;
}
}

View file

@ -1,27 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Span.h>
#include <AK/Types.h>
#include <LibGfx/Bitmap.h>
namespace Gfx {
struct VP8LHeader {
u16 width;
u16 height;
bool is_alpha_used;
ReadonlyBytes lossless_data;
};
// Parses the header data in a VP8L chunk. Pass the payload of a `VP8L` chunk, after the tag and after the tag's data size.
ErrorOr<VP8LHeader> decode_webp_chunk_VP8L_header(ReadonlyBytes vp8l_data);
ErrorOr<NonnullRefPtr<Bitmap>> decode_webp_chunk_VP8L_contents(VP8LHeader const&);
}

File diff suppressed because it is too large Load diff

View file

@ -1,32 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Span.h>
#include <AK/Types.h>
#include <LibGfx/Bitmap.h>
namespace Gfx {
struct VP8Header {
u8 version;
bool show_frame;
u32 size_of_first_partition;
u32 width;
u8 horizontal_scale;
u32 height;
u8 vertical_scale;
ReadonlyBytes first_partition;
ReadonlyBytes second_partition;
};
// Parses the header data in a VP8 chunk. Pass the payload of a `VP8 ` chunk, after the tag and after the tag's data size.
ErrorOr<VP8Header> decode_webp_chunk_VP8_header(ReadonlyBytes vp8_data);
ErrorOr<NonnullRefPtr<Bitmap>> decode_webp_chunk_VP8_contents(VP8Header const&, bool include_alpha_channel);
}

View file

@ -1,732 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
// Contains fixed data tables from the VP8 spec.
namespace Gfx {
using Prob = u8;
using TreeIndex = i8;
// https://datatracker.ietf.org/doc/html/rfc6386#section-10 "Segment-Based Feature Adjustments"
TreeIndex const MACROBLOCK_SEGMENT_TREE[2 * (4 - 1)] = {
2, 4, /* root: "0", "1" subtrees */
-0, -1, /* "00" = 0th value, "01" = 1st value */
-2, -3 /* "10" = 2nd value, "11" = 3rd value */
};
// https://datatracker.ietf.org/doc/html/rfc6386#section-8.2 "Tree Coding Example"
// Repeated in https://datatracker.ietf.org/doc/html/rfc6386#section-11.2 "Luma Modes"
enum IntraMacroblockMode : u8 {
DC_PRED, /* predict DC using row above and column to the left */
V_PRED, /* predict rows using row above */
H_PRED, /* predict columns using column to the left */
TM_PRED, /* propagate second differences a la "True Motion" */
B_PRED, /* each Y subblock is independently predicted */
num_uv_modes = B_PRED, /* first four modes apply to chroma */
num_ymodes /* all modes apply to luma */
};
// https://datatracker.ietf.org/doc/html/rfc6386#section-19.3 says "intra_y_mode selects the luminance intra-prediction mode (Section 16.1)",
// but for keyframes the correct reference is actually https://datatracker.ietf.org/doc/html/rfc6386#section-11.2 "Luma Modes".
// That is, we want "kf_ymode_tree", not "ymode_tree", and "kf_ymode_prob", not "ymode_prob".
// See "decode_kf_mb_mode" in the reference decoder in the spec.
static TreeIndex constexpr KEYFRAME_YMODE_TREE[2 * (num_ymodes - 1)] = {
-B_PRED, 2, /* root: B_PRED = "0", "1" subtree */
4, 6, /* "1" subtree has 2 descendant subtrees */
-DC_PRED, -V_PRED, /* "10" subtree: DC_PRED = "100", V_PRED = "101" */
-H_PRED, -TM_PRED /* "11" subtree: H_PRED = "110", TM_PRED = "111" */
};
static Prob constexpr KEYFRAME_YMODE_PROBABILITIES[num_ymodes - 1] = { 145, 156, 163, 128 };
// https://datatracker.ietf.org/doc/html/rfc6386#section-11.2 "Luma Modes"
enum IntraBlockMode : u8 {
B_DC_PRED, /* predict DC using row above and column
to the left */
B_TM_PRED, /* propagate second differences a la
"True Motion" */
B_VE_PRED, /* predict rows using row above */
B_HE_PRED, /* predict columns using column to the left */
B_LD_PRED, /* southwest (left and down) 45 degree diagonal
prediction */
B_RD_PRED, /* southeast (right and down) "" */
B_VR_PRED, /* SSE (vertical right) diagonal prediction */
B_VL_PRED, /* SSW (vertical left) "" */
B_HD_PRED, /* ESE (horizontal down) "" */
B_HU_PRED, /* ENE (horizontal up) "" */
num_intra_bmodes
};
// clang-format off
static TreeIndex constexpr BLOCK_MODE_TREE[2 * (num_intra_bmodes - 1)] = {
-B_DC_PRED, 2, /* B_DC_PRED = "0" */
-B_TM_PRED, 4, /* B_TM_PRED = "10" */
-B_VE_PRED, 6, /* B_VE_PRED = "110" */
8, 12,
-B_HE_PRED, 10, /* B_HE_PRED = "11100" */
-B_RD_PRED, -B_VR_PRED, /* B_RD_PRED = "111010",
B_VR_PRED = "111011" */
-B_LD_PRED, 14, /* B_LD_PRED = "111110" */
-B_VL_PRED, 16, /* B_VL_PRED = "1111110" */
-B_HD_PRED, -B_HU_PRED /* HD = "11111110",
HU = "11111111" */
};
// clang-format on
// https://datatracker.ietf.org/doc/html/rfc6386#section-11.4 "Chroma Modes"
// clang-format off
static TreeIndex constexpr UV_MODE_TREE[2 * (num_uv_modes - 1)] = {
-DC_PRED, 2, /* root: DC_PRED = "0", "1" subtree */
-V_PRED, 4, /* "1" subtree: V_PRED = "10", "11" subtree */
-H_PRED, -TM_PRED /* "11" subtree: H_PRED = "110", TM_PRED = "111" */
};
// clang-format on
static Prob constexpr KEYFRAME_UV_MODE_PROBABILITIES[num_uv_modes - 1] = { 142, 114, 183 };
// https://datatracker.ietf.org/doc/html/rfc6386#section-11.5 "Subblock Mode Probability Table"
// clang-format off
const Prob KEYFRAME_BLOCK_MODE_PROBABILITIES[num_intra_bmodes][num_intra_bmodes][num_intra_bmodes - 1] = {
{
{ 231, 120, 48, 89, 115, 113, 120, 152, 112 },
{ 152, 179, 64, 126, 170, 118, 46, 70, 95 },
{ 175, 69, 143, 80, 85, 82, 72, 155, 103 },
{ 56, 58, 10, 171, 218, 189, 17, 13, 152 },
{ 144, 71, 10, 38, 171, 213, 144, 34, 26 },
{ 114, 26, 17, 163, 44, 195, 21, 10, 173 },
{ 121, 24, 80, 195, 26, 62, 44, 64, 85 },
{ 170, 46, 55, 19, 136, 160, 33, 206, 71 },
{ 63, 20, 8, 114, 114, 208, 12, 9, 226 },
{ 81, 40, 11, 96, 182, 84, 29, 16, 36 }
},
{
{ 134, 183, 89, 137, 98, 101, 106, 165, 148 },
{ 72, 187, 100, 130, 157, 111, 32, 75, 80 },
{ 66, 102, 167, 99, 74, 62, 40, 234, 128 },
{ 41, 53, 9, 178, 241, 141, 26, 8, 107 },
{ 104, 79, 12, 27, 217, 255, 87, 17, 7 },
{ 74, 43, 26, 146, 73, 166, 49, 23, 157 },
{ 65, 38, 105, 160, 51, 52, 31, 115, 128 },
{ 87, 68, 71, 44, 114, 51, 15, 186, 23 },
{ 47, 41, 14, 110, 182, 183, 21, 17, 194 },
{ 66, 45, 25, 102, 197, 189, 23, 18, 22 }
},
{
{ 88, 88, 147, 150, 42, 46, 45, 196, 205 },
{ 43, 97, 183, 117, 85, 38, 35, 179, 61 },
{ 39, 53, 200, 87, 26, 21, 43, 232, 171 },
{ 56, 34, 51, 104, 114, 102, 29, 93, 77 },
{ 107, 54, 32, 26, 51, 1, 81, 43, 31 },
{ 39, 28, 85, 171, 58, 165, 90, 98, 64 },
{ 34, 22, 116, 206, 23, 34, 43, 166, 73 },
{ 68, 25, 106, 22, 64, 171, 36, 225, 114 },
{ 34, 19, 21, 102, 132, 188, 16, 76, 124 },
{ 62, 18, 78, 95, 85, 57, 50, 48, 51 }
},
{
{ 193, 101, 35, 159, 215, 111, 89, 46, 111 },
{ 60, 148, 31, 172, 219, 228, 21, 18, 111 },
{ 112, 113, 77, 85, 179, 255, 38, 120, 114 },
{ 40, 42, 1, 196, 245, 209, 10, 25, 109 },
{ 100, 80, 8, 43, 154, 1, 51, 26, 71 },
{ 88, 43, 29, 140, 166, 213, 37, 43, 154 },
{ 61, 63, 30, 155, 67, 45, 68, 1, 209 },
{ 142, 78, 78, 16, 255, 128, 34, 197, 171 },
{ 41, 40, 5, 102, 211, 183, 4, 1, 221 },
{ 51, 50, 17, 168, 209, 192, 23, 25, 82 }
},
{
{ 125, 98, 42, 88, 104, 85, 117, 175, 82 },
{ 95, 84, 53, 89, 128, 100, 113, 101, 45 },
{ 75, 79, 123, 47, 51, 128, 81, 171, 1 },
{ 57, 17, 5, 71, 102, 57, 53, 41, 49 },
{ 115, 21, 2, 10, 102, 255, 166, 23, 6 },
{ 38, 33, 13, 121, 57, 73, 26, 1, 85 },
{ 41, 10, 67, 138, 77, 110, 90, 47, 114 },
{ 101, 29, 16, 10, 85, 128, 101, 196, 26 },
{ 57, 18, 10, 102, 102, 213, 34, 20, 43 },
{ 117, 20, 15, 36, 163, 128, 68, 1, 26 }
},
{
{ 138, 31, 36, 171, 27, 166, 38, 44, 229 },
{ 67, 87, 58, 169, 82, 115, 26, 59, 179 },
{ 63, 59, 90, 180, 59, 166, 93, 73, 154 },
{ 40, 40, 21, 116, 143, 209, 34, 39, 175 },
{ 57, 46, 22, 24, 128, 1, 54, 17, 37 },
{ 47, 15, 16, 183, 34, 223, 49, 45, 183 },
{ 46, 17, 33, 183, 6, 98, 15, 32, 183 },
{ 65, 32, 73, 115, 28, 128, 23, 128, 205 },
{ 40, 3, 9, 115, 51, 192, 18, 6, 223 },
{ 87, 37, 9, 115, 59, 77, 64, 21, 47 }
},
{
{ 104, 55, 44, 218, 9, 54, 53, 130, 226 },
{ 64, 90, 70, 205, 40, 41, 23, 26, 57 },
{ 54, 57, 112, 184, 5, 41, 38, 166, 213 },
{ 30, 34, 26, 133, 152, 116, 10, 32, 134 },
{ 75, 32, 12, 51, 192, 255, 160, 43, 51 },
{ 39, 19, 53, 221, 26, 114, 32, 73, 255 },
{ 31, 9, 65, 234, 2, 15, 1, 118, 73 },
{ 88, 31, 35, 67, 102, 85, 55, 186, 85 },
{ 56, 21, 23, 111, 59, 205, 45, 37, 192 },
{ 55, 38, 70, 124, 73, 102, 1, 34, 98 }
},
{
{ 102, 61, 71, 37, 34, 53, 31, 243, 192 },
{ 69, 60, 71, 38, 73, 119, 28, 222, 37 },
{ 68, 45, 128, 34, 1, 47, 11, 245, 171 },
{ 62, 17, 19, 70, 146, 85, 55, 62, 70 },
{ 75, 15, 9, 9, 64, 255, 184, 119, 16 },
{ 37, 43, 37, 154, 100, 163, 85, 160, 1 },
{ 63, 9, 92, 136, 28, 64, 32, 201, 85 },
{ 86, 6, 28, 5, 64, 255, 25, 248, 1 },
{ 56, 8, 17, 132, 137, 255, 55, 116, 128 },
{ 58, 15, 20, 82, 135, 57, 26, 121, 40 }
},
{
{ 164, 50, 31, 137, 154, 133, 25, 35, 218 },
{ 51, 103, 44, 131, 131, 123, 31, 6, 158 },
{ 86, 40, 64, 135, 148, 224, 45, 183, 128 },
{ 22, 26, 17, 131, 240, 154, 14, 1, 209 },
{ 83, 12, 13, 54, 192, 255, 68, 47, 28 },
{ 45, 16, 21, 91, 64, 222, 7, 1, 197 },
{ 56, 21, 39, 155, 60, 138, 23, 102, 213 },
{ 85, 26, 85, 85, 128, 128, 32, 146, 171 },
{ 18, 11, 7, 63, 144, 171, 4, 4, 246 },
{ 35, 27, 10, 146, 174, 171, 12, 26, 128 }
},
{
{ 190, 80, 35, 99, 180, 80, 126, 54, 45 },
{ 85, 126, 47, 87, 176, 51, 41, 20, 32 },
{ 101, 75, 128, 139, 118, 146, 116, 128, 85 },
{ 56, 41, 15, 176, 236, 85, 37, 9, 62 },
{ 146, 36, 19, 30, 171, 255, 97, 27, 20 },
{ 71, 30, 17, 119, 118, 255, 17, 18, 138 },
{ 101, 38, 60, 138, 55, 70, 43, 26, 142 },
{ 138, 45, 61, 62, 219, 1, 81, 188, 64 },
{ 32, 41, 20, 117, 151, 142, 20, 21, 163 },
{ 112, 19, 12, 61, 195, 128, 48, 4, 24 }
}
};
// clang-format on
// https://datatracker.ietf.org/doc/html/rfc6386#section-13.2 "Coding of Individual Coefficient Values"
enum DCTToken {
DCT_0, /* value 0 */
DCT_1, /* 1 */
DCT_2, /* 2 */
DCT_3, /* 3 */
DCT_4, /* 4 */
dct_cat1, /* range 5 - 6 (size 2) */
dct_cat2, /* 7 - 10 (4) */
dct_cat3, /* 11 - 18 (8) */
dct_cat4, /* 19 - 34 (16) */
dct_cat5, /* 35 - 66 (32) */
dct_cat6, /* 67 - 2048 (1982) */
dct_eob, /* end of block */
num_dct_tokens /* 12 */
};
// clang-format off
const TreeIndex COEFFICIENT_TREE[2 * (num_dct_tokens - 1)] = {
-dct_eob, 2, /* eob = "0" */
-DCT_0, 4, /* 0 = "10" */
-DCT_1, 6, /* 1 = "110" */
8, 12,
-DCT_2, 10, /* 2 = "11100" */
-DCT_3, -DCT_4, /* 3 = "111010", 4 = "111011" */
14, 16,
-dct_cat1, -dct_cat2, /* cat1 = "111100",
cat2 = "111101" */
18, 20,
-dct_cat3, -dct_cat4, /* cat3 = "1111100",
cat4 = "1111101" */
-dct_cat5, -dct_cat6 /* cat4 = "1111110",
cat4 = "1111111" */
};
// clang-format on
// https://datatracker.ietf.org/doc/html/rfc6386#section-13.4 "Token Probability Updates"
// clang-format off
static Prob constexpr COEFFICIENT_UPDATE_PROBABILITIES[4][8][3][num_dct_tokens - 1] = {
{
{
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255 },
{ 250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255 },
{ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
}
},
{
{
{ 217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255 },
{ 234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255 }
},
{
{ 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
}
},
{
{
{ 186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255 },
{ 251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255 }
},
{
{ 255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
}
},
{
{
{ 248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255 },
{ 248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
},
{
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }
}
}
};
// clang-format on
// https://datatracker.ietf.org/doc/html/rfc6386#section-13.5 "Default Token Probability Table"
// clang-format off
static Prob constexpr DEFAULT_COEFFICIENT_PROBABILITIES[4][8][3][num_dct_tokens - 1] = {
{
{
{ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
},
{
{ 253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128 },
{ 189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128 },
{ 106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128 },
},
{
{ 1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128 },
{ 181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128 },
{ 78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128 },
},
{
{ 1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128 },
{ 184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128 },
{ 77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128 },
},
{
{ 1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128 },
{ 170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128 },
{ 37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128 },
},
{
{ 1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128 },
{ 207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128 },
{ 102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128 },
},
{
{ 1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128 },
{ 177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128 },
{ 80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128 },
},
{
{ 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
},
},
{
{
{ 198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62 },
{ 131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1 },
{ 68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128 },
},
{
{ 1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128 },
{ 184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128 },
{ 81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128 },
},
{
{ 1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128 },
{ 99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128 },
{ 23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128 },
},
{
{ 1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128 },
{ 109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128 },
{ 44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128 },
},
{
{ 1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128 },
{ 94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128 },
{ 22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128 },
},
{
{ 1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128 },
{ 124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128 },
{ 35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128 },
},
{
{ 1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128 },
{ 121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128 },
{ 45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128 },
},
{
{ 1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128 },
{ 203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128 },
{ 137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128 },
},
},
{
{
{ 253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128 },
{ 175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128 },
{ 73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128 },
},
{
{ 1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128 },
{ 239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128 },
{ 155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128 },
},
{
{ 1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128 },
{ 201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128 },
{ 69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128 },
},
{
{ 1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128 },
{ 223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128 },
{ 141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128 },
},
{
{ 1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128 },
{ 190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128 },
{ 149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
},
{
{ 1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
},
{
{ 1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128 },
{ 213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128 },
{ 55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
},
{
{ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 },
},
},
{
{
{ 202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255 },
{ 126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128 },
{ 61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128 },
},
{
{ 1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128 },
{ 166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128 },
{ 39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128 },
},
{
{ 1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128 },
{ 124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128 },
{ 24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128 },
},
{
{ 1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128 },
{ 149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128 },
{ 28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128 },
},
{
{ 1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128 },
{ 123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128 },
{ 20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128 },
},
{
{ 1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128 },
{ 168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128 },
{ 47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128 },
},
{
{ 1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128 },
{ 141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128 },
{ 42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128 },
},
{
{ 1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
{ 238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128 },
},
},
};
// clang-format on
// https://datatracker.ietf.org/doc/html/rfc6386#section-14.1 "Dequantization"
// clang-format off
static int constexpr dc_qlookup[] = {
4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15,
16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, 23,
24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 91, 93, 95, 96, 98, 100, 101, 102,
104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130,
132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
};
static int constexpr ac_qlookup[] = {
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78,
80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104,
106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137,
140, 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177,
181, 185, 189, 193, 197, 201, 205, 209, 213, 217, 221, 225, 229,
234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
};
// clang-format on
// https://datatracker.ietf.org/doc/html/rfc6386#section-14.3 "Implementation of the WHT Inversion"
inline void vp8_short_inv_walsh4x4_c(i16 const* input, i16* output)
{
i16 const* ip = input;
i16* op = output;
for (int i = 0; i < 4; i++) {
int a1 = ip[0] + ip[12];
int b1 = ip[4] + ip[8];
int c1 = ip[4] - ip[8];
int d1 = ip[0] - ip[12];
op[0] = a1 + b1;
op[4] = c1 + d1;
op[8] = a1 - b1;
op[12] = d1 - c1;
ip++;
op++;
}
ip = output;
op = output;
for (int i = 0; i < 4; i++) {
int a1 = ip[0] + ip[3];
int b1 = ip[1] + ip[2];
int c1 = ip[1] - ip[2];
int d1 = ip[0] - ip[3];
int a2 = a1 + b1;
int b2 = c1 + d1;
int c2 = a1 - b1;
int d2 = d1 - c1;
op[0] = (a2 + 3) >> 3;
op[1] = (b2 + 3) >> 3;
op[2] = (c2 + 3) >> 3;
op[3] = (d2 + 3) >> 3;
ip += 4;
op += 4;
}
}
// https://datatracker.ietf.org/doc/html/rfc6386#section-14.4 "Implementation of the DCT Inversion"
inline void short_idct4x4llm_c(i16 const* input, i16* output, int pitch)
{
static constexpr int cospi8sqrt2minus1 = 20091;
static constexpr int sinpi8sqrt2 = 35468;
i16 const* ip = input;
i16* op = output;
int shortpitch = pitch >> 1;
for (int i = 0; i < 4; i++) {
int a1 = ip[0] + ip[8];
int b1 = ip[0] - ip[8];
int temp1 = (ip[4] * sinpi8sqrt2) >> 16;
int temp2 = ip[12] + ((ip[12] * cospi8sqrt2minus1) >> 16);
int c1 = temp1 - temp2;
temp1 = ip[4] + ((ip[4] * cospi8sqrt2minus1) >> 16);
temp2 = (ip[12] * sinpi8sqrt2) >> 16;
int d1 = temp1 + temp2;
op[shortpitch * 0] = a1 + d1;
op[shortpitch * 3] = a1 - d1;
op[shortpitch * 1] = b1 + c1;
op[shortpitch * 2] = b1 - c1;
ip++;
op++;
}
ip = output;
op = output;
for (int i = 0; i < 4; i++) {
int a1 = ip[0] + ip[2];
int b1 = ip[0] - ip[2];
int temp1 = (ip[1] * sinpi8sqrt2) >> 16;
int temp2 = ip[3] + ((ip[3] * cospi8sqrt2minus1) >> 16);
int c1 = temp1 - temp2;
temp1 = ip[1] + ((ip[1] * cospi8sqrt2minus1) >> 16);
temp2 = (ip[3] * sinpi8sqrt2) >> 16;
int d1 = temp1 + temp2;
op[0] = (a1 + d1 + 4) >> 3;
op[3] = (a1 - d1 + 4) >> 3;
op[1] = (b1 + c1 + 4) >> 3;
op[2] = (b1 - c1 + 4) >> 3;
ip += shortpitch;
op += shortpitch;
}
}
}

View file

@ -19,6 +19,14 @@
"dav1d"
]
},
{
"name": "libwebp",
"features": [
"anim",
"libwebpmux",
"simd"
]
},
"simdutf",
{
"name": "skia",
@ -70,6 +78,10 @@
"name": "libavif",
"version": "1.0.4#1"
},
{
"name": "libwebp",
"version": "1.4.0#1"
},
{
"name": "simdutf",
"version": "5.2.5#0"