Add frame-accurate server-side replay editing prototype
- ReplayEditPlan turns removed ranges into kept ranges (merge, clamp, reject empty, out-of-range, total or excessive removals). - FfmpegPodcastReplayEditor renders kept ranges with one accurate-seek FFmpeg input per range, concat and H.264/AAC re-encoding (faststart). - Share the FFmpeg runner (FfmpegProcess) with the replay remuxer. - Tests check exact kept frames, audio/video durations, faststart and quota, with and without a start offset. - Document the server prototype results in doc/video-edition.md. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
762fc35b9c
commit
d29124c527
8 changed files with 258 additions and 55 deletions
11
src/Yavsc.Server/Interfaces/IPodcastReplayEditor.cs
Normal file
11
src/Yavsc.Server/Interfaces/IPodcastReplayEditor.cs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
namespace Yavsc.Services;
|
||||
|
||||
public interface IPodcastReplayEditor
|
||||
{
|
||||
/// <summary>
|
||||
/// Renders the kept ranges of <paramref name="sourcePath"/> into a new MP4, cut at frame
|
||||
/// boundaries with audio cut at the same times.
|
||||
/// </summary>
|
||||
Task RenderAsync(string sourcePath, IReadOnlyList<ReplayRange> kept, bool hasAudio,
|
||||
string outputPath, long maxBytes, CancellationToken ct);
|
||||
}
|
||||
43
src/Yavsc.Server/Services/FfmpegPodcastReplayEditor.cs
Normal file
43
src/Yavsc.Server/Services/FfmpegPodcastReplayEditor.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
||||
public sealed class FfmpegPodcastReplayEditor(IOptions<PodcastOptions> options) : IPodcastReplayEditor
|
||||
{
|
||||
public Task RenderAsync(string sourcePath, IReadOnlyList<ReplayRange> 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<string> { "-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);
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
using System.Diagnostics;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
|
@ -15,64 +14,17 @@ public sealed class FfmpegPodcastReplayRemuxer(IOptions<PodcastOptions> 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<string> 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();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
62
src/Yavsc.Server/Services/FfmpegProcess.cs
Normal file
62
src/Yavsc.Server/Services/FfmpegProcess.cs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
using System.Diagnostics;
|
||||
|
||||
namespace Yavsc.Services;
|
||||
|
||||
internal static class FfmpegProcess
|
||||
{
|
||||
/// <summary>
|
||||
/// Runs FFmpeg with arguments passed without a shell and fails instead of leaving a partial,
|
||||
/// empty or oversized output.
|
||||
/// </summary>
|
||||
public static async Task RunAsync(string ffmpegPath, IEnumerable<string> 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<string> 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();
|
||||
}
|
||||
}
|
||||
44
src/Yavsc.Server/Services/ReplayEditPlan.cs
Normal file
44
src/Yavsc.Server/Services/ReplayEditPlan.cs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
namespace Yavsc.Services;
|
||||
|
||||
/// <summary>A half-open time range [StartMs, EndMs) in the original replay timeline.</summary>
|
||||
public readonly record struct ReplayRange(long StartMs, long EndMs)
|
||||
{
|
||||
public long DurationMs => EndMs - StartMs;
|
||||
}
|
||||
|
||||
public static class ReplayEditPlan
|
||||
{
|
||||
public const int MaxRemovedRanges = 200;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ReplayRange> KeptRanges(IEnumerable<ReplayRange> 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<ReplayRange>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<ArgumentException>(() => ReplayEditPlan.KeptRanges([new(0, 2000), new(2000, 5000)], 5000));
|
||||
Assert.Throws<ArgumentException>(() => ReplayEditPlan.KeptRanges([new(1000, 1000)], 5000));
|
||||
Assert.Throws<ArgumentException>(() => ReplayEditPlan.KeptRanges([new(5000, 6000)], 5000));
|
||||
Assert.Throws<ArgumentException>(() => 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<IOException>(() => 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<string, int, string, long, CancellationToken, Task> remux) : IPodcastReplayRemuxer
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue