WIP: contenitori, sonda dei metadati, fotogrammi e scrittore MP4 in casa; via ffmpeg e ffprobe (#58)

Lettori ISO BMFF (anche frammentato), Matroska/WebM e AVI; ContainerVideoMetadataProbe è la sonda predefinita; VideoFrameDecoder (H.264 in casa, BMP ruotato, riconoscimento dei video fermi) sostituisce VideoFrameExtractor; Mp4Writer con moov in testa. Tolti ffmpeg e ffprobe da Dockerfile, CI, script e prove. WIP perché la corsa completa di tests/Febe.Tests non era finita al momento del commit e l'ultima correzione (data qualsiasi nella lettura dei campioni) non è stata ricompilata né riprovata: la compilazione durante la corsa fallisce per DLL bloccate dalle prove in esecuzione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 12:32:33 +01:00
1 parent 697de97ec3
commit 6ffcb1bb18
39 files changed
+4235 -469

No files matched your search

+492
View File
@@ -0,0 +1,492 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264;
namespace Febe.Core.Library;
/// <summary>A decoded video frame in 8-bit RGB, rows top to bottom, three bytes per pixel (red, green, blue).</summary>
public sealed record VideoImage(int Width, int Height, byte[] Rgb)
{
/// <summary>The image as an uncompressed 24-bit BMP file (Windows bitmap, rows bottom to top).</summary>
public byte[] ToBmp()
{
var stride = ((Width * 3) + 3) & ~3;
var size = 54 + (stride * Height);
var bmp = new byte[size];
var span = bmp.AsSpan();
span[0] = (byte)'B';
span[1] = (byte)'M';
BinaryPrimitives.WriteInt32LittleEndian(span[2..], size);
BinaryPrimitives.WriteInt32LittleEndian(span[10..], 54);
BinaryPrimitives.WriteInt32LittleEndian(span[14..], 40);
BinaryPrimitives.WriteInt32LittleEndian(span[18..], Width);
BinaryPrimitives.WriteInt32LittleEndian(span[22..], Height);
BinaryPrimitives.WriteInt16LittleEndian(span[26..], 1);
BinaryPrimitives.WriteInt16LittleEndian(span[28..], 24);
BinaryPrimitives.WriteInt32LittleEndian(span[34..], stride * Height);
BinaryPrimitives.WriteInt32LittleEndian(span[38..], 2835); // 72 dpi
BinaryPrimitives.WriteInt32LittleEndian(span[42..], 2835);
for (var y = 0; y < Height; y++)
{
var source = Rgb.AsSpan(y * Width * 3, Width * 3);
var target = span.Slice(54 + ((Height - 1 - y) * stride), Width * 3);
for (var x = 0; x < source.Length; x += 3)
{
target[x] = source[x + 2];
target[x + 1] = source[x + 1];
target[x + 2] = source[x];
}
}
return bmp;
}
}
/// <summary>
/// Whether a video only shows a still picture (a photo with music, for example): then one frame stands for the whole
/// video. <see cref="Difference"/> is the largest mean difference, on a 0–255 scale, between the first sampled frame and
/// the others, measured on a coarse grid so that the noise of the compression does not count.
/// </summary>
public sealed record VideoStillness(bool IsStill, int SampledFrames, double Difference);
/// <summary>
/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover):
/// the container readers of <see cref="ContainerReader"/> and the H.264 decoder written in house
/// (<see cref="H264Decoder"/>). Videos in other codecs (HEVC, VP9, AV1, ...) give no frame: the interface shows the
/// neutral tile.
/// </summary>
public sealed class VideoFrameDecoder
{
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
public const double StillThreshold = 3.0;
private const int GridSize = 32;
private const int SampledPositions = 6;
private const int MaxSequentialSamples = 2000;
private const int MaxRunPerTarget = 300;
private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <summary>The shared instance: it keeps no state between calls.</summary>
public static VideoFrameDecoder Instance { get; } = new();
/// <summary>
/// A frame of the video as a BMP image, taken one second in (or the first frame of shorter videos), rotated as the
/// video is shown; null when the file cannot be read or decoded.
/// </summary>
public Task<byte[]?> ExtractImageAsync(string videoPath, CancellationToken ct = default) =>
ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 0, ct);
/// <summary>
/// A frame of the video at <paramref name="at"/> (the first frame when the video is shorter), as a BMP image whose
/// long side is at most <paramref name="maxLongSide"/> pixels (0: full size); null when it cannot be decoded.
/// </summary>
public async Task<byte[]?> ExtractImageAsync(string videoPath, TimeSpan at, int maxLongSide, CancellationToken ct = default)
{
var image = await DecodeFrameAsync(videoPath, at, maxLongSide, ct).ConfigureAwait(false);
return image?.ToBmp();
}
/// <summary>A frame of the video at <paramref name="at"/> in RGB; null when it cannot be decoded.</summary>
public Task<VideoImage?> DecodeFrameAsync(string videoPath, TimeSpan at, int maxLongSide = 0, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
return Task.Run(() => DecodeFrame(videoPath, at, maxLongSide, ct), ct);
}
/// <summary>
/// Whether the video shows a still picture, from frames spread over its whole length; null when it cannot be told
/// (unreadable file, codec not decoded, or one long run without key frames in a long video).
/// </summary>
public Task<VideoStillness?> AnalyseStillnessAsync(string videoPath, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
return Task.Run(() => AnalyseStillness(videoPath, ct), ct);
}
private static VideoImage? DecodeFrame(string path, TimeSpan at, int maxLongSide, CancellationToken ct)
{
try
{
using var stream = ContainerReader.OpenRead(path);
if (Open(stream) is not { } video)
{
return null;
}
var target = SampleAt(video, at);
var frames = new Decoding(stream, video).Decode([target], ct);
if (!frames.TryGetValue(target, out var frame) && target != 0)
{
frames = new Decoding(stream, video).Decode([0], ct);
frames.TryGetValue(0, out frame);
}
return frame is null ? null : ToImage(frame, video.Rotation, maxLongSide);
}
catch (Exception ex) when (IsUnreadable(ex))
{
return null;
}
}
private static VideoStillness? AnalyseStillness(string path, CancellationToken ct)
{
try
{
using var stream = ContainerReader.OpenRead(path);
if (Open(stream) is not { } video)
{
return null;
}
var samples = video.Samples;
if (samples.Count == 1)
{
return new VideoStillness(true, 1, 0);
}
// Positions spread over the presentation, from the first to the last frame.
long first = long.MaxValue, last = long.MinValue;
foreach (var s in samples)
{
first = Math.Min(first, s.PresentationTime);
last = Math.Max(last, s.PresentationTime);
}
var keys = KeyIndices(video);
var targets = new SortedSet<int>();
for (var i = 0; i < SampledPositions; i++)
{
var time = first + ((last - first) * i / (SampledPositions - 1));
var index = Closest(samples, time);
// Far from its key frame in a long video: the key frame stands for it, so the work stays bounded.
var key = KeyBefore(keys, index);
if (index - key > MaxRunPerTarget && samples.Count > MaxSequentialSamples)
{
index = key;
}
targets.Add(index);
}
if (targets.Count < 2)
{
return null;
}
var frames = new Decoding(stream, video).Decode([.. targets], ct);
if (frames.Count < 2)
{
return null;
}
double[]? reference = null;
var difference = 0.0;
foreach (var index in targets)
{
if (!frames.TryGetValue(index, out var frame))
{
continue;
}
var grid = Grid(frame);
if (reference is null)
{
reference = grid;
continue;
}
double sum = 0;
for (var i = 0; i < grid.Length; i++)
{
sum += Math.Abs(grid[i] - reference[i]);
}
difference = Math.Max(difference, sum / grid.Length);
}
return new VideoStillness(difference <= StillThreshold, frames.Count, Math.Round(difference, 2));
}
catch (Exception ex) when (IsUnreadable(ex))
{
return null;
}
}
private static bool IsUnreadable(Exception ex) => ex is ContainerException or H264Exception or IOException or EndOfStreamException
or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException or InvalidOperationException
or OverflowException or InvalidDataException;
/// <summary>The H.264 video track of a container with its samples; null for other codecs or without video.</summary>
private static VideoTrack? Open(Stream stream)
{
// The creation time does not matter here: any date is accepted (the readers add a day to «now»).
var container = ContainerReader.Read(stream, AnyDate, samples: true);
return container?.Video is { Codec: VideoCodec.H264, Samples.Count: > 0 } video
&& (video.AnnexB || video.AvcConfiguration is not null)
? video
: null;
}
/// <summary>The sample shown at <paramref name="at"/> from the start; the first shown one when the video is shorter.</summary>
private static int SampleAt(VideoTrack video, TimeSpan at)
{
var samples = video.Samples;
long first = long.MaxValue, last = long.MinValue;
foreach (var s in samples)
{
first = Math.Min(first, s.PresentationTime);
last = Math.Max(last, s.PresentationTime);
}
var wanted = first + (long)(at.TotalSeconds * video.Timescale);
return Closest(samples, wanted > last ? first : wanted);
}
private static int Closest(IReadOnlyList<MediaSample> samples, long time)
{
var best = 0;
var distance = long.MaxValue;
for (var i = 0; i < samples.Count; i++)
{
var d = Math.Abs(samples[i].PresentationTime - time);
if (d < distance)
{
(best, distance) = (i, d);
}
}
return best;
}
private static int[] KeyIndices(VideoTrack video)
{
var keys = new List<int>();
for (var i = 0; i < video.Samples.Count; i++)
{
if (video.Samples[i].Key)
{
keys.Add(i);
}
}
return keys.Count > 0 && keys[0] == 0 ? [.. keys] : [0, .. keys];
}
private static int KeyBefore(int[] keys, int index)
{
var found = Array.BinarySearch(keys, index);
return found >= 0 ? keys[found] : keys[Math.Max(0, ~found - 1)];
}
/// <summary>Decodes chosen samples, each from the key frame before it, reusing a run when the targets share it.</summary>
private sealed class Decoding(Stream stream, VideoTrack video)
{
private readonly Dictionary<int, H264Frame> found = [];
private readonly HashSet<int> wanted = [];
private byte[] buffer = new byte[64 * 1024];
internal Dictionary<int, H264Frame> Decode(int[] targets, CancellationToken ct)
{
foreach (var t in targets)
{
wanted.Add(t);
}
var keys = KeyIndices(video);
H264Decoder? decoder = null;
var next = 0;
var lengthSize = 4;
foreach (var target in targets)
{
var key = KeyBefore(keys, target);
if (decoder is null || next > target || key >= next)
{
decoder = new H264Decoder();
var runStart = key;
decoder.Wanted = index => wanted.Contains(runStart + (int)index);
decoder.FrameDecoded += frame => found.TryAdd(runStart + (int)frame.DecodeIndex, frame);
if (!video.AnnexB)
{
lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration);
}
next = key;
}
try
{
for (; next <= target; next++)
{
ct.ThrowIfCancellationRequested();
var sample = ContainerReader.ReadSample(stream, video.Samples[next], ref buffer);
if (video.AnnexB)
{
decoder.DecodeAccessUnitAnnexB(sample);
}
else
{
decoder.DecodeSample(sample, lengthSize);
}
}
}
catch (Exception ex) when (ex is H264Exception or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
{
decoder = null; // this run is damaged: the next target starts again from its own key frame
}
}
return found;
}
}
/// <summary>A coarse grid of mean luma and chroma values, to compare frames without their compression noise.</summary>
private static double[] Grid(H264Frame frame)
{
var grid = new double[GridSize * GridSize * 2];
var counts = new int[GridSize * GridSize];
for (var y = 0; y < frame.Height; y++)
{
var gy = y * GridSize / frame.Height;
var row = frame.Y.AsSpan(y * frame.Width, frame.Width);
for (var x = 0; x < row.Length; x++)
{
var cell = (gy * GridSize) + (x * GridSize / frame.Width);
grid[cell] += row[x];
counts[cell]++;
}
}
var cw = (frame.Width + 1) / 2;
var ch = (frame.Height + 1) / 2;
var chromaCounts = new int[GridSize * GridSize];
for (var y = 0; y < ch; y++)
{
var gy = y * GridSize / ch;
for (var x = 0; x < cw; x++)
{
var cell = (gy * GridSize) + (x * GridSize / cw);
var i = (y * cw) + x;
grid[(GridSize * GridSize) + cell] += (Math.Abs(frame.Cb[i] - 128) + Math.Abs(frame.Cr[i] - 128)) / 2.0;
chromaCounts[cell]++;
}
}
for (var i = 0; i < counts.Length; i++)
{
grid[i] = counts[i] > 0 ? grid[i] / counts[i] : 0;
var c = (GridSize * GridSize) + i;
grid[c] = chromaCounts[i] > 0 ? grid[c] / chromaCounts[i] : 0;
}
return grid;
}
/// <summary>
/// The frame in RGB: BT.709 or BT.601 coefficients as the stream says (unspecified: BT.709 from 720 lines up), limited
/// or full range, reduced by an integer factor to fit <paramref name="maxLongSide"/>, then rotated clockwise.
/// </summary>
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide)
{
var (kr, kb) = frame.MatrixCoefficients 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),
_ => frame.Height >= 720 ? (0.2126, 0.0722) : (0.299, 0.114),
};
var kg = 1 - kr - kb;
var yScale = frame.FullRange ? 1.0 : 255.0 / 219.0;
var cScale = frame.FullRange ? 1.0 : 255.0 / 224.0;
var yOffset = frame.FullRange ? 0 : 16;
const int Shift = 16;
const double One = 1 << Shift;
var cy = (int)Math.Round(yScale * One);
var crR = (int)Math.Round(2 * (1 - kr) * cScale * One);
var cbB = (int)Math.Round(2 * (1 - kb) * cScale * One);
var cbG = (int)Math.Round(2 * kb * (1 - kb) / kg * cScale * One);
var crG = (int)Math.Round(2 * kr * (1 - kr) / kg * cScale * One);
const int Half = 1 << (Shift - 1);
var factor = 1;
if (maxLongSide > 0)
{
var longSide = Math.Max(frame.Width, frame.Height);
factor = Math.Max(1, (longSide + maxLongSide - 1) / maxLongSide);
}
var width = Math.Max(1, frame.Width / factor);
var height = Math.Max(1, frame.Height / factor);
var rgb = new byte[width * height * 3];
var cw = (frame.Width + 1) / 2;
var area = factor * factor;
for (var oy = 0; oy < height; oy++)
{
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 * frame.Width;
var chromaRow = (y >> 1) * cw;
for (var dx = 0; dx < factor; dx++)
{
var x = (ox * factor) + dx;
var l = (frame.Y[lumaRow + x] - yOffset) * cy;
var u = frame.Cb[chromaRow + (x >> 1)] - 128;
var v = frame.Cr[chromaRow + (x >> 1)] - 128;
r += Clip((l + (crR * v) + Half) >> Shift);
g += Clip((l - (cbG * u) - (crG * v) + Half) >> Shift);
b += Clip((l + (cbB * u) + Half) >> Shift);
}
}
var o = ((oy * width) + ox) * 3;
rgb[o] = (byte)(r / area);
rgb[o + 1] = (byte)(g / area);
rgb[o + 2] = (byte)(b / area);
}
}
return Rotate(new VideoImage(width, height, rgb), rotation);
}
private static int Clip(int v) => v < 0 ? 0 : v > 255 ? 255 : v;
private static VideoImage Rotate(VideoImage image, int rotation)
{
rotation = ((rotation % 360) + 360) % 360;
if (rotation is not (90 or 180 or 270))
{
return image;
}
var (w, h) = (image.Width, image.Height);
var (nw, nh) = rotation == 180 ? (w, h) : (h, w);
var output = new byte[image.Rgb.Length];
for (var y = 0; y < h; y++)
{
for (var x = 0; x < w; x++)
{
var (tx, ty) = rotation switch
{
90 => (h - 1 - y, x),
180 => (w - 1 - x, h - 1 - y),
_ => (y, w - 1 - x),
};
var s = ((y * w) + x) * 3;
var t = ((ty * nw) + tx) * 3;
output[t] = image.Rgb[s];
output[t + 1] = image.Rgb[s + 1];
output[t + 2] = image.Rgb[s + 2];
}
}
return new VideoImage(nw, nh, output);
}
}