Adds the playback delivery decision service

This commit is contained in:
BinaryAlley committed 2026-10-15 09:19:36 +03:00
1 parent f97c5bed47
commit 7dc5953e1d
18 files changed
+952

No files matched your search

@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Data transfer object for a single container and codec combination that a player advertises it can demux and decode directly.
/// </summary>
/// <param name="Container">The container the player can demux, for example MP3, FLAC, OGG, WAV or MP4.</param>
/// <param name="Codec">The codec the player can decode, for example MP3, FLAC, Opus, Vorbis, PCM or AAC.</param>
[DebuggerDisplay("Container: {Container} Codec: {Codec}")]
public sealed record PlaybackCapabilityDto(
string Container,
string Codec
);
@@ -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;
/// <summary>
/// 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.
/// </summary>
/// <param name="Mode">The way the audio is delivered.</param>
/// <param name="Container">The container of the delivered audio, which is the stored container of the track for a direct play.</param>
/// <param name="Codec">The codec of the delivered audio, which is the stored codec of the track for a direct play.</param>
/// <param name="Shape">The shape the delivered audio is addressed and seeked by.</param>
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds, or zero when the shape is not time addressed.</param>
[DebuggerDisplay("Mode: {Mode} Container: {Container} Codec: {Codec} Shape: {Shape}")]
public sealed record PlaybackDeliveryDecisionDto(
PlaybackDeliveryMode Mode,
string Container,
string Codec,
PlaybackDeliveryShape Shape,
int SegmentDurationSeconds
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Data transfer object for the stored format of a track's audio, that a playback delivery decision is made on.
/// </summary>
/// <param name="Container">The container of the audio file of the track, for example MP3, FLAC, OGG, MP4 or WAV.</param>
/// <param name="Codec">The codec of the audio of the track, as reported by the probe, for example AAC, FLAC, Opus or PCM.</param>
[DebuggerDisplay("Container: {Container} Codec: {Codec}")]
public sealed record PlaybackSourceFormatDto(
string? Container,
string? Codec
);
@@ -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;
/// <summary>
/// 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.
/// </summary>
public interface IPlaybackFormatService
{
/// <summary>
/// Decides how the audio of a track, described by <paramref name="sourceFormat"/>, is delivered to a player that advertises <paramref name="capabilities"/>.
/// </summary>
/// <param name="sourceFormat">The container and codec of the audio of the track, read from its stored probe result.</param>
/// <param name="capabilities">The container and codec combinations the player advertises it can demux and decode directly.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the delivery decision, or an error when the server cannot produce any
/// format the player advertises it supports.
/// </returns>
Result<PlaybackDeliveryDecisionDto> DecideDelivery(PlaybackSourceFormatDto sourceFormat, IReadOnlyList<PlaybackCapabilityDto> capabilities);
}
@@ -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;
/// <summary>
/// Parses the capabilities input of a playback manifest request into the container and codec combinations a player advertises it
/// can demux and decode directly.
/// </summary>
/// <remarks>
/// The input is a comma separated list of <c>container/codec</c> pairs, for example
/// <c>mp3/mp3,flac/flac,ogg/opus,ogg/vorbis,wav/pcm,mp4/aac</c>. 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
/// <see cref="Default"/> capabilities of the bundled player apply.
/// </remarks>
public static class PlaybackCapabilitiesParser
{
/// <summary>
/// The maximum number of capability pairs that are read from a single request, so that the parsing work stays bounded.
/// </summary>
public const int MAX_CAPABILITY_COUNT = 32;
/// <summary>
/// The character that separates the container from the codec of a single capability pair.
/// </summary>
public const char CONTAINER_CODEC_SEPARATOR = '/';
/// <summary>
/// The character that separates the capability pairs of a capability set.
/// </summary>
public const char CAPABILITY_SEPARATOR = ',';
/// <summary>
/// Gets the capability set the bundled player advertises, used when a request does not advertise any capability.
/// </summary>
public static IReadOnlyList<PlaybackCapabilityDto> 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")
];
/// <summary>
/// Parses the capabilities input of a playback manifest request into a capability set.
/// </summary>
/// <param name="capabilitiesInput">The value of the capabilities input, a comma separated list of <c>container/codec</c> pairs.</param>
/// <returns>The parsed capabilities, or <see cref="Default"/> when the input is absent, empty or lists no valid pair.</returns>
public static IReadOnlyList<PlaybackCapabilityDto> Parse(string? capabilitiesInput)
{
if (string.IsNullOrWhiteSpace(capabilitiesInput))
return Default;
List<PlaybackCapabilityDto> 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;
}
}
@@ -0,0 +1,22 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Playback;
/// <summary>
/// Enumeration for the ways in which a track's audio is delivered to a player.
/// </summary>
public enum PlaybackDeliveryMode
{
/// <summary>
/// The original audio file is delivered unchanged, because the player can demux its container and decode its codec as stored.
/// </summary>
DirectPlay,
/// <summary>
/// The audio is repackaged into a container the player can demux, without re-encoding its codec.
/// </summary>
Remux,
/// <summary>
/// The audio is re-encoded into a codec the player can decode, because the stored codec is not one the player supports.
/// </summary>
Transcode,
}
@@ -0,0 +1,18 @@
namespace Lumina.Domain.SharedKernel.Common.Enums.Playback;
/// <summary>
/// Enumeration for the shapes in which delivered audio is addressed and seeked.
/// </summary>
public enum PlaybackDeliveryShape
{
/// <summary>
/// The delivered media is the original file itself, addressed and seeked by byte range.
/// </summary>
ByteRangeSeekable,
/// <summary>
/// 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.
/// </summary>
TimeAddressedSegments,
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
#endregion
namespace Lumina.Domain.Common.Errors;
/// <summary>
/// Domain playback related error types.
/// </summary>
public static partial class Errors
{
public static class Playback
{
public static Error NoSupportedPlaybackFormat => Error.Forbidden(description: nameof(NoSupportedPlaybackFormat));
}
}
@@ -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<IMusicArtworkService, MusicArtworkService>();
// 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<IPlaybackFormatService, PlaybackFormatService>();
// 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<IBookReaderEnablementCache, BookReaderEnablementCache>();
@@ -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;
/// <summary>
/// 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).
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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<string> 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<string, IReadOnlyList<string>> s_producibleContainersByCodec = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase)
{
{ "AAC", ["MP4", "AAC"] },
{ "OPUS", ["OGG"] },
{ "VORBIS", ["OGG"] },
{ "MP3", ["MP3"] },
{ "FLAC", ["FLAC"] },
{ "PCM", ["WAV"] }
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Decides how the audio of a track, described by <paramref name="sourceFormat"/>, is delivered to a player that advertises <paramref name="capabilities"/>.
/// </summary>
/// <param name="sourceFormat">The container and codec of the audio of the track, read from its stored probe result.</param>
/// <param name="capabilities">The container and codec combinations the player advertises it can demux and decode directly.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the delivery decision, or an error when the server cannot produce any format the player advertises it supports.
/// </returns>
public Result<PlaybackDeliveryDecisionDto> DecideDelivery(PlaybackSourceFormatDto sourceFormat, IReadOnlyList<PlaybackCapabilityDto> 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);
}
/// <summary>
/// Checks whether the player advertises the provided <paramref name="container"/> and <paramref name="codec"/> as a combination it can demux and decode directly.
/// </summary>
/// <param name="capabilities">The capabilities advertised by the player.</param>
/// <param name="container">The canonical container that is looked for.</param>
/// <param name="codec">The canonical codec that is looked for.</param>
/// <returns><see langword="true"/> when the player advertises the combination, otherwise <see langword="false"/>.</returns>
private static bool IsFormatAdvertised(IReadOnlyList<PlaybackCapabilityDto> 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));
}
/// <summary>
/// Selects the container the server produces the provided <paramref name="codec"/> in, preferring the server's canonical one, among the containers the player advertises it can demux for that codec.
/// </summary>
/// <param name="capabilities">The capabilities advertised by the player.</param>
/// <param name="codec">The canonical codec that is delivered.</param>
/// <returns>
/// The container and codec the server delivers in, or <see langword="null"/> when the server cannot produce the codec in any container the player advertises it can demux.
/// </returns>
private static PlaybackCapabilityDto? SelectFormatForCodec(IReadOnlyList<PlaybackCapabilityDto> capabilities, string codec)
{
if (codec.Length == 0 || !s_producibleContainersByCodec.TryGetValue(codec, out IReadOnlyList<string>? producibleContainers))
return null;
IReadOnlyList<string> 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;
}
/// <summary>
/// Selects the most preferred codec the server can produce that the player advertises it can decode.
/// </summary>
/// <param name="capabilities">The capabilities advertised by the player.</param>
/// <returns>The preferred producible container and codec, or <see langword="null"/> when the player supports no producible codec.</returns>
private static PlaybackCapabilityDto? SelectTranscodeFormat(IReadOnlyList<PlaybackCapabilityDto> capabilities)
{
foreach (string preferredCodec in s_transcodeCodecPreference)
{
PlaybackCapabilityDto? format = SelectFormatForCodec(capabilities, preferredCodec);
if (format is not null)
return format;
}
return null;
}
/// <summary>
/// Canonicalizes the container of an audio file, so that containers compare regardless of casing.
/// </summary>
/// <param name="container">The container to canonicalize.</param>
/// <returns>The canonical container, or an empty string when there is none.</returns>
private static string CanonicalizeContainer(string? container)
{
return string.IsNullOrWhiteSpace(container) ? string.Empty : container.Trim().ToUpperInvariant();
}
/// <summary>
/// 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.
/// </summary>
/// <param name="codec">The codec to canonicalize.</param>
/// <returns>The canonical codec, or an empty string when there is none.</returns>
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;
}
}
+1
View File
@@ -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}"