E4: servizio dei video fermi, dal visualizzatore e dalla selezione

StillVideoService (Febe.Core) fa «È un video fermo?» solo a richiesta:
- dal visualizzatore un video alla volta entro 30 secondi, anche durante
  una sessione del motore (risposta 43); oltre, niente salvato e «L'analisi
  richiede troppo tempo: avviala dalla selezione»; prima controlla lo
  SHA-256 del file; ferma il video del lavoro in corso, che si rifà dopo;
- dalla selezione «Cerca i video fermi» (risposta 41): un lavoro in
  memoria, un video per file alla volta, 2 minuti per video nel
  ConversionThrottle, mai durante una sessione né con importazione, copie,
  ricostruzione o zip di fotogrammi (senza prendere il cancello: se uno
  parte a metà analisi il video si lascia e si rifà dopo), avanzamento e
  «Interrompi», conteggi della conferma; non riparte da solo e, rilanciato,
  salta i video già analizzati.

Gli esiti vanno in video_analysis con l'algoritmo 1 e segnalano la
libreria («fermi»). Registrato in FebeWeb accanto a FrameService; le prove
usano video costruiti, una sessione finta e cancello e throttle veri.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-29 15:01:10 +01:00
1 parent e61da9be23
commit 4f238f2c9f
4 files changed
+1352

No files matched your search

@@ -0,0 +1,783 @@
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;
/// <summary>What «È un video fermo?» and «Cerca i video fermi» need from the rest of Febe (tappa E4, D5).</summary>
public sealed record StillVideoEnvironment
{
public required IFebeStorage Storage { get; init; }
/// <summary>The full path of a library file on disk, or null when it is not there.</summary>
public required Func<Account, Media, string?> Resolve { get; init; }
public required IClock Clock { get; init; }
/// <summary>Import, copies, rebuild and zips of frames: the job waits while one holds it. Null: nothing to wait for (tests).</summary>
public LongWorkGate? Gate { get; init; }
/// <summary>The job never analyses during an engine session; the viewer may (answer 43).</summary>
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
/// <summary>One heavy decode at a time with the conversions (E3, D16): the job takes it, the viewer does not.</summary>
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
/// <summary>The file's SHA-256 is checked against the record before it is analysed (false only in the demo).</summary>
public bool VerifySource { get; init; } = true;
/// <summary>The longest analysis from the viewer, waiting for another included (answer 43); past it nothing is stored.</summary>
public TimeSpan ViewerBudget { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>The longest analysis of one video of the job (answer 44); past it «Non analizzabile» (TooSlow) is stored.</summary>
public TimeSpan JobBudget { get; init; } = TimeSpan.FromMinutes(2);
/// <summary>How often the job looks again while it waits, and while it analyses whether it must give way.</summary>
public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>Called with the account of a video whose analysis was stored (the composition publishes a library change).</summary>
public Action<long?>? Changed { get; init; }
/// <summary>One line for the log: only Italian text and exception type names, never paths or messages.</summary>
public Action<string>? Log { get; init; }
/// <summary>
/// Test seam: analyses the file at a path within a budget (<see cref="Timeout.InfiniteTimeSpan"/> from the viewer,
/// whose budget is the token), honouring the token. By default
/// <see cref="StillVideoAnalyzer.Analyse(Stream, TimeSpan, CancellationToken)"/> on the opened file.
/// </summary>
public Func<string, TimeSpan, CancellationToken, StillVideoResult>? Analyser { get; init; }
}
/// <summary>How an analysis asked from the viewer ended.</summary>
public enum StillVideoAnswerKind
{
/// <summary>Analysed and stored: <see cref="StillVideoAnswer.Analysis"/> is the row.</summary>
Analysed,
/// <summary>No such file in the database (404).</summary>
NotFound,
/// <summary>A photo (400).</summary>
NotAVideo,
/// <summary>The file is not on disk (404).</summary>
FileMissing,
/// <summary>The bytes on disk are not the recorded ones (409): nothing stored.</summary>
SourceChanged,
/// <summary>Past <see cref="StillVideoEnvironment.ViewerBudget"/> (503): nothing stored.</summary>
TooSlow,
}
/// <summary>The answer to «È un video fermo?» from the viewer.</summary>
/// <param name="Kind">How it ended.</param>
/// <param name="Analysis">The stored row, for <see cref="StillVideoAnswerKind.Analysed"/>.</param>
/// <param name="Result">What the analyser found, for <see cref="StillVideoAnswerKind.Analysed"/> (audio, rotation, measures).</param>
/// <param name="AccountId">The account of the file, when known.</param>
public sealed record StillVideoAnswer(StillVideoAnswerKind Kind, VideoAnalysis? Analysis, StillVideoResult? Result, long? AccountId)
{
/// <summary>The Italian text of a failure; null for <see cref="StillVideoAnswerKind.Analysed"/>.</summary>
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,
_ => null,
};
}
/// <summary>
/// What «Cerca i video fermi» would do for a selection, counted by file (SHA-256): a video found under two entries is
/// analysed once.
/// </summary>
/// <param name="ToAnalyse">Videos in the library with no result of the current algorithm.</param>
/// <param name="AlreadyAnalysed">Videos in the library with a result of the current algorithm (skipped).</param>
/// <param name="PhotosSkipped">Photos of the selection (skipped).</param>
/// <param name="Missing">Videos of the selection not in the library (not downloaded, deleted, file not recorded).</param>
public sealed record StillVideoPlan(int ToAnalyse, int AlreadyAnalysed, int PhotosSkipped, int Missing)
{
/// <summary>The videos of the selection.</summary>
public int Videos => ToAnalyse + AlreadyAnalysed + Missing;
}
/// <summary>The job «Cerca i video fermi» as the Dashboard shows it.</summary>
/// <param name="Running">True while videos are queued or one is analysed.</param>
/// <param name="Total">Videos of the job (since the last start of a job that was not running).</param>
/// <param name="Done">Videos settled: <paramref name="Still"/> + <paramref name="Moving"/> + <paramref name="NotAnalyzable"/> + <paramref name="Skipped"/>.</param>
/// <param name="Still">Found «Fermo».</param>
/// <param name="Moving">Found «In movimento».</param>
/// <param name="NotAnalyzable">Found «Non analizzabile».</param>
/// <param name="Skipped">Left out without a result: the file went or changed, or an unexpected error.</param>
/// <param name="Stopped">True once «Interrompi» ended the job.</param>
/// <param name="Waiting">Why the job waits now (an engine session, a long work, the viewer), or null.</param>
/// <param name="CurrentMediaId">The library file analysed now, or null.</param>
public sealed record StillVideoProgress(
bool Running,
int Total,
int Done,
int Still,
int Moving,
int NotAnalyzable,
int Skipped,
bool Stopped,
string? Waiting,
long? CurrentMediaId);
/// <summary>
/// «È un video fermo?» (spec §4.10, tappa E4, D5): only on request, never in the background over the library.
/// <list type="bullet">
/// <item><see cref="AnalyseNowAsync"/>, from the viewer: at any time, also during an engine session (answer 43), one at
/// a time, within <see cref="StillVideoEnvironment.ViewerBudget"/>; 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.</item>
/// <item><see cref="StartAsync"/>, «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
/// <see cref="LongWorkGate"/> (it takes no lease, so it never blocks them: a video being analysed when one starts is
/// given up and analysed again after). Each video within <see cref="StillVideoEnvironment.JobBudget"/>, inside the
/// <see cref="ConversionThrottle"/>; past it «Non analizzabile» (TooSlow) is stored. Videos with a result of the current
/// algorithm are skipped, so a job ended by «Interrompi» or by closing Febe is not resumed by itself: started again, it
/// goes on where it was.</item>
/// </list>
/// Results go to <c>video_analysis</c> by SHA-256 of the file (checked against the record first), with
/// <see cref="StillVideoAnalyzer.Algorithm"/>.
/// </summary>
public sealed class StillVideoService : IDisposable
{
private readonly StillVideoEnvironment _env;
private readonly Func<string, TimeSpan, CancellationToken, StillVideoResult> _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<JobItem> _queue = new();
private readonly HashSet<string> _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);
/// <summary>The job now.</summary>
public StillVideoProgress Progress
{
get
{
lock (_lock)
{
return Snapshot();
}
}
}
/// <summary>The loop of the job now: completed when no job runs (for the tests and an orderly stop).</summary>
public Task Job
{
get
{
lock (_lock)
{
return _loop;
}
}
}
// ------------------------------------------------------------------------------------------------- viewer
/// <summary>
/// «È 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.
/// </summary>
public async Task<StillVideoAnswer> 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 new StillVideoAnswer(StillVideoAnswerKind.TooSlow, null, null, account.Id);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The file went between the check and the analysis.
return new StillVideoAnswer(StillVideoAnswerKind.FileMissing, null, null, account.Id);
}
if (result is { Outcome: VideoAnalysisOutcome.NotAnalyzable, Note: VideoAnalysisNotes.TooSlow })
{
return new StillVideoAnswer(StillVideoAnswerKind.TooSlow, null, null, account.Id);
}
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();
}
}
// ------------------------------------------------------------------------------------------------- job
/// <summary>The counts of the confirmation of «Cerca i video fermi» for <paramref name="selection"/>.</summary>
public async Task<StillVideoPlan> 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);
}
/// <summary>
/// Starts «Cerca i video fermi» for <paramref name="selection"/>, or adds its videos to the job already running (a
/// video already queued is not queued twice). Returns the job as it is then.
/// </summary>
public async Task<StillVideoProgress> StartAsync(ExportSelection selection, CancellationToken ct = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var (items, _, _, _) = await CollectAsync(selection, ct).ConfigureAwait(false);
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();
}
foreach (var item in items)
{
if (_queued.Add(item.Sha256))
{
_queue.AddLast(item);
_total++;
}
}
if (_queue.Count > 0 && !_running)
{
_running = true;
_loop = Task.Run(LoopAsync);
}
return Snapshot();
}
}
/// <summary>«Interrompi»: the queue empties, the video being analysed is given up and nothing is stored for it.</summary>
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);
}
}
}
/// <summary>Waits for its turn, then analyses <paramref name="item"/> and stores the result; leaves it at the front when it gives way.</summary>
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 && existing.Algorithm >= StillVideoAnalyzer.Algorithm)
{
// 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();
}
}
/// <summary>The library file of <paramref name="item"/> on disk, if it is still the same file in the library.</summary>
private async Task<string?> PathAsync(JobItem item, CancellationToken ct)
{
var storage = _env.Storage;
var media = await storage.Media.GetAsync(item.MediaId, ct).ConfigureAwait(false);
if (media is null || media.Kind != MediaKind.Video || !EntryStateRules.IsPresent(media.State)
|| !string.Equals(media.Sha256?.ToLowerInvariant(), item.Sha256, StringComparison.Ordinal))
{
return 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);
return account is null ? null : _env.Resolve(account, media);
}
/// <summary>
/// While a video is analysed, every <see cref="StillVideoEnvironment.Poll"/>: an engine session or a long work that
/// started meanwhile makes the job give way (the video is analysed again after).
/// </summary>
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.
}
}
/// <summary>Waits <see cref="StillVideoEnvironment.Poll"/>, or less when an analysis from the viewer ends.</summary>
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();
}
/// <summary>Why the job may not analyse now, but for the viewer: an engine session or a long work.</summary>
private string? BackgroundReason()
{
if (_env.Session.InSession)
{
return StillVideoText.InSession;
}
return _env.Gate?.Busy is not null ? StillVideoText.LongWork : null;
}
/// <summary>Counts <paramref name="item"/> (with its outcome, or as left out) and takes it off the front of the queue.</summary>
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();
}
/// <summary>
/// The present videos of <paramref name="selection"/> 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.
/// </summary>
private async Task<(List<JobItem> 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<JobItem>();
var seen = new HashSet<string>(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<JobItem>();
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) && analysis.Algorithm >= StillVideoAnalyzer.Algorithm)
{
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<string> 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));
}
}
}
@@ -0,0 +1,78 @@
using Febe.Core.Engine;
namespace Febe.Core.Library.StillVideos;
/// <summary>The Italian texts of «È un video fermo?» and «Cerca i video fermi» (spec §4.10, tappa E4).</summary>
public static class StillVideoText
{
/// <summary>The analysis from the viewer did not end within its budget (answer 43): nothing is stored.</summary>
public const string TooSlow = "L'analisi richiede troppo tempo: avviala dalla selezione";
/// <summary>The file asked for is not in the database.</summary>
public const string NotFound = "File non trovato.";
/// <summary>The file asked for is a photo.</summary>
public const string NotAVideo = "Solo un video può essere un video fermo.";
/// <summary>The file is not on disk.</summary>
public const string FileMissing = "File non presente in libreria";
/// <summary>The bytes on disk are not the ones recorded (the same words as the copies).</summary>
public const string SourceChanged = "Il file della libreria non corrisponde a quello registrato.";
/// <summary>The job waits for the end of an engine session.</summary>
public const string InSession = "Il motore è in sessione: la ricerca dei video fermi riprende dopo";
/// <summary>The job waits for an import, a copy, a rebuild or a zip of frames.</summary>
public const string LongWork = "Un'importazione, una copia o una ricostruzione è al lavoro: la ricerca dei video fermi riprende dopo";
/// <summary>The job waits for an analysis asked from the viewer, which comes first.</summary>
public const string Viewer = "Un video si sta analizzando dal visualizzatore: la ricerca dei video fermi riprende subito dopo";
/// <summary>«28 video da analizzare · 12 già analizzati · le 5 foto si saltano · 1 video non presente in libreria».</summary>
public static string PlanSummary(StillVideoPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
var parts = new List<string> { $"{ItalianText.Number(plan.ToAnalyse)} video da analizzare" };
if (plan.AlreadyAnalysed > 0)
{
parts.Add(plan.AlreadyAnalysed == 1 ? "1 già analizzato" : $"{ItalianText.Number(plan.AlreadyAnalysed)} già analizzati");
}
if (plan.PhotosSkipped > 0)
{
parts.Add(plan.PhotosSkipped == 1 ? "la foto si salta" : $"le {ItalianText.Number(plan.PhotosSkipped)} foto si saltano");
}
if (plan.Missing > 0)
{
parts.Add($"{ItalianText.Number(plan.Missing)} video non {(plan.Missing == 1 ? "presente" : "presenti")} in libreria");
}
return string.Join(" · ", parts);
}
/// <summary>«Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile» (the toast at the end of a job).</summary>
public static string Summary(StillVideoProgress progress)
{
ArgumentNullException.ThrowIfNull(progress);
var analysed = progress.Still + progress.Moving + progress.NotAnalyzable;
var head = analysed == 1 ? "Analizzato 1 video" : $"Analizzati {ItalianText.Number(analysed)} video";
var parts = new List<string>
{
progress.Still == 1 ? "1 fermo" : $"{ItalianText.Number(progress.Still)} fermi",
$"{ItalianText.Number(progress.Moving)} in movimento",
};
if (progress.NotAnalyzable > 0)
{
parts.Add(progress.NotAnalyzable == 1 ? "1 non analizzabile" : $"{ItalianText.Number(progress.NotAnalyzable)} non analizzabili");
}
if (progress.Skipped > 0)
{
parts.Add(progress.Skipped == 1 ? "1 saltato" : $"{ItalianText.Number(progress.Skipped)} saltati");
}
return head + ": " + string.Join(", ", parts);
}
}
+17
View File
@@ -5,6 +5,7 @@ using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Web.Api;
using Febe.Web.Connection;
@@ -105,6 +106,22 @@ public static class FebeWeb
// Frames of videos (tappa E3): previews, single frames, «Scarica» of several in a zip.
services.TryAddSingleton<IConversionFileResolver, LibraryConversionFileResolver>();
services.TryAddSingleton<FrameService>();
// «È un video fermo?» and «Cerca i video fermi» (tappa E4): only on request, one video at a time.
services.TryAddSingleton(sp =>
{
var clock = sp.GetRequiredService<IClock>();
var changes = sp.GetRequiredService<LibraryChanges>();
var files = sp.GetRequiredService<IMediaFileResolver>();
return new StillVideoService(new StillVideoEnvironment
{
Storage = sp.GetRequiredService<IFebeStorage>(),
Resolve = files.Resolve,
Clock = clock,
Gate = sp.GetRequiredService<LongWorkGate>(),
Session = sp.GetRequiredService<IEngineSessionState>(),
Changed = accountId => changes.Publish(new LibraryChange(clock.Now, accountId, "fermi")),
});
});
services.AddHttpContextAccessor();
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
{
@@ -0,0 +1,474 @@
using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Tests.Codecs.Containers;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Library;
/// <summary>
/// «È un video fermo?» from the viewer and «Cerca i video fermi» from a selection (tappa E4, D5, answers 41 and 43): the
/// service over a real database and library, with videos the tests build (<see cref="PcmVideos"/>), a fake engine
/// session and a real <see cref="LongWorkGate"/> and <see cref="ConversionThrottle"/>.
/// </summary>
[TestClass]
public sealed class StillVideoServiceTests
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheViewerAnalysesStoresAndTellsTheLibrary()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, still) = await SaveVideoAsync(library, "1", StillVideo(1, audio: true));
var (_, moving) = await SaveVideoAsync(library, "2", MovingVideo());
var changed = new ConcurrentQueue<long?>();
using var service = new StillVideoService(Environment(library) with { Changed = changed.Enqueue });
var answer = await service.AnalyseNowAsync(still.Id, ct);
Assert.AreEqual(StillVideoAnswerKind.Analysed, answer.Kind);
Assert.IsNull(answer.Message);
Assert.IsTrue(answer.Result!.HasAudio);
var row = await library.Db.VideoAnalyses.GetAsync(still.Sha256!, ct);
Assert.IsNotNull(row);
Assert.AreEqual((VideoAnalysisOutcome.Still, StillVideoAnalyzer.Algorithm, library.Clock.Now), (row.Outcome, row.Algorithm, row.AnalyzedAt));
Assert.IsNotNull(row.FrameAt, "the frame «Salva il fotogramma» saves");
Assert.AreEqual(answer.Analysis, row);
CollectionAssert.AreEqual(new long?[] { account.Id }, changed.ToArray());
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await service.AnalyseNowAsync(moving.Id, ct)).Analysis!.Outcome);
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await library.Db.VideoAnalyses.GetAsync(moving.Sha256!, ct))!.Outcome);
// «Analizza di nuovo»: the viewer analyses again what is already analysed.
library.Clock.Now += TimeSpan.FromHours(1);
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(still.Id, ct)).Kind);
Assert.AreEqual(library.Clock.Now, (await library.Db.VideoAnalyses.GetAsync(still.Sha256!, ct))!.AnalyzedAt);
}
[TestMethod]
public async Task TheViewerRunsDuringAnEngineSessionAndWhileALongWorkRuns()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (_, video) = await SaveVideoAsync(library, "1", StillVideo(2));
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
using (import)
{
using var service = new StillVideoService(Environment(library, gate) with { Session = new FakeSessionState { InSession = true } });
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(video.Id, ct)).Kind, "like a frame preview (answer 43)");
}
}
[TestMethod]
public async Task APhotoAMissingFileAndAnUnknownIdAreAnsweredAndNothingIsStored()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await AccountAsync(library);
var photo = (await library.SaveAsync(account, Make.Entry(account.Id, "1", Make.T0), [TestFile.Photo(1, 3, 64, 48)])).Media[0];
var (_, video) = await SaveVideoAsync(library, "2", StillVideo(3));
File.Delete(library.Layout.FullPath(account, video.RelativePath!));
using var service = new StillVideoService(Environment(library));
var answers = new[]
{
await service.AnalyseNowAsync(photo.Id, ct),
await service.AnalyseNowAsync(video.Id, ct),
await service.AnalyseNowAsync(9999, ct),
};
CollectionAssert.AreEqual(
new[] { StillVideoAnswerKind.NotAVideo, StillVideoAnswerKind.FileMissing, StillVideoAnswerKind.NotFound },
answers.Select(a => a.Kind).ToArray());
Assert.AreEqual(StillVideoText.FileMissing, answers[1].Message);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
}
[TestMethod]
public async Task AChangedFileIsNotAnalysedExceptInTheDemo()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, video) = await SaveVideoAsync(library, "1", StillVideo(4));
await File.WriteAllBytesAsync(library.Layout.FullPath(account, video.RelativePath!), StillVideo(5), ct);
var calls = new ConcurrentQueue<string>();
using (var service = new StillVideoService(Environment(library) with { Analyser = Counting(calls) }))
{
var answer = await service.AnalyseNowAsync(video.Id, ct);
Assert.AreEqual((StillVideoAnswerKind.SourceChanged, StillVideoText.SourceChanged), (answer.Kind, answer.Message));
}
Assert.IsEmpty(calls, "the bytes are checked before the analysis");
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
// The demo's files are shared and never have the recorded SHA-256 (D14).
using var demo = new StillVideoService(Environment(library) with { VerifySource = false });
Assert.AreEqual(StillVideoAnswerKind.Analysed, (await demo.AnalyseNowAsync(video.Id, ct)).Kind);
}
[TestMethod]
public async Task PastItsBudgetTheViewerStoresNothing()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (_, video) = await SaveVideoAsync(library, "1", StillVideo(6));
using var service = new StillVideoService(Environment(library) with { ViewerBudget = TimeSpan.Zero });
var answer = await service.AnalyseNowAsync(video.Id, ct);
Assert.AreEqual(StillVideoAnswerKind.TooSlow, answer.Kind);
Assert.AreEqual("L'analisi richiede troppo tempo: avviala dalla selezione", answer.Message);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct), "only the job's budget is final");
}
[TestMethod]
public async Task TheJobCountsAnalysesOncePerFileAndSkipsWhatIsDone()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await AccountAsync(library);
var (_, first) = await SaveVideoAsync(library, "1", StillVideo(7));
// The same file under a second entry (an import with «Tieni entrambi», say).
var second = (await library.Db.Entries.AddAsync(
Make.Entry(account.Id, "2", Make.T0.AddMinutes(2)), [Make.Stored(Make.Video(1), first.Sha256!, first.RelativePath!)], ct)).Stored.Media[0];
var (_, moving) = await SaveVideoAsync(library, "3", MovingVideo());
var (_, done) = await SaveVideoAsync(library, "4", StillVideo(8));
var waiting = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "5", Make.T0.AddMinutes(5)), [Make.Video(1)], ct); // not downloaded
var photo = await library.SaveAsync(account, Make.Entry(account.Id, "6", Make.T0.AddMinutes(6)), [TestFile.Photo(1, 4, 64, 48)]);
await library.Db.VideoAnalyses.SetAsync(new VideoAnalysis(done.Sha256!, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.Moving, Make.T0), ct);
Assert.AreEqual(first.Sha256, second.Sha256);
var calls = new ConcurrentQueue<string>();
var changed = new ConcurrentQueue<long?>();
using var service = new StillVideoService(Environment(library) with { Analyser = Counting(calls), Changed = changed.Enqueue });
var selection = new ExportSelection.Entries([first.EntryId, second.EntryId, moving.EntryId, done.EntryId, waiting.Stored.Entry.Id, photo.Entry.Id]);
var plan = await service.PlanAsync(selection, ct);
Assert.AreEqual((2, 1, 1, 1, 4), (plan.ToAnalyse, plan.AlreadyAnalysed, plan.PhotosSkipped, plan.Missing, plan.Videos));
Assert.AreEqual("2 video da analizzare · 1 già analizzato · la foto si salta · 1 video non presente in libreria", StillVideoText.PlanSummary(plan));
var started = await service.StartAsync(selection, ct);
Assert.AreEqual((true, 2), (started.Running, started.Total));
await service.Job.WaitAsync(Patience, ct);
var progress = service.Progress;
Assert.AreEqual((false, 2, 2, 1, 1, 0, 0, false), (progress.Running, progress.Total, progress.Done, progress.Still, progress.Moving, progress.NotAnalyzable, progress.Skipped, progress.Stopped));
Assert.IsNull(progress.CurrentMediaId);
Assert.AreEqual("Analizzati 2 video: 1 fermo, 1 in movimento", StillVideoText.Summary(progress));
Assert.HasCount(2, calls, "the shared file is analysed once");
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct))!.Outcome);
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await library.Db.VideoAnalyses.GetAsync(moving.Sha256!, ct))!.Outcome);
Assert.AreEqual(Make.T0, (await library.Db.VideoAnalyses.GetAsync(done.Sha256!, ct))!.AnalyzedAt, "an analysed video is skipped");
Assert.HasCount(2, changed);
Assert.AreEqual(0, (await service.PlanAsync(selection, ct)).ToAnalyse);
Assert.IsFalse((await service.StartAsync(selection, ct)).Running, "nothing left to analyse");
}
[TestMethod]
public async Task TheJobWaitsForAnEngineSessionAndForALongWork()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, video) = await SaveVideoAsync(library, "1", StillVideo(10));
var session = new FakeSessionState { InSession = true };
var gate = new LongWorkGate();
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library, gate) with { Session = session, Analyser = Counting(calls) });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession, ct);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _), "the job holds no lease: an import starts at once");
session.InSession = false;
await UntilAsync(() => service.Progress.Waiting == StillVideoText.LongWork, ct);
Assert.IsEmpty(calls);
Assert.IsTrue(service.Progress.Running);
import.Dispose();
await service.Job.WaitAsync(Patience, ct);
Assert.HasCount(1, calls);
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task ASessionThatStartsDuringAnAnalysisMakesTheJobGiveWay()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, video) = await SaveVideoAsync(library, "1", StillVideo(11));
var session = new FakeSessionState();
var blocker = new Blocker(library.Layout.FullPath(account, video.RelativePath!));
using var service = new StillVideoService(Environment(library) with { Session = session, Analyser = blocker.Analyse });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
session.InSession = true;
await blocker.Cancelled.Task.WaitAsync(Patience, ct);
await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession && service.Progress.CurrentMediaId is null, ct);
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct), "a video given up stores nothing");
session.InSession = false;
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual(2, blocker.Calls, "analysed again after the session");
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task TheViewerComesBeforeTheJob()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, queued) = await SaveVideoAsync(library, "1", StillVideo(12));
var (_, viewed) = await SaveVideoAsync(library, "2", MovingVideo());
var blocker = new Blocker(library.Layout.FullPath(account, queued.RelativePath!));
using var service = new StillVideoService(Environment(library) with { Analyser = blocker.Analyse });
await service.StartAsync(new ExportSelection.Media([queued.Id]), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
var answer = await service.AnalyseNowAsync(viewed.Id, ct);
Assert.AreEqual(VideoAnalysisOutcome.Moving, answer.Analysis!.Outcome);
await blocker.Cancelled.Task.WaitAsync(Patience, ct); // the job's video was given up for the viewer
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual(2, blocker.Calls, "and analysed again after it");
Assert.AreEqual((1, 1), (service.Progress.Done, service.Progress.Still));
Assert.AreEqual(VideoAnalysisOutcome.Still, (await library.Db.VideoAnalyses.GetAsync(queued.Sha256!, ct))!.Outcome);
}
[TestMethod]
public async Task StopStoresNothingAndAStartAgainGoesOnWhereItWas()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, first) = await SaveVideoAsync(library, "1", StillVideo(13));
var (_, second) = await SaveVideoAsync(library, "2", MovingVideo());
var blocker = new Blocker(library.Layout.FullPath(account, first.RelativePath!));
var selection = new ExportSelection.Account(account.Id);
using (var service = new StillVideoService(Environment(library) with { Analyser = blocker.Analyse }))
{
await service.StartAsync(selection, ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
var stopped = service.Stop();
Assert.IsTrue(stopped.Stopped);
await service.Job.WaitAsync(Patience, ct);
var progress = service.Progress;
Assert.AreEqual((false, true, 0, 2), (progress.Running, progress.Stopped, progress.Done, progress.Total));
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct), "the video in progress stores nothing");
Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(second.Sha256!, ct), "the queue emptied");
Assert.AreEqual(1, blocker.Calls);
}
// Febe closed (a new service): nothing resumes by itself; started again, the job does it all.
using var again = new StillVideoService(Environment(library));
Assert.IsFalse(again.Progress.Running);
await again.StartAsync(selection, ct);
await again.Job.WaitAsync(Patience, ct);
Assert.AreEqual((2, false), (again.Progress.Done, again.Progress.Stopped));
Assert.AreEqual(2, (await again.PlanAsync(selection, ct)).AlreadyAnalysed);
}
[TestMethod]
public async Task OnlyTheJobStoresTooSlow()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, video) = await SaveVideoAsync(library, "1", StillVideo(14));
using var service = new StillVideoService(Environment(library) with { JobBudget = TimeSpan.Zero });
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await service.Job.WaitAsync(Patience, ct);
var row = await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct);
Assert.AreEqual((VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.TooSlow), (row!.Outcome, row.Note), "the job's budget is final (answer 44)");
Assert.AreEqual(1, service.Progress.NotAnalyzable);
Assert.AreEqual("Analizzato 1 video: 0 fermi, 0 in movimento, 1 non analizzabile", StillVideoText.Summary(service.Progress));
}
[TestMethod]
public async Task TheJobTakesTurnsWithTheConversions()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, video) = await SaveVideoAsync(library, "1", StillVideo(15));
var throttle = new ConversionThrottle();
var calls = new ConcurrentQueue<string>();
using var service = new StillVideoService(Environment(library) with { Throttle = throttle, Analyser = Counting(calls) });
var busy = new TaskCompletionSource();
var release = new TaskCompletionSource();
var conversion = throttle.RunAsync(_ =>
{
busy.SetResult();
release.Task.Wait(ct);
return 0;
}, ct);
await busy.Task;
await service.StartAsync(new ExportSelection.Account(account.Id), ct);
await UntilAsync(() => service.Progress.CurrentMediaId == video.Id, ct);
Assert.IsEmpty(calls, "no decode while a conversion holds the throttle");
release.SetResult();
await conversion;
await service.Job.WaitAsync(Patience, ct);
Assert.HasCount(1, calls);
}
[TestMethod]
public async Task AJobAskedWhileOneRunsAddsItsVideos()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var (account, first) = await SaveVideoAsync(library, "1", StillVideo(16));
var (_, second) = await SaveVideoAsync(library, "2", MovingVideo());
var blocker = new Blocker(library.Layout.FullPath(account, first.RelativePath!), cancelOnly: false);
using var service = new StillVideoService(Environment(library) with { Analyser = blocker.Analyse });
await service.StartAsync(new ExportSelection.Media([first.Id]), ct);
await blocker.Started.Task.WaitAsync(Patience, ct);
var added = await service.StartAsync(new ExportSelection.Media([first.Id, second.Id]), ct);
Assert.AreEqual((true, 2), (added.Running, added.Total), "the video in progress is not queued twice");
blocker.Release();
await service.Job.WaitAsync(Patience, ct);
Assert.AreEqual((2, 1, 1), (service.Progress.Done, service.Progress.Still, service.Progress.Moving));
}
// ------------------------------------------------------------------------------------------------- helpers
private static byte[] StillVideo(int seed, bool audio = false)
{
var photo = PcmVideos.Photo(seed);
return PcmVideos.Mp4(12, _ => photo, audio: audio);
}
private static byte[] MovingVideo() => PcmVideos.Mp4(12, i => PcmVideos.Photo(100 + i));
private static async Task<Core.Domain.Account> AccountAsync(TestLibrary library) =>
await library.Db.Accounts.FindByUsernameAsync("marta.demo") ?? await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
private static async Task<(Core.Domain.Account Account, Media Media)> SaveVideoAsync(TestLibrary library, string id, byte[] bytes)
{
var account = await AccountAsync(library);
var minutes = int.Parse(id, System.Globalization.CultureInfo.InvariantCulture);
var entry = await library.SaveAsync(account, Make.Entry(account.Id, id, Make.T0.AddMinutes(minutes)), [new TestFile(Make.Video(1), bytes, ".mp4")]);
var media = entry.Media[0];
Assert.IsTrue(EntryStateRules.IsPresent(media.State));
return (account, media);
}
private static StillVideoEnvironment Environment(TestLibrary library, LongWorkGate? gate = null) => new()
{
Storage = library.Db,
Resolve = (account, media) => media.RelativePath is { } relative && library.Layout.FullPath(account, relative) is var path && File.Exists(path) ? path : null,
Clock = new PollingClock(library.Clock),
Gate = gate,
Throttle = new ConversionThrottle(),
Poll = TimeSpan.FromMilliseconds(5),
};
/// <summary>The real analysis, counting the files it is given.</summary>
private static Func<string, TimeSpan, CancellationToken, StillVideoResult> Counting(ConcurrentQueue<string> calls) => (path, budget, ct) =>
{
calls.Enqueue(path);
return RealAnalysis(path, budget, ct);
};
private static StillVideoResult RealAnalysis(string path, TimeSpan budget, CancellationToken ct)
{
using var stream = File.OpenRead(path);
return StillVideoAnalyzer.Analyse(stream, budget == Timeout.InfiniteTimeSpan ? TimeSpan.MaxValue : budget, ct);
}
private static async Task UntilAsync(Func<bool> condition, CancellationToken ct)
{
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(Patience);
while (!condition())
{
await Task.Delay(2, limit.Token);
}
}
/// <summary>
/// An analysis that, the first time it is given <paramref name="path"/>, holds until its token is cancelled (or,
/// with <paramref name="cancelOnly"/> false, until <see cref="Release"/>); every other call is the real analysis.
/// </summary>
private sealed class Blocker(string path, bool cancelOnly = true)
{
private readonly ManualResetEventSlim _release = new();
private int _calls;
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Cancelled { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public int Calls => Volatile.Read(ref _calls);
public void Release() => _release.Set();
public StillVideoResult Analyse(string file, TimeSpan budget, CancellationToken ct)
{
if (string.Equals(file, path, StringComparison.Ordinal) && Interlocked.Increment(ref _calls) == 1)
{
Started.TrySetResult();
try
{
if (cancelOnly)
{
ct.WaitHandle.WaitOne(Patience);
}
else
{
_release.Wait(Patience, ct);
}
ct.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
Cancelled.TrySetResult();
throw;
}
}
return RealAnalysis(file, budget, ct);
}
}
/// <summary>The library's manual time, with waits that really pass (a few milliseconds), so a polling loop never spins.</summary>
private sealed class PollingClock(ManualClock time) : IClock
{
public DateTimeOffset Now => time.Now;
public TimeZoneInfo LocalZone => time.LocalZone;
public Task Delay(TimeSpan wait, CancellationToken ct) => Task.Delay(wait, ct);
}
}