using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.Images;
namespace Febe.Core.Codecs.H264;
///
/// One picture of an I_PCM stream in 4:2:0: is Width × Height luma samples, and
/// are Width/2 × Height/2, row by row. Width and height are multiples of 16.
///
public sealed class H264PcmPicture
{
public H264PcmPicture(int width, int height)
{
if (width <= 0 || height <= 0 || width % 16 != 0 || height % 16 != 0)
{
throw new ArgumentOutOfRangeException(nameof(width), "Larghezza e altezza devono essere multipli di 16.");
}
Width = width;
Height = height;
Y = new byte[width * height];
Cb = new byte[width / 2 * (height / 2)];
Cr = new byte[width / 2 * (height / 2)];
}
public int Width { get; }
public int Height { get; }
public byte[] Y { get; }
public byte[] Cb { get; }
public byte[] Cr { get; }
}
///
/// Writes H.264 streams made only of IDR pictures of I_PCM macroblocks (ITU-T H.264 §7.3: Baseline parameter sets, one
/// slice per picture, every sample written as it is), muxed in MP4 with . Every pixel is known
/// and every picture is an exact start for a decoder: the demo's video (frames in --demo) and the tests use it.
/// Nothing is compressed, so the files are large (about 1,5 bytes per pixel per picture): for short, small videos only.
///
public static class H264PcmWriter
{
/// Width of the demo video (15 macroblocks, no cropping).
public const int DemoWidth = 240;
/// Height of the demo video (27 macroblocks, no cropping).
public const int DemoHeight = 432;
/// Pictures per second of the demo video.
public const int DemoFps = 8;
/// Pictures of the demo video (two seconds).
public const int DemoPictures = 16;
/// The sequence parameter set (RBSP with emulation prevention, no start code), POC type 2, no VUI.
public static byte[] Sps(int width, int height)
{
var bits = new Bits();
bits.Write(66, 8); // profile_idc: Baseline
bits.Write(0, 8); // constraint_set flags
bits.Write(30, 8); // level_idc 3.0
bits.Ue(0); // seq_parameter_set_id
bits.Ue(0); // log2_max_frame_num_minus4
bits.Ue(2); // pic_order_cnt_type: output order = decoding order
bits.Ue(1); // max_num_ref_frames
bits.Write(0, 1); // gaps_in_frame_num_value_allowed_flag
bits.Ue((uint)(width / 16) - 1); // pic_width_in_mbs_minus1
bits.Ue((uint)(height / 16) - 1); // pic_height_in_map_units_minus1
bits.Write(1, 1); // frame_mbs_only_flag
bits.Write(1, 1); // direct_8x8_inference_flag
bits.Write(0, 1); // frame_cropping_flag
bits.Write(0, 1); // vui_parameters_present_flag
return Nal(0x67, bits);
}
/// The picture parameter set (CAVLC, one slice group, deblocking control present).
public static byte[] Pps()
{
var bits = new Bits();
bits.Ue(0); // pic_parameter_set_id
bits.Ue(0); // seq_parameter_set_id
bits.Write(0, 1); // entropy_coding_mode_flag: CAVLC
bits.Write(0, 1); // bottom_field_pic_order_in_frame_present_flag
bits.Ue(0); // num_slice_groups_minus1
bits.Ue(0); // num_ref_idx_l0_default_active_minus1
bits.Ue(0); // num_ref_idx_l1_default_active_minus1
bits.Write(0, 1); // weighted_pred_flag
bits.Write(0, 2); // weighted_bipred_idc
bits.Se(0); // pic_init_qp_minus26
bits.Se(0); // pic_init_qs_minus26
bits.Se(0); // chroma_qp_index_offset
bits.Write(1, 1); // deblocking_filter_control_present_flag
bits.Write(0, 1); // constrained_intra_pred_flag
bits.Write(0, 1); // redundant_pic_cnt_present_flag
return Nal(0x68, bits);
}
/// An IDR picture of I_PCM macroblocks (one slice, deblocking off), as a NAL unit without start code.
/// The samples.
/// idr_pic_id: two IDR pictures in a row must differ (0 and 1 alternate).
public static byte[] Idr(H264PcmPicture picture, int idrPicId)
{
ArgumentNullException.ThrowIfNull(picture);
var bits = new Bits(picture.Y.Length * 3 / 2 + 1024);
bits.Ue(0); // first_mb_in_slice
bits.Ue(7); // slice_type: I (all slices of the picture)
bits.Ue(0); // pic_parameter_set_id
bits.Write(0, 4); // frame_num
bits.Ue((uint)idrPicId);
bits.Write(0, 1); // no_output_of_prior_pics_flag
bits.Write(0, 1); // long_term_reference_flag
bits.Se(0); // slice_qp_delta
bits.Ue(1); // disable_deblocking_filter_idc: off
var mbWidth = picture.Width / 16;
var mbHeight = picture.Height / 16;
var chromaWidth = picture.Width / 2;
for (var my = 0; my < mbHeight; my++)
{
for (var mx = 0; mx < mbWidth; mx++)
{
bits.Ue(25); // mb_type: I_PCM
bits.Align(); // pcm_alignment_zero_bit
for (var y = 0; y < 16; y++)
{
bits.Bytes(picture.Y.AsSpan(((my * 16) + y) * picture.Width + (mx * 16), 16));
}
foreach (var plane in new[] { picture.Cb, picture.Cr })
{
for (var y = 0; y < 8; y++)
{
bits.Bytes(plane.AsSpan(((my * 8) + y) * chromaWidth + (mx * 8), 8));
}
}
}
}
return Nal(0x65, bits);
}
/// The avcC of a stream with these parameter sets (ISO/IEC 14496-15 §5.3.3.1), lengths on 4 bytes.
public static byte[] AvcConfiguration(byte[] sps, byte[] pps)
{
ArgumentNullException.ThrowIfNull(sps);
ArgumentNullException.ThrowIfNull(pps);
return
[
1, sps[1], sps[2], sps[3], 0xFF, 0xE1,
(byte)(sps.Length >> 8), (byte)sps.Length, .. sps,
1, (byte)(pps.Length >> 8), (byte)pps.Length, .. pps,
];
}
///
/// Writes an MP4 of pictures at per second, picture i given by
/// , every one an IDR sync sample.
///
/// Where the file goes (from its current position).
/// Width, a multiple of 16.
/// Height, a multiple of 16.
/// Pictures.
/// Pictures per second.
/// The samples of picture i (called once per picture, in order).
/// The creation date of the movie; null writes none.
public static void WriteMp4(Stream output, int width, int height, int count, int fps, Func picture, DateTimeOffset? created = null)
{
ArgumentNullException.ThrowIfNull(output);
ArgumentNullException.ThrowIfNull(picture);
ArgumentOutOfRangeException.ThrowIfLessThan(count, 1);
ArgumentOutOfRangeException.ThrowIfLessThan(fps, 1);
var sps = Sps(width, height);
var pps = Pps();
var samples = new List(count);
for (var i = 0; i < count; i++)
{
var p = picture(i);
if (p.Width != width || p.Height != height)
{
throw new ArgumentException("Ogni fotogramma deve avere le dimensioni del video.", nameof(picture));
}
var nal = Idr(p, i % 2);
var sample = new byte[nal.Length + 4];
System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(sample, nal.Length);
nal.CopyTo(sample, 4);
samples.Add(sample);
}
const int Ticks = 1000;
var track = new Mp4OutputTrack
{
IsVideo = true,
Timescale = (long)fps * Ticks,
Samples = [.. samples.Select((s, i) => new Mp4OutputSample(s.Length, (long)i * Ticks, (long)i * Ticks, true))],
WriteSample = (i, s) => s.Write(samples[i]),
Width = width,
Height = height,
AvcConfiguration = AvcConfiguration(sps, pps),
LastSampleDuration = Ticks,
};
Mp4Writer.Write(output, [track], created);
}
///
/// The demo's video: ×, pictures per second for
/// two seconds, a diagonal gradient that moves to the right with colours that change over time.
///
public static byte[] DemoVideo()
{
using var output = new MemoryStream();
WriteMp4(output, DemoWidth, DemoHeight, DemoPictures, DemoFps, DemoPicture, new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero));
return output.ToArray();
}
///
/// The demo's still video (tappa E4): alone for two seconds, pictures per
/// second, after a short fade from black (the first picture nearly black, the second at half light), as a photo
/// shared as a video. «È un video fermo?» finds it «Fermo» and «Salva il fotogramma» takes a frame after the fade.
///
/// The picture, × (see ).
public static byte[] DemoStillVideo(H264PcmPicture picture)
{
ArgumentNullException.ThrowIfNull(picture);
if (picture.Width != DemoWidth || picture.Height != DemoHeight)
{
throw new ArgumentException("Il fotogramma deve avere le dimensioni del video dimostrativo.", nameof(picture));
}
var dark = Faded(picture, 0.05);
var half = Faded(picture, 0.5);
using var output = new MemoryStream();
WriteMp4(output, DemoWidth, DemoHeight, DemoPictures, DemoFps, i => i switch { 0 => dark, 1 => half, _ => picture }, new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero));
return output.ToArray();
}
///
/// A picture of the samples of (alpha ignored), with the coefficients the decoder uses for a
/// stream that says nothing about its colours under 720 lines: BT.601, limited range (luma 16-235, chroma 16-240).
/// The chroma of each 2×2 block is the mean of its four pixels. Width and height must be multiples of 16.
///
public static H264PcmPicture FromRgba(RgbaImage image)
{
ArgumentNullException.ThrowIfNull(image);
var p = new H264PcmPicture(image.Width, image.Height);
var pixels = image.Pixels;
var chromaWidth = image.Width / 2;
for (var y = 0; y < image.Height; y += 2)
{
for (var x = 0; x < image.Width; x += 2)
{
double cb = 0, cr = 0;
for (var dy = 0; dy < 2; dy++)
{
for (var dx = 0; dx < 2; dx++)
{
var at = (((y + dy) * image.Width) + x + dx) * RgbaImage.BytesPerPixel;
double r = pixels[at], g = pixels[at + 1], b = pixels[at + 2];
p.Y[((y + dy) * image.Width) + x + dx] = Clamp(16 + (((65.481 * r) + (128.553 * g) + (24.966 * b)) / 255), 16, 235);
cb += 128 + (((-37.797 * r) - (74.203 * g) + (112.0 * b)) / 255);
cr += 128 + (((112.0 * r) - (93.786 * g) - (18.214 * b)) / 255);
}
}
p.Cb[((y / 2) * chromaWidth) + (x / 2)] = Clamp(cb / 4, 16, 240);
p.Cr[((y / 2) * chromaWidth) + (x / 2)] = Clamp(cr / 4, 16, 240);
}
}
return p;
}
/// The picture with its light scaled by toward black (luma 16, chroma 128).
private static H264PcmPicture Faded(H264PcmPicture picture, double factor)
{
var p = new H264PcmPicture(picture.Width, picture.Height);
for (var i = 0; i < p.Y.Length; i++)
{
p.Y[i] = Clamp(16 + ((picture.Y[i] - 16) * factor), 16, 235);
}
for (var i = 0; i < p.Cb.Length; i++)
{
p.Cb[i] = Clamp(128 + ((picture.Cb[i] - 128) * factor), 16, 240);
p.Cr[i] = Clamp(128 + ((picture.Cr[i] - 128) * factor), 16, 240);
}
return p;
}
private static byte Clamp(double value, int low, int high) => (byte)Math.Clamp((int)Math.Round(value), low, high);
/// Picture of the demo video (luma 16-235, chroma 16-240: no zero byte).
public static H264PcmPicture DemoPicture(int index)
{
var p = new H264PcmPicture(DemoWidth, DemoHeight);
var shift = index * 219 / DemoPictures;
for (var y = 0; y < DemoHeight; y++)
{
for (var x = 0; x < DemoWidth; x++)
{
var ramp = ((x * 219 / DemoWidth) + (y * 219 / DemoHeight / 2) + 219 - shift) % 219;
p.Y[(y * DemoWidth) + x] = (byte)(16 + ramp);
}
}
var chromaWidth = DemoWidth / 2;
for (var y = 0; y < DemoHeight / 2; y++)
{
for (var x = 0; x < chromaWidth; x++)
{
p.Cb[(y * chromaWidth) + x] = (byte)(64 + (y * 128 / (DemoHeight / 2)));
p.Cr[(y * chromaWidth) + x] = (byte)(64 + ((x * 64 / chromaWidth) + (index * 64 / DemoPictures)));
}
}
return p;
}
/// A NAL unit (header byte, then the RBSP with its trailing bits and emulation prevention).
private static byte[] Nal(byte header, Bits bits)
{
bits.Write(1, 1); // rbsp_stop_one_bit
bits.Align();
var rbsp = bits.ToArray();
var output = new List(rbsp.Length + (rbsp.Length / 64) + 2) { header };
var zeros = 0;
foreach (var b in rbsp)
{
// Never two zero bytes followed by a byte up to 3 (§7.4.1).
if (zeros >= 2 && b <= 3)
{
output.Add(3);
zeros = 0;
}
output.Add(b);
zeros = b == 0 ? zeros + 1 : 0;
}
return [.. output];
}
/// A big-endian bit writer for the RBSP.
private sealed class Bits(int capacity = 64)
{
private readonly List _bytes = new(capacity);
private int _current;
private int _used;
public void Write(uint value, int count)
{
for (var i = count - 1; i >= 0; i--)
{
_current = (_current << 1) | (int)((value >> i) & 1);
if (++_used == 8)
{
_bytes.Add((byte)_current);
_current = 0;
_used = 0;
}
}
}
public void Ue(uint value)
{
var code = value + 1;
var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
Write(0, length - 1);
Write(code, length);
}
public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
public void Align()
{
while (_used != 0)
{
Write(0, 1);
}
}
/// Whole bytes, after .
public void Bytes(ReadOnlySpan data)
{
if (_used != 0)
{
throw new InvalidOperationException("Bytes only at a byte boundary.");
}
foreach (var b in data)
{
_bytes.Add(b);
}
}
public byte[] ToArray() => _used == 0 ? [.. _bytes] : throw new InvalidOperationException("Not aligned.");
}
}