Files
Febe/src/Febe.Core/Codecs/H264/H264PcmWriter.cs
T
Alby96andClaude Opus 5.5 5eec9cc22a E4: video fermi nella dimostrazione
La dimostrazione ha ora due video fermi veri: il video più recente di
@marta.demo e la storia video più recente di un altro account sono la
loro copertina ferma per 2 secondi dopo una breve dissolvenza dal nero
(H264PcmWriter.DemoStillVideo e FromRgba, scritti in casa). Ognuno ha il
suo file, registrato con la sua impronta vera, e un'analisi «Fermo» data
dall'analizzatore vero: così il filtro «Video fermi», «Salva il
fotogramma» con «Scarica» e «Nella cartella delle copie» (dal motore
vero) funzionano. Il video dopo di @marta.demo è «In movimento», quello
dopo ancora «Non analizzabile» (troppo lento); gli altri non sono mai
analizzati, così «È un video fermo?» e «Cerca i video fermi» lavorano
davvero. Nella sola dimostrazione il servizio non controlla l'impronta
prima di analizzare (VerifySource), perché gli altri video condividono
un file che si muove. Prove in DemoStillVideoTests; riga in LEGGIMI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:15:41 +01:00

401 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.Images;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// One picture of an I_PCM stream in 4:2:0: <see cref="Y"/> is <c>Width × Height</c> luma samples, <see cref="Cb"/> and
/// <see cref="Cr"/> are <c>Width/2 × Height/2</c>, row by row. Width and height are multiples of 16.
/// </summary>
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; }
}
/// <summary>
/// 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 <see cref="Mp4Writer"/>. Every pixel is known
/// and every picture is an exact start for a decoder: the demo's video (frames in <c>--demo</c>) 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.
/// </summary>
public static class H264PcmWriter
{
/// <summary>Width of the demo video (15 macroblocks, no cropping).</summary>
public const int DemoWidth = 240;
/// <summary>Height of the demo video (27 macroblocks, no cropping).</summary>
public const int DemoHeight = 432;
/// <summary>Pictures per second of the demo video.</summary>
public const int DemoFps = 8;
/// <summary>Pictures of the demo video (two seconds).</summary>
public const int DemoPictures = 16;
/// <summary>The sequence parameter set (RBSP with emulation prevention, no start code), POC type 2, no VUI.</summary>
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);
}
/// <summary>The picture parameter set (CAVLC, one slice group, deblocking control present).</summary>
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);
}
/// <summary>An IDR picture of I_PCM macroblocks (one slice, deblocking off), as a NAL unit without start code.</summary>
/// <param name="picture">The samples.</param>
/// <param name="idrPicId">idr_pic_id: two IDR pictures in a row must differ (0 and 1 alternate).</param>
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);
}
/// <summary>The <c>avcC</c> of a stream with these parameter sets (ISO/IEC 14496-15 §5.3.3.1), lengths on 4 bytes.</summary>
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,
];
}
/// <summary>
/// Writes an MP4 of <paramref name="count"/> pictures at <paramref name="fps"/> per second, picture <c>i</c> given by
/// <paramref name="picture"/>, every one an IDR sync sample.
/// </summary>
/// <param name="output">Where the file goes (from its current position).</param>
/// <param name="width">Width, a multiple of 16.</param>
/// <param name="height">Height, a multiple of 16.</param>
/// <param name="count">Pictures.</param>
/// <param name="fps">Pictures per second.</param>
/// <param name="picture">The samples of picture <c>i</c> (called once per picture, in order).</param>
/// <param name="created">The creation date of the movie; null writes none.</param>
public static void WriteMp4(Stream output, int width, int height, int count, int fps, Func<int, H264PcmPicture> 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<byte[]>(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);
}
/// <summary>
/// The demo's video: <see cref="DemoWidth"/>×<see cref="DemoHeight"/>, <see cref="DemoFps"/> pictures per second for
/// two seconds, a diagonal gradient that moves to the right with colours that change over time.
/// </summary>
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();
}
/// <summary>
/// The demo's still video (tappa E4): <paramref name="picture"/> alone for two seconds, <see cref="DemoFps"/> 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.
/// </summary>
/// <param name="picture">The picture, <see cref="DemoWidth"/>×<see cref="DemoHeight"/> (see <see cref="FromRgba"/>).</param>
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();
}
/// <summary>
/// A picture of the samples of <paramref name="image"/> (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.
/// </summary>
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;
}
/// <summary>The picture with its light scaled by <paramref name="factor"/> toward black (luma 16, chroma 128).</summary>
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);
/// <summary>Picture <paramref name="index"/> of the demo video (luma 16-235, chroma 16-240: no zero byte).</summary>
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;
}
/// <summary>A NAL unit (header byte, then the RBSP with its trailing bits and emulation prevention).</summary>
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<byte>(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];
}
/// <summary>A big-endian bit writer for the RBSP.</summary>
private sealed class Bits(int capacity = 64)
{
private readonly List<byte> _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);
}
}
/// <summary>Whole bytes, after <see cref="Align"/>.</summary>
public void Bytes(ReadOnlySpan<byte> 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.");
}
}