Add private replay draft for refined podcasts

Emissions opted into RefineReplay (ignored for OBS) get an owner-only
source.mp4 draft after the live or an interruption. The owner saves
revisioned marks and removed ranges, streams the source and queues an
idempotent publication; the worker renders or copies it within quota and
atomically replaces replay.mp4. Originals and drafts stay private until
publication, and the web catalogue shows "Replay en preparation".

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-16 14:22:14 +00:00
commit 46fc937443
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
22 changed files with 6069 additions and 40 deletions

View file

@ -6,6 +6,8 @@
### Added
* [Yavsc.Server/Podcasts] Add the private replay draft for emissions opted into refinement (`RefineReplay`, ignored for OBS; migration `PodcastRefineReplay` adds `LiveFlow.RefineReplay`). After the live, or after an interruption, the segments are remuxed into an owner-only `source.mp4` draft (`Preparing`, `Ready`, `Publishing`, `Failed`); the owner saves revisioned marks and removed ranges (`PUT podcasts/{id}/draft`, 409 on stale revision, marks inside removed ranges dropped), streams the source (`GET/HEAD podcasts/{id}/draft/source.mp4`) and queues an idempotent publication (`POST podcasts/{id}/draft/publish`). The worker renders or copies the source within quota and atomically replaces `replay.mp4`, keeping the previous replay on failure; re-edition is supported. Until publication, playlist and segments return 403 to other users, drafts are hidden from listeners, and the web catalogue shows "Replay en préparation". The FFmpeg editor now detects audio itself and keeps the last range open to the real end of the media.
* [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.

View file

@ -214,9 +214,54 @@ la durée est un réglage de l'auteur, de 0 à 365 jours. Une tâche de fond
supprime les brouillons et originaux expirés et prévient l'auteur dans
l'interface. Avec une durée de 0 jour, ils sont supprimés dès la publication du
MP4. Le MP4 publié n'est pas concerné, mais il ne peut plus être
réédité ensuite. Après publication, PostIt propose explicitement de supprimer
réédité ensuite. Le délai court à partir de la fin du direct (ou de son
interruption), même si aucun replay n'a été publié : un brouillon jamais publié
expire donc sans replay. À l'expiration, les segments originaux, la source
`source.mp4` et le brouillon sont tous supprimés. Après publication, PostIt propose explicitement de supprimer
le brouillon et les originaux.
#### Implémentation serveur du brouillon
Le brouillon privé est implémenté côté serveur ; l'éditeur PostIt reste à faire.
- **Option** : `RefineReplay` est accepté à la création d'un direct immédiat
et à la préparation d'une émission programmée (colonne `LiveFlow.RefineReplay`).
Il est ignoré pour une émission OBS.
- **États** (`PodcastResponse.Draft.State`) : `Preparing` (remux des segments
vers une source privée `source.mp4`), `Ready` (éditable), `Publishing`
(rendu en file), `Failed` (préparation de la source en échec, relançable par
`POST {id}/replay/retry`). Tant qu'aucune version n'est publiée,
`Replay.State` reste `Pending` : les auditeurs voient « Replay en préparation ».
- **Routes réservées à l'auteur** :
- `PUT podcasts/{id}/draft` enregistre marques (500 au plus) et plages
supprimées (200 au plus) pour la révision courante ; une révision périmée
renvoie 409, des plages ou marques hors de la durée renvoient 400.
Les marques sont dédoublonnées et triées ; celles situées dans une plage
supprimée disparaissent.
- `POST podcasts/{id}/draft/publish` (202) met en file la publication d'une
révision ; répéter la demande pour la même révision est sans effet.
- `GET`/`HEAD podcasts/{id}/draft/source.mp4` sert la source navigable, avec
requêtes de plages.
- **Publication** : sans plage supprimée, la source est copiée ; sinon elle est
découpée comme dans le prototype, la dernière plage conservée restant ouverte
jusqu'à la fin réelle du média. Le quota est vérifié en déduisant le MP4
précédemment publié ; le résultat est écrit en fichier temporaire puis
déplacé atomiquement sur `replay.mp4`. Un échec laisse le brouillon `Ready`
avec son erreur et l'éventuel replay publié intact. Une réédition sert
l'ancien MP4 jusqu'au remplacement ; `PublishedRevision` indique la
révision publiée.
- **Reprise** : préparations et publications en file reprennent après un
redémarrage du serveur. Une émission raffinée interrompue prépare
automatiquement son brouillon.
- **Visibilité** : après le direct, playlist et segments d'une émission
raffinée renvoient 403 aux autres utilisateurs, et le brouillon n'est
jamais exposé dans les listes ou détails destinés aux auditeurs. Le site web
affiche « Replay en préparation » jusqu'à la publication.
- **Limite connue** : la durée éditable est celle déclarée par les segments
(arrondie à la milliseconde supérieure).
- **Reste à faire** : rétention et suppression explicite des brouillons et
originaux, chapitres, client et éditeur PostIt.
Une émission interrompue doit rester récupérable par son auteur. Lorsqu'un
direct programmé s'arrête après le délai « Direct interrompu », ou qu'un
direct immédiat est interrompu, une émission optée pour le raffinage passe en
@ -314,7 +359,8 @@ différent de celui annoncé à l'auteur.
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.
la reprise après incident (fait côté serveur, voir « Implémentation serveur
du brouillon »), puis l'éditeur de marques et plages desktop.
4. Valider la finalisation sur de vrais médias synthétiques et conserver le
comportement existant pour les émissions sans raffinage.
5. Porter l'éditeur sur Android (surface native), en réutilisant l'API et le

View file

@ -14,11 +14,54 @@ public enum PodcastReplayState { Pending, Processing, Ready, Failed }
/// <summary>Persistent MP4 preparation result; source segments are retained.</summary>
public sealed record PodcastReplayResponse(PodcastReplayState State, long Bytes = 0, string? Error = null);
/// <summary>
/// Owner-only state of a refined replay: the private source is being prepared, can be edited,
/// is being rendered for publication, or could not be prepared.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter<PodcastDraftState>))]
public enum PodcastDraftState { Preparing, Ready, Publishing, Failed }
/// <summary>A removed half-open range [StartMs, EndMs) of the original replay timeline.</summary>
public sealed record PodcastDraftRange(long StartMs, long EndMs);
/// <summary>
/// Private editing state of a refined replay, visible to its owner only. Marks and ranges use the
/// timeline of the original source. <c>Revision</c> detects concurrent edits.
/// </summary>
public sealed record PodcastDraftResponse(
PodcastDraftState State, int Revision, IReadOnlyList<long> Marks,
IReadOnlyList<PodcastDraftRange> RemovedRanges, long SourceBytes = 0, string? Error = null)
{
/// <summary>Revision of the currently published MP4, if any.</summary>
public int? PublishedRevision { get; init; }
}
/// <summary>Replaces the marks and removed ranges of a refined replay draft.</summary>
public sealed record SavePodcastDraftRequest
{
/// <summary>Revision read by the client; a different current revision is a conflict.</summary>
[Range(0, int.MaxValue)]
public required int Revision { get; init; }
[MaxLength(500)]
public IReadOnlyList<long> Marks { get; init; } = [];
[MaxLength(200)]
public IReadOnlyList<PodcastDraftRange> RemovedRanges { get; init; } = [];
}
/// <summary>Publishes the saved draft revision as the replay MP4.</summary>
public sealed record PublishPodcastDraftRequest
{
[Range(0, int.MaxValue)]
public required int Revision { get; init; }
}
/// <summary>Creates an authenticated live broadcast with a retained replay.</summary>
public sealed record CreatePodcastRequest
{
[Required, StringLength(160, MinimumLength = 1)]
public required string Title { get; init; }
/// <summary>Keeps the replay private until its owner edits and publishes it.</summary>
public bool RefineReplay { get; init; }
}
/// <summary>Prepares or edits an emission before its manual start.</summary>
@ -31,6 +74,8 @@ public sealed record PreparePodcastRequest
public required int PlannedDurationMinutes { get; init; }
[StringLength(1023)]
public string? PublicAnnouncement { get; init; }
/// <summary>Keeps the replay private until its owner edits and publishes it. Ignored for OBS.</summary>
public bool RefineReplay { get; init; }
}
/// <summary>Public presentation only; never includes playback addresses or private metadata.</summary>
@ -49,6 +94,10 @@ public sealed record PodcastResponse(
public int? PlannedDurationMinutes { get; init; }
public string? PublicAnnouncement { get; init; }
public PodcastReplayResponse? Replay { get; init; }
/// <summary>The replay is published only after its owner edits and validates it.</summary>
public bool RefineReplay { get; init; }
/// <summary>Private draft of a refined replay; present for its owner only.</summary>
public PodcastDraftResponse? Draft { get; init; }
}
/// <summary>An independently decodable MPEG-TS HLS segment.</summary>

View file

@ -60,7 +60,8 @@ public sealed class PodcastController(ILiveProcessor processor, IPodcastSchedule
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
var response = await processor.CreateAsync(ownerId, User.Identity?.Name ?? ownerId, request.Title, ct);
var response = await processor.CreateAsync(ownerId, User.Identity?.Name ?? ownerId, request.Title, ct,
refineReplay: request.RefineReplay);
return CreatedAtAction(nameof(Get), new { id = response.Id }, response);
}
@ -131,7 +132,9 @@ public sealed class PodcastController(ILiveProcessor processor, IPodcastSchedule
[Produces("application/vnd.apple.mpegurl")]
public async Task<IActionResult> Playlist(Guid id, CancellationToken ct)
{
var manifest = await processor.GetAsync(id, ct);
var viewerId = User.GetUserId();
var manifest = await schedule.GetAsync(id, viewerId, ct);
PodcastVisibility.EnsureOriginalsVisible(manifest.Podcast, viewerId);
Response.Headers.CacheControl = "no-store";
var text = new StringBuilder("#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:15\n");
text.Append("#EXT-X-MEDIA-SEQUENCE:0\n#EXT-X-PLAYLIST-TYPE:EVENT\n");
@ -150,7 +153,49 @@ public sealed class PodcastController(ILiveProcessor processor, IPodcastSchedule
public async Task<IActionResult> Segment(Guid id, int sequence, CancellationToken ct)
{
Response.Headers.CacheControl = "private, no-store";
return File(await processor.OpenSegmentAsync(id, sequence, ct), "video/mp2t");
return File(await processor.OpenSegmentAsync(id, sequence, User.GetUserId(), ct), "video/mp2t");
}
/// <summary>Saves the marks and removed ranges of an owned refined replay draft.</summary>
/// <remarks>The request revision must match the current draft revision; otherwise 409 is returned.</remarks>
[HttpPut("{id:guid}/draft")]
[ProducesResponseType<PodcastResponse>(StatusCodes.Status200OK)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<ActionResult<PodcastResponse>> SaveDraft(Guid id, SavePodcastDraftRequest request, CancellationToken ct)
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
await processor.SaveDraftAsync(id, ownerId, request, ct);
return Ok((await schedule.GetAsync(id, ownerId, ct)).Podcast);
}
/// <summary>Queues the saved draft revision for rendering; the published MP4 is replaced atomically.</summary>
[HttpPost("{id:guid}/draft/publish")]
[ProducesResponseType<PodcastResponse>(StatusCodes.Status202Accepted)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<IActionResult> PublishDraft(Guid id, PublishPodcastDraftRequest request, CancellationToken ct)
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
await processor.PublishDraftAsync(id, ownerId, request.Revision, ct);
return AcceptedAtAction(nameof(Get), new { id }, (await schedule.GetAsync(id, ownerId, ct)).Podcast);
}
/// <summary>Serves the private seekable source of a refined replay to its owner, with byte ranges.</summary>
[HttpGet("{id:guid}/draft/source.mp4")]
[HttpHead("{id:guid}/draft/source.mp4")]
[Produces("video/mp4")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status206PartialContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<IActionResult> DraftSource(Guid id, CancellationToken ct)
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
Response.Headers.CacheControl = "private, no-store";
return File(await processor.OpenDraftSourceAsync(id, ownerId, ct), "video/mp4", enableRangeProcessing: true);
}
/// <summary>Deletes an ended broadcast and releases its owner's podcast quota.</summary>

View file

@ -3,7 +3,8 @@ using Yavsc.Services;
namespace Yavsc.Api.Services;
public sealed class PodcastReplayWorker(
ILiveProcessor processor, IPodcastReplayRemuxer remuxer, ILogger<PodcastReplayWorker> logger) : BackgroundService
ILiveProcessor processor, IPodcastReplayRemuxer remuxer, IPodcastReplayEditor editor,
ILogger<PodcastReplayWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
@ -12,6 +13,7 @@ public sealed class PodcastReplayWorker(
try
{
if (await processor.PrepareNextReplayAsync(remuxer, stoppingToken)) continue;
if (await processor.PublishNextDraftAsync(editor, stoppingToken)) continue;
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
catch (Exception ex)

View file

@ -58,6 +58,7 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
flow.ScheduledStartAt = request.ScheduledStartAt.ToUniversalTime();
flow.PlannedDurationMinutes = request.PlannedDurationMinutes;
flow.PublicAnnouncement = request.PublicAnnouncement?.Trim() ?? "";
flow.RefineReplay = request.RefineReplay;
await db.SaveChangesAsync(ct);
await db.Entry(flow).Reference(f => f.Owner).LoadAsync(ct);
return Planned(flow);
@ -87,7 +88,9 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
throw new PodcastException(409, "Cette emission est terminee. Preparez une nouvelle emission.");
if (flow.StartedAt != null && existing == null)
throw new PodcastException(404, "Les medias de cette emission sont introuvables.");
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id);
// OBS composes and finalizes its own content: refinement only applies to PostIt captures.
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id,
refineReplay: flow.RefineReplay && !obsConnectionId.HasValue);
flow.StartedAt ??= podcast.CreatedAt;
await db.SaveChangesAsync(ct);
return Enrich(podcast, flow);
@ -103,7 +106,8 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
.Where(f => f.PodcastId != null).ToListAsync(ct);
var byId = flows.ToDictionary(f => f.PodcastId!.Value);
var result = media.Where(p => !byId.TryGetValue(p.Id, out var f) || !f.PodcastDeleted)
.Select(p => byId.TryGetValue(p.Id, out var f) ? Enrich(p, f) : p).ToList();
.Select(p => PodcastVisibility.ForViewer(byId.TryGetValue(p.Id, out var f) ? Enrich(p, f) : p, ownerId))
.ToList();
var mediaIds = media.Select(p => p.Id).ToHashSet();
result.AddRange(flows.Where(f => !f.PodcastDeleted && f.StartedAt == null && f.OwnerId == ownerId
&& !mediaIds.Contains(f.PodcastId!.Value)).Select(Planned));
@ -113,13 +117,13 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
public async Task<PodcastManifestResponse> GetAsync(Guid id, string ownerId, CancellationToken ct)
{
var flow = await db.LiveFlow.AsNoTracking().Include(f => f.Owner).SingleOrDefaultAsync(f => f.PodcastId == id, ct);
if (flow == null) return await processor.GetAsync(id, ct);
if (flow == null) return PodcastVisibility.ForViewer(await processor.GetAsync(id, ct), ownerId);
if (flow.PodcastDeleted) throw new PodcastException(404, "Podcast introuvable.");
var podcast = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
if (podcast != null)
{
var manifest = await processor.GetAsync(id, ct);
return manifest with { Podcast = Enrich(manifest.Podcast, flow) };
return PodcastVisibility.ForViewer(manifest with { Podcast = Enrich(manifest.Podcast, flow) }, ownerId);
}
if (flow.OwnerId != ownerId || flow.StartedAt != null)
throw new PodcastException(404, "Podcast introuvable.");
@ -178,7 +182,10 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
private static PodcastResponse Planned(LiveFlow flow) => Enrich(new(
flow.PodcastId!.Value, flow.Title, flow.OwnerId, flow.Owner.UserName ?? flow.OwnerId,
flow.PreparedAt!.Value, flow.PreparedAt.Value, PodcastState.Planned, 0, 0, 0), flow);
flow.PreparedAt!.Value, flow.PreparedAt.Value, PodcastState.Planned, 0, 0, 0)
{
RefineReplay = flow.RefineReplay && flow.ObsKeyHash is null
}, flow);
private static PodcastResponse Enrich(PodcastResponse podcast, LiveFlow flow) => podcast with
{

View file

@ -14,6 +14,7 @@ public static class PodcastServiceCollectionExtensions
services.AddSingleton<ILiveProcessor, LiveProcessor>();
services.AddScoped<IPodcastScheduleService, PodcastScheduleService>();
services.AddSingleton<IPodcastReplayRemuxer, FfmpegPodcastReplayRemuxer>();
services.AddSingleton<IPodcastReplayEditor, FfmpegPodcastReplayEditor>();
services.AddHostedService<PodcastReplayWorker>();
services.AddOpenApi("podcasts", options => options.ShouldInclude = description => description.GroupName == "podcasts");
return services;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Yavsc.Migrations
{
/// <inheritdoc />
public partial class PodcastRefineReplay : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RefineReplay",
table: "LiveFlow",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RefineReplay",
table: "LiveFlow");
}
}
}

View file

@ -3244,6 +3244,9 @@ namespace Yavsc.Migrations
.HasMaxLength(1023)
.HasColumnType("character varying(1023)");
b.Property<bool>("RefineReplay")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("ScheduledStartAt")
.HasColumnType("timestamp with time zone");

View file

@ -53,7 +53,11 @@ else
{
<p>@Localizer["Debut prevu : {0} ; duree prevue : {1} min", podcast.ScheduledStartAt.Value.ToString("u"), podcast.PlannedDurationMinutes]</p>
}
@if (podcast.SegmentCount > 0)
@if (!ready && podcast.RefineReplay && podcast.State != PodcastState.Live)
{
<p class="alert alert-info">@Localizer["Replay en préparation."]</p>
}
else if (podcast.SegmentCount > 0)
{
<video controls playsinline preload="none" class="w-100"
aria-label="@podcast.Title" data-podcast-player

View file

@ -20,16 +20,22 @@ namespace Yavsc.Services
/// <returns></returns>
Task<bool> AcceptStream (HttpContext context, ApplicationUser user, string destDir, string fileName);
Task<PodcastResponse> CreateAsync(string ownerId, string ownerName, string title, CancellationToken ct, Guid? id = null);
Task<PodcastResponse> CreateAsync(string ownerId, string ownerName, string title, CancellationToken ct,
Guid? id = null, bool refineReplay = false);
Task<IReadOnlyList<PodcastResponse>> ListAsync(CancellationToken ct);
Task<PodcastManifestResponse> GetAsync(Guid id, CancellationToken ct);
Task<PodcastResponse> AppendAsync(Guid id, string ownerId, int sequence,
double durationSeconds, Stream input, CancellationToken ct);
Task<PodcastResponse> CompleteAsync(Guid id, string ownerId, CancellationToken ct);
Task<Stream> OpenSegmentAsync(Guid id, int sequence, CancellationToken ct);
/// <summary>Opens a segment; the originals of a refined emission are reserved to its owner after the live.</summary>
Task<Stream> OpenSegmentAsync(Guid id, int sequence, string? viewerId, CancellationToken ct);
Task<Stream> OpenReplayAsync(Guid id, CancellationToken ct);
Task<bool> PrepareNextReplayAsync(IPodcastReplayRemuxer remuxer, CancellationToken ct);
Task RetryReplayAsync(Guid id, string ownerId, CancellationToken ct);
Task<PodcastResponse> SaveDraftAsync(Guid id, string ownerId, SavePodcastDraftRequest request, CancellationToken ct);
Task<PodcastResponse> PublishDraftAsync(Guid id, string ownerId, int revision, CancellationToken ct);
Task<Stream> OpenDraftSourceAsync(Guid id, string ownerId, CancellationToken ct);
Task<bool> PublishNextDraftAsync(IPodcastReplayEditor editor, CancellationToken ct);
Task DeleteAsync(Guid id, string ownerId, CancellationToken ct);
}

View file

@ -4,8 +4,9 @@ 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.
/// boundaries with audio, if any, cut at the same times. A last range ending at
/// <see cref="ReplayRange.OpenEnd"/> runs to the end of the source.
/// </summary>
Task RenderAsync(string sourcePath, IReadOnlyList<ReplayRange> kept, bool hasAudio,
Task RenderAsync(string sourcePath, IReadOnlyList<ReplayRange> kept,
string outputPath, long maxBytes, CancellationToken ct);
}

View file

@ -15,6 +15,8 @@ namespace Yavsc.Models.Streaming
public DateTimeOffset? PreparedAt { get; set; }
public DateTimeOffset? StartedAt { get; set; }
public bool PodcastDeleted { get; set; }
/// <summary>Keeps the replay private until its owner edits and publishes it; ignored for OBS.</summary>
public bool RefineReplay { get; set; }
[MaxLength(64), System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
public string? ObsKeyHash { get; set; }
[System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]

View file

@ -6,16 +6,19 @@ namespace Yavsc.Services;
public sealed class FfmpegPodcastReplayEditor(IOptions<PodcastOptions> options) : IPodcastReplayEditor
{
public Task RenderAsync(string sourcePath, IReadOnlyList<ReplayRange> kept, bool hasAudio,
public async Task RenderAsync(string sourcePath, IReadOnlyList<ReplayRange> kept,
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))
if (kept[i].StartMs < 0 || kept[i].DurationMs <= 0 || (i > 0 && kept[i].StartMs < kept[i - 1].EndMs)
|| (kept[i].EndMs == ReplayRange.OpenEnd && i != kept.Count - 1))
throw new ArgumentException("Les plages conservées doivent être ordonnées et disjointes.", nameof(kept));
var hasAudio = await FfmpegProcess.HasAudioAsync(options.Value.FfmpegPath, sourcePath, ct);
// 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
@ -25,7 +28,9 @@ public sealed class FfmpegPodcastReplayEditor(IOptions<PodcastOptions> options)
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]);
arguments.AddRange(["-ss", Seconds(kept[i].StartMs)]);
if (kept[i].EndMs != ReplayRange.OpenEnd) arguments.AddRange(["-to", Seconds(kept[i].EndMs)]);
arguments.AddRange(["-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]");
@ -35,7 +40,7 @@ public sealed class FfmpegPodcastReplayEditor(IOptions<PodcastOptions> options)
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);
await FfmpegProcess.RunAsync(options.Value.FfmpegPath, arguments, null, outputPath, maxBytes, ct);
}
private static string Seconds(long milliseconds)

View file

@ -50,6 +50,36 @@ internal static class FfmpegProcess
}
}
/// <summary>Reports whether a local media file has an audio stream, by decoding one audio frame.</summary>
public static async Task<bool> HasAudioAsync(string ffmpegPath, string sourcePath, CancellationToken ct)
{
var start = new ProcessStartInfo(ffmpegPath)
{
UseShellExecute = false,
RedirectStandardError = true,
CreateNoWindow = true
};
foreach (var argument in new[] { "-nostdin", "-hide_banner", "-loglevel", "error", "-i", sourcePath,
"-map", "0:a:0", "-frames:a", "1", "-f", "null", "-" })
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
{
await process.WaitForExitAsync(ct);
await errors;
return process.ExitCode == 0;
}
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();

View file

@ -16,6 +16,9 @@ namespace Yavsc.Services;
public sealed class LiveProcessor : ILiveProcessor, IDisposable
{
private sealed record Document(PodcastManifestResponse Manifest, string[] Hashes);
private const string ReplayFileName = "replay.mp4";
private const string SourceFileName = "source.mp4";
public const int MaxDraftMarks = 500;
private readonly ILogger<LiveProcessor> _logger;
private readonly PodcastOptions _options;
private readonly TimeProvider _clock;
@ -41,7 +44,8 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
throw new InvalidOperationException("Invalid Podcast storage options.");
}
public async Task<PodcastResponse> CreateAsync(string ownerId, string ownerName, string title, CancellationToken ct, Guid? id = null)
public async Task<PodcastResponse> CreateAsync(string ownerId, string ownerName, string title, CancellationToken ct,
Guid? id = null, bool refineReplay = false)
{
if (string.IsNullOrWhiteSpace(ownerId) || string.IsNullOrWhiteSpace(title) || title.Trim().Length > 160)
throw new PodcastException(400, "Un titre de 1 a 160 caracteres et un utilisateur sont requis.");
@ -64,7 +68,7 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
throw new PodcastException(413, "Nombre maximal de podcasts atteint. Supprimez un ancien replay.");
var now = _clock.GetUtcNow();
var podcast = new PodcastResponse(id ?? Guid.NewGuid(), title.Trim(), ownerId, ownerName,
now, now, PodcastState.Live, 0, 0, 0);
now, now, PodcastState.Live, 0, 0, 0) { RefineReplay = refineReplay };
var document = new Document(new(podcast, Array.Empty<PodcastSegmentResponse>()), Array.Empty<string>());
Directory.CreateDirectory(DirectoryFor(podcast.Id));
await SaveAsync(document, ct);
@ -196,7 +200,8 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
var updated = podcast with
{
State = PodcastState.Completed, UpdatedAt = _clock.GetUtcNow(),
Replay = new(PodcastReplayState.Pending)
Replay = podcast.Replay ?? new(PodcastReplayState.Pending),
Draft = podcast.RefineReplay ? podcast.Draft ?? NewDraft() : null
};
await SaveAsync(document with { Manifest = document.Manifest with { Podcast = updated } }, ct);
_logger.LogInformation("Podcast {PodcastId} completed with {Segments} segments", id, updated.SegmentCount);
@ -214,7 +219,7 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
var podcast = Find(id).Manifest.Podcast;
if (podcast.State != PodcastState.Completed || podcast.Replay?.State != PodcastReplayState.Ready)
throw new PodcastException(409, "Le replay MP4 n'est pas disponible.");
return new FileStream(Path.Combine(DirectoryFor(id), "replay.mp4"), FileMode.Open, FileAccess.Read,
return new FileStream(Path.Combine(DirectoryFor(id), ReplayFileName), FileMode.Open, FileAccess.Read,
FileShare.Read | FileShare.Delete, 64 * 1024, FileOptions.Asynchronous | FileOptions.RandomAccess);
}
finally { _gate.Release(); }
@ -227,7 +232,15 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
{
await LoadAsync(ct);
var document = Owned(id, ownerId);
if (document.Manifest.Podcast.Replay?.State != PodcastReplayState.Failed)
var podcast = document.Manifest.Podcast;
if (podcast.RefineReplay)
{
if (podcast.Draft?.State != PodcastDraftState.Failed)
throw new PodcastException(409, "Seule une source de brouillon en echec peut etre relancee.");
await SetDraftAsync(document, podcast.Draft with { State = PodcastDraftState.Preparing, Error = null }, ct);
return;
}
if (podcast.Replay?.State != PodcastReplayState.Failed)
throw new PodcastException(409, "Seul un replay en echec peut etre relance.");
await SetReplayAsync(document, new(PodcastReplayState.Pending), ct);
}
@ -249,20 +262,23 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
try
{
await LoadAsync(ct);
var next = _documents.Values.Where(d => d.Manifest.Podcast.State == PodcastState.Completed
&& d.Manifest.Podcast.Replay?.State == PodcastReplayState.Pending)
var next = _documents.Values.Where(d => IsRemuxQueued(d.Manifest.Podcast))
.OrderBy(d => d.Manifest.Podcast.CreatedAt).FirstOrDefault();
if (next is null) return false;
document = next;
allowance = _options.MaxOwnerBytes - OwnerBytes(document.Manifest.Podcast.OwnerId);
await SetReplayAsync(document, new(PodcastReplayState.Processing), ct);
if (!document.Manifest.Podcast.RefineReplay)
await SetReplayAsync(document, new(PodcastReplayState.Processing), ct);
_preparingReplay = document.Manifest.Podcast.Id;
}
finally { _gate.Release(); }
var id = document.Manifest.Podcast.Id;
var directory = DirectoryFor(id);
var temporary = Path.Combine(directory, "replay.tmp.mp4");
// A refined replay is first remuxed into a private, seekable editing source.
var refine = document.Manifest.Podcast.RefineReplay;
var target = Path.Combine(directory, refine ? SourceFileName : ReplayFileName);
var temporary = Path.Combine(directory, refine ? "source.tmp.mp4" : "replay.tmp.mp4");
try
{
if (allowance <= 1) throw new IOException("Quota de stockage des podcasts atteint.");
@ -278,10 +294,20 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
var podcast = current.Manifest.Podcast;
if (OwnerBytes(podcast.OwnerId) + bytes > _options.MaxOwnerBytes)
throw new IOException("Quota de stockage des podcasts atteint.");
File.Move(temporary, Path.Combine(directory, "replay.mp4"), overwrite: true);
var updated = podcast with { Bytes = podcast.Bytes + bytes, Replay = new(PodcastReplayState.Ready, bytes) };
File.Move(temporary, target, overwrite: true);
var updated = refine
? podcast with
{
Bytes = podcast.Bytes + bytes,
Draft = (podcast.Draft ?? NewDraft()) with
{
State = PodcastDraftState.Ready, SourceBytes = bytes, Error = null
}
}
: podcast with { Bytes = podcast.Bytes + bytes, Replay = new(PodcastReplayState.Ready, bytes) };
await SaveAsync(current with { Manifest = current.Manifest with { Podcast = updated } }, ct);
_logger.LogInformation("Podcast {PodcastId} MP4 ready ({Bytes} bytes)", id, bytes);
_logger.LogInformation("Podcast {PodcastId} {Kind} ready ({Bytes} bytes)", id,
refine ? "draft source" : "MP4", bytes);
}
finally { _gate.Release(); }
}
@ -289,11 +315,23 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
{
_logger.LogError(ex, "Podcast {PodcastId} MP4 preparation failed", id);
File.Delete(temporary);
File.Delete(Path.Combine(directory, "replay.mp4"));
File.Delete(target);
await _gate.WaitAsync(CancellationToken.None);
try
{
var current = Find(id);
if (refine)
{
var draft = current.Manifest.Podcast.Draft ?? NewDraft();
if (!ct.IsCancellationRequested)
await SetDraftAsync(current, draft with
{
State = PodcastDraftState.Failed, Error =
"Preparation de la source impossible. L'auteur peut relancer la preparation."
}, CancellationToken.None);
if (ct.IsCancellationRequested) throw;
return true;
}
var replay = ct.IsCancellationRequested
? new PodcastReplayResponse(PodcastReplayState.Pending)
: new PodcastReplayResponse(PodcastReplayState.Failed, Error:
@ -318,13 +356,217 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
Manifest = document.Manifest with { Podcast = document.Manifest.Podcast with { Replay = replay } }
}, ct);
public async Task<Stream> OpenSegmentAsync(Guid id, int sequence, CancellationToken ct)
private Task SetDraftAsync(Document document, PodcastDraftResponse draft, CancellationToken ct)
=> SaveAsync(document with
{
Manifest = document.Manifest with { Podcast = document.Manifest.Podcast with { Draft = draft } }
}, ct);
private static PodcastDraftResponse NewDraft() => new(PodcastDraftState.Preparing, 0, [], []);
private static bool IsRemuxQueued(PodcastResponse podcast) => podcast.RefineReplay
? podcast.Draft?.State == PodcastDraftState.Preparing
: podcast.State == PodcastState.Completed && podcast.Replay?.State == PodcastReplayState.Pending;
private static long SourceDurationMs(PodcastResponse podcast)
=> (long)Math.Ceiling(podcast.DurationSeconds * 1000);
private Document EditableDraft(Guid id, string ownerId, int revision)
{
var document = Owned(id, ownerId);
var draft = document.Manifest.Podcast.Draft;
if (!document.Manifest.Podcast.RefineReplay || draft is null)
throw new PodcastException(409, "Ce replay n'est pas en cours de raffinage.");
if (draft.State != PodcastDraftState.Ready)
throw new PodcastException(409, "Le brouillon n'est pas modifiable pendant la preparation ou la publication.");
if (draft.Revision != revision)
throw new PodcastException(409, "Le brouillon a ete modifie ailleurs. Rechargez-le avant de continuer.");
return document;
}
public async Task<PodcastResponse> SaveDraftAsync(Guid id, string ownerId, SavePodcastDraftRequest request, CancellationToken ct)
{
if (request.Marks.Count > MaxDraftMarks)
throw new PodcastException(400, $"Au plus {MaxDraftMarks} marques sont autorisees.");
await _gate.WaitAsync(ct);
try
{
await LoadAsync(ct);
var document = EditableDraft(id, ownerId, request.Revision);
var podcast = document.Manifest.Podcast;
var duration = SourceDurationMs(podcast);
var removed = request.RemovedRanges.Select(r => new ReplayRange(r.StartMs, r.EndMs)).ToArray();
try { _ = ReplayEditPlan.KeptRanges(removed, duration); }
catch (ArgumentException ex) { throw new PodcastException(400, ex.Message.Split(" (Parameter")[0]); }
if (request.Marks.Any(m => m < 0 || m > duration))
throw new PodcastException(400, "Une marque est en dehors de la video.");
// A mark inside a removed passage disappears with it.
var marks = request.Marks.Distinct().Order()
.Where(m => !removed.Any(r => m >= r.StartMs && m < r.EndMs)).ToArray();
var ranges = request.RemovedRanges.OrderBy(r => r.StartMs).ThenBy(r => r.EndMs).ToArray();
var draft = podcast.Draft! with
{
Revision = podcast.Draft!.Revision + 1, Marks = marks, RemovedRanges = ranges, Error = null
};
await SetDraftAsync(document, draft, ct);
return _documents[id].Manifest.Podcast;
}
finally { _gate.Release(); }
}
public async Task<PodcastResponse> PublishDraftAsync(Guid id, string ownerId, int revision, CancellationToken ct)
{
await _gate.WaitAsync(ct);
try
{
await LoadAsync(ct);
var current = Owned(id, ownerId).Manifest.Podcast;
if (current.Draft is { State: PodcastDraftState.Publishing } publishing && publishing.Revision == revision)
return current;
var document = EditableDraft(id, ownerId, revision);
var podcast = document.Manifest.Podcast;
if (podcast.Draft!.PublishedRevision == revision && podcast.Replay?.State == PodcastReplayState.Ready)
return podcast;
await SetDraftAsync(document, podcast.Draft with { State = PodcastDraftState.Publishing, Error = null }, ct);
_logger.LogInformation("Podcast {PodcastId} draft revision {Revision} queued for publication", id, revision);
return _documents[id].Manifest.Podcast;
}
finally { _gate.Release(); }
}
public async Task<Stream> OpenDraftSourceAsync(Guid id, string ownerId, CancellationToken ct)
{
await _gate.WaitAsync(ct);
try
{
await LoadAsync(ct);
var draft = Owned(id, ownerId).Manifest.Podcast.Draft;
if (draft is null || draft.SourceBytes <= 0)
throw new PodcastException(409, "La source du brouillon n'est pas disponible.");
return new FileStream(Path.Combine(DirectoryFor(id), SourceFileName), FileMode.Open, FileAccess.Read,
FileShare.Read | FileShare.Delete, 64 * 1024, FileOptions.Asynchronous | FileOptions.RandomAccess);
}
finally { _gate.Release(); }
}
public async Task<bool> PublishNextDraftAsync(IPodcastReplayEditor editor, CancellationToken ct)
{
await _replays.WaitAsync(ct);
try { return await PublishDraftAsync(editor, ct); }
finally { _replays.Release(); }
}
private async Task<bool> PublishDraftAsync(IPodcastReplayEditor editor, CancellationToken ct)
{
PodcastResponse podcast;
long allowance;
await _gate.WaitAsync(ct);
try
{
await LoadAsync(ct);
var next = _documents.Values.Where(d => d.Manifest.Podcast.Draft?.State == PodcastDraftState.Publishing)
.OrderBy(d => d.Manifest.Podcast.CreatedAt).FirstOrDefault();
if (next is null) return false;
podcast = next.Manifest.Podcast;
// The published MP4 is replaced, so its bytes are available for the new version.
allowance = _options.MaxOwnerBytes - OwnerBytes(podcast.OwnerId) + PublishedBytes(podcast);
_preparingReplay = podcast.Id;
}
finally { _gate.Release(); }
var id = podcast.Id;
var draft = podcast.Draft!;
var directory = DirectoryFor(id);
var source = Path.Combine(directory, SourceFileName);
var temporary = Path.Combine(directory, "replay.tmp.mp4");
try
{
if (allowance <= 1) throw new IOException("Quota de stockage des podcasts atteint.");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(_options.ReplayTimeoutSeconds));
if (draft.RemovedRanges.Count == 0)
{
if (draft.SourceBytes > allowance) throw new IOException("Quota de stockage des podcasts atteint.");
await using var input = File.OpenRead(source);
await using var output = File.Create(temporary);
await input.CopyToAsync(output, timeout.Token);
}
else
{
var duration = SourceDurationMs(podcast);
var kept = ReplayEditPlan.KeptRanges(
draft.RemovedRanges.Select(r => new ReplayRange(r.StartMs, r.EndMs)), duration).ToArray();
// The declared segment durations may be slightly shorter than the media: keep its tail.
if (kept[^1].EndMs == duration) kept[^1] = kept[^1] with { EndMs = ReplayRange.OpenEnd };
await editor.RenderAsync(source, kept, temporary, allowance, timeout.Token);
}
var bytes = new FileInfo(temporary).Length;
if (bytes <= 0 || bytes > allowance) throw new IOException("Taille du MP4 invalide ou quota atteint.");
await _gate.WaitAsync(ct);
try
{
var current = Find(id);
var latest = current.Manifest.Podcast;
var previous = PublishedBytes(latest);
if (OwnerBytes(latest.OwnerId) - previous + bytes > _options.MaxOwnerBytes)
throw new IOException("Quota de stockage des podcasts atteint.");
// Readers of the previous version keep their open file; new requests get the new one.
File.Move(temporary, Path.Combine(directory, ReplayFileName), overwrite: true);
var updated = latest with
{
Bytes = latest.Bytes - previous + bytes,
Replay = new(PodcastReplayState.Ready, bytes),
Draft = latest.Draft! with
{
State = PodcastDraftState.Ready, PublishedRevision = draft.Revision, Error = null
}
};
await SaveAsync(current with { Manifest = current.Manifest with { Podcast = updated } }, ct);
_logger.LogInformation("Podcast {PodcastId} draft revision {Revision} published ({Bytes} bytes)",
id, draft.Revision, bytes);
}
finally { _gate.Release(); }
}
catch (Exception ex)
{
_logger.LogError(ex, "Podcast {PodcastId} draft publication failed", id);
File.Delete(temporary);
if (!ct.IsCancellationRequested)
{
await _gate.WaitAsync(CancellationToken.None);
try
{
var current = Find(id);
await SetDraftAsync(current, current.Manifest.Podcast.Draft! with
{
State = PodcastDraftState.Ready, Error =
"Publication impossible. Le brouillon est conserve ; corrigez-le ou relancez la publication."
}, CancellationToken.None);
}
finally { _gate.Release(); }
}
if (ct.IsCancellationRequested) throw;
}
finally
{
await _gate.WaitAsync(CancellationToken.None);
try { _preparingReplay = null; }
finally { _gate.Release(); }
}
return true;
}
private static long PublishedBytes(PodcastResponse podcast)
=> podcast.Replay?.State == PodcastReplayState.Ready ? podcast.Replay.Bytes : 0;
public async Task<Stream> OpenSegmentAsync(Guid id, int sequence, string? viewerId, CancellationToken ct)
{
await _gate.WaitAsync(ct);
try
{
await LoadAsync(ct);
var document = Find(id);
PodcastVisibility.EnsureOriginalsVisible(document.Manifest.Podcast, viewerId);
if (sequence < 0 || sequence >= document.Manifest.Segments.Count)
throw new PodcastException(404, "Segment introuvable.");
return new FileStream(SegmentPath(id, sequence), FileMode.Open, FileAccess.Read,
@ -387,6 +629,12 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
private async Task InterruptAsync(Document document, CancellationToken ct)
{
var podcast = document.Manifest.Podcast with { State = PodcastState.Interrupted, UpdatedAt = _clock.GetUtcNow() };
// A refined emission stays recoverable by its owner: prepare its private draft as after a normal end.
if (podcast.RefineReplay)
podcast = podcast with
{
Replay = podcast.Replay ?? new(PodcastReplayState.Pending), Draft = podcast.Draft ?? NewDraft()
};
await SaveAsync(document with { Manifest = document.Manifest with { Podcast = podcast } }, ct);
_logger.LogWarning("Podcast {PodcastId} interrupted; committed segments remain playable", podcast.Id);
}

View file

@ -0,0 +1,29 @@
using Yavsc.Abstract.Streaming;
namespace Yavsc.Services;
/// <summary>
/// After the live of a refined emission, its original segments and draft are reserved to its owner
/// until the edited MP4 is published; the published MP4 is the only listener-visible replay.
/// </summary>
public static class PodcastVisibility
{
public static bool OriginalsArePrivate(PodcastResponse podcast)
=> podcast.RefineReplay && podcast.State != PodcastState.Live;
public static PodcastResponse ForViewer(PodcastResponse podcast, string? viewerId)
=> podcast.OwnerId == viewerId ? podcast : podcast with { Draft = null };
public static PodcastManifestResponse ForViewer(PodcastManifestResponse manifest, string? viewerId)
=> manifest.Podcast.OwnerId == viewerId ? manifest : manifest with
{
Podcast = ForViewer(manifest.Podcast, viewerId),
Segments = OriginalsArePrivate(manifest.Podcast) ? [] : manifest.Segments
};
public static void EnsureOriginalsVisible(PodcastResponse podcast, string? viewerId)
{
if (OriginalsArePrivate(podcast) && podcast.OwnerId != viewerId)
throw new PodcastException(403, "Les originaux de cette emission sont reserves a son auteur.");
}
}

View file

@ -3,6 +3,8 @@ 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)
{
/// <summary>End of a kept range that runs to the end of the source.</summary>
public const long OpenEnd = long.MaxValue;
public long DurationMs => EndMs - StartMs;
}

View file

@ -54,7 +54,7 @@ public sealed class LiveProcessorTests : IDisposable
Assert.Equal("Concert", manifest.Podcast.Title);
Assert.Equal(PodcastState.Completed, manifest.Podcast.State);
Assert.Equal(new[] { 0, 1 }, manifest.Segments.Select(s => s.Sequence));
await using var stream = await restored.OpenSegmentAsync(podcast.Id, 1, _ct);
await using var stream = await restored.OpenSegmentAsync(podcast.Id, 1, null, _ct);
using var actual = new MemoryStream();
await stream.CopyToAsync(actual, _ct);
Assert.Equal(second, actual.ToArray());
@ -165,7 +165,7 @@ public sealed class LiveProcessorTests : IDisposable
var replay = await restarted.GetAsync(second.Id, _ct);
Assert.Equal(PodcastState.Interrupted, replay.Podcast.State);
Assert.Single(replay.Segments);
await using var segment = await restarted.OpenSegmentAsync(second.Id, 0, _ct);
await using var segment = await restarted.OpenSegmentAsync(second.Id, 0, null, _ct);
Assert.Equal(376, segment.Length);
}

View file

@ -141,6 +141,107 @@ public sealed class PodcastControllerTests(ApiWebServerFixture fixture) : IClass
}
}
[Fact]
public async Task Refined_replay_originals_and_draft_are_owner_only_until_the_edited_MP4_is_published()
{
using var owner = Client($"refine-owner-{Guid.NewGuid():N}");
using var listener = Client("refine-listener");
var directory = Path.Combine(Path.GetTempPath(), $"yavsc-http-refine-{Guid.NewGuid():N}");
string? path = null;
try
{
var files = await PodcastMediaFixture.CreateAsync(directory, _ct);
using var created = await owner.PostAsJsonAsync("/api/v1/podcasts",
new CreatePodcastRequest { Title = "Refined", RefineReplay = true }, _ct);
var podcast = await created.Content.ReadFromJsonAsync<PodcastResponse>(_ct);
Assert.True(podcast!.RefineReplay);
path = $"/api/v1/podcasts/{podcast.Id}";
for (var i = 0; i < files.Length; i++)
{
using var content = new ByteArrayContent(await File.ReadAllBytesAsync(files[i], _ct));
content.Headers.ContentType = new MediaTypeHeaderValue("video/mp2t");
using var appended = await owner.PutAsync($"{path}/segments/{i}?duration=1", content, _ct);
appended.EnsureSuccessStatusCode();
}
Assert.Contains("segments/0.ts", await listener.GetStringAsync($"{path}/index.m3u8", _ct));
using (var completed = await owner.PostAsync($"{path}/complete", null, _ct))
completed.EnsureSuccessStatusCode();
var draft = await WaitDraftAsync(owner, path, PodcastDraftState.Ready);
var seen = await listener.GetFromJsonAsync<PodcastManifestResponse>(path, _ct);
Assert.Equal(PodcastReplayState.Pending, seen!.Podcast.Replay?.State);
Assert.Null(seen.Podcast.Draft);
Assert.Empty(seen.Segments);
Assert.Null((await listener.GetFromJsonAsync<PodcastResponse[]>("/api/v1/podcasts", _ct))!
.Single(p => p.Id == podcast.Id).Draft);
foreach (var hidden in new[] { "index.m3u8", "segments/0.ts", "draft/source.mp4" })
{
using var denied = await listener.GetAsync($"{path}/{hidden}", _ct);
Assert.Equal(HttpStatusCode.Forbidden, denied.StatusCode);
}
using (var replay = await listener.GetAsync($"{path}/replay.mp4", _ct))
Assert.Equal(HttpStatusCode.Conflict, replay.StatusCode);
using (var request = new HttpRequestMessage(HttpMethod.Get, $"{path}/draft/source.mp4"))
{
request.Headers.Range = new RangeHeaderValue(0, 7);
using var source = await owner.SendAsync(request, _ct);
Assert.Equal(HttpStatusCode.PartialContent, source.StatusCode);
Assert.Equal($"bytes 0-7/{draft.Draft!.SourceBytes}", source.Content.Headers.ContentRange?.ToString());
}
using (var denied = await listener.PutAsJsonAsync($"{path}/draft",
new SavePodcastDraftRequest { Revision = 0 }, _ct))
Assert.Equal(HttpStatusCode.Forbidden, denied.StatusCode);
using (var invalid = await owner.PutAsJsonAsync($"{path}/draft", new SavePodcastDraftRequest
{ Revision = 0, RemovedRanges = [new(2000, 1000)] }, _ct))
Assert.Equal(HttpStatusCode.BadRequest, invalid.StatusCode);
using (var saved = await owner.PutAsJsonAsync($"{path}/draft", new SavePodcastDraftRequest
{ Revision = 0, Marks = [1000, 2500], RemovedRanges = [new(1000, 2000)] }, _ct))
{
Assert.Equal(HttpStatusCode.OK, saved.StatusCode);
Assert.Equal(1, (await saved.Content.ReadFromJsonAsync<PodcastResponse>(_ct))!.Draft!.Revision);
}
using (var stale = await owner.PutAsJsonAsync($"{path}/draft", new SavePodcastDraftRequest { Revision = 0 }, _ct))
Assert.Equal(HttpStatusCode.Conflict, stale.StatusCode);
using (var publish = await owner.PostAsJsonAsync($"{path}/draft/publish",
new PublishPodcastDraftRequest { Revision = 1 }, _ct))
Assert.Equal(HttpStatusCode.Accepted, publish.StatusCode);
var ready = await WaitReplayAsync(listener, path, PodcastReplayState.Ready);
Assert.Null(ready.Draft);
var mp4 = await listener.GetByteArrayAsync($"{path}/replay.mp4", _ct);
Assert.Equal(ready.Replay!.Bytes, mp4.LongLength);
var mp4Path = Path.Combine(directory, "published.mp4");
await File.WriteAllBytesAsync(mp4Path, mp4, _ct);
var duration = double.Parse((await PodcastMediaFixture.RunAsync("ffprobe", ["-v", "error",
"-show_entries", "format=duration", "-of", "csv=p=0", mp4Path], _ct)).Trim(),
System.Globalization.CultureInfo.InvariantCulture);
Assert.InRange(duration, 2.8, 3.2); // One of the four seconds was removed.
using (var denied = await listener.GetAsync($"{path}/segments/0.ts", _ct))
Assert.Equal(HttpStatusCode.Forbidden, denied.StatusCode);
var published = (await owner.GetFromJsonAsync<PodcastManifestResponse>(path, _ct))!.Podcast;
Assert.Equal(1, published.Draft!.PublishedRevision);
Assert.Equal([2500L], published.Draft.Marks);
}
finally
{
if (path is not null) using (await owner.DeleteAsync(path, _ct)) { }
if (Directory.Exists(directory)) Directory.Delete(directory, true);
}
}
private async Task<PodcastResponse> WaitDraftAsync(HttpClient client, string path, PodcastDraftState expected)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_ct);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
while (true)
{
var manifest = await client.GetFromJsonAsync<PodcastManifestResponse>(path, timeout.Token);
if (manifest!.Podcast.Draft?.State == expected) return manifest.Podcast;
Assert.NotEqual(PodcastDraftState.Failed, manifest.Podcast.Draft?.State);
await Task.Delay(100, timeout.Token);
}
}
private async Task<PodcastResponse> WaitReplayAsync(HttpClient client, string path, PodcastReplayState expected)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_ct);

View file

@ -62,7 +62,7 @@ public sealed class PodcastReplayTests : IDisposable
mp4.Position = 2;
Assert.Equal(3, mp4.ReadByte());
}
await using (var ts = await restored.OpenSegmentAsync(podcast.Id, 0, _ct))
await using (var ts = await restored.OpenSegmentAsync(podcast.Id, 0, "alice", _ct))
Assert.Equal(podcast.Bytes, ts.Length);
await restored.DeleteAsync(podcast.Id, "alice", _ct);
Assert.False(Directory.Exists(Path.Combine(_root, podcast.Id.ToString("N"))));
@ -224,11 +224,12 @@ public sealed class PodcastReplayTests : IDisposable
"-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 kept = ReplayEditPlan.KeptRanges([new(1000, 1600), new(2400, 3000)], 4000).ToArray();
kept[^1] = kept[^1] with { EndMs = ReplayRange.OpenEnd };
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);
await editor.RenderAsync(source, kept, output, 10_000_000, _ct);
var frames = Path.Combine(_root, "edited.yuv");
await PodcastMediaFixture.RunAsync("ffmpeg",
@ -252,11 +253,182 @@ public sealed class PodcastReplayTests : IDisposable
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,
await Assert.ThrowsAsync<IOException>(() => editor.RenderAsync(source, kept,
Path.Combine(_root, "too-big.mp4"), 10, _ct));
}
[Fact]
public async Task Ffmpeg_editor_detects_a_source_without_audio()
{
Directory.CreateDirectory(_root);
var source = Path.Combine(_root, "silent.mp4");
await PodcastMediaFixture.RunAsync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "testsrc2=s=32x32:r=10:d=2",
"-c:v", "libx264", source], _ct);
var output = Path.Combine(_root, "silent-edited.mp4");
await new FfmpegPodcastReplayEditor(Options.Create(new PodcastOptions())).RenderAsync(source,
[new(0, 500), new(1000, ReplayRange.OpenEnd)], output, 10_000_000, _ct);
var probe = await PodcastMediaFixture.RunAsync("ffprobe",
["-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", output], _ct);
Assert.Equal("video", probe.Trim());
}
private async Task<PodcastResponse> Refined(LiveProcessor processor, int sourceBytes = 10)
{
var podcast = await processor.CreateAsync("alice", "alice", "Refined", _ct, refineReplay: true);
await processor.AppendAsync(podcast.Id, "alice", 0, 2, new MemoryStream(LiveProcessorTests.Packets()), _ct);
await processor.AppendAsync(podcast.Id, "alice", 1, 2, new MemoryStream(LiveProcessorTests.Packets()), _ct);
var completed = await processor.CompleteAsync(podcast.Id, "alice", _ct);
Assert.Equal(PodcastReplayState.Pending, completed.Replay?.State);
Assert.Equal(PodcastDraftState.Preparing, completed.Draft?.State);
Assert.True(await processor.PrepareNextReplayAsync(Bytes(sourceBytes), _ct));
return (await processor.GetAsync(podcast.Id, _ct)).Podcast;
}
private static SavePodcastDraftRequest Save(int revision, long[] marks, params PodcastDraftRange[] removed)
=> new() { Revision = revision, Marks = marks, RemovedRanges = removed };
[Fact]
public async Task Refined_replay_stays_private_until_the_saved_draft_is_published_and_republished()
{
var processor = New();
var podcast = await Refined(processor);
var directory = Path.Combine(_root, podcast.Id.ToString("N"));
Assert.Equal(PodcastDraftState.Ready, podcast.Draft?.State);
Assert.Equal(10, podcast.Draft!.SourceBytes);
Assert.True(File.Exists(Path.Combine(directory, "source.mp4")));
Assert.False(File.Exists(Path.Combine(directory, "replay.mp4")));
var segmentsBytes = podcast.Bytes - 10;
Assert.False(await processor.PrepareNextReplayAsync(Bytes(4), _ct));
Assert.False(await processor.PublishNextDraftAsync(new Editor((_, _, _, _, _) => Task.CompletedTask), _ct));
Assert.Equal(409, (await Assert.ThrowsAsync<PodcastException>(
() => processor.OpenReplayAsync(podcast.Id, _ct))).StatusCode);
Assert.Equal(403, (await Assert.ThrowsAsync<PodcastException>(
() => processor.OpenSegmentAsync(podcast.Id, 0, "bob", _ct))).StatusCode);
Assert.Equal(403, (await Assert.ThrowsAsync<PodcastException>(
() => processor.OpenDraftSourceAsync(podcast.Id, "bob", _ct))).StatusCode);
var hidden = PodcastVisibility.ForViewer(await processor.GetAsync(podcast.Id, _ct), "bob");
Assert.Null(hidden.Podcast.Draft);
Assert.Empty(hidden.Segments);
await using (await processor.OpenSegmentAsync(podcast.Id, 0, "alice", _ct)) { }
await using (var source = await processor.OpenDraftSourceAsync(podcast.Id, "alice", _ct))
Assert.Equal(10, source.Length);
Assert.Equal(403, (await Assert.ThrowsAsync<PodcastException>(
() => processor.SaveDraftAsync(podcast.Id, "bob", Save(0, []), _ct))).StatusCode);
Assert.Equal(400, (await Assert.ThrowsAsync<PodcastException>(() => processor.SaveDraftAsync(
podcast.Id, "alice", Save(0, [], new PodcastDraftRange(0, 4000)), _ct))).StatusCode);
Assert.Equal(400, (await Assert.ThrowsAsync<PodcastException>(() => processor.SaveDraftAsync(
podcast.Id, "alice", Save(0, [-1]), _ct))).StatusCode);
var saved = await processor.SaveDraftAsync(podcast.Id, "alice",
Save(0, [3500, 500, 1500, 500], new PodcastDraftRange(1000, 2000)), _ct);
Assert.Equal(1, saved.Draft!.Revision);
Assert.Equal([500L, 3500], saved.Draft.Marks); // The mark in the removed passage disappears.
Assert.Equal(409, (await Assert.ThrowsAsync<PodcastException>(() => processor.SaveDraftAsync(
podcast.Id, "alice", Save(0, []), _ct))).StatusCode);
Assert.Equal(PodcastDraftState.Publishing,
(await processor.PublishDraftAsync(podcast.Id, "alice", 1, _ct)).Draft?.State);
Assert.Equal(PodcastDraftState.Publishing,
(await processor.PublishDraftAsync(podcast.Id, "alice", 1, _ct)).Draft?.State);
Assert.Equal(409, (await Assert.ThrowsAsync<PodcastException>(() => processor.SaveDraftAsync(
podcast.Id, "alice", Save(1, []), _ct))).StatusCode);
// A restart keeps the queued publication.
processor = New();
Assert.True(await processor.PublishNextDraftAsync(new Editor(async (source, kept, output, allowance, ct) =>
{
Assert.Equal(Path.Combine(directory, "source.mp4"), source);
Assert.Equal([new ReplayRange(0, 1000), new ReplayRange(2000, ReplayRange.OpenEnd)], kept);
Assert.Equal(1024 * 1024 - podcast.Bytes, allowance);
await File.WriteAllBytesAsync(output, new byte[6], ct);
}), _ct));
var published = (await processor.GetAsync(podcast.Id, _ct)).Podcast;
Assert.Equal(new PodcastReplayResponse(PodcastReplayState.Ready, 6), published.Replay);
Assert.Equal(PodcastDraftState.Ready, published.Draft?.State);
Assert.Equal(1, published.Draft!.PublishedRevision);
Assert.Equal(segmentsBytes + 10 + 6, published.Bytes);
Assert.Equal(published, await processor.PublishDraftAsync(podcast.Id, "alice", 1, _ct));
Assert.Equal(403, (await Assert.ThrowsAsync<PodcastException>(
() => processor.OpenSegmentAsync(podcast.Id, 0, "bob", _ct))).StatusCode);
// Re-editing keeps the published MP4 served until its atomic replacement.
await processor.SaveDraftAsync(podcast.Id, "alice", Save(1, [500]), _ct);
await processor.PublishDraftAsync(podcast.Id, "alice", 2, _ct);
await using var previous = await processor.OpenReplayAsync(podcast.Id, _ct);
Assert.True(await processor.PublishNextDraftAsync(new Editor((_, _, _, _, _) =>
throw new InvalidOperationException("Without removals the source is copied.")), _ct));
Assert.Equal(6, previous.Length);
var replaced = (await processor.GetAsync(podcast.Id, _ct)).Podcast;
Assert.Equal(new PodcastReplayResponse(PodcastReplayState.Ready, 10), replaced.Replay);
Assert.Equal(segmentsBytes + 10 + 10, replaced.Bytes);
await using (var replay = await processor.OpenReplayAsync(podcast.Id, _ct))
Assert.Equal(10, replay.Length);
}
[Fact]
public async Task Failed_publication_keeps_the_draft_and_the_published_replay()
{
var processor = New();
var podcast = await Refined(processor);
await processor.PublishDraftAsync(podcast.Id, "alice", 0, _ct);
Assert.True(await processor.PublishNextDraftAsync(new Editor((_, _, _, _, _) => Task.CompletedTask), _ct));
await processor.SaveDraftAsync(podcast.Id, "alice", Save(0, [], new PodcastDraftRange(0, 1000)), _ct);
await processor.PublishDraftAsync(podcast.Id, "alice", 1, _ct);
Assert.True(await processor.PublishNextDraftAsync(new Editor(async (_, _, output, _, ct) =>
{
await File.WriteAllBytesAsync(output, [1, 2], ct);
throw new InvalidDataException("Synthetic failure");
}), _ct));
var failed = (await processor.GetAsync(podcast.Id, _ct)).Podcast;
Assert.Equal(PodcastDraftState.Ready, failed.Draft?.State);
Assert.NotEmpty(failed.Draft!.Error!);
Assert.Equal(1, failed.Draft.Revision);
Assert.Equal(0, failed.Draft.PublishedRevision);
Assert.Equal(new PodcastReplayResponse(PodcastReplayState.Ready, 10), failed.Replay);
Assert.False(File.Exists(Path.Combine(_root, podcast.Id.ToString("N"), "replay.tmp.mp4")));
}
[Fact]
public async Task Interrupted_refined_emission_prepares_a_private_draft_and_failed_sources_can_be_retried()
{
var processor = New();
var podcast = await processor.CreateAsync("alice", "alice", "Interrupted", _ct, refineReplay: true);
await processor.AppendAsync(podcast.Id, "alice", 0, 2, new MemoryStream(LiveProcessorTests.Packets()), _ct);
await using (await processor.OpenSegmentAsync(podcast.Id, 0, "bob", _ct)) { }
var restarted = New();
var interrupted = (await restarted.GetAsync(podcast.Id, _ct)).Podcast;
Assert.Equal(PodcastState.Interrupted, interrupted.State);
Assert.Equal(PodcastDraftState.Preparing, interrupted.Draft?.State);
Assert.Equal(403, (await Assert.ThrowsAsync<PodcastException>(
() => restarted.OpenSegmentAsync(podcast.Id, 0, "bob", _ct))).StatusCode);
Assert.True(await restarted.PrepareNextReplayAsync(new Remuxer(async (_, _, output, _, ct) =>
{
await File.WriteAllBytesAsync(output, [1], ct);
throw new InvalidDataException("Synthetic failure");
}), _ct));
var failed = (await restarted.GetAsync(podcast.Id, _ct)).Podcast;
Assert.Equal(PodcastDraftState.Failed, failed.Draft?.State);
Assert.Equal(PodcastReplayState.Pending, failed.Replay?.State);
Assert.Equal(interrupted.Bytes, failed.Bytes);
Assert.False(File.Exists(Path.Combine(_root, podcast.Id.ToString("N"), "source.mp4")));
Assert.Equal(403, (await Assert.ThrowsAsync<PodcastException>(
() => restarted.RetryReplayAsync(podcast.Id, "bob", _ct))).StatusCode);
await restarted.RetryReplayAsync(podcast.Id, "alice", _ct);
Assert.True(await restarted.PrepareNextReplayAsync(Bytes(3), _ct));
var completed = await restarted.CompleteAsync(podcast.Id, "alice", _ct);
Assert.Equal(PodcastDraftState.Ready, completed.Draft?.State);
Assert.Equal(3, completed.Draft!.SourceBytes);
}
private static Remuxer Bytes(int count) => new((_, _, output, _, ct) => File.WriteAllBytesAsync(output, new byte[count], ct));
private sealed class Editor(Func<string, IReadOnlyList<ReplayRange>, string, long, CancellationToken, Task> render)
: IPodcastReplayEditor
{
public Task RenderAsync(string source, IReadOnlyList<ReplayRange> kept, string output, long max, CancellationToken ct)
=> render(source, kept, output, max, ct);
}
private sealed class Remuxer(Func<string, int, string, long, CancellationToken, Task> remux) : IPodcastReplayRemuxer
{
public Task RemuxAsync(string directory, int count, string output, long max, CancellationToken ct)