Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<Program> configured = factory
.WithWebHostBuilder(builder => builder.ConfigureTestServices(services =>
{
services.RemoveAll<IHostedService>();
services.RemoveAll<CaptionSettings>();
services.AddSingleton<IRecordingDirectory>(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<IEncodeJobRepository>(Jobs);
services.AddSingleton<IEncodeProfileRepository>(Profiles);
services.RemoveAll<IArtefactCodecReader>();
services.AddSingleton<IArtefactCodecReader>(Codecs);
services.RemoveAll<IOnTheFlyPlayer>();
services.AddSingleton<IOnTheFlyPlayer>(new HeldOnTheFlyPlayer());
services.RemoveAll<IEncodeChapterRepository>();
services.AddSingleton<IEncodeChapterRepository>(new HeldEncodeChapters());
services.AddSingleton<IPlaybackPositionRepository>(new HeldPlaybackPositions());
services.AddSingleton<ISegmentSettingsRepository>(new HeldSegmentSettings());
services.AddSingleton<ISegmentModelVersionRepository>(new HeldSegmentModelVersions());
services.AddSingleton<IRecordingDetectionRepository>(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<Recording> 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<HttpResponseMessage> 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<string?> 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<JsonElement> 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]
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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]
Expand All @@ -312,23 +126,21 @@ 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();

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();
Expand All @@ -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]
Expand All @@ -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);
}

Expand Down Expand Up @@ -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]
Expand Down
26 changes: 26 additions & 0 deletions tests/Carina.Api.Tests/Feature/Playback/GatedOnTheFlyPlayer.cs
Original file line number Diff line number Diff line change
@@ -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<OnTheFlyStart> StartAsync(
PlaybackFile file,
ServiceId service,
TimeSpan from,
LiveProfile? profile,
VideoCodec format,
SoundPlacement sound,
CancellationToken cancellationToken)
=> Task.FromResult(OnTheFlyStart.Started(new GatedViewing(Handed)));

public Task<CarriedSounds> SoundsAsync(
PlaybackFile file,
ServiceId service,
CancellationToken cancellationToken)
=> Task.FromResult(CarriedSounds.Counted(1));
}
17 changes: 17 additions & 0 deletions tests/Carina.Api.Tests/Feature/Playback/GatedPlaybackFiles.cs
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading