using System.Security.Cryptography; using Chronos.Core.Codecs.Jpeg; using Chronos.Core.Diagnostics.Synthetic; using Chronos.Core.Metadata; using Chronos.Core.Model; using Chronos.Data.Archiving; using Chronos.Data.Tests.Archiving; using Chronos.Data.Videos; using Chronos.Testing; namespace Chronos.Data.Tests.Videos; /// A temporary archive with small synthetic sequences and renders recorded on files written by hand. internal sealed class VideoFixture : IAsyncDisposable { private VideoFixture(TestContext context, ArchiveFixture archive) { Archive = archive; VideosFolder = context.CreateTempDirectory("videos"); } public ArchiveFixture Archive { get; } public ChronosDatabase Db => Archive.Db; public VideoLibrary Library => Archive.Service.Videos; public CancellationToken Ct => Archive.Ct; /// A folder outside the archive that copies go to. public string VideosFolder { get; } /// How much space the videos folder has (bytes); null: the drive's. public static async Task CreateAsync(TestContext context, long? freeSpace = null) { string? videos = null; var archive = await ArchiveFixture.CreateAsync(context, configure: o => o with { FreeSpace = path => freeSpace is { } free && videos is not null && path.StartsWith(videos, StringComparison.OrdinalIgnoreCase) ? free : null, }); var fixture = new VideoFixture(context, archive); videos = fixture.VideosFolder; return fixture; } /// A sequence of four synthetic frames in , indexed. public async Task SequenceAsync(string folder = "Harbour", int seed = 1) { var synthetic = SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 4, Seed = seed, Start = new DateTime(2024, 6, 21, 19, 0, 0).AddDays(seed) }); var directory = Path.Combine(Archive.Paths.Root, folder); Directory.CreateDirectory(directory); for (var i = 0; i < synthetic.Count; i++) { using var image = synthetic.Render(i); var exif = ExifWriter.BuildJpegApp1(synthetic.Metadata[i]); File.WriteAllBytes(Path.Combine(directory, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] })); } await Archive.ScanAsync(Chronos.Data.Archiving.ScanMode.Full); var location = (await Db.Sequences.ListLocationsAsync(Archive.Archive.Id, Ct)).Single(l => l.Folder == folder); return (await Db.Sequences.GetAsync(location.Id, Ct))!; } /// A render of recorded on a file of written into its exports. public async Task RenderAsync(Sequence sequence, string name, int bytes, DateTimeOffset? created = null, string codec = "H264", string? kind = null, bool hashed = true) { var exports = Archive.Paths.Sequence(sequence.Folder).Exports; Directory.CreateDirectory(exports); var content = Content(name, bytes); await File.WriteAllBytesAsync(Path.Combine(exports, name), content, Ct); var render = new Render { Id = Guid.CreateVersion7(), SequenceId = sequence.Id, PresetName = "Test preset", OutputPath = $"{sequence.Folder}/exports/{name}", Codec = codec, Width = 96, Height = 64, Fps = kind == RenderKind.Still ? 0 : 24, DurationSeconds = kind == RenderKind.Still ? 0 : 2, Bytes = bytes, Created = created ?? DateTimeOffset.UtcNow, ProducedBy = "test-pc", Sha256 = hashed ? Convert.ToHexStringLower(SHA256.HashData(content)) : null, Kind = kind, }; await Db.Renders.InsertAsync(render, Ct); return render; } /// An image-sequence render: a folder of PNG-named files. public async Task SequenceRenderAsync(Sequence sequence, string name, int files) { var folder = Path.Combine(Archive.Paths.Sequence(sequence.Folder).Exports, name); Directory.CreateDirectory(folder); long total = 0; for (var i = 0; i < files; i++) { var content = Content(name + i, 300 + i); total += content.Length; await File.WriteAllBytesAsync(Path.Combine(folder, $"{name}_{i + 1:000000}.png"), content, Ct); } var render = new Render { Id = Guid.CreateVersion7(), SequenceId = sequence.Id, PresetName = "PNG", OutputPath = $"{sequence.Folder}/exports/{name}", Codec = "PngSequence", Width = 96, Height = 64, Fps = 24, Bytes = total, Created = DateTimeOffset.UtcNow, }; await Db.Renders.InsertAsync(render, Ct); return render; } public string FileOf(Render render) => Archive.Paths.FromRelative(render.OutputPath); private Chronos.Data.Jobs.JobEngine? _engine; /// Starts the archive's job engine (its handlers include the videos copy). public async Task StartEngineAsync() => _engine = await Archive.StartEngineAsync(); public Task EnqueueAsync(Chronos.Data.Archiving.Jobs.ArchiveJobRequest request) => (_engine ?? throw new InvalidOperationException("Start the engine first.")).EnqueueAsync(request, cancellationToken: Ct); /// Deterministic bytes, different for each name. public static byte[] Content(string name, int bytes) { var content = new byte[bytes]; new Random(StringComparer.Ordinal.GetHashCode(name) & 0x7FFFFFFF).NextBytes(content); content[0] = (byte)name.Length; return content; } public ValueTask DisposeAsync() => Archive.DisposeAsync(); }