diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md
new file mode 100644
index 00000000..d7a638a7
--- /dev/null
+++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md
@@ -0,0 +1,84 @@
+# Architecture Decision Record (ADR): 0016 - Playback Delivery Decision and Player Capability Negotiation
+
+## Status
+
+**Accepted** (2026-10-14)
+
+## Context
+
+Lumina's music player is implemented from scratch, on WebCodecs for decoding and the Web Audio API for output, with no `HTMLMediaElement` and no Media Source Extensions. That player can only demux a curated set of containers and decode a curated set of codecs, so the server has to tell it, before it fetches any audio, whether a track can be played as stored or whether the server has to change the container or the codec first.
+
+The server already has each track's stored probe result (the container and the codec, plus the sample rate, the channels, the bit depth, the duration and the ReplayGain values) and a stream endpoint with HTTP range support that serves the original file. What is missing is the decision itself and a way for the player to state what it can play.
+
+## Decision
+
+Introduce a playback format service (`IPlaybackFormatService`, `PlaybackFormatService`) that, given the container and the codec of a track as read from its stored probe result and the capabilities a player advertises, decides one of three delivery modes: direct play, remux, or transcode. It stays in the Application layer (interface) and the Infrastructure layer (implementation), as a service: the byte and codec pipeline is not part of the playback domain aggregate.
+
+### Delivery modes
+
+| Mode | Condition | Delivery format | Delivery shape |
+|---|---|---|---|
+| Direct play | The player can demux the stored container and decode the stored codec | The stored container and codec, unchanged | Byte range seekable |
+| Remux | The player can decode the stored codec but has no demuxer for the stored container | The stored codec, repackaged into a server container the player can demux | Time addressed segments |
+| Transcode | The player cannot decode the stored codec | The most preferred codec the server can produce that the player advertises | Time addressed segments |
+
+- The stored codec is the free form description reported by the probe (for example `MPEG-1 Layer 3`), so it is canonicalized to the codec name players advertise (for example `MP3`) before it is compared. The MPEG layer is matched by its layer number only (`LAYER 3`/`LAYER III`), so `MPEG-1 Layer 1` and `MPEG-1 Layer 2` are not mistaken for `MP3`, and a description that names no recognizable codec is left as it is, which keeps it from matching any advertised codec and forces a transcode. Containers are canonicalized by casing.
+- The container a normalized delivery is produced in is always chosen from the containers the server can produce for the codec, never from the container the player names: the player only selects among the server's known containers, so a container supplied by a client never reaches the transcoder or a cache name. The containers the server produces each codec in are, in order of preference: `PCM` in `WAV`, `MP3` in `MP3`, `FLAC` in `FLAC`, `Opus` and `Vorbis` in `OGG`, `AAC` in `MP4` then `AAC`.
+- The server can produce, in order of preference, `AAC`, `OPUS`, `MP3`, `VORBIS`, `FLAC` and `PCM` (the efficient lossy codecs before the lossless ones, and uncompressed last), so a transcode re-encodes to the first of these the player advertises in one of its containers. When the player advertises no producible codec, the decision fails with `NoSupportedPlaybackFormat`, which is a forbidden outcome (HTTP 403) rather than a malformed request, and no delivery is attempted.
+
+### Capability input convention
+
+The capabilities a player can demux and decode directly are carried on the playback manifest request as a query parameter named `capabilities`, whose value is a comma separated list of `container/codec` pairs:
+
+```
+GET /api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest?capabilities=mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac
+```
+
+- The container and the codec of a pair are matched case insensitively, and surrounding whitespace is ignored.
+- A pair must name both a container and a codec, with neither empty (for example `flac`, `a/b/c` and `a//b` are ignored).
+- At most 32 pairs are read from one request, so the parsing work stays bounded regardless of the input length.
+- When the parameter is absent, empty, or lists no valid pair, the server applies the default capabilities of the bundled player, so a request that advertises nothing still gets a playable decision:
+ `mp3/mp3`, `flac/flac`, `ogg/opus`, `ogg/vorbis`, `wav/pcm`, `aac/aac`. The default set is the bundled player's demuxer set (MP3, AAC/ADTS, FLAC, OGG and WAV, from work order 14), so it deliberately contains no `mp4/aac` pair: a track stored in MP4 is remuxed to raw AAC for a request that advertises nothing, rather than being marked direct play for a container the bundled player cannot demux.
+- The convention is a query parameter rather than a request header, so that it is part of the request's own contract, is trivially testable, and is forwarded by the web app's manifest proxy without depending on header forwarding.
+
+### Delivery shape
+
+The `TimeAddressedSegments` delivery shape is a sequence of fixed duration segments addressed and seeked by time, so that finding a time never requires mapping a byte range to it. The segment duration is 6 seconds, and it is carried in the delivery decision so that the producer of the segments and the player agree on it. Direct play is `ByteRangeSeekable`, because the original file is served by the existing range-capable stream endpoint.
+
+## Consequences
+
+### Positive Outcomes
+
+| Aspect | Benefit |
+|---|---|
+| Decoupling | The player states what it can play and never has to know the server's codecs; the server states the delivery and never has to know the player's implementation |
+| Efficiency | A container a player cannot demux but a codec it can decode is repackaged instead of re-encoded, and only a genuinely unsupported codec is re-encoded |
+| Determinism | The containers the server produces each codec in and the transcode preference order are fixed, so the same input always yields the same delivery |
+| Seekability | Time addressed segments make a normalized delivery seekable without a byte to time index |
+| Testability | The decision is a pure function of the stored container and codec and the advertised capabilities |
+
+### Risks and Mitigations
+
+| Risk | Mitigation Strategy |
+|---|---|
+| The probe reports a codec as a free form description that does not name the codec the player advertises | The stored description is canonicalized to the advertised codec names before comparison, and the MPEG layer is matched by its layer number, so a description that names no decodable codec is left unmatched and forces a transcode |
+| A player advertises a container the server cannot produce | The delivered container is always chosen from the containers the server produces the codec in, never from the container the player names, so a client supplied container never reaches the transcoder or a cache name; a codec the player cannot be served in any server container is not used |
+| The segment duration drifts between the server and the player | It is part of the delivery decision carried by the manifest, not a constant duplicated on both sides |
+
+## Alternatives Considered
+
+### 1. Decide the delivery from the container only
+
+**Rejected**: a container can carry several codecs (for example `OGG` carries both Vorbis and Opus), so the container alone cannot tell whether the player can decode the audio, and the difference between a remux and a transcode would be lost.
+
+### 2. Let the player decide, by sending its full codec support to the server and reading the probe result itself
+
+**Rejected**: it leaks the server's storage and probe details to the client and duplicates the decision on both sides. The server owns the probe result and the producible formats.
+
+### 3. Carry the capabilities in a request header
+
+**Rejected**: a header has to be explicitly forwarded by the web app's manifest proxy and is harder to exercise from a browser or a request file than a query parameter, with no benefit that a query parameter does not already provide.
+
+### 4. Deliver a remuxed track as a single byte range seekable file instead of segments
+
+**Rejected**: it makes remuxed and transcoded tracks two different delivery shapes for the player to consume, and it reintroduces the byte to time mapping the time addressed shape exists to avoid. Both normalized deliveries use the same shape.
diff --git a/docs/technical/domain/UbiquitousLanguage.md b/docs/technical/domain/UbiquitousLanguage.md
index 9bae25bd..ee4eefe1 100644
--- a/docs/technical/domain/UbiquitousLanguage.md
+++ b/docs/technical/domain/UbiquitousLanguage.md
@@ -11,6 +11,11 @@
- _**Stream**_: A media item accessed via streaming rather than local storage
- _**Language Track**_: An audio or text track in a specific language
- _**Media Contributor**_: A person, group, or organization that contributed to a media item, together with the role they played
+- _**Direct Play**_: Delivery of a track's audio as stored, because the player can demux its container and decode its codec
+- _**Remux**_: Delivery of a track's audio with its codec repackaged into a container the player can demux, without re-encoding it
+- _**Transcode**_: Delivery of a track's audio re-encoded into a codec the player can decode
+- _**Playback Capabilities**_: The container and codec combinations a player advertises it can demux and decode directly
+- _**Delivery Shape**_: The way delivered audio is addressed and seeked, by byte range or as fixed duration, time addressed segments
## Video Content
- _**TV Show**_: A series of episodes typically organized into seasons
diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs
new file mode 100644
index 00000000..49bffeb5
--- /dev/null
+++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDto.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Data transfer object for a single container and codec combination that a player advertises it can demux and decode directly.
+///
+/// The container the player can demux, for example MP3, FLAC, OGG, WAV or MP4.
+/// The codec the player can decode, for example MP3, FLAC, Opus, Vorbis, PCM or AAC.
+[DebuggerDisplay("Container: {Container} Codec: {Codec}")]
+public sealed record PlaybackCapabilityDto(
+ string Container,
+ string Codec
+);
diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs
new file mode 100644
index 00000000..72fb25db
--- /dev/null
+++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryDecisionDto.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Data transfer object for the decision of how the audio of a track is delivered to a player: as the original file, as the same codec repackaged, or re-encoded.
+///
+/// The way the audio is delivered.
+/// The container of the delivered audio, which is the stored container of the track for a direct play.
+/// The codec of the delivered audio, which is the stored codec of the track for a direct play.
+/// The shape the delivered audio is addressed and seeked by.
+/// The duration of each segment of the delivered audio, in seconds, or zero when the shape is not time addressed.
+[DebuggerDisplay("Mode: {Mode} Container: {Container} Codec: {Codec} Shape: {Shape}")]
+public sealed record PlaybackDeliveryDecisionDto(
+ PlaybackDeliveryMode Mode,
+ string Container,
+ string Codec,
+ PlaybackDeliveryShape Shape,
+ int SegmentDurationSeconds
+);
diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs
new file mode 100644
index 00000000..2c3810ec
--- /dev/null
+++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDto.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Data transfer object for the stored format of a track's audio, that a playback delivery decision is made on.
+///
+/// The container of the audio file of the track, for example MP3, FLAC, OGG, MP4 or WAV.
+/// The codec of the audio of the track, as reported by the probe, for example AAC, FLAC, Opus or PCM.
+[DebuggerDisplay("Container: {Container} Codec: {Codec}")]
+public sealed record PlaybackSourceFormatDto(
+ string? Container,
+ string? Codec
+);
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs
new file mode 100644
index 00000000..6f83888b
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackFormatService.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Domain.Common.Primitives;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Interface for the service that decides whether the audio of a track can be played as stored by a player, or has to be
+/// repackaged into another container or re-encoded into another codec before the player can play it.
+///
+public interface IPlaybackFormatService
+{
+ ///
+ /// Decides how the audio of a track, described by , is delivered to a player that advertises .
+ ///
+ /// The container and codec of the audio of the track, read from its stored probe result.
+ /// The container and codec combinations the player advertises it can demux and decode directly.
+ ///
+ /// An containing either the delivery decision, or an error when the server cannot produce any
+ /// format the player advertises it supports.
+ ///
+ Result DecideDelivery(PlaybackSourceFormatDto sourceFormat, IReadOnlyList capabilities);
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs
new file mode 100644
index 00000000..1eab4384
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParser.cs
@@ -0,0 +1,76 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Parses the capabilities input of a playback manifest request into the container and codec combinations a player advertises it
+/// can demux and decode directly.
+///
+///
+/// The input is a comma separated list of container/codec pairs, for example
+/// mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac. The container and the codec of a pair are matched case
+/// insensitively, and a pair that does not name both, with a non-empty container and codec, is ignored. The number of pairs is
+/// capped, so a request cannot force an unbounded amount of parsing work. When the input is absent or lists no valid pair, the
+/// capabilities of the bundled player apply.
+///
+public static class PlaybackCapabilitiesParser
+{
+ ///
+ /// The maximum number of capability pairs that are read from a single request, so that the parsing work stays bounded.
+ ///
+ public const int MAX_CAPABILITY_COUNT = 32;
+
+ ///
+ /// The character that separates the container from the codec of a single capability pair.
+ ///
+ public const char CONTAINER_CODEC_SEPARATOR = '/';
+
+ ///
+ /// The character that separates the capability pairs of a capability set.
+ ///
+ public const char CAPABILITY_SEPARATOR = ',';
+
+ ///
+ /// Gets the capability set the bundled player advertises, used when a request does not advertise any capability.
+ ///
+ public static IReadOnlyList Default { get; } =
+ [
+ new PlaybackCapabilityDto("MP3", "MP3"),
+ new PlaybackCapabilityDto("FLAC", "FLAC"),
+ new PlaybackCapabilityDto("OGG", "OPUS"),
+ new PlaybackCapabilityDto("OGG", "VORBIS"),
+ new PlaybackCapabilityDto("WAV", "PCM"),
+ new PlaybackCapabilityDto("AAC", "AAC")
+ ];
+
+ ///
+ /// Parses the capabilities input of a playback manifest request into a capability set.
+ ///
+ /// The value of the capabilities input, a comma separated list of container/codec pairs.
+ /// The parsed capabilities, or when the input is absent, empty or lists no valid pair.
+ public static IReadOnlyList Parse(string? capabilitiesInput)
+ {
+ if (string.IsNullOrWhiteSpace(capabilitiesInput))
+ return Default;
+
+ List capabilities = [];
+ foreach (string entry in capabilitiesInput.Split(CAPABILITY_SEPARATOR, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ // The number of pairs is capped, so a single request cannot force an unbounded amount of parsing work.
+ if (capabilities.Count >= MAX_CAPABILITY_COUNT)
+ break;
+
+ // Both parts must be named: a container or a codec that is empty (for example "a//b" or "/wav") does not name a pair.
+ string[] parts = entry.Split(CONTAINER_CODEC_SEPARATOR, StringSplitOptions.TrimEntries);
+ if (parts.Length != 2 || parts[0].Length == 0 || parts[1].Length == 0)
+ continue;
+ capabilities.Add(new PlaybackCapabilityDto(parts[0], parts[1]));
+ }
+
+ return capabilities.Count == 0 ? Default : capabilities;
+ }
+}
diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs
new file mode 100644
index 00000000..134e976e
--- /dev/null
+++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryMode.cs
@@ -0,0 +1,22 @@
+namespace Lumina.Domain.SharedKernel.Common.Enums.Playback;
+
+///
+/// Enumeration for the ways in which a track's audio is delivered to a player.
+///
+public enum PlaybackDeliveryMode
+{
+ ///
+ /// The original audio file is delivered unchanged, because the player can demux its container and decode its codec as stored.
+ ///
+ DirectPlay,
+
+ ///
+ /// The audio is repackaged into a container the player can demux, without re-encoding its codec.
+ ///
+ Remux,
+
+ ///
+ /// The audio is re-encoded into a codec the player can decode, because the stored codec is not one the player supports.
+ ///
+ Transcode,
+}
diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs
new file mode 100644
index 00000000..dfbad916
--- /dev/null
+++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackDeliveryShape.cs
@@ -0,0 +1,18 @@
+namespace Lumina.Domain.SharedKernel.Common.Enums.Playback;
+
+///
+/// Enumeration for the shapes in which delivered audio is addressed and seeked.
+///
+public enum PlaybackDeliveryShape
+{
+ ///
+ /// The delivered media is the original file itself, addressed and seeked by byte range.
+ ///
+ ByteRangeSeekable,
+
+ ///
+ /// The delivered media is a sequence of fixed duration segments, addressed and seeked by time, so that finding a time never
+ /// requires mapping a byte range to it.
+ ///
+ TimeAddressedSegments,
+}
diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs
new file mode 100644
index 00000000..8e4662fc
--- /dev/null
+++ b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.Common.Primitives;
+#endregion
+
+namespace Lumina.Domain.Common.Errors;
+
+///
+/// Domain playback related error types.
+///
+public static partial class Errors
+{
+ public static class Playback
+ {
+ public static Error NoSupportedPlaybackFormat => Error.Forbidden(description: nameof(NoSupportedPlaybackFormat));
+ }
+}
diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
index 10e7c307..4154b4a9 100644
--- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
+++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
@@ -13,6 +13,7 @@ using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
@@ -38,6 +39,7 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenCo
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
+using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Infrastructure.Core.Plugins;
@@ -146,6 +148,10 @@ public static class InfrastructureLayerServices
// Music artwork: stores the artwork of the albums into the internal media directory.
services.AddScoped();
+ // Music playback: decides, for a track and the capabilities a player advertises, whether the track is played as stored,
+ // repackaged into another container, or re-encoded into another codec.
+ services.AddSingleton();
+
// Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents.
// The enablement cache lets the reading service skip the per-request database read of the reader configurations.
services.AddSingleton();
diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs
new file mode 100644
index 00000000..3afe9bf2
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs
@@ -0,0 +1,182 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using System;
+using System.Collections.Frozen;
+using System.Collections.Generic;
+using System.Linq;
+#endregion
+
+namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Service that decides whether the audio of a track can be played as stored by a player, or has to be repackaged into another container (remuxed) or re-encoded into another codec (transcoded).
+///
+///
+/// The decision uses the container and the codec of the stored probe result together with the container and codec pairs the player advertises it can demux and decode directly:
+/// a pair the player advertises as stored is a direct play, a codec the player decodes but a container it cannot demux is a remux into a container it can demux, and a codec the player cannot decode
+/// is a transcode to the most preferred codec the server can produce and the player advertises. Everything that is not a direct play is delivered as fixed duration, time addressed segments, so that seeking never requires mapping a byte range to a time.
+///
+internal sealed class PlaybackFormatService : IPlaybackFormatService
+{
+ // The duration of each segment of a normalized (remuxed or transcoded) delivery, in seconds: short enough to seek quickly, long enough to keep the request overhead low.
+ private const int SEGMENT_DURATION_SECONDS = 6;
+
+ // The order in which the codecs the server can produce are tried when a transcode is needed, most preferred first: the
+ // efficient lossy codecs come before the lossless ones, so a transcode stays small unless the player only supports lossless.
+ private static readonly IReadOnlyList s_transcodeCodecPreference = ["AAC", "OPUS", "MP3", "VORBIS", "FLAC", "PCM"];
+
+ // The containers the server can produce each codec in, in order of preference. The delivered container is always chosen from
+ // this list, so a container the player named is only ever matched against it and never becomes the delivered container itself.
+ private static readonly FrozenDictionary> s_producibleContainersByCodec = new Dictionary>(StringComparer.OrdinalIgnoreCase)
+ {
+ { "AAC", ["MP4", "AAC"] },
+ { "OPUS", ["OGG"] },
+ { "VORBIS", ["OGG"] },
+ { "MP3", ["MP3"] },
+ { "FLAC", ["FLAC"] },
+ { "PCM", ["WAV"] }
+ }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// Decides how the audio of a track, described by , is delivered to a player that advertises .
+ ///
+ /// The container and codec of the audio of the track, read from its stored probe result.
+ /// The container and codec combinations the player advertises it can demux and decode directly.
+ ///
+ /// An containing either the delivery decision, or an error when the server cannot produce any format the player advertises it supports.
+ ///
+ public Result DecideDelivery(PlaybackSourceFormatDto sourceFormat, IReadOnlyList capabilities)
+ {
+ string container = CanonicalizeContainer(sourceFormat.Container);
+ string codec = CanonicalizeCodec(sourceFormat.Codec);
+
+ // Direct play: the player can demux the stored container and decode the stored codec, so the file is delivered unchanged, and it is addressed and seeked by byte range.
+ // The delivered container and codec are the stored ones, not the player's.
+ if (IsFormatAdvertised(capabilities, container, codec))
+ return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.DirectPlay, container, codec, PlaybackDeliveryShape.ByteRangeSeekable, 0);
+
+ // Remux: the player can decode the stored codec but has no demuxer for the stored container, so the codec is repackaged
+ // into a container the server can produce and the player can demux, without re-encoding it; the normalized output is delivered as time addressed segments.
+ PlaybackCapabilityDto? remuxFormat = SelectFormatForCodec(capabilities, codec);
+ if (remuxFormat is not null)
+ return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.Remux, remuxFormat.Container, remuxFormat.Codec, PlaybackDeliveryShape.TimeAddressedSegments, SEGMENT_DURATION_SECONDS);
+
+ // Transcode: the player cannot decode the stored codec, so the audio is re-encoded into the most preferred codec the server can produce and the player advertises,
+ // and the normalized output is delivered as time addressed segments.
+ PlaybackCapabilityDto? transcodeFormat = SelectTranscodeFormat(capabilities);
+ if (transcodeFormat is null)
+ return Errors.Playback.NoSupportedPlaybackFormat;
+
+ return new PlaybackDeliveryDecisionDto(PlaybackDeliveryMode.Transcode, transcodeFormat.Container, transcodeFormat.Codec, PlaybackDeliveryShape.TimeAddressedSegments, SEGMENT_DURATION_SECONDS);
+ }
+
+ ///
+ /// Checks whether the player advertises the provided and as a combination it can demux and decode directly.
+ ///
+ /// The capabilities advertised by the player.
+ /// The canonical container that is looked for.
+ /// The canonical codec that is looked for.
+ /// when the player advertises the combination, otherwise .
+ private static bool IsFormatAdvertised(IReadOnlyList capabilities, string container, string codec)
+ {
+ if (container.Length == 0 || codec.Length == 0)
+ return false;
+
+ return capabilities.Any(capability =>
+ string.Equals(CanonicalizeContainer(capability.Container), container, StringComparison.OrdinalIgnoreCase)
+ && string.Equals(CanonicalizeCodec(capability.Codec), codec, StringComparison.OrdinalIgnoreCase));
+ }
+
+ ///
+ /// Selects the container the server produces the provided in, preferring the server's canonical one, among the containers the player advertises it can demux for that codec.
+ ///
+ /// The capabilities advertised by the player.
+ /// The canonical codec that is delivered.
+ ///
+ /// The container and codec the server delivers in, or when the server cannot produce the codec in any container the player advertises it can demux.
+ ///
+ private static PlaybackCapabilityDto? SelectFormatForCodec(IReadOnlyList capabilities, string codec)
+ {
+ if (codec.Length == 0 || !s_producibleContainersByCodec.TryGetValue(codec, out IReadOnlyList? producibleContainers))
+ return null;
+
+ IReadOnlyList advertisedContainers = [.. capabilities
+ .Where(capability => string.Equals(CanonicalizeCodec(capability.Codec), codec, StringComparison.OrdinalIgnoreCase))
+ .Select(capability => CanonicalizeContainer(capability.Container))];
+
+ // The delivered container is one of the server's own containers, chosen as the first one the player advertises: the player
+ // only selects among the containers the server knows, so a container the player names never reaches the transcoder itself.
+ foreach (string producibleContainer in producibleContainers)
+ if (advertisedContainers.Contains(producibleContainer, StringComparer.OrdinalIgnoreCase))
+ return new PlaybackCapabilityDto(producibleContainer, codec);
+
+ return null;
+ }
+
+ ///
+ /// Selects the most preferred codec the server can produce that the player advertises it can decode.
+ ///
+ /// The capabilities advertised by the player.
+ /// The preferred producible container and codec, or when the player supports no producible codec.
+ private static PlaybackCapabilityDto? SelectTranscodeFormat(IReadOnlyList capabilities)
+ {
+ foreach (string preferredCodec in s_transcodeCodecPreference)
+ {
+ PlaybackCapabilityDto? format = SelectFormatForCodec(capabilities, preferredCodec);
+ if (format is not null)
+ return format;
+ }
+
+ return null;
+ }
+
+ ///
+ /// Canonicalizes the container of an audio file, so that containers compare regardless of casing.
+ ///
+ /// The container to canonicalize.
+ /// The canonical container, or an empty string when there is none.
+ private static string CanonicalizeContainer(string? container)
+ {
+ return string.IsNullOrWhiteSpace(container) ? string.Empty : container.Trim().ToUpperInvariant();
+ }
+
+ ///
+ /// Canonicalizes the codec of an audio file, mapping the free form descriptions reported by the probe to the canonical codec
+ /// names the players advertise, and leaving a description it does not recognize as unplayable.
+ ///
+ /// The codec to canonicalize.
+ /// The canonical codec, or an empty string when there is none.
+ private static string CanonicalizeCodec(string? codec)
+ {
+ if (string.IsNullOrWhiteSpace(codec))
+ return string.Empty;
+
+ // The probe reports the codec as the description the tagging library parsed from the file, for example "MPEG-1 Layer 3" rather than "MP3",
+ // so the known descriptions are recognized by their distinctive token, most specific ones first. The MPEG layer is matched by its layer number only,
+ // so MPEG-1 Layer 1 and Layer 2 are not mistaken for MP3, and a description that names no recognizable codec is left as it is,
+ // which keeps it from matching any advertised codec and forces a transcode.
+ string normalized = codec.Trim().ToUpperInvariant();
+ if (normalized.Contains("VORBIS", StringComparison.Ordinal))
+ return "VORBIS";
+ if (normalized.Contains("OPUS", StringComparison.Ordinal))
+ return "OPUS";
+ if (normalized.Contains("FLAC", StringComparison.Ordinal))
+ return "FLAC";
+ if (normalized.Contains("ALAC", StringComparison.Ordinal) || normalized.Contains("APPLE LOSSLESS", StringComparison.Ordinal))
+ return "ALAC";
+ if (normalized.Contains("AAC", StringComparison.Ordinal))
+ return "AAC";
+ if (normalized.Contains("MP3", StringComparison.Ordinal) || normalized.Contains("LAYER 3", StringComparison.Ordinal) || normalized.Contains("LAYER III", StringComparison.Ordinal))
+ return "MP3";
+ if (normalized.Contains("PCM", StringComparison.Ordinal) || normalized.Contains("UNCOMPRESSED", StringComparison.Ordinal) || normalized.Contains("LINEAR", StringComparison.Ordinal))
+ return "PCM";
+ if (normalized.Contains("WINDOWS MEDIA", StringComparison.Ordinal) || normalized.Contains("WMA", StringComparison.Ordinal))
+ return "WMA";
+
+ return normalized;
+ }
+}
diff --git a/src/Lumina.sln b/src/Lumina.sln
index 9de2e1b3..2de7403b 100644
--- a/src/Lumina.sln
+++ b/src/Lumina.sln
@@ -176,6 +176,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-decision-log",
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0013.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0014.md
..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0015.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0015.md
+ ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0016.md = ..\docs\technical\architecture\architecture-knowledge-management\architecture-decision-log\architecture-decision-record-0016.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "domain", "domain", "{3EE8EFDF-4D55-4EA3-BEE2-74D00CB50570}"
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDtoFixture.cs
new file mode 100644
index 00000000..b147f02d
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilityDtoFixture.cs
@@ -0,0 +1,43 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackCapabilityDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The container the player can demux.
+ /// Optional. The codec the player can decode.
+ /// The created .
+ public PlaybackCapabilityDto Create(
+ string? container = null,
+ string? codec = null)
+ {
+ return new PlaybackCapabilityDto(
+ container ?? _faker.Random.AlphaNumeric(4).ToUpperInvariant(),
+ codec ?? _faker.Random.AlphaNumeric(4).ToUpperInvariant());
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDtoFixture.cs
new file mode 100644
index 00000000..66b702a6
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackSourceFormatDtoFixture.cs
@@ -0,0 +1,47 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackSourceFormatDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The container of the audio file of the track.
+ /// Optional. The codec of the audio of the track.
+ /// Whether the container should be included, or forced to .
+ /// Whether the codec should be included, or forced to .
+ /// The created .
+ public PlaybackSourceFormatDto Create(
+ string? container = null,
+ string? codec = null,
+ bool includeContainer = true,
+ bool includeCodec = true)
+ {
+ return new PlaybackSourceFormatDto(
+ includeContainer ? (container ?? _faker.Random.AlphaNumeric(4).ToUpperInvariant()) : null,
+ includeCodec ? (codec ?? _faker.Random.AlphaNumeric(4).ToUpperInvariant()) : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParserTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParserTests.cs
new file mode 100644
index 00000000..7b46ce58
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackCapabilitiesParserTests.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackCapabilitiesParserTests
+{
+ private readonly PlaybackCapabilityDtoFixture _playbackCapabilityDtoFixture = new();
+
+ [Theory]
+ [InlineData(null)] // an absent input falls back to the default capabilities
+ [InlineData("")] // an empty input falls back to the default capabilities
+ [InlineData(" ")] // a blank input falls back to the default capabilities
+ [InlineData("not-a-pair")] // an input that does not name both a container and a codec falls back to the default capabilities
+ [InlineData("a/b/c")] // an input with more than two segments falls back to the default capabilities
+ [InlineData("a//b")] // an input whose container or codec is empty falls back to the default capabilities
+ public void Parse_WhenInputIsNotAValidCapabilitySet_ShouldReturnDefaultCapabilities(string? input)
+ {
+ // Act
+ IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse(input);
+
+ // Assert
+ Assert.Same(PlaybackCapabilitiesParser.Default, capabilities);
+ }
+
+ [Fact]
+ public void Parse_WhenInputListsPairs_ShouldReturnThosePairs()
+ {
+ // Act
+ IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse("mp3/mp3,flac/flac");
+
+ // Assert
+ Assert.NotSame(PlaybackCapabilitiesParser.Default, capabilities);
+ Assert.Equal(2, capabilities.Count);
+ Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "mp3", codec: "mp3"), capabilities);
+ Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "flac", codec: "flac"), capabilities);
+ }
+
+ [Fact]
+ public void Parse_WhenEntriesArePadded_ShouldTrimThem()
+ {
+ // Act
+ IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse(" mp3 / mp3 , flac / flac ");
+
+ // Assert
+ Assert.Equal(2, capabilities.Count);
+ Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "mp3", codec: "mp3"), capabilities);
+ Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "flac", codec: "flac"), capabilities);
+ }
+
+ [Fact]
+ public void Parse_WhenInputContainsInvalidEntriesAmongValidOnes_ShouldIgnoreTheInvalidOnes()
+ {
+ // Act
+ IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse("mp3/mp3,,not-a-pair,/wav,wav/,wav/pcm");
+
+ // Assert
+ Assert.Equal(2, capabilities.Count);
+ Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "mp3", codec: "mp3"), capabilities);
+ Assert.Contains(_playbackCapabilityDtoFixture.Create(container: "wav", codec: "pcm"), capabilities);
+ }
+
+ [Fact]
+ public void Parse_WhenMorePairsThanTheMaximumAreListed_ShouldKeepOnlyTheFirstMaximum()
+ {
+ // Arrange
+ List pairs = [];
+ for (int index = 0; index < PlaybackCapabilitiesParser.MAX_CAPABILITY_COUNT + 5; index++)
+ pairs.Add($"container{index}/codec{index}");
+
+ // Act
+ IReadOnlyList capabilities = PlaybackCapabilitiesParser.Parse(string.Join(',', pairs));
+
+ // Assert
+ Assert.Equal(PlaybackCapabilitiesParser.MAX_CAPABILITY_COUNT, capabilities.Count);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs
index d38f7e75..b9e25ec0 100644
--- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs
+++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs
@@ -5,11 +5,13 @@ using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
using Lumina.Infrastructure.Common.DependencyInjection;
+using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Time;
@@ -43,6 +45,7 @@ public class InfrastructureLayerServicesTests
// Assert
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IFileHashService) && descriptor.ImplementationType == typeof(FileHashService));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDateTimeProvider) && descriptor.ImplementationType == typeof(DateTimeProvider));
+ Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPlaybackFormatService) && descriptor.ImplementationType == typeof(PlaybackFormatService));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginManager));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginSettingsStore));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDomainEventsQueue));
diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatServiceTests.cs
new file mode 100644
index 00000000..17c4a78e
--- /dev/null
+++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatServiceTests.cs
@@ -0,0 +1,283 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class PlaybackFormatServiceTests
+{
+ private readonly PlaybackFormatService _sut;
+ private readonly PlaybackSourceFormatDtoFixture _playbackSourceFormatDtoFixture = new();
+ private readonly PlaybackCapabilityDtoFixture _playbackCapabilityDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public PlaybackFormatServiceTests()
+ {
+ _sut = new PlaybackFormatService();
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenPlayerAdvertisesTheStoredFormat_ShouldReturnDirectPlay()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "FLAC", codec: "FLAC");
+ IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC")];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
+ Assert.Equal("FLAC", result.Value.Container);
+ Assert.Equal("FLAC", result.Value.Codec);
+ Assert.Equal(PlaybackDeliveryShape.ByteRangeSeekable, result.Value.Shape);
+ Assert.Equal(0, result.Value.SegmentDurationSeconds);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenPlayerDecodesTheCodecButNotTheContainer_ShouldReturnRemux()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
+ IReadOnlyList capabilities =
+ [
+ _playbackCapabilityDtoFixture.Create(container: "WAV", codec: "PCM"),
+ _playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC")
+ ];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
+ Assert.Equal("WAV", result.Value.Container);
+ Assert.Equal("PCM", result.Value.Codec);
+ Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.Shape);
+ Assert.Equal(6, result.Value.SegmentDurationSeconds);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenPlayerCannotDecodeTheStoredCodec_ShouldReturnTranscode()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "WMA", codec: "WMA");
+ IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
+ Assert.Equal("MP3", result.Value.Container);
+ Assert.Equal("MP3", result.Value.Codec);
+ Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.Shape);
+ Assert.Equal(6, result.Value.SegmentDurationSeconds);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenTheDefaultCapabilitiesAreUsed_ShouldReturnDirectPlay()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP3", codec: "MP3");
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, PlaybackCapabilitiesParser.Default);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenDefaultCapabilitiesAreUsedForAnAacTrackInMp4_ShouldReturnRemuxToRawAac()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP4", codec: "AAC");
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, PlaybackCapabilitiesParser.Default);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
+ Assert.Equal("AAC", result.Value.Container);
+ Assert.Equal("AAC", result.Value.Codec);
+ }
+
+ [Theory]
+ [InlineData("MP3", "MPEG-1 Layer 3", "MP3")] // the free form description of an MPEG-1 Layer 3 stream
+ [InlineData("MP3", "MP3", "MP3")] // a codec that is already named canonically
+ [InlineData("FLAC", "Flac", "FLAC")] // the description of a FLAC stream
+ [InlineData("OGG", "Vorbis I", "VORBIS")] // the description of a Vorbis stream
+ [InlineData("OGG", "Opus", "OPUS")] // the description of an Opus stream
+ [InlineData("MP4", "Apple Lossless", "ALAC")] // the description of an Apple Lossless stream
+ [InlineData("AAC", "MPEG-4 AAC", "AAC")] // a description naming both MPEG and AAC is AAC, not MP3
+ [InlineData("WAV", "PCM", "PCM")] // the description of an uncompressed stream
+ [InlineData("WAV", "Uncompressed", "PCM")] // another description of an uncompressed stream
+ [InlineData("WMA", "Windows Media Audio", "WMA")] // the description of a Windows Media stream
+ public void DecideDelivery_WhenTheStoredCodecDescriptionIsRecognizable_ShouldCanonicalizeItAndDirectPlay(string container, string codecDescription, string canonicalCodec)
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: container, codec: codecDescription);
+ IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: container, codec: canonicalCodec)];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
+ Assert.Equal(canonicalCodec, result.Value.Codec);
+ }
+
+ [Theory]
+ [InlineData("MPEG-1 Layer 2")] // MP2 shares the MP3 container but an MP3 decoder cannot decode it
+ [InlineData("MPEG-1 Layer 1")] // MP1 shares the MP3 container but an MP3 decoder cannot decode it
+ [InlineData("MPEG-4 Audio")] // a description that names no decodable codec is not mistaken for MP3
+ public void DecideDelivery_WhenAnMpegDescriptionIsNotLayer3_ShouldReturnTranscode(string codecDescription)
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP3", codec: codecDescription);
+ IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
+ }
+
+ [Theory]
+ [InlineData(null, null)] // an absent probe result names no codec
+ [InlineData("", "")] // an empty probe result names no codec
+ [InlineData("MP3", "AC-3")] // a codec description the server does not recognize
+ public void DecideDelivery_WhenTheStoredFormatIsUnknown_ShouldReturnTranscode(string? container, string? codec)
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(
+ container: container,
+ codec: codec,
+ includeContainer: container is not null,
+ includeCodec: codec is not null);
+ IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenSeveralProducibleCodecsAreAdvertised_ShouldTranscodeToTheMostPreferredOne()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "OGG", codec: "OPUS");
+ IReadOnlyList capabilities =
+ [
+ _playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC"),
+ _playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC")
+ ];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
+ Assert.Equal("AAC", result.Value.Codec);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenSeveralContainersAreAdvertisedForTheSameCodec_ShouldRemuxToThePreferredContainer()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MATROSKA", codec: "AAC");
+ IReadOnlyList capabilities =
+ [
+ _playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC"),
+ _playbackCapabilityDtoFixture.Create(container: "MP4", codec: "AAC")
+ ];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
+ Assert.Equal("MP4", result.Value.Container);
+ Assert.Equal("AAC", result.Value.Codec);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenThePreferredContainerForTheCodecIsNotAdvertised_ShouldRemuxToTheOtherProducibleContainer()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MATROSKA", codec: "AAC");
+ IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC")];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
+ Assert.Equal("AAC", result.Value.Container);
+ Assert.Equal("AAC", result.Value.Codec);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenThePlayerNamesAContainerTheServerDoesNotProduce_ShouldDeliverTheServerContainer()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
+ IReadOnlyList capabilities =
+ [
+ _playbackCapabilityDtoFixture.Create(container: "evil;$(x)", codec: "PCM"),
+ _playbackCapabilityDtoFixture.Create(container: "wav", codec: "pcm")
+ ];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsSuccess);
+ Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
+ Assert.Equal("WAV", result.Value.Container);
+ Assert.Equal("PCM", result.Value.Codec);
+ }
+
+ [Fact]
+ public void DecideDelivery_WhenThePlayerOnlyNamesContainersTheServerDoesNotProduce_ShouldReturnNoSupportedPlaybackFormat()
+ {
+ // Arrange
+ PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
+ IReadOnlyList capabilities = [_playbackCapabilityDtoFixture.Create(container: "evil;$(x)", codec: "PCM")];
+
+ // Act
+ Result result = _sut.DecideDelivery(sourceFormat, capabilities);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Playback.NoSupportedPlaybackFormat, result.FirstError);
+ }
+}