E3: API di formati e fotogrammi, conversione della libreria e demo
Porta le funzioni della tappa E3 fino all'interfaccia web, così che WP4 possa costruire le schermate su indirizzi veri. - Impostazioni, cartelle delle copie e «Copia in…» hanno i formati (nomi original, jpg, png, webplossless, mp4); il riepilogo dice cosa si converte, cosa resta com'è e se c'è perdita. «Copia di nuovo» rifà la copia nella sua forma esatta. - Fotogrammi: informazioni di un video, un fotogramma (anteprima o scaricamento), gli istanti di una modalità, «Scarica» di uno o di uno zip scritto mentre parte, con il permesso dei lavori lunghi oltre 20. Kestrel non vede mai scritture sincrone: il piccolo descrittore che lo zip di .NET 10 scrive in modo sincrono parte con la scrittura seguente. - Conversione della libreria: stato, la domanda «Converti anche i N già in libreria?», riprova, pausa e ripresa; il visualizzatore mostra i file convertiti, e le eliminazioni li contano. - Demo: un video H.264 scritto in casa (solo macroblocchi I_PCM) per ogni video, una copia in PNG, un fotogramma e due conversioni; la conversione non parte mai. Due prove cambiano con il comportamento: i video della demo ora si aprono, e un file non copiato può avere il segno «solo fotogramma». Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
724c5bda6f
commit
ab0d717424
25 files changed
+2559
-95
No files matched your search
@@ -0,0 +1,322 @@
|
||||
using Febe.Core.Codecs.Containers;
|
||||
|
||||
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>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.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user