using System.Buffers; using System.Buffers.Binary; using System.Text; namespace Febe.Core.Codecs.Images; /// One component of a JPEG frame and what the decoder keeps of it. internal sealed class JpegComponent { public int Id; public int Index; public int H; public int V; public int QuantizationTable; /// Samples of the component: ceil(X × H / Hmax) × ceil(Y × V / Vmax). public int Width; public int Height; /// Data units (blocks, or samples in lossless) that cover the samples: what a non-interleaved scan codes. public int UnitsWide; public int UnitsHigh; /// Data units of the MCU grid of an interleaved scan (equal to the above in a one-component frame). public int PaddedUnitsWide; public int PaddedUnitsHigh; /// Coefficients, 64 per block of the padded grid, natural order; null when not kept. public short[]? Coefficients; /// 8-bit samples, per row, covering the padded grid. public byte[]? Plane; public int PlaneStride; /// Lossless samples before the point transform is undone, same layout as . public ushort[]? Samples; /// The quantization table latched at the component's first scan, natural order. public ushort[]? Quantization; public bool Coded; // Scan state. public int DcPredictor; public int DcContext; public int DcTable; public int AcTable; } /// /// The marker-level reader of a JPEG file and its decoded state. One instance per call; the arrays it rents from the /// pool go back in . /// internal sealed partial class JpegFile : IDisposable { private const int MaxComponentsInScan = 4; private const int MaxBlocksInMcu = 10; private readonly ReadOnlyMemory _memory; private readonly ImageLimits _limits; private readonly Mode _mode; private readonly bool _readMetadata; private readonly ushort[]?[] _quantization = new ushort[4][]; private readonly JpegHuffmanTable?[] _dcTables = new JpegHuffmanTable[4]; private readonly JpegHuffmanTable?[] _acTables = new JpegHuffmanTable[4]; private readonly byte[] _dcL = new byte[4]; private readonly byte[] _dcU = [1, 1, 1, 1]; private readonly byte[] _acK = [5, 5, 5, 5]; private int _restartInterval; private bool _jfif; private int _adobeTransform = -1; private int _metadataBudget; private byte[]? _exif; private string? _xmp; private List<(int Sequence, int Count, byte[] Data)>? _iccChunks; private List? _texts; private bool _allocated; private bool _pooledArrays; private int _scaleShift; private int _scanCount; private int _sosEnd; public JpegFile(ReadOnlyMemory data, ImageLimits limits, Mode mode, bool readMetadata) { _memory = data; _limits = limits; _mode = mode; _readMetadata = readMetadata; _metadataBudget = limits.MaxMetadataBytes; } internal enum Mode { /// Stop at the first scan: frame and metadata only. Identify, /// Decode to samples. Pixels, /// Decode and keep every coefficient (tests). Coefficients, } public int FrameMarker { get; private set; } public bool Progressive { get; private set; } public bool Arithmetic { get; private set; } public bool Lossless { get; private set; } public int Precision { get; private set; } public int Width { get; private set; } public int Height { get; private set; } public JpegComponent[] Components { get; private set; } = []; /// /// The reduction of a DCT image decoded to samples, as a power of two (0 full size, 1 half, 2 quarter, 3 eighth): /// each 8×8 block gives (8 >> shift)² samples, the means of its squares of samples (only its DC term at an /// eighth). Set before ; a lossless file is always decoded at full size. /// public int ScaleShift { get => _scaleShift; set => _scaleShift = Math.Clamp(value, 0, 3); } /// Width of the decoded image: reduced by , rounded up. public int OutputWidth => Reduce(Width); /// Height of the decoded image: reduced by , rounded up. public int OutputHeight => Reduce(Height); private int Reduce(int length) => (length + (1 << _scaleShift) - 1) >> _scaleShift; public int MaxH { get; private set; } public int MaxV { get; private set; } /// MCUs per row and rows of MCUs of an interleaved scan. public int McusWide { get; private set; } public int McusHigh { get; private set; } private ReadOnlySpan Data => _memory.Span; public void Run() { var data = Data; if (!JpegDecoder.IsJpeg(data)) { throw new ImageDecodeException("Non è un file JPEG."); } var pos = 2; var sawEoi = false; while (true) { // Bytes that are not a marker between segments are skipped, as decoders have always done. while (pos < data.Length && data[pos] != 0xFF) { pos++; } while (pos < data.Length && data[pos] == 0xFF) { pos++; } if (pos >= data.Length) { break; } int marker = data[pos++]; if (marker == 0x00 || marker == 0x01 || marker is >= 0xD0 and <= 0xD7) { continue; } if (marker == 0xD9) { sawEoi = true; break; } if (marker == 0xD8) { throw new ImageDecodeException("JPEG danneggiato: due marcatori di inizio."); } if (data.Length - pos < 2) { throw Truncated(); } var length = BinaryPrimitives.ReadUInt16BigEndian(data[pos..]); if (length < 2 || length > data.Length - pos) { throw Truncated(); } var payload = data.Slice(pos + 2, length - 2); var end = pos + length; switch (marker) { case 0xC0 or 0xC1 or 0xC2 or 0xC3 or 0xC9 or 0xCA or 0xCB: ReadFrame(marker, payload); break; case 0xC5 or 0xC6 or 0xC7 or 0xCD or 0xCE or 0xCF or 0xDE or 0xDF: throw new ImageFormatNotSupportedException("Febe non legge i JPEG gerarchici (T.81, allegato J)."); case 0xC4: ReadHuffmanTables(payload); break; case 0xCC: ReadArithmeticConditioning(payload); break; case 0xDB: ReadQuantizationTables(payload); break; case 0xDD: if (payload.Length < 2) { throw new ImageDecodeException("JPEG danneggiato: segmento DRI troppo corto."); } _restartInterval = BinaryPrimitives.ReadUInt16BigEndian(payload); break; case 0xDC: ReadDnl(payload); break; case >= 0xE0 and <= 0xEF: ReadApplication(marker, payload); break; case 0xFE: if (_readMetadata) { ReadComment(payload); } break; case 0xDA: if (Components.Length == 0) { throw new ImageDecodeException("JPEG danneggiato: una scansione prima del fotogramma."); } _sosEnd = end; if (Height == 0) { FindDnl(end); } if (_mode == Mode.Identify) { return; } pos = DecodeScan(payload, end); _scanCount++; continue; default: // JPGn, reserved markers: skipped by their length. break; } pos = end; } if (Components.Length == 0) { throw new ImageDecodeException(sawEoi ? "JPEG senza fotogramma." : "JPEG troncato prima del fotogramma."); } if (_mode == Mode.Identify) { if (Height == 0) { throw new ImageDecodeException("JPEG senza altezza: manca il segmento DNL."); } return; } if (_scanCount == 0) { throw new ImageDecodeException("JPEG senza dati d'immagine."); } foreach (var component in Components) { if (!component.Coded) { throw new ImageDecodeException("JPEG incompleto: una componente non ha dati."); } } if (Progressive && _mode == Mode.Pixels) { foreach (var component in Components) { TransformAll(component); } } } public ImageInfo ToInfo() { var icc = AssembleIcc(); var metadata = _exif is null && icc is null && _xmp is null && _texts is null ? ImageMetadata.Empty : new ImageMetadata { Exif = _exif, Orientation = _exif is null ? 1 : ExifOrientation.Read(_exif), IccProfile = icc, Xmp = _xmp, Texts = _texts ?? [], }; return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision }; } public JpegCoefficients ToCoefficients() { if (Lossless) { throw new ImageFormatNotSupportedException("Un JPEG senza perdita non ha coefficienti."); } var components = new List(Components.Length); foreach (var c in Components) { components.Add(new JpegComponentCoefficients(c.Id, c.H, c.V, c.UnitsWide, c.UnitsHigh, c.PaddedUnitsWide, c.Quantization ?? new ushort[64], c.Coefficients!) { QuantizationTable = c.QuantizationTable }); } return new JpegCoefficients(FrameMarker, Precision, Width, Height, _restartInterval, _adobeTransform, _jfif, _scanCount, components); } public void Dispose() { if (!_pooledArrays) { return; } foreach (var c in Components) { if (c.Plane is { } plane) { ImageBuffers.Return(plane); c.Plane = null; } if (c.Coefficients is { } coefficients) { ImageBuffers.Return(coefficients); c.Coefficients = null; } if (c.Samples is { } samples) { ImageBuffers.Return(samples); c.Samples = null; } } } private static ImageDecodeException Truncated() => new("JPEG troncato: un segmento finisce oltre la fine del file."); private void ReadFrame(int marker, ReadOnlySpan p) { if (Components.Length != 0) { throw new ImageDecodeException("JPEG danneggiato: più di un fotogramma."); } if (p.Length < 6) { throw new ImageDecodeException("JPEG danneggiato: intestazione del fotogramma troppo corta."); } FrameMarker = marker; Progressive = marker is 0xC2 or 0xCA; Arithmetic = marker >= 0xC8; Lossless = marker is 0xC3 or 0xCB; Precision = p[0]; Height = BinaryPrimitives.ReadUInt16BigEndian(p[1..]); Width = BinaryPrimitives.ReadUInt16BigEndian(p[3..]); int count = p[5]; if (Lossless ? Precision is < 2 or > 16 : Precision is not (8 or 12)) { throw new ImageFormatNotSupportedException($"Febe non legge i JPEG con campioni di {Precision} bit."); } if (Width == 0) { throw new ImageDecodeException("JPEG danneggiato: larghezza zero."); } if (count == 0 || p.Length < 6 + (3 * count)) { throw new ImageDecodeException("JPEG danneggiato: componenti del fotogramma mancanti."); } if (count is 2 or > 4) { throw new ImageFormatNotSupportedException($"Febe non legge i JPEG con {count} componenti."); } var components = new JpegComponent[count]; for (var i = 0; i < count; i++) { var c = p.Slice(6 + (3 * i), 3); var component = new JpegComponent { Id = c[0], Index = i, H = c[1] >> 4, V = c[1] & 15, QuantizationTable = c[2] }; if (component.H is < 1 or > 4 || component.V is < 1 or > 4 || (component.QuantizationTable > 3 && !Lossless)) { throw new ImageDecodeException("JPEG danneggiato: fattori di campionamento o tabella di quantizzazione non validi."); } for (var j = 0; j < i; j++) { if (components[j].Id == component.Id) { throw new ImageDecodeException("JPEG danneggiato: due componenti con lo stesso identificativo."); } } components[i] = component; MaxH = Math.Max(MaxH, component.H); MaxV = Math.Max(MaxV, component.V); } Components = components; if (Height != 0) { ComputeGeometry(); } } private void ComputeGeometry() { var unit = Lossless ? 1 : 8; McusWide = Ceil(Width, unit * MaxH); McusHigh = Ceil(Height, unit * MaxV); foreach (var c in Components) { c.Width = Ceil(Width * c.H, MaxH); c.Height = Ceil(Height * c.V, MaxV); c.UnitsWide = Ceil(c.Width, unit); c.UnitsHigh = Ceil(c.Height, unit); if (Components.Length == 1) { c.PaddedUnitsWide = c.UnitsWide; c.PaddedUnitsHigh = c.UnitsHigh; } else { c.PaddedUnitsWide = McusWide * c.H; c.PaddedUnitsHigh = McusHigh * c.V; } } } private static int Ceil(int value, int divisor) => (value + divisor - 1) / divisor; private void ReadDnl(ReadOnlySpan p) { if (p.Length < 2) { throw new ImageDecodeException("JPEG danneggiato: segmento DNL troppo corto."); } if (Height == 0 && Components.Length > 0) { Height = BinaryPrimitives.ReadUInt16BigEndian(p); if (Height == 0) { throw new ImageDecodeException("JPEG danneggiato: altezza zero nel segmento DNL."); } ComputeGeometry(); } } /// A frame of height 0 gives it in a DNL segment right after the first scan (T.81 B.2.5). private void FindDnl(int scanStart) { var data = Data; var pos = FindNextMarker(scanStart); if (pos + 6 <= data.Length && data[pos + 1] == 0xDC) { ReadDnl(data.Slice(pos + 4, 2)); } if (Height == 0) { throw new ImageDecodeException("JPEG senza altezza: manca il segmento DNL."); } } private void ReadQuantizationTables(ReadOnlySpan p) { var zigzag = JpegTables.ZigZag; while (p.Length > 0) { var precision = p[0] >> 4; var id = p[0] & 15; var size = precision == 0 ? 64 : 128; if (id > 3 || precision > 1 || p.Length < 1 + size) { throw new ImageDecodeException("JPEG danneggiato: tabella di quantizzazione non valida."); } var table = new ushort[64]; for (var k = 0; k < 64; k++) { table[zigzag[k]] = precision == 0 ? p[1 + k] : BinaryPrimitives.ReadUInt16BigEndian(p[(1 + (2 * k))..]); } _quantization[id] = table; p = p[(1 + size)..]; } } private void ReadHuffmanTables(ReadOnlySpan p) { while (p.Length > 0) { if (p.Length < 17) { throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman troncata."); } var tableClass = p[0] >> 4; var id = p[0] & 15; if (tableClass > 1 || id > 3) { throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman non valida."); } var counts = p.Slice(1, 16); var total = 0; foreach (var count in counts) { total += count; } if (p.Length < 17 + total) { throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman troncata."); } var table = JpegHuffmanTable.Build(counts, p.Slice(17, total)); (tableClass == 0 ? _dcTables : _acTables)[id] = table; p = p[(17 + total)..]; } } private void ReadArithmeticConditioning(ReadOnlySpan p) { for (; p.Length >= 2; p = p[2..]) { var tableClass = p[0] >> 4; var id = p[0] & 15; var value = p[1]; if (id > 3) { throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico non valido."); } if (tableClass == 0) { var low = value & 15; var high = value >> 4; if (low > high) { throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico con L maggiore di U."); } _dcL[id] = (byte)low; _dcU[id] = (byte)high; } else { if (value is < 1 or > 63) { throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico Kx non valido."); } _acK[id] = value; } } } private void ReadApplication(int marker, ReadOnlySpan p) { // JFIF and Adobe decide the colour space, so they are read even without metadata. if (marker == 0xE0 && p.Length >= 5 && p[..5].SequenceEqual("JFIF\0"u8)) { _jfif = true; return; } if (marker == 0xEE && p.Length >= 12 && p[..5].SequenceEqual("Adobe"u8)) { _adobeTransform = p[11]; return; } if (!_readMetadata) { return; } // Damaged or oversized metadata is skipped: it must never stop an image from being shown. if (marker == 0xE1) { if (_exif is null && p.Length > 6 && p[..4].SequenceEqual("Exif"u8) && p[4] == 0) { var tiff = p[6..]; if (Spend(tiff.Length)) { _exif = tiff.ToArray(); } } else if (_xmp is null && p.StartsWith(XmpNamespace)) { var packet = p[XmpNamespace.Length..]; if (Spend(packet.Length)) { _xmp = Encoding.UTF8.GetString(packet); } } } else if (marker == 0xE2 && p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8)) { int sequence = p[12]; int count = p[13]; var chunk = p[14..]; if (sequence >= 1 && sequence <= count && Spend(chunk.Length)) { (_iccChunks ??= []).Add((sequence, count, chunk.ToArray())); } } } /// The namespace that starts an XMP APP1 segment, with its terminating zero. internal static ReadOnlySpan XmpNamespace => "http://ns.adobe.com/xap/1.0/\0"u8; private void ReadComment(ReadOnlySpan p) { if (!Spend(p.Length)) { return; } string text; try { text = new UTF8Encoding(false, true).GetString(p); } catch (DecoderFallbackException) { text = Encoding.Latin1.GetString(p); } (_texts ??= []).Add(new ImageText(string.Empty, text.TrimEnd('\0'))); } private bool Spend(int bytes) { if (bytes > _metadataBudget) { return false; } _metadataBudget -= bytes; return true; } /// The ICC profile from its APP2 chunks, or null when a chunk is missing or they disagree. private byte[]? AssembleIcc() { if (_iccChunks is null) { return null; } var count = _iccChunks[0].Count; var parts = new byte[count][]; foreach (var (sequence, chunkCount, chunk) in _iccChunks) { if (chunkCount != count || parts[sequence - 1] is not null) { return null; } parts[sequence - 1] = chunk; } var total = 0; foreach (var part in parts) { if (part is null) { return null; } total += part.Length; } var profile = new byte[total]; var offset = 0; foreach (var part in parts) { part.CopyTo(profile, offset); offset += part.Length; } return profile; } /// The position of the next marker that is not a restart marker, or the end of the data. private int FindNextMarker(int pos) { var data = Data; while (pos + 1 < data.Length) { if (data[pos] == 0xFF) { var next = data[pos + 1]; if (next == 0xFF) { pos++; continue; } if (next != 0 && next is not (>= 0xD0 and <= 0xD7)) { return pos; } pos += 2; continue; } pos++; } return data.Length; } /// /// After a restart interval: the position just after the next RSTn marker, skipping any stray bytes before it; or /// the position of a marker that is not RSTn (it ends the scan), or the end of the data. /// private int SkipRestartMarker(int pos) { var data = Data; while (pos + 1 < data.Length) { if (data[pos] == 0xFF) { var next = data[pos + 1]; if (next is >= 0xD0 and <= 0xD7) { return pos + 2; } if (next != 0 && next != 0xFF) { return pos; } } pos++; } return data.Length; } private void Allocate() { if (Lossless || _mode != Mode.Pixels) { _scaleShift = 0; } _limits.CheckSize(OutputWidth, OutputHeight); var keepCoefficients = Progressive || _mode == Mode.Coefficients; long bytes = 0; foreach (var c in Components) { var unit = Lossless ? 1 : 8; long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit; bytes += samples >> (2 * _scaleShift); if (keepCoefficients && !Lossless) { bytes += samples * 2; } if (Lossless) { // The samples before the point transform, and for arithmetic coding the class of every difference. bytes += samples * (Arithmetic ? 3 : 2); } } _limits.CheckWorkingBytes(bytes); _pooledArrays = _mode == Mode.Pixels; foreach (var c in Components) { var unit = Lossless ? 1 : 8; var planeUnit = unit >> _scaleShift; c.PlaneStride = c.PaddedUnitsWide * planeUnit; var samples = c.PlaneStride * c.PaddedUnitsHigh * unit; if (_mode == Mode.Pixels) { c.Plane = ImageBuffers.Rent(c.PlaneStride * c.PaddedUnitsHigh * planeUnit); } if (Lossless) { c.Samples = _pooledArrays ? ImageBuffers.Rent(samples) : new ushort[samples]; } else if (keepCoefficients) { var length = c.PaddedUnitsWide * c.PaddedUnitsHigh * 64; if (_pooledArrays) { c.Coefficients = ImageBuffers.Rent(length); c.Coefficients.AsSpan(0, length).Clear(); } else { c.Coefficients = new short[length]; } } } _allocated = true; } /// A scan: its components in order and its spectral and approximation parameters. private readonly record struct Scan(JpegComponent[] Components, int Ss, int Se, int Ah, int Al); private int DecodeScan(ReadOnlySpan p, int start) { if (!_allocated) { Allocate(); } var scan = ReadScanHeader(p); foreach (var c in scan.Components) { if (!c.Coded) { c.Coded = true; if (!Lossless) { c.Quantization = (ushort[])(_quantization[c.QuantizationTable] ?? throw new ImageDecodeException("JPEG danneggiato: manca una tabella di quantizzazione.")).Clone(); } } c.DcPredictor = 0; c.DcContext = 0; } if (Lossless) { return Arithmetic ? DecodeLosslessArithmeticScan(scan, start) : DecodeLosslessHuffmanScan(scan, start); } return Arithmetic ? DecodeArithmeticScan(scan, start) : DecodeHuffmanScan(scan, start); } private Scan ReadScanHeader(ReadOnlySpan p) { if (p.Length < 1) { throw new ImageDecodeException("JPEG danneggiato: intestazione di scansione vuota."); } int count = p[0]; if (count is < 1 or > MaxComponentsInScan || p.Length < 4 + (2 * count)) { throw new ImageDecodeException("JPEG danneggiato: intestazione di scansione non valida."); } var components = new JpegComponent[count]; var blocks = 0; for (var i = 0; i < count; i++) { int id = p[1 + (2 * i)]; var tables = p[2 + (2 * i)]; JpegComponent? found = null; foreach (var c in Components) { if (c.Id == id) { found = c; } } if (found is null || Array.IndexOf(components, found, 0, i) >= 0) { throw new ImageDecodeException("JPEG danneggiato: la scansione nomina una componente che non c'è."); } found.DcTable = tables >> 4; found.AcTable = tables & 15; if (found.DcTable > 3 || found.AcTable > 3) { throw new ImageDecodeException("JPEG danneggiato: tabella d'entropia non valida."); } components[i] = found; blocks += found.H * found.V; } if (count > 1 && blocks > MaxBlocksInMcu) { throw new ImageDecodeException("JPEG danneggiato: troppi blocchi in un MCU."); } var tail = p.Slice(1 + (2 * count), 3); int ss = tail[0]; int se = tail[1]; var ah = tail[2] >> 4; var al = tail[2] & 15; if (Lossless) { if (ss is < 1 or > 7 || al >= Precision) { throw new ImageDecodeException("JPEG danneggiato: predittore o trasformazione di punto non validi."); } } else if (Progressive) { var valid = se <= 63 && ss <= se && al <= 13 && ah <= 13 && (ss == 0 ? se == 0 : count == 1 && ss >= 1); if (!valid) { throw new ImageDecodeException("JPEG danneggiato: parametri della scansione progressiva non validi."); } } else { ss = 0; se = 63; ah = 0; al = 0; } return new Scan(components, ss, se, ah, al); } /// The MCUs of a scan: one block (or sample) each when it has one component, the MCU grid otherwise. private (int PerRow, int Total) McuLayout(in Scan scan) { if (scan.Components.Length == 1) { var c = scan.Components[0]; return (c.UnitsWide, c.UnitsWide * c.UnitsHigh); } return (McusWide, McusWide * McusHigh); } private JpegHuffmanTable DcTable(int id) => _dcTables[id] ?? (id < 2 ? DefaultTables.Dc[id] : throw new ImageDecodeException("JPEG danneggiato: manca una tabella di Huffman.")); private JpegHuffmanTable AcTable(int id) => _acTables[id] ?? (id < 2 ? DefaultTables.Ac[id] : throw new ImageDecodeException("JPEG danneggiato: manca una tabella di Huffman.")); /// /// The Annex K tables, used when a Huffman scan refers to table 0 or 1 that the file never defines (motion JPEG /// frames leave them out). /// private static class DefaultTables { public static readonly JpegHuffmanTable[] Dc = [ JpegHuffmanTable.Build(JpegTables.LuminanceDcCounts, JpegTables.LuminanceDcValues), JpegHuffmanTable.Build(JpegTables.ChrominanceDcCounts, JpegTables.ChrominanceDcValues), ]; public static readonly JpegHuffmanTable[] Ac = [ JpegHuffmanTable.Build(JpegTables.LuminanceAcCounts, JpegTables.LuminanceAcValues), JpegHuffmanTable.Build(JpegTables.ChrominanceAcCounts, JpegTables.ChrominanceAcValues), ]; } /// The IDCT of every visible block of a component whose coefficients were kept. private void TransformAll(JpegComponent c) { var to8 = Precision == 12 ? Twelve.ToEight : default; var coefficients = c.Coefficients!; var plane = c.Plane!; for (var by = 0; by < c.UnitsHigh; by++) { for (var bx = 0; bx < c.UnitsWide; bx++) { var block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64); TransformBlock(c, plane, block, bx, by, to8); } } } /// The samples of one block into the plane of its component, at the scale of . private void TransformBlock(JpegComponent c, byte[] plane, ReadOnlySpan block, int bx, int by, ReadOnlySpan to8) { var n = 8 >> _scaleShift; var output = plane.AsSpan((by * n * c.PlaneStride) + (bx * n)); if (_scaleShift == 0) { JpegDct.Inverse(block, c.Quantization, output, c.PlaneStride, Precision, to8); } else { JpegDct.InverseReduced(block, c.Quantization, output, c.PlaneStride, Precision, to8, _scaleShift); } } /// 12-bit samples to 8 bits, rounded. private static class Twelve { public static readonly byte[] ToEight = Build(); private static byte[] Build() { var table = new byte[4096]; for (var i = 0; i < table.Length; i++) { table[i] = (byte)(((i * 255) + 2047) / 4095); } return table; } } }