using System.Numerics;
namespace Febe.Core.Codecs;
///
/// The sample planes of a decoded picture, whatever its codec: luma × , chroma
/// subsampled by 1 << ChromaShiftX and 1 << ChromaShiftY (4:2:0: 1 and 1; 4:2:2: 1 and 0; 4:4:4:
/// 0 and 0), no chroma at all for a monochrome picture. Samples are 8-bit bytes (H.264) or 16-bit values of any bit
/// depth up to 16 (HEVC).
///
internal readonly struct YuvPlanes(
T[] y, T[] cb, T[] cr, int width, int height, int chromaShiftX, int chromaShiftY, bool monochrome, int bitDepthY, int bitDepthC)
where T : unmanaged, IBinaryInteger
{
internal T[] Y { get; } = y;
internal T[] Cb { get; } = cb;
internal T[] Cr { get; } = cr;
internal int Width { get; } = width;
internal int Height { get; } = height;
internal int ChromaShiftX { get; } = chromaShiftX;
internal int ChromaShiftY { get; } = chromaShiftY;
internal bool Monochrome { get; } = monochrome;
internal int BitDepthY { get; } = bitDepthY;
internal int BitDepthC { get; } = bitDepthC;
/// Width of a chroma row (rounded up, as for odd H.264 widths).
internal int ChromaWidth => (Width + (1 << ChromaShiftX) - 1) >> ChromaShiftX;
}
///
/// Conversion of Y′CbCr samples to 8-bit RGB (ITU-T H.273 for the meaning of matrix_coeffs and video_full_range_flag):
/// BT.709 (1), FCC (4), BT.601 (5, 6), SMPTE 240M (7) or BT.2020 non-constant luminance (9) coefficients, the identity
/// matrix (0: G, B and R coded as Y, Cb and Cr), YCgCo (8: Y, Cg and Co in place of Y, Cb and Cr, the inverse of the
/// equations of H.273 for MatrixCoefficients 8), limited or full range, any bit depth; chroma taken at the nearest
/// sample. Integer arithmetic with 16 fractional bits, so every caller gets the same pixels.
///
/// Approximated: BT.2020 constant luminance (10) is converted with the non-constant luminance coefficients of 9, without
/// its transfer to linear light; the chromaticity-derived matrices (12, 13), which need the colour primaries,
/// SMPTE ST 2085 (11) and ICtCp (14), as every unspecified or unknown value, take BT.709 from 720 lines up and BT.601
/// below. None of them comes from the phones and services Febe meets.
///
///
internal static class YuvToRgb
{
private const int Shift = 16;
private const double One = 1 << Shift;
private const int Half = 1 << (Shift - 1);
/// The integer coefficients for one matrix, range and bit depth.
internal readonly struct Coefficients
{
internal bool Identity { get; init; }
/// YCgCo (matrix 8): G = Y + Cg, R = Y − Cg + Co, B = Y − Cg − Co, Cg and Co scaled by .
internal bool YCgCo { get; init; }
internal int ChromaScale { get; init; }
internal int LumaScale { get; init; }
internal int LumaOffset { get; init; }
internal int ChromaMiddle { get; init; }
internal int CrToR { get; init; }
internal int CbToB { get; init; }
internal int CbToG { get; init; }
internal int CrToG { get; init; }
/// Right shift that brings an identity-matrix sample to 8 bits, luma and chroma.
internal int IdentityShiftY { get; init; }
internal int IdentityShiftC { get; init; }
}
///
/// The coefficients for (matrix_coeffs; unspecified, unknown or approximated as the class
/// says: BT.709 from 720 lines up, BT.601 below), and the bit depths of the samples.
///
internal static Coefficients For(int matrix, bool fullRange, int bitDepthY, int bitDepthC, int height)
{
if (matrix == 0)
{
return new Coefficients { Identity = true, IdentityShiftY = Math.Max(0, bitDepthY - 8), IdentityShiftC = Math.Max(0, bitDepthC - 8) };
}
if (matrix == 8)
{
// Cg and Co are quantised as Cb and Cr are, with the same ranges (H.273, MatrixCoefficients 8).
return new Coefficients
{
YCgCo = true,
LumaScale = (int)Math.Round((fullRange ? 1.0 : 255.0 / 219.0) / (1 << Math.Max(0, bitDepthY - 8)) * One),
LumaOffset = fullRange ? 0 : 16 << Math.Max(0, bitDepthY - 8),
ChromaMiddle = 1 << (bitDepthC - 1),
ChromaScale = (int)Math.Round((fullRange ? 1.0 : 255.0 / 224.0) / (1 << Math.Max(0, bitDepthC - 8)) * One),
};
}
var (kr, kb) = matrix switch
{
1 => (0.2126, 0.0722),
4 => (0.30, 0.11),
5 or 6 => (0.299, 0.114),
7 => (0.212, 0.087),
9 or 10 => (0.2627, 0.0593),
_ => height >= 720 ? (0.2126, 0.0722) : (0.299, 0.114),
};
var kg = 1 - kr - kb;
var yScale = (fullRange ? 1.0 : 255.0 / 219.0) / (1 << Math.Max(0, bitDepthY - 8));
var cScale = (fullRange ? 1.0 : 255.0 / 224.0) / (1 << Math.Max(0, bitDepthC - 8));
return new Coefficients
{
LumaScale = (int)Math.Round(yScale * One),
LumaOffset = fullRange ? 0 : 16 << Math.Max(0, bitDepthY - 8),
ChromaMiddle = 1 << (bitDepthC - 1),
CrToR = (int)Math.Round(2 * (1 - kr) * cScale * One),
CbToB = (int)Math.Round(2 * (1 - kb) * cScale * One),
CbToG = (int)Math.Round(2 * kb * (1 - kb) / kg * cScale * One),
CrToG = (int)Math.Round(2 * kr * (1 - kr) / kg * cScale * One),
};
}
///
/// Converts the picture reduced by (each output pixel the mean of factor × factor converted
/// pixels) into : × pixels of
/// bytes (3: R, G, B; 4: R, G, B and an alpha of 255), rows
/// bytes apart. The output must fit in the picture: width × factor ≤ its width, height × factor ≤ its height.
///
internal static void Convert(in YuvPlanes p, in Coefficients k, int factor, Span target, int stride, int pixelSize, int width, int height)
where T : unmanaged, IBinaryInteger
{
var area = factor * factor;
var cw = p.ChromaWidth;
var sx = p.ChromaShiftX;
var sy = p.ChromaShiftY;
ReadOnlySpan yPlane = p.Y, cbPlane = p.Cb, crPlane = p.Cr;
var mono = p.Monochrome;
for (var oy = 0; oy < height; oy++)
{
var row = target.Slice(oy * stride, width * pixelSize);
for (var ox = 0; ox < width; ox++)
{
int r = 0, g = 0, b = 0;
for (var dy = 0; dy < factor; dy++)
{
var y = (oy * factor) + dy;
var lumaRow = y * p.Width;
var chromaRow = (y >> sy) * cw;
for (var dx = 0; dx < factor; dx++)
{
var x = (ox * factor) + dx;
var luma = int.CreateTruncating(yPlane[lumaRow + x]);
int u, v;
if (mono)
{
u = v = k.ChromaMiddle;
}
else
{
var c = chromaRow + (x >> sx);
u = int.CreateTruncating(cbPlane[c]);
v = int.CreateTruncating(crPlane[c]);
}
if (k.Identity)
{
g += Clip(luma >> k.IdentityShiftY);
b += Clip(mono ? luma >> k.IdentityShiftY : u >> k.IdentityShiftC);
r += Clip(mono ? luma >> k.IdentityShiftY : v >> k.IdentityShiftC);
continue;
}
var l = (luma - k.LumaOffset) * k.LumaScale;
u -= k.ChromaMiddle;
v -= k.ChromaMiddle;
if (k.YCgCo)
{
var cg = u * k.ChromaScale;
var co = v * k.ChromaScale;
var t = l - cg;
r += Clip((t + co + Half) >> Shift);
g += Clip((l + cg + Half) >> Shift);
b += Clip((t - co + Half) >> Shift);
continue;
}
r += Clip((l + (k.CrToR * v) + Half) >> Shift);
g += Clip((l - (k.CbToG * u) - (k.CrToG * v) + Half) >> Shift);
b += Clip((l + (k.CbToB * u) + Half) >> Shift);
}
}
var o = ox * pixelSize;
if (area == 1)
{
row[o] = (byte)r;
row[o + 1] = (byte)g;
row[o + 2] = (byte)b;
}
else
{
row[o] = (byte)(r / area);
row[o + 1] = (byte)(g / area);
row[o + 2] = (byte)(b / area);
}
if (pixelSize == 4)
{
row[o + 3] = 255;
}
}
}
}
private static int Clip(int v) => v < 0 ? 0 : v > 255 ? 255 : v;
}