diff --git a/src/Radiosender/App.xaml.cs b/src/Radiosender/App.xaml.cs
index b0d8eab..ffae6e2 100644
--- a/src/Radiosender/App.xaml.cs
+++ b/src/Radiosender/App.xaml.cs
@@ -1,29 +1,31 @@
-using System.Windows;
+using System.Net.Http;
+using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Radiosender.Controllers;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Library;
+using Radiosender.Services.Providers;
+using Radiosender.Services.Scheduling;
+using Radiosender.Services.Settings;
using Radiosender.Views;
using Radiosender.Views.Pages;
namespace Radiosender;
-/// Composition root: wires every service, controller and page once, at startup.
public partial class App : Application
{
private ServiceProvider? _services;
private static ServiceProvider BuildServices()
{
- var services = new ServiceCollection();
+ ServiceCollection services = new();
- // One instance each for the whole app. The schedule controller in particular must be shared,
- // so a running broadcast keeps going while the user switches pages.
+ // Singletons: broadcast must survive page switches.
services.AddSingleton(_ => new SongRepository(SongRepository.DefaultDatabasePath));
services.AddSingleton(_ => new ScheduleGenerator());
services.AddSingleton(provider => new SettingsStore(
provider.GetRequiredService(), provider.GetRequiredService(), AppSettings.DefaultPath));
services.AddSingleton(_ => new PlaybackEngine());
- // The one audio channel that songs and the microphone share.
services.AddSingleton(_ => ProgramOutput.Instance);
services.AddSingleton();
services.AddSingleton(provider => new ScheduleController(
@@ -31,32 +33,29 @@ public partial class App : Application
provider.GetRequiredService(),
provider.GetRequiredService(),
() => DateTime.Now));
- // One HttpClient for all providers and downloads.
services.AddSingleton(_ =>
{
- var http = new System.Net.Http.HttpClient { Timeout = TimeSpan.FromSeconds(20) };
+ var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("Radiosender/1.0");
return http;
});
- // Music providers: add a line here for each new IMusicProvider; the import page lists them all.
+ // Import page lists providers in this order.
services.AddSingleton();
services.AddSingleton();
- // The station's own library; listed only while laut.fm is switched on in the settings.
services.AddSingleton(provider => new LautFmProvider(
- provider.GetRequiredService(), () => provider.GetRequiredService().Current));
+ provider.GetRequiredService(), () => provider.GetRequiredService().Current));
services.AddSingleton(provider => new LiveController(
provider.GetRequiredService(),
provider.GetRequiredService(),
provider.GetRequiredService(),
- provider.GetRequiredService(),
+ provider.GetRequiredService(),
() => DateTime.Now));
- services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService(), TrackDownloader.DefaultMusicFolder));
+ services.AddSingleton(provider => new TrackDownloader(provider.GetRequiredService(), TrackDownloader.DefaultMusicFolder));
services.AddSingleton();
services.AddSingleton(provider => new SongImportService(provider.GetRequiredService(), SongImportService.DefaultMusicDirectory));
services.AddSingleton();
services.AddSingleton();
- // Pages are created anew on every navigation, as before; they hold only view state.
services.AddSingleton();
services.AddTransient();
services.AddTransient();
@@ -70,9 +69,8 @@ public partial class App : Application
{
base.OnStartup(e);
_services = BuildServices();
- // Loads the settings: the generator gets its minutes per hour before the first plan, the audio output its devices.
+ // Eager: applies settings to generator and audio output before first plan.
_services.GetRequiredService();
- // Follow the Windows setting: light, dark or a high-contrast theme.
Wpf.Ui.Appearance.ApplicationThemeManager.ApplySystemTheme();
_services.GetRequiredService().Show();
}
diff --git a/src/Radiosender/AssemblyInfo.cs b/src/Radiosender/AssemblyInfo.cs
index cc29e7f..76af59d 100644
--- a/src/Radiosender/AssemblyInfo.cs
+++ b/src/Radiosender/AssemblyInfo.cs
@@ -1,10 +1,3 @@
using System.Windows;
-[assembly:ThemeInfo(
- ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
- //(used if a resource is not found in the page,
- // or application resource dictionaries)
- ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
- //(used if a resource is not found in the page,
- // app, or any theme specific resource dictionaries)
-)]
+[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
diff --git a/src/Radiosender/Controllers/LibraryController.cs b/src/Radiosender/Controllers/LibraryController.cs
index 832c617..f4ff98a 100644
--- a/src/Radiosender/Controllers/LibraryController.cs
+++ b/src/Radiosender/Controllers/LibraryController.cs
@@ -1,11 +1,10 @@
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Library;
namespace Radiosender.Controllers;
public class LibraryController(SongRepository repository)
{
- /// Returns all songs whose title or artist contains (case-insensitive).
public IReadOnlyList Search(string? query)
{
var songs = repository.GetAll();
@@ -13,14 +12,10 @@ public class LibraryController(SongRepository repository)
return songs;
query = query.Trim();
- return songs
- .Where(s => s.Title.Contains(query, StringComparison.OrdinalIgnoreCase)
- || s.Artist.Contains(query, StringComparison.OrdinalIgnoreCase))
- .ToList();
+ return [.. songs.Where(s => s.Title.Contains(query, StringComparison.OrdinalIgnoreCase)
+ || s.Artist.Contains(query, StringComparison.OrdinalIgnoreCase))];
}
- /// Writes the editable metadata; file path, duration and source keep their stored values.
- /// false if the song no longer exists.
public bool Update(long id, string title, string artist, string? license, string? attribution)
{
ArgumentException.ThrowIfNullOrWhiteSpace(title);
@@ -37,6 +32,5 @@ public class LibraryController(SongRepository repository)
return repository.Update(song);
}
- /// false if the song no longer exists.
public bool Delete(long id) => repository.Delete(id);
}
diff --git a/src/Radiosender/Controllers/LiveController.cs b/src/Radiosender/Controllers/LiveController.cs
index 3bca538..94de39a 100644
--- a/src/Radiosender/Controllers/LiveController.cs
+++ b/src/Radiosender/Controllers/LiveController.cs
@@ -1,13 +1,11 @@
using System.Net.Http;
using NAudio.Wave;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Settings;
+using Radiosender.Services.Streaming;
namespace Radiosender.Controllers;
-///
-/// Sends the broadcast mix live to laut.fm, independent of the plan: whatever is on air goes out,
-/// and each item that starts sets the stream title.
-///
public class LiveController
{
private readonly ScheduleController _schedule;
@@ -30,19 +28,15 @@ public class LiveController
_schedule.ItemStarted += (_, _) => SendCurrentTitle();
}
- /// laut.fm is switched on in the settings.
public bool IsEnabled => _settings.Current.LautFmEnabled;
public bool IsLive => _stream is not null;
- ///
- /// Something went wrong: the stream broke (then is false) or a title was not taken.
- /// Raised on a background thread.
- ///
+ // Background thread.
public event EventHandler? Problem;
- /// laut.fm is off or cannot be reached, or the login was refused.
- /// No audio output device can be opened; the broadcast device sets the pace.
+ /// laut.fm off, unreachable, or login refused.
+ /// No audio output device.
public async Task StartAsync(CancellationToken cancellationToken = default)
{
if (IsLive)
@@ -74,7 +68,7 @@ public class LiveController
public void Stop() => Stop(null);
- // With a stream given, stops only if that one is still the current stream.
+ // only != null: stop only if still current stream.
private void Stop(IcecastStream? only)
{
IcecastStream stream;
diff --git a/src/Radiosender/Controllers/OnlineImportController.cs b/src/Radiosender/Controllers/OnlineImportController.cs
index d13237e..c118dca 100644
--- a/src/Radiosender/Controllers/OnlineImportController.cs
+++ b/src/Radiosender/Controllers/OnlineImportController.cs
@@ -1,22 +1,19 @@
using System.IO;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Library;
+using Radiosender.Services.Providers;
namespace Radiosender.Controllers;
-/// Searches the registered music providers and imports their results into the library.
public class OnlineImportController(IEnumerable providers, TrackDownloader downloader, SongRepository songs)
{
- private readonly IReadOnlyList _providers = providers.ToList();
+ private readonly IReadOnlyList _providers = [.. providers];
- /// The providers registered in App that are available now, in registration order.
- public IReadOnlyList Providers => _providers.Where(provider => provider.IsAvailable).ToList();
+ public IReadOnlyList Providers => [.. _providers.Where(provider => provider.IsAvailable)];
- /// Ids of the provider results that are already in the library.
public IReadOnlySet ImportedIds() => songs.GetExternalIds();
- /// Downloads the track and stores it as a song with its license and attribution.
- /// The track cannot be imported or the download failed.
+ /// Track not importable or download failed.
public async Task ImportAsync(MusicTrack track, CancellationToken cancellationToken = default)
{
if (track.Duration is not { } duration)
diff --git a/src/Radiosender/Controllers/ScheduleController.cs b/src/Radiosender/Controllers/ScheduleController.cs
index ef8cd31..51457bc 100644
--- a/src/Radiosender/Controllers/ScheduleController.cs
+++ b/src/Radiosender/Controllers/ScheduleController.cs
@@ -1,25 +1,22 @@
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Library;
+using Radiosender.Services.Scheduling;
namespace Radiosender.Controllers;
-///
-/// Creates the broadcast plan and drives its playback. One instance lives for the whole app
-/// (registered as a singleton in ), so the plan survives page navigation.
-///
-/// Events come from the playback engine's thread pool; views marshal with Dispatcher.BeginInvoke.
+// Events fire on engine thread; views marshal with Dispatcher.BeginInvoke.
public class ScheduleController
{
- public const int MaxHours = 24;
+ private const int MaxHours = 24;
- /// How far ahead an unlimited plan always reaches.
- public const int UnlimitedLookaheadHours = 5;
+ private const int UnlimitedLookaheadHours = 5;
private readonly SongRepository _songs;
private readonly ScheduleGenerator _generator;
private readonly PlaybackEngine _engine;
private readonly Func _now;
- // Guards Plan against a song request (UI thread) racing the hourly extension (engine thread).
+ // Plan edits (UI thread) vs. hourly extension (engine thread).
private readonly Lock _planLock = new();
private DateTime _itemStartedAt;
@@ -45,34 +42,26 @@ public class ScheduleController
public IReadOnlyList Plan { get; private set; } = [];
- /// true for a plan without an end: it grows by an hour whenever less than
- /// hours are left.
public bool IsUnlimited { 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 with the songs in the library; null plans without an end.
- /// The plan begins at , or at the next full hour when that is null.
- ///
- /// The library cannot fill the plan.
+ // hours null = unlimited; start null = next full hour.
+ /// Library cannot fill the plan.
public IReadOnlyList CreatePlan(int? hours, DateTime? start = null)
{
if (hours is { } h)
@@ -83,7 +72,6 @@ public class ScheduleController
var now = _now();
var nextHour = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind).AddHours(1);
- // Whole seconds, so the timeline and the item ends stay on the second.
var from = start is { } s ? new DateTime(s.Ticks - s.Ticks % TimeSpan.TicksPerSecond, s.Kind) : nextHour;
Stop();
var plan = _generator.Generate(from, hours ?? UnlimitedLookaheadHours, _songs.GetAll());
@@ -95,16 +83,14 @@ public class ScheduleController
return plan;
}
- /// Plans from this moment and goes on air at once; music leads up to the first news at :00 or :30.
- /// The library cannot fill the plan.
+ /// Library cannot fill the plan.
public void StartNow(int? hours)
{
CreatePlan(hours, _now());
_engine.Start(Plan);
}
- // Runs on the engine thread whenever an item starts.
- // shortcut: played items stay in the plan (about 20 per hour); trim them if broadcasts run for weeks.
+ // Engine thread. shortcut: played items stay in Plan (~20/h), trim if broadcasts run for weeks.
private void ExtendIfUnlimited()
{
if (!IsUnlimited)
@@ -114,12 +100,12 @@ public class ScheduleController
lock (_planLock)
{
var plan = Plan;
- if (plan.Count == 0) // the user removed every item
+ if (plan.Count == 0)
return;
var until = _now().AddHours(UnlimitedLookaheadHours);
while (plan[^1].End < until)
plan = [.. plan, .. _generator.Generate(plan[^1].End, 1, _songs.GetAll())];
- // Only appends, so the engine keeps everything up to the old end.
+ // Append only: engine keeps items up to old end.
if (!ReferenceEquals(plan, Plan) && _engine.ReplaceUpcoming(plan, Plan.Count))
Plan = plan;
}
@@ -130,13 +116,8 @@ public class ScheduleController
}
}
- /// Planned start of the next item while the broadcast waits for it, otherwise null.
public DateTime? WaitingUntil => CurrentItem is null ? _engine.WaitingUntil : null;
- ///
- /// 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.
- ///
public void Start()
{
if (Plan.Count == 0)
@@ -148,11 +129,7 @@ public class ScheduleController
public void Stop() => _engine.Stop();
- ///
- /// The next news or moderator item that is due for a reminder while the broadcast runs: it starts within
- /// the lead time of its kind. null as lead time switches that kind off. Returns null when
- /// nothing is due.
- ///
+ // Next news/moderator item within its lead time; null lead = kind off.
public ScheduleItem? UpcomingSpeech(TimeSpan? newsLead, TimeSpan? moderatorLead)
{
if (!IsPlaying)
@@ -177,8 +154,7 @@ public class ScheduleController
return null;
}
- /// Moves the item at by positions; later items shift in time.
- /// An affected item is already on air or over, or the target is outside the plan.
+ /// Item on air/over, or target outside plan.
public IReadOnlyList Move(int index, int offset)
{
var target = index + offset;
@@ -192,19 +168,17 @@ public class ScheduleController
});
}
- /// Removes the item at ; later items move up in time.
- /// The item is already on air or over.
+ /// Item on air or over.
public IReadOnlyList Remove(int index) => Change(index, change: items => items.RemoveAt(index));
- /// Ends the item on air now: its length becomes the time it has run, and the next item starts.
- /// Nothing is on air.
+ /// Nothing on air.
public IReadOnlyList EndCurrentNow()
{
var index = CurrentIndex;
if (CurrentItem is null)
throw new ScheduleException("Es ist nichts auf Sendung.");
var now = _now();
- // Whole seconds, like every other time in the plan; the next start is then not in the future.
+ // Whole seconds: next start not in the future.
var end = new DateTime(now.Ticks - now.Ticks % TimeSpan.TicksPerSecond, now.Kind);
return Change(index, currentAllowed: true, change: items =>
{
@@ -213,11 +187,7 @@ public class ScheduleController
});
}
- ///
- /// Sets the title of a news, ad or moderator item, and the length of a news or moderator item;
- /// later items shift in time. Also works for the item on air: its new length counts from its start.
- ///
- /// The item cannot be edited that way, or is already over.
+ /// Edit not allowed for item, or item over.
public IReadOnlyList EditItem(int index, string title, TimeSpan duration) => Change(index, currentAllowed: true, change: items =>
{
var item = items[index];
@@ -230,9 +200,7 @@ public class ScheduleController
items[index] = item with { Title = title.Trim(), Duration = duration };
});
- // Manual edits ripple: from the first changed position on, every item starts when the one before ends.
- // News can therefore leave :00 and :30; that is the user's call.
- // currentAllowed: the item on air may change too; the engine is then told to re-time it.
+ // Ripple re-time from firstChanged; news may leave :00/:30 (intended).
private IReadOnlyList Change(int firstChanged, Action> change, bool currentAllowed = false)
{
lock (_planLock)
@@ -245,7 +213,7 @@ public class ScheduleController
? "Dieses Element ist auf Sendung. Es kann bearbeitet oder beendet, aber nicht verschoben oder entfernt werden."
: "Dieses Element ist bereits vorbei. Ein späteres wählen.");
- var items = Plan.ToList();
+ List items = [.. Plan];
var start = items[firstChanged].Start;
change(items);
for (var i = firstChanged; i < items.Count; i++)
@@ -261,14 +229,10 @@ public class ScheduleController
}
}
- /// All songs in the library, for the song request picker.
public IReadOnlyList LibrarySongs() => _songs.GetAll();
- ///
- /// Hot swap: plays the song in place of the item at .
- /// The rest of that half hour is rebuilt so the next news still starts on time; works while playing.
- ///
- /// The item cannot be replaced or the song does not fit.
+ // Hot swap: rest of half hour rebuilt so next news stays on time.
+ /// Item not replaceable or song does not fit.
public IReadOnlyList Swap(int index, long songId)
{
lock (_planLock)
@@ -282,7 +246,6 @@ public class ScheduleController
var song = _songs.GetById(songId) ?? throw new ScheduleException("Der Song ist nicht mehr in der Bibliothek.");
var plan = _generator.Replace(Plan, index, song, _songs.GetAll());
- // The engine may have moved on while the plan was rebuilt.
if (IsPlaying && !_engine.ReplaceUpcoming(plan, index))
throw new ScheduleException("Dieses Element ist inzwischen auf Sendung gegangen. Ein späteres wählen.");
Plan = plan;
diff --git a/src/Radiosender/Controllers/UploadController.cs b/src/Radiosender/Controllers/UploadController.cs
index 15c71ca..78c963d 100644
--- a/src/Radiosender/Controllers/UploadController.cs
+++ b/src/Radiosender/Controllers/UploadController.cs
@@ -1,16 +1,13 @@
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Library;
namespace Radiosender.Controllers;
-/// The saved song, or null when the upload failed.
-public record UploadResult(bool Success, string Message, Song? Song = null);
-
public class UploadController(SongImportService importService)
{
public static string FileDialogFilter { get; } = "Audiodateien (*.mp3;*.wav)|*.mp3;*.wav";
- /// Imports one file; failures come back as a result, so a batch can go on with the next file.
+ // Never throws: batch continues with next file.
public UploadResult Upload(string filePath)
{
try
diff --git a/src/Radiosender/Controllers/UploadResult.cs b/src/Radiosender/Controllers/UploadResult.cs
new file mode 100644
index 0000000..de24f72
--- /dev/null
+++ b/src/Radiosender/Controllers/UploadResult.cs
@@ -0,0 +1,5 @@
+using Radiosender.Models;
+
+namespace Radiosender.Controllers;
+
+public record UploadResult(bool Success, string Message, Song? Song = null);
diff --git a/src/Radiosender/Models/MusicTrack.cs b/src/Radiosender/Models/MusicTrack.cs
index 7ad0de7..b42cce7 100644
--- a/src/Radiosender/Models/MusicTrack.cs
+++ b/src/Radiosender/Models/MusicTrack.cs
@@ -1,33 +1,24 @@
namespace Radiosender.Models;
-/// One search result of a music provider, in the shape the import works with.
public record MusicTrack
{
- ///
- /// Identifies the track so it is not imported twice. Must be unique across all providers: a new provider
- /// prefixes its ids with its own name. Empty when the provider has no id.
- ///
+ // Unique across providers (prefix with provider name, Openverse unprefixed); empty if none.
public string Id { get; init; } = "";
public string Title { get; init; } = "";
public string? Creator { get; init; }
- /// Direct https link to the audio file.
public string Url { get; init; } = "";
- /// File extension without the dot, e.g. "mp3"; unknown ones are saved as mp3.
public string? FileType { get; init; }
- /// Readable license name, for example "CC BY 4.0".
public string License { get; init; } = "";
public string? Attribution { get; init; }
- /// Length of the track; null when the provider does not know it.
public TimeSpan? Duration { get; init; }
- /// Songs need a duration for scheduling, so results without one cannot be imported.
public bool CanImport => Duration is not null;
public string DurationText => Duration?.ToString(@"m\:ss") ?? "unbekannt";
diff --git a/src/Radiosender/Models/OpenverseTrack.cs b/src/Radiosender/Models/OpenverseTrack.cs
index 3e6b1d7..3774bba 100644
--- a/src/Radiosender/Models/OpenverseTrack.cs
+++ b/src/Radiosender/Models/OpenverseTrack.cs
@@ -1,45 +1,42 @@
+using System.Net;
using System.Text.Json.Serialization;
namespace Radiosender.Models;
-/// One audio result of the Openverse search API (fields as documented at api.openverse.org/v1).
-/// Openverse sends some texts HTML-encoded (&), so the text fields decode on assignment.
+// Openverse sends some texts HTML-encoded: decoded on init.
public class OpenverseTrack
{
public string Id { get; init; } = "";
- public string Title { get; init => field = System.Net.WebUtility.HtmlDecode(value); } = "";
- public string? Creator { get; init => field = System.Net.WebUtility.HtmlDecode(value); }
+ public string Title { get; init => field = WebUtility.HtmlDecode(value); } = "";
+ public string? Creator { get; init => field = WebUtility.HtmlDecode(value); }
public string Url { get; init; } = "";
[JsonPropertyName("filetype")]
public string? FileType { get; init; }
public string License { get; init; } = "";
public string? LicenseVersion { get; init; }
- public string? Attribution { get; init => field = System.Net.WebUtility.HtmlDecode(value); }
+ public string? Attribution { get; init => field = WebUtility.HtmlDecode(value); }
- /// Length in milliseconds; Openverse leaves it empty for some results.
[JsonPropertyName("duration")]
public int? DurationMs { get; init; }
[JsonIgnore]
public TimeSpan? Duration => DurationMs > 0 ? TimeSpan.FromMilliseconds(DurationMs.Value) : null;
-
- /// Readable license name, for example "CC BY 4.0", "CC0 1.0" or "Public Domain Mark 1.0".
- public string LicenseName => License.ToLowerInvariant() switch
+ private string LicenseName => License.ToLowerInvariant() switch
{
"cc0" => $"CC0 {LicenseVersion}".Trim(),
"pdm" => $"Public Domain Mark {LicenseVersion}".Trim(),
_ => $"CC {License.ToUpperInvariant()} {LicenseVersion}".Trim(),
};
- /// The result in the provider-neutral shape. Openverse ids are stored as they come.
+ // Openverse ids stay unprefixed, unlike other providers.
public MusicTrack ToMusicTrack() => new()
{
Id = Id,
Title = Title,
Creator = Creator,
Url = Url,
- // Openverse reports some MP3 files as "mp32".
+ // Openverse reports some MP3s as "mp32".
FileType = FileType?.ToLowerInvariant() is "mp32" ? "mp3" : FileType,
License = LicenseName,
Attribution = Attribution,
diff --git a/src/Radiosender/Models/ScheduleItem.cs b/src/Radiosender/Models/ScheduleItem.cs
index e8e2d5a..85b776a 100644
--- a/src/Radiosender/Models/ScheduleItem.cs
+++ b/src/Radiosender/Models/ScheduleItem.cs
@@ -1,19 +1,9 @@
namespace Radiosender.Models;
-public enum ScheduleItemKind
-{
- Song,
- News,
- Ad,
- Moderator,
-}
-
-/// One entry of the broadcast plan. is set only for .
public record ScheduleItem(ScheduleItemKind Kind, string Title, DateTime Start, TimeSpan Duration, Song? Song = null)
{
public DateTime End => Start + Duration;
- /// The kind as the user reads it.
public string KindName => Kind switch
{
ScheduleItemKind.News => "Nachrichten",
diff --git a/src/Radiosender/Models/ScheduleItemKind.cs b/src/Radiosender/Models/ScheduleItemKind.cs
new file mode 100644
index 0000000..45835c8
--- /dev/null
+++ b/src/Radiosender/Models/ScheduleItemKind.cs
@@ -0,0 +1,9 @@
+namespace Radiosender.Models;
+
+public enum ScheduleItemKind
+{
+ Song,
+ News,
+ Ad,
+ Moderator,
+}
diff --git a/src/Radiosender/Models/Song.cs b/src/Radiosender/Models/Song.cs
index 435bd97..f7c16dc 100644
--- a/src/Radiosender/Models/Song.cs
+++ b/src/Radiosender/Models/Song.cs
@@ -1,13 +1,5 @@
namespace Radiosender.Models;
-public enum SongSource
-{
- Upload,
-
- /// Downloaded from a music provider such as Openverse.
- Online,
-}
-
public class Song
{
public long Id { get; set; }
@@ -18,7 +10,5 @@ public class Song
public SongSource Source { get; set; }
public string? License { get; set; }
public string? Attribution { get; set; }
-
- /// Id of the provider result the song was imported from (), so it is not imported twice.
public string? ExternalId { get; set; }
}
diff --git a/src/Radiosender/Models/SongSource.cs b/src/Radiosender/Models/SongSource.cs
new file mode 100644
index 0000000..78f1664
--- /dev/null
+++ b/src/Radiosender/Models/SongSource.cs
@@ -0,0 +1,7 @@
+namespace Radiosender.Models;
+
+public enum SongSource
+{
+ Upload,
+ Online,
+}
diff --git a/src/Radiosender/Services/Audio/AudioSource.cs b/src/Radiosender/Services/Audio/AudioSource.cs
new file mode 100644
index 0000000..7dcf19b
--- /dev/null
+++ b/src/Radiosender/Services/Audio/AudioSource.cs
@@ -0,0 +1,7 @@
+namespace Radiosender.Services.Audio;
+
+public enum AudioSource
+{
+ Music,
+ Microphone,
+}
diff --git a/src/Radiosender/Services/Audio/IAudioPlayer.cs b/src/Radiosender/Services/Audio/IAudioPlayer.cs
new file mode 100644
index 0000000..0ae182e
--- /dev/null
+++ b/src/Radiosender/Services/Audio/IAudioPlayer.cs
@@ -0,0 +1,10 @@
+namespace Radiosender.Services.Audio;
+
+public interface IAudioPlayer
+{
+ event EventHandler? TrackFinished;
+
+ void Play(string filePath);
+
+ void Stop();
+}
diff --git a/src/Radiosender/Services/Microphone.cs b/src/Radiosender/Services/Audio/Microphone.cs
similarity index 76%
rename from src/Radiosender/Services/Microphone.cs
rename to src/Radiosender/Services/Audio/Microphone.cs
index e6086d4..b1f856c 100644
--- a/src/Radiosender/Services/Microphone.cs
+++ b/src/Radiosender/Services/Audio/Microphone.cs
@@ -1,8 +1,7 @@
using NAudio.Wave;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Audio;
-/// Puts the default recording device on air through the , so the speaker can talk over or between items.
public sealed class Microphone(ProgramOutput output) : IDisposable
{
private readonly Lock _lock = new();
@@ -14,7 +13,7 @@ public sealed class Microphone(ProgramOutput output) : IDisposable
get { lock (_lock) return _capture is not null; }
}
- /// No microphone or no output device can be opened; the message can be shown to the user.
+ /// No mic or output device; message is user-facing.
public void TurnOn()
{
lock (_lock)
@@ -25,7 +24,7 @@ public sealed class Microphone(ProgramOutput output) : IDisposable
throw new InvalidOperationException("Es wurde kein Mikrofon gefunden.");
var capture = new WaveIn { WaveFormat = new WaveFormat(44100, 16, 1), BufferMilliseconds = 30 };
- // A short buffer that drops what it cannot hold: speech must not fall further and further behind.
+ // Short dropping buffer: speech must not drift further behind.
var buffer = new BufferedWaveProvider(capture.WaveFormat, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
capture.DataAvailable += (_, e) => buffer.AddSamples(e.Buffer, 0, e.BytesRecorded);
try
@@ -49,7 +48,7 @@ public sealed class Microphone(ProgramOutput output) : IDisposable
if (_input is not null)
output.Remove(_input);
_input = null;
- _capture?.Dispose(); // stops the recording
+ _capture?.Dispose();
_capture = null;
}
}
diff --git a/src/Radiosender/Services/Audio/MusicPlayer.cs b/src/Radiosender/Services/Audio/MusicPlayer.cs
new file mode 100644
index 0000000..bb06a79
--- /dev/null
+++ b/src/Radiosender/Services/Audio/MusicPlayer.cs
@@ -0,0 +1,112 @@
+using System.IO;
+using NAudio.Wave;
+
+namespace Radiosender.Services.Audio;
+
+// Events: thread pool, never UI thread. WPF: marshal via Dispatcher before touching UI.
+public sealed class MusicPlayer : IAudioPlayer
+{
+ private static readonly Lazy LazyInstance = new(() => new MusicPlayer());
+
+ private readonly ProgramOutput _output = ProgramOutput.Instance;
+ private readonly Lock _lock = new();
+ private AudioFileReader? _reader;
+ private ISampleProvider? _input;
+ private float _volume = 1f;
+
+ private MusicPlayer()
+ {
+ // Audio thread must not wait for _lock (Stop holds it while waiting for that thread) -> thread pool.
+ _output.InputEnded += (_, input) => ThreadPool.QueueUserWorkItem(_ => OnInputEnded(input));
+ AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop();
+ }
+
+ public static MusicPlayer Instance => LazyInstance.Value;
+
+ /// Not raised by or by replacing a track.
+ public event EventHandler? TrackFinished;
+
+ public bool IsPlaying
+ {
+ get { lock (_lock) return _input is not null; }
+ }
+
+ public TimeSpan Duration
+ {
+ get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; }
+ }
+
+ public float Volume
+ {
+ get { lock (_lock) return _volume; }
+ set
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f);
+ ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f);
+ lock (_lock)
+ {
+ _volume = value;
+ _reader?.Volume = value;
+ }
+ }
+ }
+
+ public void Play(string filePath)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
+
+ lock (_lock)
+ {
+ Release();
+
+ if (!File.Exists(filePath))
+ throw new FileNotFoundException($"Audiodatei nicht gefunden: {filePath}", filePath);
+
+ try
+ {
+ _reader = new AudioFileReader(filePath) { Volume = _volume };
+ _input = _output.Add(_reader, AudioSource.Music);
+ }
+ catch (Exception ex) when (ex is not (OutOfMemoryException or NAudio.MmException))
+ {
+ Release();
+ throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex);
+ }
+ catch
+ {
+ Release(); // no output device: file must not stay open
+ throw;
+ }
+ }
+ }
+
+ public void Stop()
+ {
+ lock (_lock) Release();
+ }
+
+ // Caller holds _lock. Clearing _input first: Stop/replace never raise TrackFinished.
+ private void Release()
+ {
+ if (_input is not null)
+ {
+ // Returns after audio thread let go of reader -> safe to dispose below.
+ _output.Remove(_input);
+ _input = null;
+ }
+
+ _reader?.Dispose();
+ _reader = null;
+ }
+
+ private void OnInputEnded(ISampleProvider input)
+ {
+ lock (_lock)
+ {
+ if (!ReferenceEquals(input, _input)) return;
+ Release();
+ }
+
+ TrackFinished?.Invoke(this, EventArgs.Empty);
+ }
+}
diff --git a/src/Radiosender/Services/ProgramMixer.cs b/src/Radiosender/Services/Audio/ProgramMixer.cs
similarity index 59%
rename from src/Radiosender/Services/ProgramMixer.cs
rename to src/Radiosender/Services/Audio/ProgramMixer.cs
index 628145f..fb689cf 100644
--- a/src/Radiosender/Services/ProgramMixer.cs
+++ b/src/Radiosender/Services/Audio/ProgramMixer.cs
@@ -1,46 +1,29 @@
using NAudio.Wave;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Audio;
-/// What an input of the mixer is; the levels differ by kind.
-public enum AudioSource
-{
- Music,
- Microphone,
-}
-
-///
-/// Mixes every input twice in one pass: once for the listeners (the broadcast) and once for the person at
-/// the desk (the monitor). Each input is read only once, so both mixes stay in step.
-///
public sealed class ProgramMixer
{
private readonly Lock _lock = new();
private readonly List<(ISampleProvider Input, AudioSource Kind)> _inputs = [];
private float[] _scratch = [];
- // Written by the UI thread, read by the audio thread; a level that arrives one block late is fine.
+ // UI thread writes, audio thread reads; one block late is fine.
private volatile float _musicForOthers = 1f;
private volatile float _microphoneForOthers = 1f;
private volatile float _musicForMe = 1f;
private volatile bool _listenToBroadcast = true;
- ///
- /// Raised when an input has played to its end and was dropped. Comes from the audio thread while the
- /// mixer is busy: handlers must return at once and must not call back into the mixer.
- ///
+ /// Audio thread, under mixer lock: return at once, never call back into the mixer.
public event EventHandler? InputEnded;
- /// How loud the music is on the broadcast, from 0 to 1.
public float MusicForOthers { get => _musicForOthers; set => _musicForOthers = Level(value); }
- /// How loud the microphone is on the broadcast, from 0 to 1.
public float MicrophoneForOthers { get => _microphoneForOthers; set => _microphoneForOthers = Level(value); }
- /// How loud the music is on the monitor, from 0 to 1. The monitor never carries the microphone: hearing oneself late is distracting.
+ // Monitor never carries the mic: hearing oneself late distracts.
public float MusicForMe { get => _musicForMe; set => _musicForMe = Level(value); }
- /// When set, the monitor is an exact copy of the broadcast and has no effect.
public bool ListenToBroadcast { get => _listenToBroadcast; set => _listenToBroadcast = value; }
public void Add(ISampleProvider input, AudioSource kind)
@@ -48,13 +31,12 @@ public sealed class ProgramMixer
lock (_lock) _inputs.Add((input, kind));
}
- /// Returns once the audio thread no longer reads from the input.
+ /// Returns once the audio thread no longer reads the input.
public void Remove(ISampleProvider input)
{
lock (_lock) _inputs.RemoveAll(entry => ReferenceEquals(entry.Input, input));
}
- /// Fills both buffers, which must have the same length, with the next block of each mix.
public void Mix(Span broadcast, Span monitor)
{
broadcast.Clear();
@@ -85,12 +67,17 @@ public sealed class ProgramMixer
}
}
- // Two loud inputs can add up past full scale, which would distort harshly on the device.
- for (var n = 0; n < broadcast.Length; n++)
- {
- broadcast[n] = Math.Clamp(broadcast[n], -1f, 1f);
- monitor[n] = copyBroadcast ? broadcast[n] : Math.Clamp(monitor[n], -1f, 1f);
- }
+ Clamp(broadcast);
+ if (copyBroadcast)
+ broadcast.CopyTo(monitor);
+ else
+ Clamp(monitor);
+ }
+
+ private static void Clamp(Span samples)
+ {
+ foreach (ref var sample in samples)
+ sample = Math.Clamp(sample, -1f, 1f);
}
private static float Level(float value)
diff --git a/src/Radiosender/Services/ProgramOutput.cs b/src/Radiosender/Services/Audio/ProgramOutput.cs
similarity index 58%
rename from src/Radiosender/Services/ProgramOutput.cs
rename to src/Radiosender/Services/Audio/ProgramOutput.cs
index 71bdbcf..b635e49 100644
--- a/src/Radiosender/Services/ProgramOutput.cs
+++ b/src/Radiosender/Services/Audio/ProgramOutput.cs
@@ -2,19 +2,13 @@ using System.Runtime.InteropServices;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Audio;
-///
-/// The station's audio channel: everything that goes on air (songs, the microphone) is mixed here.
-/// The broadcast mix plays on one device for the listeners. A second device, if one is chosen, plays
-/// the monitor mix for the person at the desk; without it the one device plays the monitor mix.
-/// Cues for the speaker only, like the alert tone and the import preview, stay off this channel.
-///
+// On-air channel only; speaker-only cues (alert tone, import preview) stay off it.
public sealed class ProgramOutput
{
private static readonly Lazy LazyInstance = new(() => new ProgramOutput());
- /// All inputs are converted to this format before mixing.
public static WaveFormat Format { get; } = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);
private readonly Lock _lock = new();
@@ -28,27 +22,19 @@ public sealed class ProgramOutput
private ProgramOutput()
{
Mixer.InputEnded += (_, input) => InputEnded?.Invoke(this, input);
- // Releases the audio devices when the app exits.
AppDomain.CurrentDomain.ProcessExit += (_, _) => { lock (_lock) CloseDevices(); };
}
public static ProgramOutput Instance => LazyInstance.Value;
- /// The levels of both mixes.
public ProgramMixer Mixer { get; } = new();
- /// Same as : raised on the audio thread, handlers must return at once.
+ /// Audio thread: handlers must return at once.
public event EventHandler? InputEnded;
- /// Names of the playback devices Windows offers, for the settings page.
public static IReadOnlyList DeviceNames() =>
- Enumerable.Range(0, WaveOut.DeviceCount).Select(i => WaveOut.GetCapabilities(i).ProductName).ToList();
+ [.. Enumerable.Range(0, WaveOut.DeviceCount).Select(i => WaveOut.GetCapabilities(i).ProductName)];
- ///
- /// Chooses the devices by name: null for the broadcast means the Windows default device,
- /// null for the monitor means no device of its own. Devices that are already open are reopened.
- /// A name that no longer exists counts as null.
- ///
/// A device cannot be opened.
public void UseDevices(string? broadcast, string? monitor)
{
@@ -63,47 +49,28 @@ public sealed class ProgramOutput
}
}
- /// Puts a source on air and opens the output devices on first use.
- /// The input as the mixer knows it; pass it to and compare it in .
- /// The source has more than two channels.
- /// No audio output device can be opened.
+ /// More than two channels.
+ /// No output device can be opened.
public ISampleProvider Add(ISampleProvider source, AudioSource kind)
{
var input = ToProgramFormat(source);
- lock (_lock)
- {
- if (!_started)
- {
- OpenDevices();
- _started = true;
- }
- }
+ lock (_lock) EnsureStarted();
Mixer.Add(input, kind);
return input;
}
- ///
- /// Starts a copy of the broadcast mix for a live stream and opens the output devices if needed, because
- /// the broadcast device sets the pace. Only one feed at a time: a new one replaces the old.
- ///
- /// No audio output device can be opened.
+ /// No output device can be opened.
public BufferedWaveProvider OpenLiveFeed()
{
- // Holds a few seconds; if the reader falls behind, the newest audio is dropped instead of piling up.
var feed = new BufferedWaveProvider(Format, TimeSpan.FromSeconds(5)) { DiscardOnBufferOverflow = true, ReadFully = false };
lock (_lock)
{
- if (!_started)
- {
- OpenDevices();
- _started = true;
- }
+ EnsureStarted();
_liveFeed = feed;
}
return feed;
}
- /// Stops copying into the feed from .
public void CloseLiveFeed(BufferedWaveProvider feed)
{
lock (_lock)
@@ -113,10 +80,8 @@ public sealed class ProgramOutput
}
}
- /// Takes an input off air. Returns once the audio thread no longer reads from it.
public void Remove(ISampleProvider input) => Mixer.Remove(input);
- /// Converts mono to stereo and any sample rate to the channel's 44.1 kHz.
public static ISampleProvider ToProgramFormat(ISampleProvider source)
{
if (source.WaveFormat.Channels > 2)
@@ -128,13 +93,21 @@ public sealed class ProgramOutput
return source;
}
+ // Caller holds _lock.
+ private void EnsureStarted()
+ {
+ if (_started)
+ return;
+ OpenDevices();
+ _started = true;
+ }
+
// Caller holds _lock.
private void OpenDevices()
{
var names = DeviceNames().ToList();
- var broadcast = _broadcastName is null ? -1 : names.IndexOf(_broadcastName); // -1 is the Windows default device
+ var broadcast = _broadcastName is null ? -1 : names.IndexOf(_broadcastName); // -1 = Windows default
var monitor = _monitorName is null ? -1 : names.IndexOf(_monitorName);
- // The same device twice would only play both mixes on top of each other.
if (monitor == broadcast || (broadcast == -1 && monitor == 0 && names.Count == 1))
monitor = -1;
@@ -142,14 +115,11 @@ public sealed class ProgramOutput
{
if (monitor < 0)
{
- // One device: the person at the desk hears the monitor mix; nothing is sent anywhere else.
_broadcastDevice = Open(broadcast, new Tap(this, null));
}
else
{
- // The broadcast device sets the pace. Each block it asks for also yields the monitor block,
- // which waits in a short buffer for the second device. The buffer drops what it cannot hold,
- // so the two device clocks drifting apart never builds up a delay.
+ // Broadcast device paces; monitor gets a short dropping buffer so clock drift never adds delay.
var monitorBuffer = new BufferedWaveProvider(Format, TimeSpan.FromMilliseconds(300)) { DiscardOnBufferOverflow = true };
_broadcastDevice = Open(broadcast, new Tap(this, monitorBuffer));
_monitorDevice = Open(monitor, monitorBuffer.ToSampleProvider());
@@ -164,7 +134,7 @@ public sealed class ProgramOutput
private static WaveOut Open(int deviceNumber, ISampleProvider source)
{
- // Three buffers of 50 ms: short enough that live speech does not lag noticeably.
+ // 3 x 50 ms: live speech must not lag noticeably.
var device = new WaveOut { DeviceNumber = deviceNumber, BufferMilliseconds = 50, NumberOfBuffers = 3 };
try
{
@@ -188,10 +158,7 @@ public sealed class ProgramOutput
_monitorDevice = null;
}
- ///
- /// What the pacing device plays. With a monitor buffer it plays the broadcast mix and feeds the buffer;
- /// without one it plays the monitor mix itself. Either way the broadcast mix also goes to the live feed, if there is one.
- ///
+ // Pacing device source. With buffer: plays broadcast, feeds monitor. Without: plays monitor. Broadcast always to live feed.
private sealed class Tap(ProgramOutput output, BufferedWaveProvider? monitorBuffer) : ISampleProvider
{
private float[] _other = [];
diff --git a/src/Radiosender/Services/IAudioPlayer.cs b/src/Radiosender/Services/IAudioPlayer.cs
deleted file mode 100644
index 295082c..0000000
--- a/src/Radiosender/Services/IAudioPlayer.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-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/IMusicProvider.cs b/src/Radiosender/Services/IMusicProvider.cs
deleted file mode 100644
index 9af071d..0000000
--- a/src/Radiosender/Services/IMusicProvider.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using Radiosender.Models;
-
-namespace Radiosender.Services;
-
-/// Error of a music provider or a download, with a message that can be shown to the user as is.
-public class MusicProviderException(string message, Exception? inner = null) : Exception(message, inner);
-
-///
-/// A catalog of music that can be searched online. To add one, implement this interface and register the
-/// class in App; the import page lists every registered provider. Downloading and storing the
-/// results is the same for all providers and not part of this interface.
-///
-public interface IMusicProvider
-{
- /// Name shown to the user, for example "Openverse".
- string Name { get; }
-
- /// Whether the import page offers this provider now; one that needs a setting can hide itself.
- bool IsAvailable => true;
-
- /// The search failed.
- Task> SearchAsync(string query, CancellationToken cancellationToken = default);
-}
diff --git a/src/Radiosender/Services/Library/SongImportException.cs b/src/Radiosender/Services/Library/SongImportException.cs
new file mode 100644
index 0000000..73fd1b7
--- /dev/null
+++ b/src/Radiosender/Services/Library/SongImportException.cs
@@ -0,0 +1,3 @@
+namespace Radiosender.Services.Library;
+
+public class SongImportException(string message, Exception? innerException = null) : Exception(message, innerException);
diff --git a/src/Radiosender/Services/SongImportService.cs b/src/Radiosender/Services/Library/SongImportService.cs
similarity index 85%
rename from src/Radiosender/Services/SongImportService.cs
rename to src/Radiosender/Services/Library/SongImportService.cs
index 4787c32..5a146fd 100644
--- a/src/Radiosender/Services/SongImportService.cs
+++ b/src/Radiosender/Services/Library/SongImportService.cs
@@ -2,18 +2,14 @@ using System.IO;
using NAudio.Wave;
using Radiosender.Models;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Library;
-/// An import failure with a message that can be shown to the user.
-public class SongImportException(string message, Exception? innerException = null) : Exception(message, innerException);
-
-/// Copies an uploaded MP3 or WAV file into the music folder and saves it as a song.
public class SongImportService(SongRepository songs, string musicDirectory)
{
public static string DefaultMusicDirectory { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "Music");
- public static IReadOnlyList SupportedExtensions { get; } = [".mp3", ".wav"];
+ private static IReadOnlyList SupportedExtensions { get; } = [".mp3", ".wav"];
/// The file is not a readable MP3 or WAV file with audio.
public Song Import(string sourcePath)
@@ -74,7 +70,7 @@ public class SongImportService(SongRepository songs, string musicDirectory)
}
catch (Exception e)
{
- // NAudio and Media Foundation throw many unrelated exception types for corrupt files.
+ // NAudio/Media Foundation throw many unrelated types on corrupt files.
throw new SongImportException("Die Datei ist keine lesbare MP3- oder WAV-Datei.", e);
}
diff --git a/src/Radiosender/Services/SongRepository.cs b/src/Radiosender/Services/Library/SongRepository.cs
similarity index 67%
rename from src/Radiosender/Services/SongRepository.cs
rename to src/Radiosender/Services/Library/SongRepository.cs
index fd32b9f..cc04772 100644
--- a/src/Radiosender/Services/SongRepository.cs
+++ b/src/Radiosender/Services/Library/SongRepository.cs
@@ -3,12 +3,9 @@ using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Radiosender.Models;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Library;
-///
-/// The music library in a SQLite file, accessed through Entity Framework Core.
-/// Every call uses its own short-lived context, so the repository can be used from any thread.
-///
+// Fresh DbContext per call: safe from any thread.
public class SongRepository
{
public static string DefaultDatabasePath { get; } = Path.Combine(
@@ -23,12 +20,10 @@ public class SongRepository
.UseSqlite(new SqliteConnectionStringBuilder { DataSource = databasePath }.ToString())
.Options;
- // Creates the file and the table on first start; an existing database is left as it is.
using var context = Open();
context.Database.EnsureCreated();
}
- /// Ids of all provider results that are already in the library.
public IReadOnlySet GetExternalIds()
{
using var context = Open();
@@ -47,9 +42,7 @@ public class SongRepository
return context.Songs.AsNoTracking().FirstOrDefault(s => s.Id == id);
}
- /// Inserts the song and sets its .
- /// The song has no duration.
- /// The database rejected the song, e.g. a second song with the same external id.
+ /// Rejected, e.g. duplicate external id.
public void Add(Song song)
{
RequireDuration(song);
@@ -58,9 +51,7 @@ public class SongRepository
context.SaveChanges();
}
- /// Stores everything except the external id, which never changes after the import.
- /// false if no song with this id exists.
- /// The song has no duration.
+ // ExternalId never changes after import.
public bool Update(Song song)
{
RequireDuration(song);
@@ -75,7 +66,6 @@ public class SongRepository
.SetProperty(x => x.Attribution, song.Attribution)) == 1;
}
- /// false if no song with this id exists.
public bool Delete(long id)
{
using var context = Open();
@@ -84,14 +74,12 @@ public class SongRepository
private LibraryContext Open() => new(_options);
- // Songs need a length for scheduling. Checked here, so the rule does not depend on the database schema.
private static void RequireDuration(Song song)
{
if (song.Duration <= TimeSpan.Zero)
throw new ArgumentException("A song needs a duration longer than zero.", nameof(song));
}
- /// Maps to the table Songs.
private sealed class LibraryContext(DbContextOptions options) : DbContext(options)
{
public DbSet Songs => Set();
@@ -100,14 +88,12 @@ public class SongRepository
{
var song = modelBuilder.Entity();
song.ToTable("Songs");
- // Stored as whole milliseconds in the column the first version of the app created.
+ // Legacy column names from v1; keep for existing databases.
song.Property(s => s.Duration)
.HasColumnName("DurationMs")
.HasConversion(duration => (long)duration.TotalMilliseconds, milliseconds => TimeSpan.FromMilliseconds(milliseconds));
- // The column keeps the name it got when Openverse was the only provider.
song.Property(s => s.ExternalId).HasColumnName("OpenverseId");
- // One song per provider result, also if two imports of the same track race.
- // SQLite allows any number of rows without an id in a unique index.
+ // Unique also under racing imports; SQLite allows many NULLs.
song.HasIndex(s => s.ExternalId).IsUnique();
}
}
diff --git a/src/Radiosender/Services/MusicPlayer.cs b/src/Radiosender/Services/MusicPlayer.cs
deleted file mode 100644
index c9451f8..0000000
--- a/src/Radiosender/Services/MusicPlayer.cs
+++ /dev/null
@@ -1,176 +0,0 @@
-using System.IO;
-using NAudio.Wave;
-
-namespace Radiosender.Services;
-
-///
-/// Plays one audio file at a time on the , the station's audio channel.
-///
-///
-/// and are raised on a thread-pool thread,
-/// never on the WPF UI thread. WPF callers must marshal with Dispatcher.Invoke or
-/// Dispatcher.BeginInvoke before touching UI elements.
-///
-public sealed class MusicPlayer : IAudioPlayer
-{
- private static readonly Lazy LazyInstance = new(() => new MusicPlayer());
-
- private static readonly TimeSpan PositionInterval = TimeSpan.FromMilliseconds(250);
-
- private readonly ProgramOutput _output = ProgramOutput.Instance;
- private readonly Lock _lock = new();
- private AudioFileReader? _reader;
- private ISampleProvider? _input; // the reader as it sits in the mixer; null while paused
- private Timer? _positionTimer;
- private float _volume = 1f;
-
- private MusicPlayer()
- {
- // The mixer reports the end of a track on the audio thread, which must not wait for _lock:
- // Stop holds _lock while it waits for that thread. So the work moves to the thread pool.
- _output.InputEnded += (_, input) => ThreadPool.QueueUserWorkItem(_ => OnInputEnded(input));
- // Releases the file when the app exits.
- AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop();
- }
-
- public static MusicPlayer Instance => LazyInstance.Value;
-
- /// Raised when a track reaches its end. Not raised by or by replacing a track.
- public event EventHandler? TrackFinished;
-
- /// Raised about every 250 ms while a track is playing, with the current position.
- public event EventHandler? PositionChanged;
-
- public bool IsPlaying
- {
- get { lock (_lock) return _input is not null; }
- }
-
- public TimeSpan Position
- {
- get { lock (_lock) return _reader?.CurrentTime ?? TimeSpan.Zero; }
- }
-
- public TimeSpan Duration
- {
- get { lock (_lock) return _reader?.TotalTime ?? TimeSpan.Zero; }
- }
-
- ///
- /// Volume of the music from 0 (silent) to 1 (full), before it reaches the mixer, so it applies to listeners and
- /// monitor alike. Kept across tracks; the microphone is not affected.
- ///
- public float Volume
- {
- get { lock (_lock) return _volume; }
- set
- {
- ArgumentOutOfRangeException.ThrowIfLessThan(value, 0f);
- ArgumentOutOfRangeException.ThrowIfGreaterThan(value, 1f);
- lock (_lock)
- {
- _volume = value;
- if (_reader is not null) _reader.Volume = value;
- }
- }
- }
-
- /// Stops the current track and starts playing .
- /// The file does not exist.
- /// The file is not a readable audio file.
- public void Play(string filePath)
- {
- ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
-
- lock (_lock)
- {
- Release();
-
- if (!File.Exists(filePath))
- throw new FileNotFoundException($"Audiodatei nicht gefunden: {filePath}", filePath);
-
- try
- {
- _reader = new AudioFileReader(filePath) { Volume = _volume };
- _input = _output.Add(_reader, AudioSource.Music);
- }
- catch (Exception ex) when (ex is not (OutOfMemoryException or NAudio.MmException))
- {
- Release();
- throw new InvalidDataException($"Audiodatei kann nicht gelesen werden: {filePath}", ex);
- }
- catch
- {
- Release(); // no output device: the file must not stay open
- throw;
- }
-
- _positionTimer = new Timer(OnPositionTimer, null, PositionInterval, PositionInterval);
- }
- }
-
- public void Pause()
- {
- lock (_lock)
- {
- if (_input is null) return;
- _output.Remove(_input);
- _input = null;
- }
- }
-
- public void Resume()
- {
- lock (_lock)
- {
- if (_reader is not null && _input is null) _input = _output.Add(_reader, AudioSource.Music);
- }
- }
-
- /// Stops playback and releases the file. Does not raise .
- public void Stop()
- {
- lock (_lock) Release();
- }
-
- // Caller holds _lock. Clearing _input first keeps Stop and track replacement from raising TrackFinished.
- private void Release()
- {
- _positionTimer?.Dispose();
- _positionTimer = null;
-
- if (_input is not null)
- {
- // Returns once the audio thread has let go of the reader, so disposing it below is safe.
- _output.Remove(_input);
- _input = null;
- }
-
- _reader?.Dispose();
- _reader = null;
- }
-
- private void OnInputEnded(ISampleProvider input)
- {
- lock (_lock)
- {
- // Another input of the channel, or a track that Stop or Play already replaced.
- if (!ReferenceEquals(input, _input)) return;
- Release();
- }
-
- TrackFinished?.Invoke(this, EventArgs.Empty);
- }
-
- private void OnPositionTimer(object? state)
- {
- TimeSpan position;
- lock (_lock)
- {
- if (_input is null || _reader is null) return;
- position = _reader.CurrentTime;
- }
-
- PositionChanged?.Invoke(this, position);
- }
-}
diff --git a/src/Radiosender/Services/Providers/IMusicProvider.cs b/src/Radiosender/Services/Providers/IMusicProvider.cs
new file mode 100644
index 0000000..46d4d3b
--- /dev/null
+++ b/src/Radiosender/Services/Providers/IMusicProvider.cs
@@ -0,0 +1,14 @@
+using Radiosender.Models;
+
+namespace Radiosender.Services.Providers;
+
+// New provider: implement and register in App; import page lists all registered.
+public interface IMusicProvider
+{
+ string Name { get; }
+
+ bool IsAvailable => true;
+
+ /// Search failed.
+ Task> SearchAsync(string query, CancellationToken cancellationToken = default);
+}
diff --git a/src/Radiosender/Services/InternetArchiveProvider.cs b/src/Radiosender/Services/Providers/InternetArchiveProvider.cs
similarity index 83%
rename from src/Radiosender/Services/InternetArchiveProvider.cs
rename to src/Radiosender/Services/Providers/InternetArchiveProvider.cs
index cdbc954..1411c11 100644
--- a/src/Radiosender/Services/InternetArchiveProvider.cs
+++ b/src/Radiosender/Services/Providers/InternetArchiveProvider.cs
@@ -4,18 +4,15 @@ using System.Text.Json;
using System.Text.RegularExpressions;
using Radiosender.Models;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Providers;
-///
-/// Searches the Internet Archive for Creative Commons licensed MP3 audio. The search API returns items
-/// (often whole albums), so each item's file list is fetched as well and every MP3 becomes one result.
-///
+// Search returns items (often albums); each item's file list is fetched, every MP3 is one result.
public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
{
private const string SearchUrl = "https://archive.org/advancedsearch.php";
private const string MetadataUrl = "https://archive.org/metadata/";
- // One request per item follows the search, so the item count stays small.
+ // One extra request per item: keep small.
private const int Items = 8;
private const int TracksPerItem = 5;
@@ -23,7 +20,7 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
public async Task> SearchAsync(string query, CancellationToken cancellationToken = default)
{
- // The query language is Lucene; its operators are taken out of the user's words so they cannot change the filter.
+ // Strip Lucene operators: user input must not change the filter.
var words = string.Join(' ', LuceneSyntax().Replace(query, " ").Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
if (words.Length == 0)
return [];
@@ -36,12 +33,12 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort.");
var perItem = await Task.WhenAll(docs.EnumerateArray().Select(doc => TracksOfAsync(doc, cancellationToken)));
- return perItem.SelectMany(tracks => tracks).ToList();
+ return [.. perItem.SelectMany(tracks => tracks)];
}
private async Task> TracksOfAsync(JsonElement item, CancellationToken cancellationToken)
{
- var tracks = new List();
+ List tracks = [];
if (ProviderParsing.Text(item, "identifier") is not { } identifier)
return tracks;
@@ -69,11 +66,10 @@ public partial class InternetArchiveProvider(HttpClient http) : IMusicProvider
continue;
var title = ProviderParsing.Text(file, "title") ?? Path.GetFileNameWithoutExtension(name);
var creator = ProviderParsing.Text(file, "creator") ?? ProviderParsing.Text(file, "artist") ?? ProviderParsing.Text(item, "creator");
- // A file name can contain folders; every part is escaped on its own.
+ // Name may contain folders: escape each segment.
var path = string.Join('/', name.Split('/').Select(Uri.EscapeDataString));
tracks.Add(new MusicTrack
{
- // Prefixed, so the id cannot collide with one from another provider.
Id = $"archive:{identifier}/{name}",
Title = title,
Creator = creator,
diff --git a/src/Radiosender/Services/LautFmProvider.cs b/src/Radiosender/Services/Providers/LautFmProvider.cs
similarity index 71%
rename from src/Radiosender/Services/LautFmProvider.cs
rename to src/Radiosender/Services/Providers/LautFmProvider.cs
index 9b7294d..0c1b3db 100644
--- a/src/Radiosender/Services/LautFmProvider.cs
+++ b/src/Radiosender/Services/Providers/LautFmProvider.cs
@@ -1,20 +1,17 @@
using System.Net.Http;
using System.Text.Json;
using Radiosender.Models;
+using Radiosender.Services.Settings;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Providers;
-///
-/// Searches the music library of the user's laut.fm station, so laut.fm tracks can be imported next to
-/// local songs. Uses the API behind Radioadmin with the user's login token. laut.fm does not publish
-/// this API for other programs, so it can change without notice.
-///
+// Unofficial Radioadmin API with the user's token; may change without notice.
public class LautFmProvider(HttpClient http, Func settings) : IMusicProvider
{
- public const string ApiBase = "https://api.radioadmin.laut.fm/";
+ private const string ApiBase = "https://api.radioadmin.laut.fm/";
- // Radioadmin sends track searches to its own host ("searchHost" in radioadmin.laut.fm/client/_/config.json).
- public const string SearchBase = "https://search.api.radioadmin.laut.fm/";
+ // Track search has its own host: "searchHost" in radioadmin.laut.fm/client/_/config.json.
+ private const string SearchBase = "https://search.api.radioadmin.laut.fm/";
public string Name => "laut.fm";
@@ -30,12 +27,12 @@ public class LautFmProvider(HttpClient http, Func settings) : IMusi
if (words.Length == 0)
return [];
- // The API filters one field at a time, so title and artist are two searches.
+ // API filters one field per request: title and artist separately.
var url = $"{SearchBase}stations/{Uri.EscapeDataString(station)}/tracks?";
var results = await Task.WhenAll(
SearchFieldAsync($"{url}title={Uri.EscapeDataString(words)}", current.LautFmToken, cancellationToken),
SearchFieldAsync($"{url}artist={Uri.EscapeDataString(words)}", current.LautFmToken, cancellationToken));
- return results.SelectMany(tracks => tracks).DistinctBy(track => track.Id).ToList();
+ return [.. results.SelectMany(tracks => tracks).DistinctBy(track => track.Id)];
}
private async Task> SearchFieldAsync(string url, string token, CancellationToken cancellationToken)
@@ -44,7 +41,7 @@ public class LautFmProvider(HttpClient http, Func settings) : IMusi
if (!json.RootElement.TryGetProperty("tracks", out var tracks) || tracks.ValueKind != JsonValueKind.Array)
throw new MusicProviderException($"{Name}-Suche fehlgeschlagen: unerwartete Antwort.");
- var result = new List();
+ List result = [];
foreach (var track in tracks.EnumerateArray())
{
if (ProviderParsing.Text(track, "id") is not { } id
@@ -53,13 +50,11 @@ public class LautFmProvider(HttpClient http, Func settings) : IMusi
continue;
result.Add(new MusicTrack
{
- // Prefixed, so the id cannot collide with one from another provider.
Id = $"lautfm:{id}",
Title = title,
Creator = ProviderParsing.Text(track, "artist"),
Url = audio,
FileType = "mp3",
- // The station's tracks are licensed by laut.fm for broadcasting on laut.fm only.
License = "laut.fm (nur für laut.fm)",
Duration = ProviderParsing.Duration(ProviderParsing.Text(track, "duration")),
});
@@ -67,7 +62,7 @@ public class LautFmProvider(HttpClient http, Func settings) : IMusi
return result;
}
- // The link the Radioadmin player uses; it needs no login. Relative links are taken against the API.
+ // Radioadmin player link, no login; relative to ApiBase; https only.
private static string? PrelistenUrl(JsonElement track)
{
if (!track.TryGetProperty("_links", out var links) || links.ValueKind != JsonValueKind.Object
diff --git a/src/Radiosender/Services/Providers/MusicProviderException.cs b/src/Radiosender/Services/Providers/MusicProviderException.cs
new file mode 100644
index 0000000..2424ad0
--- /dev/null
+++ b/src/Radiosender/Services/Providers/MusicProviderException.cs
@@ -0,0 +1,3 @@
+namespace Radiosender.Services.Providers;
+
+public class MusicProviderException(string message, Exception? inner = null) : Exception(message, inner);
diff --git a/src/Radiosender/Services/OpenverseProvider.cs b/src/Radiosender/Services/Providers/OpenverseProvider.cs
similarity index 95%
rename from src/Radiosender/Services/OpenverseProvider.cs
rename to src/Radiosender/Services/Providers/OpenverseProvider.cs
index 55497f4..80b6a23 100644
--- a/src/Radiosender/Services/OpenverseProvider.cs
+++ b/src/Radiosender/Services/Providers/OpenverseProvider.cs
@@ -4,9 +4,8 @@ using System.Net.Http.Json;
using System.Text.Json;
using Radiosender.Models;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Providers;
-/// Searches the Openverse audio catalog anonymously.
public class OpenverseProvider(HttpClient http) : IMusicProvider
{
private const string SearchUrl = "https://api.openverse.org/v1/audio/";
diff --git a/src/Radiosender/Services/ProviderParsing.cs b/src/Radiosender/Services/Providers/ProviderParsing.cs
similarity index 72%
rename from src/Radiosender/Services/ProviderParsing.cs
rename to src/Radiosender/Services/Providers/ProviderParsing.cs
index ff0b1ec..b403573 100644
--- a/src/Radiosender/Services/ProviderParsing.cs
+++ b/src/Radiosender/Services/Providers/ProviderParsing.cs
@@ -1,16 +1,14 @@
using System.Globalization;
+using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.RegularExpressions;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Providers;
-/// Helpers for JSON-based music providers: fetching, and reading licenses and durations.
internal static partial class ProviderParsing
{
- /// Fetches and parses it as JSON, whatever content type the server names.
- /// Sent as the Authorization header when set.
- /// The request failed or the answer is not JSON.
+ /// Request failed or answer is not JSON.
public static async Task GetJsonAsync(HttpClient http, string url, string provider, CancellationToken cancellationToken, string? bearerToken = null)
{
try
@@ -19,11 +17,11 @@ internal static partial class ProviderParsing
if (bearerToken is not null)
request.Headers.Authorization = new("Bearer", bearerToken);
using var response = await http.SendAsync(request, cancellationToken);
- if (response.StatusCode is System.Net.HttpStatusCode.Unauthorized or System.Net.HttpStatusCode.Forbidden && bearerToken is not null)
+ if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden && bearerToken is not null)
throw new MusicProviderException($"{provider} hat die Anmeldung abgelehnt. Den Token in den Einstellungen prüfen.");
if (!response.IsSuccessStatusCode)
throw new MusicProviderException($"{provider} hat HTTP {(int)response.StatusCode} geliefert.");
- // Parsed without looking at the content type: not every API labels its JSON as such.
+ // Content type ignored: not every API labels JSON.
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
}
catch (Exception e) when (e is not MusicProviderException && !cancellationToken.IsCancellationRequested)
@@ -37,10 +35,7 @@ internal static partial class ProviderParsing
}
}
- ///
- /// The property as text: a string as it is, a number as its digits, and the first entry of a list
- /// (the Internet Archive sends one creator as a string and several as a list). Otherwise null.
- ///
+ // String, number digits, or first array entry (Archive: one creator as string, several as list).
public static string? Text(JsonElement element, string property)
{
if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(property, out var value))
@@ -49,14 +44,13 @@ internal static partial class ProviderParsing
value = value.EnumerateArray().FirstOrDefault();
var text = value.ValueKind switch
{
- JsonValueKind.String => System.Net.WebUtility.HtmlDecode(value.GetString()),
+ JsonValueKind.String => WebUtility.HtmlDecode(value.GetString()),
JsonValueKind.Number => value.GetRawText(),
_ => null,
};
return string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}
- /// Readable name for a Creative Commons license URL, e.g. "CC BY-NC 3.0"; null for anything else.
public static string? License(string? url)
{
if (url is null)
@@ -68,7 +62,7 @@ internal static partial class ProviderParsing
return null;
}
- /// Reads "2:36", "05:32", "1:02:03" or seconds such as "3808.26"; null when it is none of them.
+ // "2:36", "1:02:03" or seconds "3808.26".
public static TimeSpan? Duration(string? text)
{
if (string.IsNullOrWhiteSpace(text))
@@ -81,7 +75,7 @@ internal static partial class ProviderParsing
return null;
seconds = seconds * 60 + value;
}
- // An upper bound keeps a nonsense value from overflowing TimeSpan.
+ // Upper bound: no TimeSpan overflow on nonsense.
return parts.Length <= 3 && seconds is > 0 and < 86400 ? TimeSpan.FromSeconds(seconds) : null;
}
diff --git a/src/Radiosender/Services/TrackDownloader.cs b/src/Radiosender/Services/Providers/TrackDownloader.cs
similarity index 79%
rename from src/Radiosender/Services/TrackDownloader.cs
rename to src/Radiosender/Services/Providers/TrackDownloader.cs
index 6fcc7a7..0bf68c4 100644
--- a/src/Radiosender/Services/TrackDownloader.cs
+++ b/src/Radiosender/Services/Providers/TrackDownloader.cs
@@ -2,9 +2,8 @@ using System.IO;
using System.Net.Http;
using Radiosender.Models;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Providers;
-/// Downloads the audio file of a into the music folder, for any provider.
public class TrackDownloader(HttpClient http, string musicFolder)
{
public static string DefaultMusicFolder { get; } = Path.Combine(
@@ -14,15 +13,10 @@ public class TrackDownloader(HttpClient http, string musicFolder)
private static readonly HashSet KnownExtensions = ["mp3", "ogg", "oga", "wav", "flac", "m4a", "aac", "opus"];
- /// Limit for the whole download; only covers the response headers here.
- public TimeSpan DownloadTimeout { get; init; } = TimeSpan.FromMinutes(3);
+ // Whole download; HttpClient.Timeout only covers headers (ResponseHeadersRead).
+ private static readonly TimeSpan DownloadTimeout = TimeSpan.FromMinutes(3);
- ///
- /// Downloads into the music folder under a new, unique file name.
- /// On any failure no file is left behind.
- ///
- /// Full path of the downloaded file.
- /// The download failed or the file is not acceptable.
+ /// Download failed or file not acceptable.
public async Task DownloadAsync(MusicTrack track, CancellationToken cancellationToken = default)
{
if (!Uri.TryCreate(track.Url, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
@@ -58,7 +52,7 @@ public class TrackDownloader(HttpClient http, string musicFolder)
}
catch (Exception e)
{
- // "await using" in the try block has already closed the file here.
+ // await using already closed the file.
if (path is not null)
File.Delete(path);
if (e is MusicProviderException || cancellationToken.IsCancellationRequested)
@@ -81,7 +75,7 @@ public class TrackDownloader(HttpClient http, string musicFolder)
{
var candidate = Path.Combine(musicFolder, i == 1 ? $"{name}.{extension}" : $"{name} ({i}).{extension}");
if (File.Exists(candidate)) continue;
- // CreateNew never overwrites; path is only reported once this call owns the file.
+ // CreateNew never overwrites; path set only once owned.
var stream = new FileStream(candidate, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true);
path = candidate;
return stream;
diff --git a/src/Radiosender/Services/PlaybackEngine.cs b/src/Radiosender/Services/Scheduling/PlaybackEngine.cs
similarity index 62%
rename from src/Radiosender/Services/PlaybackEngine.cs
rename to src/Radiosender/Services/Scheduling/PlaybackEngine.cs
index 4ef1e5a..38355e3 100644
--- a/src/Radiosender/Services/PlaybackEngine.cs
+++ b/src/Radiosender/Services/Scheduling/PlaybackEngine.cs
@@ -1,69 +1,46 @@
using Radiosender.Models;
+using Radiosender.Services.Audio;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Scheduling;
-///
-/// 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.
-///
-///
-/// 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
+// Songs never cut. Events: thread pool; WPF use BeginInvoke, not Invoke (Stop waits -> deadlock).
+public sealed class PlaybackEngine(IAudioPlayer player, Func delay, Func now)
{
- // Extra time before a song counts as stuck, e.g. after an audio device error that never raises TrackFinished.
+ // Stuck-song grace, e.g. 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.
+ // Item started at most this long ago still plays on start (click right after 15:00).
private static readonly TimeSpan LateStart = TimeSpan.FromSeconds(5);
- private readonly IAudioPlayer _player;
- private readonly Func _delay;
- private readonly Func _now;
+ private readonly IAudioPlayer _player = player;
+ private readonly Func _delay = delay;
+ private readonly Func _now = now;
private readonly Lock _lock = new();
private CancellationTokenSource? _cts;
private Task _run = Task.CompletedTask;
- // Completed by ReplaceCurrent to wake the wait of the item on air; a new one per wait.
+ // Set by ReplaceCurrent to wake the on-air wait; new one per wait.
private TaskCompletionSource? _currentChanged;
public PlaybackEngine() : this(MusicPlayer.Instance, Task.Delay, () => DateTime.Now)
{
}
- public PlaybackEngine(IAudioPlayer player, Func delay, Func now)
- {
- _player = player;
- _delay = delay;
- _now = now;
- }
-
- /// 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 .
+ /// 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;
- /// Planned start the engine waits for, or null when it is not waiting.
public DateTime? WaitingUntil { get; private set; }
- ///
- /// Stops any running schedule and starts on the clock. Items that should have
- /// started earlier are skipped; before the first planned start the engine waits.
- ///
public void Start(IReadOnlyList items)
{
Stop();
@@ -76,10 +53,7 @@ public sealed class PlaybackEngine
}
}
- ///
- /// Hot swap: switches to while playing. Items before
- /// must be unchanged. Returns false if the item at has already started.
- ///
+ /// Items before must be unchanged. False if that item already started.
public bool ReplaceUpcoming(IReadOnlyList items, int fromIndex)
{
lock (_lock)
@@ -91,12 +65,7 @@ public sealed class PlaybackEngine
}
}
- ///
- /// Switches to while the item at is on air and that item
- /// itself changed: a news, ad or moderator item then runs for its new length, counted from when it started,
- /// and a song ends at once. Items before must be unchanged. Returns false
- /// if that item is not the one on air.
- ///
+ /// On-air item changed: hold item gets new length from its start, song ends at once. False if not on air.
public bool ReplaceCurrent(IReadOnlyList items, int index)
{
lock (_lock)
@@ -109,7 +78,6 @@ public sealed class PlaybackEngine
}
}
- /// Stops playback. Waits until the running schedule has ended.
public void Stop()
{
Task run;
@@ -151,7 +119,6 @@ public sealed class PlaybackEngine
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)
{
@@ -160,7 +127,7 @@ public sealed class PlaybackEngine
finally { WaitingUntil = null; }
}
- // Under the lock so ReplaceUpcoming cannot swap the item that is about to start.
+ // Lock: ReplaceUpcoming must not swap the item about to start.
lock (_lock)
{
if (i >= Items.Count) break;
@@ -184,8 +151,6 @@ public sealed class PlaybackEngine
}
}
- // Keeps a news, ad or moderator item on air for its length. ReplaceCurrent can change that length
- // meanwhile; the wait then starts over with what is left.
private async Task HoldAsync(int index, CancellationToken token)
{
var startedAt = _now();
@@ -202,11 +167,11 @@ public sealed class PlaybackEngine
return;
using var wait = CancellationTokenSource.CreateLinkedTokenSource(token);
- var delay = _delay(remaining, wait.Token);
- var done = await Task.WhenAny(delay, changed.Task);
- wait.Cancel();
+ var elapsed = _delay(remaining, wait.Token);
+ var done = await Task.WhenAny(elapsed, changed.Task);
+ await wait.CancelAsync();
token.ThrowIfCancellationRequested();
- if (done == delay)
+ if (done == elapsed)
return;
}
}
@@ -234,9 +199,8 @@ public sealed class PlaybackEngine
changed = _currentChanged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
var stuck = _delay(item.Duration + SongGrace, timeout.Token);
- // changed: the user ended the song early; the finally block stops the player.
var done = await Task.WhenAny(finished.Task, stuck, changed.Task);
- timeout.Cancel();
+ await timeout.CancelAsync();
token.ThrowIfCancellationRequested();
if (done == stuck)
ItemFailed?.Invoke(this, (item, new TimeoutException($"Der Song wurde nicht rechtzeitig fertig: {item.Title}")));
@@ -244,7 +208,7 @@ public sealed class PlaybackEngine
finally
{
_player.TrackFinished -= OnFinished;
- // On cancel, timeout or a failed start the song has not ended by itself.
+ // Cancel, timeout, or user ended song (changed): stop player.
if (!finished.Task.IsCompleted) _player.Stop();
}
}
diff --git a/src/Radiosender/Services/Scheduling/ScheduleException.cs b/src/Radiosender/Services/Scheduling/ScheduleException.cs
new file mode 100644
index 0000000..f029ca6
--- /dev/null
+++ b/src/Radiosender/Services/Scheduling/ScheduleException.cs
@@ -0,0 +1,3 @@
+namespace Radiosender.Services.Scheduling;
+
+public class ScheduleException(string message) : Exception(message);
diff --git a/src/Radiosender/Services/ScheduleGenerator.cs b/src/Radiosender/Services/Scheduling/ScheduleGenerator.cs
similarity index 68%
rename from src/Radiosender/Services/ScheduleGenerator.cs
rename to src/Radiosender/Services/Scheduling/ScheduleGenerator.cs
index 596c179..abc1012 100644
--- a/src/Radiosender/Services/ScheduleGenerator.cs
+++ b/src/Radiosender/Services/Scheduling/ScheduleGenerator.cs
@@ -1,71 +1,40 @@
using Radiosender.Models;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Scheduling;
-public record ScheduleOptions
-{
- public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5);
-
- /// Target for ads per hour. Met as closely as the song lengths allow.
- public TimeSpan AdsPerHour { get; init; } = TimeSpan.FromMinutes(20);
-
- /// Target for moderator talk per hour. Met as closely as the song lengths allow.
- public TimeSpan ModeratorPerHour { get; init; } = TimeSpan.FromMinutes(10);
-
- /// Longest single ad item; longer ad time is split and separated by moderator talk or songs.
- public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5);
-
- /// Random song picks tried per half hour; the one closest to the targets wins.
- public int Attempts { get; init; } = 400;
-}
-
-public class ScheduleException(string message) : Exception(message);
-
-///
-/// Builds the plan in half-hour slots: news at :00 and :30, then random songs with ads and moderator talk
-/// in between. The last song of each slot ends exactly when the next news starts, so the ad and moderator
-/// time is whatever the songs leave; the generator picks songs that leave as close to the targets as it can
-/// and evens out the difference in the second half of the hour.
-/// A start between two news times gets a lead-in without news up to the next :00 or :30.
-///
+// Half-hour slots: news at :00/:30; last song ends exactly at next news; ads/talk fill the rest.
public class ScheduleGenerator(ScheduleOptions options, Random random)
{
- /// Can be replaced at any time, e.g. from the settings page; the next plan uses the new values.
public ScheduleOptions Options { get; set; } = options;
private static readonly TimeSpan HalfHour = TimeSpan.FromMinutes(30);
- // A pick that misses the target by this little is taken at once.
private static readonly TimeSpan CloseEnough = TimeSpan.FromSeconds(1);
public ScheduleGenerator() : this(new ScheduleOptions(), Random.Shared)
{
}
- ///
- /// Plans full hours. They begin at if that is :00 or :30,
- /// otherwise at the next :00 or :30 after a lead-in of music.
- ///
public IReadOnlyList Generate(DateTime start, int hours, IReadOnlyList songs)
{
- var options = Options; // one consistent set of values for the whole plan
+ var options = Options; // snapshot: Options can be swapped mid-plan
if (hours < 1)
throw new ArgumentOutOfRangeException(nameof(hours), "At least one full hour is required.");
if (options.MaxAdBlock <= TimeSpan.Zero || options.MaxAdBlock >= TimeSpan.FromMinutes(20))
throw new ArgumentException("MaxAdBlock must be between 0 and 20 minutes.", nameof(options));
- var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList();
+ List playable = [.. songs.Where(s => s.Duration > TimeSpan.Zero)];
if (playable.Count == 0)
throw new ScheduleException("Die Bibliothek enthält keine Songs zum Planen.");
- var items = new List();
+ List items = [];
var firstNews = new DateTime((start.Ticks + HalfHour.Ticks - 1) / HalfHour.Ticks * HalfHour.Ticks, start.Kind);
if (firstNews > start)
items.AddRange(BuildLeadIn(options, start, firstNews - start, playable));
var adHalf = options.AdsPerHour / 2;
var moderatorHalf = options.ModeratorPerHour / 2;
- // How far the :00 slot ended up over (or under) its half of the hour; the :30 slot makes up for it.
+ // :00 slot over/under target; :30 slot compensates.
var adOver = TimeSpan.Zero;
var moderatorOver = TimeSpan.Zero;
for (var slotStart = firstNews; slotStart < firstNews.AddHours(hours); slotStart += HalfHour)
@@ -88,7 +57,6 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
private List BuildLeadIn(ScheduleOptions options, DateTime start, TimeSpan length, List songs)
{
- // The targets shrink with the lead-in: half of a half hour gets half of the ads.
var share = length / HalfHour;
try
{
@@ -96,7 +64,7 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
}
catch (ScheduleException) when (length <= (options.AdsPerHour + options.ModeratorPerHour) / 2)
{
- // Too short for any song: the moderator talks until the news.
+ // Too short for any song: moderator fills.
return [new ScheduleItem(ScheduleItemKind.Moderator, "", start, length)];
}
}
@@ -108,7 +76,6 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
return [];
var target = Min(adTarget + moderatorTarget, length);
var (picked, gap) = PickBest(options, length, target, songs);
- // No song at all is only right when the targets leave no room for music.
if (picked.Count == 0 && target < length)
throw new ScheduleException(
$"Keine Song-Kombination füllt den Abschnitt ab {slotStart:HH:mm} so, dass der letzte Song pünktlich endet. Mehr Songs hinzufügen, vor allem kürzere.");
@@ -117,12 +84,8 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
return Arrange(options, slotStart, picked, ads, moderator, keepFirstSongFirst: false);
}
- ///
- /// Hot swap: puts at in place of that item and
- /// rebuilds the rest of its half-hour slot, so the last song still ends exactly when the next news starts.
- /// Items before and all later slots stay as they are.
- ///
- /// The song does not fit before the next news.
+ // Hot swap: rebuilds rest of the slot only; earlier items and later slots stay.
+ /// Song does not fit before next news.
public IReadOnlyList Replace(IReadOnlyList plan, int index, Song requested, IReadOnlyList songs)
{
ArgumentOutOfRangeException.ThrowIfNegative(index);
@@ -142,13 +105,13 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
throw new ScheduleException(
$"\"{requested.Title}\" ({requested.Duration:m\\:ss}) passt nicht vor die Nachrichten um {slotEnd:HH:mm}; es sind nur noch {length:m\\:ss} übrig. Ein früheres Element wählen.");
- // What the slot has already spent on ads and moderator talk before the request counts against its targets.
+ // Ads/talk already in this slot count against its targets.
var options = Options;
- var prefix = plan.Take(index).ToList();
- var slotPrefix = prefix.Skip(slotStartIndex + 1).ToList();
+ List prefix = [.. plan.Take(index)];
+ List slotPrefix = [.. prefix.Skip(slotStartIndex + 1)];
var adTarget = Max(options.AdsPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Ad)), TimeSpan.Zero);
var moderatorTarget = Max(options.ModeratorPerHour / 2 - Sum(slotPrefix.Where(i => i.Kind == ScheduleItemKind.Moderator)), TimeSpan.Zero);
- var playable = songs.Where(s => s.Duration > TimeSpan.Zero).ToList();
+ List playable = [.. songs.Where(s => s.Duration > TimeSpan.Zero)];
var (picked, gap) = PickBest(options, length, Min(adTarget + moderatorTarget, length), playable, requested);
var (ads, moderator) = Split(options, gap, adTarget, moderatorTarget);
@@ -170,8 +133,7 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
return -1;
}
- // Tries random song picks and keeps the one whose leftover time is closest to the target for ads and
- // moderator talk. Picks never go over the music time, so the leftover is the target or more.
+ // Picks never exceed music budget, so gap >= target; smallest gap wins.
private (List Songs, TimeSpan Gap) PickBest(
ScheduleOptions options, TimeSpan length, TimeSpan target, List songs, Song? first = null)
{
@@ -193,12 +155,12 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
private List PickSongs(TimeSpan budget, List songs, Song? previous = null)
{
- var picked = new List();
+ List picked = [];
var left = budget;
while (true)
{
var last = picked.Count > 0 ? picked[^1] : previous;
- var fitting = songs.Where(s => s.Duration <= left && (last is null || s.Id != last.Id || songs.Count == 1)).ToList();
+ List fitting = [.. songs.Where(s => s.Duration <= left && (last is null || s.Id != last.Id || songs.Count == 1))];
if (fitting.Count == 0)
return picked;
var song = fitting[random.Next(fitting.Count)];
@@ -207,12 +169,11 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
}
}
- // Shares the leftover time between ads and moderator talk in the ratio of their targets.
+ // Gap split in target ratio; no target left: hourly ratio, else talk only.
private static (TimeSpan Ads, TimeSpan Moderator) Split(ScheduleOptions options, TimeSpan gap, TimeSpan adTarget, TimeSpan moderatorTarget)
{
if (adTarget + moderatorTarget <= TimeSpan.Zero)
{
- // This slot has nothing left to aim for; fall back to the hourly ratio, or to talk alone.
adTarget = options.AdsPerHour;
moderatorTarget = options.ModeratorPerHour;
if (adTarget + moderatorTarget <= TimeSpan.Zero)
@@ -223,29 +184,25 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
return (ads, gap - ads);
}
- // Lays out the slot: songs with breaks in between, each break "moderator, ad, moderator, ad ...".
- // Ads are cut into pieces of at most MaxAdBlock and never follow each other directly as long as there
- // is moderator talk or a song to put between them. The slot always ends with a song.
+ // Breaks "moderator, ad, moderator, ad..." between songs; ads <= MaxAdBlock, never back to back; slot ends with a song.
private static List Arrange(
ScheduleOptions options, DateTime start, List songs, TimeSpan ads, TimeSpan moderator, bool keepFirstSongFirst)
{
var adPieces = Pieces(ads, (int)Math.Ceiling(ads / options.MaxAdBlock));
- // One moderator piece in front of every ad piece; without ads, one piece per five minutes of talk.
var moderatorPieces = Pieces(moderator, adPieces.Count > 0 ? adPieces.Count : (int)Math.Ceiling(moderator / TimeSpan.FromMinutes(5)));
var pairs = Math.Max(adPieces.Count, moderatorPieces.Count);
- // A hot swap keeps the requested song at its position, so breaks start after it when another song follows.
+ // Hot swap: requested song stays first, breaks start after it.
var firstBreakSong = keepFirstSongFirst && songs.Count > 1 ? 1 : 0;
var breakSlots = Math.Max(songs.Count - firstBreakSong, 1);
var breaks = Math.Min(pairs, breakSlots);
- var items = new List();
+ List items = [];
var time = start;
void Add(ScheduleItemKind kind, TimeSpan duration, Song? song = null)
{
if (duration <= TimeSpan.Zero)
return;
- // News, ads and moderator items start without a title; the user can name them in the timeline.
var title = song is null ? "" : string.IsNullOrWhiteSpace(song.Artist) ? song.Title : $"{song.Artist} - {song.Title}";
items.Add(new ScheduleItem(kind, title, time, duration, song));
time += duration;
@@ -254,7 +211,6 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
var pair = 0;
void AddBreak(int number)
{
- // Pairs are dealt out evenly; the last break takes what is left.
var until = number == breaks - 1 ? pairs : pairs * (number + 1) / breaks;
for (; pair < until; pair++)
{
@@ -266,24 +222,21 @@ public class ScheduleGenerator(ScheduleOptions options, Random random)
var nextBreak = 0;
for (var i = 0; i < songs.Count; i++)
{
- // Break n sits before the song at its share of the way through the slot.
while (nextBreak < breaks && i == firstBreakSong + nextBreak * breakSlots / breaks)
AddBreak(nextBreak++);
Add(ScheduleItemKind.Song, songs[i].Duration, songs[i]);
}
- // No songs at all: the slot is ads and talk only.
while (nextBreak < breaks)
AddBreak(nextBreak++);
return items;
}
- // Cuts a time into pieces of whole seconds that differ by at most one second, so no piece grows past
- // the limit the count was chosen for. A fraction of a second goes to the last piece.
+ // Whole-second pieces differing by <= 1 s, so none exceeds the limit; sub-second rest goes to last piece.
private static List Pieces(TimeSpan total, int count)
{
- var pieces = new List();
if (total <= TimeSpan.Zero || count < 1)
- return pieces;
+ return [];
+ List pieces = [];
var seconds = (long)Math.Floor(total.TotalSeconds);
for (var i = 0; i < count; i++)
pieces.Add(TimeSpan.FromSeconds(seconds / count + (i < seconds % count ? 1 : 0)));
diff --git a/src/Radiosender/Services/Scheduling/ScheduleOptions.cs b/src/Radiosender/Services/Scheduling/ScheduleOptions.cs
new file mode 100644
index 0000000..b74a6d9
--- /dev/null
+++ b/src/Radiosender/Services/Scheduling/ScheduleOptions.cs
@@ -0,0 +1,14 @@
+namespace Radiosender.Services.Scheduling;
+
+public record ScheduleOptions
+{
+ public TimeSpan NewsDuration { get; init; } = TimeSpan.FromMinutes(5);
+
+ public TimeSpan AdsPerHour { get; init; } = TimeSpan.FromMinutes(20);
+
+ public TimeSpan ModeratorPerHour { get; init; } = TimeSpan.FromMinutes(10);
+
+ public TimeSpan MaxAdBlock { get; init; } = TimeSpan.FromMinutes(5);
+
+ public int Attempts { get; init; } = 400;
+}
diff --git a/src/Radiosender/Services/AppSettings.cs b/src/Radiosender/Services/Settings/AppSettings.cs
similarity index 67%
rename from src/Radiosender/Services/AppSettings.cs
rename to src/Radiosender/Services/Settings/AppSettings.cs
index 5b9acb0..9548f7d 100644
--- a/src/Radiosender/Services/AppSettings.cs
+++ b/src/Radiosender/Services/Settings/AppSettings.cs
@@ -3,51 +3,42 @@ using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
+using Radiosender.Services.Scheduling;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Settings;
-/// What the user can change on the Settings page. The defaults are the values the app shipped with.
public record AppSettings
{
- public const int MinAlertSeconds = 5;
- public const int MaxAlertSeconds = 300;
+ private const int MinAlertSeconds = 5;
+ private const int MaxAlertSeconds = 300;
+
+ private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true };
public bool NewsAlert { get; init; } = true;
- /// How long before a news item the reminder appears.
public int NewsAlertSeconds { get; init; } = 30;
public bool NewsAlertSound { get; init; } = true;
public bool ModeratorAlert { get; init; } = true;
- /// How long before a moderator item the reminder appears.
public int ModeratorAlertSeconds { get; init; } = 30;
public bool ModeratorAlertSound { get; init; } = true;
- /// News time per hour, split over the two news at :00 and :30.
public int NewsMinutesPerHour { get; init; } = 10;
- /// Target; the plan gets as close as the song lengths allow.
public int ModeratorMinutesPerHour { get; init; } = 10;
-
- /// Target; the plan gets as close as the song lengths allow.
public int AdMinutesPerHour { get; init; } = 20;
- /// Playback device for the listeners; null is the Windows default device.
- public string? BroadcastDevice { get; init; }
+ public string? BroadcastDevice { get; init; } // null: Windows default device
- /// Playback device for the person at the desk; null means no device of its own.
- public string? MonitorDevice { get; init; }
+ public string? MonitorDevice { get; init; } // null: no monitor device
- /// Streaming to laut.fm and its library on the Import page; the Live button shows only while this is on.
public bool LautFmEnabled { get; init; }
- /// The station's id in Radioadmin, needed for the library.
public string LautFmStationId { get; init; } = "";
- /// Live access data from Radioadmin, "Live senden".
public string LautFmHost { get; init; } = "";
public int LautFmPort { get; init; } = 8080;
@@ -56,11 +47,10 @@ public record AppSettings
public string LautFmUser { get; init; } = "source";
- /// Kept in memory as is; the file only holds it encrypted for the Windows user.
+ // Secrets: plain in memory, DPAPI-encrypted in the file via the Protected* properties.
[JsonIgnore]
public string LautFmPassword { get; init; } = "";
- /// The Radioadmin login token for the library; stored encrypted like the password.
[JsonIgnore]
public string LautFmToken { get; init; } = "";
@@ -70,13 +60,12 @@ public record AppSettings
[JsonInclude, JsonPropertyName("LautFmToken")]
private string? ProtectedLautFmToken { get => Protect(LautFmToken); init => LautFmToken = Unprotect(value); }
- // Records print every property; the password and token stay out of logs and debugger views.
+ // Record ToString would leak secrets into logs/debugger.
public override string ToString() => nameof(AppSettings);
public static string DefaultPath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Radiosender", "settings.json");
- /// The first problem with these values as a message for the user, or null when they are fine.
public string? Validate()
{
if (NewsAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds || ModeratorAlertSeconds is < MinAlertSeconds or > MaxAlertSeconds)
@@ -108,7 +97,6 @@ public record AppSettings
ModeratorPerHour = TimeSpan.FromMinutes(ModeratorMinutesPerHour),
};
- /// Reads the settings; a missing, unreadable or invalid file gives the defaults.
public static AppSettings Load(string path)
{
try
@@ -122,20 +110,18 @@ public record AppSettings
}
}
- /// The file cannot be written.
- /// The file cannot be written.
public void Save(string path)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
- File.WriteAllText(path, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }));
+ File.WriteAllText(path, JsonSerializer.Serialize(this, WriteOptions));
}
- // DPAPI: only this Windows user on this computer can read the value back.
+ // DPAPI: only this Windows user on this machine can decrypt.
private static string? Protect(string secret) => secret.Length == 0
? null
: Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(secret), null, DataProtectionScope.CurrentUser));
- // A value from another user or computer cannot be read; the user enters it again.
+ // Other user/machine: unreadable, user re-enters it.
private static string Unprotect(string? stored)
{
if (string.IsNullOrEmpty(stored))
diff --git a/src/Radiosender/Services/SettingsStore.cs b/src/Radiosender/Services/Settings/SettingsStore.cs
similarity index 57%
rename from src/Radiosender/Services/SettingsStore.cs
rename to src/Radiosender/Services/Settings/SettingsStore.cs
index 8424dfb..b3a3d7e 100644
--- a/src/Radiosender/Services/SettingsStore.cs
+++ b/src/Radiosender/Services/Settings/SettingsStore.cs
@@ -1,9 +1,8 @@
-namespace Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Scheduling;
+
+namespace Radiosender.Services.Settings;
-///
-/// The current for the whole app. Loads them at startup and, on every save,
-/// writes the file and hands the minutes per hour to the schedule generator and the devices to the audio output.
-///
public class SettingsStore
{
private readonly ScheduleGenerator _generator;
@@ -17,19 +16,18 @@ public class SettingsStore
_path = path;
Current = AppSettings.Load(path);
_generator.Options = Current.ToScheduleOptions();
- // Nothing is open yet at startup, so this cannot fail here.
+ // Nothing open at startup: cannot fail.
_output.UseDevices(Current.BroadcastDevice, Current.MonitorDevice);
}
public AppSettings Current { get; private set; }
- /// Stores the settings and applies them: alerts and audio devices at once, minutes per hour from the next plan on.
- /// The settings file cannot be written.
- /// The settings file cannot be written.
- /// A chosen audio device cannot be opened; nothing was saved.
+ /// File not writable.
+ /// File not writable.
+ /// Device cannot be opened; nothing saved.
public void Save(AppSettings settings)
{
- // Devices first: if one cannot be opened, the old settings stay in the file.
+ // Devices first: on failure the file keeps the old settings.
if (settings.BroadcastDevice != Current.BroadcastDevice || settings.MonitorDevice != Current.MonitorDevice)
{
try
diff --git a/src/Radiosender/Services/IcecastStream.cs b/src/Radiosender/Services/Streaming/IcecastStream.cs
similarity index 72%
rename from src/Radiosender/Services/IcecastStream.cs
rename to src/Radiosender/Services/Streaming/IcecastStream.cs
index 9f17222..11f5c52 100644
--- a/src/Radiosender/Services/IcecastStream.cs
+++ b/src/Radiosender/Services/Streaming/IcecastStream.cs
@@ -5,33 +5,11 @@ using System.Text;
using NAudio.MediaFoundation;
using NAudio.Wave;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Streaming;
-/// Error of a live stream, with a message that can be shown to the user as is.
-public class LiveStreamException(string message, Exception? inner = null) : Exception(message, inner);
-
-/// Where and how a live source logs in. laut.fm shows these values in Radioadmin under "Live senden".
-public record IcecastTarget(string Host, int Port, string Mount, string User, string Password)
-{
- public string Path => Mount.StartsWith('/') ? Mount : "/" + Mount;
-
- public static IcecastTarget From(AppSettings settings) => new(
- settings.LautFmHost.Trim(), settings.LautFmPort, settings.LautFmMount.Trim(), settings.LautFmUser.Trim(), settings.LautFmPassword);
-
- /// Value of the Basic authorization header.
- public string Credentials => Convert.ToBase64String(Encoding.UTF8.GetBytes($"{User}:{Password}"));
-
- // The password stays out of logs and debugger views.
- public override string ToString() => $"{User}@{Host}:{Port}{Path}";
-}
-
-///
-/// A source connection to an Icecast server, which is what laut.fm takes for live broadcasts.
-/// Reads 32-bit float audio from a feed and sends it as MP3 at 128 kbit/s until disposed.
-///
public sealed class IcecastStream : IDisposable
{
- public const int Bitrate = 128_000;
+ private const int Bitrate = 128_000;
private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(10);
private readonly TcpClient _client;
@@ -46,17 +24,13 @@ public sealed class IcecastStream : IDisposable
_thread = new Thread(Run) { IsBackground = true, Name = "Icecast stream" };
}
- /// The connection broke or the encoder stopped. Raised on the stream's own thread.
+ /// Raised on the stream's own thread.
public event EventHandler? Failed;
- /// Logs in at the server and starts sending.
- /// Server and login.
- /// 32-bit float audio that returns 0 bytes while nothing new is there, like .
- /// Cancels the login.
- /// The server cannot be reached or refused the login.
+ /// Server unreachable or login refused.
public static async Task ConnectAsync(IcecastTarget target, IWaveProvider feed, CancellationToken cancellationToken = default)
{
- // These values end up in the request line and headers; a line break there would change the request.
+ // Security: values go into request line/headers; a line break would inject headers.
if (new[] { target.Host, target.Path, target.User }.Any(value => value.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|| target.User.Contains(':'))
throw new LiveStreamException("Server, Mountpoint oder Benutzer enthalten ungültige Zeichen.");
@@ -109,11 +83,10 @@ public sealed class IcecastStream : IDisposable
}
}
- /// Sets the title listeners see, through the server's admin interface with the same login.
/// The server did not take the title.
public static async Task UpdateTitleAsync(HttpClient http, IcecastTarget target, string title, CancellationToken cancellationToken = default)
{
- // Plain http, like the source connection itself: Icecast takes sources without TLS.
+ // Plain http like the source connection: Icecast takes sources without TLS.
var url = new UriBuilder(Uri.UriSchemeHttp, target.Host, target.Port, "/admin/metadata")
{
Query = $"mount={Uri.EscapeDataString(target.Path)}&mode=updinfo&song={Uri.EscapeDataString(title)}",
@@ -132,12 +105,11 @@ public sealed class IcecastStream : IDisposable
}
}
- /// Stops sending and closes the connection.
public void Dispose()
{
_stopping = true;
_reader.Stop();
- // The encoder ends once the reader returns 0; a stalled connection is cut by closing the socket.
+ // Encoder ends when reader returns 0; stalled connection is cut by closing the socket.
if (Thread.CurrentThread != _thread && _thread.IsAlive)
_thread.Join(TimeSpan.FromSeconds(2));
_client.Dispose();
@@ -158,7 +130,7 @@ public sealed class IcecastStream : IDisposable
}
catch (Exception ex)
{
- // While stopping, closing the socket under the encoder is expected.
+ // Stopping: socket closed under the encoder is expected.
if (!_stopping)
Failed?.Invoke(this, ex is LiveStreamException ? ex.Message : $"Verbindung zu laut.fm verloren: {ex.Message}");
}
@@ -175,14 +147,13 @@ public sealed class IcecastStream : IDisposable
throw new LiveStreamException("Der Server hat die Verbindung ohne gültige Antwort beendet.");
header.Append(Encoding.ASCII.GetString(buffer, 0, read));
}
- // "HTTP/1.1 100 Continue" or "HTTP/1.0 200 OK"
var parts = header.ToString().Split(' ', 3);
return parts.Length >= 2 && int.TryParse(parts[1], out var status)
? status
: throw new LiveStreamException("Der Server hat ungültig geantwortet.");
}
- /// Waits for audio instead of ending when the feed is empty, so the encoder keeps going in real time.
+ // Empty feed: wait instead of ending, so the encoder runs in real time.
private sealed class FeedReader(IWaveProvider feed) : IWaveProvider
{
private volatile bool _stopped;
@@ -200,7 +171,7 @@ public sealed class IcecastStream : IDisposable
return read;
Thread.Sleep(10);
}
- return 0; // the encoder finishes and returns
+ return 0; // encoder finishes
}
}
}
diff --git a/src/Radiosender/Services/Streaming/IcecastTarget.cs b/src/Radiosender/Services/Streaming/IcecastTarget.cs
new file mode 100644
index 0000000..8e05870
--- /dev/null
+++ b/src/Radiosender/Services/Streaming/IcecastTarget.cs
@@ -0,0 +1,17 @@
+using System.Text;
+using Radiosender.Services.Settings;
+
+namespace Radiosender.Services.Streaming;
+
+public record IcecastTarget(string Host, int Port, string Mount, string User, string Password)
+{
+ public string Path => Mount.StartsWith('/') ? Mount : "/" + Mount;
+
+ public static IcecastTarget From(AppSettings settings) => new(
+ settings.LautFmHost.Trim(), settings.LautFmPort, settings.LautFmMount.Trim(), settings.LautFmUser.Trim(), settings.LautFmPassword);
+
+ public string Credentials => Convert.ToBase64String(Encoding.UTF8.GetBytes($"{User}:{Password}"));
+
+ // Security: keeps the password out of logs and debugger views.
+ public override string ToString() => $"{User}@{Host}:{Port}{Path}";
+}
diff --git a/src/Radiosender/Services/Streaming/LiveStreamException.cs b/src/Radiosender/Services/Streaming/LiveStreamException.cs
new file mode 100644
index 0000000..a856a56
--- /dev/null
+++ b/src/Radiosender/Services/Streaming/LiveStreamException.cs
@@ -0,0 +1,4 @@
+namespace Radiosender.Services.Streaming;
+
+/// Message is shown to the user as is.
+public class LiveStreamException(string message, Exception? inner = null) : Exception(message, inner);
diff --git a/src/Radiosender/Services/StreamTitles.cs b/src/Radiosender/Services/Streaming/StreamTitles.cs
similarity index 63%
rename from src/Radiosender/Services/StreamTitles.cs
rename to src/Radiosender/Services/Streaming/StreamTitles.cs
index f356362..f290f00 100644
--- a/src/Radiosender/Services/StreamTitles.cs
+++ b/src/Radiosender/Services/Streaming/StreamTitles.cs
@@ -1,15 +1,12 @@
using Radiosender.Models;
-namespace Radiosender.Services;
+namespace Radiosender.Services.Streaming;
-///
-/// The stream title for each item. laut.fm starts its ad break when the title is "START_AD_BREAK" and
-/// wants that at most once in 15 minutes, so later ad items within that time keep their own title.
-///
+// laut.fm: title AdBreak starts an ad break, max once per 15 min; later ads keep their own title.
public class StreamTitles(Func now)
{
public const string AdBreak = "START_AD_BREAK";
- public static readonly TimeSpan MinAdBreakSpacing = TimeSpan.FromMinutes(15);
+ private static readonly TimeSpan MinAdBreakSpacing = TimeSpan.FromMinutes(15);
private DateTime? _lastAdBreak;
diff --git a/src/Radiosender/Views/GridColumns.cs b/src/Radiosender/Views/GridColumns.cs
index 095ffec..80cb6a6 100644
--- a/src/Radiosender/Views/GridColumns.cs
+++ b/src/Radiosender/Views/GridColumns.cs
@@ -7,34 +7,25 @@ using System.Windows.Media;
namespace Radiosender.Views;
-/// Sizes the text columns of a list so that every row can be read in full.
public static class GridColumns
{
- // Cell padding on both sides plus a little air, so the text never touches the next column.
private const double Slack = 28;
- // Rows use this size when no row exists yet to ask.
private const double DefaultFontSize = 14;
- // The width from the XAML stays the minimum, so an empty or short list keeps its designed look.
+ // XAML width = minimum.
private static readonly ConditionalWeakTable MinWidths = [];
- // Laying out text is the slow part and the same titles come up on every refresh, so widths are remembered.
- // All lists share one font. shortcut: never trimmed; clear it if libraries reach hundreds of thousands of songs.
+ // Assumes one shared font. shortcut: never trimmed, clear if libraries reach 100k+ songs.
private static readonly Dictionary TextWidths = [];
- ///
- /// Widens each column with a to its longest text over
- /// all rows, not only the visible ones: the lists are virtualized, so the built-in auto width would miss
- /// rows that are scrolled out of view. Columns with a cell template keep their width, and so do columns
- /// with a string format: those show times, which always have the same length.
- ///
+ // Measures all rows: lists are virtualized, built-in auto width misses off-screen rows.
public static void Fit(ListView list)
{
if (list.View is not GridView view)
return;
- // The rows have their own font size, so a realized row is asked rather than the list.
+ // Rows have own font size: ask realized row, not list.
var row = list.ItemContainerGenerator.ContainerFromIndex(0) as Control;
var typeface = new Typeface(row?.FontFamily ?? list.FontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
var fontSize = row?.FontSize ?? DefaultFontSize;
@@ -63,13 +54,12 @@ public static class GridColumns
}
var fitted = Math.Max(min, Math.Ceiling(widest + Slack));
- if (column.Width != fitted) // setting it triggers a layout pass
+ if (column.Width != fitted) // set triggers layout pass
column.Width = fitted;
}
}
- // Follows a simple property path such as "Item.Title". A binding on a probe element would not do:
- // it only resolves once the element is part of the window.
+ // Reflection, not probe binding: binding resolves only once in the visual tree.
private static string Text(object? value, string[] properties)
{
foreach (var property in properties)
diff --git a/src/Radiosender/Views/MainWindow.xaml.cs b/src/Radiosender/Views/MainWindow.xaml.cs
index 3c42ffa..91bf5d1 100644
--- a/src/Radiosender/Views/MainWindow.xaml.cs
+++ b/src/Radiosender/Views/MainWindow.xaml.cs
@@ -3,7 +3,7 @@ using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using Radiosender.Controllers;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Settings;
using Radiosender.Views.Pages;
using Wpf.Ui.Controls;
@@ -21,16 +21,13 @@ public partial class MainWindow : FluentWindow
_schedule = schedule;
_settings = settings;
InitializeComponent();
- // The navigation view asks the container for each page, so pages get their controllers injected.
RootNavigation.SetServiceProvider(services);
- // Re-themes the app when the user switches the Windows theme while it runs.
Wpf.Ui.Appearance.SystemThemeWatcher.Watch(this);
Loaded += (_, _) => RootNavigation.Navigate(typeof(SchedulePage));
_reminderTimer.Tick += (_, _) => RemindSpeaker();
_reminderTimer.Start();
}
- // Shortly before news or moderator talk goes on air, the person at the microphone gets a heads-up.
private void RemindSpeaker()
{
var settings = _settings.Current;
@@ -43,7 +40,6 @@ public partial class MainWindow : FluentWindow
var what = item.KindName;
if (isNews ? settings.NewsAlertSound : settings.ModeratorAlertSound)
PlayBing();
- // A dialog in the middle of the screen that stays until OK is clicked; the broadcast keeps running behind it.
_ = new Wpf.Ui.Controls.MessageBox
{
Title = "Gleich bist du dran.",
@@ -54,7 +50,6 @@ public partial class MainWindow : FluentWindow
}.ShowDialogAsync();
}
- // A short generated tone on its own output, so it sounds over the running broadcast.
private static void PlayBing()
{
try
@@ -68,7 +63,7 @@ public partial class MainWindow : FluentWindow
}
catch (Exception ex) when (ex is NAudio.MmException or InvalidOperationException)
{
- // No audio device: the dialog still reminds the speaker.
+ // No audio device: dialog still reminds.
}
}
}
diff --git a/src/Radiosender/Views/Pages/ImportPage.xaml.cs b/src/Radiosender/Views/Pages/ImportPage.xaml.cs
index 5363840..4a3c2c1 100644
--- a/src/Radiosender/Views/Pages/ImportPage.xaml.cs
+++ b/src/Radiosender/Views/Pages/ImportPage.xaml.cs
@@ -7,22 +7,21 @@ using Microsoft.Win32;
using NAudio.Wave;
using Radiosender.Controllers;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Providers;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
-/// Adds music to the library from local files or from an online provider; both list their results in one place.
public partial class ImportPage : Page
{
private readonly OnlineImportController _online;
private readonly UploadController _upload;
private readonly ObservableCollection _session = [];
- // Preview has its own output, so it never interrupts a running broadcast.
+ // Own output: never interrupts broadcast.
private WaveOut? _previewOutput;
private MediaFoundationReader? _previewReader;
- private int _previewId; // changes on every start and stop; a late callback with an old id is ignored
+ private int _previewId; // bumped on start/stop; late callbacks with old id ignored
private bool _uploading;
private bool _busy;
private bool _previewing;
@@ -32,7 +31,6 @@ public partial class ImportPage : Page
_online = online;
_upload = upload;
InitializeComponent();
- // One provider needs no choice: the tab carries its name. Several get a list next to the search box.
var providers = _online.Providers;
ProviderBox.ItemsSource = providers;
ProviderBox.SelectedIndex = providers.Count > 0 ? 0 : -1;
@@ -48,8 +46,6 @@ public partial class ImportPage : Page
};
}
- // ---- From computer ----
-
private async void OnChooseFiles(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog { Filter = UploadController.FileDialogFilter, Multiselect = true };
@@ -75,7 +71,6 @@ public partial class ImportPage : Page
await UploadAsync(paths);
}
- // Files are imported one by one on a pool thread; each result shows up as soon as it is known.
private async Task UploadAsync(IReadOnlyList paths)
{
if (paths.Count == 0) return;
@@ -104,8 +99,6 @@ public partial class ImportPage : Page
}
}
- // ---- Online providers ----
-
private ResultRow? Selected => Results.SelectedItem as ResultRow;
private void OnQueryKeyDown(object sender, KeyEventArgs e)
@@ -141,8 +134,7 @@ public partial class ImportPage : Page
}
}
- // One button: starts the preview, or stops the running one.
- // NAudio, not WPF's MediaPlayer: that one cannot open https URLs.
+ // NAudio, not WPF MediaPlayer: MediaPlayer cannot open https.
private async void OnPreview(object sender, RoutedEventArgs e)
{
if (_previewing)
@@ -157,7 +149,6 @@ public partial class ImportPage : Page
var id = ++_previewId;
try
{
- // Connects to the server, so it runs off the UI thread. The file is streamed, nothing is saved.
var reader = await Task.Run(() => new MediaFoundationReader(uri.AbsoluteUri));
if (id != _previewId) // stopped or page left in the meantime
{
@@ -200,7 +191,7 @@ public partial class ImportPage : Page
_previewOutput = null;
_previewReader = null;
SetPreviewing(false);
- // Disposing waits for the audio thread, which can sit in a network read; not on the UI thread.
+ // Off UI thread: Dispose waits for audio thread, may block in network read.
if (output is not null || reader is not null)
Task.Run(() =>
{
@@ -211,10 +202,9 @@ public partial class ImportPage : Page
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => OnImport(sender, e);
- // Everything selected that can still be imported.
- private List Importable => Results.SelectedItems.OfType().Where(r => r.CanImport).ToList();
+ private List Importable => [.. Results.SelectedItems.OfType().Where(r => r.CanImport)];
- // One after the other: providers limit anonymous requests, and each result shows up as soon as it is done.
+ // Sequential: providers rate-limit anonymous requests.
private async void OnImport(object sender, RoutedEventArgs e)
{
var rows = Importable;
@@ -240,7 +230,7 @@ public partial class ImportPage : Page
}
catch (Exception ex) when (ex is MusicProviderException or Microsoft.EntityFrameworkCore.DbUpdateException)
{
- // The database error text is technical and English; the usual cause is a song that is already stored.
+ // DB error text is technical English; usual cause: song already stored.
var reason = ex is MusicProviderException ? ex.Message : "Der Song konnte nicht in der Bibliothek gespeichert werden.";
_session.Insert(0, SessionRow.Failed(row.Track.Title, reason));
failed++;
@@ -283,7 +273,6 @@ public partial class ImportPage : Page
var importable = Importable.Count;
ImportButton.IsEnabled = !_busy && importable > 0;
ImportButton.Content = importable > 1 ? $"{importable} in Bibliothek importieren" : "In Bibliothek importieren";
- // Why the selection cannot be imported ("In Bibliothek", "Keine Dauer"); shown on the disabled button.
ImportButton.ToolTip = importable == 0 && Selected is { } blocked ? blocked.Status : null;
}
@@ -295,8 +284,6 @@ public partial class ImportPage : Page
Message.IsOpen = true;
}
- // ---- Shared ----
-
private void OnOpenLibrary(object sender, RoutedEventArgs e) =>
(Window.GetWindow(this) as MainWindow)?.RootNavigation.Navigate(typeof(LibraryPage));
diff --git a/src/Radiosender/Views/Pages/LibraryPage.xaml.cs b/src/Radiosender/Views/Pages/LibraryPage.xaml.cs
index 68657a7..d1b9214 100644
--- a/src/Radiosender/Views/Pages/LibraryPage.xaml.cs
+++ b/src/Radiosender/Views/Pages/LibraryPage.xaml.cs
@@ -19,7 +19,6 @@ public partial class LibraryPage : Page
private Song? Selected => SongList.SelectedItem as Song;
- // Loaded fires on every navigation to the page, so the list is reloaded from the database each time.
private void OnLoaded(object sender, RoutedEventArgs e) => Refresh();
private void OnSearchChanged(object sender, TextChangedEventArgs e) => Refresh();
diff --git a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs
index c606dda..b752fa1 100644
--- a/src/Radiosender/Views/Pages/SchedulePage.xaml.cs
+++ b/src/Radiosender/Views/Pages/SchedulePage.xaml.cs
@@ -4,7 +4,9 @@ using System.Windows.Controls;
using System.Windows.Threading;
using Radiosender.Controllers;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Scheduling;
+using Radiosender.Services.Streaming;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
@@ -17,16 +19,14 @@ public partial class SchedulePage : Page
private int _scrolledTo = -1;
private bool _shownPlaying;
- // Weekday names in the start list follow the interface language, not the Windows setting.
+ // UI language, not Windows culture.
private static readonly System.Globalization.CultureInfo German = new("de-DE");
- // Bound once and updated row by row, so a click never rebuilds the whole list.
private readonly ObservableCollection _rows = [];
- // A controller call is running on a pool thread; the buttons that would collide with it are off.
private bool _working;
- // Optimistic state: what the user just asked for, shown before the engine has caught up.
+ // Optimistic: shown before engine catches up.
private bool? _expectPlaying;
private readonly Microphone _microphone;
@@ -41,7 +41,7 @@ public partial class SchedulePage : Page
_mixer = output.Mixer;
InitializeComponent();
Timeline.ItemsSource = _rows;
- // Also refreshes the buttons: Finished can arrive just before the engine reports it stopped.
+ // Buttons too: Finished can arrive before engine reports stopped.
_progressTimer.Tick += (_, _) =>
{
UpdateButtons();
@@ -49,7 +49,6 @@ public partial class SchedulePage : Page
};
}
- // 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;
@@ -65,13 +64,12 @@ public partial class SchedulePage : Page
ListenToBroadcastBox.IsChecked = _mixer.ListenToBroadcast;
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
_loading = false;
- ShowMicrophone(); // it stays on while the user visits other pages
+ ShowMicrophone();
ShowLive();
FillStartTimes();
if (_controller.Plan.Count > 0)
UnlimitedBox.IsChecked = _controller.IsUnlimited;
- // The library can change on other pages.
RequestSong.ItemsSource = _controller.LibrarySongs()
.OrderBy(s => s.Artist).ThenBy(s => s.Title)
.Select(s => new SongOption(s.Id, $"{(string.IsNullOrWhiteSpace(s.Artist) ? s.Title : $"{s.Artist} - {s.Title}")} ({s.Duration:m\\:ss})"))
@@ -90,7 +88,7 @@ public partial class SchedulePage : Page
_progressTimer.Stop();
}
- // The next 12 full hours; rebuilt when the list opens, so it never offers a past hour.
+ // Rebuilt on dropdown open: never offers a past hour.
private void FillStartTimes()
{
var selected = (StartBox.SelectedItem as StartOption)?.Time;
@@ -128,10 +126,6 @@ public partial class SchedulePage : Page
});
}
- ///
- /// Runs a controller call that can take a moment (planning, waiting for the audio thread to stop)
- /// off the UI thread, so the window stays responsive. Returns false after showing the error.
- ///
private async Task RunAsync(string errorTitle, Action work)
{
_working = true;
@@ -171,7 +165,6 @@ public partial class SchedulePage : Page
private void OnMoveDown(object sender, RoutedEventArgs e) => MoveSelected(1);
- // The selection follows the item, so it can be moved several steps in a row.
private void MoveSelected(int offset) => ChangeSelected(row =>
{
_controller.Move(row.Index, offset);
@@ -185,7 +178,6 @@ public partial class SchedulePage : Page
_mixer.MusicForOthers = (float)MusicForOthersSlider.Value;
_mixer.MicrophoneForOthers = (float)MicrophoneForOthersSlider.Value;
_mixer.ListenToBroadcast = ListenToBroadcastBox.IsChecked == true;
- // While the monitor copies the broadcast, its own music level has no effect.
MusicForMeSlider.IsEnabled = !_mixer.ListenToBroadcast;
}
@@ -195,7 +187,6 @@ public partial class SchedulePage : Page
MicButton.IsEnabled = false;
try
{
- // Opening the devices can take a moment, so it runs off the UI thread.
await Task.Run(() =>
{
if (turnOn) _microphone.TurnOn();
@@ -214,7 +205,6 @@ public partial class SchedulePage : Page
private void ShowMicrophone()
{
var on = _microphone.IsOn;
- // The label names the action; the red button shows that the microphone is live.
MicButton.Content = on ? "Mikro aus" : "Mikro ein";
MicButton.Icon = new SymbolIcon(on ? SymbolRegular.MicOff24 : SymbolRegular.Mic24);
MicButton.Appearance = on ? ControlAppearance.Danger : ControlAppearance.Secondary;
@@ -232,7 +222,6 @@ public partial class SchedulePage : Page
}
else
{
- // Opening the devices and the connection can take a moment, so it runs off the UI thread.
await Task.Run(() => _live.StartAsync());
Message.IsOpen = false;
}
@@ -245,7 +234,7 @@ public partial class SchedulePage : Page
ShowLive();
}
- // Comes from a background thread; the stream may have ended.
+ // Background thread.
private void OnLiveProblem(object? sender, string message) => Dispatcher.BeginInvoke(() =>
{
ShowMessage(InfoBarSeverity.Warning, "laut.fm", message);
@@ -255,7 +244,7 @@ public partial class SchedulePage : Page
private void ShowLive()
{
var live = _live.IsLive;
- // Stays visible while live, so a stream can be stopped after laut.fm was switched off.
+ // Visible while live: stoppable after laut.fm was switched off.
LiveButton.Visibility = _live.IsEnabled || live ? Visibility.Visible : Visibility.Collapsed;
LiveButton.Content = live ? "Live beenden" : "Live";
LiveButton.Appearance = live ? ControlAppearance.Danger : ControlAppearance.Secondary;
@@ -308,7 +297,6 @@ public partial class SchedulePage : Page
private async void OnPlayToggle(object sender, RoutedEventArgs e)
{
var stop = _controller.IsPlaying;
- // The button and the card switch at once; stopping waits for the audio thread in the background.
_expectPlaying = !stop;
if (stop)
NowKind.Visibility = Visibility.Collapsed;
@@ -321,7 +309,7 @@ public partial class SchedulePage : Page
if (!_loading) _controller.Volume = (float)e.NewValue;
}
- // Engine events arrive on a pool thread. BeginInvoke, not Invoke: Stop waits for that thread.
+ // BeginInvoke, not Invoke: engine Stop waits for this pool thread -> deadlock.
private void OnItemStarted(object? sender, int index) => Dispatcher.BeginInvoke(ShowCurrent);
private void OnItemFailed(object? sender, string message) =>
@@ -333,7 +321,6 @@ public partial class SchedulePage : Page
ShowCurrent();
});
- // Syncs the rows with the controller; the selection is the user's swap target and is kept.
private void ShowCurrent()
{
var item = _controller.CurrentItem;
@@ -341,7 +328,7 @@ public partial class SchedulePage : Page
var plan = _controller.Plan;
var selected = Timeline.SelectedIndex;
- // Rows are records: only the ones whose content changed are replaced.
+ // Replace changed rows only: keeps selection (swap target).
for (var i = 0; i < plan.Count; i++)
{
var updated = new TimelineRow(i, plan[i], i == current);
@@ -352,12 +339,10 @@ public partial class SchedulePage : Page
}
while (_rows.Count > plan.Count)
_rows.RemoveAt(_rows.Count - 1);
- var rows = _rows;
GridColumns.Fit(Timeline);
- Timeline.SelectedIndex = selected < rows.Count ? selected : -1;
- // Follow the broadcast when it moves on; otherwise keep the user's row in view.
- if (current != _scrolledTo && current >= 0 && current < rows.Count)
- Timeline.ScrollIntoView(rows[current]);
+ Timeline.SelectedIndex = selected < _rows.Count ? selected : -1;
+ if (current != _scrolledTo && current >= 0 && current < _rows.Count)
+ Timeline.ScrollIntoView(_rows[current]);
else if (Timeline.SelectedItem is { } row)
Timeline.ScrollIntoView(row);
_scrolledTo = current;
@@ -376,7 +361,6 @@ public partial class SchedulePage : Page
var playing = _expectPlaying ?? _controller.IsPlaying;
PlayButton.IsEnabled = !_working && (playing || _controller.Plan.Count > 0);
CreateButton.IsEnabled = StartNowButton.IsEnabled = !_working;
- // Called every timer tick, so the label and icon change only with the state.
if (playing != _shownPlaying)
{
_shownPlaying = playing;
@@ -386,7 +370,6 @@ public partial class SchedulePage : Page
var row = Timeline.SelectedItem as TimelineRow;
- // Only items that are not on air or over can be moved or removed; the one on air can still be edited.
var count = _controller.Plan.Count;
var current = _controller.CurrentIndex;
bool Editable(int i) => !_working && i >= 0 && i < count && (!playing || i > current);
@@ -406,7 +389,6 @@ public partial class SchedulePage : Page
_ => null,
};
SwapHint.Text = blocker ?? $"Ersetzt das Element um {row!.Item.Start:HH:mm:ss}.";
- // The hint only matters once a song is chosen.
var requested = RequestSong.SelectedItem is not null;
SwapHint.Visibility = requested ? Visibility.Visible : Visibility.Collapsed;
SwapButton.IsEnabled = !_working && requested && blocker is null;
@@ -417,7 +399,7 @@ public partial class SchedulePage : Page
if (_expectPlaying == false || _controller.CurrentItem is not { } item)
{
NowProgress.Value = 0;
- // Checked here, not in ShowCurrent: the engine starts waiting a moment after Start.
+ // Here, not in ShowCurrent: engine starts waiting shortly after Start.
var waiting = _expectPlaying == false ? null : _controller.WaitingUntil;
NowTitle.Text = waiting is { } at ? $"Auf Sendung um {at:HH:mm:ss}" : "Nichts auf Sendung";
NowTime.Text = " ";
diff --git a/src/Radiosender/Views/Pages/SettingsPage.xaml.cs b/src/Radiosender/Views/Pages/SettingsPage.xaml.cs
index e15510f..0690f2f 100644
--- a/src/Radiosender/Views/Pages/SettingsPage.xaml.cs
+++ b/src/Radiosender/Views/Pages/SettingsPage.xaml.cs
@@ -1,12 +1,12 @@
using System.IO;
using System.Windows;
using System.Windows.Controls;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Settings;
using Wpf.Ui.Controls;
namespace Radiosender.Views.Pages;
-/// Edits . Nothing changes until Save.
public partial class SettingsPage : Page
{
private readonly SettingsStore _store;
@@ -17,16 +17,14 @@ public partial class SettingsPage : Page
InitializeComponent();
}
- // Loaded fires on every navigation to the page, so unsaved edits from an earlier visit are dropped.
private void OnLoaded(object sender, RoutedEventArgs e) => Show(_store.Current);
- // First entry of each list: the choice that names no device.
+ // Index 0 of each list = no device name (null).
private const string DefaultDevice = "Windows-Standardgerät";
private const string NoDevice = "Kein eigenes Gerät";
private void Show(AppSettings settings)
{
- // Read again on every visit, so a headset plugged in meanwhile shows up.
var devices = ProgramOutput.DeviceNames().ToList();
BroadcastDeviceBox.ItemsSource = devices.Prepend(DefaultDevice).ToList();
MonitorDeviceBox.ItemsSource = devices.Prepend(NoDevice).ToList();
@@ -52,11 +50,10 @@ public partial class SettingsPage : Page
OnLautFmChanged(this, new RoutedEventArgs());
}
- // The access fields only matter while laut.fm is on.
private void OnLautFmChanged(object sender, RoutedEventArgs e) =>
LautFmFields.Visibility = LautFmSwitch.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
- // An emptied number box counts as its default.
+ // Empty number box -> default.
private static AppSettings Defaults { get; } = new();
private AppSettings Read() => new()
diff --git a/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs b/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs
index 69100f5..7e01f12 100644
--- a/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs
+++ b/src/Radiosender/Views/ScheduleItemEditWindow.xaml.cs
@@ -5,10 +5,6 @@ using Wpf.Ui.Controls;
namespace Radiosender.Views;
-///
-/// Dialog for the title of a news, ad or moderator item and, for news and moderator items, its length.
-/// Only collects input; the caller changes the schedule.
-///
public partial class ScheduleItemEditWindow : FluentWindow
{
private static readonly string[] DurationFormats = [@"m\:ss", @"mm\:ss"];
@@ -20,7 +16,6 @@ public partial class ScheduleItemEditWindow : FluentWindow
TitleBox.Text = item.Title;
DurationBox.Text = item.Duration.ToString(@"m\:ss");
Duration = item.Duration;
- // Ads keep their length.
DurationLabel.IsEnabled = DurationBox.IsEnabled = item.Kind is ScheduleItemKind.News or ScheduleItemKind.Moderator;
}
diff --git a/src/Radiosender/Views/SongEditWindow.xaml.cs b/src/Radiosender/Views/SongEditWindow.xaml.cs
index c2d9c52..158becc 100644
--- a/src/Radiosender/Views/SongEditWindow.xaml.cs
+++ b/src/Radiosender/Views/SongEditWindow.xaml.cs
@@ -4,7 +4,6 @@ using Wpf.Ui.Controls;
namespace Radiosender.Views;
-/// Dialog for the editable song metadata. Only collects input; saving is done by the caller.
public partial class SongEditWindow : FluentWindow
{
public SongEditWindow(Song song)
diff --git a/tests/Radiosender.Tests/AppSettingsTests.cs b/tests/Radiosender.Tests/AppSettingsTests.cs
index b393ae9..11754c5 100644
--- a/tests/Radiosender.Tests/AppSettingsTests.cs
+++ b/tests/Radiosender.Tests/AppSettingsTests.cs
@@ -1,4 +1,4 @@
-using Radiosender.Services;
+using Radiosender.Services.Settings;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/AudioDeviceFactAttribute.cs b/tests/Radiosender.Tests/AudioDeviceFactAttribute.cs
new file mode 100644
index 0000000..2af8129
--- /dev/null
+++ b/tests/Radiosender.Tests/AudioDeviceFactAttribute.cs
@@ -0,0 +1,12 @@
+using NAudio.Wave;
+
+namespace Radiosender.Tests;
+
+/// Skips the test on machines without an audio output device (for example CI agents).
+public sealed class AudioDeviceFactAttribute : FactAttribute
+{
+ public AudioDeviceFactAttribute()
+ {
+ if (WaveOut.DeviceCount == 0) Skip = "No audio output device available.";
+ }
+}
diff --git a/tests/Radiosender.Tests/LautFmTests.cs b/tests/Radiosender.Tests/LautFmTests.cs
index 2165b32..da63cdb 100644
--- a/tests/Radiosender.Tests/LautFmTests.cs
+++ b/tests/Radiosender.Tests/LautFmTests.cs
@@ -5,7 +5,11 @@ using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using Radiosender.Controllers;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Library;
+using Radiosender.Services.Providers;
+using Radiosender.Services.Settings;
+using Radiosender.Services.Streaming;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/LibraryControllerTests.cs b/tests/Radiosender.Tests/LibraryControllerTests.cs
index 9420585..5aa646c 100644
--- a/tests/Radiosender.Tests/LibraryControllerTests.cs
+++ b/tests/Radiosender.Tests/LibraryControllerTests.cs
@@ -1,7 +1,7 @@
using Microsoft.Data.Sqlite;
using Radiosender.Controllers;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Library;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/MusicPlayerTests.cs b/tests/Radiosender.Tests/MusicPlayerTests.cs
index 8a846fb..46086c8 100644
--- a/tests/Radiosender.Tests/MusicPlayerTests.cs
+++ b/tests/Radiosender.Tests/MusicPlayerTests.cs
@@ -1,18 +1,9 @@
using System.IO;
using NAudio.Wave;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
namespace Radiosender.Tests;
-/// Skips the test on machines without an audio output device (for example CI agents).
-public sealed class AudioDeviceFactAttribute : FactAttribute
-{
- public AudioDeviceFactAttribute()
- {
- if (WaveOut.DeviceCount == 0) Skip = "No audio output device available.";
- }
-}
-
public sealed class MusicPlayerTests : IDisposable
{
private readonly string _directory = Path.Combine(Path.GetTempPath(), "radiosender-tests", Guid.NewGuid().ToString("N"));
@@ -50,25 +41,6 @@ public sealed class MusicPlayerTests : IDisposable
Assert.Throws(() => ProgramOutput.ToProgramFormat(new NAudio.Wave.SampleProviders.SignalGenerator(44100, 6)));
}
- [AudioDeviceFact]
- public void PauseAndResume_KeepThePosition()
- {
- var player = MusicPlayer.Instance;
- player.Play(CreateWav(TimeSpan.FromSeconds(3)));
- Thread.Sleep(400);
-
- player.Pause();
- Assert.False(player.IsPlaying);
- var paused = player.Position;
- Thread.Sleep(300);
- Assert.Equal(paused, player.Position);
-
- player.Resume();
- Assert.True(player.IsPlaying);
- Thread.Sleep(400);
- Assert.True(player.Position > paused);
- }
-
[AudioDeviceFact]
public void Play_TwoTracksInARow_RaisesTrackFinishedOnlyForTheSecond()
{
@@ -162,29 +134,24 @@ public sealed class MusicPlayerTests : IDisposable
}
[AudioDeviceFact]
- public void Play_ShortWav_RaisesTrackFinishedAndPositionChanged()
+ public void Play_ShortWav_RaisesTrackFinished()
{
var player = MusicPlayer.Instance;
using var finished = new ManualResetEventSlim();
- var positionChanged = false;
EventHandler finishedHandler = (_, _) => finished.Set();
- EventHandler positionHandler = (_, _) => positionChanged = true;
player.TrackFinished += finishedHandler;
- player.PositionChanged += positionHandler;
try
{
player.Play(CreateWav(TimeSpan.FromSeconds(0.6)));
Assert.InRange(player.Duration.TotalSeconds, 0.59, 0.61);
Assert.True(finished.Wait(TimeSpan.FromSeconds(5)), "TrackFinished was not raised.");
- Assert.True(positionChanged);
Assert.False(player.IsPlaying);
Assert.Equal(TimeSpan.Zero, player.Duration);
}
finally
{
player.TrackFinished -= finishedHandler;
- player.PositionChanged -= positionHandler;
}
}
}
diff --git a/tests/Radiosender.Tests/MusicProviderTests.cs b/tests/Radiosender.Tests/MusicProviderTests.cs
index 95f99db..432f8ee 100644
--- a/tests/Radiosender.Tests/MusicProviderTests.cs
+++ b/tests/Radiosender.Tests/MusicProviderTests.cs
@@ -1,6 +1,6 @@
using System.Net;
using System.Text;
-using Radiosender.Services;
+using Radiosender.Services.Providers;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/OpenverseTests.cs b/tests/Radiosender.Tests/OpenverseTests.cs
index b7cf854..3c0e5a2 100644
--- a/tests/Radiosender.Tests/OpenverseTests.cs
+++ b/tests/Radiosender.Tests/OpenverseTests.cs
@@ -3,7 +3,8 @@ using System.Text;
using Microsoft.Data.Sqlite;
using Radiosender.Controllers;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Library;
+using Radiosender.Services.Providers;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/PlaybackEngineTests.cs b/tests/Radiosender.Tests/PlaybackEngineTests.cs
index eb5c2b1..8a01f1a 100644
--- a/tests/Radiosender.Tests/PlaybackEngineTests.cs
+++ b/tests/Radiosender.Tests/PlaybackEngineTests.cs
@@ -1,6 +1,7 @@
using System.Collections.Concurrent;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Scheduling;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/ProgramMixerTests.cs b/tests/Radiosender.Tests/ProgramMixerTests.cs
index 25b665b..a60b88e 100644
--- a/tests/Radiosender.Tests/ProgramMixerTests.cs
+++ b/tests/Radiosender.Tests/ProgramMixerTests.cs
@@ -1,5 +1,5 @@
using NAudio.Wave;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/ScheduleControllerTests.cs b/tests/Radiosender.Tests/ScheduleControllerTests.cs
index 8359bc3..b48956b 100644
--- a/tests/Radiosender.Tests/ScheduleControllerTests.cs
+++ b/tests/Radiosender.Tests/ScheduleControllerTests.cs
@@ -1,7 +1,9 @@
using Microsoft.Data.Sqlite;
using Radiosender.Controllers;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Audio;
+using Radiosender.Services.Library;
+using Radiosender.Services.Scheduling;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/ScheduleGeneratorTests.cs b/tests/Radiosender.Tests/ScheduleGeneratorTests.cs
index 550146a..0ffe45c 100644
--- a/tests/Radiosender.Tests/ScheduleGeneratorTests.cs
+++ b/tests/Radiosender.Tests/ScheduleGeneratorTests.cs
@@ -1,5 +1,5 @@
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Scheduling;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/SongImportServiceTests.cs b/tests/Radiosender.Tests/SongImportServiceTests.cs
index 2c1c240..468e9a9 100644
--- a/tests/Radiosender.Tests/SongImportServiceTests.cs
+++ b/tests/Radiosender.Tests/SongImportServiceTests.cs
@@ -1,7 +1,7 @@
using Microsoft.Data.Sqlite;
using NAudio.Wave;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Library;
namespace Radiosender.Tests;
diff --git a/tests/Radiosender.Tests/SongRepositoryTests.cs b/tests/Radiosender.Tests/SongRepositoryTests.cs
index 5960a84..5caa8f3 100644
--- a/tests/Radiosender.Tests/SongRepositoryTests.cs
+++ b/tests/Radiosender.Tests/SongRepositoryTests.cs
@@ -1,7 +1,7 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Radiosender.Models;
-using Radiosender.Services;
+using Radiosender.Services.Library;
namespace Radiosender.Tests;