diff --git a/tests/Carina.Api.Tests/FeatureTest/CaptionDeliveryTests.cs b/tests/Carina.Api.Tests/Feature/Captions/CaptionDeliveryTests.cs similarity index 55% rename from tests/Carina.Api.Tests/FeatureTest/CaptionDeliveryTests.cs rename to tests/Carina.Api.Tests/Feature/Captions/CaptionDeliveryTests.cs index a09d08824..953778feb 100644 --- a/tests/Carina.Api.Tests/FeatureTest/CaptionDeliveryTests.cs +++ b/tests/Carina.Api.Tests/Feature/Captions/CaptionDeliveryTests.cs @@ -1,200 +1,17 @@ using System.Net; -using System.Net.Http.Headers; using System.Text.Json; -using Carina.Domain.Captions; +using Carina.Api.Tests.FeatureTest; using Carina.Domain.Encodings; -using Carina.Domain.Integrity; -using Carina.Domain.Playback; using Carina.Domain.Recordings; -using Carina.Domain.Streaming; -using Carina.Domain.Viewing; using Carina.Infrastructure.Captions; -using Carina.TestSupport; -using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Hosting; -using IRecordingDetectionRepository = Carina.Domain.Segments.IRecordingDetectionRepository; -using ISegmentModelVersionRepository = Carina.Domain.Segments.ISegmentModelVersionRepository; -using ISegmentSettingsRepository = Carina.Domain.Segments.ISegmentSettingsRepository; - -namespace Carina.Api.Tests.FeatureTest; - -internal sealed class CaptionFeature : IAsyncDisposable -{ - public static readonly OutputRoot Root = new("bulk"); - - public static readonly TimeSpan FileBegins = TimeSpan.FromSeconds(6115.5); - - private const long Second = CaptionCue.Hertz; - - private readonly TestingWebApplicationFactory factory = new(); - - private readonly DirectoryInfo mounted = Directory.CreateTempSubdirectory("carina-captions-mounted-"); - - private readonly DirectoryInfo encoded = Directory.CreateTempSubdirectory("carina-captions-encoded-"); - - private readonly DirectoryInfo shelved = Directory.CreateTempSubdirectory("carina-captions-shelf-"); - - public CaptionFeature(bool anywhereToKeepThem = true) - { - Settings = new CaptionSettings { WrittenTo = anywhereToKeepThem ? shelved.FullName : null }; - - WebApplicationFactory configured = factory - .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => - { - services.RemoveAll(); - services.RemoveAll(); - services.AddSingleton(Recordings); - services.AddSingleton(Settings); - services.AddSingleton(new IntegritySettings - { - OutputRoots = [new StorageRootPath(Root, mounted.FullName)], - }); - services.AddSingleton(new EncodeSettings - { - OutputRoots = [new StorageRootPath(EncodedArtefact.Shelf, encoded.FullName)], - }); - services.AddSingleton(Jobs); - services.AddSingleton(Profiles); - services.RemoveAll(); - services.AddSingleton(Codecs); - services.RemoveAll(); - services.AddSingleton(new HeldOnTheFlyPlayer()); - services.RemoveAll(); - services.AddSingleton(new HeldEncodeChapters()); - services.AddSingleton(new HeldPlaybackPositions()); - services.AddSingleton(new HeldSegmentSettings()); - services.AddSingleton(new HeldSegmentModelVersions()); - services.AddSingleton(new HeldRecordingDetections()); - })); - - Client = configured.WithTestScheme().CreateClient(); - Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( - TestAuthenticationHandler.SchemeName, - "anything"); - Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - Stranger = configured.WithTestScheme().CreateClient(); - } - - public CaptionSettings Settings { get; } - - public HttpClient Client { get; } - - public HttpClient Stranger { get; } - - public HeldRecordings Recordings { get; } = new(); - - public HeldEncodeJobs Jobs { get; } = new(); - - public HeldEncodeProfiles Profiles { get; } = new(); - - public HeldArtefactCodecs Codecs { get; } = new(); - - public static CaptionRecord Record(TimeSpan? begins = null) - => new( - 1440, - 1080, - begins ?? FileBegins, - [ - new CaptionCue(At(6115.7), Picture(10)), - new CaptionCue(At(6120.5), Picture(20)), - new CaptionCue(At(6123.5), null), - new CaptionCue(At(6800), Picture(30)), - ]); - - public Recording Ended(bool scrambled = false) - { - Recording recording = RecordingFeature.Begin(RecordingId.New()); - recording.Wrote(TimeSpan.FromMinutes(30)); - recording.Abort(RecordingFeature.Noon.AddMinutes(30)); - - if (scrambled) - { - recording.Note(new OutcomeDetail(RecordingFault.ScramblingUnresolved, null, string.Empty, RecordingFeature.Noon.AddMinutes(30))); - } - - recording.Settle(scrambled ? RecordingOutcome.Truncated : RecordingOutcome.Complete, 4_000, RecordingFeature.Noon.AddMinutes(30)); - Recordings.Recordings.Add(recording); - File.WriteAllBytes(Path.Combine(mounted.FullName, recording.FileName.Value), new byte[4_000]); - - return recording; - } - - public async Task CaptionedAsync(CaptionRecord? record = null, bool onTheShelf = true) - { - Recording recording = Ended(); - recording.Caption(CaptionState.Ready, 3, RecordingFeature.Noon.AddHours(1)); - - if (onTheShelf) - { - await new CaptionShelf(Settings).KeepAsync(recording.Id, record ?? Record(), CancellationToken.None); - } - - return recording; - } - - public void Encoded(Recording recording, EncodeTimeline? timeline, EncodeCodec codec = EncodeCodec.H264, string? taggedAs = null) - { - EncodeProfile profile = EncodedArtefact.Profile(codec, RecordingFeature.Noon.AddHours(-1)); - Profiles.Profiles.Add(profile); - - EncodeJob job = EncodedArtefact.Made(recording, profile, RecordingFeature.Noon.AddHours(1), timeline); - Jobs.Jobs.Add(job); - - if (codec is EncodeCodec.H265) - { - Codecs.ReadAs(job.ArtefactName!, codec, taggedAs); - } - - File.WriteAllBytes(Path.Combine(encoded.FullName, job.ArtefactName!.Value), new byte[900]); - } - - public Task CaptionsAsync(Recording recording, string query = "", HttpClient? asking = null) - => (asking ?? Client).GetAsync(new Uri($"/api/videos/{recording.Id.Wire}/captions{query}", UriKind.Relative)); - - public async Task PlannedAsync(Recording recording, string query = "") - { - using HttpResponseMessage answer = await Client.GetAsync(new Uri($"/api/videos/{recording.Id.Wire}/play{query}", UriKind.Relative)); - - Assert.True(answer.StatusCode is HttpStatusCode.OK, await answer.Content.ReadAsStringAsync()); - - using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); - - return read.RootElement.GetProperty("data").GetProperty("captions").GetString(); - } - - public static async Task WindowOfAsync(HttpResponseMessage answer) - { - Assert.True(answer.StatusCode is HttpStatusCode.OK, await answer.Content.ReadAsStringAsync()); - - using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); - - return read.RootElement.GetProperty("data").Clone(); - } - - public static double[] Moments(JsonElement window) - => [.. window.GetProperty("cues").EnumerateArray().Select(cue => Math.Round(cue.GetProperty("atSec").GetDouble(), 3))]; - - public async ValueTask DisposeAsync() - { - Client.Dispose(); - Stranger.Dispose(); - await factory.DisposeAsync(); - mounted.Delete(recursive: true); - encoded.Delete(recursive: true); - shelved.Delete(recursive: true); - } - - private static long At(double seconds) => (long)Math.Round(seconds * Second); - - private static CaptionPlacement Picture(int left) => new(left, 900, 320, 48, new byte[] { 0x89, 0x50, 0x4e, 0x47, (byte)left }); -} +namespace Carina.Api.Tests.Feature.Captions; +[Trait("Category", "Feature")] public sealed class CaptionDeliveryTests { [Fact] @@ -258,7 +75,6 @@ public async Task BrPd017OnTheArtefactEachCaptionIsAtItsMomentLessTheJobsCaption JsonElement window = await CaptionFeature.WindowOfAsync(answer); Assert.Equal([0.0, 4.5, 7.5], CaptionFeature.Moments(window)); - Assert.Equal("ready", await feature.PlannedAsync(recording)); } [Fact] @@ -298,8 +114,6 @@ public async Task BrPd017TheTwoClocksDisagreeingByAMillisecondDrawsNothingOverTh Assert.Equal(HttpStatusCode.NotFound, overTheArtefact.StatusCode); Assert.Equal(HttpStatusCode.OK, overTheRecording.StatusCode); - Assert.Equal("none", await feature.PlannedAsync(recording, "?source=artefact")); - Assert.Equal("ready", await feature.PlannedAsync(recording, "?source=recording")); } [Fact] @@ -312,11 +126,10 @@ public async Task AnArtefactWhoseJobNeverMeasuredItsTimelineHasNoCaptionsOverIt( using HttpResponseMessage answer = await feature.CaptionsAsync(recording); Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Equal("none", await feature.PlannedAsync(recording)); } [Fact] - public async Task BrPd017CaptionsStillBeingTakenAreRefusedAsComingAndThePlanSaysSo() + public async Task BrPd017CaptionsStillBeingTakenAreRefusedAsComing() { await using var feature = new CaptionFeature(); Recording recording = feature.Ended(); @@ -324,11 +137,10 @@ public async Task BrPd017CaptionsStillBeingTakenAreRefusedAsComingAndThePlanSays using HttpResponseMessage answer = await feature.CaptionsAsync(recording); Assert.Equal(HttpStatusCode.Conflict, answer.StatusCode); - Assert.Equal("coming", await feature.PlannedAsync(recording)); } [Fact] - public async Task BrPd017ARecordingWithNoCaptionsIsRefusedAsNotFoundAndThePlanSaysNone() + public async Task BrPd017ARecordingWithNoCaptionsIsRefusedAsNotFound() { await using var feature = new CaptionFeature(); Recording recording = feature.Ended(); @@ -337,7 +149,6 @@ public async Task BrPd017ARecordingWithNoCaptionsIsRefusedAsNotFoundAndThePlanSa using HttpResponseMessage answer = await feature.CaptionsAsync(recording); Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Equal("none", await feature.PlannedAsync(recording)); } [Fact] @@ -349,7 +160,6 @@ public async Task BrPd016CaptionsTheRowSaysAreReadyWithNoRecordOnTheShelfAreComi using HttpResponseMessage answer = await feature.CaptionsAsync(recording, "?source=recording"); Assert.Equal(HttpStatusCode.Conflict, answer.StatusCode); - Assert.Equal("coming", await feature.PlannedAsync(recording, "?source=recording")); Assert.Equal(CaptionState.Ready, recording.CaptionState); } @@ -390,7 +200,6 @@ public async Task WithNowhereToKeepCaptionsThereAreNone() using HttpResponseMessage answer = await feature.CaptionsAsync(recording); Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Equal("none", await feature.PlannedAsync(recording)); } [Theory] diff --git a/tests/Carina.Api.Tests/Feature/Playback/GatedOnTheFlyPlayer.cs b/tests/Carina.Api.Tests/Feature/Playback/GatedOnTheFlyPlayer.cs new file mode 100644 index 000000000..5496aa15b --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Playback/GatedOnTheFlyPlayer.cs @@ -0,0 +1,26 @@ +using Carina.Domain.Channels; +using Carina.Domain.Playback; +using Carina.Domain.Streaming; + +namespace Carina.Api.Tests.Feature.Playback; + +internal sealed class GatedOnTheFlyPlayer(byte[] bytes) : IOnTheFlyPlayer +{ + public GatedStream Handed { get; } = new(bytes); + + public Task StartAsync( + PlaybackFile file, + ServiceId service, + TimeSpan from, + LiveProfile? profile, + VideoCodec format, + SoundPlacement sound, + CancellationToken cancellationToken) + => Task.FromResult(OnTheFlyStart.Started(new GatedViewing(Handed))); + + public Task SoundsAsync( + PlaybackFile file, + ServiceId service, + CancellationToken cancellationToken) + => Task.FromResult(CarriedSounds.Counted(1)); +} diff --git a/tests/Carina.Api.Tests/Feature/Playback/GatedPlaybackFiles.cs b/tests/Carina.Api.Tests/Feature/Playback/GatedPlaybackFiles.cs new file mode 100644 index 000000000..5e3ce203f --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Playback/GatedPlaybackFiles.cs @@ -0,0 +1,17 @@ +using Carina.Domain.Playback; +using Carina.Domain.Recordings; +using Carina.Domain.Streaming; + +namespace Carina.Api.Tests.Feature.Playback; + +internal sealed class GatedPlaybackFiles(byte[] bytes) : IPlaybackFileStore +{ + public GatedStream Handed { get; } = new(bytes); + + public PlaybackFileSearch Find(OutputRoot root, RecordingFileName fileName) + => PlaybackFileSearch.Of(new PlaybackFile(root, fileName, bytes.Length)); + + public PlaybackFileOpening OpenRead(PlaybackFile file) => PlaybackFileOpening.Of(Handed); + + public StreamSource? SourceOf(PlaybackFile file) => null; +} diff --git a/tests/Carina.Api.Tests/Feature/Playback/GatedStream.cs b/tests/Carina.Api.Tests/Feature/Playback/GatedStream.cs new file mode 100644 index 000000000..c08442754 --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Playback/GatedStream.cs @@ -0,0 +1,86 @@ +namespace Carina.Api.Tests.Feature.Playback; + +internal sealed class GatedStream(byte[] bytes) : Stream +{ + private readonly SemaphoreSlim released = new(0); + + private long position; + + private int reach; + + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override long Length => bytes.Length; + + public override long Position + { + get => position; + set => position = value; + } + + public void Release(int upTo) + { + Volatile.Write(ref reach, upTo); + released.Release(); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + while (position >= Volatile.Read(ref reach) && position < bytes.Length) + { + await released.WaitAsync(cancellationToken); + } + + int take = (int)Math.Min(Math.Min(buffer.Length, Volatile.Read(ref reach) - position), bytes.Length - position); + + if (take <= 0) + { + return 0; + } + + bytes.AsMemory((int)position, take).CopyTo(buffer); + position += take; + + return take; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override int Read(byte[] buffer, int offset, int count) + => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); + + public override long Seek(long offset, SeekOrigin origin) + { + position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => position + offset, + _ => bytes.Length + offset, + }; + + return position; + } + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + released.Dispose(); + } + + base.Dispose(disposing); + } +} diff --git a/tests/Carina.Api.Tests/Feature/Playback/GatedViewing.cs b/tests/Carina.Api.Tests/Feature/Playback/GatedViewing.cs new file mode 100644 index 000000000..e1a8fe219 --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Playback/GatedViewing.cs @@ -0,0 +1,21 @@ +using Carina.Domain.Streaming; + +namespace Carina.Api.Tests.Feature.Playback; + +internal sealed class GatedViewing(GatedStream output) : IOnTheFlyViewing +{ + public OnTheFlyStanding Standing { get; } = new( + TimeSpan.Zero, + TimeSpan.FromMilliseconds(1), + LiveProfile.Hd30, + LiveEncoderChoice.Asked(LiveEncoder.Software), + attributesWereMeasured: true, + 1, + 2); + + public Stream Output => output; + + public Task Completion { get; } = Task.FromResult(TranscoderExit.Finished()); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; +} diff --git a/tests/Carina.Api.Tests/Feature/Playback/PlayDeliveryTests.cs b/tests/Carina.Api.Tests/Feature/Playback/PlayDeliveryTests.cs new file mode 100644 index 000000000..582fee209 --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Playback/PlayDeliveryTests.cs @@ -0,0 +1,2207 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; + +using Carina.Api.Playback; +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Auth; +using Carina.Domain.Base; +using Carina.Domain.Encodings; +using Carina.Domain.Playback; +using Carina.Domain.Recordings; +using Carina.Domain.Segments; +using Carina.Domain.Streaming; +using Carina.Domain.Viewing; +using Carina.TestSupport; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +using SoundPlacement = Carina.Domain.Streaming.SoundPlacement; + +namespace Carina.Api.Tests.Feature.Playback; + +[Trait("Category", "Feature")] +public sealed class PlayDeliveryTests +{ + private const int Size = 256 * 1024; + + private const int FirstHalf = Size / 2; + + private static readonly DateTime Noon = new(2026, 9, 16, 12, 0, 0, DateTimeKind.Utc); + + private static readonly EncodeTimeline HalfASecondSkipped = new(TimeSpan.FromSeconds(1.4), TimeSpan.FromSeconds(0.5), TimeSpan.FromMinutes(30), TimeSpan.FromSeconds(1799.5)); + + private static readonly byte[] Written = [.. Enumerable.Range(0, Size).Select(index => (byte)(index % 251))]; + + [Theory] + [InlineData(RecordingOutcome.Complete, "whole", true)] + [InlineData(RecordingOutcome.Truncated, "cutShort", false)] + [InlineData(RecordingOutcome.Failed, "failed", false)] + public async Task HowTheRecordingEndedIsPartOfEveryAnswerSoNoneOfTheThreeLooksLikeAnother( + RecordingOutcome outcome, + string said, + bool whole) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(outcome); + + using HttpResponseMessage plan = await feature.PlanAsync(recording); + JsonElement read = await PlayFeature.PlanOfAsync(plan); + using HttpResponseMessage picture = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.OK, plan.StatusCode); + Assert.Equal(said, read.GetProperty("data").GetProperty("standing").GetString()); + Assert.Equal(whole, read.GetProperty("data").GetProperty("showsAsAWholeRecording").GetBoolean()); + Assert.Equal(said, Header(picture, PlaybackHeaders.Standing)); + } + + [Fact] + public async Task AViewerWhoNamesNoSoundIsGivenTheMainOneAsTheyAlwaysWere() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Player.Sounds = 2; + + using HttpResponseMessage answer = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal([SoundPlacement.WholeStream(0)], feature.Player.AskedWith); + } + + [Fact] + public async Task AViewerWhoAsksForTheSecondSoundIsGivenIt() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Player.Sounds = 2; + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal([SoundPlacement.WholeStream(1)], feature.Player.AskedWith); + } + + [Fact] + public async Task ARecordingOfABroadcastThatCarriedOneSoundHasNoSecondOneToAskFor() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Player.Sounds = 1; + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.AskedWith); + Assert.Equal( + PlayDelivery.TheRecordingDoesNotCarryThatSound, + (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); + } + + [Fact] + public async Task ARecordingOfABroadcastThatCarriedTwoSoundsOfTheirOwnHasNoThirdOneToAskFor() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 2); + feature.Player.Sounds = 2; + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=third"); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.AskedWith); + Assert.Equal( + PlayDelivery.TheRecordingDoesNotCarryThatSound, + (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); + } + + [Fact] + public void TheSoundsARecordingCanBePlayedWithAreNamedInTheRefusal() + => Assert.All(SoundTracks.Names, name => Assert.Contains(name, PlayDelivery.TheSoundsThereAre, StringComparison.Ordinal)); + + [Fact] + public async Task ARecordingWhoseSoundsCouldNotBeReadIsNotStartedOnAGuess() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Player.SoundsCannotBeRead = "the programme was still reading the stream"; + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); + Assert.Empty(feature.Player.AskedWith); + } + + [Theory] + [InlineData("sub")] + [InlineData("Main")] + [InlineData("1")] + public async Task ASoundThisApplicationDoesNotCarryIsRefusedAndTheOnesItDoesAreNamed(string said) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.PictureAsync(recording, $"?sound={said}"); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.AskedWith); + Assert.Equal( + PlayDelivery.TheSoundsThereAre, + (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); + } + + [Theory] + [InlineData("encoded")] + [InlineData("Artefact")] + [InlineData("1")] + [InlineData("../../etc/passwd")] + public async Task SomethingThisApplicationCannotPlayARecordingFromIsRefusedAndTheTwoItCanAreNamed(string said) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.PictureAsync(recording, $"?source={said}"); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.Opened); + Assert.Equal( + PlayDelivery.TheSourcesThereAre, + (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); + } + + [Theory] + [InlineData("encoded")] + [InlineData("Artefact")] + public async Task APlanAskedForFromSomethingThisApplicationCannotPlayARecordingFromIsRefusedTheSameWay( + string said) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.PlanAsync(recording, $"?source={said}"); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Equal( + PlayDelivery.TheSourcesThereAre, + (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); + } + + [Theory] + [InlineData("?source=recording")] + [InlineData("?source=artefact")] + [InlineData("")] + public async Task ARecordingNothingHasEncodedIsTranscodedFromItselfWhicheverSourceIsAskedFor(string query) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, bytes: 2_500); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, query); + JsonElement read = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, query))).GetProperty("data"); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); + } + + [Fact(DisplayName = "a recording asked for as it was recorded takes one of the few pictures this machine transcodes at once, and is refused when they are all taken")] + public async Task ARecordingAskedForAsItWasRecordedIsRefusedWhenAsManyAreBeingTranscodedAsThisMachineAllows() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + feature.Player.Refuses = OnTheFlyRefusal.TooManyAlready; + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=recording"); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, picture.StatusCode); + Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); + } + + [Fact] + public async Task BrEd2019AnArtefactHandedOutWholeIsNotedAsOpenedAndAPlanOpensNothing() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + string artefact = feature.Jobs.Jobs.Single().ArtefactName!.Value; + + using HttpResponseMessage plan = await feature.PlanAsync(recording); + + Assert.Null(feature.Reads.LastOpened(EncodedArtefact.Shelf, artefact)); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, string.Empty, "bytes=0-99"); + + Assert.Equal(HttpStatusCode.PartialContent, picture.StatusCode); + Assert.NotNull(feature.Reads.LastOpened(EncodedArtefact.Shelf, artefact)); + } + + [Fact] + public async Task ThePlanNamesTheSoundsTheRecordingCanBeAskedFor() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Player.Sounds = 2; + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal( + ["main", "secondary"], + read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); + } + + [Fact] + public async Task ThePlanOfABroadcastThatCarriedOneSoundNamesOnlyTheMainOne() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Player.Sounds = 1; + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal( + ["main"], + read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); + } + + [Fact] + public async Task ThePlanOfARecordingWhoseSoundsCouldNotBeReadNamesTheMainSoundItPlaysRatherThanNone() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Player.SoundsCannotBeRead = "the programme was still reading the stream"; + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal( + ["main"], + read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); + } + + [Fact] + public async Task ThePlanOfASecondSoundThatCouldNotBeReadIsRefusedAsThePictureOfItIs() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Player.SoundsCannotBeRead = "the programme was still reading the stream"; + + using HttpResponseMessage plan = await feature.PlanAsync(recording, "?sound=secondary"); + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, plan.StatusCode); + Assert.Equal(picture.StatusCode, plan.StatusCode); + Assert.Equal( + (await PlayFeature.PlanOfAsync(picture)).GetProperty("message").GetString(), + (await PlayFeature.PlanOfAsync(plan)).GetProperty("message").GetString()); + } + + [Fact] + public async Task BrPd008ARecordingWhoseBroadcastPutTwoLanguagesOnOneSoundIsPlayedWithOneOfThemInBothEars() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); + feature.Player.Sounds = 1; + + using HttpResponseMessage main = await feature.PictureAsync(recording); + using HttpResponseMessage secondary = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.OK, main.StatusCode); + Assert.Equal(HttpStatusCode.OK, secondary.StatusCode); + Assert.Equal( + [ + SoundPlacement.OneChannelOf(0, SoundChannel.Left), + SoundPlacement.OneChannelOf(0, SoundChannel.Right), + ], + feature.Player.AskedWith); + } + + [Fact] + public async Task ThePlanOfABroadcastThatPutTwoLanguagesOnOneSoundNamesBothOfThem() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); + feature.Player.SoundsCannotBeRead = "the stream is never asked when the broadcast announced its sound"; + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal( + ["main", "secondary"], + read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); + } + + [Fact] + public async Task BrPd008ARecordingWithTwoLanguagesOnTheMainSoundBesideASecondStreamIsPlayedWithAnyOfTheThree() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 2); + feature.Player.Sounds = 2; + + using HttpResponseMessage main = await feature.PictureAsync(recording); + using HttpResponseMessage secondary = await feature.PictureAsync(recording, "?sound=secondary"); + using HttpResponseMessage third = await feature.PictureAsync(recording, "?sound=third"); + + Assert.Equal( + [HttpStatusCode.OK, HttpStatusCode.OK, HttpStatusCode.OK], + [main.StatusCode, secondary.StatusCode, third.StatusCode]); + Assert.Equal( + [ + SoundPlacement.OneChannelOf(0, SoundChannel.Left), + SoundPlacement.OneChannelOf(0, SoundChannel.Right), + SoundPlacement.WholeStream(1), + ], + feature.Player.AskedWith); + } + + [Fact] + public async Task ThePlanOfABroadcastWithTwoLanguagesOnTheMainSoundBesideASecondStreamNamesAllThree() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 2); + feature.Player.SoundsCannotBeRead = "the stream is never asked when the broadcast announced its sound"; + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal( + ["main", "secondary", "third"], + read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); + } + + [Fact] + public async Task ABroadcastThatAnnouncedTwoSoundsOfTheirOwnIsPlayedByTakingTheSecondStreamItCarries() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 2); + feature.Player.Sounds = 2; + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal([SoundPlacement.WholeStream(1)], feature.Player.AskedWith); + Assert.Equal(1, feature.Player.AskedWhatItCarries); + } + + [Fact] + public async Task ABroadcastThatAnnouncedTwoSoundsTheRecordingDoesNotCarryIsRefusedRatherThanStarted() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 2); + feature.Player.Sounds = 1; + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.AskedWith); + Assert.Equal(1, feature.Player.AskedWhatItCarries); + Assert.Equal( + PlayDelivery.TheRecordingDoesNotCarryThatSound, + (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); + } + + [Fact] + public async Task ARecordingWhoseAnnouncedSecondSoundCannotBeLookedForIsNotStartedOnAGuess() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 2); + feature.Player.SoundsCannotBeRead = "the programme was still reading the stream"; + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); + Assert.Empty(feature.Player.AskedWith); + } + + [Fact] + public async Task ABroadcastThatAnnouncedTheOneSoundHasNoSecondOneEvenWhereTheStreamCarriesTwo() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 1); + feature.Player.Sounds = 2; + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.AskedWith); + Assert.Equal(0, feature.Player.AskedWhatItCarries); + Assert.Equal( + ["main"], + read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); + } + + [Fact] + public async Task ABroadcastThatAnnouncedItsMainSoundOnlyIsPlayedWithoutTheStreamBeingRead() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 1); + feature.Player.SoundsCannotBeRead = "the stream is never asked for the main sound of an announced recording"; + + using HttpResponseMessage answer = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal([SoundPlacement.WholeStream(0)], feature.Player.AskedWith); + Assert.Equal(0, feature.Player.AskedWhatItCarries); + } + + [Fact] + public async Task ARecordingThatHasNotEndedIsNotPlayedAtAll() + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.PlanAsync(feature.StillWriting()); + + Assert.Equal(HttpStatusCode.Conflict, answer.StatusCode); + Assert.False((await PlayFeature.PlanOfAsync(answer)).GetProperty("status").GetBoolean()); + } + + [Fact] + public async Task SeekingIsAStartingAgainAndTheAnswerSaysSoRatherThanPretendingToBeFast() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage plan = await feature.PlanAsync(recording); + JsonElement read = (await PlayFeature.PlanOfAsync(plan)).GetProperty("data"); + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?from=300"); + + Assert.Equal("byStartingAgain", read.GetProperty("seeking").GetString()); + Assert.False(read.GetProperty("canSeek").GetBoolean()); + Assert.True(read.GetProperty("transcodes").GetBoolean()); + + Assert.Equal("byStartingAgain", Header(picture, PlaybackHeaders.Seeking)); + Assert.Equal("false", Header(picture, PlaybackHeaders.CanSeek)); + Assert.Equal("none", Assert.Single(picture.Headers.AcceptRanges)); + } + + [Fact] + public async Task WhereTheZeroOfTheStreamSitsInsideTheRecordingIsNamedByTheAnswer() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?from=300"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("300", Header(answer, PlaybackHeaders.StartsAt)); + Assert.Equal(TimeSpan.FromSeconds(300), Assert.Single(feature.Player.AskedFrom)); + Assert.Equal(recording.ServiceId, Assert.Single(feature.Player.AskedOf)); + } + + [Fact] + public async Task WhatTheTranscoderWroteIsWhatComesBackAndItIsAnMp4() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.PictureAsync(recording); + byte[] body = await answer.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); + Assert.Equal(feature.Player.Picture, body); + Assert.True(feature.Player.Handed!.WasLetGo); + } + + [Fact] + public async Task TheAnswerSaysWhatItTookToStartAndHowManyAreRunning() + { + await using var feature = new PlayFeature(); + feature.Player.Running = 2; + feature.Player.AtOnce = 2; + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.PictureAsync(recording); + + Assert.Equal("0.138", Header(answer, PlaybackHeaders.Waited)); + Assert.Equal("2", Header(answer, PlaybackHeaders.Running)); + Assert.Equal("2", Header(answer, PlaybackHeaders.AtOnce)); + Assert.Equal("720p30", Header(answer, PlaybackHeaders.Profile)); + Assert.Equal("software", Header(answer, PlaybackHeaders.Encoder)); + Assert.Equal("true", Header(answer, PlaybackHeaders.AttributesWereMeasured)); + } + + [Fact] + public async Task WhenAsManyAreRunningAsThisMachineIsAskedToTheAnswerSaysWhyRatherThanHanging() + { + await using var feature = new PlayFeature(); + feature.Player.Refuses = OnTheFlyRefusal.TooManyAlready; + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); + Assert.Equal("tooManyAlready", Header(answer, PlaybackHeaders.Refusal)); + Assert.Equal("whole", Header(answer, PlaybackHeaders.Standing)); + } + + [Theory] + [InlineData(OnTheFlyRefusal.NothingToPlay, HttpStatusCode.NotFound)] + [InlineData(OnTheFlyRefusal.TranscoderWouldNotStart, HttpStatusCode.ServiceUnavailable)] + [InlineData(OnTheFlyRefusal.NothingCameOut, HttpStatusCode.ServiceUnavailable)] + [InlineData(OnTheFlyRefusal.TookTooLong, HttpStatusCode.ServiceUnavailable)] + public async Task EveryWayTheTranscoderCanRefuseHasAnAnswerOfItsOwn( + OnTheFlyRefusal refusal, + HttpStatusCode expected) + { + await using var feature = new PlayFeature(); + feature.Player.Refuses = refusal; + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); + + Assert.Equal(expected, answer.StatusCode); + Assert.Equal( + System.Text.Json.JsonNamingPolicy.CamelCase.ConvertName(refusal.ToString()), + Header(answer, PlaybackHeaders.Refusal)); + } + + [Fact] + public async Task ARecordingOfNoBytesIsNotHandedToATranscoder() + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.PlanAsync(feature.Ended(RecordingOutcome.Failed, 0)); + + Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); + Assert.Empty(feature.Player.AskedFrom); + } + + [Fact] + public async Task ARecordingWhoseFileIsGoneWhileItsRootIsThereIsNotFoundRatherThanHandedToATranscoder() + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.PlanAsync( + feature.Ended(RecordingOutcome.Complete, onDisk: false)); + + Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); + Assert.Empty(feature.Player.AskedFrom); + } + + [Fact] + public async Task ARecordingWhoseRootIsGoneIsOutOfReachRatherThanNotFoundAndNoTranscoderIsStarted() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + Directory.Delete(feature.MountedAt, recursive: true); + + using HttpResponseMessage answer = await feature.PlanAsync(recording); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); + Assert.Empty(feature.Player.AskedFrom); + } + + [Fact] + public async Task ARecordingNobodyHasIsNotFound() + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.Client.GetAsync( + new Uri($"/api/videos/{RecordingId.New().Wire}/play", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); + } + + [Fact] + public async Task SomethingThatIsNotARecordingIdIsRefusedBeforeAnythingIsLookedFor() + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.Client.GetAsync( + new Uri("/api/videos/not-an-id/play", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + } + + [Theory] + [InlineData("?profile=1080p60", "1080p60")] + [InlineData("?profile=720p60", "720p60")] + public async Task AProfileIsOneOfTheFewThereAre(string query, string chosen) + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(chosen, Assert.Single(feature.Player.AskedFor)); + } + + [Fact] + public async Task AskingForNoProfileLeavesTheChoiceToWhereTheEncoderIsKnownRatherThanNamingOneHere() + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Null(Assert.Single(feature.Player.AskedFor)); + } + + [Theory] + [InlineData(LiveEncoder.Vaapi, "1080p60")] + [InlineData(LiveEncoder.Software, "720p30")] + public async Task ARecordingNobodyChoseAProfileForOpensAtWhatThisMachineOpensAt( + LiveEncoder machine, + string opened) + { + await using var feature = new PlayFeature(); + feature.Player.Machine = machine; + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(opened, Header(answer, PlaybackHeaders.Profile)); + } + + [Fact] + public async Task AProfileNamedOutrightIsHonouredOnAMachineThatWouldHaveOpenedAtAnother() + { + await using var feature = new PlayFeature(); + feature.Player.Machine = LiveEncoder.Vaapi; + + using HttpResponseMessage answer = await feature.PictureAsync( + feature.Ended(RecordingOutcome.Complete), + "?profile=720p30"); + + Assert.Equal("720p30", Assert.Single(feature.Player.AskedFor)); + Assert.Equal("720p30", Header(answer, PlaybackHeaders.Profile)); + } + + [Theory(DisplayName = "a recording transcoded as it plays is encoded in the format asked for, where this machine encodes it")] + [InlineData("?format=h265", VideoCodec.H265)] + [InlineData("?format=av1", VideoCodec.Av1)] + [InlineData("?format=h264", VideoCodec.H264)] + public async Task ARecordingTranscodedAsItPlaysIsEncodedInTheFormatAskedFor(string query, VideoCodec format) + { + await using PlayFeature feature = new(VideoCodecs.InOrder); + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(format, Assert.Single(feature.Player.AskedIn)); + } + + [Fact(DisplayName = "a recording played without naming a format is transcoded in H.264, as it always was")] + public async Task ARecordingPlayedWithoutNamingAFormatIsTranscodedInH264() + { + await using PlayFeature feature = new(VideoCodecs.InOrder); + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(VideoCodec.H264, Assert.Single(feature.Player.AskedIn)); + } + + [Theory(DisplayName = "a format off the list is refused rather than passed on")] + [InlineData("?format=hevc")] + [InlineData("?format=AV1")] + [InlineData("?format=h264,h265")] + public async Task AFormatOffTheListIsRefusedRatherThanPassedOn(string query) + { + await using PlayFeature feature = new(VideoCodecs.InOrder); + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.AskedIn); + Assert.Equal( + PlayDelivery.TheFormatsThereAre, + (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); + } + + [Theory(DisplayName = "a format this machine does not encode is refused, picture and plan alike, rather than turned into H.264")] + [InlineData("h265")] + [InlineData("av1")] + public async Task AFormatThisMachineDoesNotEncodeIsRefusedRatherThanTurnedIntoH264(string format) + { + await using PlayFeature feature = new([VideoCodec.H264]); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?format=" + format); + using HttpResponseMessage plan = await feature.PlanAsync(recording, "?format=" + format); + + Assert.Equal(HttpStatusCode.BadRequest, picture.StatusCode); + Assert.Equal(HttpStatusCode.BadRequest, plan.StatusCode); + Assert.Empty(feature.Player.AskedIn); + Assert.Contains(format, (await PlayFeature.PlanOfAsync(picture)).GetProperty("message").GetString(), StringComparison.Ordinal); + } + + [Theory(DisplayName = "an artefact handed over as it is does not look at the format, even one this machine does not encode")] + [InlineData("?format=av1")] + [InlineData("?format=h265")] + public async Task AnArtefactHandedOverAsItIsDoesNotLookAtTheFormat(string query) + { + await using PlayFeature feature = new([VideoCodec.H264]); + Recording recording = feature.Ended(RecordingOutcome.Complete); + byte[] made = feature.Encoded(recording); + + using HttpResponseMessage plan = await feature.PlanAsync(recording, query); + using HttpResponseMessage picture = await feature.PictureAsync(recording, query); + + Assert.Equal(HttpStatusCode.OK, plan.StatusCode); + Assert.False((await PlayFeature.PlanOfAsync(plan)).GetProperty("data").GetProperty("transcodes").GetBoolean()); + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal(made, await picture.Content.ReadAsByteArrayAsync()); + Assert.Empty(feature.Player.AskedIn); + } + + [Theory] + [InlineData("?profile=4320p120")] + [InlineData("?profile=../../etc/passwd")] + public async Task AProfileThisApplicationDoesNotEncodeIsRefusedRatherThanPassedOn(string query) + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.AskedFor); + Assert.Equal( + PlayDelivery.TheProfilesThereAre, + (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); + } + + [Theory] + [InlineData("?from=-1")] + [InlineData("?from=soon")] + [InlineData("?from=NaN")] + [InlineData("?from=Infinity")] + public async Task APositionThatIsNotASecondIntoTheRecordingIsRefused(string query) + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(feature.Player.AskedFrom); + } + + [Fact] + public async Task AClientCarryingNoCredentialsIsRefusedRatherThanSentToASignInScreen() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.Stranger.GetAsync( + new Uri($"/api/videos/{recording.Id.Wire}/play", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); + Assert.Null(answer.Headers.Location); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task NothingHandedBackSaysWhereOnThisMachineTheFileIs() + { + await using var feature = new PlayFeature(); + Recording gone = feature.Ended(RecordingOutcome.Complete, onDisk: false); + + using HttpResponseMessage answer = await feature.PlanAsync(gone); + string body = await answer.Content.ReadAsStringAsync(); + + Assert.DoesNotContain(feature.MountedAt, body, StringComparison.Ordinal); + Assert.DoesNotContain( + answer.Headers.Concat(answer.Content.Headers), + header => header.Value.Any(value => value.Contains(feature.MountedAt, StringComparison.Ordinal))); + } + + [Fact] + public async Task NothingAboutThisAnswerMayBeHeldByAnythingInFront() + { + await using var feature = new PlayFeature(); + + using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); + + Assert.Equal(PlayDelivery.NeverCached, answer.Headers.CacheControl?.ToString()); + Assert.Contains("Accept", answer.Headers.Vary, StringComparer.OrdinalIgnoreCase); + } + + [Fact(DisplayName = "a recording nobody has watched is played from its beginning")] + public async Task ARecordingNobodyHasWatchedIsPlayedFromItsBeginning() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using HttpResponseMessage answer = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(TimeSpan.Zero, Assert.Single(feature.Player.AskedFrom)); + Assert.Equal("0", Header(answer, PlaybackHeaders.StartsAt)); + } + + [Fact(DisplayName = "playing without saying where starts where this viewer left this recording")] + public async Task PlayingWithoutSayingWhereStartsWhereThisViewerLeftIt() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + (HttpStatusCode kept, _) = await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 600 }); + + using HttpResponseMessage answer = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.OK, kept); + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(TimeSpan.FromSeconds(600), Assert.Single(feature.Player.AskedFrom)); + Assert.Equal("600", Header(answer, PlaybackHeaders.StartsAt)); + } + + [Fact(DisplayName = "saying where to start wins over where the watching was left")] + public async Task SayingWhereToStartWinsOverWhereTheWatchingWasLeft() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 600 }); + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?from=30"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(TimeSpan.FromSeconds(30), Assert.Single(feature.Player.AskedFrom)); + } + + [Fact(DisplayName = "asking to start at the beginning is not the same as asking for nothing")] + public async Task AskingToStartAtTheBeginningIsNotTheSameAsAskingForNothing() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 600 }); + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?from=0"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(TimeSpan.Zero, Assert.Single(feature.Player.AskedFrom)); + } + + [Fact(DisplayName = "where another viewer left a recording is not where this one is taken to")] + public async Task WhereAnotherViewerLeftARecordingIsNotWhereThisOneIsTakenTo() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + feature.Positions.Positions.Add(PlaybackPosition.Reached( + recording.Id, + new Subject("someone else"), + TimeSpan.FromSeconds(900), + Noon)); + + using HttpResponseMessage answer = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(TimeSpan.Zero, Assert.Single(feature.Player.AskedFrom)); + } + + [Fact(DisplayName = "the plan says where the watching got to, so a player that seeks itself can go there")] + public async Task ThePlanSaysWhereTheWatchingGotTo() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + using (HttpResponseMessage unwatched = await feature.PlanAsync(recording)) + { + JsonElement read = (await PlayFeature.PlanOfAsync(unwatched)).GetProperty("data"); + + Assert.Equal(JsonValueKind.Null, read.GetProperty("resumeAtSec").ValueKind); + } + + await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 612.5 }); + + using HttpResponseMessage watched = await feature.PlanAsync(recording); + JsonElement plan = (await PlayFeature.PlanOfAsync(watched)).GetProperty("data"); + + Assert.Equal(612.5, plan.GetProperty("resumeAtSec").GetDouble()); + } + + [Fact(DisplayName = "where the watching got to is kept once for a recording, whichever of the two it is watched from")] + public async Task WhereTheWatchingGotToIsTheSameWhicheverOfTheTwoThePlanIsAskedFor() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + + await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 618.5 }); + + using HttpResponseMessage asEncoded = await feature.PlanAsync(recording, "?source=artefact"); + using HttpResponseMessage asRecorded = await feature.PlanAsync(recording, "?source=recording"); + JsonElement artefact = (await PlayFeature.PlanOfAsync(asEncoded)).GetProperty("data"); + JsonElement itself = (await PlayFeature.PlanOfAsync(asRecorded)).GetProperty("data"); + + Assert.Equal("artefact", artefact.GetProperty("source").GetString()); + Assert.Equal("recording", itself.GetProperty("source").GetString()); + Assert.Equal(618.5, artefact.GetProperty("resumeAtSec").GetDouble()); + Assert.Equal(618.5, itself.GetProperty("resumeAtSec").GetDouble()); + Assert.Single(feature.Positions.Positions); + } + + [Fact(DisplayName = "a recording asked for as it was recorded is started where the watching got to, as it is when it is asked for encoded")] + public async Task ARecordingAskedForAsItWasRecordedIsStartedWhereTheWatchingGotTo() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + + await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 300 }); + + using HttpResponseMessage answer = await feature.PictureAsync(recording, "?source=recording"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(TimeSpan.FromSeconds(300), Assert.Single(feature.Player.AskedFrom)); + Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); + } + + [Fact] + public async Task AnArtefactOnTheDiskIsWhatComesBackAndNothingIsTranscodedWhilePlaying() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage plan = await feature.PlanAsync(recording); + JsonElement read = (await PlayFeature.PlanOfAsync(plan)).GetProperty("data"); + using HttpResponseMessage picture = await feature.PictureAsync(recording); + + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.False(read.GetProperty("transcodes").GetBoolean()); + Assert.True(read.GetProperty("canSeek").GetBoolean()); + Assert.Equal("video/mp4", read.GetProperty("mediaType").GetString()); + Assert.Equal(artefact.Length, read.GetProperty("bytes").GetInt64()); + + Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); + Assert.Null(feature.Player.Handed); + } + + [Fact] + public async Task AnArtefactCarriesTheOneSoundItWasEncodedWithSoThePlanNamesNoneToChooseFrom() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + feature.Player.Sounds = 2; + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.Empty(read.GetProperty("sounds").EnumerateArray()); + } + + [Fact] + public async Task AskingAnArtefactForASecondSoundIsRefusedRatherThanQuietlyGivingTheOneItHas() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.BadRequest, picture.StatusCode); + Assert.Equal( + PlayDelivery.NothingToChooseFrom, + (await PlayFeature.PlanOfAsync(picture)).GetProperty("message").GetString()); + Assert.Null(feature.Player.Handed); + } + + [Fact] + public async Task AskingAnArtefactForTheMainSoundHandsItOverAsItAlwaysWas() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=main"); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); + } + + [Fact(DisplayName = "an encoded recording of a broadcast that announced two sounds still offers both of them")] + public async Task ThePlanOfAnEncodedRecordingStillNamesTheSoundsTheBroadcastAnnounced() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); + feature.Encoded(recording); + feature.Player.SoundsCannotBeRead = "the stream is never asked when the broadcast announced its sound"; + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.Equal( + ["main", "secondary"], + read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); + Assert.Equal(0, feature.Player.AskedWhatItCarries); + } + + [Fact(DisplayName = "the secondary sound of an encoded recording is transcoded from the recording, because the artefact was baked with the main one")] + public async Task AskingAnEncodedRecordingForItsSecondSoundGoesBackToTheRecordingItself() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=secondary"); + byte[] body = await picture.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); + Assert.Equal([SoundPlacement.OneChannelOf(0, SoundChannel.Right)], feature.Player.AskedWith); + Assert.Equal(feature.Player.Picture, body); + Assert.NotEqual(artefact, body); + } + + [Fact(DisplayName = "the main sound of an encoded recording is the artefact itself, whatever the broadcast announced")] + public async Task AskingAnEncodedRecordingForItsMainSoundHandsOverTheArtefact() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=main"); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); + Assert.Null(feature.Player.Handed); + } + + [Fact] + public async Task ThePlanOfAnEncodedRecordingAskedForItsSecondSoundIsThePlanOfATranscode() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); + feature.Encoded(recording); + + JsonElement read = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, "?sound=secondary"))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.True(read.GetProperty("transcodes").GetBoolean()); + Assert.False(read.GetProperty("canSeek").GetBoolean()); + Assert.Equal("byStartingAgain", read.GetProperty("seeking").GetString()); + } + + [Fact(DisplayName = "when the recording itself is out of reach, the plan of an encoded recording asked for its second sound offers the artefact and the one sound it carries")] + public async Task ThePlanNarrowsToTheArtefactWhenTheSoundAskedForCannotBeReachedAnyMore() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended( + RecordingOutcome.Complete, + onDisk: false, + audio: AudioMode.DualMono, + sounds: 1); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage plan = await feature.PlanAsync(recording, "?sound=secondary"); + JsonElement read = (await PlayFeature.PlanOfAsync(plan)).GetProperty("data"); + + Assert.Equal(HttpStatusCode.OK, plan.StatusCode); + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.False(read.GetProperty("transcodes").GetBoolean()); + Assert.Equal(artefact.Length, read.GetProperty("bytes").GetInt64()); + Assert.Equal( + ["main"], + read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); + } + + [Fact(DisplayName = "a picture asked for a sound that cannot be reached is refused rather than quietly handed the artefact of another sound")] + public async Task ThePictureOfASoundThatCannotBeReachedIsRefusedRatherThanQuietlyHandedTheArtefact() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended( + RecordingOutcome.Complete, + onDisk: false, + audio: AudioMode.DualMono, + sounds: 1); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=secondary"); + + Assert.Equal(HttpStatusCode.NotFound, picture.StatusCode); + Assert.NotEqual(artefact, await picture.Content.ReadAsByteArrayAsync()); + Assert.Null(feature.Player.Handed); + } + + [Fact] + public async Task AnArtefactIsMovedAboutByAskingForARangeOfItRatherThanByStartingAgain() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + byte[] artefact = feature.Encoded(recording, bytes: 2_000); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, string.Empty, "bytes=1000-1099"); + + Assert.Equal(HttpStatusCode.PartialContent, picture.StatusCode); + Assert.Equal("byRange", Header(picture, PlaybackHeaders.Seeking)); + Assert.Equal("bytes", Assert.Single(picture.Headers.AcceptRanges)); + Assert.Equal(artefact[1_000..1_100], await picture.Content.ReadAsByteArrayAsync()); + Assert.Null(feature.Player.Handed); + } + + [Fact] + public async Task OfTwoArtefactsOfOneRecordingTheOneMadeLastIsPlayed() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, bytes: 700); + byte[] later = feature.Encoded(recording, minutesLater: 90, bytes: 1_300); + + using HttpResponseMessage picture = await feature.PictureAsync(recording); + + Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(later, await picture.Content.ReadAsByteArrayAsync()); + } + + [Fact(DisplayName = "an artefact a newer one replaced is never played, even while its file is still on the disk, so a newer one a browser cannot decode as it is leaves the recording to the transcoder")] + public async Task AnArtefactANewerOneReplacedIsNeverPlayed() + { + await using PlayFeature feature = new(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, bytes: 700); + feature.Encoded(recording, EncodeCodec.H265, minutesLater: 90); + feature.Jobs.Jobs[0].Replaced(feature.Jobs.Jobs[1], RecordingFeature.Noon.AddHours(3)); + + using HttpResponseMessage picture = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); + } + + [Fact] + public async Task AnArtefactTheLedgerNamesAndTheDiskHasNotIsTranscodedInsteadAndSaidToHaveBeen() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, onDisk: false); + + using HttpResponseMessage picture = await feature.PictureAsync(recording); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); + Assert.Equal("encodedFileGone", Header(picture, PlaybackHeaders.FellBack)); + Assert.Equal(feature.Player.Picture, await picture.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task AnArtefactABrowserWouldNotDecodeAsItIsIsLeftToTheTranscoder() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H265); + + using HttpResponseMessage picture = await feature.PictureAsync(recording); + + Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); + Assert.Null(Header(picture, PlaybackHeaders.FellBack)); + } + + [Fact(DisplayName = "an artefact made in H.264 is still played as it is after its profile was changed to H.265")] + public async Task AnArtefactMadeInH264IsStillPlayedAsItIsAfterItsProfileWasChangedToH265() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + byte[] artefact = feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H264); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + JsonElement asked = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, "?source=artefact"))).GetProperty("data"); + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=artefact"); + + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.Equal("artefact", read.GetProperty("source").GetString()); + Assert.Equal("recording", read.GetProperty("alternative").GetString()); + Assert.Equal("artefact", asked.GetProperty("source").GetString()); + Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); + Assert.Null(feature.Player.Handed); + } + + [Fact(DisplayName = "the plan of a recording asked for as it was recorded names the artefact made in H.264 as the other one after its profile was changed to H.265")] + public async Task ThePlanAskedForTheRecordingNamesTheArtefactMadeInH264AfterItsProfileWasChangedToH265() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H264); + + JsonElement read = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, "?source=recording"))).GetProperty("data"); + + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal("artefact", read.GetProperty("alternative").GetString()); + } + + [Fact(DisplayName = "an artefact whose file is H.265 is left to the transcoder even when its profile says H.264 now")] + public async Task AnArtefactWhoseFileIsH265IsLeftToTheTranscoderEvenWhenItsProfileSaysH264Now() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H264, fileReadAs: EncodeCodec.H265); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); + } + + [Fact(DisplayName = "an artefact made in H.265 and tagged hvc1 is handed over as it is to a browser that says it decodes h265")] + public async Task AnArtefactInH265TaggedHvc1IsHandedOverToABrowserThatSaysItDecodesH265() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + byte[] artefact = feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1"); + + JsonElement read = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, "?decodes=h265"))).GetProperty("data"); + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=artefact&decodes=h265"); + + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.Equal("artefact", read.GetProperty("source").GetString()); + Assert.Equal("recording", read.GetProperty("alternative").GetString()); + Assert.Equal(["artefact", "recording"], ExternalPlayerSources(read)); + Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); + Assert.Null(feature.Player.Handed); + } + + [Theory(DisplayName = "a browser that does not say it decodes h265 has an artefact made in H.265 transcoded, and the plan still names it for external players")] + [InlineData("")] + [InlineData("?decodes=h264")] + public async Task ABrowserThatDoesNotSayItDecodesH265HasTheArtefactTranscoded(string query) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1"); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording, query))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); + Assert.Equal(["artefact", "recording"], ExternalPlayerSources(read)); + } + + [Fact(DisplayName = "an artefact made in H.265 and tagged hev1 is transcoded even for a browser that says it decodes h265")] + public async Task AnArtefactInH265TaggedHev1IsTranscodedEvenForABrowserThatDecodesH265() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hev1"); + + JsonElement read = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, "?decodes=h264&decodes=h265"))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.Equal(["artefact", "recording"], ExternalPlayerSources(read)); + } + + [Fact(DisplayName = "the plan of a recording with nothing encoded names only the recording itself for external players")] + public async Task ThePlanOfARecordingWithNothingEncodedNamesOnlyTheRecordingForExternalPlayers() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal(["recording"], ExternalPlayerSources(read)); + } + + [Theory(DisplayName = "a decoding that is not one of the three is refused, for the plan and for the picture alike")] + [InlineData("?decodes=vp9")] + [InlineData("?decodes=h265&decodes=H264")] + public async Task ADecodingThatIsNotOneOfTheThreeIsRefused(string query) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + + using HttpResponseMessage plan = await feature.PlanAsync(recording, query); + using HttpResponseMessage picture = await feature.PictureAsync(recording, query); + + Assert.Equal(HttpStatusCode.BadRequest, plan.StatusCode); + Assert.Equal(HttpStatusCode.BadRequest, picture.StatusCode); + Assert.Equal(PlayDelivery.TheDecodingsThereAre, (await PlayFeature.PlanOfAsync(plan)).GetProperty("message").GetString()); + } + + [Theory(DisplayName = "a browser saying it decodes AV1 is answered, and settles on the file one naming nothing more would")] + [InlineData("?decodes=av1", "?decodes=h264")] + [InlineData("?decodes=h265&decodes=av1", "?decodes=h265")] + public async Task ABrowserSayingItDecodesAv1IsAnswered(string withAv1, string without) + { + await using PlayFeature feature = new(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1"); + + using HttpResponseMessage asked = await feature.PlanAsync(recording, withAv1); + using HttpResponseMessage plain = await feature.PlanAsync(recording, without); + + Assert.Equal(HttpStatusCode.OK, asked.StatusCode); + Assert.Equal( + (await PlayFeature.PlanOfAsync(plain)).GetProperty("data").GetProperty("transcodes").GetBoolean(), + (await PlayFeature.PlanOfAsync(asked)).GetProperty("data").GetProperty("transcodes").GetBoolean()); + } + + [Fact] + public async Task NothingSaysAPlanFellBackWhenTheArtefactItNamesIsThere() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording); + + Assert.Null(Header(picture, PlaybackHeaders.FellBack)); + } + + [Fact(DisplayName = "the chapters that come back are placed on the clock of the artefact that is played rather than of an earlier one")] + public async Task TheChaptersThatComeBackArePlacedOnTheClockOfTheArtefactThatIsPlayed() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, bytes: 700, timeline: Skipped(0.5)); + feature.Encoded(recording, minutesLater: 90, bytes: 1_300, timeline: Skipped(1.5)); + await APodAsync(feature, recording); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal(1_300, read.GetProperty("bytes").GetInt64()); + Assert.Equal([0d, 298.5d, 358.5d], read.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("startsAtSec").GetDouble()).ToArray()); + } + + [Theory(DisplayName = "with an earlier artefact in H.264 and a later one in H.265, a browser is handed the newest one it decodes, with the chapters placed on that artefact's clock")] + [InlineData("?decodes=h265", 1_300, 298.5d)] + [InlineData("", 700, 299.5d)] + public async Task ABrowserIsHandedTheNewestArtefactItDecodesWithItsOwnChapters(string query, long bytes, double breakStartsAt) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H264, bytes: 700, fileReadAs: EncodeCodec.H264, timeline: Skipped(0.5)); + feature.Encoded(recording, EncodeCodec.H265, minutesLater: 90, bytes: 1_300, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1", timeline: Skipped(1.5)); + await APodAsync(feature, recording); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording, query))).GetProperty("data"); + JsonElement[] chapters = [.. read.GetProperty("chapters").EnumerateArray()]; + + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.Equal(bytes, read.GetProperty("bytes").GetInt64()); + Assert.Equal(("break", breakStartsAt), (chapters[1].GetProperty("kind").GetString(), chapters[1].GetProperty("startsAtSec").GetDouble())); + } + + [Fact] + public async Task ThePlanOfAnArtefactWhoseRunMarkedNothingCarriesAnEmptyListRatherThanNoField() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.Empty(read.GetProperty("chapters").EnumerateArray()); + } + + [Fact(DisplayName = "A recording played as it was recorded is answered with no chapters, because the ledger holds them on the artefact's clock")] + public async Task ThePlanOfARecordingPlayedAsItWasRecordedCarriesNoChapters() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.Empty(read.GetProperty("chapters").EnumerateArray()); + } + + [Fact] + public async Task ThePlanOfAnEncodedRecordingAskedForItsSecondSoundCarriesNoneOfTheArtefactsChapters() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); + feature.Encoded(recording); + await feature.MarkedAsync( + feature.Jobs.Jobs[0], + new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme)); + + JsonElement read = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, "?sound=secondary"))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.Empty(read.GetProperty("chapters").EnumerateArray()); + } + + [Fact(DisplayName = "a recording with an artefact asked for as it was recorded hands the recording itself to the transcoder rather than the artefact")] + public async Task ARecordingAskedForAsItWasRecordedIsTranscodedFromTheRecordingAndNotFromTheArtefact() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, bytes: 3_500); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=recording"); + byte[] body = await picture.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); + Assert.Equal(PlayFeature.Root, Assert.Single(feature.Player.Opened).Root); + Assert.Equal(feature.Player.Picture, body); + Assert.NotEqual(artefact, body); + } + + [Fact(DisplayName = "the plan of a recording asked for as it was recorded says it plays the recording and names the artefact as the other one")] + public async Task ThePlanOfARecordingAskedForAsItWasRecordedNamesTheArtefactAsTheOtherOne() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + + JsonElement read = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, "?source=recording"))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal("artefact", read.GetProperty("alternative").GetString()); + Assert.True(read.GetProperty("transcodes").GetBoolean()); + Assert.False(read.GetProperty("canSeek").GetBoolean()); + Assert.Equal(JsonValueKind.Null, read.GetProperty("bytes").ValueKind); + } + + [Fact(DisplayName = "the plan of an encoded recording asked for as it is says it plays the artefact and names the recording itself as the other one")] + public async Task ThePlanOfAnEncodedRecordingNamesTheRecordingItselfAsTheOtherOne() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + byte[] artefact = feature.Encoded(recording); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("direct", read.GetProperty("route").GetString()); + Assert.Equal("artefact", read.GetProperty("source").GetString()); + Assert.Equal("recording", read.GetProperty("alternative").GetString()); + Assert.Equal(artefact.Length, read.GetProperty("bytes").GetInt64()); + } + + [Fact(DisplayName = "asking outright for the artefact is asking for what playing a recording has always given")] + public async Task AskingOutrightForTheArtefactHandsOverTheArtefact() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=artefact"); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); + Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); + Assert.Null(feature.Player.Handed); + } + + [Fact(DisplayName = "an artefact the ledger names and the disk has not is not the other one the plan offers")] + public async Task AnArtefactTheDiskHasNotIsNotOfferedAsTheOtherOne() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, onDisk: false); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); + } + + [Fact(DisplayName = "an artefact holding no bytes is not the other one the plan offers")] + public async Task AnArtefactHoldingNoBytesIsNotOfferedAsTheOtherOne() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, bytes: 0); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("onTheFly", read.GetProperty("route").GetString()); + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); + } + + [Fact(DisplayName = "an artefact a browser would not decode as it is, is not the other one the plan offers")] + public async Task AnArtefactABrowserWouldNotDecodeIsNotOfferedAsTheOtherOne() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H265); + + JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); + + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); + } + + [Fact(DisplayName = "a recording asked for as it was recorded and no longer on the disk is refused rather than quietly handed its artefact")] + public async Task ARecordingAskedForAsItWasRecordedAndNoLongerOnTheDiskIsRefused() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, onDisk: false); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=recording"); + using HttpResponseMessage plan = await feature.PlanAsync(recording, "?source=recording"); + + Assert.Equal(HttpStatusCode.NotFound, picture.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, plan.StatusCode); + Assert.NotEqual(artefact, await picture.Content.ReadAsByteArrayAsync()); + Assert.Null(feature.Player.Handed); + Assert.Empty(feature.Player.Opened); + } + + [Fact(DisplayName = "a recording asked for as it was recorded with a second sound is not narrowed to the artefact when the recording is gone")] + public async Task ARecordingAskedForAsItWasRecordedIsNotNarrowedToTheArtefactWhenItsSecondSoundIsAskedFor() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended( + RecordingOutcome.Complete, + onDisk: false, + audio: AudioMode.DualMono, + sounds: 1); + feature.Encoded(recording); + + using HttpResponseMessage plan = await feature.PlanAsync(recording, "?source=recording&sound=secondary"); + + Assert.Equal(HttpStatusCode.NotFound, plan.StatusCode); + Assert.Null(feature.Player.Handed); + } + + [Fact(DisplayName = "a recording asked for as it was recorded and holding no bytes is refused rather than quietly handed its artefact")] + public async Task ARecordingAskedForAsItWasRecordedAndHoldingNoBytesIsRefused() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Failed, bytes: 0); + feature.Encoded(recording); + + using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=recording"); + + Assert.Equal(HttpStatusCode.NotFound, picture.StatusCode); + Assert.Empty(feature.Player.Opened); + } + + [Fact(DisplayName = "a recording asked for as it was recorded is moved about by starting again, because it is transcoded while playing")] + public async Task ARecordingAskedForAsItWasRecordedIsMovedAboutByStartingAgainRatherThanByARange() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, bytes: 2_000); + feature.Encoded(recording, bytes: 2_000); + + using HttpResponseMessage picture = await feature.PictureAsync( + recording, + "?source=recording", + "bytes=1000-1099"); + + Assert.Equal(HttpStatusCode.OK, picture.StatusCode); + Assert.Equal("byStartingAgain", Header(picture, PlaybackHeaders.Seeking)); + Assert.Equal("none", Assert.Single(picture.Headers.AcceptRanges)); + } + + [Fact(DisplayName = "the chapters the ledger holds belong to the artefact, so a recording asked for as it was recorded comes back with none")] + public async Task ARecordingAskedForAsItWasRecordedComesBackWithNoneOfTheArtefactsChapters() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + await feature.MarkedAsync( + feature.Jobs.Jobs[0], + new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme)); + + JsonElement read = (await PlayFeature.PlanOfAsync( + await feature.PlanAsync(recording, "?source=recording"))).GetProperty("data"); + + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Empty(read.GetProperty("chapters").EnumerateArray()); + } + + [Theory(DisplayName = "BR-PD-009: the plan names the codec the artefact's file was read as, whatever its profile says now")] + [InlineData(EncodeCodec.H264, EncodeCodec.H264, "h264")] + [InlineData(EncodeCodec.H265, EncodeCodec.H264, "h264")] + [InlineData(EncodeCodec.H265, EncodeCodec.H265, "h265")] + [InlineData(EncodeCodec.H264, EncodeCodec.H265, "h265")] + public async Task ThePlanNamesTheCodecTheArtefactsFileWasReadAs(EncodeCodec profile, EncodeCodec file, string named) + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, profile, fileReadAs: file, taggedAs: "hvc1"); + + JsonElement read = await PlanAsync(feature, recording); + + Assert.Equal(named, read.GetProperty("artefactFile").GetProperty("codec").GetString()); + } + + [Fact(DisplayName = "BR-PD-009: an artefact in H.265 a browser cannot play is still named, while the recording is transcoded")] + public async Task AnArtefactInH265ABrowserCannotPlayIsStillNamed() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1"); + + JsonElement read = await PlanAsync(feature, recording); + + Assert.True(read.GetProperty("transcodes").GetBoolean()); + Assert.Equal("h265", read.GetProperty("artefactFile").GetProperty("codec").GetString()); + } + + [Fact(DisplayName = "BR-PD-009: the artefact is named when the recording itself is asked for")] + public async Task TheArtefactIsNamedWhenTheRecordingItselfIsAskedFor() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H264, fileReadAs: EncodeCodec.H264); + + JsonElement read = await PlanAsync(feature, recording, "?source=recording"); + + Assert.Equal("recording", read.GetProperty("source").GetString()); + Assert.Equal("h264", read.GetProperty("artefactFile").GetProperty("codec").GetString()); + } + + [Fact(DisplayName = "BR-PD-009: an artefact whose file could not be read is named by no codec rather than by its profile")] + public async Task AnArtefactWhoseFileCouldNotBeReadIsNamedByNoCodec() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, EncodeCodec.H264); + + JsonElement read = await PlanAsync(feature, recording); + + Assert.Equal(JsonValueKind.Null, read.GetProperty("artefactFile").ValueKind); + } + + [Fact(DisplayName = "BR-PD-009: a recording with no artefact is named by no codec")] + public async Task ARecordingWithNoArtefactIsNamedByNoCodec() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + + JsonElement read = await PlanAsync(feature, recording); + + Assert.Equal(JsonValueKind.Null, read.GetProperty("artefactFile").ValueKind); + } + + [Fact(DisplayName = "BR-CD-001: the plan of an artefact carries the chapters the version in use detected, on the artefact's clock, a likely break with something after it offered to be skipped")] + public async Task TheArtefactsPlanCarriesTheDetectedChaptersOnItsClock() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, timeline: HalfASecondSkipped); + await DetectedAsync(feature, recording.Id, (0, 912.3, SegmentKind.Programme, 0.98), (912.3, 1002.3, SegmentKind.Break, 0.93), (1002.3, 1800, SegmentKind.Programme, 0.99)); + + JsonElement plan = await PlanAsync(feature, recording); + JsonElement[] chapters = [.. plan.GetProperty("chapters").EnumerateArray()]; + + Assert.Equal("direct", plan.GetProperty("route").GetString()); + Assert.Equal( + [(0d, 911.8d, "programme", false), (911.8d, 1001.8d, "break", true), (1001.8d, 1799.5d, "programme", false)], + chapters.Select(Read)); + } + + [Fact(DisplayName = "BR-CD-001: the plan of the recording itself carries the chapters the version in use detected at the recording's own time")] + public async Task TheRecordingsOwnPlanCarriesTheDetectedChaptersAtItsOwnTime() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + await DetectedAsync(feature, recording.Id, (0, 912.3, SegmentKind.Programme, 0.98), (912.3, 1002.3, SegmentKind.Break, 0.93), (1002.3, 1800, SegmentKind.Programme, 0.99)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.True(plan.GetProperty("transcodes").GetBoolean()); + Assert.Equal( + [(0d, 912.3d, "programme", false), (912.3d, 1002.3d, "break", true), (1002.3d, 1800d, "programme", false)], + plan.GetProperty("chapters").EnumerateArray().Select(Read)); + } + + [Fact(DisplayName = "BR-CD-001: a recording with an artefact asked for as it was recorded carries the chapters at the recording's own time")] + public async Task TheRecordingAskedForAsRecordedCarriesTheChaptersAtItsOwnTime() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, timeline: HalfASecondSkipped); + await DetectedAsync(feature, recording.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); + + JsonElement plan = await PlanAsync(feature, recording, "?source=recording"); + + Assert.Equal("recording", plan.GetProperty("source").GetString()); + Assert.Equal([0d, 300d, 360d], plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("startsAtSec").GetDouble())); + } + + [Fact(DisplayName = "BR-CD-009: a break less likely than the threshold is marked but not offered to be skipped, and neither is a break the recording ends on")] + public async Task UnlikelyOrFinalBreaksAreNotOfferedToBeSkipped() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + await DetectedAsync( + feature, + recording.Id, + (0, 300, SegmentKind.Programme, 0.98), + (300, 360, SegmentKind.Break, 0.69), + (360, 1740, SegmentKind.Programme, 0.99), + (1740, 1800, SegmentKind.Break, 0.99)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Equal([false, false, false, false], plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("skippable").GetBoolean())); + Assert.Equal("break", plan.GetProperty("chapters")[1].GetProperty("kind").GetString()); + } + + [Theory(DisplayName = "BR-CD-009: the threshold the settings hold decides which breaks are offered to be skipped")] + [InlineData(0.60, true, true)] + [InlineData(0.90, false, true)] + [InlineData(0.95, false, false)] + public async Task TheThresholdTheSettingsHoldDecidesWhichBreaksAreOffered(double threshold, bool unlikely, bool likely) + { + await using var feature = new PlayFeature(); + await feature.SegmentSettings.SaveAsync(SegmentSettings.Rehydrate(SegmentSettings.TheOnlyRow, threshold, RecordingFeature.Noon), CancellationToken.None); + Recording recording = feature.Ended(RecordingOutcome.Complete); + await DetectedAsync( + feature, + recording.Id, + (0, 300, SegmentKind.Programme, 0.98), + (300, 360, SegmentKind.Break, 0.69), + (360, 900, SegmentKind.Programme, 0.99), + (900, 960, SegmentKind.Break, 0.93), + (960, 1800, SegmentKind.Programme, 0.99)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Equal([false, unlikely, false, likely, false], plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("skippable").GetBoolean())); + } + + [Fact(DisplayName = "BR-CD-009: an opening and an ending are played by their own kinds on the artefact and on the recording itself, each offered to be skipped when it is likely enough and something follows it")] + public async Task AnOpeningAndAnEndingArePlayedByTheirOwnKinds() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, timeline: HalfASecondSkipped); + await DetectedAsync( + feature, + recording.Id, + (0, 60, SegmentKind.Programme, 0.98), + (60, 150, SegmentKind.Opening, 0.92), + (150, 900, SegmentKind.Programme, 0.99), + (900, 960, SegmentKind.Break, 0.93), + (960, 1710, SegmentKind.Programme, 0.99), + (1710, 1800, SegmentKind.Ending, 0.95)); + + JsonElement artefact = await PlanAsync(feature, recording); + JsonElement original = await PlanAsync(feature, recording, "?source=recording"); + + Assert.Equal( + [ + (0d, 59.5d, "programme", false), (59.5d, 149.5d, "opening", true), (149.5d, 899.5d, "programme", false), + (899.5d, 959.5d, "break", true), (959.5d, 1709.5d, "programme", false), (1709.5d, 1799.5d, "ending", false), + ], + artefact.GetProperty("chapters").EnumerateArray().Select(Read)); + Assert.Equal( + [ + (0d, 60d, "programme", false), (60d, 150d, "opening", true), (150d, 900d, "programme", false), + (900d, 960d, "break", true), (960d, 1710d, "programme", false), (1710d, 1800d, "ending", false), + ], + original.GetProperty("chapters").EnumerateArray().Select(Read)); + } + + [Theory(DisplayName = "BR-CD-009: the threshold the settings hold decides for an opening and an ending as it does for a break, and an ending with something after it is offered to be skipped")] + [InlineData(0.70, false, true, true)] + [InlineData(0.60, true, true, true)] + [InlineData(0.90, false, false, true)] + [InlineData(0.95, false, false, false)] + public async Task TheThresholdDecidesForAnOpeningAndAnEnding(double threshold, bool opening, bool breaks, bool ending) + { + await using var feature = new PlayFeature(); + await feature.SegmentSettings.SaveAsync(SegmentSettings.Rehydrate(SegmentSettings.TheOnlyRow, threshold, RecordingFeature.Noon), CancellationToken.None); + Recording recording = feature.Ended(RecordingOutcome.Complete); + await DetectedAsync( + feature, + recording.Id, + (0, 90, SegmentKind.Opening, 0.65), + (90, 900, SegmentKind.Programme, 0.99), + (900, 960, SegmentKind.Break, 0.8), + (960, 1680, SegmentKind.Programme, 0.99), + (1680, 1770, SegmentKind.Ending, 0.93), + (1770, 1800, SegmentKind.Programme, 0.9)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Equal( + ["opening", "programme", "break", "programme", "ending", "programme"], + plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("kind").GetString())); + Assert.Equal( + [opening, false, breaks, false, ending, false], + plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("skippable").GetBoolean())); + } + + [Fact(DisplayName = "BR-CS-002: a recording whose detected sequence was thrown away plays with no chapters, even with chapters its encode marked")] + public async Task ASequenceThrownAwayPlaysWithNoChapters() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, timeline: HalfASecondSkipped); + await feature.MarkedAsync(feature.Jobs.Jobs[0], new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme), new ChapterSegment(TimeSpan.FromSeconds(90), TimeSpan.FromSeconds(150), ChapterKind.Break), new ChapterSegment(TimeSpan.FromSeconds(150), TimeSpan.FromSeconds(300), ChapterKind.Programme)); + await DetectedAsync(feature, recording.Id, (0, 600, SegmentKind.Programme, 0.6), (600, 1800, SegmentKind.Break, 0.8)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Empty(plan.GetProperty("chapters").EnumerateArray()); + } + + [Fact(DisplayName = "BR-CD-013: a recording not detected plays with no chapters, whatever its encode marked")] + public async Task ANotDetectedRecordingPlaysWithNoChapters() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, timeline: HalfASecondSkipped); + await feature.MarkedAsync(feature.Jobs.Jobs[0], new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme), new ChapterSegment(TimeSpan.FromSeconds(90), TimeSpan.FromSeconds(150), ChapterKind.Break), new ChapterSegment(TimeSpan.FromSeconds(150), TimeSpan.FromSeconds(300), ChapterKind.Programme)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Empty(plan.GetProperty("chapters").EnumerateArray()); + } + + [Fact(DisplayName = "BR-CS-002: a detection by a version no longer in use is not played")] + public async Task ADetectionByAnotherVersionIsNotPlayed() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + await DetectedAsync(feature, recording.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); + feature.Versions.Active = HeldSegmentModelVersions.InUse(2, RecordingFeature.Noon); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Empty(plan.GetProperty("chapters").EnumerateArray()); + } + + [Fact(DisplayName = "an artefact whose timeline was not kept has no detected stretch placed on it")] + public async Task AnArtefactWithoutATimelineHasNoDetectedChapters() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + await DetectedAsync(feature, recording.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Equal("direct", plan.GetProperty("route").GetString()); + Assert.Empty(plan.GetProperty("chapters").EnumerateArray()); + } + + [Fact(DisplayName = "BR-CD-001: the plan of an artefact says how far the recording's time stands ahead of the artefact's, the head the job that made it skipped, by which its chapters were moved")] + public async Task TheArtefactsPlanSaysHowFarTheRecordingsTimeStandsAhead() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, timeline: Skipped(0.533)); + await DetectedAsync(feature, recording.Id, (0, 912.3, SegmentKind.Programme, 0.98), (912.3, 1002.3, SegmentKind.Break, 0.93), (1002.3, 1800, SegmentKind.Programme, 0.99)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Equal("direct", plan.GetProperty("route").GetString()); + Assert.Equal(0.533, plan.GetProperty("recordingOffsetSec").GetDouble()); + Assert.Equal([0d, 911.77d, 1001.77d], plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("startsAtSec").GetDouble())); + } + + [Fact(DisplayName = "BR-CD-001: the plan says the head skipped by the artefact it hands over, not by a newer one it could not hand over, whatever chapters it carries")] + public async Task ThePlanSaysTheHeadSkippedByTheArtefactItHandsOver() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, timeline: Skipped(0.533)); + feature.Encoded(recording, minutesLater: 10, onDisk: false, timeline: Skipped(1.2)); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Equal("direct", plan.GetProperty("route").GetString()); + Assert.Equal(0.533, plan.GetProperty("recordingOffsetSec").GetDouble()); + } + + [Fact(DisplayName = "BR-CD-001: the plan of the recording itself says its time is the recording's own, whether or not an artefact was made of it")] + public async Task TheRecordingsOwnPlanSaysItsTimeIsTheRecordingsOwn() + { + await using var feature = new PlayFeature(); + Recording alone = feature.Ended(RecordingOutcome.Complete); + Recording encoded = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(encoded, timeline: Skipped(0.533)); + await DetectedAsync(feature, encoded.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); + + JsonElement transcoded = await PlanAsync(feature, alone); + JsonElement asRecorded = await PlanAsync(feature, encoded, "?source=recording"); + + Assert.True(transcoded.GetProperty("transcodes").GetBoolean()); + Assert.Equal(0d, transcoded.GetProperty("recordingOffsetSec").GetDouble()); + Assert.Equal("recording", asRecorded.GetProperty("source").GetString()); + Assert.Equal(0d, asRecorded.GetProperty("recordingOffsetSec").GetDouble()); + } + + [Fact(DisplayName = "an artefact whose timeline was not kept says nothing of how far the recording's time stands ahead of its own")] + public async Task AnArtefactWithoutATimelineSaysNoOffset() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording); + + JsonElement plan = await PlanAsync(feature, recording); + + Assert.Equal("direct", plan.GetProperty("route").GetString()); + Assert.Equal(JsonValueKind.Null, plan.GetProperty("recordingOffsetSec").ValueKind); + } + + [Fact(DisplayName = "BR-CS-002: chapters an encode took from a detection, or from the reader of the source, are not played on an artefact the version in use has not detected")] + public async Task ChaptersEncodedAreNotPlayedWithoutADetection() + { + await using var fromADetection = new PlayFeature(); + Recording detected = fromADetection.Ended(RecordingOutcome.Complete); + fromADetection.Encoded(detected, timeline: HalfASecondSkipped, chapters: new ChapterReading(ChapterDetectorName.Segments, ChapterVerdict.Marked, 0.03, RecordingFeature.Noon.AddHours(1), 2)); + await fromADetection.MarkedAsync(fromADetection.Jobs.Jobs[0], Marked()); + await using var fromTheReader = new PlayFeature(); + Recording read = fromTheReader.Ended(RecordingOutcome.Complete); + fromTheReader.Encoded(read, timeline: HalfASecondSkipped, chapters: new ChapterReading(ChapterDetectorName.Ffmpeg, ChapterVerdict.Marked, 0.03, RecordingFeature.Noon.AddHours(1))); + await fromTheReader.MarkedAsync(fromTheReader.Jobs.Jobs[0], Marked()); + + JsonElement fromTheSegments = await PlanAsync(fromADetection, detected); + JsonElement fromAReader = await PlanAsync(fromTheReader, read); + + Assert.Empty(fromTheSegments.GetProperty("chapters").EnumerateArray()); + Assert.Empty(fromAReader.GetProperty("chapters").EnumerateArray()); + } + + [Fact(DisplayName = "BR-CA-001: asking for the plan writes nothing: no detection is kept and no setting saved")] + public async Task AskingForThePlanWritesNothing() + { + await using var feature = new PlayFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete); + feature.Encoded(recording, timeline: HalfASecondSkipped); + await DetectedAsync(feature, recording.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); + int kept = feature.Detections.Keeps; + + await PlanAsync(feature, recording); + await PlanAsync(feature, recording, "?source=recording"); + + Assert.Equal(kept, feature.Detections.Keeps); + Assert.Equal(0, feature.SegmentSettings.Saves); + } + + [Fact] + public async Task APictureAlreadyBeingTranscodedKeepsFlowingAfterItsSessionIsEnded() + { + GatedOnTheFlyPlayer player = new(Written); + await using AuthProbe probe = Wiring(new GatedPlaybackFiles(Written), player, out Recording recording); + AuthSession session = await probe.SignedInAsync(); + + player.Handed.Release(FirstHalf); + + using HttpRequestMessage asking = Playing(recording); + using HttpResponseMessage response = await probe.Client.SendAsync(asking, HttpCompletionOption.ResponseHeadersRead); + await using Stream body = await response.Content.ReadAsStreamAsync(); + byte[] heard = new byte[Size]; + + await body.ReadExactlyAsync(heard.AsMemory(0, FirstHalf)); + + session.Revoke(DateTime.UtcNow); + player.Handed.Release(Size); + + await body.ReadExactlyAsync(heard.AsMemory(FirstHalf)); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("video/mp4", response.Content.Headers.ContentType?.MediaType); + Assert.Equal(Written, heard); + } + + [Fact] + public async Task TheNextPictureAskedForAfterThatSessionEndedIsRefused() + { + await using AuthProbe probe = Wiring(new GatedPlaybackFiles(Written), new GatedOnTheFlyPlayer(Written), out Recording recording); + AuthSession session = await probe.SignedInAsync(); + + session.Revoke(DateTime.UtcNow); + + using HttpRequestMessage asking = Playing(recording); + using HttpResponseMessage response = await probe.Client.SendAsync(asking, HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Null(response.Headers.Location); + Assert.Empty(await response.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task BrPd017ThePlanOfAnArtefactWhoseCaptionShiftWasMeasuredSaysItsCaptionsAreReady() + { + await using CaptionFeature feature = new(); + Recording recording = await feature.CaptionedAsync(); + feature.Encoded(recording, new EncodeTimeline(CaptionFeature.FileBegins, TimeSpan.FromSeconds(0.5), TimeSpan.FromMinutes(30), TimeSpan.FromSeconds(600))); + + Assert.Equal("ready", await feature.PlannedAsync(recording)); + } + + [Fact] + public async Task BrPd017TheTwoClocksDisagreeingByAMillisecondPlansNoCaptionsOverTheArtefactAndStillPlansThemOverTheRecording() + { + await using CaptionFeature feature = new(); + Recording recording = await feature.CaptionedAsync(); + feature.Encoded(recording, new EncodeTimeline(CaptionFeature.FileBegins + TimeSpan.FromMilliseconds(1), TimeSpan.FromSeconds(0.5), null, null)); + + Assert.Equal("none", await feature.PlannedAsync(recording, "?source=artefact")); + Assert.Equal("ready", await feature.PlannedAsync(recording, "?source=recording")); + } + + [Fact] + public async Task AnArtefactWhoseJobNeverMeasuredItsTimelineHasNoCaptionsOverIt() + { + await using CaptionFeature feature = new(); + Recording recording = await feature.CaptionedAsync(); + feature.Encoded(recording, null); + + Assert.Equal("none", await feature.PlannedAsync(recording)); + } + + [Fact] + public async Task BrPd017ThePlanSaysCaptionsStillBeingTakenAreComing() + { + await using CaptionFeature feature = new(); + Recording recording = feature.Ended(); + + Assert.Equal("coming", await feature.PlannedAsync(recording)); + } + + [Fact] + public async Task BrPd017ThePlanOfARecordingWithNoCaptionsSaysThereAreNone() + { + await using CaptionFeature feature = new(); + Recording recording = feature.Ended(); + recording.Caption(CaptionState.Absent, null, RecordingFeature.Noon.AddHours(1)); + + Assert.Equal("none", await feature.PlannedAsync(recording)); + } + + [Fact] + public async Task BrPd016CaptionsTheRowSaysAreReadyWithNoRecordOnTheShelfAreComingAndNothingIsWritten() + { + await using CaptionFeature feature = new(); + Recording recording = await feature.CaptionedAsync(onTheShelf: false); + + Assert.Equal("coming", await feature.PlannedAsync(recording, "?source=recording")); + Assert.Equal(CaptionState.Ready, recording.CaptionState); + } + + [Fact] + public async Task WithNowhereToKeepCaptionsThereAreNone() + { + await using CaptionFeature feature = new(anywhereToKeepThem: false); + Recording recording = feature.Ended(); + + Assert.Equal("none", await feature.PlannedAsync(recording)); + } + + private static async Task<(HttpStatusCode Status, JsonElement Body)> KeepAsync( + HttpClient client, + string recordingId, + object body) + { + using HttpResponseMessage response = await client.PutAsJsonAsync( + new Uri($"/api/videos/{recordingId}/position", UriKind.Relative), + body); + string read = await response.Content.ReadAsStringAsync(); + + if (!read.StartsWith('{')) + { + return (response.StatusCode, default); + } + + using var document = JsonDocument.Parse(read); + + return (response.StatusCode, document.RootElement.Clone()); + } + + private static string? Header(HttpResponseMessage answer, string named) + => answer.Headers.TryGetValues(named, out IEnumerable? values) ? values.Single() : null; + + private static EncodeTimeline Skipped(double head) + => new(TimeSpan.FromSeconds(1.4), TimeSpan.FromSeconds(head), TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30) - TimeSpan.FromSeconds(head)); + + /// + /// Keeps a detection of the recording by the version in use with a pod of adverts five minutes in. + /// + private static async Task APodAsync(PlayFeature feature, Recording recording) + { + SegmentSpan[] segments = + [ + new(TimeSpan.Zero, TimeSpan.FromSeconds(300), SegmentKind.Programme, 0.98), + new(TimeSpan.FromSeconds(300), TimeSpan.FromSeconds(360), SegmentKind.Break, 0.93), + new(TimeSpan.FromSeconds(360), TimeSpan.FromMinutes(30), SegmentKind.Programme, 0.99), + ]; + + await feature.Detections.KeepAsync( + RecordingDetection.Of( + recording.Id, + SegmentModelVersion.FirstNumber, + SegmentDetection.Judged(segments, TimeSpan.FromMinutes(30), []), + 2, + RecordingFeature.Noon, + RecordingFeature.Noon), + CancellationToken.None); + } + + private static string[] ExternalPlayerSources(JsonElement plan) + => [.. plan.GetProperty("externalPlayerSources").EnumerateArray().Select(source => source.GetString()!)]; + + private static async Task PlanAsync(PlayFeature feature, Recording recording, string query = "") + { + using HttpResponseMessage plan = await feature.PlanAsync(recording, query); + + return (await PlayFeature.PlanOfAsync(plan)).GetProperty("data"); + } + + private static (double Starts, double Ends, string Kind, bool Skippable) Read(JsonElement chapter) + => (chapter.GetProperty("startsAtSec").GetDouble(), + chapter.GetProperty("endsAtSec").GetDouble(), + chapter.GetProperty("kind").GetString()!, + chapter.GetProperty("skippable").GetBoolean()); + + private static ChapterSegment[] Marked() + => + [ + new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme), + new ChapterSegment(TimeSpan.FromSeconds(90), TimeSpan.FromSeconds(150), ChapterKind.Break), + new ChapterSegment(TimeSpan.FromSeconds(150), TimeSpan.FromSeconds(1799.5), ChapterKind.Programme), + ]; + + private static async Task DetectedAsync(PlayFeature feature, RecordingId recording, params (double Starts, double Ends, SegmentKind Kind, double Probability)[] stretches) + { + SegmentSpan[] segments = [.. stretches.Select(stretch => new SegmentSpan(TimeSpan.FromSeconds(stretch.Starts), TimeSpan.FromSeconds(stretch.Ends), stretch.Kind, stretch.Probability))]; + + await feature.Detections.KeepAsync( + RecordingDetection.Of(recording, SegmentModelVersion.FirstNumber, SegmentDetection.Judged(segments, TimeSpan.FromMinutes(30), []), 2, RecordingFeature.Noon, RecordingFeature.Noon), + CancellationToken.None); + } + + private static HttpRequestMessage Playing(Recording recording) + { + HttpRequestMessage asking = new(HttpMethod.Get, new Uri($"/api/videos/{recording.Id.Wire}/play", UriKind.Relative)); + + asking.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); + + return asking; + } + + private static AuthProbe Wiring(IPlaybackFileStore files, IOnTheFlyPlayer player, out Recording recording) + { + HeldRecordings recordings = new(); + + recording = RecordingFeature.Begin(RecordingId.New()); + recording.Wrote(TimeSpan.FromMinutes(30)); + recording.Abort(RecordingFeature.Noon.AddMinutes(30)); + recording.Settle(RecordingOutcome.Complete, Size, RecordingFeature.Noon.AddMinutes(30)); + recordings.Recordings.Add(recording); + + return AuthProbe.OverHttp(services => + { + services.RemoveAll(); + services.RemoveAll(); + services.AddSingleton(recordings); + services.AddSingleton(new HeldEncodeJobs()); + services.AddSingleton(new HeldEncodeProfiles()); + services.AddSingleton(new HeldPlaybackPositions()); + services.AddSingleton(files); + services.AddSingleton(player); + }); + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/PlaybackFeature.cs b/tests/Carina.Api.Tests/Feature/Playback/PlaybackFeature.cs similarity index 95% rename from tests/Carina.Api.Tests/FeatureTest/PlaybackFeature.cs rename to tests/Carina.Api.Tests/Feature/Playback/PlaybackFeature.cs index 4032944f4..471efa3a3 100644 --- a/tests/Carina.Api.Tests/FeatureTest/PlaybackFeature.cs +++ b/tests/Carina.Api.Tests/Feature/Playback/PlaybackFeature.cs @@ -1,5 +1,6 @@ using System.Net.Http.Headers; +using Carina.Api.Tests.FeatureTest; using Carina.Domain.Encodings; using Carina.Domain.Integrity; using Carina.Domain.Playback; @@ -12,7 +13,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; -namespace Carina.Api.Tests.FeatureTest; +namespace Carina.Api.Tests.Feature.Playback; internal sealed class PlaybackFeature : IAsyncDisposable { @@ -143,16 +144,7 @@ public async ValueTask DisposeAsync() Client.Dispose(); Stranger.Dispose(); await factory.DisposeAsync(); - - if (Directory.Exists(mounted.FullName)) - { - mounted.Delete(recursive: true); - } - - if (Directory.Exists(shelved.FullName)) - { - shelved.Delete(recursive: true); - } + TemporaryDirectories.RemoveAll(mounted, shelved); } private async Task SendAsync( diff --git a/tests/Carina.Api.Tests/FeatureTest/RecordingHlsTests.cs b/tests/Carina.Api.Tests/Feature/Playback/RecordingHlsDeliveryTests.cs similarity index 98% rename from tests/Carina.Api.Tests/FeatureTest/RecordingHlsTests.cs rename to tests/Carina.Api.Tests/Feature/Playback/RecordingHlsDeliveryTests.cs index e517aceee..7d9e3d7e3 100644 --- a/tests/Carina.Api.Tests/FeatureTest/RecordingHlsTests.cs +++ b/tests/Carina.Api.Tests/Feature/Playback/RecordingHlsDeliveryTests.cs @@ -2,6 +2,7 @@ using System.Text.RegularExpressions; using Carina.Api.Live; +using Carina.Api.Tests.FeatureTest; using Carina.Domain.Auth; using Carina.Domain.Recordings; using Carina.Domain.Streaming; @@ -9,9 +10,10 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Api.Tests.FeatureTest; +namespace Carina.Api.Tests.Feature.Playback; -public sealed partial class RecordingHlsTests +[Trait("Category", "Feature")] +public sealed partial class RecordingHlsDeliveryTests { private const uint OneFrame = 1001; diff --git a/tests/Carina.Api.Tests/Feature/Playback/VanishingPlaybackFiles.cs b/tests/Carina.Api.Tests/Feature/Playback/VanishingPlaybackFiles.cs new file mode 100644 index 000000000..cd4107e1c --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Playback/VanishingPlaybackFiles.cs @@ -0,0 +1,15 @@ +using Carina.Domain.Playback; +using Carina.Domain.Recordings; +using Carina.Domain.Streaming; + +namespace Carina.Api.Tests.Feature.Playback; + +internal sealed class VanishingPlaybackFiles(long bytes, PlaybackFileAbsence then = PlaybackFileAbsence.Gone) : IPlaybackFileStore +{ + public PlaybackFileSearch Find(OutputRoot root, RecordingFileName fileName) + => PlaybackFileSearch.Of(new PlaybackFile(root, fileName, bytes)); + + public PlaybackFileOpening OpenRead(PlaybackFile file) => PlaybackFileOpening.Missing(then); + + public StreamSource? SourceOf(PlaybackFile file) => null; +} diff --git a/tests/Carina.Api.Tests/Feature/Playback/VideoDeliveryTests.cs b/tests/Carina.Api.Tests/Feature/Playback/VideoDeliveryTests.cs new file mode 100644 index 000000000..8bca80319 --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Playback/VideoDeliveryTests.cs @@ -0,0 +1,936 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; + +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Auth; +using Carina.Domain.Channels; +using Carina.Domain.Encodings; +using Carina.Domain.Playback; +using Carina.Domain.Recordings; +using Carina.Domain.Streaming; +using Carina.Domain.Viewing; +using Carina.TestSupport; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Carina.Api.Tests.Feature.Playback; + +[Trait("Category", "Feature")] +public sealed class VideoDeliveryTests +{ + private const int Size = 4_000; + + private const int GatedSize = 256 * 1024; + + private const int FirstHalf = GatedSize / 2; + + private const string AName = "a-programme.ts"; + + private static readonly byte[] Written = [.. Enumerable.Range(0, GatedSize).Select(index => (byte)(index % 251))]; + + private static readonly DateTime At = new(2026, 9, 3, 0, 0, 0, DateTimeKind.Utc); + + private readonly PipedSupply supply = new(); + + [Fact] + public async Task TheWholeFileComesBackWhenNoRangeIsAskedFor() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + + using HttpResponseMessage answer = await feature.GetAsync(recording); + byte[] body = await answer.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("bytes", Assert.Single(answer.Headers.AcceptRanges)); + Assert.Equal("video/mp2t", answer.Content.Headers.ContentType?.MediaType); + Assert.Equal(Size, answer.Content.Headers.ContentLength); + Assert.Equal(written, body); + } + + [Fact] + public async Task AskingFromTheStartIsAPartAndCarriesTheWholeFile() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-"); + byte[] body = await answer.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); + Assert.Equal($"bytes 0-{Size - 1}/{Size}", answer.Content.Headers.ContentRange?.ToString()); + Assert.Equal(Size, answer.Content.Headers.ContentLength); + Assert.Equal(written, body); + } + + [Fact] + public async Task AskingFromAnOffsetHandsBackTheBytesFromThatOffset() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=100-"); + byte[] body = await answer.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); + Assert.Equal($"bytes 100-{Size - 1}/{Size}", answer.Content.Headers.ContentRange?.ToString()); + Assert.Equal(written[100..], body); + } + + [Fact] + public async Task AskingForTheLastBytesHandsBackTheEndOfTheFileAndNotItsStart() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=-500"); + byte[] body = await answer.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); + Assert.Equal($"bytes {Size - 500}-{Size - 1}/{Size}", answer.Content.Headers.ContentRange?.ToString()); + Assert.Equal(written[^500..], body); + Assert.NotEqual(written[..500], body); + } + + [Fact] + public async Task AskingForBothEndsHandsBackWhatIsBetweenThem() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=100-199"); + byte[] body = await answer.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); + Assert.Equal(100, body.Length); + Assert.Equal(written[100..200], body); + } + + [Fact] + public async Task ARangeThatStartsPastTheEndIsRefusedWithTheSizeOfWhatThereIs() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=999999-"); + byte[] body = await answer.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.RequestedRangeNotSatisfiable, answer.StatusCode); + Assert.Equal($"bytes */{Size}", answer.Content.Headers.ContentRange?.ToString()); + Assert.Equal("bytes", Assert.Single(answer.Headers.AcceptRanges)); + Assert.Empty(body); + } + + [Theory] + [InlineData("bytes=abc")] + [InlineData("bytes=100-50")] + [InlineData("items=0-99")] + public async Task ARangeThatCannotBeReadIsIgnoredAndTheWholeFileComesBack(string range) + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + + using HttpResponseMessage answer = await feature.GetAsync(recording, range); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(written, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task MoreThanOneRangeIsNotServedAsSeveralParts() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-99,200-299"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Null(answer.Content.Headers.ContentRange); + Assert.Equal(written, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task AskingOnlyWhatIsThereSendsTheSameHeadersAndNoBody() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); + + using HttpResponseMessage whole = await feature.HeadAsync(recording); + using HttpResponseMessage part = await feature.HeadAsync(recording, "bytes=-500"); + + Assert.Equal(HttpStatusCode.OK, whole.StatusCode); + Assert.Equal("bytes", Assert.Single(whole.Headers.AcceptRanges)); + Assert.Equal(Size, whole.Content.Headers.ContentLength); + Assert.Empty(await whole.Content.ReadAsByteArrayAsync()); + + Assert.Equal(HttpStatusCode.PartialContent, part.StatusCode); + Assert.Equal($"bytes {Size - 500}-{Size - 1}/{Size}", part.Content.Headers.ContentRange?.ToString()); + Assert.Equal(500, part.Content.Headers.ContentLength); + Assert.Empty(await part.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task ARecordingCutShortIsStillHandedOverToAPlayerThatCanReadIt() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Truncated, written); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-9"); + + Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); + Assert.Equal(written[..10], await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task ARecordingOfNoBytesHasNoVideoToHandOver() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Failed, []); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-"); + + Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task ARecordingWhoseFileIsGoneWhileItsRootIsThereIsNotFound() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size), onDisk: false); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-"); + + Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task ARecordingWhoseRootIsGoneSaysTheBytesAreOutOfReachRatherThanNotFound() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); + Directory.Delete(feature.MountedAt, recursive: true); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-"); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); + } + + [Fact] + public async Task AFileTakenOffTheDiskBetweenBeingFoundAndBeingOpenedIsNotFoundRatherThanHalfServed() + { + await using var feature = new PlaybackFeature(new VanishingPlaybackFiles(Size)); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size), onDisk: false); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=1000-1999"); + + Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task ARootThatWentAwayBetweenTheFileBeingFoundAndOpenedIsOutOfReachRatherThanNotFound() + { + await using var feature = new PlaybackFeature(new VanishingPlaybackFiles(Size, PlaybackFileAbsence.OutOfReach)); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size), onDisk: false); + + using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=1000-1999"); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); + } + + [Fact] + public async Task ARecordingStillBeingWrittenIsNotHandedOverAsAWholeFile() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.StillWriting(); + + using HttpResponseMessage answer = await feature.GetAsync(recording); + + Assert.Equal(HttpStatusCode.Conflict, answer.StatusCode); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task ARecordingNobodyHasIsNotFound() + { + await using var feature = new PlaybackFeature(); + + using HttpResponseMessage answer = await feature.Client.GetAsync( + new Uri($"/api/videos/{RecordingId.New().Wire}", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); + } + + [Fact] + public async Task ARecordingWithNoArtefactAskedForAsItWasRecordedIsHandedOverAsItIs() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(Size); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + + using HttpResponseMessage answer = await feature.GetFromAsync(recording, "recording"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("video/mp2t", answer.Content.Headers.ContentType?.MediaType); + Assert.Equal(written, await answer.Content.ReadAsByteArrayAsync()); + } + + [Theory] + [InlineData("proxy")] + [InlineData("Recording ")] + public async Task AFileThatIsNeitherOfTheTwoIsRefusedBeforeAnythingIsHandedOver(string source) + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); + + using HttpResponseMessage answer = await feature.GetFromAsync(recording, source); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task SomethingThatIsNotARecordingIdIsRefusedBeforeAnythingIsLookedFor() + { + await using var feature = new PlaybackFeature(); + + using HttpResponseMessage answer = await feature.Client.GetAsync( + new Uri("/api/videos/not-an-id", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); + } + + [Theory] + [InlineData("GET")] + [InlineData("HEAD")] + public async Task AClientCarryingNoCredentialsIsRefusedRatherThanSentToASignInScreen(string method) + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); + + using var asking = new HttpRequestMessage( + new HttpMethod(method), + new Uri($"/api/videos/{recording.Id.Wire}", UriKind.Relative)); + using HttpResponseMessage answer = await feature.Stranger.SendAsync(asking); + + Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); + Assert.Null(answer.Headers.Location); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task NothingHandedBackSaysWhereOnThisMachineTheFileIs() + { + await using var feature = new PlaybackFeature(); + Recording gone = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size), onDisk: false); + Recording empty = feature.Ended(RecordingOutcome.Failed, []); + + using HttpResponseMessage missing = await feature.GetAsync(gone); + using HttpResponseMessage nothing = await feature.GetAsync(empty, "bytes=0-"); + + Assert.Empty(await missing.Content.ReadAsByteArrayAsync()); + Assert.Empty(await nothing.Content.ReadAsByteArrayAsync()); + Assert.DoesNotContain( + missing.Headers.Concat(missing.Content.Headers), + header => header.Value.Any(value => value.Contains(feature.MountedAt, StringComparison.Ordinal))); + } + + [Fact] + public async Task TheFileOfARecordingWithAnArtefactIsTheArtefactAndItIsHandedOverAsAnMp4() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(4_000)); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage answer = await feature.GetAsync(recording); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); + Assert.Equal(artefact, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task TheFileOfAnEncodedRecordingAskedForAsItWasRecordedIsTheRecordingHandedOverAsATransportStream() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(4_000); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + feature.Encoded(recording); + + using HttpResponseMessage answer = await feature.GetFromAsync(recording, "recording"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("video/mp2t", answer.Content.Headers.ContentType?.MediaType); + Assert.Equal(written, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task TheRecordingItselfIsMovedAboutByARangeAndAskedForItsSizeAloneLikeTheArtefact() + { + await using var feature = new PlaybackFeature(); + byte[] written = PlaybackFeature.Bytes(4_000); + Recording recording = feature.Ended(RecordingOutcome.Complete, written); + feature.Encoded(recording); + + using HttpResponseMessage part = await feature.GetFromAsync(recording, "recording", "bytes=100-199"); + using HttpResponseMessage head = await feature.HeadFromAsync(recording, "recording"); + + Assert.Equal(HttpStatusCode.PartialContent, part.StatusCode); + Assert.Equal(written[100..200], await part.Content.ReadAsByteArrayAsync()); + Assert.Equal(HttpStatusCode.OK, head.StatusCode); + Assert.Equal(written.Length, head.Content.Headers.ContentLength); + } + + [Fact] + public async Task TheFileOfAnEncodedRecordingAskedForAsTheArtefactByNameIsTheArtefact() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(4_000)); + byte[] artefact = feature.Encoded(recording); + + using HttpResponseMessage answer = await feature.GetFromAsync(recording, "artefact"); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); + Assert.Equal(artefact, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task TheRecordingItselfAskedForWhenItIsGoneIsRefusedRatherThanQuietlyHandedTheArtefact() + { + await using var feature = new PlaybackFeature(); + Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(4_000), onDisk: false); + feature.Encoded(recording); + + using HttpResponseMessage answer = await feature.GetFromAsync(recording, "recording"); + + Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task ARecordingAlreadyBeingHandedOverKeepsFlowingAfterItsSessionIsEnded() + { + GatedPlaybackFiles files = new(Written); + await using AuthProbe probe = Wiring(files, new GatedOnTheFlyPlayer(Written), out Recording recording); + AuthSession session = await probe.SignedInAsync(); + + files.Handed.Release(FirstHalf); + + using HttpResponseMessage response = await probe.Client.GetAsync( + Bytes(recording), + HttpCompletionOption.ResponseHeadersRead); + await using Stream body = await response.Content.ReadAsStreamAsync(); + byte[] heard = new byte[GatedSize]; + + await body.ReadExactlyAsync(heard.AsMemory(0, FirstHalf)); + + session.Revoke(DateTime.UtcNow); + files.Handed.Release(GatedSize); + + await body.ReadExactlyAsync(heard.AsMemory(FirstHalf)); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(Written, heard); + } + + [Fact] + public async Task TheNextRequestForTheRecordingAfterThatSessionEndedIsRefused() + { + await using AuthProbe probe = Wiring(new GatedPlaybackFiles(Written), new GatedOnTheFlyPlayer(Written), out Recording recording); + AuthSession session = await probe.SignedInAsync(); + + session.Revoke(DateTime.UtcNow); + + using HttpResponseMessage response = await probe.Client.GetAsync(Bytes(recording), HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Null(response.Headers.Location); + Assert.Empty(await response.Content.ReadAsByteArrayAsync()); + } + + [Fact(DisplayName = "a player with a ticket asking for the artefact is handed the file made in H.264 after its profile was changed to H.265")] + public async Task APlayerAskingForTheArtefactIsHandedTheFileMadeInH264AfterItsProfileWasChangedToH265() + { + await using var feature = new TicketedFeature(); + Recording recording = feature.Ended(); + byte[] artefact = feature.Encoded(recording, EncodeCodec.H265, EncodeCodec.H264); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + $"/api/videos/{recording.Id.Wire}?source=artefact", + ticket); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); + Assert.Equal(artefact, await answer.Content.ReadAsByteArrayAsync()); + } + + [Theory(DisplayName = "a player with a ticket is handed an artefact made in H.265, however it is tagged, which no browser's decoding narrows")] + [InlineData("", "hvc1")] + [InlineData("?source=artefact", "hev1")] + public async Task APlayerWithATicketIsHandedAnArtefactMadeInH265(string query, string tag) + { + await using var feature = new TicketedFeature(); + Recording recording = feature.Ended(); + byte[] artefact = feature.Encoded(recording, EncodeCodec.H265, EncodeCodec.H265, tag); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + $"/api/videos/{recording.Id.Wire}{query}", + ticket); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); + Assert.Equal(artefact, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact(DisplayName = "a player with a ticket is not handed an artefact whose file is neither of the two codecs, and gets the recording itself")] + public async Task APlayerWithATicketIsNotHandedAnArtefactOfNeitherCodec() + { + await using var feature = new TicketedFeature(); + Recording recording = feature.Ended(); + feature.Encoded(recording, EncodeCodec.H265, EncodeCodec.H265); + feature.Codecs.Readings[feature.Jobs.Jobs[0].ArtefactName!.Value] = ArtefactCodecReading.Neither("av1"); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync($"/api/videos/{recording.Id.Wire}", ticket); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(feature.Written, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task APlayerThatAsksTheHeadersThenSeeksTwiceIsAdmittedEveryTime() + { + await using var feature = new TicketedFeature(); + Recording recording = feature.Ended(); + string ticket = await feature.TicketForAsync(recording.Id); + string path = $"/api/videos/{recording.Id.Wire}"; + + using HttpResponseMessage headers = await feature.AsAPlayerAsync(path, ticket, method: HttpMethod.Head); + using HttpResponseMessage whole = await feature.AsAPlayerAsync(path, ticket, "bytes=0-"); + using HttpResponseMessage middle = await feature.AsAPlayerAsync(path, ticket, "bytes=1000-1999"); + using HttpResponseMessage tail = await feature.AsAPlayerAsync(path, ticket, "bytes=-500"); + + Assert.Equal(HttpStatusCode.OK, headers.StatusCode); + Assert.Equal(feature.Written.Length, headers.Content.Headers.ContentLength); + Assert.Equal(HttpStatusCode.PartialContent, whole.StatusCode); + Assert.Equal(feature.Written, await whole.Content.ReadAsByteArrayAsync()); + Assert.Equal(HttpStatusCode.PartialContent, middle.StatusCode); + Assert.Equal(feature.Written[1000..2000], await middle.Content.ReadAsByteArrayAsync()); + Assert.Equal(HttpStatusCode.PartialContent, tail.StatusCode); + Assert.Equal(feature.Written[^500..], await tail.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task AGrantOpensTheOneRecordingItWasEnteredWithAndNoOther() + { + await using var feature = new TicketedFeature(); + Recording mine = feature.Ended(); + Recording another = feature.Ended(); + string ticket = await feature.TicketForAsync(mine.Id); + + using HttpResponseMessage entered = await feature.AsAPlayerAsync($"/api/videos/{mine.Id.Wire}", ticket); + using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync( + $"/api/videos/{another.Id.Wire}", + ticket); + + Assert.Equal(HttpStatusCode.OK, entered.StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); + } + + [Fact] + public async Task BrLa004ATicketIssuedForOneRecordingOpensNoOtherEvenOnItsFirstUse() + { + await using var feature = new TicketedFeature(); + Recording mine = feature.Ended(); + Recording another = feature.Ended(); + string ticket = await feature.TicketForAsync(mine.Id); + + using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync( + $"/api/videos/{another.Id.Wire}", + ticket, + "bytes=0-"); + + Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); + Assert.NotEqual(feature.Written, await elsewhere.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task BrLa004ATicketOfferedAtTheWrongRecordingIsSpentAndOpensItsOwnNoLonger() + { + await using var feature = new TicketedFeature(); + Recording mine = feature.Ended(); + Recording another = feature.Ended(); + string ticket = await feature.TicketForAsync(mine.Id); + + using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync($"/api/videos/{another.Id.Wire}", ticket); + using HttpResponseMessage afterwards = await feature.AsAPlayerAsync($"/api/videos/{mine.Id.Wire}", ticket); + + Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, afterwards.StatusCode); + } + + [Fact] + public async Task APlayerCarryingNothingIsRefusedWithoutBeingSentToASignInScreen() + { + await using var feature = new TicketedFeature(); + Recording recording = feature.Ended(); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync($"/api/videos/{recording.Id.Wire}", null); + + Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); + Assert.Null(answer.Headers.Location); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task SomethingThatWasNeverIssuedIsRefusedBeforeAnyByteLeaves() + { + await using var feature = new TicketedFeature(); + Recording recording = feature.Ended(); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + $"/api/videos/{recording.Id.Wire}", + new string('a', 43)); + + byte[] body = await answer.Content.ReadAsByteArrayAsync(); + + Assert.Equal(HttpStatusCode.Forbidden, answer.StatusCode); + Assert.NotEqual(feature.Written, body); + } + + [Theory] + [InlineData("/play")] + [InlineData("/thumbnail")] + [InlineData("/scrub")] + [InlineData("/captions")] + [InlineData("/data-broadcast")] + [InlineData("/data-broadcast/modules/64/7/0/1")] + public async Task TheTicketOpensTheBytesAndNothingElseUnderTheSamePrefix(string beneath) + { + await using var feature = new TicketedFeature(); + Recording recording = feature.Ended(); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + $"/api/videos/{recording.Id.Wire}{beneath}", + ticket); + + Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); + Assert.Null(answer.Headers.Location); + } + + [Fact] + public async Task TheAnswerToATicketIsNeverHeldByAnythingInFront() + { + await using var feature = new TicketedFeature(); + Recording recording = feature.Ended(); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync($"/api/videos/{recording.Id.Wire}", ticket); + + Assert.Equal("no-store, private", answer.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", answer.Headers.Vary, StringComparer.OrdinalIgnoreCase); + } + + [Fact(DisplayName = "a player handed the ticket in the path is handed the recording, asks its headers and seeks on the same URL")] + public async Task APlayerHandedTheTicketInThePathIsHandedTheRecordingAndSeeksOnTheSameUrl() + { + await using TicketedFeature feature = new(); + Recording recording = feature.Ended(); + string path = WithTicket(recording, await feature.TicketForAsync(recording.Id), AName); + + using HttpResponseMessage headers = await feature.AsAPlayerAsync(path, null, method: HttpMethod.Head); + using HttpResponseMessage whole = await feature.AsAPlayerAsync(path, null, "bytes=0-"); + using HttpResponseMessage middle = await feature.AsAPlayerAsync(path, null, "bytes=1000-1999"); + + Assert.Equal(HttpStatusCode.OK, headers.StatusCode); + Assert.Equal(feature.Written.Length, headers.Content.Headers.ContentLength); + Assert.Equal(HttpStatusCode.PartialContent, whole.StatusCode); + Assert.Equal(feature.Written, await whole.Content.ReadAsByteArrayAsync()); + Assert.Equal(HttpStatusCode.PartialContent, middle.StatusCode); + Assert.Equal(feature.Written[1000..2000], await middle.Content.ReadAsByteArrayAsync()); + } + + [Fact(DisplayName = "the ticket in the path hands over the source the query asks for")] + public async Task TheTicketInThePathHandsOverTheSourceTheQueryAsksFor() + { + await using TicketedFeature feature = new(); + Recording recording = feature.Ended(); + byte[] artefact = feature.Encoded(recording, EncodeCodec.H264, EncodeCodec.H264); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage encoded = await feature.AsAPlayerAsync( + $"{WithTicket(recording, ticket, "a-programme.mp4")}?source=artefact", + null); + using HttpResponseMessage itself = await feature.AsAPlayerAsync( + $"{WithTicket(recording, ticket, AName)}?source=recording", + null); + + Assert.Equal(HttpStatusCode.OK, encoded.StatusCode); + Assert.Equal("video/mp4", encoded.Content.Headers.ContentType?.MediaType); + Assert.Equal(artefact, await encoded.Content.ReadAsByteArrayAsync()); + Assert.Equal(HttpStatusCode.OK, itself.StatusCode); + Assert.Equal(feature.Written, await itself.Content.ReadAsByteArrayAsync()); + } + + [Theory(DisplayName = "the name at the end of the path is only for showing and is never read")] + [InlineData("")] + [InlineData("a-programme.mp4")] + [InlineData("%E7%95%AA%E7%B5%84%20%E3%81%AE%E5%90%8D%E5%89%8D.ts")] + [InlineData("two/segments.ts")] + [InlineData("no-extension")] + public async Task TheNameAtTheEndOfThePathIsOnlyForShowing(string name) + { + await using TicketedFeature feature = new(); + Recording recording = feature.Ended(); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + WithTicket(recording, await feature.TicketForAsync(recording.Id), name), + null); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(feature.Written, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact(DisplayName = "the ticket in the path opens the one recording it was issued for and no other")] + public async Task TheTicketInThePathOpensTheOneRecordingItWasIssuedForAndNoOther() + { + await using TicketedFeature feature = new(); + Recording mine = feature.Ended(); + Recording another = feature.Ended(); + string ticket = await feature.TicketForAsync(mine.Id); + + using HttpResponseMessage entered = await feature.AsAPlayerAsync(WithTicket(mine, ticket, AName), null); + using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync(WithTicket(another, ticket, AName), null); + + Assert.Equal(HttpStatusCode.OK, entered.StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); + Assert.NotEqual(feature.Written, await elsewhere.Content.ReadAsByteArrayAsync()); + } + + [Fact(DisplayName = "something that was never issued in the ticket's place is refused before any byte leaves")] + public async Task SomethingThatWasNeverIssuedInTheTicketsPlaceIsRefused() + { + await using TicketedFeature feature = new(); + Recording recording = feature.Ended(); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + WithTicket(recording, new string('a', 43), AName), + null); + + Assert.Equal(HttpStatusCode.Forbidden, answer.StatusCode); + Assert.NotEqual(feature.Written, await answer.Content.ReadAsByteArrayAsync()); + } + + [Fact(DisplayName = "something that is not the shape of a ticket in its place is refused without being sent to a sign-in screen, whatever the header carries")] + public async Task SomethingThatIsNotTheShapeOfATicketInItsPlaceIsRefused() + { + await using TicketedFeature feature = new(); + Recording recording = feature.Ended(); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + WithTicket(recording, "short", AName), + ticket); + + Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); + Assert.Null(answer.Headers.Location); + Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); + } + + [Theory(DisplayName = "the ticket in the path opens the bytes and nothing else under the same prefix")] + [InlineData("play")] + [InlineData("thumbnail")] + [InlineData("scrub")] + [InlineData("captions")] + [InlineData("data-broadcast")] + public async Task TheTicketInThePathOpensTheBytesAndNothingElse(string beneath) + { + await using TicketedFeature feature = new(); + Recording recording = feature.Ended(); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + $"/api/videos/{recording.Id.Wire}/{beneath}/with-ticket/{ticket}/{AName}", + null); + + Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); + Assert.Null(answer.Headers.Location); + } + + [Fact(DisplayName = "a ticket in the query is refused on both surfaces, because it shows as the title in a player")] + public async Task ATicketInTheQueryIsRefusedOnBothSurfaces() + { + await using TicketedFeature feature = new(); + Recording recording = feature.Ended(); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage plain = await feature.AsAPlayerAsync( + $"/api/videos/{recording.Id.Wire}?ticket={ticket}", + null); + using HttpResponseMessage named = await feature.AsAPlayerAsync( + $"/api/videos/{recording.Id.Wire}/with-ticket/short/{AName}?ticket={ticket}", + null); + + Assert.Equal(HttpStatusCode.Unauthorized, plain.StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, named.StatusCode); + } + + [Fact(DisplayName = "the answer to a ticket in the path is never held by anything in front")] + public async Task TheAnswerToATicketInThePathIsNeverHeldByAnythingInFront() + { + await using TicketedFeature feature = new(); + Recording recording = feature.Ended(); + + using HttpResponseMessage answer = await feature.AsAPlayerAsync( + WithTicket(recording, await feature.TicketForAsync(recording.Id), AName), + null); + + Assert.Equal("no-store, private", answer.Headers.CacheControl?.ToString()); + } + + [Fact(DisplayName = "with every log turned up to its finest, no line carries the ticket in the path")] + public async Task WithEveryLogTurnedUpNoLineCarriesTheTicketInThePath() + { + RecordedStartup heard = new(); + await using TicketedFeature feature = new(heard); + Recording recording = feature.Ended(); + Recording another = feature.Ended(); + string ticket = await feature.TicketForAsync(recording.Id); + + using HttpResponseMessage entered = await feature.AsAPlayerAsync(WithTicket(recording, ticket, AName), null); + using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync(WithTicket(another, ticket, AName), null); + + Assert.Equal(HttpStatusCode.OK, entered.StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); + Assert.Contains(heard.Everything, line => line.Category.StartsWith("Microsoft.AspNetCore", StringComparison.Ordinal)); + Assert.Empty(heard.Everything + .Where(line => line.Text.Contains(ticket, StringComparison.Ordinal)) + .Select(line => $"{line.Category} {line.Level}") + .Distinct()); + } + + [Fact] + public async Task ALiveTicketOpensNoRecordingAndIsSpentByTheAttempt() + { + await using AuthProbe probe = WiringWithARecording(out Recording recording); + string ticket = await IssuedAsync(probe); + Uri bytes = new($"/api/videos/{recording.Id.Wire}", UriKind.Relative); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage first = await player.GetAsync(bytes); + using HttpResponseMessage again = await player.GetAsync(bytes); + + Assert.Equal(HttpStatusCode.Forbidden, first.StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, again.StatusCode); + Assert.Null(first.Headers.Location); + } + + private static Uri Bytes(Recording recording) => new($"/api/videos/{recording.Id.Wire}", UriKind.Relative); + + private static AuthProbe Wiring(IPlaybackFileStore files, IOnTheFlyPlayer player, out Recording recording) + { + HeldRecordings recordings = new(); + + recording = RecordingFeature.Begin(RecordingId.New()); + recording.Wrote(TimeSpan.FromMinutes(30)); + recording.Abort(RecordingFeature.Noon.AddMinutes(30)); + recording.Settle(RecordingOutcome.Complete, GatedSize, RecordingFeature.Noon.AddMinutes(30)); + recordings.Recordings.Add(recording); + + return AuthProbe.OverHttp(services => + { + services.RemoveAll(); + services.RemoveAll(); + services.AddSingleton(recordings); + services.AddSingleton(new HeldEncodeJobs()); + services.AddSingleton(new HeldEncodeProfiles()); + services.AddSingleton(new HeldPlaybackPositions()); + services.AddSingleton(files); + services.AddSingleton(player); + }); + } + + private static string WithTicket(Recording recording, string ticket, string name) + => $"/api/videos/{recording.Id.Wire}/with-ticket/{ticket}/{name}"; + + private static HttpClient Carrying(AuthProbe probe, string? ticket) + { + HttpClient player = probe.Wired.CreateClient(new WebApplicationFactoryClientOptions + { + BaseAddress = new Uri("http://localhost"), + AllowAutoRedirect = false, + }); + + if (ticket is not null) + { + player.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ticket); + } + + return player; + } + + private static async Task IssuedAsync(AuthProbe probe) + { + await probe.SignedInAsync(); + + using HttpResponseMessage answer = await probe.Client.PostAsJsonAsync( + new Uri("/api/live/ticket", UriKind.Relative), + new { networkId = 32736, serviceId = 1024 }); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + + using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); + + return read.RootElement.GetProperty("data").GetProperty("inTheClear").GetString()!; + } + + private AuthProbe WiringWithARecording(out Recording recording) + { + HeldServices services = new(); + HeldCandidates candidates = new(); + HeldRecordings recordings = new(); + NetworkId network = new(32736); + ServiceId service = new(1024); + CandidateChannel candidate = CandidateChannel.Discover( + CandidateChannelId.New(), + network, + service, + TuningParameters.Terrestrial(27), + At); + + candidate.Select(SelectionSource.Manual, null, At); + services.Services.Add(BroadcastService.Discover(network, service, "Watched", ServiceCategory.Television, At)); + candidates.Candidates.Add(candidate); + + recording = RecordingFeature.Begin(RecordingId.New()); + recording.Wrote(TimeSpan.FromMinutes(30)); + recording.Abort(RecordingFeature.Noon.AddMinutes(30)); + recording.Settle(RecordingOutcome.Complete, 4_000, RecordingFeature.Noon.AddMinutes(30)); + recordings.Recordings.Add(recording); + + return AuthProbe.OverHttp(wired => + { + wired.AddSingleton(services); + wired.AddSingleton(candidates); + wired.AddSingleton(recordings); + wired.AddSingleton(supply); + }); + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveHlsTests.cs b/tests/Carina.Api.Tests/Feature/Streaming/LiveHlsDeliveryTests.cs similarity index 81% rename from tests/Carina.Api.Tests/FeatureTest/LiveHlsTests.cs rename to tests/Carina.Api.Tests/Feature/Streaming/LiveHlsDeliveryTests.cs index 6525fc468..6f2cad713 100644 --- a/tests/Carina.Api.Tests/FeatureTest/LiveHlsTests.cs +++ b/tests/Carina.Api.Tests/Feature/Streaming/LiveHlsDeliveryTests.cs @@ -1,9 +1,9 @@ using System.Net; -using System.Net.Http.Json; using System.Text.Json; using System.Text.RegularExpressions; using Carina.Api.Live; +using Carina.Api.Tests.FeatureTest; using Carina.Domain.Auth; using Carina.Domain.Channels; using Carina.Domain.Streaming; @@ -13,9 +13,10 @@ using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; -namespace Carina.Api.Tests.FeatureTest; +namespace Carina.Api.Tests.Feature.Streaming; -public sealed partial class LiveHlsTests +[Trait("Category", "Feature")] +public sealed partial class LiveHlsDeliveryTests { private const uint OneFrame = 1001; @@ -33,24 +34,6 @@ public sealed partial class LiveHlsTests private int gops; - [Fact(DisplayName = "BR-PV-002, BR-PV-005: a ticket in the path under a name ending in .m3u8 is answered with a playlist naming the playlist of one key")] - public async Task ATicketUnderANameEndingInM3u8IsAnsweredWithAPlaylistNamingThePlaylistOfOneKey() - { - await using AuthProbe probe = Wiring(); - using HttpClient player = Player(probe); - - using HttpResponseMessage answer = await OpenedAsync(player, WithTicket(await IssuedAsync(probe), "a-channel%20a-programme.m3u8")); - string playlist = await answer.Content.ReadAsStringAsync(); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(LiveHlsPlaylists.MediaType, answer.Content.Headers.ContentType?.MediaType); - Assert.Equal("no-store, private", answer.Headers.CacheControl?.ToString()); - Assert.StartsWith("#EXTM3U\n", playlist, StringComparison.Ordinal); - Assert.Single(Regex.Matches(playlist, "#EXT-X-STREAM-INF:")); - Assert.Contains(",RESOLUTION=1920x1080,FRAME-RATE=59.940,CODECS=\"avc1.640028,mp4a.40.2\"\n", playlist, StringComparison.Ordinal); - Assert.True(Unguessable.IsOne(KeyIn(playlist))); - } - [Fact(DisplayName = "BR-PV-005: the playlist of a key, its initialisation and its segments are opened by the key alone")] public async Task ThePlaylistOfAKeyItsInitialisationAndItsSegmentsAreOpenedByTheKeyAlone() { @@ -107,21 +90,6 @@ public async Task AKeyNeverHandedOutOpensNothing(string beneath) Assert.Equal(HttpStatusCode.Unauthorized, shortened.StatusCode); } - [Fact(DisplayName = "BR-PD-022: an external player's playlist sits on the profile this machine opens at with the main sound, in H.264 though another format is encoded here")] - public async Task AnExternalPlayersPlaylistSitsOnTheProfileThisMachineOpensAtInH264() - { - await using AuthProbe probe = Wiring(); - using HttpClient player = Player(probe); - - using HttpResponseMessage answer = await OpenedAsync(player, WithTicket(await IssuedAsync(probe), "a.m3u8")); - - LiveSessionKey seated = Assert.Single(Seating(probe).Asked); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(new LiveSessionKey(new NetworkId(32736), new ServiceId(1024), LiveProfile.FullHd60), seated); - Assert.Equal(VideoCodec.H264, seated.Format); - } - [Fact(DisplayName = "BR-PD-022: a playlist sits on the session a wire asking for the same profile and sound sits on, so it takes no transcoder of its own")] public async Task APlaylistSitsOnTheSessionAWireAskingForTheSameSitsOn() { @@ -178,33 +146,6 @@ public async Task ABrowsersPlaylistAskedForWhatThereIsNotIsRefusedBeforeAnybodyI Assert.Empty(Seating(probe).Asked); } - [Fact(DisplayName = "BR-PV-002, BR-PV-005: the ticket is spent on the first playlist, and opening the same name again enters by the grant and is handed a new key")] - public async Task OpeningTheSameNameAgainEntersByTheGrantAndIsHandedANewKey() - { - await using AuthProbe probe = Wiring(); - using HttpClient player = Player(probe); - string path = WithTicket(await IssuedAsync(probe), "a.m3u8"); - - string first = KeyIn(await (await OpenedAsync(player, path)).Content.ReadAsStringAsync()); - string second = KeyIn(await (await OpenedAsync(player, path)).Content.ReadAsStringAsync()); - - Assert.NotEqual(first, second); - Assert.Equal(2, fanout.Viewers); - } - - [Fact] - public async Task ATicketForOneChannelOpensNoPlaylistOnAnother() - { - await using AuthProbe probe = Wiring(); - using HttpClient player = Player(probe); - - using HttpResponseMessage refused = await player.GetAsync( - new Uri($"/api/live/32736-1025/with-ticket/{await IssuedAsync(probe)}/a.m3u8", UriKind.Relative)); - - Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode); - Assert.Empty(Seating(probe).Asked); - } - [Fact(DisplayName = "BR-PV-005: a key nothing is asked with for thirty seconds is refused, and the seat it held is let go of")] public async Task AKeyNothingIsAskedWithForThirtySecondsIsRefusedAndItsSeatLetGoOf() { diff --git a/tests/Carina.Api.Tests/Feature/Streaming/LiveStreamDeliveryTests.cs b/tests/Carina.Api.Tests/Feature/Streaming/LiveStreamDeliveryTests.cs new file mode 100644 index 000000000..55e06a63e --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Streaming/LiveStreamDeliveryTests.cs @@ -0,0 +1,593 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.RegularExpressions; + +using Carina.Api.Live; +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Auth; +using Carina.Domain.Channels; +using Carina.Domain.Recordings; +using Carina.Domain.Streaming; +using Carina.Infrastructure.Streaming; +using Carina.TestSupport; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Net.Http.Headers; + +namespace Carina.Api.Tests.Feature.Streaming; + +[Trait("Category", "Feature")] +public sealed partial class LiveStreamDeliveryTests +{ + private const uint OneFrame = 1001; + + private const string Channel = "/api/live/32736-1024"; + + private static readonly Uri Exit = new("/api/live/32736-1024/stream", UriKind.Relative); + + private static readonly DateTime At = new(2026, 9, 3, 0, 0, 0, DateTimeKind.Utc); + + private static readonly TimeSpan NoTimeAtAllToSayAnything = TimeSpan.FromMilliseconds(200); + + private readonly PipedSupply supply = new(); + + private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); + + private readonly HeldTranscoders transcoders; + + private readonly LiveFanout fanout = new(new LiveFanoutSettings()); + + private int gops; + + public LiveStreamDeliveryTests() => transcoders = new HeldTranscoders(budget); + + [Fact] + public async Task APlayerThatOpensTheStreamAgainWithTheSameTicketIsLetInAgain() + { + await using AuthProbe probe = Wiring(); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + HttpResponseMessage first = await OpenedAsync(player); + + Assert.Equal(HttpStatusCode.OK, first.StatusCode); + Assert.Equal(LiveStreamDelivery.MediaType, first.Content.Headers.ContentType?.MediaType); + + first.Dispose(); + + using HttpResponseMessage again = await OpenedAsync(player); + + Assert.Equal(HttpStatusCode.OK, again.StatusCode); + Assert.Equal(LiveStreamDelivery.MediaType, again.Content.Headers.ContentType?.MediaType); + } + + [Fact] + public async Task TheTicketThatOpenedOneChannelOpensNoOther() + { + await using AuthProbe probe = Wiring(); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage opened = await OpenedAsync(player); + + Assert.Equal(HttpStatusCode.OK, opened.StatusCode); + + using HttpResponseMessage another = await player.GetAsync( + new Uri("/api/live/32737-1032/stream", UriKind.Relative), + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Forbidden, another.StatusCode); + Assert.Null(another.Headers.Location); + } + + [Fact] + public async Task AReaderCarryingNoTicketAndNoCookieIsRefusedWithNothingInTheBody() + { + await using AuthProbe probe = Wiring(); + + using HttpClient player = probe.Wired.CreateClient(new WebApplicationFactoryClientOptions + { + BaseAddress = new Uri("http://localhost"), + AllowAutoRedirect = false, + }); + + using HttpResponseMessage refused = await player.GetAsync(Exit, HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); + Assert.Null(refused.Headers.Location); + Assert.Empty(await refused.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task TheBytesOfTheChannelReachTheReaderAsTheyAre() + { + await using AuthProbe probe = Wiring(); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage opened = await OpenedAsync(player); + + Assert.Equal(HttpStatusCode.OK, opened.StatusCode); + + byte[] sent = Mouthful(); + byte[] twice = [.. sent, .. sent]; + + await supply.Opened[0].WriteAsync(sent); + + await using Stream reading = await opened.Content.ReadAsStreamAsync(); + + Assert.Equal(twice, await ReadAsync(reading, twice.Length)); + } + + [Fact] + public async Task AReaderRidesTheReadingAWireIsWatchingAndNoSecondTunerIsTaken() + { + await using AuthProbe probe = Wiring(); + string cookie = await probe.SignedInCookieAsync(); + string ticket = await IssuedAsync(probe); + + using System.Net.WebSockets.WebSocket wire = await Wired(probe, cookie).ConnectAsync( + Handshake(), + Patiently()); + + Assert.Equal(1, transcoders.Started); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage opened = await OpenedAsync(player); + + Assert.Equal(HttpStatusCode.OK, opened.StatusCode); + Assert.Equal(1, supply.Asked); + Assert.Single(supply.Opened); + Assert.Equal(1, transcoders.Started); + Assert.Equal(1, budget.Running); + } + + [Fact] + public async Task TheReadingIsHeldOpenWhileTheReaderReadsAndIsLetGoWhenItStops() + { + await using AuthProbe probe = Wiring(); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + HttpResponseMessage opened = await OpenedAsync(player); + + Assert.Equal(HttpStatusCode.OK, opened.StatusCode); + + await Eventually.Happens( + () => supply.Opened[0].HeldOpenUntil.Count > 0, + "the reading is asked to be held open while it is being read"); + + opened.Dispose(); + + await Eventually.Happens(() => supply.Opened[0].Disposed, "the reading is let go once the reader has stopped"); + } + + [Fact] + public async Task AChannelOutsideWhatABroadcastCarriesIsRefusedBeforeAnythingIsTuned() + { + await using AuthProbe probe = Wiring(); + string cookie = await probe.SignedInCookieAsync(); + + using HttpClient watcher = probe.Relaying(cookie); + using HttpResponseMessage refused = await watcher.GetAsync( + new Uri("/api/live/70000-1024/stream", UriKind.Relative), + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode); + Assert.Equal(0, supply.Asked); + } + + [Fact] + public async Task AChannelNoTunerWillReachIsRefusedInWordsAndTheTicketIsGoodAfterwards() + { + supply.Refusing = LiveRefusal.NoTunerFree; + + await using AuthProbe probe = Wiring(); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage refused = await player.GetAsync(Exit, HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, refused.StatusCode); + Assert.Equal( + LiveRefusalClosures.Because(LiveRefusal.NoTunerFree), + await refused.Content.ReadAsStringAsync()); + + supply.Refusing = null; + + using HttpResponseMessage opened = await OpenedAsync(player); + + Assert.Equal(HttpStatusCode.OK, opened.StatusCode); + } + + [Fact] + public async Task AChannelThatSaysNothingInTimeIsRefusedRatherThanOpenedOnNothing() + { + await using AuthProbe probe = Wiring(NoTimeAtAllToSayAnything); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage refused = await player.GetAsync(Exit, HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, refused.StatusCode); + Assert.Equal(LiveStreamDelivery.NothingCameInTime, await refused.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task TheOneSurfaceALiveTicketOpensIsTheChannelHandedOverAsItIs() + { + await using AuthProbe probe = WiringWithARecording(out _); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage opened = await OpenedAsync(player); + + Assert.Equal(HttpStatusCode.OK, opened.StatusCode); + Assert.Equal(LiveStreamDelivery.MediaType, opened.Content.Headers.ContentType?.MediaType); + } + + [Fact] + public async Task ATicketForOneChannelOpensTheChannelHandedOverOnNoOther() + { + await using AuthProbe probe = WiringWithARecording(out _); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage refused = await player.GetAsync( + new Uri("/api/live/32736-1025/stream", UriKind.Relative), + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode); + } + + [Theory(DisplayName = "a player handed the live ticket in the path is handed the channel, whatever name ends the path")] + [InlineData("a-channel%20a-programme.ts")] + [InlineData("")] + [InlineData("a-name.mp4")] + public async Task APlayerHandedTheLiveTicketInThePathIsHandedTheChannel(string name) + { + await using AuthProbe probe = WiringWithARecording(out _); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, null); + using HttpResponseMessage opened = await OpenedAsync( + player, + new Uri($"/api/live/32736-1024/with-ticket/{ticket}/{name}", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.OK, opened.StatusCode); + Assert.Equal(LiveStreamDelivery.MediaType, opened.Content.Headers.ContentType?.MediaType); + } + + [Fact(DisplayName = "a live ticket in the path opens the channel it was issued for and no other")] + public async Task ALiveTicketInThePathOpensTheChannelItWasIssuedForAndNoOther() + { + await using AuthProbe probe = WiringWithARecording(out _); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, null); + using HttpResponseMessage refused = await player.GetAsync( + new Uri($"/api/live/32736-1025/with-ticket/{ticket}/a-channel.ts", UriKind.Relative), + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode); + } + + [Fact(DisplayName = "something that is not the shape of a ticket in the live path is refused without being sent to a sign-in screen")] + public async Task SomethingThatIsNotATicketInTheLivePathIsRefused() + { + await using AuthProbe probe = WiringWithARecording(out _); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, ticket); + using HttpResponseMessage refused = await player.GetAsync( + new Uri("/api/live/32736-1024/with-ticket/short/a-channel.ts", UriKind.Relative), + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); + Assert.Null(refused.Headers.Location); + } + + [Fact(DisplayName = "a live ticket in the query is refused, because it shows as the title in a player")] + public async Task ALiveTicketInTheQueryIsRefused() + { + await using AuthProbe probe = WiringWithARecording(out _); + string ticket = await IssuedAsync(probe); + + using HttpClient player = Carrying(probe, null); + using HttpResponseMessage refused = await player.GetAsync( + new Uri($"{Exit}?ticket={ticket}", UriKind.Relative), + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); + } + + [Fact(DisplayName = "BR-PV-002, BR-PV-005: a ticket in the path under a name ending in .m3u8 is answered with a playlist naming the playlist of one key")] + public async Task ATicketUnderANameEndingInM3u8IsAnsweredWithAPlaylistNamingThePlaylistOfOneKey() + { + await using AuthProbe probe = WiringTheFanout(); + using HttpClient player = Player(probe); + + using HttpResponseMessage answer = await OpenedOnTheFanoutAsync(player, WithTicket(await IssuedAsync(probe), "a-channel%20a-programme.m3u8")); + string playlist = await answer.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(LiveHlsPlaylists.MediaType, answer.Content.Headers.ContentType?.MediaType); + Assert.Equal("no-store, private", answer.Headers.CacheControl?.ToString()); + Assert.StartsWith("#EXTM3U\n", playlist, StringComparison.Ordinal); + Assert.Single(Regex.Matches(playlist, "#EXT-X-STREAM-INF:")); + Assert.Contains(",RESOLUTION=1920x1080,FRAME-RATE=59.940,CODECS=\"avc1.640028,mp4a.40.2\"\n", playlist, StringComparison.Ordinal); + Assert.True(Unguessable.IsOne(KeyIn(playlist))); + } + + [Fact(DisplayName = "BR-PD-022: an external player's playlist sits on the profile this machine opens at with the main sound, in H.264 though another format is encoded here")] + public async Task AnExternalPlayersPlaylistSitsOnTheProfileThisMachineOpensAtInH264() + { + await using AuthProbe probe = WiringTheFanout(); + using HttpClient player = Player(probe); + + using HttpResponseMessage answer = await OpenedOnTheFanoutAsync(player, WithTicket(await IssuedAsync(probe), "a.m3u8")); + + LiveSessionKey seated = Assert.Single(Seating(probe).Asked); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + Assert.Equal(new LiveSessionKey(new NetworkId(32736), new ServiceId(1024), LiveProfile.FullHd60), seated); + Assert.Equal(VideoCodec.H264, seated.Format); + } + + [Fact(DisplayName = "BR-PV-002, BR-PV-005: the ticket is spent on the first playlist, and opening the same name again enters by the grant and is handed a new key")] + public async Task OpeningTheSameNameAgainEntersByTheGrantAndIsHandedANewKey() + { + await using AuthProbe probe = WiringTheFanout(); + using HttpClient player = Player(probe); + string path = WithTicket(await IssuedAsync(probe), "a.m3u8"); + + string first = KeyIn(await (await OpenedOnTheFanoutAsync(player, path)).Content.ReadAsStringAsync()); + string second = KeyIn(await (await OpenedOnTheFanoutAsync(player, path)).Content.ReadAsStringAsync()); + + Assert.NotEqual(first, second); + Assert.Equal(2, fanout.Viewers); + } + + [Fact] + public async Task ATicketForOneChannelOpensNoPlaylistOnAnother() + { + await using AuthProbe probe = WiringTheFanout(); + using HttpClient player = Player(probe); + + using HttpResponseMessage refused = await player.GetAsync( + new Uri($"/api/live/32736-1025/with-ticket/{await IssuedAsync(probe)}/a.m3u8", UriKind.Relative)); + + Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode); + Assert.Empty(Seating(probe).Asked); + } + + private static Uri Handshake() + => new($"ws://localhost{LiveWire.Path}?network=32736&service=1024&profile=720p30"); + + private static CancellationToken Patiently() => new CancellationTokenSource(Eventually.Patience).Token; + + private static byte[] Mouthful() => [.. Enumerable.Range(0, 4_000).Select(at => (byte)(at % 251))]; + + private static WebSocketClient Wired(AuthProbe probe, string cookie) + { + WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); + + client.ConfigureRequest += request => request.Headers[HeaderNames.Cookie] = cookie; + + return client; + } + + private static async Task ReadAsync(Stream reading, int many) + { + byte[] heard = new byte[many]; + int filled = 0; + + while (filled < many) + { + int read = await reading.ReadAsync(heard.AsMemory(filled), Patiently()); + + if (read is 0) + { + break; + } + + filled += read; + } + + return [.. heard.Take(filled)]; + } + + private static async Task IssuedAsync(AuthProbe probe) + { + await probe.SignedInAsync(); + + using HttpResponseMessage answer = await probe.Client.PostAsJsonAsync( + new Uri("/api/live/ticket", UriKind.Relative), + new { networkId = 32736, serviceId = 1024 }); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + + using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); + + return read.RootElement.GetProperty("data").GetProperty("inTheClear").GetString()!; + } + + private AuthProbe Wiring() => Wiring(new LiveSessionSettings().LongestRaise); + + private AuthProbe Wiring(TimeSpan longestRaise) + { + HeldServices services = new(); + HeldCandidates candidates = new(); + NetworkId network = new(32736); + ServiceId service = new(1024); + CandidateChannel candidate = CandidateChannel.Discover( + CandidateChannelId.New(), + network, + service, + TuningParameters.Terrestrial(27), + At); + + candidate.Select(SelectionSource.Manual, null, At); + services.Services.Add(BroadcastService.Discover(network, service, "Watched", ServiceCategory.Television, At)); + candidates.Candidates.Add(candidate); + + return AuthProbe.OverHttp(wired => + { + wired.AddSingleton(services); + wired.AddSingleton(candidates); + wired.AddSingleton(supply); + wired.AddSingleton(budget); + wired.AddSingleton(transcoders); + wired.AddSingleton(new LiveSessionSettings( + longestRaise: longestRaise, + betweenHolds: TimeSpan.FromMilliseconds(50), + heldAhead: TimeSpan.FromSeconds(2))); + }); + } + + private static HttpClient Carrying(AuthProbe probe, string? ticket) + { + HttpClient player = probe.Wired.CreateClient(new WebApplicationFactoryClientOptions + { + BaseAddress = new Uri("http://localhost"), + AllowAutoRedirect = false, + }); + + if (ticket is not null) + { + player.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ticket); + } + + return player; + } + + private Task OpenedAsync(HttpClient player) => OpenedAsync(player, Exit); + + private async Task OpenedAsync(HttpClient player, Uri at) + { + Task opening = player.GetAsync(at, HttpCompletionOption.ResponseHeadersRead); + + while (!opening.IsCompleted) + { + await supply.FeedAsync(Mouthful()); + await Task.WhenAny(opening, Task.Delay(TimeSpan.FromMilliseconds(20))); + } + + return await opening; + } + + private AuthProbe WiringWithARecording(out Recording recording) + { + HeldServices services = new(); + HeldCandidates candidates = new(); + HeldRecordings recordings = new(); + NetworkId network = new(32736); + ServiceId service = new(1024); + CandidateChannel candidate = CandidateChannel.Discover( + CandidateChannelId.New(), + network, + service, + TuningParameters.Terrestrial(27), + At); + + candidate.Select(SelectionSource.Manual, null, At); + services.Services.Add(BroadcastService.Discover(network, service, "Watched", ServiceCategory.Television, At)); + candidates.Candidates.Add(candidate); + + recording = RecordingFeature.Begin(RecordingId.New()); + recording.Wrote(TimeSpan.FromMinutes(30)); + recording.Abort(RecordingFeature.Noon.AddMinutes(30)); + recording.Settle(RecordingOutcome.Complete, 4_000, RecordingFeature.Noon.AddMinutes(30)); + recordings.Recordings.Add(recording); + + return AuthProbe.OverHttp(wired => + { + wired.AddSingleton(services); + wired.AddSingleton(candidates); + wired.AddSingleton(recordings); + wired.AddSingleton(supply); + }); + } + + [GeneratedRegex(@"^/api/hls/([^/]+)/index\.m3u8$", RegexOptions.Multiline)] + private static partial Regex KeyedPlaylist(); + + private static string KeyIn(string playlist) => KeyedPlaylist().Match(playlist).Groups[1].Value; + + private static string WithTicket(string ticket, string name) => $"{Channel}/with-ticket/{ticket}/{name}"; + + private static SeatingAt Seating(AuthProbe probe) + => Assert.IsType(probe.Wired.Services.GetRequiredService()); + + private static HttpClient Player(AuthProbe probe) + => probe.Wired.CreateClient(new WebApplicationFactoryClientOptions + { + BaseAddress = new Uri("http://localhost"), + AllowAutoRedirect = false, + HandleCookies = false, + }); + + private LiveFrame Gop() + { + int gop = gops++; + + return new LiveFrame( + LiveChannel.Picture, + LivePts.Start, + Fmp4Media.Fragment((ulong)gop * 60 * OneFrame, [.. Enumerable.Repeat(OneFrame, 60)], true)); + } + + /// + /// Opens while the channel goes on carrying a keyframe every two seconds of pictures, for + /// as long as the answer takes. + /// + private async Task OpenedOnTheFanoutAsync(HttpClient client, string path) + { + Task opening = client.GetAsync(new Uri(path, UriKind.Relative)); + + while (!opening.IsCompleted) + { + fanout.Publish(Gop()); + await Task.WhenAny(opening, Task.Delay(TimeSpan.FromMilliseconds(20))); + } + + return await opening; + } + + private AuthProbe WiringTheFanout(HlsKeys? keys = null, RecordedStartup? heard = null) + { + HeldServices services = new(); + HeldCandidates candidates = new(); + NetworkId network = new(32736); + ServiceId service = new(1024); + CandidateChannel candidate = CandidateChannel.Discover( + CandidateChannelId.New(), + network, + service, + TuningParameters.Terrestrial(27), + At); + + candidate.Select(SelectionSource.Manual, null, At); + services.Services.Add(BroadcastService.Discover(network, service, "Watched", ServiceCategory.Television, At)); + candidates.Candidates.Add(candidate); + fanout.Publish(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Fmp4Media.Initialisation())); + + void Wired(IServiceCollection wired) + { + wired.AddSingleton(services); + wired.AddSingleton(candidates); + wired.AddSingleton(new SeatingAt(fanout)); + wired.AddSingleton(new AlreadyChosen(LiveEncoder.Vaapi, [VideoCodec.H264, VideoCodec.H265])); + + if (keys is not null) + { + wired.AddSingleton(keys); + } + } + + return heard is null ? AuthProbe.OverHttp(Wired) : AuthProbe.OverHttpHeardBy(heard, Wired); + } +} diff --git a/tests/Carina.Api.Tests/Feature/Streaming/LiveWireTests.cs b/tests/Carina.Api.Tests/Feature/Streaming/LiveWireTests.cs new file mode 100644 index 000000000..f5e799bc7 --- /dev/null +++ b/tests/Carina.Api.Tests/Feature/Streaming/LiveWireTests.cs @@ -0,0 +1,1616 @@ +using System.Net; +using System.Net.WebSockets; +using System.Text.Json; + +using Carina.Api.Events; +using Carina.Api.Live; +using Carina.Api.Tests.FeatureTest; +using Carina.Domain.Base; +using Carina.Domain.Channels; +using Carina.Domain.Driver; +using Carina.Domain.Programmes; +using Carina.Domain.Recordings; +using Carina.Domain.Streaming; +using Carina.Infrastructure.Streaming; +using Carina.TestSupport; + +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using Microsoft.Net.Http.Headers; + +using Puppis.Contracts; + +using SessionId = Puppis.Contracts.SessionId; + +namespace Carina.Api.Tests.Feature.Streaming; + +[Trait("Category", "Feature")] +public sealed class LiveWireTests +{ + private static readonly Uri Wire = new(LiveWire.Path, UriKind.Relative); + + private static readonly Uri Handshake = new("ws://localhost" + LiveWire.Path + "?network=32736&service=1024&profile=720p30"); + + private static readonly byte[] Picture = [0x0a, 0x0b, 0x0c]; + + private static readonly LiveSessionKey EveryFrame = new(new NetworkId(32736), new ServiceId(1024), LiveProfile.Hd30); + + private static readonly TimeSpan Linger = TimeSpan.FromMilliseconds(400); + + private static readonly TuningParameters Channel27 = TuningParameters.Terrestrial(27); + + private static readonly Uri Events = new(AppEventStream.Path, UriKind.Relative); + + private static readonly DateTime At = new(2026, 9, 3, 0, 0, 0, DateTimeKind.Utc); + + private readonly PipedSupply supply = new(); + + private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); + + private readonly HeldTranscoders transcoders; + + private readonly ScriptedDriverClient driver = new(); + + public LiveWireTests() + { + transcoders = new HeldTranscoders(budget); + driver.Script(Channel27, new ChannelScript { Paced = () => PacedStream.InChunksOf(new byte[188 * 16], 188) }); + } + + [Fact] + public async Task TheWireIsRefusedToACallerCarryingNoCookie() + { + await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); + + using HttpResponseMessage response = await probe.Client.GetAsync( + Wire, + HttpCompletionOption.ResponseHeadersRead); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Empty(await response.Content.ReadAsByteArrayAsync()); + } + + [Fact] + public async Task AHandshakeCarryingNoCookieIsRefusedBeforeItBecomesAWebSocket() + { + await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); + + InvalidOperationException refused = await Assert.ThrowsAsync( + () => probe.Wired.Server.CreateWebSocketClient().ConnectAsync(Handshake, Patiently())); + + Assert.Contains("401", refused.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AHandshakeCarryingARevokedSessionIsRefusedTheSameWay() + { + await using AuthProbe probe = AuthProbe.OverHttp(); + string cookie = await probe.SignedInCookieAsync(); + + probe.Sessions.Sessions[^1].Revoke(DateTime.UtcNow); + + InvalidOperationException refused = await Assert.ThrowsAsync( + () => Carrying(probe, cookie).ConnectAsync(Handshake, Patiently())); + + Assert.Contains("401", refused.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task AskingForTheWireWithoutAskingToUpgradeIsRefused() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + + await probe.SignedInAsync(); + + using HttpResponseMessage response = await probe.Client.GetAsync(Wire); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Theory] + [InlineData("http://elsewhere.invalid")] + [InlineData("null")] + public async Task AHandshakeNamingAnotherOriginIsRefused(string origin) + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + WebSocketClient client = Carrying(probe, cookie); + + client.ConfigureRequest += request => request.Headers[HeaderNames.Origin] = origin; + + InvalidOperationException refused = await Assert.ThrowsAsync( + () => client.ConnectAsync(Handshake, Patiently())); + + Assert.Contains("403", refused.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("")] + [InlineData("?network=32736&service=1024")] + [InlineData("?network=32736&service=1024&profile=hls")] + [InlineData("?network=32736&service=1024&profile=720P30")] + [InlineData("?network=thirty&service=1024&profile=720p30")] + [InlineData("?network=32736&service=1024&profile=720p30&format=hevc")] + [InlineData("?network=32736&service=1024&profile=720p30&format=h264&format=h265")] + public async Task AHandshakeNamingNoKeyOrAProfileOffTheListIsRefusedBeforeItBecomesAWebSocket(string query) + { + HeldLiveSource held = new(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + InvalidOperationException refused = await Assert.ThrowsAsync( + () => Carrying(probe, cookie).ConnectAsync(new Uri("ws://localhost" + LiveWire.Path + query), Patiently())); + + Assert.Contains("400", refused.Message, StringComparison.Ordinal); + Assert.Empty(Seating(probe).Asked); + } + + [Theory(DisplayName = "a handshake asking for a format this machine does not transcode in is refused before it becomes a WebSocket, and no tuner is asked for")] + [InlineData("h265")] + [InlineData("av1")] + public async Task AHandshakeAskingForAFormatThisMachineDoesNotTranscodeInIsRefused(string format) + { + HeldLiveSource held = new(); + await using AuthProbe probe = Wiring(held, formats: [VideoCodec.H264]); + string cookie = await probe.SignedInCookieAsync(); + + InvalidOperationException refused = await Assert.ThrowsAsync( + () => Carrying(probe, cookie).ConnectAsync( + new Uri("ws://localhost" + LiveWire.Path + "?network=32736&service=1024&profile=720p30&format=" + format), + Patiently())); + + Assert.Contains("400", refused.Message, StringComparison.Ordinal); + Assert.Empty(Seating(probe).Asked); + Assert.Empty(Seating(probe).Reached); + } + + [Theory(DisplayName = "a handshake asking for a format this machine transcodes in is seated on a key in that format")] + [InlineData("h265", VideoCodec.H265)] + [InlineData("av1", VideoCodec.Av1)] + public async Task AHandshakeAskingForAFormatThisMachineTranscodesInIsSeatedOnAKeyInThatFormat(string named, VideoCodec format) + { + HeldLiveSource held = new(); + await using AuthProbe probe = Wiring(held, formats: VideoCodecs.InOrder); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync( + new Uri("ws://localhost" + LiveWire.Path + "?network=32736&service=1024&profile=720p30&format=" + named), + Patiently()); + + LiveSessionKey asked = Assert.Single(Seating(probe).Asked); + + Assert.Equal(format, asked.Format); + Assert.Equal(LiveProfile.Hd30, asked.Profile); + } + + [Fact(DisplayName = "a handshake naming no format is seated on a key in H.264, as every wire was")] + public async Task AHandshakeNamingNoFormatIsSeatedOnAKeyInH264() + { + HeldLiveSource held = new(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + Assert.Equal(VideoCodec.H264, Assert.Single(Seating(probe).Asked).Format); + } + + [Fact] + public async Task TheHeaderAndThePicturesArriveInTheOrderTheSourcePutThemIn() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + held.Send(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Picture)); + held.Send(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); + held.Send(new LiveFrame(LiveChannel.Sound, LivePts.Of(180_000UL), Picture)); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(Handshake, Patiently()); + + LiveFrame first = await Take(socket); + LiveFrame second = await Take(socket); + LiveFrame third = await Take(socket); + + Assert.Equal(LiveChannel.PictureHeader, first.Channel); + Assert.Equal(LivePts.Start, first.Pts); + Assert.Equal(LiveChannel.Picture, second.Channel); + Assert.Equal(LivePts.Of(90_000UL), second.Pts); + Assert.Equal(LiveChannel.Sound, third.Channel); + Assert.Equal(Picture, third.Payload.ToArray()); + } + + [Fact] + public async Task AWireThatIsAlreadyOpenKeepsCarryingFramesAfterItsSessionIsEnded() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(Handshake, Patiently()); + + probe.Sessions.Sessions[^1].Revoke(DateTime.UtcNow); + + held.Send(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); + + LiveFrame carried = await Take(socket); + + Assert.Equal(LiveChannel.Picture, carried.Channel); + Assert.Equal(Picture, carried.Payload.ToArray()); + } + + [Fact] + public async Task APingArrivesOnAWireThatIsCarryingNothing() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held, new LiveWireSettings(betweenPings: TimeSpan.FromMilliseconds(50))); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(Handshake, Patiently()); + + LiveFrame ping = await Take(socket); + + Assert.Equal(LiveChannel.Control, ping.Channel); + Assert.Equal([(byte)LiveControl.Ping], ping.Payload.ToArray()); + } + + [Fact] + public async Task AViewerSayingItIsLeavingIsClosedNormallyAndLetGoOf() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(Handshake, Patiently()); + + await Say(socket, LiveControl.Leaving); + + WebSocketReceiveResult ending = await Heard(socket); + + Assert.Equal(WebSocketMessageType.Close, ending.MessageType); + + Assert.Equal(WebSocketCloseStatus.NormalClosure, ending.CloseStatus); + Assert.Equal(LiveDepartures.Because(LiveDeparture.ViewerLeft), ending.CloseStatusDescription); + await Until(() => held.LetGo); + } + + [Fact] + public async Task AViewerSayingSomethingTheWireDoesNotUnderstandIsToldWhyItIsClosed() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(Handshake, Patiently()); + + await socket.SendAsync( + "seek 42"u8.ToArray(), + WebSocketMessageType.Text, + true, + Patiently()); + + WebSocketReceiveResult ending = await Heard(socket); + + Assert.Equal(WebSocketMessageType.Close, ending.MessageType); + + Assert.Equal(WebSocketCloseStatus.InvalidPayloadData, ending.CloseStatus); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SaidSomethingUnknown), ending.CloseStatusDescription); + } + + [Fact] + public async Task TheSourceRunningOutClosesTheWireAndSaysSo() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(Handshake, Patiently()); + + held.NoMore(); + + LiveFrame said = await Take(socket); + + Assert.Equal(LiveChannel.Control, said.Channel); + Assert.Equal( + LiveDepartures.Ending(LiveDeparture.SourceEnded), + LiveEndingReport.Read(said.Payload.Span).Report!.Why); + + WebSocketReceiveResult ending = await Heard(socket); + + Assert.Equal(WebSocketMessageType.Close, ending.MessageType); + + Assert.Equal(WebSocketCloseStatus.NormalClosure, ending.CloseStatus); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), ending.CloseStatusDescription); + } + + [Fact] + public async Task AViewerJoiningAFanoutLateIsHandedTheHeaderBeforeTheNextPicture() + { + LiveFanout fanout = new(new LiveFanoutSettings()); + await using AuthProbe probe = Wiring(fanout); + string cookie = await probe.SignedInCookieAsync(); + + fanout.Publish(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Picture)); + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(Handshake, Patiently()); + + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(180_000UL), Picture)); + + LiveFrame first = await Take(socket); + LiveFrame second = await Take(socket); + + Assert.Equal(LiveChannel.PictureHeader, first.Channel); + Assert.Equal(LiveChannel.Picture, second.Channel); + Assert.Equal(LivePts.Of(180_000UL), second.Pts); + Assert.Equal(1, fanout.Viewers); + } + + [Fact] + public async Task TwoWiresOnOneFanoutAreBothCarriedAndBothClosedWhenItEnds() + { + LiveFanout fanout = new(new LiveFanoutSettings()); + await using AuthProbe probe = Wiring(fanout); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket one = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + using WebSocket another = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); + + Assert.Equal(LivePts.Of(90_000UL), (await Take(one)).Pts); + Assert.Equal(LivePts.Of(90_000UL), (await Take(another)).Pts); + + fanout.End(); + + Assert.Equal(LiveChannel.Control, (await Take(one)).Channel); + Assert.Equal(LiveChannel.Control, (await Take(another)).Channel); + + WebSocketReceiveResult oneEnding = await Heard(one); + WebSocketReceiveResult anotherEnding = await Heard(another); + + Assert.Equal(WebSocketCloseStatus.NormalClosure, oneEnding.CloseStatus); + Assert.Equal(WebSocketCloseStatus.NormalClosure, anotherEnding.CloseStatus); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), oneEnding.CloseStatusDescription); + await Until(() => fanout.Viewers is 0); + } + + [Fact] + public async Task AWireOnAFanoutThatHasEndedIsToldSoOnTheControlChannelAndClosed() + { + LiveFanout fanout = new(new LiveFanoutSettings()); + await using AuthProbe probe = Wiring(fanout); + string cookie = await probe.SignedInCookieAsync(); + + fanout.End(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + LiveFrame said = await Take(socket); + + Assert.Equal(LiveChannel.Control, said.Channel); + + LiveRefusalReading read = LiveRefusalReport.Read(said.Payload.Span); + + Assert.Null(read.Fault); + Assert.Equal(LiveRefusal.TranscoderWouldNotStart, read.Report!.Refusal); + + WebSocketReceiveResult ending = await Heard(socket); + + Assert.Equal(WebSocketMessageType.Close, ending.MessageType); + Assert.Equal(WebSocketCloseStatus.InternalServerError, ending.CloseStatus); + Assert.Equal(LiveRefusalClosures.Because(LiveRefusal.TranscoderWouldNotStart), ending.CloseStatusDescription); + } + + [Fact] + public async Task TheKeyInTheHandshakeIsTheKeyThatIsJoined() + { + HeldLiveSource held = new(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + Assert.Equal( + [new LiveSessionKey(new NetworkId(32736), new ServiceId(1024), LiveProfile.Hd30)], + Seating(probe).Asked); + } + + [Fact] + public async Task TheChannelInTheHandshakeIsReachedForUntilItsSessionIsJoined() + { + HeldLiveSource held = new(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + Assert.Equal([new LiveChannelKey(new NetworkId(32736), new ServiceId(1024))], Seating(probe).Reached); + Assert.True(Seating(probe).ReachHeldWhileJoining); + Assert.Equal(1, Seating(probe).ReachesLetGo); + } + + [Fact] + public async Task TheChannelIsAlreadyBeingReachedForWhenTheSoundOnAirIsLookedUp() + { + SeatingAt seating = new(new HeldLiveSource()); + SoundAskedWhileReaching sound = new(() => seating.HoldsAReach); + await using AuthProbe probe = AuthProbe.OverHttp(services => + { + services.AddSingleton(seating); + services.AddSingleton(sound); + }); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + Assert.Equal(1, sound.Asked); + Assert.True(sound.AskedWhileReaching); + } + + [Fact] + public async Task AWireThatAViewerLeftIsCountedAsTheViewerLeaving() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + Assert.Equal(0L, Everything(probe)); + + await Say(socket, LiveControl.Leaving); + await Heard(socket); + await Until(() => Counted(probe, LiveDeparture.ViewerLeft) is 1L); + + Assert.Equal(1L, Everything(probe)); + } + + [Fact] + public async Task AWireEndedByWhatTheViewerSaidIsCountedUnderThatAndNotUnderLeaving() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + await socket.SendAsync("seek 42"u8.ToArray(), WebSocketMessageType.Text, true, Patiently()); + await Heard(socket); + await Until(() => Counted(probe, LiveDeparture.SaidSomethingUnknown) is 1L); + + Assert.Equal(0L, Counted(probe, LiveDeparture.ViewerLeft)); + } + + [Fact] + public async Task AWireEndedBecauseTheSourceRanOutIsCountedAsTheSourceEnding() + { + var held = new HeldLiveSource(); + await using AuthProbe probe = Wiring(held); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + held.NoMore(); + + await Take(socket); + await Heard(socket); + await Until(() => Counted(probe, LiveDeparture.SourceEnded) is 1L); + + Assert.Equal(1L, Everything(probe)); + } + + [Fact] + public async Task AWireThatWasNeverSeatedIsNotCountedAsHavingEnded() + { + LiveFanout fanout = new(new LiveFanoutSettings()); + await using AuthProbe probe = Wiring(fanout); + string cookie = await probe.SignedInCookieAsync(); + + fanout.End(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + await Take(socket); + await Heard(socket); + await Stays(() => Everything(probe) is 0L); + } + + [Fact] + public async Task TwoWiresAskingForOneKeyAreCarriedByOneTranscoderAndSeeTheSamePicture() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket one = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + using WebSocket another = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + Assert.Equal(1, transcoders.Started); + Assert.Equal(1, budget.Running); + + await transcoders.Raised[0].WriteAsync(Fmp4.Header); + await transcoders.Raised[0].WriteAsync(Fmp4.Fragment(1_000)); + + LiveFrame[] toOne = [await TakePictureHeader(one), await TakePastProgress(one)]; + LiveFrame[] toAnother = [await TakePictureHeader(another), await TakePastProgress(another)]; + + Assert.Equal([LiveChannel.PictureHeader, LiveChannel.Picture], toOne.Select(frame => frame.Channel)); + Assert.Equal(toOne.Select(frame => frame.Channel), toAnother.Select(frame => frame.Channel)); + Assert.Equal( + toOne.Select(frame => frame.Payload.ToArray()), + toAnother.Select(frame => frame.Payload.ToArray())); + Assert.Equal(2, Sessions(probe).Viewers(EveryFrame)); + } + + [Fact] + public async Task AWireAskingForAnotherProfileOfTheSameChannelRaisesASecondTranscoder() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket frames = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + using WebSocket fields = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p60"), Patiently()); + + Assert.Equal(2, transcoders.Started); + Assert.Equal(2, budget.Running); + Assert.Equal([LiveProfile.Hd30, LiveProfile.Hd60], transcoders.Raised.Select(raised => raised.Profile)); + } + + [Fact] + public async Task AWireOnASessionStillStartingIsFirstToldHowFarItHasGot() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + LiveFrame progress = await TakeAFrame(socket); + + Assert.Equal(LiveChannel.Control, progress.Channel); + + LiveStartupReading read = LiveStartup.ReadProgress(progress.Payload.Span); + + Assert.Null(read.Fault); + Assert.True(read.Startup!.Reached(LiveStartupSegment.TranscoderStarted)); + Assert.False(read.Startup.Reached(LiveStartupSegment.InitReached)); + Assert.True(read.Startup.Reached(LiveStartupSegment.TunerSecured)); + Assert.False(read.Startup.Reached(LiveStartupSegment.ChannelLocked)); + + await transcoders.Raised[0].WriteAsync(Fmp4.Header); + await transcoders.Raised[0].WriteAsync(Fmp4.Fragment(1_000)); + + Assert.Equal(LiveChannel.PictureHeader, (await TakePictureHeader(socket)).Channel); + Assert.Equal(LiveChannel.Picture, (await TakePastProgress(socket)).Channel); + } + + [Fact] + public async Task AWireIsToldEachStepOfTheStartupAsItIsReached() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + LiveStartup atTheHandshake = await NextProgress(socket); + + Assert.True(atTheHandshake.Reached(LiveStartupSegment.TranscoderStarted)); + Assert.False(atTheHandshake.Reached(LiveStartupSegment.ChannelLocked)); + + await supply.Opened[0].WriteAsync(new byte[1_000]); + + LiveStartup locked = await NextProgress(socket); + + Assert.True(locked.Reached(LiveStartupSegment.ChannelLocked)); + Assert.False(locked.Reached(LiveStartupSegment.InitReached)); + + await transcoders.Raised[0].WriteAsync(Fmp4.Header); + + LiveStartup init = await NextProgress(socket); + + Assert.True(init.Reached(LiveStartupSegment.InitReached)); + Assert.False(init.Reached(LiveStartupSegment.FirstPicture)); + + await transcoders.Raised[0].WriteAsync(Fmp4.Fragment(1_000)); + + LiveStartup done = await NextProgress(socket); + + Assert.True(done.Reached(LiveStartupSegment.FirstPicture)); + Assert.False(done.InProgress); + Assert.All(done.Timeline, mark => Assert.True(mark.Took >= TimeSpan.Zero)); + } + + [Fact] + public async Task AWireJoiningASessionPastItsStartupIsHandedTheHeaderFirst() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket early = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + await transcoders.Raised[0].WriteAsync(Fmp4.Header); + await transcoders.Raised[0].WriteAsync(Fmp4.Fragment(1_000)); + await Eventually.Happens( + () => Sessions(probe).Startup(EveryFrame)?.Current is { InProgress: false }, + "the first picture ends the startup"); + + using WebSocket late = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + Assert.Equal(LiveChannel.PictureHeader, (await TakeAFrame(late)).Channel); + } + + [Fact] + public async Task AWireLeavingIsForgottenByTheSession() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket staying = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + using WebSocket leaving = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + await leaving.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); + + await Eventually.Happens(() => Sessions(probe).Viewers(EveryFrame) is 1, "the session counts one viewer fewer"); + + Assert.Equal(1, budget.Running); + } + + [Fact] + public async Task WhyTheSupplyEndedReachesTheWireOnTheControlChannelBeforeItIsClosed() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + Assert.Equal(LiveChannel.Control, (await TakeAFrame(socket)).Channel); + + supply.Opened[0].Ending = LiveSupplyEnding.Of(LiveSupplyEnd.TakenForARecording, "a recording outranked it."); + supply.Opened[0].NoMore(); + + await Eventually.Happens(() => supply.Opened[0].Disposed, "the reading of the supply has taken in why it ended"); + + await transcoders.Raised[0].WriteAsync(Fmp4.Header); + transcoders.Raised[0].NoMore(); + + (IReadOnlyList heard, WebSocketReceiveResult ending) = await UntilItIsClosed(socket); + + Assert.Contains(LiveChannel.PictureHeader, heard.Select(frame => frame.Channel)); + + LiveEndingReport said = Assert.Single( + heard.Where(frame => frame.Channel is LiveChannel.Control) + .Select(frame => LiveEndingReport.Read(frame.Payload.Span)) + .Where(read => read.Fault is null) + .Select(read => read.Report!)); + + Assert.Equal(LiveSupplyEnd.TakenForARecording, said.Why); + Assert.Equal(WebSocketMessageType.Close, ending.MessageType); + Assert.Equal(WebSocketCloseStatus.NormalClosure, ending.CloseStatus); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), ending.CloseStatusDescription); + } + + [Fact] + public async Task WhyItEndedReachesTheWireWhenTheTranscoderEndsBeforeTheSupplyEverDoes() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + Assert.Equal(LiveChannel.Control, (await TakeAFrame(socket)).Channel); + + await transcoders.Raised[0].WriteAsync(Fmp4.Header); + transcoders.Raised[0].NoMore(); + + (IReadOnlyList heard, WebSocketReceiveResult ending) = await UntilItIsClosed(socket); + + Assert.Contains(LiveChannel.PictureHeader, heard.Select(frame => frame.Channel)); + + LiveEndingReport said = Assert.Single( + heard.Where(frame => frame.Channel is LiveChannel.Control) + .Select(frame => LiveEndingReport.Read(frame.Payload.Span)) + .Where(read => read.Fault is null) + .Select(read => read.Report!)); + + Assert.Null(supply.Opened[0].Ending); + Assert.Equal(LiveSupplyEnd.LetGo, said.Why); + Assert.Equal(WebSocketMessageType.Close, ending.MessageType); + Assert.Equal(WebSocketCloseStatus.NormalClosure, ending.CloseStatus); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), ending.CloseStatusDescription); + } + + [Fact] + public async Task AWireNamingAProfileOffTheListIsRefusedBeforeAnythingIsRaised() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + InvalidOperationException refused = await Assert.ThrowsAsync( + () => Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "hls"), Patiently())); + + Assert.Contains("400", refused.Message, StringComparison.Ordinal); + Assert.Equal(0, supply.Asked); + Assert.Equal(0, transcoders.Started); + } + + [Fact] + public async Task AWireIsToldOnTheControlChannelThatTheDriverCannotBeReachedAndIsClosed() + { + TuningByServiceId tuning = new(); + + tuning.Answer(1024, TuningParameters.Terrestrial(27)); + + await using AuthProbe probe = AuthProbe.OverHttp(services => + services.AddSingleton(tuning)); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + LiveRefusalReport report = await Refused(socket); + + Assert.Equal(LiveRefusal.DriverUnavailable, report.Refusal); + Assert.Null(report.Ceiling); + + WebSocketReceiveResult ending = await Heard(socket); + + Assert.Equal(WebSocketMessageType.Close, ending.MessageType); + Assert.Equal(WebSocketCloseStatus.InternalServerError, ending.CloseStatus); + Assert.Equal(LiveRefusalClosures.Because(LiveRefusal.DriverUnavailable), ending.CloseStatusDescription); + } + + [Theory] + [InlineData(LiveRefusal.NoSuchChannel, WebSocketCloseStatus.InvalidPayloadData)] + [InlineData(LiveRefusal.NoTunerFree, WebSocketCloseStatus.PolicyViolation)] + [InlineData(LiveRefusal.WouldNotTune, WebSocketCloseStatus.InternalServerError)] + public async Task WhatTheSupplyRefusesForReachesTheViewerAsThatReason(LiveRefusal why, WebSocketCloseStatus closed) + { + supply.Refusing = why; + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + LiveRefusalReport report = await Refused(socket); + + Assert.Equal(why, report.Refusal); + Assert.Null(report.Ceiling); + + WebSocketReceiveResult ending = await Heard(socket); + + Assert.Equal(closed, ending.CloseStatus); + Assert.Equal(LiveRefusalClosures.Because(why), ending.CloseStatusDescription); + Assert.Equal(0, transcoders.Started); + } + + [Fact] + public async Task AFullBudgetReachesTheViewerWithHowFullItIs() + { + TranscodeBudget one = new(new TranscodeBudgetSettings { AtOnce = 1 }); + HeldTranscoders few = new(one); + await using AuthProbe probe = AuthProbe.OverHttp(services => + { + services.AddSingleton(supply); + services.AddSingleton(one); + services.AddSingleton(few); + }); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket seated = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + using WebSocket refused = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p60"), Patiently()); + + LiveRefusalReport report = await Refused(refused); + + Assert.Equal(LiveRefusal.TooManyAlready, report.Refusal); + Assert.Equal(new TranscodeCeiling(1, 1), report.Ceiling); + + WebSocketReceiveResult ending = await Heard(refused); + + Assert.Equal(WebSocketCloseStatus.PolicyViolation, ending.CloseStatus); + Assert.Equal(1, few.Started); + Assert.Equal(1, Sessions(probe).Viewers(EveryFrame)); + } + + [Theory(DisplayName = "BR-PD-008: a wire opened while the channel is announcing two languages on one sound is given the channel of the language asked for")] + [InlineData("", SoundChannel.Left)] + [InlineData("&sound=main", SoundChannel.Left)] + [InlineData("&sound=secondary", SoundChannel.Right)] + public async Task AWireOpenedWhileTwoLanguagesAreOnOneSoundIsGivenTheChannelOfTheLanguageAskedFor( + string asked, + SoundChannel channel) + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + probe.Programmes.Programmes.Add(OnAir(event_: 7, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(-10))); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(new Uri(HandshakeFor("32736", "1024", "720p30") + asked), Patiently()); + + Assert.Equal(SoundPlacement.OneChannelOf(0, channel), Assert.Single(transcoders.Raised).Sound); + } + + [Theory(DisplayName = "BR-PD-008: a wire opened while the channel announces two languages on its main sound beside a second stream is given a channel of the main sound, or the second stream as the third sound")] + [InlineData("", 0, SoundChannel.Left)] + [InlineData("&sound=secondary", 0, SoundChannel.Right)] + [InlineData("&sound=third", 1, null)] + public async Task AWireOpenedWhileTwoLanguagesAreOnTheMainSoundBesideASecondStreamIsGivenTheSoundAskedFor( + string asked, + int ordinal, + SoundChannel? channel) + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + probe.Programmes.Programmes.Add(OnAir(event_: 7, AudioMode.DualMono, sounds: 2, TimeSpan.FromMinutes(-10))); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(new Uri(HandshakeFor("32736", "1024", "720p30") + asked), Patiently()); + + SoundPlacement expected = channel is { } side ? SoundPlacement.OneChannelOf(ordinal, side) : SoundPlacement.WholeStream(ordinal); + + Assert.Equal(expected, Assert.Single(transcoders.Raised).Sound); + } + + [Theory(DisplayName = "BR-PD-008: a wire opened on any other broadcast is given the whole stream of the sound asked for")] + [InlineData(AudioMode.Stereo, 1, "", 0)] + [InlineData(AudioMode.Stereo, 2, "&sound=secondary", 1)] + [InlineData(AudioMode.Surround, 1, "", 0)] + public async Task AWireOpenedOnAnyOtherBroadcastIsGivenTheWholeStreamOfTheSoundAskedFor( + AudioMode audio, + int sounds, + string asked, + int ordinal) + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + probe.Programmes.Programmes.Add(OnAir(event_: 7, audio, sounds, TimeSpan.FromMinutes(-10))); + + using WebSocket socket = await Carrying(probe, cookie) + .ConnectAsync(new Uri(HandshakeFor("32736", "1024", "720p30") + asked), Patiently()); + + Assert.Equal(SoundPlacement.WholeStream(ordinal), Assert.Single(transcoders.Raised).Sound); + } + + [Fact(DisplayName = "BR-PD-008: what the channel announced before and what it will announce next do not decide how the sound on air is taken")] + public async Task WhatWasAnnouncedBeforeAndWhatComesNextDoNotDecideHowTheSoundOnAirIsTaken() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + + probe.Programmes.Programmes.Add(OnAir(event_: 6, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(-70))); + probe.Programmes.Programmes.Add(OnAir(event_: 7, AudioMode.Stereo, sounds: 1, TimeSpan.FromMinutes(-10))); + probe.Programmes.Programmes.Add(OnAir(event_: 8, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(50))); + probe.Programmes.Programmes.Add(OnAir(event_: 9, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(-10), service: 1032)); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + Assert.Equal(SoundPlacement.WholeStream(0), Assert.Single(transcoders.Raised).Sound); + } + + [Fact(DisplayName = "BR-PD-008: a wire opened after the broadcast changed how it carries its sound is not seated on the transcoder raised before it did")] + public async Task AWireOpenedAfterTheBroadcastChangedIsNotSeatedOnTheTranscoderRaisedBefore() + { + await using AuthProbe probe = WiringSessions(); + string cookie = await probe.SignedInCookieAsync(); + Programme twoLanguages = OnAir(event_: 7, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(-10)); + + probe.Programmes.Programmes.Add(twoLanguages); + + using WebSocket before = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + probe.Programmes.Programmes.Remove(twoLanguages); + probe.Programmes.Programmes.Add(OnAir(event_: 8, AudioMode.Stereo, sounds: 1, TimeSpan.FromMinutes(-1))); + + using WebSocket after = await Carrying(probe, cookie).ConnectAsync(HandshakeFor("32736", "1024", "720p30"), Patiently()); + + Assert.Equal( + [SoundPlacement.OneChannelOf(0, SoundChannel.Left), SoundPlacement.WholeStream(0)], + transcoders.Raised.Select(raised => raised.Sound)); + Assert.Equal(1, Sessions(probe).Viewers(EveryFrame)); + Assert.Equal(1, Sessions(probe).Viewers(EveryFrame.Taking(SoundPlacement.OneChannelOf(0, SoundChannel.Left)))); + } + + [Fact] + public async Task AWireThatSaysItIsLeavingHasItsSessionStoppedOnTheDriverOnceAfterTheLinger() + { + await using AuthProbe probe = WiringTheDriver(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeOn("1024"), Patiently()); + + SessionId held = await TheOneSessionHeldAsync(); + + await socket.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); + await ReadUntilClosed(socket); + + await StoppedOnceAsync(held); + } + + [Fact] + public async Task AWireClosedTheOrdinaryWayHasItsSessionStoppedOnTheDriverOnceAfterTheLinger() + { + await using AuthProbe probe = WiringTheDriver(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeOn("1024"), Patiently()); + + SessionId held = await TheOneSessionHeldAsync(); + + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "leaving", Patiently()); + await ReadUntilClosed(socket); + + await StoppedOnceAsync(held); + } + + [Fact] + public async Task AWireThatBreaksOffWithoutAWordHasItsSessionStoppedOnTheDriverOnceAfterTheLinger() + { + await using AuthProbe probe = WiringTheDriver(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(HandshakeOn("1024"), Patiently()); + + SessionId held = await TheOneSessionHeldAsync(); + + socket.Abort(); + + await StoppedOnceAsync(held); + } + + [Fact] + public async Task AWireSwitchingChannelsStopsOnlyTheSessionItLeftAndTheNewOneWhenItLeavesThatToo() + { + await using AuthProbe probe = WiringTheDriver(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket first = await Carrying(probe, cookie).ConnectAsync(HandshakeOn("1024"), Patiently()); + + SessionId before = await TheOneSessionHeldAsync(); + + using WebSocket second = await Carrying(probe, cookie).ConnectAsync(HandshakeOn("1032"), Patiently()); + + await Eventually.Happens(() => driver.Live.Count is 2, "the second channel has a session of its own on the driver"); + + SessionId after = driver.Live.Single(session => session != before); + + await first.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); + await ReadUntilClosed(first); + + await StoppedOnceAsync(before); + + Assert.Equal([after], driver.Live); + + await second.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); + await ReadUntilClosed(second); + + await Eventually.Happens(() => driver.Stopped.Count is 2, "the second session is stopped once its viewer has left"); + await Task.Delay(Linger * 3); + + Assert.Equal([before, after], driver.Stopped); + Assert.Empty(driver.Live); + } + + [Fact] + public async Task AWireBackWithinTheLingerRidesTheSameSessionAndItsLeavingAgainStopsThatSessionOnce() + { + await using AuthProbe probe = WiringTheDriver(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket gone = await Carrying(probe, cookie).ConnectAsync(HandshakeOn("1024"), Patiently()); + + SessionId held = await TheOneSessionHeldAsync(); + + await gone.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); + await ReadUntilClosed(gone); + + using WebSocket back = await Carrying(probe, cookie).ConnectAsync(HandshakeOn("1024"), Patiently()); + + Assert.Equal(LiveChannel.Control, (await TakeABinaryFrame(back)).Channel); + + await Task.Delay(Linger * 2); + + Assert.Single(driver.Started); + Assert.Empty(driver.Stopped); + Assert.Equal([held], driver.Live); + + await back.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); + await ReadUntilClosed(back); + + await StoppedOnceAsync(held); + + Assert.Single(driver.Started); + } + + [Fact] + public async Task AWireRaisingASessionIsSignalledOnTheHubAsLiveAndNothingElseIsCarried() + { + await using AuthProbe probe = WiringTheHub(); + string cookie = await probe.SignedInCookieAsync(); + + using HttpResponseMessage listening = await probe.Client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); + await using Stream body = await listening.Content.ReadAsStreamAsync(); + using StreamReader reader = new(body); + + Assert.Equal(HttpStatusCode.OK, listening.StatusCode); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + Assert.Equal([$"event: {AppEvents.Live}", "data"], await NextFrame(reader)); + } + + [Fact] + public async Task TheLastViewerLeavingIsSignalledAgainOnceTheSessionIsGone() + { + await using AuthProbe probe = WiringTheHub(); + string cookie = await probe.SignedInCookieAsync(); + + using HttpResponseMessage listening = await probe.Client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); + await using Stream body = await listening.Content.ReadAsStreamAsync(); + using StreamReader reader = new(body); + + using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + Assert.Equal([$"event: {AppEvents.Live}", "data"], await NextFrame(reader)); + + await socket.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); + + Assert.Equal([$"event: {AppEvents.Live}", "data"], await NextFrame(reader)); + await Eventually.Happens(() => budget.Running is 0, "the session is torn down once its linger is over"); + } + + [Fact] + public async Task ASecondViewerOnTheSameSessionSignalsNothing() + { + await using AuthProbe probe = WiringTheHub(); + string cookie = await probe.SignedInCookieAsync(); + + using WebSocket first = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + using HttpResponseMessage listening = await probe.Client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); + await using Stream body = await listening.Content.ReadAsStreamAsync(); + using StreamReader reader = new(body); + + using WebSocket second = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); + + Task anything = reader.ReadLineAsync(); + + Assert.NotSame(anything, await Task.WhenAny(anything, Task.Delay(TimeSpan.FromMilliseconds(500)))); + } + + [Theory] + [InlineData("wss", "https")] + [InlineData("ws", "http")] + public async Task AWireTheProxyLabelsAsAWebSocketIsOpenedForThePageThatWasServedOverTheMatchingScheme( + string forwardedProto, + string page) + { + await using ProxiedKestrelProbe probe = ProxiedKestrelProbe.ListeningOnKestrel(); + string cookie = await probe.SignedInCookieAsync(); + + using ClientWebSocket client = probe.Opening(cookie, forwardedProto, probe.PageAt(page)); + + await client.ConnectAsync(probe.Wire, Patiently()); + + Assert.Equal(WebSocketState.Open, client.State); + Assert.Equal(HttpStatusCode.SwitchingProtocols, client.HttpStatusCode); + + LiveFrame first = await TakeABinaryFrame(client); + + Assert.Equal(LiveChannel.Control, first.Channel); + Assert.Null(LiveStartup.ReadProgress(first.Payload.Span).Fault); + Assert.Equal(1, probe.Transcoders.Started); + } + + [Theory] + [InlineData("wss", "https://elsewhere.example")] + [InlineData("wss", "http")] + [InlineData("ws", "https")] + [InlineData("ftp", "http")] + public async Task AWireFromAPageThisAppDidNotServeIsStillRefusedWhateverTheProxyLabelsIt( + string forwardedProto, + string origin) + { + await using ProxiedKestrelProbe probe = ProxiedKestrelProbe.ListeningOnKestrel(); + string cookie = await probe.SignedInCookieAsync(); + string page = origin.Contains("://", StringComparison.Ordinal) ? origin : probe.PageAt(origin); + + using ClientWebSocket client = probe.Opening(cookie, forwardedProto, page); + + await Assert.ThrowsAsync(() => client.ConnectAsync(probe.Wire, Patiently())); + + Assert.Equal(HttpStatusCode.Forbidden, client.HttpStatusCode); + Assert.Equal(0, probe.Transcoders.Started); + } + + [Fact] + public async Task AViewerThatStopsReadingOverRealKestrelIsRecordedAsHavingStoppedReading() + { + var held = new HeldLiveSource(); + await using LiveKestrelHost host = await LiveKestrelHost.StartAsync( + held, + new LiveWireSettings( + betweenPings: TimeSpan.FromSeconds(30), + writePatience: TimeSpan.FromMilliseconds(300))); + + using var client = new ClientWebSocket(); + await client.ConnectAsync(host.Wire, Patiently()); + + held.Send(new LiveFrame(LiveChannel.Picture, LivePts.Start, new byte[8 * 1024 * 1024])); + + LiveDeparture departure = await host.DepartureAsync(Patiently()); + + Assert.Equal(LiveDeparture.ViewerStoppedReading, departure); + + WebSocketException cut = await Assert.ThrowsAsync(() => ReadUntilClose(client)); + + Assert.Equal(WebSocketError.ConnectionClosedPrematurely, cut.WebSocketErrorCode); + Assert.Null(client.CloseStatus); + } + + [Fact] + public async Task TheSourceRunningOutIsReadByARealClientAsACleanCloseItCanNameTheReasonOf() + { + var held = new HeldLiveSource(); + await using LiveKestrelHost host = await LiveKestrelHost.StartAsync(held); + + using var client = new ClientWebSocket(); + await client.ConnectAsync(host.Wire, Patiently()); + + held.Send(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); + held.NoMore(); + + WebSocketReceiveResult ending = await ReadUntilClose(client); + + Assert.Equal(WebSocketMessageType.Close, ending.MessageType); + Assert.Equal(WebSocketCloseStatus.NormalClosure, client.CloseStatus); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), client.CloseStatusDescription); + Assert.Equal(LiveDeparture.SourceEnded, await host.DepartureAsync(Patiently())); + Assert.Equal( + 1L, + host.Tally.Counted.Single(counted => counted.Departure == LiveDeparture.SourceEnded).Times); + Assert.NotNull( + host.Tally.Counted.Single(counted => counted.Departure == LiveDeparture.SourceEnded).Longest); + } + + [Fact] + public async Task ALiveTicketOfferedOnTheWireHandshakeIsRefusedBeforeItBecomesAWebSocket() + { + await using AuthProbe probe = WiringWithARecording(out _); + string ticket = await IssuedAsync(probe); + + WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); + + client.ConfigureRequest += request => request.Headers[HeaderNames.Authorization] = $"Bearer {ticket}"; + + InvalidOperationException refused = await Assert.ThrowsAsync( + () => client.ConnectAsync(Handshake, new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token)); + + Assert.Contains("401", refused.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task ATicketIsNotHandedToTheWire() + { + await using LiveFeature feature = new(); + + feature.Seed(1024, "Alpha", remoteControlKey: 1); + + using HttpResponseMessage ticket = await feature.AskForATicketAsync(new { networkId = 32736, serviceId = 1024 }); + using JsonDocument body = JsonDocument.Parse(await ticket.Content.ReadAsStringAsync()); + string inTheClear = body.RootElement.GetProperty("data").GetProperty("inTheClear").GetString()!; + + using HttpRequestMessage asking = new( + HttpMethod.Get, + new Uri(LiveWire.Path + "?network=32736&service=1024&profile=720p30", UriKind.Relative)); + + asking.Headers.TryAddWithoutValidation("Authorization", $"Bearer {inTheClear}"); + + using HttpResponseMessage response = await feature.Anonymous.SendAsync(asking); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + private static long Counted(AuthProbe probe, LiveDeparture departure) + => Departures(probe).Counted.Single(counted => counted.Departure == departure).Times; + + private static long Everything(AuthProbe probe) => Departures(probe).Counted.Sum(counted => counted.Times); + + private static LiveDepartureTally Departures(AuthProbe probe) + => probe.Wired.Services.GetRequiredService().Read(); + + private static CancellationToken Patiently() => new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token; + + private static AuthProbe Wiring( + ILiveWireSource source, + LiveWireSettings? settings = null, + IReadOnlyList? formats = null) + => AuthProbe.OverHttp(services => + { + services.AddSingleton(new SeatingAt(source)); + + if (settings is not null) + { + services.AddSingleton(settings); + } + + if (formats is not null) + { + services.AddSingleton(new AlreadyChosen(LiveEncoder.Vaapi, formats)); + } + }); + + private static SeatingAt Seating(AuthProbe probe) + => Assert.IsType(probe.Wired.Services.GetRequiredService()); + + private static WebSocketClient Carrying(AuthProbe probe, string cookie) + { + WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); + + client.ConfigureRequest += request => request.Headers[HeaderNames.Cookie] = cookie; + + return client; + } + + private static Task Say(WebSocket socket, LiveControl said) + => socket.SendAsync( + LiveControls.Frame(said).ToArray(), + WebSocketMessageType.Binary, + true, + Patiently()); + + private static async Task Take(WebSocket socket) + { + byte[] heard = new byte[64 * 1024]; + + WebSocketReceiveResult said = await socket.ReceiveAsync( + new ArraySegment(heard), + Patiently()); + + LiveFraming framing = LiveFrame.Read(heard.AsSpan(0, said.Count)); + + Assert.Null(framing.Fault); + + return framing.Frame!; + } + + private static async Task Stays(Func so) + { + for (int tries = 0; tries < 40; tries++) + { + Assert.True(so(), "What was to stay as it was did not."); + + await Task.Delay(25); + } + } + + private static async Task Until(Func settled) + { + for (int tries = 0; tries < 200; tries++) + { + if (settled()) + { + return; + } + + await Task.Delay(25); + } + + Assert.Fail("The wire never finished what was expected of it."); + } + + private static async Task Heard(WebSocket socket) + { + byte[] heard = new byte[64 * 1024]; + + return await socket.ReceiveAsync(new ArraySegment(heard), Patiently()); + } + + private static Programme OnAir(int event_, AudioMode audio, int sounds, TimeSpan startsIn, int service = 1024) + { + DateTime startsAt = DateTime.UtcNow + startsIn; + + return Programme.Rehydrate( + new ProgrammeId(new NetworkId(32736), new ServiceId(service), new EventId(event_)), + new TransportStreamId(32736), + startsAt, + startsAt + TimeSpan.FromHours(1), + "a programme", + string.Empty, + isShadow: false, + startsAt, + audio: audio, + sounds: sounds); + } + + private static Uri HandshakeFor(string network, string service, string profile) + => new($"ws://localhost{LiveWire.Path}?network={network}&service={service}&profile={profile}"); + + private static LiveSessionManager Sessions(AuthProbe probe) + => Assert.IsType(probe.Wired.Services.GetRequiredService()); + + private static async Task Refused(WebSocket socket) + { + LiveFrame said = await TakeAFrame(socket); + + Assert.Equal(LiveChannel.Control, said.Channel); + + LiveRefusalReading read = LiveRefusalReport.Read(said.Payload.Span); + + Assert.Null(read.Fault); + + return read.Report!; + } + + private static bool IsProgress(LiveFrame frame) + => frame.Channel is LiveChannel.Control && frame.Payload.Length == LiveStartup.PayloadLength; + + private static async Task TakePastProgress(WebSocket socket) + { + while (true) + { + LiveFrame frame = await TakeAFrame(socket); + + if (!IsProgress(frame)) + { + return frame; + } + } + } + + private static async Task TakePictureHeader(WebSocket socket) + { + LiveFrame first = await TakePastProgress(socket); + + if (first.Channel is not LiveChannel.CaptionHeader) + { + return first; + } + + LiveFrame afterTheCanvas = await TakePastProgress(socket); + + Assert.Equal(LiveChannel.PictureHeader, afterTheCanvas.Channel); + + return afterTheCanvas; + } + + private static async Task NextProgress(WebSocket socket) + { + while (true) + { + LiveFrame frame = await TakeAFrame(socket); + + if (IsProgress(frame)) + { + LiveStartupReading read = LiveStartup.ReadProgress(frame.Payload.Span); + + Assert.Null(read.Fault); + + return read.Startup!; + } + } + } + + private static async Task TakeAFrame(WebSocket socket) + { + byte[] heard = new byte[64 * 1024]; + + WebSocketReceiveResult said = await socket.ReceiveAsync(new ArraySegment(heard), Patiently()); + + Assert.True( + said.MessageType is WebSocketMessageType.Binary, + $"a frame was expected, and the wire said {said.MessageType} ({said.CloseStatusDescription})"); + + LiveFraming framing = LiveFrame.Read(heard.AsSpan(0, said.Count)); + + Assert.NotNull(framing.Frame); + + return framing.Frame; + } + + private static async Task<(IReadOnlyList Heard, WebSocketReceiveResult Ending)> UntilItIsClosed( + WebSocket socket) + { + List heard = []; + byte[] said = new byte[64 * 1024]; + + while (true) + { + WebSocketReceiveResult came = await socket.ReceiveAsync(new ArraySegment(said), Patiently()); + + if (came.MessageType is WebSocketMessageType.Close) + { + return (heard, came); + } + + LiveFraming framing = LiveFrame.Read(said.AsSpan(0, came.Count)); + + Assert.NotNull(framing.Frame); + + heard.Add(framing.Frame); + } + } + + private AuthProbe WiringSessions() + => AuthProbe.OverHttp(services => + { + services.AddSingleton(supply); + services.AddSingleton(budget); + services.AddSingleton(transcoders); + }); + + private static Uri HandshakeOn(string service) + => new($"ws://localhost{LiveWire.Path}?network=32736&service={service}&profile=720p30"); + + private static async Task TakeABinaryFrame(WebSocket socket) + { + byte[] heard = new byte[64 * 1024]; + + WebSocketReceiveResult said = await socket.ReceiveAsync(new ArraySegment(heard), Patiently()); + + Assert.Equal(WebSocketMessageType.Binary, said.MessageType); + + LiveFraming framing = LiveFrame.Read(heard.AsSpan(0, said.Count)); + + Assert.NotNull(framing.Frame); + + return framing.Frame; + } + + private static async Task ReadUntilClosed(WebSocket socket) + { + byte[] heard = new byte[64 * 1024]; + + try + { + while ((await socket.ReceiveAsync(new ArraySegment(heard), Patiently())).MessageType is not WebSocketMessageType.Close) + { + } + } + catch (WebSocketException) + { + } + } + + private async Task TheOneSessionHeldAsync() + { + await Eventually.Happens(() => driver.Live.Count is 1, "the driver holds one live session for the wire"); + + Assert.Equal([SessionPurpose.Live], driver.Purposes); + + return driver.Live.Single(); + } + + private async Task StoppedOnceAsync(SessionId held) + { + await Eventually.Happens(() => driver.Stopped.Count >= 1, "the session is stopped on the driver once the linger is over"); + await Task.Delay(Linger * 3); + + Assert.Equal([held], driver.Stopped); + Assert.DoesNotContain(held, driver.Live); + } + + private AuthProbe WiringTheDriver() + => AuthProbe.OverHttp(services => + { + services.RemoveAll(); + services.AddSingleton(driver); + services.AddSingleton(new ResolvedTuning( + TuningResolution.Tunable(new CandidateChannelId(Guid.NewGuid()), Channel27, impaired: false))); + services.AddSingleton(new LiveSessionSettings(linger: Linger)); + services.AddSingleton(budget); + services.AddSingleton(transcoders); + }); + + private static async Task NextFrame(StreamReader reader) + { + List frame = []; + + while (true) + { + string? line = await reader.ReadLineAsync().WaitAsync(Eventually.Patience); + + Assert.NotNull(line); + + if (line.Length > 0 && line[0] is ':') + { + continue; + } + + if (line.Length is 0) + { + if (frame.Count > 0) + { + return [.. frame]; + } + + continue; + } + + frame.Add(line); + } + } + + private AuthProbe WiringTheHub() + => AuthProbe.OverHttp(services => + { + services.AddSingleton(supply); + services.AddSingleton(budget); + services.AddSingleton(new HeldTranscoders(budget)); + services.AddSingleton(new LiveSessionSettings(linger: TimeSpan.FromMilliseconds(100))); + }); + + private static async Task ReadUntilClose(ClientWebSocket client) + { + byte[] heard = new byte[64 * 1024]; + + while (true) + { + WebSocketReceiveResult said = await client.ReceiveAsync(new ArraySegment(heard), Patiently()); + + if (said.MessageType is WebSocketMessageType.Close) + { + return said; + } + } + } + + private static async Task IssuedAsync(AuthProbe probe) + { + await probe.SignedInAsync(); + + using HttpResponseMessage answer = await probe.Client.PostAsJsonAsync( + new Uri("/api/live/ticket", UriKind.Relative), + new { networkId = 32736, serviceId = 1024 }); + + Assert.Equal(HttpStatusCode.OK, answer.StatusCode); + + using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); + + return read.RootElement.GetProperty("data").GetProperty("inTheClear").GetString()!; + } + + private AuthProbe WiringWithARecording(out Recording recording) + { + HeldServices services = new(); + HeldCandidates candidates = new(); + HeldRecordings recordings = new(); + NetworkId network = new(32736); + ServiceId service = new(1024); + CandidateChannel candidate = CandidateChannel.Discover( + CandidateChannelId.New(), + network, + service, + TuningParameters.Terrestrial(27), + At); + + candidate.Select(SelectionSource.Manual, null, At); + services.Services.Add(BroadcastService.Discover(network, service, "Watched", ServiceCategory.Television, At)); + candidates.Candidates.Add(candidate); + + recording = RecordingFeature.Begin(RecordingId.New()); + recording.Wrote(TimeSpan.FromMinutes(30)); + recording.Abort(RecordingFeature.Noon.AddMinutes(30)); + recording.Settle(RecordingOutcome.Complete, 4_000, RecordingFeature.Noon.AddMinutes(30)); + recordings.Recordings.Add(recording); + + return AuthProbe.OverHttp(wired => + { + wired.AddSingleton(services); + wired.AddSingleton(candidates); + wired.AddSingleton(recordings); + wired.AddSingleton(supply); + }); + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/ArtefactCodecInThePlanTests.cs b/tests/Carina.Api.Tests/FeatureTest/ArtefactCodecInThePlanTests.cs deleted file mode 100644 index b3fcfd040..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/ArtefactCodecInThePlanTests.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Text.Json; - -using Carina.Domain.Encodings; -using Carina.Domain.Recordings; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class ArtefactCodecInThePlanTests -{ - [Theory(DisplayName = "BR-PD-009: the plan names the codec the artefact's file was read as, whatever its profile says now")] - [InlineData(EncodeCodec.H264, EncodeCodec.H264, "h264")] - [InlineData(EncodeCodec.H265, EncodeCodec.H264, "h264")] - [InlineData(EncodeCodec.H265, EncodeCodec.H265, "h265")] - [InlineData(EncodeCodec.H264, EncodeCodec.H265, "h265")] - public async Task ThePlanNamesTheCodecTheArtefactsFileWasReadAs(EncodeCodec profile, EncodeCodec file, string named) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, profile, fileReadAs: file, taggedAs: "hvc1"); - - JsonElement read = await PlanAsync(feature, recording); - - Assert.Equal(named, read.GetProperty("artefactFile").GetProperty("codec").GetString()); - } - - [Fact(DisplayName = "BR-PD-009: an artefact in H.265 a browser cannot play is still named, while the recording is transcoded")] - public async Task AnArtefactInH265ABrowserCannotPlayIsStillNamed() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1"); - - JsonElement read = await PlanAsync(feature, recording); - - Assert.True(read.GetProperty("transcodes").GetBoolean()); - Assert.Equal("h265", read.GetProperty("artefactFile").GetProperty("codec").GetString()); - } - - [Fact(DisplayName = "BR-PD-009: the artefact is named when the recording itself is asked for")] - public async Task TheArtefactIsNamedWhenTheRecordingItselfIsAskedFor() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H264, fileReadAs: EncodeCodec.H264); - - JsonElement read = await PlanAsync(feature, recording, "?source=recording"); - - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal("h264", read.GetProperty("artefactFile").GetProperty("codec").GetString()); - } - - [Fact(DisplayName = "BR-PD-009: an artefact whose file could not be read is named by no codec rather than by its profile")] - public async Task AnArtefactWhoseFileCouldNotBeReadIsNamedByNoCodec() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H264); - - JsonElement read = await PlanAsync(feature, recording); - - Assert.Equal(JsonValueKind.Null, read.GetProperty("artefactFile").ValueKind); - } - - [Fact(DisplayName = "BR-PD-009: a recording with no artefact is named by no codec")] - public async Task ARecordingWithNoArtefactIsNamedByNoCodec() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - JsonElement read = await PlanAsync(feature, recording); - - Assert.Equal(JsonValueKind.Null, read.GetProperty("artefactFile").ValueKind); - } - - private static async Task PlanAsync(PlayFeature feature, Recording recording, string query = "") - { - using HttpResponseMessage plan = await feature.PlanAsync(recording, query); - - return (await PlayFeature.PlanOfAsync(plan)).GetProperty("data"); - } -} diff --git a/tests/Carina.Api.Tests/FeatureTest/CaptionFeature.cs b/tests/Carina.Api.Tests/FeatureTest/CaptionFeature.cs new file mode 100644 index 000000000..2df1d0d8e --- /dev/null +++ b/tests/Carina.Api.Tests/FeatureTest/CaptionFeature.cs @@ -0,0 +1,194 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; + +using Carina.Domain.Captions; +using Carina.Domain.Encodings; +using Carina.Domain.Integrity; +using Carina.Domain.Playback; +using Carina.Domain.Recordings; +using Carina.Domain.Streaming; +using Carina.Domain.Viewing; +using Carina.Infrastructure.Captions; +using Carina.TestSupport; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; + +using IRecordingDetectionRepository = Carina.Domain.Segments.IRecordingDetectionRepository; +using ISegmentModelVersionRepository = Carina.Domain.Segments.ISegmentModelVersionRepository; +using ISegmentSettingsRepository = Carina.Domain.Segments.ISegmentSettingsRepository; + +namespace Carina.Api.Tests.FeatureTest; + +internal sealed class CaptionFeature : IAsyncDisposable +{ + public static readonly OutputRoot Root = new("bulk"); + + public static readonly TimeSpan FileBegins = TimeSpan.FromSeconds(6115.5); + + private const long Second = CaptionCue.Hertz; + + private readonly TestingWebApplicationFactory factory = new(); + + private readonly DirectoryInfo mounted = Directory.CreateTempSubdirectory("carina-captions-mounted-"); + + private readonly DirectoryInfo encoded = Directory.CreateTempSubdirectory("carina-captions-encoded-"); + + private readonly DirectoryInfo shelved = Directory.CreateTempSubdirectory("carina-captions-shelf-"); + + public CaptionFeature(bool anywhereToKeepThem = true) + { + Settings = new CaptionSettings { WrittenTo = anywhereToKeepThem ? shelved.FullName : null }; + + WebApplicationFactory configured = factory + .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => + { + services.RemoveAll(); + services.RemoveAll(); + services.AddSingleton(Recordings); + services.AddSingleton(Settings); + services.AddSingleton(new IntegritySettings + { + OutputRoots = [new StorageRootPath(Root, mounted.FullName)], + }); + services.AddSingleton(new EncodeSettings + { + OutputRoots = [new StorageRootPath(EncodedArtefact.Shelf, encoded.FullName)], + }); + services.AddSingleton(Jobs); + services.AddSingleton(Profiles); + services.RemoveAll(); + services.AddSingleton(Codecs); + services.RemoveAll(); + services.AddSingleton(new HeldOnTheFlyPlayer()); + services.RemoveAll(); + services.AddSingleton(new HeldEncodeChapters()); + services.AddSingleton(new HeldPlaybackPositions()); + services.AddSingleton(new HeldSegmentSettings()); + services.AddSingleton(new HeldSegmentModelVersions()); + services.AddSingleton(new HeldRecordingDetections()); + })); + + Client = configured.WithTestScheme().CreateClient(); + Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( + TestAuthenticationHandler.SchemeName, + "anything"); + Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + Stranger = configured.WithTestScheme().CreateClient(); + } + + public CaptionSettings Settings { get; } + + public HttpClient Client { get; } + + public HttpClient Stranger { get; } + + public HeldRecordings Recordings { get; } = new(); + + public HeldEncodeJobs Jobs { get; } = new(); + + public HeldEncodeProfiles Profiles { get; } = new(); + + public HeldArtefactCodecs Codecs { get; } = new(); + + public static CaptionRecord Record(TimeSpan? begins = null) + => new( + 1440, + 1080, + begins ?? FileBegins, + [ + new CaptionCue(At(6115.7), Picture(10)), + new CaptionCue(At(6120.5), Picture(20)), + new CaptionCue(At(6123.5), null), + new CaptionCue(At(6800), Picture(30)), + ]); + + public Recording Ended(bool scrambled = false) + { + Recording recording = RecordingFeature.Begin(RecordingId.New()); + recording.Wrote(TimeSpan.FromMinutes(30)); + recording.Abort(RecordingFeature.Noon.AddMinutes(30)); + + if (scrambled) + { + recording.Note(new OutcomeDetail(RecordingFault.ScramblingUnresolved, null, string.Empty, RecordingFeature.Noon.AddMinutes(30))); + } + + recording.Settle(scrambled ? RecordingOutcome.Truncated : RecordingOutcome.Complete, 4_000, RecordingFeature.Noon.AddMinutes(30)); + Recordings.Recordings.Add(recording); + File.WriteAllBytes(Path.Combine(mounted.FullName, recording.FileName.Value), new byte[4_000]); + + return recording; + } + + public async Task CaptionedAsync(CaptionRecord? record = null, bool onTheShelf = true) + { + Recording recording = Ended(); + recording.Caption(CaptionState.Ready, 3, RecordingFeature.Noon.AddHours(1)); + + if (onTheShelf) + { + await new CaptionShelf(Settings).KeepAsync(recording.Id, record ?? Record(), CancellationToken.None); + } + + return recording; + } + + public void Encoded(Recording recording, EncodeTimeline? timeline, EncodeCodec codec = EncodeCodec.H264, string? taggedAs = null) + { + EncodeProfile profile = EncodedArtefact.Profile(codec, RecordingFeature.Noon.AddHours(-1)); + Profiles.Profiles.Add(profile); + + EncodeJob job = EncodedArtefact.Made(recording, profile, RecordingFeature.Noon.AddHours(1), timeline); + Jobs.Jobs.Add(job); + + if (codec is EncodeCodec.H265) + { + Codecs.ReadAs(job.ArtefactName!, codec, taggedAs); + } + + File.WriteAllBytes(Path.Combine(encoded.FullName, job.ArtefactName!.Value), new byte[900]); + } + + public Task CaptionsAsync(Recording recording, string query = "", HttpClient? asking = null) + => (asking ?? Client).GetAsync(new Uri($"/api/videos/{recording.Id.Wire}/captions{query}", UriKind.Relative)); + + public async Task PlannedAsync(Recording recording, string query = "") + { + using HttpResponseMessage answer = await Client.GetAsync(new Uri($"/api/videos/{recording.Id.Wire}/play{query}", UriKind.Relative)); + + Assert.True(answer.StatusCode is HttpStatusCode.OK, await answer.Content.ReadAsStringAsync()); + + using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); + + return read.RootElement.GetProperty("data").GetProperty("captions").GetString(); + } + + public static async Task WindowOfAsync(HttpResponseMessage answer) + { + Assert.True(answer.StatusCode is HttpStatusCode.OK, await answer.Content.ReadAsStringAsync()); + + using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); + + return read.RootElement.GetProperty("data").Clone(); + } + + public static double[] Moments(JsonElement window) + => [.. window.GetProperty("cues").EnumerateArray().Select(cue => Math.Round(cue.GetProperty("atSec").GetDouble(), 3))]; + + public async ValueTask DisposeAsync() + { + Client.Dispose(); + Stranger.Dispose(); + await factory.DisposeAsync(); + TemporaryDirectories.RemoveAll(mounted, encoded, shelved); + } + + private static long At(double seconds) => (long)Math.Round(seconds * Second); + + private static CaptionPlacement Picture(int left) => new(left, 900, 320, 48, new byte[] { 0x89, 0x50, 0x4e, 0x47, (byte)left }); +} diff --git a/tests/Carina.Api.Tests/FeatureTest/EncodedPlaybackTests.cs b/tests/Carina.Api.Tests/FeatureTest/EncodedPlaybackTests.cs deleted file mode 100644 index eb64cafdb..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/EncodedPlaybackTests.cs +++ /dev/null @@ -1,787 +0,0 @@ -using System.Net; -using System.Text.Json; - -using Carina.Api.Playback; -using Carina.Domain.Base; -using Carina.Domain.Encodings; -using Carina.Domain.Recordings; -using Carina.Domain.Streaming; - -using Segments = Carina.Domain.Segments; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class EncodedPlaybackTests -{ - [Fact] - public async Task AnArtefactOnTheDiskIsWhatComesBackAndNothingIsTranscodedWhilePlaying() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage plan = await feature.PlanAsync(recording); - JsonElement read = (await PlayFeature.PlanOfAsync(plan)).GetProperty("data"); - using HttpResponseMessage picture = await feature.PictureAsync(recording); - - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.False(read.GetProperty("transcodes").GetBoolean()); - Assert.True(read.GetProperty("canSeek").GetBoolean()); - Assert.Equal("video/mp4", read.GetProperty("mediaType").GetString()); - Assert.Equal(artefact.Length, read.GetProperty("bytes").GetInt64()); - - Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); - Assert.Null(feature.Player.Handed); - } - - [Fact] - public async Task AnArtefactCarriesTheOneSoundItWasEncodedWithSoThePlanNamesNoneToChooseFrom() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - feature.Player.Sounds = 2; - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.Empty(read.GetProperty("sounds").EnumerateArray()); - } - - [Fact] - public async Task AskingAnArtefactForASecondSoundIsRefusedRatherThanQuietlyGivingTheOneItHas() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.BadRequest, picture.StatusCode); - Assert.Equal( - PlayDelivery.NothingToChooseFrom, - (await PlayFeature.PlanOfAsync(picture)).GetProperty("message").GetString()); - Assert.Null(feature.Player.Handed); - } - - [Fact] - public async Task AskingAnArtefactForTheMainSoundHandsItOverAsItAlwaysWas() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=main"); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); - } - - [Fact(DisplayName = "an encoded recording of a broadcast that announced two sounds still offers both of them")] - public async Task ThePlanOfAnEncodedRecordingStillNamesTheSoundsTheBroadcastAnnounced() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); - feature.Encoded(recording); - feature.Player.SoundsCannotBeRead = "the stream is never asked when the broadcast announced its sound"; - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.Equal( - ["main", "secondary"], - read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); - Assert.Equal(0, feature.Player.AskedWhatItCarries); - } - - [Fact(DisplayName = "the secondary sound of an encoded recording is transcoded from the recording, because the artefact was baked with the main one")] - public async Task AskingAnEncodedRecordingForItsSecondSoundGoesBackToTheRecordingItself() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=secondary"); - byte[] body = await picture.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); - Assert.Equal([SoundPlacement.OneChannelOf(0, SoundChannel.Right)], feature.Player.AskedWith); - Assert.Equal(feature.Player.Picture, body); - Assert.NotEqual(artefact, body); - } - - [Fact(DisplayName = "the main sound of an encoded recording is the artefact itself, whatever the broadcast announced")] - public async Task AskingAnEncodedRecordingForItsMainSoundHandsOverTheArtefact() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=main"); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); - Assert.Null(feature.Player.Handed); - } - - [Fact] - public async Task ThePlanOfAnEncodedRecordingAskedForItsSecondSoundIsThePlanOfATranscode() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); - feature.Encoded(recording); - - JsonElement read = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, "?sound=secondary"))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.True(read.GetProperty("transcodes").GetBoolean()); - Assert.False(read.GetProperty("canSeek").GetBoolean()); - Assert.Equal("byStartingAgain", read.GetProperty("seeking").GetString()); - } - - [Fact(DisplayName = "when the recording itself is out of reach, the plan of an encoded recording asked for its second sound offers the artefact and the one sound it carries")] - public async Task ThePlanNarrowsToTheArtefactWhenTheSoundAskedForCannotBeReachedAnyMore() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended( - RecordingOutcome.Complete, - onDisk: false, - audio: AudioMode.DualMono, - sounds: 1); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage plan = await feature.PlanAsync(recording, "?sound=secondary"); - JsonElement read = (await PlayFeature.PlanOfAsync(plan)).GetProperty("data"); - - Assert.Equal(HttpStatusCode.OK, plan.StatusCode); - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.False(read.GetProperty("transcodes").GetBoolean()); - Assert.Equal(artefact.Length, read.GetProperty("bytes").GetInt64()); - Assert.Equal( - ["main"], - read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); - } - - [Fact(DisplayName = "a picture asked for a sound that cannot be reached is refused rather than quietly handed the artefact of another sound")] - public async Task ThePictureOfASoundThatCannotBeReachedIsRefusedRatherThanQuietlyHandedTheArtefact() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended( - RecordingOutcome.Complete, - onDisk: false, - audio: AudioMode.DualMono, - sounds: 1); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.NotFound, picture.StatusCode); - Assert.NotEqual(artefact, await picture.Content.ReadAsByteArrayAsync()); - Assert.Null(feature.Player.Handed); - } - - [Fact] - public async Task AnArtefactIsMovedAboutByAskingForARangeOfItRatherThanByStartingAgain() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - byte[] artefact = feature.Encoded(recording, bytes: 2_000); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, string.Empty, "bytes=1000-1099"); - - Assert.Equal(HttpStatusCode.PartialContent, picture.StatusCode); - Assert.Equal("byRange", Header(picture, PlaybackHeaders.Seeking)); - Assert.Equal("bytes", Assert.Single(picture.Headers.AcceptRanges)); - Assert.Equal(artefact[1_000..1_100], await picture.Content.ReadAsByteArrayAsync()); - Assert.Null(feature.Player.Handed); - } - - [Fact] - public async Task OfTwoArtefactsOfOneRecordingTheOneMadeLastIsPlayed() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, bytes: 700); - byte[] later = feature.Encoded(recording, minutesLater: 90, bytes: 1_300); - - using HttpResponseMessage picture = await feature.PictureAsync(recording); - - Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(later, await picture.Content.ReadAsByteArrayAsync()); - } - - [Fact(DisplayName = "an artefact a newer one replaced is never played, even while its file is still on the disk, so a newer one a browser cannot decode as it is leaves the recording to the transcoder")] - public async Task AnArtefactANewerOneReplacedIsNeverPlayed() - { - await using PlayFeature feature = new(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, bytes: 700); - feature.Encoded(recording, EncodeCodec.H265, minutesLater: 90); - feature.Jobs.Jobs[0].Replaced(feature.Jobs.Jobs[1], RecordingFeature.Noon.AddHours(3)); - - using HttpResponseMessage picture = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); - } - - [Fact] - public async Task AnArtefactTheLedgerNamesAndTheDiskHasNotIsTranscodedInsteadAndSaidToHaveBeen() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, onDisk: false); - - using HttpResponseMessage picture = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); - Assert.Equal("encodedFileGone", Header(picture, PlaybackHeaders.FellBack)); - Assert.Equal(feature.Player.Picture, await picture.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task AnArtefactABrowserWouldNotDecodeAsItIsIsLeftToTheTranscoder() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H265); - - using HttpResponseMessage picture = await feature.PictureAsync(recording); - - Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); - Assert.Null(Header(picture, PlaybackHeaders.FellBack)); - } - - [Fact(DisplayName = "an artefact made in H.264 is still played as it is after its profile was changed to H.265")] - public async Task AnArtefactMadeInH264IsStillPlayedAsItIsAfterItsProfileWasChangedToH265() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - byte[] artefact = feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H264); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - JsonElement asked = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, "?source=artefact"))).GetProperty("data"); - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=artefact"); - - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.Equal("artefact", read.GetProperty("source").GetString()); - Assert.Equal("recording", read.GetProperty("alternative").GetString()); - Assert.Equal("artefact", asked.GetProperty("source").GetString()); - Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); - Assert.Null(feature.Player.Handed); - } - - [Fact(DisplayName = "the plan of a recording asked for as it was recorded names the artefact made in H.264 as the other one after its profile was changed to H.265")] - public async Task ThePlanAskedForTheRecordingNamesTheArtefactMadeInH264AfterItsProfileWasChangedToH265() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H264); - - JsonElement read = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, "?source=recording"))).GetProperty("data"); - - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal("artefact", read.GetProperty("alternative").GetString()); - } - - [Fact(DisplayName = "an artefact whose file is H.265 is left to the transcoder even when its profile says H.264 now")] - public async Task AnArtefactWhoseFileIsH265IsLeftToTheTranscoderEvenWhenItsProfileSaysH264Now() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H264, fileReadAs: EncodeCodec.H265); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); - } - - [Fact(DisplayName = "an artefact made in H.265 and tagged hvc1 is handed over as it is to a browser that says it decodes h265")] - public async Task AnArtefactInH265TaggedHvc1IsHandedOverToABrowserThatSaysItDecodesH265() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - byte[] artefact = feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1"); - - JsonElement read = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, "?decodes=h265"))).GetProperty("data"); - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=artefact&decodes=h265"); - - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.Equal("artefact", read.GetProperty("source").GetString()); - Assert.Equal("recording", read.GetProperty("alternative").GetString()); - Assert.Equal(["artefact", "recording"], ExternalPlayerSources(read)); - Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); - Assert.Null(feature.Player.Handed); - } - - [Theory(DisplayName = "a browser that does not say it decodes h265 has an artefact made in H.265 transcoded, and the plan still names it for external players")] - [InlineData("")] - [InlineData("?decodes=h264")] - public async Task ABrowserThatDoesNotSayItDecodesH265HasTheArtefactTranscoded(string query) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1"); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording, query))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); - Assert.Equal(["artefact", "recording"], ExternalPlayerSources(read)); - } - - [Fact(DisplayName = "an artefact made in H.265 and tagged hev1 is transcoded even for a browser that says it decodes h265")] - public async Task AnArtefactInH265TaggedHev1IsTranscodedEvenForABrowserThatDecodesH265() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hev1"); - - JsonElement read = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, "?decodes=h264&decodes=h265"))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.Equal(["artefact", "recording"], ExternalPlayerSources(read)); - } - - [Fact(DisplayName = "the plan of a recording with nothing encoded names only the recording itself for external players")] - public async Task ThePlanOfARecordingWithNothingEncodedNamesOnlyTheRecordingForExternalPlayers() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal(["recording"], ExternalPlayerSources(read)); - } - - [Theory(DisplayName = "a decoding that is not one of the three is refused, for the plan and for the picture alike")] - [InlineData("?decodes=vp9")] - [InlineData("?decodes=h265&decodes=H264")] - public async Task ADecodingThatIsNotOneOfTheThreeIsRefused(string query) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - - using HttpResponseMessage plan = await feature.PlanAsync(recording, query); - using HttpResponseMessage picture = await feature.PictureAsync(recording, query); - - Assert.Equal(HttpStatusCode.BadRequest, plan.StatusCode); - Assert.Equal(HttpStatusCode.BadRequest, picture.StatusCode); - Assert.Equal(PlayDelivery.TheDecodingsThereAre, (await PlayFeature.PlanOfAsync(plan)).GetProperty("message").GetString()); - } - - [Theory(DisplayName = "a browser saying it decodes AV1 is answered, and settles on the file one naming nothing more would")] - [InlineData("?decodes=av1", "?decodes=h264")] - [InlineData("?decodes=h265&decodes=av1", "?decodes=h265")] - public async Task ABrowserSayingItDecodesAv1IsAnswered(string withAv1, string without) - { - await using PlayFeature feature = new(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H265, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1"); - - using HttpResponseMessage asked = await feature.PlanAsync(recording, withAv1); - using HttpResponseMessage plain = await feature.PlanAsync(recording, without); - - Assert.Equal(HttpStatusCode.OK, asked.StatusCode); - Assert.Equal( - (await PlayFeature.PlanOfAsync(plain)).GetProperty("data").GetProperty("transcodes").GetBoolean(), - (await PlayFeature.PlanOfAsync(asked)).GetProperty("data").GetProperty("transcodes").GetBoolean()); - } - - [Fact] - public async Task NothingSaysAPlanFellBackWhenTheArtefactItNamesIsThere() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording); - - Assert.Null(Header(picture, PlaybackHeaders.FellBack)); - } - - [Fact] - public async Task TheFileOfARecordingWithAnArtefactIsTheArtefactAndItIsHandedOverAsAnMp4() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(4_000)); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage answer = await feature.GetAsync(recording); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); - Assert.Equal(artefact, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task TheFileOfAnEncodedRecordingAskedForAsItWasRecordedIsTheRecordingHandedOverAsATransportStream() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(4_000); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - feature.Encoded(recording); - - using HttpResponseMessage answer = await feature.GetFromAsync(recording, "recording"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("video/mp2t", answer.Content.Headers.ContentType?.MediaType); - Assert.Equal(written, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task TheRecordingItselfIsMovedAboutByARangeAndAskedForItsSizeAloneLikeTheArtefact() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(4_000); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - feature.Encoded(recording); - - using HttpResponseMessage part = await feature.GetFromAsync(recording, "recording", "bytes=100-199"); - using HttpResponseMessage head = await feature.HeadFromAsync(recording, "recording"); - - Assert.Equal(HttpStatusCode.PartialContent, part.StatusCode); - Assert.Equal(written[100..200], await part.Content.ReadAsByteArrayAsync()); - Assert.Equal(HttpStatusCode.OK, head.StatusCode); - Assert.Equal(written.Length, head.Content.Headers.ContentLength); - } - - [Fact] - public async Task TheFileOfAnEncodedRecordingAskedForAsTheArtefactByNameIsTheArtefact() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(4_000)); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage answer = await feature.GetFromAsync(recording, "artefact"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); - Assert.Equal(artefact, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task TheRecordingItselfAskedForWhenItIsGoneIsRefusedRatherThanQuietlyHandedTheArtefact() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(4_000), onDisk: false); - feature.Encoded(recording); - - using HttpResponseMessage answer = await feature.GetFromAsync(recording, "recording"); - - Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact(DisplayName = "the chapters that come back are placed on the clock of the artefact that is played rather than of an earlier one")] - public async Task TheChaptersThatComeBackArePlacedOnTheClockOfTheArtefactThatIsPlayed() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, bytes: 700, timeline: Skipped(0.5)); - feature.Encoded(recording, minutesLater: 90, bytes: 1_300, timeline: Skipped(1.5)); - await APodAsync(feature, recording); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal(1_300, read.GetProperty("bytes").GetInt64()); - Assert.Equal([0d, 298.5d, 358.5d], read.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("startsAtSec").GetDouble()).ToArray()); - } - - [Theory(DisplayName = "with an earlier artefact in H.264 and a later one in H.265, a browser is handed the newest one it decodes, with the chapters placed on that artefact's clock")] - [InlineData("?decodes=h265", 1_300, 298.5d)] - [InlineData("", 700, 299.5d)] - public async Task ABrowserIsHandedTheNewestArtefactItDecodesWithItsOwnChapters(string query, long bytes, double breakStartsAt) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H264, bytes: 700, fileReadAs: EncodeCodec.H264, timeline: Skipped(0.5)); - feature.Encoded(recording, EncodeCodec.H265, minutesLater: 90, bytes: 1_300, fileReadAs: EncodeCodec.H265, taggedAs: "hvc1", timeline: Skipped(1.5)); - await APodAsync(feature, recording); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording, query))).GetProperty("data"); - JsonElement[] chapters = [.. read.GetProperty("chapters").EnumerateArray()]; - - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.Equal(bytes, read.GetProperty("bytes").GetInt64()); - Assert.Equal(("break", breakStartsAt), (chapters[1].GetProperty("kind").GetString(), chapters[1].GetProperty("startsAtSec").GetDouble())); - } - - [Fact] - public async Task ThePlanOfAnArtefactWhoseRunMarkedNothingCarriesAnEmptyListRatherThanNoField() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.Empty(read.GetProperty("chapters").EnumerateArray()); - } - - [Fact(DisplayName = "A recording played as it was recorded is answered with no chapters, because the ledger holds them on the artefact's clock")] - public async Task ThePlanOfARecordingPlayedAsItWasRecordedCarriesNoChapters() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.Empty(read.GetProperty("chapters").EnumerateArray()); - } - - [Fact] - public async Task ThePlanOfAnEncodedRecordingAskedForItsSecondSoundCarriesNoneOfTheArtefactsChapters() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); - feature.Encoded(recording); - await feature.MarkedAsync( - feature.Jobs.Jobs[0], - new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme)); - - JsonElement read = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, "?sound=secondary"))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.Empty(read.GetProperty("chapters").EnumerateArray()); - } - - [Fact(DisplayName = "a recording with an artefact asked for as it was recorded hands the recording itself to the transcoder rather than the artefact")] - public async Task ARecordingAskedForAsItWasRecordedIsTranscodedFromTheRecordingAndNotFromTheArtefact() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, bytes: 3_500); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=recording"); - byte[] body = await picture.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); - Assert.Equal(PlayFeature.Root, Assert.Single(feature.Player.Opened).Root); - Assert.Equal(feature.Player.Picture, body); - Assert.NotEqual(artefact, body); - } - - [Fact(DisplayName = "the plan of a recording asked for as it was recorded says it plays the recording and names the artefact as the other one")] - public async Task ThePlanOfARecordingAskedForAsItWasRecordedNamesTheArtefactAsTheOtherOne() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - - JsonElement read = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, "?source=recording"))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal("artefact", read.GetProperty("alternative").GetString()); - Assert.True(read.GetProperty("transcodes").GetBoolean()); - Assert.False(read.GetProperty("canSeek").GetBoolean()); - Assert.Equal(JsonValueKind.Null, read.GetProperty("bytes").ValueKind); - } - - [Fact(DisplayName = "the plan of an encoded recording asked for as it is says it plays the artefact and names the recording itself as the other one")] - public async Task ThePlanOfAnEncodedRecordingNamesTheRecordingItselfAsTheOtherOne() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - byte[] artefact = feature.Encoded(recording); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("direct", read.GetProperty("route").GetString()); - Assert.Equal("artefact", read.GetProperty("source").GetString()); - Assert.Equal("recording", read.GetProperty("alternative").GetString()); - Assert.Equal(artefact.Length, read.GetProperty("bytes").GetInt64()); - } - - [Fact(DisplayName = "asking outright for the artefact is asking for what playing a recording has always given")] - public async Task AskingOutrightForTheArtefactHandsOverTheArtefact() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=artefact"); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal("direct", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(artefact, await picture.Content.ReadAsByteArrayAsync()); - Assert.Null(feature.Player.Handed); - } - - [Fact(DisplayName = "an artefact the ledger names and the disk has not is not the other one the plan offers")] - public async Task AnArtefactTheDiskHasNotIsNotOfferedAsTheOtherOne() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, onDisk: false); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); - } - - [Fact(DisplayName = "an artefact holding no bytes is not the other one the plan offers")] - public async Task AnArtefactHoldingNoBytesIsNotOfferedAsTheOtherOne() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, bytes: 0); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("onTheFly", read.GetProperty("route").GetString()); - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); - } - - [Fact(DisplayName = "an artefact a browser would not decode as it is, is not the other one the plan offers")] - public async Task AnArtefactABrowserWouldNotDecodeIsNotOfferedAsTheOtherOne() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, EncodeCodec.H265); - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); - } - - [Fact(DisplayName = "a recording asked for as it was recorded and no longer on the disk is refused rather than quietly handed its artefact")] - public async Task ARecordingAskedForAsItWasRecordedAndNoLongerOnTheDiskIsRefused() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, onDisk: false); - byte[] artefact = feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=recording"); - using HttpResponseMessage plan = await feature.PlanAsync(recording, "?source=recording"); - - Assert.Equal(HttpStatusCode.NotFound, picture.StatusCode); - Assert.Equal(HttpStatusCode.NotFound, plan.StatusCode); - Assert.NotEqual(artefact, await picture.Content.ReadAsByteArrayAsync()); - Assert.Null(feature.Player.Handed); - Assert.Empty(feature.Player.Opened); - } - - [Fact(DisplayName = "a recording asked for as it was recorded with a second sound is not narrowed to the artefact when the recording is gone")] - public async Task ARecordingAskedForAsItWasRecordedIsNotNarrowedToTheArtefactWhenItsSecondSoundIsAskedFor() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended( - RecordingOutcome.Complete, - onDisk: false, - audio: AudioMode.DualMono, - sounds: 1); - feature.Encoded(recording); - - using HttpResponseMessage plan = await feature.PlanAsync(recording, "?source=recording&sound=secondary"); - - Assert.Equal(HttpStatusCode.NotFound, plan.StatusCode); - Assert.Null(feature.Player.Handed); - } - - [Fact(DisplayName = "a recording asked for as it was recorded and holding no bytes is refused rather than quietly handed its artefact")] - public async Task ARecordingAskedForAsItWasRecordedAndHoldingNoBytesIsRefused() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Failed, bytes: 0); - feature.Encoded(recording); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=recording"); - - Assert.Equal(HttpStatusCode.NotFound, picture.StatusCode); - Assert.Empty(feature.Player.Opened); - } - - [Fact(DisplayName = "a recording asked for as it was recorded is moved about by starting again, because it is transcoded while playing")] - public async Task ARecordingAskedForAsItWasRecordedIsMovedAboutByStartingAgainRatherThanByARange() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, bytes: 2_000); - feature.Encoded(recording, bytes: 2_000); - - using HttpResponseMessage picture = await feature.PictureAsync( - recording, - "?source=recording", - "bytes=1000-1099"); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal("byStartingAgain", Header(picture, PlaybackHeaders.Seeking)); - Assert.Equal("none", Assert.Single(picture.Headers.AcceptRanges)); - } - - [Fact(DisplayName = "the chapters the ledger holds belong to the artefact, so a recording asked for as it was recorded comes back with none")] - public async Task ARecordingAskedForAsItWasRecordedComesBackWithNoneOfTheArtefactsChapters() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - await feature.MarkedAsync( - feature.Jobs.Jobs[0], - new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme)); - - JsonElement read = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, "?source=recording"))).GetProperty("data"); - - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Empty(read.GetProperty("chapters").EnumerateArray()); - } - - private static EncodeTimeline Skipped(double head) - => new(TimeSpan.FromSeconds(1.4), TimeSpan.FromSeconds(head), TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30) - TimeSpan.FromSeconds(head)); - - /// - /// Keeps a detection of the recording by the version in use with a pod of adverts five minutes in. - /// - private static async Task APodAsync(PlayFeature feature, Recording recording) - { - Segments.SegmentSpan[] segments = - [ - new(TimeSpan.Zero, TimeSpan.FromSeconds(300), Segments.SegmentKind.Programme, 0.98), - new(TimeSpan.FromSeconds(300), TimeSpan.FromSeconds(360), Segments.SegmentKind.Break, 0.93), - new(TimeSpan.FromSeconds(360), TimeSpan.FromMinutes(30), Segments.SegmentKind.Programme, 0.99), - ]; - - await feature.Detections.KeepAsync( - Segments.RecordingDetection.Of( - recording.Id, - Segments.SegmentModelVersion.FirstNumber, - Segments.SegmentDetection.Judged(segments, TimeSpan.FromMinutes(30), []), - 2, - RecordingFeature.Noon, - RecordingFeature.Noon), - CancellationToken.None); - } - - private static string? Header(HttpResponseMessage answer, string named) - => answer.Headers.TryGetValues(named, out IEnumerable? values) ? values.Single() : null; - - private static string[] ExternalPlayerSources(JsonElement plan) - => [.. plan.GetProperty("externalPlayerSources").EnumerateArray().Select(source => source.GetString()!)]; -} diff --git a/tests/Carina.Api.Tests/FeatureTest/HeldOnTheFlyPlayer.cs b/tests/Carina.Api.Tests/FeatureTest/HeldOnTheFlyPlayer.cs new file mode 100644 index 000000000..76b2536bc --- /dev/null +++ b/tests/Carina.Api.Tests/FeatureTest/HeldOnTheFlyPlayer.cs @@ -0,0 +1,103 @@ +using Carina.Domain.Channels; +using Carina.Domain.Playback; +using Carina.Domain.Streaming; + +namespace Carina.Api.Tests.FeatureTest; + +internal sealed class HeldOnTheFlyPlayer : IOnTheFlyPlayer +{ + public byte[] Picture { get; set; } = [.. Enumerable.Range(0, 3_000).Select(index => (byte)(index % 251))]; + + public OnTheFlyRefusal? Refuses { get; set; } + + public int Running { get; set; } = 1; + + public int AtOnce { get; set; } = 2; + + public TimeSpan Waited { get; set; } = TimeSpan.FromMilliseconds(138); + + public LiveEncoder Machine { get; set; } = LiveEncoder.Software; + + public List AskedFrom { get; } = []; + + public List AskedFor { get; } = []; + + public List AskedIn { get; } = []; + + public List AskedOf { get; } = []; + + public List AskedWith { get; } = []; + + public List Opened { get; } = []; + + public int Sounds { get; set; } = 1; + + public string? SoundsCannotBeRead { get; set; } + + public int AskedWhatItCarries { get; private set; } + + public HeldViewing? Handed { get; private set; } + + public List EveryHanded { get; } = []; + + public TranscoderExit Exit { get; set; } = TranscoderExit.Finished(); + + public bool WritesOn { get; set; } + + public int? Seats { get; set; } + + public Task StartAsync( + PlaybackFile file, + ServiceId service, + TimeSpan from, + LiveProfile? profile, + VideoCodec format, + SoundPlacement sound, + CancellationToken cancellationToken) + { + AskedFrom.Add(from); + AskedFor.Add(profile?.Name); + AskedIn.Add(format); + AskedOf.Add(service); + AskedWith.Add(sound); + Opened.Add(file); + + if (Refuses is { } refusal) + { + return Task.FromResult(OnTheFlyStart.Refused(refusal, "the held player was told to refuse.")); + } + + if (Seats is { } seats && EveryHanded.Count(viewing => !viewing.WasLetGo) >= seats) + { + return Task.FromResult(OnTheFlyStart.Refused(OnTheFlyRefusal.TooManyAlready, "every seat the held player has is taken.")); + } + + Handed = new HeldViewing( + new OnTheFlyStanding( + from, + Waited, + profile ?? LiveProfile.Unasked(Machine), + LiveEncoderChoice.Asked(Machine), + attributesWereMeasured: true, + Running, + AtOnce), + Picture, + Exit, + WritesOn); + EveryHanded.Add(Handed); + + return Task.FromResult(OnTheFlyStart.Started(Handed)); + } + + public Task SoundsAsync( + PlaybackFile file, + ServiceId service, + CancellationToken cancellationToken) + { + AskedWhatItCarries++; + + return Task.FromResult(SoundsCannotBeRead is { } why + ? CarriedSounds.Unread(why) + : CarriedSounds.Counted(Sounds)); + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/HeldViewing.cs b/tests/Carina.Api.Tests/FeatureTest/HeldViewing.cs new file mode 100644 index 000000000..070f2b1fe --- /dev/null +++ b/tests/Carina.Api.Tests/FeatureTest/HeldViewing.cs @@ -0,0 +1,50 @@ +using System.IO.Pipelines; + +using Carina.Domain.Streaming; + +namespace Carina.Api.Tests.FeatureTest; + +internal sealed class HeldViewing : IOnTheFlyViewing +{ + private readonly Pipe? endless; + + private int letGo; + + public HeldViewing(OnTheFlyStanding standing, byte[] picture, TranscoderExit? exit = null, bool writesOn = false) + { + Standing = standing; + Completion = Task.FromResult(exit ?? TranscoderExit.Finished()); + + if (!writesOn) + { + Output = new MemoryStream(picture); + + return; + } + + endless = new Pipe(); + endless.Writer.WriteAsync(picture).AsTask().GetAwaiter().GetResult(); + Output = endless.Reader.AsStream(); + } + + public OnTheFlyStanding Standing { get; } + + public Stream Output { get; } + + public Task Completion { get; } + + public bool WasLetGo => Volatile.Read(ref letGo) is 1; + + public ValueTask DisposeAsync() + { + Volatile.Write(ref letGo, 1); + endless?.Writer.Complete(); + + if (endless is null) + { + Output.Dispose(); + } + + return ValueTask.CompletedTask; + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveEndpointTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveEndpointTests.cs index 5c373dad8..3d29c4540 100644 --- a/tests/Carina.Api.Tests/FeatureTest/LiveEndpointTests.cs +++ b/tests/Carina.Api.Tests/FeatureTest/LiveEndpointTests.cs @@ -1,9 +1,7 @@ using System.Net; -using System.Net.Http.Json; using System.Text; using System.Text.Json; -using Carina.Api.Live; using Carina.Domain.Auth; using Carina.Domain.Channels; using Carina.Domain.Streaming; @@ -717,28 +715,6 @@ public async Task TooManyOutstandingTicketsIsSaidAsTooManyRequests() Assert.Equal(HttpStatusCode.TooManyRequests, response.StatusCode); } - [Fact] - public async Task ATicketIsNotHandedToTheWire() - { - await using LiveFeature feature = new(); - - feature.Seed(1024, "Alpha", remoteControlKey: 1); - - using HttpResponseMessage ticket = await feature.AskForATicketAsync(new { networkId = 32736, serviceId = 1024 }); - using JsonDocument body = JsonDocument.Parse(await ticket.Content.ReadAsStringAsync()); - string inTheClear = body.RootElement.GetProperty("data").GetProperty("inTheClear").GetString()!; - - using HttpRequestMessage asking = new( - HttpMethod.Get, - new Uri(LiveWire.Path + "?network=32736&service=1024&profile=720p30", UriKind.Relative)); - - asking.Headers.TryAddWithoutValidation("Authorization", $"Bearer {inTheClear}"); - - using HttpResponseMessage response = await feature.Anonymous.SendAsync(asking); - - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - } - private static string[] Names(JsonElement data) => [.. data.GetProperty("items").EnumerateArray().Select(item => item.GetProperty("name").GetString()!)]; } diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveLeaseTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveLeaseTests.cs deleted file mode 100644 index b54851fc5..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/LiveLeaseTests.cs +++ /dev/null @@ -1,222 +0,0 @@ -using System.Net.WebSockets; - -using Carina.Api.Live; -using Carina.Domain.Channels; -using Carina.Domain.Driver; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Hosting; -using Microsoft.Net.Http.Headers; - -using Puppis.Contracts; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class LiveLeaseTests -{ - private static readonly TimeSpan Linger = TimeSpan.FromMilliseconds(400); - - private static readonly TuningParameters Channel27 = TuningParameters.Terrestrial(27); - - private readonly ScriptedDriverClient driver = new(); - - private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); - - private readonly HeldTranscoders transcoders; - - public LiveLeaseTests() - { - transcoders = new HeldTranscoders(budget); - driver.Script(Channel27, new ChannelScript { Paced = () => PacedStream.InChunksOf(new byte[188 * 16], 188) }); - } - - [Fact] - public async Task AWireThatSaysItIsLeavingHasItsSessionStoppedOnTheDriverOnceAfterTheLinger() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("1024"), Patiently()); - - SessionId held = await TheOneSessionHeldAsync(); - - await socket.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); - await ReadUntilClosed(socket); - - await StoppedOnceAsync(held); - } - - [Fact] - public async Task AWireClosedTheOrdinaryWayHasItsSessionStoppedOnTheDriverOnceAfterTheLinger() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("1024"), Patiently()); - - SessionId held = await TheOneSessionHeldAsync(); - - await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "leaving", Patiently()); - await ReadUntilClosed(socket); - - await StoppedOnceAsync(held); - } - - [Fact] - public async Task AWireThatBreaksOffWithoutAWordHasItsSessionStoppedOnTheDriverOnceAfterTheLinger() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("1024"), Patiently()); - - SessionId held = await TheOneSessionHeldAsync(); - - socket.Abort(); - - await StoppedOnceAsync(held); - } - - [Fact] - public async Task AWireSwitchingChannelsStopsOnlyTheSessionItLeftAndTheNewOneWhenItLeavesThatToo() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket first = await Carrying(probe, cookie).ConnectAsync(Handshake("1024"), Patiently()); - - SessionId before = await TheOneSessionHeldAsync(); - - using WebSocket second = await Carrying(probe, cookie).ConnectAsync(Handshake("1032"), Patiently()); - - await Eventually.Happens(() => driver.Live.Count is 2, "the second channel has a session of its own on the driver"); - - SessionId after = driver.Live.Single(session => session != before); - - await first.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); - await ReadUntilClosed(first); - - await StoppedOnceAsync(before); - - Assert.Equal([after], driver.Live); - - await second.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); - await ReadUntilClosed(second); - - await Eventually.Happens(() => driver.Stopped.Count is 2, "the second session is stopped once its viewer has left"); - await Task.Delay(Linger * 3); - - Assert.Equal([before, after], driver.Stopped); - Assert.Empty(driver.Live); - } - - [Fact] - public async Task AWireBackWithinTheLingerRidesTheSameSessionAndItsLeavingAgainStopsThatSessionOnce() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket gone = await Carrying(probe, cookie).ConnectAsync(Handshake("1024"), Patiently()); - - SessionId held = await TheOneSessionHeldAsync(); - - await gone.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); - await ReadUntilClosed(gone); - - using WebSocket back = await Carrying(probe, cookie).ConnectAsync(Handshake("1024"), Patiently()); - - Assert.Equal(LiveChannel.Control, (await Take(back)).Channel); - - await Task.Delay(Linger * 2); - - Assert.Single(driver.Started); - Assert.Empty(driver.Stopped); - Assert.Equal([held], driver.Live); - - await back.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); - await ReadUntilClosed(back); - - await StoppedOnceAsync(held); - - Assert.Single(driver.Started); - } - - private static Uri Handshake(string service) - => new($"ws://localhost{LiveWire.Path}?network=32736&service={service}&profile=720p30"); - - private static CancellationToken Patiently() => new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token; - - private static WebSocketClient Carrying(AuthProbe probe, string cookie) - { - WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); - - client.ConfigureRequest += request => request.Headers[HeaderNames.Cookie] = cookie; - - return client; - } - - private static async Task Take(WebSocket socket) - { - byte[] heard = new byte[64 * 1024]; - - WebSocketReceiveResult said = await socket.ReceiveAsync(new ArraySegment(heard), Patiently()); - - Assert.Equal(WebSocketMessageType.Binary, said.MessageType); - - LiveFraming framing = LiveFrame.Read(heard.AsSpan(0, said.Count)); - - Assert.NotNull(framing.Frame); - - return framing.Frame; - } - - private static async Task ReadUntilClosed(WebSocket socket) - { - byte[] heard = new byte[64 * 1024]; - - try - { - while ((await socket.ReceiveAsync(new ArraySegment(heard), Patiently())).MessageType is not WebSocketMessageType.Close) - { - } - } - catch (WebSocketException) - { - } - } - - private async Task TheOneSessionHeldAsync() - { - await Eventually.Happens(() => driver.Live.Count is 1, "the driver holds one live session for the wire"); - - Assert.Equal([SessionPurpose.Live], driver.Purposes); - - return driver.Live.Single(); - } - - private async Task StoppedOnceAsync(SessionId held) - { - await Eventually.Happens(() => driver.Stopped.Count >= 1, "the session is stopped on the driver once the linger is over"); - await Task.Delay(Linger * 3); - - Assert.Equal([held], driver.Stopped); - Assert.DoesNotContain(held, driver.Live); - } - - private AuthProbe Wiring() - => AuthProbe.OverHttp(services => - { - services.RemoveAll(); - services.AddSingleton(driver); - services.AddSingleton(new ResolvedTuning( - TuningResolution.Tunable(new CandidateChannelId(Guid.NewGuid()), Channel27, impaired: false))); - services.AddSingleton(new LiveSessionSettings(linger: Linger)); - services.AddSingleton(budget); - services.AddSingleton(transcoders); - }); -} diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveSessionWireTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveSessionWireTests.cs deleted file mode 100644 index 635ff7b1a..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/LiveSessionWireTests.cs +++ /dev/null @@ -1,576 +0,0 @@ -using System.Net.WebSockets; - -using Carina.Api.Live; -using Carina.Domain.Base; -using Carina.Domain.Channels; -using Carina.Domain.Programmes; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Net.Http.Headers; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class LiveSessionWireTests -{ - private static readonly LiveSessionKey EveryFrame = new(new NetworkId(32736), new ServiceId(1024), LiveProfile.Hd30); - - private readonly PipedSupply supply = new(); - - private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); - - private readonly HeldTranscoders transcoders; - - public LiveSessionWireTests() - { - transcoders = new HeldTranscoders(budget); - } - - [Fact] - public async Task TwoWiresAskingForOneKeyAreCarriedByOneTranscoderAndSeeTheSamePicture() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket one = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - using WebSocket another = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - Assert.Equal(1, transcoders.Started); - Assert.Equal(1, budget.Running); - - await transcoders.Raised[0].WriteAsync(Fmp4.Header); - await transcoders.Raised[0].WriteAsync(Fmp4.Fragment(1_000)); - - LiveFrame[] toOne = [await TakePictureHeader(one), await TakePastProgress(one)]; - LiveFrame[] toAnother = [await TakePictureHeader(another), await TakePastProgress(another)]; - - Assert.Equal([LiveChannel.PictureHeader, LiveChannel.Picture], toOne.Select(frame => frame.Channel)); - Assert.Equal(toOne.Select(frame => frame.Channel), toAnother.Select(frame => frame.Channel)); - Assert.Equal( - toOne.Select(frame => frame.Payload.ToArray()), - toAnother.Select(frame => frame.Payload.ToArray())); - Assert.Equal(2, Sessions(probe).Viewers(EveryFrame)); - } - - [Fact] - public async Task AWireAskingForAnotherProfileOfTheSameChannelRaisesASecondTranscoder() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket frames = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - using WebSocket fields = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p60"), Patiently()); - - Assert.Equal(2, transcoders.Started); - Assert.Equal(2, budget.Running); - Assert.Equal([LiveProfile.Hd30, LiveProfile.Hd60], transcoders.Raised.Select(raised => raised.Profile)); - } - - [Fact] - public async Task AWireOnASessionStillStartingIsFirstToldHowFarItHasGot() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - LiveFrame progress = await Take(socket); - - Assert.Equal(LiveChannel.Control, progress.Channel); - - LiveStartupReading read = LiveStartup.ReadProgress(progress.Payload.Span); - - Assert.Null(read.Fault); - Assert.True(read.Startup!.Reached(LiveStartupSegment.TranscoderStarted)); - Assert.False(read.Startup.Reached(LiveStartupSegment.InitReached)); - Assert.True(read.Startup.Reached(LiveStartupSegment.TunerSecured)); - Assert.False(read.Startup.Reached(LiveStartupSegment.ChannelLocked)); - - await transcoders.Raised[0].WriteAsync(Fmp4.Header); - await transcoders.Raised[0].WriteAsync(Fmp4.Fragment(1_000)); - - Assert.Equal(LiveChannel.PictureHeader, (await TakePictureHeader(socket)).Channel); - Assert.Equal(LiveChannel.Picture, (await TakePastProgress(socket)).Channel); - } - - [Fact] - public async Task AWireIsToldEachStepOfTheStartupAsItIsReached() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - LiveStartup atTheHandshake = await NextProgress(socket); - - Assert.True(atTheHandshake.Reached(LiveStartupSegment.TranscoderStarted)); - Assert.False(atTheHandshake.Reached(LiveStartupSegment.ChannelLocked)); - - await supply.Opened[0].WriteAsync(new byte[1_000]); - - LiveStartup locked = await NextProgress(socket); - - Assert.True(locked.Reached(LiveStartupSegment.ChannelLocked)); - Assert.False(locked.Reached(LiveStartupSegment.InitReached)); - - await transcoders.Raised[0].WriteAsync(Fmp4.Header); - - LiveStartup init = await NextProgress(socket); - - Assert.True(init.Reached(LiveStartupSegment.InitReached)); - Assert.False(init.Reached(LiveStartupSegment.FirstPicture)); - - await transcoders.Raised[0].WriteAsync(Fmp4.Fragment(1_000)); - - LiveStartup done = await NextProgress(socket); - - Assert.True(done.Reached(LiveStartupSegment.FirstPicture)); - Assert.False(done.InProgress); - Assert.All(done.Timeline, mark => Assert.True(mark.Took >= TimeSpan.Zero)); - } - - [Fact] - public async Task AWireJoiningASessionPastItsStartupIsHandedTheHeaderFirst() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket early = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - await transcoders.Raised[0].WriteAsync(Fmp4.Header); - await transcoders.Raised[0].WriteAsync(Fmp4.Fragment(1_000)); - await Eventually.Happens( - () => Sessions(probe).Startup(EveryFrame)?.Current is { InProgress: false }, - "the first picture ends the startup"); - - using WebSocket late = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - Assert.Equal(LiveChannel.PictureHeader, (await Take(late)).Channel); - } - - [Fact] - public async Task AWireLeavingIsForgottenByTheSession() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket staying = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - using WebSocket leaving = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - await leaving.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); - - await Eventually.Happens(() => Sessions(probe).Viewers(EveryFrame) is 1, "the session counts one viewer fewer"); - - Assert.Equal(1, budget.Running); - } - - [Fact] - public async Task WhyTheSupplyEndedReachesTheWireOnTheControlChannelBeforeItIsClosed() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - Assert.Equal(LiveChannel.Control, (await Take(socket)).Channel); - - supply.Opened[0].Ending = LiveSupplyEnding.Of(LiveSupplyEnd.TakenForARecording, "a recording outranked it."); - supply.Opened[0].NoMore(); - - await Eventually.Happens(() => supply.Opened[0].Disposed, "the reading of the supply has taken in why it ended"); - - await transcoders.Raised[0].WriteAsync(Fmp4.Header); - transcoders.Raised[0].NoMore(); - - (IReadOnlyList heard, WebSocketReceiveResult ending) = await UntilItIsClosed(socket); - - Assert.Contains(LiveChannel.PictureHeader, heard.Select(frame => frame.Channel)); - - LiveEndingReport said = Assert.Single( - heard.Where(frame => frame.Channel is LiveChannel.Control) - .Select(frame => LiveEndingReport.Read(frame.Payload.Span)) - .Where(read => read.Fault is null) - .Select(read => read.Report!)); - - Assert.Equal(LiveSupplyEnd.TakenForARecording, said.Why); - Assert.Equal(WebSocketMessageType.Close, ending.MessageType); - Assert.Equal(WebSocketCloseStatus.NormalClosure, ending.CloseStatus); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), ending.CloseStatusDescription); - } - - [Fact] - public async Task WhyItEndedReachesTheWireWhenTheTranscoderEndsBeforeTheSupplyEverDoes() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - Assert.Equal(LiveChannel.Control, (await Take(socket)).Channel); - - await transcoders.Raised[0].WriteAsync(Fmp4.Header); - transcoders.Raised[0].NoMore(); - - (IReadOnlyList heard, WebSocketReceiveResult ending) = await UntilItIsClosed(socket); - - Assert.Contains(LiveChannel.PictureHeader, heard.Select(frame => frame.Channel)); - - LiveEndingReport said = Assert.Single( - heard.Where(frame => frame.Channel is LiveChannel.Control) - .Select(frame => LiveEndingReport.Read(frame.Payload.Span)) - .Where(read => read.Fault is null) - .Select(read => read.Report!)); - - Assert.Null(supply.Opened[0].Ending); - Assert.Equal(LiveSupplyEnd.LetGo, said.Why); - Assert.Equal(WebSocketMessageType.Close, ending.MessageType); - Assert.Equal(WebSocketCloseStatus.NormalClosure, ending.CloseStatus); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), ending.CloseStatusDescription); - } - - [Fact] - public async Task AWireNamingAProfileOffTheListIsRefusedBeforeAnythingIsRaised() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - InvalidOperationException refused = await Assert.ThrowsAsync( - () => Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "hls"), Patiently())); - - Assert.Contains("400", refused.Message, StringComparison.Ordinal); - Assert.Equal(0, supply.Asked); - Assert.Equal(0, transcoders.Started); - } - - [Fact] - public async Task AWireIsToldOnTheControlChannelThatTheDriverCannotBeReachedAndIsClosed() - { - TuningByServiceId tuning = new(); - - tuning.Answer(1024, TuningParameters.Terrestrial(27)); - - await using AuthProbe probe = AuthProbe.OverHttp(services => - services.AddSingleton(tuning)); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - LiveRefusalReport report = await Refused(socket); - - Assert.Equal(LiveRefusal.DriverUnavailable, report.Refusal); - Assert.Null(report.Ceiling); - - WebSocketReceiveResult ending = await Heard(socket); - - Assert.Equal(WebSocketMessageType.Close, ending.MessageType); - Assert.Equal(WebSocketCloseStatus.InternalServerError, ending.CloseStatus); - Assert.Equal(LiveRefusalClosures.Because(LiveRefusal.DriverUnavailable), ending.CloseStatusDescription); - } - - [Theory] - [InlineData(LiveRefusal.NoSuchChannel, WebSocketCloseStatus.InvalidPayloadData)] - [InlineData(LiveRefusal.NoTunerFree, WebSocketCloseStatus.PolicyViolation)] - [InlineData(LiveRefusal.WouldNotTune, WebSocketCloseStatus.InternalServerError)] - public async Task WhatTheSupplyRefusesForReachesTheViewerAsThatReason(LiveRefusal why, WebSocketCloseStatus closed) - { - supply.Refusing = why; - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - LiveRefusalReport report = await Refused(socket); - - Assert.Equal(why, report.Refusal); - Assert.Null(report.Ceiling); - - WebSocketReceiveResult ending = await Heard(socket); - - Assert.Equal(closed, ending.CloseStatus); - Assert.Equal(LiveRefusalClosures.Because(why), ending.CloseStatusDescription); - Assert.Equal(0, transcoders.Started); - } - - [Fact] - public async Task AFullBudgetReachesTheViewerWithHowFullItIs() - { - TranscodeBudget one = new(new TranscodeBudgetSettings { AtOnce = 1 }); - HeldTranscoders few = new(one); - await using AuthProbe probe = AuthProbe.OverHttp(services => - { - services.AddSingleton(supply); - services.AddSingleton(one); - services.AddSingleton(few); - }); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket seated = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - using WebSocket refused = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p60"), Patiently()); - - LiveRefusalReport report = await Refused(refused); - - Assert.Equal(LiveRefusal.TooManyAlready, report.Refusal); - Assert.Equal(new TranscodeCeiling(1, 1), report.Ceiling); - - WebSocketReceiveResult ending = await Heard(refused); - - Assert.Equal(WebSocketCloseStatus.PolicyViolation, ending.CloseStatus); - Assert.Equal(1, few.Started); - Assert.Equal(1, Sessions(probe).Viewers(EveryFrame)); - } - - [Theory(DisplayName = "BR-PD-008: a wire opened while the channel is announcing two languages on one sound is given the channel of the language asked for")] - [InlineData("", SoundChannel.Left)] - [InlineData("&sound=main", SoundChannel.Left)] - [InlineData("&sound=secondary", SoundChannel.Right)] - public async Task AWireOpenedWhileTwoLanguagesAreOnOneSoundIsGivenTheChannelOfTheLanguageAskedFor( - string asked, - SoundChannel channel) - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - probe.Programmes.Programmes.Add(OnAir(event_: 7, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(-10))); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(new Uri(Handshake("32736", "1024", "720p30") + asked), Patiently()); - - Assert.Equal(SoundPlacement.OneChannelOf(0, channel), Assert.Single(transcoders.Raised).Sound); - } - - [Theory(DisplayName = "BR-PD-008: a wire opened while the channel announces two languages on its main sound beside a second stream is given a channel of the main sound, or the second stream as the third sound")] - [InlineData("", 0, SoundChannel.Left)] - [InlineData("&sound=secondary", 0, SoundChannel.Right)] - [InlineData("&sound=third", 1, null)] - public async Task AWireOpenedWhileTwoLanguagesAreOnTheMainSoundBesideASecondStreamIsGivenTheSoundAskedFor( - string asked, - int ordinal, - SoundChannel? channel) - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - probe.Programmes.Programmes.Add(OnAir(event_: 7, AudioMode.DualMono, sounds: 2, TimeSpan.FromMinutes(-10))); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(new Uri(Handshake("32736", "1024", "720p30") + asked), Patiently()); - - SoundPlacement expected = channel is { } side ? SoundPlacement.OneChannelOf(ordinal, side) : SoundPlacement.WholeStream(ordinal); - - Assert.Equal(expected, Assert.Single(transcoders.Raised).Sound); - } - - [Theory(DisplayName = "BR-PD-008: a wire opened on any other broadcast is given the whole stream of the sound asked for")] - [InlineData(AudioMode.Stereo, 1, "", 0)] - [InlineData(AudioMode.Stereo, 2, "&sound=secondary", 1)] - [InlineData(AudioMode.Surround, 1, "", 0)] - public async Task AWireOpenedOnAnyOtherBroadcastIsGivenTheWholeStreamOfTheSoundAskedFor( - AudioMode audio, - int sounds, - string asked, - int ordinal) - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - probe.Programmes.Programmes.Add(OnAir(event_: 7, audio, sounds, TimeSpan.FromMinutes(-10))); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(new Uri(Handshake("32736", "1024", "720p30") + asked), Patiently()); - - Assert.Equal(SoundPlacement.WholeStream(ordinal), Assert.Single(transcoders.Raised).Sound); - } - - [Fact(DisplayName = "BR-PD-008: what the channel announced before and what it will announce next do not decide how the sound on air is taken")] - public async Task WhatWasAnnouncedBeforeAndWhatComesNextDoNotDecideHowTheSoundOnAirIsTaken() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - probe.Programmes.Programmes.Add(OnAir(event_: 6, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(-70))); - probe.Programmes.Programmes.Add(OnAir(event_: 7, AudioMode.Stereo, sounds: 1, TimeSpan.FromMinutes(-10))); - probe.Programmes.Programmes.Add(OnAir(event_: 8, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(50))); - probe.Programmes.Programmes.Add(OnAir(event_: 9, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(-10), service: 1032)); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - Assert.Equal(SoundPlacement.WholeStream(0), Assert.Single(transcoders.Raised).Sound); - } - - [Fact(DisplayName = "BR-PD-008: a wire opened after the broadcast changed how it carries its sound is not seated on the transcoder raised before it did")] - public async Task AWireOpenedAfterTheBroadcastChangedIsNotSeatedOnTheTranscoderRaisedBefore() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - Programme twoLanguages = OnAir(event_: 7, AudioMode.DualMono, sounds: 1, TimeSpan.FromMinutes(-10)); - - probe.Programmes.Programmes.Add(twoLanguages); - - using WebSocket before = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - probe.Programmes.Programmes.Remove(twoLanguages); - probe.Programmes.Programmes.Add(OnAir(event_: 8, AudioMode.Stereo, sounds: 1, TimeSpan.FromMinutes(-1))); - - using WebSocket after = await Carrying(probe, cookie).ConnectAsync(Handshake("32736", "1024", "720p30"), Patiently()); - - Assert.Equal( - [SoundPlacement.OneChannelOf(0, SoundChannel.Left), SoundPlacement.WholeStream(0)], - transcoders.Raised.Select(raised => raised.Sound)); - Assert.Equal(1, Sessions(probe).Viewers(EveryFrame)); - Assert.Equal(1, Sessions(probe).Viewers(EveryFrame.Taking(SoundPlacement.OneChannelOf(0, SoundChannel.Left)))); - } - - private static Programme OnAir(int event_, AudioMode audio, int sounds, TimeSpan startsIn, int service = 1024) - { - DateTime startsAt = DateTime.UtcNow + startsIn; - - return Programme.Rehydrate( - new ProgrammeId(new NetworkId(32736), new ServiceId(service), new EventId(event_)), - new TransportStreamId(32736), - startsAt, - startsAt + TimeSpan.FromHours(1), - "a programme", - string.Empty, - isShadow: false, - startsAt, - audio: audio, - sounds: sounds); - } - - private static Uri Handshake(string network, string service, string profile) - => new($"ws://localhost{LiveWire.Path}?network={network}&service={service}&profile={profile}"); - - private static CancellationToken Patiently() => new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token; - - private static LiveSessionManager Sessions(AuthProbe probe) - => Assert.IsType(probe.Wired.Services.GetRequiredService()); - - private static WebSocketClient Carrying(AuthProbe probe, string cookie) - { - WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); - - client.ConfigureRequest += request => request.Headers[HeaderNames.Cookie] = cookie; - - return client; - } - - private static async Task Refused(WebSocket socket) - { - LiveFrame said = await Take(socket); - - Assert.Equal(LiveChannel.Control, said.Channel); - - LiveRefusalReading read = LiveRefusalReport.Read(said.Payload.Span); - - Assert.Null(read.Fault); - - return read.Report!; - } - - private static async Task Heard(WebSocket socket) - { - byte[] heard = new byte[64 * 1024]; - - return await socket.ReceiveAsync(new ArraySegment(heard), Patiently()); - } - - private static bool IsProgress(LiveFrame frame) - => frame.Channel is LiveChannel.Control && frame.Payload.Length == LiveStartup.PayloadLength; - - private static async Task TakePastProgress(WebSocket socket) - { - while (true) - { - LiveFrame frame = await Take(socket); - - if (!IsProgress(frame)) - { - return frame; - } - } - } - - private static async Task TakePictureHeader(WebSocket socket) - { - LiveFrame first = await TakePastProgress(socket); - - if (first.Channel is not LiveChannel.CaptionHeader) - { - return first; - } - - LiveFrame afterTheCanvas = await TakePastProgress(socket); - - Assert.Equal(LiveChannel.PictureHeader, afterTheCanvas.Channel); - - return afterTheCanvas; - } - - private static async Task NextProgress(WebSocket socket) - { - while (true) - { - LiveFrame frame = await Take(socket); - - if (IsProgress(frame)) - { - LiveStartupReading read = LiveStartup.ReadProgress(frame.Payload.Span); - - Assert.Null(read.Fault); - - return read.Startup!; - } - } - } - - private static async Task Take(WebSocket socket) - { - byte[] heard = new byte[64 * 1024]; - - WebSocketReceiveResult said = await socket.ReceiveAsync(new ArraySegment(heard), Patiently()); - - Assert.True( - said.MessageType is WebSocketMessageType.Binary, - $"a frame was expected, and the wire said {said.MessageType} ({said.CloseStatusDescription})"); - - LiveFraming framing = LiveFrame.Read(heard.AsSpan(0, said.Count)); - - Assert.NotNull(framing.Frame); - - return framing.Frame; - } - - private static async Task<(IReadOnlyList Heard, WebSocketReceiveResult Ending)> UntilItIsClosed( - WebSocket socket) - { - List heard = []; - byte[] said = new byte[64 * 1024]; - - while (true) - { - WebSocketReceiveResult came = await socket.ReceiveAsync(new ArraySegment(said), Patiently()); - - if (came.MessageType is WebSocketMessageType.Close) - { - return (heard, came); - } - - LiveFraming framing = LiveFrame.Read(said.AsSpan(0, came.Count)); - - Assert.NotNull(framing.Frame); - - heard.Add(framing.Frame); - } - } - - private AuthProbe Wiring() - => AuthProbe.OverHttp(services => - { - services.AddSingleton(supply); - services.AddSingleton(budget); - services.AddSingleton(transcoders); - }); -} diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveSignalTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveSignalTests.cs deleted file mode 100644 index e6a46e562..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/LiveSignalTests.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System.Net; -using System.Net.WebSockets; - -using Carina.Api.Events; -using Carina.Api.Live; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Net.Http.Headers; - -using Puppis.Contracts; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class LiveSignalTests -{ - private static readonly Uri Events = new(AppEventStream.Path, UriKind.Relative); - - private static readonly Uri Handshake = new("ws://localhost" + LiveWire.Path + "?network=32736&service=1024&profile=720p30"); - - private readonly PipedSupply supply = new(); - - private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); - - [Fact] - public async Task AWireRaisingASessionIsSignalledOnTheHubAsLiveAndNothingElseIsCarried() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using HttpResponseMessage listening = await probe.Client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); - await using Stream body = await listening.Content.ReadAsStreamAsync(); - using StreamReader reader = new(body); - - Assert.Equal(HttpStatusCode.OK, listening.StatusCode); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - Assert.Equal([$"event: {AppEvents.Live}", "data"], await NextFrame(reader)); - } - - [Fact] - public async Task TheLastViewerLeavingIsSignalledAgainOnceTheSessionIsGone() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using HttpResponseMessage listening = await probe.Client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); - await using Stream body = await listening.Content.ReadAsStreamAsync(); - using StreamReader reader = new(body); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - Assert.Equal([$"event: {AppEvents.Live}", "data"], await NextFrame(reader)); - - await socket.SendAsync(LiveControls.Frame(LiveControl.Leaving).ToArray(), WebSocketMessageType.Binary, true, Patiently()); - - Assert.Equal([$"event: {AppEvents.Live}", "data"], await NextFrame(reader)); - await Eventually.Happens(() => budget.Running is 0, "the session is torn down once its linger is over"); - } - - [Fact] - public async Task ASecondViewerOnTheSameSessionSignalsNothing() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket first = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - using HttpResponseMessage listening = await probe.Client.GetAsync(Events, HttpCompletionOption.ResponseHeadersRead); - await using Stream body = await listening.Content.ReadAsStreamAsync(); - using StreamReader reader = new(body); - - using WebSocket second = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - Task anything = reader.ReadLineAsync(); - - Assert.NotSame(anything, await Task.WhenAny(anything, Task.Delay(TimeSpan.FromMilliseconds(500)))); - } - - private static CancellationToken Patiently() => new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token; - - private static async Task NextFrame(StreamReader reader) - { - List frame = []; - - while (true) - { - string? line = await reader.ReadLineAsync().WaitAsync(Eventually.Patience); - - Assert.NotNull(line); - - if (line.Length > 0 && line[0] is ':') - { - continue; - } - - if (line.Length is 0) - { - if (frame.Count > 0) - { - return [.. frame]; - } - - continue; - } - - frame.Add(line); - } - } - - private static WebSocketClient Carrying(AuthProbe probe, string cookie) - { - WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); - - client.ConfigureRequest += request => request.Headers[HeaderNames.Cookie] = cookie; - - return client; - } - - private AuthProbe Wiring() - => AuthProbe.OverHttp(services => - { - services.AddSingleton(supply); - services.AddSingleton(budget); - services.AddSingleton(new HeldTranscoders(budget)); - services.AddSingleton(new LiveSessionSettings(linger: TimeSpan.FromMilliseconds(100))); - }); -} diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveStreamExitTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveStreamExitTests.cs deleted file mode 100644 index 772e14194..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/LiveStreamExitTests.cs +++ /dev/null @@ -1,318 +0,0 @@ -using System.Net; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; - -using Carina.Api.Live; -using Carina.Domain.Channels; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Net.Http.Headers; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class LiveStreamExitTests -{ - private const string Watched = "/api/live/32736-1024/stream"; - - private static readonly DateTime At = new(2026, 9, 3, 0, 0, 0, DateTimeKind.Utc); - - private static readonly TimeSpan NoTimeAtAllToSayAnything = TimeSpan.FromMilliseconds(200); - - private readonly PipedSupply supply = new(); - - private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); - - private readonly HeldTranscoders transcoders; - - public LiveStreamExitTests() => transcoders = new HeldTranscoders(budget); - - [Fact] - public async Task APlayerThatOpensTheStreamAgainWithTheSameTicketIsLetInAgain() - { - await using AuthProbe probe = Wiring(); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - HttpResponseMessage first = await OpenedAsync(player); - - Assert.Equal(HttpStatusCode.OK, first.StatusCode); - Assert.Equal(LiveStreamDelivery.MediaType, first.Content.Headers.ContentType?.MediaType); - - first.Dispose(); - - using HttpResponseMessage again = await OpenedAsync(player); - - Assert.Equal(HttpStatusCode.OK, again.StatusCode); - Assert.Equal(LiveStreamDelivery.MediaType, again.Content.Headers.ContentType?.MediaType); - } - - [Fact] - public async Task TheTicketThatOpenedOneChannelOpensNoOther() - { - await using AuthProbe probe = Wiring(); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage opened = await OpenedAsync(player); - - Assert.Equal(HttpStatusCode.OK, opened.StatusCode); - - using HttpResponseMessage another = await player.GetAsync( - new Uri("/api/live/32737-1032/stream", UriKind.Relative), - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Forbidden, another.StatusCode); - Assert.Null(another.Headers.Location); - } - - [Fact] - public async Task AReaderCarryingNoTicketAndNoCookieIsRefusedWithNothingInTheBody() - { - await using AuthProbe probe = Wiring(); - - using HttpClient player = probe.Wired.CreateClient(new WebApplicationFactoryClientOptions - { - BaseAddress = new Uri("http://localhost"), - AllowAutoRedirect = false, - }); - - using HttpResponseMessage refused = await player.GetAsync(Asked(), HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); - Assert.Null(refused.Headers.Location); - Assert.Empty(await refused.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task TheBytesOfTheChannelReachTheReaderAsTheyAre() - { - await using AuthProbe probe = Wiring(); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage opened = await OpenedAsync(player); - - Assert.Equal(HttpStatusCode.OK, opened.StatusCode); - - byte[] sent = Mouthful(); - byte[] twice = [.. sent, .. sent]; - - await supply.Opened[0].WriteAsync(sent); - - await using Stream reading = await opened.Content.ReadAsStreamAsync(); - - Assert.Equal(twice, await ReadAsync(reading, twice.Length)); - } - - [Fact] - public async Task AReaderRidesTheReadingAWireIsWatchingAndNoSecondTunerIsTaken() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - string ticket = await IssuedAsync(probe); - - using System.Net.WebSockets.WebSocket wire = await Wired(probe, cookie).ConnectAsync( - Handshake(), - Patiently()); - - Assert.Equal(1, transcoders.Started); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage opened = await OpenedAsync(player); - - Assert.Equal(HttpStatusCode.OK, opened.StatusCode); - Assert.Equal(1, supply.Asked); - Assert.Single(supply.Opened); - Assert.Equal(1, transcoders.Started); - Assert.Equal(1, budget.Running); - } - - [Fact] - public async Task TheReadingIsHeldOpenWhileTheReaderReadsAndIsLetGoWhenItStops() - { - await using AuthProbe probe = Wiring(); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - HttpResponseMessage opened = await OpenedAsync(player); - - Assert.Equal(HttpStatusCode.OK, opened.StatusCode); - - await Eventually.Happens( - () => supply.Opened[0].HeldOpenUntil.Count > 0, - "the reading is asked to be held open while it is being read"); - - opened.Dispose(); - - await Eventually.Happens(() => supply.Opened[0].Disposed, "the reading is let go once the reader has stopped"); - } - - [Fact] - public async Task AChannelOutsideWhatABroadcastCarriesIsRefusedBeforeAnythingIsTuned() - { - await using AuthProbe probe = Wiring(); - string cookie = await probe.SignedInCookieAsync(); - - using HttpClient watcher = probe.Relaying(cookie); - using HttpResponseMessage refused = await watcher.GetAsync( - new Uri("/api/live/70000-1024/stream", UriKind.Relative), - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode); - Assert.Equal(0, supply.Asked); - } - - [Fact] - public async Task AChannelNoTunerWillReachIsRefusedInWordsAndTheTicketIsGoodAfterwards() - { - supply.Refusing = LiveRefusal.NoTunerFree; - - await using AuthProbe probe = Wiring(); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage refused = await player.GetAsync(Asked(), HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, refused.StatusCode); - Assert.Equal( - LiveRefusalClosures.Because(LiveRefusal.NoTunerFree), - await refused.Content.ReadAsStringAsync()); - - supply.Refusing = null; - - using HttpResponseMessage opened = await OpenedAsync(player); - - Assert.Equal(HttpStatusCode.OK, opened.StatusCode); - } - - [Fact] - public async Task AChannelThatSaysNothingInTimeIsRefusedRatherThanOpenedOnNothing() - { - await using AuthProbe probe = Wiring(NoTimeAtAllToSayAnything); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage refused = await player.GetAsync(Asked(), HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, refused.StatusCode); - Assert.Equal(LiveStreamDelivery.NothingCameInTime, await refused.Content.ReadAsStringAsync()); - } - - private static Uri Asked() => new(Watched, UriKind.Relative); - - private static Uri Handshake() - => new($"ws://localhost{LiveWire.Path}?network=32736&service=1024&profile=720p30"); - - private static CancellationToken Patiently() => new CancellationTokenSource(Eventually.Patience).Token; - - private static byte[] Mouthful() => [.. Enumerable.Range(0, 4_000).Select(at => (byte)(at % 251))]; - - private static WebSocketClient Wired(AuthProbe probe, string cookie) - { - WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); - - client.ConfigureRequest += request => request.Headers[HeaderNames.Cookie] = cookie; - - return client; - } - - private static async Task ReadAsync(Stream reading, int many) - { - byte[] heard = new byte[many]; - int filled = 0; - - while (filled < many) - { - int read = await reading.ReadAsync(heard.AsMemory(filled), Patiently()); - - if (read is 0) - { - break; - } - - filled += read; - } - - return [.. heard.Take(filled)]; - } - - private static HttpClient Carrying(AuthProbe probe, string ticket) - { - HttpClient player = probe.Wired.CreateClient(new WebApplicationFactoryClientOptions - { - BaseAddress = new Uri("http://localhost"), - AllowAutoRedirect = false, - }); - - player.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ticket); - - return player; - } - - private static async Task IssuedAsync(AuthProbe probe) - { - await probe.SignedInAsync(); - - using HttpResponseMessage answer = await probe.Client.PostAsJsonAsync( - new Uri("/api/live/ticket", UriKind.Relative), - new { networkId = 32736, serviceId = 1024 }); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - - using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); - - return read.RootElement.GetProperty("data").GetProperty("inTheClear").GetString()!; - } - - private async Task OpenedAsync(HttpClient player) - { - Task opening = player.GetAsync(Asked(), HttpCompletionOption.ResponseHeadersRead); - - while (!opening.IsCompleted) - { - await supply.FeedAsync(Mouthful()); - await Task.WhenAny(opening, Task.Delay(TimeSpan.FromMilliseconds(20))); - } - - return await opening; - } - - private AuthProbe Wiring() => Wiring(new LiveSessionSettings().LongestRaise); - - private AuthProbe Wiring(TimeSpan longestRaise) - { - HeldServices services = new(); - HeldCandidates candidates = new(); - NetworkId network = new(32736); - ServiceId service = new(1024); - CandidateChannel candidate = CandidateChannel.Discover( - CandidateChannelId.New(), - network, - service, - TuningParameters.Terrestrial(27), - At); - - candidate.Select(SelectionSource.Manual, null, At); - services.Services.Add(BroadcastService.Discover(network, service, "Watched", ServiceCategory.Television, At)); - candidates.Candidates.Add(candidate); - - return AuthProbe.OverHttp(wired => - { - wired.AddSingleton(services); - wired.AddSingleton(candidates); - wired.AddSingleton(supply); - wired.AddSingleton(budget); - wired.AddSingleton(transcoders); - wired.AddSingleton(new LiveSessionSettings( - longestRaise: longestRaise, - betweenHolds: TimeSpan.FromMilliseconds(50), - heldAhead: TimeSpan.FromSeconds(2))); - }); - } -} diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveTicketReachTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveTicketReachTests.cs index c19555e5a..785703ecb 100644 --- a/tests/Carina.Api.Tests/FeatureTest/LiveTicketReachTests.cs +++ b/tests/Carina.Api.Tests/FeatureTest/LiveTicketReachTests.cs @@ -1,19 +1,15 @@ using System.Net; using System.Net.Http.Headers; -using System.Net.Http.Json; using System.Text.Json; using Carina.Api.Events; -using Carina.Api.Live; using Carina.Domain.Channels; using Carina.Domain.Recordings; using Carina.Domain.Streaming; using Carina.TestSupport; using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Net.Http.Headers; namespace Carina.Api.Tests.FeatureTest; @@ -21,10 +17,6 @@ public sealed class LiveTicketReachTests { private static readonly DateTime At = new(2026, 9, 3, 0, 0, 0, DateTimeKind.Utc); - private static readonly Uri Handshake = new("ws://localhost" + LiveWire.Path + "?network=32736&service=1024&profile=720p30"); - - private static readonly Uri Exit = new("/api/live/32736-1024/stream", UriKind.Relative); - private readonly PipedSupply supply = new(); [Theory] @@ -50,126 +42,6 @@ public async Task ALiveTicketOpensNoOtherSurfaceABrowserReachesWithItsCookie(str Assert.Empty(await response.Content.ReadAsByteArrayAsync()); } - [Fact] - public async Task TheOneSurfaceALiveTicketOpensIsTheChannelHandedOverAsItIs() - { - await using AuthProbe probe = Wiring(out _); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage opened = await OpenedAsync(player); - - Assert.Equal(HttpStatusCode.OK, opened.StatusCode); - Assert.Equal(LiveStreamDelivery.MediaType, opened.Content.Headers.ContentType?.MediaType); - } - - [Fact] - public async Task ATicketForOneChannelOpensTheChannelHandedOverOnNoOther() - { - await using AuthProbe probe = Wiring(out _); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage refused = await player.GetAsync( - new Uri("/api/live/32736-1025/stream", UriKind.Relative), - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode); - } - - [Theory(DisplayName = "a player handed the live ticket in the path is handed the channel, whatever name ends the path")] - [InlineData("a-channel%20a-programme.ts")] - [InlineData("")] - [InlineData("a-name.mp4")] - public async Task APlayerHandedTheLiveTicketInThePathIsHandedTheChannel(string name) - { - await using AuthProbe probe = Wiring(out _); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, null); - using HttpResponseMessage opened = await OpenedAsync( - player, - new Uri($"/api/live/32736-1024/with-ticket/{ticket}/{name}", UriKind.Relative)); - - Assert.Equal(HttpStatusCode.OK, opened.StatusCode); - Assert.Equal(LiveStreamDelivery.MediaType, opened.Content.Headers.ContentType?.MediaType); - } - - [Fact(DisplayName = "a live ticket in the path opens the channel it was issued for and no other")] - public async Task ALiveTicketInThePathOpensTheChannelItWasIssuedForAndNoOther() - { - await using AuthProbe probe = Wiring(out _); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, null); - using HttpResponseMessage refused = await player.GetAsync( - new Uri($"/api/live/32736-1025/with-ticket/{ticket}/a-channel.ts", UriKind.Relative), - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode); - } - - [Fact(DisplayName = "something that is not the shape of a ticket in the live path is refused without being sent to a sign-in screen")] - public async Task SomethingThatIsNotATicketInTheLivePathIsRefused() - { - await using AuthProbe probe = Wiring(out _); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage refused = await player.GetAsync( - new Uri("/api/live/32736-1024/with-ticket/short/a-channel.ts", UriKind.Relative), - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); - Assert.Null(refused.Headers.Location); - } - - [Fact(DisplayName = "a live ticket in the query is refused, because it shows as the title in a player")] - public async Task ALiveTicketInTheQueryIsRefused() - { - await using AuthProbe probe = Wiring(out _); - string ticket = await IssuedAsync(probe); - - using HttpClient player = Carrying(probe, null); - using HttpResponseMessage refused = await player.GetAsync( - new Uri($"{Exit}?ticket={ticket}", UriKind.Relative), - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); - } - - [Fact] - public async Task ALiveTicketOfferedOnTheWireHandshakeIsRefusedBeforeItBecomesAWebSocket() - { - await using AuthProbe probe = Wiring(out _); - string ticket = await IssuedAsync(probe); - - WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); - - client.ConfigureRequest += request => request.Headers[HeaderNames.Authorization] = $"Bearer {ticket}"; - - InvalidOperationException refused = await Assert.ThrowsAsync( - () => client.ConnectAsync(Handshake, new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token)); - - Assert.Contains("401", refused.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task ALiveTicketOpensNoRecordingAndIsSpentByTheAttempt() - { - await using AuthProbe probe = Wiring(out Recording recording); - string ticket = await IssuedAsync(probe); - Uri bytes = new($"/api/videos/{recording.Id.Wire}", UriKind.Relative); - - using HttpClient player = Carrying(probe, ticket); - using HttpResponseMessage first = await player.GetAsync(bytes); - using HttpResponseMessage again = await player.GetAsync(bytes); - - Assert.Equal(HttpStatusCode.Forbidden, first.StatusCode); - Assert.Equal(HttpStatusCode.Forbidden, again.StatusCode); - Assert.Null(first.Headers.Location); - } - private static HttpClient Carrying(AuthProbe probe, string? ticket) { HttpClient player = probe.Wired.CreateClient(new WebApplicationFactoryClientOptions @@ -201,23 +73,6 @@ private static async Task IssuedAsync(AuthProbe probe) return read.RootElement.GetProperty("data").GetProperty("inTheClear").GetString()!; } - private static byte[] Mouthful() => [.. Enumerable.Range(0, 4_000).Select(at => (byte)(at % 251))]; - - private Task OpenedAsync(HttpClient player) => OpenedAsync(player, Exit); - - private async Task OpenedAsync(HttpClient player, Uri at) - { - Task opening = player.GetAsync(at, HttpCompletionOption.ResponseHeadersRead); - - while (!opening.IsCompleted) - { - await supply.FeedAsync(Mouthful()); - await Task.WhenAny(opening, Task.Delay(TimeSpan.FromMilliseconds(20))); - } - - return await opening; - } - private AuthProbe Wiring(out Recording recording) { HeldServices services = new(); diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveWireBehindAProxyTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveWireBehindAProxyTests.cs index e9ddc72db..448152fea 100644 --- a/tests/Carina.Api.Tests/FeatureTest/LiveWireBehindAProxyTests.cs +++ b/tests/Carina.Api.Tests/FeatureTest/LiveWireBehindAProxyTests.cs @@ -1,188 +1,9 @@ using System.Net; -using System.Net.Http.Json; -using System.Net.WebSockets; - -using Carina.Api.Authentication; -using Carina.Api.Live; -using Carina.Domain.Auth; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Hosting.Server; -using Microsoft.AspNetCore.Hosting.Server.Features; -using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Net.Http.Headers; namespace Carina.Api.Tests.FeatureTest; -internal sealed class ProxiedKestrelProbe : IAsyncDisposable -{ - public const string Password = "a password long enough"; - - private const string ForwardedProto = "X-Forwarded-Proto"; - - private readonly TestingWebApplicationFactory factory = new(); - - private readonly WebApplicationFactory wired; - - private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); - - private ProxiedKestrelProbe() - { - Transcoders = new HeldTranscoders(budget); - wired = factory.WithWebHostBuilder(builder => - { - builder.UseSetting(TrustedProxies.ProxiesKey, "127.0.0.1 ::1"); - builder.ConfigureTestServices(services => - { - services.AddSingleton(Sessions); - services.AddSingleton(Accounts); - services.AddSingleton(Hasher); - services.AddSingleton(Supply); - services.AddSingleton(new HeldSoundOnAir()); - services.AddSingleton(budget); - services.AddSingleton(Transcoders); - }); - }); - wired.UseKestrel(kestrel => kestrel.Listen(IPAddress.Loopback, 0)); - wired.StartServer(); - Address = wired.Services - .GetRequiredService() - .Features - .Get()! - .Addresses - .Select(address => new Uri(address)) - .First(address => address.Host == IPAddress.Loopback.ToString()); - Accounts.Account = LocalAccount.Bootstrap( - FirstCredentials.Username, - Hasher.Hash(Password, PasswordHashPolicy.Default), - DateTime.UtcNow); - } - - public Uri Address { get; } - - public HeldAuthSessions Sessions { get; } = new(); - - public HeldLocalAccount Accounts { get; } = new(); - - public QuickPasswordHasher Hasher { get; } = new(); - - public PipedSupply Supply { get; } = new(); - - public HeldTranscoders Transcoders { get; } - - public static ProxiedKestrelProbe ListeningOnKestrel() => new(); - - public string PageAt(string scheme) => $"{scheme}://{Address.Authority}"; - - public Uri Wire => new($"ws://{Address.Authority}{LiveWire.Path}?network=32736&service=1024&profile=720p30"); - - public async Task SignedInCookieAsync() - { - using HttpClient client = new() { BaseAddress = Address }; - - client.DefaultRequestHeaders.Add(HeaderNames.Origin, PageAt(Uri.UriSchemeHttp)); - - using HttpResponseMessage response = await client.PostAsJsonAsync( - new Uri("/api/auth/login", UriKind.Relative), - new { username = FirstCredentials.Username, password = Password }); - - response.EnsureSuccessStatusCode(); - - string handed = response.Headers.GetValues(HeaderNames.SetCookie).Single(); - - return handed[..handed.IndexOf(';', StringComparison.Ordinal)]; - } - - public async Task PostThroughTheProxyAsync(string forwardedProto, string origin, string cookie) - { - using HttpClient client = new() { BaseAddress = Address }; - - client.DefaultRequestHeaders.Add(HeaderNames.Origin, origin); - client.DefaultRequestHeaders.Add(HeaderNames.Cookie, cookie); - client.DefaultRequestHeaders.Add(ForwardedProto, forwardedProto); - - return await client.PostAsJsonAsync(new Uri("/api/live/ticket", UriKind.Relative), new { network = 32736, service = 1024 }); - } - - public ClientWebSocket Opening(string cookie, string? forwardedProto, string? origin) - { - ClientWebSocket client = new(); - - client.Options.CollectHttpResponseDetails = true; - client.Options.SetRequestHeader(HeaderNames.Cookie, cookie); - - if (forwardedProto is not null) - { - client.Options.SetRequestHeader(ForwardedProto, forwardedProto); - } - - if (origin is not null) - { - client.Options.SetRequestHeader(HeaderNames.Origin, origin); - } - - return client; - } - - public async ValueTask DisposeAsync() - { - await wired.DisposeAsync(); - await factory.DisposeAsync(); - } -} - public sealed class LiveWireBehindAProxyTests { - [Theory] - [InlineData("wss", "https")] - [InlineData("ws", "http")] - public async Task AWireTheProxyLabelsAsAWebSocketIsOpenedForThePageThatWasServedOverTheMatchingScheme( - string forwardedProto, - string page) - { - await using ProxiedKestrelProbe probe = ProxiedKestrelProbe.ListeningOnKestrel(); - string cookie = await probe.SignedInCookieAsync(); - - using ClientWebSocket client = probe.Opening(cookie, forwardedProto, probe.PageAt(page)); - - await client.ConnectAsync(probe.Wire, Patiently()); - - Assert.Equal(WebSocketState.Open, client.State); - Assert.Equal(HttpStatusCode.SwitchingProtocols, client.HttpStatusCode); - - LiveFrame first = await Take(client); - - Assert.Equal(LiveChannel.Control, first.Channel); - Assert.Null(LiveStartup.ReadProgress(first.Payload.Span).Fault); - Assert.Equal(1, probe.Transcoders.Started); - } - - [Theory] - [InlineData("wss", "https://elsewhere.example")] - [InlineData("wss", "http")] - [InlineData("ws", "https")] - [InlineData("ftp", "http")] - public async Task AWireFromAPageThisAppDidNotServeIsStillRefusedWhateverTheProxyLabelsIt( - string forwardedProto, - string origin) - { - await using ProxiedKestrelProbe probe = ProxiedKestrelProbe.ListeningOnKestrel(); - string cookie = await probe.SignedInCookieAsync(); - string page = origin.Contains("://", StringComparison.Ordinal) ? origin : probe.PageAt(origin); - - using ClientWebSocket client = probe.Opening(cookie, forwardedProto, page); - - await Assert.ThrowsAsync(() => client.ConnectAsync(probe.Wire, Patiently())); - - Assert.Equal(HttpStatusCode.Forbidden, client.HttpStatusCode); - Assert.Equal(0, probe.Transcoders.Started); - } - [Fact] public async Task ARequestThatChangesStateBehindTheSameProxyIsStillAnsweredForThePageItNames() { @@ -201,21 +22,4 @@ public async Task ARequestThatChangesStateBehindTheSameProxyIsStillAnsweredForTh Assert.NotEqual(HttpStatusCode.Forbidden, fromThisPage.StatusCode); Assert.Equal(HttpStatusCode.Forbidden, fromElsewhere.StatusCode); } - - private static CancellationToken Patiently() => new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token; - - private static async Task Take(WebSocket socket) - { - byte[] heard = new byte[64 * 1024]; - - WebSocketReceiveResult said = await socket.ReceiveAsync(new ArraySegment(heard), Patiently()); - - Assert.Equal(WebSocketMessageType.Binary, said.MessageType); - - LiveFraming framing = LiveFrame.Read(heard.AsSpan(0, said.Count)); - - Assert.NotNull(framing.Frame); - - return framing.Frame; - } } diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveWireOverKestrelTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveWireOverKestrelTests.cs deleted file mode 100644 index b4882a225..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/LiveWireOverKestrelTests.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Net.WebSockets; - -using Carina.Api.Live; -using Carina.Domain.Streaming; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class LiveWireOverKestrelTests -{ - private static readonly byte[] Picture = [0x0a, 0x0b, 0x0c]; - - [Fact] - public async Task AViewerThatStopsReadingOverRealKestrelIsRecordedAsHavingStoppedReading() - { - var held = new HeldLiveSource(); - await using LiveKestrelHost host = await LiveKestrelHost.StartAsync( - held, - new LiveWireSettings( - betweenPings: TimeSpan.FromSeconds(30), - writePatience: TimeSpan.FromMilliseconds(300))); - - using var client = new ClientWebSocket(); - await client.ConnectAsync(host.Wire, Patiently()); - - held.Send(new LiveFrame(LiveChannel.Picture, LivePts.Start, new byte[8 * 1024 * 1024])); - - LiveDeparture departure = await host.DepartureAsync(Patiently()); - - Assert.Equal(LiveDeparture.ViewerStoppedReading, departure); - - WebSocketException cut = await Assert.ThrowsAsync(() => ReadUntilClose(client)); - - Assert.Equal(WebSocketError.ConnectionClosedPrematurely, cut.WebSocketErrorCode); - Assert.Null(client.CloseStatus); - } - - [Fact] - public async Task TheSourceRunningOutIsReadByARealClientAsACleanCloseItCanNameTheReasonOf() - { - var held = new HeldLiveSource(); - await using LiveKestrelHost host = await LiveKestrelHost.StartAsync(held); - - using var client = new ClientWebSocket(); - await client.ConnectAsync(host.Wire, Patiently()); - - held.Send(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); - held.NoMore(); - - WebSocketReceiveResult ending = await ReadUntilClose(client); - - Assert.Equal(WebSocketMessageType.Close, ending.MessageType); - Assert.Equal(WebSocketCloseStatus.NormalClosure, client.CloseStatus); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), client.CloseStatusDescription); - Assert.Equal(LiveDeparture.SourceEnded, await host.DepartureAsync(Patiently())); - Assert.Equal( - 1L, - host.Tally.Counted.Single(counted => counted.Departure == LiveDeparture.SourceEnded).Times); - Assert.NotNull( - host.Tally.Counted.Single(counted => counted.Departure == LiveDeparture.SourceEnded).Longest); - } - - private static async Task ReadUntilClose(ClientWebSocket client) - { - byte[] heard = new byte[64 * 1024]; - - while (true) - { - WebSocketReceiveResult said = await client.ReceiveAsync(new ArraySegment(heard), Patiently()); - - if (said.MessageType is WebSocketMessageType.Close) - { - return said; - } - } - } - - private static CancellationToken Patiently() => new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token; -} diff --git a/tests/Carina.Api.Tests/FeatureTest/LiveWireTests.cs b/tests/Carina.Api.Tests/FeatureTest/LiveWireTests.cs deleted file mode 100644 index 355500059..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/LiveWireTests.cs +++ /dev/null @@ -1,586 +0,0 @@ -using System.Net; -using System.Net.WebSockets; - -using Carina.Api.Live; -using Carina.Domain.Channels; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; - -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Net.Http.Headers; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class LiveWireTests -{ - private static readonly Uri Wire = new(LiveWire.Path, UriKind.Relative); - - private static readonly Uri Handshake = new("ws://localhost" + LiveWire.Path + "?network=32736&service=1024&profile=720p30"); - - private static readonly byte[] Picture = [0x0a, 0x0b, 0x0c]; - - [Fact] - public async Task TheWireIsRefusedToACallerCarryingNoCookie() - { - await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); - - using HttpResponseMessage response = await probe.Client.GetAsync( - Wire, - HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Empty(await response.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task AHandshakeCarryingNoCookieIsRefusedBeforeItBecomesAWebSocket() - { - await using AuthProbe probe = AuthProbe.OverHttp().WithAnAccount(); - - InvalidOperationException refused = await Assert.ThrowsAsync( - () => probe.Wired.Server.CreateWebSocketClient().ConnectAsync(Handshake, Patiently())); - - Assert.Contains("401", refused.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task AHandshakeCarryingARevokedSessionIsRefusedTheSameWay() - { - await using AuthProbe probe = AuthProbe.OverHttp(); - string cookie = await probe.SignedInCookieAsync(); - - probe.Sessions.Sessions[^1].Revoke(DateTime.UtcNow); - - InvalidOperationException refused = await Assert.ThrowsAsync( - () => Carrying(probe, cookie).ConnectAsync(Handshake, Patiently())); - - Assert.Contains("401", refused.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task AskingForTheWireWithoutAskingToUpgradeIsRefused() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - - await probe.SignedInAsync(); - - using HttpResponseMessage response = await probe.Client.GetAsync(Wire); - - Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - } - - [Theory] - [InlineData("http://elsewhere.invalid")] - [InlineData("null")] - public async Task AHandshakeNamingAnotherOriginIsRefused(string origin) - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - WebSocketClient client = Carrying(probe, cookie); - - client.ConfigureRequest += request => request.Headers[HeaderNames.Origin] = origin; - - InvalidOperationException refused = await Assert.ThrowsAsync( - () => client.ConnectAsync(Handshake, Patiently())); - - Assert.Contains("403", refused.Message, StringComparison.Ordinal); - } - - [Theory] - [InlineData("")] - [InlineData("?network=32736&service=1024")] - [InlineData("?network=32736&service=1024&profile=hls")] - [InlineData("?network=32736&service=1024&profile=720P30")] - [InlineData("?network=thirty&service=1024&profile=720p30")] - [InlineData("?network=32736&service=1024&profile=720p30&format=hevc")] - [InlineData("?network=32736&service=1024&profile=720p30&format=h264&format=h265")] - public async Task AHandshakeNamingNoKeyOrAProfileOffTheListIsRefusedBeforeItBecomesAWebSocket(string query) - { - HeldLiveSource held = new(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - InvalidOperationException refused = await Assert.ThrowsAsync( - () => Carrying(probe, cookie).ConnectAsync(new Uri("ws://localhost" + LiveWire.Path + query), Patiently())); - - Assert.Contains("400", refused.Message, StringComparison.Ordinal); - Assert.Empty(Seating(probe).Asked); - } - - [Theory(DisplayName = "a handshake asking for a format this machine does not transcode in is refused before it becomes a WebSocket, and no tuner is asked for")] - [InlineData("h265")] - [InlineData("av1")] - public async Task AHandshakeAskingForAFormatThisMachineDoesNotTranscodeInIsRefused(string format) - { - HeldLiveSource held = new(); - await using AuthProbe probe = Wiring(held, formats: [VideoCodec.H264]); - string cookie = await probe.SignedInCookieAsync(); - - InvalidOperationException refused = await Assert.ThrowsAsync( - () => Carrying(probe, cookie).ConnectAsync( - new Uri("ws://localhost" + LiveWire.Path + "?network=32736&service=1024&profile=720p30&format=" + format), - Patiently())); - - Assert.Contains("400", refused.Message, StringComparison.Ordinal); - Assert.Empty(Seating(probe).Asked); - Assert.Empty(Seating(probe).Reached); - } - - [Theory(DisplayName = "a handshake asking for a format this machine transcodes in is seated on a key in that format")] - [InlineData("h265", VideoCodec.H265)] - [InlineData("av1", VideoCodec.Av1)] - public async Task AHandshakeAskingForAFormatThisMachineTranscodesInIsSeatedOnAKeyInThatFormat(string named, VideoCodec format) - { - HeldLiveSource held = new(); - await using AuthProbe probe = Wiring(held, formats: VideoCodecs.InOrder); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync( - new Uri("ws://localhost" + LiveWire.Path + "?network=32736&service=1024&profile=720p30&format=" + named), - Patiently()); - - LiveSessionKey asked = Assert.Single(Seating(probe).Asked); - - Assert.Equal(format, asked.Format); - Assert.Equal(LiveProfile.Hd30, asked.Profile); - } - - [Fact(DisplayName = "a handshake naming no format is seated on a key in H.264, as every wire was")] - public async Task AHandshakeNamingNoFormatIsSeatedOnAKeyInH264() - { - HeldLiveSource held = new(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - Assert.Equal(VideoCodec.H264, Assert.Single(Seating(probe).Asked).Format); - } - - [Fact] - public async Task TheHeaderAndThePicturesArriveInTheOrderTheSourcePutThemIn() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - held.Send(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Picture)); - held.Send(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); - held.Send(new LiveFrame(LiveChannel.Sound, LivePts.Of(180_000UL), Picture)); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(Handshake, Patiently()); - - LiveFrame first = await Take(socket); - LiveFrame second = await Take(socket); - LiveFrame third = await Take(socket); - - Assert.Equal(LiveChannel.PictureHeader, first.Channel); - Assert.Equal(LivePts.Start, first.Pts); - Assert.Equal(LiveChannel.Picture, second.Channel); - Assert.Equal(LivePts.Of(90_000UL), second.Pts); - Assert.Equal(LiveChannel.Sound, third.Channel); - Assert.Equal(Picture, third.Payload.ToArray()); - } - - [Fact] - public async Task AWireThatIsAlreadyOpenKeepsCarryingFramesAfterItsSessionIsEnded() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(Handshake, Patiently()); - - probe.Sessions.Sessions[^1].Revoke(DateTime.UtcNow); - - held.Send(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); - - LiveFrame carried = await Take(socket); - - Assert.Equal(LiveChannel.Picture, carried.Channel); - Assert.Equal(Picture, carried.Payload.ToArray()); - } - - [Fact] - public async Task APingArrivesOnAWireThatIsCarryingNothing() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held, new LiveWireSettings(betweenPings: TimeSpan.FromMilliseconds(50))); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(Handshake, Patiently()); - - LiveFrame ping = await Take(socket); - - Assert.Equal(LiveChannel.Control, ping.Channel); - Assert.Equal([(byte)LiveControl.Ping], ping.Payload.ToArray()); - } - - [Fact] - public async Task AViewerSayingItIsLeavingIsClosedNormallyAndLetGoOf() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(Handshake, Patiently()); - - await Say(socket, LiveControl.Leaving); - - WebSocketReceiveResult ending = await Heard(socket); - - Assert.Equal(WebSocketMessageType.Close, ending.MessageType); - - Assert.Equal(WebSocketCloseStatus.NormalClosure, ending.CloseStatus); - Assert.Equal(LiveDepartures.Because(LiveDeparture.ViewerLeft), ending.CloseStatusDescription); - await Until(() => held.LetGo); - } - - [Fact] - public async Task AViewerSayingSomethingTheWireDoesNotUnderstandIsToldWhyItIsClosed() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(Handshake, Patiently()); - - await socket.SendAsync( - "seek 42"u8.ToArray(), - WebSocketMessageType.Text, - true, - Patiently()); - - WebSocketReceiveResult ending = await Heard(socket); - - Assert.Equal(WebSocketMessageType.Close, ending.MessageType); - - Assert.Equal(WebSocketCloseStatus.InvalidPayloadData, ending.CloseStatus); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SaidSomethingUnknown), ending.CloseStatusDescription); - } - - [Fact] - public async Task TheSourceRunningOutClosesTheWireAndSaysSo() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(Handshake, Patiently()); - - held.NoMore(); - - LiveFrame said = await Take(socket); - - Assert.Equal(LiveChannel.Control, said.Channel); - Assert.Equal( - LiveDepartures.Ending(LiveDeparture.SourceEnded), - LiveEndingReport.Read(said.Payload.Span).Report!.Why); - - WebSocketReceiveResult ending = await Heard(socket); - - Assert.Equal(WebSocketMessageType.Close, ending.MessageType); - - Assert.Equal(WebSocketCloseStatus.NormalClosure, ending.CloseStatus); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), ending.CloseStatusDescription); - } - - [Fact] - public async Task AViewerJoiningAFanoutLateIsHandedTheHeaderBeforeTheNextPicture() - { - LiveFanout fanout = new(new LiveFanoutSettings()); - await using AuthProbe probe = Wiring(fanout); - string cookie = await probe.SignedInCookieAsync(); - - fanout.Publish(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Picture)); - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); - - using WebSocket socket = await Carrying(probe, cookie) - .ConnectAsync(Handshake, Patiently()); - - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(180_000UL), Picture)); - - LiveFrame first = await Take(socket); - LiveFrame second = await Take(socket); - - Assert.Equal(LiveChannel.PictureHeader, first.Channel); - Assert.Equal(LiveChannel.Picture, second.Channel); - Assert.Equal(LivePts.Of(180_000UL), second.Pts); - Assert.Equal(1, fanout.Viewers); - } - - [Fact] - public async Task TwoWiresOnOneFanoutAreBothCarriedAndBothClosedWhenItEnds() - { - LiveFanout fanout = new(new LiveFanoutSettings()); - await using AuthProbe probe = Wiring(fanout); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket one = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - using WebSocket another = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); - - Assert.Equal(LivePts.Of(90_000UL), (await Take(one)).Pts); - Assert.Equal(LivePts.Of(90_000UL), (await Take(another)).Pts); - - fanout.End(); - - Assert.Equal(LiveChannel.Control, (await Take(one)).Channel); - Assert.Equal(LiveChannel.Control, (await Take(another)).Channel); - - WebSocketReceiveResult oneEnding = await Heard(one); - WebSocketReceiveResult anotherEnding = await Heard(another); - - Assert.Equal(WebSocketCloseStatus.NormalClosure, oneEnding.CloseStatus); - Assert.Equal(WebSocketCloseStatus.NormalClosure, anotherEnding.CloseStatus); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), oneEnding.CloseStatusDescription); - await Until(() => fanout.Viewers is 0); - } - - [Fact] - public async Task AWireOnAFanoutThatHasEndedIsToldSoOnTheControlChannelAndClosed() - { - LiveFanout fanout = new(new LiveFanoutSettings()); - await using AuthProbe probe = Wiring(fanout); - string cookie = await probe.SignedInCookieAsync(); - - fanout.End(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - LiveFrame said = await Take(socket); - - Assert.Equal(LiveChannel.Control, said.Channel); - - LiveRefusalReading read = LiveRefusalReport.Read(said.Payload.Span); - - Assert.Null(read.Fault); - Assert.Equal(LiveRefusal.TranscoderWouldNotStart, read.Report!.Refusal); - - WebSocketReceiveResult ending = await Heard(socket); - - Assert.Equal(WebSocketMessageType.Close, ending.MessageType); - Assert.Equal(WebSocketCloseStatus.InternalServerError, ending.CloseStatus); - Assert.Equal(LiveRefusalClosures.Because(LiveRefusal.TranscoderWouldNotStart), ending.CloseStatusDescription); - } - - [Fact] - public async Task TheKeyInTheHandshakeIsTheKeyThatIsJoined() - { - HeldLiveSource held = new(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - Assert.Equal( - [new LiveSessionKey(new NetworkId(32736), new ServiceId(1024), LiveProfile.Hd30)], - Seating(probe).Asked); - } - - [Fact] - public async Task TheChannelInTheHandshakeIsReachedForUntilItsSessionIsJoined() - { - HeldLiveSource held = new(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - Assert.Equal([new LiveChannelKey(new NetworkId(32736), new ServiceId(1024))], Seating(probe).Reached); - Assert.True(Seating(probe).ReachHeldWhileJoining); - Assert.Equal(1, Seating(probe).ReachesLetGo); - } - - [Fact] - public async Task TheChannelIsAlreadyBeingReachedForWhenTheSoundOnAirIsLookedUp() - { - SeatingAt seating = new(new HeldLiveSource()); - SoundAskedWhileReaching sound = new(() => seating.HoldsAReach); - await using AuthProbe probe = AuthProbe.OverHttp(services => - { - services.AddSingleton(seating); - services.AddSingleton(sound); - }); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - Assert.Equal(1, sound.Asked); - Assert.True(sound.AskedWhileReaching); - } - - [Fact] - public async Task AWireThatAViewerLeftIsCountedAsTheViewerLeaving() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - Assert.Equal(0L, Everything(probe)); - - await Say(socket, LiveControl.Leaving); - await Heard(socket); - await Until(() => Counted(probe, LiveDeparture.ViewerLeft) is 1L); - - Assert.Equal(1L, Everything(probe)); - } - - [Fact] - public async Task AWireEndedByWhatTheViewerSaidIsCountedUnderThatAndNotUnderLeaving() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - await socket.SendAsync("seek 42"u8.ToArray(), WebSocketMessageType.Text, true, Patiently()); - await Heard(socket); - await Until(() => Counted(probe, LiveDeparture.SaidSomethingUnknown) is 1L); - - Assert.Equal(0L, Counted(probe, LiveDeparture.ViewerLeft)); - } - - [Fact] - public async Task AWireEndedBecauseTheSourceRanOutIsCountedAsTheSourceEnding() - { - var held = new HeldLiveSource(); - await using AuthProbe probe = Wiring(held); - string cookie = await probe.SignedInCookieAsync(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - held.NoMore(); - - await Take(socket); - await Heard(socket); - await Until(() => Counted(probe, LiveDeparture.SourceEnded) is 1L); - - Assert.Equal(1L, Everything(probe)); - } - - [Fact] - public async Task AWireThatWasNeverSeatedIsNotCountedAsHavingEnded() - { - LiveFanout fanout = new(new LiveFanoutSettings()); - await using AuthProbe probe = Wiring(fanout); - string cookie = await probe.SignedInCookieAsync(); - - fanout.End(); - - using WebSocket socket = await Carrying(probe, cookie).ConnectAsync(Handshake, Patiently()); - - await Take(socket); - await Heard(socket); - await Stays(() => Everything(probe) is 0L); - } - - private static long Counted(AuthProbe probe, LiveDeparture departure) - => Departures(probe).Counted.Single(counted => counted.Departure == departure).Times; - - private static long Everything(AuthProbe probe) => Departures(probe).Counted.Sum(counted => counted.Times); - - private static LiveDepartureTally Departures(AuthProbe probe) - => probe.Wired.Services.GetRequiredService().Read(); - - private static CancellationToken Patiently() => new CancellationTokenSource(TimeSpan.FromSeconds(20)).Token; - - private static AuthProbe Wiring( - ILiveWireSource source, - LiveWireSettings? settings = null, - IReadOnlyList? formats = null) - => AuthProbe.OverHttp(services => - { - services.AddSingleton(new SeatingAt(source)); - - if (settings is not null) - { - services.AddSingleton(settings); - } - - if (formats is not null) - { - services.AddSingleton(new AlreadyChosen(LiveEncoder.Vaapi, formats)); - } - }); - - private static SeatingAt Seating(AuthProbe probe) - => Assert.IsType(probe.Wired.Services.GetRequiredService()); - - private static WebSocketClient Carrying(AuthProbe probe, string cookie) - { - WebSocketClient client = probe.Wired.Server.CreateWebSocketClient(); - - client.ConfigureRequest += request => request.Headers[HeaderNames.Cookie] = cookie; - - return client; - } - - private static Task Say(WebSocket socket, LiveControl said) - => socket.SendAsync( - LiveControls.Frame(said).ToArray(), - WebSocketMessageType.Binary, - true, - Patiently()); - - private static async Task Take(WebSocket socket) - { - byte[] heard = new byte[64 * 1024]; - - WebSocketReceiveResult said = await socket.ReceiveAsync( - new ArraySegment(heard), - Patiently()); - - LiveFraming framing = LiveFrame.Read(heard.AsSpan(0, said.Count)); - - Assert.Null(framing.Fault); - - return framing.Frame!; - } - - private static async Task Stays(Func so) - { - for (int tries = 0; tries < 40; tries++) - { - Assert.True(so(), "What was to stay as it was did not."); - - await Task.Delay(25); - } - } - - private static async Task Until(Func settled) - { - for (int tries = 0; tries < 200; tries++) - { - if (settled()) - { - return; - } - - await Task.Delay(25); - } - - Assert.Fail("The wire never finished what was expected of it."); - } - - private static async Task Heard(WebSocket socket) - { - byte[] heard = new byte[64 * 1024]; - - return await socket.ReceiveAsync(new ArraySegment(heard), Patiently()); - } -} diff --git a/tests/Carina.Api.Tests/FeatureTest/LongLivedPlaybackTests.cs b/tests/Carina.Api.Tests/FeatureTest/LongLivedPlaybackTests.cs deleted file mode 100644 index 3bafd43e3..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/LongLivedPlaybackTests.cs +++ /dev/null @@ -1,278 +0,0 @@ -using System.Net; -using System.Net.Http.Headers; - -using Carina.Domain.Auth; -using Carina.Domain.Channels; -using Carina.Domain.Encodings; -using Carina.Domain.Playback; -using Carina.Domain.Recordings; -using Carina.Domain.Streaming; -using Carina.Domain.Viewing; -using Carina.TestSupport; - -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; - -namespace Carina.Api.Tests.FeatureTest; - -internal sealed class GatedStream(byte[] bytes) : Stream -{ - private readonly SemaphoreSlim released = new(0); - - private long position; - - private int reach; - - public override bool CanRead => true; - - public override bool CanSeek => true; - - public override bool CanWrite => false; - - public override long Length => bytes.Length; - - public override long Position - { - get => position; - set => position = value; - } - - public void Release(int upTo) - { - Volatile.Write(ref reach, upTo); - released.Release(); - } - - public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) - { - while (position >= Volatile.Read(ref reach) && position < bytes.Length) - { - await released.WaitAsync(cancellationToken); - } - - int take = (int)Math.Min(Math.Min(buffer.Length, Volatile.Read(ref reach) - position), bytes.Length - position); - - if (take <= 0) - { - return 0; - } - - bytes.AsMemory((int)position, take).CopyTo(buffer); - position += take; - - return take; - } - - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); - - public override int Read(byte[] buffer, int offset, int count) - => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); - - public override long Seek(long offset, SeekOrigin origin) - { - position = origin switch - { - SeekOrigin.Begin => offset, - SeekOrigin.Current => position + offset, - _ => bytes.Length + offset, - }; - - return position; - } - - public override void Flush() - { - } - - public override void SetLength(long value) => throw new NotSupportedException(); - - public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - - protected override void Dispose(bool disposing) - { - if (disposing) - { - released.Dispose(); - } - - base.Dispose(disposing); - } -} - -internal sealed class GatedPlaybackFiles(byte[] bytes) : IPlaybackFileStore -{ - public GatedStream Handed { get; } = new(bytes); - - public PlaybackFileSearch Find(OutputRoot root, RecordingFileName fileName) - => PlaybackFileSearch.Of(new PlaybackFile(root, fileName, bytes.Length)); - - public PlaybackFileOpening OpenRead(PlaybackFile file) => PlaybackFileOpening.Of(Handed); - - public StreamSource? SourceOf(PlaybackFile file) => null; -} - -internal sealed class GatedViewing(GatedStream output) : IOnTheFlyViewing -{ - public OnTheFlyStanding Standing { get; } = new( - TimeSpan.Zero, - TimeSpan.FromMilliseconds(1), - LiveProfile.Hd30, - LiveEncoderChoice.Asked(LiveEncoder.Software), - attributesWereMeasured: true, - 1, - 2); - - public Stream Output => output; - - public Task Completion { get; } = Task.FromResult(TranscoderExit.Finished()); - - public ValueTask DisposeAsync() => ValueTask.CompletedTask; -} - -internal sealed class GatedOnTheFlyPlayer(byte[] bytes) : IOnTheFlyPlayer -{ - public GatedStream Handed { get; } = new(bytes); - - public Task StartAsync( - PlaybackFile file, - ServiceId service, - TimeSpan from, - LiveProfile? profile, - VideoCodec format, - SoundPlacement sound, - CancellationToken cancellationToken) - => Task.FromResult(OnTheFlyStart.Started(new GatedViewing(Handed))); - - public Task SoundsAsync( - PlaybackFile file, - ServiceId service, - CancellationToken cancellationToken) - => Task.FromResult(CarriedSounds.Counted(1)); -} - -public sealed class LongLivedPlaybackTests -{ - private const int Size = 256 * 1024; - - private const int FirstHalf = Size / 2; - - private static readonly byte[] Written = [.. Enumerable.Range(0, Size).Select(index => (byte)(index % 251))]; - - [Fact] - public async Task ARecordingAlreadyBeingHandedOverKeepsFlowingAfterItsSessionIsEnded() - { - GatedPlaybackFiles files = new(Written); - await using AuthProbe probe = Wiring(files, new GatedOnTheFlyPlayer(Written), out Recording recording); - AuthSession session = await probe.SignedInAsync(); - - files.Handed.Release(FirstHalf); - - using HttpResponseMessage response = await probe.Client.GetAsync( - Bytes(recording), - HttpCompletionOption.ResponseHeadersRead); - await using Stream body = await response.Content.ReadAsStreamAsync(); - byte[] heard = new byte[Size]; - - await body.ReadExactlyAsync(heard.AsMemory(0, FirstHalf)); - - session.Revoke(DateTime.UtcNow); - files.Handed.Release(Size); - - await body.ReadExactlyAsync(heard.AsMemory(FirstHalf)); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(Written, heard); - } - - [Fact] - public async Task TheNextRequestForTheRecordingAfterThatSessionEndedIsRefused() - { - await using AuthProbe probe = Wiring(new GatedPlaybackFiles(Written), new GatedOnTheFlyPlayer(Written), out Recording recording); - AuthSession session = await probe.SignedInAsync(); - - session.Revoke(DateTime.UtcNow); - - using HttpResponseMessage response = await probe.Client.GetAsync(Bytes(recording), HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Null(response.Headers.Location); - Assert.Empty(await response.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task APictureAlreadyBeingTranscodedKeepsFlowingAfterItsSessionIsEnded() - { - GatedOnTheFlyPlayer player = new(Written); - await using AuthProbe probe = Wiring(new GatedPlaybackFiles(Written), player, out Recording recording); - AuthSession session = await probe.SignedInAsync(); - - player.Handed.Release(FirstHalf); - - using HttpRequestMessage asking = Playing(recording); - using HttpResponseMessage response = await probe.Client.SendAsync(asking, HttpCompletionOption.ResponseHeadersRead); - await using Stream body = await response.Content.ReadAsStreamAsync(); - byte[] heard = new byte[Size]; - - await body.ReadExactlyAsync(heard.AsMemory(0, FirstHalf)); - - session.Revoke(DateTime.UtcNow); - player.Handed.Release(Size); - - await body.ReadExactlyAsync(heard.AsMemory(FirstHalf)); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("video/mp4", response.Content.Headers.ContentType?.MediaType); - Assert.Equal(Written, heard); - } - - [Fact] - public async Task TheNextPictureAskedForAfterThatSessionEndedIsRefused() - { - await using AuthProbe probe = Wiring(new GatedPlaybackFiles(Written), new GatedOnTheFlyPlayer(Written), out Recording recording); - AuthSession session = await probe.SignedInAsync(); - - session.Revoke(DateTime.UtcNow); - - using HttpRequestMessage asking = Playing(recording); - using HttpResponseMessage response = await probe.Client.SendAsync(asking, HttpCompletionOption.ResponseHeadersRead); - - Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); - Assert.Null(response.Headers.Location); - Assert.Empty(await response.Content.ReadAsByteArrayAsync()); - } - - private static Uri Bytes(Recording recording) => new($"/api/videos/{recording.Id.Wire}", UriKind.Relative); - - private static HttpRequestMessage Playing(Recording recording) - { - HttpRequestMessage asking = new(HttpMethod.Get, new Uri($"/api/videos/{recording.Id.Wire}/play", UriKind.Relative)); - - asking.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); - - return asking; - } - - private static AuthProbe Wiring(IPlaybackFileStore files, IOnTheFlyPlayer player, out Recording recording) - { - HeldRecordings recordings = new(); - - recording = RecordingFeature.Begin(RecordingId.New()); - recording.Wrote(TimeSpan.FromMinutes(30)); - recording.Abort(RecordingFeature.Noon.AddMinutes(30)); - recording.Settle(RecordingOutcome.Complete, Size, RecordingFeature.Noon.AddMinutes(30)); - recordings.Recordings.Add(recording); - - return AuthProbe.OverHttp(services => - { - services.RemoveAll(); - services.RemoveAll(); - services.AddSingleton(recordings); - services.AddSingleton(new HeldEncodeJobs()); - services.AddSingleton(new HeldEncodeProfiles()); - services.AddSingleton(new HeldPlaybackPositions()); - services.AddSingleton(files); - services.AddSingleton(player); - }); - } -} diff --git a/tests/Carina.Api.Tests/FeatureTest/PlayDeliveryTests.cs b/tests/Carina.Api.Tests/FeatureTest/PlayDeliveryTests.cs deleted file mode 100644 index b9f80e8a8..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/PlayDeliveryTests.cs +++ /dev/null @@ -1,1348 +0,0 @@ -using System.IO.Pipelines; -using System.Net; -using System.Net.Http.Headers; -using System.Net.Http.Json; -using System.Text.Json; - -using Carina.Api.Playback; -using Carina.Domain.Auth; -using Carina.Domain.Base; -using Carina.Domain.Channels; -using Carina.Domain.Encodings; -using Carina.Domain.Integrity; -using Carina.Domain.Playback; -using Carina.Domain.Recordings; -using Carina.Domain.Reservations; -using Carina.Domain.Streaming; -using Carina.Domain.Viewing; -using Carina.TestSupport; - -using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Hosting; - -using IRecordingDetectionRepository = Carina.Domain.Segments.IRecordingDetectionRepository; -using ISegmentModelVersionRepository = Carina.Domain.Segments.ISegmentModelVersionRepository; -using ISegmentSettingsRepository = Carina.Domain.Segments.ISegmentSettingsRepository; - -namespace Carina.Api.Tests.FeatureTest; - -internal sealed class HeldViewing : IOnTheFlyViewing -{ - private readonly Pipe? endless; - - private int letGo; - - public HeldViewing(OnTheFlyStanding standing, byte[] picture, TranscoderExit? exit = null, bool writesOn = false) - { - Standing = standing; - Completion = Task.FromResult(exit ?? TranscoderExit.Finished()); - - if (!writesOn) - { - Output = new MemoryStream(picture); - - return; - } - - endless = new Pipe(); - endless.Writer.WriteAsync(picture).AsTask().GetAwaiter().GetResult(); - Output = endless.Reader.AsStream(); - } - - public OnTheFlyStanding Standing { get; } - - public Stream Output { get; } - - public Task Completion { get; } - - public bool WasLetGo => Volatile.Read(ref letGo) is 1; - - public ValueTask DisposeAsync() - { - Volatile.Write(ref letGo, 1); - endless?.Writer.Complete(); - - if (endless is null) - { - Output.Dispose(); - } - - return ValueTask.CompletedTask; - } -} - -internal sealed class HeldOnTheFlyPlayer : IOnTheFlyPlayer -{ - public byte[] Picture { get; set; } = [.. Enumerable.Range(0, 3_000).Select(index => (byte)(index % 251))]; - - public OnTheFlyRefusal? Refuses { get; set; } - - public int Running { get; set; } = 1; - - public int AtOnce { get; set; } = 2; - - public TimeSpan Waited { get; set; } = TimeSpan.FromMilliseconds(138); - - public LiveEncoder Machine { get; set; } = LiveEncoder.Software; - - public List AskedFrom { get; } = []; - - public List AskedFor { get; } = []; - - public List AskedIn { get; } = []; - - public List AskedOf { get; } = []; - - public List AskedWith { get; } = []; - - public List Opened { get; } = []; - - public int Sounds { get; set; } = 1; - - public string? SoundsCannotBeRead { get; set; } - - public int AskedWhatItCarries { get; private set; } - - public HeldViewing? Handed { get; private set; } - - public List EveryHanded { get; } = []; - - public TranscoderExit Exit { get; set; } = TranscoderExit.Finished(); - - public bool WritesOn { get; set; } - - public int? Seats { get; set; } - - public Task StartAsync( - PlaybackFile file, - ServiceId service, - TimeSpan from, - LiveProfile? profile, - VideoCodec format, - SoundPlacement sound, - CancellationToken cancellationToken) - { - AskedFrom.Add(from); - AskedFor.Add(profile?.Name); - AskedIn.Add(format); - AskedOf.Add(service); - AskedWith.Add(sound); - Opened.Add(file); - - if (Refuses is { } refusal) - { - return Task.FromResult(OnTheFlyStart.Refused(refusal, "the held player was told to refuse.")); - } - - if (Seats is { } seats && EveryHanded.Count(viewing => !viewing.WasLetGo) >= seats) - { - return Task.FromResult(OnTheFlyStart.Refused(OnTheFlyRefusal.TooManyAlready, "every seat the held player has is taken.")); - } - - Handed = new HeldViewing( - new OnTheFlyStanding( - from, - Waited, - profile ?? LiveProfile.Unasked(Machine), - LiveEncoderChoice.Asked(Machine), - attributesWereMeasured: true, - Running, - AtOnce), - Picture, - Exit, - WritesOn); - EveryHanded.Add(Handed); - - return Task.FromResult(OnTheFlyStart.Started(Handed)); - } - - public Task SoundsAsync( - PlaybackFile file, - ServiceId service, - CancellationToken cancellationToken) - { - AskedWhatItCarries++; - - return Task.FromResult(SoundsCannotBeRead is { } why - ? CarriedSounds.Unread(why) - : CarriedSounds.Counted(Sounds)); - } -} - -internal sealed class PlayFeature : IAsyncDisposable -{ - public static readonly OutputRoot Root = new("bulk"); - - private readonly TestingWebApplicationFactory factory = new(); - - private readonly DirectoryInfo mounted = Directory.CreateTempSubdirectory("carina-play-"); - - private readonly DirectoryInfo shelved = Directory.CreateTempSubdirectory("carina-play-shelf-"); - - public PlayFeature(IReadOnlyList? formats = null) - { - WebApplicationFactory configured = factory - .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => - { - if (formats is not null) - { - services.AddSingleton(new AlreadyChosen(LiveEncoder.Vaapi, formats)); - } - - services.RemoveAll(); - services.RemoveAll(); - services.AddSingleton(Recordings); - services.AddSingleton(Player); - services.AddSingleton(new IntegritySettings - { - OutputRoots = [new StorageRootPath(Root, mounted.FullName)], - }); - services.AddSingleton(new EncodeSettings - { - OutputRoots = [new StorageRootPath(EncodedArtefact.Shelf, shelved.FullName)], - }); - services.AddSingleton(Jobs); - services.AddSingleton(Profiles); - services.RemoveAll(); - services.AddSingleton(Codecs); - services.RemoveAll(); - services.AddSingleton(Chapters); - services.AddSingleton(Positions); - services.AddSingleton(SegmentSettings); - services.AddSingleton(Versions); - services.AddSingleton(Detections); - })); - - WebApplicationFactory serving = configured.WithTestScheme(); - Client = serving.CreateClient(); - Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( - TestAuthenticationHandler.SchemeName, - "anything"); - Stranger = configured.WithTestScheme().CreateClient(); - Reads = serving.Services.GetRequiredService(); - } - - public IArtefactOpenings Reads { get; } - - public HttpClient Client { get; } - - public HttpClient Stranger { get; } - - public HeldRecordings Recordings { get; } = new(); - - public HeldEncodeJobs Jobs { get; } = new(); - - public HeldEncodeProfiles Profiles { get; } = new(); - - public HeldArtefactCodecs Codecs { get; } = new(); - - public HeldEncodeChapters Chapters { get; } = new(); - - public HeldPlaybackPositions Positions { get; } = new(); - - public HeldOnTheFlyPlayer Player { get; } = new(); - - public HeldSegmentSettings SegmentSettings { get; } = new(); - - public HeldSegmentModelVersions Versions { get; } = new(); - - public HeldRecordingDetections Detections { get; } = new(); - - public string MountedAt => mounted.FullName; - - public Recording Ended( - RecordingOutcome outcome, - int bytes = 4_000, - bool onDisk = true, - AudioMode audio = AudioMode.Undetermined, - int sounds = ProgrammeSnapshot.SoundsUnannounced) - { - Recording recording = RecordingFeature.Begin(RecordingId.New(), audio: audio, sounds: sounds); - recording.Wrote(TimeSpan.FromMinutes(30)); - - if (outcome is RecordingOutcome.Complete) - { - recording.Abort(RecordingFeature.Noon.AddMinutes(30)); - } - else - { - recording.Note(new OutcomeDetail( - RecordingFault.DriverLost, - null, - string.Empty, - RecordingFeature.Noon.AddMinutes(20))); - } - - recording.Settle(outcome, bytes, RecordingFeature.Noon.AddMinutes(30)); - Recordings.Recordings.Add(recording); - - if (onDisk) - { - File.WriteAllBytes( - Path.Combine(mounted.FullName, recording.FileName.Value), - [.. Enumerable.Range(0, bytes).Select(index => (byte)(index % 251))]); - } - - return recording; - } - - public Recording StillWriting() - { - Recording recording = RecordingFeature.Begin(RecordingId.New()); - - Recordings.Recordings.Add(recording); - File.WriteAllBytes(Path.Combine(mounted.FullName, recording.FileName.Value), new byte[1_000]); - - return recording; - } - - public byte[] Encoded( - Recording recording, - EncodeCodec codec = EncodeCodec.H264, - int minutesLater = 0, - int bytes = 900, - bool onDisk = true, - EncodeCodec? fileReadAs = null, - string? taggedAs = null, - EncodeTimeline? timeline = null, - ChapterReading? chapters = null) - { - EncodeProfile profile = EncodedArtefact.Profile(codec, RecordingFeature.Noon.AddHours(-1)); - Profiles.Profiles.Add(profile); - - EncodeJob job = EncodedArtefact.Made( - recording, - profile, - RecordingFeature.Noon.AddHours(1).AddMinutes(minutesLater), - timeline, - chapters); - Jobs.Jobs.Add(job); - - if (fileReadAs is { } read) - { - Codecs.ReadAs(job.ArtefactName!, read, taggedAs); - } - - byte[] made = [.. Enumerable.Range(0, bytes).Select(index => (byte)((index * 3) % 251))]; - - if (onDisk) - { - File.WriteAllBytes(Path.Combine(shelved.FullName, job.ArtefactName!.Value), made); - } - - return made; - } - - public async Task> MarkedAsync(EncodeJob job, params ChapterSegment[] segments) - { - ArgumentNullException.ThrowIfNull(job); - ArgumentNullException.ThrowIfNull(segments); - - IReadOnlyList marked = EncodeChapter.Mark(job.Id, segments); - await Chapters.RecordAsync(job.Id, marked, CancellationToken.None); - - return marked; - } - - public Task PlanAsync(Recording recording, string query = "") - => AskAsync(recording, query, PlayDelivery.Json); - - public Task PictureAsync(Recording recording, string query = "") - => AskAsync(recording, query, "*/*"); - - public async ValueTask DisposeAsync() - { - Client.Dispose(); - Stranger.Dispose(); - await factory.DisposeAsync(); - - if (Directory.Exists(mounted.FullName)) - { - mounted.Delete(recursive: true); - } - - if (Directory.Exists(shelved.FullName)) - { - shelved.Delete(recursive: true); - } - } - - public static async Task PlanOfAsync(HttpResponseMessage answer) - { - ArgumentNullException.ThrowIfNull(answer); - - using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); - - return read.RootElement.Clone(); - } - - public Task PictureAsync(Recording recording, string query, string range) - => AskAsync(recording, query, "*/*", range); - - private async Task AskAsync( - Recording recording, - string query, - string accepting, - string? range = null) - { - ArgumentNullException.ThrowIfNull(recording); - - using var asking = new HttpRequestMessage( - HttpMethod.Get, - new Uri($"/api/videos/{recording.Id.Wire}/play{query}", UriKind.Relative)); - - asking.Headers.TryAddWithoutValidation("Accept", accepting); - - if (range is not null) - { - asking.Headers.TryAddWithoutValidation("Range", range); - } - - return await Client.SendAsync(asking, HttpCompletionOption.ResponseHeadersRead); - } -} - -public sealed class PlayDeliveryTests -{ - private static readonly DateTime Noon = new(2026, 9, 16, 12, 0, 0, DateTimeKind.Utc); - - [Theory] - [InlineData(RecordingOutcome.Complete, "whole", true)] - [InlineData(RecordingOutcome.Truncated, "cutShort", false)] - [InlineData(RecordingOutcome.Failed, "failed", false)] - public async Task HowTheRecordingEndedIsPartOfEveryAnswerSoNoneOfTheThreeLooksLikeAnother( - RecordingOutcome outcome, - string said, - bool whole) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(outcome); - - using HttpResponseMessage plan = await feature.PlanAsync(recording); - JsonElement read = await PlayFeature.PlanOfAsync(plan); - using HttpResponseMessage picture = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.OK, plan.StatusCode); - Assert.Equal(said, read.GetProperty("data").GetProperty("standing").GetString()); - Assert.Equal(whole, read.GetProperty("data").GetProperty("showsAsAWholeRecording").GetBoolean()); - Assert.Equal(said, Header(picture, PlaybackHeaders.Standing)); - } - - [Fact] - public async Task AViewerWhoNamesNoSoundIsGivenTheMainOneAsTheyAlwaysWere() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Player.Sounds = 2; - - using HttpResponseMessage answer = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal([SoundPlacement.WholeStream(0)], feature.Player.AskedWith); - } - - [Fact] - public async Task AViewerWhoAsksForTheSecondSoundIsGivenIt() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Player.Sounds = 2; - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal([SoundPlacement.WholeStream(1)], feature.Player.AskedWith); - } - - [Fact] - public async Task ARecordingOfABroadcastThatCarriedOneSoundHasNoSecondOneToAskFor() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Player.Sounds = 1; - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.AskedWith); - Assert.Equal( - PlayDelivery.TheRecordingDoesNotCarryThatSound, - (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); - } - - [Fact] - public async Task ARecordingOfABroadcastThatCarriedTwoSoundsOfTheirOwnHasNoThirdOneToAskFor() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 2); - feature.Player.Sounds = 2; - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=third"); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.AskedWith); - Assert.Equal( - PlayDelivery.TheRecordingDoesNotCarryThatSound, - (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); - } - - [Fact] - public void TheSoundsARecordingCanBePlayedWithAreNamedInTheRefusal() - => Assert.All(SoundTracks.Names, name => Assert.Contains(name, PlayDelivery.TheSoundsThereAre, StringComparison.Ordinal)); - - [Fact] - public async Task ARecordingWhoseSoundsCouldNotBeReadIsNotStartedOnAGuess() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Player.SoundsCannotBeRead = "the programme was still reading the stream"; - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); - Assert.Empty(feature.Player.AskedWith); - } - - [Theory] - [InlineData("sub")] - [InlineData("Main")] - [InlineData("1")] - public async Task ASoundThisApplicationDoesNotCarryIsRefusedAndTheOnesItDoesAreNamed(string said) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.PictureAsync(recording, $"?sound={said}"); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.AskedWith); - Assert.Equal( - PlayDelivery.TheSoundsThereAre, - (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); - } - - [Theory] - [InlineData("encoded")] - [InlineData("Artefact")] - [InlineData("1")] - [InlineData("../../etc/passwd")] - public async Task SomethingThisApplicationCannotPlayARecordingFromIsRefusedAndTheTwoItCanAreNamed(string said) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.PictureAsync(recording, $"?source={said}"); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.Opened); - Assert.Equal( - PlayDelivery.TheSourcesThereAre, - (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); - } - - [Theory] - [InlineData("encoded")] - [InlineData("Artefact")] - public async Task APlanAskedForFromSomethingThisApplicationCannotPlayARecordingFromIsRefusedTheSameWay( - string said) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.PlanAsync(recording, $"?source={said}"); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Equal( - PlayDelivery.TheSourcesThereAre, - (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); - } - - [Theory] - [InlineData("?source=recording")] - [InlineData("?source=artefact")] - [InlineData("")] - public async Task ARecordingNothingHasEncodedIsTranscodedFromItselfWhicheverSourceIsAskedFor(string query) - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, bytes: 2_500); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, query); - JsonElement read = (await PlayFeature.PlanOfAsync( - await feature.PlanAsync(recording, query))).GetProperty("data"); - - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal("onTheFly", Header(picture, PlaybackHeaders.Route)); - Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); - Assert.Equal("recording", read.GetProperty("source").GetString()); - Assert.Equal(JsonValueKind.Null, read.GetProperty("alternative").ValueKind); - } - - [Fact(DisplayName = "a recording asked for as it was recorded takes one of the few pictures this machine transcodes at once, and is refused when they are all taken")] - public async Task ARecordingAskedForAsItWasRecordedIsRefusedWhenAsManyAreBeingTranscodedAsThisMachineAllows() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - feature.Player.Refuses = OnTheFlyRefusal.TooManyAlready; - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?source=recording"); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, picture.StatusCode); - Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); - } - - [Fact] - public async Task BrEd2019AnArtefactHandedOutWholeIsNotedAsOpenedAndAPlanOpensNothing() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - string artefact = feature.Jobs.Jobs.Single().ArtefactName!.Value; - - using HttpResponseMessage plan = await feature.PlanAsync(recording); - - Assert.Null(feature.Reads.LastOpened(EncodedArtefact.Shelf, artefact)); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, string.Empty, "bytes=0-99"); - - Assert.Equal(HttpStatusCode.PartialContent, picture.StatusCode); - Assert.NotNull(feature.Reads.LastOpened(EncodedArtefact.Shelf, artefact)); - } - - [Fact] - public async Task ThePlanNamesTheSoundsTheRecordingCanBeAskedFor() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Player.Sounds = 2; - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal( - ["main", "secondary"], - read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); - } - - [Fact] - public async Task ThePlanOfABroadcastThatCarriedOneSoundNamesOnlyTheMainOne() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Player.Sounds = 1; - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal( - ["main"], - read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); - } - - [Fact] - public async Task ThePlanOfARecordingWhoseSoundsCouldNotBeReadNamesTheMainSoundItPlaysRatherThanNone() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Player.SoundsCannotBeRead = "the programme was still reading the stream"; - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal( - ["main"], - read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); - } - - [Fact] - public async Task ThePlanOfASecondSoundThatCouldNotBeReadIsRefusedAsThePictureOfItIs() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Player.SoundsCannotBeRead = "the programme was still reading the stream"; - - using HttpResponseMessage plan = await feature.PlanAsync(recording, "?sound=secondary"); - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, plan.StatusCode); - Assert.Equal(picture.StatusCode, plan.StatusCode); - Assert.Equal( - (await PlayFeature.PlanOfAsync(picture)).GetProperty("message").GetString(), - (await PlayFeature.PlanOfAsync(plan)).GetProperty("message").GetString()); - } - - [Fact] - public async Task BrPd008ARecordingWhoseBroadcastPutTwoLanguagesOnOneSoundIsPlayedWithOneOfThemInBothEars() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); - feature.Player.Sounds = 1; - - using HttpResponseMessage main = await feature.PictureAsync(recording); - using HttpResponseMessage secondary = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.OK, main.StatusCode); - Assert.Equal(HttpStatusCode.OK, secondary.StatusCode); - Assert.Equal( - [ - SoundPlacement.OneChannelOf(0, SoundChannel.Left), - SoundPlacement.OneChannelOf(0, SoundChannel.Right), - ], - feature.Player.AskedWith); - } - - [Fact] - public async Task ThePlanOfABroadcastThatPutTwoLanguagesOnOneSoundNamesBothOfThem() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 1); - feature.Player.SoundsCannotBeRead = "the stream is never asked when the broadcast announced its sound"; - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal( - ["main", "secondary"], - read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); - } - - [Fact] - public async Task BrPd008ARecordingWithTwoLanguagesOnTheMainSoundBesideASecondStreamIsPlayedWithAnyOfTheThree() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 2); - feature.Player.Sounds = 2; - - using HttpResponseMessage main = await feature.PictureAsync(recording); - using HttpResponseMessage secondary = await feature.PictureAsync(recording, "?sound=secondary"); - using HttpResponseMessage third = await feature.PictureAsync(recording, "?sound=third"); - - Assert.Equal( - [HttpStatusCode.OK, HttpStatusCode.OK, HttpStatusCode.OK], - [main.StatusCode, secondary.StatusCode, third.StatusCode]); - Assert.Equal( - [ - SoundPlacement.OneChannelOf(0, SoundChannel.Left), - SoundPlacement.OneChannelOf(0, SoundChannel.Right), - SoundPlacement.WholeStream(1), - ], - feature.Player.AskedWith); - } - - [Fact] - public async Task ThePlanOfABroadcastWithTwoLanguagesOnTheMainSoundBesideASecondStreamNamesAllThree() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.DualMono, sounds: 2); - feature.Player.SoundsCannotBeRead = "the stream is never asked when the broadcast announced its sound"; - - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal( - ["main", "secondary", "third"], - read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); - } - - [Fact] - public async Task ABroadcastThatAnnouncedTwoSoundsOfTheirOwnIsPlayedByTakingTheSecondStreamItCarries() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 2); - feature.Player.Sounds = 2; - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal([SoundPlacement.WholeStream(1)], feature.Player.AskedWith); - Assert.Equal(1, feature.Player.AskedWhatItCarries); - } - - [Fact] - public async Task ABroadcastThatAnnouncedTwoSoundsTheRecordingDoesNotCarryIsRefusedRatherThanStarted() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 2); - feature.Player.Sounds = 1; - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.AskedWith); - Assert.Equal(1, feature.Player.AskedWhatItCarries); - Assert.Equal( - PlayDelivery.TheRecordingDoesNotCarryThatSound, - (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); - } - - [Fact] - public async Task ARecordingWhoseAnnouncedSecondSoundCannotBeLookedForIsNotStartedOnAGuess() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 2); - feature.Player.SoundsCannotBeRead = "the programme was still reading the stream"; - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); - Assert.Empty(feature.Player.AskedWith); - } - - [Fact] - public async Task ABroadcastThatAnnouncedTheOneSoundHasNoSecondOneEvenWhereTheStreamCarriesTwo() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 1); - feature.Player.Sounds = 2; - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?sound=secondary"); - JsonElement read = (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording))).GetProperty("data"); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.AskedWith); - Assert.Equal(0, feature.Player.AskedWhatItCarries); - Assert.Equal( - ["main"], - read.GetProperty("sounds").EnumerateArray().Select(sound => sound.GetString()!).ToArray()); - } - - [Fact] - public async Task ABroadcastThatAnnouncedItsMainSoundOnlyIsPlayedWithoutTheStreamBeingRead() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, audio: AudioMode.Stereo, sounds: 1); - feature.Player.SoundsCannotBeRead = "the stream is never asked for the main sound of an announced recording"; - - using HttpResponseMessage answer = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal([SoundPlacement.WholeStream(0)], feature.Player.AskedWith); - Assert.Equal(0, feature.Player.AskedWhatItCarries); - } - - [Fact] - public async Task ARecordingThatHasNotEndedIsNotPlayedAtAll() - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.PlanAsync(feature.StillWriting()); - - Assert.Equal(HttpStatusCode.Conflict, answer.StatusCode); - Assert.False((await PlayFeature.PlanOfAsync(answer)).GetProperty("status").GetBoolean()); - } - - [Fact] - public async Task SeekingIsAStartingAgainAndTheAnswerSaysSoRatherThanPretendingToBeFast() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage plan = await feature.PlanAsync(recording); - JsonElement read = (await PlayFeature.PlanOfAsync(plan)).GetProperty("data"); - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?from=300"); - - Assert.Equal("byStartingAgain", read.GetProperty("seeking").GetString()); - Assert.False(read.GetProperty("canSeek").GetBoolean()); - Assert.True(read.GetProperty("transcodes").GetBoolean()); - - Assert.Equal("byStartingAgain", Header(picture, PlaybackHeaders.Seeking)); - Assert.Equal("false", Header(picture, PlaybackHeaders.CanSeek)); - Assert.Equal("none", Assert.Single(picture.Headers.AcceptRanges)); - } - - [Fact] - public async Task WhereTheZeroOfTheStreamSitsInsideTheRecordingIsNamedByTheAnswer() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?from=300"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("300", Header(answer, PlaybackHeaders.StartsAt)); - Assert.Equal(TimeSpan.FromSeconds(300), Assert.Single(feature.Player.AskedFrom)); - Assert.Equal(recording.ServiceId, Assert.Single(feature.Player.AskedOf)); - } - - [Fact] - public async Task WhatTheTranscoderWroteIsWhatComesBackAndItIsAnMp4() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.PictureAsync(recording); - byte[] body = await answer.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); - Assert.Equal(feature.Player.Picture, body); - Assert.True(feature.Player.Handed!.WasLetGo); - } - - [Fact] - public async Task TheAnswerSaysWhatItTookToStartAndHowManyAreRunning() - { - await using var feature = new PlayFeature(); - feature.Player.Running = 2; - feature.Player.AtOnce = 2; - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.PictureAsync(recording); - - Assert.Equal("0.138", Header(answer, PlaybackHeaders.Waited)); - Assert.Equal("2", Header(answer, PlaybackHeaders.Running)); - Assert.Equal("2", Header(answer, PlaybackHeaders.AtOnce)); - Assert.Equal("720p30", Header(answer, PlaybackHeaders.Profile)); - Assert.Equal("software", Header(answer, PlaybackHeaders.Encoder)); - Assert.Equal("true", Header(answer, PlaybackHeaders.AttributesWereMeasured)); - } - - [Fact] - public async Task WhenAsManyAreRunningAsThisMachineIsAskedToTheAnswerSaysWhyRatherThanHanging() - { - await using var feature = new PlayFeature(); - feature.Player.Refuses = OnTheFlyRefusal.TooManyAlready; - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); - Assert.Equal("tooManyAlready", Header(answer, PlaybackHeaders.Refusal)); - Assert.Equal("whole", Header(answer, PlaybackHeaders.Standing)); - } - - [Theory] - [InlineData(OnTheFlyRefusal.NothingToPlay, HttpStatusCode.NotFound)] - [InlineData(OnTheFlyRefusal.TranscoderWouldNotStart, HttpStatusCode.ServiceUnavailable)] - [InlineData(OnTheFlyRefusal.NothingCameOut, HttpStatusCode.ServiceUnavailable)] - [InlineData(OnTheFlyRefusal.TookTooLong, HttpStatusCode.ServiceUnavailable)] - public async Task EveryWayTheTranscoderCanRefuseHasAnAnswerOfItsOwn( - OnTheFlyRefusal refusal, - HttpStatusCode expected) - { - await using var feature = new PlayFeature(); - feature.Player.Refuses = refusal; - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); - - Assert.Equal(expected, answer.StatusCode); - Assert.Equal( - System.Text.Json.JsonNamingPolicy.CamelCase.ConvertName(refusal.ToString()), - Header(answer, PlaybackHeaders.Refusal)); - } - - [Fact] - public async Task ARecordingOfNoBytesIsNotHandedToATranscoder() - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.PlanAsync(feature.Ended(RecordingOutcome.Failed, 0)); - - Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Empty(feature.Player.AskedFrom); - } - - [Fact] - public async Task ARecordingWhoseFileIsGoneWhileItsRootIsThereIsNotFoundRatherThanHandedToATranscoder() - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.PlanAsync( - feature.Ended(RecordingOutcome.Complete, onDisk: false)); - - Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Empty(feature.Player.AskedFrom); - } - - [Fact] - public async Task ARecordingWhoseRootIsGoneIsOutOfReachRatherThanNotFoundAndNoTranscoderIsStarted() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - Directory.Delete(feature.MountedAt, recursive: true); - - using HttpResponseMessage answer = await feature.PlanAsync(recording); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); - Assert.Empty(feature.Player.AskedFrom); - } - - [Fact] - public async Task ARecordingNobodyHasIsNotFound() - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.Client.GetAsync( - new Uri($"/api/videos/{RecordingId.New().Wire}/play", UriKind.Relative)); - - Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - } - - [Fact] - public async Task SomethingThatIsNotARecordingIdIsRefusedBeforeAnythingIsLookedFor() - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.Client.GetAsync( - new Uri("/api/videos/not-an-id/play", UriKind.Relative)); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - } - - [Theory] - [InlineData("?profile=1080p60", "1080p60")] - [InlineData("?profile=720p60", "720p60")] - public async Task AProfileIsOneOfTheFewThereAre(string query, string chosen) - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(chosen, Assert.Single(feature.Player.AskedFor)); - } - - [Fact] - public async Task AskingForNoProfileLeavesTheChoiceToWhereTheEncoderIsKnownRatherThanNamingOneHere() - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Null(Assert.Single(feature.Player.AskedFor)); - } - - [Theory] - [InlineData(LiveEncoder.Vaapi, "1080p60")] - [InlineData(LiveEncoder.Software, "720p30")] - public async Task ARecordingNobodyChoseAProfileForOpensAtWhatThisMachineOpensAt( - LiveEncoder machine, - string opened) - { - await using var feature = new PlayFeature(); - feature.Player.Machine = machine; - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(opened, Header(answer, PlaybackHeaders.Profile)); - } - - [Fact] - public async Task AProfileNamedOutrightIsHonouredOnAMachineThatWouldHaveOpenedAtAnother() - { - await using var feature = new PlayFeature(); - feature.Player.Machine = LiveEncoder.Vaapi; - - using HttpResponseMessage answer = await feature.PictureAsync( - feature.Ended(RecordingOutcome.Complete), - "?profile=720p30"); - - Assert.Equal("720p30", Assert.Single(feature.Player.AskedFor)); - Assert.Equal("720p30", Header(answer, PlaybackHeaders.Profile)); - } - - [Theory(DisplayName = "a recording transcoded as it plays is encoded in the format asked for, where this machine encodes it")] - [InlineData("?format=h265", VideoCodec.H265)] - [InlineData("?format=av1", VideoCodec.Av1)] - [InlineData("?format=h264", VideoCodec.H264)] - public async Task ARecordingTranscodedAsItPlaysIsEncodedInTheFormatAskedFor(string query, VideoCodec format) - { - await using PlayFeature feature = new(VideoCodecs.InOrder); - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(format, Assert.Single(feature.Player.AskedIn)); - } - - [Fact(DisplayName = "a recording played without naming a format is transcoded in H.264, as it always was")] - public async Task ARecordingPlayedWithoutNamingAFormatIsTranscodedInH264() - { - await using PlayFeature feature = new(VideoCodecs.InOrder); - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(VideoCodec.H264, Assert.Single(feature.Player.AskedIn)); - } - - [Theory(DisplayName = "a format off the list is refused rather than passed on")] - [InlineData("?format=hevc")] - [InlineData("?format=AV1")] - [InlineData("?format=h264,h265")] - public async Task AFormatOffTheListIsRefusedRatherThanPassedOn(string query) - { - await using PlayFeature feature = new(VideoCodecs.InOrder); - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.AskedIn); - Assert.Equal( - PlayDelivery.TheFormatsThereAre, - (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); - } - - [Theory(DisplayName = "a format this machine does not encode is refused, picture and plan alike, rather than turned into H.264")] - [InlineData("h265")] - [InlineData("av1")] - public async Task AFormatThisMachineDoesNotEncodeIsRefusedRatherThanTurnedIntoH264(string format) - { - await using PlayFeature feature = new([VideoCodec.H264]); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage picture = await feature.PictureAsync(recording, "?format=" + format); - using HttpResponseMessage plan = await feature.PlanAsync(recording, "?format=" + format); - - Assert.Equal(HttpStatusCode.BadRequest, picture.StatusCode); - Assert.Equal(HttpStatusCode.BadRequest, plan.StatusCode); - Assert.Empty(feature.Player.AskedIn); - Assert.Contains(format, (await PlayFeature.PlanOfAsync(picture)).GetProperty("message").GetString(), StringComparison.Ordinal); - } - - [Theory(DisplayName = "an artefact handed over as it is does not look at the format, even one this machine does not encode")] - [InlineData("?format=av1")] - [InlineData("?format=h265")] - public async Task AnArtefactHandedOverAsItIsDoesNotLookAtTheFormat(string query) - { - await using PlayFeature feature = new([VideoCodec.H264]); - Recording recording = feature.Ended(RecordingOutcome.Complete); - byte[] made = feature.Encoded(recording); - - using HttpResponseMessage plan = await feature.PlanAsync(recording, query); - using HttpResponseMessage picture = await feature.PictureAsync(recording, query); - - Assert.Equal(HttpStatusCode.OK, plan.StatusCode); - Assert.False((await PlayFeature.PlanOfAsync(plan)).GetProperty("data").GetProperty("transcodes").GetBoolean()); - Assert.Equal(HttpStatusCode.OK, picture.StatusCode); - Assert.Equal(made, await picture.Content.ReadAsByteArrayAsync()); - Assert.Empty(feature.Player.AskedIn); - } - - [Theory] - [InlineData("?profile=4320p120")] - [InlineData("?profile=../../etc/passwd")] - public async Task AProfileThisApplicationDoesNotEncodeIsRefusedRatherThanPassedOn(string query) - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.AskedFor); - Assert.Equal( - PlayDelivery.TheProfilesThereAre, - (await PlayFeature.PlanOfAsync(answer)).GetProperty("message").GetString()); - } - - [Theory] - [InlineData("?from=-1")] - [InlineData("?from=soon")] - [InlineData("?from=NaN")] - [InlineData("?from=Infinity")] - public async Task APositionThatIsNotASecondIntoTheRecordingIsRefused(string query) - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete), query); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(feature.Player.AskedFrom); - } - - [Fact] - public async Task AClientCarryingNoCredentialsIsRefusedRatherThanSentToASignInScreen() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.Stranger.GetAsync( - new Uri($"/api/videos/{recording.Id.Wire}/play", UriKind.Relative)); - - Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); - Assert.Null(answer.Headers.Location); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task NothingHandedBackSaysWhereOnThisMachineTheFileIs() - { - await using var feature = new PlayFeature(); - Recording gone = feature.Ended(RecordingOutcome.Complete, onDisk: false); - - using HttpResponseMessage answer = await feature.PlanAsync(gone); - string body = await answer.Content.ReadAsStringAsync(); - - Assert.DoesNotContain(feature.MountedAt, body, StringComparison.Ordinal); - Assert.DoesNotContain( - answer.Headers.Concat(answer.Content.Headers), - header => header.Value.Any(value => value.Contains(feature.MountedAt, StringComparison.Ordinal))); - } - - [Fact] - public async Task NothingAboutThisAnswerMayBeHeldByAnythingInFront() - { - await using var feature = new PlayFeature(); - - using HttpResponseMessage answer = await feature.PictureAsync(feature.Ended(RecordingOutcome.Complete)); - - Assert.Equal(PlayDelivery.NeverCached, answer.Headers.CacheControl?.ToString()); - Assert.Contains("Accept", answer.Headers.Vary, StringComparer.OrdinalIgnoreCase); - } - - [Fact(DisplayName = "a recording nobody has watched is played from its beginning")] - public async Task ARecordingNobodyHasWatchedIsPlayedFromItsBeginning() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using HttpResponseMessage answer = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(TimeSpan.Zero, Assert.Single(feature.Player.AskedFrom)); - Assert.Equal("0", Header(answer, PlaybackHeaders.StartsAt)); - } - - [Fact(DisplayName = "playing without saying where starts where this viewer left this recording")] - public async Task PlayingWithoutSayingWhereStartsWhereThisViewerLeftIt() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - (HttpStatusCode kept, _) = await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 600 }); - - using HttpResponseMessage answer = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.OK, kept); - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(TimeSpan.FromSeconds(600), Assert.Single(feature.Player.AskedFrom)); - Assert.Equal("600", Header(answer, PlaybackHeaders.StartsAt)); - } - - [Fact(DisplayName = "saying where to start wins over where the watching was left")] - public async Task SayingWhereToStartWinsOverWhereTheWatchingWasLeft() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 600 }); - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?from=30"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(TimeSpan.FromSeconds(30), Assert.Single(feature.Player.AskedFrom)); - } - - [Fact(DisplayName = "asking to start at the beginning is not the same as asking for nothing")] - public async Task AskingToStartAtTheBeginningIsNotTheSameAsAskingForNothing() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 600 }); - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?from=0"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(TimeSpan.Zero, Assert.Single(feature.Player.AskedFrom)); - } - - [Fact(DisplayName = "where another viewer left a recording is not where this one is taken to")] - public async Task WhereAnotherViewerLeftARecordingIsNotWhereThisOneIsTakenTo() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - feature.Positions.Positions.Add(PlaybackPosition.Reached( - recording.Id, - new Subject("someone else"), - TimeSpan.FromSeconds(900), - Noon)); - - using HttpResponseMessage answer = await feature.PictureAsync(recording); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(TimeSpan.Zero, Assert.Single(feature.Player.AskedFrom)); - } - - [Fact(DisplayName = "the plan says where the watching got to, so a player that seeks itself can go there")] - public async Task ThePlanSaysWhereTheWatchingGotTo() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - - using (HttpResponseMessage unwatched = await feature.PlanAsync(recording)) - { - JsonElement read = (await PlayFeature.PlanOfAsync(unwatched)).GetProperty("data"); - - Assert.Equal(JsonValueKind.Null, read.GetProperty("resumeAtSec").ValueKind); - } - - await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 612.5 }); - - using HttpResponseMessage watched = await feature.PlanAsync(recording); - JsonElement plan = (await PlayFeature.PlanOfAsync(watched)).GetProperty("data"); - - Assert.Equal(612.5, plan.GetProperty("resumeAtSec").GetDouble()); - } - - [Fact(DisplayName = "where the watching got to is kept once for a recording, whichever of the two it is watched from")] - public async Task WhereTheWatchingGotToIsTheSameWhicheverOfTheTwoThePlanIsAskedFor() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - - await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 618.5 }); - - using HttpResponseMessage asEncoded = await feature.PlanAsync(recording, "?source=artefact"); - using HttpResponseMessage asRecorded = await feature.PlanAsync(recording, "?source=recording"); - JsonElement artefact = (await PlayFeature.PlanOfAsync(asEncoded)).GetProperty("data"); - JsonElement itself = (await PlayFeature.PlanOfAsync(asRecorded)).GetProperty("data"); - - Assert.Equal("artefact", artefact.GetProperty("source").GetString()); - Assert.Equal("recording", itself.GetProperty("source").GetString()); - Assert.Equal(618.5, artefact.GetProperty("resumeAtSec").GetDouble()); - Assert.Equal(618.5, itself.GetProperty("resumeAtSec").GetDouble()); - Assert.Single(feature.Positions.Positions); - } - - [Fact(DisplayName = "a recording asked for as it was recorded is started where the watching got to, as it is when it is asked for encoded")] - public async Task ARecordingAskedForAsItWasRecordedIsStartedWhereTheWatchingGotTo() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - - await KeepAsync(feature.Client, recording.Id.Wire, new { positionSec = 300 }); - - using HttpResponseMessage answer = await feature.PictureAsync(recording, "?source=recording"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(TimeSpan.FromSeconds(300), Assert.Single(feature.Player.AskedFrom)); - Assert.Equal(recording.FileName, Assert.Single(feature.Player.Opened).Name); - } - - private static async Task<(HttpStatusCode Status, JsonElement Body)> KeepAsync( - HttpClient client, - string recordingId, - object body) - { - using HttpResponseMessage response = await client.PutAsJsonAsync( - new Uri($"/api/videos/{recordingId}/position", UriKind.Relative), - body); - string read = await response.Content.ReadAsStringAsync(); - - if (!read.StartsWith('{')) - { - return (response.StatusCode, default); - } - - using var document = JsonDocument.Parse(read); - - return (response.StatusCode, document.RootElement.Clone()); - } - - private static string? Header(HttpResponseMessage answer, string named) - => answer.Headers.TryGetValues(named, out IEnumerable? values) ? values.Single() : null; -} diff --git a/tests/Carina.Api.Tests/FeatureTest/PlayFeature.cs b/tests/Carina.Api.Tests/FeatureTest/PlayFeature.cs new file mode 100644 index 000000000..be4755d9d --- /dev/null +++ b/tests/Carina.Api.Tests/FeatureTest/PlayFeature.cs @@ -0,0 +1,249 @@ +using System.Net.Http.Headers; +using System.Text.Json; + +using Carina.Api.Playback; +using Carina.Domain.Base; +using Carina.Domain.Encodings; +using Carina.Domain.Integrity; +using Carina.Domain.Playback; +using Carina.Domain.Recordings; +using Carina.Domain.Reservations; +using Carina.Domain.Streaming; +using Carina.Domain.Viewing; +using Carina.TestSupport; + +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; + +using IRecordingDetectionRepository = Carina.Domain.Segments.IRecordingDetectionRepository; +using ISegmentModelVersionRepository = Carina.Domain.Segments.ISegmentModelVersionRepository; +using ISegmentSettingsRepository = Carina.Domain.Segments.ISegmentSettingsRepository; + +namespace Carina.Api.Tests.FeatureTest; + +internal sealed class PlayFeature : IAsyncDisposable +{ + public static readonly OutputRoot Root = new("bulk"); + + private readonly TestingWebApplicationFactory factory = new(); + + private readonly DirectoryInfo mounted = Directory.CreateTempSubdirectory("carina-play-"); + + private readonly DirectoryInfo shelved = Directory.CreateTempSubdirectory("carina-play-shelf-"); + + public PlayFeature(IReadOnlyList? formats = null) + { + WebApplicationFactory configured = factory + .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => + { + if (formats is not null) + { + services.AddSingleton(new AlreadyChosen(LiveEncoder.Vaapi, formats)); + } + + services.RemoveAll(); + services.RemoveAll(); + services.AddSingleton(Recordings); + services.AddSingleton(Player); + services.AddSingleton(new IntegritySettings + { + OutputRoots = [new StorageRootPath(Root, mounted.FullName)], + }); + services.AddSingleton(new EncodeSettings + { + OutputRoots = [new StorageRootPath(EncodedArtefact.Shelf, shelved.FullName)], + }); + services.AddSingleton(Jobs); + services.AddSingleton(Profiles); + services.RemoveAll(); + services.AddSingleton(Codecs); + services.RemoveAll(); + services.AddSingleton(Chapters); + services.AddSingleton(Positions); + services.AddSingleton(SegmentSettings); + services.AddSingleton(Versions); + services.AddSingleton(Detections); + })); + + WebApplicationFactory serving = configured.WithTestScheme(); + Client = serving.CreateClient(); + Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( + TestAuthenticationHandler.SchemeName, + "anything"); + Stranger = configured.WithTestScheme().CreateClient(); + Reads = serving.Services.GetRequiredService(); + } + + public IArtefactOpenings Reads { get; } + + public HttpClient Client { get; } + + public HttpClient Stranger { get; } + + public HeldRecordings Recordings { get; } = new(); + + public HeldEncodeJobs Jobs { get; } = new(); + + public HeldEncodeProfiles Profiles { get; } = new(); + + public HeldArtefactCodecs Codecs { get; } = new(); + + public HeldEncodeChapters Chapters { get; } = new(); + + public HeldPlaybackPositions Positions { get; } = new(); + + public HeldOnTheFlyPlayer Player { get; } = new(); + + public HeldSegmentSettings SegmentSettings { get; } = new(); + + public HeldSegmentModelVersions Versions { get; } = new(); + + public HeldRecordingDetections Detections { get; } = new(); + + public string MountedAt => mounted.FullName; + + public Recording Ended( + RecordingOutcome outcome, + int bytes = 4_000, + bool onDisk = true, + AudioMode audio = AudioMode.Undetermined, + int sounds = ProgrammeSnapshot.SoundsUnannounced) + { + Recording recording = RecordingFeature.Begin(RecordingId.New(), audio: audio, sounds: sounds); + recording.Wrote(TimeSpan.FromMinutes(30)); + + if (outcome is RecordingOutcome.Complete) + { + recording.Abort(RecordingFeature.Noon.AddMinutes(30)); + } + else + { + recording.Note(new OutcomeDetail( + RecordingFault.DriverLost, + null, + string.Empty, + RecordingFeature.Noon.AddMinutes(20))); + } + + recording.Settle(outcome, bytes, RecordingFeature.Noon.AddMinutes(30)); + Recordings.Recordings.Add(recording); + + if (onDisk) + { + File.WriteAllBytes( + Path.Combine(mounted.FullName, recording.FileName.Value), + [.. Enumerable.Range(0, bytes).Select(index => (byte)(index % 251))]); + } + + return recording; + } + + public Recording StillWriting() + { + Recording recording = RecordingFeature.Begin(RecordingId.New()); + + Recordings.Recordings.Add(recording); + File.WriteAllBytes(Path.Combine(mounted.FullName, recording.FileName.Value), new byte[1_000]); + + return recording; + } + + public byte[] Encoded( + Recording recording, + EncodeCodec codec = EncodeCodec.H264, + int minutesLater = 0, + int bytes = 900, + bool onDisk = true, + EncodeCodec? fileReadAs = null, + string? taggedAs = null, + EncodeTimeline? timeline = null, + ChapterReading? chapters = null) + { + EncodeProfile profile = EncodedArtefact.Profile(codec, RecordingFeature.Noon.AddHours(-1)); + Profiles.Profiles.Add(profile); + + EncodeJob job = EncodedArtefact.Made( + recording, + profile, + RecordingFeature.Noon.AddHours(1).AddMinutes(minutesLater), + timeline, + chapters); + Jobs.Jobs.Add(job); + + if (fileReadAs is { } read) + { + Codecs.ReadAs(job.ArtefactName!, read, taggedAs); + } + + byte[] made = [.. Enumerable.Range(0, bytes).Select(index => (byte)((index * 3) % 251))]; + + if (onDisk) + { + File.WriteAllBytes(Path.Combine(shelved.FullName, job.ArtefactName!.Value), made); + } + + return made; + } + + public async Task> MarkedAsync(EncodeJob job, params ChapterSegment[] segments) + { + ArgumentNullException.ThrowIfNull(job); + ArgumentNullException.ThrowIfNull(segments); + + IReadOnlyList marked = EncodeChapter.Mark(job.Id, segments); + await Chapters.RecordAsync(job.Id, marked, CancellationToken.None); + + return marked; + } + + public Task PlanAsync(Recording recording, string query = "") + => AskAsync(recording, query, PlayDelivery.Json); + + public Task PictureAsync(Recording recording, string query = "") + => AskAsync(recording, query, "*/*"); + + public async ValueTask DisposeAsync() + { + Client.Dispose(); + Stranger.Dispose(); + await factory.DisposeAsync(); + TemporaryDirectories.RemoveAll(mounted, shelved); + } + + public static async Task PlanOfAsync(HttpResponseMessage answer) + { + ArgumentNullException.ThrowIfNull(answer); + + using JsonDocument read = JsonDocument.Parse(await answer.Content.ReadAsStringAsync()); + + return read.RootElement.Clone(); + } + + public Task PictureAsync(Recording recording, string query, string range) + => AskAsync(recording, query, "*/*", range); + + private async Task AskAsync( + Recording recording, + string query, + string accepting, + string? range = null) + { + ArgumentNullException.ThrowIfNull(recording); + + using var asking = new HttpRequestMessage( + HttpMethod.Get, + new Uri($"/api/videos/{recording.Id.Wire}/play{query}", UriKind.Relative)); + + asking.Headers.TryAddWithoutValidation("Accept", accepting); + + if (range is not null) + { + asking.Headers.TryAddWithoutValidation("Range", range); + } + + return await Client.SendAsync(asking, HttpCompletionOption.ResponseHeadersRead); + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/ProxiedKestrelProbe.cs b/tests/Carina.Api.Tests/FeatureTest/ProxiedKestrelProbe.cs new file mode 100644 index 000000000..88709c8e1 --- /dev/null +++ b/tests/Carina.Api.Tests/FeatureTest/ProxiedKestrelProbe.cs @@ -0,0 +1,135 @@ +using System.Net; +using System.Net.WebSockets; + +using Carina.Api.Authentication; +using Carina.Api.Live; +using Carina.Domain.Auth; +using Carina.Domain.Streaming; +using Carina.Infrastructure.Streaming; +using Carina.TestSupport; + +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Net.Http.Headers; + +namespace Carina.Api.Tests.FeatureTest; + +internal sealed class ProxiedKestrelProbe : IAsyncDisposable +{ + public const string Password = "a password long enough"; + + private const string ForwardedProto = "X-Forwarded-Proto"; + + private readonly TestingWebApplicationFactory factory = new(); + + private readonly WebApplicationFactory wired; + + private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); + + private ProxiedKestrelProbe() + { + Transcoders = new HeldTranscoders(budget); + wired = factory.WithWebHostBuilder(builder => + { + builder.UseSetting(TrustedProxies.ProxiesKey, "127.0.0.1 ::1"); + builder.ConfigureTestServices(services => + { + services.AddSingleton(Sessions); + services.AddSingleton(Accounts); + services.AddSingleton(Hasher); + services.AddSingleton(Supply); + services.AddSingleton(new HeldSoundOnAir()); + services.AddSingleton(budget); + services.AddSingleton(Transcoders); + }); + }); + wired.UseKestrel(kestrel => kestrel.Listen(IPAddress.Loopback, 0)); + wired.StartServer(); + Address = wired.Services + .GetRequiredService() + .Features + .Get()! + .Addresses + .Select(address => new Uri(address)) + .First(address => address.Host == IPAddress.Loopback.ToString()); + Accounts.Account = LocalAccount.Bootstrap( + FirstCredentials.Username, + Hasher.Hash(Password, PasswordHashPolicy.Default), + DateTime.UtcNow); + } + + public Uri Address { get; } + + public HeldAuthSessions Sessions { get; } = new(); + + public HeldLocalAccount Accounts { get; } = new(); + + public QuickPasswordHasher Hasher { get; } = new(); + + public PipedSupply Supply { get; } = new(); + + public HeldTranscoders Transcoders { get; } + + public static ProxiedKestrelProbe ListeningOnKestrel() => new(); + + public string PageAt(string scheme) => $"{scheme}://{Address.Authority}"; + + public Uri Wire => new($"ws://{Address.Authority}{LiveWire.Path}?network=32736&service=1024&profile=720p30"); + + public async Task SignedInCookieAsync() + { + using HttpClient client = new() { BaseAddress = Address }; + + client.DefaultRequestHeaders.Add(HeaderNames.Origin, PageAt(Uri.UriSchemeHttp)); + + using HttpResponseMessage response = await client.PostAsJsonAsync( + new Uri("/api/auth/login", UriKind.Relative), + new { username = FirstCredentials.Username, password = Password }); + + response.EnsureSuccessStatusCode(); + + string handed = response.Headers.GetValues(HeaderNames.SetCookie).Single(); + + return handed[..handed.IndexOf(';', StringComparison.Ordinal)]; + } + + public async Task PostThroughTheProxyAsync(string forwardedProto, string origin, string cookie) + { + using HttpClient client = new() { BaseAddress = Address }; + + client.DefaultRequestHeaders.Add(HeaderNames.Origin, origin); + client.DefaultRequestHeaders.Add(HeaderNames.Cookie, cookie); + client.DefaultRequestHeaders.Add(ForwardedProto, forwardedProto); + + return await client.PostAsJsonAsync(new Uri("/api/live/ticket", UriKind.Relative), new { network = 32736, service = 1024 }); + } + + public ClientWebSocket Opening(string cookie, string? forwardedProto, string? origin) + { + ClientWebSocket client = new(); + + client.Options.CollectHttpResponseDetails = true; + client.Options.SetRequestHeader(HeaderNames.Cookie, cookie); + + if (forwardedProto is not null) + { + client.Options.SetRequestHeader(ForwardedProto, forwardedProto); + } + + if (origin is not null) + { + client.Options.SetRequestHeader(HeaderNames.Origin, origin); + } + + return client; + } + + public async ValueTask DisposeAsync() + { + await wired.DisposeAsync(); + await factory.DisposeAsync(); + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/RoutedSurfaceTests.cs b/tests/Carina.Api.Tests/FeatureTest/RoutedSurfaceTests.cs index 6bd504802..4ac5a9f06 100644 --- a/tests/Carina.Api.Tests/FeatureTest/RoutedSurfaceTests.cs +++ b/tests/Carina.Api.Tests/FeatureTest/RoutedSurfaceTests.cs @@ -7,7 +7,6 @@ using Carina.Domain.Auth; using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc.Testing; namespace Carina.Api.Tests.FeatureTest; @@ -19,6 +18,24 @@ public sealed class RoutedSurfaceTests(TestingWebApplicationFactory factory) private const string MigrationRoot = "/api/migration"; + public static readonly IReadOnlyList StreamingRoots = ["/api/live", "/api/videos"]; + + private static readonly string[] SurfacesTheFeatureHadWhenTheseRulesWereWritten = + [ + "GET /api/live/channels", + "GET /api/live/profiles", + "GET /api/live/sessions", + "GET /api/live/ws", + "POST /api/live/ticket", + "GET /api/videos/{id}", + "HEAD /api/videos/{id}", + "GET /api/videos/{id}/play", + "PUT /api/videos/{id}/position", + "GET /api/videos/{id}/scrub", + "GET /api/videos/{id}/thumbnail", + "POST /api/videos/{id}/ticket", + ]; + [Fact] public void EveryRoutedSurfaceSaysWhetherItDestroys() { @@ -558,6 +575,76 @@ public async Task APathThatMerelyLooksLikeAnEnumeratedSurfaceIsRefused(string pa Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } + [Fact] + public void TheStreamingSurfacesAreInTheInventoryTheEffectRuleReads() + { + string[] streaming = [.. Streaming().Select(surface => surface.ToString())]; + + Assert.All( + SurfacesTheFeatureHadWhenTheseRulesWereWritten, + surface => Assert.Contains(surface, streaming, StringComparer.Ordinal)); + } + + [Fact] + public void NothingUnderTheStreamingSurfaceDeletes() + { + Assert.All(StreamingRoots, root => Assert.Empty(EndpointRules.SurfacesThatDeleteUnder(Inventory(), root))); + } + + [Fact] + public void NothingUnderTheStreamingSurfaceSaysItDestroys() + { + Assert.Empty( + Streaming() + .Where(surface => surface.Effect is EndpointEffect.Destructive) + .Select(surface => surface.ToString())); + } + + [Fact] + public void TheOnlyThingsThatChangeStateUnderTheStreamingSurfaceAreATicketAndAPositionBeingKept() + { + RoutedSurface[] changing = + [ + .. Streaming().Where(surface => surface.Effect is EndpointEffect.Changing), + ]; + + Assert.NotEmpty(changing); + Assert.All( + changing, + surface => + { + if (surface.Pattern.EndsWith("/position", StringComparison.Ordinal)) + { + Assert.True( + HttpMethods.IsPut(surface.Method), + $"{surface} keeps where the watching got to on {surface.Method}"); + + return; + } + + Assert.True(HttpMethods.IsPost(surface.Method), $"{surface} changes state on {surface.Method}"); + Assert.EndsWith("/ticket", surface.Pattern, StringComparison.Ordinal); + }); + } + + [Fact] + public void TheRootsAreReadAsWholeSegmentsAndNotAsLeadingLetters() + { + RoutedSurface[] inventory = + [ + new("DELETE", "/api/videos-archive/{id}", EndpointEffect.Destructive), + new("DELETE", "/api/livestock/{id}", EndpointEffect.Destructive), + new("DELETE", "/api/live/sessions/{id}", EndpointEffect.Destructive), + ]; + + Assert.Equal( + ["DELETE /api/live/sessions/{id}"], + StreamingRoots.SelectMany(root => EndpointRules.SurfacesThatDeleteUnder(inventory, root)).ToArray()); + Assert.Equal( + ["DELETE /api/live/sessions/{id}"], + inventory.Where(UnderARoot).Select(surface => surface.ToString()).ToArray()); + } + private static bool UnderTheMigrationRoot(RoutedSurface surface) => string.Equals(surface.Pattern, MigrationRoot, StringComparison.Ordinal) || surface.Pattern.StartsWith(MigrationRoot + "/", StringComparison.Ordinal); @@ -565,4 +652,10 @@ private static bool UnderTheMigrationRoot(RoutedSurface surface) private IEnumerable MigrationSurfaces() => Inventory().Where(UnderTheMigrationRoot); private IReadOnlyList Inventory() => RouteInventory.Of(factory); + + private static bool UnderARoot(RoutedSurface surface) + => StreamingRoots.Any(root => string.Equals(surface.Pattern, root, StringComparison.Ordinal) + || surface.Pattern.StartsWith(root + "/", StringComparison.Ordinal)); + + private IEnumerable Streaming() => Inventory().Where(UnderARoot); } diff --git a/tests/Carina.Api.Tests/FeatureTest/SegmentChapterPlaybackTests.cs b/tests/Carina.Api.Tests/FeatureTest/SegmentChapterPlaybackTests.cs deleted file mode 100644 index d6ebadb38..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/SegmentChapterPlaybackTests.cs +++ /dev/null @@ -1,342 +0,0 @@ -using System.Text.Json; - -using Carina.Domain.Encodings; -using Carina.Domain.Recordings; -using Carina.Domain.Segments; -using Carina.TestSupport; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class SegmentChapterPlaybackTests -{ - private static readonly EncodeTimeline HalfASecondSkipped = new(TimeSpan.FromSeconds(1.4), TimeSpan.FromSeconds(0.5), TimeSpan.FromMinutes(30), TimeSpan.FromSeconds(1799.5)); - - [Fact(DisplayName = "BR-CD-001: the plan of an artefact carries the chapters the version in use detected, on the artefact's clock, a likely break with something after it offered to be skipped")] - public async Task TheArtefactsPlanCarriesTheDetectedChaptersOnItsClock() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, timeline: HalfASecondSkipped); - await DetectedAsync(feature, recording.Id, (0, 912.3, SegmentKind.Programme, 0.98), (912.3, 1002.3, SegmentKind.Break, 0.93), (1002.3, 1800, SegmentKind.Programme, 0.99)); - - JsonElement plan = await PlanAsync(feature, recording); - JsonElement[] chapters = [.. plan.GetProperty("chapters").EnumerateArray()]; - - Assert.Equal("direct", plan.GetProperty("route").GetString()); - Assert.Equal( - [(0d, 911.8d, "programme", false), (911.8d, 1001.8d, "break", true), (1001.8d, 1799.5d, "programme", false)], - chapters.Select(Read)); - } - - [Fact(DisplayName = "BR-CD-001: the plan of the recording itself carries the chapters the version in use detected at the recording's own time")] - public async Task TheRecordingsOwnPlanCarriesTheDetectedChaptersAtItsOwnTime() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - await DetectedAsync(feature, recording.Id, (0, 912.3, SegmentKind.Programme, 0.98), (912.3, 1002.3, SegmentKind.Break, 0.93), (1002.3, 1800, SegmentKind.Programme, 0.99)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.True(plan.GetProperty("transcodes").GetBoolean()); - Assert.Equal( - [(0d, 912.3d, "programme", false), (912.3d, 1002.3d, "break", true), (1002.3d, 1800d, "programme", false)], - plan.GetProperty("chapters").EnumerateArray().Select(Read)); - } - - [Fact(DisplayName = "BR-CD-001: a recording with an artefact asked for as it was recorded carries the chapters at the recording's own time")] - public async Task TheRecordingAskedForAsRecordedCarriesTheChaptersAtItsOwnTime() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, timeline: HalfASecondSkipped); - await DetectedAsync(feature, recording.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); - - JsonElement plan = await PlanAsync(feature, recording, "?source=recording"); - - Assert.Equal("recording", plan.GetProperty("source").GetString()); - Assert.Equal([0d, 300d, 360d], plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("startsAtSec").GetDouble())); - } - - [Fact(DisplayName = "BR-CD-009: a break less likely than the threshold is marked but not offered to be skipped, and neither is a break the recording ends on")] - public async Task UnlikelyOrFinalBreaksAreNotOfferedToBeSkipped() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - await DetectedAsync( - feature, - recording.Id, - (0, 300, SegmentKind.Programme, 0.98), - (300, 360, SegmentKind.Break, 0.69), - (360, 1740, SegmentKind.Programme, 0.99), - (1740, 1800, SegmentKind.Break, 0.99)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Equal([false, false, false, false], plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("skippable").GetBoolean())); - Assert.Equal("break", plan.GetProperty("chapters")[1].GetProperty("kind").GetString()); - } - - [Theory(DisplayName = "BR-CD-009: the threshold the settings hold decides which breaks are offered to be skipped")] - [InlineData(0.60, true, true)] - [InlineData(0.90, false, true)] - [InlineData(0.95, false, false)] - public async Task TheThresholdTheSettingsHoldDecidesWhichBreaksAreOffered(double threshold, bool unlikely, bool likely) - { - await using var feature = new PlayFeature(); - await feature.SegmentSettings.SaveAsync(SegmentSettings.Rehydrate(SegmentSettings.TheOnlyRow, threshold, RecordingFeature.Noon), CancellationToken.None); - Recording recording = feature.Ended(RecordingOutcome.Complete); - await DetectedAsync( - feature, - recording.Id, - (0, 300, SegmentKind.Programme, 0.98), - (300, 360, SegmentKind.Break, 0.69), - (360, 900, SegmentKind.Programme, 0.99), - (900, 960, SegmentKind.Break, 0.93), - (960, 1800, SegmentKind.Programme, 0.99)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Equal([false, unlikely, false, likely, false], plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("skippable").GetBoolean())); - } - - [Fact(DisplayName = "BR-CD-009: an opening and an ending are played by their own kinds on the artefact and on the recording itself, each offered to be skipped when it is likely enough and something follows it")] - public async Task AnOpeningAndAnEndingArePlayedByTheirOwnKinds() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, timeline: HalfASecondSkipped); - await DetectedAsync( - feature, - recording.Id, - (0, 60, SegmentKind.Programme, 0.98), - (60, 150, SegmentKind.Opening, 0.92), - (150, 900, SegmentKind.Programme, 0.99), - (900, 960, SegmentKind.Break, 0.93), - (960, 1710, SegmentKind.Programme, 0.99), - (1710, 1800, SegmentKind.Ending, 0.95)); - - JsonElement artefact = await PlanAsync(feature, recording); - JsonElement original = await PlanAsync(feature, recording, "?source=recording"); - - Assert.Equal( - [ - (0d, 59.5d, "programme", false), (59.5d, 149.5d, "opening", true), (149.5d, 899.5d, "programme", false), - (899.5d, 959.5d, "break", true), (959.5d, 1709.5d, "programme", false), (1709.5d, 1799.5d, "ending", false), - ], - artefact.GetProperty("chapters").EnumerateArray().Select(Read)); - Assert.Equal( - [ - (0d, 60d, "programme", false), (60d, 150d, "opening", true), (150d, 900d, "programme", false), - (900d, 960d, "break", true), (960d, 1710d, "programme", false), (1710d, 1800d, "ending", false), - ], - original.GetProperty("chapters").EnumerateArray().Select(Read)); - } - - [Theory(DisplayName = "BR-CD-009: the threshold the settings hold decides for an opening and an ending as it does for a break, and an ending with something after it is offered to be skipped")] - [InlineData(0.70, false, true, true)] - [InlineData(0.60, true, true, true)] - [InlineData(0.90, false, false, true)] - [InlineData(0.95, false, false, false)] - public async Task TheThresholdDecidesForAnOpeningAndAnEnding(double threshold, bool opening, bool breaks, bool ending) - { - await using var feature = new PlayFeature(); - await feature.SegmentSettings.SaveAsync(SegmentSettings.Rehydrate(SegmentSettings.TheOnlyRow, threshold, RecordingFeature.Noon), CancellationToken.None); - Recording recording = feature.Ended(RecordingOutcome.Complete); - await DetectedAsync( - feature, - recording.Id, - (0, 90, SegmentKind.Opening, 0.65), - (90, 900, SegmentKind.Programme, 0.99), - (900, 960, SegmentKind.Break, 0.8), - (960, 1680, SegmentKind.Programme, 0.99), - (1680, 1770, SegmentKind.Ending, 0.93), - (1770, 1800, SegmentKind.Programme, 0.9)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Equal( - ["opening", "programme", "break", "programme", "ending", "programme"], - plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("kind").GetString())); - Assert.Equal( - [opening, false, breaks, false, ending, false], - plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("skippable").GetBoolean())); - } - - [Fact(DisplayName = "BR-CS-002: a recording whose detected sequence was thrown away plays with no chapters, even with chapters its encode marked")] - public async Task ASequenceThrownAwayPlaysWithNoChapters() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, timeline: HalfASecondSkipped); - await feature.MarkedAsync(feature.Jobs.Jobs[0], new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme), new ChapterSegment(TimeSpan.FromSeconds(90), TimeSpan.FromSeconds(150), ChapterKind.Break), new ChapterSegment(TimeSpan.FromSeconds(150), TimeSpan.FromSeconds(300), ChapterKind.Programme)); - await DetectedAsync(feature, recording.Id, (0, 600, SegmentKind.Programme, 0.6), (600, 1800, SegmentKind.Break, 0.8)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Empty(plan.GetProperty("chapters").EnumerateArray()); - } - - [Fact(DisplayName = "BR-CD-013: a recording not detected plays with no chapters, whatever its encode marked")] - public async Task ANotDetectedRecordingPlaysWithNoChapters() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, timeline: HalfASecondSkipped); - await feature.MarkedAsync(feature.Jobs.Jobs[0], new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme), new ChapterSegment(TimeSpan.FromSeconds(90), TimeSpan.FromSeconds(150), ChapterKind.Break), new ChapterSegment(TimeSpan.FromSeconds(150), TimeSpan.FromSeconds(300), ChapterKind.Programme)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Empty(plan.GetProperty("chapters").EnumerateArray()); - } - - [Fact(DisplayName = "BR-CS-002: a detection by a version no longer in use is not played")] - public async Task ADetectionByAnotherVersionIsNotPlayed() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - await DetectedAsync(feature, recording.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); - feature.Versions.Active = HeldSegmentModelVersions.InUse(2, RecordingFeature.Noon); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Empty(plan.GetProperty("chapters").EnumerateArray()); - } - - [Fact(DisplayName = "an artefact whose timeline was not kept has no detected stretch placed on it")] - public async Task AnArtefactWithoutATimelineHasNoDetectedChapters() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - await DetectedAsync(feature, recording.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Equal("direct", plan.GetProperty("route").GetString()); - Assert.Empty(plan.GetProperty("chapters").EnumerateArray()); - } - - [Fact(DisplayName = "BR-CD-001: the plan of an artefact says how far the recording's time stands ahead of the artefact's, the head the job that made it skipped, by which its chapters were moved")] - public async Task TheArtefactsPlanSaysHowFarTheRecordingsTimeStandsAhead() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, timeline: Skipped(0.533)); - await DetectedAsync(feature, recording.Id, (0, 912.3, SegmentKind.Programme, 0.98), (912.3, 1002.3, SegmentKind.Break, 0.93), (1002.3, 1800, SegmentKind.Programme, 0.99)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Equal("direct", plan.GetProperty("route").GetString()); - Assert.Equal(0.533, plan.GetProperty("recordingOffsetSec").GetDouble()); - Assert.Equal([0d, 911.77d, 1001.77d], plan.GetProperty("chapters").EnumerateArray().Select(chapter => chapter.GetProperty("startsAtSec").GetDouble())); - } - - [Fact(DisplayName = "BR-CD-001: the plan says the head skipped by the artefact it hands over, not by a newer one it could not hand over, whatever chapters it carries")] - public async Task ThePlanSaysTheHeadSkippedByTheArtefactItHandsOver() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, timeline: Skipped(0.533)); - feature.Encoded(recording, minutesLater: 10, onDisk: false, timeline: Skipped(1.2)); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Equal("direct", plan.GetProperty("route").GetString()); - Assert.Equal(0.533, plan.GetProperty("recordingOffsetSec").GetDouble()); - } - - [Fact(DisplayName = "BR-CD-001: the plan of the recording itself says its time is the recording's own, whether or not an artefact was made of it")] - public async Task TheRecordingsOwnPlanSaysItsTimeIsTheRecordingsOwn() - { - await using var feature = new PlayFeature(); - Recording alone = feature.Ended(RecordingOutcome.Complete); - Recording encoded = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(encoded, timeline: Skipped(0.533)); - await DetectedAsync(feature, encoded.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); - - JsonElement transcoded = await PlanAsync(feature, alone); - JsonElement asRecorded = await PlanAsync(feature, encoded, "?source=recording"); - - Assert.True(transcoded.GetProperty("transcodes").GetBoolean()); - Assert.Equal(0d, transcoded.GetProperty("recordingOffsetSec").GetDouble()); - Assert.Equal("recording", asRecorded.GetProperty("source").GetString()); - Assert.Equal(0d, asRecorded.GetProperty("recordingOffsetSec").GetDouble()); - } - - [Fact(DisplayName = "an artefact whose timeline was not kept says nothing of how far the recording's time stands ahead of its own")] - public async Task AnArtefactWithoutATimelineSaysNoOffset() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording); - - JsonElement plan = await PlanAsync(feature, recording); - - Assert.Equal("direct", plan.GetProperty("route").GetString()); - Assert.Equal(JsonValueKind.Null, plan.GetProperty("recordingOffsetSec").ValueKind); - } - - [Fact(DisplayName = "BR-CS-002: chapters an encode took from a detection, or from the reader of the source, are not played on an artefact the version in use has not detected")] - public async Task ChaptersEncodedAreNotPlayedWithoutADetection() - { - await using var fromADetection = new PlayFeature(); - Recording detected = fromADetection.Ended(RecordingOutcome.Complete); - fromADetection.Encoded(detected, timeline: HalfASecondSkipped, chapters: new ChapterReading(ChapterDetectorName.Segments, ChapterVerdict.Marked, 0.03, RecordingFeature.Noon.AddHours(1), 2)); - await fromADetection.MarkedAsync(fromADetection.Jobs.Jobs[0], Marked()); - await using var fromTheReader = new PlayFeature(); - Recording read = fromTheReader.Ended(RecordingOutcome.Complete); - fromTheReader.Encoded(read, timeline: HalfASecondSkipped, chapters: new ChapterReading(ChapterDetectorName.Ffmpeg, ChapterVerdict.Marked, 0.03, RecordingFeature.Noon.AddHours(1))); - await fromTheReader.MarkedAsync(fromTheReader.Jobs.Jobs[0], Marked()); - - JsonElement fromTheSegments = await PlanAsync(fromADetection, detected); - JsonElement fromAReader = await PlanAsync(fromTheReader, read); - - Assert.Empty(fromTheSegments.GetProperty("chapters").EnumerateArray()); - Assert.Empty(fromAReader.GetProperty("chapters").EnumerateArray()); - } - - [Fact(DisplayName = "BR-CA-001: asking for the plan writes nothing: no detection is kept and no setting saved")] - public async Task AskingForThePlanWritesNothing() - { - await using var feature = new PlayFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete); - feature.Encoded(recording, timeline: HalfASecondSkipped); - await DetectedAsync(feature, recording.Id, (0, 300, SegmentKind.Programme, 0.98), (300, 360, SegmentKind.Break, 0.93), (360, 1800, SegmentKind.Programme, 0.99)); - int kept = feature.Detections.Keeps; - - await PlanAsync(feature, recording); - await PlanAsync(feature, recording, "?source=recording"); - - Assert.Equal(kept, feature.Detections.Keeps); - Assert.Equal(0, feature.SegmentSettings.Saves); - } - - private static EncodeTimeline Skipped(double head) - => new(TimeSpan.FromSeconds(1.4), TimeSpan.FromSeconds(head), TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30) - TimeSpan.FromSeconds(head)); - - private static async Task PlanAsync(PlayFeature feature, Recording recording, string query = "") - => (await PlayFeature.PlanOfAsync(await feature.PlanAsync(recording, query))).GetProperty("data"); - - private static (double Starts, double Ends, string Kind, bool Skippable) Read(JsonElement chapter) - => (chapter.GetProperty("startsAtSec").GetDouble(), - chapter.GetProperty("endsAtSec").GetDouble(), - chapter.GetProperty("kind").GetString()!, - chapter.GetProperty("skippable").GetBoolean()); - - private static ChapterSegment[] Marked() - => - [ - new ChapterSegment(TimeSpan.Zero, TimeSpan.FromSeconds(90), ChapterKind.Programme), - new ChapterSegment(TimeSpan.FromSeconds(90), TimeSpan.FromSeconds(150), ChapterKind.Break), - new ChapterSegment(TimeSpan.FromSeconds(150), TimeSpan.FromSeconds(1799.5), ChapterKind.Programme), - ]; - - private static async Task DetectedAsync(PlayFeature feature, RecordingId recording, params (double Starts, double Ends, SegmentKind Kind, double Probability)[] stretches) - { - SegmentSpan[] segments = [.. stretches.Select(stretch => new SegmentSpan(TimeSpan.FromSeconds(stretch.Starts), TimeSpan.FromSeconds(stretch.Ends), stretch.Kind, stretch.Probability))]; - - await feature.Detections.KeepAsync( - RecordingDetection.Of(recording, SegmentModelVersion.FirstNumber, SegmentDetection.Judged(segments, TimeSpan.FromMinutes(30), []), 2, RecordingFeature.Noon, RecordingFeature.Noon), - CancellationToken.None); - } -} diff --git a/tests/Carina.Api.Tests/FeatureTest/StreamingSurfaceTests.cs b/tests/Carina.Api.Tests/FeatureTest/StreamingSurfaceTests.cs deleted file mode 100644 index 000bc6879..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/StreamingSurfaceTests.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Carina.Api.Authentication; -using Carina.Api.Tests.Unit; - -using Microsoft.AspNetCore.Http; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class StreamingSurfaceTests(TestingWebApplicationFactory factory) - : IClassFixture -{ - public static readonly IReadOnlyList Roots = ["/api/live", "/api/videos"]; - - private static readonly string[] SurfacesTheFeatureHadWhenTheseRulesWereWritten = - [ - "GET /api/live/channels", - "GET /api/live/profiles", - "GET /api/live/sessions", - "GET /api/live/ws", - "POST /api/live/ticket", - "GET /api/videos/{id}", - "HEAD /api/videos/{id}", - "GET /api/videos/{id}/play", - "PUT /api/videos/{id}/position", - "GET /api/videos/{id}/scrub", - "GET /api/videos/{id}/thumbnail", - "POST /api/videos/{id}/ticket", - ]; - - [Fact] - public void TheStreamingSurfacesAreInTheInventoryTheEffectRuleReads() - { - string[] streaming = [.. Streaming().Select(surface => surface.ToString())]; - - Assert.All( - SurfacesTheFeatureHadWhenTheseRulesWereWritten, - surface => Assert.Contains(surface, streaming, StringComparer.Ordinal)); - } - - [Fact] - public void NothingUnderTheStreamingSurfaceDeletes() - { - Assert.All(Roots, root => Assert.Empty(EndpointRules.SurfacesThatDeleteUnder(Inventory(), root))); - } - - [Fact] - public void NothingUnderTheStreamingSurfaceSaysItDestroys() - { - Assert.Empty( - Streaming() - .Where(surface => surface.Effect is EndpointEffect.Destructive) - .Select(surface => surface.ToString())); - } - - [Fact] - public void TheOnlyThingsThatChangeStateUnderTheStreamingSurfaceAreATicketAndAPositionBeingKept() - { - RoutedSurface[] changing = - [ - .. Streaming().Where(surface => surface.Effect is EndpointEffect.Changing), - ]; - - Assert.NotEmpty(changing); - Assert.All( - changing, - surface => - { - if (surface.Pattern.EndsWith("/position", StringComparison.Ordinal)) - { - Assert.True( - HttpMethods.IsPut(surface.Method), - $"{surface} keeps where the watching got to on {surface.Method}"); - - return; - } - - Assert.True(HttpMethods.IsPost(surface.Method), $"{surface} changes state on {surface.Method}"); - Assert.EndsWith("/ticket", surface.Pattern, StringComparison.Ordinal); - }); - } - - [Fact] - public void TheRootsAreReadAsWholeSegmentsAndNotAsLeadingLetters() - { - RoutedSurface[] inventory = - [ - new("DELETE", "/api/videos-archive/{id}", EndpointEffect.Destructive), - new("DELETE", "/api/livestock/{id}", EndpointEffect.Destructive), - new("DELETE", "/api/live/sessions/{id}", EndpointEffect.Destructive), - ]; - - Assert.Equal( - ["DELETE /api/live/sessions/{id}"], - Roots.SelectMany(root => EndpointRules.SurfacesThatDeleteUnder(inventory, root)).ToArray()); - Assert.Equal( - ["DELETE /api/live/sessions/{id}"], - inventory.Where(UnderARoot).Select(surface => surface.ToString()).ToArray()); - } - - private static bool UnderARoot(RoutedSurface surface) - => Roots.Any(root => string.Equals(surface.Pattern, root, StringComparison.Ordinal) - || surface.Pattern.StartsWith(root + "/", StringComparison.Ordinal)); - - private IEnumerable Streaming() => Inventory().Where(UnderARoot); - - private IReadOnlyList Inventory() => RouteInventory.Of(factory); -} diff --git a/tests/Carina.Api.Tests/FeatureTest/TemporaryDirectories.cs b/tests/Carina.Api.Tests/FeatureTest/TemporaryDirectories.cs new file mode 100644 index 000000000..1bd425188 --- /dev/null +++ b/tests/Carina.Api.Tests/FeatureTest/TemporaryDirectories.cs @@ -0,0 +1,38 @@ +namespace Carina.Api.Tests.FeatureTest; + +/// +/// Removes the directories a feature made for itself, every one of them even when removing another fails. +/// +internal static class TemporaryDirectories +{ + public static void RemoveAll(params DirectoryInfo[] directories) + { + ArgumentNullException.ThrowIfNull(directories); + + List refused = []; + + foreach (DirectoryInfo directory in directories) + { + try + { + if (Directory.Exists(directory.FullName)) + { + directory.Delete(recursive: true); + } + } + catch (IOException removing) + { + refused.Add(removing); + } + catch (UnauthorizedAccessException removing) + { + refused.Add(removing); + } + } + + if (refused.Count > 0) + { + throw new AggregateException(refused); + } + } +} diff --git a/tests/Carina.Api.Tests/FeatureTest/TicketInThePathTests.cs b/tests/Carina.Api.Tests/FeatureTest/TicketInThePathTests.cs deleted file mode 100644 index 3e44d12db..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/TicketInThePathTests.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System.Net; - -using Carina.Domain.Encodings; -using Carina.Domain.Recordings; - -namespace Carina.Api.Tests.FeatureTest; - -public sealed class TicketInThePathTests -{ - private const string AName = "a-programme.ts"; - - [Fact(DisplayName = "a player handed the ticket in the path is handed the recording, asks its headers and seeks on the same URL")] - public async Task APlayerHandedTheTicketInThePathIsHandedTheRecordingAndSeeksOnTheSameUrl() - { - await using TicketedFeature feature = new(); - Recording recording = feature.Ended(); - string path = WithTicket(recording, await feature.TicketForAsync(recording.Id), AName); - - using HttpResponseMessage headers = await feature.AsAPlayerAsync(path, null, method: HttpMethod.Head); - using HttpResponseMessage whole = await feature.AsAPlayerAsync(path, null, "bytes=0-"); - using HttpResponseMessage middle = await feature.AsAPlayerAsync(path, null, "bytes=1000-1999"); - - Assert.Equal(HttpStatusCode.OK, headers.StatusCode); - Assert.Equal(feature.Written.Length, headers.Content.Headers.ContentLength); - Assert.Equal(HttpStatusCode.PartialContent, whole.StatusCode); - Assert.Equal(feature.Written, await whole.Content.ReadAsByteArrayAsync()); - Assert.Equal(HttpStatusCode.PartialContent, middle.StatusCode); - Assert.Equal(feature.Written[1000..2000], await middle.Content.ReadAsByteArrayAsync()); - } - - [Fact(DisplayName = "the ticket in the path hands over the source the query asks for")] - public async Task TheTicketInThePathHandsOverTheSourceTheQueryAsksFor() - { - await using TicketedFeature feature = new(); - Recording recording = feature.Ended(); - byte[] artefact = feature.Encoded(recording, EncodeCodec.H264, EncodeCodec.H264); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage encoded = await feature.AsAPlayerAsync( - $"{WithTicket(recording, ticket, "a-programme.mp4")}?source=artefact", - null); - using HttpResponseMessage itself = await feature.AsAPlayerAsync( - $"{WithTicket(recording, ticket, AName)}?source=recording", - null); - - Assert.Equal(HttpStatusCode.OK, encoded.StatusCode); - Assert.Equal("video/mp4", encoded.Content.Headers.ContentType?.MediaType); - Assert.Equal(artefact, await encoded.Content.ReadAsByteArrayAsync()); - Assert.Equal(HttpStatusCode.OK, itself.StatusCode); - Assert.Equal(feature.Written, await itself.Content.ReadAsByteArrayAsync()); - } - - [Theory(DisplayName = "the name at the end of the path is only for showing and is never read")] - [InlineData("")] - [InlineData("a-programme.mp4")] - [InlineData("%E7%95%AA%E7%B5%84%20%E3%81%AE%E5%90%8D%E5%89%8D.ts")] - [InlineData("two/segments.ts")] - [InlineData("no-extension")] - public async Task TheNameAtTheEndOfThePathIsOnlyForShowing(string name) - { - await using TicketedFeature feature = new(); - Recording recording = feature.Ended(); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - WithTicket(recording, await feature.TicketForAsync(recording.Id), name), - null); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(feature.Written, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact(DisplayName = "the ticket in the path opens the one recording it was issued for and no other")] - public async Task TheTicketInThePathOpensTheOneRecordingItWasIssuedForAndNoOther() - { - await using TicketedFeature feature = new(); - Recording mine = feature.Ended(); - Recording another = feature.Ended(); - string ticket = await feature.TicketForAsync(mine.Id); - - using HttpResponseMessage entered = await feature.AsAPlayerAsync(WithTicket(mine, ticket, AName), null); - using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync(WithTicket(another, ticket, AName), null); - - Assert.Equal(HttpStatusCode.OK, entered.StatusCode); - Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); - Assert.NotEqual(feature.Written, await elsewhere.Content.ReadAsByteArrayAsync()); - } - - [Fact(DisplayName = "something that was never issued in the ticket's place is refused before any byte leaves")] - public async Task SomethingThatWasNeverIssuedInTheTicketsPlaceIsRefused() - { - await using TicketedFeature feature = new(); - Recording recording = feature.Ended(); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - WithTicket(recording, new string('a', 43), AName), - null); - - Assert.Equal(HttpStatusCode.Forbidden, answer.StatusCode); - Assert.NotEqual(feature.Written, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact(DisplayName = "something that is not the shape of a ticket in its place is refused without being sent to a sign-in screen, whatever the header carries")] - public async Task SomethingThatIsNotTheShapeOfATicketInItsPlaceIsRefused() - { - await using TicketedFeature feature = new(); - Recording recording = feature.Ended(); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - WithTicket(recording, "short", AName), - ticket); - - Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); - Assert.Null(answer.Headers.Location); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Theory(DisplayName = "the ticket in the path opens the bytes and nothing else under the same prefix")] - [InlineData("play")] - [InlineData("thumbnail")] - [InlineData("scrub")] - [InlineData("captions")] - [InlineData("data-broadcast")] - public async Task TheTicketInThePathOpensTheBytesAndNothingElse(string beneath) - { - await using TicketedFeature feature = new(); - Recording recording = feature.Ended(); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - $"/api/videos/{recording.Id.Wire}/{beneath}/with-ticket/{ticket}/{AName}", - null); - - Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); - Assert.Null(answer.Headers.Location); - } - - [Fact(DisplayName = "a ticket in the query is refused on both surfaces, because it shows as the title in a player")] - public async Task ATicketInTheQueryIsRefusedOnBothSurfaces() - { - await using TicketedFeature feature = new(); - Recording recording = feature.Ended(); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage plain = await feature.AsAPlayerAsync( - $"/api/videos/{recording.Id.Wire}?ticket={ticket}", - null); - using HttpResponseMessage named = await feature.AsAPlayerAsync( - $"/api/videos/{recording.Id.Wire}/with-ticket/short/{AName}?ticket={ticket}", - null); - - Assert.Equal(HttpStatusCode.Unauthorized, plain.StatusCode); - Assert.Equal(HttpStatusCode.Unauthorized, named.StatusCode); - } - - [Fact(DisplayName = "the answer to a ticket in the path is never held by anything in front")] - public async Task TheAnswerToATicketInThePathIsNeverHeldByAnythingInFront() - { - await using TicketedFeature feature = new(); - Recording recording = feature.Ended(); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - WithTicket(recording, await feature.TicketForAsync(recording.Id), AName), - null); - - Assert.Equal("no-store, private", answer.Headers.CacheControl?.ToString()); - } - - [Fact(DisplayName = "with every log turned up to its finest, no line carries the ticket in the path")] - public async Task WithEveryLogTurnedUpNoLineCarriesTheTicketInThePath() - { - RecordedStartup heard = new(); - await using TicketedFeature feature = new(heard); - Recording recording = feature.Ended(); - Recording another = feature.Ended(); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage entered = await feature.AsAPlayerAsync(WithTicket(recording, ticket, AName), null); - using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync(WithTicket(another, ticket, AName), null); - - Assert.Equal(HttpStatusCode.OK, entered.StatusCode); - Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); - Assert.Contains(heard.Everything, line => line.Category.StartsWith("Microsoft.AspNetCore", StringComparison.Ordinal)); - Assert.Empty(heard.Everything - .Where(line => line.Text.Contains(ticket, StringComparison.Ordinal)) - .Select(line => $"{line.Category} {line.Level}") - .Distinct()); - } - - private static string WithTicket(Recording recording, string ticket, string name) - => $"/api/videos/{recording.Id.Wire}/with-ticket/{ticket}/{name}"; -} diff --git a/tests/Carina.Api.Tests/FeatureTest/TicketedFeature.cs b/tests/Carina.Api.Tests/FeatureTest/TicketedFeature.cs index 2a8f6db7e..fe984ed47 100644 --- a/tests/Carina.Api.Tests/FeatureTest/TicketedFeature.cs +++ b/tests/Carina.Api.Tests/FeatureTest/TicketedFeature.cs @@ -185,7 +185,6 @@ public async ValueTask DisposeAsync() Client.Dispose(); Player.Dispose(); await factory.DisposeAsync(); - mounted.Delete(recursive: true); - shelved.Delete(recursive: true); + TemporaryDirectories.RemoveAll(mounted, shelved); } } diff --git a/tests/Carina.Api.Tests/FeatureTest/TicketedVideoTests.cs b/tests/Carina.Api.Tests/FeatureTest/TicketedVideoTests.cs index fbeefeded..d947be802 100644 --- a/tests/Carina.Api.Tests/FeatureTest/TicketedVideoTests.cs +++ b/tests/Carina.Api.Tests/FeatureTest/TicketedVideoTests.cs @@ -1,8 +1,6 @@ using System.Net; using System.Text.Json; -using Carina.Domain.Encodings; -using Carina.Domain.Playback; using Carina.Domain.Recordings; namespace Carina.Api.Tests.FeatureTest; @@ -23,179 +21,6 @@ public async Task ATicketIsIssuedForOneRecordingAndSaysWhenItDies() Assert.True(read.RootElement.GetProperty("data").TryGetProperty("lapsesAt", out _)); } - [Fact(DisplayName = "a player with a ticket asking for the artefact is handed the file made in H.264 after its profile was changed to H.265")] - public async Task APlayerAskingForTheArtefactIsHandedTheFileMadeInH264AfterItsProfileWasChangedToH265() - { - await using var feature = new TicketedFeature(); - Recording recording = feature.Ended(); - byte[] artefact = feature.Encoded(recording, EncodeCodec.H265, EncodeCodec.H264); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - $"/api/videos/{recording.Id.Wire}?source=artefact", - ticket); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); - Assert.Equal(artefact, await answer.Content.ReadAsByteArrayAsync()); - } - - [Theory(DisplayName = "a player with a ticket is handed an artefact made in H.265, however it is tagged, which no browser's decoding narrows")] - [InlineData("", "hvc1")] - [InlineData("?source=artefact", "hev1")] - public async Task APlayerWithATicketIsHandedAnArtefactMadeInH265(string query, string tag) - { - await using var feature = new TicketedFeature(); - Recording recording = feature.Ended(); - byte[] artefact = feature.Encoded(recording, EncodeCodec.H265, EncodeCodec.H265, tag); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - $"/api/videos/{recording.Id.Wire}{query}", - ticket); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("video/mp4", answer.Content.Headers.ContentType?.MediaType); - Assert.Equal(artefact, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact(DisplayName = "a player with a ticket is not handed an artefact whose file is neither of the two codecs, and gets the recording itself")] - public async Task APlayerWithATicketIsNotHandedAnArtefactOfNeitherCodec() - { - await using var feature = new TicketedFeature(); - Recording recording = feature.Ended(); - feature.Encoded(recording, EncodeCodec.H265, EncodeCodec.H265); - feature.Codecs.Readings[feature.Jobs.Jobs[0].ArtefactName!.Value] = ArtefactCodecReading.Neither("av1"); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync($"/api/videos/{recording.Id.Wire}", ticket); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(feature.Written, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task APlayerThatAsksTheHeadersThenSeeksTwiceIsAdmittedEveryTime() - { - await using var feature = new TicketedFeature(); - Recording recording = feature.Ended(); - string ticket = await feature.TicketForAsync(recording.Id); - string path = $"/api/videos/{recording.Id.Wire}"; - - using HttpResponseMessage headers = await feature.AsAPlayerAsync(path, ticket, method: HttpMethod.Head); - using HttpResponseMessage whole = await feature.AsAPlayerAsync(path, ticket, "bytes=0-"); - using HttpResponseMessage middle = await feature.AsAPlayerAsync(path, ticket, "bytes=1000-1999"); - using HttpResponseMessage tail = await feature.AsAPlayerAsync(path, ticket, "bytes=-500"); - - Assert.Equal(HttpStatusCode.OK, headers.StatusCode); - Assert.Equal(feature.Written.Length, headers.Content.Headers.ContentLength); - Assert.Equal(HttpStatusCode.PartialContent, whole.StatusCode); - Assert.Equal(feature.Written, await whole.Content.ReadAsByteArrayAsync()); - Assert.Equal(HttpStatusCode.PartialContent, middle.StatusCode); - Assert.Equal(feature.Written[1000..2000], await middle.Content.ReadAsByteArrayAsync()); - Assert.Equal(HttpStatusCode.PartialContent, tail.StatusCode); - Assert.Equal(feature.Written[^500..], await tail.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task AGrantOpensTheOneRecordingItWasEnteredWithAndNoOther() - { - await using var feature = new TicketedFeature(); - Recording mine = feature.Ended(); - Recording another = feature.Ended(); - string ticket = await feature.TicketForAsync(mine.Id); - - using HttpResponseMessage entered = await feature.AsAPlayerAsync($"/api/videos/{mine.Id.Wire}", ticket); - using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync( - $"/api/videos/{another.Id.Wire}", - ticket); - - Assert.Equal(HttpStatusCode.OK, entered.StatusCode); - Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); - } - - [Fact] - public async Task BrLa004ATicketIssuedForOneRecordingOpensNoOtherEvenOnItsFirstUse() - { - await using var feature = new TicketedFeature(); - Recording mine = feature.Ended(); - Recording another = feature.Ended(); - string ticket = await feature.TicketForAsync(mine.Id); - - using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync( - $"/api/videos/{another.Id.Wire}", - ticket, - "bytes=0-"); - - Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); - Assert.NotEqual(feature.Written, await elsewhere.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task BrLa004ATicketOfferedAtTheWrongRecordingIsSpentAndOpensItsOwnNoLonger() - { - await using var feature = new TicketedFeature(); - Recording mine = feature.Ended(); - Recording another = feature.Ended(); - string ticket = await feature.TicketForAsync(mine.Id); - - using HttpResponseMessage elsewhere = await feature.AsAPlayerAsync($"/api/videos/{another.Id.Wire}", ticket); - using HttpResponseMessage afterwards = await feature.AsAPlayerAsync($"/api/videos/{mine.Id.Wire}", ticket); - - Assert.Equal(HttpStatusCode.Forbidden, elsewhere.StatusCode); - Assert.Equal(HttpStatusCode.Forbidden, afterwards.StatusCode); - } - - [Fact] - public async Task APlayerCarryingNothingIsRefusedWithoutBeingSentToASignInScreen() - { - await using var feature = new TicketedFeature(); - Recording recording = feature.Ended(); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync($"/api/videos/{recording.Id.Wire}", null); - - Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); - Assert.Null(answer.Headers.Location); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task SomethingThatWasNeverIssuedIsRefusedBeforeAnyByteLeaves() - { - await using var feature = new TicketedFeature(); - Recording recording = feature.Ended(); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - $"/api/videos/{recording.Id.Wire}", - new string('a', 43)); - - byte[] body = await answer.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.Forbidden, answer.StatusCode); - Assert.NotEqual(feature.Written, body); - } - - [Theory] - [InlineData("/play")] - [InlineData("/thumbnail")] - [InlineData("/scrub")] - [InlineData("/captions")] - [InlineData("/data-broadcast")] - [InlineData("/data-broadcast/modules/64/7/0/1")] - public async Task TheTicketOpensTheBytesAndNothingElseUnderTheSamePrefix(string beneath) - { - await using var feature = new TicketedFeature(); - Recording recording = feature.Ended(); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync( - $"/api/videos/{recording.Id.Wire}{beneath}", - ticket); - - Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); - Assert.Null(answer.Headers.Location); - } - [Theory] [InlineData("")] [InlineData("/play")] @@ -216,17 +41,4 @@ public async Task EverySurfaceUnderThisPrefixRefusesAStrangerWithTheSameStatus(s Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); Assert.Null(answer.Headers.Location); } - - [Fact] - public async Task TheAnswerToATicketIsNeverHeldByAnythingInFront() - { - await using var feature = new TicketedFeature(); - Recording recording = feature.Ended(); - string ticket = await feature.TicketForAsync(recording.Id); - - using HttpResponseMessage answer = await feature.AsAPlayerAsync($"/api/videos/{recording.Id.Wire}", ticket); - - Assert.Equal("no-store, private", answer.Headers.CacheControl?.ToString()); - Assert.Contains("Authorization", answer.Headers.Vary, StringComparer.OrdinalIgnoreCase); - } } diff --git a/tests/Carina.Api.Tests/FeatureTest/VideoDeliveryTests.cs b/tests/Carina.Api.Tests/FeatureTest/VideoDeliveryTests.cs deleted file mode 100644 index 058c7c90b..000000000 --- a/tests/Carina.Api.Tests/FeatureTest/VideoDeliveryTests.cs +++ /dev/null @@ -1,335 +0,0 @@ -using System.Net; - -using Carina.Domain.Playback; -using Carina.Domain.Recordings; -using Carina.Domain.Streaming; - -namespace Carina.Api.Tests.FeatureTest; - -internal sealed class VanishingPlaybackFiles(long bytes, PlaybackFileAbsence then = PlaybackFileAbsence.Gone) : IPlaybackFileStore -{ - public PlaybackFileSearch Find(OutputRoot root, RecordingFileName fileName) - => PlaybackFileSearch.Of(new PlaybackFile(root, fileName, bytes)); - - public PlaybackFileOpening OpenRead(PlaybackFile file) => PlaybackFileOpening.Missing(then); - - public StreamSource? SourceOf(PlaybackFile file) => null; -} - -public sealed class VideoDeliveryTests -{ - private const int Size = 4_000; - - [Fact] - public async Task TheWholeFileComesBackWhenNoRangeIsAskedFor() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - - using HttpResponseMessage answer = await feature.GetAsync(recording); - byte[] body = await answer.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("bytes", Assert.Single(answer.Headers.AcceptRanges)); - Assert.Equal("video/mp2t", answer.Content.Headers.ContentType?.MediaType); - Assert.Equal(Size, answer.Content.Headers.ContentLength); - Assert.Equal(written, body); - } - - [Fact] - public async Task AskingFromTheStartIsAPartAndCarriesTheWholeFile() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-"); - byte[] body = await answer.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); - Assert.Equal($"bytes 0-{Size - 1}/{Size}", answer.Content.Headers.ContentRange?.ToString()); - Assert.Equal(Size, answer.Content.Headers.ContentLength); - Assert.Equal(written, body); - } - - [Fact] - public async Task AskingFromAnOffsetHandsBackTheBytesFromThatOffset() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=100-"); - byte[] body = await answer.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); - Assert.Equal($"bytes 100-{Size - 1}/{Size}", answer.Content.Headers.ContentRange?.ToString()); - Assert.Equal(written[100..], body); - } - - [Fact] - public async Task AskingForTheLastBytesHandsBackTheEndOfTheFileAndNotItsStart() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=-500"); - byte[] body = await answer.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); - Assert.Equal($"bytes {Size - 500}-{Size - 1}/{Size}", answer.Content.Headers.ContentRange?.ToString()); - Assert.Equal(written[^500..], body); - Assert.NotEqual(written[..500], body); - } - - [Fact] - public async Task AskingForBothEndsHandsBackWhatIsBetweenThem() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=100-199"); - byte[] body = await answer.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); - Assert.Equal(100, body.Length); - Assert.Equal(written[100..200], body); - } - - [Fact] - public async Task ARangeThatStartsPastTheEndIsRefusedWithTheSizeOfWhatThereIs() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=999999-"); - byte[] body = await answer.Content.ReadAsByteArrayAsync(); - - Assert.Equal(HttpStatusCode.RequestedRangeNotSatisfiable, answer.StatusCode); - Assert.Equal($"bytes */{Size}", answer.Content.Headers.ContentRange?.ToString()); - Assert.Equal("bytes", Assert.Single(answer.Headers.AcceptRanges)); - Assert.Empty(body); - } - - [Theory] - [InlineData("bytes=abc")] - [InlineData("bytes=100-50")] - [InlineData("items=0-99")] - public async Task ARangeThatCannotBeReadIsIgnoredAndTheWholeFileComesBack(string range) - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - - using HttpResponseMessage answer = await feature.GetAsync(recording, range); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal(written, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task MoreThanOneRangeIsNotServedAsSeveralParts() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-99,200-299"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Null(answer.Content.Headers.ContentRange); - Assert.Equal(written, await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task AskingOnlyWhatIsThereSendsTheSameHeadersAndNoBody() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); - - using HttpResponseMessage whole = await feature.HeadAsync(recording); - using HttpResponseMessage part = await feature.HeadAsync(recording, "bytes=-500"); - - Assert.Equal(HttpStatusCode.OK, whole.StatusCode); - Assert.Equal("bytes", Assert.Single(whole.Headers.AcceptRanges)); - Assert.Equal(Size, whole.Content.Headers.ContentLength); - Assert.Empty(await whole.Content.ReadAsByteArrayAsync()); - - Assert.Equal(HttpStatusCode.PartialContent, part.StatusCode); - Assert.Equal($"bytes {Size - 500}-{Size - 1}/{Size}", part.Content.Headers.ContentRange?.ToString()); - Assert.Equal(500, part.Content.Headers.ContentLength); - Assert.Empty(await part.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task ARecordingCutShortIsStillHandedOverToAPlayerThatCanReadIt() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Truncated, written); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-9"); - - Assert.Equal(HttpStatusCode.PartialContent, answer.StatusCode); - Assert.Equal(written[..10], await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task ARecordingOfNoBytesHasNoVideoToHandOver() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Failed, []); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-"); - - Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task ARecordingWhoseFileIsGoneWhileItsRootIsThereIsNotFound() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size), onDisk: false); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-"); - - Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task ARecordingWhoseRootIsGoneSaysTheBytesAreOutOfReachRatherThanNotFound() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); - Directory.Delete(feature.MountedAt, recursive: true); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=0-"); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); - } - - [Fact] - public async Task AFileTakenOffTheDiskBetweenBeingFoundAndBeingOpenedIsNotFoundRatherThanHalfServed() - { - await using var feature = new PlaybackFeature(new VanishingPlaybackFiles(Size)); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size), onDisk: false); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=1000-1999"); - - Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task ARootThatWentAwayBetweenTheFileBeingFoundAndOpenedIsOutOfReachRatherThanNotFound() - { - await using var feature = new PlaybackFeature(new VanishingPlaybackFiles(Size, PlaybackFileAbsence.OutOfReach)); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size), onDisk: false); - - using HttpResponseMessage answer = await feature.GetAsync(recording, "bytes=1000-1999"); - - Assert.Equal(HttpStatusCode.ServiceUnavailable, answer.StatusCode); - } - - [Fact] - public async Task ARecordingStillBeingWrittenIsNotHandedOverAsAWholeFile() - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.StillWriting(); - - using HttpResponseMessage answer = await feature.GetAsync(recording); - - Assert.Equal(HttpStatusCode.Conflict, answer.StatusCode); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task ARecordingNobodyHasIsNotFound() - { - await using var feature = new PlaybackFeature(); - - using HttpResponseMessage answer = await feature.Client.GetAsync( - new Uri($"/api/videos/{RecordingId.New().Wire}", UriKind.Relative)); - - Assert.Equal(HttpStatusCode.NotFound, answer.StatusCode); - } - - [Fact] - public async Task ARecordingWithNoArtefactAskedForAsItWasRecordedIsHandedOverAsItIs() - { - await using var feature = new PlaybackFeature(); - byte[] written = PlaybackFeature.Bytes(Size); - Recording recording = feature.Ended(RecordingOutcome.Complete, written); - - using HttpResponseMessage answer = await feature.GetFromAsync(recording, "recording"); - - Assert.Equal(HttpStatusCode.OK, answer.StatusCode); - Assert.Equal("video/mp2t", answer.Content.Headers.ContentType?.MediaType); - Assert.Equal(written, await answer.Content.ReadAsByteArrayAsync()); - } - - [Theory] - [InlineData("proxy")] - [InlineData("Recording ")] - public async Task AFileThatIsNeitherOfTheTwoIsRefusedBeforeAnythingIsHandedOver(string source) - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); - - using HttpResponseMessage answer = await feature.GetFromAsync(recording, source); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task SomethingThatIsNotARecordingIdIsRefusedBeforeAnythingIsLookedFor() - { - await using var feature = new PlaybackFeature(); - - using HttpResponseMessage answer = await feature.Client.GetAsync( - new Uri("/api/videos/not-an-id", UriKind.Relative)); - - Assert.Equal(HttpStatusCode.BadRequest, answer.StatusCode); - } - - [Theory] - [InlineData("GET")] - [InlineData("HEAD")] - public async Task AClientCarryingNoCredentialsIsRefusedRatherThanSentToASignInScreen(string method) - { - await using var feature = new PlaybackFeature(); - Recording recording = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size)); - - using var asking = new HttpRequestMessage( - new HttpMethod(method), - new Uri($"/api/videos/{recording.Id.Wire}", UriKind.Relative)); - using HttpResponseMessage answer = await feature.Stranger.SendAsync(asking); - - Assert.Equal(HttpStatusCode.Unauthorized, answer.StatusCode); - Assert.Null(answer.Headers.Location); - Assert.Empty(await answer.Content.ReadAsByteArrayAsync()); - } - - [Fact] - public async Task NothingHandedBackSaysWhereOnThisMachineTheFileIs() - { - await using var feature = new PlaybackFeature(); - Recording gone = feature.Ended(RecordingOutcome.Complete, PlaybackFeature.Bytes(Size), onDisk: false); - Recording empty = feature.Ended(RecordingOutcome.Failed, []); - - using HttpResponseMessage missing = await feature.GetAsync(gone); - using HttpResponseMessage nothing = await feature.GetAsync(empty, "bytes=0-"); - - Assert.Empty(await missing.Content.ReadAsByteArrayAsync()); - Assert.Empty(await nothing.Content.ReadAsByteArrayAsync()); - Assert.DoesNotContain( - missing.Headers.Concat(missing.Content.Headers), - header => header.Value.Any(value => value.Contains(feature.MountedAt, StringComparison.Ordinal))); - } -} diff --git a/tests/Carina.Api.Tests/Unit/AskedDecodingTests.cs b/tests/Carina.Api.Tests/Unit/App/Playback/AskedDecodingTests.cs similarity index 97% rename from tests/Carina.Api.Tests/Unit/AskedDecodingTests.cs rename to tests/Carina.Api.Tests/Unit/App/Playback/AskedDecodingTests.cs index d64e36596..1ff514dc2 100644 --- a/tests/Carina.Api.Tests/Unit/AskedDecodingTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Playback/AskedDecodingTests.cs @@ -3,8 +3,9 @@ using Microsoft.Extensions.Primitives; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Playback; +[Trait("Category", "Unit")] public sealed class AskedDecodingTests { [Fact(DisplayName = "a browser naming no decoding is one that said nothing")] diff --git a/tests/Carina.Api.Tests/Unit/AskedFormatTests.cs b/tests/Carina.Api.Tests/Unit/App/Playback/AskedFormatTests.cs similarity index 94% rename from tests/Carina.Api.Tests/Unit/AskedFormatTests.cs rename to tests/Carina.Api.Tests/Unit/App/Playback/AskedFormatTests.cs index 9f3503c7a..a5ae0fecd 100644 --- a/tests/Carina.Api.Tests/Unit/AskedFormatTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Playback/AskedFormatTests.cs @@ -1,8 +1,9 @@ using Carina.Api.Playback; using Carina.Domain.Streaming; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Playback; +[Trait("Category", "Unit")] public sealed class AskedFormatTests { [Theory(DisplayName = "a recording played without naming a format is transcoded in H.264, as it always was")] diff --git a/tests/Carina.Api.Tests/Unit/ByteRangeTests.cs b/tests/Carina.Api.Tests/Unit/App/Playback/ByteRangeTests.cs similarity index 98% rename from tests/Carina.Api.Tests/Unit/ByteRangeTests.cs rename to tests/Carina.Api.Tests/Unit/App/Playback/ByteRangeTests.cs index d2bafb721..98fff3671 100644 --- a/tests/Carina.Api.Tests/Unit/ByteRangeTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Playback/ByteRangeTests.cs @@ -1,8 +1,9 @@ using Carina.Api.Playback; using Carina.Domain.Recordings; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Playback; +[Trait("Category", "Unit")] public sealed class ByteRangeTests { private const long Size = 4_000; diff --git a/tests/Carina.Api.Tests/Unit/PlaybackChapterResponderTests.cs b/tests/Carina.Api.Tests/Unit/App/Playback/PlaybackChapterResponderTests.cs similarity index 95% rename from tests/Carina.Api.Tests/Unit/PlaybackChapterResponderTests.cs rename to tests/Carina.Api.Tests/Unit/App/Playback/PlaybackChapterResponderTests.cs index 5299a3e3c..f553bb947 100644 --- a/tests/Carina.Api.Tests/Unit/PlaybackChapterResponderTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Playback/PlaybackChapterResponderTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Encodings; using Carina.Domain.Segments; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Playback; +[Trait("Category", "Unit")] public sealed class PlaybackChapterResponderTests { [Fact(DisplayName = "BR-CD-009: an opening and an ending detected are handed to playback by their own kinds, each skippable as it was")] diff --git a/tests/Carina.Api.Tests/Unit/LiveHlsPlaylistsTests.cs b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveHlsPlaylistsTests.cs similarity index 98% rename from tests/Carina.Api.Tests/Unit/LiveHlsPlaylistsTests.cs rename to tests/Carina.Api.Tests/Unit/App/Streaming/LiveHlsPlaylistsTests.cs index 2d4a60ebd..14cc92941 100644 --- a/tests/Carina.Api.Tests/Unit/LiveHlsPlaylistsTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveHlsPlaylistsTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Auth; using Carina.Domain.Streaming; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Streaming; +[Trait("Category", "Unit")] public sealed class LiveHlsPlaylistsTests { private static readonly string Key = Unguessable.Issue(); diff --git a/tests/Carina.Api.Tests/Unit/LiveRefusalClosuresTests.cs b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveRefusalClosuresTests.cs similarity index 95% rename from tests/Carina.Api.Tests/Unit/LiveRefusalClosuresTests.cs rename to tests/Carina.Api.Tests/Unit/App/Streaming/LiveRefusalClosuresTests.cs index af836d49e..0c24660e0 100644 --- a/tests/Carina.Api.Tests/Unit/LiveRefusalClosuresTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveRefusalClosuresTests.cs @@ -3,8 +3,9 @@ using Carina.Api.Live; using Carina.Domain.Streaming; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Streaming; +[Trait("Category", "Unit")] public sealed class LiveRefusalClosuresTests { [Fact] diff --git a/tests/Carina.Api.Tests/Unit/LiveWireRequestTests.cs b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireRequestTests.cs similarity index 98% rename from tests/Carina.Api.Tests/Unit/LiveWireRequestTests.cs rename to tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireRequestTests.cs index 2b8957ca4..7d9f20a91 100644 --- a/tests/Carina.Api.Tests/Unit/LiveWireRequestTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireRequestTests.cs @@ -5,8 +5,9 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Streaming; +[Trait("Category", "Unit")] public sealed class LiveWireRequestTests { private static readonly LiveSessionKey Asked = new(new NetworkId(32736), new ServiceId(1024), LiveProfile.Hd30); diff --git a/tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireSocketTests.cs b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireSocketTests.cs new file mode 100644 index 000000000..022b41e55 --- /dev/null +++ b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireSocketTests.cs @@ -0,0 +1,1179 @@ +using System.Diagnostics; +using System.Net.WebSockets; +using System.Threading.Channels; + +using Carina.Api.Live; +using Carina.Domain.Channels; +using Carina.Domain.Streaming; +using Carina.Infrastructure.Streaming; +using Carina.TestSupport; + +namespace Carina.Api.Tests.Unit.App.Streaming; + +[Trait("Category", "Unit")] +public sealed class LiveWireSocketTests +{ + private const string NeverCarried = "The wire never carried what was expected of it."; + + private const string NeverSaid = "The wire never said what was expected of it."; + + private static readonly LiveWireSettings Impatient = new( + betweenPings: TimeSpan.FromMilliseconds(30), + writePatience: TimeSpan.FromMilliseconds(200)); + + private static readonly byte[] Picture = [0x01, 0x02, 0x03]; + + private static readonly LiveWireSettings Patient = new( + betweenPings: TimeSpan.FromSeconds(10), + writePatience: TimeSpan.FromMilliseconds(200)); + + private static readonly LiveStartupSegment[] AsTheyHappen = + [ + LiveStartupSegment.TunerSecured, + LiveStartupSegment.TranscoderStarted, + LiveStartupSegment.ChannelLocked, + LiveStartupSegment.InitReached, + LiveStartupSegment.FirstPicture, + ]; + + private static readonly LiveStartup Starting = LiveStartup.NotStarted + .Reaching(LiveStartupSegment.TranscoderStarted, TimeSpan.FromSeconds(8)) + .Reaching(LiveStartupSegment.InitReached, TimeSpan.FromMilliseconds(8100)); + + private static readonly LiveWireSettings Gateway = new( + betweenPings: TimeSpan.FromSeconds(15), + silenceCeiling: TimeSpan.FromSeconds(100)); + + private static readonly LiveWireSettings ImpatientToWrite = new( + betweenPings: TimeSpan.FromSeconds(30), + writePatience: TimeSpan.FromMilliseconds(200)); + + public static TheoryData EveryReasonASupplyEnds() + { + TheoryData reasons = []; + + foreach (LiveSupplyEnd why in Enum.GetValues()) + { + reasons.Add(why); + } + + return reasons; + } + + [Fact] + public async Task AFrameIsSentAsOneBinaryMessageCarryingItsOwnHeader() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); + frames.Writer.Complete(); + + LiveDeparture departure = await Carry(socket, frames); + + Assert.Equal(LiveDeparture.SourceEnded, departure); + Assert.Equal( + [0x01, 0, 0, 0, 0, 0, 0x01, 0x5f, 0x90, 0x01, 0x02, 0x03], + socket.Sent[0]); + } + + [Fact] + public async Task TheHeaderGoesOutBeforeTheFirstPictureThatNeedsIt() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.TryWrite(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Picture)); + frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of(1UL), Picture)); + frames.Writer.Complete(); + + await Carry(socket, frames); + + Assert.Equal( + [(byte)LiveChannel.PictureHeader, (byte)LiveChannel.Picture, (byte)LiveChannel.Control], + socket.Sent.Select(message => message[0]).ToArray()); + } + + [Fact] + public async Task TheSourceRunningOutIsANormalEnding() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.Complete(); + + Assert.Equal(LiveDeparture.SourceEnded, await Carry(socket, frames)); + Assert.True(socket.CloseAttempted); + Assert.Equal(WebSocketCloseStatus.NormalClosure, socket.Closed); + } + + [Fact] + public async Task TheSourceBreakingIsNotANormalEnding() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.Complete(new InvalidOperationException("the transcoder stopped")); + + Assert.Equal(LiveDeparture.SourceBroke, await Carry(socket, frames)); + Assert.Equal(WebSocketCloseStatus.InternalServerError, socket.Closed); + } + + [Fact] + public void EveryEndingSaysWhyInWordsTheViewerIsGiven() + { + Assert.All( + Enum.GetValues(), + departure => Assert.NotEmpty(LiveDepartures.Because(departure))); + } + + [Fact] + public void EveryWayTheSupplyItselfEndsNamesAReasonEvenWhenTheSupplySaidNothing() + { + Assert.Equal(LiveSupplyEnd.WentQuiet, LiveDepartures.Ending(LiveDeparture.SourceWentQuiet)); + Assert.Equal(LiveSupplyEnd.DriverLost, LiveDepartures.Ending(LiveDeparture.SourceEnded)); + Assert.Equal(LiveSupplyEnd.DriverLost, LiveDepartures.Ending(LiveDeparture.SourceBroke)); + } + + [Fact] + public void TheFourWaysThatAreTheViewerOrTheAppRatherThanTheSupplyNameNoReason() + { + Assert.All( + new[] + { + LiveDeparture.ViewerLeft, + LiveDeparture.ViewerStoppedReading, + LiveDeparture.SaidSomethingUnknown, + LiveDeparture.SaidMoreThanTheWireTakes, + LiveDeparture.ServerStopping, + }, + departure => Assert.Null(LiveDepartures.Ending(departure))); + } + + [Fact] + public async Task AWireWhoseSupplyStoppedWithoutSayingWhyStillSaysThatMuch() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.Complete(); + + Assert.Equal(LiveDeparture.SourceEnded, await Carry(socket, frames)); + + LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; + + Assert.Equal(LiveChannel.Control, said.Channel); + Assert.Equal(LiveSupplyEnd.DriverLost, LiveEndingReport.Read(said.Payload.Span).Report!.Why); + } + + [Fact] + public async Task APingGoesOutWhileTheSourceHasNothingToSay() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + + Task carrying = Carry(socket, frames, stop.Token); + + await Until(() => socket.Sent.Count >= 2, NeverCarried); + await stop.CancelAsync(); + await carrying; + + Assert.All( + socket.Sent, + message => Assert.Equal(LiveControls.Frame(LiveControl.Ping).ToArray(), message)); + } + + [Fact] + public async Task NoPingGoesOutAfterTheWireHasBeenToldToStop() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + + await stop.CancelAsync(); + + Assert.Equal(LiveDeparture.ViewerLeft, await Carry(socket, frames, stop.Token)); + Assert.Empty(socket.Sent); + } + + [Fact] + public async Task NoPingInterruptsAWireThatIsCarryingPictures() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + for (int written = 0; written < 20; written++) + { + frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of((ulong)written), Picture)); + } + + frames.Writer.Complete(); + + await Carry(socket, frames); + + Assert.Equal( + Enumerable.Repeat((byte)LiveChannel.Picture, 20).Append((byte)LiveChannel.Control), + socket.Sent.Select(message => message[0])); + } + + [Fact] + public async Task AViewerSayingItIsLeavingIsAnsweredByLettingItGo() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + socket.Say(new WebSocketSaying( + WebSocketMessageType.Binary, + LiveControls.Frame(LiveControl.Leaving).ToArray())); + + Assert.Equal(LiveDeparture.ViewerLeft, await Carry(socket, frames)); + Assert.Equal(WebSocketCloseStatus.NormalClosure, socket.Closed); + } + + [Fact] + public async Task AViewerClosingTheSocketIsTheSameAsSayingItIsLeaving() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + socket.Say(new WebSocketSaying(WebSocketMessageType.Close, [])); + + Assert.Equal(LiveDeparture.ViewerLeft, await Carry(socket, frames)); + } + + [Fact] + public async Task AViewerAnsweringAPingIsNotAnEnding() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + socket.Say(new WebSocketSaying( + WebSocketMessageType.Binary, + LiveControls.Frame(LiveControl.Pong).ToArray())); + socket.Say(new WebSocketSaying( + WebSocketMessageType.Binary, + LiveControls.Frame(LiveControl.Leaving).ToArray())); + + Assert.Equal(LiveDeparture.ViewerLeft, await Carry(socket, frames)); + } + + [Fact] + public async Task AViewerSayingSomethingThatIsNotAControlMessageIsShownOut() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + socket.Say(new WebSocketSaying(WebSocketMessageType.Binary, [0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f])); + + Assert.Equal(LiveDeparture.SaidSomethingUnknown, await Carry(socket, frames)); + Assert.Equal(WebSocketCloseStatus.InvalidPayloadData, socket.Closed); + } + + [Fact] + public async Task AViewerRepeatingWhatOnlyTheServerSaysIsShownOut() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + socket.Say(new WebSocketSaying( + WebSocketMessageType.Binary, + LiveControls.Frame(LiveControl.Ping).ToArray())); + + Assert.Equal(LiveDeparture.SaidSomethingUnknown, await Carry(socket, frames)); + } + + [Fact] + public async Task AViewerPushingBytesUpAPictureChannelIsShownOut() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + socket.Say(new WebSocketSaying( + WebSocketMessageType.Binary, + new LiveFrame(LiveChannel.Picture, LivePts.Start, Picture).ToArray())); + + Assert.Equal(LiveDeparture.SaidSomethingUnknown, await Carry(socket, frames)); + } + + [Fact] + public async Task AViewerTypingWordsAtTheWireIsShownOut() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + socket.Say(new WebSocketSaying(WebSocketMessageType.Text, "seek 42"u8.ToArray())); + + Assert.Equal(LiveDeparture.SaidSomethingUnknown, await Carry(socket, frames)); + } + + [Fact] + public async Task AViewerSendingMoreThanTheWireTakesIsShownOut() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + socket.Say(new WebSocketSaying( + WebSocketMessageType.Binary, + new byte[Impatient.LargestFrameFromAViewer + 64])); + + Assert.Equal(LiveDeparture.SaidMoreThanTheWireTakes, await Carry(socket, frames)); + Assert.Equal(WebSocketCloseStatus.MessageTooBig, socket.Closed); + } + + [Fact] + public async Task AViewerThatStopsReadingIsGivenUpOnRatherThanHoldingTheSource() + { + var socket = new ScriptedWebSocket { HoldEverySend = TimeSpan.FromSeconds(30) }; + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Start, Picture)); + + Assert.Equal(LiveDeparture.ViewerStoppedReading, await Carry(socket, frames)); + Assert.True(socket.Aborted); + Assert.False(socket.CloseAttempted); + Assert.Null(socket.Closed); + } + + [Fact] + public async Task AWireCarryingAFrameLargerThanAnythingTheFragmenterHoldsStillSendsItWhole() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Start, new byte[4 * 1024 * 1024])); + frames.Writer.Complete(); + + await Carry(socket, frames); + + Assert.Equal(LiveFrame.HeaderLength + (4 * 1024 * 1024), socket.Sent[0].Length); + } + + [Fact] + public async Task TheAppShuttingDownIsNotTheViewerLeaving() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stopping = new CancellationTokenSource(); + using var stop = new CancellationTokenSource(); + + Task carrying = new LiveWireSocket(socket, Impatient) + .CarryAsync(frames.Reader, stopping.Token, stop.Token); + + await stopping.CancelAsync(); + await stop.CancelAsync(); + + Assert.Equal(LiveDeparture.ServerStopping, await carrying); + Assert.Equal(WebSocketCloseStatus.EndpointUnavailable, socket.Closed); + } + + [Fact] + public async Task WhyTheSupplyEndedIsSaidOnTheControlChannelAfterTheLastFrameAndBeforeTheClose() + { + ScriptedWebSocket socket = new(); + Channel frames = Channel.CreateUnbounded(); + HeldEnding ending = new(LiveSupplyEnding.Of(LiveSupplyEnd.TakenForARecording, "a recording outranked it.")); + + frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); + frames.Writer.Complete(); + + LiveDeparture departure = await Carry(socket, frames, ending); + + Assert.Equal(LiveDeparture.SourceEnded, departure); + Assert.Equal(2, socket.Sent.Count); + Assert.Equal(LiveChannel.Picture, LiveFrame.Read(socket.Sent[0]).Frame!.Channel); + + LiveFrame said = LiveFrame.Read(socket.Sent[1]).Frame!; + + Assert.Equal(LiveChannel.Control, said.Channel); + + LiveEndingReading read = LiveEndingReport.Read(said.Payload.Span); + + Assert.Null(read.Fault); + Assert.Equal(LiveSupplyEnd.TakenForARecording, read.Report!.Why); + Assert.Equal(WebSocketCloseStatus.NormalClosure, socket.Closed); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), socket.ClosedBecause); + } + + [Fact] + public async Task ASourceThatBreaksStillSaysWhyItEndedWhenTheSupplyKnows() + { + ScriptedWebSocket socket = new(); + Channel frames = Channel.CreateUnbounded(); + HeldEnding ending = new(LiveSupplyEnding.Of(LiveSupplyEnd.DriverLost, "the driver went away.")); + + frames.Writer.Complete(new InvalidOperationException("What was being sent live broke.")); + + LiveDeparture departure = await Carry(socket, frames, ending); + + Assert.Equal(LiveDeparture.SourceBroke, departure); + + LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; + + Assert.Equal(LiveSupplyEnd.DriverLost, LiveEndingReport.Read(said.Payload.Span).Report!.Why); + Assert.Equal(WebSocketCloseStatus.InternalServerError, socket.Closed); + } + + [Theory] + [MemberData(nameof(EveryReasonASupplyEnds))] + public async Task AWireIsNeverClosedWithoutTheReasonHavingBeenSaidFirst(LiveSupplyEnd why) + { + ScriptedWebSocket socket = new(); + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.Complete(); + + LiveDeparture departure = await Carry( + socket, + frames, + new HeldEnding(LiveSupplyEnding.Of(why, "the supply named a reason."))); + + Assert.Equal(LiveDeparture.SourceEnded, departure); + + LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; + + Assert.Equal(LiveChannel.Control, said.Channel); + Assert.Equal(why, LiveEndingReport.Read(said.Payload.Span).Report!.Why); + Assert.Equal(WebSocketCloseStatus.NormalClosure, socket.Closed); + } + + [Fact] + public async Task WhatIsSaidIsNeitherAPingNorARefusalNorAProgressReportNorSomethingAViewerCouldSay() + { + ScriptedWebSocket socket = new(); + Channel frames = Channel.CreateUnbounded(); + + frames.Writer.Complete(); + + await Carry(socket, frames, new HeldEnding(LiveSupplyEnding.Of(LiveSupplyEnd.WindowClosed, "the window closed."))); + + LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; + + Assert.Equal(LiveEndingReport.PayloadLength, said.Payload.Length); + Assert.Null(LiveControls.SaidByAViewer(said.Payload.Span)); + Assert.NotNull(LiveRefusalReport.Read(said.Payload.Span).Fault); + Assert.NotNull(LiveStartup.ReadProgress(said.Payload.Span).Fault); + } + + [Fact] + public async Task ProgressGoesOutRightAfterTheHandshakeWhileTheStartupIsStillRunning() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + + Task carrying = Carry(socket, frames, new HeldStartup(Starting), stop.Token); + + await Until(() => socket.Sent.Count >= 1, NeverSaid); + await stop.CancelAsync(); + await carrying; + + LiveFrame first = LiveFrame.Read(socket.Sent[0]).Frame!; + + Assert.Equal(LiveChannel.Control, first.Channel); + + LiveStartupReading read = LiveStartup.ReadProgress(first.Payload.Span); + + Assert.Null(read.Fault); + Assert.Equal(TimeSpan.FromSeconds(8), read.Startup!.At(LiveStartupSegment.TranscoderStarted)); + Assert.Equal(TimeSpan.FromMilliseconds(8100), read.Startup.At(LiveStartupSegment.InitReached)); + Assert.False(read.Startup.Reached(LiveStartupSegment.FirstPicture)); + } + + [Fact] + public async Task AProgressReportRidesTheControlChannelButIsNotSomethingAViewerCouldEverSay() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + + Task carrying = Carry(socket, frames, new HeldStartup(Starting), stop.Token); + + await Until(() => socket.Sent.Count >= 1, NeverSaid); + await stop.CancelAsync(); + await carrying; + + LiveFrame first = LiveFrame.Read(socket.Sent[0]).Frame!; + + Assert.Equal(LiveChannel.Control, first.Channel); + Assert.NotEqual(1, first.Payload.Length); + Assert.Null(LiveControls.SaidByAViewer(first.Payload.Span)); + } + + [Fact] + public async Task OnceTheFirstPictureIsReachedTheWireFallsBackToTheKeepAlivePing() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + + LiveStartup done = Starting.Reaching(LiveStartupSegment.FirstPicture, TimeSpan.FromMilliseconds(10100)); + + Task carrying = Carry(socket, frames, new HeldStartup(done), stop.Token); + + await Until(() => socket.Sent.Count >= 2, NeverSaid); + await stop.CancelAsync(); + await carrying; + + Assert.All( + socket.Sent, + message => Assert.Equal(LiveControls.Frame(LiveControl.Ping).ToArray(), message)); + } + + [Fact] + public async Task AWireWithNothingToReportSaysNothingButTheKeepAlivePing() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + + Task carrying = Carry(socket, frames, new HeldStartup(null), stop.Token); + + await Until(() => socket.Sent.Count >= 2, NeverSaid); + await stop.CancelAsync(); + await carrying; + + Assert.All( + socket.Sent, + message => Assert.Equal(LiveControls.Frame(LiveControl.Ping).ToArray(), message)); + } + + [Fact] + public async Task AReportGoesOutEachTimeASegmentIsReachedNotOnlyWhenTheWireFallsQuiet() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + var startup = new SteppingStartup(); + + Task carrying = new LiveWireSocket(socket, Patient, startup) + .CarryAsync(frames.Reader, CancellationToken.None, stop.Token); + + await Until(() => socket.Sent.Count >= 1, NeverSaid); + + int reached = 0; + + foreach (LiveStartupSegment segment in AsTheyHappen) + { + reached++; + startup.Reach(segment, TimeSpan.FromMilliseconds(100 * reached)); + + int expected = reached + 1; + + await Until(() => socket.Sent.Count >= expected, NeverSaid); + } + + await Task.Delay(150); + await stop.CancelAsync(); + await carrying; + + LiveStartup[] reports = [.. socket.Sent.Select(Reported)]; + + Assert.Equal(6, reports.Length); + Assert.Equal([0, 1, 2, 3, 4, 5], reports.Select(report => report.Timeline.Count(mark => mark.Reached))); + Assert.True(reports[2].Reached(LiveStartupSegment.TranscoderStarted)); + Assert.False(reports[2].Reached(LiveStartupSegment.ChannelLocked)); + Assert.False(reports[^1].InProgress); + } + + [Fact] + public async Task AStepTheWireHadAlreadyReportedIsNotReportedAgainUntilTheNextOne() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + var startup = new SteppingStartup(); + + startup.Reach(LiveStartupSegment.TunerSecured, TimeSpan.FromMilliseconds(100)); + startup.Reach(LiveStartupSegment.TranscoderStarted, TimeSpan.FromMilliseconds(110)); + + Task carrying = new LiveWireSocket(socket, Patient, startup) + .CarryAsync(frames.Reader, CancellationToken.None, stop.Token); + + await Until(() => socket.Sent.Count >= 1, NeverSaid); + await Task.Delay(150); + + Assert.Single(socket.Sent); + + startup.Reach(LiveStartupSegment.ChannelLocked, TimeSpan.FromMilliseconds(700)); + + await Until(() => socket.Sent.Count >= 2, NeverSaid); + await Task.Delay(150); + await stop.CancelAsync(); + await carrying; + + Assert.Equal(2, socket.Sent.Count); + Assert.Equal(2, Reported(socket.Sent[0]).Timeline.Count(mark => mark.Reached)); + Assert.Equal(3, Reported(socket.Sent[1]).Timeline.Count(mark => mark.Reached)); + } + + [Fact] + public async Task TheKeepAlivePingTakesOverOnceTheLastStepHasBeenReported() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + using var stop = new CancellationTokenSource(); + var startup = new SteppingStartup(); + + Task carrying = new LiveWireSocket(socket, Impatient, startup) + .CarryAsync(frames.Reader, CancellationToken.None, stop.Token); + + await Until(() => socket.Sent.Count >= 1, NeverSaid); + + foreach (LiveStartupSegment segment in AsTheyHappen) + { + startup.Reach(segment, TimeSpan.FromMilliseconds(100)); + } + + await Until(() => socket.Sent.Any(message => message.SequenceEqual(LiveControls.Frame(LiveControl.Ping).ToArray())), NeverSaid); + await stop.CancelAsync(); + await carrying; + + byte[][] afterTheLast = [.. socket.Sent.SkipWhile(message => !Reported(message, out LiveStartup? report) || report!.InProgress).Skip(1)]; + + Assert.NotEmpty(afterTheLast); + Assert.All(afterTheLast, message => Assert.Equal(LiveControls.Frame(LiveControl.Ping).ToArray(), message)); + } + + [Fact] + public async Task ProgressDoesNotInterruptTheFramesTheSourceIsAlreadySending() + { + var socket = new ScriptedWebSocket(); + Channel frames = Channel.CreateUnbounded(); + + for (int written = 0; written < 10; written++) + { + frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of((ulong)written), Picture)); + } + + frames.Writer.Complete(); + + await Carry(socket, frames, new HeldStartup(Starting), CancellationToken.None); + + Assert.Equal(10, socket.Sent.Count(message => message[0] == (byte)LiveChannel.Picture)); + } + + [Fact] + public async Task ARefusalIsSaidOnTheControlChannelAndThenTheWireIsClosedWithItsReason() + { + ScriptedWebSocket socket = new(); + + await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( + LiveJoin.Refused(LiveRefusal.NoTunerFree, "every tuner is recording."), + CancellationToken.None); + + LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; + + Assert.Equal(LiveChannel.Control, said.Channel); + Assert.Equal(LivePts.Start, said.Pts); + + LiveRefusalReading read = LiveRefusalReport.Read(said.Payload.Span); + + Assert.Null(read.Fault); + Assert.Equal(LiveRefusal.NoTunerFree, read.Report!.Refusal); + Assert.Equal(WebSocketCloseStatus.PolicyViolation, socket.Closed); + Assert.Equal(LiveRefusalClosures.Because(LiveRefusal.NoTunerFree), socket.ClosedBecause); + Assert.False(socket.Aborted); + } + + [Fact] + public async Task AFullBudgetIsSaidWithItsCeiling() + { + ScriptedWebSocket socket = new(); + + await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( + LiveJoin.Refused(new TranscodeCeiling(4, 4)), + CancellationToken.None); + + LiveRefusalReading read = LiveRefusalReport.Read(LiveFrame.Read(socket.Sent[0]).Frame!.Payload.Span); + + Assert.Equal(LiveRefusal.TooManyAlready, read.Report!.Refusal); + Assert.Equal(new TranscodeCeiling(4, 4), read.Report.Ceiling); + } + + [Theory] + [InlineData(TuneFailureKind.NoLock)] + [InlineData(TuneFailureKind.NoData)] + [InlineData(TuneFailureKind.IncompletePsi)] + [InlineData(TuneFailureKind.StreamMismatch)] + public async Task BrTd004TheReasonATuningFailedLeavesTheWireBesideTheRefusalRatherThanOnlyInTheNote( + TuneFailureKind kind) + { + ScriptedWebSocket socket = new(); + + await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( + LiveJoin.Refused(LiveRefusal.WouldNotTune, "no lock.", LiveRefusalDetail.Of(kind)), + CancellationToken.None); + + LiveRefusalReading read = LiveRefusalReport.Read(LiveFrame.Read(socket.Sent[0]).Frame!.Payload.Span); + + Assert.Null(read.Fault); + Assert.Equal(LiveRefusal.WouldNotTune, read.Report!.Refusal); + Assert.Equal(kind, read.Report.Detail.TuneFailure); + } + + [Fact] + public async Task Fr012WhatHoldsTheTunerLeavesTheWireBesideTheRefusalTheSameWay() + { + ScriptedWebSocket socket = new(); + + await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( + LiveJoin.Refused( + LiveRefusal.NoTunerFree, + "a recording holds it.", + LiveRefusalDetail.Of(LiveTunerHolder.ARecording)), + CancellationToken.None); + + LiveRefusalReading read = LiveRefusalReport.Read(LiveFrame.Read(socket.Sent[0]).Frame!.Payload.Span); + + Assert.Null(read.Fault); + Assert.Equal(LiveRefusal.NoTunerFree, read.Report!.Refusal); + Assert.Equal(LiveTunerHolder.ARecording, read.Report.Detail.Holder); + Assert.Equal(LiveRefusalReport.PayloadLength, LiveFrame.Read(socket.Sent[0]).Frame!.Payload.Length); + } + + [Fact] + public async Task WhatIsSaidIsNeitherAPingNorAProgressReportNorSomethingAViewerCouldSay() + { + ScriptedWebSocket socket = new(); + + await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( + LiveJoin.Refused(LiveRefusal.DriverUnavailable, "nothing supplies a stream."), + CancellationToken.None); + + LiveFrame said = LiveFrame.Read(socket.Sent[0]).Frame!; + + Assert.Equal(LiveRefusalReport.PayloadLength, said.Payload.Length); + Assert.Null(LiveControls.SaidByAViewer(said.Payload.Span)); + Assert.NotNull(LiveStartup.ReadProgress(said.Payload.Span).Fault); + } + + [Fact] + public async Task ASeatedViewerCannotBeRefused() + { + ScriptedWebSocket socket = new(); + + await Assert.ThrowsAsync(() => new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( + LiveJoin.Joined(new SeatedNowhere()), + CancellationToken.None)); + + Assert.Empty(socket.Sent); + } + + [Fact] + public async Task AViewerThatNeverAnswersTheCloseIsCutOffRatherThanWaitedFor() + { + SilentWebSocket socket = new(); + + await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( + LiveJoin.Refused(LiveRefusal.WouldNotTune, "no lock."), + CancellationToken.None); + + Assert.True(socket.Aborted); + } + + [Fact] + public async Task ASupplyThatSaysNothingPastTheCeilingIsTakenForGoneAndTheWireIsClosed() + { + ScriptedWebSocket socket = new(); + Channel frames = Channel.CreateUnbounded(); + HandTurnedClock clock = new(); + + Task carrying = Carrying(socket, frames, clock); + + await WaitOutTheCeiling(clock); + + Assert.Equal(LiveDeparture.SourceWentQuiet, await carrying.WaitAsync(Eventually.Patience)); + Assert.Equal(WebSocketCloseStatus.InternalServerError, socket.Closed); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceWentQuiet), socket.ClosedBecause); + Assert.Equal(Gateway.QuietsBeforeTheCeiling + 1, socket.Sent.Count); + Assert.All( + socket.Sent.Take(Gateway.QuietsBeforeTheCeiling), + sent => Assert.Equal( + [(byte)LiveControl.Ping], + LiveFrame.Read(sent).Frame!.Payload.ToArray())); + } + + [Fact] + public async Task AWireTakingItsSupplyForGoneSaysSoOnTheControlChannelBeforeItIsClosed() + { + ScriptedWebSocket socket = new(); + HandTurnedClock clock = new(); + LiveStartupRecord startup = new(clock); + LiveEndingRecord ending = new(); + LiveFanout fanout = new(new LiveFanoutSettings(), startup, ending); + + Started(startup); + + await using ILiveViewing viewing = await Joined(fanout); + + Task carrying = Carrying(socket, viewing, clock); + + await WaitOutTheCeiling(clock); + + Assert.Equal(LiveDeparture.SourceWentQuiet, await carrying.WaitAsync(Eventually.Patience)); + Assert.Null(ending.Current); + + LiveFrame said = LiveFrame.Read(socket.Sent[^1]).Frame!; + + Assert.Equal(LiveChannel.Control, said.Channel); + + LiveEndingReading read = LiveEndingReport.Read(said.Payload.Span); + + Assert.Null(read.Fault); + Assert.Equal(LiveSupplyEnd.WentQuiet, read.Report!.Why); + Assert.Equal(WebSocketCloseStatus.InternalServerError, socket.Closed); + Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceWentQuiet), socket.ClosedBecause); + } + + [Fact] + public async Task WhatTheSupplyItselfSaidIsPreferredToTheWireTakingItForGone() + { + ScriptedWebSocket socket = new(); + HandTurnedClock clock = new(); + LiveStartupRecord startup = new(clock); + LiveEndingRecord ending = new(); + LiveFanout fanout = new(new LiveFanoutSettings(), startup, ending); + + Started(startup); + ending.Note(LiveSupplyEnding.Of(LiveSupplyEnd.TakenForARecording, "a recording outranked it.")); + + await using ILiveViewing viewing = await Joined(fanout); + + Task carrying = Carrying(socket, viewing, clock); + + await WaitOutTheCeiling(clock); + + Assert.Equal(LiveDeparture.SourceWentQuiet, await carrying.WaitAsync(Eventually.Patience)); + + LiveFrame said = LiveFrame.Read(socket.Sent[^1]).Frame!; + + Assert.Equal(LiveSupplyEnd.TakenForARecording, LiveEndingReport.Read(said.Payload.Span).Report!.Why); + } + + [Fact] + public async Task TheCeilingIsCountedFromTheLastFrameSoAWireStillBeingFedIsNeverClosedForQuiet() + { + ScriptedWebSocket socket = new(); + Channel frames = Channel.CreateUnbounded(); + HandTurnedClock clock = new(); + + Task carrying = Carrying(socket, frames, clock); + + int sent = 0; + + for (int rounds = 0; rounds < 4; rounds++) + { + for (int quiet = 0; quiet < Gateway.QuietsBeforeTheCeiling; quiet++) + { + await WaitingOutTheQuiet(clock); + clock.Turn(Gateway.BetweenPings); + sent++; + } + + frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Start, Picture)); + sent++; + + await Eventually.Happens(() => socket.Sent.Count == sent, "the picture reaches the wire"); + } + + Assert.False(carrying.IsCompleted); + Assert.Null(socket.Closed); + + frames.Writer.Complete(); + + Assert.Equal(LiveDeparture.SourceEnded, await carrying); + Assert.Equal(sent + 1, socket.Sent.Count); + Assert.Equal( + (byte)LiveChannel.Control, + socket.Sent[^1][0]); + } + + [Fact] + public async Task OneViewerHoldingItsSocketNeitherHoldsUpAnotherNorTheSource() + { + LiveFanout fanout = new(new LiveFanoutSettings { LongestBacklog = 3 }); + ScriptedWebSocket prompt = new(); + ScriptedWebSocket held = new() { HoldEverySend = TimeSpan.FromSeconds(30) }; + await using ILiveViewing promptViewing = await Joined(fanout); + await using ILiveViewing heldViewing = await Joined(fanout); + + Task promptCarrying = Carry(prompt, promptViewing); + Task heldCarrying = Carry(held, heldViewing); + + for (ulong pts = 0; pts < 20; pts++) + { + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(pts), Picture)); + await Eventually.Happens(() => prompt.Sent.Count == (int)pts + 1, "the prompt socket takes the frame"); + } + + fanout.End(); + + Assert.Equal(LiveDeparture.SourceEnded, await promptCarrying); + Assert.Equal(LiveDeparture.ViewerStoppedReading, await heldCarrying); + Assert.Equal( + Enumerable.Repeat((byte)LiveChannel.Picture, 20).Append((byte)LiveChannel.Control), + prompt.Sent.Select(message => message[0])); + Assert.Equal(LiveBacklog.Empty, promptViewing.Backlog); + Assert.InRange(heldViewing.Backlog.Dropped, 16L, 17L); + Assert.Empty(held.Sent); + Assert.True(held.Aborted); + } + + [Fact] + public async Task TheHeaderReachesAViewerThatJoinedAfterItWasSentBeforeAnyPicture() + { + LiveFanout fanout = new(new LiveFanoutSettings()); + ScriptedWebSocket socket = new(); + + fanout.Publish(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Picture)); + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(1UL), Picture)); + + await using ILiveViewing viewing = await Joined(fanout); + + Task carrying = Carry(socket, viewing); + + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(2UL), Picture)); + fanout.End(); + + Assert.Equal(LiveDeparture.SourceEnded, await carrying); + Assert.Equal( + [(byte)LiveChannel.PictureHeader, (byte)LiveChannel.Picture, (byte)LiveChannel.Control], + socket.Sent.Select(message => message[0]).ToArray()); + Assert.Equal(2UL, LiveFrame.Read(socket.Sent[1]).Frame?.Pts.Value); + } + + [Fact] + public async Task TheSourceBreakingReachesEveryWireAsABreakRatherThanAnEnd() + { + LiveFanout fanout = new(new LiveFanoutSettings()); + ScriptedWebSocket one = new(); + ScriptedWebSocket another = new(); + await using ILiveViewing oneViewing = await Joined(fanout); + await using ILiveViewing anotherViewing = await Joined(fanout); + + Task oneCarrying = Carry(one, oneViewing); + Task anotherCarrying = Carry(another, anotherViewing); + + fanout.Break(LiveFragmentFault.StoppedPartWayThrough); + + Assert.Equal(LiveDeparture.SourceBroke, await oneCarrying); + Assert.Equal(LiveDeparture.SourceBroke, await anotherCarrying); + } + + private static Task Carry( + ScriptedWebSocket socket, + Channel frames, + CancellationToken cancellationToken = default) + => new LiveWireSocket(socket, Impatient) + .CarryAsync(frames.Reader, CancellationToken.None, cancellationToken); + + private static Task Carry(ScriptedWebSocket socket, Channel frames, ILiveEnding ending) + => new LiveWireSocket(socket, new LiveWireSettings(), null, ending).CarryAsync( + frames.Reader, + CancellationToken.None, + CancellationToken.None); + + private static Task Carry( + ScriptedWebSocket socket, + Channel frames, + ILiveStartup startup, + CancellationToken cancellationToken) + => new LiveWireSocket(socket, Impatient, startup) + .CarryAsync(frames.Reader, CancellationToken.None, cancellationToken); + + private static Task Carry(ScriptedWebSocket socket, ILiveViewing viewing) + => new LiveWireSocket(socket, ImpatientToWrite) + .CarryAsync(viewing.Frames, CancellationToken.None, CancellationToken.None); + + private static Task Carrying( + ScriptedWebSocket socket, + Channel frames, + TimeProvider clock) + => new LiveWireSocket(socket, Gateway, null, null, clock).CarryAsync( + frames.Reader, + CancellationToken.None, + CancellationToken.None); + + private static Task Carrying( + ScriptedWebSocket socket, + ILiveViewing viewing, + TimeProvider clock) + => new LiveWireSocket(socket, Gateway, viewing.Startup, viewing.Ending, clock).CarryAsync( + viewing.Frames, + CancellationToken.None, + CancellationToken.None); + + private static async Task Until(Func settled, string never) + { + for (int tries = 0; tries < 200; tries++) + { + if (settled()) + { + return; + } + + await Task.Delay(25); + } + + Assert.Fail(never); + } + + private static LiveStartup Reported(byte[] message) + { + Assert.True(Reported(message, out LiveStartup? report), "the wire said something that is not a progress report."); + + return report!; + } + + private static bool Reported(byte[] message, out LiveStartup? report) + { + report = null; + + if (LiveFrame.Read(message).Frame is not { Channel: LiveChannel.Control } frame + || frame.Payload.Length != LiveStartup.PayloadLength) + { + return false; + } + + report = LiveStartup.ReadProgress(frame.Payload.Span).Startup; + + return report is not null; + } + + private static void Started(LiveStartupRecord startup) + { + foreach (LiveStartupSegment segment in LiveStartupSegments.InOrder) + { + startup.Reach(segment); + } + } + + private static async Task Joined(LiveFanout fanout) + { + ILiveViewing? viewing = await fanout.JoinAsync(CancellationToken.None); + + Assert.NotNull(viewing); + + return viewing; + } + + private static async Task WaitOutTheCeiling(HandTurnedClock clock) + { + for (int quiet = 0; quiet <= Gateway.QuietsBeforeTheCeiling; quiet++) + { + await WaitingOutTheQuiet(clock); + clock.Turn(Gateway.BetweenPings); + } + } + + private static Task WaitingOutTheQuiet(HandTurnedClock clock) + => Eventually.Happens( + () => clock.Waiting.SequenceEqual([Gateway.BetweenPings]), + "the wire is waiting out the quiet"); + + private sealed class HeldEnding(LiveSupplyEnding? current) : ILiveEnding + { + public LiveSupplyEnding? Current => current; + } + + private sealed class HeldStartup(LiveStartup? current) : ILiveStartup + { + public LiveStartup? Current { get; } = current; + + public Task Advanced { get; } = new TaskCompletionSource().Task; + } + + private sealed class SteppingStartup : ILiveStartup + { + private readonly Lock gate = new(); + + private TaskCompletionSource advanced = new(TaskCreationOptions.RunContinuationsAsynchronously); + + private LiveStartup current = LiveStartup.NotStarted; + + public LiveStartup? Current + { + get + { + lock (gate) + { + return current; + } + } + } + + public Task Advanced + { + get + { + lock (gate) + { + return advanced.Task; + } + } + } + + public void Reach(LiveStartupSegment segment, TimeSpan at) + { + TaskCompletionSource told; + + lock (gate) + { + current = current.Reaching(segment, at); + told = advanced; + advanced = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + + told.SetResult(); + } + } + + private sealed class SeatedNowhere : ILiveViewing + { + public ChannelReader Frames { get; } = Channel.CreateUnbounded().Reader; + + public LiveBacklog Backlog => LiveBacklog.Empty; + + public ILiveStartup? Startup => null; + + public ILiveEnding? Ending => null; + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private sealed class SilentWebSocket : WebSocket + { + public override WebSocketCloseStatus? CloseStatus => null; + + public override string? CloseStatusDescription => null; + + public override string? SubProtocol => null; + + public override WebSocketState State => WebSocketState.Open; + + public bool Aborted { get; private set; } + + public override void Abort() => Aborted = true; + + public override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) + => Task.CompletedTask; + + public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) + => Task.CompletedTask; + + public override void Dispose() + { + } + + public override async Task ReceiveAsync(ArraySegment buffer, CancellationToken cancellationToken) + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + + throw new UnreachableException(); + } + + public override Task SendAsync(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) + => Task.CompletedTask; + } +} diff --git a/tests/Carina.Api.Tests/Unit/LiveWireDepartureTests.cs b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireTests.cs similarity index 97% rename from tests/Carina.Api.Tests/Unit/LiveWireDepartureTests.cs rename to tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireTests.cs index 6611aef11..82abbd047 100644 --- a/tests/Carina.Api.Tests/Unit/LiveWireDepartureTests.cs +++ b/tests/Carina.Api.Tests/Unit/App/Streaming/LiveWireTests.cs @@ -11,9 +11,10 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Abstractions; -namespace Carina.Api.Tests.Unit; +namespace Carina.Api.Tests.Unit.App.Streaming; -public sealed class LiveWireDepartureTests +[Trait("Category", "Unit")] +public sealed class LiveWireTests { private static readonly DateTimeOffset Opened = new(2026, 9, 13, 4, 0, 0, TimeSpan.Zero); diff --git a/tests/Carina.Api.Tests/Unit/LiveFanoutWireTests.cs b/tests/Carina.Api.Tests/Unit/LiveFanoutWireTests.cs deleted file mode 100644 index 465566e25..000000000 --- a/tests/Carina.Api.Tests/Unit/LiveFanoutWireTests.cs +++ /dev/null @@ -1,100 +0,0 @@ -using Carina.Api.Live; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -namespace Carina.Api.Tests.Unit; - -public sealed class LiveFanoutWireTests -{ - private static readonly LiveWireSettings Impatient = new( - betweenPings: TimeSpan.FromSeconds(30), - writePatience: TimeSpan.FromMilliseconds(200)); - - private static readonly byte[] Picture = [0x01, 0x02, 0x03]; - - [Fact] - public async Task OneViewerHoldingItsSocketNeitherHoldsUpAnotherNorTheSource() - { - LiveFanout fanout = new(new LiveFanoutSettings { LongestBacklog = 3 }); - ScriptedWebSocket prompt = new(); - ScriptedWebSocket held = new() { HoldEverySend = TimeSpan.FromSeconds(30) }; - await using ILiveViewing promptViewing = await Joined(fanout); - await using ILiveViewing heldViewing = await Joined(fanout); - - Task promptCarrying = Carry(prompt, promptViewing); - Task heldCarrying = Carry(held, heldViewing); - - for (ulong pts = 0; pts < 20; pts++) - { - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(pts), Picture)); - await Eventually.Happens(() => prompt.Sent.Count == (int)pts + 1, "the prompt socket takes the frame"); - } - - fanout.End(); - - Assert.Equal(LiveDeparture.SourceEnded, await promptCarrying); - Assert.Equal(LiveDeparture.ViewerStoppedReading, await heldCarrying); - Assert.Equal( - Enumerable.Repeat((byte)LiveChannel.Picture, 20).Append((byte)LiveChannel.Control), - prompt.Sent.Select(message => message[0])); - Assert.Equal(LiveBacklog.Empty, promptViewing.Backlog); - Assert.InRange(heldViewing.Backlog.Dropped, 16L, 17L); - Assert.Empty(held.Sent); - Assert.True(held.Aborted); - } - - [Fact] - public async Task TheHeaderReachesAViewerThatJoinedAfterItWasSentBeforeAnyPicture() - { - LiveFanout fanout = new(new LiveFanoutSettings()); - ScriptedWebSocket socket = new(); - - fanout.Publish(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Picture)); - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(1UL), Picture)); - - await using ILiveViewing viewing = await Joined(fanout); - - Task carrying = Carry(socket, viewing); - - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(2UL), Picture)); - fanout.End(); - - Assert.Equal(LiveDeparture.SourceEnded, await carrying); - Assert.Equal( - [(byte)LiveChannel.PictureHeader, (byte)LiveChannel.Picture, (byte)LiveChannel.Control], - socket.Sent.Select(message => message[0]).ToArray()); - Assert.Equal(2UL, LiveFrame.Read(socket.Sent[1]).Frame?.Pts.Value); - } - - [Fact] - public async Task TheSourceBreakingReachesEveryWireAsABreakRatherThanAnEnd() - { - LiveFanout fanout = new(new LiveFanoutSettings()); - ScriptedWebSocket one = new(); - ScriptedWebSocket another = new(); - await using ILiveViewing oneViewing = await Joined(fanout); - await using ILiveViewing anotherViewing = await Joined(fanout); - - Task oneCarrying = Carry(one, oneViewing); - Task anotherCarrying = Carry(another, anotherViewing); - - fanout.Break(LiveFragmentFault.StoppedPartWayThrough); - - Assert.Equal(LiveDeparture.SourceBroke, await oneCarrying); - Assert.Equal(LiveDeparture.SourceBroke, await anotherCarrying); - } - - private static Task Carry(ScriptedWebSocket socket, ILiveViewing viewing) - => new LiveWireSocket(socket, Impatient) - .CarryAsync(viewing.Frames, CancellationToken.None, CancellationToken.None); - - private static async Task Joined(LiveFanout fanout) - { - ILiveViewing? viewing = await fanout.JoinAsync(CancellationToken.None); - - Assert.NotNull(viewing); - - return viewing; - } -} diff --git a/tests/Carina.Api.Tests/Unit/LiveWireSocketEndingTests.cs b/tests/Carina.Api.Tests/Unit/LiveWireSocketEndingTests.cs deleted file mode 100644 index 34ae6d9e2..000000000 --- a/tests/Carina.Api.Tests/Unit/LiveWireSocketEndingTests.cs +++ /dev/null @@ -1,123 +0,0 @@ -using System.Net.WebSockets; -using System.Threading.Channels; - -using Carina.Api.Live; -using Carina.Domain.Streaming; - -namespace Carina.Api.Tests.Unit; - -public sealed class LiveWireSocketEndingTests -{ - private static readonly byte[] Picture = [0x01, 0x02, 0x03]; - - public static TheoryData EveryReasonASupplyEnds() - { - TheoryData reasons = []; - - foreach (LiveSupplyEnd why in Enum.GetValues()) - { - reasons.Add(why); - } - - return reasons; - } - - [Fact] - public async Task WhyTheSupplyEndedIsSaidOnTheControlChannelAfterTheLastFrameAndBeforeTheClose() - { - ScriptedWebSocket socket = new(); - Channel frames = Channel.CreateUnbounded(); - HeldEnding ending = new(LiveSupplyEnding.Of(LiveSupplyEnd.TakenForARecording, "a recording outranked it.")); - - frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); - frames.Writer.Complete(); - - LiveDeparture departure = await Carry(socket, frames, ending); - - Assert.Equal(LiveDeparture.SourceEnded, departure); - Assert.Equal(2, socket.Sent.Count); - Assert.Equal(LiveChannel.Picture, LiveFrame.Read(socket.Sent[0]).Frame!.Channel); - - LiveFrame said = LiveFrame.Read(socket.Sent[1]).Frame!; - - Assert.Equal(LiveChannel.Control, said.Channel); - - LiveEndingReading read = LiveEndingReport.Read(said.Payload.Span); - - Assert.Null(read.Fault); - Assert.Equal(LiveSupplyEnd.TakenForARecording, read.Report!.Why); - Assert.Equal(WebSocketCloseStatus.NormalClosure, socket.Closed); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceEnded), socket.ClosedBecause); - } - - [Fact] - public async Task ASourceThatBreaksStillSaysWhyItEndedWhenTheSupplyKnows() - { - ScriptedWebSocket socket = new(); - Channel frames = Channel.CreateUnbounded(); - HeldEnding ending = new(LiveSupplyEnding.Of(LiveSupplyEnd.DriverLost, "the driver went away.")); - - frames.Writer.Complete(new InvalidOperationException("What was being sent live broke.")); - - LiveDeparture departure = await Carry(socket, frames, ending); - - Assert.Equal(LiveDeparture.SourceBroke, departure); - - LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; - - Assert.Equal(LiveSupplyEnd.DriverLost, LiveEndingReport.Read(said.Payload.Span).Report!.Why); - Assert.Equal(WebSocketCloseStatus.InternalServerError, socket.Closed); - } - - [Theory] - [MemberData(nameof(EveryReasonASupplyEnds))] - public async Task AWireIsNeverClosedWithoutTheReasonHavingBeenSaidFirst(LiveSupplyEnd why) - { - ScriptedWebSocket socket = new(); - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.Complete(); - - LiveDeparture departure = await Carry( - socket, - frames, - new HeldEnding(LiveSupplyEnding.Of(why, "the supply named a reason."))); - - Assert.Equal(LiveDeparture.SourceEnded, departure); - - LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; - - Assert.Equal(LiveChannel.Control, said.Channel); - Assert.Equal(why, LiveEndingReport.Read(said.Payload.Span).Report!.Why); - Assert.Equal(WebSocketCloseStatus.NormalClosure, socket.Closed); - } - - [Fact] - public async Task WhatIsSaidIsNeitherAPingNorARefusalNorAProgressReportNorSomethingAViewerCouldSay() - { - ScriptedWebSocket socket = new(); - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.Complete(); - - await Carry(socket, frames, new HeldEnding(LiveSupplyEnding.Of(LiveSupplyEnd.WindowClosed, "the window closed."))); - - LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; - - Assert.Equal(LiveEndingReport.PayloadLength, said.Payload.Length); - Assert.Null(LiveControls.SaidByAViewer(said.Payload.Span)); - Assert.NotNull(LiveRefusalReport.Read(said.Payload.Span).Fault); - Assert.NotNull(LiveStartup.ReadProgress(said.Payload.Span).Fault); - } - - private static Task Carry(ScriptedWebSocket socket, Channel frames, ILiveEnding ending) - => new LiveWireSocket(socket, new LiveWireSettings(), null, ending).CarryAsync( - frames.Reader, - CancellationToken.None, - CancellationToken.None); - - private sealed class HeldEnding(LiveSupplyEnding? current) : ILiveEnding - { - public LiveSupplyEnding? Current => current; - } -} diff --git a/tests/Carina.Api.Tests/Unit/LiveWireSocketProgressTests.cs b/tests/Carina.Api.Tests/Unit/LiveWireSocketProgressTests.cs deleted file mode 100644 index 7d5e1a13e..000000000 --- a/tests/Carina.Api.Tests/Unit/LiveWireSocketProgressTests.cs +++ /dev/null @@ -1,327 +0,0 @@ -using System.Threading.Channels; - -using Carina.Api.Live; -using Carina.Domain.Streaming; - -namespace Carina.Api.Tests.Unit; - -public sealed class LiveWireSocketProgressTests -{ - private static readonly LiveWireSettings Impatient = new( - betweenPings: TimeSpan.FromMilliseconds(30), - writePatience: TimeSpan.FromMilliseconds(200)); - - private static readonly LiveWireSettings Patient = new( - betweenPings: TimeSpan.FromSeconds(10), - writePatience: TimeSpan.FromMilliseconds(200)); - - private static readonly byte[] Picture = [0x01, 0x02, 0x03]; - - private static readonly LiveStartupSegment[] AsTheyHappen = - [ - LiveStartupSegment.TunerSecured, - LiveStartupSegment.TranscoderStarted, - LiveStartupSegment.ChannelLocked, - LiveStartupSegment.InitReached, - LiveStartupSegment.FirstPicture, - ]; - - private static readonly LiveStartup Starting = LiveStartup.NotStarted - .Reaching(LiveStartupSegment.TranscoderStarted, TimeSpan.FromSeconds(8)) - .Reaching(LiveStartupSegment.InitReached, TimeSpan.FromMilliseconds(8100)); - - [Fact] - public async Task ProgressGoesOutRightAfterTheHandshakeWhileTheStartupIsStillRunning() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - - Task carrying = Carry(socket, frames, new HeldStartup(Starting), stop.Token); - - await Until(() => socket.Sent.Count >= 1); - await stop.CancelAsync(); - await carrying; - - LiveFrame first = LiveFrame.Read(socket.Sent[0]).Frame!; - - Assert.Equal(LiveChannel.Control, first.Channel); - - LiveStartupReading read = LiveStartup.ReadProgress(first.Payload.Span); - - Assert.Null(read.Fault); - Assert.Equal(TimeSpan.FromSeconds(8), read.Startup!.At(LiveStartupSegment.TranscoderStarted)); - Assert.Equal(TimeSpan.FromMilliseconds(8100), read.Startup.At(LiveStartupSegment.InitReached)); - Assert.False(read.Startup.Reached(LiveStartupSegment.FirstPicture)); - } - - [Fact] - public async Task AProgressReportRidesTheControlChannelButIsNotSomethingAViewerCouldEverSay() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - - Task carrying = Carry(socket, frames, new HeldStartup(Starting), stop.Token); - - await Until(() => socket.Sent.Count >= 1); - await stop.CancelAsync(); - await carrying; - - LiveFrame first = LiveFrame.Read(socket.Sent[0]).Frame!; - - Assert.Equal(LiveChannel.Control, first.Channel); - Assert.NotEqual(1, first.Payload.Length); - Assert.Null(LiveControls.SaidByAViewer(first.Payload.Span)); - } - - [Fact] - public async Task OnceTheFirstPictureIsReachedTheWireFallsBackToTheKeepAlivePing() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - - LiveStartup done = Starting.Reaching(LiveStartupSegment.FirstPicture, TimeSpan.FromMilliseconds(10100)); - - Task carrying = Carry(socket, frames, new HeldStartup(done), stop.Token); - - await Until(() => socket.Sent.Count >= 2); - await stop.CancelAsync(); - await carrying; - - Assert.All( - socket.Sent, - message => Assert.Equal(LiveControls.Frame(LiveControl.Ping).ToArray(), message)); - } - - [Fact] - public async Task AWireWithNothingToReportSaysNothingButTheKeepAlivePing() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - - Task carrying = Carry(socket, frames, new HeldStartup(null), stop.Token); - - await Until(() => socket.Sent.Count >= 2); - await stop.CancelAsync(); - await carrying; - - Assert.All( - socket.Sent, - message => Assert.Equal(LiveControls.Frame(LiveControl.Ping).ToArray(), message)); - } - - [Fact] - public async Task AReportGoesOutEachTimeASegmentIsReachedNotOnlyWhenTheWireFallsQuiet() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - var startup = new SteppingStartup(); - - Task carrying = new LiveWireSocket(socket, Patient, startup) - .CarryAsync(frames.Reader, CancellationToken.None, stop.Token); - - await Until(() => socket.Sent.Count >= 1); - - int reached = 0; - - foreach (LiveStartupSegment segment in AsTheyHappen) - { - reached++; - startup.Reach(segment, TimeSpan.FromMilliseconds(100 * reached)); - - int expected = reached + 1; - - await Until(() => socket.Sent.Count >= expected); - } - - await Task.Delay(150); - await stop.CancelAsync(); - await carrying; - - LiveStartup[] reports = [.. socket.Sent.Select(Reported)]; - - Assert.Equal(6, reports.Length); - Assert.Equal([0, 1, 2, 3, 4, 5], reports.Select(report => report.Timeline.Count(mark => mark.Reached))); - Assert.True(reports[2].Reached(LiveStartupSegment.TranscoderStarted)); - Assert.False(reports[2].Reached(LiveStartupSegment.ChannelLocked)); - Assert.False(reports[^1].InProgress); - } - - [Fact] - public async Task AStepTheWireHadAlreadyReportedIsNotReportedAgainUntilTheNextOne() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - var startup = new SteppingStartup(); - - startup.Reach(LiveStartupSegment.TunerSecured, TimeSpan.FromMilliseconds(100)); - startup.Reach(LiveStartupSegment.TranscoderStarted, TimeSpan.FromMilliseconds(110)); - - Task carrying = new LiveWireSocket(socket, Patient, startup) - .CarryAsync(frames.Reader, CancellationToken.None, stop.Token); - - await Until(() => socket.Sent.Count >= 1); - await Task.Delay(150); - - Assert.Single(socket.Sent); - - startup.Reach(LiveStartupSegment.ChannelLocked, TimeSpan.FromMilliseconds(700)); - - await Until(() => socket.Sent.Count >= 2); - await Task.Delay(150); - await stop.CancelAsync(); - await carrying; - - Assert.Equal(2, socket.Sent.Count); - Assert.Equal(2, Reported(socket.Sent[0]).Timeline.Count(mark => mark.Reached)); - Assert.Equal(3, Reported(socket.Sent[1]).Timeline.Count(mark => mark.Reached)); - } - - [Fact] - public async Task TheKeepAlivePingTakesOverOnceTheLastStepHasBeenReported() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - var startup = new SteppingStartup(); - - Task carrying = new LiveWireSocket(socket, Impatient, startup) - .CarryAsync(frames.Reader, CancellationToken.None, stop.Token); - - await Until(() => socket.Sent.Count >= 1); - - foreach (LiveStartupSegment segment in AsTheyHappen) - { - startup.Reach(segment, TimeSpan.FromMilliseconds(100)); - } - - await Until(() => socket.Sent.Any(message => message.SequenceEqual(LiveControls.Frame(LiveControl.Ping).ToArray()))); - await stop.CancelAsync(); - await carrying; - - byte[][] afterTheLast = [.. socket.Sent.SkipWhile(message => !Reported(message, out LiveStartup? report) || report!.InProgress).Skip(1)]; - - Assert.NotEmpty(afterTheLast); - Assert.All(afterTheLast, message => Assert.Equal(LiveControls.Frame(LiveControl.Ping).ToArray(), message)); - } - - [Fact] - public async Task ProgressDoesNotInterruptTheFramesTheSourceIsAlreadySending() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - for (int written = 0; written < 10; written++) - { - frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of((ulong)written), Picture)); - } - - frames.Writer.Complete(); - - await Carry(socket, frames, new HeldStartup(Starting), CancellationToken.None); - - Assert.Equal(10, socket.Sent.Count(message => message[0] == (byte)LiveChannel.Picture)); - } - - private static Task Carry( - ScriptedWebSocket socket, - Channel frames, - ILiveStartup startup, - CancellationToken cancellationToken) - => new LiveWireSocket(socket, Impatient, startup) - .CarryAsync(frames.Reader, CancellationToken.None, cancellationToken); - - private static async Task Until(Func settled) - { - for (int tries = 0; tries < 200; tries++) - { - if (settled()) - { - return; - } - - await Task.Delay(25); - } - - Assert.Fail("The wire never said what was expected of it."); - } - - private static LiveStartup Reported(byte[] message) - { - Assert.True(Reported(message, out LiveStartup? report), "the wire said something that is not a progress report."); - - return report!; - } - - private static bool Reported(byte[] message, out LiveStartup? report) - { - report = null; - - if (LiveFrame.Read(message).Frame is not { Channel: LiveChannel.Control } frame - || frame.Payload.Length != LiveStartup.PayloadLength) - { - return false; - } - - report = LiveStartup.ReadProgress(frame.Payload.Span).Startup; - - return report is not null; - } - - private sealed class HeldStartup(LiveStartup? current) : ILiveStartup - { - public LiveStartup? Current { get; } = current; - - public Task Advanced { get; } = new TaskCompletionSource().Task; - } - - private sealed class SteppingStartup : ILiveStartup - { - private readonly Lock gate = new(); - - private TaskCompletionSource advanced = new(TaskCreationOptions.RunContinuationsAsynchronously); - - private LiveStartup current = LiveStartup.NotStarted; - - public LiveStartup? Current - { - get - { - lock (gate) - { - return current; - } - } - } - - public Task Advanced - { - get - { - lock (gate) - { - return advanced.Task; - } - } - } - - public void Reach(LiveStartupSegment segment, TimeSpan at) - { - TaskCompletionSource told; - - lock (gate) - { - current = current.Reaching(segment, at); - told = advanced; - advanced = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - } - - told.SetResult(); - } - } -} diff --git a/tests/Carina.Api.Tests/Unit/LiveWireSocketRefusalTests.cs b/tests/Carina.Api.Tests/Unit/LiveWireSocketRefusalTests.cs deleted file mode 100644 index c840f5ae8..000000000 --- a/tests/Carina.Api.Tests/Unit/LiveWireSocketRefusalTests.cs +++ /dev/null @@ -1,179 +0,0 @@ -using System.Diagnostics; -using System.Net.WebSockets; -using System.Threading.Channels; - -using Carina.Api.Live; -using Carina.Domain.Channels; -using Carina.Domain.Streaming; - -namespace Carina.Api.Tests.Unit; - -public sealed class LiveWireSocketRefusalTests -{ - [Fact] - public async Task ARefusalIsSaidOnTheControlChannelAndThenTheWireIsClosedWithItsReason() - { - ScriptedWebSocket socket = new(); - - await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( - LiveJoin.Refused(LiveRefusal.NoTunerFree, "every tuner is recording."), - CancellationToken.None); - - LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; - - Assert.Equal(LiveChannel.Control, said.Channel); - Assert.Equal(LivePts.Start, said.Pts); - - LiveRefusalReading read = LiveRefusalReport.Read(said.Payload.Span); - - Assert.Null(read.Fault); - Assert.Equal(LiveRefusal.NoTunerFree, read.Report!.Refusal); - Assert.Equal(WebSocketCloseStatus.PolicyViolation, socket.Closed); - Assert.Equal(LiveRefusalClosures.Because(LiveRefusal.NoTunerFree), socket.ClosedBecause); - Assert.False(socket.Aborted); - } - - [Fact] - public async Task AFullBudgetIsSaidWithItsCeiling() - { - ScriptedWebSocket socket = new(); - - await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( - LiveJoin.Refused(new TranscodeCeiling(4, 4)), - CancellationToken.None); - - LiveRefusalReading read = LiveRefusalReport.Read(LiveFrame.Read(socket.Sent[0]).Frame!.Payload.Span); - - Assert.Equal(LiveRefusal.TooManyAlready, read.Report!.Refusal); - Assert.Equal(new TranscodeCeiling(4, 4), read.Report.Ceiling); - } - - [Theory] - [InlineData(TuneFailureKind.NoLock)] - [InlineData(TuneFailureKind.NoData)] - [InlineData(TuneFailureKind.IncompletePsi)] - [InlineData(TuneFailureKind.StreamMismatch)] - public async Task BrTd004TheReasonATuningFailedLeavesTheWireBesideTheRefusalRatherThanOnlyInTheNote( - TuneFailureKind kind) - { - ScriptedWebSocket socket = new(); - - await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( - LiveJoin.Refused(LiveRefusal.WouldNotTune, "no lock.", LiveRefusalDetail.Of(kind)), - CancellationToken.None); - - LiveRefusalReading read = LiveRefusalReport.Read(LiveFrame.Read(socket.Sent[0]).Frame!.Payload.Span); - - Assert.Null(read.Fault); - Assert.Equal(LiveRefusal.WouldNotTune, read.Report!.Refusal); - Assert.Equal(kind, read.Report.Detail.TuneFailure); - } - - [Fact] - public async Task Fr012WhatHoldsTheTunerLeavesTheWireBesideTheRefusalTheSameWay() - { - ScriptedWebSocket socket = new(); - - await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( - LiveJoin.Refused( - LiveRefusal.NoTunerFree, - "a recording holds it.", - LiveRefusalDetail.Of(LiveTunerHolder.ARecording)), - CancellationToken.None); - - LiveRefusalReading read = LiveRefusalReport.Read(LiveFrame.Read(socket.Sent[0]).Frame!.Payload.Span); - - Assert.Null(read.Fault); - Assert.Equal(LiveRefusal.NoTunerFree, read.Report!.Refusal); - Assert.Equal(LiveTunerHolder.ARecording, read.Report.Detail.Holder); - Assert.Equal(LiveRefusalReport.PayloadLength, LiveFrame.Read(socket.Sent[0]).Frame!.Payload.Length); - } - - [Fact] - public async Task WhatIsSaidIsNeitherAPingNorAProgressReportNorSomethingAViewerCouldSay() - { - ScriptedWebSocket socket = new(); - - await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( - LiveJoin.Refused(LiveRefusal.DriverUnavailable, "nothing supplies a stream."), - CancellationToken.None); - - LiveFrame said = LiveFrame.Read(socket.Sent[0]).Frame!; - - Assert.Equal(LiveRefusalReport.PayloadLength, said.Payload.Length); - Assert.Null(LiveControls.SaidByAViewer(said.Payload.Span)); - Assert.NotNull(LiveStartup.ReadProgress(said.Payload.Span).Fault); - } - - [Fact] - public async Task ASeatedViewerCannotBeRefused() - { - ScriptedWebSocket socket = new(); - - await Assert.ThrowsAsync(() => new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( - LiveJoin.Joined(new SeatedNowhere()), - CancellationToken.None)); - - Assert.Empty(socket.Sent); - } - - [Fact] - public async Task AViewerThatNeverAnswersTheCloseIsCutOffRatherThanWaitedFor() - { - SilentWebSocket socket = new(); - - await new LiveWireSocket(socket, new LiveWireSettings()).RefuseAsync( - LiveJoin.Refused(LiveRefusal.WouldNotTune, "no lock."), - CancellationToken.None); - - Assert.True(socket.Aborted); - } - - private sealed class SeatedNowhere : ILiveViewing - { - public ChannelReader Frames { get; } = Channel.CreateUnbounded().Reader; - - public LiveBacklog Backlog => LiveBacklog.Empty; - - public ILiveStartup? Startup => null; - - public ILiveEnding? Ending => null; - - public ValueTask DisposeAsync() => ValueTask.CompletedTask; - } - - private sealed class SilentWebSocket : WebSocket - { - public override WebSocketCloseStatus? CloseStatus => null; - - public override string? CloseStatusDescription => null; - - public override string? SubProtocol => null; - - public override WebSocketState State => WebSocketState.Open; - - public bool Aborted { get; private set; } - - public override void Abort() => Aborted = true; - - public override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) - => Task.CompletedTask; - - public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) - => Task.CompletedTask; - - public override void Dispose() - { - } - - public override async Task ReceiveAsync(ArraySegment buffer, CancellationToken cancellationToken) - { - await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); - - throw new UnreachableException(); - } - - public override Task SendAsync(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) - => Task.CompletedTask; - } -} diff --git a/tests/Carina.Api.Tests/Unit/LiveWireSocketSilenceTests.cs b/tests/Carina.Api.Tests/Unit/LiveWireSocketSilenceTests.cs deleted file mode 100644 index 4762d4dcb..000000000 --- a/tests/Carina.Api.Tests/Unit/LiveWireSocketSilenceTests.cs +++ /dev/null @@ -1,184 +0,0 @@ -using System.Net.WebSockets; -using System.Threading.Channels; - -using Carina.Api.Live; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -namespace Carina.Api.Tests.Unit; - -public sealed class LiveWireSocketSilenceTests -{ - private static readonly LiveWireSettings Gateway = new( - betweenPings: TimeSpan.FromSeconds(15), - silenceCeiling: TimeSpan.FromSeconds(100)); - - private static readonly byte[] Picture = [0x01, 0x02, 0x03]; - - [Fact] - public async Task ASupplyThatSaysNothingPastTheCeilingIsTakenForGoneAndTheWireIsClosed() - { - ScriptedWebSocket socket = new(); - Channel frames = Channel.CreateUnbounded(); - HandTurnedClock clock = new(); - - Task carrying = Carrying(socket, frames, clock); - - await WaitOutTheCeiling(clock); - - Assert.Equal(LiveDeparture.SourceWentQuiet, await carrying.WaitAsync(Eventually.Patience)); - Assert.Equal(WebSocketCloseStatus.InternalServerError, socket.Closed); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceWentQuiet), socket.ClosedBecause); - Assert.Equal(Gateway.QuietsBeforeTheCeiling + 1, socket.Sent.Count); - Assert.All( - socket.Sent.Take(Gateway.QuietsBeforeTheCeiling), - sent => Assert.Equal( - [(byte)LiveControl.Ping], - LiveFrame.Read(sent).Frame!.Payload.ToArray())); - } - - [Fact] - public async Task AWireTakingItsSupplyForGoneSaysSoOnTheControlChannelBeforeItIsClosed() - { - ScriptedWebSocket socket = new(); - HandTurnedClock clock = new(); - LiveStartupRecord startup = new(clock); - LiveEndingRecord ending = new(); - LiveFanout fanout = new(new LiveFanoutSettings(), startup, ending); - - Started(startup); - - await using ILiveViewing viewing = await Joined(fanout); - - Task carrying = Carrying(socket, viewing, clock); - - await WaitOutTheCeiling(clock); - - Assert.Equal(LiveDeparture.SourceWentQuiet, await carrying.WaitAsync(Eventually.Patience)); - Assert.Null(ending.Current); - - LiveFrame said = LiveFrame.Read(socket.Sent[^1]).Frame!; - - Assert.Equal(LiveChannel.Control, said.Channel); - - LiveEndingReading read = LiveEndingReport.Read(said.Payload.Span); - - Assert.Null(read.Fault); - Assert.Equal(LiveSupplyEnd.WentQuiet, read.Report!.Why); - Assert.Equal(WebSocketCloseStatus.InternalServerError, socket.Closed); - Assert.Equal(LiveDepartures.Because(LiveDeparture.SourceWentQuiet), socket.ClosedBecause); - } - - [Fact] - public async Task WhatTheSupplyItselfSaidIsPreferredToTheWireTakingItForGone() - { - ScriptedWebSocket socket = new(); - HandTurnedClock clock = new(); - LiveStartupRecord startup = new(clock); - LiveEndingRecord ending = new(); - LiveFanout fanout = new(new LiveFanoutSettings(), startup, ending); - - Started(startup); - ending.Note(LiveSupplyEnding.Of(LiveSupplyEnd.TakenForARecording, "a recording outranked it.")); - - await using ILiveViewing viewing = await Joined(fanout); - - Task carrying = Carrying(socket, viewing, clock); - - await WaitOutTheCeiling(clock); - - Assert.Equal(LiveDeparture.SourceWentQuiet, await carrying.WaitAsync(Eventually.Patience)); - - LiveFrame said = LiveFrame.Read(socket.Sent[^1]).Frame!; - - Assert.Equal(LiveSupplyEnd.TakenForARecording, LiveEndingReport.Read(said.Payload.Span).Report!.Why); - } - - [Fact] - public async Task TheCeilingIsCountedFromTheLastFrameSoAWireStillBeingFedIsNeverClosedForQuiet() - { - ScriptedWebSocket socket = new(); - Channel frames = Channel.CreateUnbounded(); - HandTurnedClock clock = new(); - - Task carrying = Carrying(socket, frames, clock); - - int sent = 0; - - for (int rounds = 0; rounds < 4; rounds++) - { - for (int quiet = 0; quiet < Gateway.QuietsBeforeTheCeiling; quiet++) - { - await WaitingOutTheQuiet(clock); - clock.Turn(Gateway.BetweenPings); - sent++; - } - - frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Start, Picture)); - sent++; - - await Eventually.Happens(() => socket.Sent.Count == sent, "the picture reaches the wire"); - } - - Assert.False(carrying.IsCompleted); - Assert.Null(socket.Closed); - - frames.Writer.Complete(); - - Assert.Equal(LiveDeparture.SourceEnded, await carrying); - Assert.Equal(sent + 1, socket.Sent.Count); - Assert.Equal( - (byte)LiveChannel.Control, - socket.Sent[^1][0]); - } - - private static void Started(LiveStartupRecord startup) - { - foreach (LiveStartupSegment segment in LiveStartupSegments.InOrder) - { - startup.Reach(segment); - } - } - - private static async Task Joined(LiveFanout fanout) - { - ILiveViewing? viewing = await fanout.JoinAsync(CancellationToken.None); - - Assert.NotNull(viewing); - - return viewing; - } - - private static Task Carrying( - ScriptedWebSocket socket, - Channel frames, - TimeProvider clock) - => new LiveWireSocket(socket, Gateway, null, null, clock).CarryAsync( - frames.Reader, - CancellationToken.None, - CancellationToken.None); - - private static Task Carrying( - ScriptedWebSocket socket, - ILiveViewing viewing, - TimeProvider clock) - => new LiveWireSocket(socket, Gateway, viewing.Startup, viewing.Ending, clock).CarryAsync( - viewing.Frames, - CancellationToken.None, - CancellationToken.None); - - private static async Task WaitOutTheCeiling(HandTurnedClock clock) - { - for (int quiet = 0; quiet <= Gateway.QuietsBeforeTheCeiling; quiet++) - { - await WaitingOutTheQuiet(clock); - clock.Turn(Gateway.BetweenPings); - } - } - - private static Task WaitingOutTheQuiet(HandTurnedClock clock) - => Eventually.Happens( - () => clock.Waiting.SequenceEqual([Gateway.BetweenPings]), - "the wire is waiting out the quiet"); -} diff --git a/tests/Carina.Api.Tests/Unit/LiveWireSocketTests.cs b/tests/Carina.Api.Tests/Unit/LiveWireSocketTests.cs deleted file mode 100644 index a913517fa..000000000 --- a/tests/Carina.Api.Tests/Unit/LiveWireSocketTests.cs +++ /dev/null @@ -1,345 +0,0 @@ -using System.Net.WebSockets; -using System.Threading.Channels; - -using Carina.Api.Live; -using Carina.Domain.Streaming; - -namespace Carina.Api.Tests.Unit; - -public sealed class LiveWireSocketTests -{ - private static readonly LiveWireSettings Impatient = new( - betweenPings: TimeSpan.FromMilliseconds(30), - writePatience: TimeSpan.FromMilliseconds(200)); - - private static readonly byte[] Picture = [0x01, 0x02, 0x03]; - - [Fact] - public async Task AFrameIsSentAsOneBinaryMessageCarryingItsOwnHeader() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of(90_000UL), Picture)); - frames.Writer.Complete(); - - LiveDeparture departure = await Carry(socket, frames); - - Assert.Equal(LiveDeparture.SourceEnded, departure); - Assert.Equal( - [0x01, 0, 0, 0, 0, 0, 0x01, 0x5f, 0x90, 0x01, 0x02, 0x03], - socket.Sent[0]); - } - - [Fact] - public async Task TheHeaderGoesOutBeforeTheFirstPictureThatNeedsIt() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.TryWrite(new LiveFrame(LiveChannel.PictureHeader, LivePts.Start, Picture)); - frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of(1UL), Picture)); - frames.Writer.Complete(); - - await Carry(socket, frames); - - Assert.Equal( - [(byte)LiveChannel.PictureHeader, (byte)LiveChannel.Picture, (byte)LiveChannel.Control], - socket.Sent.Select(message => message[0]).ToArray()); - } - - [Fact] - public async Task TheSourceRunningOutIsANormalEnding() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.Complete(); - - Assert.Equal(LiveDeparture.SourceEnded, await Carry(socket, frames)); - Assert.True(socket.CloseAttempted); - Assert.Equal(WebSocketCloseStatus.NormalClosure, socket.Closed); - } - - [Fact] - public async Task TheSourceBreakingIsNotANormalEnding() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.Complete(new InvalidOperationException("the transcoder stopped")); - - Assert.Equal(LiveDeparture.SourceBroke, await Carry(socket, frames)); - Assert.Equal(WebSocketCloseStatus.InternalServerError, socket.Closed); - } - - [Fact] - public void EveryEndingSaysWhyInWordsTheViewerIsGiven() - { - Assert.All( - Enum.GetValues(), - departure => Assert.NotEmpty(LiveDepartures.Because(departure))); - } - - [Fact] - public void EveryWayTheSupplyItselfEndsNamesAReasonEvenWhenTheSupplySaidNothing() - { - Assert.Equal(LiveSupplyEnd.WentQuiet, LiveDepartures.Ending(LiveDeparture.SourceWentQuiet)); - Assert.Equal(LiveSupplyEnd.DriverLost, LiveDepartures.Ending(LiveDeparture.SourceEnded)); - Assert.Equal(LiveSupplyEnd.DriverLost, LiveDepartures.Ending(LiveDeparture.SourceBroke)); - } - - [Fact] - public void TheFourWaysThatAreTheViewerOrTheAppRatherThanTheSupplyNameNoReason() - { - Assert.All( - new[] - { - LiveDeparture.ViewerLeft, - LiveDeparture.ViewerStoppedReading, - LiveDeparture.SaidSomethingUnknown, - LiveDeparture.SaidMoreThanTheWireTakes, - LiveDeparture.ServerStopping, - }, - departure => Assert.Null(LiveDepartures.Ending(departure))); - } - - [Fact] - public async Task AWireWhoseSupplyStoppedWithoutSayingWhyStillSaysThatMuch() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.Complete(); - - Assert.Equal(LiveDeparture.SourceEnded, await Carry(socket, frames)); - - LiveFrame said = LiveFrame.Read(Assert.Single(socket.Sent)).Frame!; - - Assert.Equal(LiveChannel.Control, said.Channel); - Assert.Equal(LiveSupplyEnd.DriverLost, LiveEndingReport.Read(said.Payload.Span).Report!.Why); - } - - [Fact] - public async Task APingGoesOutWhileTheSourceHasNothingToSay() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - - Task carrying = Carry(socket, frames, stop.Token); - - await Until(() => socket.Sent.Count >= 2); - await stop.CancelAsync(); - await carrying; - - Assert.All( - socket.Sent, - message => Assert.Equal(LiveControls.Frame(LiveControl.Ping).ToArray(), message)); - } - - [Fact] - public async Task NoPingGoesOutAfterTheWireHasBeenToldToStop() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stop = new CancellationTokenSource(); - - await stop.CancelAsync(); - - Assert.Equal(LiveDeparture.ViewerLeft, await Carry(socket, frames, stop.Token)); - Assert.Empty(socket.Sent); - } - - [Fact] - public async Task NoPingInterruptsAWireThatIsCarryingPictures() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - for (int written = 0; written < 20; written++) - { - frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Of((ulong)written), Picture)); - } - - frames.Writer.Complete(); - - await Carry(socket, frames); - - Assert.Equal( - Enumerable.Repeat((byte)LiveChannel.Picture, 20).Append((byte)LiveChannel.Control), - socket.Sent.Select(message => message[0])); - } - - [Fact] - public async Task AViewerSayingItIsLeavingIsAnsweredByLettingItGo() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - socket.Say(new WebSocketSaying( - WebSocketMessageType.Binary, - LiveControls.Frame(LiveControl.Leaving).ToArray())); - - Assert.Equal(LiveDeparture.ViewerLeft, await Carry(socket, frames)); - Assert.Equal(WebSocketCloseStatus.NormalClosure, socket.Closed); - } - - [Fact] - public async Task AViewerClosingTheSocketIsTheSameAsSayingItIsLeaving() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - socket.Say(new WebSocketSaying(WebSocketMessageType.Close, [])); - - Assert.Equal(LiveDeparture.ViewerLeft, await Carry(socket, frames)); - } - - [Fact] - public async Task AViewerAnsweringAPingIsNotAnEnding() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - socket.Say(new WebSocketSaying( - WebSocketMessageType.Binary, - LiveControls.Frame(LiveControl.Pong).ToArray())); - socket.Say(new WebSocketSaying( - WebSocketMessageType.Binary, - LiveControls.Frame(LiveControl.Leaving).ToArray())); - - Assert.Equal(LiveDeparture.ViewerLeft, await Carry(socket, frames)); - } - - [Fact] - public async Task AViewerSayingSomethingThatIsNotAControlMessageIsShownOut() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - socket.Say(new WebSocketSaying(WebSocketMessageType.Binary, [0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f])); - - Assert.Equal(LiveDeparture.SaidSomethingUnknown, await Carry(socket, frames)); - Assert.Equal(WebSocketCloseStatus.InvalidPayloadData, socket.Closed); - } - - [Fact] - public async Task AViewerRepeatingWhatOnlyTheServerSaysIsShownOut() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - socket.Say(new WebSocketSaying( - WebSocketMessageType.Binary, - LiveControls.Frame(LiveControl.Ping).ToArray())); - - Assert.Equal(LiveDeparture.SaidSomethingUnknown, await Carry(socket, frames)); - } - - [Fact] - public async Task AViewerPushingBytesUpAPictureChannelIsShownOut() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - socket.Say(new WebSocketSaying( - WebSocketMessageType.Binary, - new LiveFrame(LiveChannel.Picture, LivePts.Start, Picture).ToArray())); - - Assert.Equal(LiveDeparture.SaidSomethingUnknown, await Carry(socket, frames)); - } - - [Fact] - public async Task AViewerTypingWordsAtTheWireIsShownOut() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - socket.Say(new WebSocketSaying(WebSocketMessageType.Text, "seek 42"u8.ToArray())); - - Assert.Equal(LiveDeparture.SaidSomethingUnknown, await Carry(socket, frames)); - } - - [Fact] - public async Task AViewerSendingMoreThanTheWireTakesIsShownOut() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - socket.Say(new WebSocketSaying( - WebSocketMessageType.Binary, - new byte[Impatient.LargestFrameFromAViewer + 64])); - - Assert.Equal(LiveDeparture.SaidMoreThanTheWireTakes, await Carry(socket, frames)); - Assert.Equal(WebSocketCloseStatus.MessageTooBig, socket.Closed); - } - - [Fact] - public async Task AViewerThatStopsReadingIsGivenUpOnRatherThanHoldingTheSource() - { - var socket = new ScriptedWebSocket { HoldEverySend = TimeSpan.FromSeconds(30) }; - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Start, Picture)); - - Assert.Equal(LiveDeparture.ViewerStoppedReading, await Carry(socket, frames)); - Assert.True(socket.Aborted); - Assert.False(socket.CloseAttempted); - Assert.Null(socket.Closed); - } - - [Fact] - public async Task AWireCarryingAFrameLargerThanAnythingTheFragmenterHoldsStillSendsItWhole() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - - frames.Writer.TryWrite(new LiveFrame(LiveChannel.Picture, LivePts.Start, new byte[4 * 1024 * 1024])); - frames.Writer.Complete(); - - await Carry(socket, frames); - - Assert.Equal(LiveFrame.HeaderLength + (4 * 1024 * 1024), socket.Sent[0].Length); - } - - [Fact] - public async Task TheAppShuttingDownIsNotTheViewerLeaving() - { - var socket = new ScriptedWebSocket(); - Channel frames = Channel.CreateUnbounded(); - using var stopping = new CancellationTokenSource(); - using var stop = new CancellationTokenSource(); - - Task carrying = new LiveWireSocket(socket, Impatient) - .CarryAsync(frames.Reader, stopping.Token, stop.Token); - - await stopping.CancelAsync(); - await stop.CancelAsync(); - - Assert.Equal(LiveDeparture.ServerStopping, await carrying); - Assert.Equal(WebSocketCloseStatus.EndpointUnavailable, socket.Closed); - } - - private static Task Carry( - ScriptedWebSocket socket, - Channel frames, - CancellationToken cancellationToken = default) - => new LiveWireSocket(socket, Impatient) - .CarryAsync(frames.Reader, CancellationToken.None, cancellationToken); - - private static async Task Until(Func settled) - { - for (int tries = 0; tries < 200; tries++) - { - if (settled()) - { - return; - } - - await Task.Delay(25); - } - - Assert.Fail("The wire never carried what was expected of it."); - } -} diff --git a/tests/Carina.Conventions.Tests/TestLayoutRules.cs b/tests/Carina.Conventions.Tests/TestLayoutRules.cs index 5476ddd28..4429e6ba7 100644 --- a/tests/Carina.Conventions.Tests/TestLayoutRules.cs +++ b/tests/Carina.Conventions.Tests/TestLayoutRules.cs @@ -20,7 +20,6 @@ public static class TestLayoutRules public static readonly IReadOnlyList AreasNotYetMoved = [ "Base", - "Captions", "Collection", "Configuration", "DataBroadcast", @@ -34,12 +33,9 @@ public static class TestLayoutRules "Machines", "Net", "Persistence", - "Playback", "Services", - "Streaming", "Tuners", "Version", - "Viewing", ]; /// @@ -56,6 +52,7 @@ public static class TestLayoutRules new("Auth", "src/Carina.Db/Migrations/20260929160610_TheClientSecretIsSealed.cs"), new("Auth", "src/Carina.Infrastructure/Configuration/AuthOptions.cs"), new("Auth", "src/Carina.Infrastructure/Persistence/Repositories/OidcSettingsRepository.cs"), + new("Captions", "src/Carina.Api/Playback/CaptionDelivery.cs"), new("Encoding", "src/Carina.Api/Services/EncodeRerun.cs"), new("Encodings", "src/Carina.Db/Migrations/20260914061902_WhereTheBreaksWereJudgedToBe.cs"), new("Encodings", "src/Carina.Db/Migrations/20260927053702_ReplacedArtefactsAreRemoved.cs"), @@ -73,6 +70,13 @@ public static class TestLayoutRules new("Notifications", "src/Carina.Api/Services/NotificationRuleService.cs"), new("Notifications", "src/Carina.Db/Migrations/20261110182416_AProgrammeCanBeWatchedWithoutBeingRecorded.cs"), new("Notifications", "src/Carina.Db/Migrations/20261112182442_ANoticeCanBeSentToABrowser.cs"), + new("Playback", "src/Carina.Api/Playback/AskedDecoding.cs"), + new("Playback", "src/Carina.Api/Playback/AskedFormat.cs"), + new("Playback", "src/Carina.Api/Playback/ByteRange.cs"), + new("Playback", "src/Carina.Api/Playback/PlayDelivery.cs"), + new("Playback", "src/Carina.Api/Playback/RecordingHlsDelivery.cs"), + new("Playback", "src/Carina.Api/Playback/VideoDelivery.cs"), + new("Playback", "src/Carina.Api/Responder/Playback/PlaybackPlanResponder.cs"), new("Programmes", "src/Carina.Db/Migrations/20260821083911_ProgrammeSearchNormalisation.cs"), new("Programmes", "src/Carina.Db/Migrations/20260821090203_ArchivedProgrammeSearchColumns.cs"), new("Programmes", "src/Carina.Db/Migrations/20260913150647_ThePictureABroadcastAnnounces.cs"), @@ -100,6 +104,13 @@ public static class TestLayoutRules new("Segments", "src/Carina.Db/Migrations/20261026110822_RoundsOfLearningKeepOutACandidateThatLosesOpeningsOrEndings.cs"), new("Segments", "src/Carina.Db/Migrations/20261107141136_TheSkipThresholdReachesNinetyNineHundredths.cs"), new("Segments", "src/Carina.Infrastructure/Configuration/LearningOptions.cs"), + new("Streaming", "src/Carina.Api/Live/LiveHlsDelivery.cs"), + new("Streaming", "src/Carina.Api/Live/LiveHlsPlaylists.cs"), + new("Streaming", "src/Carina.Api/Live/LiveRefusalClosures.cs"), + new("Streaming", "src/Carina.Api/Live/LiveStreamDelivery.cs"), + new("Streaming", "src/Carina.Api/Live/LiveWire.cs"), + new("Streaming", "src/Carina.Api/Live/LiveWireRequest.cs"), + new("Streaming", "src/Carina.Api/Live/LiveWireSocket.cs"), new("Thumbnails", "src/Carina.Api/Playback/ScrubDelivery.cs"), new("Thumbnails", "src/Carina.Api/Playback/ThumbnailDelivery.cs"), ]; @@ -129,6 +140,7 @@ public static class TestLayoutRules new("Segments", "SegmentLearningRoundSchema"), new("Segments", "SegmentSettingsSchema"), new("Segments", "SkipEventSchema"), + new("Viewing", "PlaybackPositionSchema"), ]; private const string ApiTests = "Carina.Api.Tests"; diff --git a/tests/Carina.Db.Tests/PlaybackPositionSchemaTests.cs b/tests/Carina.Db.Tests/DbIntegration/Infra/Viewing/PlaybackPositionSchemaTests.cs similarity index 99% rename from tests/Carina.Db.Tests/PlaybackPositionSchemaTests.cs rename to tests/Carina.Db.Tests/DbIntegration/Infra/Viewing/PlaybackPositionSchemaTests.cs index cc16cd879..dc15ee00a 100644 --- a/tests/Carina.Db.Tests/PlaybackPositionSchemaTests.cs +++ b/tests/Carina.Db.Tests/DbIntegration/Infra/Viewing/PlaybackPositionSchemaTests.cs @@ -10,7 +10,7 @@ using Npgsql; -namespace Carina.Db.Tests; +namespace Carina.Db.Tests.DbIntegration.Infra.Viewing; [Collection(ConnectionEnvironmentCollection.Name)] [Trait("Category", "DbIntegration")] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveRateControlTests.cs b/tests/Carina.Domain.Tests/Streaming/LiveRateControlTests.cs deleted file mode 100644 index 16fa8f05e..000000000 --- a/tests/Carina.Domain.Tests/Streaming/LiveRateControlTests.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System.Reflection; - -using Carina.Domain.Streaming; - -namespace Carina.Domain.Tests.Streaming; - -public sealed class LiveRateControlTests -{ - [Theory] - [InlineData(0)] - [InlineData(-1)] - [InlineData(-3000)] - public void ACapOfNothingASecondIsRefused(int kilobitsPerSecond) - { - Assert.Throws(() => new BitrateCap(kilobitsPerSecond)); - } - - [Theory] - [InlineData(1)] - [InlineData(3000)] - public void ACapIsTheRateItNames(int kilobitsPerSecond) - { - Assert.Equal(kilobitsPerSecond, new BitrateCap(kilobitsPerSecond).KilobitsPerSecond); - } - - [Theory] - [InlineData(-1)] - [InlineData(52)] - public void AQuantiserOutsideWhatTheCodecQuantisesIsRefused(int quantiser) - { - Assert.Throws(() => new ConstantQuantiser(quantiser)); - } - - [Theory] - [InlineData(ConstantQuantiser.Finest)] - [InlineData(24)] - [InlineData(ConstantQuantiser.Coarsest)] - public void AQuantiserOnTheEdgeOfWhatTheCodecQuantisesIsTaken(int quantiser) - { - Assert.Equal(quantiser, new ConstantQuantiser(quantiser).Quantiser); - } - - [Theory(DisplayName = "an AV1 quality index outside what the card quantises between is refused")] - [InlineData(-1)] - [InlineData(256)] - public void AnAv1QualityIndexOutsideWhatTheCardQuantisesBetweenIsRefused(int index) - { - Assert.Throws(() => new QualityIndex(index)); - } - - [Theory(DisplayName = "an AV1 quality index on the edge of what the card quantises between is taken")] - [InlineData(QualityIndex.Finest)] - [InlineData(80)] - [InlineData(QualityIndex.Coarsest)] - public void AnAv1QualityIndexOnTheEdgeIsTaken(int index) - { - Assert.Equal(index, new QualityIndex(index).Index); - } - - [Fact(DisplayName = "the card is handed a quantiser for H.264 and H.265 and a quality index for AV1")] - public void TheCardIsHandedAQuantiserForH264AndH265AndAQualityIndexForAv1() - { - CardRateControl handed = new(new ConstantQuantiser(24), new ConstantQuantiser(26), new QualityIndex(80)); - - Assert.Equal(new ConstantQuantiser(24), handed.H264); - Assert.Equal(new ConstantQuantiser(26), handed.H265); - Assert.Equal(new QualityIndex(80), handed.Av1); - Assert.Throws(() => new CardRateControl(null!, new ConstantQuantiser(24), new QualityIndex(80))); - Assert.Throws(() => new CardRateControl(new ConstantQuantiser(24), null!, new QualityIndex(80))); - Assert.Throws(() => new CardRateControl(new ConstantQuantiser(24), new ConstantQuantiser(24), null!)); - } - - [Fact] - public void NothingTheCardIsHandedCanBeChangedOnceItIsMade() - { - Assert.All( - typeof(CardRateControl).GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Concat(typeof(QualityIndex).GetProperties(BindingFlags.Public | BindingFlags.Instance)), - property => Assert.Null(property.SetMethod)); - } - - [Fact] - public void TwoCapsOfTheSameRateAreTheSameCap() - { - Assert.Equal(new BitrateCap(3000), new BitrateCap(3000)); - Assert.NotEqual(new BitrateCap(3000), new BitrateCap(4500)); - } - - [Fact] - public void AQuantiserCarriesAQuantiserAndNothingElse() - { - Assert.Equal( - [nameof(ConstantQuantiser.Quantiser)], - typeof(ConstantQuantiser) - .GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Select(property => property.Name)); - } - - [Fact] - public void NothingInTheDomainNamedForVaapiHoldsABitrate() - { - Assert.Empty(MembersPairingVaapiWithABitrate(typeof(BitrateCap).Assembly)); - } - - [Fact] - public void TheRuleCatchesAMemberNamedForVaapiTypedAsABitrate() - { - Assert.Contains( - $"{typeof(VaapiRateControlFixtures).FullName}.{nameof(VaapiRateControlFixtures.VaapiRateControl)}", - MembersPairingVaapiWithABitrate(typeof(VaapiRateControlFixtures).Assembly), - StringComparer.Ordinal); - } - - [Fact] - public void TheRuleDoesNotSeeARateWrittenOutAsAPlainNumber() - { - Assert.DoesNotContain( - $"{typeof(VaapiRateControlFixtures).FullName}.{nameof(VaapiRateControlFixtures.VaapiKilobitsPerSecond)}", - MembersPairingVaapiWithABitrate(typeof(VaapiRateControlFixtures).Assembly), - StringComparer.Ordinal); - } - - private static IReadOnlyList MembersPairingVaapiWithABitrate(Assembly assembly) - => - [ - .. from type in assembly.GetTypes() - where type.IsPublic - from member in Named(type) - where member.Name.Contains("vaapi", StringComparison.OrdinalIgnoreCase) - && member.Type == typeof(BitrateCap) - select $"{type.FullName}.{member.Name}", - ]; - - private static IEnumerable<(string Name, Type Type)> Named(Type type) - { - foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) - { - yield return (property.Name, property.PropertyType); - } - - foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) - { - foreach (ParameterInfo parameter in method.GetParameters()) - { - yield return ($"{method.Name}.{parameter.Name}", parameter.ParameterType); - } - } - - foreach (ConstructorInfo constructor in type.GetConstructors()) - { - foreach (ParameterInfo parameter in constructor.GetParameters()) - { - yield return ($"{type.Name}.{parameter.Name}", parameter.ParameterType); - } - } - } -} - -public sealed class VaapiRateControlFixtures -{ - public BitrateCap VaapiRateControl => new(3000); - - public int VaapiKilobitsPerSecond => 3000; -} diff --git a/tests/Carina.Domain.Tests/Streaming/StreamAttributeTypeTests.cs b/tests/Carina.Domain.Tests/Streaming/StreamAttributeTypeTests.cs deleted file mode 100644 index 48f4d6f85..000000000 --- a/tests/Carina.Domain.Tests/Streaming/StreamAttributeTypeTests.cs +++ /dev/null @@ -1,90 +0,0 @@ -using Carina.Domain.Base; -using Carina.Domain.Streaming; - -namespace Carina.Domain.Tests.Streaming; - -public sealed class StreamAttributeTypeTests -{ - [Theory] - [InlineData("30000/1001", 30000, 1001)] - [InlineData("30/1", 30, 1)] - [InlineData("60000/1001", 60000, 1001)] - public void ARateIsReadAsTheRatioItIs(string text, int numerator, int denominator) - { - FrameRate? rate = FrameRate.Read(text); - - Assert.NotNull(rate); - Assert.Equal(numerator, rate.Numerator); - Assert.Equal(denominator, rate.Denominator); - } - - [Theory] - [InlineData("0/0")] - [InlineData("30")] - [InlineData("/1001")] - [InlineData("30000/0")] - [InlineData("N/A")] - [InlineData("")] - [InlineData(null)] - public void SomethingThatIsNotARatioIsNotARate(string? text) - { - Assert.Null(FrameRate.Read(text)); - } - - [Fact] - public void ARateOfAlmostThirtyIsNotThirty() - { - Assert.Equal(29.97, FrameRate.Of(30000, 1001).PerSecond, 2); - Assert.NotEqual(30d, FrameRate.Of(30000, 1001).PerSecond); - } - - [Theory] - [InlineData(0, 1)] - [InlineData(30, 0)] - [InlineData(-30, 1)] - public void ARateOutsideTheShapeIsRefused(int numerator, int denominator) - { - Assert.Throws(() => FrameRate.Of(numerator, denominator)); - } - - [Theory] - [InlineData(0, 1080)] - [InlineData(1440, 0)] - [InlineData(-1440, 1080)] - public void APictureOfNoSizeIsRefused(int width, int height) - { - Assert.Throws(() => new VideoSize(width, height)); - } - - [Fact] - public void TwoPicturesOfTheSameSizeAreTheSameSize() - { - Assert.Equal(new VideoSize(1440, 1080), new VideoSize(1440, 1080)); - Assert.NotEqual(new VideoSize(1440, 1080), new VideoSize(1080, 1440)); - Assert.Equal("1440x1080", new VideoSize(1440, 1080).ToString()); - } - - [Fact] - public void ASourceIsTheValueItWasGiven() - { - Assert.Equal("/srv/recordings/k-1.ts", new StreamSource("/srv/recordings/k-1.ts").Value); - Assert.Equal(new StreamSource("/srv/recordings/k-1.ts"), new StreamSource("/srv/recordings/k-1.ts")); - } - - [Fact] - public void AScanTheStreamNeverSettledIsNotOneOfTheTwoWaysAPictureIsDrawn() - { - Assert.Equal(0, (int)ScanType.Undetermined); - Assert.Equal(0, (int)AudioMode.Undetermined); - } - - [Fact] - public void AnAttributeSetIsRefusedAValueOutsideTheOnesNamed() - { - Assert.Throws( - () => new StreamAttributes(new VideoSize(1, 1), (ScanType)99, FrameRate.Of(30, 1), AudioMode.Stereo)); - - Assert.Throws( - () => new StreamAttributes(new VideoSize(1, 1), ScanType.Progressive, FrameRate.Of(30, 1), (AudioMode)99)); - } -} diff --git a/tests/Carina.Domain.Tests/Streaming/TranscodeBudgetTypeTests.cs b/tests/Carina.Domain.Tests/Streaming/TranscodeBudgetTypeTests.cs deleted file mode 100644 index 9286cd478..000000000 --- a/tests/Carina.Domain.Tests/Streaming/TranscodeBudgetTypeTests.cs +++ /dev/null @@ -1,116 +0,0 @@ -using Carina.Domain.Streaming; - -namespace Carina.Domain.Tests.Streaming; - -public sealed class TranscodeBudgetTypeTests -{ - [Fact] - public void TheMachineRunsFourTranscodersAtOnceUnlessItIsToldOtherwise() - { - Assert.Equal(4, new TranscodeBudgetSettings().AtOnce); - } - - [Fact] - public void ACeilingOfNoneIsRefusedBecauseItIsARouteThatNeverPlaysRatherThanABoundedOne() - { - Assert.Throws(() => new TranscodeBudgetSettings { AtOnce = 0 }); - Assert.Throws(() => new TranscodeBudgetSettings { AtOnce = -1 }); - Assert.Equal(1, new TranscodeBudgetSettings { AtOnce = 1 }.AtOnce); - Assert.Equal(TranscodeBudgetSettings.Fewest, new TranscodeBudgetSettings { AtOnce = 1 }.AtOnce); - } - - [Fact] - public void ACeilingSaysHowManyAreRunningAndHowManyTheMachineIsAskedToRun() - { - TranscodeCeiling ceiling = new(3, 3); - - Assert.Equal(3, ceiling.Running); - Assert.Equal(3, ceiling.AtOnce); - Assert.Contains("3 transcoder", ceiling.Said, StringComparison.Ordinal); - Assert.Contains("live and playback together", ceiling.Said, StringComparison.Ordinal); - } - - [Fact] - public void ACeilingIsOnlyReachedWhenAsManyAreRunningAsTheMachineIsAskedTo() - { - Assert.Throws(() => new TranscodeCeiling(2, 3)); - Assert.Throws(() => new TranscodeCeiling(0, 0)); - Assert.Throws(() => new TranscodeCeiling(1, -1)); - Assert.Equal(4, new TranscodeCeiling(4, 3).Running); - } - - [Fact] - public void AClaimThatWasSeatedCarriesTheSeatAndNoRefusal() - { - HeldSeat seat = new(TranscodePurpose.Live, 1, 4); - - TranscodeClaim claim = TranscodeClaim.Seated(seat); - - Assert.True(claim.Taken); - Assert.Same(seat, claim.Seat); - Assert.Null(claim.Refusal); - } - - [Fact] - public void AClaimThatWasRefusedCarriesTheCeilingAndNoSeat() - { - TranscodeCeiling ceiling = new(4, 4); - - TranscodeClaim claim = TranscodeClaim.Refused(ceiling); - - Assert.False(claim.Taken); - Assert.Null(claim.Seat); - Assert.Same(ceiling, claim.Refusal); - } - - [Fact] - public void AClaimIsMadeOfSomethingRatherThanNothing() - { - Assert.Throws(() => TranscodeClaim.Seated(null!)); - Assert.Throws(() => TranscodeClaim.Refused(null!)); - } - - [Fact] - public void ATranscoderIsRaisedForOneOfTheTwoPurposesThereAre() - { - Assert.Equal( - [TranscodePurpose.Live, TranscodePurpose.Playback], - Enum.GetValues().Order().ToArray()); - } - - [Fact] - public void ALiveStartRefusedAtTheCeilingSaysSoInTypeAndInWords() - { - TranscodeCeiling ceiling = new(4, 4); - - LiveTranscoderStart refused = LiveTranscoderStart.Refused(ceiling); - - Assert.False(refused.Running); - Assert.Null(refused.Transcoder); - Assert.Equal(TranscoderFault.TooManyAlready, refused.Fault); - Assert.Same(ceiling, refused.Ceiling); - Assert.Equal(ceiling.Said, refused.Note); - } - - [Fact] - public void ALiveStartThatFailedAnotherWayCarriesNoCeiling() - { - LiveTranscoderStart failed = LiveTranscoderStart.Failed(TranscoderFault.ProgrammeMissing, "gone"); - - Assert.Null(failed.Ceiling); - Assert.Throws(() => LiveTranscoderStart.Refused(null!)); - } - - private sealed class HeldSeat(TranscodePurpose purpose, int place, int atOnce) : ITranscodeSeat - { - public TranscodePurpose Purpose { get; } = purpose; - - public int Place { get; } = place; - - public int AtOnce { get; } = atOnce; - - public void Dispose() - { - } - } -} diff --git a/tests/Carina.Domain.Tests/Captions/CaptionLedgerTests.cs b/tests/Carina.Domain.Tests/Unit/Captions/CaptionLedgerTests.cs similarity index 97% rename from tests/Carina.Domain.Tests/Captions/CaptionLedgerTests.cs rename to tests/Carina.Domain.Tests/Unit/Captions/CaptionLedgerTests.cs index 391652990..08577ac38 100644 --- a/tests/Carina.Domain.Tests/Captions/CaptionLedgerTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Captions/CaptionLedgerTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Recordings; using Carina.Domain.Tests.Unit.Recordings; -namespace Carina.Domain.Tests.Captions; +namespace Carina.Domain.Tests.Unit.Captions; +[Trait("Category", "Unit")] public sealed class CaptionLedgerTests { private static readonly DateTime Later = RecordingFactory.Now.AddHours(2); diff --git a/tests/Carina.Domain.Tests/Captions/CaptionRequeueDomainServiceTests.cs b/tests/Carina.Domain.Tests/Unit/Captions/CaptionRequeueDomainServiceTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Captions/CaptionRequeueDomainServiceTests.cs rename to tests/Carina.Domain.Tests/Unit/Captions/CaptionRequeueDomainServiceTests.cs index 2dfa0ae41..cc1feed2c 100644 --- a/tests/Carina.Domain.Tests/Captions/CaptionRequeueDomainServiceTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Captions/CaptionRequeueDomainServiceTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Captions; using Carina.Domain.Recordings; -namespace Carina.Domain.Tests.Captions; +namespace Carina.Domain.Tests.Unit.Captions; +[Trait("Category", "Unit")] public sealed class CaptionRequeueDomainServiceTests { private static readonly CancellationToken Cancel = CancellationToken.None; diff --git a/tests/Carina.Domain.Tests/Captions/CaptionWindowTests.cs b/tests/Carina.Domain.Tests/Unit/Captions/CaptionWindowTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Captions/CaptionWindowTests.cs rename to tests/Carina.Domain.Tests/Unit/Captions/CaptionWindowTests.cs index 93117394d..bde2a80c5 100644 --- a/tests/Carina.Domain.Tests/Captions/CaptionWindowTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Captions/CaptionWindowTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Captions; -namespace Carina.Domain.Tests.Captions; +namespace Carina.Domain.Tests.Unit.Captions; +[Trait("Category", "Unit")] public sealed class CaptionWindowTests { private const long Second = CaptionCue.Hertz; diff --git a/tests/Carina.Domain.Tests/Playback/ArtefactCodecReadingTests.cs b/tests/Carina.Domain.Tests/Unit/Playback/ArtefactCodecReadingTests.cs similarity index 96% rename from tests/Carina.Domain.Tests/Playback/ArtefactCodecReadingTests.cs rename to tests/Carina.Domain.Tests/Unit/Playback/ArtefactCodecReadingTests.cs index bc98c9b8e..fe0ea1f90 100644 --- a/tests/Carina.Domain.Tests/Playback/ArtefactCodecReadingTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Playback/ArtefactCodecReadingTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Encodings; using Carina.Domain.Playback; -namespace Carina.Domain.Tests.Playback; +namespace Carina.Domain.Tests.Unit.Playback; +[Trait("Category", "Unit")] public sealed class ArtefactCodecReadingTests { [Fact(DisplayName = "a file read as H.265 tagged hvc1 says it is tagged the way Safari plays")] diff --git a/tests/Carina.Domain.Tests/Playback/PlaybackArtefactDomainServiceTests.cs b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackArtefactDomainServiceTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Playback/PlaybackArtefactDomainServiceTests.cs rename to tests/Carina.Domain.Tests/Unit/Playback/PlaybackArtefactDomainServiceTests.cs index 1b84438f5..851afcfe5 100644 --- a/tests/Carina.Domain.Tests/Playback/PlaybackArtefactDomainServiceTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackArtefactDomainServiceTests.cs @@ -3,8 +3,9 @@ using Carina.Domain.Recordings; using Carina.TestSupport; -namespace Carina.Domain.Tests.Playback; +namespace Carina.Domain.Tests.Unit.Playback; +[Trait("Category", "Unit")] public sealed class PlaybackArtefactDomainServiceTests { private static readonly CancellationToken Cancel = CancellationToken.None; diff --git a/tests/Carina.Domain.Tests/Playback/PlaybackAudienceTests.cs b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackAudienceTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Playback/PlaybackAudienceTests.cs rename to tests/Carina.Domain.Tests/Unit/Playback/PlaybackAudienceTests.cs index 7f0bf6788..0e5ecbc0d 100644 --- a/tests/Carina.Domain.Tests/Playback/PlaybackAudienceTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackAudienceTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Encodings; using Carina.Domain.Playback; -namespace Carina.Domain.Tests.Playback; +namespace Carina.Domain.Tests.Unit.Playback; +[Trait("Category", "Unit")] public sealed class PlaybackAudienceTests { public static TheoryData EveryAudience => new() diff --git a/tests/Carina.Domain.Tests/Playback/PlaybackPlanTests.cs b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackPlanTests.cs similarity index 99% rename from tests/Carina.Domain.Tests/Playback/PlaybackPlanTests.cs rename to tests/Carina.Domain.Tests/Unit/Playback/PlaybackPlanTests.cs index 35463526f..fd35dee63 100644 --- a/tests/Carina.Domain.Tests/Playback/PlaybackPlanTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackPlanTests.cs @@ -3,8 +3,9 @@ using Carina.Domain.Recordings; using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Playback; +namespace Carina.Domain.Tests.Unit.Playback; +[Trait("Category", "Unit")] public sealed class PlaybackPlanTests { public static TheoryData EveryWayARecordingCanStand => new() diff --git a/tests/Carina.Domain.Tests/Playback/PlaybackSeekingTests.cs b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackSeekingTests.cs similarity index 96% rename from tests/Carina.Domain.Tests/Playback/PlaybackSeekingTests.cs rename to tests/Carina.Domain.Tests/Unit/Playback/PlaybackSeekingTests.cs index e9d3ae1de..dee280c32 100644 --- a/tests/Carina.Domain.Tests/Playback/PlaybackSeekingTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackSeekingTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Playback; using Carina.Domain.Recordings; -namespace Carina.Domain.Tests.Playback; +namespace Carina.Domain.Tests.Unit.Playback; +[Trait("Category", "Unit")] public sealed class PlaybackSeekingTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Playback/PlaybackSourceTests.cs b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackSourceTests.cs similarity index 94% rename from tests/Carina.Domain.Tests/Playback/PlaybackSourceTests.cs rename to tests/Carina.Domain.Tests/Unit/Playback/PlaybackSourceTests.cs index 50f2717b8..846afbc88 100644 --- a/tests/Carina.Domain.Tests/Playback/PlaybackSourceTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Playback/PlaybackSourceTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Playback; -namespace Carina.Domain.Tests.Playback; +namespace Carina.Domain.Tests.Unit.Playback; +[Trait("Category", "Unit")] public sealed class PlaybackSourceTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Playback/SourcePlacementDomainServiceTests.cs b/tests/Carina.Domain.Tests/Unit/Playback/SourcePlacementDomainServiceTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Playback/SourcePlacementDomainServiceTests.cs rename to tests/Carina.Domain.Tests/Unit/Playback/SourcePlacementDomainServiceTests.cs index 55190bf75..b6cbca38e 100644 --- a/tests/Carina.Domain.Tests/Playback/SourcePlacementDomainServiceTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Playback/SourcePlacementDomainServiceTests.cs @@ -3,8 +3,9 @@ using Carina.Domain.Recordings; using Carina.TestSupport; -namespace Carina.Domain.Tests.Playback; +namespace Carina.Domain.Tests.Unit.Playback; +[Trait("Category", "Unit")] public sealed class SourcePlacementDomainServiceTests { private static readonly CancellationToken Cancel = CancellationToken.None; diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/BitrateCapTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/BitrateCapTests.cs new file mode 100644 index 000000000..ccf4129ae --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/BitrateCapTests.cs @@ -0,0 +1,92 @@ +using System.Reflection; + +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class BitrateCapTests +{ + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(-3000)] + public void ACapOfNothingASecondIsRefused(int kilobitsPerSecond) + { + Assert.Throws(() => new BitrateCap(kilobitsPerSecond)); + } + + [Theory] + [InlineData(1)] + [InlineData(3000)] + public void ACapIsTheRateItNames(int kilobitsPerSecond) + { + Assert.Equal(kilobitsPerSecond, new BitrateCap(kilobitsPerSecond).KilobitsPerSecond); + } + + [Fact] + public void TwoCapsOfTheSameRateAreTheSameCap() + { + Assert.Equal(new BitrateCap(3000), new BitrateCap(3000)); + Assert.NotEqual(new BitrateCap(3000), new BitrateCap(4500)); + } + + [Fact] + public void NothingInTheDomainNamedForVaapiHoldsABitrate() + { + Assert.Empty(MembersPairingVaapiWithABitrate(typeof(BitrateCap).Assembly)); + } + + [Fact] + public void TheRuleCatchesAMemberNamedForVaapiTypedAsABitrate() + { + Assert.Contains( + $"{typeof(VaapiRateControlFixtures).FullName}.{nameof(VaapiRateControlFixtures.VaapiRateControl)}", + MembersPairingVaapiWithABitrate(typeof(VaapiRateControlFixtures).Assembly), + StringComparer.Ordinal); + } + + [Fact] + public void TheRuleDoesNotSeeARateWrittenOutAsAPlainNumber() + { + Assert.DoesNotContain( + $"{typeof(VaapiRateControlFixtures).FullName}.{nameof(VaapiRateControlFixtures.VaapiKilobitsPerSecond)}", + MembersPairingVaapiWithABitrate(typeof(VaapiRateControlFixtures).Assembly), + StringComparer.Ordinal); + } + + private static IReadOnlyList MembersPairingVaapiWithABitrate(Assembly assembly) + => + [ + .. from type in assembly.GetTypes() + where type.IsPublic + from member in Named(type) + where member.Name.Contains("vaapi", StringComparison.OrdinalIgnoreCase) + && member.Type == typeof(BitrateCap) + select $"{type.FullName}.{member.Name}", + ]; + + private static IEnumerable<(string Name, Type Type)> Named(Type type) + { + foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) + { + yield return (property.Name, property.PropertyType); + } + + foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) + { + foreach (ParameterInfo parameter in method.GetParameters()) + { + yield return ($"{method.Name}.{parameter.Name}", parameter.ParameterType); + } + } + + foreach (ConstructorInfo constructor in type.GetConstructors()) + { + foreach (ParameterInfo parameter in constructor.GetParameters()) + { + yield return ($"{type.Name}.{parameter.Name}", parameter.ParameterType); + } + } + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/CardRateControlTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/CardRateControlTests.cs new file mode 100644 index 000000000..df92801e7 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/CardRateControlTests.cs @@ -0,0 +1,31 @@ +using System.Reflection; + +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class CardRateControlTests +{ + [Fact(DisplayName = "the card is handed a quantiser for H.264 and H.265 and a quality index for AV1")] + public void TheCardIsHandedAQuantiserForH264AndH265AndAQualityIndexForAv1() + { + CardRateControl handed = new(new ConstantQuantiser(24), new ConstantQuantiser(26), new QualityIndex(80)); + + Assert.Equal(new ConstantQuantiser(24), handed.H264); + Assert.Equal(new ConstantQuantiser(26), handed.H265); + Assert.Equal(new QualityIndex(80), handed.Av1); + Assert.Throws(() => new CardRateControl(null!, new ConstantQuantiser(24), new QualityIndex(80))); + Assert.Throws(() => new CardRateControl(new ConstantQuantiser(24), null!, new QualityIndex(80))); + Assert.Throws(() => new CardRateControl(new ConstantQuantiser(24), new ConstantQuantiser(24), null!)); + } + + [Fact] + public void NothingTheCardIsHandedCanBeChangedOnceItIsMade() + { + Assert.All( + typeof(CardRateControl).GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Concat(typeof(QualityIndex).GetProperties(BindingFlags.Public | BindingFlags.Instance)), + property => Assert.Null(property.SetMethod)); + } +} diff --git a/tests/Carina.Domain.Tests/Streaming/CarriedSoundsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/CarriedSoundsTests.cs similarity index 97% rename from tests/Carina.Domain.Tests/Streaming/CarriedSoundsTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/CarriedSoundsTests.cs index 7554e8700..6f07b456e 100644 --- a/tests/Carina.Domain.Tests/Streaming/CarriedSoundsTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/CarriedSoundsTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class CarriedSoundsTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/ConstantQuantiserTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/ConstantQuantiserTests.cs new file mode 100644 index 000000000..b93e7344b --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/ConstantQuantiserTests.cs @@ -0,0 +1,36 @@ +using System.Reflection; + +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class ConstantQuantiserTests +{ + [Theory] + [InlineData(-1)] + [InlineData(52)] + public void AQuantiserOutsideWhatTheCodecQuantisesIsRefused(int quantiser) + { + Assert.Throws(() => new ConstantQuantiser(quantiser)); + } + + [Theory] + [InlineData(ConstantQuantiser.Finest)] + [InlineData(24)] + [InlineData(ConstantQuantiser.Coarsest)] + public void AQuantiserOnTheEdgeOfWhatTheCodecQuantisesIsTaken(int quantiser) + { + Assert.Equal(quantiser, new ConstantQuantiser(quantiser).Quantiser); + } + + [Fact] + public void AQuantiserCarriesAQuantiserAndNothingElse() + { + Assert.Equal( + [nameof(ConstantQuantiser.Quantiser)], + typeof(ConstantQuantiser) + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Select(property => property.Name)); + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/FrameRateTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/FrameRateTests.cs new file mode 100644 index 000000000..996d2fadb --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/FrameRateTests.cs @@ -0,0 +1,49 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class FrameRateTests +{ + [Theory] + [InlineData("30000/1001", 30000, 1001)] + [InlineData("30/1", 30, 1)] + [InlineData("60000/1001", 60000, 1001)] + public void ARateIsReadAsTheRatioItIs(string text, int numerator, int denominator) + { + FrameRate? rate = FrameRate.Read(text); + + Assert.NotNull(rate); + Assert.Equal(numerator, rate.Numerator); + Assert.Equal(denominator, rate.Denominator); + } + + [Theory] + [InlineData("0/0")] + [InlineData("30")] + [InlineData("/1001")] + [InlineData("30000/0")] + [InlineData("N/A")] + [InlineData("")] + [InlineData(null)] + public void SomethingThatIsNotARatioIsNotARate(string? text) + { + Assert.Null(FrameRate.Read(text)); + } + + [Fact] + public void ARateOfAlmostThirtyIsNotThirty() + { + Assert.Equal(29.97, FrameRate.Of(30000, 1001).PerSecond, 2); + Assert.NotEqual(30d, FrameRate.Of(30000, 1001).PerSecond); + } + + [Theory] + [InlineData(0, 1)] + [InlineData(30, 0)] + [InlineData(-30, 1)] + public void ARateOutsideTheShapeIsRefused(int numerator, int denominator) + { + Assert.Throws(() => FrameRate.Of(numerator, denominator)); + } +} diff --git a/tests/Carina.Domain.Tests/Streaming/HlsSettingsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/HlsSettingsTests.cs similarity index 97% rename from tests/Carina.Domain.Tests/Streaming/HlsSettingsTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/HlsSettingsTests.cs index 1705dd3de..e80bc9e5e 100644 --- a/tests/Carina.Domain.Tests/Streaming/HlsSettingsTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/HlsSettingsTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class HlsSettingsTests { [Fact(DisplayName = "BR-PV-005: by default a key nobody asks with for thirty seconds is let go of")] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveBacklogTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveBacklogTests.cs similarity index 92% rename from tests/Carina.Domain.Tests/Streaming/LiveBacklogTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveBacklogTests.cs index c04cc4129..e6aba7614 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveBacklogTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveBacklogTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveBacklogTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveCaptionsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveCaptionsTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/LiveCaptionsTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveCaptionsTests.cs index 22a170a90..8b2d19f1f 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveCaptionsTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveCaptionsTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveCaptionsTests { private static readonly byte[] Png = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]; diff --git a/tests/Carina.Domain.Tests/Streaming/LiveChannelQueryTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveChannelQueryTests.cs similarity index 97% rename from tests/Carina.Domain.Tests/Streaming/LiveChannelQueryTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveChannelQueryTests.cs index 2ad84a128..8ce60ba33 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveChannelQueryTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveChannelQueryTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveChannelQueryTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveChannelTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveChannelTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/LiveChannelTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveChannelTests.cs index c66a30007..f9d44658b 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveChannelTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveChannelTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveChannelTests { [Theory] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveControlTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveControlTests.cs similarity index 97% rename from tests/Carina.Domain.Tests/Streaming/LiveControlTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveControlTests.cs index d7a455893..0e52566c8 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveControlTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveControlTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveControlTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveDepartureTallyTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveDepartureTallyTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/LiveDepartureTallyTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveDepartureTallyTests.cs index 76f8a226e..033c19085 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveDepartureTallyTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveDepartureTallyTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveDepartureTallyTests { private static readonly DateTime Since = new(2026, 9, 13, 4, 0, 0, DateTimeKind.Utc); diff --git a/tests/Carina.Domain.Tests/Streaming/LiveTranscodeTypeTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveEncoderChoiceTests.cs similarity index 52% rename from tests/Carina.Domain.Tests/Streaming/LiveTranscodeTypeTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveEncoderChoiceTests.cs index f470dbfb0..3bde11d31 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveTranscodeTypeTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveEncoderChoiceTests.cs @@ -1,9 +1,10 @@ using Carina.Domain.Machines; using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; -public sealed class LiveTranscodeTypeTests +[Trait("Category", "Unit")] +public sealed class LiveEncoderChoiceTests { [Theory] [InlineData(LiveEncoder.Software)] @@ -72,69 +73,4 @@ public void TheOnlyReasonsACardIsTurnedDownAreThese() ], Enum.GetValues().Where(standing => !CardStandings.IsUsable(standing))); } - - [Fact] - public void APictureIsEncodedInSoftwareUntilSomebodyAsksForTheCard() - { - Assert.Equal(LiveEncoder.Software, new LiveTranscodeSettings().Prefer); - Assert.Equal("ffmpeg", new LiveTranscodeSettings().Programme); - } - - [Fact] - public void AProgrammeThatExitedZeroRanToTheEnd() - { - TranscoderExit ended = TranscoderExit.Finished(); - - Assert.True(ended.RanToTheEnd); - Assert.Null(ended.Fault); - Assert.Equal(0, ended.ExitCode); - } - - [Fact] - public void AProgrammeThatRefusedSaysWithWhatCodeAndWhatItComplainedOf() - { - TranscoderExit refused = TranscoderExit.Refused(1, "Invalid data found when processing input"); - - Assert.False(refused.RanToTheEnd); - Assert.Equal(TranscoderFault.Refused, refused.Fault); - Assert.Equal(1, refused.ExitCode); - Assert.Contains("Invalid data", refused.Note, StringComparison.Ordinal); - } - - [Fact] - public void AProgrammeThatExitedZeroWasNotRefusedByIt() - { - Assert.Throws(() => TranscoderExit.Refused(0, "fine")); - } - - [Fact] - public void AProgrammeThatWasCalledOffHasNoCodeToReport() - { - TranscoderExit off = TranscoderExit.CalledOff("nothing said"); - - Assert.False(off.RanToTheEnd); - Assert.Equal(TranscoderFault.CalledOff, off.Fault); - Assert.Null(off.ExitCode); - } - - [Fact] - public void AStartThatFailedCarriesNeitherATranscoderNorAPath() - { - LiveTranscoderStart failed = LiveTranscoderStart.Failed( - TranscoderFault.ProgrammeMissing, - "'/usr/local/bin/ffmpeg' could not be started on this machine"); - - Assert.False(failed.Running); - Assert.Null(failed.Transcoder); - Assert.Equal(TranscoderFault.ProgrammeMissing, failed.Fault); - Assert.NotEmpty(failed.Note); - Assert.DoesNotContain('/', failed.Note); - } - - [Fact] - public void AStartThatFailedForNoNamedReasonIsRefused() - { - Assert.Throws( - () => LiveTranscoderStart.Failed((TranscoderFault)9, "silently")); - } } diff --git a/tests/Carina.Domain.Tests/Streaming/LiveEndingReportTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveEndingReportTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/LiveEndingReportTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveEndingReportTests.cs index 272fdbb21..9c7263d9e 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveEndingReportTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveEndingReportTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveEndingReportTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveFanoutSettingsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveFanoutSettingsTests.cs similarity index 91% rename from tests/Carina.Domain.Tests/Streaming/LiveFanoutSettingsTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveFanoutSettingsTests.cs index 215c82fbf..01c416624 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveFanoutSettingsTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveFanoutSettingsTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveFanoutSettingsTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveFrameTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveFrameTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/LiveFrameTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveFrameTests.cs index 3c5a65b3e..3aa2f6571 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveFrameTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveFrameTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveFrameTests { private static readonly byte[] Payload = [0xde, 0xad, 0xbe, 0xef]; diff --git a/tests/Carina.Domain.Tests/Streaming/LiveJoinTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveJoinTests.cs similarity index 96% rename from tests/Carina.Domain.Tests/Streaming/LiveJoinTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveJoinTests.cs index 5ba4792ad..847308d84 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveJoinTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveJoinTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveJoinTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveProfileTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveProfileTests.cs similarity index 99% rename from tests/Carina.Domain.Tests/Streaming/LiveProfileTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveProfileTests.cs index 6073a6215..7ff873168 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveProfileTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveProfileTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveProfileTests { public static TheoryData WhatIsNotAProfile => diff --git a/tests/Carina.Domain.Tests/Streaming/LivePtsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LivePtsTests.cs similarity index 96% rename from tests/Carina.Domain.Tests/Streaming/LivePtsTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LivePtsTests.cs index 9aa773823..36d42996c 100644 --- a/tests/Carina.Domain.Tests/Streaming/LivePtsTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LivePtsTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LivePtsTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveRefusalDetailTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveRefusalDetailTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/LiveRefusalDetailTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveRefusalDetailTests.cs index a241687ee..945ccc561 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveRefusalDetailTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveRefusalDetailTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Channels; using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveRefusalDetailTests { [Theory] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveRefusalReportTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveRefusalReportTests.cs similarity index 99% rename from tests/Carina.Domain.Tests/Streaming/LiveRefusalReportTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveRefusalReportTests.cs index 87016c5df..410461f39 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveRefusalReportTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveRefusalReportTests.cs @@ -3,8 +3,9 @@ using Carina.Domain.Channels; using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveRefusalReportTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveSessionKeyTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionKeyTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/LiveSessionKeyTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionKeyTests.cs index 4ecb0173e..79b8d65c0 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveSessionKeyTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionKeyTests.cs @@ -3,8 +3,9 @@ using Carina.Domain.Channels; using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveSessionKeyTests { private static readonly NetworkId Network = new(32736); diff --git a/tests/Carina.Domain.Tests/Streaming/LiveSessionSettingsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionSettingsTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/LiveSessionSettingsTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionSettingsTests.cs index a75359b90..f2611ada8 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveSessionSettingsTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionSettingsTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveSessionSettingsTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveSessionViewTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionViewTests.cs similarity index 97% rename from tests/Carina.Domain.Tests/Streaming/LiveSessionViewTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionViewTests.cs index 9fcd87102..35e5b0142 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveSessionViewTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSessionViewTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Channels; using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveSessionViewTests { private static readonly LiveSessionKey Key = new(new NetworkId(32736), new ServiceId(1024), LiveProfile.Hd30); diff --git a/tests/Carina.Domain.Tests/Streaming/LiveStartupTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveStartupTests.cs similarity index 99% rename from tests/Carina.Domain.Tests/Streaming/LiveStartupTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveStartupTests.cs index 201c0104d..f7deec7f0 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveStartupTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveStartupTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveStartupTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveSupplyEndingTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSupplyEndingTests.cs similarity index 95% rename from tests/Carina.Domain.Tests/Streaming/LiveSupplyEndingTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveSupplyEndingTests.cs index e08eed29c..3283c9c97 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveSupplyEndingTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSupplyEndingTests.cs @@ -2,8 +2,9 @@ using Puppis.Contracts; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveSupplyEndingTests { [Theory] diff --git a/tests/Carina.Domain.Tests/Streaming/LiveSupplyStartTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSupplyStartTests.cs similarity index 96% rename from tests/Carina.Domain.Tests/Streaming/LiveSupplyStartTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveSupplyStartTests.cs index 4987a90a5..52eb13b57 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveSupplyStartTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveSupplyStartTests.cs @@ -2,8 +2,9 @@ using Puppis.Contracts; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveSupplyStartTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/LiveTranscodeSettingsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveTranscodeSettingsTests.cs new file mode 100644 index 000000000..21136d154 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveTranscodeSettingsTests.cs @@ -0,0 +1,14 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class LiveTranscodeSettingsTests +{ + [Fact] + public void APictureIsEncodedInSoftwareUntilSomebodyAsksForTheCard() + { + Assert.Equal(LiveEncoder.Software, new LiveTranscodeSettings().Prefer); + Assert.Equal("ffmpeg", new LiveTranscodeSettings().Programme); + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/LiveTranscoderStartTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveTranscoderStartTests.cs new file mode 100644 index 000000000..6f5c5fbe5 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveTranscoderStartTests.cs @@ -0,0 +1,51 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class LiveTranscoderStartTests +{ + [Fact] + public void AStartThatFailedCarriesNeitherATranscoderNorAPath() + { + LiveTranscoderStart failed = LiveTranscoderStart.Failed( + TranscoderFault.ProgrammeMissing, + "'/usr/local/bin/ffmpeg' could not be started on this machine"); + + Assert.False(failed.Running); + Assert.Null(failed.Transcoder); + Assert.Equal(TranscoderFault.ProgrammeMissing, failed.Fault); + Assert.NotEmpty(failed.Note); + Assert.DoesNotContain('/', failed.Note); + } + + [Fact] + public void AStartThatFailedForNoNamedReasonIsRefused() + { + Assert.Throws( + () => LiveTranscoderStart.Failed((TranscoderFault)9, "silently")); + } + + [Fact] + public void ALiveStartRefusedAtTheCeilingSaysSoInTypeAndInWords() + { + TranscodeCeiling ceiling = new(4, 4); + + LiveTranscoderStart refused = LiveTranscoderStart.Refused(ceiling); + + Assert.False(refused.Running); + Assert.Null(refused.Transcoder); + Assert.Equal(TranscoderFault.TooManyAlready, refused.Fault); + Assert.Same(ceiling, refused.Ceiling); + Assert.Equal(ceiling.Said, refused.Note); + } + + [Fact] + public void ALiveStartThatFailedAnotherWayCarriesNoCeiling() + { + LiveTranscoderStart failed = LiveTranscoderStart.Failed(TranscoderFault.ProgrammeMissing, "gone"); + + Assert.Null(failed.Ceiling); + Assert.Throws(() => LiveTranscoderStart.Refused(null!)); + } +} diff --git a/tests/Carina.Domain.Tests/Streaming/LiveWireSettingsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/LiveWireSettingsTests.cs similarity index 97% rename from tests/Carina.Domain.Tests/Streaming/LiveWireSettingsTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/LiveWireSettingsTests.cs index d8fbc4ec4..6919e73be 100644 --- a/tests/Carina.Domain.Tests/Streaming/LiveWireSettingsTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/LiveWireSettingsTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class LiveWireSettingsTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlySettingsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlySettingsTests.cs new file mode 100644 index 000000000..42169e758 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlySettingsTests.cs @@ -0,0 +1,22 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class OnTheFlySettingsTests +{ + [Fact] + public void ATranscoderIsGivenHalfAMinuteForItsFirstByteUnlessItIsToldOtherwise() + { + Assert.Equal(TimeSpan.FromSeconds(30), new OnTheFlySettings().LongestWaitForTheFirstByte); + } + + [Fact] + public void ATranscoderIsGivenSomeTimeToProduceItsFirstByteRatherThanNone() + { + Assert.Throws( + () => new OnTheFlySettings { LongestWaitForTheFirstByte = TimeSpan.Zero }); + Assert.Throws( + () => new OnTheFlySettings { LongestWaitForTheFirstByte = TimeSpan.FromSeconds(-1) }); + } +} diff --git a/tests/Carina.Domain.Tests/Streaming/OnTheFlyTypeTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlyStandingTests.cs similarity index 61% rename from tests/Carina.Domain.Tests/Streaming/OnTheFlyTypeTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlyStandingTests.cs index a5f1b8ce7..a6f6aa464 100644 --- a/tests/Carina.Domain.Tests/Streaming/OnTheFlyTypeTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlyStandingTests.cs @@ -1,24 +1,10 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; -public sealed class OnTheFlyTypeTests +[Trait("Category", "Unit")] +public sealed class OnTheFlyStandingTests { - [Fact] - public void ATranscoderIsGivenHalfAMinuteForItsFirstByteUnlessItIsToldOtherwise() - { - Assert.Equal(TimeSpan.FromSeconds(30), new OnTheFlySettings().LongestWaitForTheFirstByte); - } - - [Fact] - public void ATranscoderIsGivenSomeTimeToProduceItsFirstByteRatherThanNone() - { - Assert.Throws( - () => new OnTheFlySettings { LongestWaitForTheFirstByte = TimeSpan.Zero }); - Assert.Throws( - () => new OnTheFlySettings { LongestWaitForTheFirstByte = TimeSpan.FromSeconds(-1) }); - } - [Fact] public void AStandingSaysWhereInTheRecordingItsFirstByteSitsAndWhatGettingThereCost() { @@ -70,27 +56,6 @@ public void AStandingIsToldWhichProfileAndWhichEncoderRatherThanNeither() atOnce: 2)); } - [Fact] - public void ARefusalNamesNoPathOnThisMachine() - { - OnTheFlyStart refused = OnTheFlyStart.Refused( - OnTheFlyRefusal.NothingCameOut, - "Error opening input /srv/recordings/a1b2c3.ts: No such file"); - - Assert.False(refused.Running); - Assert.Null(refused.Viewing); - Assert.Equal(OnTheFlyRefusal.NothingCameOut, refused.Refusal); - Assert.DoesNotContain('/', refused.Note); - Assert.Contains("Error opening input", refused.Note, StringComparison.Ordinal); - } - - [Fact] - public void ARecordingIsRefusedForOneOfTheReasonsNamedRatherThanAnyNumberAtAll() - { - Assert.Throws(() => OnTheFlyStart.Refused((OnTheFlyRefusal)99, "no")); - Assert.Throws(() => OnTheFlyStart.Started(null!)); - } - private static OnTheFlyStanding Standing( TimeSpan? startsAt = null, TimeSpan? waited = null, diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlyStartTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlyStartTests.cs new file mode 100644 index 000000000..9425aa4fc --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/OnTheFlyStartTests.cs @@ -0,0 +1,28 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class OnTheFlyStartTests +{ + [Fact] + public void ARefusalNamesNoPathOnThisMachine() + { + OnTheFlyStart refused = OnTheFlyStart.Refused( + OnTheFlyRefusal.NothingCameOut, + "Error opening input /srv/recordings/a1b2c3.ts: No such file"); + + Assert.False(refused.Running); + Assert.Null(refused.Viewing); + Assert.Equal(OnTheFlyRefusal.NothingCameOut, refused.Refusal); + Assert.DoesNotContain('/', refused.Note); + Assert.Contains("Error opening input", refused.Note, StringComparison.Ordinal); + } + + [Fact] + public void ARecordingIsRefusedForOneOfTheReasonsNamedRatherThanAnyNumberAtAll() + { + Assert.Throws(() => OnTheFlyStart.Refused((OnTheFlyRefusal)99, "no")); + Assert.Throws(() => OnTheFlyStart.Started(null!)); + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/QualityIndexTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/QualityIndexTests.cs new file mode 100644 index 000000000..ef1aea4c9 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/QualityIndexTests.cs @@ -0,0 +1,24 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class QualityIndexTests +{ + [Theory(DisplayName = "an AV1 quality index outside what the card quantises between is refused")] + [InlineData(-1)] + [InlineData(256)] + public void AnAv1QualityIndexOutsideWhatTheCardQuantisesBetweenIsRefused(int index) + { + Assert.Throws(() => new QualityIndex(index)); + } + + [Theory(DisplayName = "an AV1 quality index on the edge of what the card quantises between is taken")] + [InlineData(QualityIndex.Finest)] + [InlineData(80)] + [InlineData(QualityIndex.Coarsest)] + public void AnAv1QualityIndexOnTheEdgeIsTaken(int index) + { + Assert.Equal(index, new QualityIndex(index).Index); + } +} diff --git a/tests/Carina.Domain.Tests/Streaming/SoundArrangementTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/SoundArrangementTests.cs similarity index 99% rename from tests/Carina.Domain.Tests/Streaming/SoundArrangementTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/SoundArrangementTests.cs index 0ba8429f8..ba490c49a 100644 --- a/tests/Carina.Domain.Tests/Streaming/SoundArrangementTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/SoundArrangementTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Reservations; using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class SoundArrangementTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/SoundTrackTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/SoundTrackTests.cs similarity index 96% rename from tests/Carina.Domain.Tests/Streaming/SoundTrackTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/SoundTrackTests.cs index 3fcbb5fdf..80c5ff010 100644 --- a/tests/Carina.Domain.Tests/Streaming/SoundTrackTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/SoundTrackTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class SoundTrackTests { [Fact] diff --git a/tests/Carina.Domain.Tests/Streaming/StreamAttributeReadingTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/StreamAttributeReadingTests.cs similarity index 98% rename from tests/Carina.Domain.Tests/Streaming/StreamAttributeReadingTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/StreamAttributeReadingTests.cs index 0c6e84b78..fafc3daf9 100644 --- a/tests/Carina.Domain.Tests/Streaming/StreamAttributeReadingTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/StreamAttributeReadingTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Base; using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class StreamAttributeReadingTests { private static readonly StreamAttributes Measured = new( diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/StreamAttributesTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/StreamAttributesTests.cs new file mode 100644 index 000000000..5d1cb6d4a --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/StreamAttributesTests.cs @@ -0,0 +1,25 @@ +using Carina.Domain.Base; +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class StreamAttributesTests +{ + [Fact] + public void AScanTheStreamNeverSettledIsNotOneOfTheTwoWaysAPictureIsDrawn() + { + Assert.Equal(0, (int)ScanType.Undetermined); + Assert.Equal(0, (int)AudioMode.Undetermined); + } + + [Fact] + public void AnAttributeSetIsRefusedAValueOutsideTheOnesNamed() + { + Assert.Throws( + () => new StreamAttributes(new VideoSize(1, 1), (ScanType)99, FrameRate.Of(30, 1), AudioMode.Stereo)); + + Assert.Throws( + () => new StreamAttributes(new VideoSize(1, 1), ScanType.Progressive, FrameRate.Of(30, 1), (AudioMode)99)); + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/StreamSourceTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/StreamSourceTests.cs new file mode 100644 index 000000000..235e30082 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/StreamSourceTests.cs @@ -0,0 +1,14 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class StreamSourceTests +{ + [Fact] + public void ASourceIsTheValueItWasGiven() + { + Assert.Equal("/srv/recordings/k-1.ts", new StreamSource("/srv/recordings/k-1.ts").Value); + Assert.Equal(new StreamSource("/srv/recordings/k-1.ts"), new StreamSource("/srv/recordings/k-1.ts")); + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeBudgetSettingsTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeBudgetSettingsTests.cs new file mode 100644 index 000000000..7655f7092 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeBudgetSettingsTests.cs @@ -0,0 +1,22 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class TranscodeBudgetSettingsTests +{ + [Fact] + public void TheMachineRunsFourTranscodersAtOnceUnlessItIsToldOtherwise() + { + Assert.Equal(4, new TranscodeBudgetSettings().AtOnce); + } + + [Fact] + public void ACeilingOfNoneIsRefusedBecauseItIsARouteThatNeverPlaysRatherThanABoundedOne() + { + Assert.Throws(() => new TranscodeBudgetSettings { AtOnce = 0 }); + Assert.Throws(() => new TranscodeBudgetSettings { AtOnce = -1 }); + Assert.Equal(1, new TranscodeBudgetSettings { AtOnce = 1 }.AtOnce); + Assert.Equal(TranscodeBudgetSettings.Fewest, new TranscodeBudgetSettings { AtOnce = 1 }.AtOnce); + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeCeilingTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeCeilingTests.cs new file mode 100644 index 000000000..9559294fd --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeCeilingTests.cs @@ -0,0 +1,27 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class TranscodeCeilingTests +{ + [Fact] + public void ACeilingSaysHowManyAreRunningAndHowManyTheMachineIsAskedToRun() + { + TranscodeCeiling ceiling = new(3, 3); + + Assert.Equal(3, ceiling.Running); + Assert.Equal(3, ceiling.AtOnce); + Assert.Contains("3 transcoder", ceiling.Said, StringComparison.Ordinal); + Assert.Contains("live and playback together", ceiling.Said, StringComparison.Ordinal); + } + + [Fact] + public void ACeilingIsOnlyReachedWhenAsManyAreRunningAsTheMachineIsAskedTo() + { + Assert.Throws(() => new TranscodeCeiling(2, 3)); + Assert.Throws(() => new TranscodeCeiling(0, 0)); + Assert.Throws(() => new TranscodeCeiling(1, -1)); + Assert.Equal(4, new TranscodeCeiling(4, 3).Running); + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeClaimTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeClaimTests.cs new file mode 100644 index 000000000..da4d4f8c0 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/TranscodeClaimTests.cs @@ -0,0 +1,51 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class TranscodeClaimTests +{ + [Fact] + public void AClaimThatWasSeatedCarriesTheSeatAndNoRefusal() + { + HeldSeat seat = new(TranscodePurpose.Live, 1, 4); + + TranscodeClaim claim = TranscodeClaim.Seated(seat); + + Assert.True(claim.Taken); + Assert.Same(seat, claim.Seat); + Assert.Null(claim.Refusal); + } + + [Fact] + public void AClaimThatWasRefusedCarriesTheCeilingAndNoSeat() + { + TranscodeCeiling ceiling = new(4, 4); + + TranscodeClaim claim = TranscodeClaim.Refused(ceiling); + + Assert.False(claim.Taken); + Assert.Null(claim.Seat); + Assert.Same(ceiling, claim.Refusal); + } + + [Fact] + public void AClaimIsMadeOfSomethingRatherThanNothing() + { + Assert.Throws(() => TranscodeClaim.Seated(null!)); + Assert.Throws(() => TranscodeClaim.Refused(null!)); + } + + private sealed class HeldSeat(TranscodePurpose purpose, int place, int atOnce) : ITranscodeSeat + { + public TranscodePurpose Purpose { get; } = purpose; + + public int Place { get; } = place; + + public int AtOnce { get; } = atOnce; + + public void Dispose() + { + } + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/TranscodePurposeTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/TranscodePurposeTests.cs new file mode 100644 index 000000000..72941afd4 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/TranscodePurposeTests.cs @@ -0,0 +1,15 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class TranscodePurposeTests +{ + [Fact] + public void ATranscoderIsRaisedForOneOfTheTwoPurposesThereAre() + { + Assert.Equal( + [TranscodePurpose.Live, TranscodePurpose.Playback], + Enum.GetValues().Order().ToArray()); + } +} diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/TranscoderExitTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/TranscoderExitTests.cs new file mode 100644 index 000000000..f5b711322 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/TranscoderExitTests.cs @@ -0,0 +1,44 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class TranscoderExitTests +{ + [Fact] + public void AProgrammeThatExitedZeroRanToTheEnd() + { + TranscoderExit ended = TranscoderExit.Finished(); + + Assert.True(ended.RanToTheEnd); + Assert.Null(ended.Fault); + Assert.Equal(0, ended.ExitCode); + } + + [Fact] + public void AProgrammeThatRefusedSaysWithWhatCodeAndWhatItComplainedOf() + { + TranscoderExit refused = TranscoderExit.Refused(1, "Invalid data found when processing input"); + + Assert.False(refused.RanToTheEnd); + Assert.Equal(TranscoderFault.Refused, refused.Fault); + Assert.Equal(1, refused.ExitCode); + Assert.Contains("Invalid data", refused.Note, StringComparison.Ordinal); + } + + [Fact] + public void AProgrammeThatExitedZeroWasNotRefusedByIt() + { + Assert.Throws(() => TranscoderExit.Refused(0, "fine")); + } + + [Fact] + public void AProgrammeThatWasCalledOffHasNoCodeToReport() + { + TranscoderExit off = TranscoderExit.CalledOff("nothing said"); + + Assert.False(off.RanToTheEnd); + Assert.Equal(TranscoderFault.CalledOff, off.Fault); + Assert.Null(off.ExitCode); + } +} diff --git a/tests/Carina.Domain.Tests/Streaming/TranscoderNoteTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/TranscoderNoteTests.cs similarity index 95% rename from tests/Carina.Domain.Tests/Streaming/TranscoderNoteTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/TranscoderNoteTests.cs index 5094fdc04..220142dd7 100644 --- a/tests/Carina.Domain.Tests/Streaming/TranscoderNoteTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/TranscoderNoteTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class TranscoderNoteTests { [Theory] diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/VaapiRateControlFixtures.cs b/tests/Carina.Domain.Tests/Unit/Streaming/VaapiRateControlFixtures.cs new file mode 100644 index 000000000..8d87a9ede --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/VaapiRateControlFixtures.cs @@ -0,0 +1,10 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +public sealed class VaapiRateControlFixtures +{ + public BitrateCap VaapiRateControl => new(3000); + + public int VaapiKilobitsPerSecond => 3000; +} diff --git a/tests/Carina.Domain.Tests/Streaming/VideoCodecTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/VideoCodecTests.cs similarity index 95% rename from tests/Carina.Domain.Tests/Streaming/VideoCodecTests.cs rename to tests/Carina.Domain.Tests/Unit/Streaming/VideoCodecTests.cs index 5cedb9a5c..a1369f224 100644 --- a/tests/Carina.Domain.Tests/Streaming/VideoCodecTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Streaming/VideoCodecTests.cs @@ -1,7 +1,8 @@ using Carina.Domain.Streaming; -namespace Carina.Domain.Tests.Streaming; +namespace Carina.Domain.Tests.Unit.Streaming; +[Trait("Category", "Unit")] public sealed class VideoCodecTests { [Fact(DisplayName = "a picture transcoded as it plays is encoded in H.264, H.265 or AV1")] diff --git a/tests/Carina.Domain.Tests/Unit/Streaming/VideoSizeTests.cs b/tests/Carina.Domain.Tests/Unit/Streaming/VideoSizeTests.cs new file mode 100644 index 000000000..03cbfc415 --- /dev/null +++ b/tests/Carina.Domain.Tests/Unit/Streaming/VideoSizeTests.cs @@ -0,0 +1,24 @@ +using Carina.Domain.Streaming; + +namespace Carina.Domain.Tests.Unit.Streaming; + +[Trait("Category", "Unit")] +public sealed class VideoSizeTests +{ + [Theory] + [InlineData(0, 1080)] + [InlineData(1440, 0)] + [InlineData(-1440, 1080)] + public void APictureOfNoSizeIsRefused(int width, int height) + { + Assert.Throws(() => new VideoSize(width, height)); + } + + [Fact] + public void TwoPicturesOfTheSameSizeAreTheSameSize() + { + Assert.Equal(new VideoSize(1440, 1080), new VideoSize(1440, 1080)); + Assert.NotEqual(new VideoSize(1440, 1080), new VideoSize(1080, 1440)); + Assert.Equal("1440x1080", new VideoSize(1440, 1080).ToString()); + } +} diff --git a/tests/Carina.Domain.Tests/Viewing/PlaybackPositionTests.cs b/tests/Carina.Domain.Tests/Unit/Viewing/PlaybackPositionTests.cs similarity index 96% rename from tests/Carina.Domain.Tests/Viewing/PlaybackPositionTests.cs rename to tests/Carina.Domain.Tests/Unit/Viewing/PlaybackPositionTests.cs index dab488684..d5ed0da46 100644 --- a/tests/Carina.Domain.Tests/Viewing/PlaybackPositionTests.cs +++ b/tests/Carina.Domain.Tests/Unit/Viewing/PlaybackPositionTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Recordings; using Carina.Domain.Viewing; -namespace Carina.Domain.Tests.Viewing; +namespace Carina.Domain.Tests.Unit.Viewing; +[Trait("Category", "Unit")] public sealed class PlaybackPositionTests { private static readonly DateTime Noon = new(2026, 9, 16, 12, 0, 0, DateTimeKind.Utc); diff --git a/tests/Carina.Infrastructure.Tests/Carina.Infrastructure.Tests.csproj b/tests/Carina.Infrastructure.Tests/Carina.Infrastructure.Tests.csproj index 6c4c7978d..dcff28a8b 100644 --- a/tests/Carina.Infrastructure.Tests/Carina.Infrastructure.Tests.csproj +++ b/tests/Carina.Infrastructure.Tests/Carina.Infrastructure.Tests.csproj @@ -13,7 +13,7 @@ - + diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveDataBroadcastTests.cs b/tests/Carina.Infrastructure.Tests/DataBroadcast/LiveDataBroadcastTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveDataBroadcastTests.cs rename to tests/Carina.Infrastructure.Tests/DataBroadcast/LiveDataBroadcastTests.cs index 835aa91b5..acd76f2d1 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveDataBroadcastTests.cs +++ b/tests/Carina.Infrastructure.Tests/DataBroadcast/LiveDataBroadcastTests.cs @@ -5,12 +5,11 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.DataBroadcast; using Carina.Infrastructure.Streaming; -using Carina.Infrastructure.Tests.DataBroadcast; using Carina.TestSupport; using Microsoft.Extensions.Logging; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.DataBroadcast; /// /// The data broadcast of a live channel as the sessions of the channel carry it: read once from the one diff --git a/tests/Carina.Infrastructure.Tests/Captions/CaptionWorklistTests.cs b/tests/Carina.Infrastructure.Tests/DbIntegration/Domain/Captions/CaptionWorklistTests.cs similarity index 86% rename from tests/Carina.Infrastructure.Tests/Captions/CaptionWorklistTests.cs rename to tests/Carina.Infrastructure.Tests/DbIntegration/Domain/Captions/CaptionWorklistTests.cs index f15070442..05ad4fee6 100644 --- a/tests/Carina.Infrastructure.Tests/Captions/CaptionWorklistTests.cs +++ b/tests/Carina.Infrastructure.Tests/DbIntegration/Domain/Captions/CaptionWorklistTests.cs @@ -4,11 +4,12 @@ using Carina.Domain.Programmes; using Carina.Domain.Recordings; using Carina.Domain.Reservations; -using Carina.Infrastructure.Captions; using Carina.Infrastructure.Persistence; using Carina.Infrastructure.Tests.Integrity; -namespace Carina.Infrastructure.Tests.Captions; +using Microsoft.Extensions.DependencyInjection; + +namespace Carina.Infrastructure.Tests.DbIntegration.Domain.Captions; [Collection(RepositoryDatabaseCollection.Name)] [Trait("Category", "DbIntegration")] @@ -134,9 +135,8 @@ public async Task ARootThisProcessCannotReachIsNotReadAtAllAndIsCountedInstead() Assert.Empty(await AwaitingAsync(alone)); Assert.Single(await AwaitingAsync(unreached)); - await using CarinaDbContext context = database.Open(); - int outOfReach = await new CaptionWorklist(context, Clock()).WaitingOutOfReachAsync([alone], Cancel); - int withinReach = await new CaptionWorklist(context, Clock()).WaitingOutOfReachAsync([alone, unreached], Cancel); + int outOfReach = await WorklistAsync(Clock(), worklist => worklist.WaitingOutOfReachAsync([alone], Cancel)); + int withinReach = await WorklistAsync(Clock(), worklist => worklist.WaitingOutOfReachAsync([alone, unreached], Cancel)); Assert.Equal(1, outOfReach - withinReach); } @@ -167,8 +167,7 @@ public async Task TheRecordingsWhoseCaptionsAreReadyAreNamedAndNoOthers() await CaptionAsync(ready.Id, CaptionState.Ready, 2, Now.AddHours(2)); await CaptionAsync(absent.Id, CaptionState.Absent, null, Now.AddHours(2)); - await using CarinaDbContext context = database.Open(); - IReadOnlyList named = await new CaptionWorklist(context, Clock()).ReadyAsync(Cancel); + IReadOnlyList named = await WorklistAsync(Clock(), worklist => worklist.ReadyAsync(Cancel)); Assert.Contains(ready.Id, named); Assert.DoesNotContain(absent.Id, named); @@ -195,24 +194,23 @@ public async Task BrPd016TheRecordingsToTakeAgainAreTheReadyOnesAmongThoseAskedF await CaptionAsync(notAsked.Id, CaptionState.Ready, 2, Now.AddHours(6)); await CaptionAsync(outOfReach.Id, CaptionState.Ready, 2, Now.AddHours(6)); - await using CarinaDbContext context = database.Open(); - CaptionWorklist worklist = new(context, Clock(Now.AddHours(7))); RecordingId[] asked = [older.Id, newer.Id, absent.Id, outOfReach.Id]; - IReadOnlyList all = await worklist.ReadyAmongAsync(asked, [alone], 64, Cancel); - IReadOnlyList one = await worklist.ReadyAmongAsync(asked, [alone], 1, Cancel); + (IReadOnlyList all, IReadOnlyList one, IReadOnlyList none) = + await WorklistAsync(Clock(Now.AddHours(7)), async worklist => ( + await worklist.ReadyAmongAsync(asked, [alone], 64, Cancel), + await worklist.ReadyAmongAsync(asked, [alone], 1, Cancel), + await worklist.ReadyAmongAsync([], [alone], 64, Cancel))); Assert.Equal([newer.Id, older.Id], all.Select(subject => subject.Id)); Assert.Equal([newer.Id], one.Select(subject => subject.Id)); - Assert.Empty(await worklist.ReadyAmongAsync([], [alone], 64, Cancel)); + Assert.Empty(none); } [Fact] public async Task KeepingCaptionsForARecordingNobodyHasHeardOfSaysSoAndWritesNothing() { - await using CarinaDbContext context = database.Open(); - - Assert.False(await new CaptionWorklist(context, Clock()).CaptionAsync(RecordingId.New(), CaptionState.Absent, null, Cancel)); + Assert.False(await WorklistAsync(Clock(), worklist => worklist.CaptionAsync(RecordingId.New(), CaptionState.Absent, null, Cancel))); } [Fact] @@ -225,18 +223,18 @@ public async Task AskingForNoneAtAllIsRefused() private static StoppedClock Clock(DateTime? at = null) => new(at ?? Now.AddHours(2)); - private async Task> AwaitingAsync(OutputRoot within, int atMost = 64) - { - await using CarinaDbContext context = database.Open(); - - return await new CaptionWorklist(context, Clock()).AwaitingAsync([within], atMost, Cancel); - } + private Task> AwaitingAsync(OutputRoot within, int atMost = 64) + => WorklistAsync(Clock(), worklist => worklist.AwaitingAsync([within], atMost, Cancel)); private async Task CaptionAsync(RecordingId id, CaptionState state, int? pictures, DateTime at) + => Assert.True(await WorklistAsync(Clock(at), worklist => worklist.CaptionAsync(id, state, pictures, Cancel))); + + private async Task WorklistAsync(StoppedClock clock, Func> asked) { - await using CarinaDbContext context = database.Open(); + await using ServiceProvider container = database.Infrastructure(replace => replace.AddSingleton(clock)); + await using AsyncServiceScope scope = container.CreateAsyncScope(); - Assert.True(await new CaptionWorklist(context, Clock(at)).CaptionAsync(id, state, pictures, Cancel)); + return await asked(scope.ServiceProvider.GetRequiredService()); } private async Task ReadAsync(RecordingId id) diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes.cs b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes.cs similarity index 88% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes.cs rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes.cs index 06234768b..efd22363c 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/Probes.cs +++ b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes.cs @@ -1,6 +1,6 @@ using System.Reflection; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Fixtures.Streaming; public static class Probes { @@ -17,7 +17,7 @@ public static string Recorded(string name) { using Stream? held = Assembly .GetExecutingAssembly() - .GetManifestResourceStream($"Carina.Infrastructure.Tests.Streaming.Probes.{name}.txt"); + .GetManifestResourceStream($"Carina.Infrastructure.Tests.Fixtures.Streaming.Probes.{name}.txt"); Assert.NotNull(held); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes/audio-mono.txt b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/audio-mono.txt similarity index 100% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes/audio-mono.txt rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/audio-mono.txt diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes/audio-surround.txt b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/audio-surround.txt similarity index 100% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes/audio-surround.txt rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/audio-surround.txt diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes/audio-undetermined-layout.txt b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/audio-undetermined-layout.txt similarity index 100% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes/audio-undetermined-layout.txt rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/audio-undetermined-layout.txt diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes/broadcast-hd.txt b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/broadcast-hd.txt similarity index 100% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes/broadcast-hd.txt rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/broadcast-hd.txt diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes/broadcast-sd.txt b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/broadcast-sd.txt similarity index 100% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes/broadcast-sd.txt rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/broadcast-sd.txt diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes/multiplex.txt b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/multiplex.txt similarity index 100% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes/multiplex.txt rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/multiplex.txt diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes/progressive.txt b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/progressive.txt similarity index 100% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes/progressive.txt rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/progressive.txt diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Probes/refused.txt b/tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/refused.txt similarity index 100% rename from tests/Carina.Infrastructure.Tests/Streaming/Probes/refused.txt rename to tests/Carina.Infrastructure.Tests/Fixtures/Streaming/Probes/refused.txt diff --git a/tests/Carina.Infrastructure.Tests/Machines/FfprobeRecordsTests.cs b/tests/Carina.Infrastructure.Tests/Machines/FfprobeRecordsTests.cs index 2778e5017..d01674c61 100644 --- a/tests/Carina.Infrastructure.Tests/Machines/FfprobeRecordsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Machines/FfprobeRecordsTests.cs @@ -1,6 +1,6 @@ using Carina.Infrastructure.Machines; using Carina.Infrastructure.Streaming; -using Carina.Infrastructure.Tests.Streaming; +using Carina.Infrastructure.Tests.Fixtures.Streaming; namespace Carina.Infrastructure.Tests.Machines; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/RecordedMaterialTests.cs b/tests/Carina.Infrastructure.Tests/RecordedMaterialTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/RecordedMaterialTests.cs rename to tests/Carina.Infrastructure.Tests/RecordedMaterialTests.cs index 159abe426..ec450dbbb 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/RecordedMaterialTests.cs +++ b/tests/Carina.Infrastructure.Tests/RecordedMaterialTests.cs @@ -2,7 +2,7 @@ using Carina.Domain.Reservations; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests; public sealed class RecordedMaterialTests : IDisposable { diff --git a/tests/Carina.Infrastructure.Tests/Streaming/CaptionFontTests.cs b/tests/Carina.Infrastructure.Tests/Streaming/CaptionFontTests.cs deleted file mode 100644 index a4a71b5ba..000000000 --- a/tests/Carina.Infrastructure.Tests/Streaming/CaptionFontTests.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Carina.Infrastructure.Streaming; - -namespace Carina.Infrastructure.Tests.Streaming; - -public sealed class CaptionFontTests -{ - [Fact] - public void TheCaptionsAreDrawnWithDenpaFontAndWhatItLacksFallsToNoto() - { - Assert.Equal(["Denpa Font", "Noto Sans CJK JP"], FfmpegLiveInvocation.Font.Split(',')); - } -} diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveHandoverTests.cs b/tests/Carina.Infrastructure.Tests/Streaming/LiveHandoverTests.cs deleted file mode 100644 index e6d703743..000000000 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveHandoverTests.cs +++ /dev/null @@ -1,334 +0,0 @@ -using Carina.Domain.Channels; -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -using Microsoft.Extensions.Logging.Abstractions; - -namespace Carina.Infrastructure.Tests.Streaming; - -public sealed class LiveHandoverTests -{ - private const int MouthfulsThatOverfillTheReader = 128; - - private const int RoundsOfArrivingWhileLeaving = 2_000; - - private static readonly LiveChannelKey Watched = new(new NetworkId(32736), new ServiceId(1024)); - - private static readonly LiveSessionKey EveryFrame = - new(new NetworkId(32736), new ServiceId(1024), LiveProfile.Hd30); - - private static readonly TimeSpan SoonerThanASeatIsCutLooseFor = TimeSpan.FromSeconds(5); - - private static readonly LiveSessionSettings Settings = new(); - - private readonly HandTurnedClock clock = new(); - - private readonly PipedSupply supply = new(); - - private readonly TranscodeBudget budget = new(new TranscodeBudgetSettings { AtOnce = 4 }); - - private readonly HeldTranscoders transcoders; - - private readonly SilentEvents events = new(); - - private readonly LiveSessionManager manager; - - public LiveHandoverTests() - { - transcoders = new HeldTranscoders(budget); - manager = new LiveSessionManager( - Settings, - new LiveFanoutSettings(), - new LiveTranscodeSettings(), - supply, - transcoders, - clock, - events, - NullLogger.Instance); - } - - [Fact] - public async Task TheChannelIsHandedOverAsItIsAndNoTranscoderIsRaised() - { - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(handed.Handed); - - await using ILiveHandedOver carrying = handed.Handed!; - - byte[] sent = Mouthful(); - - await supply.Opened[0].WriteAsync(sent); - - Assert.Equal(sent, await ReadAsync(carrying.Bytes, sent.Length)); - Assert.Equal(0, transcoders.Started); - Assert.Equal(0, budget.Running); - } - - [Fact] - public async Task AReaderRidesTheReadingAViewerRaisedAndNoSecondTunerIsAskedFor() - { - LiveJoin joined = await manager.JoinAsync(EveryFrame, CancellationToken.None); - - Assert.True(joined.Seated, "a viewer is seated on the channel"); - - await using ILiveViewing viewing = joined.Viewing!; - - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(handed.Handed); - - await using ILiveHandedOver carrying = handed.Handed!; - - Assert.Equal(1, supply.Asked); - Assert.Single(supply.Opened); - Assert.Equal(1, transcoders.Started); - Assert.Equal(1, budget.Running); - } - - [Fact] - public async Task TheReadingIsLetGoOnceTheReaderHasStoppedAndNobodyElseIsBehindIt() - { - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(handed.Handed); - - await handed.Handed!.DisposeAsync(); - await Eventually.Happens(() => supply.Opened[0].Disposed, "the reading is let go"); - } - - [Fact] - public async Task AChannelNoTunerWillReachIsRefusedAndNothingIsHandedOver() - { - supply.Refusing = LiveRefusal.NoTunerFree; - - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.Null(handed.Handed); - Assert.Equal(LiveRefusal.NoTunerFree, handed.Refusal); - } - - [Fact] - public async Task ASeatThatRefusesAMouthfulInAWayNobodyNamedIsDroppedAndTheOthersGoOnBeingFed() - { - LiveJoin joined = await manager.JoinAsync(EveryFrame, CancellationToken.None); - - Assert.True(joined.Seated, "a viewer is seated on the channel"); - - await using ILiveViewing viewing = joined.Viewing!; - - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(handed.Handed); - - await using ILiveHandedOver carrying = handed.Handed!; - - transcoders.Raised[0].FailingToTake = - new InvalidOperationException("writing to a writer that has already been completed."); - - byte[] sent = Mouthful(); - - await supply.Opened[0].WriteAsync(sent); - - Assert.Equal(sent, await ReadAsync(carrying.Bytes, sent.Length)); - - await manager.DisposeAsync(); - } - - [Fact] - public async Task AReaderThatHasLetGoIsNotOfferedAnotherMouthfulAndTheReadingCarriesOn() - { - LiveJoin joined = await manager.JoinAsync(EveryFrame, CancellationToken.None); - - Assert.True(joined.Seated, "a viewer is seated on the channel"); - - await using ILiveViewing viewing = joined.Viewing!; - - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(handed.Handed); - - ILiveHandedOver carrying = handed.Handed!; - - await carrying.DisposeAsync(); - - byte[] sent = Mouthful(); - - await supply.Opened[0].WriteAsync(sent); - await Eventually.Happens( - () => transcoders.Raised[0].TakenIn >= sent.Length, - "the transcoding seat is fed after the reader has let go"); - - Assert.Equal(0, carrying.ChunksDroppedSinceTheSupplyOpened); - - await manager.DisposeAsync(); - } - - [Fact] - public async Task AReaderThatNeverReadsDropsWhatItCannotHoldAndNeverHoldsUpTheTranscodingSeat() - { - LiveJoin joined = await manager.JoinAsync(EveryFrame, CancellationToken.None); - - Assert.True(joined.Seated, "a viewer is seated on the channel"); - - await using ILiveViewing viewing = joined.Viewing!; - - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(handed.Handed); - - await using ILiveHandedOver carrying = handed.Handed!; - - byte[] sent = new byte[64 * 1024]; - long poured = (long)sent.Length * MouthfulsThatOverfillTheReader; - Task pouring = Task.Run(async () => - { - for (int at = 0; at < MouthfulsThatOverfillTheReader; at++) - { - await supply.Opened[0].WriteAsync(sent); - } - }); - - await Sooner( - () => transcoders.Raised[0].TakenIn >= poured, - "the transcoding seat is fed everything while the reader takes nothing"); - await pouring.WaitAsync(Eventually.Patience); - - Assert.True( - carrying.ChunksDroppedSinceTheSupplyOpened > 0, - "a reader that takes nothing has what it cannot hold dropped and counted"); - Assert.NotEmpty(await ReadAsync(carrying.Bytes, sent.Length)); - - await manager.DisposeAsync(); - } - - [Fact] - public async Task NothingIsSaidToHaveReachedTheReaderUntilTheFirstMouthfulHas() - { - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(handed.Handed); - - await using ILiveHandedOver carrying = handed.Handed!; - - Task reaching = carrying.ReachedAsync(CancellationToken.None).AsTask(); - - Assert.False(reaching.IsCompleted, "nothing has come from the channel yet"); - - await supply.Opened[0].WriteAsync(Mouthful()); - - Assert.True(await reaching.WaitAsync(Eventually.Patience)); - } - - [Fact] - public async Task AChannelThatSaysNothingWithinTheLongestRaiseNeverReachesTheReader() - { - LiveHandover handed = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(handed.Handed); - - await using ILiveHandedOver carrying = handed.Handed!; - - Task reaching = carrying.ReachedAsync(CancellationToken.None).AsTask(); - - clock.Turn(Settings.LongestRaise); - - Assert.False(await reaching.WaitAsync(Eventually.Patience)); - } - - [Fact] - public async Task AReaderIsNeverSeatedOnAReadingWhoseCarryingHasAlreadyEnded() - { - LiveHandover first = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.NotNull(first.Handed); - - supply.Opened[0].NoMore(); - - await Eventually.Happens( - () => supply.Opened[0].Disposed, - "the reading lets the supply go once its carrying has ended"); - - LiveHandover second = await manager.HandOverAsync(Watched, CancellationToken.None); - - Assert.Equal(2, supply.Asked); - - await first.Handed!.DisposeAsync(); - - if (second.Handed is { } more) - { - await more.DisposeAsync(); - } - } - - [Fact(DisplayName = "a reader handed the channel while the last reader before it is leaving is never left on a reading that is being let go")] - public async Task AReaderArrivingAsTheLastOneLeavesIsNeverLeftOnAReadingBeingLetGo() - { - for (int round = 0; round < RoundsOfArrivingWhileLeaving; round++) - { - LiveHandover first = await manager.HandOverAsync(Watched, CancellationToken.None); - int spins = round % 64; - - Task leaving = Task.Run(async () => await first.Handed!.DisposeAsync()); - Task arriving = Task.Run(() => - { - Thread.SpinWait(spins * 16); - - return manager.HandOverAsync(Watched, CancellationToken.None); - }); - - await leaving; - - await using ILiveHandedOver arrived = (await arriving).Handed!; - - int askedByNow = supply.Asked; - - await using ILiveHandedOver next = (await manager.HandOverAsync(Watched, CancellationToken.None)).Handed!; - - Assert.Equal(askedByNow, supply.Asked); - } - } - - private static byte[] Mouthful() => [.. Enumerable.Range(0, 4_000).Select(at => (byte)(at % 251))]; - - private static async Task Sooner(Func condition, string what) - { - long start = Environment.TickCount64; - - while (Environment.TickCount64 - start < SoonerThanASeatIsCutLooseFor.TotalMilliseconds) - { - if (condition()) - { - return; - } - - await Task.Delay(TimeSpan.FromMilliseconds(10)); - } - - throw new TimeoutException($"Did not happen within {SoonerThanASeatIsCutLooseFor.TotalSeconds}s: {what}."); - } - - private static async Task ReadAsync(Stream reading, int many) - { - byte[] heard = new byte[many]; - int filled = 0; - - while (filled < many) - { - int read = await reading - .ReadAsync(heard.AsMemory(filled), CancellationToken.None) - .AsTask() - .WaitAsync(Eventually.Patience); - - if (read is 0) - { - break; - } - - filled += read; - } - - return [.. heard.Take(filled)]; - } -} diff --git a/tests/Carina.Infrastructure.Tests/Streaming/SlowViewerTests.cs b/tests/Carina.Infrastructure.Tests/Streaming/SlowViewerTests.cs deleted file mode 100644 index 15e3188af..000000000 --- a/tests/Carina.Infrastructure.Tests/Streaming/SlowViewerTests.cs +++ /dev/null @@ -1,96 +0,0 @@ -using Carina.Domain.Streaming; -using Carina.Infrastructure.Streaming; -using Carina.TestSupport; - -namespace Carina.Infrastructure.Tests.Streaming; - -public sealed class SlowViewerTests -{ - private const int Published = 40; - - private static readonly byte[] Payload = [0x0a, 0x0b, 0x0c]; - - [Fact] - public async Task AViewerThatStopsReadingKeepsOnlyItsBacklogAndLosesTheRestUntilItIsCutOff() - { - LiveFanout fanout = new(new LiveFanoutSettings { LongestBacklog = 3 }); - await using ILiveViewing draining = await Joined(fanout); - await using ILiveViewing stalled = await Joined(fanout); - - for (ulong pts = 0; pts < Published; pts++) - { - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(pts), Payload)); - } - - fanout.End(); - - using CancellationTokenSource cut = new(); - Task stalling = SlowViewer.StallingAfter(2).WatchAsync(stalled, cut.Token); - SlowViewing read = await SlowViewer.ReadingOneEvery(TimeSpan.Zero).WatchAsync(draining, CancellationToken.None); - - Assert.False(stalling.IsCompleted); - - await cut.CancelAsync(); - - SlowViewing stuck = await stalling; - - Assert.Equal(3, read.Received); - Assert.Equal(new LiveBacklog(0, Published - 3), read.Backlog); - Assert.Equal(2, stuck.Received); - Assert.Equal(new LiveBacklog(1, Published - 3), stuck.Backlog); - } - - [Fact] - public async Task AViewerThatPausesBetweenFramesDropsSomeAndEverythingPublishedIsEitherReceivedOrDropped() - { - LiveFanout fanout = new(new LiveFanoutSettings { LongestBacklog = 3 }); - await using ILiveViewing slow = await Joined(fanout); - - Task watching = SlowViewer - .ReadingOneEvery(TimeSpan.FromMilliseconds(20)) - .WatchAsync(slow, CancellationToken.None); - - for (ulong pts = 0; pts < Published; pts++) - { - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(pts), Payload)); - } - - fanout.End(); - - SlowViewing watched = await watching; - - Assert.InRange(watched.Backlog.Dropped, 1L, Published - 3); - Assert.Equal(Published, watched.Received + watched.Backlog.Dropped); - Assert.Equal(0, watched.Backlog.Queued); - } - - [Fact] - public async Task AViewerThatIsCutOffReportsWhatItReceivedUntilThen() - { - LiveFanout fanout = new(new LiveFanoutSettings { LongestBacklog = 3 }); - await using ILiveViewing viewing = await Joined(fanout); - using CancellationTokenSource cut = new(); - - fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Start, Payload)); - - Task watching = SlowViewer.ReadingOneEvery(TimeSpan.Zero).WatchAsync(viewing, cut.Token); - - await Task.Delay(TimeSpan.FromMilliseconds(50)); - await cut.CancelAsync(); - - Assert.Equal(1, (await watching).Received); - } - - [Fact] - public void TheMeasuredPaceIsTheOneTheFanoutWasProvedAgainst() - => Assert.Equal(TimeSpan.FromMilliseconds(400), SlowViewer.MeasuredPace); - - private static async Task Joined(LiveFanout fanout) - { - ILiveViewing? viewing = await fanout.JoinAsync(CancellationToken.None); - - Assert.NotNull(viewing); - - return viewing; - } -} diff --git a/tests/Carina.Infrastructure.Tests/Streaming/SyntheticBroadcastMaterialTests.cs b/tests/Carina.Infrastructure.Tests/SyntheticBroadcastMaterialTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/SyntheticBroadcastMaterialTests.cs rename to tests/Carina.Infrastructure.Tests/SyntheticBroadcastMaterialTests.cs index f2247aeb2..c1ae5c84d 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/SyntheticBroadcastMaterialTests.cs +++ b/tests/Carina.Infrastructure.Tests/SyntheticBroadcastMaterialTests.cs @@ -15,7 +15,7 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests; [SupportedOSPlatform("linux")] [Trait("Category", "Material")] diff --git a/tests/Carina.Infrastructure.Tests/Captions/CaptionJobTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionJobTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Captions/CaptionJobTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionJobTests.cs index 922f7fe05..6d36d9385 100644 --- a/tests/Carina.Infrastructure.Tests/Captions/CaptionJobTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionJobTests.cs @@ -11,8 +11,9 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; -namespace Carina.Infrastructure.Tests.Captions; +namespace Carina.Infrastructure.Tests.Unit.Infra.Captions; +[Trait("Category", "Unit")] public sealed class CaptionJobTests : IDisposable { private static readonly CancellationToken Cancel = CancellationToken.None; diff --git a/tests/Carina.Infrastructure.Tests/Captions/CaptionRecordFormatTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionRecordFormatTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Captions/CaptionRecordFormatTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionRecordFormatTests.cs index 0c2bde53a..a9956fd2b 100644 --- a/tests/Carina.Infrastructure.Tests/Captions/CaptionRecordFormatTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionRecordFormatTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Captions; using Carina.Infrastructure.Captions; -namespace Carina.Infrastructure.Tests.Captions; +namespace Carina.Infrastructure.Tests.Unit.Infra.Captions; +[Trait("Category", "Unit")] public sealed class CaptionRecordFormatTests { private static readonly CaptionPlacement Lower = new(120, 900, 640, 72, new byte[] { 0x89, 0x50, 0x4e, 0x47, 1, 2, 3 }); diff --git a/tests/Carina.Infrastructure.Tests/Captions/CaptionShelfTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionShelfTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Captions/CaptionShelfTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionShelfTests.cs index 7f07afd06..75b079ebd 100644 --- a/tests/Carina.Infrastructure.Tests/Captions/CaptionShelfTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Captions/CaptionShelfTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Recordings; using Carina.Infrastructure.Captions; -namespace Carina.Infrastructure.Tests.Captions; +namespace Carina.Infrastructure.Tests.Unit.Infra.Captions; +[Trait("Category", "Unit")] public sealed class CaptionShelfTests : IDisposable { private static readonly CancellationToken Cancel = CancellationToken.None; diff --git a/tests/Carina.Infrastructure.Tests/Playback/HevcTagMaterialTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/FfprobeArtefactCodecsMaterialTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Playback/HevcTagMaterialTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/FfprobeArtefactCodecsMaterialTests.cs index c12e3a83c..6709523fe 100644 --- a/tests/Carina.Infrastructure.Tests/Playback/HevcTagMaterialTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/FfprobeArtefactCodecsMaterialTests.cs @@ -12,7 +12,7 @@ using Microsoft.Extensions.Logging.Abstractions; -namespace Carina.Infrastructure.Tests.Playback; +namespace Carina.Infrastructure.Tests.Unit.Infra.Playback; /// /// Writes a synthetic H.265 picture into an mp4 with the ffmpeg the application runs, the way an encode @@ -22,7 +22,7 @@ namespace Carina.Infrastructure.Tests.Playback; /// [SupportedOSPlatform("linux")] [Trait("Category", "Material")] -public sealed class HevcTagMaterialTests : IDisposable +public sealed class FfprobeArtefactCodecsMaterialTests : IDisposable { /// /// Two black 64x64 frames in H.265 as a raw stream, made once with x265. The ffmpeg the application diff --git a/tests/Carina.Infrastructure.Tests/Playback/FfprobeArtefactCodecsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/FfprobeArtefactCodecsTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Playback/FfprobeArtefactCodecsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/FfprobeArtefactCodecsTests.cs index 6d8b01264..564c20190 100644 --- a/tests/Carina.Infrastructure.Tests/Playback/FfprobeArtefactCodecsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/FfprobeArtefactCodecsTests.cs @@ -10,8 +10,9 @@ using Microsoft.Extensions.Logging.Abstractions; -namespace Carina.Infrastructure.Tests.Playback; +namespace Carina.Infrastructure.Tests.Unit.Infra.Playback; +[Trait("Category", "Unit")] [SupportedOSPlatform("linux")] public sealed class FfprobeArtefactCodecsTests : IDisposable { diff --git a/tests/Carina.Infrastructure.Tests/Playback/LocalPlaybackFileStoreTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/LocalPlaybackFileStoreTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Playback/LocalPlaybackFileStoreTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/LocalPlaybackFileStoreTests.cs index 2fbb2469f..9ffe36489 100644 --- a/tests/Carina.Infrastructure.Tests/Playback/LocalPlaybackFileStoreTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Playback/LocalPlaybackFileStoreTests.cs @@ -11,8 +11,9 @@ using Microsoft.Extensions.Logging.Abstractions; -namespace Carina.Infrastructure.Tests.Playback; +namespace Carina.Infrastructure.Tests.Unit.Infra.Playback; +[Trait("Category", "Unit")] public sealed class LocalPlaybackFileStoreTests : IDisposable { private static readonly OutputRoot Root = new("bulk"); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/CaptionCanvasTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionCanvasTests.cs similarity index 96% rename from tests/Carina.Infrastructure.Tests/Streaming/CaptionCanvasTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionCanvasTests.cs index 041e93aa1..3acbb3a01 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/CaptionCanvasTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionCanvasTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class CaptionCanvasTests { private static readonly CaptionCanvas Small = new(new VideoSize(8, 4)); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/CaptionFramesTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionFramesTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/CaptionFramesTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionFramesTests.cs index 10956204b..b6bb3c2e1 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/CaptionFramesTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionFramesTests.cs @@ -4,8 +4,9 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class CaptionFramesTests { private static readonly VideoSize FourByTwo = new(4, 2); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/CaptionTextsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionTextsTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/CaptionTextsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionTextsTests.cs index 04193ae19..02c925c19 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/CaptionTextsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/CaptionTextsTests.cs @@ -3,8 +3,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class CaptionTextsTests { private const long Lift = 9_000_000_000; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/DriverLiveSupplyTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/DriverLiveSupplyTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/DriverLiveSupplyTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/DriverLiveSupplyTests.cs index cf640df35..e65f94dc1 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/DriverLiveSupplyTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/DriverLiveSupplyTests.cs @@ -10,8 +10,9 @@ using Puppis.Contracts; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class DriverLiveSupplyTests { private static readonly NetworkId Network = new(32736); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfmpegCaptionInvocationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionInvocationTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/FfmpegCaptionInvocationTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionInvocationTests.cs index f22865f59..24a7f3764 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfmpegCaptionInvocationTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionInvocationTests.cs @@ -3,8 +3,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class FfmpegCaptionInvocationTests { private static readonly ServiceId Service = new(1040); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/CaptionTranscriptionMaterialTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionTranscriberMaterialTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/CaptionTranscriptionMaterialTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionTranscriberMaterialTests.cs index 459066fc0..4857d8eab 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/CaptionTranscriptionMaterialTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionTranscriberMaterialTests.cs @@ -14,7 +14,7 @@ using Xunit.Abstractions; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; /// /// Takes the captions out of synthetic broadcasts with the ffmpeg the application runs: the moment each @@ -23,7 +23,7 @@ namespace Carina.Infrastructure.Tests.Streaming; /// [SupportedOSPlatform("linux")] [Trait("Category", "Material")] -public sealed class CaptionTranscriptionMaterialTests(ITestOutputHelper output) : IDisposable +public sealed class FfmpegCaptionTranscriberMaterialTests(ITestOutputHelper output) : IDisposable { private const long ComesAround = 1L << 33; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfmpegCaptionTranscriberTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionTranscriberTests.cs similarity index 93% rename from tests/Carina.Infrastructure.Tests/Streaming/FfmpegCaptionTranscriberTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionTranscriberTests.cs index a24a29261..64ab6e9ee 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfmpegCaptionTranscriberTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegCaptionTranscriberTests.cs @@ -4,8 +4,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class FfmpegCaptionTranscriberTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/CaptionFontMaterialTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegLiveInvocationMaterialTests.cs similarity index 94% rename from tests/Carina.Infrastructure.Tests/Streaming/CaptionFontMaterialTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegLiveInvocationMaterialTests.cs index 163235cfc..3f19d8b12 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/CaptionFontMaterialTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegLiveInvocationMaterialTests.cs @@ -1,6 +1,6 @@ using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; /// /// Reads the face the image installs for the captions. The decoder scales a glyph's em to the cell a @@ -9,7 +9,7 @@ namespace Carina.Infrastructure.Tests.Streaming; /// captions are drawn with the face itself rather than falling through to the one behind it. /// [Trait("Category", "Material")] -public sealed class CaptionFontMaterialTests +public sealed class FfmpegLiveInvocationMaterialTests { public const string Installed = "/usr/local/share/fonts/denpa-font/denpa-font.ttf"; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfmpegLiveInvocationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegLiveInvocationTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/FfmpegLiveInvocationTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegLiveInvocationTests.cs index ef631d497..6c39a765f 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfmpegLiveInvocationTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegLiveInvocationTests.cs @@ -7,14 +7,15 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class FfmpegLiveInvocationTests { - private static readonly ServiceId Service = new(1040); - private const string RenderNode = "/dev/dri/renderD129"; + private static readonly ServiceId Service = new(1040); + private static readonly MachineSettings Machine = new() { RenderNode = RenderNode }; private static readonly ServiceId AnotherService = new(1048); @@ -48,6 +49,36 @@ public static TheoryData EveryProfileOnEveryEncoder } } + public static TheoryData EveryProfile => [.. LiveProfile.All]; + + public static TheoryData EveryProfileInEveryFormatOnTheCard + { + get + { + TheoryData pairs = []; + + foreach (LiveProfile profile in LiveProfile.All) + { + foreach (VideoCodec format in VideoCodecs.InOrder) + { + pairs.Add(profile, format); + } + } + + return pairs; + } + } + + public static TheoryData EveryKindOfPicture + => + [ + Interlaced, + Progressive, + StreamAttributes.SafeSide, + new StreamAttributes(new VideoSize(720, 480), ScanType.Interlaced, FrameRate.BroadcastFrames, AudioMode.DualMono), + new StreamAttributes(new VideoSize(1920, 1080), ScanType.Undetermined, FrameRate.BroadcastFrames, AudioMode.Surround), + ]; + [Fact] public void TheSoftwareArgumentsAreExactlyThese() { @@ -336,36 +367,6 @@ public void AFormatNobodyNamedIsRefused() () => FfmpegLiveInvocation.Arguments(Service, LiveProfile.Hd30, Interlaced, LiveEncoder.Vaapi, Machine, CaptionOutlet.None, format: (VideoCodec)9)); } - public static TheoryData EveryProfile => [.. LiveProfile.All]; - - public static TheoryData EveryProfileInEveryFormatOnTheCard - { - get - { - TheoryData pairs = []; - - foreach (LiveProfile profile in LiveProfile.All) - { - foreach (VideoCodec format in VideoCodecs.InOrder) - { - pairs.Add(profile, format); - } - } - - return pairs; - } - } - - public static TheoryData EveryKindOfPicture - => - [ - Interlaced, - Progressive, - StreamAttributes.SafeSide, - new StreamAttributes(new VideoSize(720, 480), ScanType.Interlaced, FrameRate.BroadcastFrames, AudioMode.DualMono), - new StreamAttributes(new VideoSize(1920, 1080), ScanType.Undetermined, FrameRate.BroadcastFrames, AudioMode.Surround), - ]; - [Theory] [MemberData(nameof(EveryProfileOnEveryEncoder))] public void TheInputIsReadForAQuarterOfASecondOfTheBroadcastAndNoMoreThanHalfAMegabyteBeforeAnythingIsDecoded( @@ -1138,6 +1139,12 @@ public void TheCheckOnTheWayInReadsConstructorsAndNotStaticFactories() Assert.Null(FrameRate.Read("thirty")); } + [Fact] + public void TheCaptionsAreDrawnWithDenpaFontAndWhatItLacksFallsToNoto() + { + Assert.Equal(["Denpa Font", "Noto Sans CJK JP"], FfmpegLiveInvocation.Font.Split(',')); + } + private static IReadOnlyList TextTakenBy(Type builder) { List taking = []; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfmpegPlaybackInvocationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegPlaybackInvocationTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/FfmpegPlaybackInvocationTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegPlaybackInvocationTests.cs index 869cd1de2..a0d527e88 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfmpegPlaybackInvocationTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfmpegPlaybackInvocationTests.cs @@ -4,8 +4,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class FfmpegPlaybackInvocationTests { private static readonly StreamAttributes Interlaced = new( diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeAttributesTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeAttributesTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/FfprobeAttributesTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeAttributesTests.cs index fb7b66648..93a141c15 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeAttributesTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeAttributesTests.cs @@ -1,9 +1,11 @@ using Carina.Domain.Base; using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; +using Carina.Infrastructure.Tests.Fixtures.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class FfprobeAttributesTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeFileStartTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeFileStartTests.cs similarity index 93% rename from tests/Carina.Infrastructure.Tests/Streaming/FfprobeFileStartTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeFileStartTests.cs index 1829b8598..ae15d1b92 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeFileStartTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeFileStartTests.cs @@ -2,8 +2,9 @@ using Carina.Infrastructure.Machines; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class FfprobeFileStartTests { [Fact(DisplayName = "where the file's clock begins is read by its key, hours into the day or before zero")] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeInvocationTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeInvocationTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/FfprobeInvocationTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeInvocationTests.cs index 14fe01773..1d201356e 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeInvocationTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeInvocationTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class FfprobeInvocationTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeSoundsTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeSoundsTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/FfprobeSoundsTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeSoundsTests.cs index ca61f22f6..cbe24d188 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeSoundsTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeSoundsTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class FfprobeSoundsTests { private static readonly ServiceId Service = new(1040); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeStreamAttributeReaderTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeStreamAttributeReaderTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/FfprobeStreamAttributeReaderTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeStreamAttributeReaderTests.cs index e2e8a86eb..25ab68ba4 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/FfprobeStreamAttributeReaderTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/FfprobeStreamAttributeReaderTests.cs @@ -3,10 +3,12 @@ using Carina.Domain.Base; using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; +using Carina.Infrastructure.Tests.Fixtures.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] [SupportedOSPlatform("linux")] public sealed class FfprobeStreamAttributeReaderTests : IDisposable { diff --git a/tests/Carina.Infrastructure.Tests/Streaming/Fmp4FragmentTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/Fmp4FragmentTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/Fmp4FragmentTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/Fmp4FragmentTests.cs index a785582ee..e40719e8a 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/Fmp4FragmentTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/Fmp4FragmentTests.cs @@ -1,8 +1,9 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class Fmp4FragmentTests { private const uint OneFrame = 1001; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/HlsKeysTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/HlsKeysTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/HlsKeysTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/HlsKeysTests.cs index c3f45fa27..c556c9241 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/HlsKeysTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/HlsKeysTests.cs @@ -7,8 +7,9 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class HlsKeysTests { private const uint OneFrame = 1001; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/HlsSegmenterTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/HlsSegmenterTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/HlsSegmenterTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/HlsSegmenterTests.cs index 86f527396..966269dc0 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/HlsSegmenterTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/HlsSegmenterTests.cs @@ -4,8 +4,9 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class HlsSegmenterTests { private const uint OneFrame = 1001; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveDepartureLedgerTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveDepartureLedgerTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveDepartureLedgerTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveDepartureLedgerTests.cs index 15dcc3ffd..c671a7266 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveDepartureLedgerTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveDepartureLedgerTests.cs @@ -6,8 +6,9 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveDepartureLedgerTests { private static readonly DateTimeOffset Opened = new(2026, 9, 13, 4, 0, 0, TimeSpan.Zero); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveDriverStandIn.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveDriverStandIn.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveDriverStandIn.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveDriverStandIn.cs index 53bb88535..6c69d28b2 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveDriverStandIn.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveDriverStandIn.cs @@ -4,7 +4,7 @@ using Puppis.Contracts; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; internal sealed class LiveDriverStandIn : IDriverClient { diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveEncoderSelectionTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveEncoderSelectionTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveEncoderSelectionTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveEncoderSelectionTests.cs index 712097006..7abfdc9ad 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveEncoderSelectionTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveEncoderSelectionTests.cs @@ -2,8 +2,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveEncoderSelectionTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveFanoutTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFanoutTests.cs similarity index 89% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveFanoutTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFanoutTests.cs index 7fb294d0b..6ed8a5c9c 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveFanoutTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFanoutTests.cs @@ -2,10 +2,13 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveFanoutTests { + private const int Published = 40; + private static readonly byte[] Payload = [0x0a, 0x0b, 0x0c]; private static readonly LiveFrame PictureHeader = new(LiveChannel.PictureHeader, LivePts.Start, new byte[] { 0x00, 0x01 }); @@ -87,9 +90,6 @@ public async Task CaptionsAreNeverThrownAwayWhenTheBacklogIsFull() Assert.Equal(3L, viewing.Backlog.Dropped); } - private static LiveFrame Caption(ulong pts) - => LiveCaptions.Shown(LivePts.Of(pts), new CaptionPicture(10, 20, 30, 40, Png)); - [Fact] public async Task AViewerThatJoinsIsHandedTheHeldHeaderAndThenTheNextPictureRatherThanAnyEarlierOne() { @@ -716,14 +716,6 @@ public async Task FramesPublishedAtOneGoReachAViewerOnceEachAndLeaveTheSetKeptOn Assert.Throws(() => fanout.Publish([], [catalog])); } - private static LiveFrame Data(ulong pts, byte kind) => new(LiveChannel.DataBroadcast, LivePts.Of(pts), new byte[] { kind }); - - private static LiveFanoutSettings Room(int frames) => new() { LongestBacklog = frames }; - - private static LiveFrame Picture(ulong pts) => new(LiveChannel.Picture, LivePts.Of(pts), Payload); - - private static LiveFrame Sound(ulong pts) => new(LiveChannel.Sound, LivePts.Of(pts), Payload); - [Fact] public async Task AFanoutHandsWhoeverJoinsTheStartupItWasGivenAndNothingWhenItHadNone() { @@ -738,6 +730,92 @@ public async Task AFanoutHandsWhoeverJoinsTheStartupItWasGivenAndNothingWhenItHa Assert.Same(held, aware.Startup); } + [Fact] + public async Task AViewerThatStopsReadingKeepsOnlyItsBacklogAndLosesTheRestUntilItIsCutOff() + { + LiveFanout fanout = new(new LiveFanoutSettings { LongestBacklog = 3 }); + await using ILiveViewing draining = await Joined(fanout); + await using ILiveViewing stalled = await Joined(fanout); + + for (ulong pts = 0; pts < Published; pts++) + { + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(pts), Payload)); + } + + fanout.End(); + + using CancellationTokenSource cut = new(); + Task stalling = SlowViewer.StallingAfter(2).WatchAsync(stalled, cut.Token); + SlowViewing read = await SlowViewer.ReadingOneEvery(TimeSpan.Zero).WatchAsync(draining, CancellationToken.None); + + Assert.False(stalling.IsCompleted); + + await cut.CancelAsync(); + + SlowViewing stuck = await stalling; + + Assert.Equal(3, read.Received); + Assert.Equal(new LiveBacklog(0, Published - 3), read.Backlog); + Assert.Equal(2, stuck.Received); + Assert.Equal(new LiveBacklog(1, Published - 3), stuck.Backlog); + } + + [Fact] + public async Task AViewerThatPausesBetweenFramesDropsSomeAndEverythingPublishedIsEitherReceivedOrDropped() + { + LiveFanout fanout = new(new LiveFanoutSettings { LongestBacklog = 3 }); + await using ILiveViewing slow = await Joined(fanout); + + Task watching = SlowViewer + .ReadingOneEvery(TimeSpan.FromMilliseconds(20)) + .WatchAsync(slow, CancellationToken.None); + + for (ulong pts = 0; pts < Published; pts++) + { + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Of(pts), Payload)); + } + + fanout.End(); + + SlowViewing watched = await watching; + + Assert.InRange(watched.Backlog.Dropped, 1L, Published - 3); + Assert.Equal(Published, watched.Received + watched.Backlog.Dropped); + Assert.Equal(0, watched.Backlog.Queued); + } + + [Fact] + public async Task AViewerThatIsCutOffReportsWhatItReceivedUntilThen() + { + LiveFanout fanout = new(new LiveFanoutSettings { LongestBacklog = 3 }); + await using ILiveViewing viewing = await Joined(fanout); + using CancellationTokenSource cut = new(); + + fanout.Publish(new LiveFrame(LiveChannel.Picture, LivePts.Start, Payload)); + + Task watching = SlowViewer.ReadingOneEvery(TimeSpan.Zero).WatchAsync(viewing, cut.Token); + + await Task.Delay(TimeSpan.FromMilliseconds(50)); + await cut.CancelAsync(); + + Assert.Equal(1, (await watching).Received); + } + + [Fact] + public void TheMeasuredPaceIsTheOneTheFanoutWasProvedAgainst() + => Assert.Equal(TimeSpan.FromMilliseconds(400), SlowViewer.MeasuredPace); + + private static LiveFrame Caption(ulong pts) + => LiveCaptions.Shown(LivePts.Of(pts), new CaptionPicture(10, 20, 30, 40, Png)); + + private static LiveFrame Data(ulong pts, byte kind) => new(LiveChannel.DataBroadcast, LivePts.Of(pts), new byte[] { kind }); + + private static LiveFanoutSettings Room(int frames) => new() { LongestBacklog = frames }; + + private static LiveFrame Picture(ulong pts) => new(LiveChannel.Picture, LivePts.Of(pts), Payload); + + private static LiveFrame Sound(ulong pts) => new(LiveChannel.Sound, LivePts.Of(pts), Payload); + private static async Task Joined(LiveFanout fanout) { ILiveViewing? viewing = await fanout.JoinAsync(CancellationToken.None); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveFeedTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFeedTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveFeedTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFeedTests.cs index 8a4183655..2d7d65fc5 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveFeedTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFeedTests.cs @@ -5,8 +5,9 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveFeedTests { private static readonly byte[] Head = Joined(Box("ftyp", 24), Box("moov", 300)); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveFragmentMaterialTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFragmentMaterialTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveFragmentMaterialTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFragmentMaterialTests.cs index 663c51849..58ba4ee72 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveFragmentMaterialTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFragmentMaterialTests.cs @@ -13,7 +13,7 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; [SupportedOSPlatform("linux")] [Trait("Category", "Material")] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveFragmenterTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFragmenterTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveFragmenterTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFragmenterTests.cs index 3ec6db524..d6fa0eb00 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveFragmenterTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFragmenterTests.cs @@ -3,8 +3,9 @@ using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveFragmenterTests { private static readonly byte[] Head = Joined(Box("ftyp", 24), Box("moov", 300)); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveFramesTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFramesTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveFramesTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFramesTests.cs index 34a3e76f8..4fdda671b 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveFramesTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveFramesTests.cs @@ -4,8 +4,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveFramesTests { [Theory] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveSessionManagerTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveSessionManagerTests.cs similarity index 89% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveSessionManagerTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveSessionManagerTests.cs index c5aa2c887..e4ab9e468 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveSessionManagerTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveSessionManagerTests.cs @@ -7,13 +7,23 @@ using Carina.TestSupport; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Puppis.Contracts; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveSessionManagerTests { + private const int TheHoldOnTheSupply = 1; + + private const int MouthfulsPoured = 8; + + private const int MouthfulsThatOverfillTheReader = 128; + + private const int RoundsOfArrivingWhileLeaving = 2_000; + private static readonly TimeSpan Linger = TimeSpan.FromSeconds(5); private static readonly TimeSpan LongestRaise = TimeSpan.FromSeconds(30); @@ -26,10 +36,6 @@ public sealed class LiveSessionManagerTests private static readonly TimeSpan WaitForATunerToComeFree = TimeSpan.FromSeconds(5); - private const int TheHoldOnTheSupply = 1; - - private const int MouthfulsPoured = 8; - private static readonly TimeSpan SoonerThanATranscoderIsCutLooseFor = TimeSpan.FromSeconds(5); private static readonly byte[] Mouthful = new byte[64 * 1024]; @@ -46,6 +52,10 @@ public sealed class LiveSessionManagerTests private static readonly LiveSessionKey InH265 = new(new NetworkId(32736), new ServiceId(1024), LiveProfile.Hd30, SoundTrack.Main, VideoCodec.H265); + private static readonly LiveChannelKey Watched = new(new NetworkId(32736), new ServiceId(1024)); + + private static readonly LiveSessionSettings Settings = new(); + private readonly HandTurnedClock clock = new(); private readonly PipedSupply supply = new(); @@ -60,12 +70,23 @@ public sealed class LiveSessionManagerTests private readonly LiveSessionManager manager; + private readonly LiveSessionManager handing; + private ILiveSessionLedger Ledger => manager; public LiveSessionManagerTests() { transcoders = new HeldTranscoders(budget); manager = Managing(budget, transcoders); + handing = new LiveSessionManager( + Settings, + new LiveFanoutSettings(), + new LiveTranscodeSettings(), + supply, + transcoders, + clock, + events, + NullLogger.Instance); } [Fact] @@ -588,27 +609,6 @@ await Eventually.Happens( lettingGo.SetResult(); } - private async Task GivenUpOnWhileStillOpeningAsync() - { - TaskCompletionSource lettingGo = new(TaskCreationOptions.RunContinuationsAsynchronously); - - supply.AsIfThereWereOneTuner = true; - supply.HeldUntil = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - supply.LettingGoOfAGivenUpOpening = lettingGo; - - using CancellationTokenSource givingUp = new(); - - Task abandoned = manager.JoinAsync(EveryFrame, givingUp.Token); - - await Eventually.Happens(() => supply.Asked is 1, "the first viewer reaches the supply"); - await givingUp.CancelAsync(); - await Assert.ThrowsAnyAsync(() => abandoned); - - supply.HeldUntil = null; - - return lettingGo; - } - [Fact] public async Task BrPs001AChannelSomebodyIsStillWatchingIsNotGivenUpAndTheOneAskingIsRefusedAtOnce() { @@ -1872,42 +1872,6 @@ .. typeof(LiveSessionManager) typeof(ILiveSessionManager).GetMethods().Select(method => method.Name).Order()); } - private static ILiveViewing Seated(LiveJoin join) - { - Assert.True(join.Seated, join.Note); - - return join.Viewing!; - } - - private static async Task Drained(ILiveViewing viewing) - { - while (await viewing.Frames.WaitToReadAsync().AsTask().WaitAsync(Eventually.Patience)) - { - while (viewing.Frames.TryRead(out _)) - { - } - } - } - - /// - /// Waits for a session's ending to be told and for the session to be torn down, so that a second line about - /// the same ending would have been written by then. - /// - private async Task Told() - { - await Eventually.Happens(() => warnings.Endings.Count > 0, "how the session ended is told"); - await Eventually.Happens( - () => budget.Running is 0 && supply.Opened.All(opened => opened.Disposed) && manager.Keys.Count is 0, - "the session is torn down, its transcoder gone and its stream let go"); - } - - private static async Task Next(ILiveViewing viewing) - { - using CancellationTokenSource patience = new(Eventually.Patience); - - return await viewing.Frames.ReadAsync(patience.Token); - } - [Fact] public async Task AChannelSomebodyIsWatchingIsAskedToBeHeldOpenAgainAndAgain() { @@ -1981,6 +1945,305 @@ await Eventually.Happens( Assert.False(transcoders.Raised[0].Disposed); } + [Fact] + public async Task TheChannelIsHandedOverAsItIsAndNoTranscoderIsRaised() + { + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(handed.Handed); + + await using ILiveHandedOver carrying = handed.Handed!; + + byte[] sent = AMouthful(); + + await supply.Opened[0].WriteAsync(sent); + + Assert.Equal(sent, await ReadAsync(carrying.Bytes, sent.Length)); + Assert.Equal(0, transcoders.Started); + Assert.Equal(0, budget.Running); + } + + [Fact] + public async Task AReaderRidesTheReadingAViewerRaisedAndNoSecondTunerIsAskedFor() + { + LiveJoin joined = await handing.JoinAsync(EveryFrame, CancellationToken.None); + + Assert.True(joined.Seated, "a viewer is seated on the channel"); + + await using ILiveViewing viewing = joined.Viewing!; + + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(handed.Handed); + + await using ILiveHandedOver carrying = handed.Handed!; + + Assert.Equal(1, supply.Asked); + Assert.Single(supply.Opened); + Assert.Equal(1, transcoders.Started); + Assert.Equal(1, budget.Running); + } + + [Fact] + public async Task TheReadingIsLetGoOnceTheReaderHasStoppedAndNobodyElseIsBehindIt() + { + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(handed.Handed); + + await handed.Handed!.DisposeAsync(); + await Eventually.Happens(() => supply.Opened[0].Disposed, "the reading is let go"); + } + + [Fact] + public async Task AChannelNoTunerWillReachIsRefusedAndNothingIsHandedOver() + { + supply.Refusing = LiveRefusal.NoTunerFree; + + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.Null(handed.Handed); + Assert.Equal(LiveRefusal.NoTunerFree, handed.Refusal); + } + + [Fact] + public async Task ASeatThatRefusesAMouthfulInAWayNobodyNamedIsDroppedAndTheOthersGoOnBeingFed() + { + LiveJoin joined = await handing.JoinAsync(EveryFrame, CancellationToken.None); + + Assert.True(joined.Seated, "a viewer is seated on the channel"); + + await using ILiveViewing viewing = joined.Viewing!; + + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(handed.Handed); + + await using ILiveHandedOver carrying = handed.Handed!; + + transcoders.Raised[0].FailingToTake = + new InvalidOperationException("writing to a writer that has already been completed."); + + byte[] sent = AMouthful(); + + await supply.Opened[0].WriteAsync(sent); + + Assert.Equal(sent, await ReadAsync(carrying.Bytes, sent.Length)); + + await handing.DisposeAsync(); + } + + [Fact] + public async Task AReaderThatHasLetGoIsNotOfferedAnotherMouthfulAndTheReadingCarriesOn() + { + LiveJoin joined = await handing.JoinAsync(EveryFrame, CancellationToken.None); + + Assert.True(joined.Seated, "a viewer is seated on the channel"); + + await using ILiveViewing viewing = joined.Viewing!; + + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(handed.Handed); + + ILiveHandedOver carrying = handed.Handed!; + + await carrying.DisposeAsync(); + + byte[] sent = AMouthful(); + + await supply.Opened[0].WriteAsync(sent); + await Eventually.Happens( + () => transcoders.Raised[0].TakenIn >= sent.Length, + "the transcoding seat is fed after the reader has let go"); + + Assert.Equal(0, carrying.ChunksDroppedSinceTheSupplyOpened); + + await handing.DisposeAsync(); + } + + [Fact] + public async Task AReaderThatNeverReadsDropsWhatItCannotHoldAndNeverHoldsUpTheTranscodingSeat() + { + LiveJoin joined = await handing.JoinAsync(EveryFrame, CancellationToken.None); + + Assert.True(joined.Seated, "a viewer is seated on the channel"); + + await using ILiveViewing viewing = joined.Viewing!; + + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(handed.Handed); + + await using ILiveHandedOver carrying = handed.Handed!; + + byte[] sent = new byte[64 * 1024]; + long poured = (long)sent.Length * MouthfulsThatOverfillTheReader; + Task pouring = Task.Run(async () => + { + for (int at = 0; at < MouthfulsThatOverfillTheReader; at++) + { + await supply.Opened[0].WriteAsync(sent); + } + }); + + await Sooner( + () => transcoders.Raised[0].TakenIn >= poured, + "the transcoding seat is fed everything while the reader takes nothing"); + await pouring.WaitAsync(Eventually.Patience); + + Assert.True( + carrying.ChunksDroppedSinceTheSupplyOpened > 0, + "a reader that takes nothing has what it cannot hold dropped and counted"); + Assert.NotEmpty(await ReadAsync(carrying.Bytes, sent.Length)); + + await handing.DisposeAsync(); + } + + [Fact] + public async Task NothingIsSaidToHaveReachedTheReaderUntilTheFirstMouthfulHas() + { + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(handed.Handed); + + await using ILiveHandedOver carrying = handed.Handed!; + + Task reaching = carrying.ReachedAsync(CancellationToken.None).AsTask(); + + Assert.False(reaching.IsCompleted, "nothing has come from the channel yet"); + + await supply.Opened[0].WriteAsync(AMouthful()); + + Assert.True(await reaching.WaitAsync(Eventually.Patience)); + } + + [Fact] + public async Task AChannelThatSaysNothingWithinTheLongestRaiseNeverReachesTheReader() + { + LiveHandover handed = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(handed.Handed); + + await using ILiveHandedOver carrying = handed.Handed!; + + Task reaching = carrying.ReachedAsync(CancellationToken.None).AsTask(); + + clock.Turn(Settings.LongestRaise); + + Assert.False(await reaching.WaitAsync(Eventually.Patience)); + } + + [Fact] + public async Task AReaderIsNeverSeatedOnAReadingWhoseCarryingHasAlreadyEnded() + { + LiveHandover first = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.NotNull(first.Handed); + + supply.Opened[0].NoMore(); + + await Eventually.Happens( + () => supply.Opened[0].Disposed, + "the reading lets the supply go once its carrying has ended"); + + LiveHandover second = await handing.HandOverAsync(Watched, CancellationToken.None); + + Assert.Equal(2, supply.Asked); + + await first.Handed!.DisposeAsync(); + + if (second.Handed is { } more) + { + await more.DisposeAsync(); + } + } + + [Fact(DisplayName = "a reader handed the channel while the last reader before it is leaving is never left on a reading that is being let go")] + public async Task AReaderArrivingAsTheLastOneLeavesIsNeverLeftOnAReadingBeingLetGo() + { + for (int round = 0; round < RoundsOfArrivingWhileLeaving; round++) + { + LiveHandover first = await handing.HandOverAsync(Watched, CancellationToken.None); + int spins = round % 64; + + Task leaving = Task.Run(async () => await first.Handed!.DisposeAsync()); + Task arriving = Task.Run(() => + { + Thread.SpinWait(spins * 16); + + return handing.HandOverAsync(Watched, CancellationToken.None); + }); + + await leaving; + + await using ILiveHandedOver arrived = (await arriving).Handed!; + + int askedByNow = supply.Asked; + + await using ILiveHandedOver next = (await handing.HandOverAsync(Watched, CancellationToken.None)).Handed!; + + Assert.Equal(askedByNow, supply.Asked); + } + } + + private async Task GivenUpOnWhileStillOpeningAsync() + { + TaskCompletionSource lettingGo = new(TaskCreationOptions.RunContinuationsAsynchronously); + + supply.AsIfThereWereOneTuner = true; + supply.HeldUntil = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + supply.LettingGoOfAGivenUpOpening = lettingGo; + + using CancellationTokenSource givingUp = new(); + + Task abandoned = manager.JoinAsync(EveryFrame, givingUp.Token); + + await Eventually.Happens(() => supply.Asked is 1, "the first viewer reaches the supply"); + await givingUp.CancelAsync(); + await Assert.ThrowsAnyAsync(() => abandoned); + + supply.HeldUntil = null; + + return lettingGo; + } + + private static ILiveViewing Seated(LiveJoin join) + { + Assert.True(join.Seated, join.Note); + + return join.Viewing!; + } + + private static async Task Drained(ILiveViewing viewing) + { + while (await viewing.Frames.WaitToReadAsync().AsTask().WaitAsync(Eventually.Patience)) + { + while (viewing.Frames.TryRead(out _)) + { + } + } + } + + /// + /// Waits for a session's ending to be told and for the session to be torn down, so that a second line about + /// the same ending would have been written by then. + /// + private async Task Told() + { + await Eventually.Happens(() => warnings.Endings.Count > 0, "how the session ended is told"); + await Eventually.Happens( + () => budget.Running is 0 && supply.Opened.All(opened => opened.Disposed) && manager.Keys.Count is 0, + "the session is torn down, its transcoder gone and its stream let go"); + } + + private static async Task Next(ILiveViewing viewing) + { + using CancellationTokenSource patience = new(Eventually.Patience); + + return await viewing.Frames.ReadAsync(patience.Token); + } + private LiveSessionManager Managing(TranscodeBudget counting, HeldTranscoders? raising = null) => new( new LiveSessionSettings( @@ -2127,4 +2390,29 @@ private sealed class HookedEvents : IAppEventPublisher public void Signal(AppEventName name) => Signalled(); } + + private static byte[] AMouthful() => [.. Enumerable.Range(0, 4_000).Select(at => (byte)(at % 251))]; + + private static async Task ReadAsync(Stream reading, int many) + { + byte[] heard = new byte[many]; + int filled = 0; + + while (filled < many) + { + int read = await reading + .ReadAsync(heard.AsMemory(filled), CancellationToken.None) + .AsTask() + .WaitAsync(Eventually.Patience); + + if (read is 0) + { + break; + } + + filled += read; + } + + return [.. heard.Take(filled)]; + } } diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveStartupRecordTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveStartupRecordTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveStartupRecordTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveStartupRecordTests.cs index 957238bf3..af4129441 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveStartupRecordTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveStartupRecordTests.cs @@ -1,8 +1,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveStartupRecordTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveStraySweepTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveStraySweepTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveStraySweepTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveStraySweepTests.cs index 2a7207cb4..a61e36d44 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveStraySweepTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveStraySweepTests.cs @@ -6,8 +6,9 @@ using Puppis.Contracts; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class LiveStraySweepTests { private const string Device = "adapter3.frontend0"; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveProbeMaterialTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveTranscoderFactoryMaterialTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveProbeMaterialTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveTranscoderFactoryMaterialTests.cs index 3355bcd22..1176b1836 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveProbeMaterialTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveTranscoderFactoryMaterialTests.cs @@ -7,7 +7,7 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; /// /// Feeds a synthetic broadcast into the live transcoder at the rate it was written for, joining it part way @@ -19,7 +19,7 @@ namespace Carina.Infrastructure.Tests.Streaming; /// [SupportedOSPlatform("linux")] [Trait("Category", "Material")] -public sealed class LiveProbeMaterialTests : IDisposable +public sealed class LiveTranscoderFactoryMaterialTests : IDisposable { private const int PacketLength = 188; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/LiveTranscoderFactoryTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveTranscoderFactoryTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/LiveTranscoderFactoryTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveTranscoderFactoryTests.cs index 34f2ecbbb..a351170d3 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/LiveTranscoderFactoryTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/LiveTranscoderFactoryTests.cs @@ -9,8 +9,9 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] [SupportedOSPlatform("linux")] public sealed class LiveTranscoderFactoryTests : IDisposable { diff --git a/tests/Carina.Infrastructure.Tests/Streaming/NutFramesTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/NutFramesTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/NutFramesTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/NutFramesTests.cs index db86267d0..30bd49cc0 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/NutFramesTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/NutFramesTests.cs @@ -3,8 +3,9 @@ using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class NutFramesTests { private static readonly byte[] Png = [0x89, 0x50, 0x4e, 0x47, 1, 2, 3]; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/OnTheFlyPlayerTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/OnTheFlyPlayerTests.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/OnTheFlyPlayerTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/OnTheFlyPlayerTests.cs index 5765affc6..3af264c10 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/OnTheFlyPlayerTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/OnTheFlyPlayerTests.cs @@ -14,8 +14,9 @@ using Microsoft.Extensions.Logging.Abstractions; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] [SupportedOSPlatform("linux")] public sealed class OnTheFlyPlayerTests : IDisposable { diff --git a/tests/Carina.Infrastructure.Tests/Streaming/PalettePngTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/PalettePngTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/PalettePngTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/PalettePngTests.cs index fd9dca7ab..bc3d0f640 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/PalettePngTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/PalettePngTests.cs @@ -4,8 +4,9 @@ using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class PalettePngTests { private static readonly byte[] White = [0xff, 0xff, 0xff, 0xff]; diff --git a/tests/Carina.Infrastructure.Tests/Streaming/RgbaPngTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/RgbaPngTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/RgbaPngTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/RgbaPngTests.cs index 4c06fa736..f5d3cb5da 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/RgbaPngTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/RgbaPngTests.cs @@ -4,8 +4,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class RgbaPngTests { private static readonly VideoSize TwoByTwo = new(2, 2); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/SoundOnAirTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/SoundOnAirTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/SoundOnAirTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/SoundOnAirTests.cs index c94625e3d..b802813c7 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/SoundOnAirTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/SoundOnAirTests.cs @@ -5,8 +5,9 @@ using Carina.Infrastructure.Streaming; using Carina.TestSupport; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class SoundOnAirTests { private static readonly DateTime Noon = new(2026, 9, 13, 12, 0, 0, DateTimeKind.Utc); diff --git a/tests/Carina.Infrastructure.Tests/Streaming/TranscodeBudgetTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TranscodeBudgetTests.cs similarity index 98% rename from tests/Carina.Infrastructure.Tests/Streaming/TranscodeBudgetTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TranscodeBudgetTests.cs index 2ad2bfa93..5b8e1c200 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/TranscodeBudgetTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TranscodeBudgetTests.cs @@ -3,8 +3,9 @@ using Carina.Domain.Streaming; using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class TranscodeBudgetTests { [Fact] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/TranscoderTalkTests.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TranscoderTalkTests.cs similarity index 97% rename from tests/Carina.Infrastructure.Tests/Streaming/TranscoderTalkTests.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TranscoderTalkTests.cs index 8029f466f..0f4890606 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/TranscoderTalkTests.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TranscoderTalkTests.cs @@ -1,7 +1,8 @@ using Carina.Infrastructure.Streaming; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; +[Trait("Category", "Unit")] public sealed class TranscoderTalkTests { [Theory] diff --git a/tests/Carina.Infrastructure.Tests/Streaming/TrueTypeFace.cs b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TrueTypeFace.cs similarity index 99% rename from tests/Carina.Infrastructure.Tests/Streaming/TrueTypeFace.cs rename to tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TrueTypeFace.cs index e6a2d2339..cdab210e1 100644 --- a/tests/Carina.Infrastructure.Tests/Streaming/TrueTypeFace.cs +++ b/tests/Carina.Infrastructure.Tests/Unit/Infra/Streaming/TrueTypeFace.cs @@ -1,7 +1,7 @@ using System.Buffers.Binary; using System.Text; -namespace Carina.Infrastructure.Tests.Streaming; +namespace Carina.Infrastructure.Tests.Unit.Infra.Streaming; /// /// Reads from a TrueType file the little the caption tests ask of a face: its family name, its em, the