diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f3dbbd71..f49269cb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ ### Added +* [Yavsc.Server/Podcasts] Add the frame-accurate replay editing prototype: `ReplayEditPlan` turns removed ranges into kept ranges (merge, clamp, reject empty, out-of-range, total or excessive removals) and `FfmpegPodcastReplayEditor` renders them with one accurate-seek FFmpeg input per range, `concat` and H.264/AAC re-encoding. Share the FFmpeg runner with the replay remuxer. Tests check exact kept frames, audio/video durations, faststart and quota on synthetic sources with and without a start offset; the editor is not wired to the API yet. + * [PostIt/Podcasts] Preview the replay frame while dragging the desktop position slider, coalescing seek requests to the latest position. A native LibVLC test checks frame-accurate paused seeking on a synthetic video; the video edition document records the prototype result. * [Docs/Podcasts] Add the video edition design document: optional author-only replay refinement (marks, frame-accurate cuts, chapters, timed overlays, re-edition and retention), live credits and overlays, end postponement and server-side "Direct interrompu" handling. Desktop first; OBS broadcasts are out of scope. diff --git a/doc/video-edition.md b/doc/video-edition.md index 3cb7a0160..402c64873 100644 --- a/doc/video-edition.md +++ b/doc/video-edition.md @@ -160,6 +160,33 @@ traitement doit couper aussi l'audio, rétablir des horodatages continus et MP4 final. La faisabilité et le coût doivent être mesurés sur des sources à cadence variable, sans audio et avec audio. +**Résultat du prototype serveur** : `ReplayEditPlan` convertit les plages +supprimées en plages conservées : il fusionne les plages qui se chevauchent ou +se touchent, les borne à la durée, refuse les plages vides ou hors vidéo, la +suppression totale et plus de 200 plages. `FfmpegPodcastReplayEditor` ouvre la +source une fois par plage conservée, avec une recherche précise +(`-ss`/`-to` en entrée), puis assemble les plages avec le filtre `concat` et +réencode en H.264/AAC avec `+faststart`. Une plage [début, fin) conserve les +images dont l'horodatage est dans l'intervalle ; l'audio est coupé aux mêmes +temps. Seuls des nombres formatés et le chemin de la source, généré par le +serveur, sont transmis à FFmpeg. + +- `trim` suivi de `setpts=PTS-STARTPTS` a été écarté : avec FFmpeg 7.1, la + durée de la dernière image est perdue et cette image disparaît du MP4. +- **Origine des temps** : LibVLC et le `-ss` d'entrée de FFmpeg mesurent tous + deux le temps depuis le début du format, c'est-à-dire du premier flux, et non + depuis la première image vidéo. Mesuré : avec une vidéo qui commence 0,52 s + après l'audio, LibVLC affiche à 1 500 ms l'image vidéo de 980 ms. Les marques + prises dans le lecteur sont donc directement utilisables par le serveur. +- Lorsque l'audio commence avant la vidéo (décalage d'encodage AAC, segments + live), chaque plage garde ce léger décalage. La vidéo finale peut ainsi + dépasser d'une image la somme des plages, sans désynchronisation. +- Le test serveur vérifie, sur une source synthétique avec audio, la liste + exacte des images conservées, les durées audio et vidéo, `faststart` et le + refus d'un résultat dépassant le quota, avec et sans décalage de départ. +- Restent à mesurer : le coût du réencodage sur un replay long, et les + sources à cadence variable issues des captures PostIt. + ### États et persistance Proposition, à adapter aux états déjà exposés par l'API : @@ -284,7 +311,8 @@ différent de celui annoncé à l'auteur. 1. Valider le parcours, la politique de visibilité et les questions ci-dessous. 2. Prototyper sur desktop la navigation précise et l'aperçu pendant le glissement (fait, voir « Résultat du prototype desktop »), puis - l'assemblage audio/vidéo précis côté serveur. + l'assemblage audio/vidéo précis côté serveur (fait, voir « Résultat du + prototype serveur »). 3. Ajouter le brouillon privé et ses états, les autorisations, les limites et la reprise après incident, puis l'éditeur de marques et plages desktop. 4. Valider la finalisation sur de vrais médias synthétiques et conserver le @@ -323,6 +351,7 @@ différent de celui annoncé à l'auteur. Toutes les questions de conception posées jusqu'ici ont reçu une réponse. Les points encore ouverts sont techniques et seront tranchés par les -prototypes : chaîne FFmpeg de découpe et d'incrustation, détection d'une -interruption côté serveur et choix de composition live (PostIt ou serveur). -L'aperçu à l'image près sur desktop est tranché : recherche directe LibVLC. +prototypes : chaîne FFmpeg d'incrustation, détection d'une interruption côté +serveur et choix de composition live (PostIt ou serveur). L'aperçu à l'image +près sur desktop (recherche directe LibVLC) et la découpe côté serveur +(une entrée FFmpeg par plage conservée, puis `concat`) sont tranchés. diff --git a/src/Yavsc.Server/Interfaces/IPodcastReplayEditor.cs b/src/Yavsc.Server/Interfaces/IPodcastReplayEditor.cs new file mode 100644 index 000000000..3d3f5747d --- /dev/null +++ b/src/Yavsc.Server/Interfaces/IPodcastReplayEditor.cs @@ -0,0 +1,11 @@ +namespace Yavsc.Services; + +public interface IPodcastReplayEditor +{ + /// + /// Renders the kept ranges of into a new MP4, cut at frame + /// boundaries with audio cut at the same times. + /// + Task RenderAsync(string sourcePath, IReadOnlyList kept, bool hasAudio, + string outputPath, long maxBytes, CancellationToken ct); +} diff --git a/src/Yavsc.Server/Services/FfmpegPodcastReplayEditor.cs b/src/Yavsc.Server/Services/FfmpegPodcastReplayEditor.cs new file mode 100644 index 000000000..07ad389e2 --- /dev/null +++ b/src/Yavsc.Server/Services/FfmpegPodcastReplayEditor.cs @@ -0,0 +1,43 @@ +using System.Globalization; +using System.Text; +using Microsoft.Extensions.Options; + +namespace Yavsc.Services; + +public sealed class FfmpegPodcastReplayEditor(IOptions options) : IPodcastReplayEditor +{ + public Task RenderAsync(string sourcePath, IReadOnlyList kept, bool hasAudio, + string outputPath, long maxBytes, CancellationToken ct) + { + if (kept.Count == 0) throw new ArgumentException("Aucune plage conservée.", nameof(kept)); + if (kept.Count > ReplayEditPlan.MaxRemovedRanges + 1) + throw new ArgumentException("Trop de plages conservées.", nameof(kept)); + for (var i = 0; i < kept.Count; i++) + if (kept[i].StartMs < 0 || kept[i].DurationMs <= 0 || (i > 0 && kept[i].StartMs < kept[i - 1].EndMs)) + throw new ArgumentException("Les plages conservées doivent être ordonnées et disjointes.", nameof(kept)); + + // Each kept range is a separate input with an accurate seek: FFmpeg decodes from the previous + // keyframe, drops frames before the start and stops at the end, with timestamps reset to zero + // and frame durations preserved (trim + setpts loses the last frame duration). concat then + // rebuilds continuous audio and video timestamps. Only formatted numbers and the + // server-generated source path are passed to FFmpeg, never user text. + var arguments = new List { "-nostdin", "-hide_banner", "-loglevel", "error", "-y" }; + var graph = new StringBuilder(); + for (var i = 0; i < kept.Count; i++) + { + arguments.AddRange(["-ss", Seconds(kept[i].StartMs), "-to", Seconds(kept[i].EndMs), "-i", sourcePath]); + graph.Append(hasAudio ? $"[{i}:v:0][{i}:a:0]" : $"[{i}:v:0]"); + } + graph.Append($"concat=n={kept.Count}:v=1:a={(hasAudio ? 1 : 0)}[v]"); + if (hasAudio) graph.Append("[a]"); + + arguments.AddRange(["-filter_complex", graph.ToString(), "-map", "[v]"]); + if (hasAudio) arguments.AddRange(["-map", "[a]", "-c:a", "aac"]); + arguments.AddRange(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-fps_mode", "vfr", + "-movflags", "+faststart", "-f", "mp4", outputPath]); + return FfmpegProcess.RunAsync(options.Value.FfmpegPath, arguments, null, outputPath, maxBytes, ct); + } + + private static string Seconds(long milliseconds) + => (milliseconds / 1000m).ToString("0.###", CultureInfo.InvariantCulture); +} diff --git a/src/Yavsc.Server/Services/FfmpegPodcastReplayRemuxer.cs b/src/Yavsc.Server/Services/FfmpegPodcastReplayRemuxer.cs index d2caed29f..73b80d3a9 100644 --- a/src/Yavsc.Server/Services/FfmpegPodcastReplayRemuxer.cs +++ b/src/Yavsc.Server/Services/FfmpegPodcastReplayRemuxer.cs @@ -1,4 +1,3 @@ -using System.Diagnostics; using Microsoft.Extensions.Options; namespace Yavsc.Services; @@ -15,64 +14,17 @@ public sealed class FfmpegPodcastReplayRemuxer(IOptions options) { await File.WriteAllLinesAsync(list, Enumerable.Range(0, segmentCount).Select(i => $"{i:D8}.ts"), ct); - var start = new ProcessStartInfo(options.Value.FfmpegPath) - { - UseShellExecute = false, - RedirectStandardError = true, - CreateNoWindow = true, - WorkingDirectory = directory - }; - foreach (var argument in new[] - { + await FfmpegProcess.RunAsync(options.Value.FfmpegPath, + [ "-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-protocol_whitelist", "file,concatf", "-f", "mpegts", "-i", $"concatf:{list}", "-map", "0:v:0", "-map", "0:a:0?", "-c", "copy", "-bsf:a", "aac_adtstoasc", "-movflags", "+faststart", "-f", "mp4", outputPath - }) - start.ArgumentList.Add(argument); - using var process = Process.Start(start) - ?? throw new IOException("Impossible de demarrer FFmpeg."); - var errors = DrainErrorsAsync(process.StandardError, CancellationToken.None); - try - { - var exited = process.WaitForExitAsync(ct); - // -fs can report success for a truncated replay. Abort instead of publishing partial media. - while (!exited.IsCompleted) - { - await Task.WhenAny(exited, Task.Delay(50, ct)); - ct.ThrowIfCancellationRequested(); - if (File.Exists(outputPath) && new FileInfo(outputPath).Length > maxBytes) - throw new IOException("Le MP4 depasse le quota de stockage disponible."); - } - await exited; - var error = await errors; - if (process.ExitCode != 0) - throw new InvalidDataException($"FFmpeg a echoue ({process.ExitCode}) : {error}"); - var length = new FileInfo(outputPath).Length; - if (length == 0 || length > maxBytes) - throw new IOException("Le MP4 depasse le quota de stockage disponible ou est vide."); - } - catch - { - if (!process.HasExited) process.Kill(entireProcessTree: true); - await process.WaitForExitAsync(CancellationToken.None); - await errors; - throw; - } + ], directory, outputPath, maxBytes, ct); } finally { File.Delete(list); } } - - private static async Task DrainErrorsAsync(StreamReader reader, CancellationToken ct) - { - var text = new System.Text.StringBuilder(); - var buffer = new char[1024]; - int count; - while ((count = await reader.ReadAsync(buffer.AsMemory(), ct)) != 0) - if (text.Length < 4096) text.Append(buffer, 0, Math.Min(count, 4096 - text.Length)); - return text.ToString(); - } } diff --git a/src/Yavsc.Server/Services/FfmpegProcess.cs b/src/Yavsc.Server/Services/FfmpegProcess.cs new file mode 100644 index 000000000..c9a3bb794 --- /dev/null +++ b/src/Yavsc.Server/Services/FfmpegProcess.cs @@ -0,0 +1,62 @@ +using System.Diagnostics; + +namespace Yavsc.Services; + +internal static class FfmpegProcess +{ + /// + /// Runs FFmpeg with arguments passed without a shell and fails instead of leaving a partial, + /// empty or oversized output. + /// + public static async Task RunAsync(string ffmpegPath, IEnumerable arguments, string? workingDirectory, + string outputPath, long maxBytes, CancellationToken ct) + { + var start = new ProcessStartInfo(ffmpegPath) + { + UseShellExecute = false, + RedirectStandardError = true, + CreateNoWindow = true + }; + if (workingDirectory is not null) start.WorkingDirectory = workingDirectory; + foreach (var argument in arguments) start.ArgumentList.Add(argument); + using var process = Process.Start(start) + ?? throw new IOException("Impossible de demarrer FFmpeg."); + var errors = DrainErrorsAsync(process.StandardError, CancellationToken.None); + try + { + var exited = process.WaitForExitAsync(ct); + // -fs can report success for a truncated output. Abort instead of publishing partial media. + while (!exited.IsCompleted) + { + await Task.WhenAny(exited, Task.Delay(50, ct)); + ct.ThrowIfCancellationRequested(); + if (File.Exists(outputPath) && new FileInfo(outputPath).Length > maxBytes) + throw new IOException("Le MP4 depasse le quota de stockage disponible."); + } + await exited; + var error = await errors; + if (process.ExitCode != 0) + throw new InvalidDataException($"FFmpeg a echoue ({process.ExitCode}) : {error}"); + var length = new FileInfo(outputPath).Length; + if (length == 0 || length > maxBytes) + throw new IOException("Le MP4 depasse le quota de stockage disponible ou est vide."); + } + catch + { + if (!process.HasExited) process.Kill(entireProcessTree: true); + await process.WaitForExitAsync(CancellationToken.None); + await errors; + throw; + } + } + + private static async Task DrainErrorsAsync(StreamReader reader, CancellationToken ct) + { + var text = new System.Text.StringBuilder(); + var buffer = new char[1024]; + int count; + while ((count = await reader.ReadAsync(buffer.AsMemory(), ct)) != 0) + if (text.Length < 4096) text.Append(buffer, 0, Math.Min(count, 4096 - text.Length)); + return text.ToString(); + } +} diff --git a/src/Yavsc.Server/Services/ReplayEditPlan.cs b/src/Yavsc.Server/Services/ReplayEditPlan.cs new file mode 100644 index 000000000..8e2d85b08 --- /dev/null +++ b/src/Yavsc.Server/Services/ReplayEditPlan.cs @@ -0,0 +1,44 @@ +namespace Yavsc.Services; + +/// A half-open time range [StartMs, EndMs) in the original replay timeline. +public readonly record struct ReplayRange(long StartMs, long EndMs) +{ + public long DurationMs => EndMs - StartMs; +} + +public static class ReplayEditPlan +{ + public const int MaxRemovedRanges = 200; + + /// + /// Converts ranges removed by the author into the ordered ranges kept in the final replay. + /// Overlapping or touching removals are merged; removals are clamped to the source duration. + /// + public static IReadOnlyList KeptRanges(IEnumerable removed, long durationMs) + { + if (durationMs <= 0) throw new ArgumentException("La durée de la source est invalide.", nameof(durationMs)); + var cuts = removed.ToList(); + if (cuts.Count > MaxRemovedRanges) + throw new ArgumentException($"Au plus {MaxRemovedRanges} plages peuvent être supprimées.", nameof(removed)); + foreach (var cut in cuts) + { + if (cut.StartMs >= cut.EndMs) + throw new ArgumentException("Une plage supprimée doit avoir une fin postérieure à son début.", nameof(removed)); + if (cut.EndMs <= 0 || cut.StartMs >= durationMs) + throw new ArgumentException("Une plage supprimée est en dehors de la vidéo.", nameof(removed)); + } + + var kept = new List(); + var position = 0L; + foreach (var cut in cuts.OrderBy(c => c.StartMs)) + { + var start = Math.Max(0, cut.StartMs); + if (start > position) kept.Add(new ReplayRange(position, start)); + position = Math.Max(position, Math.Min(durationMs, cut.EndMs)); + } + if (position < durationMs) kept.Add(new ReplayRange(position, durationMs)); + if (kept.Count == 0) + throw new ArgumentException("Ces suppressions retireraient toute la vidéo.", nameof(removed)); + return kept; + } +} diff --git a/src/test/Yavsc.Api.Tests/PodcastReplayTests.cs b/src/test/Yavsc.Api.Tests/PodcastReplayTests.cs index 0c390f968..c9c29cb16 100644 --- a/src/test/Yavsc.Api.Tests/PodcastReplayTests.cs +++ b/src/test/Yavsc.Api.Tests/PodcastReplayTests.cs @@ -196,6 +196,66 @@ public sealed class PodcastReplayTests : IDisposable Path.Combine(source, "too-big.mp4"), 10, _ct)); } + [Fact] + public void Edit_plan_merges_clamps_and_rejects_invalid_or_total_removals() + { + Assert.Equal([new ReplayRange(0, 1000), new ReplayRange(3000, 3500), new ReplayRange(4000, 5000)], + ReplayEditPlan.KeptRanges([new(2000, 3000), new(1000, 2500), new(3500, 4000)], 5000)); + Assert.Equal([new ReplayRange(1000, 4000)], + ReplayEditPlan.KeptRanges([new(-500, 1000), new(4000, 9000)], 5000)); + Assert.Equal([new ReplayRange(0, 5000)], ReplayEditPlan.KeptRanges([], 5000)); + Assert.Throws(() => ReplayEditPlan.KeptRanges([new(0, 2000), new(2000, 5000)], 5000)); + Assert.Throws(() => ReplayEditPlan.KeptRanges([new(1000, 1000)], 5000)); + Assert.Throws(() => ReplayEditPlan.KeptRanges([new(5000, 6000)], 5000)); + Assert.Throws(() => ReplayEditPlan.KeptRanges( + Enumerable.Range(0, ReplayEditPlan.MaxRemovedRanges + 1).Select(i => new ReplayRange(i * 10, i * 10 + 5)), 5000)); + } + + [Theory] + [InlineData("0")] + [InlineData("1.4")] // Replays remuxed from live TS segments do not start at zero. + public async Task Ffmpeg_editor_cuts_at_exact_frames_and_keeps_audio_in_sync(string startOffset) + { + Directory.CreateDirectory(_root); + var source = Path.Combine(_root, "frames.mp4"); + // 10 fps, frame N has luma 20 + 5N; keyframes every 2 s so cuts fall between keyframes. + await PodcastMediaFixture.RunAsync("ffmpeg", ["-v", "error", + "-f", "lavfi", "-i", "color=black:s=32x32:r=10:d=4,format=yuv420p,geq=lum='20+5*N':cb=128:cr=128", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=4", + "-c:v", "libx264", "-qp", "0", "-g", "20", "-c:a", "aac", "-shortest", + "-output_ts_offset", startOffset, source], _ct); + var kept = ReplayEditPlan.KeptRanges([new(1000, 1600), new(2400, 3000)], 4000); + var output = Path.Combine(_root, "edited.mp4"); + var editor = new FfmpegPodcastReplayEditor(Options.Create(new PodcastOptions())); + + await editor.RenderAsync(source, kept, hasAudio: true, output, 10_000_000, _ct); + + var frames = Path.Combine(_root, "edited.yuv"); + await PodcastMediaFixture.RunAsync("ffmpeg", + ["-v", "error", "-i", output, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", frames], _ct); + var bytes = await File.ReadAllBytesAsync(frames, _ct); + const int FrameBytes = 32 * 32 * 3 / 2; + var indices = Enumerable.Range(0, bytes.Length / FrameBytes) + .Select(i => (int)Math.Round((bytes[i * FrameBytes + 16 * 32 + 16] - 20) / 5.0)).ToArray(); + Assert.Equal(Enumerable.Range(0, 10).Concat(Enumerable.Range(16, 8)).Concat(Enumerable.Range(30, 10)), indices); + + var probe = await PodcastMediaFixture.RunAsync("ffprobe", + ["-v", "error", "-show_streams", "-of", "json", output], _ct); + using var json = JsonDocument.Parse(probe); + var durations = json.RootElement.GetProperty("streams").EnumerateArray().ToDictionary( + s => s.GetProperty("codec_type").GetString()!, + s => double.Parse(s.GetProperty("duration").GetString()!, System.Globalization.CultureInfo.InvariantCulture)); + // Ranges use the format timeline, like LibVLC and FFmpeg input seeking. When audio starts + // slightly before video, each range keeps that lead, so allow one frame (100 ms) of slack. + Assert.InRange(durations["video"], 2.7, 2.91); + Assert.InRange(durations["audio"], 2.7, 2.91); + Assert.InRange(Math.Abs(durations["video"] - durations["audio"]), 0, 0.1); + var ascii = Encoding.Latin1.GetString(await File.ReadAllBytesAsync(output, _ct)); + Assert.True(ascii.IndexOf("moov", StringComparison.Ordinal) < ascii.IndexOf("mdat", StringComparison.Ordinal)); + await Assert.ThrowsAsync(() => editor.RenderAsync(source, kept, true, + Path.Combine(_root, "too-big.mp4"), 10, _ct)); + } + private static Remuxer Bytes(int count) => new((_, _, output, _, ct) => File.WriteAllBytesAsync(output, new byte[count], ct)); private sealed class Remuxer(Func remux) : IPodcastReplayRemuxer {