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:
1 parent
697de97ec3
commit
6ffcb1bb18
39 files changed
+4235
-469
No files matched your search
@@ -0,0 +1,385 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Reader of RIFF AVI files (the Microsoft AVI RIFF format, with the OpenDML extension of RIFF <c>AVIX</c> parts),
|
||||
/// written from the format description: the main header, the first video and audio streams and the chunks of the
|
||||
/// <c>movi</c> lists in file order. Key frames come from the <c>idx1</c> index when there is one.
|
||||
/// </summary>
|
||||
public static class AviReader
|
||||
{
|
||||
private const int MaxSamples = 20_000_000;
|
||||
private const int MaxHeaderBytes = 16 * 1024 * 1024;
|
||||
|
||||
/// <summary>True when the stream starts like an AVI file.</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) =>
|
||||
start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8);
|
||||
|
||||
/// <summary>Reads a seekable stream from its start.</summary>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var state = new State();
|
||||
long position = 0;
|
||||
var length = stream.Length;
|
||||
Span<byte> header = stackalloc byte[12];
|
||||
var first = true;
|
||||
while (position + 12 <= length)
|
||||
{
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(header);
|
||||
if (!header[..4].SequenceEqual("RIFF"u8))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]);
|
||||
var form = header.Slice(8, 4);
|
||||
if (first && !form.SequenceEqual("AVI "u8))
|
||||
{
|
||||
throw new ContainerException("Non è un file AVI.");
|
||||
}
|
||||
|
||||
var end = Math.Min(length, position + 8 + size);
|
||||
ParseList(stream, position + 12, end, state, samples, now, depth: 0);
|
||||
if (!samples)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
first = false;
|
||||
position = position + 8 + size + (size & 1);
|
||||
}
|
||||
|
||||
if (!state.HaveHeader)
|
||||
{
|
||||
throw new ContainerException("Manca l'intestazione AVI.");
|
||||
}
|
||||
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
private static void ParseList(Stream stream, long start, long end, State state, bool samples, DateTimeOffset now, int depth)
|
||||
{
|
||||
Span<byte> header = stackalloc byte[12];
|
||||
var position = start;
|
||||
while (position + 8 <= end)
|
||||
{
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(header[..8]);
|
||||
var id = Encoding.Latin1.GetString(header[..4]);
|
||||
var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]);
|
||||
var body = position + 8;
|
||||
var next = body + size + (size & 1);
|
||||
if (next > end)
|
||||
{
|
||||
next = end; // truncated
|
||||
size = (uint)Math.Max(0, end - body);
|
||||
}
|
||||
|
||||
if (id == "LIST" && size >= 4)
|
||||
{
|
||||
stream.ReadExactly(header.Slice(8, 4));
|
||||
var type = Encoding.Latin1.GetString(header.Slice(8, 4));
|
||||
if (type == "movi" && !samples)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == "strl")
|
||||
{
|
||||
state.StreamIndex++;
|
||||
}
|
||||
|
||||
if (depth < 4 && type is "hdrl" or "strl" or "movi" or "rec " or "odml")
|
||||
{
|
||||
state.InMovi |= type == "movi";
|
||||
ParseList(stream, body + 4, body + size, state, samples, now, depth + 1);
|
||||
if (type == "movi")
|
||||
{
|
||||
state.InMovi = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (state.InMovi)
|
||||
{
|
||||
AddChunk(id, body, (int)size, state);
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case "avih" when size >= 40:
|
||||
{
|
||||
var data = Read(stream, body, (int)size);
|
||||
state.MicroSecondsPerFrame = BinaryPrimitives.ReadUInt32LittleEndian(data);
|
||||
state.TotalFrames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16));
|
||||
state.Width = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32));
|
||||
state.Height = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(36));
|
||||
state.HaveHeader = true;
|
||||
break;
|
||||
}
|
||||
|
||||
case "strh" when size >= 36:
|
||||
{
|
||||
var data = Read(stream, body, (int)size);
|
||||
var type = Encoding.Latin1.GetString(data, 0, 4);
|
||||
var handler = Encoding.Latin1.GetString(data, 4, 4);
|
||||
var scale = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(20));
|
||||
var rate = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(24));
|
||||
var frames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32));
|
||||
if (type == "vids" && state.VideoStream < 0)
|
||||
{
|
||||
state.VideoStream = state.StreamIndex - 1;
|
||||
state.VideoHandler = handler;
|
||||
(state.VideoScale, state.VideoRate, state.VideoLength) = (scale, rate, frames);
|
||||
}
|
||||
else if (type == "auds" && state.AudioStream < 0)
|
||||
{
|
||||
state.AudioStream = state.StreamIndex - 1;
|
||||
(state.AudioScale, state.AudioRate) = (scale, rate);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "strf":
|
||||
{
|
||||
var data = Read(stream, body, (int)Math.Min(size, 4096));
|
||||
if (state.StreamIndex - 1 == state.VideoStream && data.Length >= 20)
|
||||
{
|
||||
state.VideoWidth = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4));
|
||||
state.VideoHeight = Math.Abs(BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(8)));
|
||||
state.Compression = Encoding.Latin1.GetString(data, 16, 4);
|
||||
}
|
||||
else if (state.StreamIndex - 1 == state.AudioStream && data.Length >= 16)
|
||||
{
|
||||
state.AudioFormat = BinaryPrimitives.ReadUInt16LittleEndian(data);
|
||||
state.Channels = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(2));
|
||||
state.SampleRate = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4));
|
||||
if (data.Length >= 18)
|
||||
{
|
||||
var extra = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(16));
|
||||
if (extra > 0 && 18 + extra <= data.Length)
|
||||
{
|
||||
state.AudioExtra = data[18..(18 + extra)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "IDIT" when size is > 0 and < 128:
|
||||
state.Created = ParseDate(Encoding.ASCII.GetString(Read(stream, body, (int)size)), now);
|
||||
break;
|
||||
case "idx1" when samples:
|
||||
state.Index = Read(stream, body, (int)Math.Min(size, MaxHeaderBytes * 8L));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] Read(Stream stream, long offset, int count)
|
||||
{
|
||||
if (count > MaxHeaderBytes * 8)
|
||||
{
|
||||
throw new ContainerException("Intestazione AVI troppo grande.");
|
||||
}
|
||||
|
||||
var data = new byte[count];
|
||||
stream.Position = offset;
|
||||
stream.ReadExactly(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
private static void AddChunk(string id, long body, int size, State state)
|
||||
{
|
||||
if (id.Length != 4 || !char.IsAsciiDigit(id[0]) || !char.IsAsciiDigit(id[1]))
|
||||
{
|
||||
return; // JUNK, ix## indexes and the like
|
||||
}
|
||||
|
||||
var stream = (id[0] - '0') * 10 + (id[1] - '0');
|
||||
if (state.Chunks.Count >= MaxSamples)
|
||||
{
|
||||
throw new ContainerException("Troppi campioni.");
|
||||
}
|
||||
|
||||
if (stream == state.VideoStream && (id[2..] is "dc" or "db"))
|
||||
{
|
||||
state.Chunks.Add((body, size));
|
||||
}
|
||||
else if (stream == state.AudioStream && id[2..] == "wb")
|
||||
{
|
||||
state.AudioChunks.Add((body, size));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021».</summary>
|
||||
private static DateTimeOffset? ParseDate(string text, DateTimeOffset now)
|
||||
{
|
||||
var value = text.Trim('\0', ' ', '\r', '\n');
|
||||
foreach (var format in new[] { "ddd MMM dd HH:mm:ss yyyy", "ddd MMM d HH:mm:ss yyyy", "yyyy:MM:dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss" })
|
||||
{
|
||||
if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var local)
|
||||
&& local.Year >= 1995)
|
||||
{
|
||||
var instant = new DateTimeOffset(DateTime.SpecifyKind(local, DateTimeKind.Unspecified), TimeSpan.Zero);
|
||||
return instant <= now.AddDays(1) ? instant : null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private sealed class State
|
||||
{
|
||||
internal bool HaveHeader;
|
||||
internal bool InMovi;
|
||||
internal int StreamIndex;
|
||||
internal uint MicroSecondsPerFrame;
|
||||
internal uint TotalFrames;
|
||||
internal int Width;
|
||||
internal int Height;
|
||||
internal int VideoStream = -1;
|
||||
internal int AudioStream = -1;
|
||||
internal string VideoHandler = string.Empty;
|
||||
internal string Compression = string.Empty;
|
||||
internal uint VideoScale;
|
||||
internal uint VideoRate;
|
||||
internal uint VideoLength;
|
||||
internal int VideoWidth;
|
||||
internal int VideoHeight;
|
||||
internal uint AudioScale;
|
||||
internal uint AudioRate;
|
||||
internal int AudioFormat;
|
||||
internal int Channels;
|
||||
internal int SampleRate;
|
||||
internal byte[]? AudioExtra;
|
||||
internal DateTimeOffset? Created;
|
||||
internal byte[]? Index;
|
||||
internal readonly List<(long Offset, int Size)> Chunks = [];
|
||||
internal readonly List<(long Offset, int Size)> AudioChunks = [];
|
||||
|
||||
internal MediaContainer Build()
|
||||
{
|
||||
// Frame rate: the stream header first (rate / scale frames per second), then the main header.
|
||||
long timescale = 1000;
|
||||
long frameTicks = 40;
|
||||
if (VideoRate > 0 && VideoScale > 0)
|
||||
{
|
||||
timescale = VideoRate;
|
||||
frameTicks = VideoScale;
|
||||
}
|
||||
else if (MicroSecondsPerFrame > 0)
|
||||
{
|
||||
timescale = 1_000_000;
|
||||
frameTicks = MicroSecondsPerFrame;
|
||||
}
|
||||
|
||||
var keys = KeyFrames();
|
||||
var samples = new List<MediaSample>(Chunks.Count);
|
||||
var n = 0;
|
||||
for (var i = 0; i < Chunks.Count; i++)
|
||||
{
|
||||
var (offset, size) = Chunks[i];
|
||||
if (size == 0)
|
||||
{
|
||||
n++; // a dropped frame keeps its time slot
|
||||
continue;
|
||||
}
|
||||
|
||||
var t = n * frameTicks;
|
||||
samples.Add(new MediaSample(offset, size, t, t, keys is null || keys.Contains(i)));
|
||||
n++;
|
||||
}
|
||||
|
||||
var tag = (Compression.Length == 4 ? Compression : VideoHandler).ToUpperInvariant();
|
||||
var frames = VideoLength > 0 ? VideoLength : TotalFrames;
|
||||
var video = VideoStream < 0 ? null : new VideoTrack
|
||||
{
|
||||
Codec = tag switch
|
||||
{
|
||||
"H264" or "X264" or "AVC1" or "DAVC" or "VSSH" => VideoCodec.H264,
|
||||
"HEVC" or "H265" or "HVC1" => VideoCodec.Hevc,
|
||||
"MJPG" => VideoCodec.Mjpeg,
|
||||
"XVID" or "DIVX" or "DX50" or "FMP4" or "MP4V" => VideoCodec.Mpeg4Part2,
|
||||
_ => VideoCodec.Unknown,
|
||||
},
|
||||
CodecTag = Compression.Length == 4 ? Compression : VideoHandler,
|
||||
Width = VideoWidth > 0 ? VideoWidth : Width,
|
||||
Height = VideoHeight > 0 ? VideoHeight : Height,
|
||||
AnnexB = true,
|
||||
Timescale = timescale,
|
||||
Duration = frames * frameTicks,
|
||||
Samples = samples,
|
||||
};
|
||||
|
||||
AudioTrack? audio = null;
|
||||
if (AudioStream >= 0)
|
||||
{
|
||||
var audioSamples = new List<MediaSample>(AudioChunks.Count);
|
||||
foreach (var (offset, size) in AudioChunks)
|
||||
{
|
||||
audioSamples.Add(new MediaSample(offset, size, 0, 0, true));
|
||||
}
|
||||
|
||||
audio = new AudioTrack
|
||||
{
|
||||
Codec = AudioFormat switch
|
||||
{
|
||||
0x55 => AudioCodec.Mp3,
|
||||
0xFF or 0x1600 or 0x706D => AudioCodec.Aac,
|
||||
1 => AudioCodec.Pcm,
|
||||
_ => AudioCodec.Unknown,
|
||||
},
|
||||
CodecTag = AudioFormat.ToString("X4", CultureInfo.InvariantCulture),
|
||||
Channels = Channels,
|
||||
SampleRate = SampleRate,
|
||||
AacConfiguration = AudioFormat == 0xFF ? AudioExtra : null,
|
||||
Timescale = Math.Max(1, SampleRate),
|
||||
Samples = audioSamples,
|
||||
};
|
||||
}
|
||||
|
||||
TimeSpan? duration = video is { Duration: > 0 } ? TimeSpan.FromSeconds(video.Seconds(video.Duration)) : null;
|
||||
return new MediaContainer { Format = ContainerFormat.Avi, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
|
||||
}
|
||||
|
||||
/// <summary>Chunks of the video stream flagged as key frames in idx1 (by position among them); null without an index.</summary>
|
||||
private HashSet<int>? KeyFrames()
|
||||
{
|
||||
if (Index is null || VideoStream < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var keys = new HashSet<int>();
|
||||
var n = 0;
|
||||
for (var p = 0; p + 16 <= Index.Length; p += 16)
|
||||
{
|
||||
var id = Index.AsSpan(p, 4);
|
||||
if (!char.IsAsciiDigit((char)id[0]) || (id[0] - '0') * 10 + (id[1] - '0') != VideoStream || id[2] != 'd')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((BinaryPrimitives.ReadUInt32LittleEndian(Index.AsSpan(p + 4)) & 0x10) != 0)
|
||||
{
|
||||
keys.Add(n);
|
||||
}
|
||||
|
||||
n++;
|
||||
}
|
||||
|
||||
return n == Chunks.Count ? keys : null; // an index that does not match the chunks is ignored
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>Recognises the container of a video by its first bytes and reads it with the matching reader.</summary>
|
||||
public static class ContainerReader
|
||||
{
|
||||
/// <summary>The format of a file from its first bytes; null when it is none of those read here.</summary>
|
||||
public static ContainerFormat? Detect(ReadOnlySpan<byte> start)
|
||||
{
|
||||
if (MatroskaReader.Looks(start))
|
||||
{
|
||||
return ContainerFormat.Matroska;
|
||||
}
|
||||
|
||||
if (AviReader.Looks(start))
|
||||
{
|
||||
return ContainerFormat.Avi;
|
||||
}
|
||||
|
||||
return IsoBmffReader.Looks(start) ? ContainerFormat.IsoBmff : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a seekable stream; null when its format is not recognised. Damaged files raise
|
||||
/// <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/> when truncated).
|
||||
/// </summary>
|
||||
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
Span<byte> 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),
|
||||
ContainerFormat.Avi => AviReader.Read(stream, now, samples),
|
||||
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Reads a file (read-only, shared); null when its format is not recognised.</summary>
|
||||
public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
using var stream = OpenRead(path);
|
||||
return Read(stream, now, samples);
|
||||
}
|
||||
|
||||
/// <summary>Opens a file for reading without blocking other readers or writers.</summary>
|
||||
public static FileStream OpenRead(string path) =>
|
||||
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, FileOptions.RandomAccess);
|
||||
|
||||
/// <summary>The bytes of a sample, read into <paramref name="buffer"/> (grown when needed).</summary>
|
||||
public static ReadOnlySpan<byte> 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 (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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,842 @@
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Reader of the ISO base media file format (ISO/IEC 14496-12: MP4, MOV, 3GP), written from the standard: the movie
|
||||
/// header, the first video and audio tracks with their sample tables, and the fragments (<c>moof</c>) of fragmented
|
||||
/// files. Only boxes are read into memory; media data is never loaded here.
|
||||
/// </summary>
|
||||
public static class IsoBmffReader
|
||||
{
|
||||
private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private const long MaxBoxInMemory = 128L * 1024 * 1024;
|
||||
private const int MaxTopLevelBoxes = 1_000_000;
|
||||
private const int MaxSamples = 20_000_000;
|
||||
|
||||
/// <summary>True when the stream starts like an ISO media file (an <c>ftyp</c>, <c>moov</c>, <c>mdat</c>... box).</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) =>
|
||||
start.Length >= 8 && (start.Slice(4, 4).SequenceEqual("ftyp"u8) || start.Slice(4, 4).SequenceEqual("moov"u8)
|
||||
|| start.Slice(4, 4).SequenceEqual("mdat"u8) || start.Slice(4, 4).SequenceEqual("wide"u8)
|
||||
|| start.Slice(4, 4).SequenceEqual("free"u8) || start.Slice(4, 4).SequenceEqual("skip"u8));
|
||||
|
||||
/// <summary>Reads a seekable stream from its start.</summary>
|
||||
/// <param name="stream">The file.</param>
|
||||
/// <param name="now">Current time: later creation times are ignored.</param>
|
||||
/// <param name="samples">False to stop at the metadata (no sample tables, no fragments).</param>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var length = stream.Length;
|
||||
long position = 0;
|
||||
Span<byte> header = stackalloc byte[16];
|
||||
Movie? movie = null;
|
||||
var fragments = new List<(long Start, byte[] Body)>();
|
||||
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
|
||||
{
|
||||
stream.Position = position;
|
||||
stream.ReadExactly(header[..8]);
|
||||
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
|
||||
var headerSize = 8;
|
||||
if (size == 1)
|
||||
{
|
||||
stream.ReadExactly(header.Slice(8, 8));
|
||||
size = (long)BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8));
|
||||
headerSize = 16;
|
||||
}
|
||||
else if (size == 0)
|
||||
{
|
||||
size = length - position;
|
||||
}
|
||||
|
||||
if (size < headerSize || size > length - position)
|
||||
{
|
||||
if (movie is not null)
|
||||
{
|
||||
break; // a truncated last box (often mdat): what was read stands
|
||||
}
|
||||
|
||||
throw new ContainerException("Box ISO danneggiato.");
|
||||
}
|
||||
|
||||
var type = header.Slice(4, 4);
|
||||
if (type.SequenceEqual("moov"u8))
|
||||
{
|
||||
movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples);
|
||||
if (!samples)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (samples && type.SequenceEqual("moof"u8))
|
||||
{
|
||||
fragments.Add((position, ReadBody(stream, position + headerSize, size - headerSize)));
|
||||
}
|
||||
|
||||
position += size;
|
||||
}
|
||||
|
||||
if (movie is null)
|
||||
{
|
||||
throw new ContainerException("Manca il box moov.");
|
||||
}
|
||||
|
||||
foreach (var (start, body) in fragments)
|
||||
{
|
||||
movie.AddFragment(start, body);
|
||||
}
|
||||
|
||||
return movie.Build();
|
||||
}
|
||||
|
||||
private static byte[] ReadBody(Stream stream, long offset, long count)
|
||||
{
|
||||
if (count > MaxBoxInMemory)
|
||||
{
|
||||
throw new ContainerException("Box ISO troppo grande.");
|
||||
}
|
||||
|
||||
var body = new byte[count];
|
||||
stream.Position = offset;
|
||||
stream.ReadExactly(body);
|
||||
return body;
|
||||
}
|
||||
|
||||
private static Movie ParseMoov(byte[] moov, DateTimeOffset now, bool samples)
|
||||
{
|
||||
var movie = new Movie(samples);
|
||||
try
|
||||
{
|
||||
foreach (var (type, start, count) in Children(moov, 0, moov.Length))
|
||||
{
|
||||
var body = moov.AsSpan(start, count);
|
||||
switch (type)
|
||||
{
|
||||
case "mvhd":
|
||||
movie.ParseMvhd(body, now);
|
||||
break;
|
||||
case "trak":
|
||||
movie.ParseTrak(moov, start, count);
|
||||
break;
|
||||
case "mvex":
|
||||
foreach (var (t, s, c) in Children(moov, start, count))
|
||||
{
|
||||
if (t == "trex" && c >= 24)
|
||||
{
|
||||
var id = BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4));
|
||||
movie.TrackDefaults[id] = (
|
||||
BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 12)),
|
||||
BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 16)),
|
||||
BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 20)));
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ArgumentOutOfRangeException)
|
||||
{
|
||||
throw new ContainerException("Box moov danneggiato.");
|
||||
}
|
||||
|
||||
return movie;
|
||||
}
|
||||
|
||||
/// <summary>Child boxes of the box body data[start..start+count]: type, body start and body length.</summary>
|
||||
internal static List<(string Type, int Start, int Length)> Children(byte[] data, int start, int count)
|
||||
{
|
||||
var list = new List<(string, int, int)>();
|
||||
var offset = start;
|
||||
var end = start + count;
|
||||
while (offset + 8 <= end && list.Count < 100_000)
|
||||
{
|
||||
long size = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(offset));
|
||||
var type = System.Text.Encoding.Latin1.GetString(data, offset + 4, 4);
|
||||
var headerSize = 8;
|
||||
if (size == 1)
|
||||
{
|
||||
if (offset + 16 > end)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
size = (long)BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(offset + 8));
|
||||
headerSize = 16;
|
||||
}
|
||||
else if (size == 0)
|
||||
{
|
||||
size = end - offset;
|
||||
}
|
||||
|
||||
if (size < headerSize || size > end - offset)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
list.Add((type, offset + headerSize, (int)size - headerSize));
|
||||
offset += (int)size;
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static int Rotation(ReadOnlySpan<byte> matrix)
|
||||
{
|
||||
var a = BinaryPrimitives.ReadInt32BigEndian(matrix);
|
||||
var b = BinaryPrimitives.ReadInt32BigEndian(matrix[4..]);
|
||||
var c = BinaryPrimitives.ReadInt32BigEndian(matrix[12..]);
|
||||
var d = BinaryPrimitives.ReadInt32BigEndian(matrix[16..]);
|
||||
const int One = 0x10000;
|
||||
if (a == 0 && d == 0 && b == One && c == -One)
|
||||
{
|
||||
return 90;
|
||||
}
|
||||
|
||||
if (a == -One && d == -One && b == 0 && c == 0)
|
||||
{
|
||||
return 180;
|
||||
}
|
||||
|
||||
if (a == 0 && d == 0 && b == -One && c == One)
|
||||
{
|
||||
return 270;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private sealed class Track
|
||||
{
|
||||
internal uint Id;
|
||||
internal string Handler = string.Empty;
|
||||
internal long Timescale;
|
||||
internal long Duration;
|
||||
internal int Rotation;
|
||||
internal int TkhdWidth;
|
||||
internal int TkhdHeight;
|
||||
internal string Format = string.Empty;
|
||||
internal int Width;
|
||||
internal int Height;
|
||||
internal int Channels;
|
||||
internal int SampleRate;
|
||||
internal byte[]? Avcc;
|
||||
internal byte[]? Asc;
|
||||
internal long EditOffset;
|
||||
internal List<MediaSample> Samples = [];
|
||||
internal long FragmentTime = -1;
|
||||
}
|
||||
|
||||
private sealed class Movie(bool samples)
|
||||
{
|
||||
internal readonly Dictionary<uint, (uint Description, uint Duration, uint Size)> TrackDefaults = [];
|
||||
private readonly List<Track> tracks = [];
|
||||
private DateTimeOffset? created;
|
||||
private long timescale;
|
||||
private long duration;
|
||||
|
||||
internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now)
|
||||
{
|
||||
ulong creation;
|
||||
if (body[0] == 1)
|
||||
{
|
||||
creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]);
|
||||
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
|
||||
duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
|
||||
duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
|
||||
if (duration == uint.MaxValue)
|
||||
{
|
||||
duration = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (creation > 0 && creation < 400UL * 366 * 86400)
|
||||
{
|
||||
var instant = Epoch1904.AddSeconds(creation);
|
||||
if (instant >= Earliest && instant <= now.AddDays(1))
|
||||
{
|
||||
created = instant;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal void ParseTrak(byte[] data, int start, int count)
|
||||
{
|
||||
var track = new Track();
|
||||
foreach (var (type, s, c) in Children(data, start, count))
|
||||
{
|
||||
var body = data.AsSpan(s, c);
|
||||
switch (type)
|
||||
{
|
||||
case "tkhd":
|
||||
{
|
||||
var v1 = body[0] == 1;
|
||||
track.Id = BinaryPrimitives.ReadUInt32BigEndian(body[(v1 ? 20 : 12)..]);
|
||||
var offset = (v1 ? 36 : 24) + 16;
|
||||
track.Rotation = Rotation(body.Slice(offset, 36));
|
||||
track.TkhdWidth = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 36)..]) >> 16);
|
||||
track.TkhdHeight = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 40)..]) >> 16);
|
||||
break;
|
||||
}
|
||||
|
||||
case "edts":
|
||||
foreach (var (t, es, ec) in Children(data, s, c))
|
||||
{
|
||||
if (t == "elst")
|
||||
{
|
||||
ParseElst(data.AsSpan(es, ec), track);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case "mdia":
|
||||
ParseMdia(data, s, c, track);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
tracks.Add(track);
|
||||
}
|
||||
|
||||
private static void ParseElst(ReadOnlySpan<byte> body, Track track)
|
||||
{
|
||||
var v1 = body[0] == 1;
|
||||
var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||
var offset = 8;
|
||||
for (var i = 0; i < entries && i < 16; i++)
|
||||
{
|
||||
long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]);
|
||||
offset += v1 ? 20 : 12;
|
||||
if (mediaTime >= 0)
|
||||
{
|
||||
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ParseMdia(byte[] data, int start, int count, Track track)
|
||||
{
|
||||
foreach (var (type, s, c) in Children(data, start, count))
|
||||
{
|
||||
var body = data.AsSpan(s, c);
|
||||
switch (type)
|
||||
{
|
||||
case "mdhd":
|
||||
if (body[0] == 1)
|
||||
{
|
||||
track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
|
||||
track.Duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
|
||||
var d = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
|
||||
track.Duration = d == uint.MaxValue ? 0 : d;
|
||||
}
|
||||
|
||||
break;
|
||||
case "hdlr":
|
||||
track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4));
|
||||
break;
|
||||
case "minf":
|
||||
foreach (var (t, ms, mc) in Children(data, s, c))
|
||||
{
|
||||
if (t == "stbl")
|
||||
{
|
||||
ParseStbl(data, ms, mc, track);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ParseStbl(byte[] data, int start, int count, Track track)
|
||||
{
|
||||
byte[]? stts = null, ctts = null, stsc = null, stsz = null, stco = null, stss = null;
|
||||
var co64 = false;
|
||||
var stz2 = false;
|
||||
foreach (var (type, s, c) in Children(data, start, count))
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case "stsd":
|
||||
ParseStsd(data, s, c, track);
|
||||
break;
|
||||
case "stts":
|
||||
stts = data[s..(s + c)];
|
||||
break;
|
||||
case "ctts":
|
||||
ctts = data[s..(s + c)];
|
||||
break;
|
||||
case "stsc":
|
||||
stsc = data[s..(s + c)];
|
||||
break;
|
||||
case "stsz":
|
||||
stsz = data[s..(s + c)];
|
||||
break;
|
||||
case "stz2":
|
||||
stsz = data[s..(s + c)];
|
||||
stz2 = true;
|
||||
break;
|
||||
case "stco":
|
||||
stco = data[s..(s + c)];
|
||||
break;
|
||||
case "co64":
|
||||
stco = data[s..(s + c)];
|
||||
co64 = true;
|
||||
break;
|
||||
case "stss":
|
||||
stss = data[s..(s + c)];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!samples || stts is null || stsc is null || stsz is null || stco is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
BuildSamples(track, stts, ctts, stsc, stsz, stz2, stco, co64, stss);
|
||||
}
|
||||
|
||||
private static void ParseStsd(byte[] data, int start, int count, Track track)
|
||||
{
|
||||
if (count < 16)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// version/flags, entry count, then the first sample entry.
|
||||
var entry = start + 8;
|
||||
var size = (int)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(entry));
|
||||
if (size < 16 || entry + size > start + count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
track.Format = System.Text.Encoding.Latin1.GetString(data, entry + 4, 4);
|
||||
var body = entry + 8;
|
||||
var bodyEnd = entry + size;
|
||||
if (track.Handler == "vide" && size >= 8 + 78)
|
||||
{
|
||||
track.Width = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 24));
|
||||
track.Height = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 26));
|
||||
foreach (var (t, s, c) in Children(data, body + 78, bodyEnd - body - 78))
|
||||
{
|
||||
if (t == "avcC")
|
||||
{
|
||||
track.Avcc = data[s..(s + c)];
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (track.Handler == "soun" && size >= 8 + 28)
|
||||
{
|
||||
var version = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 8));
|
||||
track.Channels = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 16));
|
||||
track.SampleRate = (int)(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(body + 24)) >> 16);
|
||||
var children = body + 28 + (version == 1 ? 16 : version == 2 ? 36 : 0);
|
||||
if (children < bodyEnd)
|
||||
{
|
||||
foreach (var (t, s, c) in Children(data, children, bodyEnd - children))
|
||||
{
|
||||
if (t == "esds")
|
||||
{
|
||||
track.Asc = EsdsConfig(data.AsSpan(s, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1 descriptors).</summary>
|
||||
private static byte[]? EsdsConfig(ReadOnlySpan<byte> body)
|
||||
{
|
||||
var p = 4; // version and flags
|
||||
while (p + 2 <= body.Length)
|
||||
{
|
||||
var tag = body[p++];
|
||||
var length = 0;
|
||||
for (var i = 0; i < 4 && p < body.Length; i++)
|
||||
{
|
||||
var b = body[p++];
|
||||
length = (length << 7) | (b & 0x7F);
|
||||
if ((b & 0x80) == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
switch (tag)
|
||||
{
|
||||
case 0x03: // ES_Descriptor
|
||||
{
|
||||
var flags = body[p + 2];
|
||||
p += 3;
|
||||
if ((flags & 0x80) != 0)
|
||||
{
|
||||
p += 2;
|
||||
}
|
||||
|
||||
if ((flags & 0x40) != 0)
|
||||
{
|
||||
p += 1 + body[p];
|
||||
}
|
||||
|
||||
if ((flags & 0x20) != 0)
|
||||
{
|
||||
p += 2;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 0x04: // DecoderConfigDescriptor: its fixed fields, then the children
|
||||
p += 13;
|
||||
break;
|
||||
case 0x05:
|
||||
return p + length <= body.Length ? body.Slice(p, length).ToArray() : null;
|
||||
default:
|
||||
p += length;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss)
|
||||
{
|
||||
int count;
|
||||
uint fixedSize = 0;
|
||||
var fieldSize = 32;
|
||||
if (stz2)
|
||||
{
|
||||
fieldSize = stsz[7];
|
||||
count = (int)BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8));
|
||||
}
|
||||
else
|
||||
{
|
||||
fixedSize = BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(4));
|
||||
count = (int)BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8));
|
||||
}
|
||||
|
||||
if (count < 0 || count > MaxSamples)
|
||||
{
|
||||
throw new ContainerException("Troppi campioni.");
|
||||
}
|
||||
|
||||
int SizeOf(int i)
|
||||
{
|
||||
if (!stz2)
|
||||
{
|
||||
return (int)(fixedSize != 0 ? fixedSize : BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(12 + (i * 4))));
|
||||
}
|
||||
|
||||
return fieldSize switch
|
||||
{
|
||||
4 => (stsz[12 + (i / 2)] >> ((i & 1) == 0 ? 4 : 0)) & 15,
|
||||
8 => stsz[12 + i],
|
||||
_ => BinaryPrimitives.ReadUInt16BigEndian(stsz.AsSpan(12 + (i * 2))),
|
||||
};
|
||||
}
|
||||
|
||||
var chunkCount = (int)BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(4));
|
||||
long ChunkOffset(int i) => co64
|
||||
? (long)BinaryPrimitives.ReadUInt64BigEndian(stco.AsSpan(8 + (i * 8)))
|
||||
: BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(8 + (i * 4)));
|
||||
|
||||
var keys = stss is null ? null : new HashSet<int>();
|
||||
if (stss is not null)
|
||||
{
|
||||
var n = BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(4));
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
keys!.Add((int)BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(8 + (i * 4))) - 1);
|
||||
}
|
||||
}
|
||||
|
||||
var list = new List<MediaSample>(count);
|
||||
|
||||
// Decode times (stts) and composition offsets (ctts) run along the samples.
|
||||
var sttsEntries = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(4));
|
||||
int sttsIndex = 0, sttsLeft = 0;
|
||||
uint delta = 0;
|
||||
var cttsEntries = ctts is null ? 0 : BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(4));
|
||||
var cttsSigned = ctts is not null && ctts[0] == 1;
|
||||
int cttsIndex = 0, cttsLeft = 0;
|
||||
long offsetCt = 0;
|
||||
long dts = 0;
|
||||
|
||||
var stscEntries = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(4));
|
||||
var sample = 0;
|
||||
for (var e = 0; e < stscEntries && sample < count; e++)
|
||||
{
|
||||
var firstChunk = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + (e * 12))) - 1;
|
||||
var perChunk = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(12 + (e * 12)));
|
||||
var nextFirst = e + 1 < stscEntries ? (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + ((e + 1) * 12))) - 1 : chunkCount;
|
||||
for (var chunk = firstChunk; chunk < nextFirst && chunk < chunkCount && sample < count; chunk++)
|
||||
{
|
||||
var offset = ChunkOffset(chunk);
|
||||
for (var k = 0; k < perChunk && sample < count; k++)
|
||||
{
|
||||
while (sttsLeft == 0 && sttsIndex < sttsEntries)
|
||||
{
|
||||
sttsLeft = (int)BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(8 + (sttsIndex * 8)));
|
||||
delta = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(12 + (sttsIndex * 8)));
|
||||
sttsIndex++;
|
||||
}
|
||||
|
||||
while (ctts is not null && cttsLeft == 0 && cttsIndex < cttsEntries)
|
||||
{
|
||||
cttsLeft = (int)BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(8 + (cttsIndex * 8)));
|
||||
offsetCt = cttsSigned
|
||||
? BinaryPrimitives.ReadInt32BigEndian(ctts.AsSpan(12 + (cttsIndex * 8)))
|
||||
: BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(12 + (cttsIndex * 8)));
|
||||
cttsIndex++;
|
||||
}
|
||||
|
||||
var size = SizeOf(sample);
|
||||
list.Add(new MediaSample(offset, size, dts, dts + offsetCt - track.EditOffset, keys is null || keys.Contains(sample)));
|
||||
offset += size;
|
||||
dts += delta;
|
||||
sttsLeft = Math.Max(0, sttsLeft - 1);
|
||||
cttsLeft = Math.Max(0, cttsLeft - 1);
|
||||
sample++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
track.Samples = list;
|
||||
track.FragmentTime = dts;
|
||||
}
|
||||
|
||||
/// <summary>Adds the samples of one movie fragment (ISO/IEC 14496-12 §8.8).</summary>
|
||||
internal void AddFragment(long moofStart, byte[] moof)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var (type, s, c) in Children(moof, 0, moof.Length))
|
||||
{
|
||||
if (type == "traf")
|
||||
{
|
||||
AddTrackFragment(moofStart, moof, s, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ArgumentOutOfRangeException)
|
||||
{
|
||||
// A damaged fragment: the samples read so far stand.
|
||||
}
|
||||
}
|
||||
|
||||
private void AddTrackFragment(long moofStart, byte[] data, int start, int count)
|
||||
{
|
||||
Track? track = null;
|
||||
long baseOffset = moofStart;
|
||||
uint defDuration = 0, defSize = 0, defFlags = 0;
|
||||
long? decodeTime = null;
|
||||
foreach (var (type, s, c) in Children(data, start, count))
|
||||
{
|
||||
var body = data.AsSpan(s, c);
|
||||
switch (type)
|
||||
{
|
||||
case "tfhd":
|
||||
{
|
||||
var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF;
|
||||
var id = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||
track = tracks.Find(t => t.Id == id);
|
||||
if (TrackDefaults.TryGetValue(id, out var d))
|
||||
{
|
||||
(defDuration, defSize, defFlags) = (d.Duration, d.Size, 0);
|
||||
}
|
||||
|
||||
var p = 8;
|
||||
if ((flags & 0x1) != 0)
|
||||
{
|
||||
baseOffset = (long)BinaryPrimitives.ReadUInt64BigEndian(body[p..]);
|
||||
p += 8;
|
||||
}
|
||||
|
||||
if ((flags & 0x2) != 0)
|
||||
{
|
||||
p += 4;
|
||||
}
|
||||
|
||||
if ((flags & 0x8) != 0)
|
||||
{
|
||||
defDuration = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
if ((flags & 0x10) != 0)
|
||||
{
|
||||
defSize = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
if ((flags & 0x20) != 0)
|
||||
{
|
||||
defFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "tfdt":
|
||||
decodeTime = body[0] == 1 ? (long)BinaryPrimitives.ReadUInt64BigEndian(body[4..]) : BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||
break;
|
||||
case "trun" when track is not null:
|
||||
{
|
||||
var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF;
|
||||
var signed = body[0] == 1;
|
||||
var n = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||
if (n < 0 || track.Samples.Count + n > MaxSamples)
|
||||
{
|
||||
throw new ContainerException("Troppi campioni.");
|
||||
}
|
||||
|
||||
var p = 8;
|
||||
var offset = baseOffset;
|
||||
if ((flags & 0x1) != 0)
|
||||
{
|
||||
offset += BinaryPrimitives.ReadInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
uint? firstFlags = null;
|
||||
if ((flags & 0x4) != 0)
|
||||
{
|
||||
firstFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
var dts = decodeTime ?? Math.Max(0, track.FragmentTime);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var duration = defDuration;
|
||||
var size = defSize;
|
||||
var sampleFlags = i == 0 && firstFlags is { } ff ? ff : defFlags;
|
||||
long ct = 0;
|
||||
if ((flags & 0x100) != 0)
|
||||
{
|
||||
duration = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
if ((flags & 0x200) != 0)
|
||||
{
|
||||
size = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
if ((flags & 0x400) != 0)
|
||||
{
|
||||
sampleFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
if ((flags & 0x800) != 0)
|
||||
{
|
||||
ct = signed ? BinaryPrimitives.ReadInt32BigEndian(body[p..]) : BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
|
||||
p += 4;
|
||||
}
|
||||
|
||||
var key = (sampleFlags & 0x10000) == 0; // sample_is_non_sync_sample
|
||||
track.Samples.Add(new MediaSample(offset, (int)size, dts, dts + ct - track.EditOffset, key));
|
||||
offset += size;
|
||||
dts += duration;
|
||||
}
|
||||
|
||||
track.FragmentTime = dts;
|
||||
decodeTime = dts;
|
||||
baseOffset = offset; // a later trun of the same traf continues the data
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal MediaContainer Build()
|
||||
{
|
||||
var video = tracks.Find(t => t.Handler == "vide");
|
||||
var audio = tracks.Find(t => t.Handler == "soun");
|
||||
VideoTrack? v = null;
|
||||
if (video is not null)
|
||||
{
|
||||
v = new VideoTrack
|
||||
{
|
||||
Codec = video.Format switch
|
||||
{
|
||||
"avc1" or "avc3" => VideoCodec.H264,
|
||||
"hvc1" or "hev1" => VideoCodec.Hevc,
|
||||
"vp08" => VideoCodec.Vp8,
|
||||
"vp09" => VideoCodec.Vp9,
|
||||
"av01" => VideoCodec.Av1,
|
||||
"mp4v" => VideoCodec.Mpeg4Part2,
|
||||
"jpeg" or "mjpa" => VideoCodec.Mjpeg,
|
||||
_ => VideoCodec.Unknown,
|
||||
},
|
||||
CodecTag = video.Format,
|
||||
Width = video.Width > 0 ? video.Width : video.TkhdWidth,
|
||||
Height = video.Height > 0 ? video.Height : video.TkhdHeight,
|
||||
Rotation = video.Rotation,
|
||||
Timescale = video.Timescale > 0 ? video.Timescale : 1,
|
||||
Duration = DurationOf(video),
|
||||
AvcConfiguration = video.Avcc,
|
||||
Samples = video.Samples,
|
||||
};
|
||||
}
|
||||
|
||||
AudioTrack? a = null;
|
||||
if (audio is not null)
|
||||
{
|
||||
a = new AudioTrack
|
||||
{
|
||||
Codec = audio.Format switch
|
||||
{
|
||||
"mp4a" => AudioCodec.Aac,
|
||||
".mp3" => AudioCodec.Mp3,
|
||||
"Opus" => AudioCodec.Opus,
|
||||
"lpcm" or "sowt" or "twos" => AudioCodec.Pcm,
|
||||
_ => AudioCodec.Unknown,
|
||||
},
|
||||
CodecTag = audio.Format,
|
||||
Channels = audio.Channels,
|
||||
SampleRate = audio.SampleRate,
|
||||
AacConfiguration = audio.Asc,
|
||||
Timescale = audio.Timescale > 0 ? audio.Timescale : 1,
|
||||
Duration = DurationOf(audio),
|
||||
Samples = audio.Samples,
|
||||
};
|
||||
}
|
||||
|
||||
TimeSpan? total = timescale > 0 && duration > 0 ? TimeSpan.FromSeconds((double)duration / timescale) : null;
|
||||
if (total is null && v is { Duration: > 0 })
|
||||
{
|
||||
total = TimeSpan.FromSeconds(v.Seconds(v.Duration));
|
||||
}
|
||||
|
||||
return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a };
|
||||
}
|
||||
|
||||
private static long DurationOf(Track track)
|
||||
{
|
||||
if (track.FragmentTime > track.Duration)
|
||||
{
|
||||
return track.FragmentTime; // fragmented: the header says 0
|
||||
}
|
||||
|
||||
return track.Duration;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Reader of Matroska and WebM (EBML, RFC 8794, and the Matroska specification, RFC 9559), written from the
|
||||
/// specifications: segment information, the first video and audio tracks and, when asked, the blocks of the clusters.
|
||||
/// Elements are read one by one from the stream; the frames are never loaded here.
|
||||
/// </summary>
|
||||
public static class MatroskaReader
|
||||
{
|
||||
private static readonly DateTimeOffset Epoch2001 = new(2001, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private const uint EbmlId = 0x1A45DFA3;
|
||||
private const uint SegmentId = 0x18538067;
|
||||
private const uint InfoId = 0x1549A966;
|
||||
private const uint TracksId = 0x1654AE6B;
|
||||
private const uint ClusterId = 0x1F43B675;
|
||||
private const uint CuesId = 0x1C53BB6B;
|
||||
private const uint TagsId = 0x1254C367;
|
||||
private const uint AttachmentsId = 0x1941A469;
|
||||
private const uint ChaptersId = 0x1043A770;
|
||||
private const uint SeekHeadId = 0x114D9B74;
|
||||
private const long UnknownSize = -1;
|
||||
private const int MaxSamples = 20_000_000;
|
||||
private const long MaxElementInMemory = 64L * 1024 * 1024;
|
||||
|
||||
/// <summary>True when the stream starts with an EBML header.</summary>
|
||||
public static bool Looks(ReadOnlySpan<byte> start) => start.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(start) == EbmlId;
|
||||
|
||||
/// <summary>Reads a seekable stream from its start.</summary>
|
||||
/// <param name="stream">The file.</param>
|
||||
/// <param name="now">Current time: later creation times are ignored.</param>
|
||||
/// <param name="samples">False to stop before the first cluster.</param>
|
||||
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
var reader = new Reader(stream);
|
||||
stream.Position = 0;
|
||||
var (id, size) = reader.Header();
|
||||
if (id != EbmlId || size < 0)
|
||||
{
|
||||
throw new ContainerException("Intestazione EBML mancante.");
|
||||
}
|
||||
|
||||
var docType = "matroska";
|
||||
var end = stream.Position + size;
|
||||
while (stream.Position < end)
|
||||
{
|
||||
var (cid, csize) = reader.Header();
|
||||
if (cid == 0x4282)
|
||||
{
|
||||
docType = reader.String(csize);
|
||||
}
|
||||
else
|
||||
{
|
||||
reader.Skip(csize);
|
||||
}
|
||||
}
|
||||
|
||||
if (docType is not ("matroska" or "webm"))
|
||||
{
|
||||
throw new ContainerException("Documento EBML che non è Matroska.");
|
||||
}
|
||||
|
||||
stream.Position = end;
|
||||
(id, size) = reader.Header();
|
||||
while (id != SegmentId)
|
||||
{
|
||||
if (size < 0)
|
||||
{
|
||||
throw new ContainerException("Segmento Matroska mancante.");
|
||||
}
|
||||
|
||||
reader.Skip(size);
|
||||
(id, size) = reader.Header();
|
||||
}
|
||||
|
||||
var segmentEnd = size < 0 ? stream.Length : Math.Min(stream.Length, stream.Position + size);
|
||||
var state = new State();
|
||||
while (stream.Position < segmentEnd)
|
||||
{
|
||||
var elementStart = stream.Position;
|
||||
if (segmentEnd - elementStart < 2)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
(id, size) = reader.Header();
|
||||
var bodyEnd = size < 0 ? segmentEnd : stream.Position + size;
|
||||
if (bodyEnd > segmentEnd)
|
||||
{
|
||||
bodyEnd = segmentEnd; // truncated file
|
||||
}
|
||||
|
||||
switch (id)
|
||||
{
|
||||
case InfoId:
|
||||
ParseInfo(reader, bodyEnd, state, now);
|
||||
break;
|
||||
case TracksId:
|
||||
ParseTracks(reader, bodyEnd, state);
|
||||
break;
|
||||
case ClusterId:
|
||||
if (!samples)
|
||||
{
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
ParseCluster(reader, bodyEnd, size < 0, state);
|
||||
continue; // the position is already past the cluster
|
||||
default:
|
||||
if (size < 0)
|
||||
{
|
||||
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
stream.Position = bodyEnd;
|
||||
}
|
||||
|
||||
return state.Build();
|
||||
}
|
||||
|
||||
private static void ParseInfo(Reader reader, long end, State state, DateTimeOffset now)
|
||||
{
|
||||
var stream = reader.Stream;
|
||||
while (stream.Position < end)
|
||||
{
|
||||
var (id, size) = reader.Header();
|
||||
switch (id)
|
||||
{
|
||||
case 0x2AD7B1:
|
||||
state.TimecodeScale = (long)reader.Unsigned(size);
|
||||
break;
|
||||
case 0x4489:
|
||||
state.DurationTicks = reader.Float(size);
|
||||
break;
|
||||
case 0x4461:
|
||||
{
|
||||
var ns = reader.Signed(size);
|
||||
var instant = Epoch2001.AddTicks(ns / 100);
|
||||
if (instant >= Earliest && instant <= now.AddDays(1))
|
||||
{
|
||||
state.Created = instant;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
reader.Skip(size);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ParseTracks(Reader reader, long end, State state)
|
||||
{
|
||||
var stream = reader.Stream;
|
||||
while (stream.Position < end)
|
||||
{
|
||||
var (id, size) = reader.Header();
|
||||
if (id != 0xAE)
|
||||
{
|
||||
reader.Skip(size);
|
||||
continue;
|
||||
}
|
||||
|
||||
var entryEnd = stream.Position + size;
|
||||
var track = new TrackEntry();
|
||||
while (stream.Position < entryEnd)
|
||||
{
|
||||
var (tid, tsize) = reader.Header();
|
||||
switch (tid)
|
||||
{
|
||||
case 0xD7:
|
||||
track.Number = (long)reader.Unsigned(tsize);
|
||||
break;
|
||||
case 0x83:
|
||||
track.Type = (int)reader.Unsigned(tsize);
|
||||
break;
|
||||
case 0x86:
|
||||
track.CodecId = reader.String(tsize);
|
||||
break;
|
||||
case 0x63A2:
|
||||
track.CodecPrivate = reader.Bytes(tsize);
|
||||
break;
|
||||
case 0x23E383:
|
||||
track.DefaultDuration = (long)reader.Unsigned(tsize);
|
||||
break;
|
||||
case 0x55EE: // MaxBlockAdditionID, and others: ignored
|
||||
reader.Skip(tsize);
|
||||
break;
|
||||
case 0xE0:
|
||||
{
|
||||
var videoEnd = stream.Position + tsize;
|
||||
while (stream.Position < videoEnd)
|
||||
{
|
||||
var (vid, vsize) = reader.Header();
|
||||
switch (vid)
|
||||
{
|
||||
case 0xB0:
|
||||
track.Width = (int)reader.Unsigned(vsize);
|
||||
break;
|
||||
case 0xBA:
|
||||
track.Height = (int)reader.Unsigned(vsize);
|
||||
break;
|
||||
case 0x7670: // Projection
|
||||
{
|
||||
var projectionEnd = stream.Position + vsize;
|
||||
while (stream.Position < projectionEnd)
|
||||
{
|
||||
var (pid, psize) = reader.Header();
|
||||
if (pid == 0x7675)
|
||||
{
|
||||
track.Roll = reader.Float(psize);
|
||||
}
|
||||
else
|
||||
{
|
||||
reader.Skip(psize);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
reader.Skip(vsize);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 0xE1:
|
||||
{
|
||||
var audioEnd = stream.Position + tsize;
|
||||
while (stream.Position < audioEnd)
|
||||
{
|
||||
var (aid, asize) = reader.Header();
|
||||
switch (aid)
|
||||
{
|
||||
case 0xB5:
|
||||
track.SampleRate = (int)reader.Float(asize);
|
||||
break;
|
||||
case 0x9F:
|
||||
track.Channels = (int)reader.Unsigned(asize);
|
||||
break;
|
||||
default:
|
||||
reader.Skip(asize);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
reader.Skip(tsize);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
stream.Position = entryEnd;
|
||||
if (track.Type == 1 && state.Video is null)
|
||||
{
|
||||
state.Video = track;
|
||||
}
|
||||
else if (track.Type == 2 && state.Audio is null)
|
||||
{
|
||||
state.Audio = track;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ParseCluster(Reader reader, long end, bool unknownSize, State state)
|
||||
{
|
||||
var stream = reader.Stream;
|
||||
long clusterTime = 0;
|
||||
while (stream.Position < end)
|
||||
{
|
||||
var start = stream.Position;
|
||||
if (end - start < 2)
|
||||
{
|
||||
stream.Position = end;
|
||||
return;
|
||||
}
|
||||
|
||||
var (id, size) = reader.Header();
|
||||
if (unknownSize && id is ClusterId or CuesId or TagsId or AttachmentsId or ChaptersId or SeekHeadId or InfoId or TracksId)
|
||||
{
|
||||
stream.Position = start; // the next top-level element ends a cluster of unknown size
|
||||
return;
|
||||
}
|
||||
|
||||
if (size < 0)
|
||||
{
|
||||
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
|
||||
}
|
||||
|
||||
var bodyEnd = Math.Min(stream.Position + size, end);
|
||||
switch (id)
|
||||
{
|
||||
case 0xE7:
|
||||
clusterTime = (long)reader.Unsigned(size);
|
||||
break;
|
||||
case 0xA3: // SimpleBlock
|
||||
AddBlock(reader, stream.Position, bodyEnd, clusterTime, simple: true, hasReference: false, state);
|
||||
break;
|
||||
case 0xA0: // BlockGroup
|
||||
{
|
||||
long blockStart = -1, blockEnd = -1;
|
||||
var reference = false;
|
||||
while (stream.Position < bodyEnd)
|
||||
{
|
||||
var (gid, gsize) = reader.Header();
|
||||
if (gid == 0xA1)
|
||||
{
|
||||
blockStart = stream.Position;
|
||||
blockEnd = Math.Min(blockStart + gsize, bodyEnd);
|
||||
}
|
||||
else if (gid == 0xFB)
|
||||
{
|
||||
reference = true;
|
||||
}
|
||||
|
||||
reader.Skip(gsize);
|
||||
}
|
||||
|
||||
if (blockStart >= 0)
|
||||
{
|
||||
AddBlock(reader, blockStart, blockEnd, clusterTime, simple: false, reference, state);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
stream.Position = bodyEnd;
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddBlock(Reader reader, long start, long end, long clusterTime, bool simple, bool hasReference, State state)
|
||||
{
|
||||
var stream = reader.Stream;
|
||||
stream.Position = start;
|
||||
var track = (long)reader.VintValue();
|
||||
Span<byte> fixedPart = stackalloc byte[3];
|
||||
stream.ReadExactly(fixedPart);
|
||||
var relative = BinaryPrimitives.ReadInt16BigEndian(fixedPart);
|
||||
var flags = fixedPart[2];
|
||||
var key = simple ? (flags & 0x80) != 0 : !hasReference;
|
||||
var target = track == state.Video?.Number ? state.Video : track == state.Audio?.Number ? state.Audio : null;
|
||||
if (target is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.Samples.Count >= MaxSamples)
|
||||
{
|
||||
throw new ContainerException("Troppi campioni.");
|
||||
}
|
||||
|
||||
var time = clusterTime + relative;
|
||||
var lacing = (flags >> 1) & 3;
|
||||
var dataStart = stream.Position;
|
||||
if (lacing == 0)
|
||||
{
|
||||
target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key));
|
||||
return;
|
||||
}
|
||||
|
||||
var frames = stream.ReadByte() + 1;
|
||||
var sizes = new long[frames];
|
||||
switch (lacing)
|
||||
{
|
||||
case 1: // Xiph
|
||||
for (var i = 0; i < frames - 1; i++)
|
||||
{
|
||||
long value = 0;
|
||||
int b;
|
||||
do
|
||||
{
|
||||
b = stream.ReadByte();
|
||||
if (b < 0)
|
||||
{
|
||||
throw new ContainerException("Blocco Matroska troncato.");
|
||||
}
|
||||
|
||||
value += b;
|
||||
}
|
||||
while (b == 255);
|
||||
sizes[i] = value;
|
||||
}
|
||||
|
||||
break;
|
||||
case 3: // EBML
|
||||
{
|
||||
sizes[0] = (long)reader.VintValue();
|
||||
for (var i = 1; i < frames - 1; i++)
|
||||
{
|
||||
var (raw, length) = reader.VintRaw();
|
||||
var bias = (1L << ((7 * length) - 1)) - 1;
|
||||
sizes[i] = sizes[i - 1] + ((long)raw - bias);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var dataBegin = stream.Position;
|
||||
var total = end - dataBegin;
|
||||
if (lacing == 2)
|
||||
{
|
||||
for (var i = 0; i < frames; i++)
|
||||
{
|
||||
sizes[i] = total / frames;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
long used = 0;
|
||||
for (var i = 0; i < frames - 1; i++)
|
||||
{
|
||||
used += sizes[i];
|
||||
}
|
||||
|
||||
sizes[frames - 1] = total - used;
|
||||
}
|
||||
|
||||
var offset = dataBegin;
|
||||
var frameDuration = target.DefaultDuration > 0 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0;
|
||||
for (var i = 0; i < frames; i++)
|
||||
{
|
||||
if (sizes[i] < 0 || offset + sizes[i] > end)
|
||||
{
|
||||
throw new ContainerException("Blocco Matroska danneggiato.");
|
||||
}
|
||||
|
||||
var t = time + (i * frameDuration);
|
||||
target.Samples.Add(new MediaSample(offset, (int)sizes[i], t, t, key));
|
||||
offset += sizes[i];
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TrackEntry
|
||||
{
|
||||
internal long Number = -1;
|
||||
internal int Type;
|
||||
internal string CodecId = string.Empty;
|
||||
internal byte[]? CodecPrivate;
|
||||
internal long DefaultDuration;
|
||||
internal int Width;
|
||||
internal int Height;
|
||||
internal double Roll;
|
||||
internal int SampleRate;
|
||||
internal int Channels;
|
||||
internal readonly List<MediaSample> Samples = [];
|
||||
}
|
||||
|
||||
private sealed class State
|
||||
{
|
||||
internal long TimecodeScale = 1_000_000;
|
||||
internal double DurationTicks;
|
||||
internal DateTimeOffset? Created;
|
||||
internal TrackEntry? Video;
|
||||
internal TrackEntry? Audio;
|
||||
|
||||
internal MediaContainer Build()
|
||||
{
|
||||
var timescale = Math.Max(1, 1_000_000_000L / Math.Max(1, TimecodeScale));
|
||||
VideoTrack? video = null;
|
||||
if (Video is { } v)
|
||||
{
|
||||
var samples = v.Samples;
|
||||
if (samples.Count > 0)
|
||||
{
|
||||
// Blocks carry presentation times in decoding order; decoding times are those times sorted.
|
||||
var times = new long[samples.Count];
|
||||
for (var i = 0; i < times.Length; i++)
|
||||
{
|
||||
times[i] = samples[i].PresentationTime;
|
||||
}
|
||||
|
||||
Array.Sort(times);
|
||||
for (var i = 0; i < times.Length; i++)
|
||||
{
|
||||
samples[i] = samples[i] with { DecodeTime = times[i] };
|
||||
}
|
||||
}
|
||||
|
||||
var roll = ((int)Math.Round(-v.Roll) % 360 + 360) % 360;
|
||||
video = new VideoTrack
|
||||
{
|
||||
Codec = v.CodecId switch
|
||||
{
|
||||
"V_MPEG4/ISO/AVC" => VideoCodec.H264,
|
||||
"V_MPEGH/ISO/HEVC" => VideoCodec.Hevc,
|
||||
"V_VP8" => VideoCodec.Vp8,
|
||||
"V_VP9" => VideoCodec.Vp9,
|
||||
"V_AV1" => VideoCodec.Av1,
|
||||
"V_MJPEG" => VideoCodec.Mjpeg,
|
||||
_ when v.CodecId.StartsWith("V_MPEG4/ISO/", StringComparison.Ordinal) => VideoCodec.Mpeg4Part2,
|
||||
_ => VideoCodec.Unknown,
|
||||
},
|
||||
CodecTag = v.CodecId,
|
||||
Width = v.Width,
|
||||
Height = v.Height,
|
||||
Rotation = roll is 90 or 180 or 270 ? roll : 0,
|
||||
AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null,
|
||||
Timescale = timescale,
|
||||
Duration = (long)DurationTicks,
|
||||
Samples = samples,
|
||||
};
|
||||
}
|
||||
|
||||
AudioTrack? audio = null;
|
||||
if (Audio is { } a)
|
||||
{
|
||||
audio = new AudioTrack
|
||||
{
|
||||
Codec = a.CodecId switch
|
||||
{
|
||||
_ when a.CodecId.StartsWith("A_AAC", StringComparison.Ordinal) => AudioCodec.Aac,
|
||||
"A_MPEG/L3" => AudioCodec.Mp3,
|
||||
"A_OPUS" => AudioCodec.Opus,
|
||||
"A_VORBIS" => AudioCodec.Vorbis,
|
||||
_ when a.CodecId.StartsWith("A_PCM", StringComparison.Ordinal) => AudioCodec.Pcm,
|
||||
_ => AudioCodec.Unknown,
|
||||
},
|
||||
CodecTag = a.CodecId,
|
||||
SampleRate = a.SampleRate,
|
||||
Channels = a.Channels,
|
||||
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
|
||||
Timescale = timescale,
|
||||
Duration = (long)DurationTicks,
|
||||
Samples = a.Samples,
|
||||
};
|
||||
}
|
||||
|
||||
TimeSpan? duration = DurationTicks > 0 ? TimeSpan.FromSeconds(DurationTicks * TimecodeScale / 1e9) : null;
|
||||
return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>EBML primitives over the stream.</summary>
|
||||
private sealed class Reader(Stream stream)
|
||||
{
|
||||
internal Stream Stream => stream;
|
||||
|
||||
internal (uint Id, long Size) Header()
|
||||
{
|
||||
var first = stream.ReadByte();
|
||||
if (first <= 0)
|
||||
{
|
||||
throw new ContainerException("Elemento EBML non valido.");
|
||||
}
|
||||
|
||||
var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24);
|
||||
if (length > 4)
|
||||
{
|
||||
throw new ContainerException("Identificatore EBML non valido.");
|
||||
}
|
||||
|
||||
var id = (uint)first;
|
||||
for (var i = 1; i < length; i++)
|
||||
{
|
||||
id = (id << 8) | (uint)ReadByteOrThrow();
|
||||
}
|
||||
|
||||
var (raw, sizeLength) = VintRaw();
|
||||
var allOnes = (1UL << (7 * sizeLength)) - 1;
|
||||
return (id, raw == allOnes ? UnknownSize : (long)raw);
|
||||
}
|
||||
|
||||
internal (ulong Raw, int Length) VintRaw()
|
||||
{
|
||||
var first = ReadByteOrThrow();
|
||||
if (first == 0)
|
||||
{
|
||||
throw new ContainerException("Intero EBML non valido.");
|
||||
}
|
||||
|
||||
var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24);
|
||||
ulong value = (ulong)(first & (0xFF >> length));
|
||||
for (var i = 1; i < length; i++)
|
||||
{
|
||||
value = (value << 8) | (uint)ReadByteOrThrow();
|
||||
}
|
||||
|
||||
return (value, length);
|
||||
}
|
||||
|
||||
internal ulong VintValue() => VintRaw().Raw;
|
||||
|
||||
internal ulong Unsigned(long size)
|
||||
{
|
||||
if (size is < 0 or > 8)
|
||||
{
|
||||
throw new ContainerException("Intero EBML troppo lungo.");
|
||||
}
|
||||
|
||||
ulong value = 0;
|
||||
for (var i = 0; i < size; i++)
|
||||
{
|
||||
value = (value << 8) | (uint)ReadByteOrThrow();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
internal long Signed(long size)
|
||||
{
|
||||
var value = Unsigned(size);
|
||||
if (size is > 0 and < 8 && (value & (1UL << (int)((size * 8) - 1))) != 0)
|
||||
{
|
||||
value |= ulong.MaxValue << (int)(size * 8);
|
||||
}
|
||||
|
||||
return (long)value;
|
||||
}
|
||||
|
||||
internal double Float(long size)
|
||||
{
|
||||
Span<byte> buffer = stackalloc byte[8];
|
||||
if (size == 4)
|
||||
{
|
||||
stream.ReadExactly(buffer[..4]);
|
||||
return BinaryPrimitives.ReadSingleBigEndian(buffer);
|
||||
}
|
||||
|
||||
if (size == 8)
|
||||
{
|
||||
stream.ReadExactly(buffer);
|
||||
return BinaryPrimitives.ReadDoubleBigEndian(buffer);
|
||||
}
|
||||
|
||||
Skip(size);
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal string String(long size) => Encoding.UTF8.GetString(Bytes(size)).TrimEnd('\0');
|
||||
|
||||
internal byte[] Bytes(long size)
|
||||
{
|
||||
if (size < 0 || size > MaxElementInMemory)
|
||||
{
|
||||
throw new ContainerException("Elemento Matroska troppo grande.");
|
||||
}
|
||||
|
||||
var data = new byte[size];
|
||||
stream.ReadExactly(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
internal void Skip(long size)
|
||||
{
|
||||
if (size < 0)
|
||||
{
|
||||
throw new ContainerException("Elemento Matroska di lunghezza ignota.");
|
||||
}
|
||||
|
||||
stream.Position += size;
|
||||
}
|
||||
|
||||
private int ReadByteOrThrow()
|
||||
{
|
||||
var b = stream.ReadByte();
|
||||
return b < 0 ? throw new ContainerException("File Matroska troncato.") : b;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>The container formats Febe reads without external programs.</summary>
|
||||
public enum ContainerFormat
|
||||
{
|
||||
/// <summary>ISO base media file format: MP4, MOV, 3GP, M4V (also fragmented).</summary>
|
||||
IsoBmff,
|
||||
|
||||
/// <summary>Matroska and WebM.</summary>
|
||||
Matroska,
|
||||
|
||||
/// <summary>RIFF AVI (also OpenDML).</summary>
|
||||
Avi,
|
||||
}
|
||||
|
||||
/// <summary>Video codecs recognised in a container; only <see cref="H264"/> can be decoded.</summary>
|
||||
public enum VideoCodec
|
||||
{
|
||||
Unknown,
|
||||
H264,
|
||||
Hevc,
|
||||
Vp8,
|
||||
Vp9,
|
||||
Av1,
|
||||
Mpeg4Part2,
|
||||
Mjpeg,
|
||||
}
|
||||
|
||||
/// <summary>Audio codecs recognised in a container.</summary>
|
||||
public enum AudioCodec
|
||||
{
|
||||
Unknown,
|
||||
Aac,
|
||||
Mp3,
|
||||
Opus,
|
||||
Vorbis,
|
||||
Pcm,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One sample (an access unit) of a track: where its bytes are in the file and when it is decoded and shown, in units of
|
||||
/// the track's <see cref="MediaTrack.Timescale"/>. Samples are listed in decoding order.
|
||||
/// </summary>
|
||||
public readonly record struct MediaSample(long Offset, int Size, long DecodeTime, long PresentationTime, bool Key);
|
||||
|
||||
/// <summary>A track of a container.</summary>
|
||||
public abstract class MediaTrack
|
||||
{
|
||||
/// <summary>Ticks per second of the sample times.</summary>
|
||||
public long Timescale { get; init; } = 1000;
|
||||
|
||||
/// <summary>Duration of the track in <see cref="Timescale"/> units; 0 when unknown.</summary>
|
||||
public long Duration { get; init; }
|
||||
|
||||
/// <summary>Samples in decoding order (empty when the container was read for its metadata only).</summary>
|
||||
public IReadOnlyList<MediaSample> Samples { get; init; } = [];
|
||||
|
||||
/// <summary>The four-character code or codec identifier of the container, for messages.</summary>
|
||||
public string CodecTag { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>Time in seconds of a value in track units.</summary>
|
||||
public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0;
|
||||
}
|
||||
|
||||
/// <summary>The video track of a container.</summary>
|
||||
public sealed class VideoTrack : MediaTrack
|
||||
{
|
||||
public VideoCodec Codec { get; init; }
|
||||
|
||||
/// <summary>Coded width in pixels (before rotation).</summary>
|
||||
public int Width { get; init; }
|
||||
|
||||
/// <summary>Coded height in pixels (before rotation).</summary>
|
||||
public int Height { get; init; }
|
||||
|
||||
/// <summary>Clockwise rotation to apply when showing the frames: 0, 90, 180 or 270.</summary>
|
||||
public int Rotation { get; init; }
|
||||
|
||||
/// <summary>The AVCDecoderConfigurationRecord (<c>avcC</c>) of an H.264 track stored with length prefixes.</summary>
|
||||
public byte[]? AvcConfiguration { get; init; }
|
||||
|
||||
/// <summary>True when the samples are an Annex B byte stream (start codes), as in AVI.</summary>
|
||||
public bool AnnexB { get; init; }
|
||||
|
||||
/// <summary>Width as shown (rotation applied).</summary>
|
||||
public int DisplayWidth => Rotation % 180 == 0 ? Width : Height;
|
||||
|
||||
/// <summary>Height as shown (rotation applied).</summary>
|
||||
public int DisplayHeight => Rotation % 180 == 0 ? Height : Width;
|
||||
}
|
||||
|
||||
/// <summary>The audio track of a container.</summary>
|
||||
public sealed class AudioTrack : MediaTrack
|
||||
{
|
||||
public AudioCodec Codec { get; init; }
|
||||
|
||||
public int SampleRate { get; init; }
|
||||
|
||||
public int Channels { get; init; }
|
||||
|
||||
/// <summary>The AudioSpecificConfig of an AAC track.</summary>
|
||||
public byte[]? AacConfiguration { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>What a container says: its creation time, duration and first video and audio tracks.</summary>
|
||||
public sealed class MediaContainer
|
||||
{
|
||||
public ContainerFormat Format { get; init; }
|
||||
|
||||
/// <summary>Creation time written in the container, when plausible.</summary>
|
||||
public DateTimeOffset? CreatedAt { get; init; }
|
||||
|
||||
/// <summary>Duration of the whole presentation.</summary>
|
||||
public TimeSpan? Duration { get; init; }
|
||||
|
||||
public VideoTrack? Video { get; init; }
|
||||
|
||||
public AudioTrack? Audio { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A container that cannot be read: damaged, truncated or of a shape Febe does not handle.</summary>
|
||||
public sealed class ContainerException(string message) : Exception(message);
|
||||
@@ -0,0 +1,643 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>A sample to write: its size, its times in track units, whether it is a sync sample.</summary>
|
||||
public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key);
|
||||
|
||||
/// <summary>A track to write: H.264 video (with its <c>avcC</c>) or AAC audio (with its AudioSpecificConfig).</summary>
|
||||
public sealed class Mp4OutputTrack
|
||||
{
|
||||
public required bool IsVideo { get; init; }
|
||||
|
||||
public required long Timescale { get; init; }
|
||||
|
||||
public required IReadOnlyList<Mp4OutputSample> Samples { get; init; }
|
||||
|
||||
/// <summary>Writes the bytes of sample <c>i</c> (exactly its <see cref="Mp4OutputSample.Size"/>) into the stream.</summary>
|
||||
public required Action<int, Stream> WriteSample { get; init; }
|
||||
|
||||
public int Width { get; init; }
|
||||
|
||||
public int Height { get; init; }
|
||||
|
||||
/// <summary>Clockwise rotation written in the track matrix: 0, 90, 180 or 270.</summary>
|
||||
public int Rotation { get; init; }
|
||||
|
||||
public byte[]? AvcConfiguration { get; init; }
|
||||
|
||||
public byte[]? AacConfiguration { get; init; }
|
||||
|
||||
public int SampleRate { get; init; }
|
||||
|
||||
public int Channels { get; init; }
|
||||
|
||||
/// <summary>Duration of the last sample, when the times cannot tell it (0: as the one before it).</summary>
|
||||
public long LastSampleDuration { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writer of MP4 files (ISO/IEC 14496-12 and 14496-14/15), written from the standards: <c>ftyp</c>, then the
|
||||
/// <c>moov</c> box (so the file plays while it downloads), then one <c>mdat</c> with the tracks interleaved about every
|
||||
/// half second.
|
||||
/// </summary>
|
||||
public static class Mp4Writer
|
||||
{
|
||||
private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
private const int MovieTimescale = 1000;
|
||||
|
||||
/// <summary>Writes the tracks into <paramref name="output"/> (from its current position).</summary>
|
||||
public static void Write(Stream output, IReadOnlyList<Mp4OutputTrack> tracks, DateTimeOffset? created = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
ArgumentNullException.ThrowIfNull(tracks);
|
||||
if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0))
|
||||
{
|
||||
throw new ArgumentException("Servono tracce con campioni.", nameof(tracks));
|
||||
}
|
||||
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
if (track.IsVideo ? track.AvcConfiguration is null : track.AacConfiguration is null)
|
||||
{
|
||||
throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks));
|
||||
}
|
||||
}
|
||||
|
||||
var timing = tracks.Select(Timing.Of).ToArray();
|
||||
var chunks = Interleave(tracks);
|
||||
long payload = 0;
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
foreach (var s in track.Samples)
|
||||
{
|
||||
payload += s.Size;
|
||||
}
|
||||
}
|
||||
|
||||
var wideMdat = payload + 8 > uint.MaxValue;
|
||||
var ftyp = Ftyp();
|
||||
var time = created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL;
|
||||
|
||||
// The moov box has the same size whatever the chunk offsets: build it once to know where the data starts.
|
||||
var co64 = false;
|
||||
var moov = Moov(tracks, timing, chunks, new long[chunks.Count], co64, time);
|
||||
var dataStart = ftyp.Length + moov.Length + (wideMdat ? 16 : 8);
|
||||
if (dataStart + payload > uint.MaxValue)
|
||||
{
|
||||
co64 = true;
|
||||
moov = Moov(tracks, timing, chunks, new long[chunks.Count], co64, time);
|
||||
dataStart = ftyp.Length + moov.Length + (wideMdat ? 16 : 8);
|
||||
}
|
||||
|
||||
var offsets = new long[chunks.Count];
|
||||
var position = (long)dataStart;
|
||||
for (var i = 0; i < chunks.Count; i++)
|
||||
{
|
||||
offsets[i] = position;
|
||||
var (track, first, count) = chunks[i];
|
||||
for (var k = first; k < first + count; k++)
|
||||
{
|
||||
position += tracks[track].Samples[k].Size;
|
||||
}
|
||||
}
|
||||
|
||||
moov = Moov(tracks, timing, chunks, offsets, co64, time);
|
||||
output.Write(ftyp);
|
||||
output.Write(moov);
|
||||
Span<byte> header = stackalloc byte[16];
|
||||
if (wideMdat)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32BigEndian(header, 1);
|
||||
"mdat"u8.CopyTo(header[4..]);
|
||||
BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16));
|
||||
output.Write(header);
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8));
|
||||
"mdat"u8.CopyTo(header[4..]);
|
||||
output.Write(header[..8]);
|
||||
}
|
||||
|
||||
foreach (var (track, first, count) in chunks)
|
||||
{
|
||||
for (var k = first; k < first + count; k++)
|
||||
{
|
||||
var before = output.CanSeek ? output.Position : -1;
|
||||
tracks[track].WriteSample(k, output);
|
||||
if (before >= 0 && output.Position - before != tracks[track].Samples[k].Size)
|
||||
{
|
||||
throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Times of a track as the boxes need them.</summary>
|
||||
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey)
|
||||
{
|
||||
internal static Timing Of(Mp4OutputTrack track)
|
||||
{
|
||||
var samples = track.Samples;
|
||||
var n = samples.Count;
|
||||
var durations = new long[n];
|
||||
for (var i = 0; i < n - 1; i++)
|
||||
{
|
||||
durations[i] = Math.Max(0, samples[i + 1].DecodeTime - samples[i].DecodeTime);
|
||||
}
|
||||
|
||||
durations[n - 1] = track.LastSampleDuration > 0 ? track.LastSampleDuration : n > 1 ? durations[n - 2] : 1;
|
||||
|
||||
// Decoding must not come after presentation: delay the decoding times when it would.
|
||||
long shift = 0;
|
||||
var minPts = long.MaxValue;
|
||||
foreach (var s in samples)
|
||||
{
|
||||
shift = Math.Max(shift, s.DecodeTime - s.PresentationTime);
|
||||
minPts = Math.Min(minPts, s.PresentationTime);
|
||||
}
|
||||
|
||||
var first = samples[0].DecodeTime;
|
||||
var offsets = new int[n];
|
||||
var allKey = true;
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
offsets[i] = (int)Math.Clamp(samples[i].PresentationTime - samples[i].DecodeTime + shift, 0, int.MaxValue);
|
||||
allKey &= samples[i].Key;
|
||||
}
|
||||
|
||||
long total = 0;
|
||||
foreach (var d in durations)
|
||||
{
|
||||
total += d;
|
||||
}
|
||||
|
||||
// The edit list starts the presentation at the first shown sample.
|
||||
var editTime = minPts - first + shift;
|
||||
return new Timing(durations, offsets, total, editTime, allKey);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<(int Track, int First, int Count)> Interleave(IReadOnlyList<Mp4OutputTrack> tracks)
|
||||
{
|
||||
var list = new List<(int Track, int First, int Count, double Start)>();
|
||||
for (var t = 0; t < tracks.Count; t++)
|
||||
{
|
||||
var track = tracks[t];
|
||||
var samples = track.Samples;
|
||||
var first = 0;
|
||||
var limit = track.Timescale / 2;
|
||||
for (var i = 1; i <= samples.Count; i++)
|
||||
{
|
||||
if (i == samples.Count || samples[i].DecodeTime - samples[first].DecodeTime >= limit || i - first >= 1024)
|
||||
{
|
||||
list.Add((t, first, i - first, (double)(samples[first].DecodeTime - samples[0].DecodeTime) / track.Timescale));
|
||||
first = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
list.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : a.Track.CompareTo(b.Track));
|
||||
return list.ConvertAll(c => (c.Track, c.First, c.Count));
|
||||
}
|
||||
|
||||
private static byte[] Ftyp()
|
||||
{
|
||||
var box = new Box("ftyp");
|
||||
box.Bytes("isom"u8);
|
||||
box.U32(512);
|
||||
box.Bytes("isomiso2avc1mp41"u8);
|
||||
return box.ToArray();
|
||||
}
|
||||
|
||||
private static byte[] Moov(IReadOnlyList<Mp4OutputTrack> tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time)
|
||||
{
|
||||
long movieDuration = 0;
|
||||
for (var t = 0; t < tracks.Count; t++)
|
||||
{
|
||||
movieDuration = Math.Max(movieDuration, ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale));
|
||||
}
|
||||
|
||||
var moov = new Box("moov");
|
||||
var mvhd = new Box("mvhd");
|
||||
var wide = movieDuration > uint.MaxValue || time > uint.MaxValue;
|
||||
mvhd.U32(wide ? 0x01000000u : 0);
|
||||
Times(mvhd, wide, time, MovieTimescale, movieDuration);
|
||||
mvhd.U32(0x00010000);
|
||||
mvhd.U16(0x0100);
|
||||
mvhd.Zero(10);
|
||||
Matrix(mvhd, 0, 0, 0);
|
||||
mvhd.Zero(24);
|
||||
mvhd.U32((uint)tracks.Count + 1);
|
||||
moov.Child(mvhd);
|
||||
|
||||
for (var t = 0; t < tracks.Count; t++)
|
||||
{
|
||||
moov.Child(Trak(tracks[t], timing[t], t, chunks, offsets, co64, time));
|
||||
}
|
||||
|
||||
return moov.ToArray();
|
||||
}
|
||||
|
||||
private static long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale);
|
||||
|
||||
private static void Times(Box box, bool wide, ulong time, long timescale, long duration)
|
||||
{
|
||||
if (wide)
|
||||
{
|
||||
box.U64(time);
|
||||
box.U64(time);
|
||||
box.U32((uint)timescale);
|
||||
box.U64((ulong)duration);
|
||||
}
|
||||
else
|
||||
{
|
||||
box.U32((uint)time);
|
||||
box.U32((uint)time);
|
||||
box.U32((uint)timescale);
|
||||
box.U32((uint)duration);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Matrix(Box box, int rotation, int width, int height)
|
||||
{
|
||||
int a = 0x10000, b = 0, c = 0, d = 0x10000, x = 0, y = 0;
|
||||
switch (rotation)
|
||||
{
|
||||
case 90:
|
||||
(a, b, c, d, x) = (0, 0x10000, -0x10000, 0, height << 16);
|
||||
break;
|
||||
case 180:
|
||||
(a, d, x, y) = (-0x10000, -0x10000, width << 16, height << 16);
|
||||
break;
|
||||
case 270:
|
||||
(a, b, c, d, y) = (0, -0x10000, 0x10000, 0, width << 16);
|
||||
break;
|
||||
}
|
||||
|
||||
foreach (var v in new[] { a, b, 0, c, d, 0, x, y, 0x40000000 })
|
||||
{
|
||||
box.U32((uint)v);
|
||||
}
|
||||
}
|
||||
|
||||
private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time)
|
||||
{
|
||||
var trak = new Box("trak");
|
||||
var duration = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale);
|
||||
var wide = duration > uint.MaxValue || time > uint.MaxValue;
|
||||
var tkhd = new Box("tkhd");
|
||||
tkhd.U32((wide ? 0x01000000u : 0) | 3);
|
||||
if (wide)
|
||||
{
|
||||
tkhd.U64(time);
|
||||
tkhd.U64(time);
|
||||
tkhd.U32((uint)index + 1);
|
||||
tkhd.U32(0);
|
||||
tkhd.U64((ulong)duration);
|
||||
}
|
||||
else
|
||||
{
|
||||
tkhd.U32((uint)time);
|
||||
tkhd.U32((uint)time);
|
||||
tkhd.U32((uint)index + 1);
|
||||
tkhd.U32(0);
|
||||
tkhd.U32((uint)duration);
|
||||
}
|
||||
|
||||
tkhd.Zero(8);
|
||||
tkhd.U16(0);
|
||||
tkhd.U16(0);
|
||||
tkhd.U16(track.IsVideo ? (ushort)0 : (ushort)0x0100);
|
||||
tkhd.U16(0);
|
||||
Matrix(tkhd, track.IsVideo ? track.Rotation : 0, track.Width, track.Height);
|
||||
tkhd.U32(track.IsVideo ? (uint)track.Width << 16 : 0);
|
||||
tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0);
|
||||
trak.Child(tkhd);
|
||||
|
||||
if (timing.EditMediaTime != 0)
|
||||
{
|
||||
var edts = new Box("edts");
|
||||
var elst = new Box("elst");
|
||||
elst.U32(0x01000000);
|
||||
elst.U32(1);
|
||||
elst.U64((ulong)duration);
|
||||
elst.U64((ulong)timing.EditMediaTime);
|
||||
elst.U16(1);
|
||||
elst.U16(0);
|
||||
edts.Child(elst);
|
||||
trak.Child(edts);
|
||||
}
|
||||
|
||||
var mdia = new Box("mdia");
|
||||
var mdhd = new Box("mdhd");
|
||||
var mediaWide = timing.MediaDuration > uint.MaxValue || time > uint.MaxValue;
|
||||
mdhd.U32(mediaWide ? 0x01000000u : 0);
|
||||
Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration);
|
||||
mdhd.U16(0x55C4); // «und»
|
||||
mdhd.U16(0);
|
||||
mdia.Child(mdhd);
|
||||
|
||||
var hdlr = new Box("hdlr");
|
||||
hdlr.U32(0);
|
||||
hdlr.U32(0);
|
||||
hdlr.Bytes(track.IsVideo ? "vide"u8 : "soun"u8);
|
||||
hdlr.Zero(12);
|
||||
hdlr.Bytes(track.IsVideo ? "VideoHandler\0"u8 : "SoundHandler\0"u8);
|
||||
mdia.Child(hdlr);
|
||||
|
||||
var minf = new Box("minf");
|
||||
if (track.IsVideo)
|
||||
{
|
||||
var vmhd = new Box("vmhd");
|
||||
vmhd.U32(1);
|
||||
vmhd.Zero(8);
|
||||
minf.Child(vmhd);
|
||||
}
|
||||
else
|
||||
{
|
||||
var smhd = new Box("smhd");
|
||||
smhd.U32(0);
|
||||
smhd.Zero(4);
|
||||
minf.Child(smhd);
|
||||
}
|
||||
|
||||
var dinf = new Box("dinf");
|
||||
var dref = new Box("dref");
|
||||
dref.U32(0);
|
||||
dref.U32(1);
|
||||
var url = new Box("url ");
|
||||
url.U32(1);
|
||||
dref.Child(url);
|
||||
dinf.Child(dref);
|
||||
minf.Child(dinf);
|
||||
minf.Child(Stbl(track, timing, index, chunks, offsets, co64));
|
||||
mdia.Child(minf);
|
||||
trak.Child(mdia);
|
||||
return trak;
|
||||
}
|
||||
|
||||
private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64)
|
||||
{
|
||||
var stbl = new Box("stbl");
|
||||
var stsd = new Box("stsd");
|
||||
stsd.U32(0);
|
||||
stsd.U32(1);
|
||||
stsd.Child(track.IsVideo ? Avc1(track) : Mp4a(track));
|
||||
stbl.Child(stsd);
|
||||
|
||||
// stts: runs of equal durations.
|
||||
var stts = new Box("stts");
|
||||
var runs = new List<(int Count, long Delta)>();
|
||||
foreach (var d in timing.Durations)
|
||||
{
|
||||
if (runs.Count > 0 && runs[^1].Delta == d)
|
||||
{
|
||||
runs[^1] = (runs[^1].Count + 1, d);
|
||||
}
|
||||
else
|
||||
{
|
||||
runs.Add((1, d));
|
||||
}
|
||||
}
|
||||
|
||||
stts.U32(0);
|
||||
stts.U32((uint)runs.Count);
|
||||
foreach (var (count, delta) in runs)
|
||||
{
|
||||
stts.U32((uint)count);
|
||||
stts.U32((uint)delta);
|
||||
}
|
||||
|
||||
stbl.Child(stts);
|
||||
|
||||
var anyOffset = false;
|
||||
foreach (var o in timing.CompositionOffsets)
|
||||
{
|
||||
anyOffset |= o != 0;
|
||||
}
|
||||
|
||||
if (anyOffset)
|
||||
{
|
||||
var ctts = new Box("ctts");
|
||||
var cruns = new List<(int Count, int Offset)>();
|
||||
foreach (var o in timing.CompositionOffsets)
|
||||
{
|
||||
if (cruns.Count > 0 && cruns[^1].Offset == o)
|
||||
{
|
||||
cruns[^1] = (cruns[^1].Count + 1, o);
|
||||
}
|
||||
else
|
||||
{
|
||||
cruns.Add((1, o));
|
||||
}
|
||||
}
|
||||
|
||||
ctts.U32(0);
|
||||
ctts.U32((uint)cruns.Count);
|
||||
foreach (var (count, offset) in cruns)
|
||||
{
|
||||
ctts.U32((uint)count);
|
||||
ctts.U32((uint)offset);
|
||||
}
|
||||
|
||||
stbl.Child(ctts);
|
||||
}
|
||||
|
||||
if (track.IsVideo && !timing.AllKey)
|
||||
{
|
||||
var stss = new Box("stss");
|
||||
var keys = new List<int>();
|
||||
for (var i = 0; i < track.Samples.Count; i++)
|
||||
{
|
||||
if (track.Samples[i].Key)
|
||||
{
|
||||
keys.Add(i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
stss.U32(0);
|
||||
stss.U32((uint)keys.Count);
|
||||
foreach (var k in keys)
|
||||
{
|
||||
stss.U32((uint)k);
|
||||
}
|
||||
|
||||
stbl.Child(stss);
|
||||
}
|
||||
|
||||
// stsc and the chunk offsets of this track, in file order.
|
||||
var stsc = new Box("stsc");
|
||||
var entries = new List<(int FirstChunk, int PerChunk)>();
|
||||
var mine = new List<long>();
|
||||
for (var c = 0; c < chunks.Count; c++)
|
||||
{
|
||||
if (chunks[c].Track != index)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
mine.Add(offsets[c]);
|
||||
if (entries.Count == 0 || entries[^1].PerChunk != chunks[c].Count)
|
||||
{
|
||||
entries.Add((mine.Count, chunks[c].Count));
|
||||
}
|
||||
}
|
||||
|
||||
stsc.U32(0);
|
||||
stsc.U32((uint)entries.Count);
|
||||
foreach (var (firstChunk, perChunk) in entries)
|
||||
{
|
||||
stsc.U32((uint)firstChunk);
|
||||
stsc.U32((uint)perChunk);
|
||||
stsc.U32(1);
|
||||
}
|
||||
|
||||
stbl.Child(stsc);
|
||||
|
||||
var stsz = new Box("stsz");
|
||||
stsz.U32(0);
|
||||
stsz.U32(0);
|
||||
stsz.U32((uint)track.Samples.Count);
|
||||
foreach (var s in track.Samples)
|
||||
{
|
||||
stsz.U32((uint)s.Size);
|
||||
}
|
||||
|
||||
stbl.Child(stsz);
|
||||
|
||||
var stco = new Box(co64 ? "co64" : "stco");
|
||||
stco.U32(0);
|
||||
stco.U32((uint)mine.Count);
|
||||
foreach (var o in mine)
|
||||
{
|
||||
if (co64)
|
||||
{
|
||||
stco.U64((ulong)o);
|
||||
}
|
||||
else
|
||||
{
|
||||
stco.U32((uint)o);
|
||||
}
|
||||
}
|
||||
|
||||
stbl.Child(stco);
|
||||
return stbl;
|
||||
}
|
||||
|
||||
private static Box Avc1(Mp4OutputTrack track)
|
||||
{
|
||||
var entry = new Box("avc1");
|
||||
entry.Zero(6);
|
||||
entry.U16(1);
|
||||
entry.Zero(16);
|
||||
entry.U16((ushort)track.Width);
|
||||
entry.U16((ushort)track.Height);
|
||||
entry.U32(0x00480000);
|
||||
entry.U32(0x00480000);
|
||||
entry.U32(0);
|
||||
entry.U16(1);
|
||||
entry.Zero(32);
|
||||
entry.U16(0x0018);
|
||||
entry.U16(0xFFFF);
|
||||
var avcC = new Box("avcC");
|
||||
avcC.Bytes(track.AvcConfiguration);
|
||||
entry.Child(avcC);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static Box Mp4a(Mp4OutputTrack track)
|
||||
{
|
||||
var entry = new Box("mp4a");
|
||||
entry.Zero(6);
|
||||
entry.U16(1);
|
||||
entry.Zero(8);
|
||||
entry.U16((ushort)Math.Max(1, track.Channels));
|
||||
entry.U16(16);
|
||||
entry.U16(0);
|
||||
entry.U16(0);
|
||||
entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16);
|
||||
|
||||
var asc = track.AacConfiguration!;
|
||||
var decoderSpecific = Descriptor(0x05, asc);
|
||||
var config = new byte[13 + decoderSpecific.Length];
|
||||
config[0] = 0x40; // MPEG-4 audio
|
||||
config[1] = 0x15; // audio stream
|
||||
decoderSpecific.CopyTo(config, 13);
|
||||
byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])];
|
||||
var esds = new Box("esds");
|
||||
esds.U32(0);
|
||||
esds.Bytes(Descriptor(0x03, es));
|
||||
entry.Child(esds);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static byte[] Descriptor(byte tag, ReadOnlySpan<byte> body)
|
||||
{
|
||||
var data = new byte[5 + body.Length];
|
||||
data[0] = tag;
|
||||
var length = body.Length;
|
||||
data[1] = (byte)(0x80 | ((length >> 21) & 0x7F));
|
||||
data[2] = (byte)(0x80 | ((length >> 14) & 0x7F));
|
||||
data[3] = (byte)(0x80 | ((length >> 7) & 0x7F));
|
||||
data[4] = (byte)(length & 0x7F);
|
||||
body.CopyTo(data.AsSpan(5));
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>A box being built in memory.</summary>
|
||||
private sealed class Box
|
||||
{
|
||||
private readonly MemoryStream body = new();
|
||||
|
||||
internal Box(string type) => Type = type;
|
||||
|
||||
internal string Type { get; }
|
||||
|
||||
internal void U16(ushort v)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[2];
|
||||
BinaryPrimitives.WriteUInt16BigEndian(b, v);
|
||||
body.Write(b);
|
||||
}
|
||||
|
||||
internal void U32(uint v)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteUInt32BigEndian(b, v);
|
||||
body.Write(b);
|
||||
}
|
||||
|
||||
internal void U64(ulong v)
|
||||
{
|
||||
Span<byte> b = stackalloc byte[8];
|
||||
BinaryPrimitives.WriteUInt64BigEndian(b, v);
|
||||
body.Write(b);
|
||||
}
|
||||
|
||||
internal void Zero(int count)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
body.WriteByte(0);
|
||||
}
|
||||
}
|
||||
|
||||
internal void Bytes(ReadOnlySpan<byte> data) => body.Write(data);
|
||||
|
||||
internal void Child(Box child) => body.Write(child.ToArray());
|
||||
|
||||
internal byte[] ToArray()
|
||||
{
|
||||
var size = body.Length + 8;
|
||||
var result = new byte[size];
|
||||
BinaryPrimitives.WriteUInt32BigEndian(result, (uint)size);
|
||||
Encoding.Latin1.GetBytes(Type, result.AsSpan(4, 4));
|
||||
body.Position = 0;
|
||||
body.ReadExactly(result, 8, (int)body.Length);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ internal sealed record ContentFacts(
|
||||
|
||||
/// <summary>
|
||||
/// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for
|
||||
/// photos, date from the metadata (EXIF for photos, <c>mvhd</c> for MP4/MOV, ffprobe as an extra for the rest).
|
||||
/// photos, date from the metadata (EXIF for photos, <c>mvhd</c> for MP4/MOV, the in-house container readers for WebM, Matroska and AVI).
|
||||
/// </summary>
|
||||
internal static class ContentAnalysis
|
||||
{
|
||||
@@ -123,8 +123,9 @@ internal static class ContentAnalysis
|
||||
}
|
||||
}
|
||||
|
||||
if (env.VideoProbe is { } probe && (created is null || duration is null || width is null))
|
||||
if (created is null || duration is null || width is null)
|
||||
{
|
||||
var probe = env.VideoProbe ?? new ContainerVideoMetadataProbe(env.Clock);
|
||||
var extra = await probe.ProbeAsync(fullPath, ct).ConfigureAwait(false);
|
||||
if (extra is not null)
|
||||
{
|
||||
|
||||
@@ -688,7 +688,7 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
return null;
|
||||
}
|
||||
|
||||
var frame = await env.Frames.ExtractJpegAsync(videoPath, ct).ConfigureAwait(false);
|
||||
var frame = await env.Frames.ExtractImageAsync(videoPath, ct).ConfigureAwait(false);
|
||||
return frame is null ? null : new MemoryStream(frame, writable: false);
|
||||
}
|
||||
|
||||
|
||||
@@ -33,10 +33,13 @@ public sealed record ImportEnvironment
|
||||
/// </summary>
|
||||
public PerceptualHashIndex? HashIndex { get; init; }
|
||||
|
||||
/// <summary>ffmpeg, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.</summary>
|
||||
public VideoFrameExtractor? Frames { get; init; }
|
||||
/// <summary>The in-house frame decoder, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.</summary>
|
||||
public VideoFrameDecoder? Frames { get; init; }
|
||||
|
||||
/// <summary>ffprobe, an optional extra for videos the hand-written reader does not cover.</summary>
|
||||
/// <summary>
|
||||
/// Reader of the metadata of videos the MP4 header reader does not cover (WebM, Matroska, AVI). Null: the in-house
|
||||
/// <see cref="ContainerVideoMetadataProbe"/> on the clock of this environment.
|
||||
/// </summary>
|
||||
public IVideoMetadataProbe? VideoProbe { get; init; }
|
||||
|
||||
/// <summary>«Imposta la data del file a quella di pubblicazione» (library setting).</summary>
|
||||
|
||||
@@ -21,8 +21,8 @@ var import = new ImportService(new ImportEnvironment
|
||||
Clock = clock,
|
||||
Thumbnails = new ThumbnailStore(data.Thumbnails),
|
||||
HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta
|
||||
Frames = VideoFrameExtractor.TryCreate(), // miniature dei video importati, se c'è ffmpeg
|
||||
VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), // facoltativo
|
||||
Frames = VideoFrameDecoder.Instance, // miniature dei video H.264 importati, decodificate in casa
|
||||
VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska e AVI (null: la stessa, predefinita)
|
||||
SetFileTimeToPublication = settings.SetFileTimeToPublication,
|
||||
Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder,
|
||||
DataFolder = data.Root,
|
||||
@@ -68,8 +68,8 @@ video), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, i
|
||||
probabile, tipo probabile e titolo della raccolta.
|
||||
|
||||
- **Data**, nell'ordine: nome del file (o `_febe.jsonl` di una libreria di Febe, data esatta), metadati (EXIF
|
||||
`DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; ffprobe
|
||||
solo come aggiunta per gli altri video), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora
|
||||
`DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; i lettori di
|
||||
contenitori scritti in casa per WebM, Matroska e AVI), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora
|
||||
dello stesso giorno, vince l'ora dei metadati. Le ore senza fuso sono quelle di Alberto (`IClock.LocalZone`).
|
||||
- **Cartelle** (`SourceLayout`): se la cartella scelta contiene solo cartelle di tipo (post, storie, evidenza,
|
||||
taggati, anni...) o solo file, è un account; altrimenti ogni sottocartella di primo livello è un'unità da associare a
|
||||
|
||||
@@ -1,192 +1,53 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Security;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
|
||||
namespace Febe.Core.Import;
|
||||
|
||||
/// <summary>Metadata of a video read by an external tool.</summary>
|
||||
/// <summary>Metadata of a video read from its container.</summary>
|
||||
public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height);
|
||||
|
||||
/// <summary>
|
||||
/// Reads creation time, duration and size of videos the hand-written reader does not cover (WebM, Matroska, AVI, ...).
|
||||
/// Optional: the analysis works without it (spec §9.2: «oppure si usa ffprobe dove è presente»).
|
||||
/// </summary>
|
||||
/// <summary>Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI).</summary>
|
||||
public interface IVideoMetadataProbe
|
||||
{
|
||||
/// <summary>Metadata of a video file, read-only; null when the tool cannot read it.</summary>
|
||||
/// <summary>Metadata of a video file, read-only; null when it cannot be read.</summary>
|
||||
Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IVideoMetadataProbe"/> with ffprobe, when installed (in Docker it comes with ffmpeg, §11). The output is
|
||||
/// parsed with <see cref="JsonDocument"/>; error output is never logged (it may contain paths).
|
||||
/// <see cref="IVideoMetadataProbe"/> written in house on the container readers of <see cref="ContainerReader"/>: no
|
||||
/// external program. Only the headers are read (no sample tables), so it is quick also on long videos.
|
||||
/// </summary>
|
||||
public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe
|
||||
public sealed class ContainerVideoMetadataProbe(IClock? clock = null) : IVideoMetadataProbe
|
||||
{
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(20);
|
||||
private readonly IClock _clock = clock ?? new SystemClock();
|
||||
|
||||
private FfprobeVideoMetadataProbe(string executable) => Executable = executable;
|
||||
|
||||
/// <summary>Full path of ffprobe.</summary>
|
||||
public string Executable { get; }
|
||||
|
||||
/// <summary>Finds ffprobe on the PATH (or at <paramref name="explicitPath"/>); null when it is not available.</summary>
|
||||
public static FfprobeVideoMetadataProbe? TryCreate(string? explicitPath = null)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(explicitPath))
|
||||
{
|
||||
return File.Exists(explicitPath) ? new FfprobeVideoMetadataProbe(Path.GetFullPath(explicitPath)) : null;
|
||||
}
|
||||
|
||||
var name = OperatingSystem.IsWindows() ? "ffprobe.exe" : "ffprobe";
|
||||
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
try
|
||||
{
|
||||
var candidate = Path.Combine(folder.Trim('"'), name);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return new FfprobeVideoMetadataProbe(candidate);
|
||||
}
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// A malformed PATH entry: skip it.
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The start of ffprobe for <paramref name="path"/>: its arguments, and the environment of Febe without
|
||||
/// <c>FEBE_PASSWORD</c> and <c>FEBE_CHIAVE_SESSIONE</c>, removed last (spec §13.2).
|
||||
/// </summary>
|
||||
internal ProcessStartInfo BuildStartInfo(string path)
|
||||
{
|
||||
var start = new ProcessStartInfo(Executable)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
};
|
||||
foreach (var argument in new[]
|
||||
{
|
||||
"-hide_banner", "-v", "error", "-print_format", "json",
|
||||
"-show_entries", "format=duration:format_tags=creation_time:stream=codec_type,width,height:stream_tags=rotate,creation_time",
|
||||
"-i", path,
|
||||
})
|
||||
{
|
||||
start.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
return start.WithoutSecrets();
|
||||
}
|
||||
|
||||
public async Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default)
|
||||
public Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
using var process = new Process { StartInfo = BuildStartInfo(path) };
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(Probe(path, _clock.Now));
|
||||
}
|
||||
|
||||
/// <summary>The metadata of <paramref name="path"/>; null when the file is unreadable or of another format.</summary>
|
||||
public static VideoMetadata? Probe(string path, DateTimeOffset now)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!process.Start())
|
||||
if (ContainerReader.ReadFile(path, now, samples: false) is not { } container)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var video = container.Video;
|
||||
int? width = video is { DisplayWidth: > 0 } ? video.DisplayWidth : null;
|
||||
int? height = video is { DisplayHeight: > 0 } ? video.DisplayHeight : null;
|
||||
var duration = container.Duration is { } d && d > TimeSpan.Zero ? d : (TimeSpan?)null;
|
||||
return new VideoMetadata(container.CreatedAt, duration, width, height);
|
||||
}
|
||||
catch (System.ComponentModel.Win32Exception)
|
||||
catch (Exception ex) when (ex is ContainerException or IOException or EndOfStreamException or UnauthorizedAccessException
|
||||
or ArgumentException or OverflowException or InvalidDataException)
|
||||
{
|
||||
return null;
|
||||
return null; // a damaged or unreadable file: as if the container had nothing to say
|
||||
}
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(Timeout);
|
||||
string output;
|
||||
try
|
||||
{
|
||||
var read = process.StandardOutput.ReadToEndAsync(timeout.Token);
|
||||
var drain = process.StandardError.ReadToEndAsync(timeout.Token);
|
||||
await Task.WhenAll(read, drain).ConfigureAwait(false);
|
||||
await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false);
|
||||
output = read.Result;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
try
|
||||
{
|
||||
process.Kill(entireProcessTree: true);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return null;
|
||||
}
|
||||
|
||||
return process.ExitCode == 0 ? Parse(output) : null;
|
||||
}
|
||||
|
||||
/// <summary>Parses the JSON printed by ffprobe.</summary>
|
||||
internal static VideoMetadata? Parse(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
DateTimeOffset? created = null;
|
||||
TimeSpan? duration = null;
|
||||
int? width = null, height = null;
|
||||
if (root.TryGetProperty("format", out var format))
|
||||
{
|
||||
if (format.TryGetProperty("duration", out var d) && d.ValueKind == JsonValueKind.String
|
||||
&& double.TryParse(d.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var seconds) && seconds > 0)
|
||||
{
|
||||
duration = TimeSpan.FromSeconds(seconds);
|
||||
}
|
||||
|
||||
created = CreationTime(format);
|
||||
}
|
||||
|
||||
if (root.TryGetProperty("streams", out var streams) && streams.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var stream in streams.EnumerateArray())
|
||||
{
|
||||
if (stream.TryGetProperty("codec_type", out var type) && type.ValueKind == JsonValueKind.String && type.GetString() == "video"
|
||||
&& stream.TryGetProperty("width", out var w) && w.TryGetInt32(out var wv) && wv > 0
|
||||
&& stream.TryGetProperty("height", out var h) && h.TryGetInt32(out var hv) && hv > 0)
|
||||
{
|
||||
var rotate = stream.TryGetProperty("tags", out var tags) && tags.TryGetProperty("rotate", out var r)
|
||||
&& int.TryParse(r.ValueKind == JsonValueKind.String ? r.GetString() : r.GetRawText(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var degrees)
|
||||
? Math.Abs(degrees) % 180
|
||||
: 0;
|
||||
(width, height) = rotate == 90 ? (hv, wv) : (wv, hv);
|
||||
created ??= CreationTime(stream);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new VideoMetadata(created, duration, width, height);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidOperationException or FormatException)
|
||||
{
|
||||
return null; // an unexpected shape: as if ffprobe had nothing to say
|
||||
}
|
||||
}
|
||||
|
||||
private static DateTimeOffset? CreationTime(JsonElement element)
|
||||
{
|
||||
if (element.TryGetProperty("tags", out var tags) && tags.ValueKind == JsonValueKind.Object
|
||||
&& tags.TryGetProperty("creation_time", out var value) && value.ValueKind == JsonValueKind.String
|
||||
&& DateTimeOffset.TryParse(value.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var instant)
|
||||
&& instant.Year >= 1995)
|
||||
{
|
||||
return instant.ToUniversalTime();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ public sealed record RebuildOptions
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> ExtraAccountFolders { get; init; } = [];
|
||||
|
||||
/// <summary>Create missing thumbnails (photos; videos with ffmpeg when available).</summary>
|
||||
/// <summary>Create missing thumbnails (photos; H.264 videos with the in-house frame decoder).</summary>
|
||||
public bool CreateThumbnails { get; init; } = true;
|
||||
|
||||
/// <summary>Files hashed in parallel.</summary>
|
||||
@@ -80,7 +80,7 @@ public sealed class LibraryRebuilder(
|
||||
LibraryLayout layout,
|
||||
IClock clock,
|
||||
ThumbnailStore? thumbnails = null,
|
||||
VideoFrameExtractor? frames = null,
|
||||
VideoFrameDecoder? frames = null,
|
||||
PerceptualHashIndex? hashIndex = null)
|
||||
{
|
||||
private const int BatchSize = 200;
|
||||
@@ -468,7 +468,7 @@ public sealed class LibraryRebuilder(
|
||||
}
|
||||
else if (isVideo && createThumbnails && thumbnails is not null && !thumbnail && frames is not null)
|
||||
{
|
||||
var frame = await frames.ExtractJpegAsync(path, ct).ConfigureAwait(false);
|
||||
var frame = await frames.ExtractImageAsync(path, ct).ConfigureAwait(false);
|
||||
if (frame is not null)
|
||||
{
|
||||
using var stream = new MemoryStream(frame);
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace Febe.Core.Library;
|
||||
/// Thumbnails of the library (spec §8.4): 480 pixels on the long side, JPEG, generated once and kept under
|
||||
/// <c>Dati/miniature</c>, in 256 shard folders named after the first two hex digits of the key. The key is the
|
||||
/// SHA-256 of the library file, so identical files share one thumbnail. Videos use the cover given by the page or a
|
||||
/// frame (<see cref="VideoFrameExtractor"/>); without either, the interface shows the neutral tile
|
||||
/// frame (<see cref="VideoFrameDecoder"/>); without either, the interface shows the neutral tile
|
||||
/// (<see cref="NeutralVideoTile"/>).
|
||||
/// </summary>
|
||||
public sealed class ThumbnailStore
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Core.Security;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Extracts a frame from a video with ffmpeg, when ffmpeg is installed (spec §8.4: thumbnails of imported videos and of
|
||||
/// videos without a cover). In Docker ffmpeg is part of the image (§11); on Windows it is optional.
|
||||
/// </summary>
|
||||
public sealed class VideoFrameExtractor
|
||||
{
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
|
||||
|
||||
private VideoFrameExtractor(string executable) => Executable = executable;
|
||||
|
||||
/// <summary>Full path of ffmpeg.</summary>
|
||||
public string Executable { get; }
|
||||
|
||||
/// <summary>Finds ffmpeg on the PATH (or at <paramref name="explicitPath"/>); null when it is not available.</summary>
|
||||
public static VideoFrameExtractor? TryCreate(string? explicitPath = null)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(explicitPath))
|
||||
{
|
||||
return File.Exists(explicitPath) ? new VideoFrameExtractor(Path.GetFullPath(explicitPath)) : null;
|
||||
}
|
||||
|
||||
var name = OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg";
|
||||
var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
|
||||
foreach (var folder in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
try
|
||||
{
|
||||
var candidate = Path.Combine(folder.Trim('"'), name);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return new VideoFrameExtractor(candidate);
|
||||
}
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// A malformed PATH entry: skip it.
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A JPEG frame of the video, taken one second in (or the first frame of shorter videos); null when ffmpeg cannot
|
||||
/// read the file.
|
||||
/// </summary>
|
||||
public async Task<byte[]?> ExtractJpegAsync(string videoPath, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
|
||||
foreach (var seek in new[] { "1", "0" })
|
||||
{
|
||||
var frame = await RunAsync(videoPath, seek, ct).ConfigureAwait(false);
|
||||
if (frame is { Length: > 0 })
|
||||
{
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The start of ffmpeg for one frame of <paramref name="videoPath"/> at <paramref name="seek"/> seconds: its
|
||||
/// arguments, and the environment of Febe without <c>FEBE_PASSWORD</c> and <c>FEBE_CHIAVE_SESSIONE</c>, removed last
|
||||
/// (spec §13.2).
|
||||
/// </summary>
|
||||
internal ProcessStartInfo BuildStartInfo(string videoPath, string seek)
|
||||
{
|
||||
var start = new ProcessStartInfo(Executable)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardInput = false,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
};
|
||||
foreach (var argument in new[] { "-hide_banner", "-nostdin", "-v", "error", "-ss", seek, "-i", videoPath, "-frames:v", "1", "-f", "image2pipe", "-c:v", "mjpeg", "-q:v", "3", "-" })
|
||||
{
|
||||
start.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
return start.WithoutSecrets();
|
||||
}
|
||||
|
||||
private async Task<byte[]?> RunAsync(string videoPath, string seek, CancellationToken ct)
|
||||
{
|
||||
using var process = new Process { StartInfo = BuildStartInfo(videoPath, seek) };
|
||||
try
|
||||
{
|
||||
if (!process.Start())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (System.ComponentModel.Win32Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(Timeout);
|
||||
using var output = new MemoryStream();
|
||||
try
|
||||
{
|
||||
var copy = process.StandardOutput.BaseStream.CopyToAsync(output, timeout.Token);
|
||||
var drainErrors = process.StandardError.ReadToEndAsync(timeout.Token); // never logged: may contain paths
|
||||
await Task.WhenAll(copy, drainErrors).ConfigureAwait(false);
|
||||
await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
try
|
||||
{
|
||||
process.Kill(entireProcessTree: true);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return null;
|
||||
}
|
||||
|
||||
return process.ExitCode == 0 && output.Length > 0 ? output.ToArray() : null;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ using System.Diagnostics;
|
||||
namespace Febe.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// What a process Febe starts (Chromium, Edge, Xvfb, ffmpeg, ffprobe, Explorer) must not inherit from Febe (issue #36,
|
||||
/// What a process Febe starts (Chromium, Edge, Xvfb, Explorer) must not inherit from Febe (issue #36,
|
||||
/// S4, rule 10): the interface password and the key of the saved session. A child process copies the environment of its
|
||||
/// parent; Chromium runs the site's code, so a secret in its environment is a secret one step from the site.
|
||||
/// </summary>
|
||||
|
||||
Reference in new issue
Block a user