diff --git a/src/Radiosender/Services/IAudioPlayer.cs b/src/Radiosender/Services/IAudioPlayer.cs new file mode 100644 index 0000000..295082c --- /dev/null +++ b/src/Radiosender/Services/IAudioPlayer.cs @@ -0,0 +1,11 @@ +namespace Radiosender.Services; + +/// The part of the playback engine needs; lets tests run without audio. +public interface IAudioPlayer +{ + event EventHandler? TrackFinished; + + void Play(string filePath); + + void Stop(); +} diff --git a/src/Radiosender/Services/MusicPlayer.cs b/src/Radiosender/Services/MusicPlayer.cs index c84fd16..eb51a31 100644 --- a/src/Radiosender/Services/MusicPlayer.cs +++ b/src/Radiosender/Services/MusicPlayer.cs @@ -11,7 +11,7 @@ namespace Radiosender.Services; /// never on the WPF UI thread. WPF callers must marshal with Dispatcher.Invoke or /// Dispatcher.BeginInvoke before touching UI elements. /// -public sealed class MusicPlayer +public sealed class MusicPlayer : IAudioPlayer { private static readonly Lazy LazyInstance = new(() => new MusicPlayer()); diff --git a/src/Radiosender/Services/PlaybackEngine.cs b/src/Radiosender/Services/PlaybackEngine.cs new file mode 100644 index 0000000..530c188 --- /dev/null +++ b/src/Radiosender/Services/PlaybackEngine.cs @@ -0,0 +1,148 @@ +using Radiosender.Models; + +namespace Radiosender.Services; + +/// +/// Runs a generated schedule from start to end: songs play through the audio player, news, ads and +/// moderator placeholders are held for their duration. +/// +/// +/// Events are raised on the engine's thread-pool thread. WPF callers must marshal with +/// Dispatcher.BeginInvoke, not Dispatcher.Invoke: waits for that thread, +/// so a handler that blocks on the UI thread while the UI calls Stop would deadlock. +/// +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 _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 delay) + { + _player = player; + _delay = delay; + } + + /// Raised when an item starts, with its index in . + public event EventHandler<(int Index, ScheduleItem Item)>? ItemStarted; + + /// Raised when a song cannot be played; the engine then moves on to the next item. + public event EventHandler<(ScheduleItem Item, Exception Error)>? ItemFailed; + + /// Raised after the last item has ended. Not raised by . + public event EventHandler? Finished; + + public IReadOnlyList Items { get; private set; } = []; + + /// Index of the item that is playing, or -1 when the engine is not running. + public int CurrentIndex { get; private set; } = -1; + + public bool IsRunning => !_run.IsCompleted; + + /// Stops any running schedule and starts from the first item. + public void Start(IReadOnlyList items) + { + Stop(); + lock (_lock) + { + Items = items; + _cts = new CancellationTokenSource(); + var token = _cts.Token; + _run = Task.Run(() => RunAsync(token)); + } + } + + /// Stops playback. Waits until the running schedule has ended. + 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(); + } + } +} diff --git a/tests/Radiosender.Tests/PlaybackEngineTests.cs b/tests/Radiosender.Tests/PlaybackEngineTests.cs new file mode 100644 index 0000000..650dd64 --- /dev/null +++ b/tests/Radiosender.Tests/PlaybackEngineTests.cs @@ -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); + + /// Finishes each track right away unless told to hang or fail. + private sealed class FakePlayer : IAudioPlayer + { + public ConcurrentQueue 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 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 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 Started, TaskCompletionSource Finished) Create(FakePlayer player, FakeClock clock) + { + var engine = new PlaybackEngine(player, clock.Delay); + var started = new List(); + 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(); + 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(); + engine.ItemFailed += (_, e) => failed.Add(e.Error); + + engine.Start(Plan); + await finished.Task.WaitAsync(Wait); + + Assert.IsType(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); + } +}