fix: start each schedule item at its planned time

Start played the first item right away, although the plan begins at
the next full hour. The news was at :00 and :30 in the plan but not on
the real clock.

PlaybackEngine now takes a clock and waits before each item until its
planned start. An item that runs late is never cut; the next one then
starts right after it. When the broadcast starts after the plan has
begun, items that should already have started are skipped and playback
joins at the next one.

While the engine waits for the first item, the now-playing card shows
"On air at" with the planned time. Starting a plan that is already
over is refused with a message.

Refs #12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
fraujulianandClaude Opus 5.5 committed 2026-11-23 11:20:10 +01:00
1 parent 6f3ce85307
commit 497ac8fd6c
6 files changed
+127 -17

No files matched your search

+7 -5
View File
@@ -29,7 +29,7 @@ On first start the app creates its data under `%LOCALAPPDATA%\Radiosender`:
4. **Schedule**:
1. Enter the number of hours (1 to 24) and click **Create schedule**. The plan starts at the next full hour.
2. The timeline shows every item with start time, type (song, news, ad, moderator), title and duration.
3. **Start** plays the plan from the first item, **Stop** ends it. The now-playing card shows the current item, its progress and the volume.
3. **Start** puts the plan on air on the real clock. Before the planned start the now-playing card shows when the broadcast begins; if the plan has already begun, playback joins at the next item. **Stop** ends it. The now-playing card shows the current item, its progress and the volume.
4. **Song request**: choose a song, select an upcoming row in the timeline and click **Play instead of selected**. This also works while the broadcast is running.
News, ads and moderator talk are placeholders: the app shows them in the timeline and keeps silent for their duration.
@@ -43,6 +43,8 @@ News, ads and moderator talk are placeholders: the app shows them in the timelin
- Ads and moderator items alternate, and one ad item lasts at most 5 minutes, so there is never a long block of ads.
- The filler sits between the songs and the slot always ends with a song, so that song ends exactly when the next news starts. Songs are never cut. When the filler does not add up, the last placeholder is shortened.
During playback `PlaybackEngine` starts every item at its planned time. If the previous item ended early, it waits; if it ran late, the next item starts right after it and is never cut. The news therefore comes at the real :00 and :30.
A song request (`ScheduleGenerator.Replace`) puts the song at the selected position and rebuilds only the rest of that half hour with the same rules. Earlier items and later half hours stay as they are, so the next news keeps its time. News items cannot be replaced, and a song that is longer than the time left before the next news is rejected.
## Architecture
@@ -80,7 +82,7 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a
| Requirement | Where | Status |
| --- | --- | --- |
| Plays random music for X hours; only full hours, entered by the user | Schedule page, hours 1 to 24; `ScheduleGenerator.PickSongs` | Done |
| 2 × 5 minutes of news per hour, at :00 and :30 | `ScheduleGenerator.Generate` | Done in the plan, see the limitation below |
| 2 × 5 minutes of news per hour, at :00 and :30 | `ScheduleGenerator.Generate`; `PlaybackEngine` waits for each planned start | Done |
| News comes after a song, no song is cut | Slot ends with a song that ends at the news start; tests in `ScheduleGeneratorTests` | Done |
| Up to 20 minutes of ads and moderator talk per hour | At most 10 minutes per half hour | Done |
| Ads never 20 minutes in a row | Ads alternate with moderator items, one ad item lasts at most 5 minutes | Done |
@@ -97,8 +99,8 @@ For each downloaded track the app stores the license (for example `CC BY 4.0`) a
## Known limitations
- **Real clock**: the plan starts at the next full hour, but **Start** begins with the first item right away. The news therefore lands on the real :00 and :30 only when the broadcast is started at a full hour. The timeline and the now-playing card always show the planned times.
- **Drift**: placeholders are timed with a timer and songs by the audio device, so the real end can drift by a few seconds over long runs.
- **Skipped songs**: a song that cannot be played (missing file, unsupported format) is skipped with a warning, so later items start earlier than planned.
- **Waiting for the start**: a new plan starts at the next full hour, so after **Start** the app can stay silent for up to an hour.
- **Late items**: if a song plays longer than its stored duration, the following items start late by the same amount. Nothing is cut to catch up; the delay only disappears when a later item ends early.
- **Skipped songs**: a song that cannot be played (missing file, unsupported format) is skipped with a warning, and the station stays silent until the next planned item.
- **Deleting a song** removes it from the library but keeps its file in the `Music` folder.
- **Placeholders** have no audio. The last filler of a half hour can be very short (for example 2 seconds) because it is cut to fit.
@@ -72,11 +72,19 @@ public class ScheduleController
return Plan;
}
/// <summary>Plays the plan from its first item; the planned times are the on-air clock, playback starts right away.</summary>
/// <summary>Planned start of the next item while the broadcast waits for it, otherwise <c>null</c>.</summary>
public DateTime? WaitingUntil => CurrentItem is null ? _engine.WaitingUntil : null;
/// <summary>
/// Goes on air with the plan on the real clock: waits for the planned start, or joins at the next item
/// when the plan has already begun.
/// </summary>
public void Start()
{
if (Plan.Count == 0)
throw new InvalidOperationException("Create a schedule first.");
if (Plan[^1].Start <= _now())
throw new InvalidOperationException("This schedule is already over. Create a new one.");
_engine.Start(Plan);
}
+35 -5
View File
@@ -3,8 +3,9 @@ using Radiosender.Models;
namespace Radiosender.Services;
/// <summary>
/// Runs a generated schedule from start to end: songs play through the audio player, news, ads and
/// moderator placeholders are held for their duration.
/// Runs a generated schedule on the real clock: each item starts at its planned time, or right after the
/// previous item if that one ran late. Songs play through the audio player, news, ads and moderator
/// placeholders are held for their duration. Songs are never cut.
/// </summary>
/// <remarks>
/// Events are raised on the engine's thread-pool thread. WPF callers must marshal with
@@ -16,20 +17,25 @@ public sealed class PlaybackEngine
// Extra time before a song counts as stuck, e.g. after an audio device error that never raises TrackFinished.
private static readonly TimeSpan SongGrace = TimeSpan.FromSeconds(10);
// An item that started at most this long ago still plays when the broadcast starts, e.g. a click right after 15:00.
private static readonly TimeSpan LateStart = TimeSpan.FromSeconds(5);
private readonly IAudioPlayer _player;
private readonly Func<TimeSpan, CancellationToken, Task> _delay;
private readonly Func<DateTime> _now;
private readonly Lock _lock = new();
private CancellationTokenSource? _cts;
private Task _run = Task.CompletedTask;
public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay)
public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay, () => DateTime.Now)
{
}
public PlaybackEngine(IAudioPlayer player, Func<TimeSpan, CancellationToken, Task> delay)
public PlaybackEngine(IAudioPlayer player, Func<TimeSpan, CancellationToken, Task> delay, Func<DateTime> now)
{
_player = player;
_delay = delay;
_now = now;
}
/// <summary>Raised when an item starts, with its index in <see cref="Items"/>.</summary>
@@ -48,7 +54,13 @@ public sealed class PlaybackEngine
public bool IsRunning => !_run.IsCompleted;
/// <summary>Stops any running schedule and starts <paramref name="items"/> from the first item.</summary>
/// <summary>Planned start the engine waits for, or <c>null</c> when it is not waiting.</summary>
public DateTime? WaitingUntil { get; private set; }
/// <summary>
/// Stops any running schedule and starts <paramref name="items"/> on the clock. Items that should have
/// started earlier are skipped; before the first planned start the engine waits.
/// </summary>
public void Start(IReadOnlyList<ScheduleItem> items)
{
Stop();
@@ -105,10 +117,28 @@ public sealed class PlaybackEngine
{
try
{
var skipBefore = _now() - LateStart;
for (var i = 0; ; i++)
{
token.ThrowIfCancellationRequested();
ScheduleItem item;
lock (_lock)
{
if (i >= Items.Count) break;
item = Items[i];
}
if (item.Start < skipBefore)
continue;
// Early items wait for their slot, so the news hits :00 and :30; late items start right away.
var wait = item.Start - _now();
if (wait > TimeSpan.Zero)
{
WaitingUntil = item.Start;
try { await _delay(wait, token); }
finally { WaitingUntil = null; }
}
// Under the lock so ReplaceUpcoming cannot swap the item that is about to start.
lock (_lock)
{
@@ -97,7 +97,14 @@ public partial class SchedulePage : Page
private void OnStart(object sender, RoutedEventArgs e)
{
Message.IsOpen = false;
_controller.Start();
try
{
_controller.Start();
}
catch (InvalidOperationException ex)
{
ShowMessage(InfoBarSeverity.Warning, "Could not start", ex.Message);
}
ShowCurrent();
}
@@ -145,7 +152,7 @@ public partial class SchedulePage : Page
NowKind.Content = item;
NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible;
NowTitle.Text = item?.Title ?? "Nothing on air";
if (item is not null) NowTitle.Text = item.Title;
UpdateButtons();
UpdateProgress();
@@ -175,7 +182,10 @@ public partial class SchedulePage : Page
if (_controller.CurrentItem is not { } item)
{
NowProgress.Value = 0;
NowTime.Text = " ";
// Checked here, not in ShowCurrent: the engine starts waiting a moment after Start.
var waiting = _controller.WaitingUntil;
NowTitle.Text = waiting is { } at ? $"On air at {at:HH:mm:ss}" : "Nothing on air";
NowTime.Text = waiting is null ? " " : "Waiting for the planned start, so the news comes at :00 and :30.";
return;
}
+30 -2
View File
@@ -65,7 +65,7 @@ public class PlaybackEngineTests
private static (PlaybackEngine Engine, List<int> Started, TaskCompletionSource Finished) Create(FakePlayer player, FakeClock clock)
{
var engine = new PlaybackEngine(player, clock.Delay);
var engine = new PlaybackEngine(player, clock.Delay, () => Start);
var started = new List<int>();
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
engine.ItemStarted += (_, e) => { lock (started) started.Add(e.Index); };
@@ -172,7 +172,7 @@ public class PlaybackEngineTests
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 engine = new PlaybackEngine(player, Delay, () => Start);
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
engine.ItemStarted += (_, _) => started.TrySetResult();
@@ -188,4 +188,32 @@ public class PlaybackEngineTests
await finished.Task.WaitAsync(Wait);
Assert.Equal(["request.mp3", "b.mp3"], player.Played);
}
[Fact]
public async Task Start_SkipsItemsThatShouldHaveStartedEarlierAndWaitsForTheNext()
{
var player = new FakePlayer();
var clock = new FakeClock();
IReadOnlyList<ScheduleItem> timed =
[
Plan[0],
Plan[1] with { Start = Start.AddSeconds(300) },
Plan[2] with { Start = Start.AddSeconds(500) },
Plan[3] with { Start = Start.AddSeconds(545) },
Plan[4] with { Start = Start.AddSeconds(605) },
];
var engine = new PlaybackEngine(player, clock.Delay, () => Start.AddSeconds(360));
var started = new List<int>();
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
engine.ItemStarted += (_, e) => started.Add(e.Index);
engine.Finished += (_, _) => finished.TrySetResult();
engine.Start(timed);
await finished.Task.WaitAsync(Wait);
// News and song a already began at 14:06; the ad waits until its planned 14:08:20.
Assert.Equal([2, 3, 4], started);
Assert.Equal(["b.mp3"], player.Played);
Assert.Equal(TimeSpan.FromSeconds(140), clock.Delays.First());
}}
@@ -29,7 +29,7 @@ public sealed class ScheduleControllerTests : IDisposable
private ScheduleController Create(Func<TimeSpan, CancellationToken, Task>? delay = null) =>
new(_songs,
new ScheduleGenerator(new ScheduleOptions(), new Random(7)),
new PlaybackEngine(new InstantPlayer(), delay ?? ((_, _) => Task.CompletedTask)),
new PlaybackEngine(new InstantPlayer(), delay ?? ((_, _) => Task.CompletedTask), () => _now),
() => _now);
private void AddSongs()
@@ -101,6 +101,7 @@ public sealed class ScheduleControllerTests : IDisposable
var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
controller.ItemStarted += (_, _) => first.TrySetResult();
_now = controller.Plan[0].Start; // on air at the planned start, so the held delay is the news
controller.Start();
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
_now = _now.AddMinutes(2);
@@ -140,6 +141,7 @@ public sealed class ScheduleControllerTests : IDisposable
controller.ItemStarted += (_, _) => first.TrySetResult();
var request = _songs.GetAll()[3];
_now = controller.Plan[0].Start; // on air at the planned start, so the held delay is the news
controller.Start();
await first.Task.WaitAsync(TimeSpan.FromSeconds(5));
@@ -159,4 +161,34 @@ public sealed class ScheduleControllerTests : IDisposable
controller.CreatePlan(1);
Assert.Throws<ScheduleException>(() => controller.Swap(1, 12345));
}
[Fact]
public async Task Start_WaitsForThePlannedStart()
{
AddSongs();
var hold = new TaskCompletionSource();
var controller = Create((_, token) => hold.Task.WaitAsync(token));
controller.CreatePlan(1);
controller.Start(); // at 14:37:12, the plan starts at 15:00
var deadline = DateTime.UtcNow.AddSeconds(5);
while (controller.WaitingUntil is null && DateTime.UtcNow < deadline) await Task.Delay(10);
Assert.Equal(new DateTime(2026, 11, 23, 15, 0, 0), controller.WaitingUntil);
Assert.True(controller.IsPlaying);
Assert.Null(controller.CurrentItem);
controller.Stop();
Assert.Null(controller.WaitingUntil);
}
[Fact]
public void Start_RejectsAPlanThatIsOver()
{
AddSongs();
var controller = Create();
controller.CreatePlan(1);
_now = controller.Plan[^1].Start;
Assert.Throws<InvalidOperationException>(() => controller.Start());
}}