using System.Numerics; using Febe.Core.Codecs.Images; namespace Febe.Tests.Imaging; /// Entropy coding of the test encoder. public enum JpegTestCoding { Huffman, Arithmetic, } /// One scan of a progressive script: components (frame indices), band and approximation. internal sealed record JpegTestScan(int[] Components, int Ss, int Se, int Ah, int Al); /// What the test encoder writes around the coefficients it is given. internal sealed record JpegTestOptions { public JpegTestCoding Coding { get; init; } = JpegTestCoding.Huffman; public bool Progressive { get; init; } /// The progressive script; null for . public IReadOnlyList? Script { get; init; } /// Sequential only: one scan per component instead of one interleaved scan. public bool SeparateScans { get; init; } public int RestartInterval { get; init; } /// Write height 0 in the frame and give it in a DNL segment after the first scan. public bool HeightInDnl { get; init; } public bool Jfif { get; init; } = true; /// Adobe APP14 transform to write (0 none/RGB/CMYK, 1 YCbCr, 2 YCCK), or -1 for no segment. public int AdobeTransform { get; init; } = -1; /// Arithmetic DC conditioning (L, U) and AC conditioning Kx, written in DAC when not the defaults. public (int L, int U) DcConditioning { get; init; } = (0, 1); public int AcConditioning { get; init; } = 5; } /// /// A JPEG writer for the tests only, from quantized coefficients (, /// ): extended sequential and progressive DCT (T.81 Annex G: spectral /// selection and successive approximation, EOB runs, correction bits), Huffman with tables built from the symbol counts /// of each scan (Annex K.2) or arithmetic coding (Annex D, F.1.4, G.1.3), restart intervals, DNL, Adobe APP14; and /// lossless (Annex H) from samples. It exists to make files the reference set lacks; the tests then check that the /// decoder gets back exactly the coefficients (or samples) that went in. /// internal static class JpegTestEncoder { private const int DcStatistics = 64; private const int AcStatistics = 256; private const int LosslessStatistics = 158; /// A script like the usual ones: DC first with Al 1, AC bands with Al 2 then 1, refinements down to 0. public static IReadOnlyList DefaultScript(int componentCount) { var all = Enumerable.Range(0, componentCount).ToArray(); var scans = new List { new(all, 0, 0, 0, 1) }; for (var c = 0; c < componentCount; c++) { scans.Add(new([c], 1, 5, 0, 2)); scans.Add(new([c], 6, 63, 0, 2)); } for (var c = componentCount - 1; c >= 0; c--) { scans.Add(new([c], 1, 63, 2, 1)); } scans.Add(new(all, 0, 0, 1, 0)); for (var c = 0; c < componentCount; c++) { scans.Add(new([c], 1, 63, 1, 0)); } return scans; } /// Writes a DCT-based file holding exactly 's coefficients. public static byte[] Write(JpegCoefficients image, JpegTestOptions options) { var output = new JpegOutput(); output.Marker(0xD8); WriteHeaders(output, options); var tables = new List(); foreach (var c in image.Components) { while (tables.Count <= c.QuantizationTable) { tables.Add(new ushort[64]); } tables[c.QuantizationTable] = c.Quantization; } JpegSegments.WriteQuantization(output, tables); var marker = (options.Coding, options.Progressive) switch { (JpegTestCoding.Huffman, false) => 0xC1, (JpegTestCoding.Huffman, true) => 0xC2, (JpegTestCoding.Arithmetic, false) => 0xC9, _ => 0xCA, }; JpegSegments.WriteFrame(output, marker, image.Precision, image.Width, options.HeightInDnl ? 0 : image.Height, image.Components.Select(c => (c.Id, c.H, c.V, c.QuantizationTable)).ToList()); if (options.RestartInterval > 0) { JpegSegments.WriteRestartInterval(output, options.RestartInterval); } if (options.Coding == JpegTestCoding.Arithmetic) { WriteConditioning(output, options, image.Components.Count); } var all = Enumerable.Range(0, image.Components.Count).ToArray(); IReadOnlyList script = options.Progressive ? options.Script ?? DefaultScript(image.Components.Count) : options.SeparateScans ? all.Select(c => new JpegTestScan([c], 0, 63, 0, 0)).ToList() : [new JpegTestScan(all, 0, 63, 0, 0)]; var layout = new Layout(image.Width, image.Height, image.Components.Select(c => (c.H, c.V)).ToList(), 8); var first = true; foreach (var scan in script) { if (options.Coding == JpegTestCoding.Huffman) { WriteHuffmanScan(output, image, layout, scan, options); } else { WriteArithmeticScan(output, image, layout, scan, options); } if (first && options.HeightInDnl) { JpegSegments.WriteSegment(output, 0xDC, [(byte)(image.Height >> 8), (byte)image.Height]); } first = false; } output.Marker(0xD9); return output.ToArray(); } /// /// Writes a lossless file (SOF3 or SOF11) of the given samples: one plane per component at its own size, values /// below 2^precision; 1-7, point transform . /// public static byte[] WriteLossless( int width, int height, int precision, IReadOnlyList<(int Id, int H, int V, int[] Samples)> planes, int predictor, int pointTransform, JpegTestOptions options) { var output = new JpegOutput(); output.Marker(0xD8); WriteHeaders(output, options); JpegSegments.WriteFrame(output, options.Coding == JpegTestCoding.Huffman ? 0xC3 : 0xCB, precision, width, height, planes.Select(p => (p.Id, p.H, p.V, 0)).ToList()); if (options.RestartInterval > 0) { JpegSegments.WriteRestartInterval(output, options.RestartInterval); } if (options.Coding == JpegTestCoding.Arithmetic) { WriteConditioning(output, options, planes.Count); } var layout = new Layout(width, height, planes.Select(p => (p.H, p.V)).ToList(), 1); var all = Enumerable.Range(0, planes.Count).ToArray(); var scans = options.SeparateScans ? all.Select(c => new[] { c }).ToList() : [all]; foreach (var components in scans) { var model = new LosslessModel(layout, planes, components, precision, predictor, pointTransform); if (options.Coding == JpegTestCoding.Huffman) { var counter = new CountingSink(); model.EncodeHuffman(counter, options.RestartInterval); var tables = counter.BuildTables(output, components.Length); JpegSegments.WriteScan(output, components.Select((c, j) => (planes[c].Id, j, 0)).ToList(), predictor, 0, 0, pointTransform); var writer = new WritingSink(output, tables); model.EncodeHuffman(writer, options.RestartInterval); writer.Finish(); } else { JpegSegments.WriteScan(output, components.Select((c, j) => (planes[c].Id, j, 0)).ToList(), predictor, 0, 0, pointTransform); var encoder = new ArithmeticEncoder(output); model.EncodeArithmetic(encoder, options); encoder.Flush(); } } output.Marker(0xD9); return output.ToArray(); } private static void WriteHeaders(JpegOutput output, JpegTestOptions options) { if (options.Jfif) { JpegSegments.WriteJfif(output); } if (options.AdobeTransform >= 0) { JpegSegments.WriteSegment(output, 0xEE, [(byte)'A', (byte)'d', (byte)'o', (byte)'b', (byte)'e', 0, 100, 0, 0, 0, 0, (byte)options.AdobeTransform]); } } private static void WriteConditioning(JpegOutput output, JpegTestOptions options, int tables) { if (options.DcConditioning == (0, 1) && options.AcConditioning == 5) { return; } var payload = new List(); for (var t = 0; t < Math.Min(tables, 4); t++) { payload.Add((byte)t); payload.Add((byte)((options.DcConditioning.U << 4) | options.DcConditioning.L)); payload.Add((byte)(0x10 | t)); payload.Add((byte)options.AcConditioning); } JpegSegments.WriteSegment(output, 0xCC, payload.ToArray()); } /// MCU geometry, the same rules as the decoder (T.81 A.2). private sealed class Layout { public Layout(int width, int height, IReadOnlyList<(int H, int V)> sampling, int unit) { var maxH = sampling.Max(s => s.H); var maxV = sampling.Max(s => s.V); McusWide = (width + (unit * maxH) - 1) / (unit * maxH); McusHigh = (height + (unit * maxV) - 1) / (unit * maxV); Sampling = sampling; Wide = new int[sampling.Count]; High = new int[sampling.Count]; Stride = new int[sampling.Count]; for (var i = 0; i < sampling.Count; i++) { var cw = ((width * sampling[i].H) + maxH - 1) / maxH; var ch = ((height * sampling[i].V) + maxV - 1) / maxV; Wide[i] = (cw + unit - 1) / unit; High[i] = (ch + unit - 1) / unit; Stride[i] = sampling.Count == 1 ? Wide[i] : McusWide * sampling[i].H; } } public int McusWide { get; } public int McusHigh { get; } public IReadOnlyList<(int H, int V)> Sampling { get; } /// Units covering each component (a non-interleaved scan). public int[] Wide { get; } public int[] High { get; } /// Units per row of each component's storage. public int[] Stride { get; } /// Calls (position in scan, component, x, y) for every data unit, and () between intervals. public void Walk(int[] components, int restartInterval, Action unit, Action restart) { var single = components.Length == 1; var perRow = single ? Wide[components[0]] : McusWide; var total = single ? Wide[components[0]] * High[components[0]] : McusWide * McusHigh; for (var mcu = 0; mcu < total; mcu++) { if (restartInterval > 0 && mcu > 0 && mcu % restartInterval == 0) { restart(); } var mx = mcu % perRow; var my = mcu / perRow; for (var j = 0; j < components.Length; j++) { var c = components[j]; var (h, v) = single ? (1, 1) : Sampling[c]; for (var yy = 0; yy < v; yy++) { for (var xx = 0; xx < h; xx++) { unit(j, c, single ? mx : (mx * h) + xx, single ? my : (my * v) + yy); } } } } } } /// Receives Huffman symbols (tables 0-3 DC, 4-7 AC) and raw bits. private interface ISink { void Symbol(int table, int symbol); void Bits(int value, int count); void Restart(); } private sealed class CountingSink : ISink { private readonly long[][] _counts = Enumerable.Range(0, 8).Select(_ => new long[256]).ToArray(); public void Symbol(int table, int symbol) => _counts[table][symbol]++; public void Bits(int value, int count) { } public void Restart() { } /// Optimal tables for the counted symbols (T.81 K.2), written as DHT segments. public JpegHuffmanTable?[] BuildTables(JpegOutput output, int count) { var tables = new JpegHuffmanTable?[8]; for (var t = 0; t < 8; t++) { if (_counts[t].All(c => c == 0)) { continue; } var (counts, values) = OptimalTable(_counts[t]); tables[t] = JpegHuffmanTable.Build(counts, values); JpegSegments.WriteHuffman(output, t >= 4 ? 1 : 0, t & 3, counts, values); } return tables; } } private sealed class WritingSink : ISink { private readonly JpegOutput _output; private readonly JpegHuffmanTable?[] _tables; private readonly JpegBitWriter _writer; private int _restart; public WritingSink(JpegOutput output, JpegHuffmanTable?[] tables) { _output = output; _tables = tables; _writer = new JpegBitWriter(output); } public void Symbol(int table, int symbol) => _writer.WriteSymbol(_tables[table]!, symbol); public void Bits(int value, int count) { if (count > 0) { _writer.WriteBits(value, count); } } public void Restart() { _writer.Flush(); _output.Marker(0xD0 + (_restart++ & 7)); } public void Finish() => _writer.Flush(); } /// Code lengths from symbol counts (Figures K.1-K.3), limited to 16 bits, no all-ones code. private static (byte[] Counts, byte[] Values) OptimalTable(long[] frequencies) { var freq = new long[257]; Array.Copy(frequencies, freq, 256); freq[256] = 1; var codeSize = new int[257]; var others = Enumerable.Repeat(-1, 257).ToArray(); while (true) { var v1 = -1; var v2 = -1; for (var i = 0; i <= 256; i++) { if (freq[i] > 0 && (v1 < 0 || freq[i] <= freq[v1])) { v1 = i; } } for (var i = 0; i <= 256; i++) { if (freq[i] > 0 && i != v1 && (v2 < 0 || freq[i] <= freq[v2])) { v2 = i; } } if (v2 < 0) { break; } freq[v1] += freq[v2]; freq[v2] = 0; codeSize[v1]++; while (others[v1] >= 0) { v1 = others[v1]; codeSize[v1]++; } others[v1] = v2; codeSize[v2]++; while (others[v2] >= 0) { v2 = others[v2]; codeSize[v2]++; } } var bits = new int[33]; for (var i = 0; i <= 256; i++) { if (codeSize[i] > 0) { bits[codeSize[i]]++; } } for (var i = 32; i > 16; i--) { while (bits[i] > 0) { var j = i - 2; while (bits[j] == 0) { j--; } bits[i] -= 2; bits[i - 1]++; bits[j + 1] += 2; bits[j]--; } } var longest = 16; while (bits[longest] == 0) { longest--; } bits[longest]--; var values = new List(); for (var size = 1; size <= 32; size++) { for (var s = 0; s < 256; s++) { if (codeSize[s] == size) { values.Add((byte)s); } } } return (bits.Skip(1).Take(16).Select(b => (byte)b).ToArray(), values.ToArray()); } private static int Category(int value) => value == 0 ? 0 : BitOperations.Log2((uint)Math.Abs(value)) + 1; private static void Value(ISink sink, int table, int run, int value) { var category = Category(value); sink.Symbol(table, (run << 4) | category); sink.Bits(value < 0 ? value - 1 : value, category); } /// Point transform of an AC coefficient: the magnitude shifted, the sign kept (G.1.2.3). private static int Shifted(int coefficient, int al) => coefficient >= 0 ? coefficient >> al : -(-coefficient >> al); private static void WriteHuffmanScan(JpegOutput output, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) { var counter = new CountingSink(); EncodeHuffmanScan(counter, image, layout, scan, options); var tables = counter.BuildTables(output, scan.Components.Length); JpegSegments.WriteScan(output, scan.Components.Select((c, j) => (image.Components[c].Id, j, j)).ToList(), scan.Ss, scan.Se, scan.Ah, scan.Al); var writer = new WritingSink(output, tables); EncodeHuffmanScan(writer, image, layout, scan, options); writer.Finish(); } private static void EncodeHuffmanScan(ISink sink, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) { var zigzag = JpegTables.ZigZag; var predictors = new int[scan.Components.Length]; var eobRun = 0; var pendingBits = new List(); var progressive = options.Progressive; var refineAc = progressive && scan.Ss > 0 && scan.Ah > 0; void EmitEobRun() { if (eobRun > 0) { var bits = BitOperations.Log2((uint)eobRun); sink.Symbol(4, bits << 4); sink.Bits(eobRun, bits); eobRun = 0; } foreach (var bit in pendingBits) { sink.Bits(bit, 1); } pendingBits.Clear(); } layout.Walk( scan.Components, options.RestartInterval, (j, c, x, y) => { var component = image.Components[c]; var block = component.Block(x, y); if (!progressive) { var difference = block[0] - predictors[j]; predictors[j] = block[0]; Value(sink, j, 0, difference); var run = 0; for (var k = 1; k < 64; k++) { int value = block[zigzag[k]]; if (value == 0) { run++; continue; } for (; run > 15; run -= 16) { sink.Symbol(4 + j, 0xF0); } Value(sink, 4 + j, run, value); run = 0; } if (run > 0) { sink.Symbol(4 + j, 0x00); } } else if (scan.Ss == 0 && scan.Ah == 0) { var dc = block[0] >> scan.Al; Value(sink, j, 0, dc - predictors[j]); predictors[j] = dc; } else if (scan.Ss == 0) { sink.Bits((block[0] >> scan.Al) & 1, 1); } else if (!refineAc) { var run = 0; for (var k = scan.Ss; k <= scan.Se; k++) { var value = Shifted(block[zigzag[k]], scan.Al); if (value == 0) { run++; continue; } EmitEobRun(); for (; run > 15; run -= 16) { sink.Symbol(4, 0xF0); } Value(sink, 4, run, value); run = 0; } if (run > 0 && ++eobRun == 0x7FFF) { EmitEobRun(); } } else { var end = scan.Ss - 1; for (var k = scan.Ss; k <= scan.Se; k++) { if (Math.Abs(block[zigzag[k]]) >> scan.Al == 1) { end = k; } } var run = 0; var corrections = new List(); for (var k = scan.Ss; k <= scan.Se; k++) { var coefficient = block[zigzag[k]]; var magnitude = Math.Abs(coefficient) >> scan.Al; if (magnitude == 0) { run++; continue; } while (run > 15 && k <= end) { EmitEobRun(); sink.Symbol(4, 0xF0); run -= 16; foreach (var bit in corrections) { sink.Bits(bit, 1); } corrections.Clear(); } if (magnitude > 1) { corrections.Add(magnitude & 1); continue; } EmitEobRun(); sink.Symbol(4, (run << 4) | 1); sink.Bits(coefficient < 0 ? 0 : 1, 1); foreach (var bit in corrections) { sink.Bits(bit, 1); } corrections.Clear(); run = 0; } if (run > 0 || corrections.Count > 0) { eobRun++; pendingBits.AddRange(corrections); if (eobRun == 0x7FFF || pendingBits.Count > 900) { EmitEobRun(); } } } }, () => { EmitEobRun(); sink.Restart(); Array.Clear(predictors); }); EmitEobRun(); } /// The QM coder of T.81 D.1 (Initenc, Code_0/Code_1, Renorm_e, Byte_out with carry, Flush). private sealed class ArithmeticEncoder { private readonly JpegOutput _output; private long _c; private int _a; private int _ct; private int _buffer; private int _stack; private int _start; private int _restart; public ArithmeticEncoder(JpegOutput output) { _output = output; Initialize(); } public void Encode(ref byte state, int bit) { var s = state; int qe = JpegArithmeticTable.Qe[s & 0x7F]; var mps = s >> 7; _a -= qe; if (bit != mps) { if (_a >= qe) { _c += _a; _a = qe; } state = JpegArithmeticTable.AfterLps(s); } else { if (_a >= 0x8000) { return; } if (_a < qe) { _c += _a; _a = qe; } state = JpegArithmeticTable.AfterMps(s); } do { _a <<= 1; _c <<= 1; _ct--; if (_ct == 0) { ByteOut(); _ct = 8; } } while (_a < 0x8000); } public void EncodeFixed(int bit) { var state = JpegArithmeticTable.FixedState; Encode(ref state, bit); } public void Flush() { var t = (_c + _a - 1) & 0xFFFF0000L; if (t < _c) { t += 0x8000; } _c = t << _ct; ByteOut(); _c <<= 8; ByteOut(); EmitBuffer(); for (; _stack > 0; _stack--) { _output.Add(0xFF); _output.Add(0); } // Discard_final_zeros: the decoder supplies zeros at the marker anyway; stuffed zeros stay. while (_output.Length > _start && _output[_output.Length - 1] == 0 && (_output.Length - 1 == _start || _output[_output.Length - 2] != 0xFF)) { _output.Truncate(_output.Length - 1); } } public void Restart() { Flush(); _output.Marker(0xD0 + (_restart++ & 7)); Initialize(); } private void Initialize() { _c = 0; _a = 0x10000; _ct = 11; _buffer = -1; _stack = 0; _start = _output.Length; } private void ByteOut() { var t = _c >> 19; if (t > 0xFF) { _buffer++; EmitBuffer(); for (; _stack > 0; _stack--) { _output.Add(0); } _buffer = (int)(t & 0xFF); } else if (t == 0xFF) { _stack++; } else { EmitBuffer(); for (; _stack > 0; _stack--) { _output.Add(0xFF); _output.Add(0); } _buffer = (int)t; } _c &= 0x7FFFF; } private void EmitBuffer() { if (_buffer >= 0) { _output.Add((byte)_buffer); if (_buffer == 0xFF) { _output.Add(0); } } _buffer = -1; } } private static int Classify(int difference, int low, int high) { var magnitude = Math.Abs(difference); if (magnitude <= (low == 0 ? 0 : 1 << (low - 1))) { return 0; } var negative = difference < 0 ? 1 : 0; return magnitude <= 1 << high ? 1 + negative : 3 + negative; } /// Encode_V of a DC-model value (Figures F.4, F.6-F.9; Tables F.4, H.3). private static void EncodeValue(ArithmeticEncoder encoder, byte[] statistics, int offset, int s0, int x1, int value) { if (value == 0) { encoder.Encode(ref statistics[offset + s0], 0); return; } encoder.Encode(ref statistics[offset + s0], 1); var sign = value < 0 ? 1 : 0; encoder.Encode(ref statistics[offset + s0 + 1], sign); var s = s0 + 2 + sign; var sz = Math.Abs(value) - 1; if (sz == 0) { encoder.Encode(ref statistics[offset + s], 0); return; } encoder.Encode(ref statistics[offset + s], 1); var m = 1; s = x1; while (sz >= m << 1) { encoder.Encode(ref statistics[offset + s], 1); m <<= 1; s++; } encoder.Encode(ref statistics[offset + s], 0); for (var bit = m >> 1; bit != 0; bit >>= 1) { encoder.Encode(ref statistics[offset + s + 14], (sz & bit) != 0 ? 1 : 0); } } private static void EncodeAc(ArithmeticEncoder encoder, byte[] statistics, int offset, int kx, int ss, int se, int al, ReadOnlySpan block) { var zigzag = JpegTables.ZigZag; var last = ss - 1; for (var k = ss; k <= se; k++) { if (Shifted(block[zigzag[k]], al) != 0) { last = k; } } for (var k = ss; k <= se; k++) { var se3 = 3 * (k - 1); if (k > last) { encoder.Encode(ref statistics[offset + se3], 1); return; } encoder.Encode(ref statistics[offset + se3], 0); while (Shifted(block[zigzag[k]], al) == 0) { encoder.Encode(ref statistics[offset + se3 + 1], 0); se3 += 3; k++; } encoder.Encode(ref statistics[offset + se3 + 1], 1); var value = Shifted(block[zigzag[k]], al); encoder.EncodeFixed(value < 0 ? 1 : 0); var s = se3 + 2; var sz = Math.Abs(value) - 1; if (sz == 0) { encoder.Encode(ref statistics[offset + s], 0); continue; } encoder.Encode(ref statistics[offset + s], 1); var m = 1; if (sz < 2) { encoder.Encode(ref statistics[offset + s], 0); } else { encoder.Encode(ref statistics[offset + s], 1); m = 2; s = k <= kx ? 189 : 217; while (sz >= m << 1) { encoder.Encode(ref statistics[offset + s], 1); m <<= 1; s++; } encoder.Encode(ref statistics[offset + s], 0); } for (var bit = m >> 1; bit != 0; bit >>= 1) { encoder.Encode(ref statistics[offset + s + 14], (sz & bit) != 0 ? 1 : 0); } } } private static void EncodeAcRefine(ArithmeticEncoder encoder, byte[] statistics, int offset, int ss, int se, int al, ReadOnlySpan block) { var zigzag = JpegTables.ZigZag; var endOfBand = 0; for (var k = 1; k <= se; k++) { if (Math.Abs(block[zigzag[k]]) >> (al + 1) != 0) { endOfBand = k; } } var last = ss - 1; for (var k = ss; k <= se; k++) { if (Math.Abs(block[zigzag[k]]) >> al != 0) { last = k; } } for (var k = ss; k <= se; k++) { var se3 = 3 * (k - 1); if (k > endOfBand) { if (k > last) { encoder.Encode(ref statistics[offset + se3], 1); return; } encoder.Encode(ref statistics[offset + se3], 0); } while (true) { var coefficient = block[zigzag[k]]; var magnitude = Math.Abs(coefficient) >> al; if (magnitude > 1) { encoder.Encode(ref statistics[offset + se3 + 2], magnitude & 1); break; } if (magnitude == 1) { encoder.Encode(ref statistics[offset + se3 + 1], 1); encoder.EncodeFixed(coefficient < 0 ? 1 : 0); break; } encoder.Encode(ref statistics[offset + se3 + 1], 0); se3 += 3; k++; } } } private static void WriteArithmeticScan(JpegOutput output, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) { JpegSegments.WriteScan(output, scan.Components.Select((c, j) => (image.Components[c].Id, j, j)).ToList(), scan.Ss, scan.Se, scan.Ah, scan.Al); var encoder = new ArithmeticEncoder(output); var dc = new byte[4 * DcStatistics]; var ac = new byte[4 * AcStatistics]; var predictors = new int[scan.Components.Length]; var contexts = new int[scan.Components.Length]; var (low, high) = options.DcConditioning; var kx = options.AcConditioning; layout.Walk( scan.Components, options.RestartInterval, (j, c, x, y) => { var block = image.Components[c].Block(x, y); if (!options.Progressive || (scan.Ss == 0 && scan.Ah == 0)) { var value = options.Progressive ? block[0] >> scan.Al : block[0]; var difference = value - predictors[j]; predictors[j] = value; EncodeValue(encoder, dc, j * DcStatistics, contexts[j], 20, difference); contexts[j] = Classify(difference, low, high) * 4; if (!options.Progressive) { EncodeAc(encoder, ac, j * AcStatistics, kx, 1, 63, 0, block); } } else if (scan.Ss == 0) { encoder.EncodeFixed((block[0] >> scan.Al) & 1); } else if (scan.Ah == 0) { EncodeAc(encoder, ac, 0, kx, scan.Ss, scan.Se, scan.Al, block); } else { EncodeAcRefine(encoder, ac, 0, scan.Ss, scan.Se, scan.Al, block); } }, () => { encoder.Restart(); Array.Clear(dc); Array.Clear(ac); Array.Clear(predictors); Array.Clear(contexts); }); encoder.Flush(); } /// Predictions and differences of a lossless scan (H.1.2), the inverse of the decoder. private sealed class LosslessModel { private readonly Layout _layout; private readonly IReadOnlyList<(int Id, int H, int V, int[] Samples)> _planes; private readonly int[] _components; private readonly int _precision; private readonly int _predictor; private readonly int _pt; private readonly int[] _widths; private readonly int[] _heights; public LosslessModel(Layout layout, IReadOnlyList<(int Id, int H, int V, int[] Samples)> planes, int[] components, int precision, int predictor, int pt) { _layout = layout; _planes = planes; _components = components; _precision = precision; _predictor = predictor; _pt = pt; _widths = layout.Wide; _heights = layout.High; } /// The sample (x, y) of component c after the point transform, edges repeated beyond the plane. private int Sample(int c, int x, int y) => _planes[c].Samples[(Math.Min(y, _heights[c] - 1) * _widths[c]) + Math.Min(x, _widths[c] - 1)] >> _pt; private int Predict(int c, int x, int y, int firstRow) { if (y == firstRow) { return x == 0 ? 1 << (_precision - _pt - 1) : Sample(c, x - 1, y); } if (x == 0) { return Sample(c, x, y - 1); } var a = Sample(c, x - 1, y); var b = Sample(c, x, y - 1); var cc = Sample(c, x - 1, y - 1); return _predictor switch { 1 => a, 2 => b, 3 => cc, 4 => a + b - cc, 5 => a + ((b - cc) >> 1), 6 => b + ((a - cc) >> 1), _ => (a + b) >> 1, }; } /// The difference modulo 2^16, as a value in -32767..32768. private static int Difference(int sample, int prediction) { var d = (sample - prediction) & 0xFFFF; return d > 32768 ? d - 65536 : d; } private IEnumerable<(int J, int C, int X, int Y, int FirstRow)> Units(int restartInterval, Action restart) { // The walk is recorded first, restart points as J = -1; the first line of an interval is the first sample // row of its first MCU row. var list = new List<(int J, int C, int X, int Y)>(); _layout.Walk(_components, restartInterval, (j, c, x, y) => list.Add((j, c, x, y)), () => list.Add((-1, 0, 0, 0))); var single = _components.Length == 1; var perRow = single ? _layout.Wide[_components[0]] : _layout.McusWide; var unitsPerMcu = single ? 1 : _components.Sum(c => _layout.Sampling[c].H * _layout.Sampling[c].V); var units = 0; var firstMcuRow = 0; foreach (var (j, c, x, y) in list) { if (j < 0) { restart(); firstMcuRow = units / unitsPerMcu / perRow; continue; } units++; yield return (j, c, x, y, firstMcuRow * (single ? 1 : _layout.Sampling[c].V)); } } public void EncodeHuffman(ISink sink, int restartInterval) { foreach (var (j, c, x, y, firstRow) in Units(restartInterval, sink.Restart)) { var difference = Difference(Sample(c, x, y), Predict(c, x, y, firstRow)); var category = difference == 32768 ? 16 : Category(difference); sink.Symbol(j, category); if (category < 16) { sink.Bits(difference < 0 ? difference - 1 : difference, category); } } } public void EncodeArithmetic(ArithmeticEncoder encoder, JpegTestOptions options) { var statistics = new byte[4 * LosslessStatistics]; var classes = new Dictionary<(int C, int X, int Y), int>(); var (low, high) = options.DcConditioning; foreach (var (j, c, x, y, firstRow) in Units(options.RestartInterval, () => { encoder.Restart(); Array.Clear(statistics); })) { var classA = x == 0 ? 0 : classes[(c, x - 1, y)]; var classB = y == firstRow ? 0 : classes[(c, x, y - 1)]; var difference = Difference(Sample(c, x, y), Predict(c, x, y, firstRow)); EncodeValue(encoder, statistics, j * LosslessStatistics, (20 * classB) + (4 * classA), classB >= 3 ? 129 : 100, difference); classes[(c, x, y)] = Classify(difference, low, high); } } } }