using System.Collections.Concurrent; using System.Globalization; using System.IO.Compression; using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Codecs.Images; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Library.Conversion; using Febe.Web.Api; namespace Febe.Web.Export; /// A frame encoded for the page: its bytes, media type, extension and the instant really shown. public sealed record EncodedFrame(byte[] Data, string ContentType, string Extension, TimeSpan Actual); /// The frames of one video in a download: where it is, its account and name, and the instants asked. /// The account (first segment of the zip entries). /// The library file. /// The library file name without extension. /// The instants asked, in increasing order. /// When the entry was published (the time of the zip entries, D18). public sealed record FrameDownloadVideo(string Username, string Path, string Stem, IReadOnlyList Instants, DateTimeOffset PublishedAt); /// A «Scarica» of frames waiting for its address to be opened. public sealed record FrameDownloadPlan(FrameMode Mode, ExportFormat Format, IReadOnlyList Videos) { /// The frames in all. public int Frames => Videos.Sum(v => v.Instants.Count); } /// /// Frames of videos for the page (spec §4.10 «Fotogrammi», tappa E3, D14): what a video allows (kept for 64 files by /// SHA-256), a single frame for the previews and «Scarica», and the zip of several. Previews and single frames go one at /// a time (one decoder busy, never a queue of heavy work) within ; they are not long work and run at /// any time. A zip of up to frames runs at any time too; from 21 to /// it takes and never runs during an engine session. Nothing here writes a /// file: the frames go to the page only. /// public sealed class FrameService(IClock clock) { /// The longest side of a preview. public const int MaxPreview = 480; /// The most frames of a zip at any time. public const int MaxAnyTime = 20; /// The most frames of «Scarica». public const int MaxDownload = 500; /// Video infos kept. public const int CacheSize = 64; public const string TimeoutText = "Il fotogramma richiede troppo tempo: scegli la cartella delle copie"; public const string SessionText = "Il motore è in sessione: per più di 20 fotogrammi riprova fra poco"; public const string TooManyText = "Per più di 500 fotogrammi scegli la cartella delle copie"; public const string NothingText = "Nessun fotogramma da scaricare: scegli dei video con i fotogrammi disponibili."; private static readonly TimeSpan TokenLife = TimeSpan.FromMinutes(5); private readonly SemaphoreSlim _one = new(1, 1); private readonly Lock _cacheGate = new(); private readonly Dictionary _cache = new(StringComparer.Ordinal); private readonly ConcurrentDictionary _tokens = new(StringComparer.Ordinal); private long _uses; /// The time a preview or a single frame may take, waiting included. public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30); /// /// A write of the zip that makes no progress for this long aborts the download: each piece of 64 KB sent restarts /// the time, so a slow link that keeps reading is never cut. /// public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60); /// What a video allows, from the cache by SHA-256 when known (the file is opened only the first time). public async Task InfoAsync(string path, string? sha256, CancellationToken ct) { ArgumentNullException.ThrowIfNull(path); if (sha256 is { Length: > 0 } && Cached(sha256) is { } cached) { return cached; } var info = await Task.Run( () => { using var stream = OpenRead(path); using var reader = VideoFrameReader.Open(stream, out var found); return found; }, ct).ConfigureAwait(false); if (sha256 is { Length: > 0 }) { Remember(sha256, info); } return info; } /// /// The instants of for the video at with the samples really shown; /// empty when the video has no frames. over 1.000 frames. /// public Task<(VideoFrameInfo Info, IReadOnlyList Targets)> LocateAsync(string path, string? sha256, ExportFramesRequest request, CancellationToken ct) { ArgumentNullException.ThrowIfNull(path); ArgumentNullException.ThrowIfNull(request); return Task.Run( () => { using var stream = OpenRead(path); using var reader = VideoFrameReader.Open(stream, out var info); if (sha256 is { Length: > 0 }) { Remember(sha256, info); } if (!info.Available) { return (info, (IReadOnlyList)[]); } var instants = ExportFrames.Instants(info.Duration, request); return (info, reader.Locate(instants)); }, ct); } /// /// The frame shown at , encoded in ; with /// scaled down to fit it (a preview). One at a time, within : past it /// 503. when the video has no frames. /// public async Task FrameAsync(string path, string? sha256, TimeSpan at, ExportFormat format, int? maxSide, CancellationToken ct) { ArgumentNullException.ThrowIfNull(path); var image = MediaConverter.ImageFormatOf(format) ?? throw new BadRequestException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita."); using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct); budget.CancelAfter(Budget); try { await _one.WaitAsync(budget.Token).ConfigureAwait(false); try { return await Task.Run(() => Decode(path, sha256, at, image, maxSide, budget.Token), budget.Token).ConfigureAwait(false); } finally { _one.Release(); } } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { throw new ApiStatusException(503, TimeoutText); } } /// Keeps a download for , for one use; returns its token. public string Register(FrameDownloadPlan plan) { ArgumentNullException.ThrowIfNull(plan); var now = clock.Now; foreach (var (key, value) in _tokens) { if (value.Expires <= now) { _tokens.TryRemove(key, out _); } } var token = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16)); _tokens[token] = (plan, now + TokenLife); return token; } /// The download of , taken once; null when unknown, used or expired. public FrameDownloadPlan? Take(string token) { if (string.IsNullOrEmpty(token) || !_tokens.TryRemove(token, out var found)) { return null; } return found.Expires > clock.Now ? found.Plan : null; } /// The name of a frame file: the library stem, the suffix of its instant (D13), the format's extension. public static string FileName(string stem, FrameMode mode, TimeSpan actual, int index, int count, ExportFormat format) => WindowsFileNames.SanitizeSegment(stem + ExportFrames.Suffix(mode, actual, index, count) + MediaConverter.ExtensionOf(format)); /// /// Writes the zip of into as it is made (not compressed: the /// images are), entries account/name unique as the copies number them («x (2).png»), dated per /// (the publication, else now), within the years a zip can hold. /// public async Task WriteZipAsync(Stream output, FrameDownloadPlan plan, bool publicationTime, CancellationToken ct) { ArgumentNullException.ThrowIfNull(output); ArgumentNullException.ThrowIfNull(plan); var image = MediaConverter.ImageFormatOf(plan.Format) ?? throw new ArgumentException("Formato del fotogramma non valido.", nameof(plan)); var guarded = new StallGuardStream(output, WriteStall); var names = new HashSet(StringComparer.OrdinalIgnoreCase); var zip = await ZipArchive.CreateAsync(guarded, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct).ConfigureAwait(false); await using (zip.ConfigureAwait(false)) { foreach (var video in plan.Videos) { var folder = WindowsFileNames.SanitizeSegment(video.Username); var time = EntryTime(publicationTime ? video.PublishedAt : clock.Now); await foreach (var (index, frame) in FramesAsync(video, plan, image, ct).ConfigureAwait(false)) { var name = FileName(video.Stem, plan.Mode, frame.Actual, index, video.Instants.Count, plan.Format); var relative = folder + "/" + name; var suffix = ExportFrames.Suffix(plan.Mode, frame.Actual, index, video.Instants.Count); for (var attempt = 2; !names.Add(relative); attempt++) { relative = ExportPaths.NumberedName("febe", folder + "/" + name, attempt, keepSuffix: suffix); } var entry = zip.CreateEntry(relative, CompressionLevel.NoCompression); entry.LastWriteTime = time; var stream = await entry.OpenAsync(ct).ConfigureAwait(false); await using (stream.ConfigureAwait(false)) { await stream.WriteAsync(frame.Data, ct).ConfigureAwait(false); } } } } await guarded.CompleteAsync(ct).ConfigureAwait(false); } /// The frames of one video of a download, encoded, in decoding order, with their index among its instants. public async IAsyncEnumerable<(int Index, EncodedFrame Frame)> FramesAsync(FrameDownloadVideo video, FrameDownloadPlan plan, ImageFormat image, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct) { ArgumentNullException.ThrowIfNull(video); ArgumentNullException.ThrowIfNull(plan); Stream stream; try { stream = OpenRead(video.Path); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { yield break; // the file went since the plan: its frames are left out } await using (stream.ConfigureAwait(false)) { var (reader, info) = await Task.Run(() => (VideoFrameReader.Open(stream, out var found), found), ct).ConfigureAwait(false); using (reader) { if (!info.Available) { yield break; } var targets = reader.Locate(video.Instants); using var frames = reader.Decode(targets, ct).GetEnumerator(); var shown = new HashSet(); while (await Task.Run(() => frames.MoveNext(), ct).ConfigureAwait(false)) { using var frame = frames.Current; if (!shown.Add(frame.Actual.Ticks)) { continue; // two instants on the same picture give it once, as the copies do } var data = await Task.Run(() => ImageConverter.Encode(frame.Image, image, null), ct).ConfigureAwait(false); yield return (frame.Index, new EncodedFrame(data, ContentType(image), MediaConverter.ExtensionOf(plan.Format), frame.Actual)); } } } } /// The media type of an image format written by Febe. public static string ContentType(ImageFormat format) => format switch { ImageFormat.Jpeg => "image/jpeg", ImageFormat.Png => "image/png", _ => "image/webp", }; private EncodedFrame Decode(string path, string? sha256, TimeSpan at, ImageFormat image, int? maxSide, CancellationToken ct) { using var stream = OpenRead(path); using var reader = VideoFrameReader.Open(stream, out var info); if (sha256 is { Length: > 0 }) { Remember(sha256, info); } if (!info.Available) { throw new NotFoundException(info.Unavailable ?? VideoFrameReader.NotAvailableMessage); } var targets = reader.Locate([at]); using var frame = reader.Decode(targets, ct).FirstOrDefault() ?? throw new NotFoundException(VideoFrameReader.NotAvailableMessage); ct.ThrowIfCancellationRequested(); var source = frame.Image; if (maxSide is { } max && Math.Max(source.Width, source.Height) > max) { var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, max); using var small = ImageResampler.Resize(source, width, height); return new EncodedFrame(ImageConverter.Encode(small, image, null), ContentType(image), Extension(image), frame.Actual); } return new EncodedFrame(ImageConverter.Encode(source, image, null), ContentType(image), Extension(image), frame.Actual); } private static string Extension(ImageFormat image) => image switch { ImageFormat.Jpeg => ".jpg", ImageFormat.Png => ".png", _ => ".webp", }; /// The time of a zip entry: within 1980-2107, the years a zip can hold. private DateTimeOffset EntryTime(DateTimeOffset instant) { var local = TimeZoneInfo.ConvertTime(instant, clock.LocalZone); var min = new DateTimeOffset(1980, 1, 1, 0, 0, 0, local.Offset); var max = new DateTimeOffset(2107, 12, 31, 23, 59, 58, local.Offset); return local < min ? min : local > max ? max : local; } private VideoFrameInfo? Cached(string sha256) { lock (_cacheGate) { if (_cache.TryGetValue(sha256, out var found)) { _cache[sha256] = (found.Info, ++_uses); return found.Info; } return null; } } private void Remember(string sha256, VideoFrameInfo info) { lock (_cacheGate) { _cache[sha256] = (info, ++_uses); if (_cache.Count > CacheSize) { var oldest = _cache.MinBy(p => p.Value.Used).Key; _cache.Remove(oldest); } } } private static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess); internal static string Day(DateTimeOffset now, TimeZoneInfo zone) => LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); /// /// A write-only stream that gives up a write making no progress for a while (the page stopped reading). The zip of /// .NET 10 writes the small data descriptor of each entry synchronously even through its asynchronous API: those /// bytes are kept here and sent with the next asynchronous write, so the response never sees a synchronous write. /// private sealed class StallGuardStream(Stream inner, TimeSpan stall) : Stream { // A data descriptor is 16 or 24 bytes; anything far larger written synchronously is a change of the BCL. private const int MaxPending = 64 * 1024; // The bytes of one guarded write: the response buffer of Kestrel (64 KB). private const int Piece = 64 * 1024; private readonly MemoryStream _pending = new(); private long _position; public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotSupportedException(); public override long Position { get => _position; set => throw new NotSupportedException(); } public override void Flush() { } public override async Task FlushAsync(CancellationToken cancellationToken) { await SendPendingAsync(cancellationToken).ConfigureAwait(false); await inner.FlushAsync(cancellationToken).ConfigureAwait(false); } public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); public override void Write(ReadOnlySpan buffer) { if (_pending.Length + buffer.Length > MaxPending) { throw new NotSupportedException("Lo zip dei fotogrammi si scrive solo in modo asincrono."); } _pending.Write(buffer); _position += buffer.Length; } public override void WriteByte(byte value) => Write([value]); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) { await SendPendingAsync(cancellationToken).ConfigureAwait(false); await GuardedAsync(buffer, cancellationToken).ConfigureAwait(false); _position += buffer.Length; } /// Sends what was written synchronously and flushes: call it once the zip is complete. public Task CompleteAsync(CancellationToken ct) => FlushAsync(ct); private async Task SendPendingAsync(CancellationToken ct) { if (_pending.Length == 0) { return; } var bytes = _pending.ToArray(); _pending.SetLength(0); await GuardedAsync(bytes, ct).ConfigureAwait(false); } /// /// Sends in pieces of bytes, each with its own time: a frame of /// several megabytes on a slow link keeps going as long as every piece goes (a response write completes only once /// the socket has taken nearly all of it), and stops after stall without one. /// private async Task GuardedAsync(ReadOnlyMemory buffer, CancellationToken ct) { for (var offset = 0; offset < buffer.Length; offset += Piece) { using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct); guard.CancelAfter(stall); await inner.WriteAsync(buffer.Slice(offset, Math.Min(Piece, buffer.Length - offset)), guard.Token).ConfigureAwait(false); } } } }