using System.Buffers.Binary;
using System.Numerics;
using Febe.Core.Codecs;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
namespace Febe.Core.Library;
/// A decoded video frame in 8-bit RGB, rows top to bottom, three bytes per pixel (red, green, blue).
public sealed record VideoImage(int Width, int Height, byte[] Rgb)
{
/// The image as an uncompressed 24-bit BMP file (Windows bitmap, rows bottom to top).
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;
}
}
///
/// Whether a video only shows a still picture (a photo with music, for example): then one frame stands for the whole
/// video. 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.
///
public sealed record VideoStillness(bool IsStill, int SampledFrames, double Difference);
///
/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover):
/// the container readers of and the H.264 and HEVC decoders written in house
/// (, ). Videos in other codecs (VP9, AV1, ...) give no frame: the
/// interface shows the neutral tile.
///
public sealed class VideoFrameDecoder
{
/// Differences up to this value (0–255) count as compression noise of a still picture.
public const double StillThreshold = 3.0;
///
/// The longest a frame or a stillness analysis may take: what the external extractor used before C3 was given. A damaged
/// file never holds an import or a rebuild for longer.
///
public static readonly TimeSpan DefaultBudget = TimeSpan.FromSeconds(30);
private const int GridSize = 32;
private const int SampledPositions = 6;
private const int MaxSequentialSamples = 2000;
private const int DefaultMaxRun = 300;
/// How far back from a sample flagged as key the decoder looks for one it can really start from.
private const int MaxRunStartSearch = 2000;
private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
private readonly TimeSpan budget;
private readonly int maxRun;
/// A decoder with the default budget and run length.
public VideoFrameDecoder()
: this(DefaultBudget, DefaultMaxRun)
{
}
/// The longest one call may take (zero: no time at all).
///
/// Samples decoded at most from a random access point to the frame asked for; a frame further away (a damaged time
/// table, a track with a single key frame) gives way to the frame of the random access point itself.
///
internal VideoFrameDecoder(TimeSpan budget, int maxRun)
{
this.budget = budget;
this.maxRun = maxRun;
}
/// The shared instance: it keeps no state between calls.
public static VideoFrameDecoder Instance { get; } = new();
///
/// 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, reduced to at most twice the long side of a thumbnail (a 4K frame would be a 24 MB bitmap);
/// null when the file cannot be read or decoded.
///
public Task ExtractImageAsync(string videoPath, CancellationToken ct = default) =>
ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 2 * ThumbnailStore.LongSide, ct);
///
/// A frame of the video at (the first frame when the video is shorter), as a BMP image whose
/// long side is at most pixels (0: full size); null when it cannot be decoded.
///
public async Task ExtractImageAsync(string videoPath, TimeSpan at, int maxLongSide, CancellationToken ct = default)
{
var image = await DecodeFrameAsync(videoPath, at, maxLongSide, ct).ConfigureAwait(false);
return image?.ToBmp();
}
/// A frame of the video at in RGB; null when it cannot be decoded.
public Task DecodeFrameAsync(string videoPath, TimeSpan at, int maxLongSide = 0, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
return Task.Run(() => WithinBudget(token => DecodeFrame(videoPath, at, maxLongSide, token), ct), ct);
}
///
/// 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).
///
public Task AnalyseStillnessAsync(string videoPath, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
return Task.Run(() => WithinBudget(token => AnalyseStillness(videoPath, token), ct), ct);
}
/// Runs for at most the budget: past it the result is null, as for an unreadable file.
private T? WithinBudget(Func work, CancellationToken ct)
where T : class
{
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
if (budget <= TimeSpan.Zero)
{
limit.Cancel();
}
else
{
limit.CancelAfter(budget);
}
try
{
return work(limit.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return null;
}
}
private VideoImage? DecodeFrame(string path, TimeSpan at, int maxLongSide, CancellationToken ct)
{
try
{
ct.ThrowIfCancellationRequested();
using var stream = ContainerReader.OpenRead(path);
if (Open(stream) is not { } video)
{
return null;
}
var decoding = new Decoding(stream, video, maxRun);
var target = SampleAt(video, at);
// Too far from where decoding can start: the frame there stands for it, so the work stays bounded.
var start = decoding.RunStart(target);
if (target - start > maxRun)
{
target = start;
}
// The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture
// of the HEVC CRA picture decoding starts from, a damaged sample).
var frames = decoding.Decode(start < target ? [start, target] : [target], ct);
if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0)
{
frames = new Decoding(stream, video, maxRun).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 VideoStillness? AnalyseStillness(string path, CancellationToken ct)
{
try
{
ct.ThrowIfCancellationRequested();
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 decoding = new Decoding(stream, video, maxRun);
var targets = new SortedSet();
for (var i = 0; i < SampledPositions; i++)
{
ct.ThrowIfCancellationRequested();
var time = first + ((last - first) * i / (SampledPositions - 1));
var index = Closest(samples, time);
// Far from where decoding can start in a long video: the frame there stands for it, so the work stays
// bounded.
var start = decoding.RunStart(index);
if (index - start > maxRun && samples.Count > MaxSequentialSamples)
{
index = start;
}
targets.Add(index);
}
if (targets.Count < 2)
{
return null;
}
var frames = decoding.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 H265Exception or IOException
or EndOfStreamException or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException
or InvalidOperationException or OverflowException or InvalidDataException;
/// The H.264 or HEVC video track of a container with its samples; null for other codecs or without video.
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 { Samples.Count: > 0 } video && video.Codec switch
{
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
VideoCodec.Hevc => video.AnnexB || video.HevcConfiguration is not null,
_ => false,
}
? video
: null;
}
/// The sample shown at from the start; the first shown one when the video is shorter.
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 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();
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];
}
/// Where decoding can start, whatever the codec.
private enum StartPoint
{
/// Decoding cannot start here.
None,
/// Close: an H.264 picture of I slices that is not IDR, an HEVC CRA picture (its RASL pictures are lost).
Intra,
/// Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.
Idr,
}
/// Size of the NAL length fields of the samples (0: Annex B), from the configuration record.
private static int LengthSize(VideoTrack video)
{
if (video.AnnexB)
{
return 0;
}
return video.Codec == VideoCodec.Hevc
? video.HevcConfiguration is { Length: > 21 } hvcC ? (hvcC[21] & 3) + 1 : 4
: video.AvcConfiguration is { Length: > 4 } avcC ? (avcC[4] & 3) + 1 : 4;
}
/// A decoded frame of either codec.
private sealed class Frame(H264Frame? avc, H265Frame? hevc)
{
internal H264Frame? Avc { get; } = avc;
internal H265Frame? Hevc { get; } = hevc;
}
/// The decoder of the track's codec, configured from its configuration record.
private sealed class Runner
{
private readonly H264Decoder? avc;
private readonly H265Decoder? hevc;
private readonly int lengthSize;
internal Runner(VideoTrack video, Func wanted, Action found)
{
if (video.Codec == VideoCodec.Hevc)
{
hevc = new H265Decoder { Wanted = _ => wanted() };
hevc.FrameDecoded += frame => found(new Frame(null, frame));
lengthSize = video.AnnexB ? 0 : hevc.ConfigureHvcC(video.HevcConfiguration);
}
else
{
// Of an MVC stream only the base view: it is the 2D video, and the other views would add frames.
avc = new H264Decoder { Wanted = _ => wanted(), DecodeAllViews = false };
avc.FrameDecoded += frame => found(new Frame(frame, null));
lengthSize = video.AnnexB ? 0 : avc.ConfigureAvcC(video.AvcConfiguration);
}
}
internal void Decode(ReadOnlySpan sample)
{
if (hevc is not null)
{
if (lengthSize == 0)
{
hevc.DecodeAccessUnitAnnexB(sample);
}
else
{
hevc.DecodeSample(sample, lengthSize);
}
}
else if (lengthSize == 0)
{
avc!.DecodeAccessUnitAnnexB(sample);
}
else
{
avc!.DecodeSample(sample, lengthSize);
}
}
}
///
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
///
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun)
{
private readonly Dictionary found = [];
private readonly HashSet wanted = [];
private readonly int[] keys = KeyIndices(video);
private readonly Dictionary accessPoints = [];
private readonly int lengthSize = LengthSize(video);
private byte[] buffer = new byte[64 * 1024];
/// The sample being decoded: the picture it finishes is that sample's frame.
private int current;
///
/// The sample where decoding for starts. A container without an index (an AVI cut short,
/// or OpenDML past its first gigabyte) flags every sample as key, and starting from a P or B frame there would give
/// a corrupt picture, or none: so the samples flagged as key are looked at, from the nearest one back. The nearest
/// exact start (an IDR picture, or an HEVC BLA picture) is taken when it is within the run limit (the frame comes
/// out exact); otherwise the nearest close one (an H.264 picture of I slices, an HEVC CRA picture: close, though
/// pictures after it may refer to earlier ones); otherwise the exact start further back, or the first sample.
///
internal int RunStart(int index)
{
var position = Array.BinarySearch(keys, index);
position = position >= 0 ? position : Math.Max(0, ~position - 1);
var intra = -1;
for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++)
{
var candidate = keys[position];
if (!accessPoints.TryGetValue(candidate, out var point))
{
point = AccessPointOf(candidate);
accessPoints[candidate] = point;
}
if (point == StartPoint.Idr)
{
return index - candidate <= maxRun || intra < 0 ? candidate : intra;
}
if (point == StartPoint.Intra && intra < 0)
{
intra = candidate;
}
if (index - candidate > maxRun && intra >= 0)
{
return intra; // no exact start within reach: the nearest close one
}
}
// The first sample, where every stream starts (or the end of the search): it counts as an exact start.
return index <= maxRun || intra < 0 ? 0 : intra;
}
private StartPoint AccessPointOf(int index)
{
try
{
var sample = ContainerReader.ReadSample(stream, video.Samples[index], ref buffer);
if (video.Codec == VideoCodec.Hevc)
{
return H265Decoder.AccessPoint(sample, lengthSize) switch
{
H265AccessPoint.Idr => StartPoint.Idr,
H265AccessPoint.Cra => StartPoint.Intra,
_ => StartPoint.None,
};
}
return H264Decoder.AccessPoint(sample, lengthSize) switch
{
H264AccessPoint.Idr => StartPoint.Idr,
H264AccessPoint.IntraPicture => StartPoint.Intra,
_ => StartPoint.None,
};
}
catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException)
{
return StartPoint.None;
}
}
internal Dictionary Decode(int[] targets, CancellationToken ct)
{
foreach (var t in targets)
{
wanted.Add(t);
}
Runner? runner = null;
var next = 0;
foreach (var target in targets)
{
var key = RunStart(target);
if (runner is null || next > target || key >= next)
{
runner = null;
next = key;
}
try
{
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a
// sample without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift
// the frames after it.
runner ??= new Runner(video, () => wanted.Contains(current), frame => found.TryAdd(current, frame));
for (; next <= target; next++)
{
ct.ThrowIfCancellationRequested();
current = next;
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[next], ref buffer));
}
}
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
{
// This run is damaged (or its samples lie past the end of a truncated file): the next target starts
// again from its own key frame, and what was decoded so far stands.
runner = null;
}
}
return found;
}
}
/// A coarse grid of mean luma and chroma values, to compare frames without their compression noise.
private static double[] Grid(Frame frame) =>
frame.Hevc is { } h ? Grid(Planes(h)) : frame.Avc!.BytesPerSample == 2 ? Grid(WidePlanes(frame.Avc)) : Grid(Planes(frame.Avc));
///
/// The grid on an 8-bit scale: luma means in the first half, mean distances of the chroma from its middle in the
/// second (zero for a monochrome picture).
///
private static double[] Grid(in YuvPlanes frame)
where T : unmanaged, IBinaryInteger
{
var grid = new double[GridSize * GridSize * 2];
var counts = new int[GridSize * GridSize];
var lumaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthY - 8));
ReadOnlySpan luma = frame.Y;
for (var y = 0; y < frame.Height; y++)
{
var gy = y * GridSize / frame.Height;
var row = luma.Slice(y * frame.Width, frame.Width);
for (var x = 0; x < row.Length; x++)
{
var cell = (gy * GridSize) + (x * GridSize / frame.Width);
grid[cell] += int.CreateTruncating(row[x]) * lumaScale;
counts[cell]++;
}
}
var chromaCounts = new int[GridSize * GridSize];
if (!frame.Monochrome)
{
var cw = frame.ChromaWidth;
var ch = (frame.Height + (1 << frame.ChromaShiftY) - 1) >> frame.ChromaShiftY;
var middle = 1 << (frame.BitDepthC - 1);
var chromaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthC - 8)) / 2;
ReadOnlySpan cb = frame.Cb, cr = frame.Cr;
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(int.CreateTruncating(cb[i]) - middle) + Math.Abs(int.CreateTruncating(cr[i]) - middle)) * chromaScale;
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;
}
///
/// The planes of an H.264 frame of 8-bit samples, at any chroma sampling. A monochrome frame comes with grey 4:2:0
/// chroma planes (), which the conversion does not read.
///
private static YuvPlanes Planes(H264Frame frame)
{
var (sx, sy) = ChromaShifts(frame.ChromaFormat);
return new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0, frame.BitDepthLuma, frame.BitDepthChroma);
}
///
/// The planes of an H.264 frame above 8 bits (two bytes a sample, little-endian), as 16-bit values: copied once,
/// for the few frames a thumbnail or a stillness check decodes.
///
private static YuvPlanes WidePlanes(H264Frame frame)
{
static ushort[] Wide(byte[] plane)
{
var values = new ushort[plane.Length / 2];
for (var i = 0; i < values.Length; i++)
{
values[i] = BinaryPrimitives.ReadUInt16LittleEndian(plane.AsSpan(2 * i));
}
return values;
}
var (sx, sy) = ChromaShifts(frame.ChromaFormat);
return new(Wide(frame.Y), Wide(frame.Cb), Wide(frame.Cr), frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0,
frame.BitDepthLuma, frame.BitDepthChroma);
}
/// Chroma subsampling of chroma_format_idc (0, monochrome, as 4:2:0: the planes H.264 gives it are that size).
private static (int X, int Y) ChromaShifts(int chromaFormat) => chromaFormat switch
{
0 or 1 => (1, 1),
2 => (1, 0),
_ => (0, 0),
};
private static YuvPlanes Planes(H265Frame frame)
{
var (sx, sy) = frame.ChromaFormat switch
{
1 => (1, 1),
2 => (1, 0),
_ => (0, 0),
};
return new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0, frame.BitDepthLuma, frame.BitDepthChroma);
}
private static VideoImage ToImage(Frame frame, int rotation, int maxLongSide) =>
frame.Hevc is { } h ? ToImage(h, rotation, maxLongSide) : ToImage(frame.Avc!, rotation, maxLongSide);
///
/// 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 , then rotated clockwise.
///
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) =>
frame.BytesPerSample == 2
? ToImage(WidePlanes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide)
: ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide);
///
/// An HEVC frame in RGB, as : any chroma format (4:0:0 in grey) and bit
/// depth, brought to 8 bits.
///
internal static VideoImage ToImage(H265Frame frame, int rotation, int maxLongSide) =>
ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide);
private static VideoImage ToImage(in YuvPlanes planes, int matrix, bool fullRange, int rotation, int maxLongSide)
where T : unmanaged, IBinaryInteger
{
var factor = 1;
if (maxLongSide > 0)
{
var longSide = Math.Max(planes.Width, planes.Height);
factor = Math.Max(1, (longSide + maxLongSide - 1) / maxLongSide);
}
var width = Math.Max(1, planes.Width / factor);
var height = Math.Max(1, planes.Height / factor);
factor = Math.Min(factor, Math.Min(planes.Width, planes.Height)); // a frame thinner than the factor
var rgb = new byte[width * height * 3];
var k = YuvToRgb.For(matrix, fullRange, planes.BitDepthY, planes.BitDepthC, planes.Height);
YuvToRgb.Convert(planes, k, factor, rgb, width * 3, 3, width, height);
return Rotate(new VideoImage(width, height, rgb), rotation);
}
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);
}
}