Merge branch 'j.lechner/playback-engine' into 'main'

feat: add playback engine that runs a schedule

Closes #9

See merge request julian/blockwoche3.1-radiosender!9
This commit is contained in:
Julian Lechner committed 2026-11-23 09:53:28 +00:00
commit 992b74e42d
4 files changed
+322 -1

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
namespace Radiosender.Services;
/// <summary>The part of <see cref="MusicPlayer"/> the playback engine needs; lets tests run without audio.</summary>
public interface IAudioPlayer
{
event EventHandler? TrackFinished;
void Play(string filePath);
void Stop();
}
+1 -1
View File
@@ -11,7 +11,7 @@ namespace Radiosender.Services;
/// never on the WPF UI thread. WPF callers must marshal with <c>Dispatcher.Invoke</c> or
/// <c>Dispatcher.BeginInvoke</c> before touching UI elements.
/// </remarks>
public sealed class MusicPlayer
public sealed class MusicPlayer : IAudioPlayer
{
private static readonly Lazy<MusicPlayer> LazyInstance = new(() => new MusicPlayer());
+148
View File
@@ -0,0 +1,148 @@
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.
/// </summary>
/// <remarks>
/// Events are raised on the engine's thread-pool thread. WPF callers must marshal with
/// <c>Dispatcher.BeginInvoke</c>, not <c>Dispatcher.Invoke</c>: <see cref="Stop"/> waits for that thread,
/// so a handler that blocks on the UI thread while the UI calls Stop would deadlock.
/// </remarks>
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);
private readonly IAudioPlayer _player;
private readonly Func<TimeSpan, CancellationToken, Task> _delay;
private readonly Lock _lock = new();
private CancellationTokenSource? _cts;
private Task _run = Task.CompletedTask;
public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay)
{
}
public PlaybackEngine(IAudioPlayer player, Func<TimeSpan, CancellationToken, Task> delay)
{
_player = player;
_delay = delay;
}
/// <summary>Raised when an item starts, with its index in <see cref="Items"/>.</summary>
public event EventHandler<(int Index, ScheduleItem Item)>? ItemStarted;
/// <summary>Raised when a song cannot be played; the engine then moves on to the next item.</summary>
public event EventHandler<(ScheduleItem Item, Exception Error)>? ItemFailed;
/// <summary>Raised after the last item has ended. Not raised by <see cref="Stop"/>.</summary>
public event EventHandler? Finished;
public IReadOnlyList<ScheduleItem> Items { get; private set; } = [];
/// <summary>Index of the item that is playing, or -1 when the engine is not running.</summary>
public int CurrentIndex { get; private set; } = -1;
public bool IsRunning => !_run.IsCompleted;
/// <summary>Stops any running schedule and starts <paramref name="items"/> from the first item.</summary>
public void Start(IReadOnlyList<ScheduleItem> items)
{
Stop();
lock (_lock)
{
Items = items;
_cts = new CancellationTokenSource();
var token = _cts.Token;
_run = Task.Run(() => RunAsync(token));
}
}
/// <summary>Stops playback. Waits until the running schedule has ended.</summary>
public void Stop()
{
Task run;
lock (_lock)
{
_cts?.Cancel();
run = _run;
}
try
{
run.Wait();
}
catch (AggregateException ex) when (ex.InnerExceptions.All(e => e is OperationCanceledException))
{
}
lock (_lock)
{
_cts?.Dispose();
_cts = null;
}
}
private async Task RunAsync(CancellationToken token)
{
try
{
for (var i = 0; i < Items.Count; i++)
{
token.ThrowIfCancellationRequested();
var item = Items[i];
CurrentIndex = i;
ItemStarted?.Invoke(this, (i, item));
if (item.Kind == ScheduleItemKind.Song && item.Song is not null)
await PlaySongAsync(item, token);
else
await _delay(item.Duration, token);
}
CurrentIndex = -1;
Finished?.Invoke(this, EventArgs.Empty);
}
catch (OperationCanceledException)
{
CurrentIndex = -1;
}
}
private async Task PlaySongAsync(ScheduleItem item, CancellationToken token)
{
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
void OnFinished(object? sender, EventArgs e) => finished.TrySetResult();
_player.TrackFinished += OnFinished;
try
{
try
{
_player.Play(item.Song!.FilePath);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
ItemFailed?.Invoke(this, (item, ex));
return;
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
var stuck = _delay(item.Duration + SongGrace, timeout.Token);
var done = await Task.WhenAny(finished.Task, stuck);
timeout.Cancel();
token.ThrowIfCancellationRequested();
if (done == stuck)
ItemFailed?.Invoke(this, (item, new TimeoutException($"Song did not finish in time: {item.Title}")));
}
finally
{
_player.TrackFinished -= OnFinished;
// On cancel, timeout or a failed start the song has not ended by itself.
if (!finished.Task.IsCompleted) _player.Stop();
}
}
}
@@ -0,0 +1,162 @@
using System.Collections.Concurrent;
using Radiosender.Models;
using Radiosender.Services;
namespace Radiosender.Tests;
public class PlaybackEngineTests
{
private static readonly DateTime Start = new(2026, 11, 23, 14, 0, 0);
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(5);
/// <summary>Finishes each track right away unless told to hang or fail.</summary>
private sealed class FakePlayer : IAudioPlayer
{
public ConcurrentQueue<string> Played { get; } = new();
public int StopCount;
public string? FailPath;
public string? HangPath;
public event EventHandler? TrackFinished;
public void Play(string filePath)
{
if (filePath == FailPath) throw new FileNotFoundException("missing", filePath);
Played.Enqueue(filePath);
if (filePath != HangPath)
TrackFinished?.Invoke(this, EventArgs.Empty);
}
public void Stop() => Interlocked.Increment(ref StopCount);
}
// Records requested delays and completes them at once. Song timeouts (song length + 10 s) and,
// with Hold, every delay only end on cancellation.
private sealed class FakeClock(bool songTimeoutsFire = false)
{
private static readonly TimeSpan[] SongTimeouts = [TimeSpan.FromSeconds(210), TimeSpan.FromSeconds(190), TimeSpan.FromSeconds(110)];
public ConcurrentQueue<TimeSpan> Delays { get; } = new();
public volatile bool Hold;
public Task Delay(TimeSpan duration, CancellationToken token)
{
Delays.Enqueue(duration);
var held = Hold || (!songTimeoutsFire && SongTimeouts.Contains(duration));
return held ? Task.Delay(Timeout.Infinite, token) : Task.CompletedTask;
}
}
private static ScheduleItem SongItem(string path, int seconds) =>
new(ScheduleItemKind.Song, path, Start, TimeSpan.FromSeconds(seconds),
new Song { Title = path, FilePath = path, Duration = TimeSpan.FromSeconds(seconds) });
private static ScheduleItem Placeholder(ScheduleItemKind kind, int seconds) =>
new(kind, kind.ToString(), Start, TimeSpan.FromSeconds(seconds));
private static readonly IReadOnlyList<ScheduleItem> Plan =
[
Placeholder(ScheduleItemKind.News, 300),
SongItem("a.mp3", 200),
Placeholder(ScheduleItemKind.Ad, 45),
Placeholder(ScheduleItemKind.Moderator, 60),
SongItem("b.mp3", 180),
];
private static (PlaybackEngine Engine, List<int> Started, TaskCompletionSource Finished) Create(FakePlayer player, FakeClock clock)
{
var engine = new PlaybackEngine(player, clock.Delay);
var started = new List<int>();
var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
engine.ItemStarted += (_, e) => { lock (started) started.Add(e.Index); };
engine.Finished += (_, _) => finished.TrySetResult();
return (engine, started, finished);
}
[Fact]
public async Task Start_PlaysAllItemsInOrderWithoutInput()
{
var player = new FakePlayer();
var clock = new FakeClock();
var (engine, started, finished) = Create(player, clock);
engine.Start(Plan);
await finished.Task.WaitAsync(Wait);
Assert.Equal([0, 1, 2, 3, 4], started);
Assert.Equal(["a.mp3", "b.mp3"], player.Played);
// Placeholders are held for their own duration.
Assert.Contains(TimeSpan.FromSeconds(300), clock.Delays);
Assert.Contains(TimeSpan.FromSeconds(45), clock.Delays);
Assert.Contains(TimeSpan.FromSeconds(60), clock.Delays);
Assert.Equal(-1, engine.CurrentIndex);
Assert.False(engine.IsRunning);
}
[Fact]
public async Task Start_SkipsSongThatCannotBePlayed()
{
var player = new FakePlayer { FailPath = "a.mp3" };
var (engine, started, finished) = Create(player, new FakeClock());
var failed = new List<ScheduleItem>();
engine.ItemFailed += (_, e) => failed.Add(e.Item);
engine.Start(Plan);
await finished.Task.WaitAsync(Wait);
Assert.Equal("a.mp3", Assert.Single(failed).Title);
Assert.Equal(["b.mp3"], player.Played);
Assert.Equal([0, 1, 2, 3, 4], started);
}
[Fact]
public async Task Start_MovesOnWhenSongNeverFinishes()
{
var player = new FakePlayer { HangPath = "a.mp3" };
var (engine, _, finished) = Create(player, new FakeClock(songTimeoutsFire: true));
var failed = new List<Exception>();
engine.ItemFailed += (_, e) => failed.Add(e.Error);
engine.Start(Plan);
await finished.Task.WaitAsync(Wait);
Assert.IsType<TimeoutException>(Assert.Single(failed));
Assert.Equal(["a.mp3", "b.mp3"], player.Played);
Assert.True(player.StopCount >= 1);
}
[Fact]
public async Task Stop_EndsPlaybackWithoutFinishedEvent()
{
var player = new FakePlayer();
var clock = new FakeClock { Hold = true };
var (engine, started, finished) = Create(player, clock);
engine.Start(Plan);
while (clock.Delays.IsEmpty) await Task.Delay(10);
engine.Stop();
Assert.False(engine.IsRunning);
Assert.Equal(-1, engine.CurrentIndex);
Assert.Equal([0], started);
Assert.False(finished.Task.IsCompleted);
}
[Fact]
public async Task Start_ReplacesARunningSchedule()
{
var player = new FakePlayer();
var clock = new FakeClock { Hold = true };
var (engine, _, _) = Create(player, clock);
engine.Start(Plan);
while (clock.Delays.IsEmpty) await Task.Delay(10);
clock.Hold = false;
var finished = new TaskCompletionSource();
engine.Finished += (_, _) => finished.TrySetResult();
engine.Start([SongItem("c.mp3", 100)]);
await finished.Task.WaitAsync(Wait);
Assert.Equal(["c.mp3"], player.Played);
}
}