diff --git a/Tests/LibGfx/TestImageDecoder.cpp b/Tests/LibGfx/TestImageDecoder.cpp index a0b6107d796..4ccc5af2213 100644 --- a/Tests/LibGfx/TestImageDecoder.cpp +++ b/Tests/LibGfx/TestImageDecoder.cpp @@ -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) diff --git a/Userland/Libraries/LibGfx/CMakeLists.txt b/Userland/Libraries/LibGfx/CMakeLists.txt index c2d09a1bd6c..bc3900d57cb 100644 --- a/Userland/Libraries/LibGfx/CMakeLists.txt +++ b/Userland/Libraries/LibGfx/CMakeLists.txt @@ -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) diff --git a/Userland/Libraries/LibGfx/ImageFormats/WebPLoader.cpp b/Userland/Libraries/LibGfx/ImageFormats/WebPLoader.cpp index a2b45591a55..9efa648fdec 100644 --- a/Userland/Libraries/LibGfx/ImageFormats/WebPLoader.cpp +++ b/Userland/Libraries/LibGfx/ImageFormats/WebPLoader.cpp @@ -1,595 +1,41 @@ /* * Copyright (c) 2023, Nico Weber + * Copyright (c) 2024, doctortheemh * * SPDX-License-Identifier: BSD-2-Clause */ -#include -#include -#include -#include -#include -#include +#include #include -#include -#include -#include -#include -#include -#include -// Overview: https://developers.google.com/speed/webp/docs/compression -// Container: https://developers.google.com/speed/webp/docs/riff_container +#include +#include +#include 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 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 size; - - RefPtr bitmap; - - // Either 'VP8 ' (simple lossy file), 'VP8L' (simple lossless file), or 'VP8X' (extended file). - Optional 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 image_data; - - Optional animation_header_chunk; // 'ANIM' - Vector animation_frame_chunks; // 'ANMF' - - // These are set in state >= AnimationFrameChunksDecoded, if first_chunk.type == 'VP8X' && vp8x_header.has_animation. - Optional animation_header_chunk_data; - Optional> animation_frame_chunks_data; - size_t current_frame { 0 }; - - Optional iccp_chunk; // 'ICCP' - Optional exif_chunk; // 'EXIF' - Optional xmp_chunk; // 'XMP ' + Vector frame_descriptors; }; -// https://developers.google.com/speed/webp/docs/riff_container#webp_file_header -static ErrorOr decode_webp_header(WebPLoadingContext& context) -{ - if (context.state >= WebPLoadingContext::HeaderDecoded) - return {}; - - FixedMemoryStream header_stream { context.data }; - auto header = TRY(header_stream.read_value()); - 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 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(bitmap.width()), static_cast(bitmap.height()), /*is_alpha_used=*/false, alpha_data }; - auto lossless_bitmap = TRY(decode_webp_chunk_VP8L_contents(vp8l_header)); - - if (pixel_count != static_cast(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 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 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 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((flags >> 1) & 1); - auto disposal_method = static_cast(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 decode_webp_set_image_data(Optional alpha, Optional 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 decode_webp_extended(WebPLoadingContext& context, ReadonlyBytes chunks) -{ - VERIFY(context.first_chunk->id() == "VP8X"sv); - - Optional 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 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 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 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 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 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 decode_webp_animation_frame_image_data(ANMFChunk const& frame) -{ - ReadonlyBytes chunks = frame.frame_data; - auto chunk = TRY(RIFF::Chunk::decode_and_advance(chunks)); - - Optional 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> 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 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(frame_bitmap->width()) != frame_description.frame_width || static_cast(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(context.animation_frame_chunks_data.value()[frame_index].header.frame_duration_in_milliseconds) }; -} - WebPImageDecoderPlugin::WebPImageDecoderPlugin(ReadonlyBytes data, OwnPtr context) : m_context(move(context)) { @@ -598,27 +44,129 @@ WebPImageDecoderPlugin::WebPImageDecoderPlugin(ReadonlyBytes data, OwnPtr 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 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 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, ×tamp)) + 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> WebPImageDecoderPlugin::create(Readon auto context = TRY(try_make()); 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 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 { - 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(bitmap->width()) != m_context->vp8x_header.width || static_cast(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> 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 {}; } } diff --git a/Userland/Libraries/LibGfx/ImageFormats/WebPLoader.h b/Userland/Libraries/LibGfx/ImageFormats/WebPLoader.h index 215e677fdd0..cc9ae2716f1 100644 --- a/Userland/Libraries/LibGfx/ImageFormats/WebPLoader.h +++ b/Userland/Libraries/LibGfx/ImageFormats/WebPLoader.h @@ -29,8 +29,6 @@ public: virtual ErrorOr> icc_data() override; private: - bool set_error(ErrorOr const&); - WebPImageDecoderPlugin(ReadonlyBytes, OwnPtr); OwnPtr m_context; diff --git a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossless.cpp b/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossless.cpp deleted file mode 100644 index 67610c600e4..00000000000 --- a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossless.cpp +++ /dev/null @@ -1,923 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// 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 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(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 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 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(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 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 const alphabet_sizes { 256 + 24 + static_cast(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> 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 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 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 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 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 { - // 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(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> transform(NonnullRefPtr) = 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> read(LittleEndianInputBitStream&, IntSize const& image_size); - virtual ErrorOr> transform(NonnullRefPtr) override; - -private: - PredictorTransform(int size_bits, NonnullRefPtr 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 predict(u8 predictor, ARGB32 TL, ARGB32 T, ARGB32 TR, ARGB32 L); - - int m_size_bits; - NonnullRefPtr m_predictor_bitmap; -}; - -ErrorOr> 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> PredictorTransform::transform(NonnullRefPtr 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 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> read(LittleEndianInputBitStream&, IntSize const& image_size); - virtual ErrorOr> transform(NonnullRefPtr) override; - -private: - ColorTransform(int size_bits, NonnullRefPtr 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 m_color_bitmap; -}; - -ErrorOr> 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> ColorTransform::transform(NonnullRefPtr 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(transform_color.red()); - i8 green_to_blue = static_cast(transform_color.green()); - i8 green_to_red = static_cast(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> transform(NonnullRefPtr) override; -}; - -ErrorOr> SubtractGreenTransform::transform(NonnullRefPtr 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> read(LittleEndianInputBitStream&, int original_width); - virtual ErrorOr> transform(NonnullRefPtr) 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 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 m_palette_bitmap; -}; - -ErrorOr> 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> ColorIndexingTransform::transform(NonnullRefPtr 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> decode_webp_chunk_VP8L_contents(VP8LHeader const& vp8l_header) -{ - FixedMemoryStream memory_stream { vp8l_header.lossless_data }; - LittleEndianInputBitStream bit_stream { MaybeOwned(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, 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(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()))); - 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; -} - -} diff --git a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossless.h b/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossless.h deleted file mode 100644 index 76c17dcd36a..00000000000 --- a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossless.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include -#include -#include - -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 decode_webp_chunk_VP8L_header(ReadonlyBytes vp8l_data); - -ErrorOr> decode_webp_chunk_VP8L_contents(VP8LHeader const&); - -} diff --git a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossy.cpp b/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossy.cpp deleted file mode 100644 index 87ab9e713e2..00000000000 --- a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossy.cpp +++ /dev/null @@ -1,1295 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -// Lossy format: https://datatracker.ietf.org/doc/html/rfc6386 - -// Summary: -// A lossy webp image is a VP8 keyframe. -// A VP8 keyframe consists of 16x16 pixel tiles called macroblocks. Each macroblock is subdivided into 4x4 pixel tiles called subblocks. -// Pixel values are stored as YUV 4:2:0. That is, each 4x4 luma pixels are covered by 1 pixel U chroma and 1 pixel V chroma. -// This means one macroblock is covered by 4x4 Y subblocks and 2x2 U and V subblocks each. -// VP8 data consists of: -// * A tiny bit of uncompressed data, storing image dimensions and the size of the first compressed chunk of data, called the first partition -// * The first partition, which is a entropy-coded bitstream storing: -// 1. A fixed-size header. -// The main piece of data this stores is a probability distribution for how pixel values of each macroblock are predicted from previously decoded data. -// It also stores how may independent entropy-coded bitstreams are used to store the actual pixel data (for all images I've seen so far, just one). -// 2. For each macroblock, it stores how that macroblock's pixel values are predicted from previously decoded data (and some more per-macroblock metadata). -// There are independent prediction modes for Y, U, V. -// U and V store a single prediction mode per macroblock. -// Y can store a single prediction mode per macroblock, or it can store one subblock prediction mode for each of the 4x4 luma subblocks. -// * One or more additional entropy-coded bitstreams ("partitions") that store the discrete cosine transform ("DCT") coefficients for the actual pixel data for each macroblock. -// Each macroblock is subdivided into 4x4 tiles called "subblocks". A 16x16 pixel macroblock consists of: -// 0. If the macroblock stores 4x4 luma subblock prediction modes, the 4x4 DC coefficients of each subblock's DCT are stored at the start of the macroblock's data, -// as coefficients of an inverse Walsh-Hadamard Transform (WHT). -// 1. 4x4 luma subblocks -// 2. 2x2 U chrome subblocks -// 3. 2x2 U chrome subblocks -// That is, each macroblock stores 24 or 25 sets of coefficients. -// Each set of coefficients stores 16 numbers, using a combination of a custom prefix tree and dequantization. -// The inverse DCT output is added to the output of the prediction. - -namespace Gfx { - -// https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossy -// https://datatracker.ietf.org/doc/html/rfc6386#section-19 "Annex A: Bitstream Syntax" -ErrorOr decode_webp_chunk_VP8_header(ReadonlyBytes vp8_data) -{ - if (vp8_data.size() < 10) - return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk too small"); - - // FIXME: Eventually, this should probably call into LibVideo/VP8, - // and image decoders should move into LibImageDecoders which depends on both LibGfx and LibVideo. - // (LibVideo depends on LibGfx, so LibGfx can't depend on LibVideo itself.) - - // https://datatracker.ietf.org/doc/html/rfc6386#section-4 "Overview of Compressed Data Format" - // "The decoder is simply presented with a sequence of compressed frames [...] - // The first frame presented to the decompressor is [...] a key frame. [...] - // [E]very compressed frame has three or more pieces. It begins with an uncompressed data chunk comprising 10 bytes in the case of key frames" - - u8 const* data = vp8_data.data(); - - // https://datatracker.ietf.org/doc/html/rfc6386#section-9.1 "Uncompressed Data Chunk" - u32 frame_tag = data[0] | (data[1] << 8) | (data[2] << 16); - bool is_key_frame = (frame_tag & 1) == 0; // https://www.rfc-editor.org/errata/eid5534 - u8 version = (frame_tag & 0xe) >> 1; - bool show_frame = (frame_tag & 0x10) != 0; - u32 size_of_first_partition = frame_tag >> 5; - - if (!is_key_frame) - return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk not a key frame"); - - if (!show_frame) - return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk has invalid visibility for webp image"); - - if (version > 3) - return Error::from_string_literal("WebPImageDecoderPlugin: unknown version number in 'VP8 ' chunk"); - - u32 start_code = data[3] | (data[4] << 8) | (data[5] << 16); - if (start_code != 0x2a019d) // https://www.rfc-editor.org/errata/eid7370 - return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk invalid start_code"); - - // "The scaling specifications for each dimension are encoded as follows. - // 0 | No upscaling (the most common case). - // 1 | Upscale by 5/4. - // 2 | Upscale by 5/3. - // 3 | Upscale by 2." - // This is a display-time operation and doesn't affect decoding." - u16 width_and_horizontal_scale = data[6] | (data[7] << 8); - u16 width = width_and_horizontal_scale & 0x3fff; - u8 horizontal_scale = width_and_horizontal_scale >> 14; - - u16 heigth_and_vertical_scale = data[8] | (data[9] << 8); - u16 height = heigth_and_vertical_scale & 0x3fff; - u8 vertical_scale = heigth_and_vertical_scale >> 14; - - dbgln_if(WEBP_DEBUG, "version {}, show_frame {}, size_of_first_partition {}, width {}, horizontal_scale {}, height {}, vertical_scale {}", - version, show_frame, size_of_first_partition, width, horizontal_scale, height, vertical_scale); - - if (vp8_data.size() < 10 + size_of_first_partition) - return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk too small for full first partition"); - - return VP8Header { version, show_frame, size_of_first_partition, width, horizontal_scale, height, vertical_scale, vp8_data.slice(10, size_of_first_partition), vp8_data.slice(10 + size_of_first_partition) }; -} - -namespace { - -// Reads n bits followed by a sign bit (0: positive, 1: negative). -i8 read_signed_literal(BooleanDecoder& decoder, u8 n) -{ - VERIFY(n <= 7); - i8 i = decoder.read_literal(n); - if (decoder.read_literal(1)) - i = -i; - return i; -} - -// https://datatracker.ietf.org/doc/html/rfc6386#section-19 "Annex A: Bitstream Syntax" -#define L(n) decoder.read_literal(n) -#define B(prob) decoder.read_bool(prob) -#define L_signed(n) read_signed_literal(decoder, n) - -// https://datatracker.ietf.org/doc/html/rfc6386#section-9.3 Segment-Based Adjustments" -// https://datatracker.ietf.org/doc/html/rfc6386#section-19.2 "Frame Header" -enum class SegmentFeatureMode { - // Spec 19.2 says 0 is delta, 1 absolute; spec 9.3 has it the other way round. 19.2 is correct. - // https://www.rfc-editor.org/errata/eid7519 - DeltaValueMode = 0, - AbsoluteValueMode = 1, - -}; -struct Segmentation { - bool update_macroblock_segmentation_map { false }; - SegmentFeatureMode segment_feature_mode { SegmentFeatureMode::DeltaValueMode }; - - i8 quantizer_update_value[4] {}; - i8 loop_filter_update_value[4] {}; - - u8 macroblock_segment_tree_probabilities[3] = { 255, 255, 255 }; -}; -Segmentation decode_VP8_frame_header_segmentation(BooleanDecoder&); - -// Also https://datatracker.ietf.org/doc/html/rfc6386#section-9.6 "Dequantization Indices" -struct QuantizationIndices { - u8 y_ac { 0 }; - i8 y_dc_delta { 0 }; - - i8 y2_dc_delta { 0 }; - i8 y2_ac_delta { 0 }; - - i8 uv_dc_delta { 0 }; - i8 uv_ac_delta { 0 }; -}; -QuantizationIndices decode_VP8_frame_header_quantization_indices(BooleanDecoder&); - -struct LoopFilterAdjustment { - bool enable_loop_filter_adjustment { false }; - i8 ref_frame_delta[4] {}; - i8 mb_mode_delta[4] {}; -}; -LoopFilterAdjustment decode_VP8_frame_header_loop_filter_adjustment(BooleanDecoder&); - -using CoefficientProbabilities = Prob[4][8][3][num_dct_tokens - 1]; -ErrorOr decode_VP8_frame_header_coefficient_probabilities(BooleanDecoder&, CoefficientProbabilities); - -// https://datatracker.ietf.org/doc/html/rfc6386#section-15 "Loop Filter" -// "The first is a flag (filter_type) selecting the type of filter (normal or simple)" -enum class FilterType { - Normal = 0, - Simple = 1, -}; - -// https://datatracker.ietf.org/doc/html/rfc6386#section-9.2 "Color Space and Pixel Type (Key Frames Only)" -enum class ColorSpaceAndPixelType { - YUV = 0, - ReservedForFutureUse = 1, -}; -enum class ClampingSpecification { - DecoderMustClampTo0To255 = 0, - NoClampingNecessary = 1, -}; - -// https://datatracker.ietf.org/doc/html/rfc6386#section-19.2 "Frame Header" -struct FrameHeader { - ColorSpaceAndPixelType color_space {}; - ClampingSpecification clamping_type {}; - - bool is_segmentation_enabled {}; - Segmentation segmentation {}; - - FilterType filter_type {}; - u8 loop_filter_level {}; - u8 sharpness_level {}; - LoopFilterAdjustment loop_filter_adjustment {}; - - u8 number_of_dct_partitions {}; - - QuantizationIndices quantization_indices {}; - - CoefficientProbabilities coefficient_probabilities; - - bool enable_skipping_of_macroblocks_containing_only_zero_coefficients {}; - u8 probability_skip_false; -}; - -ErrorOr decode_VP8_frame_header(BooleanDecoder& decoder) -{ - // https://datatracker.ietf.org/doc/html/rfc6386#section-19.2 "Frame Header" - FrameHeader header; - - // In the VP8 spec, this is in an `if (key_frames)`, but webp files only have key frames. - header.color_space = ColorSpaceAndPixelType { L(1) }; - header.clamping_type = ClampingSpecification { L(1) }; - dbgln_if(WEBP_DEBUG, "color_space {} clamping_type {}", (int)header.color_space, (int)header.clamping_type); - - // https://datatracker.ietf.org/doc/html/rfc6386#section-9.3 "Segment-Based Adjustments" - header.is_segmentation_enabled = L(1); - dbgln_if(WEBP_DEBUG, "segmentation_enabled {}", header.is_segmentation_enabled); - - if (header.is_segmentation_enabled) - header.segmentation = decode_VP8_frame_header_segmentation(decoder); - - header.filter_type = FilterType { L(1) }; - header.loop_filter_level = L(6); - header.sharpness_level = L(3); - dbgln_if(WEBP_DEBUG, "filter_type {} loop_filter_level {} sharpness_level {}", (int)header.filter_type, header.loop_filter_level, header.sharpness_level); - - header.loop_filter_adjustment = decode_VP8_frame_header_loop_filter_adjustment(decoder); - - u8 log2_nbr_of_dct_partitions = L(2); - dbgln_if(WEBP_DEBUG, "log2_nbr_of_dct_partitions {}", log2_nbr_of_dct_partitions); - header.number_of_dct_partitions = 1 << log2_nbr_of_dct_partitions; - - header.quantization_indices = decode_VP8_frame_header_quantization_indices(decoder); - - // In the VP8 spec, this is in an `if (key_frames)` followed by a lengthy `else`, but webp files only have key frames. - u8 refresh_entropy_probs = L(1); // Has no effect in webp files. - dbgln_if(WEBP_DEBUG, "refresh_entropy_probs {}", refresh_entropy_probs); - - memcpy(header.coefficient_probabilities, DEFAULT_COEFFICIENT_PROBABILITIES, sizeof(header.coefficient_probabilities)); - TRY(decode_VP8_frame_header_coefficient_probabilities(decoder, header.coefficient_probabilities)); - - // https://datatracker.ietf.org/doc/html/rfc6386#section-9.11 "Remaining Frame Header Data (Key Frame)" - header.enable_skipping_of_macroblocks_containing_only_zero_coefficients = L(1); - dbgln_if(WEBP_DEBUG, "mb_no_skip_coeff {}", header.enable_skipping_of_macroblocks_containing_only_zero_coefficients); - if (header.enable_skipping_of_macroblocks_containing_only_zero_coefficients) { - header.probability_skip_false = L(8); - dbgln_if(WEBP_DEBUG, "prob_skip_false {}", header.probability_skip_false); - } - - // In the VP8 spec, there is a length `if (!key_frames)` here, but webp files only have key frames. - - return header; -} - -Segmentation decode_VP8_frame_header_segmentation(BooleanDecoder& decoder) -{ - // Corresponds to "update_segmentation()" in section 19.2 of the spec. - Segmentation segmentation; - - segmentation.update_macroblock_segmentation_map = L(1); - u8 update_segment_feature_data = L(1); - - dbgln_if(WEBP_DEBUG, "update_mb_segmentation_map {} update_segment_feature_data {}", - segmentation.update_macroblock_segmentation_map, update_segment_feature_data); - - if (update_segment_feature_data) { - segmentation.segment_feature_mode = static_cast(L(1)); - dbgln_if(WEBP_DEBUG, "segment_feature_mode {}", (int)segmentation.segment_feature_mode); - - for (int i = 0; i < 4; ++i) { - u8 quantizer_update = L(1); - dbgln_if(WEBP_DEBUG, "quantizer_update {}", quantizer_update); - if (quantizer_update) { - i8 quantizer_update_value = L_signed(7); - dbgln_if(WEBP_DEBUG, "quantizer_update_value {}", quantizer_update_value); - segmentation.quantizer_update_value[i] = quantizer_update_value; - } - } - for (int i = 0; i < 4; ++i) { - u8 loop_filter_update = L(1); - dbgln_if(WEBP_DEBUG, "loop_filter_update {}", loop_filter_update); - if (loop_filter_update) { - i8 loop_filter_update_value = L_signed(6); - dbgln_if(WEBP_DEBUG, "loop_filter_update_value {}", loop_filter_update_value); - segmentation.loop_filter_update_value[i] = loop_filter_update_value; - } - } - } - - if (segmentation.update_macroblock_segmentation_map) { - // This reads mb_segment_tree_probs for https://datatracker.ietf.org/doc/html/rfc6386#section-10. - for (int i = 0; i < 3; ++i) { - u8 segment_prob_update = L(1); - dbgln_if(WEBP_DEBUG, "segment_prob_update {}", segment_prob_update); - if (segment_prob_update) { - u8 segment_prob = L(8); - dbgln_if(WEBP_DEBUG, "segment_prob {}", segment_prob); - segmentation.macroblock_segment_tree_probabilities[i] = segment_prob; - } - } - } - - return segmentation; -} - -QuantizationIndices decode_VP8_frame_header_quantization_indices(BooleanDecoder& decoder) -{ - // Corresponds to "quant_indices()" in section 19.2 of the spec. - QuantizationIndices quantization_indices; - - // "The first 7-bit index gives the dequantization table index for - // Y-plane AC coefficients, called yac_qi. It is always coded and acts - // as a baseline for the other 5 quantization indices, each of which is - // represented by a delta from this baseline index." - quantization_indices.y_ac = L(7); - dbgln_if(WEBP_DEBUG, "y_ac_qi {}", quantization_indices.y_ac); - - auto read_delta = [&decoder](StringView name, i8* destination) -> void { - u8 is_present = L(1); - dbgln_if(WEBP_DEBUG, "{}_present {}", name, is_present); - if (is_present) { - i8 delta = L_signed(4); - dbgln_if(WEBP_DEBUG, "{} {}", name, delta); - *destination = delta; - } - }; - read_delta("y_dc_delta"sv, &quantization_indices.y_dc_delta); - read_delta("y2_dc_delta"sv, &quantization_indices.y2_dc_delta); - read_delta("y2_ac_delta"sv, &quantization_indices.y2_ac_delta); - read_delta("uv_dc_delta"sv, &quantization_indices.uv_dc_delta); - read_delta("uv_ac_delta"sv, &quantization_indices.uv_ac_delta); - - return quantization_indices; -} - -LoopFilterAdjustment decode_VP8_frame_header_loop_filter_adjustment(BooleanDecoder& decoder) -{ - // Corresponds to "mb_lf_adjustments()" in section 19.2 of the spec. - LoopFilterAdjustment adjustment; - - adjustment.enable_loop_filter_adjustment = L(1); - if (adjustment.enable_loop_filter_adjustment) { - u8 mode_ref_lf_delta_update = L(1); - dbgln_if(WEBP_DEBUG, "mode_ref_lf_delta_update {}", mode_ref_lf_delta_update); - if (mode_ref_lf_delta_update) { - for (int i = 0; i < 4; ++i) { - u8 ref_frame_delta_update_flag = L(1); - dbgln_if(WEBP_DEBUG, "ref_frame_delta_update_flag {}", ref_frame_delta_update_flag); - if (ref_frame_delta_update_flag) { - i8 delta = L_signed(6); - dbgln_if(WEBP_DEBUG, "delta {}", delta); - adjustment.ref_frame_delta[i] = delta; - } - } - for (int i = 0; i < 4; ++i) { - u8 mb_mode_delta_update_flag = L(1); - dbgln_if(WEBP_DEBUG, "mb_mode_delta_update_flag {}", mb_mode_delta_update_flag); - if (mb_mode_delta_update_flag) { - i8 delta = L_signed(6); - dbgln_if(WEBP_DEBUG, "delta {}", delta); - adjustment.mb_mode_delta[i] = delta; - } - } - } - } - - return adjustment; -} - -ErrorOr decode_VP8_frame_header_coefficient_probabilities(BooleanDecoder& decoder, CoefficientProbabilities coefficient_probabilities) -{ - // Corresponds to "token_prob_update()" in section 19.2 of the spec. - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 8; j++) { - for (int k = 0; k < 3; k++) { - for (int l = 0; l < 11; l++) { - // token_prob_update() says L(1) and L(8), but it's actually B(p) and L(8). - // https://datatracker.ietf.org/doc/html/rfc6386#section-13.4 "Token Probability Updates" describes it correctly. - if (B(COEFFICIENT_UPDATE_PROBABILITIES[i][j][k][l])) - coefficient_probabilities[i][j][k][l] = L(8); - } - } - } - } - - return {}; -} - -// https://datatracker.ietf.org/doc/html/rfc6386#section-8.1 "Tree Coding Implementation" -u8 tree_decode(BooleanDecoder& decoder, ReadonlySpan tree, ReadonlyBytes probabilities, TreeIndex initial_i = 0) -{ - TreeIndex i = initial_i; - while (true) { - u8 b = B(probabilities[i >> 1]); - i = tree[i + b]; - if (i <= 0) - return -i; - } -} - -// Similar to BlockContext in LibVideo/VP9/Context.h -struct MacroblockMetadata { - // https://datatracker.ietf.org/doc/html/rfc6386#section-10 "Segment-Based Feature Adjustments" - // Read only if `update_mb_segmentation_map` is set. - u8 segment_id { 0 }; // 0, 1, 2, or 3. Fits in two bits. - - // https://datatracker.ietf.org/doc/html/rfc6386#section-11.1 "mb_skip_coeff" - bool skip_coefficients { false }; - - IntraMacroblockMode intra_y_mode; - IntraMacroblockMode uv_mode; - - IntraBlockMode intra_b_modes[16]; -}; - -ErrorOr> decode_VP8_macroblock_metadata(BooleanDecoder& decoder, FrameHeader const& header, int macroblock_width, int macroblock_height) -{ - // https://datatracker.ietf.org/doc/html/rfc6386#section-19.3 - - // Corresponds to "macroblock_header()" in section 19.3 of the spec. - - Vector macroblock_metadata; - - // Key frames must use intra prediction, that is new macroblocks are predicted from old macroblocks in the same frame. - // (Inter prediction on the other hand predicts new macroblocks from the corresponding macroblock in the previous frame.) - - // https://datatracker.ietf.org/doc/html/rfc6386#section-11.3 "Subblock Mode Contexts" - // "For macroblocks on the top row or left edge of the image, some of - // the predictors will be non-existent. Such predictors are taken - // to have had the value B_DC_PRED, which, perhaps conveniently, - // takes the value 0 in the enumeration above. - // A simple management scheme for these contexts might maintain a row - // of above predictors and four left predictors. Before decoding the - // frame, the entire row is initialized to B_DC_PRED; before decoding - // each row of macroblocks, the four left predictors are also set to - // B_DC_PRED. After decoding a macroblock, the bottom four subblock - // modes are copied into the row predictor (at the current position, - // which then advances to be above the next macroblock), and the - // right four subblock modes are copied into the left predictor." - Vector above; - TRY(above.try_resize(macroblock_width * 4)); // One per 4x4 subblock. - - // It's possible to not decode all macroblock metadata at once. Instead, this could for example decode one row of metadata, - // then decode the coefficients for one row of macroblocks, convert that row to pixels, and then go on to the next row of macroblocks. - // That'd require slightly less memory. But MacroblockMetadata is fairly small, and this way we can keep the context - // (`above`, `left`) in stack variables instead of having to have a class for that. So keep it simple for now. - for (int mb_y = 0; mb_y < macroblock_height; ++mb_y) { - IntraBlockMode left[4] {}; - - for (int mb_x = 0; mb_x < macroblock_width; ++mb_x) { - MacroblockMetadata metadata; - - if (header.segmentation.update_macroblock_segmentation_map) - metadata.segment_id = tree_decode(decoder, MACROBLOCK_SEGMENT_TREE, header.segmentation.macroblock_segment_tree_probabilities); - - if (header.enable_skipping_of_macroblocks_containing_only_zero_coefficients) - metadata.skip_coefficients = B(header.probability_skip_false); - - int intra_y_mode = tree_decode(decoder, KEYFRAME_YMODE_TREE, KEYFRAME_YMODE_PROBABILITIES); - metadata.intra_y_mode = (IntraMacroblockMode)intra_y_mode; - - // "If the Ymode is B_PRED, it is followed by a (tree-coded) mode for each of the 16 Y subblocks." - if (intra_y_mode == B_PRED) { - for (int y = 0; y < 4; ++y) { - for (int x = 0; x < 4; ++x) { - // "The outer two dimensions of this array are indexed by the already- - // coded subblock modes above and to the left of the current block, - // respectively." - int A = above[mb_x * 4 + x]; - int L = left[y]; - - auto intra_b_mode = static_cast(tree_decode(decoder, BLOCK_MODE_TREE, KEYFRAME_BLOCK_MODE_PROBABILITIES[A][L])); - metadata.intra_b_modes[y * 4 + x] = intra_b_mode; - - above[mb_x * 4 + x] = intra_b_mode; - left[y] = intra_b_mode; - } - } - } else { - VERIFY(intra_y_mode < B_PRED); - constexpr IntraBlockMode b_mode_from_y_mode[] = { B_DC_PRED, B_VE_PRED, B_HE_PRED, B_TM_PRED }; - IntraBlockMode intra_b_mode = b_mode_from_y_mode[intra_y_mode]; - for (int i = 0; i < 4; ++i) { - above[mb_x * 4 + i] = intra_b_mode; - left[i] = intra_b_mode; - } - } - - metadata.uv_mode = (IntraMacroblockMode)tree_decode(decoder, UV_MODE_TREE, KEYFRAME_UV_MODE_PROBABILITIES); - - TRY(macroblock_metadata.try_append(metadata)); - } - } - - return macroblock_metadata; -} - -// Every macroblock stores: -// - One optional set of coefficients for Y2 -// - 16 sets of Y coefficients for the 4x4 Y subblocks of the macroblock -// - 4 sets of U coefficients for the 2x2 U subblocks of the macroblock -// - 4 sets of V coefficients for the 2x2 V subblocks of the macroblock -// That's 24 or 25 sets of coefficients total. This struct identifies one of these sets by index. -// If a macroblock does not have Y2, then i goes from [1..25], else it goes [0..25]. -struct CoefficientBlockIndex { - int i; - - CoefficientBlockIndex(int i) - : i(i) - { - VERIFY(i >= 0); - VERIFY(i <= 25); - } - - bool is_y2() const { return i == 0; } - bool is_y() const { return i >= 1 && i <= 16; } - bool is_u() const { return i >= 17 && i <= 20; } - bool is_v() const { return i >= 21; } - - u8 sub_x() const - { - VERIFY(i > 0); - if (i <= 16) - return (i - 1) % 4; - if (i <= 20) - return (i - 17) % 2; - return (i - 21) % 2; - } - - u8 sub_y() const - { - VERIFY(i > 0); - if (i <= 16) - return (i - 1) / 4; - if (i <= 20) - return (i - 17) / 2; - return (i - 21) / 2; - } -}; - -int plane_index(CoefficientBlockIndex index, bool have_y2) -{ - // https://datatracker.ietf.org/doc/html/rfc6386#section-13.3 "Token Probabilities" - // "o 0 - Y beginning at coefficient 1 (i.e., Y after Y2) - // o 1 - Y2 - // o 2 - U or V - // o 3 - Y beginning at coefficient 0 (i.e., Y in the absence of Y2)." - if (index.is_y2()) - return 1; - if (index.is_u() || index.is_v()) - return 2; - if (have_y2) - return 0; - return 3; -} - -i16 coefficient_value_for_token(BooleanDecoder& decoder, u8 token) -{ - // Implements the second half of https://datatracker.ietf.org/doc/html/rfc6386#section-13.2 "Coding of Individual Coefficient Values" - i16 v = static_cast(token); // For DCT_0 to DCT4 - - if (token >= dct_cat1 && token <= dct_cat6) { - static int constexpr starts[] = { 5, 7, 11, 19, 35, 67 }; - static int constexpr bits[] = { 1, 2, 3, 4, 5, 11 }; - - static Prob constexpr Pcat1[] = { 159 }; - static Prob constexpr Pcat2[] = { 165, 145 }; - static Prob constexpr Pcat3[] = { 173, 148, 140 }; - static Prob constexpr Pcat4[] = { 176, 155, 140, 135 }; - static Prob constexpr Pcat5[] = { 180, 157, 141, 134, 130 }; - static Prob constexpr Pcat6[] = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 }; - static Prob const* const Pcats[] = { Pcat1, Pcat2, Pcat3, Pcat4, Pcat5, Pcat6 }; - - v = 0; - - // This loop corresponds to `DCTextra` in the spec in section 13.2. - for (int i = 0; i < bits[token - dct_cat1]; ++i) - v = (v << 1) | decoder.read_bool(Pcats[token - dct_cat1][i]); - - v += starts[token - dct_cat1]; - } - - if (v) { - if (decoder.read_bool(128)) - v = -v; - } - - return v; -} - -i16 dequantize_value(i16 value, bool is_dc, QuantizationIndices const& quantization_indices, Segmentation const& segmentation, int segment_id, CoefficientBlockIndex index) -{ - // https://datatracker.ietf.org/doc/html/rfc6386#section-9.6 "Dequantization Indices" - // "before inverting the transform, each decoded coefficient - // is multiplied by one of six dequantization factors, the choice of - // which depends on the plane (Y, chroma = U or V, Y2) and coefficient - // position (DC = coefficient 0, AC = coefficients 1-15). The six - // values are specified using 7-bit indices into six corresponding fixed - // tables (the tables are given in Section 14)." - // Section 14 then lists two (!) fixed tables (which are in WebPLoaderLossyTables.h) - - // "Lookup values from the above two tables are directly used in the DC - // and AC coefficients in Y1, respectively. For Y2 and chroma, values - // from the above tables undergo either scaling or clamping before the - // multiplies. Details regarding these scaling and clamping processes - // can be found in related lookup functions in dixie.c (Section 20.4)." - // Apparently spec writing became too much work at this point. In section 20.4, in dequant_init(): - // * For y2, the output (!) of dc_qlookup is multiplied by 2, the output of ac_qlookup is multiplied by 155 / 100 - // * Also for y2, ac_qlookup is at least 8 for lower table entries - // * For uv, the dc_qlookup index is clamped to 117 (instead of 127 for everything else) - // (or, alternatively, the value is clamped to 132 at most) - - int y_ac_base = quantization_indices.y_ac; - if (segmentation.update_macroblock_segmentation_map) { - if (segmentation.segment_feature_mode == SegmentFeatureMode::DeltaValueMode) - y_ac_base += segmentation.quantizer_update_value[segment_id]; - else - y_ac_base = segmentation.quantizer_update_value[segment_id]; - } - - int dequantization_index; - if (index.is_y2()) - dequantization_index = y_ac_base + (is_dc ? quantization_indices.y2_dc_delta : quantization_indices.y2_ac_delta); - else if (index.is_u() || index.is_v()) - dequantization_index = y_ac_base + (is_dc ? quantization_indices.uv_dc_delta : quantization_indices.uv_ac_delta); - else - dequantization_index = is_dc ? (y_ac_base + quantization_indices.y_dc_delta) : y_ac_base; - - // clamp index - if ((index.is_u() || index.is_v()) && is_dc) - dequantization_index = clamp(dequantization_index, 0, 117); - else - dequantization_index = clamp(dequantization_index, 0, 127); - - // "the multiplies are computed and stored using 16-bit signed integers." - i16 dequantization_factor; - if (is_dc) - dequantization_factor = (i16)dc_qlookup[dequantization_index]; - else - dequantization_factor = (i16)ac_qlookup[dequantization_index]; - - if (index.is_y2()) { - if (is_dc) - dequantization_factor *= 2; - else - dequantization_factor = max((dequantization_factor * 155) / 100, 8); - } - - return dequantization_factor * value; -} - -// Reading macroblock coefficients requires needing to know if the block to the left and above the current macroblock -// has non-zero coefficients. This stores that state. -struct CoefficientReadingContext { - // Store if each plane has nonzero coefficients in the block above and to the left of the current block. - Vector y2_above; - Vector y_above; - Vector u_above; - Vector v_above; - - bool y2_left {}; - bool y_left[4] {}; - bool u_left[2] {}; - bool v_left[2] {}; - - ErrorOr initialize(int macroblock_width) - { - TRY(y2_above.try_resize(macroblock_width)); - TRY(y_above.try_resize(macroblock_width * 4)); - TRY(u_above.try_resize(macroblock_width * 2)); - TRY(v_above.try_resize(macroblock_width * 2)); - return {}; - } - - void start_new_row() - { - y2_left = false; - for (bool& b : y_left) - b = false; - for (bool& b : u_left) - b = false; - for (bool& b : v_left) - b = false; - } - - bool& was_above_nonzero(CoefficientBlockIndex index, int mb_x) - { - if (index.is_y2()) - return y2_above[mb_x]; - if (index.is_u()) - return u_above[mb_x * 2 + index.sub_x()]; - if (index.is_v()) - return v_above[mb_x * 2 + index.sub_x()]; - return y_above[mb_x * 4 + index.sub_x()]; - } - bool was_above_nonzero(CoefficientBlockIndex index, int mb_x) const { return const_cast(*this).was_above_nonzero(index, mb_x); } - - bool& was_left_nonzero(CoefficientBlockIndex index) - { - if (index.is_y2()) - return y2_left; - if (index.is_u()) - return u_left[index.sub_y()]; - if (index.is_v()) - return v_left[index.sub_y()]; - return y_left[index.sub_y()]; - } - bool was_left_nonzero(CoefficientBlockIndex index) const { return const_cast(*this).was_left_nonzero(index); } - - void update(CoefficientBlockIndex index, int mb_x, bool subblock_has_nonzero_coefficients) - { - was_above_nonzero(index, mb_x) = subblock_has_nonzero_coefficients; - was_left_nonzero(index) = subblock_has_nonzero_coefficients; - } -}; - -using Coefficients = i16[16]; - -// Returns if any non-zero coefficients were read. -bool read_coefficent_block(BooleanDecoder& decoder, Coefficients out_coefficients, CoefficientBlockIndex block_index, CoefficientReadingContext& coefficient_reading_context, int mb_x, bool have_y2, int segment_id, FrameHeader const& header) -{ - // Corresponds to `residual_block()` in https://datatracker.ietf.org/doc/html/rfc6386#section-19.3, - // but also does dequantization of the stored values. - // "firstCoeff is 1 for luma blocks of macroblocks containing Y2 subblock; otherwise 0" - int firstCoeff = have_y2 && block_index.is_y() ? 1 : 0; - i16 last_decoded_value = num_dct_tokens; // Start with an invalid value - - bool subblock_has_nonzero_coefficients = false; - - for (int j = firstCoeff; j < 16; ++j) { - // https://datatracker.ietf.org/doc/html/rfc6386#section-13.2 "Coding of Individual Coefficient Values" - // https://datatracker.ietf.org/doc/html/rfc6386#section-13.3 "Token Probabilities" - - // "Working from the outside in, the outermost dimension is indexed by - // the type of plane being decoded" - int plane = plane_index(block_index, have_y2); - - // "The next dimension is selected by the position of the coefficient - // being decoded. That position, c, steps by ones up to 15, starting - // from zero for block types 1, 2, or 3 and starting from one for block - // type 0. The second array index is then" - // "block type" here seems to refer to the "type of plane" in the previous paragraph. - static int constexpr coeff_bands[16] = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7 }; - int band = coeff_bands[j]; - - // "The third dimension is the trickiest." - int tricky = 0; - - // "For the first coefficient (DC, unless the block type is 0), we - // consider the (already encoded) blocks within the same plane (Y2, Y, - // U, or V) above and to the left of the current block. The context - // index is then the number (0, 1, or 2) of these blocks that had at - // least one non-zero coefficient in their residue record. Specifically - // for Y2, because macroblocks above and to the left may or may not have - // a Y2 block, the block above is determined by the most recent - // macroblock in the same column that has a Y2 block, and the block to - // the left is determined by the most recent macroblock in the same row - // that has a Y2 block. - // [...] - // As with other contexts used by VP8, the "neighboring block" context - // described here needs a special definition for subblocks lying along - // the top row or left edge of the frame. These "non-existent" - // predictors above and to the left of the image are simply taken to be - // empty -- that is, taken to contain no non-zero coefficients." - if (j == firstCoeff) { - bool was_left_nonzero = coefficient_reading_context.was_left_nonzero(block_index); - bool was_above_nonzero = coefficient_reading_context.was_above_nonzero(block_index, mb_x); - tricky = static_cast(was_left_nonzero) + static_cast(was_above_nonzero); - } - // "Beyond the first coefficient, the context index is determined by the - // absolute value of the most recently decoded coefficient (necessarily - // within the current block) and is 0 if the last coefficient was a - // zero, 1 if it was plus or minus one, and 2 if its absolute value - // exceeded one." - else { - if (last_decoded_value == 0) - tricky = 0; - else if (last_decoded_value == 1 || last_decoded_value == -1) - tricky = 1; - else - tricky = 2; - } - - // "In general, all DCT coefficients are decoded using the same tree. - // However, if the preceding coefficient is a DCT_0, decoding will skip - // the first branch, since it is not possible for dct_eob to follow a - // DCT_0." - u8 token = tree_decode(decoder, COEFFICIENT_TREE, header.coefficient_probabilities[plane][band][tricky], last_decoded_value == DCT_0 ? 2 : 0); - if (token == dct_eob) - break; - - i16 v = coefficient_value_for_token(decoder, token); - - if (v) { - // Subblock has non-0 coefficients. Store that, so that `tricky` on the next subblock is initialized correctly. - subblock_has_nonzero_coefficients = true; - } - - // last_decoded_value is used for setting `tricky`. It needs to be set to the last decoded token, not to the last dequantized value. - last_decoded_value = v; - - i16 dequantized_value = dequantize_value(v, j == 0, header.quantization_indices, header.segmentation, segment_id, block_index); - - static int constexpr Zigzag[] = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 }; - out_coefficients[Zigzag[j]] = dequantized_value; - } - - return subblock_has_nonzero_coefficients; -} - -struct MacroblockCoefficients { - Coefficients y_coeffs[16] {}; - Coefficients u_coeffs[4] {}; - Coefficients v_coeffs[4] {}; -}; - -MacroblockCoefficients read_macroblock_coefficients(BooleanDecoder& decoder, FrameHeader const& header, CoefficientReadingContext& coefficient_reading_context, MacroblockMetadata const& metadata, int mb_x) -{ - // Corresponds to `residual_data()` in https://datatracker.ietf.org/doc/html/rfc6386#section-19.3, - // but also does the inverse walsh-hadamard transform if a Y2 block is present. - - MacroblockCoefficients coefficients; - Coefficients y2_coeffs {}; - - // "firstCoeff is 1 for luma blocks of macroblocks containing Y2 subblock; otherwise 0" - - // https://datatracker.ietf.org/doc/html/rfc6386#section-13 - - // "For all intra- and inter-prediction modes apart from B_PRED (intra: - // whose Y subblocks are independently predicted) and SPLITMV (inter), - // each macroblock's residue record begins with the Y2 component of the - // residue, coded using a WHT. B_PRED and SPLITMV coded macroblocks - // omit this WHT and specify the 0th DCT coefficient in each of the 16 Y - // subblocks." - bool have_y2 = metadata.intra_y_mode != B_PRED; - - // "for Y2, because macroblocks above and to the left may or may not have - // a Y2 block, the block above is determined by the most recent - // macroblock in the same column that has a Y2 block, and the block to - // the left is determined by the most recent macroblock in the same row - // that has a Y2 block." - // We only write to y2_above / y2_left when it's present, so we don't need to do any explicit work to get the right behavior. - - // "After the optional Y2 block, the residue record continues with 16 - // DCTs for the Y subblocks, followed by 4 DCTs for the U subblocks, - // ending with 4 DCTs for the V subblocks. The subblocks occur in the - // usual order." - - /* (1 Y2)?, 16 Y, 4 U, 4 V */ - for (int i = have_y2 ? 0 : 1; i < 25; ++i) { - CoefficientBlockIndex block_index { i }; - - bool subblock_has_nonzero_coefficients = false; - - if (!metadata.skip_coefficients) { - i16* to_read; - if (block_index.is_y2()) - to_read = y2_coeffs; - else if (block_index.is_u()) - to_read = coefficients.u_coeffs[i - 17]; - else if (block_index.is_v()) - to_read = coefficients.v_coeffs[i - 21]; - else // Y - to_read = coefficients.y_coeffs[i - 1]; - subblock_has_nonzero_coefficients = read_coefficent_block(decoder, to_read, block_index, coefficient_reading_context, mb_x, have_y2, metadata.segment_id, header); - } - - coefficient_reading_context.update(block_index, mb_x, subblock_has_nonzero_coefficients); - } - - // https://datatracker.ietf.org/doc/html/rfc6386#section-14.2 "Inverse Transforms" - // "If the Y2 residue block exists (i.e., the macroblock luma mode is not - // SPLITMV or B_PRED), it is inverted first (using the inverse WHT) and - // the element of the result at row i, column j is used as the 0th - // coefficient of the Y subblock at position (i, j), that is, the Y - // subblock whose index is (i * 4) + j." - if (have_y2) { - Coefficients wht_output; - vp8_short_inv_walsh4x4_c(y2_coeffs, wht_output); - for (size_t i = 0; i < 16; ++i) - coefficients.y_coeffs[i][0] = wht_output[i]; - } - - return coefficients; -} - -template -void predict_macroblock(Bytes prediction, IntraMacroblockMode mode, int mb_x, int mb_y, ReadonlyBytes left, ReadonlyBytes above, u8 truemotion_corner) -{ - // https://datatracker.ietf.org/doc/html/rfc6386#section-12.2 "Chroma Prediction" - // (Also used for the DC_PRED, H_PRED, V_PRED, TM_PRED for luma prediction.) - if (mode == DC_PRED) { - if (mb_x == 0 && mb_y == 0) { - for (size_t i = 0; i < N * N; ++i) - prediction[i] = 128; - } else { - int sum = 0, n = 0; - if (mb_x > 0) { - for (int i = 0; i < N; ++i) - sum += left[i]; - n += N; - } - if (mb_y > 0) { - for (int i = 0; i < N; ++i) - sum += above[mb_x * N + i]; - n += N; - } - u8 average = (sum + n / 2) / n; - for (size_t i = 0; i < N * N; ++i) - prediction[i] = average; - } - } else if (mode == H_PRED) { - for (int y = 0; y < N; ++y) - for (int x = 0; x < N; ++x) - prediction[y * N + x] = left[y]; - } else if (mode == V_PRED) { - for (int y = 0; y < N; ++y) - for (int x = 0; x < N; ++x) - prediction[y * N + x] = above[mb_x * N + x]; - } else { - VERIFY(mode == TM_PRED); - for (int y = 0; y < N; ++y) - for (int x = 0; x < N; ++x) - prediction[y * N + x] = clamp(left[y] + above[mb_x * N + x] - truemotion_corner, 0, 255); - } -} - -void predict_y_subblock(Bytes y_prediction, IntraBlockMode mode, int x, int y, ReadonlyBytes left, ReadonlyBytes above, u8 corner) -{ - // https://datatracker.ietf.org/doc/html/rfc6386#section-12.3 "Luma Prediction" - // Roughly corresponds to "subblock_intra_predict()" in the spec. - auto weighted_average = [](u8 x, u8 y, u8 z) { return (x + 2 * y + z + 2) / 4; }; - auto average = [](u8 x, u8 y) { return (x + y + 1) / 2; }; - - auto at = [&y_prediction, y, x](int px, int py) -> u8& { return y_prediction[(4 * y + py) * 16 + 4 * x + px]; }; - - if (mode == B_DC_PRED) { - // The spec text says this is like DC_PRED, but predict_dc_nxn() in the sample implementation doesn't do the "oob isn't read" part. - int sum = 0, n = 8; - for (int i = 0; i < 4; ++i) - sum += left[i] + above[i]; - u8 average = (sum + n / 2) / n; - for (int py = 0; py < 4; ++py) - for (int px = 0; px < 4; ++px) - y_prediction[(4 * y + py) * 16 + 4 * x + px] = average; - } else if (mode == B_TM_PRED) { - for (int py = 0; py < 4; ++py) - for (int px = 0; px < 4; ++px) - y_prediction[(4 * y + py) * 16 + 4 * x + px] = clamp(left[py] + above[px] - corner, 0, 255); - } else if (mode == B_VE_PRED) { - // The spec text says this is like V_PRED, but the sample implementation shows it does weighted averages (unlike V_PRED). - for (int py = 0; py < 4; ++py) - for (int px = 0; px < 4; ++px) { - auto top_left = (px > 0 ? above[px - 1] : corner); - y_prediction[(4 * y + py) * 16 + 4 * x + px] = weighted_average(top_left, above[px], above[px + 1]); - } - } else if (mode == B_HE_PRED) { - // The spec text says this is like H_PRED, but the sample implementation shows it does weighted averages (unlike H_PRED). - for (int py = 0; py < 4; ++py) - for (int px = 0; px < 4; ++px) { - if (py == 0) { - y_prediction[(4 * y + py) * 16 + 4 * x + px] = weighted_average(corner, left[py], left[py + 1]); - } else if (py == 3) { - /* Bottom row is exceptional because L[4] does not exist */ - y_prediction[(4 * y + py) * 16 + 4 * x + px] = weighted_average(left[2], left[3], left[3]); - } else { - y_prediction[(4 * y + py) * 16 + 4 * x + px] = weighted_average(left[py - 1], left[py], left[py + 1]); - } - } - } else if (mode == B_LD_PRED) { - // this is 45-deg prediction from above, going left-down (i.e. isochromes on -1/+1 diags) - at(0, 0) = weighted_average(above[0], above[1], above[2]); - at(0, 1) = at(1, 0) = weighted_average(above[1], above[2], above[3]); - at(0, 2) = at(1, 1) = at(2, 0) = weighted_average(above[2], above[3], above[4]); - at(0, 3) = at(1, 2) = at(2, 1) = at(3, 0) = weighted_average(above[3], above[4], above[5]); - at(1, 3) = at(2, 2) = at(3, 1) = weighted_average(above[4], above[5], above[6]); - at(2, 3) = at(3, 2) = weighted_average(above[5], above[6], above[7]); - at(3, 3) = weighted_average(above[6], above[7], above[7]); // intentionally 6, 7, 7 - } else if (mode == B_RD_PRED) { - // this is 45-deg prediction from above / left, going right-down (i.e. isochromes on +1/+1 diags) - at(0, 3) = weighted_average(left[3], left[2], left[1]); - at(0, 2) = at(1, 3) = weighted_average(left[2], left[1], left[0]); - at(0, 1) = at(1, 2) = at(2, 3) = weighted_average(left[1], left[0], corner); - at(0, 0) = at(1, 1) = at(2, 2) = at(3, 3) = weighted_average(left[0], corner, above[0]); - at(1, 0) = at(2, 1) = at(3, 2) = weighted_average(corner, above[0], above[1]); - at(2, 0) = at(3, 1) = weighted_average(above[0], above[1], above[2]); - at(3, 0) = weighted_average(above[1], above[2], above[3]); - } else if (mode == B_VR_PRED) { - // this is 22.5-deg prediction - at(0, 3) = weighted_average(left[2], left[1], left[0]); - at(0, 2) = weighted_average(left[1], left[0], corner); - at(1, 3) = at(0, 1) = weighted_average(left[0], corner, above[0]); - at(1, 2) = at(0, 0) = average(corner, above[0]); - at(2, 3) = at(1, 1) = weighted_average(corner, above[0], above[1]); - at(2, 2) = at(1, 0) = average(above[0], above[1]); - at(3, 3) = at(2, 1) = weighted_average(above[0], above[1], above[2]); - at(3, 2) = at(2, 0) = average(above[1], above[2]); - at(3, 1) = weighted_average(above[1], above[2], above[3]); - at(3, 0) = average(above[2], above[3]); - } else if (mode == B_VL_PRED) { - // this is 22.5-deg prediction - at(0, 0) = average(above[0], above[1]); - at(0, 1) = weighted_average(above[0], above[1], above[2]); - at(0, 2) = at(1, 0) = average(above[1], above[2]); - at(1, 1) = at(0, 3) = weighted_average(above[1], above[2], above[3]); - at(1, 2) = at(2, 0) = average(above[2], above[3]); - at(1, 3) = at(2, 1) = weighted_average(above[2], above[3], above[4]); - at(2, 2) = at(3, 0) = average(above[3], above[4]); - at(2, 3) = at(3, 1) = weighted_average(above[3], above[4], above[5]); - /* Last two values do not strictly follow the pattern. */ - at(3, 2) = weighted_average(above[4], above[5], above[6]); - at(3, 3) = weighted_average(above[5], above[6], above[7]); - } else if (mode == B_HD_PRED) { - // this is 22.5-deg prediction - at(0, 3) = average(left[3], left[2]); - at(1, 3) = weighted_average(left[3], left[2], left[1]); - at(0, 2) = at(2, 3) = average(left[2], left[1]); - at(1, 2) = at(3, 3) = weighted_average(left[2], left[1], left[0]); - at(2, 2) = at(0, 1) = average(left[1], left[0]); - at(3, 2) = at(1, 1) = weighted_average(left[1], left[0], corner); - at(2, 1) = at(0, 0) = average(left[0], corner); - at(3, 1) = at(1, 0) = weighted_average(left[0], corner, above[0]); - at(2, 0) = weighted_average(corner, above[0], above[1]); - at(3, 0) = weighted_average(above[0], above[1], above[2]); - } else { - VERIFY(mode == B_HU_PRED); - // this is 22.5-deg prediction - at(0, 0) = average(left[0], left[1]); - at(1, 0) = weighted_average(left[0], left[1], left[2]); - at(2, 0) = at(0, 1) = average(left[1], left[2]); - at(3, 0) = at(1, 1) = weighted_average(left[1], left[2], left[3]); - at(2, 1) = at(0, 2) = average(left[2], left[3]); - at(3, 1) = at(1, 2) = weighted_average(left[2], left[3], left[3]); // Intentionally 2, 3, 3 - /* Not possible to follow pattern for much of the bottom - row because no (nearby) already-constructed pixels lie - on the diagonals in question. */ - at(2, 2) = at(3, 2) = at(0, 3) = at(1, 3) = at(2, 3) = at(3, 3) = left[3]; - } -} - -template -void add_idct_to_prediction(Bytes prediction, Coefficients coefficients, int x, int y) -{ - Coefficients idct_output; - short_idct4x4llm_c(coefficients, idct_output, 4 * sizeof(i16)); - - // https://datatracker.ietf.org/doc/html/rfc6386#section-14.5 "Summation of Predictor and Residue" - // FIXME: Could omit the clamp() call if FrameHeader.clamping_type == ClampingSpecification::NoClampingNecessary. - for (int py = 0; py < 4; ++py) { - for (int px = 0; px < 4; ++px) { - u8& p = prediction[(4 * y + py) * N + (4 * x + px)]; - p = clamp(p + idct_output[py * 4 + px], 0, 255); - } - } -} - -template -void process_macroblock(Bytes output, IntraMacroblockMode mode, int mb_x, int mb_y, ReadonlyBytes left, ReadonlyBytes above, u8 truemotion_corner, Coefficients coefficients_array[]) -{ - predict_macroblock<4 * N>(output, mode, mb_x, mb_y, left, above, truemotion_corner); - - // https://datatracker.ietf.org/doc/html/rfc6386#section-14.4 "Implementation of the DCT Inversion" - // Loop over the 4x4 subblocks - for (int y = 0, i = 0; y < N; ++y) - for (int x = 0; x < N; ++x, ++i) - add_idct_to_prediction<4 * N>(output, coefficients_array[i], x, y); -} - -void process_subblocks(Bytes y_output, MacroblockMetadata const& metadata, int mb_x, ReadonlyBytes predicted_y_left, ReadonlyBytes predicted_y_above, u8 y_truemotion_corner, Coefficients coefficients_array[], int macroblock_width) -{ - // Loop over the 4x4 subblocks - for (int y = 0, i = 0; y < 4; ++y) { - for (int x = 0; x < 4; ++x, ++i) { - u8 corner = y_truemotion_corner; - if (x > 0 && y == 0) - corner = predicted_y_above[mb_x * 16 + 4 * x - 1]; - else if (x > 0 && y > 0) - corner = y_output[(4 * y - 1) * 16 + 4 * x - 1]; - else if (x == 0 && y > 0) - corner = predicted_y_left[4 * y - 1]; - - u8 left[4], above[8]; - for (int i = 0; i < 4; ++i) { - if (x == 0) - left[i] = predicted_y_left[4 * y + i]; - else - left[i] = y_output[(4 * y + i) * 16 + 4 * x - 1]; - } - // Subblock prediction can read 8 pixels above the block. - // For rightmost subblocks, the right 4 pixels there aren't initialized yet, so those get the 4 pixels to the right above the macroblock. - // For the rightmost macroblock, there's no macroblock to its right, so there they get the rightmost pixel above. - // But in the 0th row, there's no pixel above, so there they become 127. - for (int i = 0; i < 8; ++i) { - if (x == 3 && i >= 4) { // rightmost subblock, 4 right pixels? - if (mb_x == macroblock_width - 1) { // rightmost macroblock - // predicted_y_above is initialized to 127 above the first row, so no need for an explicit branch for mb_y == 0. - above[i] = predicted_y_above[mb_x * 16 + 4 * x + 3]; - } else { - above[i] = predicted_y_above[mb_x * 16 + 4 * x + i]; - } - } else if (y == 0) { - above[i] = predicted_y_above[mb_x * 16 + 4 * x + i]; - } else { - above[i] = y_output[(4 * y - 1) * 16 + 4 * x + i]; - } - } - - predict_y_subblock(y_output, metadata.intra_b_modes[y * 4 + x], x, y, left, above, corner); - - // Have to do IDCT summation here, since its results affect prediction of next subblock already. - add_idct_to_prediction<16>(y_output, coefficients_array[4 * y + x], x, y); - } - } -} - -void convert_yuv_to_rgb(Bitmap& bitmap, int mb_x, int mb_y, ReadonlyBytes y_data, ReadonlyBytes u_data, ReadonlyBytes v_data) -{ - for (int y = 0; y < 16; ++y) { - for (int x = 0; x < 16; ++x) { - u8 Y = y_data[y * 16 + x]; - - // FIXME: Could do nicer upsampling than just nearest neighbor - u8 U = u_data[(y / 2) * 8 + x / 2]; - u8 V = v_data[(y / 2) * 8 + x / 2]; - - // XXX: These numbers are from the fixed-point values in libwebp's yuv.h. There's probably a better reference somewhere. - int r = 1.1655 * Y + 1.596 * V - 222.4; - int g = 1.1655 * Y - 0.3917 * U - 0.8129 * V + 136.0625; - int b = 1.1655 * Y + 2.0172 * U - 276.33; - - bitmap.scanline(mb_y * 16 + y)[mb_x * 16 + x] = Color(clamp(r, 0, 255), clamp(g, 0, 255), clamp(b, 0, 255)).value(); - } - } -} - -ErrorOr decode_VP8_image_data(Gfx::Bitmap& bitmap, FrameHeader const& header, Vector data_partitions, int macroblock_width, int macroblock_height, Vector const& macroblock_metadata) -{ - - Vector streams; - for (auto data : data_partitions) { - auto decoder = TRY(BooleanDecoder::initialize(data)); - TRY(streams.try_append(move(decoder))); - } - - CoefficientReadingContext coefficient_reading_context; - TRY(coefficient_reading_context.initialize(macroblock_width)); - - Vector predicted_y_above; - TRY(predicted_y_above.try_resize(macroblock_width * 16)); - for (size_t i = 0; i < predicted_y_above.size(); ++i) - predicted_y_above[i] = 127; - - Vector predicted_u_above; - TRY(predicted_u_above.try_resize(macroblock_width * 8)); - for (size_t i = 0; i < predicted_u_above.size(); ++i) - predicted_u_above[i] = 127; - - Vector predicted_v_above; - TRY(predicted_v_above.try_resize(macroblock_width * 8)); - for (size_t i = 0; i < predicted_v_above.size(); ++i) - predicted_v_above[i] = 127; - - for (int mb_y = 0, macroblock_index = 0; mb_y < macroblock_height; ++mb_y) { - BooleanDecoder& decoder = streams[mb_y % streams.size()]; - - coefficient_reading_context.start_new_row(); - - u8 predicted_y_left[16] { 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129 }; - u8 predicted_u_left[8] { 129, 129, 129, 129, 129, 129, 129, 129 }; - u8 predicted_v_left[8] { 129, 129, 129, 129, 129, 129, 129, 129 }; - - // The spec doesn't say if this should be 127, 129, or something else. - // But ReconstructRow in frame_dec.c in libwebp suggests 129. - u8 y_truemotion_corner = 129; - u8 u_truemotion_corner = 129; - u8 v_truemotion_corner = 129; - - for (int mb_x = 0; mb_x < macroblock_width; ++mb_x, ++macroblock_index) { - auto const& metadata = macroblock_metadata[macroblock_index]; - - auto coefficients = read_macroblock_coefficients(decoder, header, coefficient_reading_context, metadata, mb_x); - - u8 y_data[16 * 16] {}; - if (metadata.intra_y_mode == B_PRED) - process_subblocks(y_data, metadata, mb_x, predicted_y_left, predicted_y_above, y_truemotion_corner, coefficients.y_coeffs, macroblock_width); - else - process_macroblock<4>(y_data, metadata.intra_y_mode, mb_x, mb_y, predicted_y_left, predicted_y_above, y_truemotion_corner, coefficients.y_coeffs); - - u8 u_data[8 * 8] {}; - process_macroblock<2>(u_data, metadata.uv_mode, mb_x, mb_y, predicted_u_left, predicted_u_above, u_truemotion_corner, coefficients.u_coeffs); - - u8 v_data[8 * 8] {}; - process_macroblock<2>(v_data, metadata.uv_mode, mb_x, mb_y, predicted_v_left, predicted_v_above, v_truemotion_corner, coefficients.v_coeffs); - - // FIXME: insert loop filtering here - - convert_yuv_to_rgb(bitmap, mb_x, mb_y, y_data, u_data, v_data); - - y_truemotion_corner = predicted_y_above[mb_x * 16 + 15]; - for (int i = 0; i < 16; ++i) - predicted_y_left[i] = y_data[15 + i * 16]; - for (int i = 0; i < 16; ++i) - predicted_y_above[mb_x * 16 + i] = y_data[15 * 16 + i]; - - u_truemotion_corner = predicted_u_above[mb_x * 8 + 7]; - for (int i = 0; i < 8; ++i) - predicted_u_left[i] = u_data[7 + i * 8]; - for (int i = 0; i < 8; ++i) - predicted_u_above[mb_x * 8 + i] = u_data[7 * 8 + i]; - - v_truemotion_corner = predicted_v_above[mb_x * 8 + 7]; - for (int i = 0; i < 8; ++i) - predicted_v_left[i] = v_data[7 + i * 8]; - for (int i = 0; i < 8; ++i) - predicted_v_above[mb_x * 8 + i] = v_data[7 * 8 + i]; - } - } - - for (auto& decoder : streams) - TRY(decoder.finish_decode()); - - return {}; -} - -static ErrorOr> split_data_partitions(ReadonlyBytes second_partition, u8 number_of_dct_partitions) -{ - Vector data_partitions; - // https://datatracker.ietf.org/doc/html/rfc6386#section-9.5 "Token Partition and Partition Data Offsets" - // "If the number of data partitions is - // greater than 1, the size of each partition (except the last) is - // written in 3 bytes (24 bits). The size of the last partition is the - // remainder of the data not used by any of the previous partitions. - // The partitioned data are consecutive in the bitstream, so the size - // can also be used to calculate the offset of each partition." - // In practice, virtually all lossy webp files have a single data partition. - VERIFY(number_of_dct_partitions >= 1); - VERIFY(number_of_dct_partitions <= 8); - - size_t sizes_size = (number_of_dct_partitions - 1) * 3; - if (second_partition.size() < sizes_size) - return Error::from_string_literal("WebPImageDecoderPlugin: not enough data for partition sizes"); - - ReadonlyBytes sizes = second_partition.slice(0, sizes_size); - ReadonlyBytes data = second_partition.slice(sizes_size); - - for (int i = 0; i < number_of_dct_partitions - 1; ++i) { - u32 partition_size = sizes[0] | (sizes[1] << 8) | (sizes[2] << 16); - dbgln_if(WEBP_DEBUG, "partition_size {}", partition_size); - sizes = sizes.slice(3); - if (partition_size > data.size()) - return Error::from_string_literal("WebPImageDecoderPlugin: not enough data for partition data"); - TRY(data_partitions.try_append(data.slice(0, partition_size))); - data = data.slice(partition_size); - } - TRY(data_partitions.try_append(data)); - return data_partitions; -} - -} - -ErrorOr> decode_webp_chunk_VP8_contents(VP8Header const& vp8_header, bool include_alpha_channel) -{ - // The first partition stores header, per-segment state, and macroblock metadata. - auto decoder = TRY(BooleanDecoder::initialize(vp8_header.first_partition)); - - auto header = TRY(decode_VP8_frame_header(decoder)); - - // https://datatracker.ietf.org/doc/html/rfc6386#section-2 "Format Overview" - // "Internally, VP8 decomposes each output frame into an array of - // macroblocks. A macroblock is a square array of pixels whose Y - // dimensions are 16x16 and whose U and V dimensions are 8x8." - int macroblock_width = ceil_div(vp8_header.width, 16); - int macroblock_height = ceil_div(vp8_header.height, 16); - - auto macroblock_metadata = TRY(decode_VP8_macroblock_metadata(decoder, header, macroblock_width, macroblock_height)); - - TRY(decoder.finish_decode()); - // Done with the first partition! - - auto bitmap_format = include_alpha_channel ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888; - auto bitmap = TRY(Bitmap::create(bitmap_format, { macroblock_width * 16, macroblock_height * 16 })); - - auto data_partitions = TRY(split_data_partitions(vp8_header.second_partition, header.number_of_dct_partitions)); - TRY(decode_VP8_image_data(*bitmap, header, move(data_partitions), macroblock_width, macroblock_height, macroblock_metadata)); - - auto width = static_cast(vp8_header.width); - auto height = static_cast(vp8_header.height); - if (bitmap->size() == IntSize { width, height }) - return bitmap; - return bitmap->cropped({ 0, 0, width, height }); -} - -} diff --git a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossy.h b/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossy.h deleted file mode 100644 index b918471a3ae..00000000000 --- a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossy.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include -#include -#include - -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 decode_webp_chunk_VP8_header(ReadonlyBytes vp8_data); - -ErrorOr> decode_webp_chunk_VP8_contents(VP8Header const&, bool include_alpha_channel); - -} diff --git a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossyTables.h b/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossyTables.h deleted file mode 100644 index 24b9d07c3e6..00000000000 --- a/Userland/Libraries/LibGfx/ImageFormats/WebPLoaderLossyTables.h +++ /dev/null @@ -1,732 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * 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; - } -} - -} diff --git a/vcpkg.json b/vcpkg.json index 032a75ca8b9..40a291961fe 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -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"