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; /// /// «È 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 (), a fake engine /// session and a real and . /// [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(); 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(); 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(); var changed = new ConcurrentQueue(); 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(); 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(); 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 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), }; /// The real analysis, counting the files it is given. private static Func Counting(ConcurrentQueue 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 condition, CancellationToken ct) { using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); limit.CancelAfter(Patience); while (!condition()) { await Task.Delay(2, limit.Token); } } /// /// An analysis that, the first time it is given , holds until its token is cancelled (or, /// with false, until ); every other call is the real analysis. /// 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); } } /// The library's manual time, with waits that really pass (a few milliseconds), so a polling loop never spins. 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); } }