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
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;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue