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

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

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

No files matched your search

+3 -2
View File
@@ -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)
{
+1 -1
View File
@@ -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);
}
+6 -3
View File
@@ -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>
+4 -4
View File
@@ -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
+27 -166
View File
@@ -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;
}
}