Publier les marques nommées comme chapitres du replay

Le brouillon accepte un titre facultatif par marque (120 caractères au
plus) ; la publication convertit les temps vers la chronologie du MP4,
intègre les chapitres par FFmpeg sans réencodage et les expose dans
PodcastResponse.Chapters. L'éditeur PostIt nomme les marques, le lecteur
PostIt et la page web des podcasts listent les chapitres cliquables.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-16 16:33:53 +00:00
commit 989c782d5c
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
17 changed files with 422 additions and 33 deletions

View file

@ -130,6 +130,54 @@ public sealed class ReplayEditorTests(AvaloniaUiFixture ui)
Assert.False(vm.AddMarkCommand.CanExecute(null));
}, TestContext.Current.CancellationToken);
[Fact]
public Task Mark_titles_are_loaded_edited_and_saved_as_chapters()
=> ui.RunAsync(async () =>
{
var api = new DraftApi();
api.Podcast = api.Podcast with
{
Draft = api.Podcast.Draft! with { Marks = [5_000, 15_000, 25_000], Chapters = [new(15_000, "Invite")] }
};
var vm = Editor(api);
Assert.Equal([null, "Invite", null], vm.Marks.Select(m => m.Title));
Assert.False(vm.IsDirty);
vm.Marks[0].Title = " Ouverture\t";
Assert.True(vm.IsDirty);
vm.Marks[1].Title = "Coupee";
vm.Marks[2].Title = " ";
// [15 s, 25 s) removes the start mark and keeps the end mark.
RemoveBetween(vm, 25_000, 15_000);
Assert.True(await vm.SaveAsync());
Assert.Equal([new PodcastChapter(5_000, "Ouverture"), new PodcastChapter(15_000, "Coupee")], api.Saved!.Chapters);
// The server drops the title of a removed mark.
Assert.Equal([5_000L, 25_000], vm.Marks.Select(m => m.TimeMs));
Assert.Equal(["Ouverture", null], vm.Marks.Select(m => m.Title));
Assert.False(vm.IsDirty);
}, TestContext.Current.CancellationToken);
[Fact]
public Task Published_chapters_seek_the_replay_player()
=> ui.RunAsync(() =>
{
var vm = new VideoPageViewModel(new Uri("https://api.example/replay.mp4"), "video/mp4");
long? seek = null;
vm.SeekRequested += t => seek = t;
Assert.False(vm.HasChapters);
vm.ShowChapters([new(0, "Intro"), new(61_500, "Fin")]);
Assert.True(vm.HasChapters);
Assert.Equal("1:01 Fin", vm.Chapters[1].Label);
vm.GoToChapterCommand.Execute(vm.Chapters[1]);
Assert.Equal(61_500, seek);
vm.ShowChapters([]);
Assert.False(vm.HasChapters);
return Task.CompletedTask;
}, TestContext.Current.CancellationToken);
private static ReplayEditorPageViewModel Editor(DraftApi api)
=> new(new PodcastApiClient(api, () => "https://api.example/"), api.Podcast);
@ -142,7 +190,7 @@ public sealed class ReplayEditorTests(AvaloniaUiFixture ui)
private sealed class DraftApi : IYavscApiClient
{
public PodcastResponse Podcast { get; private set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner",
public PodcastResponse Podcast { get; set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner",
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Completed, 1, 1024, 60)
{
RefineReplay = true,
@ -162,13 +210,13 @@ public sealed class ReplayEditorTests(AvaloniaUiFixture ui)
{
Saved = Assert.IsType<SavePodcastDraftRequest>(body);
var ranges = Saved.RemovedRanges;
var marks = Saved.Marks.Where(m => !ranges.Any(r => m >= r.StartMs && m < r.EndMs)).ToArray();
Podcast = Podcast with
{
Draft = draft with
{
Revision = draft.Revision + 1,
Marks = Saved.Marks.Where(m => !ranges.Any(r => m >= r.StartMs && m < r.EndMs)).ToArray(),
RemovedRanges = ranges
Revision = draft.Revision + 1, Marks = marks, RemovedRanges = ranges,
Chapters = Saved.Chapters.Where(c => marks.Contains(c.TimeMs)).ToArray()
}
};
}

View file

@ -1,10 +1,20 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PostIt.Services;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Client;
namespace PostIt.ViewModels;
/// <summary>A chapter of a published replay, in the timeline of its MP4.</summary>
public sealed record PodcastChapterItem(long TimeMs, string Title)
{
public string Label => $"{ReplayControlsState.FormatTime(TimeMs)} {Title}";
}
public partial class VideoPageViewModel(Uri source, string mimeType, Uri? externalUri = null) : ViewModelBase
{
public Uri Source { get; } = source;
@ -13,6 +23,25 @@ public partial class VideoPageViewModel(Uri source, string mimeType, Uri? extern
public PodcastApiClient? PodcastClient { get; init; }
public PodcastResponse? Podcast { get; set; }
public ObservableCollection<PodcastChapterItem> Chapters { get; } = new();
public bool HasChapters => Chapters.Count > 0;
/// <summary>Requests the player to show this time of the published replay.</summary>
public event Action<long>? SeekRequested;
/// <summary>Shows the chapters of the replay actually played; other sources have none.</summary>
public void ShowChapters(IEnumerable<PodcastChapter> chapters)
{
Chapters.Clear();
foreach (var chapter in chapters) Chapters.Add(new(chapter.TimeMs, chapter.Title));
OnPropertyChanged(nameof(HasChapters));
}
[RelayCommand]
private void GoToChapter(PodcastChapterItem? chapter)
{
if (chapter is not null) SeekRequested?.Invoke(chapter.TimeMs);
}
public bool CanOpenExternal => CanLaunchExternally(ExternalUri);
public string Title => Podcast?.Title ?? Uri.UnescapeDataString(System.IO.Path.GetFileName(Source.AbsolutePath));
public override bool CanNavigateNext { get => false; protected set { } }

View file

@ -27,6 +27,9 @@ public sealed partial class ReplayMarkItem(long timeMs) : ObservableObject
public partial bool IsRemoved { get; set; }
[ObservableProperty]
public partial bool IsSelected { get; set; }
/// <summary>Optional title; a named mark is published as a chapter.</summary>
[ObservableProperty]
public partial string? Title { get; set; }
}
public sealed record ReplayRangeItem(long StartMs, long EndMs)
@ -167,7 +170,7 @@ public sealed partial class ReplayEditorPageViewModel : ViewModelBase
Status = $"Une marque existe deja a {ReplayControlsState.FormatPreciseTime(time)}.";
return;
}
var mark = new ReplayMarkItem(time);
var mark = Track(new ReplayMarkItem(time));
var index = Marks.TakeWhile(m => m.TimeMs < time).Count();
Marks.Insert(index, mark);
UpdateRemovedMarks();
@ -181,6 +184,15 @@ public sealed partial class ReplayEditorPageViewModel : ViewModelBase
}
}
private ReplayMarkItem Track(ReplayMarkItem mark)
{
mark.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(ReplayMarkItem.Title) && Marks.Contains(mark)) IsDirty = true;
};
return mark;
}
private void RemoveMark(ReplayMarkItem? mark)
{
if (mark is null || !Marks.Remove(mark)) return;
@ -261,7 +273,9 @@ public sealed partial class ReplayEditorPageViewModel : ViewModelBase
{
Revision = draft.Revision,
Marks = Marks.Select(m => m.TimeMs).ToArray(),
RemovedRanges = RemovedRanges.Select(r => new PodcastDraftRange(r.StartMs, r.EndMs)).ToArray()
RemovedRanges = RemovedRanges.Select(r => new PodcastDraftRange(r.StartMs, r.EndMs)).ToArray(),
Chapters = Marks.Select(m => (m.TimeMs, Title: ReplayEditPlan.ChapterTitle(m.Title)))
.Where(c => c.Title is not null).Select(c => new PodcastChapter(c.TimeMs, c.Title!)).ToArray()
});
Load(saved, keepThumbnails: true);
Status = $"Brouillon enregistre (revision {saved.Draft?.Revision}).";
@ -318,8 +332,12 @@ public sealed partial class ReplayEditorPageViewModel : ViewModelBase
RangeStart = null;
RangeEnd = null;
Marks.Clear();
var titles = (podcast.Draft?.Chapters ?? []).ToDictionary(c => c.TimeMs, c => c.Title);
foreach (var time in marks.Order())
Marks.Add(new ReplayMarkItem(time) { Thumbnail = thumbnails.GetValueOrDefault(time) });
Marks.Add(Track(new ReplayMarkItem(time)
{
Thumbnail = thumbnails.GetValueOrDefault(time), Title = titles.GetValueOrDefault(time)
}));
RemovedRanges.Clear();
foreach (var range in (podcast.Draft?.RemovedRanges ?? []).OrderBy(r => r.StartMs))
RemovedRanges.Add(new(range.StartMs, range.EndMs));

View file

@ -3,6 +3,7 @@
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
xmlns:abs="using:Yavsc.Abstract.Streaming"
x:DataType="vm:ReplayEditorPageViewModel">
<Grid ColumnDefinitions="2*,*" RowDefinitions="Auto,*,Auto,Auto" Margin="16" ColumnSpacing="16" RowSpacing="8">
<TextBlock Grid.ColumnSpan="2" Text="{Binding Title}" FontSize="22" TextWrapping="Wrap" />
@ -23,7 +24,7 @@
<TextBlock Text="{Binding DraftState}" TextWrapping="Wrap" />
<TextBlock Text="{Binding DurationSummary}" TextWrapping="Wrap" />
<TextBlock Text="Marques" FontWeight="SemiBold" />
<TextBlock Text="Les temps sont ceux de la source originale. Les miniatures restent locales et sont effacees en quittant l'editeur."
<TextBlock Text="Les temps sont ceux de la source originale. Les miniatures restent locales et sont effacees en quittant l'editeur. Une marque nommee devient un chapitre du replay publie."
TextWrapping="Wrap" />
<ItemsControl ItemsSource="{Binding Marks}">
<ItemsControl.ItemTemplate>
@ -37,6 +38,9 @@
<TextBlock Text="(supprimee)" IsVisible="{Binding IsRemoved}" />
<TextBlock Text="✓ selectionnee" IsVisible="{Binding IsSelected}" />
</StackPanel>
<TextBox Text="{Binding Title}" Watermark="Titre du chapitre (facultatif)"
MaxLength="{x:Static abs:ReplayEditPlan.MaxChapterTitleLength}"
IsEnabled="{Binding $parent[ContentPage].((vm:ReplayEditorPageViewModel)DataContext).CanEdit}" />
<WrapPanel>
<Button Content="Aller" Margin="0,0,4,4"
Command="{Binding $parent[ContentPage].((vm:ReplayEditorPageViewModel)DataContext).GoToMarkCommand}"

View file

@ -4,12 +4,31 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:PostIt.ViewModels"
x:DataType="vm:VideoPageViewModel">
<Grid RowDefinitions="Auto,*,Auto,Auto" Margin="16" RowSpacing="12">
<Grid RowDefinitions="Auto,*,Auto,Auto,Auto" Margin="16" RowSpacing="12">
<TextBlock Text="{Binding Title}" FontSize="22" TextWrapping="Wrap" />
<Border Grid.Row="1" Background="Black" BorderThickness="1" BorderBrush="Green">
<ContentControl x:Name="VideoSurface" />
</Border>
<Button Grid.Row="2" Content="Ouvrir dans le navigateur" Click="OpenExternal_Click" IsVisible="{Binding CanOpenExternal}" />
<TextBlock x:Name="PlaybackStatus" Grid.Row="3" TextWrapping="Wrap" />
<StackPanel Grid.Row="2" Spacing="4" IsVisible="{Binding HasChapters}">
<TextBlock Text="Chapitres" FontWeight="SemiBold" />
<ScrollViewer MaxHeight="160">
<ItemsControl ItemsSource="{Binding Chapters}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:PodcastChapterItem">
<Button Content="{Binding Label}" Margin="0,0,6,6"
Command="{Binding $parent[ContentPage].((vm:VideoPageViewModel)DataContext).GoToChapterCommand}"
CommandParameter="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</StackPanel>
<Button Grid.Row="3" Content="Ouvrir dans le navigateur" Click="OpenExternal_Click" IsVisible="{Binding CanOpenExternal}" />
<TextBlock x:Name="PlaybackStatus" Grid.Row="4" TextWrapping="Wrap" />
</Grid>
</ContentPage>

View file

@ -19,6 +19,7 @@ public partial class VideoPage : ContentPage
private PodcastMediaInput? _podcastInput;
private PodcastReplayMediaInput? _replayInput;
private CancellationTokenSource? _initialization;
private VideoPageViewModel? _chaptersOwner;
public VideoPage() => InitializeComponent();
@ -35,6 +36,9 @@ public partial class VideoPage : ContentPage
ReleasePlayer();
if (Design.IsDesignMode || DataContext is not VideoPageViewModel vm)
return;
vm.ShowChapters([]);
vm.SeekRequested += SeekToChapter;
_chaptersOwner = vm;
var cancellation = new CancellationTokenSource();
_initialization = cancellation;
var ct = cancellation.Token;
@ -55,6 +59,7 @@ public partial class VideoPage : ContentPage
{
_replayInput = new PodcastReplayMediaInput(replayClient, podcast.Id, podcast.Replay!.Bytes);
_replayInput.Failed += PodcastFailed;
vm.ShowChapters(podcast.Chapters);
replay = true;
break;
}
@ -122,8 +127,18 @@ public partial class VideoPage : ContentPage
base.OnDetachedFromVisualTree(e);
}
private void SeekToChapter(long timeMs)
{
if (_player is { IsSeekable: true } player) player.Time = timeMs;
}
private void ReleasePlayer()
{
if (_chaptersOwner is not null)
{
_chaptersOwner.SeekRequested -= SeekToChapter;
_chaptersOwner = null;
}
_initialization?.Cancel();
_initialization?.Dispose();
_initialization = null;

View file

@ -24,6 +24,12 @@ 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>
/// A named position of a replay. In a draft, it names a mark of the original timeline; in a published
/// replay, it is converted to the timeline of the published MP4.
/// </summary>
public sealed record PodcastChapter(long TimeMs, string Title);
/// <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.
@ -34,6 +40,8 @@ public sealed record PodcastDraftResponse(
{
/// <summary>Revision of the currently published MP4, if any.</summary>
public int? PublishedRevision { get; init; }
/// <summary>Named marks, published as chapters; each time is also one of the marks.</summary>
public IReadOnlyList<PodcastChapter> Chapters { get; init; } = [];
}
/// <summary>Replaces the marks and removed ranges of a refined replay draft.</summary>
@ -46,6 +54,9 @@ public sealed record SavePodcastDraftRequest
public IReadOnlyList<long> Marks { get; init; } = [];
[MaxLength(200)]
public IReadOnlyList<PodcastDraftRange> RemovedRanges { get; init; } = [];
/// <summary>Titles of named marks; their times are added to the marks if missing.</summary>
[MaxLength(500)]
public IReadOnlyList<PodcastChapter> Chapters { get; init; } = [];
}
/// <summary>Publishes the saved draft revision as the replay MP4.</summary>
@ -120,6 +131,8 @@ public sealed record PodcastResponse(
public DateTimeOffset? OriginalsExpireAt { get; init; }
/// <summary>The originals and draft were deleted; only the published MP4 remains and it cannot be re-edited.</summary>
public bool OriginalsDeleted { get; init; }
/// <summary>Chapters of the published refined replay, in the timeline of its MP4.</summary>
public IReadOnlyList<PodcastChapter> Chapters { get; init; } = [];
}
/// <summary>An independently decodable MPEG-TS HLS segment.</summary>

View file

@ -12,6 +12,42 @@ public readonly record struct ReplayRange(long StartMs, long EndMs)
public static class ReplayEditPlan
{
public const int MaxRemovedRanges = 200;
public const int MaxChapterTitleLength = 120;
/// <summary>
/// Normalizes a chapter title: control characters become spaces and surrounding spaces are removed.
/// Returns null for an empty title, which leaves the mark unnamed.
/// </summary>
public static string? ChapterTitle(string? title)
{
if (title is null) return null;
var normalized = new string(title.Select(c => char.IsControl(c) ? ' ' : c).ToArray()).Trim();
return normalized.Length == 0 ? null : normalized;
}
/// <summary>
/// Converts source times to the published timeline, where the kept ranges are concatenated.
/// Chapters inside a removed range, or at the end of the source, are dropped.
/// </summary>
public static IReadOnlyList<PodcastChapter> PublishedChapters(IEnumerable<PodcastChapter> chapters,
IReadOnlyList<ReplayRange> kept)
{
var result = new List<PodcastChapter>();
foreach (var chapter in chapters.OrderBy(c => c.TimeMs))
{
var offset = 0L;
foreach (var range in kept)
{
if (chapter.TimeMs >= range.StartMs && chapter.TimeMs < range.EndMs)
{
result.Add(chapter with { TimeMs = offset + chapter.TimeMs - range.StartMs });
break;
}
offset += range.DurationMs;
}
}
return result;
}
/// <summary>
/// Converts ranges removed by the author into the ordered ranges kept in the final replay.

View file

@ -66,6 +66,25 @@ else
type="@(ready ? "video/mp4" : "application/vnd.apple.mpegurl")" />
@Localizer["Votre navigateur ne prend pas en charge la lecture vidéo."]
</video>
@if (ready && podcast.Chapters.Count > 0)
{
<nav class="mt-2" aria-label="@Localizer["Chapitres de {0}", podcast.Title]">
<h3 class="h6">@Localizer["Chapitres"]</h3>
<ol class="list-unstyled d-flex flex-wrap gap-2 mb-0">
@foreach (var chapter in podcast.Chapters)
{
var time = TimeSpan.FromMilliseconds(chapter.TimeMs);
<li>
<button type="button" class="btn btn-sm btn-outline-secondary"
data-chapter-time="@((chapter.TimeMs / 1000d).ToString("0.###", System.Globalization.CultureInfo.InvariantCulture))">
<time datetime="@System.Xml.XmlConvert.ToString(time)">@(time.TotalHours >= 1 ? time.ToString(@"h\:mm\:ss") : time.ToString(@"m\:ss"))</time>
@chapter.Title
</button>
</li>
}
</ol>
</nav>
}
@if (!ready)
{
<button type="button" class="btn btn-outline-primary mt-2 d-none" data-start-playback>

View file

@ -29,4 +29,10 @@ document.querySelectorAll("[data-podcast-player]").forEach(player => {
source.addEventListener("error", showError);
}
player.addEventListener("error", showError);
player.parentElement.querySelectorAll("[data-chapter-time]").forEach(chapter => {
chapter.addEventListener("click", () => {
player.currentTime = Number(chapter.dataset.chapterTime);
player.play().catch(showError);
});
});
});

View file

@ -11,4 +11,11 @@ public interface IPodcastReplayEditor
/// </summary>
Task RenderAsync(string sourcePath, IReadOnlyList<ReplayRange> kept,
string outputPath, long maxBytes, CancellationToken ct);
/// <summary>
/// Copies <paramref name="inputPath"/> without re-encoding into a new MP4 carrying these chapters,
/// given in its timeline and ordered. The last chapter ends at <paramref name="durationMs"/>.
/// </summary>
Task AddChaptersAsync(string inputPath, IReadOnlyList<PodcastChapter> chapters, long durationMs,
string outputPath, long maxBytes, CancellationToken ct);
}

View file

@ -44,6 +44,48 @@ public sealed class FfmpegPodcastReplayEditor(IOptions<PodcastOptions> options)
await FfmpegProcess.RunAsync(options.Value.FfmpegPath, arguments, null, outputPath, maxBytes, ct);
}
public async Task AddChaptersAsync(string inputPath, IReadOnlyList<PodcastChapter> chapters, long durationMs,
string outputPath, long maxBytes, CancellationToken ct)
{
if (chapters.Count == 0) throw new ArgumentException("Aucun chapitre.", nameof(chapters));
var metadata = new StringBuilder(";FFMETADATA1\n");
for (var i = 0; i < chapters.Count; i++)
{
var start = chapters[i].TimeMs;
var end = i + 1 < chapters.Count ? chapters[i + 1].TimeMs : Math.Max(durationMs, start + 1);
if (start < 0 || end <= start)
throw new ArgumentException("Les chapitres doivent etre ordonnes et distincts.", nameof(chapters));
metadata.Append(CultureInfo.InvariantCulture,
$"[CHAPTER]\nTIMEBASE=1/1000\nSTART={start}\nEND={end}\ntitle={MetadataValue(chapters[i].Title)}\n");
}
// Titles are user text: they only reach FFmpeg through this escaped metadata file.
var metadataPath = outputPath + ".chapters.txt";
await File.WriteAllTextAsync(metadataPath, metadata.ToString(), new UTF8Encoding(false), ct);
try
{
await FfmpegProcess.RunAsync(options.Value.FfmpegPath,
[
"-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", inputPath,
"-f", "ffmetadata", "-i", metadataPath, "-map", "0:v", "-map", "0:a?",
"-map_metadata", "0", "-map_chapters", "1", "-c", "copy",
"-movflags", "+faststart", "-f", "mp4", outputPath
], null, outputPath, maxBytes, ct);
}
finally { File.Delete(metadataPath); }
}
private static string MetadataValue(string value)
{
var escaped = new StringBuilder(value.Length);
foreach (var c in value)
{
if (char.IsControl(c)) { escaped.Append(' '); continue; }
if (c is '=' or ';' or '#' or '\\') escaped.Append('\\');
escaped.Append(c);
}
return escaped.ToString();
}
private static string Seconds(long milliseconds)
=> (milliseconds / 1000m).ToString("0.###", CultureInfo.InvariantCulture);
}

View file

@ -396,8 +396,19 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
public async Task<PodcastResponse> SaveDraftAsync(Guid id, string ownerId, SavePodcastDraftRequest request, CancellationToken ct)
{
if (request.Marks.Count > MaxDraftMarks)
if (request.Marks.Count > MaxDraftMarks || request.Chapters.Count > MaxDraftMarks)
throw new PodcastException(400, $"Au plus {MaxDraftMarks} marques sont autorisees.");
var chapters = new List<PodcastChapter>();
foreach (var chapter in request.Chapters)
{
var title = ReplayEditPlan.ChapterTitle(chapter.Title);
if (title is null) continue;
if (title.Length > ReplayEditPlan.MaxChapterTitleLength)
throw new PodcastException(400, $"Un titre de chapitre depasse {ReplayEditPlan.MaxChapterTitleLength} caracteres.");
chapters.Add(chapter with { Title = title });
}
if (chapters.DistinctBy(c => c.TimeMs).Count() != chapters.Count)
throw new PodcastException(400, "Une marque ne peut porter qu'un titre de chapitre.");
await _gate.WaitAsync(ct);
try
{
@ -408,15 +419,18 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
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))
var requested = request.Marks.Concat(chapters.Select(c => c.TimeMs)).Distinct().ToArray();
if (requested.Length > MaxDraftMarks)
throw new PodcastException(400, $"Au plus {MaxDraftMarks} marques sont autorisees.");
if (requested.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();
// A mark inside a removed passage disappears with it, and so does its chapter title.
var marks = requested.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
Revision = podcast.Draft!.Revision + 1, Marks = marks, RemovedRanges = ranges, Error = null,
Chapters = chapters.Where(c => marks.Contains(c.TimeMs)).OrderBy(c => c.TimeMs).ToArray()
};
await SetDraftAsync(document, draft, ct);
return _documents[id].Manifest.Podcast;
@ -489,27 +503,39 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
var directory = DirectoryFor(id);
var source = Path.Combine(directory, SourceFileName);
var temporary = Path.Combine(directory, "replay.tmp.mp4");
var rendered = Path.Combine(directory, "replay.render.tmp.mp4");
IReadOnlyList<PodcastChapter> chapters = [];
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.RemovedRanges.Count > 0 || draft.Chapters.Count > 0)
{
var duration = SourceDurationMs(podcast);
var kept = ReplayEditPlan.KeptRanges(
draft.RemovedRanges.Select(r => new ReplayRange(r.StartMs, r.EndMs)), duration).ToArray();
var publishedDuration = kept.Sum(r => r.DurationMs);
chapters = ReplayEditPlan.PublishedChapters(draft.Chapters, kept);
var media = source;
if (draft.RemovedRanges.Count > 0)
{
// 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 };
media = chapters.Count == 0 ? temporary : rendered;
await editor.RenderAsync(source, kept, media, allowance, timeout.Token);
}
if (chapters.Count > 0)
await editor.AddChaptersAsync(media, chapters, publishedDuration, temporary, allowance, timeout.Token);
}
if (draft.RemovedRanges.Count == 0 && chapters.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);
}
File.Delete(rendered);
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);
@ -526,6 +552,7 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
{
Bytes = latest.Bytes - previous + bytes,
Replay = new(PodcastReplayState.Ready, bytes),
Chapters = chapters,
Draft = latest.Draft! with
{
State = PodcastDraftState.Ready, PublishedRevision = draft.Revision, Error = null
@ -543,6 +570,7 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
{
_logger.LogError(ex, "Podcast {PodcastId} draft publication failed", id);
File.Delete(temporary);
File.Delete(rendered);
if (!ct.IsCancellationRequested)
{
await _gate.WaitAsync(CancellationToken.None);

View file

@ -215,6 +215,11 @@ public sealed class PodcastReplayTests : IDisposable
Assert.Equal([new ReplayRange(0, 3000), new ReplayRange(4000, 5000)],
ReplayEditPlan.RemovedRanges([new(2000, 3000), new(1000, 2500), new(-500, 1000), new(4000, 9000)], 5000));
Assert.Throws<ArgumentException>(() => ReplayEditPlan.RemovedRanges([new(0, 2000), new(2000, 5000)], 5000));
Assert.Equal([new PodcastChapter(0, "a"), new PodcastChapter(1000, "c"), new PodcastChapter(2000, "d")],
ReplayEditPlan.PublishedChapters([new(4500, "d"), new(0, "a"), new(1000, "b"), new(3000, "c"), new(5000, "e")],
ReplayEditPlan.KeptRanges([new(1000, 3000), new(4000, 4500)], 5000)));
Assert.Equal("Titre a b", ReplayEditPlan.ChapterTitle(" Titre\ta\r\nb "));
Assert.Null(ReplayEditPlan.ChapterTitle(" \n "));
}
[Theory]
@ -374,6 +379,81 @@ public sealed class PodcastReplayTests : IDisposable
Assert.Equal(10, replay.Length);
}
[Fact]
public async Task Named_marks_are_saved_and_published_as_chapters_in_the_mp4_timeline()
{
var processor = New();
var podcast = await Refined(processor);
var directory = Path.Combine(_root, podcast.Id.ToString("N"));
Assert.Equal(400, (await Assert.ThrowsAsync<PodcastException>(() => processor.SaveDraftAsync(podcast.Id, "alice",
Save(0, []) with { Chapters = [new(500, "A"), new(500, "B")] }, _ct))).StatusCode);
Assert.Equal(400, (await Assert.ThrowsAsync<PodcastException>(() => processor.SaveDraftAsync(podcast.Id, "alice",
Save(0, []) with { Chapters = [new(500, new string('x', ReplayEditPlan.MaxChapterTitleLength + 1))] }, _ct))).StatusCode);
var saved = await processor.SaveDraftAsync(podcast.Id, "alice", Save(0, [500], new PodcastDraftRange(1000, 2000))
with { Chapters = [new(2500, "Fin = ;#"), new(1500, "Coupé"), new(500, " Intro\n"), new(3000, " ")] }, _ct);
// Named marks are marks; a blank title leaves no mark and a removed mark loses its title.
Assert.Equal([500L, 2500], saved.Draft!.Marks);
Assert.Equal([new PodcastChapter(500, "Intro"), new PodcastChapter(2500, "Fin = ;#")], saved.Draft.Chapters);
await processor.PublishDraftAsync(podcast.Id, "alice", 1, _ct);
string? rendered = null;
Assert.True(await processor.PublishNextDraftAsync(new Editor(async (_, _, output, _, ct) =>
{
rendered = output;
await File.WriteAllBytesAsync(output, new byte[6], ct);
}, async (input, chapters, duration, output, ct) =>
{
Assert.Equal(rendered, input);
Assert.Equal([new PodcastChapter(500, "Intro"), new PodcastChapter(1500, "Fin = ;#")], chapters);
Assert.Equal(3000, duration);
await File.WriteAllBytesAsync(output, new byte[7], ct);
}), _ct));
var published = PodcastVisibility.ForViewer(await processor.GetAsync(podcast.Id, _ct), "bob").Podcast;
Assert.Equal(new PodcastReplayResponse(PodcastReplayState.Ready, 7), published.Replay);
Assert.Equal([new PodcastChapter(500, "Intro"), new PodcastChapter(1500, "Fin = ;#")], published.Chapters);
Assert.False(File.Exists(rendered));
// Without removal, chapters are added to the source itself.
await processor.SaveDraftAsync(podcast.Id, "alice", Save(1, []) with { Chapters = [new(2500, "Fin")] }, _ct);
await processor.PublishDraftAsync(podcast.Id, "alice", 2, _ct);
Assert.True(await processor.PublishNextDraftAsync(new Editor((_, _, _, _, _) =>
throw new InvalidOperationException("Without removals the source is not rendered."),
async (input, chapters, duration, output, ct) =>
{
Assert.Equal(Path.Combine(directory, "source.mp4"), input);
Assert.Equal(4000, duration);
await File.WriteAllBytesAsync(output, new byte[8], ct);
}), _ct));
Assert.Equal([new PodcastChapter(2500, "Fin")], (await processor.GetAsync(podcast.Id, _ct)).Podcast.Chapters);
}
[Fact]
public async Task Ffmpeg_editor_adds_escaped_chapters_without_reencoding()
{
Directory.CreateDirectory(_root);
var source = Path.Combine(_root, "plain.mp4");
await PodcastMediaFixture.RunAsync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "testsrc2=s=32x32:r=10:d=3",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=3", "-c:v", "libx264", "-c:a", "aac",
"-shortest", source], _ct);
var output = Path.Combine(_root, "chapters.mp4");
await new FfmpegPodcastReplayEditor(Options.Create(new PodcastOptions())).AddChaptersAsync(source,
[new(0, "Intro"), new(1500, "Fin = ;#\\ !")], 3000, output, 10_000_000, _ct);
var probe = await PodcastMediaFixture.RunAsync("ffprobe",
["-v", "error", "-show_chapters", "-show_streams", "-of", "json", output], _ct);
using var json = JsonDocument.Parse(probe);
var chapters = json.RootElement.GetProperty("chapters").EnumerateArray().Select(c =>
(c.GetProperty("start_time").GetString(), c.GetProperty("tags").GetProperty("title").GetString())).ToArray();
Assert.Equal([("0.000000", "Intro"), ("1.500000", "Fin = ;#\\ !")], chapters);
var codecs = json.RootElement.GetProperty("streams").EnumerateArray()
.Select(s => s.GetProperty("codec_name").GetString()).ToArray();
Assert.Contains("h264", codecs);
Assert.Contains("aac", codecs);
Assert.False(File.Exists(output + ".chapters.txt"));
}
[Fact]
public async Task Failed_publication_keeps_the_draft_and_the_published_replay()
{
@ -507,11 +587,16 @@ public sealed class PodcastReplayTests : IDisposable
}
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)
private sealed class Editor(Func<string, IReadOnlyList<ReplayRange>, string, long, CancellationToken, Task> render,
Func<string, IReadOnlyList<PodcastChapter>, long, string, CancellationToken, Task>? chapters = null)
: IPodcastReplayEditor
{
public Task RenderAsync(string source, IReadOnlyList<ReplayRange> kept, string output, long max, CancellationToken ct)
=> render(source, kept, output, max, ct);
public Task AddChaptersAsync(string input, IReadOnlyList<PodcastChapter> list, long duration, string output,
long max, CancellationToken ct)
=> chapters is null ? throw new InvalidOperationException("No chapter expected.") : chapters(input, list, duration, output, ct);
}
private sealed class Clock : TimeProvider

View file

@ -98,6 +98,10 @@ public sealed class PodcastWebTests : IClassFixture<PodcastWebTests.Factory>
Assert.DoesNotContain("<script>unsafe-title</script>", html);
Assert.Contains("&lt;script&gt;unsafe-title&lt;/script&gt;", html);
Assert.Contains("hls.light.min.js", html);
Assert.Contains("data-chapter-time=\"0\"", html);
Assert.Contains("data-chapter-time=\"1.5\"", html);
Assert.Contains("<time datetime=\"PT1.5S\">0:01</time>", html);
Assert.Contains("&lt;b&gt;Fin&lt;/b&gt;", html);
Assert.True(response.Headers.CacheControl?.NoStore);
var requests = _factory.Api.Requests.ToArray();
var request = Assert.Single(requests);
@ -154,6 +158,7 @@ public sealed class PodcastWebTests : IClassFixture<PodcastWebTests.Factory>
using var client = SignedInClient();
var html = await client.GetStringAsync("/Podcast", Ct);
Assert.Contains($"/Podcast/{PodcastId}/index.m3u8", html);
Assert.DoesNotContain("data-chapter-time", html); // Chapters belong to the published MP4.
Assert.DoesNotContain("/Donation/Create/other-author", html);
Assert.Contains("PayPal", html);
var playlist = await client.GetStringAsync($"/Podcast/{PodcastId}/index.m3u8", Ct);
@ -315,7 +320,8 @@ public sealed class PodcastWebTests : IClassFixture<PodcastWebTests.Factory>
Live ? "other-author" : "author", "Author", DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow, Live ? PodcastState.Live : PodcastState.Completed, 1, 188, 2.5)
{
Replay = Live ? null : new(PodcastReplayState.Ready, 10)
Replay = Live ? null : new(PodcastReplayState.Ready, 10),
Chapters = [new(0, "Intro"), new(1500, "<b>Fin</b>")]
};
if (path == "/api/v1/podcasts/")
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)