diff --git a/src/Radiosender/App.xaml.cs b/src/Radiosender/App.xaml.cs index 1a339b1..d33ba2d 100644 --- a/src/Radiosender/App.xaml.cs +++ b/src/Radiosender/App.xaml.cs @@ -1,4 +1,5 @@ using System.Windows; +using Radiosender.Controllers; using Radiosender.Services; namespace Radiosender; @@ -7,10 +8,20 @@ public partial class App : Application { public static SongRepository Songs { get; private set; } = null!; + /// App-wide, so a running broadcast keeps going while the user switches pages. + public static ScheduleController Schedule { get; private set; } = null!; + protected override void OnStartup(StartupEventArgs e) { // Creates the database file and table on first start. Songs = new SongRepository(SongRepository.DefaultDatabasePath); + Schedule = new ScheduleController(Songs, new ScheduleGenerator(), new PlaybackEngine(), () => DateTime.Now); base.OnStartup(e); } + + protected override void OnExit(ExitEventArgs e) + { + Schedule.Stop(); + base.OnExit(e); + } } diff --git a/src/Radiosender/Controllers/ScheduleController.cs b/src/Radiosender/Controllers/ScheduleController.cs new file mode 100644 index 0000000..ef7f063 --- /dev/null +++ b/src/Radiosender/Controllers/ScheduleController.cs @@ -0,0 +1,84 @@ +using Radiosender.Models; +using Radiosender.Services; + +namespace Radiosender.Controllers; + +/// +/// Creates the broadcast plan and drives its playback. One instance lives for the whole app +/// (), so the plan survives page navigation. +/// +/// Events come from the playback engine's thread pool; views marshal with Dispatcher.BeginInvoke. +public class ScheduleController +{ + public const int MaxHours = 24; + + private readonly SongRepository _songs; + private readonly ScheduleGenerator _generator; + private readonly PlaybackEngine _engine; + private readonly Func _now; + private DateTime _itemStartedAt; + + public ScheduleController(SongRepository songs, ScheduleGenerator generator, PlaybackEngine engine, Func now) + { + _songs = songs; + _generator = generator; + _engine = engine; + _now = now; + _engine.ItemStarted += (_, e) => + { + _itemStartedAt = _now(); + ItemStarted?.Invoke(this, e.Index); + }; + _engine.ItemFailed += (_, e) => ItemFailed?.Invoke(this, $"Skipped \"{e.Item.Title}\": {e.Error.Message}"); + _engine.Finished += (_, _) => Finished?.Invoke(this, EventArgs.Empty); + } + + public event EventHandler? ItemStarted; + public event EventHandler? ItemFailed; + public event EventHandler? Finished; + + public IReadOnlyList Plan { get; private set; } = []; + + public bool IsPlaying => _engine.IsRunning; + + public int CurrentIndex => _engine.CurrentIndex; + + /// The item on air, or null when nothing plays. + public ScheduleItem? CurrentItem => CurrentIndex is var i && i >= 0 && i < _engine.Items.Count ? _engine.Items[i] : null; + + /// Time since the current item started, capped at its duration. + public TimeSpan CurrentElapsed => CurrentItem is { } item + ? TimeSpan.FromTicks(Math.Clamp((_now() - _itemStartedAt).Ticks, 0, item.Duration.Ticks)) + : TimeSpan.Zero; + + /// Playback volume from 0 to 1. + public float Volume + { + get => MusicPlayer.Instance.Volume; + set => MusicPlayer.Instance.Volume = value; + } + + /// Plans full hours from the next full hour with the songs in the library. + /// The library cannot fill the plan. + public IReadOnlyList CreatePlan(int hours) + { + ArgumentOutOfRangeException.ThrowIfLessThan(hours, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(hours, MaxHours); + + var now = _now(); + var nextHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind).AddHours(1); + Stop(); + Plan = _generator.Generate(nextHour, hours, _songs.GetAll()); + return Plan; + } + + /// Plays the plan from its first item; the planned times are the on-air clock, playback starts right away. + public void Start() + { + if (Plan.Count == 0) + throw new InvalidOperationException("Create a schedule first."); + _engine.Start(Plan); + } + + public void Stop() => _engine.Stop(); +} diff --git a/src/Radiosender/Views/MainWindow.xaml b/src/Radiosender/Views/MainWindow.xaml index 46b5e60..728ceff 100644 --- a/src/Radiosender/Views/MainWindow.xaml +++ b/src/Radiosender/Views/MainWindow.xaml @@ -22,6 +22,9 @@ + diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml b/src/Radiosender/Views/Pages/SchedulePage.xaml new file mode 100644 index 0000000..b4e5cfc --- /dev/null +++ b/src/Radiosender/Views/Pages/SchedulePage.xaml @@ -0,0 +1,169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs new file mode 100644 index 0000000..d297ff9 --- /dev/null +++ b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs @@ -0,0 +1,149 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Threading; +using Radiosender.Controllers; +using Radiosender.Services; +using Wpf.Ui.Controls; + +namespace Radiosender.Views.Pages; + +public partial class SchedulePage : Page +{ + private readonly ScheduleController _controller = App.Schedule; + private readonly DispatcherTimer _progressTimer = new() { Interval = TimeSpan.FromMilliseconds(250) }; + private bool _loading; + + public SchedulePage() + { + InitializeComponent(); + // Also refreshes the buttons: Finished can arrive just before the engine reports it stopped. + _progressTimer.Tick += (_, _) => + { + UpdateButtons(); + UpdateProgress(); + }; + } + + // The page can be shown again while a broadcast runs, so it always rebuilds from the controller. + private void OnLoaded(object sender, RoutedEventArgs e) + { + _controller.ItemStarted += OnItemStarted; + _controller.ItemFailed += OnItemFailed; + _controller.Finished += OnFinished; + + _loading = true; + VolumeSlider.Value = _controller.Volume; + _loading = false; + + ShowPlan(); + ShowCurrent(); + _progressTimer.Start(); + } + + private void OnUnloaded(object sender, RoutedEventArgs e) + { + _controller.ItemStarted -= OnItemStarted; + _controller.ItemFailed -= OnItemFailed; + _controller.Finished -= OnFinished; + _progressTimer.Stop(); + } + + private void OnCreate(object sender, RoutedEventArgs e) + { + var hours = (int)(HoursBox.Value ?? 1); + try + { + _controller.CreatePlan(hours); + var plan = _controller.Plan; + ShowMessage(InfoBarSeverity.Success, "Schedule created", + $"{hours} h from {plan[0].Start:HH:mm} to {plan[^1].End:HH:mm}, {plan.Count} items."); + } + catch (Exception ex) when (ex is ScheduleException or ArgumentOutOfRangeException) + { + ShowMessage(InfoBarSeverity.Error, "Could not create the schedule", ex.Message); + } + ShowPlan(); + ShowCurrent(); + } + + private void OnStart(object sender, RoutedEventArgs e) + { + Message.IsOpen = false; + _controller.Start(); + ShowCurrent(); + } + + private void OnStop(object sender, RoutedEventArgs e) + { + _controller.Stop(); + ShowCurrent(); + } + + private void OnVolumeChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (!_loading) _controller.Volume = (float)e.NewValue; + } + + // Engine events arrive on a pool thread. BeginInvoke, not Invoke: Stop waits for that thread. + private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent); + + private void OnItemFailed(object? sender, string message) => + Dispatcher.BeginInvoke(() => ShowMessage(InfoBarSeverity.Warning, "Item skipped", message)); + + private void OnFinished(object? sender, EventArgs e) => Dispatcher.BeginInvoke(() => + { + ShowMessage(InfoBarSeverity.Informational, "Broadcast finished", "The whole schedule has been played."); + ShowCurrent(); + }); + + private void ShowPlan() + { + Timeline.ItemsSource = _controller.Plan; + EmptyText.Visibility = _controller.Plan.Count == 0 ? Visibility.Visible : Visibility.Collapsed; + } + + private void ShowCurrent() + { + var item = _controller.CurrentItem; + UpdateButtons(); + + NowKind.Content = item; + NowKind.Visibility = item is null ? Visibility.Collapsed : Visibility.Visible; + NowTitle.Text = item?.Title ?? "Nothing on air"; + + Timeline.SelectedIndex = _controller.CurrentIndex; + if (Timeline.SelectedItem is { } selected) + Timeline.ScrollIntoView(selected); + + UpdateProgress(); + } + + private void UpdateButtons() + { + var playing = _controller.IsPlaying; + StartButton.IsEnabled = !playing && _controller.Plan.Count > 0; + StopButton.IsEnabled = playing; + } + + private void UpdateProgress() + { + if (_controller.CurrentItem is not { } item) + { + NowProgress.Value = 0; + NowTime.Text = " "; + return; + } + + var elapsed = _controller.CurrentElapsed; + NowProgress.Value = item.Duration.Ticks == 0 ? 0 : (double)elapsed.Ticks / item.Duration.Ticks; + NowTime.Text = $"{elapsed:m\\:ss} / {item.Duration:m\\:ss} · planned {item.Start:HH:mm:ss}"; + } + + private void ShowMessage(InfoBarSeverity severity, string title, string text) + { + Message.Severity = severity; + Message.Title = title; + Message.Message = text; + Message.IsOpen = true; + } +} diff --git a/tests/Radiosender.Tests/ScheduleControllerTests.cs b/tests/Radiosender.Tests/ScheduleControllerTests.cs new file mode 100644 index 0000000..cf29a17 --- /dev/null +++ b/tests/Radiosender.Tests/ScheduleControllerTests.cs @@ -0,0 +1,117 @@ +using Microsoft.Data.Sqlite; +using Radiosender.Controllers; +using Radiosender.Models; +using Radiosender.Services; + +namespace Radiosender.Tests; + +public sealed class ScheduleControllerTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N")); + private readonly SongRepository _songs; + private DateTime _now = new(2026, 11, 23, 14, 37, 12); + + public ScheduleControllerTests() => _songs = new SongRepository(Path.Combine(_directory, "test.db")); + + public void Dispose() + { + SqliteConnection.ClearAllPools(); + Directory.Delete(_directory, recursive: true); + } + + private sealed class InstantPlayer : IAudioPlayer + { + public event EventHandler? TrackFinished; + public void Play(string filePath) => TrackFinished?.Invoke(this, EventArgs.Empty); + public void Stop() { } + } + + private ScheduleController Create(Func? delay = null) => + new(_songs, + new ScheduleGenerator(new ScheduleOptions(), new Random(7)), + new PlaybackEngine(new InstantPlayer(), delay ?? ((_, _) => Task.CompletedTask)), + () => _now); + + private void AddSongs() + { + int[] seconds = [192, 245, 167, 331, 238, 183, 369, 141]; + for (var i = 0; i < seconds.Length; i++) + _songs.Add(new Song { Title = $"Song {i}", Artist = "Artist", Duration = TimeSpan.FromSeconds(seconds[i]), FilePath = $"{i}.mp3" }); + } + + [Fact] + public void CreatePlan_StartsAtNextFullHourAndCoversTheHours() + { + AddSongs(); + var controller = Create(); + + var plan = controller.CreatePlan(2); + + Assert.Equal(new DateTime(2026, 11, 23, 15, 0, 0), plan[0].Start); + Assert.Equal(new DateTime(2026, 11, 23, 17, 0, 0), plan[^1].End); + Assert.Same(plan, controller.Plan); + } + + [Fact] + public void CreatePlan_ThrowsScheduleExceptionForEmptyLibrary() + { + Assert.Throws(() => Create().CreatePlan(1)); + } + + [Theory] + [InlineData(0)] + [InlineData(25)] + public void CreatePlan_RejectsHoursOutOfRange(int hours) + { + AddSongs(); + Assert.Throws(() => Create().CreatePlan(hours)); + } + + [Fact] + public void Start_WithoutPlanThrows() + { + Assert.Throws(() => Create().Start()); + } + + [Fact] + public async Task Start_PlaysThePlanAndRaisesFinished() + { + AddSongs(); + var controller = Create(); + controller.CreatePlan(1); + var started = 0; + var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + controller.ItemStarted += (_, _) => Interlocked.Increment(ref started); + controller.Finished += (_, _) => finished.TrySetResult(); + + controller.Start(); + await finished.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.Equal(controller.Plan.Count, started); + Assert.Null(controller.CurrentItem); + } + + [Fact] + public async Task CurrentItemAndElapsed_FollowThePlayingItem() + { + 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(); + + controller.Start(); + await first.Task.WaitAsync(TimeSpan.FromSeconds(5)); + _now = _now.AddMinutes(2); + + Assert.Equal(ScheduleItemKind.News, controller.CurrentItem!.Kind); + Assert.Equal(TimeSpan.FromMinutes(2), controller.CurrentElapsed); + _now = _now.AddHours(1); + Assert.Equal(controller.CurrentItem.Duration, controller.CurrentElapsed); + + controller.Stop(); + Assert.False(controller.IsPlaying); + Assert.Null(controller.CurrentItem); + } +}