using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Codecs.Containers; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Library.StillVideos; /// What «È un video fermo?» and «Cerca i video fermi» need from the rest of Febe (tappa E4, D5). public sealed record StillVideoEnvironment { public required IFebeStorage Storage { get; init; } /// The full path of a library file on disk, or null when it is not there. public required Func Resolve { get; init; } public required IClock Clock { get; init; } /// Import, copies, rebuild and zips of frames: the job waits while one holds it. Null: nothing to wait for (tests). public LongWorkGate? Gate { get; init; } /// The job never analyses during an engine session; the viewer may (answer 43). public IEngineSessionState Session { get; init; } = NoEngineSession.Instance; /// One heavy decode at a time with the conversions (E3, D16): the job takes it, the viewer does not. public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared; /// The file's SHA-256 is checked against the record before it is analysed (false only in the demo). public bool VerifySource { get; init; } = true; /// The longest analysis from the viewer, waiting for another included (answer 43); past it nothing is stored. public TimeSpan ViewerBudget { get; init; } = TimeSpan.FromSeconds(30); /// The longest analysis of one video of the job (answer 44); past it «Non analizzabile» (TooSlow) is stored. public TimeSpan JobBudget { get; init; } = TimeSpan.FromMinutes(2); /// How often the job looks again while it waits, and while it analyses whether it must give way. public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5); /// Called with the account of a video whose analysis was stored (the composition publishes a library change). public Action? Changed { get; init; } /// One line for the log: only Italian text and exception type names, never paths or messages. public Action? Log { get; init; } /// /// Test seam: analyses the file at a path within a budget ( from the viewer, /// whose budget is the token), honouring the token. By default /// on the opened file. /// public Func? Analyser { get; init; } } /// How an analysis asked from the viewer ended. public enum StillVideoAnswerKind { /// Analysed and stored: is the row. Analysed, /// No such file in the database (404). NotFound, /// A photo (400). NotAVideo, /// The file is not on disk (404). FileMissing, /// The bytes on disk are not the recorded ones (409): nothing stored. SourceChanged, /// Past (503): nothing stored. TooSlow, /// /// As , on a video with a result the selection would skip: that result stays (503). /// TooSlowKept, } /// The answer to «È un video fermo?» from the viewer. /// How it ended. /// The stored row, for . /// What the analyser found, for (audio, rotation, measures). /// The account of the file, when known. public sealed record StillVideoAnswer(StillVideoAnswerKind Kind, VideoAnalysis? Analysis, StillVideoResult? Result, long? AccountId) { /// The Italian text of a failure; null for . public string? Message => Kind switch { StillVideoAnswerKind.NotFound => StillVideoText.NotFound, StillVideoAnswerKind.NotAVideo => StillVideoText.NotAVideo, StillVideoAnswerKind.FileMissing => StillVideoText.FileMissing, StillVideoAnswerKind.SourceChanged => StillVideoText.SourceChanged, StillVideoAnswerKind.TooSlow => StillVideoText.TooSlow, StillVideoAnswerKind.TooSlowKept => StillVideoText.TooSlowKept, _ => null, }; } /// /// What «Cerca i video fermi» would do for a selection, counted by file (SHA-256): a video found under two entries is /// analysed once. /// /// Videos in the library with no result of the current algorithm. /// /// Videos in the library with a result of the current algorithm (skipped); one whose analysis took too long counts among /// those to analyse. /// /// Photos of the selection (skipped). /// Videos of the selection not in the library (not downloaded, deleted, file not recorded). public sealed record StillVideoPlan(int ToAnalyse, int AlreadyAnalysed, int PhotosSkipped, int Missing) { /// The videos of the selection. public int Videos => ToAnalyse + AlreadyAnalysed + Missing; } /// The job «Cerca i video fermi» as the Dashboard shows it. /// True while videos are queued or one is analysed. /// Videos of the job (since the last start of a job that was not running). /// Videos settled: + + + . /// Found «Fermo». /// Found «In movimento». /// Found «Non analizzabile». /// Left out without a result: the file went or changed, or an unexpected error. /// True once «Interrompi» ended the job. /// Why the job waits now (an engine session, a long work, the viewer), or null. /// The library file analysed now, or null. /// Of the answer of a start: the videos it added to the job (those already queued are not); else 0. public sealed record StillVideoProgress( bool Running, int Total, int Done, int Still, int Moving, int NotAnalyzable, int Skipped, bool Stopped, string? Waiting, long? CurrentMediaId, int Added = 0); /// /// «È un video fermo?» (spec §4.10, tappa E4, D5): only on request, never in the background over the library. /// /// , from the viewer: at any time, also during an engine session (answer 43), one at /// a time, within ; past it nothing is stored. It comes before the job: /// the video the job is analysing is put back at the front of its queue. /// , «Cerca i video fermi» from a selection (answer 41): a job in memory, one video at a /// time, never during an engine session and never while an import, a copy, a rebuild or a zip of frames holds the /// (it takes no lease, so it never blocks them: a video being analysed when one starts is /// given up and analysed again after). An automatic copy is the exception: a start asks it to stop /// (, tappa E5), and the job waits only until it has let go. Each video within , inside the /// ; past it «Non analizzabile» (TooSlow) is stored. Videos with a result of the current /// algorithm are skipped, but for those whose analysis took too long (a start tries them again, once): so a job ended by /// «Interrompi» or by closing Febe is not resumed by itself: started again, it goes on where it was. /// /// Results go to video_analysis by SHA-256 of the file (checked against the record first), with /// . /// public sealed class StillVideoService : IDisposable { private readonly StillVideoEnvironment _env; private readonly Func _analyse; private readonly CancellationTokenSource _life = new(); private readonly SemaphoreSlim _one = new(1, 1); private readonly Lock _lock = new(); // The job, under _lock. private readonly LinkedList _queue = new(); private readonly HashSet _queued = new(StringComparer.Ordinal); private CancellationTokenSource _jobStop = new(); private CancellationTokenSource? _item; private JobItem? _current; private Task _loop = Task.CompletedTask; private bool _running; private int _viewers; private TaskCompletionSource _wake = NewWake(); private int _total; private int _still; private int _moving; private int _notAnalyzable; private int _skipped; private bool _stopped; private string? _waiting; private bool _disposed; public StillVideoService(StillVideoEnvironment env) { _env = env ?? throw new ArgumentNullException(nameof(env)); _analyse = env.Analyser ?? AnalyseFile; } private sealed record JobItem(string Sha256, long MediaId, long AccountId); /// The job now. public StillVideoProgress Progress { get { lock (_lock) { return Snapshot(); } } } /// The loop of the job now: completed when no job runs (for the tests and an orderly stop). public Task Job { get { lock (_lock) { return _loop; } } } // ------------------------------------------------------------------------------------------------- viewer /// /// «È un video fermo?» for one library file, now (D5): resolves it, checks its SHA-256, analyses it and stores the /// result, also when one is already stored («Analizza di nuovo»). Never throws for what the page can be told. /// public async Task AnalyseNowAsync(long mediaId, CancellationToken ct = default) { ObjectDisposedException.ThrowIf(_disposed, this); var storage = _env.Storage; var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false); if (media is null) { return new StillVideoAnswer(StillVideoAnswerKind.NotFound, null, null, null); } if (media.Kind != MediaKind.Video) { return new StillVideoAnswer(StillVideoAnswerKind.NotAVideo, null, null, null); } var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false); var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false); if (account is null) { return new StillVideoAnswer(StillVideoAnswerKind.NotFound, null, null, null); } var path = media.Sha256 is { Length: 64 } && EntryStateRules.IsPresent(media.State) ? _env.Resolve(account, media) : null; if (path is null) { return new StillVideoAnswer(StillVideoAnswerKind.FileMissing, null, null, account.Id); } var sha = media.Sha256!.ToLowerInvariant(); EnterViewer(); try { if (_env.VerifySource) { // Outside the budget, as reading the file for a frame is: the page shows that it is working. string actual; try { actual = await HashAsync(path, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return new StillVideoAnswer(StillVideoAnswerKind.FileMissing, null, null, account.Id); } if (!string.Equals(actual, sha, StringComparison.Ordinal)) { return new StillVideoAnswer(StillVideoAnswerKind.SourceChanged, null, null, account.Id); } } using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct); if (_env.ViewerBudget <= TimeSpan.Zero) { // No time at all: cancelled now, not by a timer that a busy machine may fire after a quick analysis. budget.Cancel(); } else { budget.CancelAfter(_env.ViewerBudget); } StillVideoResult result; try { await _one.WaitAsync(budget.Token).ConfigureAwait(false); try { result = await Task.Run(() => _analyse(path, Timeout.InfiniteTimeSpan, budget.Token), budget.Token).ConfigureAwait(false); } finally { _one.Release(); } } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return await TooSlowAsync(sha, account.Id).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // The file went between the check and the analysis, or stopped being readable during it. return new StillVideoAnswer(StillVideoAnswerKind.FileMissing, null, null, account.Id); } if (result is { Outcome: VideoAnalysisOutcome.NotAnalyzable, Note: VideoAnalysisNotes.TooSlow }) { return await TooSlowAsync(sha, account.Id).ConfigureAwait(false); } var analysis = result.ToAnalysis(sha, _env.Clock.Now); await storage.VideoAnalyses.SetAsync(analysis, CancellationToken.None).ConfigureAwait(false); _env.Changed?.Invoke(account.Id); return new StillVideoAnswer(StillVideoAnswerKind.Analysed, analysis, result, account.Id); } finally { LeaveViewer(); } } /// /// The answer past the budget of the viewer: «avviala dalla selezione» only for a video the selection would analyse. /// private async Task TooSlowAsync(string sha, long accountId) { var kept = await _env.Storage.VideoAnalyses.GetAsync(sha, CancellationToken.None).ConfigureAwait(false); return new StillVideoAnswer(kept is not null && IsSettled(kept) ? StillVideoAnswerKind.TooSlowKept : StillVideoAnswerKind.TooSlow, null, null, accountId); } /// /// Whether the job skips a video with this result: one of the current algorithm, unless its analysis took too long /// (it is not an analysis of the video: another moment, or an idle machine, may give one). /// private static bool IsSettled(VideoAnalysis analysis) => analysis.Algorithm >= StillVideoAnalyzer.Algorithm && !(analysis.Outcome == VideoAnalysisOutcome.NotAnalyzable && (analysis.Note ?? string.Empty).Split(' ').Contains(VideoAnalysisNotes.TooSlow, StringComparer.Ordinal)); // ------------------------------------------------------------------------------------------------- job /// The counts of the confirmation of «Cerca i video fermi» for . public async Task PlanAsync(ExportSelection selection, CancellationToken ct = default) { var (items, already, photos, missing) = await CollectAsync(selection, ct).ConfigureAwait(false); return new StillVideoPlan(items.Count, already, photos, missing); } /// /// Starts «Cerca i video fermi» for , or adds its videos to the job already running (a /// video already queued is not queued twice). Returns the job as it is then, with how many videos were added. /// public async Task StartAsync(ExportSelection selection, CancellationToken ct = default) { ObjectDisposedException.ThrowIf(_disposed, this); var (items, _, _, _) = await CollectAsync(selection, ct).ConfigureAwait(false); StillVideoProgress started; lock (_lock) { if (!_running || _jobStop.IsCancellationRequested) { // A new job (none runs, or the last one was stopped and is still giving up its video): its counts go. _total = _still = _moving = _notAnalyzable = _skipped = 0; _stopped = false; _waiting = null; } if (_jobStop.IsCancellationRequested) { // Not disposed: the loop that is ending may still read its token. _jobStop = new CancellationTokenSource(); } var added = 0; foreach (var item in items) { if (_queued.Add(item.Sha256)) { _queue.AddLast(item); _total++; added++; } } if (_queue.Count > 0 && !_running) { _running = true; _loop = Task.Run(LoopAsync); } started = Snapshot() with { Added = added }; } if (started.Running) { // Alberto's search comes before an automatic copy (§16 answer 49): it is asked to stop, outside the lock (the // token's callbacks run synchronously), and the job waits for the gate as for any long work. _env.Gate?.CancelYielding(); } return started; } /// «Interrompi»: the queue empties, the video being analysed is given up and nothing is stored for it. public StillVideoProgress Stop() { lock (_lock) { if (_running) { _queue.Clear(); _queued.Clear(); _stopped = true; _waiting = null; _jobStop.Cancel(); } return Snapshot(); } } public void Dispose() { lock (_lock) { if (_disposed) { return; } _disposed = true; _queue.Clear(); _queued.Clear(); } _life.Cancel(); // The loop may still be ending: the token sources are left to the collector, as LongWorkGate does. } private async Task LoopAsync() { while (true) { JobItem item; lock (_lock) { if (_queue.First is not { } first || _life.IsCancellationRequested) { _running = false; _current = null; _waiting = null; return; } item = first.Value; } try { await RunItemAsync(item).ConfigureAwait(false); } catch (OperationCanceledException) when (_life.IsCancellationRequested) { lock (_lock) { _running = false; _current = null; return; } } catch (OperationCanceledException) { // Given way (viewer, session, long work: the video stays at the front) or «Interrompi» (the queue is // empty): the top of the loop decides. } catch (Exception ex) { // One video never stops the job: it is left out without a result, the log gets the type only. _env.Log?.Invoke($"Un video non si è potuto analizzare ({ex.GetType().Name})."); Settle(item, null); } } } /// Waits for its turn, then analyses and stores the result; leaves it at the front when it gives way. private async Task RunItemAsync(JobItem item) { var life = _life.Token; CancellationTokenSource itemSource; CancellationToken stop; while (true) { var reason = BackgroundReason(); lock (_lock) { stop = _jobStop.Token; stop.ThrowIfCancellationRequested(); reason ??= _viewers > 0 ? StillVideoText.Viewer : null; _waiting = reason; if (reason is null) { itemSource = CancellationTokenSource.CreateLinkedTokenSource(life, stop); _item = itemSource; _current = item; break; } } await WaitAsync(stop).ConfigureAwait(false); } using var watch = CancellationTokenSource.CreateLinkedTokenSource(itemSource.Token); var watcher = WatchAsync(itemSource, watch.Token); try { var token = itemSource.Token; var storage = _env.Storage; var sha = item.Sha256; if (await storage.VideoAnalyses.GetAsync(sha, token).ConfigureAwait(false) is { } existing && IsSettled(existing)) { // Analysed meanwhile (from the viewer, or under another entry of the same file). Settle(item, existing.Outcome); return; } var path = await PathAsync(item, token).ConfigureAwait(false); if (path is null) { Settle(item, null); return; } if (_env.VerifySource) { string actual; try { actual = await HashAsync(path, token).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Settle(item, null); return; } if (!string.Equals(actual, sha, StringComparison.Ordinal)) { Settle(item, null); return; } } StillVideoResult result; try { result = await _env.Throttle.RunAsync(t => _analyse(path, _env.JobBudget, t), token).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Settle(item, null); return; } token.ThrowIfCancellationRequested(); await storage.VideoAnalyses.SetAsync(result.ToAnalysis(sha, _env.Clock.Now), CancellationToken.None).ConfigureAwait(false); Settle(item, result.Outcome); _env.Changed?.Invoke(item.AccountId); } finally { await watch.CancelAsync().ConfigureAwait(false); await watcher.ConfigureAwait(false); lock (_lock) { if (ReferenceEquals(_item, itemSource)) { _item = null; } _current = null; } itemSource.Dispose(); } } /// /// The library file of on disk, if it is still the same file in the library; otherwise another /// file of the library with the same bytes (the same video under another entry or account). /// private async Task PathAsync(JobItem item, CancellationToken ct) { var storage = _env.Storage; var media = await storage.Media.GetAsync(item.MediaId, ct).ConfigureAwait(false); if (media is not null && media.Kind == MediaKind.Video && EntryStateRules.IsPresent(media.State) && string.Equals(media.Sha256?.ToLowerInvariant(), item.Sha256, StringComparison.Ordinal) && await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) is { } entry && await ResolveAsync(media, entry.AccountId, ct).ConfigureAwait(false) is { } path) { return path; } foreach (var location in await storage.Media.FindBySha256Async(item.Sha256, ct).ConfigureAwait(false)) { if (location.Media.Kind == MediaKind.Video && EntryStateRules.IsPresent(location.Media.State) && await ResolveAsync(location.Media, location.Entry.AccountId, ct).ConfigureAwait(false) is { } other) { return other; } } return null; } /// The path of a library file that is really on the disk, or null. private async Task ResolveAsync(Media media, long accountId, CancellationToken ct) { var account = await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false); var path = account is null ? null : _env.Resolve(account, media); return path is not null && File.Exists(path) ? path : null; } /// /// While a video is analysed, every : an engine session or a long work that /// started meanwhile makes the job give way (the video is analysed again after). /// private async Task WatchAsync(CancellationTokenSource item, CancellationToken ct) { try { while (!ct.IsCancellationRequested) { await _env.Clock.Delay(_env.Poll, ct).ConfigureAwait(false); await Task.Yield(); if (!ct.IsCancellationRequested && BackgroundReason() is { } reason) { lock (_lock) { _waiting = reason; } await item.CancelAsync().ConfigureAwait(false); return; } } } catch (OperationCanceledException) { // The video ended. } catch (ObjectDisposedException) { // The video ended and its token source went. } } /// Waits , or less when an analysis from the viewer ends. private async Task WaitAsync(CancellationToken stop) { Task wake; lock (_lock) { wake = _wake.Task; } using var linked = CancellationTokenSource.CreateLinkedTokenSource(_life.Token, stop); var delay = _env.Clock.Delay(_env.Poll, linked.Token); await Task.WhenAny(delay, wake).ConfigureAwait(false); await linked.CancelAsync().ConfigureAwait(false); await Task.Yield(); _life.Token.ThrowIfCancellationRequested(); stop.ThrowIfCancellationRequested(); } /// /// Why the job may not analyse now, but for the viewer: an engine session or a long work. An automatic copy that took /// the gate after the search started is asked to stop at every look (§16 answer 49: the search comes first), not /// only at the start, so the search never waits behind a whole automatic job. /// private string? BackgroundReason() { if (_env.Session.InSession) { return StillVideoText.InSession; } if (_env.Gate is not { } gate) { return null; } if (gate.HeldByYielding) { gate.CancelYielding(); } return gate.Busy is not null ? StillVideoText.LongWork : null; } /// Counts (with its outcome, or as left out) and takes it off the front of the queue. private void Settle(JobItem item, VideoAnalysisOutcome? outcome) { lock (_lock) { if (_queue.First is not { } first || !ReferenceEquals(first.Value, item)) { return; // «Interrompi» emptied the queue meanwhile } _queue.RemoveFirst(); _queued.Remove(item.Sha256); switch (outcome) { case VideoAnalysisOutcome.Still: _still++; break; case VideoAnalysisOutcome.Moving: _moving++; break; case VideoAnalysisOutcome.NotAnalyzable: _notAnalyzable++; break; default: _skipped++; break; } } } private void EnterViewer() { CancellationTokenSource? preempted; lock (_lock) { _viewers++; preempted = _item; _item = null; if (preempted is not null) { _waiting = StillVideoText.Viewer; } } // Outside the lock: the token's callbacks run synchronously. try { preempted?.Cancel(); } catch (ObjectDisposedException) { // That video had just ended. } } private void LeaveViewer() { TaskCompletionSource wake; lock (_lock) { _viewers--; wake = _wake; _wake = NewWake(); } wake.TrySetResult(); } /// /// The present videos of to analyse, one per SHA-256 in media order, with the counts of /// those already analysed (by file), the photos and the videos not in the library. /// private async Task<(List Items, int Already, int Photos, int Missing)> CollectAsync(ExportSelection selection, CancellationToken ct) { ArgumentNullException.ThrowIfNull(selection); var storage = _env.Storage; var accounts = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).Select(a => a.Id).ToHashSet(); var present = new List(); var seen = new HashSet(StringComparer.Ordinal); var photos = 0; var missing = 0; long after = 0; while (true) { var page = await storage.Exports.ListCandidatesAsync(selection, after, 500, ct).ConfigureAwait(false); if (page.Count == 0) { break; } after = page[^1].MediaId; foreach (var c in page) { if (c.MediaKind != MediaKind.Video) { photos++; } else if (!EntryStateRules.IsPresent(c.State) || c.RelativePath is null || c.Sha256 is not { Length: 64 } || !accounts.Contains(c.AccountId)) { missing++; } else if (seen.Add(c.Sha256.ToLowerInvariant())) { present.Add(new JobItem(c.Sha256.ToLowerInvariant(), c.MediaId, c.AccountId)); } } } var items = new List(); var already = 0; foreach (var chunk in present.Chunk(500)) { var found = await storage.VideoAnalyses.GetManyAsync(chunk.Select(i => i.Sha256).ToList(), ct).ConfigureAwait(false); foreach (var item in chunk) { if (found.TryGetValue(item.Sha256, out var analysis) && IsSettled(analysis)) { already++; } else { items.Add(item); } } } return (items, already, photos, missing); } private StillVideoProgress Snapshot() { var done = _still + _moving + _notAnalyzable + _skipped; return new StillVideoProgress(_running, _total, done, _still, _moving, _notAnalyzable, _skipped, _stopped, _running ? _waiting : null, _current?.MediaId); } private static TaskCompletionSource NewWake() => new(TaskCreationOptions.RunContinuationsAsynchronously); private static StillVideoResult AnalyseFile(string path, TimeSpan budget, CancellationToken ct) { using var stream = ContainerReader.OpenRead(path); return StillVideoAnalyzer.Analyse(stream, budget == Timeout.InfiniteTimeSpan ? TimeSpan.MaxValue : budget, ct); } private static async Task HashAsync(string path, CancellationToken ct) { var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan); await using (stream.ConfigureAwait(false)) { return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); } } }