feat: add song requests with hot swap

A listener request can now replace any upcoming item in the schedule,
also while the broadcast is running. The user picks a song from the
library, selects a row in the timeline and clicks "Play instead of
selected".

ScheduleGenerator.Replace puts the song at that position and rebuilds
only the rest of its half hour. Filler goes before the songs, so the
last song still ends exactly when the next news starts. Items before
the swap and all later half hours stay as they were. The filler budget
counts the ads and talk already planned earlier in that half hour, and
an ad never follows another ad.

PlaybackEngine.ReplaceUpcoming switches the running engine to the new
plan. It refuses when the item has already started, and the engine
reads each next item under a lock, so a swap cannot hit an item that
is just going on air.

The timeline marks the item on air with a play icon instead of
selecting it, so the selection is free for the swap target. A hint
next to the button says why a row cannot be replaced (news, already
played, no song chosen).

Refs #11

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Opus 5.5 committed 2026-11-23 11:10:38 +01:00
1 parent ce0bc03ef7
commit 667501e805
8 files changed
+387 -30

No files matched your search

+30 -1
View File
@@ -159,4 +159,33 @@ public class PlaybackEngineTests
Assert.Equal(["c.mp3"], player.Played);
}
}
[Fact]
public async Task ReplaceUpcoming_PlaysTheNewItemsButNotOverItemsAlreadyStarted()
{
var player = new FakePlayer();
var news = new TaskCompletionSource();
var first = true;
// The first delay is the news; it waits until released. Song timeouts never fire.
Task Delay(TimeSpan d, CancellationToken t)
{
if (first) { first = false; return news.Task.WaitAsync(t); }
return d > TimeSpan.FromSeconds(180) ? Task.Delay(Timeout.Infinite, t) : Task.CompletedTask;
}
var engine = new PlaybackEngine(player, Delay);
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
engine.ItemStarted += (_, _) => started.TrySetResult();
engine.Finished += (_, _) => finished.TrySetResult();
engine.Start(Plan);
await started.Task.WaitAsync(Wait);
IReadOnlyList<ScheduleItem> swapped = [Plan[0], SongItem("request.mp3", 200), .. Plan.Skip(2)];
Assert.False(engine.ReplaceUpcoming(swapped, 0));
Assert.True(engine.ReplaceUpcoming(swapped, 1));
news.SetResult();
await finished.Task.WaitAsync(Wait);
Assert.Equal(["request.mp3", "b.mp3"], player.Played);
}}
@@ -114,4 +114,49 @@ public sealed class ScheduleControllerTests : IDisposable
Assert.False(controller.IsPlaying);
Assert.Null(controller.CurrentItem);
}
}
[Fact]
public void Swap_ReplacesAnItemBeforeStart()
{
AddSongs();
var controller = Create();
controller.CreatePlan(1);
var request = _songs.GetAll()[3];
var plan = controller.Swap(1, request.Id);
Assert.Equal(request.Id, plan[1].Song!.Id);
Assert.Same(plan, controller.Plan);
}
[Fact]
public async Task Swap_WhilePlayingRejectsTheItemOnAirAndAcceptsALaterOne()
{
AddSongs();
var hold = new TaskCompletionSource();
var controller = Create((_, token) => hold.Task.WaitAsync(token));
controller.CreatePlan(1);
var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
controller.ItemStarted += (_, _) => first.TrySetResult();
var request = _songs.GetAll()[3];
controller.Start();
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
var onAir = Assert.Throws<ScheduleException>(() => controller.Swap(0, request.Id));
Assert.Contains("already on air", onAir.Message);
controller.Swap(1, request.Id);
Assert.Equal(request.Id, controller.Plan[1].Song!.Id);
controller.Stop();
}
[Fact]
public void Swap_RejectsUnknownSongAndMissingPlan()
{
AddSongs();
var controller = Create();
Assert.Throws<ScheduleException>(() => controller.Swap(1, _songs.GetAll()[0].Id));
controller.CreatePlan(1);
Assert.Throws<ScheduleException>(() => controller.Swap(1, 12345));
}}
@@ -143,4 +143,69 @@ public class ScheduleGeneratorTests
Assert.Throws<ArgumentException>(() =>
new ScheduleGenerator(new ScheduleOptions { MaxAdBlock = TimeSpan.FromMinutes(20) }, new Random(1)).Generate(Start, 1, Library));
}
}
private static readonly Song Request = Song(99, 4 * 60 + 17);
private static ScheduleGenerator Generator(int seed) => new(new ScheduleOptions(), new Random(seed));
[Theory]
[MemberData(nameof(Seeds))]
public void Replace_PutsTheSongInPlaceAndKeepsEverythingElseOnTime(int seed)
{
var plan = Generate(seed, hours: 2);
var index = 1; // first item after the 14:00 news
var nextNews = plan.Select((p, i) => (p, i)).First(x => x.i > index && x.p.Kind == ScheduleItemKind.News).i;
var swapped = Generator(seed).Replace(plan, index, Request, Library);
Assert.Equal(plan.Take(index), swapped.Take(index));
Assert.Equal(Request, swapped[index].Song);
Assert.Equal(plan[index].Start, swapped[index].Start);
// Later slots are untouched, so the next news is still at 14:30.
var swappedNews = swapped.Select((p, i) => (p, i)).First(x => x.i > index && x.p.Kind == ScheduleItemKind.News).i;
Assert.Equal(plan.Skip(nextNews), swapped.Skip(swappedNews));
Assert.Equal(ScheduleItemKind.Song, swapped[swappedNews - 1].Kind);
for (var i = 1; i < swapped.Count; i++)
Assert.Equal(swapped[i - 1].End, swapped[i].Start);
}
[Theory]
[MemberData(nameof(Seeds))]
public void Replace_KeepsFillerLimitsAndNoAdsBackToBack(int seed)
{
var plan = Generate(seed, hours: 1);
// Every non-news item in the first half hour, so prefixes with filler are covered too.
var last = plan.Select((p, i) => (p, i)).First(x => x.i > 0 && x.p.Kind == ScheduleItemKind.News).i;
for (var index = 1; index < last; index++)
{
IReadOnlyList<ScheduleItem> swapped;
try { swapped = Generator(seed).Replace(plan, index, Request, Library); }
catch (ScheduleException) { continue; } // too little time left before the news
var filler = swapped.Where(i => i.Kind is ScheduleItemKind.Ad or ScheduleItemKind.Moderator)
.Aggregate(TimeSpan.Zero, (sum, i) => sum + i.Duration);
Assert.True(filler <= TimeSpan.FromMinutes(20), $"{filler} filler after swap at {index}");
for (var i = 1; i < swapped.Count; i++)
Assert.False(swapped[i - 1].Kind == ScheduleItemKind.Ad && swapped[i].Kind == ScheduleItemKind.Ad,
$"Ads back to back at {swapped[i].Start:HH:mm:ss}");
}
}
[Fact]
public void Replace_RejectsSongThatDoesNotFitBeforeTheNews()
{
var plan = Generate(1, hours: 1);
var beforeNews = plan.Select((p, i) => (p, i)).First(x => x.i > 0 && x.p.Kind == ScheduleItemKind.News).i - 1;
var tooLong = Song(98, 25 * 60);
var ex = Assert.Throws<ScheduleException>(() => Generator(1).Replace(plan, beforeNews, tooLong, Library));
Assert.Contains("does not fit", ex.Message);
}
[Fact]
public void Replace_RejectsNews()
{
var plan = Generate(1, hours: 1);
Assert.Throws<ScheduleException>(() => Generator(1).Replace(plan, 0, Request, Library));
}}