Truly independent web browser
LibImageDecoders: Port the BMP decoder to Rust
Andreas Klinge42fd4b4bbd8
diff --git a/AK/Debug.h.in b/AK/Debug.h.inindex 3459b66cab7..6bb6524525a 100644--- a/AK/Debug.h.in+++ b/AK/Debug.h.in@@ -14,10 +14,6 @@# cmakedefine01 AUDIO_DEBUG#endif-#ifndef BMP_DEBUG-# cmakedefine01 BMP_DEBUG-#endif-#ifndef CACHE_DEBUG# cmakedefine01 CACHE_DEBUG#endifdiff --git a/Libraries/LibGfx/ImageFormats/BMPLoader.cpp b/Libraries/LibGfx/ImageFormats/BMPLoader.cppindex 4b2f116f166..52735f72ead 100644--- a/Libraries/LibGfx/ImageFormats/BMPLoader.cpp+++ b/Libraries/LibGfx/ImageFormats/BMPLoader.cpp@@ -6,1538 +6,90 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/BuiltinWrappers.h>-#include <AK/ByteString.h>-#include <AK/Debug.h>-#include <AK/Error.h>-#include <AK/Function.h>#include <AK/NumericLimits.h>-#include <AK/Try.h>-#include <AK/Vector.h>+#include <AK/ScopeGuard.h>#include <LibGfx/ImageFormats/BMPLoader.h>+#include <LibImageDecoders/RustFFI.h>namespace Gfx {-u8 const bmp_header_size = 14;-u32 const color_palette_limit = 1024;--// Compression flags-// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/4e588f70-bd92-4a6f-b77f-35d0feaf7a57-struct Compression {- enum : u32 {- RGB = 0,- RLE8,- RLE4,- BITFIELDS,- RLE24, // doubles as JPEG for V4+, but that is unsupported- PNG,- ALPHABITFIELDS,- CMYK = 11,- CMYKRLE8,- CMYKRLE4,- };-};--struct DIBCore {- // u16 for BITMAPHEADERCORE, but i32 for everything else. If the dib type is- // BITMAPHEADERCORE, this is range checked.- i32 width;- i32 height;- u16 bpp;-};--struct DIBInfo {- u32 compression { Compression::RGB };- u32 image_size { 0 };- i32 horizontal_resolution { 0 };- i32 vertical_resolution { 0 };- u32 number_of_palette_colors { 0 };- u32 number_of_important_palette_colors { number_of_palette_colors };-- // Introduced in the BITMAPV2INFOHEADER and would ideally be stored in the- // DIBV2 struct, however with a compression value of BI_BITFIELDS or- // BI_ALPHABITFIELDS, these can be specified with the Info header.- Vector<u32> masks;- Vector<i8> mask_shifts;- Vector<u8> mask_sizes;-};--struct DIBOSV2 {- u16 recording;- u16 halftoning;- u16 size1;- u16 size2;-};--template<typename T>-struct Endpoint {- T x;- T y;- T z;-};--}--namespace AK {--template<typename T>-struct Formatter<Gfx::Endpoint<T>> : Formatter<StringView> {- ErrorOr<void> format(FormatBuilder& builder, Gfx::Endpoint<T> const& value)- {- return Formatter<StringView>::format(builder, ByteString::formatted("({}, {}, {})", value.x, value.y, value.z));- }-};--}--namespace Gfx {--namespace BMP {--// CALIBRATED_RGB, sRGB, WINDOWS_COLOR_SPACE values are from-// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/eb4bbd50-b3ce-4917-895c-be31f214797f-// PROFILE_LINKED, PROFILE_EMBEDDED values are from-// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/3c289fe1-c42e-42f6-b125-4b5fc49a2b20-struct ColorSpace {- enum : u32 {- // "This value implies that endpoints and gamma values are given in the appropriate fields" in DIBV4.- // The only valid value in v4 bmps.- CALIBRATED_RGB = 0,-- // "Specifies that the bitmap is in sRGB color space."- sRGB = 0x73524742, // 'sRGB'-- // "This value indicates that the bitmap is in the system default color space, sRGB."- WINDOWS_COLOR_SPACE = 0x57696E20, // 'Win '-- // "This value indicates that bV5ProfileData points to the file name of the profile to use- // (gamma and endpoints values are ignored)."- LINKED = 0x4C494E4B, // 'LINK'-- // "This value indicates that bV5ProfileData points to a memory buffer that contains the profile to be used- // (gamma and endpoints values are ignored)."- EMBEDDED = 0x4D424544, // 'MBED'- };-};--}--// https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapv4header-struct DIBV4 {- u32 color_space { 0 };- Endpoint<i32> red_endpoint { 0, 0, 0 };- Endpoint<i32> green_endpoint { 0, 0, 0 };- Endpoint<i32> blue_endpoint { 0, 0, 0 };- Endpoint<u32> gamma_endpoint { 0, 0, 0 };-};--// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/9fec0834-607d-427d-abd5-ab240fb0db38-struct GamutMappingIntent {- enum : u32 {- // "Specifies that the white point SHOULD be maintained.- // Typically used when logical colors MUST be matched to their nearest physical color in the destination color gamut.- //- // Intent: Match- //- // ICC name: Absolute Colorimetric"- ABS_COLORIMETRIC = 8,-- // "Specifies that saturation SHOULD be maintained.- // Typically used for business charts and other situations in which dithering is not required.- //- // Intent: Graphic- //- // ICC name: Saturation"- BUSINESS = 1,-- // "Specifies that a colorimetric match SHOULD be maintained.- // Typically used for graphic designs and named colors.- //- // Intent: Proof- //- // ICC name: Relative Colorimetric"- GRAPHICS = 2,-- // "Specifies that contrast SHOULD be maintained.- // Typically used for photographs and natural images.- //- // Intent: Picture- //- // ICC name: Perceptual"- IMAGES = 4,- };-};--// https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapv5header-struct DIBV5 {- u32 intent { 0 };- u32 profile_data { 0 };- u32 profile_size { 0 };-};--struct DIB {- DIBCore core;- DIBInfo info;- DIBOSV2 osv2;- DIBV4 v4;- DIBV5 v5;-};--enum class DIBType {- Core = 0,- OSV2Short,- OSV2,- Info,- V2,- V3,- V4,- V5,-};-struct BMPLoadingContext {- AK_ALLOC_WITH_KMALLOC;-- enum class State {- NotDecoded = 0,- DIBDecoded,- ColorTableDecoded,- PixelDataDecoded,- Error,- };- State state { State::NotDecoded };-- u8 const* file_bytes { nullptr };- size_t file_size { 0 };- u32 data_offset { 0 };-- bool is_included_in_ico { false };-- DIB dib;- DIBType dib_type;-- Vector<u32> color_table;- RefPtr<Gfx::Bitmap> bitmap;-- u32 dib_size() const- {- switch (dib_type) {- case DIBType::Core:- return 12;- case DIBType::OSV2Short:- return 16;- case DIBType::OSV2:- return 64;- case DIBType::Info:- return 40;- case DIBType::V2:- return 52;- case DIBType::V3:- return 56;- case DIBType::V4:- return 108;- case DIBType::V5:- return 124;- }+ AK_MAKE_NONCOPYABLE(BMPLoadingContext);+ AK_MAKE_NONMOVABLE(BMPLoadingContext);- VERIFY_NOT_REACHED();- }-};--class InputStreamer {public:- InputStreamer(u8 const* data, size_t size)- : m_data_ptr(data)- , m_size_remaining(size)- {- }-- u8 read_u8()- {- VERIFY(m_size_remaining >= 1);- m_size_remaining--;- return *(m_data_ptr++);- }-- u16 read_u16()- {- return read_u8() | (read_u8() << 8);- }-- u32 read_u24()- {- return read_u8() | (read_u8() << 8) | (read_u8() << 16);- }-- i32 read_i32()- {- return static_cast<i32>(read_u16() | (read_u16() << 16));- }+ AK_ALLOC_WITH_KMALLOC;- u32 read_u32()+ BMPLoadingContext(ImageDecoders::FFI::BMPDecoder* decoder, ImageDecoders::FFI::BMPImageInfo const& info, ReadonlyBytes data)+ : decoder(decoder)+ , info(info)+ , data(data){- return read_u16() | (read_u16() << 16);}- void drop_bytes(u8 num_bytes)+ ~BMPLoadingContext(){- VERIFY(m_size_remaining >= num_bytes);- m_size_remaining -= num_bytes;- m_data_ptr += num_bytes;+ ImageDecoders::FFI::bmp_rust_decoder_free(decoder);}- bool at_end() const { return !m_size_remaining; }-- bool has_u8() const { return m_size_remaining >= 1; }- bool has_u16() const { return m_size_remaining >= 2; }- bool has_u24() const { return m_size_remaining >= 3; }- bool has_u32() const { return m_size_remaining >= 4; }-- size_t remaining() const { return m_size_remaining; }--private:- u8 const* m_data_ptr { nullptr };- size_t m_size_remaining { 0 };-};--// Lookup table for distributing all possible 2-bit numbers evenly into 8-bit numbers-static u8 scaling_factors_2bit[4] = {- 0x00,- 0x55,- 0xaa,- 0xff,-};--// Lookup table for distributing all possible 3-bit numbers evenly into 8-bit numbers-static u8 scaling_factors_3bit[8] = {- 0x00,- 0x24,- 0x48,- 0x6d,- 0x91,- 0xb6,- 0xdb,- 0xff,-};--static u8 scale_masked_8bit_number(u8 number, u8 bits_set)-{- // If there are more than 4 bit set, an easy way to scale the number is to- // just copy the most significant bits into the least significant bits- if (bits_set >= 4)- return number | (number >> bits_set);- if (!bits_set)- return 0;- if (bits_set == 1)- return number ? 0xff : 0;- if (bits_set == 2)- return scaling_factors_2bit[number >> 6];- return scaling_factors_3bit[number >> 5];-}--static u8 get_scaled_color(u32 data, u8 mask_size, i8 mask_shift)-{- // A negative mask_shift indicates we actually need to left shift- // the result in order to get out a valid 8-bit color (for example, the blue- // value in an RGB555 encoding is XXXBBBBB, which needs to be shifted to the- // left by 3, hence it would have a "mask_shift" value of -3).- if (mask_shift < 0)- return scale_masked_8bit_number(data << -mask_shift, mask_size);- return scale_masked_8bit_number(data >> mask_shift, mask_size);-}--// Scales an 8-bit number with "mask_size" bits set (and "8 - mask_size" bits-// ignored). This function scales the number appropriately over the entire-// 256 value color spectrum.-// Note that a much simpler scaling can be done by simple bit shifting. If you-// just ignore the bottom 8-mask_size bits, then you get *close*. However,-// consider, as an example, a 5 bit number (so the bottom 3 bits are ignored).-// The purest white you could get is 0xf8, which is 248 in RGB-land. We need-// to scale the values in order to reach the proper value of 255.-static u32 int_to_scaled_rgb(BMPLoadingContext& context, u32 data)-{- dbgln_if(BMP_DEBUG, "DIB info sizes before access: #masks={}, #mask_sizes={}, #mask_shifts={}",- context.dib.info.masks.size(),- context.dib.info.mask_sizes.size(),- context.dib.info.mask_shifts.size());-- u8 r = get_scaled_color(data & context.dib.info.masks[0], context.dib.info.mask_sizes[0], context.dib.info.mask_shifts[0]);- u8 g = get_scaled_color(data & context.dib.info.masks[1], context.dib.info.mask_sizes[1], context.dib.info.mask_shifts[1]);- u8 b = get_scaled_color(data & context.dib.info.masks[2], context.dib.info.mask_sizes[2], context.dib.info.mask_shifts[2]);- u32 color = (r << 16) | (g << 8) | b;-- if (context.dib.info.masks.size() == 4) {- // The bitmap has an alpha mask- u8 a = get_scaled_color(data & context.dib.info.masks[3], context.dib.info.mask_sizes[3], context.dib.info.mask_shifts[3]);- color |= (a << 24);- } else {- color |= 0xff000000;- }-- return color;-}--static void populate_dib_mask_info_if_needed(BMPLoadingContext& context)-{- if (context.dib.info.masks.is_empty())- return;-- // Mask shift is the number of right shifts needed to align the MSb of the- // mask to the MSb of the LSB. Note that this can be a negative number.- // Mask size is the number of set bits in the mask. This is required for- // color scaling (for example, ensuring that a 4-bit color value spans the- // entire 256 value color spectrum.- auto& masks = context.dib.info.masks;- auto& mask_shifts = context.dib.info.mask_shifts;- auto& mask_sizes = context.dib.info.mask_sizes;-- if (!mask_shifts.is_empty() && !mask_sizes.is_empty())- return;-- VERIFY(mask_shifts.is_empty() && mask_sizes.is_empty());-- mask_shifts.ensure_capacity(masks.size());- mask_sizes.ensure_capacity(masks.size());-- for (size_t i = 0; i < masks.size(); ++i) {- u32 mask = masks[i];- if (!mask) {- mask_shifts.append(0);- mask_sizes.append(0);- continue;- }- int trailing_zeros = count_trailing_zeroes(mask);- // If mask is exactly `0xFFFFFFFF`, then we might try to count the trailing zeros of 0x00000000 here, so we need the safe version:- int size = count_trailing_zeroes_safe(~(mask >> trailing_zeros));- if (size > 8) {- // Drop lowest bits if mask is longer than 8 bits.- trailing_zeros += size - 8;- size = 8;- }- mask_shifts.append(size + trailing_zeros - 8);- mask_sizes.append(size);- }-}--static bool check_for_invalid_bitmask_combinations(BMPLoadingContext& context)-{- auto& bpp = context.dib.core.bpp;- auto& compression = context.dib.info.compression;-- if (compression == Compression::ALPHABITFIELDS && context.dib_type != DIBType::Info)- return false;-- switch (context.dib_type) {- case DIBType::Core:- if (bpp == 2 || bpp == 16 || bpp == 32)- return false;- break;- case DIBType::Info:- switch (compression) {- case Compression::BITFIELDS:- case Compression::ALPHABITFIELDS:- if (bpp != 16 && bpp != 32)- return false;- break;- case Compression::RGB:- break;- case Compression::RLE8:- if (bpp > 8)- return false;- break;- case Compression::RLE4:- if (bpp > 4)- return false;- break;- default:- // Other compressions are not officially supported.- // Technically, we could even drop ALPHABITFIELDS.- return false;- }- break;- case DIBType::OSV2Short:- case DIBType::OSV2:- case DIBType::V2:- case DIBType::V3:- case DIBType::V4:- case DIBType::V5:- if (compression == Compression::BITFIELDS && bpp != 16 && bpp != 32)- return false;- if (compression == Compression::RLE8 && bpp > 8)- return false;- if (compression == Compression::RLE4 && bpp > 4)- return false;- break;- }-- return true;-}--static bool set_dib_bitmasks(BMPLoadingContext& context, InputStreamer& streamer)-{- if (!check_for_invalid_bitmask_combinations(context))- return false;-- auto& bpp = context.dib.core.bpp;- if (bpp <= 8 || bpp == 24)- return true;-- auto& compression = context.dib.info.compression;- auto& type = context.dib_type;-- if (type > DIBType::OSV2 && bpp == 16 && compression == Compression::RGB) {- context.dib.info.masks.extend({ 0x7c00, 0x03e0, 0x001f });- context.dib.info.mask_shifts.extend({ 7, 2, -3 });- context.dib.info.mask_sizes.extend({ 5, 5, 5 });- } else if (type == DIBType::Info && (compression == Compression::BITFIELDS || compression == Compression::ALPHABITFIELDS)) {- // Consume the extra BITFIELDS bytes- auto number_of_mask_fields = compression == Compression::ALPHABITFIELDS ? 4 : 3;-- for (auto i = 0; i < number_of_mask_fields; i++) {- if (!streamer.has_u32())- return false;- context.dib.info.masks.append(streamer.read_u32());- }- }-- populate_dib_mask_info_if_needed(context);- return true;-}--static ErrorOr<void> decode_bmp_header(BMPLoadingContext& context)-{- if (!context.file_bytes || context.file_size < bmp_header_size) {- dbgln_if(BMP_DEBUG, "Missing BMP header");- context.state = BMPLoadingContext::State::Error;- return Error::from_string_literal("Missing BMP header");- }-- InputStreamer streamer(context.file_bytes, bmp_header_size);-- u16 header = streamer.read_u16();- if (header != 0x4d42) {- dbgln_if(BMP_DEBUG, "BMP has invalid magic header number: {:#04x}", header);- context.state = BMPLoadingContext::State::Error;- return Error::from_string_literal("BMP has invalid magic header number");- }-- // The reported size of the file in the header is actually not important- // for decoding the file. Some specifications say that this value should- // be the size of the header instead, so we just rely on the known file- // size, instead of a possibly-correct-but-also-possibly-incorrect reported- // value of the file size.- streamer.drop_bytes(4);-- // Ignore reserved bytes- streamer.drop_bytes(4);- context.data_offset = streamer.read_u32();- if (context.data_offset >= context.file_size) {- dbgln_if(BMP_DEBUG, "BMP has invalid data offset: {}", context.data_offset);- context.state = BMPLoadingContext::State::Error;- return Error::from_string_literal("BMP has invalid data offset");- }-- if constexpr (BMP_DEBUG) {- dbgln("BMP file size: {}", context.file_size);- dbgln("BMP data offset: {}", context.data_offset);- }-- if (context.data_offset >= context.file_size) {- dbgln_if(BMP_DEBUG, "BMP data offset is beyond file end?!");- return Error::from_string_literal("BMP data offset is beyond file end");- }-- return {};-}--static bool decode_bmp_core_dib(BMPLoadingContext& context, InputStreamer& streamer)-{- auto& core = context.dib.core;-- // The width and height are u16 fields in the actual BITMAPCOREHEADER format.- if (context.dib_type == DIBType::Core) {- core.width = streamer.read_u16();- core.height = streamer.read_u16();- } else {- core.width = streamer.read_i32();- core.height = streamer.read_i32();- }-- if (core.width < 0) {- dbgln("BMP has a negative width: {}", core.width);- return false;- }- if (core.height == NumericLimits<i32>::min()) {- dbgln("BMP has an invalid height: {}", core.height);- return false;- }-- auto color_planes = streamer.read_u16();- if (color_planes != 1) {- dbgln("BMP has an invalid number of color planes: {}", color_planes);- return false;- }-- core.bpp = streamer.read_u16();- switch (core.bpp) {- case 1:- case 2:- case 4:- case 8:- case 16:- case 24:- case 32:- break;- default:- dbgln("BMP has an invalid bpp: {}", core.bpp);- context.state = BMPLoadingContext::State::Error;- return false;- }-- if constexpr (BMP_DEBUG) {- dbgln("BMP width: {}", core.width);- dbgln("BMP height: {}", core.height);- dbgln("BMP bits_per_pixel: {}", core.bpp);- }-- return true;-}--ALWAYS_INLINE static bool is_supported_compression_format(BMPLoadingContext& context, u32 compression)-{- return compression == Compression::RGB || compression == Compression::BITFIELDS- || compression == Compression::ALPHABITFIELDS || compression == Compression::RLE8- || compression == Compression::RLE4 || (compression == Compression::RLE24 && context.dib_type <= DIBType::OSV2);-}--static bool decode_bmp_osv2_dib(BMPLoadingContext& context, InputStreamer& streamer, bool short_variant = false)-{- auto& core = context.dib.core;-- core.width = streamer.read_u32();- core.height = streamer.read_u32();-- if (core.width < 0) {- dbgln("BMP has a negative width: {}", core.width);- return false;- }- if (core.height == NumericLimits<i32>::min()) {- dbgln("BMP has an invalid height: {}", core.height);- return false;- }-- auto color_planes = streamer.read_u16();- if (color_planes != 1) {- dbgln("BMP has an invalid number of color planes: {}", color_planes);- return false;- }-- core.bpp = streamer.read_u16();- switch (core.bpp) {- case 1:- case 2:- case 4:- case 8:- case 24:- break;- default:- // OS/2 didn't expect 16- or 32-bpp to be popular.- dbgln("BMP has an invalid bpp: {}", core.bpp);- context.state = BMPLoadingContext::State::Error;- return false;- }-- if constexpr (BMP_DEBUG) {- dbgln("BMP width: {}", core.width);- dbgln("BMP height: {}", core.height);- dbgln("BMP bits_per_pixel: {}", core.bpp);- }-- if (short_variant)- return true;-- auto& info = context.dib.info;- auto& osv2 = context.dib.osv2;-- info.compression = streamer.read_u32();- info.image_size = streamer.read_u32();- info.horizontal_resolution = streamer.read_u32();- info.vertical_resolution = streamer.read_u32();- info.number_of_palette_colors = streamer.read_u32();- info.number_of_important_palette_colors = streamer.read_u32();-- if (!is_supported_compression_format(context, info.compression)) {- dbgln("BMP has unsupported compression value: {}", info.compression);- return false;- }-- info.number_of_palette_colors = min(info.number_of_palette_colors, color_palette_limit);- info.number_of_important_palette_colors = min(info.number_of_important_palette_colors, color_palette_limit);-- // Units (2) + reserved (2)- streamer.drop_bytes(4);-- osv2.recording = streamer.read_u16();- osv2.halftoning = streamer.read_u16();- osv2.size1 = streamer.read_u32();- osv2.size2 = streamer.read_u32();-- // ColorEncoding (4) + Identifier (4)- streamer.drop_bytes(8);-- if constexpr (BMP_DEBUG) {- dbgln("BMP compression: {}", info.compression);- dbgln("BMP image size: {}", info.image_size);- dbgln("BMP horizontal res: {}", info.horizontal_resolution);- dbgln("BMP vertical res: {}", info.vertical_resolution);- dbgln("BMP colors: {}", info.number_of_palette_colors);- dbgln("BMP important colors: {}", info.number_of_important_palette_colors);- }-- return true;-}--static bool decode_bmp_info_dib(BMPLoadingContext& context, InputStreamer& streamer)-{- if (!decode_bmp_core_dib(context, streamer))- return false;-- auto& info = context.dib.info;-- auto compression = streamer.read_u32();- info.compression = compression;- if (!is_supported_compression_format(context, compression)) {- dbgln("BMP has unsupported compression value: {}", compression);- return false;- }-- info.image_size = streamer.read_u32();- info.horizontal_resolution = streamer.read_i32();- info.vertical_resolution = streamer.read_i32();- info.number_of_palette_colors = streamer.read_u32();- info.number_of_important_palette_colors = streamer.read_u32();-- info.number_of_palette_colors = min(info.number_of_palette_colors, color_palette_limit);- info.number_of_important_palette_colors = min(info.number_of_important_palette_colors, color_palette_limit);-- if (info.number_of_important_palette_colors == 0)- info.number_of_important_palette_colors = info.number_of_palette_colors;-- if constexpr (BMP_DEBUG) {- dbgln("BMP compression: {}", info.compression);- dbgln("BMP image size: {}", info.image_size);- dbgln("BMP horizontal res: {}", info.horizontal_resolution);- dbgln("BMP vertical res: {}", info.vertical_resolution);- dbgln("BMP colors: {}", info.number_of_palette_colors);- dbgln("BMP important colors: {}", info.number_of_important_palette_colors);- }-- return true;-}--static bool decode_bmp_v2_dib(BMPLoadingContext& context, InputStreamer& streamer)-{- if (!decode_bmp_info_dib(context, streamer))- return false;-- if (context.dib.info.compression != Compression::BITFIELDS && context.dib.info.compression != Compression::ALPHABITFIELDS) {- streamer.drop_bytes(12);- return true;- }-- context.dib.info.masks.append(streamer.read_u32());- context.dib.info.masks.append(streamer.read_u32());- context.dib.info.masks.append(streamer.read_u32());-- if constexpr (BMP_DEBUG) {- dbgln("BMP red mask: {:#08x}", context.dib.info.masks[0]);- dbgln("BMP green mask: {:#08x}", context.dib.info.masks[1]);- dbgln("BMP blue mask: {:#08x}", context.dib.info.masks[2]);- }-- return true;-}--static bool decode_bmp_v3_dib(BMPLoadingContext& context, InputStreamer& streamer)-{- if (!decode_bmp_v2_dib(context, streamer))- return false;-- // There is zero documentation about when alpha masks actually get applied.- // Well, there's some, but it's not even close to comprehensive. So, this is- // in no way based off of any spec, it's simply based off of the BMP test- // suite results.- if (context.dib.info.compression == Compression::ALPHABITFIELDS) {- context.dib.info.masks.append(streamer.read_u32());- dbgln_if(BMP_DEBUG, "BMP alpha mask: {:#08x}", context.dib.info.masks[3]);- } else if (context.dib_size() >= 56 && context.dib.core.bpp >= 16) {- auto mask = streamer.read_u32();- if (context.dib.info.compression == Compression::RGB && context.dib.core.bpp == 32 && mask != 0)- context.dib.info.masks.extend({ 0xff0000, 0x00ff00, 0x0000ff });- if ((context.dib.core.bpp == 32 && mask != 0) || (context.dib.core.bpp == 16 && context.dib.info.compression != Compression::RGB)) {- context.dib.info.masks.append(mask);- dbgln_if(BMP_DEBUG, "BMP alpha mask: {:#08x}", mask);- } else {- dbgln_if(BMP_DEBUG, "BMP alpha mask (ignored): {:#08x}", mask);- }- } else {- streamer.drop_bytes(4);- dbgln_if(BMP_DEBUG, "BMP alpha mask skipped");- }-- return true;-}--static bool decode_bmp_v4_dib(BMPLoadingContext& context, InputStreamer& streamer)-{- if (!decode_bmp_v3_dib(context, streamer))- return false;-- auto& v4 = context.dib.v4;- v4.color_space = streamer.read_u32();- v4.red_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };- v4.green_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };- v4.blue_endpoint = { streamer.read_i32(), streamer.read_i32(), streamer.read_i32() };- v4.gamma_endpoint = { streamer.read_u32(), streamer.read_u32(), streamer.read_u32() };-- if constexpr (BMP_DEBUG) {- dbgln("BMP color space: {}", v4.color_space);- dbgln("BMP red endpoint: {}", v4.red_endpoint);- dbgln("BMP green endpoint: {}", v4.green_endpoint);- dbgln("BMP blue endpoint: {}", v4.blue_endpoint);- dbgln("BMP gamma endpoint: {}", v4.gamma_endpoint);- }-- return true;-}--static bool decode_bmp_v5_dib(BMPLoadingContext& context, InputStreamer& streamer)-{- if (!decode_bmp_v4_dib(context, streamer))- return false;-- auto& v5 = context.dib.v5;- v5.intent = streamer.read_u32();- v5.profile_data = streamer.read_u32();- v5.profile_size = streamer.read_u32();- streamer.drop_bytes(4); // Ignore reserved field.-- if constexpr (BMP_DEBUG) {- dbgln("BMP intent: {}", v5.intent);- dbgln("BMP profile data: {}", v5.profile_data);- dbgln("BMP profile size: {}", v5.profile_size);- }-- return true;-}--static ErrorOr<void> decode_bmp_dib(BMPLoadingContext& context)-{- if (context.state == BMPLoadingContext::State::Error)- return Error::from_string_literal("Error before starting decode_bmp_dib");-- if (context.state >= BMPLoadingContext::State::DIBDecoded)- return {};-- if (!context.is_included_in_ico)- TRY(decode_bmp_header(context));-- u8 header_size = context.is_included_in_ico ? 0 : bmp_header_size;-- if (context.file_size < header_size + 4u)- return Error::from_string_literal("File size too short");-- InputStreamer streamer(context.file_bytes + header_size, 4);-- u64 dib_size = streamer.read_u32();-- if (context.file_size < header_size + dib_size)- return Error::from_string_literal("File size too short");-- if (!context.is_included_in_ico && (context.data_offset < header_size + dib_size)) {- dbgln("Shenanigans! BMP pixel data and header usually don't overlap.");- return Error::from_string_literal("BMP pixel data and header usually don't overlap");- }-- // NOTE: If this is a headless BMP (embedded on ICO files), then we can only infer the data_offset after we know the data table size.- // We are also assuming that no Extra bit masks are present- u64 dib_offset = dib_size;- if (!context.is_included_in_ico) {- if (context.data_offset < header_size + 4u)- return Error::from_string_literal("Data offset too small");-- dib_offset = context.data_offset - header_size - 4;- }-- if (dib_offset + header_size + 4 >= context.file_size)- return Error::from_string_literal("DIB too large");-- streamer = InputStreamer(context.file_bytes + header_size + 4, dib_offset);-- dbgln_if(BMP_DEBUG, "BMP dib size: {}", dib_size);-- bool error = false;-- if (dib_size == 12) {- context.dib_type = DIBType::Core;- if (!decode_bmp_core_dib(context, streamer))- error = true;- } else if (dib_size == 64) {- context.dib_type = DIBType::OSV2;- if (!decode_bmp_osv2_dib(context, streamer))- error = true;- } else if (dib_size == 16) {- context.dib_type = DIBType::OSV2Short;- if (!decode_bmp_osv2_dib(context, streamer, true))- error = true;- } else if (dib_size == 40) {- context.dib_type = DIBType::Info;- if (!decode_bmp_info_dib(context, streamer))- error = true;- } else if (dib_size == 52) {- context.dib_type = DIBType::V2;- if (!decode_bmp_v2_dib(context, streamer))- error = true;- } else if (dib_size == 56) {- context.dib_type = DIBType::V3;- if (!decode_bmp_v3_dib(context, streamer))- error = true;- } else if (dib_size == 108) {- context.dib_type = DIBType::V4;- if (!decode_bmp_v4_dib(context, streamer))- error = true;- } else if (dib_size == 124) {- context.dib_type = DIBType::V5;- if (!decode_bmp_v5_dib(context, streamer))- error = true;- } else {- dbgln("Unsupported BMP DIB size: {}", dib_size);- error = true;- }-- switch (context.dib.info.compression) {- case Compression::RGB:- case Compression::RLE8:- case Compression::RLE4:- case Compression::BITFIELDS:- case Compression::RLE24:- case Compression::PNG:- case Compression::ALPHABITFIELDS:- case Compression::CMYK:- case Compression::CMYKRLE8:- case Compression::CMYKRLE4:- break;- default:- error = true;- }-- if (!error && !set_dib_bitmasks(context, streamer))- error = true;-- if (error) {- dbgln("BMP has an invalid DIB");- context.state = BMPLoadingContext::State::Error;- return Error::from_string_literal("BMP has an invalid DIB");- }-- // NOTE: If this is a headless BMP (included on ICOns), the data_offset is set based on the number_of_palette_colors found on the DIB header- if (context.is_included_in_ico) {- if (context.dib.core.bpp > 8)- context.data_offset = dib_size;- else {- auto bytes_per_color = context.dib_type == DIBType::Core ? 3 : 4;- u32 max_colors = 1 << context.dib.core.bpp;- auto size_of_color_table = (context.dib.info.number_of_palette_colors > 0 ? context.dib.info.number_of_palette_colors : max_colors) * bytes_per_color;- context.data_offset = dib_size + size_of_color_table;- }- }-- if (context.data_offset >= context.file_size) {- dbgln_if(BMP_DEBUG, "BMP has invalid data offset: {}", context.data_offset);- context.state = BMPLoadingContext::State::Error;- return Error::from_string_literal("BMP has invalid data offset");- }-- context.state = BMPLoadingContext::State::DIBDecoded;-- return {};-}--static ErrorOr<void> decode_bmp_color_table(BMPLoadingContext& context)-{- if (context.state == BMPLoadingContext::State::Error)- return Error::from_string_literal("Error before starting decode_bmp_color_table");-- if (context.state >= BMPLoadingContext::State::ColorTableDecoded)- return {};-- if (context.dib.core.bpp > 8) {- context.state = BMPLoadingContext::State::ColorTableDecoded;- return {};- }-- // OS/2 1.x (Core) uses 3 bytes per color- // OS/2 2.x (OSV2) can use 3 or 4 bytes per color- u8 bytes_per_color;- if (context.dib_type == DIBType::Core) {- bytes_per_color = 3;- } else if (context.dib_type == DIBType::OSV2 || context.dib_type == DIBType::OSV2Short) {- // For OS/2 2.x we need to determine the number of bytes per color based on the size of the color table- u8 header_size = context.is_included_in_ico ? 0 : bmp_header_size;- u32 available_size = context.data_offset - header_size - context.dib_size();- u32 max_colors = 1 << context.dib.core.bpp;-- if (available_size == 3 * max_colors) {- bytes_per_color = 3;- } else {- bytes_per_color = 4;- }- } else {- bytes_per_color = 4;- }-- u32 max_colors = 1 << context.dib.core.bpp;-- u8 header_size = !context.is_included_in_ico ? bmp_header_size : 0;- VERIFY(context.data_offset >= header_size + context.dib_size());-- u32 size_of_color_table;- if (!context.is_included_in_ico) {- size_of_color_table = context.data_offset - header_size - context.dib_size();- } else {- size_of_color_table = (context.dib.info.number_of_palette_colors > 0 ? context.dib.info.number_of_palette_colors : max_colors) * bytes_per_color;- }-- if (context.dib_type <= DIBType::OSV2) {- // Partial color tables are not supported, so the space of the color- // table must be at least enough for the maximum amount of colors- if (size_of_color_table < bytes_per_color * max_colors) {- // This is against the spec, but most viewers process it anyways- dbgln("BMP with CORE header does not have enough colors. Has: {}, expected: {}", size_of_color_table, (bytes_per_color * max_colors));- }- }-- InputStreamer streamer(context.file_bytes + header_size + context.dib_size(), size_of_color_table);- for (u32 i = 0; !streamer.at_end() && i < max_colors; ++i) {- if (bytes_per_color == 4) {- if (!streamer.has_u32())- return Error::from_string_literal("Cannot read 32 bits");- context.color_table.append(streamer.read_u32() | 0xff'00'00'00);- } else {- if (!streamer.has_u24())- return Error::from_string_literal("Cannot read 24 bits");- context.color_table.append(streamer.read_u24() | 0xff'00'00'00);- }- }-- context.state = BMPLoadingContext::State::ColorTableDecoded;-- return {};-}--struct RLEState {- enum : u8 {- PixelCount = 0,- PixelValue,- Meta, // Represents just consuming a null byte, which indicates something special+ enum class State : u8 {+ HeaderDecoded,+ PixelDataDecoded,+ Error,};++ ImageDecoders::FFI::BMPDecoder* decoder { nullptr };+ ImageDecoders::FFI::BMPImageInfo info {};+ ReadonlyBytes data;+ State state { State::HeaderDecoded };+ RefPtr<Bitmap> bitmap;};-static ErrorOr<void> uncompress_bmp_rle_data(BMPLoadingContext& context, ByteBuffer& buffer)+static BitmapFormat to_bitmap_format(ImageDecoders::FFI::BMPBitmapFormat format){- // RLE-compressed images cannot be stored top-down- if (context.dib.core.height < 0) {- dbgln_if(BMP_DEBUG, "BMP is top-down and RLE compressed");- context.state = BMPLoadingContext::State::Error;- return Error::from_string_literal("BMP is top-down and RLE compressed");- }-- InputStreamer streamer(context.file_bytes + context.data_offset, context.file_size - context.data_offset);-- auto compression = context.dib.info.compression;-- u32 total_rows = static_cast<u32>(context.dib.core.height);- u32 total_columns = round_up_to_power_of_two(static_cast<u32>(context.dib.core.width), 4);- u32 column = 0;- u32 row = 0;- auto currently_consuming = RLEState::PixelCount;- i16 pixel_count = 0;-- // ByteBuffer asserts that allocating the memory never fails.- // FIXME: ByteBuffer should return either RefPtr<> or Optional<>.- // Decoding the RLE data on-the-fly might actually be faster, and avoids this topic entirely.- u32 buffer_size;- if (compression == Compression::RLE24) {- buffer_size = total_rows * round_up_to_power_of_two(total_columns, 4) * 3;- } else {- buffer_size = total_rows * round_up_to_power_of_two(total_columns, 4);- }- if (buffer_size > 300 * MiB) {- dbgln("Suspiciously large amount of RLE data");- return Error::from_string_literal("Suspiciously large amount of RLE data");- }- auto buffer_result = ByteBuffer::create_zeroed(buffer_size);- if (buffer_result.is_error()) {- dbgln("Not enough memory for buffer allocation");- return buffer_result.release_error();- }- buffer = buffer_result.release_value();-- // Avoid as many if statements as possible by pulling out- // compression-dependent actions into separate lambdas- Function<u32()> get_buffer_index;- Function<ErrorOr<void>(u32, bool)> set_byte;- Function<ErrorOr<u32>()> read_byte;-- if (compression == Compression::RLE8) {- get_buffer_index = [&]() -> u32 { return row * total_columns + column; };- } else if (compression == Compression::RLE4) {- get_buffer_index = [&]() -> u32 { return (row * total_columns + column) / 2; };- } else {- get_buffer_index = [&]() -> u32 { return (row * total_columns + column) * 3; };- }-- if (compression == Compression::RLE8) {- set_byte = [&](u32 color, bool) -> ErrorOr<void> {- if (column >= total_columns) {- column = 0;- row++;- }- auto index = get_buffer_index();- if (index >= buffer.size()) {- dbgln("BMP has badly-formatted RLE data");- return Error::from_string_literal("BMP has badly-formatted RLE data");- }- buffer[index] = color;- column++;- return {};- };- } else if (compression == Compression::RLE24) {- set_byte = [&](u32 color, bool) -> ErrorOr<void> {- if (column >= total_columns) {- column = 0;- row++;- }- auto index = get_buffer_index();- if (index + 2 >= buffer.size()) {- dbgln("BMP has badly-formatted RLE data");- return Error::from_string_literal("BMP has badly-formatted RLE data");- }- buffer[index] = color & 0xff;- buffer[index + 1] = (color >> 8) & 0xff;- buffer[index + 2] = (color >> 16) & 0xff;- column++;- return {};- };- } else {- set_byte = [&](u32 byte, bool rle4_set_second_nibble) -> ErrorOr<void> {- if (column >= total_columns) {- column = 0;- row++;- }-- u32 index = get_buffer_index();- if (index >= buffer.size() || (rle4_set_second_nibble && index + 1 >= buffer.size())) {- dbgln("BMP has badly-formatted RLE data");- return Error::from_string_literal("BMP has badly-formatted RLE data");- }-- if (column % 2) {- buffer[index] |= byte >> 4;- if (rle4_set_second_nibble) {- buffer[index + 1] |= byte << 4;- column++;- }- } else {- if (rle4_set_second_nibble) {- buffer[index] = byte;- column++;- } else {- buffer[index] |= byte & 0xf0;- }- }-- column++;- return {};- };- }-- if (compression == Compression::RLE24) {- read_byte = [&]() -> ErrorOr<u32> {- if (!streamer.has_u24()) {- dbgln("BMP has badly-formatted RLE data");- return Error::from_string_literal("BMP has badly-formatted RLE data");- }- return streamer.read_u24();- };- } else {- read_byte = [&]() -> ErrorOr<u32> {- if (!streamer.has_u8()) {- dbgln("BMP has badly-formatted RLE data");- return Error::from_string_literal("BMP has badly-formatted RLE data");- }- return streamer.read_u8();- };- }-- while (true) {- u32 byte;-- switch (currently_consuming) {- case RLEState::PixelCount:- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");- byte = streamer.read_u8();- if (!byte) {- currently_consuming = RLEState::Meta;- } else {- pixel_count = byte;- currently_consuming = RLEState::PixelValue;- }- break;- case RLEState::PixelValue:- byte = TRY(read_byte());- for (u16 i = 0; i < pixel_count; ++i) {- if (compression != Compression::RLE4) {- TRY(set_byte(byte, true));- } else {- TRY(set_byte(byte, i != pixel_count - 1));- i++;- }- }-- currently_consuming = RLEState::PixelCount;- break;- case RLEState::Meta:- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");- byte = streamer.read_u8();- if (!byte) {- column = 0;- row++;- currently_consuming = RLEState::PixelCount;- continue;- }- if (byte == 1)- return {};- if (byte == 2) {- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");- u8 offset_x = streamer.read_u8();- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");- u8 offset_y = streamer.read_u8();- column += offset_x;- if (column >= total_columns) {- column -= total_columns;- row++;- }- row += offset_y;- currently_consuming = RLEState::PixelCount;- continue;- }-- // Consume literal bytes- pixel_count = byte;- i16 i = byte;-- while (i >= 1) {- byte = TRY(read_byte());- TRY(set_byte(byte, i != 1));- i--;- if (compression == Compression::RLE4)- i--;- }-- // Optionally consume a padding byte- if (compression != Compression::RLE4) {- if (pixel_count % 2) {- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");- byte = streamer.read_u8();- }- } else {- if (((pixel_count + 1) / 2) % 2) {- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");- byte = streamer.read_u8();- }- }- currently_consuming = RLEState::PixelCount;- break;- }+ switch (format) {+ case ImageDecoders::FFI::BMPBitmapFormat::BGRx8888:+ return BitmapFormat::BGRx8888;+ case ImageDecoders::FFI::BMPBitmapFormat::BGRA8888:+ return BitmapFormat::BGRA8888;+ case ImageDecoders::FFI::BMPBitmapFormat::RGBx8888:+ return BitmapFormat::RGBx8888;}-VERIFY_NOT_REACHED();}-static ErrorOr<void> decode_bmp_pixel_data(BMPLoadingContext& context)+BMPImageDecoderPlugin::BMPImageDecoderPlugin(NonnullOwnPtr<BMPLoadingContext> context)+ : m_context(move(context)){- if (context.state == BMPLoadingContext::State::Error)- return Error::from_string_literal("Error before starting decode_bmp_pixel_data");-- if (context.state <= BMPLoadingContext::State::ColorTableDecoded)- TRY(decode_bmp_color_table(context));-- u16 const bits_per_pixel = context.dib.core.bpp;-- BitmapFormat format = [&]() -> BitmapFormat {- // NOTE: If this is an BMP included in an ICO, the bitmap format will be converted to BGRA8888.- // This is because images with less than 32 bits of color depth follow a particular format:- // the image is encoded with a color mask (the "XOR mask") together with an opacity mask (the "AND mask") of 1 bit per pixel.- // The height of the encoded image must be exactly twice the real height, before both masks are combined.- // Bitmaps have no knowledge of this format as they do not store extra rows for the AND mask.- if (context.is_included_in_ico)- return BitmapFormat::BGRA8888;-- switch (bits_per_pixel) {- case 1:- case 2:- case 4:- case 8:- return BitmapFormat::BGRx8888;- case 16:- if (context.dib.info.masks.size() == 4)- return BitmapFormat::BGRA8888;- return BitmapFormat::BGRx8888;- case 24:- return BitmapFormat::RGBx8888;- case 32:- return BitmapFormat::BGRA8888;- default:- return BitmapFormat::Invalid;- }- }();-- if (format == BitmapFormat::Invalid) {- dbgln("BMP has invalid bpp of {}", bits_per_pixel);- context.state = BMPLoadingContext::State::Error;- return Error::from_string_literal("BMP has invalid bpp");- }-- u32 const width = static_cast<u32>(abs(static_cast<i64>(context.dib.core.width)));- u32 const absolute_height = static_cast<u32>(abs(static_cast<i64>(context.dib.core.height)));- u32 const height = !context.is_included_in_ico ? absolute_height : (absolute_height / 2);-- context.bitmap = TRY(Bitmap::create_shareable_with_gpu_access(format, Gfx::AlphaType::Unpremultiplied, { static_cast<int>(width), static_cast<int>(height) }));-- ByteBuffer rle_buffer;- ReadonlyBytes bytes { context.file_bytes + context.data_offset, context.file_size - context.data_offset };-- if (context.dib.info.compression == Compression::RLE4 || context.dib.info.compression == Compression::RLE8- || context.dib.info.compression == Compression::RLE24) {- TRY(uncompress_bmp_rle_data(context, rle_buffer));- bytes = rle_buffer.bytes();- }-- InputStreamer streamer(bytes.data(), bytes.size());-- auto process_row_padding = [&](u8 const consumed) -> ErrorOr<void> {- // Calculate padding- u8 remaining = consumed % 4;- u8 bytes_to_drop = remaining == 0 ? 0 : 4 - remaining;-- if (streamer.remaining() < bytes_to_drop)- return Error::from_string_literal("Not enough bytes available to drop");- streamer.drop_bytes(bytes_to_drop);-- return {};- };-- auto process_row = [&](u32 row) -> ErrorOr<void> {- u32 space_remaining_before_consuming_row = streamer.remaining();-- for (u32 column = 0; column < width;) {- switch (bits_per_pixel) {- case 1: {- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");- u8 byte = streamer.read_u8();- u8 mask = 8;- while (column < width && mask > 0) {- mask -= 1;- size_t color_idx = (byte >> mask) & 0x1;- if (color_idx >= context.color_table.size())- return Error::from_string_literal("Invalid color table index");- auto color = context.color_table[color_idx];- context.bitmap->scanline(row)[column++] = color;- }- break;- }- case 2: {- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");- u8 byte = streamer.read_u8();- u8 mask = 8;- while (column < width && mask > 0) {- mask -= 2;- size_t color_idx = (byte >> mask) & 0x3;- if (color_idx >= context.color_table.size())- return Error::from_string_literal("Invalid color table index");- auto color = context.color_table[color_idx];- context.bitmap->scanline(row)[column++] = color;- }- break;- }- case 4: {- if (!streamer.has_u8()) {- return Error::from_string_literal("Cannot read 8 bits");- }- u8 byte = streamer.read_u8();-- u32 high_color_idx = (byte >> 4) & 0xf;- u32 low_color_idx = byte & 0xf;-- if (high_color_idx >= context.color_table.size() || low_color_idx >= context.color_table.size())- return Error::from_string_literal("Invalid color table index");- auto high_color = context.color_table[high_color_idx];- auto low_color = context.color_table[low_color_idx];- context.bitmap->scanline(row)[column++] = high_color;- if (column < width) {- context.bitmap->scanline(row)[column++] = low_color;- }- break;- }- case 8: {- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");-- u8 byte = streamer.read_u8();- if (byte >= context.color_table.size())- return Error::from_string_literal("Invalid color table index");- auto color = context.color_table[byte];- context.bitmap->scanline(row)[column++] = color;- break;- }- case 16: {- if (!streamer.has_u16())- return Error::from_string_literal("Cannot read 16 bits");- context.bitmap->scanline(row)[column++] = int_to_scaled_rgb(context, streamer.read_u16());- break;- }- case 24: {- if (!streamer.has_u24())- return Error::from_string_literal("Cannot read 24 bits");-- u32 pixel = streamer.read_u24();-- if (context.is_included_in_ico) {- // 24-bit ICO files already use BGRA8888 format- context.bitmap->scanline(row)[column++] = pixel;- } else {- u8 b = (pixel & 0x0000FF);- u8 g = (pixel & 0x00FF00) >> 8;- u8 r = (pixel & 0xFF0000) >> 16;-- context.bitmap->scanline(row)[column++] = (b << 16) | (g << 8) | r;- }-- break;- }- case 32:- if (!streamer.has_u32())- return Error::from_string_literal("Cannot read 32 bits");- if (context.dib.info.masks.is_empty()) {- context.bitmap->scanline(row)[column++] = streamer.read_u32();- } else {- context.bitmap->scanline(row)[column++] = int_to_scaled_rgb(context, streamer.read_u32());- }- break;- }- }-- auto consumed = space_remaining_before_consuming_row - streamer.remaining();-- return process_row_padding(consumed);- };-- auto process_mask_row = [&](u32 row) -> ErrorOr<void> {- u32 space_remaining_before_consuming_row = streamer.remaining();-- for (u32 column = 0; column < width;) {- if (!streamer.has_u8())- return Error::from_string_literal("Cannot read 8 bits");-- u8 byte = streamer.read_u8();- u8 mask = 8;- while (column < width && mask > 0) {- mask -= 1;- // apply transparency mask- // AND mask = 0 -> fully opaque- // AND mask = 1 -> fully transparent- u8 and_byte = (byte >> (mask)) & 0x1;- auto pixel = context.bitmap->scanline(row)[column];-- if (and_byte) {- pixel &= 0x00ffffff;- } else if (context.dib.core.bpp < 32) {- pixel |= 0xff000000;- }-- context.bitmap->scanline(row)[column++] = pixel;- }- }-- auto consumed = space_remaining_before_consuming_row - streamer.remaining();- return process_row_padding(consumed);- };-- if (context.dib.core.height < 0) {- // BMP is stored top-down- for (u32 row = 0; row < height; ++row) {- TRY(process_row(row));- }-- if (context.is_included_in_ico && !streamer.at_end()) {- for (u32 row = 0; row < height; ++row) {- TRY(process_mask_row(row));- }- }- } else {- // BMP is stored bottom-up- for (i32 row = height - 1; row >= 0; --row) {- TRY(process_row(row));- }-- if (context.is_included_in_ico && !streamer.at_end()) {- for (i32 row = height - 1; row >= 0; --row) {- TRY(process_mask_row(row));- }- }- }-- context.state = BMPLoadingContext::State::PixelDataDecoded;-- return {};-}--BMPImageDecoderPlugin::BMPImageDecoderPlugin(u8 const* data, size_t data_size, IncludedInICO is_included_in_ico)-{- m_context = make<BMPLoadingContext>();- m_context->file_bytes = data;- m_context->file_size = data_size;- m_context->is_included_in_ico = (is_included_in_ico == IncludedInICO::Yes);}BMPImageDecoderPlugin::~BMPImageDecoderPlugin() = default;IntSize BMPImageDecoderPlugin::size(){- return { m_context->dib.core.width, abs(m_context->dib.core.height) };+ return { static_cast<int>(m_context->info.width), static_cast<int>(m_context->info.height) };}bool BMPImageDecoderPlugin::sniff(ReadonlyBytes data){- BMPLoadingContext context;- context.file_bytes = data.data();- context.file_size = data.size();- return !decode_bmp_header(context).is_error();+ return ImageDecoders::FFI::bmp_rust_sniff(data.data(), data.size());}ErrorOr<NonnullOwnPtr<BMPImageDecoderPlugin>> BMPImageDecoderPlugin::create_impl(ReadonlyBytes data, IncludedInICO included_in_ico){- auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) BMPImageDecoderPlugin(data.data(), data.size(), included_in_ico)));- TRY(decode_bmp_dib(*plugin->m_context));- return plugin;+ ImageDecoders::FFI::BMPImageInfo info {};+ auto* decoder = ImageDecoders::FFI::bmp_rust_decoder_new(data.data(), data.size(), included_in_ico == IncludedInICO::Yes, &info);+ if (!decoder)+ return Error::from_string_literal("BMPImageDecoderPlugin: BMP has an invalid header");+ ArmedScopeGuard free_decoder = [decoder] { ImageDecoders::FFI::bmp_rust_decoder_free(decoder); };++ if (info.width > static_cast<u32>(NumericLimits<int>::max()) || info.height > static_cast<u32>(NumericLimits<int>::max()))+ return Error::from_string_literal("BMPImageDecoderPlugin: Image dimensions are too large");++ auto context = TRY(adopt_nonnull_own_or_enomem(new (nothrow) BMPLoadingContext(decoder, info, data)));+ free_decoder.disarm();++ return TRY(adopt_nonnull_own_or_enomem(new (nothrow) BMPImageDecoderPlugin(move(context))));}ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> BMPImageDecoderPlugin::create(ReadonlyBytes data)@@ -1550,11 +102,6 @@ ErrorOr<NonnullOwnPtr<BMPImageDecoderPlugin>> BMPImageDecoderPlugin::create_as_ireturn create_impl(data, IncludedInICO::Yes);}-bool BMPImageDecoderPlugin::sniff_dib()-{- return !decode_bmp_dib(*m_context).is_error();-}-ErrorOr<ImageFrameDescriptor> BMPImageDecoderPlugin::frame(size_t index, Optional<IntSize>){if (index > 0)@@ -1563,35 +110,31 @@ ErrorOr<ImageFrameDescriptor> BMPImageDecoderPlugin::frame(size_t index, Optionaif (m_context->state == BMPLoadingContext::State::Error)return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed");- if (m_context->state < BMPLoadingContext::State::PixelDataDecoded)- TRY(decode_bmp_pixel_data(*m_context));+ if (m_context->state == BMPLoadingContext::State::HeaderDecoded) {+ auto bitmap = TRY(Bitmap::create_shareable_with_gpu_access(to_bitmap_format(m_context->info.format), AlphaType::Unpremultiplied, size()));+ if (!ImageDecoders::FFI::bmp_rust_decode(m_context->decoder, m_context->data.data(), m_context->data.size(), bitmap->unchecked_scanline_u8(0), bitmap->pitch())) {+ m_context->state = BMPLoadingContext::State::Error;+ return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed");+ }+ m_context->bitmap = move(bitmap);+ m_context->state = BMPLoadingContext::State::PixelDataDecoded;+ }- VERIFY(m_context->bitmap);return ImageFrameDescriptor { *m_context->bitmap, 0 };}ErrorOr<Optional<ReadonlyBytes>> BMPImageDecoderPlugin::icc_data(){- if (m_context->dib_type != DIBType::V5)- return OptionalNone {};-- // FIXME: For LINKED, return data from the linked file?- // FIXME: For sRGB and WINDOWS_COLOR_SPACE, return an sRGB profile somehow.- // FIXME: For CALIBRATED_RGB, do something with v4.{red_endpoint,green_endpoint,blue_endpoint,gamma_endpoint}- if (m_context->dib.v4.color_space != BMP::ColorSpace::EMBEDDED)- return OptionalNone {};-- auto const& v5 = m_context->dib.v5;- if (!v5.profile_data || !v5.profile_size)+ auto const& info = m_context->info;+ switch (info.icc_profile) {+ case ImageDecoders::FFI::BMPICCProfile::Absent:return OptionalNone {};-- // FIXME: Do something with v5.intent (which has a GamutMappingIntent value).-- u8 header_size = m_context->is_included_in_ico ? 0 : bmp_header_size;- if (static_cast<u64>(v5.profile_data) + header_size + v5.profile_size > m_context->file_size)+ case ImageDecoders::FFI::BMPICCProfile::OutOfBounds:return Error::from_string_literal("BMPImageDecoderPlugin: ICC profile data out of bounds");-- return ReadonlyBytes { m_context->file_bytes + header_size + v5.profile_data, v5.profile_size };+ case ImageDecoders::FFI::BMPICCProfile::Embedded:+ return m_context->data.slice(info.icc_profile_offset, info.icc_profile_size);+ }+ VERIFY_NOT_REACHED();}}diff --git a/Libraries/LibGfx/ImageFormats/BMPLoader.h b/Libraries/LibGfx/ImageFormats/BMPLoader.hindex e5b3e3366d7..39b1640c8de 100644--- a/Libraries/LibGfx/ImageFormats/BMPLoader.h+++ b/Libraries/LibGfx/ImageFormats/BMPLoader.h@@ -20,24 +20,23 @@ public:static ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> create(ReadonlyBytes);static ErrorOr<NonnullOwnPtr<BMPImageDecoderPlugin>> create_as_included_in_ico(Badge<ICOImageDecoderPlugin>, ReadonlyBytes);- enum class IncludedInICO {- Yes,- No,- };-virtual ~BMPImageDecoderPlugin() override;virtual IntSize size() override;- bool sniff_dib();virtual ErrorOr<ImageFrameDescriptor> frame(size_t index, Optional<IntSize> ideal_size = {}) override;virtual ErrorOr<Optional<ReadonlyBytes>> icc_data() override;private:- BMPImageDecoderPlugin(u8 const*, size_t, IncludedInICO included_in_ico = IncludedInICO::No);+ enum class IncludedInICO : u8 {+ No,+ Yes,+ };++ explicit BMPImageDecoderPlugin(NonnullOwnPtr<BMPLoadingContext>);static ErrorOr<NonnullOwnPtr<BMPImageDecoderPlugin>> create_impl(ReadonlyBytes, IncludedInICO);- OwnPtr<BMPLoadingContext> m_context;+ NonnullOwnPtr<BMPLoadingContext> m_context;};}diff --git a/Libraries/LibGfx/ImageFormats/ICOLoader.cpp b/Libraries/LibGfx/ImageFormats/ICOLoader.cppindex b92dcf1972d..829ec2c35ff 100644--- a/Libraries/LibGfx/ImageFormats/ICOLoader.cpp+++ b/Libraries/LibGfx/ImageFormats/ICOLoader.cpp@@ -178,16 +178,8 @@ ErrorOr<void> ICOImageDecoderPlugin::load_ico_bitmap(ICOLoadingContext& context)return {};} else {auto bmp_decoder = TRY(BMPImageDecoderPlugin::create_as_included_in_ico({}, { context.data + desc.offset, desc.size }));- // NOTE: We don't initialize a BMP decoder in the usual way, but rather- // we just create an object and try to sniff for a frame when it's included- // inside an ICO image.- if (bmp_decoder->sniff_dib()) {- auto decoded_bmp_frame = TRY(bmp_decoder->frame(0));- desc.bitmap = decoded_bmp_frame.image;- } else {- dbgln_if(ICO_DEBUG, "load_ico_bitmap: encoded image not supported at index: {}", real_index);- return Error::from_string_literal("Encoded image not supported");- }+ auto decoded_bmp_frame = TRY(bmp_decoder->frame(0));+ desc.bitmap = decoded_bmp_frame.image;return {};}}diff --git a/Libraries/LibImageDecoders/Rust/src/bmp.rs b/Libraries/LibImageDecoders/Rust/src/bmp.rsnew file mode 100644index 00000000000..c92efa0df7e--- /dev/null+++ b/Libraries/LibImageDecoders/Rust/src/bmp.rs@@ -0,0 +1,964 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use crate::ffi::{bytes_from_raw, catch_panic_or};++const BMP_FILE_HEADER_SIZE: usize = 14;+const COLOR_PALETTE_LIMIT: u32 = 1024;+const MAX_RLE_BUFFER_SIZE: usize = 300 * 1024 * 1024;++// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/4e588f70-bd92-4a6f-b77f-35d0feaf7a57+mod compression {+ pub const RGB: u32 = 0;+ pub const RLE8: u32 = 1;+ pub const RLE4: u32 = 2;+ pub const BITFIELDS: u32 = 3;+ // NB: This doubles as JPEG for V4+ headers, which we do not support.+ pub const RLE24: u32 = 4;+ pub const ALPHABITFIELDS: u32 = 6;+}++// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/3c289fe1-c42e-42f6-b125-4b5fc49a2b20+const COLOR_SPACE_PROFILE_EMBEDDED: u32 = 0x4D42_4544; // 'MBED'++#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum DIBType {+ Core,+ OSV2Short,+ OSV2,+ Info,+ V2,+ V3,+ V4,+ V5,+}++impl DIBType {+ fn from_size(size: usize) -> Option<Self> {+ Some(match size {+ 12 => Self::Core,+ 16 => Self::OSV2Short,+ 64 => Self::OSV2,+ 40 => Self::Info,+ 52 => Self::V2,+ 56 => Self::V3,+ 108 => Self::V4,+ 124 => Self::V5,+ _ => return None,+ })+ }+}++#[repr(u8)]+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum BMPBitmapFormat {+ BGRx8888,+ BGRA8888,+ RGBx8888,+}++#[repr(u8)]+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum BMPICCProfile {+ Absent,+ Embedded,+ OutOfBounds,+}++#[repr(C)]+pub struct BMPImageInfo {+ pub width: u32,+ pub height: u32,+ pub format: BMPBitmapFormat,+ pub icc_profile: BMPICCProfile,+ pub icc_profile_offset: usize,+ pub icc_profile_size: usize,+}++struct Reader<'a> {+ data: &'a [u8],+}++impl<'a> Reader<'a> {+ fn new(data: &'a [u8]) -> Self {+ Self { data }+ }++ fn remaining(&self) -> usize {+ self.data.len()+ }++ fn is_at_end(&self) -> bool {+ self.data.is_empty()+ }++ fn read_array<const N: usize>(&mut self) -> Option<[u8; N]> {+ let (head, tail) = self.data.split_first_chunk::<N>()?;+ self.data = tail;+ Some(*head)+ }++ fn read_u8(&mut self) -> Option<u8> {+ Some(self.read_array::<1>()?[0])+ }++ fn read_u16(&mut self) -> Option<u16> {+ Some(u16::from_le_bytes(self.read_array()?))+ }++ fn read_u24(&mut self) -> Option<u32> {+ let [b0, b1, b2] = self.read_array()?;+ Some(u32::from_le_bytes([b0, b1, b2, 0]))+ }++ fn read_u32(&mut self) -> Option<u32> {+ Some(u32::from_le_bytes(self.read_array()?))+ }++ fn read_i32(&mut self) -> Option<i32> {+ Some(i32::from_le_bytes(self.read_array()?))+ }++ fn skip(&mut self, count: usize) -> Option<()> {+ self.data = self.data.get(count..)?;+ Some(())+ }+}++#[derive(Clone, Copy)]+struct ColorMask {+ mask: u32,+ // The number of right shifts that align the most significant bit of the mask with bit 7. This can be negative.+ shift: i8,+ // The number of set bits in the mask, capped at 8.+ size: u8,+}++impl ColorMask {+ fn new(mask: u32) -> Self {+ if mask == 0 {+ return Self {+ mask,+ shift: 0,+ size: 0,+ };+ }+ let mut trailing_zeros = mask.trailing_zeros() as i32;+ let mut size = (!(mask >> trailing_zeros)).trailing_zeros() as i32;+ if size > 8 {+ // Drop the lowest bits if the mask is longer than 8 bits.+ trailing_zeros += size - 8;+ size = 8;+ }+ Self {+ mask,+ shift: (size + trailing_zeros - 8) as i8,+ size: size as u8,+ }+ }++ // Scales the masked bits of `data` over the entire 8-bit range, so that for example the 5-bit value 0x1f becomes+ // 0xff instead of 0xf8.+ fn scaled_value(&self, data: u32) -> u8 {+ const SCALING_FACTORS_2BIT: [u8; 4] = [0x00, 0x55, 0xaa, 0xff];+ const SCALING_FACTORS_3BIT: [u8; 8] = [0x00, 0x24, 0x48, 0x6d, 0x91, 0xb6, 0xdb, 0xff];++ let data = data & self.mask;+ let number = if self.shift < 0 {+ (data << -self.shift) as u8+ } else {+ (data >> self.shift) as u8+ };+ match self.size {+ 0 => 0,+ 1 => {+ if number != 0 {+ 0xff+ } else {+ 0+ }+ }+ 2 => SCALING_FACTORS_2BIT[(number >> 6) as usize],+ 3 => SCALING_FACTORS_3BIT[(number >> 5) as usize],+ // With 4 or more bits, copying the most significant bits into the least significant bits scales evenly.+ size => (u32::from(number) | (u32::from(number) >> size)) as u8,+ }+ }+}++struct DIBHeader {+ width: i32,+ height: i32,+ bpp: u16,+ compression: u32,+ number_of_palette_colors: u32,+ masks: Vec<u32>,+ color_space: u32,+ profile_data: u32,+ profile_size: u32,+}++pub struct BMPDecoder {+ included_in_ico: bool,+ dib_type: DIBType,+ dib_size: usize,+ data_offset: usize,+ width: usize,+ height: usize,+ top_down: bool,+ bpp: u16,+ compression: u32,+ number_of_palette_colors: u32,+ masks: Vec<ColorMask>,+}++fn decode_file_header(data: &[u8]) -> Option<usize> {+ if data.get(0..2)? != b"BM" {+ return None;+ }+ // NB: The file size field is ignored, since files disagree on whether it holds the size of the file or of the+ // header. The four bytes after it are reserved.+ let data_offset = u32::from_le_bytes(*data.get(10..14)?.first_chunk()?) as usize;+ if data_offset >= data.len() {+ return None;+ }+ Some(data_offset)+}++fn is_supported_compression(dib_type: DIBType, compression: u32) -> bool {+ matches!(+ compression,+ compression::RGB | compression::BITFIELDS | compression::ALPHABITFIELDS | compression::RLE8 | compression::RLE4+ ) || (compression == compression::RLE24 && dib_type <= DIBType::OSV2)+}++fn decode_core_dib(reader: &mut Reader, dib: &mut DIBHeader, dib_type: DIBType) -> Option<()> {+ // The width and height are u16 fields in BITMAPCOREHEADER.+ if dib_type == DIBType::Core {+ dib.width = i32::from(reader.read_u16()?);+ dib.height = i32::from(reader.read_u16()?);+ } else {+ dib.width = reader.read_i32()?;+ dib.height = reader.read_i32()?;+ }+ if dib.width < 0 || dib.height == i32::MIN {+ return None;+ }+ if reader.read_u16()? != 1 {+ return None;+ }+ dib.bpp = reader.read_u16()?;+ match dib.bpp {+ 1 | 2 | 4 | 8 | 16 | 24 | 32 => Some(()),+ _ => None,+ }+}++fn decode_osv2_dib(reader: &mut Reader, dib: &mut DIBHeader, dib_type: DIBType) -> Option<()> {+ dib.width = reader.read_i32()?;+ dib.height = reader.read_i32()?;+ if dib.width < 0 || dib.height == i32::MIN {+ return None;+ }+ if reader.read_u16()? != 1 {+ return None;+ }+ dib.bpp = reader.read_u16()?;+ // OS/2 did not expect 16 or 32 bpp to be popular.+ if !matches!(dib.bpp, 1 | 2 | 4 | 8 | 24) {+ return None;+ }+ if dib_type == DIBType::OSV2Short {+ return Some(());+ }++ dib.compression = reader.read_u32()?;+ if !is_supported_compression(dib_type, dib.compression) {+ return None;+ }+ // Image size, horizontal resolution, vertical resolution.+ reader.skip(12)?;+ dib.number_of_palette_colors = reader.read_u32()?.min(COLOR_PALETTE_LIMIT);+ // Important colors, units, reserved, recording, halftoning, size1, size2, color encoding, identifier.+ reader.skip(4 + 4 + 4 + 4 + 4 + 8)+}++fn decode_info_dib(reader: &mut Reader, dib: &mut DIBHeader, dib_type: DIBType) -> Option<()> {+ decode_core_dib(reader, dib, dib_type)?;+ dib.compression = reader.read_u32()?;+ if !is_supported_compression(dib_type, dib.compression) {+ return None;+ }+ // Image size, horizontal resolution, vertical resolution.+ reader.skip(12)?;+ dib.number_of_palette_colors = reader.read_u32()?.min(COLOR_PALETTE_LIMIT);+ // Important colors.+ reader.skip(4)+}++fn decode_v2_dib(reader: &mut Reader, dib: &mut DIBHeader) -> Option<()> {+ if dib.compression != compression::BITFIELDS && dib.compression != compression::ALPHABITFIELDS {+ return reader.skip(12);+ }+ for _ in 0..3 {+ dib.masks.push(reader.read_u32()?);+ }+ Some(())+}++fn decode_v3_dib(reader: &mut Reader, dib: &mut DIBHeader) -> Option<()> {+ // There is no comprehensive documentation of when alpha masks apply, so this follows the results of the BMP test+ // suite.+ if dib.compression == compression::ALPHABITFIELDS {+ dib.masks.push(reader.read_u32()?);+ return Some(());+ }+ if dib.bpp < 16 {+ return reader.skip(4);+ }+ let mask = reader.read_u32()?;+ if dib.compression == compression::RGB && dib.bpp == 32 && mask != 0 {+ dib.masks.extend([0xff0000, 0x00ff00, 0x0000ff]);+ }+ if (dib.bpp == 32 && mask != 0) || (dib.bpp == 16 && dib.compression != compression::RGB) {+ dib.masks.push(mask);+ }+ Some(())+}++fn decode_v4_dib(reader: &mut Reader, dib: &mut DIBHeader) -> Option<()> {+ dib.color_space = reader.read_u32()?;+ // Red, green and blue endpoints, then gamma values.+ reader.skip(36 + 12)+}++fn decode_v5_dib(reader: &mut Reader, dib: &mut DIBHeader) -> Option<()> {+ // Intent.+ reader.skip(4)?;+ dib.profile_data = reader.read_u32()?;+ dib.profile_size = reader.read_u32()?;+ // Reserved.+ reader.skip(4)+}++fn is_valid_bitmask_combination(dib_type: DIBType, dib: &DIBHeader) -> bool {+ let bpp = dib.bpp;+ let compression = dib.compression;++ if compression == compression::ALPHABITFIELDS && dib_type != DIBType::Info {+ return false;+ }++ match dib_type {+ DIBType::Core => !matches!(bpp, 2 | 16 | 32),+ DIBType::Info => match compression {+ compression::BITFIELDS | compression::ALPHABITFIELDS => bpp == 16 || bpp == 32,+ compression::RGB => true,+ compression::RLE8 => bpp <= 8,+ compression::RLE4 => bpp <= 4,+ // Other compressions are not officially supported.+ _ => false,+ },+ _ => {+ !(compression == compression::BITFIELDS && bpp != 16 && bpp != 32)+ && !(compression == compression::RLE8 && bpp > 8)+ && !(compression == compression::RLE4 && bpp > 4)+ && !(compression == compression::RLE24 && bpp != 24)+ }+ }+}++fn decode_dib(data: &[u8], included_in_ico: bool) -> Option<(BMPDecoder, BMPImageInfo)> {+ let header_size = if included_in_ico { 0 } else { BMP_FILE_HEADER_SIZE };+ let mut data_offset = if included_in_ico { 0 } else { decode_file_header(data)? };++ let dib_size = u32::from_le_bytes(*data.get(header_size..header_size + 4)?.first_chunk()?) as usize;+ if data.len() < header_size.checked_add(dib_size)? {+ return None;+ }+ if !included_in_ico && data_offset < header_size + dib_size {+ return None;+ }++ // NB: A BMP included in an ICO has no file header, so its data offset is only known after the color table size.+ // This also means that it cannot contain extra bit masks.+ let dib_offset = if included_in_ico {+ dib_size+ } else {+ data_offset.checked_sub(header_size + 4)?+ };+ let dib_start = header_size + 4;+ if dib_offset.checked_add(dib_start)? >= data.len() {+ return None;+ }+ let mut reader = Reader::new(&data[dib_start..dib_start + dib_offset]);++ let dib_type = DIBType::from_size(dib_size)?;+ let mut dib = DIBHeader {+ width: 0,+ height: 0,+ bpp: 0,+ compression: compression::RGB,+ number_of_palette_colors: 0,+ masks: Vec::new(),+ color_space: 0,+ profile_data: 0,+ profile_size: 0,+ };+ match dib_type {+ DIBType::Core => decode_core_dib(&mut reader, &mut dib, dib_type)?,+ DIBType::OSV2Short | DIBType::OSV2 => decode_osv2_dib(&mut reader, &mut dib, dib_type)?,+ _ => {+ decode_info_dib(&mut reader, &mut dib, dib_type)?;+ if dib_type >= DIBType::V2 {+ decode_v2_dib(&mut reader, &mut dib)?;+ }+ if dib_type >= DIBType::V3 {+ decode_v3_dib(&mut reader, &mut dib)?;+ }+ if dib_type >= DIBType::V4 {+ decode_v4_dib(&mut reader, &mut dib)?;+ }+ if dib_type >= DIBType::V5 {+ decode_v5_dib(&mut reader, &mut dib)?;+ }+ }+ }++ if !is_valid_bitmask_combination(dib_type, &dib) {+ return None;+ }+ if dib.bpp == 16 || dib.bpp == 32 {+ if dib_type > DIBType::OSV2 && dib.bpp == 16 && dib.compression == compression::RGB {+ // RGB555.+ dib.masks.extend([0x7c00, 0x03e0, 0x001f]);+ } else if dib_type == DIBType::Info+ && (dib.compression == compression::BITFIELDS || dib.compression == compression::ALPHABITFIELDS)+ {+ // The masks follow the BITMAPINFOHEADER.+ let mask_count = if dib.compression == compression::ALPHABITFIELDS {+ 4+ } else {+ 3+ };+ for _ in 0..mask_count {+ dib.masks.push(reader.read_u32()?);+ }+ }+ }++ if included_in_ico {+ data_offset = dib_size;+ if dib.bpp <= 8 {+ let bytes_per_color = if dib_type == DIBType::Core { 3 } else { 4 };+ data_offset += palette_color_count(&dib) as usize * bytes_per_color;+ }+ }+ if data_offset >= data.len() {+ return None;+ }++ let mut icc_profile = BMPICCProfile::Absent;+ let mut icc_profile_offset = 0;+ let mut icc_profile_size = 0;+ // FIXME: Handle linked profiles, the sRGB color spaces, and calibrated RGB endpoints.+ if dib_type == DIBType::V5+ && dib.color_space == COLOR_SPACE_PROFILE_EMBEDDED+ && dib.profile_data != 0+ && dib.profile_size != 0+ {+ let offset = header_size as u64 + u64::from(dib.profile_data);+ if offset + u64::from(dib.profile_size) > data.len() as u64 {+ icc_profile = BMPICCProfile::OutOfBounds;+ } else {+ icc_profile = BMPICCProfile::Embedded;+ icc_profile_offset = offset as usize;+ icc_profile_size = dib.profile_size as usize;+ }+ }++ let masks: Vec<ColorMask> = dib.masks.iter().map(|&mask| ColorMask::new(mask)).collect();++ // NB: A BMP included in an ICO is always given an alpha channel, since its AND mask makes pixels transparent.+ let format = if included_in_ico {+ BMPBitmapFormat::BGRA8888+ } else {+ match dib.bpp {+ 16 if masks.len() == 4 => BMPBitmapFormat::BGRA8888,+ 24 => BMPBitmapFormat::RGBx8888,+ 32 => BMPBitmapFormat::BGRA8888,+ _ => BMPBitmapFormat::BGRx8888,+ }+ };++ let width = dib.width as u32;+ let absolute_height = dib.height.unsigned_abs();+ // The height of a BMP included in an ICO covers both the image and its AND mask.+ let height = if included_in_ico {+ absolute_height / 2+ } else {+ absolute_height+ };++ let decoder = BMPDecoder {+ included_in_ico,+ dib_type,+ dib_size,+ data_offset,+ width: width as usize,+ height: height as usize,+ top_down: dib.height < 0,+ bpp: dib.bpp,+ compression: dib.compression,+ number_of_palette_colors: dib.number_of_palette_colors,+ masks,+ };+ let info = BMPImageInfo {+ width,+ height,+ format,+ icc_profile,+ icc_profile_offset,+ icc_profile_size,+ };+ Some((decoder, info))+}++fn palette_color_count(dib: &DIBHeader) -> u32 {+ if dib.number_of_palette_colors > 0 {+ dib.number_of_palette_colors+ } else {+ 1 << dib.bpp+ }+}++impl BMPDecoder {+ fn header_size(&self) -> usize {+ if self.included_in_ico { 0 } else { BMP_FILE_HEADER_SIZE }+ }++ fn decode_color_table(&self, data: &[u8]) -> Option<Vec<u32>> {+ if self.bpp > 8 {+ return Some(Vec::new());+ }++ let max_colors = 1usize << self.bpp;+ let header_size = self.header_size();+ let bytes_per_color = match self.dib_type {+ // OS/2 1.x uses 3 bytes per color.+ DIBType::Core => 3,+ // OS/2 2.x uses 3 or 4 bytes per color, which is only known from the size of the color table.+ DIBType::OSV2 | DIBType::OSV2Short if self.data_offset - header_size - self.dib_size == 3 * max_colors => 3,+ _ => 4,+ };++ let size_of_color_table = if self.included_in_ico {+ let count = if self.number_of_palette_colors > 0 {+ self.number_of_palette_colors as usize+ } else {+ max_colors+ };+ count * bytes_per_color+ } else {+ self.data_offset - header_size - self.dib_size+ };++ // NB: Partial color tables are against the spec, but are accepted since most viewers process them anyway.+ let start = header_size + self.dib_size;+ let mut reader = Reader::new(data.get(start..start.checked_add(size_of_color_table)?)?);+ let mut color_table = Vec::with_capacity(max_colors);+ while !reader.is_at_end() && color_table.len() < max_colors {+ let color = if bytes_per_color == 4 {+ reader.read_u32()?+ } else {+ reader.read_u24()?+ };+ color_table.push(color | 0xff00_0000);+ }+ Some(color_table)+ }++ // Returns the number of bits per pixel of the data that `decode_rle_data()` produces.+ fn rle_bits_per_pixel(&self) -> Option<u16> {+ match self.compression {+ // INTEROP: RLE8 and RLE4 data with a lower bit count has an equally small color table, but its pixel+ // data is still RLE8 or RLE4.+ compression::RLE8 => Some(8),+ compression::RLE4 => Some(4),+ compression::RLE24 => Some(24),+ _ => None,+ }+ }++ fn decode_rle_data(&self, data: &[u8], bits_per_pixel: u16) -> Option<Vec<u8>> {+ // RLE-compressed images cannot be stored top-down.+ if self.top_down {+ return None;+ }++ let mut reader = Reader::new(data.get(self.data_offset..)?);+ let compression = self.compression;+ let width = self.width;+ let total_rows = self.height;+ let row_size = row_size(width, bits_per_pixel)?;+ // NB: Runs and deltas wrap at the 4-pixel boundary after the end of a row. Pixels past the end of the row are+ // dropped.+ let total_columns = width.checked_next_multiple_of(4)?;++ let buffer_size = row_size.checked_mul(total_rows)?;+ if buffer_size > MAX_RLE_BUFFER_SIZE {+ return None;+ }+ let mut buffer = Vec::new();+ buffer.try_reserve_exact(buffer_size).ok()?;+ buffer.resize(buffer_size, 0);++ let mut column = 0usize;+ let mut row = 0usize;++ let mut set_pixel = |column: &mut usize, row: &mut usize, value: u32| -> Option<()> {+ if *column >= total_columns {+ *column = 0;+ *row += 1;+ }+ if *row >= total_rows {+ return None;+ }+ if *column < width {+ let row_start = *row * row_size;+ match compression {+ compression::RLE8 => buffer[row_start + *column] = value as u8,+ compression::RLE4 => {+ let byte = &mut buffer[row_start + *column / 2];+ if (*column).is_multiple_of(2) {+ *byte = (*byte & 0x0f) | ((value as u8) << 4);+ } else {+ *byte = (*byte & 0xf0) | (value as u8 & 0x0f);+ }+ }+ _ => {+ let index = row_start + *column * 3;+ buffer[index..index + 3].copy_from_slice(&value.to_le_bytes()[..3]);+ }+ }+ }+ *column += 1;+ Some(())+ };++ let read_value = |reader: &mut Reader| -> Option<u32> {+ if compression == compression::RLE24 {+ reader.read_u24()+ } else {+ reader.read_u8().map(u32::from)+ }+ };++ loop {+ let count = reader.read_u8()?;+ if count != 0 {+ // Encoded mode: repeat one value. In RLE4, the value holds two pixels that alternate.+ let value = read_value(&mut reader)?;+ for i in 0..count {+ let pixel = if compression == compression::RLE4 {+ if i % 2 == 0 { value >> 4 } else { value & 0x0f }+ } else {+ value+ };+ set_pixel(&mut column, &mut row, pixel)?;+ }+ continue;+ }++ match reader.read_u8()? {+ // End of line.+ 0 => {+ column = 0;+ row += 1;+ }+ // End of bitmap.+ 1 => break,+ // Delta.+ 2 => {+ let offset_x = reader.read_u8()?;+ let offset_y = reader.read_u8()?;+ column += usize::from(offset_x);+ if column >= total_columns {+ column -= total_columns;+ row += 1;+ }+ row += usize::from(offset_y);+ }+ // Absolute mode: a run of literal values, padded to a 16-bit boundary.+ count => {+ let count = usize::from(count);+ if compression == compression::RLE4 {+ let byte_count = count.div_ceil(2);+ for i in 0..count {+ if i % 2 == 0 {+ let byte = reader.read_u8()?;+ set_pixel(&mut column, &mut row, u32::from(byte >> 4))?;+ if i + 1 < count {+ set_pixel(&mut column, &mut row, u32::from(byte & 0x0f))?;+ }+ }+ }+ if byte_count % 2 != 0 {+ reader.read_u8()?;+ }+ } else {+ for _ in 0..count {+ let value = read_value(&mut reader)?;+ set_pixel(&mut column, &mut row, value)?;+ }+ if count % 2 != 0 {+ reader.read_u8()?;+ }+ }+ }+ }+ }++ Some(buffer)+ }++ fn masked_color(&self, data: u32) -> u32 {+ let red = u32::from(self.masks[0].scaled_value(data));+ let green = u32::from(self.masks[1].scaled_value(data));+ let blue = u32::from(self.masks[2].scaled_value(data));+ let alpha = match self.masks.get(3) {+ Some(mask) => u32::from(mask.scaled_value(data)),+ None => 0xff,+ };+ (alpha << 24) | (red << 16) | (green << 8) | blue+ }++ fn decode(&self, data: &[u8], output: &mut [u8], stride: usize) -> Option<()> {+ let color_table = self.decode_color_table(data)?;++ let rle_buffer;+ let (pixel_data, bits_per_pixel) = match self.rle_bits_per_pixel() {+ Some(bits_per_pixel) => {+ rle_buffer = self.decode_rle_data(data, bits_per_pixel)?;+ (rle_buffer.as_slice(), bits_per_pixel)+ }+ None => (data.get(self.data_offset..)?, self.bpp),+ };+ let mut reader = Reader::new(pixel_data);++ let width = self.width;+ let height = self.height;+ let row_bytes = width * 4;+ let output_row = |row: usize| -> usize {+ if self.top_down {+ row * stride+ } else {+ (height - 1 - row) * stride+ }+ };+ let palette_color = |index: u8| -> Option<u32> { color_table.get(usize::from(index)).copied() };++ let skip_row_padding = |reader: &mut Reader, consumed: usize| -> Option<()> {+ let remainder = consumed % 4;+ if remainder != 0 {+ reader.skip(4 - remainder)?;+ }+ Some(())+ };++ for row in 0..height {+ let row_start = output_row(row);+ let pixels = &mut output[row_start..row_start + row_bytes];+ let remaining_before_row = reader.remaining();+ let mut set_pixel = |column: usize, color: u32| {+ pixels[column * 4..column * 4 + 4].copy_from_slice(&color.to_ne_bytes());+ };++ let mut column = 0;+ while column < width {+ match bits_per_pixel {+ 1 | 2 | 4 => {+ let byte = reader.read_u8()?;+ let pixels_per_byte = 8 / usize::from(bits_per_pixel);+ let index_mask = (1u8 << bits_per_pixel) - 1;+ for i in 0..pixels_per_byte {+ if column >= width {+ break;+ }+ let shift = 8 - bits_per_pixel as usize * (i + 1);+ set_pixel(column, palette_color((byte >> shift) & index_mask)?);+ column += 1;+ }+ }+ 8 => {+ let byte = reader.read_u8()?;+ set_pixel(column, palette_color(byte)?);+ column += 1;+ }+ 16 => {+ let value = reader.read_u16()?;+ set_pixel(column, self.masked_color(u32::from(value)));+ column += 1;+ }+ 24 => {+ let pixel = reader.read_u24()?;+ if self.included_in_ico {+ // 24-bit BMPs included in ICOs are already in BGRA8888 order.+ set_pixel(column, pixel);+ } else {+ set_pixel(+ column,+ ((pixel & 0xff) << 16) | (pixel & 0xff00) | ((pixel >> 16) & 0xff),+ );+ }+ column += 1;+ }+ 32 => {+ let value = reader.read_u32()?;+ if self.masks.is_empty() {+ set_pixel(column, value);+ } else {+ set_pixel(column, self.masked_color(value));+ }+ column += 1;+ }+ _ => return None,+ }+ }++ let consumed = remaining_before_row - reader.remaining();++ skip_row_padding(&mut reader, consumed)?;+ }++ // An ICO image is followed by an AND mask with one bit per pixel, which makes pixels transparent.+ if self.included_in_ico && !reader.is_at_end() {+ for row in 0..height {+ let row_start = output_row(row);+ let pixels = &mut output[row_start..row_start + row_bytes];+ let remaining_before_row = reader.remaining();++ let mut column = 0;+ while column < width {+ let byte = reader.read_u8()?;+ for bit in (0..8).rev() {+ if column >= width {+ break;+ }+ let pixel_bytes = &mut pixels[column * 4..column * 4 + 4];+ let mut pixel = u32::from_ne_bytes(pixel_bytes.try_into().ok()?);+ if (byte >> bit) & 1 != 0 {+ pixel &= 0x00ff_ffff;+ } else if self.bpp < 32 {+ pixel |= 0xff00_0000;+ }+ pixel_bytes.copy_from_slice(&pixel.to_ne_bytes());+ column += 1;+ }+ }++ let consumed = remaining_before_row - reader.remaining();++ skip_row_padding(&mut reader, consumed)?;+ }+ }++ Some(())+ }+}++fn row_size(width: usize, bits_per_pixel: u16) -> Option<usize> {+ width+ .checked_mul(usize::from(bits_per_pixel))?+ .div_ceil(8)+ .checked_next_multiple_of(4)+}++/// # Safety+/// `data` must be valid for `data_len` bytes.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn bmp_rust_sniff(data: *const u8, data_len: usize) -> bool {+ catch_panic_or(false, || {+ let Some(data) = (unsafe { bytes_from_raw(data, data_len) }) else {+ return false;+ };+ decode_file_header(data).is_some()+ })+}++/// # Safety+/// - `data` must be valid for `data_len` bytes.+/// - `out_info` must be a valid writable pointer.+/// - The returned pointer must be freed with `bmp_rust_decoder_free`.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn bmp_rust_decoder_new(+ data: *const u8,+ data_len: usize,+ included_in_ico: bool,+ out_info: *mut BMPImageInfo,+) -> *mut BMPDecoder {+ catch_panic_or(std::ptr::null_mut(), || {+ let Some(data) = (unsafe { bytes_from_raw(data, data_len) }) else {+ return std::ptr::null_mut();+ };+ let Some(out_info) = (unsafe { out_info.as_mut() }) else {+ return std::ptr::null_mut();+ };+ let Some((decoder, info)) = decode_dib(data, included_in_ico) else {+ return std::ptr::null_mut();+ };+ *out_info = info;+ Box::into_raw(Box::new(decoder))+ })+}++/// # Safety+/// `decoder` must be null or a pointer returned by `bmp_rust_decoder_new` that has not already been freed.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn bmp_rust_decoder_free(decoder: *mut BMPDecoder) {+ catch_panic_or((), || {+ if !decoder.is_null() {+ // SAFETY: The caller transfers ownership of a decoder allocated by `bmp_rust_decoder_new`.+ drop(unsafe { Box::from_raw(decoder) });+ }+ });+}++/// # Safety+/// - `decoder` must be a valid pointer returned by `bmp_rust_decoder_new`.+/// - `data` must be the same image passed to `bmp_rust_decoder_new` and be valid for `data_len` bytes.+/// - `buffer` must be valid for writes of `stride * height` bytes, where `height` is the height returned by+/// `bmp_rust_decoder_new`.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn bmp_rust_decode(+ decoder: *const BMPDecoder,+ data: *const u8,+ data_len: usize,+ buffer: *mut u8,+ stride: usize,+) -> bool {+ catch_panic_or(false, || {+ let Some(data) = (unsafe { bytes_from_raw(data, data_len) }) else {+ return false;+ };+ let Some(decoder) = (unsafe { decoder.as_ref() }) else {+ return false;+ };+ if stride < decoder.width.saturating_mul(4) {+ return false;+ }+ let Some(buffer_size) = stride.checked_mul(decoder.height) else {+ return false;+ };+ // NB: An empty bitmap may have no buffer at all.+ if buffer.is_null() && buffer_size != 0 {+ return false;+ }+ // SAFETY: The caller guarantees that `buffer` is valid for writes of `stride * height` bytes.+ let output = unsafe { ak::slice_from_raw_parts_mut(buffer, buffer_size) };+ decoder.decode(data, output, stride).is_some()+ })+}diff --git a/Libraries/LibImageDecoders/Rust/src/ffi.rs b/Libraries/LibImageDecoders/Rust/src/ffi.rsnew file mode 100644index 00000000000..253d6c71948--- /dev/null+++ b/Libraries/LibImageDecoders/Rust/src/ffi.rs@@ -0,0 +1,49 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::panic::AssertUnwindSafe;+use std::panic::catch_unwind;++pub(crate) fn catch_panic_or<F: FnOnce() -> R, R>(fallback: R, f: F) -> R {+ match catch_unwind(AssertUnwindSafe(f)) {+ Ok(result) => result,+ Err(payload) => {+ if let Some(message) = payload.downcast_ref::<&str>() {+ eprintln!("Rust panic at image decoder FFI boundary: {message}");+ } else if let Some(message) = payload.downcast_ref::<String>() {+ eprintln!("Rust panic at image decoder FFI boundary: {message}");+ } else {+ eprintln!("Rust panic at image decoder FFI boundary");+ }+ fallback+ }+ }+}++/// # Safety+/// `bytes` must be null or valid for `len` bytes.+pub(crate) unsafe fn bytes_from_raw<'a>(bytes: *const u8, len: usize) -> Option<&'a [u8]> {+ if len == 0 {+ return Some(&[]);+ }+ if bytes.is_null() {+ eprintln!("bytes_from_raw: null pointer with non-zero length {len}");+ return None;+ }++ // SAFETY: The caller guarantees that `bytes` is valid for `len` bytes.+ Some(unsafe { ak::slice_from_raw_parts(bytes, len) })+}++#[cfg(test)]+mod tests {+ use super::catch_panic_or;++ #[test]+ fn panic_at_ffi_boundary_is_contained() {+ assert!(!catch_panic_or(false, || panic!("expected test panic")));+ }+}diff --git a/Libraries/LibImageDecoders/Rust/src/jpeg_xl.rs b/Libraries/LibImageDecoders/Rust/src/jpeg_xl.rsindex 04ce2d1bf9e..60fa82efc72 100644--- a/Libraries/LibImageDecoders/Rust/src/jpeg_xl.rs+++ b/Libraries/LibImageDecoders/Rust/src/jpeg_xl.rs@@ -4,12 +4,11 @@* SPDX-License-Identifier: BSD-2-Clause*/+use crate::ffi::{bytes_from_raw, catch_panic_or};use jxl::api::states::{Initialized, WithImageInfo};use jxl::api::{JxlDecoder, JxlDecoderOptions, JxlOutputBuffer, JxlPixelFormat, ProcessingResult, check_signature};use jxl::headers::extra_channels::ExtraChannel;use std::ffi::c_void;-use std::panic::AssertUnwindSafe;-use std::panic::catch_unwind;#[repr(C)]pub struct JPEGXLImageInfo {@@ -29,35 +28,6 @@ pub struct JPEGXLDecoder {input_offset: usize,}-fn catch_panic_or<F: FnOnce() -> R, R>(fallback: R, f: F) -> R {- match catch_unwind(AssertUnwindSafe(f)) {- Ok(result) => result,- Err(payload) => {- if let Some(message) = payload.downcast_ref::<&str>() {- eprintln!("Rust panic at JPEG XL FFI boundary: {message}");- } else if let Some(message) = payload.downcast_ref::<String>() {- eprintln!("Rust panic at JPEG XL FFI boundary: {message}");- } else {- eprintln!("Rust panic at JPEG XL FFI boundary");- }- fallback- }- }-}--unsafe fn bytes_from_raw<'a>(bytes: *const u8, len: usize) -> Option<&'a [u8]> {- if len == 0 {- return Some(&[]);- }- if bytes.is_null() {- eprintln!("bytes_from_raw: null pointer with non-zero length {len}");- return None;- }-- // SAFETY: The caller guarantees that `bytes` is valid for `len` bytes.- Some(unsafe { ak::slice_from_raw_parts(bytes, len) })-}-fn decode_header(input: &mut &[u8], options: JxlDecoderOptions) -> Option<JxlDecoder<WithImageInfo>> {let decoder = JxlDecoder::<Initialized>::new(options);match decoder.process(input, None).ok()? {@@ -227,13 +197,3 @@ pub unsafe extern "C" fn jpegxl_rust_decode(}})}--#[cfg(test)]-mod tests {- use super::catch_panic_or;-- #[test]- fn panic_at_ffi_boundary_is_contained() {- assert!(!catch_panic_or(false, || panic!("expected test panic")));- }-}diff --git a/Libraries/LibImageDecoders/Rust/src/lib.rs b/Libraries/LibImageDecoders/Rust/src/lib.rsindex b2ed82189c9..7c8e8f1f8ba 100644--- a/Libraries/LibImageDecoders/Rust/src/lib.rs+++ b/Libraries/LibImageDecoders/Rust/src/lib.rs@@ -13,5 +13,10 @@ mod rust_demangle;#[path = "../../../RustPanic.rs"]mod rust_panic;+mod ffi;++pub mod bmp;+pub use bmp::*;+pub mod jpeg_xl;pub use jpeg_xl::*;diff --git a/Meta/CMake/all_the_debug_macros.cmake b/Meta/CMake/all_the_debug_macros.cmakeindex 79aeee6aea2..aa5a6dff40b 100644--- a/Meta/CMake/all_the_debug_macros.cmake+++ b/Meta/CMake/all_the_debug_macros.cmake@@ -1,6 +1,5 @@set(AK_STRINGBASE_VERIFY_LAUNDER_DEBUG ON)set(AUDIO_DEBUG ON)-set(BMP_DEBUG ON)set(CACHE_DEBUG ON)set(CALLBACK_MACHINE_DEBUG ON)set(COMPOSITOR_DEBUG ON)diff --git a/Tests/LibGfx/TestImageDecoder.cpp b/Tests/LibGfx/TestImageDecoder.cppindex 05b9c6e4c57..70a486331c5 100644--- a/Tests/LibGfx/TestImageDecoder.cpp+++ b/Tests/LibGfx/TestImageDecoder.cpp@@ -272,6 +272,51 @@ TEST_CASE(test_bmp_rle24)EXPECT_EQ(frame.image->begin()[1] & 0x00ffffffU, 0x00332211U);}+TEST_CASE(test_bmp_rle4_rows_with_odd_width)+{+ // 9x2 BI_RLE4 image. Each row is one run of two alternating colors, so every row ends mid-byte.+ Array<u8, 8> rle_data { 9, 0x12, 0, 0, 9, 0x34, 0, 1 };+ Vector<u8> bmp_data;+ auto append_u16 = [&](u16 value) {+ bmp_data.append(value & 0xff);+ bmp_data.append(value >> 8);+ };+ auto append_u32 = [&](u32 value) {+ append_u16(value & 0xffff);+ append_u16(value >> 16);+ };+ bmp_data.append('B');+ bmp_data.append('M');+ append_u32(118 + rle_data.size()); // File size.+ append_u32(0); // Reserved.+ append_u32(118); // Pixel offset.+ append_u32(40); // BITMAPINFOHEADER size.+ append_u32(9); // Width.+ append_u32(2); // Height.+ append_u16(1); // Plane count.+ append_u16(4); // Bits per pixel.+ append_u32(2); // BI_RLE4 compression.+ append_u32(rle_data.size()); // Pixel data size.+ append_u32(0); // Horizontal resolution.+ append_u32(0); // Vertical resolution.+ append_u32(16); // Palette colors.+ append_u32(0); // Important palette colors.+ for (u8 i = 0; i < 16; ++i) {+ bmp_data.append(0); // Blue.+ bmp_data.append(0); // Green.+ bmp_data.append(i * 16); // Red.+ bmp_data.append(0);+ }+ bmp_data.append(rle_data.data(), rle_data.size());++ auto plugin_decoder = TRY_OR_FAIL(Gfx::BMPImageDecoderPlugin::create(bmp_data));+ auto frame = TRY_OR_FAIL(expect_single_frame_of_size(*plugin_decoder, { 9, 2 }));+ for (int x = 0; x < 9; ++x) {+ EXPECT_EQ(frame.image->get_pixel(x, 0), Gfx::Color(x % 2 ? 4 * 16 : 3 * 16, 0, 0));+ EXPECT_EQ(frame.image->get_pixel(x, 1), Gfx::Color(x % 2 ? 2 * 16 : 1 * 16, 0, 0));+ }+}+TEST_CASE(test_ico_malformed_frame){Array test_inputs = {