Il passaggio che segue la ripresa di un giro non rifà il lavoro di recupero (prova delle cartelle in pausa, ripresa dei lavori fermati da un errore): un lavoro che si ferma di nuovo aspetta il giro dopo invece di essere ripreso all'infinito senza dormire. Il giro misura lo spazio per il lavoro automatico che riprenderebbe, non per una pausa di Alberto, così una pausa per spazio non va e viene con un evento nuovo ogni volta. «Annulla» tiene lontane le partenze automatiche finché il lavoro è annullato; «Esporta questo account» spento ferma subito la copia automatica; «Cerca i video fermi» chiede di fermarsi a una copia automatica partita dopo di lei; un file che manca sul disco non crea più un lavoro automatico a ogni passaggio. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
860 lines
33 KiB
C#
860 lines
33 KiB
C#
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>
|
|
/// As <see cref="TooSlow"/>, on a video with a result the selection would skip: that result stays (503).
|
|
/// </summary>
|
|
TooSlowKept,
|
|
}
|
|
|
|
/// <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,
|
|
StillVideoAnswerKind.TooSlowKept => StillVideoText.TooSlowKept,
|
|
_ => 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); one whose analysis took too long counts among
|
|
/// those to analyse.
|
|
/// </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>
|
|
/// <param name="Added">Of the answer of a start: the videos it added to the job (those already queued are not); else 0.</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,
|
|
int Added = 0);
|
|
|
|
/// <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). An automatic copy is the exception: a start asks it to stop
|
|
/// (<see cref="LongWorkGate.CancelYielding"/>, tappa E5), and the job waits only until it has let go. 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, 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.</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 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();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The answer past the budget of the viewer: «avviala dalla selezione» only for a video the selection would analyse.
|
|
/// </summary>
|
|
private async Task<StillVideoAnswer> 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
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
|
|
|
|
/// <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, with how many videos were added.
|
|
/// </summary>
|
|
public async Task<StillVideoProgress> 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;
|
|
}
|
|
|
|
/// <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 && 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();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The library file of <paramref name="item"/> 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).
|
|
/// </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 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;
|
|
}
|
|
|
|
/// <summary>The path of a library file that is really on the disk, or null.</summary>
|
|
private async Task<string?> 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;
|
|
}
|
|
|
|
/// <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. 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.
|
|
/// </summary>
|
|
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;
|
|
}
|
|
|
|
/// <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) && 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<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));
|
|
}
|
|
}
|
|
}
|