using System.Buffers.Binary;
using System.Numerics;
namespace Febe.Core.Codecs.Images;
///
/// Reads Windows BMP files: core (OS/2 1.x), information and V2–V5 headers; 1, 2, 4, 8, 16, 24 and 32 bits per pixel;
/// BI_RGB, BI_BITFIELDS, BI_ALPHABITFIELDS, BI_RLE8, BI_RLE4 and an embedded PNG (BI_PNG); rows from the bottom or
/// from the top. Alpha comes only from an alpha mask of a BITFIELDS image (V3 headers and later); everything else is
/// opaque. Pixels an RLE image skips stay (0, 0, 0, 0). Colour profiles and gamma are not applied.
///
public static class BmpDecoder
{
private const int FileHeaderSize = 14;
private const uint BiRgb = 0;
private const uint BiRle8 = 1;
private const uint BiRle4 = 2;
private const uint BiBitfields = 3;
private const uint BiJpeg = 4;
private const uint BiPng = 5;
private const uint BiAlphaBitfields = 6;
/// Whether the bytes start like a BMP file.
public static bool IsBmp(ReadOnlySpan data) =>
data.Length >= 18 && data[0] == (byte)'B' && data[1] == (byte)'M' && ImageFormatSniffer.IsBmpHeaderSize(BinaryPrimitives.ReadUInt32LittleEndian(data[14..]));
/// Size of a BMP, without decoding the pixels.
public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null)
{
var header = ReadHeader(data.Span);
if (header.Compression == BiPng)
{
var png = PngDecoder.Identify(data[header.PixelOffset..], limits);
return png with { Format = ImageFormat.Bmp };
}
var widest = Math.Max(Math.Max(BitOperations.PopCount(header.RedMask), BitOperations.PopCount(header.GreenMask)), Math.Max(BitOperations.PopCount(header.BlueMask), BitOperations.PopCount(header.AlphaMask)));
return new ImageInfo(ImageFormat.Bmp, header.Width, header.Height, 1, header.AlphaMask != 0, ImageMetadata.Empty)
{
BitsPerSample = Math.Max(8, widest),
};
}
/// Decodes a BMP to straight RGBA8, top row first.
/// The file is damaged, truncated or not a BMP.
/// A BMP variant Febe does not read (JPEG inside, OS/2 Huffman, 64 bits).
/// The image is larger than allow.
public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false)
{
limits ??= ImageLimits.Default;
var span = data.Span;
var header = ReadHeader(span);
if (header.Compression == BiPng)
{
return PngDecoder.Decode(data[header.PixelOffset..], limits, pooled);
}
var image = RgbaImage.Create(header.Width, header.Height, limits, pooled);
try
{
switch (header.Compression)
{
case BiRle8:
case BiRle4:
DecodeRle(span, header, image);
break;
default:
DecodeRows(span, header, image);
break;
}
return image;
}
catch
{
image.Dispose();
throw;
}
}
/// Decodes a BMP and returns what returns as well.
public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
{
var image = Decode(data, limits, pooled);
try
{
info = Identify(data, limits);
return image;
}
catch
{
image.Dispose();
throw;
}
}
private sealed class BmpHeader
{
public int Width;
public int Height;
public bool TopDown;
public int BitsPerPixel;
public uint Compression;
public int PixelOffset;
public uint RedMask;
public uint GreenMask;
public uint BlueMask;
public uint AlphaMask;
/// RGBA of each palette index (256 entries; those the file does not give are opaque black).
public uint[]? Palette;
public int Stride => (int)((((long)Width * BitsPerPixel) + 31) / 32 * 4);
}
private static BmpHeader ReadHeader(ReadOnlySpan data)
{
if (data.Length < 2 || data[0] != (byte)'B' || data[1] != (byte)'M')
{
throw new ImageDecodeException("Non è un file BMP.");
}
if (data.Length < FileHeaderSize + 4)
{
throw new ImageDecodeException("BMP troncato: manca l'intestazione.");
}
var infoSize = BinaryPrimitives.ReadUInt32LittleEndian(data[FileHeaderSize..]);
if (!ImageFormatSniffer.IsBmpHeaderSize(infoSize))
{
throw new ImageFormatNotSupportedException($"BMP con un'intestazione di {infoSize} byte, che Febe non conosce.");
}
if (data.Length < FileHeaderSize + infoSize)
{
throw new ImageDecodeException("BMP troncato: l'intestazione finisce dopo il file.");
}
var info = data.Slice(FileHeaderSize, (int)infoSize);
var header = new BmpHeader();
long width;
long height;
int planes;
var paletteEntrySize = 4;
uint colorsUsed = 0;
if (infoSize == 12)
{
width = BinaryPrimitives.ReadUInt16LittleEndian(info[4..]);
// bcHeight is an unsigned WORD and core bitmaps are always bottom-up (the sign test below keeps them so).
height = BinaryPrimitives.ReadUInt16LittleEndian(info[6..]);
planes = BinaryPrimitives.ReadUInt16LittleEndian(info[8..]);
header.BitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(info[10..]);
header.Compression = BiRgb;
paletteEntrySize = 3;
}
else
{
width = BinaryPrimitives.ReadInt32LittleEndian(info[4..]);
height = BinaryPrimitives.ReadInt32LittleEndian(info[8..]);
planes = BinaryPrimitives.ReadUInt16LittleEndian(info[12..]);
header.BitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(info[14..]);
if (infoSize >= 20)
{
header.Compression = BinaryPrimitives.ReadUInt32LittleEndian(info[16..]);
}
if (infoSize >= 36)
{
colorsUsed = BinaryPrimitives.ReadUInt32LittleEndian(info[32..]);
}
if (infoSize is 16 or 64 && header.Compression is 3 or 4)
{
throw new ImageFormatNotSupportedException("BMP di OS/2 con compressione Huffman o RLE24, che Febe non legge.");
}
}
if (planes != 1 && planes != 0)
{
throw new ImageDecodeException($"BMP danneggiato: {planes} piani di colore.");
}
header.TopDown = height < 0;
height = Math.Abs(height);
if (width <= 0 || height == 0 || height > int.MaxValue)
{
throw new ImageDecodeException($"BMP danneggiato: misura non valida ({width}×{height}).");
}
header.Width = (int)width;
header.Height = (int)height;
switch (header.Compression)
{
case BiJpeg:
throw new ImageFormatNotSupportedException("BMP con un JPEG dentro, che Febe non legge.");
case BiRgb or BiBitfields or BiAlphaBitfields or BiRle8 or BiRle4 or BiPng:
break;
default:
throw new ImageFormatNotSupportedException($"BMP con la compressione {header.Compression}, che Febe non conosce.");
}
var bpp = header.BitsPerPixel;
var valid = header.Compression switch
{
BiRgb => bpp is 1 or 2 or 4 or 8 or 16 or 24 or 32,
BiBitfields or BiAlphaBitfields => bpp is 16 or 32,
BiRle8 => bpp == 8,
BiRle4 => bpp == 4,
_ => true,
};
if (!valid)
{
throw bpp == 64
? new ImageFormatNotSupportedException("BMP a 64 bit per pixel, che Febe non legge.")
: new ImageDecodeException($"BMP danneggiato: {bpp} bit per pixel con la compressione {header.Compression}.");
}
if ((header.Compression is BiRle8 or BiRle4) && header.TopDown)
{
throw new ImageDecodeException("BMP danneggiato: un'immagine RLE non può essere dall'alto.");
}
var afterHeader = FileHeaderSize + (int)infoSize;
if (header.Compression is BiBitfields or BiAlphaBitfields)
{
if (infoSize >= 52)
{
header.RedMask = BinaryPrimitives.ReadUInt32LittleEndian(info[40..]);
header.GreenMask = BinaryPrimitives.ReadUInt32LittleEndian(info[44..]);
header.BlueMask = BinaryPrimitives.ReadUInt32LittleEndian(info[48..]);
header.AlphaMask = infoSize >= 56 ? BinaryPrimitives.ReadUInt32LittleEndian(info[52..]) : 0;
}
else
{
// An information header is followed by the three (or four) masks.
var maskCount = header.Compression == BiAlphaBitfields ? 4 : 3;
if (data.Length < afterHeader + (maskCount * 4))
{
throw new ImageDecodeException("BMP troncato: mancano le maschere dei colori.");
}
header.RedMask = BinaryPrimitives.ReadUInt32LittleEndian(data[afterHeader..]);
header.GreenMask = BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 4)..]);
header.BlueMask = BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 8)..]);
header.AlphaMask = maskCount == 4 ? BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 12)..]) : 0;
afterHeader += maskCount * 4;
}
if (!IsContiguous(header.RedMask) || !IsContiguous(header.GreenMask) || !IsContiguous(header.BlueMask) || !IsContiguous(header.AlphaMask)
|| (header.BitsPerPixel == 16 && ((header.RedMask | header.GreenMask | header.BlueMask | header.AlphaMask) >> 16) != 0))
{
throw new ImageDecodeException("BMP danneggiato: maschere dei colori non valide.");
}
}
else if (bpp == 16)
{
(header.RedMask, header.GreenMask, header.BlueMask) = (0x7C00, 0x03E0, 0x001F);
}
else if (bpp == 32)
{
(header.RedMask, header.GreenMask, header.BlueMask) = (0x00FF0000, 0x0000FF00, 0x000000FF);
}
var offset = BinaryPrimitives.ReadUInt32LittleEndian(data[10..]);
if (bpp <= 8 && header.Compression != BiPng)
{
var max = 1 << bpp;
var count = colorsUsed == 0 || colorsUsed > max ? max : (int)colorsUsed;
if (offset >= afterHeader)
{
// The pixels may start before the palette would end: the palette is what fits in between.
count = (int)Math.Min(count, (offset - afterHeader) / paletteEntrySize);
}
count = Math.Min(count, Math.Max(0, (data.Length - afterHeader) / paletteEntrySize));
var palette = new uint[256];
Array.Fill(palette, 0xFF000000u);
for (var i = 0; i < count; i++)
{
var p = afterHeader + (i * paletteEntrySize);
palette[i] = Rgba(data[p + 2], data[p + 1], data[p], 255);
}
header.Palette = palette;
if (offset < afterHeader)
{
offset = (uint)(afterHeader + (count * paletteEntrySize));
}
}
else if (offset < afterHeader)
{
offset = (uint)afterHeader;
}
if (offset >= data.Length)
{
throw new ImageDecodeException("BMP troncato: i pixel cominciano dopo la fine del file.");
}
header.PixelOffset = (int)offset;
return header;
}
private static bool IsContiguous(uint mask) => mask == 0 || (((mask >> BitOperations.TrailingZeroCount(mask)) + 1) & (mask >> BitOperations.TrailingZeroCount(mask))) == 0;
private static uint Rgba(byte r, byte g, byte b, byte a) => r | ((uint)g << 8) | ((uint)b << 16) | ((uint)a << 24);
private static void DecodeRows(ReadOnlySpan data, BmpHeader header, RgbaImage image)
{
var stride = header.Stride;
var width = header.Width;
var height = header.Height;
var needed = (long)stride * (height - 1) + ((((long)width * header.BitsPerPixel) + 7) / 8);
if (header.PixelOffset + needed > data.Length)
{
throw new ImageDecodeException("BMP troncato: i pixel finiscono dopo il file.");
}
var bpp = header.BitsPerPixel;
Span red = stackalloc byte[256];
Span green = stackalloc byte[256];
Span blue = stackalloc byte[256];
Span alpha = stackalloc byte[256];
var rs = MaskShift(header.RedMask, red);
var gs = MaskShift(header.GreenMask, green);
var bs = MaskShift(header.BlueMask, blue);
var hasAlpha = header.AlphaMask != 0;
var @as = hasAlpha ? MaskShift(header.AlphaMask, alpha) : default;
var palette = header.Palette;
for (var y = 0; y < height; y++)
{
var source = data.Slice(header.PixelOffset + (y * stride));
var destination = image.GetRow(header.TopDown ? y : height - 1 - y);
switch (bpp)
{
case 1 or 2 or 4 or 8:
{
var mask = (1 << bpp) - 1;
var perByte = 8 / bpp;
for (var x = 0; x < width; x++)
{
var shift = 8 - bpp - ((x % perByte) * bpp);
var index = (source[x / perByte] >> shift) & mask;
BinaryPrimitives.WriteUInt32LittleEndian(destination[(x * 4)..], palette![index]);
}
break;
}
case 24:
for (int x = 0, s = 0, d = 0; x < width; x++, s += 3, d += 4)
{
destination[d] = source[s + 2];
destination[d + 1] = source[s + 1];
destination[d + 2] = source[s];
destination[d + 3] = 255;
}
break;
case 32 when header.RedMask == 0x00FF0000 && header.GreenMask == 0x0000FF00 && header.BlueMask == 0x000000FF && (!hasAlpha || header.AlphaMask == 0xFF000000):
for (int x = 0, s = 0; x < width; x++, s += 4)
{
destination[s] = source[s + 2];
destination[s + 1] = source[s + 1];
destination[s + 2] = source[s];
destination[s + 3] = hasAlpha ? source[s + 3] : (byte)255;
}
break;
default:
for (int x = 0, d = 0; x < width; x++, d += 4)
{
var pixel = bpp == 16
? BinaryPrimitives.ReadUInt16LittleEndian(source[(x * 2)..])
: BinaryPrimitives.ReadUInt32LittleEndian(source[(x * 4)..]);
destination[d] = Channel(pixel, header.RedMask, rs, red);
destination[d + 1] = Channel(pixel, header.GreenMask, gs, green);
destination[d + 2] = Channel(pixel, header.BlueMask, bs, blue);
destination[d + 3] = hasAlpha ? Channel(pixel, header.AlphaMask, @as, alpha) : (byte)255;
}
break;
}
}
}
///
/// The shift of a mask and, for masks of up to 8 bits, the 8-bit value of each of their values (scaled with
/// rounding: 31 → 255, 1 of 5 bits → 8) in . Wider masks keep their top 8 bits.
///
private static (int Shift, int Bits) MaskShift(uint mask, Span table)
{
if (mask == 0)
{
return (0, 0);
}
var shift = BitOperations.TrailingZeroCount(mask);
var bits = BitOperations.PopCount(mask);
if (bits <= 8)
{
var max = (1 << bits) - 1;
for (var v = 0; v <= max; v++)
{
table[v] = (byte)(((v * 255) + (max / 2)) / max);
}
}
return (shift, bits);
}
private static byte Channel(uint pixel, uint mask, (int Shift, int Bits) layout, ReadOnlySpan table)
{
if (layout.Bits == 0)
{
return 0;
}
var value = (pixel & mask) >> layout.Shift;
return layout.Bits <= 8 ? table[(int)value] : (byte)(value >> (layout.Bits - 8));
}
private static void DecodeRle(ReadOnlySpan data, BmpHeader header, RgbaImage image)
{
var palette = header.Palette!;
var four = header.Compression == BiRle4;
var width = header.Width;
var height = header.Height;
var pixels = image.Pixels;
var pos = header.PixelOffset;
int x = 0, y = 0;
while (y < height)
{
if (pos + 2 > data.Length)
{
throw new ImageDecodeException("BMP troncato: i dati RLE finiscono prima della fine dell'immagine.");
}
int count = data[pos], value = data[pos + 1];
pos += 2;
if (count > 0)
{
// An encoded run: «count» pixels of one index (RLE8) or of two alternating indices (RLE4).
var rowStart = (height - 1 - y) * width;
for (var k = 0; k < count && x < width; k++, x++)
{
var index = four ? ((k & 1) == 0 ? value >> 4 : value & 0x0F) : value;
BinaryPrimitives.WriteUInt32LittleEndian(pixels[((rowStart + x) * 4)..], palette[index]);
}
continue;
}
switch (value)
{
case 0:
x = 0;
y++;
break;
case 1:
return;
case 2:
if (pos + 2 > data.Length)
{
throw new ImageDecodeException("BMP troncato: uno spostamento RLE finisce dopo il file.");
}
x += data[pos];
y += data[pos + 1];
pos += 2;
break;
default:
{
// An absolute run: «value» indices one after the other, padded to an even number of bytes.
var bytes = four ? (value + 1) / 2 : value;
if (pos + bytes > data.Length)
{
throw new ImageDecodeException("BMP troncato: un tratto RLE assoluto finisce dopo il file.");
}
var rowStart = (height - 1 - y) * width;
for (var k = 0; k < value && x < width; k++, x++)
{
var index = four ? ((k & 1) == 0 ? data[pos + (k / 2)] >> 4 : data[pos + (k / 2)] & 0x0F) : data[pos + k];
BinaryPrimitives.WriteUInt32LittleEndian(pixels[((rowStart + x) * 4)..], palette[index]);
}
pos += bytes + (bytes & 1);
break;
}
}
}
}
}