namespace Febe.Core.Codecs.Containers;
/// Recognises the container of a video by its first bytes and reads it with the matching reader.
public static class ContainerReader
{
/// The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.
public const int MaxSampleSize = 64 * 1024 * 1024;
/// The format of a file from its first bytes; null when it is none of those read here.
public static ContainerFormat? Detect(ReadOnlySpan start)
{
if (MatroskaReader.Looks(start))
{
return ContainerFormat.Matroska;
}
if (AviReader.Looks(start))
{
return ContainerFormat.Avi;
}
return IsoBmffReader.Looks(start) ? ContainerFormat.IsoBmff : null;
}
///
/// Reads a seekable stream; null when its format is not recognised. Damaged files raise
/// (or when truncated); is
/// checked between the top-level boxes, elements and fragments.
///
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
Span start = stackalloc byte[16];
stream.Position = 0;
var read = stream.ReadAtLeast(start, start.Length, throwOnEndOfStream: false);
stream.Position = 0;
return Detect(start[..read]) switch
{
ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples, ct),
ContainerFormat.Avi => AviReader.Read(stream, now, samples, ct),
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples, ct),
_ => null,
};
}
/// Reads a file (read-only, shared); null when its format is not recognised.
public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
using var stream = OpenRead(path);
return Read(stream, now, samples, ct);
}
/// Opens a file for reading without blocking other readers or writers.
public static FileStream OpenRead(string path) =>
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, FileOptions.RandomAccess);
/// The bytes of a sample, read into (grown when needed).
public static ReadOnlySpan ReadSample(Stream stream, in MediaSample sample, ref byte[] buffer)
{
if (sample.Size < 0 || sample.Offset < 0 || sample.Offset + sample.Size > stream.Length)
{
throw new ContainerException("Campione fuori dal file.");
}
if (sample.Size > MaxSampleSize)
{
throw new ContainerException("Campione troppo grande."); // no real frame comes near: a damaged table
}
if (buffer.Length < sample.Size)
{
buffer = new byte[Math.Max(sample.Size, buffer.Length * 2)];
}
stream.Position = sample.Offset;
stream.ReadExactly(buffer, 0, sample.Size);
return buffer.AsSpan(0, sample.Size);
}
}