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))
{