Adds normalized audio playback pipeline

This commit is contained in:
BinaryAlley committed 2026-10-17 20:52:08 +03:00
1 parent 6991640710
commit 4e13b23f16
35 files changed
+3817 -41

No files matched your search

+14 -6
View File
@@ -21,16 +21,17 @@ Lumina ships as two applications that talk to each other over the network: the *
> **Not production ready yet.** Lumina is pre-alpha software. Updates are one way and can lose Lumina's data, so read [Updating](#updating) before you install or upgrade.
There are **two ways to install Lumina**. Pick one:
There are **two ways to run Lumina**. Pick one:
- **[Option A: run with Docker Compose](#option-a-run-with-docker-compose)**, the recommended route, where a single command brings up the whole system.
- **[Option B: build and run manually](#option-b-build-and-run-manually)**, if you would rather run the applications directly, without containers.
- **[Option B: run the applications directly](#option-b-run-the-applications-directly)**, whether you install a release package or build from source, if you would rather run them without containers.
Everything from Configuration onward applies to whichever route you chose.
## Before you start
- **Docker**, if you want the container route, or the **.NET 10 SDK** if you want to build and run from source.
- **Docker**, if you want the container route. For a non-container install, you need the Lumina application files, from a release package or installer, or from your own build, plus the **.NET 10 runtime** unless that package is self-contained. The **.NET 10 SDK** is only needed if you build from source.
- **ffmpeg**, for any non-container install, however you obtained the application files. The API server uses it to remux or transcode audio that the browser cannot play as stored. The Docker API container image already includes it.
- By default the **web client listens on port `5012`** and the **API on port `5214`**. You can change either, as long as the two agree on where the API is (see [Configuration](#configuration)).
- For anything reachable beyond your own machine, put a **reverse proxy** in front to terminate TLS and forward to the web client.
- Lumina needs **no external database server**. It keeps its data in a local SQLite file that is created automatically.
@@ -77,15 +78,15 @@ The development configuration embeds throwaway keys so the container route works
Set them as environment variables on the `lumina-api` and `lumina-web` services in your own compose file or orchestration.
## Option B: build and run manually
## Option B: run the applications directly
With the .NET 10 SDK installed, build the solution from the `src` directory:
Use a release package or installer when one is available, or, with the .NET 10 SDK installed, build the solution from the `src` directory:
```bash
dotnet build Lumina.sln
```
Run the API and the web client. In development, their addresses come from each project's `launchSettings.json` (`http://localhost:5214` and `http://localhost:5012`). When you run a published build directly on a host, set the addresses yourself, either with `ASPNETCORE_URLS` or with `ASPNETCORE_HTTP_PORTS`:
Run the API and the web client from the installed release package or from the published build. In development, their addresses come from each project's `launchSettings.json` (`http://localhost:5214` and `http://localhost:5012`). When you run a published build directly on a host, set the addresses yourself, either with `ASPNETCORE_URLS` or with `ASPNETCORE_HTTP_PORTS`:
```bash
ASPNETCORE_HTTP_PORTS=5012 dotnet Lumina.Presentation.Web.dll
@@ -93,6 +94,8 @@ ASPNETCORE_HTTP_PORTS=5012 dotnet Lumina.Presentation.Web.dll
The API creates its SQLite database (`Lumina.db`) next to its own binary and applies any pending migrations at startup, so the first launch sets up the schema on its own.
The API server needs **ffmpeg** on its `PATH` to normalize audio that a player cannot play as stored. Install it with your platform's package manager, or point `TranscodingSettings:FfmpegPath` at the binary if it is somewhere else.
## Configuration
Each application reads its own `appsettings.json` and an optional environment specific `appsettings.development.json`, and environment variables override both. The API also loads the `appsettings.shared.json` file (and its development variant), which holds the server side settings that are not specific to a single layer, such as the media, plugins and theme options.
@@ -112,10 +115,15 @@ The settings that matter most when installing:
| `PluginsSettings:Directory` | API server | Folder holding installed plugin assemblies, `plugins` by default. |
| `ThemeEngine:StoragePath`, `ThemeEngine:BundledThemesPath`, `ThemeEngine:DefaultThemeId` | API server | Where installed and bundled themes live, and which theme is activated by default. |
| `ThemeEngine:MaxArchiveBytes`, `MaxExpandedBytes`, `MaxSingleFileBytes`, `MaxEntries` | API server | Limits enforced on uploaded theme packs. |
| `TranscodingSettings:FfmpegPath`, `MaxConcurrentJobs`, `MaxCacheBytes`, `JobTimeoutSeconds`, `EvictionGraceSeconds`, `CacheDirectory` | API server | Where the ffmpeg binary is, how many audio normalization jobs may run at once, the maximum size of the normalized audio cache in bytes, how long a single job may take in seconds, how long a freshly produced or served cache entry is protected from eviction, and where the cache is stored. When `CacheDirectory` is absent, a private directory under the API account's temporary directory is used. |
| `Telemetry:Enabled`, `Telemetry:Otlp:Endpoint`, `Telemetry:TraceSampleRatio`, `Telemetry:ConsoleExporterEnabled` | API server and web client | Telemetry behavior. The OTLP endpoint also falls back to the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable. Again, while telemetry is enabled as a feature, nothing is sent anywhere. |
The `LOG_PATH` environment variable selects where the rolling log files are written.
The normalized audio cache must not be placed inside `MediaSettings:RootDirectory`, because that directory is served at the `/media` route, and it must not contain that directory either, because cleaning the cache would remove the media. The startup configuration also rejects a cache directory that is a filesystem root, the application directory or one of its parents, or that overlaps the logs or plugins directories. The default uses a private directory under the API account's temporary directory and avoids all of these. The cache holds transcoded or remuxed audio only while it is useful: at API startup only the entries the cache itself owns are removed, and a directory is cleaned only when it carries Lumina's cache marker file (`.lumina-transcoding-cache`) or is empty, so a directory that belongs to something else is left untouched. Its total footprint is capped by `TranscodingSettings:MaxCacheBytes`, but an entry that is still being read, or that was just produced when the cache was already at the limit, is kept until it can be removed, so the cache can exceed the cap temporarily. The cache is not part of the media library.
The default cache directory is scoped to the API account, but the coordinator, the running jobs and the startup cleanup are per process. Run a single API process per account and host, or configure a distinct `CacheDirectory` for each instance. On a multi-user Unix host the directory is created with private permissions, and a pre-existing directory owned by another account is treated as unavailable rather than reused or deleted.
### Keeping the two applications in step
The web client and the API must agree on two addresses, and getting them wrong is the usual cause of a client that loads but never updates live:
+1 -1
View File
@@ -87,6 +87,6 @@ Wherever Lumina needs a folder or a file from the server, it opens the file syst
The tools section holds your settings and the language picker.
Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. A final group of options shapes playback: whether the player keeps downloading while it is paused, whether it continues automatically at the end of an album or artist, whether consecutive tracks play without a gap, how ReplayGain normalizes loudness, and the quality cap used when the server has to normalize a track. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md).
Your **settings** decide how lists and books behave for you. Enable pagination and the number of items per page control how browsing is split. The alpha picker option decides whether titles beginning with "The" are filed under the next word. Theme caching decides whether the theme is fetched fresh each time. Rendering PDFs as images and preserving book styles shape how books are shown, and the metadata and artwork aggregation options decide whether missing fields are completed from your other providers. A final group of options shapes playback: whether the player keeps downloading while it is paused, whether it continues automatically at the end of an album or artist, whether consecutive tracks play without a gap, how ReplayGain normalizes loudness, and the quality cap used when the server has to normalize a track. That cap applies only when the server re-encodes a track into a lossy format; a remux only repackages the stored audio, and a lossless delivery is not reduced. The ones that touch libraries are described in more detail in [Managing Libraries](../managing-libraries/index.md).
The **language** picker switches the interface between the languages Lumina ships with, and remembers your choice.
@@ -38,7 +38,7 @@ GET /api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{tr
- 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.
`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), 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
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Data transfer object for the normalized audio of a track, produced and cached as a sequence of fixed duration segments.
/// </summary>
/// <param name="TrackId">The Id of the track whose audio the cached entry holds, so the caller can verify that the entry is the one it authorized.</param>
/// <param name="CacheId">The opaque identifier of the cached entry that holds the normalized audio.</param>
/// <param name="Mode">The way the audio is delivered, which is a remux or a transcode.</param>
/// <param name="Container">The container of the delivered audio.</param>
/// <param name="Codec">The codec of the delivered audio.</param>
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="DurationInSeconds">
/// The duration of the produced and cached audio, in seconds, rounded up to the next second. It is the produced end rather than the probed duration, so
/// it always covers every produced segment.
/// </param>
/// <param name="Segments">The segments that make up the delivered audio, in playback order.</param>
[DebuggerDisplay("TrackId: {TrackId} CacheId: {CacheId} Container: {Container} Codec: {Codec}")]
public sealed record NormalizedTrackDto(
Guid TrackId,
string CacheId,
PlaybackDeliveryMode Mode,
string Container,
string Codec,
int SegmentDurationSeconds,
int DurationInSeconds,
IReadOnlyList<NormalizedTrackSegmentDto> Segments
);
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Data transfer object for the request to produce the normalized audio of a track, as the delivery decision of a playback manifest describes it.
/// </summary>
/// <param name="TrackId">The Id of the track whose audio is normalized. It binds the produced cache entry to the track the caller authorized.</param>
/// <param name="SourcePath">The file system path of the stored audio file of the track.</param>
/// <param name="AllowedRoots">
/// The content locations the source path is allowed to be inside. The service validates the path against them and re-checks it after opening, so a
/// caller that forgets to enforce containment cannot hand an arbitrary path to the transcoder.
/// </param>
/// <param name="SourceContainer">The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. Optional.</param>
/// <param name="Mode">The way the audio is delivered, which is a remux or a transcode.</param>
/// <param name="Container">The container of the delivered audio, as chosen by the delivery decision.</param>
/// <param name="Codec">The codec of the delivered audio, as chosen by the delivery decision.</param>
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="DurationInSeconds">The duration of the audio of the track, in seconds.</param>
/// <param name="Bitrate">The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. Optional.</param>
/// <param name="SampleRate">The sample rate of the stored audio of the track, in Hz, used to estimate the size of a lossless delivery.</param>
/// <param name="Channels">The number of audio channels of the track, used to estimate the size of a lossless delivery.</param>
/// <param name="BitDepth">The bit depth of the stored audio of the track, if applicable, used to estimate the size of a lossless delivery.</param>
/// <param name="Quality">The quality cap applied to the delivered audio when it has to be re-encoded.</param>
[DebuggerDisplay("TrackId: {TrackId} Mode: {Mode} Container: {Container} Codec: {Codec}")]
public sealed record NormalizedTrackRequestDto(
Guid TrackId,
string SourcePath,
IReadOnlyList<string> AllowedRoots,
string? SourceContainer,
PlaybackDeliveryMode Mode,
string Container,
string Codec,
int SegmentDurationSeconds,
int DurationInSeconds,
int? Bitrate,
int SampleRate,
int Channels,
int? BitDepth,
PlaybackStreamingQuality Quality
);
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Data transfer object for a single fixed duration segment of the normalized audio of a track.
/// </summary>
/// <param name="Index">The zero based position of the segment in the delivered audio.</param>
/// <param name="StartSeconds">The time, in seconds from the start of the track, at which the segment starts.</param>
/// <param name="DurationSeconds">The duration of the segment, in seconds.</param>
/// <param name="Length">The length of the segment, in bytes.</param>
[DebuggerDisplay("Index: {Index} StartSeconds: {StartSeconds} DurationSeconds: {DurationSeconds}")]
public sealed record NormalizedTrackSegmentDto(
int Index,
decimal StartSeconds,
decimal DurationSeconds,
long Length
);
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Primitives;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Interface for the service that produces, caches and serves the normalized audio of a track, when the player cannot play the stored audio directly.
/// </summary>
/// <remarks>
/// The caller is responsible for authorizing the request. The service re-validates the source path against the allowed roots carried by the request and
/// re-checks it after opening, as defense in depth, so a caller that forgets containment cannot hand an arbitrary path to the transcoder. The service
/// itself only handles the media pipeline: it never reads or writes a database row, and it never emits a domain event. Every entry is bound to the track
/// it was produced for, so a cache handle can never be used to read the audio of another track.
/// A production is atomic: the cache entry is published only after ffmpeg has finished the whole track, so the first request waits for a complete
/// production. Streaming in this contract means serving the produced segments from the cache without buffering them into memory, not publishing a partial
/// track. Incremental publication of segment 0 while the rest is produced would be a different contract. Admission is bounded: when every normalization job
/// slot is in use, a request for an entry that is not cached yet is reported as unavailable instead of being queued behind the running jobs. A production
/// that was admitted outlives the request that started it, so repeated aborts converge to a cached entry. A production that needs a toolchain the startup
/// probe found unusable reports <see cref="Domain.Common.Errors.Errors.Playback.NormalizationUnavailable"/> as well, while an entry that is already
/// cached is still served. The playback stream surface that exposes the produced segments is the intended consumer of this contract; no API request path
/// calls it yet.
/// </remarks>
public interface ITrackNormalizationService
{
/// <summary>
/// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet.
/// </summary>
/// <param name="request">The track, the delivery decision, the source file and the quality cap the normalized audio is produced with.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the cached normalized audio of the track, or an error message.
/// </returns>
/// <exception cref="OperationCanceledException">
/// Thrown when <paramref name="cancellationToken"/> is canceled while the caller is waiting. The production continues in the background, so this is a
/// disconnect signal and must not be treated as a production failure.
/// </exception>
Task<Result<NormalizedTrackDto>> GetOrCreateNormalizedTrackAsync(NormalizedTrackRequestDto request, CancellationToken cancellationToken);
/// <summary>
/// Opens a read stream over a single segment of a cached normalized track, after verifying that the entry belongs to the provided track.
/// </summary>
/// <remarks>
/// A missing or evicted cache entry, a segment that is no longer present, an entry that cannot be read, or a value that is not a well formed handle is
/// reported with <see cref="Domain.Common.Errors.Errors.Playback.NormalizedTrackCacheEntryNotFound"/>. That is the caller's signal to request the
/// playback manifest again, or to trigger a new production, instead of treating the result as a broken transcode. A genuine production failure keeps
/// its own error. A service that has already been disposed reports
/// <see cref="Domain.Common.Errors.Errors.Playback.NormalizationUnavailable"/>.
/// </remarks>
/// <param name="cacheId">The opaque identifier of the cached entry that holds the normalized audio.</param>
/// <param name="trackId">The Id of the track the caller authorized and whose segment is opened.</param>
/// <param name="segmentIndex">The zero based position of the segment in the delivered audio.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either a read stream over the segment, or an error message. The caller owns the returned stream.
/// </returns>
Result<Stream> OpenNormalizedSegment(string cacheId, Guid trackId, int segmentIndex);
}
@@ -4,27 +4,28 @@ namespace Lumina.Domain.SharedKernel.Common.Enums.Playback;
/// Enumeration for the quality cap applied to the audio the server normalizes (remuxes or transcodes) for a user.
/// </summary>
/// <remarks>
/// The caps apply only to audio the server has to change; a track that is played directly is always delivered as it was stored.
/// The caps apply only to audio the server re-encodes into a lossy codec. A track that is played directly is delivered as it was stored, a remux only
/// repackages the stored codec without re-encoding it, and a lossless transcode is not reduced, so none of those deliveries is capped.
/// </remarks>
public enum PlaybackStreamingQuality
{
/// <summary>
/// The server chooses the quality, with no explicit cap.
/// The server chooses the quality, with a default cap of 192 kbps for a lossy re-encode.
/// </summary>
Auto,
/// <summary>
/// Normalized audio is capped at 96 kbps.
/// A lossy normalized audio stream is capped at 96 kbps.
/// </summary>
Low,
/// <summary>
/// Normalized audio is capped at 160 kbps.
/// A lossy normalized audio stream is capped at 160 kbps.
/// </summary>
Medium,
/// <summary>
/// Normalized audio is capped at 320 kbps.
/// A lossy normalized audio stream is capped at 320 kbps.
/// </summary>
High,
}
@@ -12,5 +12,14 @@ public static partial class Errors
public static class Playback
{
public static Error NoSupportedPlaybackFormat => Error.Forbidden(description: nameof(NoSupportedPlaybackFormat));
public static Error PlaybackFormatNotImplemented => Error.Internal(description: nameof(PlaybackFormatNotImplemented));
public static Error NormalizedTrackCacheEntryNotFound => Error.NotFound(description: nameof(NormalizedTrackCacheEntryNotFound));
public static Error NormalizationFailed => Error.Failure(description: nameof(NormalizationFailed));
public static Error NormalizationCacheLimitExceeded => Error.Failure(description: nameof(NormalizationCacheLimitExceeded));
public static Error NormalizationTimedOut => Error.Timeout(description: nameof(NormalizationTimedOut));
public static Error NormalizationUnavailable => Error.ResourceUnavailable(description: nameof(NormalizationUnavailable));
public static Error NormalizationIsNotRequiredForDirectPlay => Error.InvalidOperation(description: nameof(NormalizationIsNotRequiredForDirectPlay));
public static Error SegmentDurationMustBePositive => Error.Validation(description: nameof(SegmentDurationMustBePositive));
public static Error TrackDurationMustBePositive => Error.Validation(description: nameof(TrackDurationMustBePositive));
}
}
@@ -0,0 +1,275 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.Common.Caching;
/// <summary>
/// Provides the location, the ownership marker and the permissions of the temporary directory into which the audio normalization pipeline writes the normalized audio.
/// </summary>
internal static class TranscodingCachePaths
{
/// <summary>
/// The name of the temporary directory that is used when no cache directory is configured.
/// </summary>
public const string DEFAULT_DIRECTORY_NAME = "lumina-transcoding-cache";
/// <summary>
/// The name of the file that marks a directory as a normalized audio cache created and owned by this application.
/// </summary>
public const string CACHE_MARKER_FILE_NAME = ".lumina-transcoding-cache";
/// <summary>
/// The prefix of the temporary directories of the normalization jobs that have not been published to the cache yet.
/// </summary>
public const string TEMPORARY_DIRECTORY_PREFIX = "tmp-";
/// <summary>
/// The prefix of the tombstone directories that were detached from the cache and are waiting to be deleted.
/// </summary>
public const string DELETION_DIRECTORY_PREFIX = "del-";
private const int CACHE_ID_HEX_LENGTH = 64;
private const UnixFileMode PRIVATE_DIRECTORY_MODE = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;
private const UnixFileMode PRIVATE_FILE_MODE = UnixFileMode.UserRead | UnixFileMode.UserWrite;
private const int USER_SUFFIX_LENGTH = 16;
/// <summary>
/// Gets the absolute path of the directory into which the audio normalization pipeline writes the normalized audio of the tracks.
/// </summary>
/// <param name="configuredDirectory">
/// The configured cache directory, relative to the application base directory when not rooted, or <see langword="null"/> to use a private directory
/// under the system temporary directory. The default directory is scoped to the operating system account that runs the process.
/// </param>
/// <returns>The absolute path of the transcoding cache directory.</returns>
public static string GetRootDirectory(string? configuredDirectory)
{
if (!string.IsNullOrWhiteSpace(configuredDirectory))
{
string trimmedDirectory = configuredDirectory.Trim();
string absoluteDirectory = Path.IsPathRooted(trimmedDirectory)
? trimmedDirectory
: Path.Combine(AppContext.BaseDirectory, trimmedDirectory);
return Path.GetFullPath(absoluteDirectory);
}
return Path.Combine(Path.GetTempPath(), DEFAULT_DIRECTORY_NAME + "-" + GetUserSuffix());
}
/// <summary>
/// Checks whether a directory carries the marker of a normalized audio cache created by this application.
/// </summary>
/// <param name="directoryPath">The absolute path of the directory to check.</param>
/// <returns><see langword="true"/> when the directory carries the cache marker, otherwise <see langword="false"/>.</returns>
public static bool HasCacheMarker(string directoryPath)
{
return File.Exists(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME));
}
/// <summary>
/// Writes the marker that records the directory as a normalized audio cache created and owned by this application.
/// </summary>
/// <param name="directoryPath">The absolute path of the directory to mark.</param>
/// <remarks>
/// The marker is an ownership signal, not a lock: it is written once, and its presence is what allows a later startup to clean the directory. A directory
/// without the marker is never cleaned, so a cache directory that was configured by mistake can never lose data that does not belong to this application.
/// </remarks>
public static void WriteCacheMarker(string directoryPath)
{
if (HasCacheMarker(directoryPath))
return;
File.WriteAllText(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME), "Lumina normalized audio cache." + Environment.NewLine);
}
/// <summary>
/// Checks whether an entry name belongs to the namespace of the normalized audio cache.
/// </summary>
/// <param name="entryName">The name of the entry, without its directory.</param>
/// <returns><see langword="true"/> when the name is a cache identifier, a temporary directory name or a deletion tombstone name, otherwise <see langword="false"/>.</returns>
public static bool IsCacheEntryName(string entryName)
{
if (string.IsNullOrEmpty(entryName))
return false;
return IsValidCacheId(entryName) ||
entryName.StartsWith(TEMPORARY_DIRECTORY_PREFIX, StringComparison.Ordinal) ||
entryName.StartsWith(DELETION_DIRECTORY_PREFIX, StringComparison.Ordinal);
}
/// <summary>
/// Checks whether a value is a well formed opaque cache identifier.
/// </summary>
/// <param name="cacheId">The value to check.</param>
/// <returns><see langword="true"/> when the value is a well formed cache identifier, otherwise <see langword="false"/>.</returns>
public static bool IsValidCacheId(string cacheId)
{
if (string.IsNullOrEmpty(cacheId) || cacheId.Length != CACHE_ID_HEX_LENGTH)
return false;
foreach (char character in cacheId)
if (!char.IsAsciiHexDigitLower(character))
return false;
return true;
}
/// <summary>
/// Removes the entries of a directory that belong to the namespace of the normalized audio cache, and leaves every other entry untouched.
/// </summary>
/// <param name="directoryPath">The absolute path of the cache directory.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <remarks>
/// The cache directory itself is never deleted, and entries that do not carry a cache identifier, a temporary directory name or a deletion tombstone
/// name are never inspected. This makes the startup cleanup safe even when the configured directory is not one this application created.
/// </remarks>
/// <exception cref="OperationCanceledException">The cleanup was canceled.</exception>
/// <exception cref="IOException">An entry could not be deleted.</exception>
/// <exception cref="UnauthorizedAccessException">An entry could not be deleted because access was denied.</exception>
public static void ClearCacheEntries(string directoryPath, CancellationToken cancellationToken)
{
foreach (string entryPath in Directory.GetDirectories(directoryPath))
{
cancellationToken.ThrowIfCancellationRequested();
if (!IsCacheEntryName(Path.GetFileName(entryPath)))
continue;
DirectoryInfo entryDirectory = new(entryPath);
// A cache entry is never a link. A link left under a cache like name is deleted as a link, so the deletion can never be redirected outside the cache.
if (entryDirectory.LinkTarget is not null)
entryDirectory.Delete();
else
DeleteDirectoryRecursive(entryPath, cancellationToken);
}
}
/// <summary>
/// Deletes a directory and everything it contains.
/// </summary>
/// <param name="directoryPath">The directory to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="OperationCanceledException">The deletion was canceled.</exception>
/// <exception cref="IOException">A file or directory could not be deleted.</exception>
/// <exception cref="UnauthorizedAccessException">A file or directory could not be deleted because access was denied.</exception>
private static void DeleteDirectoryRecursive(string directoryPath, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (string filePath in Directory.EnumerateFiles(directoryPath))
{
cancellationToken.ThrowIfCancellationRequested();
File.Delete(filePath);
}
foreach (string childDirectoryPath in Directory.EnumerateDirectories(directoryPath))
{
cancellationToken.ThrowIfCancellationRequested();
DirectoryInfo childDirectory = new(childDirectoryPath);
// A link is deleted as a link, so a tampered entry can never make the cleanup follow it outside the cache.
if (childDirectory.LinkTarget is not null)
childDirectory.Delete();
else
DeleteDirectoryRecursive(childDirectoryPath, cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
Directory.Delete(directoryPath);
}
/// <summary>
/// Verifies that an existing cache directory is not a symbolic link and tightens its permissions to the private mode on Unix.
/// </summary>
/// <param name="directoryPath">The absolute path of the cache directory.</param>
/// <exception cref="IOException">The path is a symbolic link or cannot be inspected.</exception>
/// <exception cref="UnauthorizedAccessException">The directory is owned by another user or cannot be changed.</exception>
public static void RestrictPermissions(string directoryPath)
{
DirectoryInfo directoryInformation = new(directoryPath);
// A symbolic link is rejected even when its target does not exist, so CreateDirectory can never be redirected outside the intended path.
if (directoryInformation.LinkTarget is not null)
throw new IOException("The normalized audio cache directory is a symbolic link.");
// On Unix a directory that already exists is not changed by CreateDirectory, and a directory planted by another user under a predictable name in
// the shared temporary directory would otherwise be reused with its own mode. Tightening it fails when the directory is not owned by this
// account, which makes the caller treat the cache as unavailable instead of using a directory it does not control.
if (!OperatingSystem.IsWindows() && directoryInformation.Exists)
File.SetUnixFileMode(directoryPath, PRIVATE_DIRECTORY_MODE);
}
/// <summary>
/// Tightens the permissions of a file the cache created to owner read and write on Unix.
/// </summary>
/// <param name="filePath">The absolute path of the file.</param>
/// <exception cref="IOException">The file permissions could not be changed.</exception>
/// <exception cref="UnauthorizedAccessException">The file is owned by another user or cannot be changed.</exception>
public static void RestrictFilePermissions(string filePath)
{
// Windows inherits the ACL of the private cache directory, so only the Unix mode bits need to be tightened here.
if (!OperatingSystem.IsWindows())
File.SetUnixFileMode(filePath, PRIVATE_FILE_MODE);
}
/// <summary>
/// Creates a directory with private permissions on the platforms that support them.
/// </summary>
/// <param name="directoryPath">The absolute path of the directory to create.</param>
/// <exception cref="IOException">The directory could not be created.</exception>
/// <exception cref="UnauthorizedAccessException">The directory could not be created because access was denied.</exception>
public static void CreatePrivateDirectory(string directoryPath)
{
if (OperatingSystem.IsWindows())
{
Directory.CreateDirectory(directoryPath);
return;
}
Directory.CreateDirectory(directoryPath, PRIVATE_DIRECTORY_MODE);
// CreateDirectory does not change an existing directory, so the mode is applied again after the directory is known to exist.
File.SetUnixFileMode(directoryPath, PRIVATE_DIRECTORY_MODE);
}
/// <summary>
/// Creates the cache directory when it does not exist, or tightens an existing one, with private permissions on the platforms that support them.
/// </summary>
/// <param name="directoryPath">The absolute path of the cache directory.</param>
/// <remarks>
/// A directory created by this method is marked as owned by this application. An existing directory is never marked, so an operator supplied directory
/// is adopted only by the startup component, and only when it is empty.
/// </remarks>
/// <exception cref="IOException">The directory could not be created, or the path is a symbolic link.</exception>
/// <exception cref="UnauthorizedAccessException">The directory could not be created or changed because access was denied.</exception>
public static void EnsureDirectoryExists(string directoryPath)
{
RestrictPermissions(directoryPath);
bool isCreated = !Directory.Exists(directoryPath);
CreatePrivateDirectory(directoryPath);
if (isCreated)
WriteCacheMarker(directoryPath);
}
/// <summary>
/// Deletes a directory, and reports whether it was deleted.
/// </summary>
/// <param name="directoryPath">The directory to delete.</param>
/// <returns><see langword="true"/> when the directory no longer exists, otherwise <see langword="false"/>.</returns>
public static bool TryDeleteDirectory(string directoryPath)
{
try
{
if (Directory.Exists(directoryPath))
Directory.Delete(directoryPath, recursive: true);
return true;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>
/// Gets a short, file name safe suffix of the operating system account that runs the process, so the default directory is not shared between users.
/// </summary>
/// <returns>The account suffix used in the default cache directory name.</returns>
private static string GetUserSuffix()
{
string userIdentity = Environment.UserName;
if (string.IsNullOrWhiteSpace(userIdentity))
userIdentity = "default";
byte[] identityHash = SHA256.HashData(Encoding.UTF8.GetBytes(userIdentity));
return Convert.ToHexString(identityHash).ToLowerInvariant()[..USER_SUFFIX_LENGTH];
}
}
@@ -152,6 +152,18 @@ public static class InfrastructureLayerServices
// repackaged into another container, or re-encoded into another codec.
services.AddSingleton<IPlaybackFormatService, PlaybackFormatService>();
// Music playback: records the outcome of the ffmpeg probe, so a missing binary or encoder is reported as unavailable for the affected formats.
services.AddSingleton<TranscodingToolchainStatus>();
// Music playback: produces the normalized (remuxed or transcoded) audio of a track with ffmpeg, caches it as fixed duration
// segments and serves it from the cache, bounded in concurrency, cancellable and capped in disk usage. The playback stream surface
// is its intended consumer; no API request path calls it yet.
services.AddSingleton<ITrackNormalizationService, TrackNormalizationService>();
// Music playback: owns the normalized audio cache lifecycle and verifies the ffmpeg encoders at startup, so a missing or changed toolchain
// is recorded and reported as unavailable for the affected formats instead of surfacing as a per track playback failure.
services.AddHostedService<TranscodingStartupInitializer>();
// 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>();
@@ -70,6 +70,11 @@ public static class SharedConfiguration
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<TranscodingSettingsDto>()
.Bind(configuration.GetRequiredSection(TranscodingSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
return services;
}
}
@@ -33,5 +33,18 @@ public static partial class Errors
public static Error ThemeMaxExpandedBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxExpandedBytesMustBePositive));
public static Error ThemeMaxSingleFileBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxSingleFileBytesMustBePositive));
public static Error ThemeMaxEntriesMustBePositive => Error.Validation(description: nameof(ThemeMaxEntriesMustBePositive));
public static Error TranscodingFfmpegPathCannotBeEmpty => Error.Validation(description: nameof(TranscodingFfmpegPathCannotBeEmpty));
public static Error TranscodingMaxConcurrentJobsMustBePositive => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsMustBePositive));
public static Error TranscodingMaxConcurrentJobsIsTooLarge => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsIsTooLarge));
public static Error TranscodingMaxCacheBytesMustBePositive => Error.Validation(description: nameof(TranscodingMaxCacheBytesMustBePositive));
public static Error TranscodingJobTimeoutMustBePositive => Error.Validation(description: nameof(TranscodingJobTimeoutMustBePositive));
public static Error TranscodingJobTimeoutIsTooLong => Error.Validation(description: nameof(TranscodingJobTimeoutIsTooLong));
public static Error TranscodingEvictionGraceSecondsMustBePositive => Error.Validation(description: nameof(TranscodingEvictionGraceSecondsMustBePositive));
public static Error TranscodingEvictionGraceSecondsIsTooLong => Error.Validation(description: nameof(TranscodingEvictionGraceSecondsIsTooLong));
public static Error TranscodingCacheDirectoryIsInvalid => Error.Validation(description: nameof(TranscodingCacheDirectoryIsInvalid));
public static Error TranscodingCacheDirectoryIsInsideMediaRoot => Error.Validation(description: nameof(TranscodingCacheDirectoryIsInsideMediaRoot));
public static Error TranscodingCacheDirectoryContainsMediaRoot => Error.Validation(description: nameof(TranscodingCacheDirectoryContainsMediaRoot));
public static Error TranscodingCacheDirectoryIsUnsafeLocation => Error.Validation(description: nameof(TranscodingCacheDirectoryIsUnsafeLocation));
public static Error TranscodingDefaultCacheDirectoryIsInsideMediaRoot => Error.Validation(description: nameof(TranscodingDefaultCacheDirectoryIsInsideMediaRoot));
}
}
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.Configuration;
/// <summary>
/// Data transfer object for deserializing the settings of the audio normalization pipeline.
/// </summary>
[DebuggerDisplay("Section name: {SECTION_NAME}")]
public sealed class TranscodingSettingsDto
{
public const string SECTION_NAME = "TranscodingSettings";
/// <summary>
/// Gets or sets the file name or path of the ffmpeg binary, relative to the process search path when not rooted.
/// </summary>
public string FfmpegPath { get; set; } = "ffmpeg";
/// <summary>
/// Gets or sets the maximum number of normalization jobs that may run at the same time.
/// </summary>
public int MaxConcurrentJobs { get; set; } = 2;
/// <summary>
/// Gets or sets the maximum total size of the normalized audio cache, in bytes.
/// </summary>
public long MaxCacheBytes { get; set; } = 2L * 1024 * 1024 * 1024;
/// <summary>
/// Gets or sets the maximum duration of a single normalization job, in seconds, after which the job is stopped.
/// </summary>
public int JobTimeoutSeconds { get; set; } = 900;
/// <summary>
/// Gets or sets the period, in seconds, during which a cache entry that was just produced or served is protected from eviction.
/// </summary>
public int EvictionGraceSeconds { get; set; } = 120;
/// <summary>
/// Gets or sets the directory where normalized audio is cached, relative to the API base directory when not rooted. When absent or empty, a
/// private directory under the system temporary directory is used.
/// </summary>
public string? CacheDirectory { get; set; }
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Describes how a single container and codec combination of the audio normalization pipeline is muxed and, when it has to be re-encoded, encoded.
/// </summary>
/// <param name="Container">The canonical container of the delivered audio.</param>
/// <param name="Codec">The canonical codec of the delivered audio.</param>
/// <param name="MuxerName">The name of the ffmpeg muxer that writes the container.</param>
/// <param name="FileExtension">The file extension of a single segment, including the leading dot.</param>
/// <param name="EncoderName">The name of the ffmpeg encoder used when the audio is transcoded.</param>
/// <param name="IsLossless">Whether the codec is lossless, in which case an encoder bitrate cap does not apply.</param>
[DebuggerDisplay("Container: {Container} Codec: {Codec} Muxer: {MuxerName}")]
internal sealed record NormalizedAudioFormatDto(
string Container,
string Codec,
string MuxerName,
string FileExtension,
string EncoderName,
bool IsLossless
);
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents the persisted description of a cached normalized track, which lets the cache be read without parsing the ffmpeg output again.
/// </summary>
/// <param name="Version">The version of the index layout, so an index written by an older version is treated as a cache miss.</param>
/// <param name="TrackId">The Id of the track the cached audio belongs to, so a cache handle can be authorized against the track of the route.</param>
/// <param name="Mode">The way the audio is delivered, which is a remux or a transcode.</param>
/// <param name="Container">The container of the delivered audio.</param>
/// <param name="Codec">The codec of the delivered audio.</param>
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="DurationInSeconds">
/// The duration of the produced and cached audio, in seconds, rounded up to the next second. It is the produced end rather than the probed duration, so
/// it always covers every produced segment.
/// </param>
/// <param name="Segments">The segments that make up the delivered audio, in playback order.</param>
[DebuggerDisplay("TrackId: {TrackId} Container: {Container} Codec: {Codec} Segments: {Segments.Count}")]
// The record is internal, so its primary constructor is not public. Marking it tells System.Text.Json to use it for the on disk index anyway.
[method: JsonConstructor]
internal sealed record NormalizedTrackIndexDto(
int Version,
Guid TrackId,
PlaybackDeliveryMode Mode,
string Container,
string Codec,
int SegmentDurationSeconds,
int DurationInSeconds,
IReadOnlyList<NormalizedTrackSegmentIndexDto> Segments
);
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents the persisted description of a single segment of a cached normalized track.
/// </summary>
/// <param name="Index">The zero based position of the segment in the delivered audio.</param>
/// <param name="StartSeconds">The time, in seconds from the start of the track, at which the segment starts.</param>
/// <param name="DurationSeconds">The duration of the segment, in seconds.</param>
/// <param name="FileName">The file name of the segment inside the cache entry.</param>
/// <param name="Length">The length of the segment, in bytes.</param>
[DebuggerDisplay("Index: {Index} StartSeconds: {StartSeconds} FileName: {FileName}")]
// The record is internal, so its primary constructor is not public. Marking it tells System.Text.Json to use it for the on disk index anyway.
[method: JsonConstructor]
internal sealed record NormalizedTrackSegmentIndexDto(
int Index,
decimal StartSeconds,
decimal DurationSeconds,
string FileName,
long Length
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents a single entry of the normalized audio cache, used to enforce the cache size limit.
/// </summary>
/// <param name="Path">The absolute path of the directory that holds the entry.</param>
/// <param name="Size">The total size of the entry, in bytes.</param>
/// <param name="LastUsedUtc">The date and time, in UTC, when the entry was last produced or served.</param>
/// <param name="ProducedAtUtc">The date and time, in UTC, when the entry was produced or, for an entry found on disk, the earliest representable time.</param>
[DebuggerDisplay("Path: {Path} Size: {Size}")]
internal sealed record TranscodingCacheEntryDto(
string Path,
long Size,
DateTime LastUsedUtc,
DateTime ProducedAtUtc
);
@@ -0,0 +1,291 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Common.Caching;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the TranscodingSettings application configuration settings section.
/// </summary>
public class TranscodingSettingsDtoValidator : AbstractValidator<TranscodingSettingsDto>
{
private const int MAX_CONCURRENT_JOBS = 64;
private const int MAX_JOB_TIMEOUT_SECONDS = 86400;
private const int MAX_EVICTION_GRACE_SECONDS = 86400;
private static readonly StringComparison s_pathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
private readonly IPathService _pathService;
private readonly string _mediaRootDirectory;
private readonly string[] _conflictingDirectories;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingSettingsDtoValidator"/> class.
/// </summary>
/// <param name="mediaSettings">The media settings, used to reject a cache directory that would be served by the media route.</param>
/// <param name="pluginsSettings">The plugin settings, used to reject a cache directory that would overlap the plugins directory.</param>
/// <param name="pathService">The service used to check whether two directories overlap.</param>
public TranscodingSettingsDtoValidator(IOptions<MediaSettingsDto> mediaSettings, IOptions<PluginsSettingsDto> pluginsSettings, IPathService pathService)
{
_pathService = pathService;
_mediaRootDirectory = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, mediaSettings.Value.RootDirectory));
_conflictingDirectories = BuildConflictingDirectories(pluginsSettings.Value);
RuleFor(settings => settings.FfmpegPath)
.NotEmpty()
.WithError(Errors.Errors.Configuration.TranscodingFfmpegPathCannotBeEmpty);
RuleFor(settings => settings.MaxConcurrentJobs)
.GreaterThan(0)
.WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive);
RuleFor(settings => settings.MaxConcurrentJobs)
.Must(maxConcurrentJobs => maxConcurrentJobs <= MAX_CONCURRENT_JOBS)
.WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge);
RuleFor(settings => settings.MaxCacheBytes)
.GreaterThan(0)
.WithError(Errors.Errors.Configuration.TranscodingMaxCacheBytesMustBePositive);
RuleFor(settings => settings.JobTimeoutSeconds)
.GreaterThan(0)
.WithError(Errors.Errors.Configuration.TranscodingJobTimeoutMustBePositive);
// CancellationTokenSource(TimeSpan) cannot represent an arbitrarily large delay, and a job that may run for days is a configuration error.
RuleFor(settings => settings.JobTimeoutSeconds)
.Must(jobTimeoutSeconds => jobTimeoutSeconds <= MAX_JOB_TIMEOUT_SECONDS)
.WithError(Errors.Errors.Configuration.TranscodingJobTimeoutIsTooLong);
RuleFor(settings => settings.EvictionGraceSeconds)
.GreaterThan(0)
.WithError(Errors.Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive);
RuleFor(settings => settings.EvictionGraceSeconds)
.Must(evictionGraceSeconds => evictionGraceSeconds <= MAX_EVICTION_GRACE_SECONDS)
.WithError(Errors.Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong);
RuleFor(settings => settings.CacheDirectory)
.Must(BeAValidDirectoryPath)
.WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsInvalid)
.When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory));
// A malformed path is reported by the rule above, so the rules below must not try to resolve it: Path.GetFullPath would throw and abort
// startup with a raw exception instead of a configuration error.
RuleFor(settings => settings.CacheDirectory)
.Must(BeConfiguredDirectoryOutsideMediaRoot)
.WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot)
.When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory));
// The reverse containment is just as destructive: a cache directory that contains the media root would delete the media when it is cleaned.
RuleFor(settings => settings.CacheDirectory)
.Must(BeConfiguredDirectoryNotContainingMediaRoot)
.WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot)
.When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory));
// The cache directory is cleaned at startup, so it must never resolve to a location whose cleanup would damage the application or the host.
RuleFor(settings => settings.CacheDirectory)
.Must(BeInSafeLocation)
.WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation)
.When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory));
// When no directory is configured the service uses a per-user directory under the system temporary directory. A failure of that default is a
// different configuration problem from a CacheDirectory the operator chose, so it is reported with its own error and never names CacheDirectory.
RuleFor(settings => settings.CacheDirectory)
.Must(_ => BeDefaultDirectoryOutsideMediaRoot())
.WithError(Errors.Errors.Configuration.TranscodingDefaultCacheDirectoryIsInsideMediaRoot)
.When(settings => string.IsNullOrWhiteSpace(settings.CacheDirectory));
}
/// <summary>
/// Checks whether the provided cache directory is a path the file system accepts.
/// </summary>
/// <param name="cacheDirectory">The configured cache directory, or <see langword="null"/> when the default is used.</param>
/// <returns><see langword="true"/> when the path is valid, otherwise <see langword="false"/>.</returns>
private static bool BeAValidDirectoryPath(string? cacheDirectory)
{
if (string.IsNullOrWhiteSpace(cacheDirectory))
return true;
try
{
Path.GetFullPath(cacheDirectory);
return true;
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
return false;
}
}
/// <summary>
/// Checks whether the configured cache directory is outside the media root, which is served without authentication at the media route.
/// </summary>
/// <param name="cacheDirectory">The configured cache directory. It is already known to be a valid path.</param>
/// <returns><see langword="true"/> when the cache is outside the media root, otherwise <see langword="false"/>.</returns>
private bool BeConfiguredDirectoryOutsideMediaRoot(string? cacheDirectory)
{
try
{
return !IsSameOrWithin(TranscodingCachePaths.GetRootDirectory(cacheDirectory), _mediaRootDirectory);
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception.
return true;
}
}
/// <summary>
/// Checks whether the configured cache directory does not contain the media root.
/// </summary>
/// <param name="cacheDirectory">The configured cache directory. It is already known to be a valid path.</param>
/// <returns><see langword="true"/> when the cache does not contain the media root, otherwise <see langword="false"/>.</returns>
private bool BeConfiguredDirectoryNotContainingMediaRoot(string? cacheDirectory)
{
try
{
return !IsSameOrWithin(_mediaRootDirectory, TranscodingCachePaths.GetRootDirectory(cacheDirectory));
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception.
return true;
}
}
/// <summary>
/// Checks whether the configured cache directory is a location whose cleanup cannot damage the application or the host.
/// </summary>
/// <param name="cacheDirectory">The configured cache directory. It is already known to be a valid path.</param>
/// <returns><see langword="true"/> when the location is safe, otherwise <see langword="false"/>.</returns>
private bool BeInSafeLocation(string? cacheDirectory)
{
try
{
string resolvedCacheDirectory = TranscodingCachePaths.GetRootDirectory(cacheDirectory);
if (IsFileSystemRoot(resolvedCacheDirectory))
return false;
// The cache must never be the application base directory or one of its ancestors, because cleaning it would remove the application itself.
if (IsSameOrWithin(AppContext.BaseDirectory, resolvedCacheDirectory))
return false;
// The logs and plugins directories are managed by the application, so the cache must not overlap them in either direction.
foreach (string conflictingDirectory in _conflictingDirectories)
if (IsSameOrWithin(resolvedCacheDirectory, conflictingDirectory) || IsSameOrWithin(conflictingDirectory, resolvedCacheDirectory))
return false;
return true;
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception.
return true;
}
}
/// <summary>
/// Checks whether the default cache directory, used when none is configured, is outside the media root.
/// </summary>
/// <returns><see langword="true"/> when the default cache is outside the media root, otherwise <see langword="false"/>.</returns>
private bool BeDefaultDirectoryOutsideMediaRoot()
{
try
{
return !IsSameOrWithin(TranscodingCachePaths.GetRootDirectory(configuredDirectory: null), _mediaRootDirectory);
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// A temporary directory that cannot be resolved is reported by the startup initializer; it is not a media root containment error.
return true;
}
}
/// <summary>
/// Checks whether a path is equal to, or is located inside, another path.
/// </summary>
/// <param name="path">The path to check.</param>
/// <param name="parentPath">The path that must contain, or be equal to, the checked path.</param>
/// <returns><see langword="true"/> when the path is equal to or inside the parent path, otherwise <see langword="false"/>.</returns>
private bool IsSameOrWithin(string path, string parentPath)
{
string normalizedPath = NormalizePath(path);
string normalizedParentPath = NormalizePath(parentPath);
if (string.Equals(normalizedPath, normalizedParentPath, s_pathComparison))
return true;
return _pathService.IsPathWithin(normalizedPath, normalizedParentPath);
}
/// <summary>
/// Checks whether a path is the root of a file system, or of a volume, instead of a directory inside it.
/// </summary>
/// <param name="path">The absolute path to check.</param>
/// <returns><see langword="true"/> when the path is a file system root, otherwise <see langword="false"/>.</returns>
private static bool IsFileSystemRoot(string path)
{
string normalizedPath = NormalizePath(path);
string? rootPath = Path.GetPathRoot(normalizedPath);
return rootPath is not null && string.Equals(normalizedPath, rootPath, s_pathComparison);
}
/// <summary>
/// Gets the full form of a path, without a trailing separator unless the path itself is the root of a file system or volume.
/// </summary>
/// <param name="path">The path to normalize.</param>
/// <returns>The normalized absolute path.</returns>
private static string NormalizePath(string path)
{
string fullPath = Path.GetFullPath(path);
string? rootPath = Path.GetPathRoot(fullPath);
// The root must keep its trailing separator, otherwise a drive root such as "C:\" degenerates into the drive relative path "C:".
if (rootPath is null || fullPath.Length <= rootPath.Length)
return fullPath;
return fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
/// <summary>
/// Gets the directories that the cache directory must never overlap: the logs directory and the plugins directory.
/// </summary>
/// <param name="pluginsSettings">The plugin settings, whose directory is resolved against the application base directory.</param>
/// <returns>The absolute paths of the directories the cache must not overlap.</returns>
private static string[] BuildConflictingDirectories(PluginsSettingsDto pluginsSettings)
{
List<string> conflictingDirectories = [];
if (!string.IsNullOrWhiteSpace(pluginsSettings.Directory))
AddConflictingDirectory(conflictingDirectories, Path.Combine(AppContext.BaseDirectory, pluginsSettings.Directory));
// The local log path is always the logs directory of the application base directory; the environment variable and the container path cover
// the other two ways the log path is selected at startup.
AddConflictingDirectory(conflictingDirectories, Path.Combine(AppContext.BaseDirectory, "logs"));
AddConflictingDirectory(conflictingDirectories, Environment.GetEnvironmentVariable("LOG_PATH"));
if (string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase))
AddConflictingDirectory(conflictingDirectories, "/logs");
return [.. conflictingDirectories];
}
/// <summary>
/// Adds the full form of a directory to the list of conflicting directories, when it can be resolved and is not already listed.
/// </summary>
/// <param name="conflictingDirectories">The list of conflicting directories to add to.</param>
/// <param name="directory">The directory to add, or <see langword="null"/> when it is not configured.</param>
private static void AddConflictingDirectory(List<string> conflictingDirectories, string? directory)
{
if (string.IsNullOrWhiteSpace(directory))
return;
try
{
string resolvedDirectory = NormalizePath(directory);
if (!conflictingDirectories.Contains(resolvedDirectory, StringComparer.FromComparison(s_pathComparison)))
conflictingDirectories.Add(resolvedDirectory);
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// A malformed log path is reported by the logging configuration, not by the cache validation.
}
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// The single catalog of the audio formats the server can produce, shared by the playback delivery decision and the audio normalization pipeline.
/// </summary>
/// <remarks>
/// The order of <see cref="Formats"/> is significant: the first appearance of a codec is its transcode preference, and the order of the containers of a
/// codec is the order in which the server prefers to produce it. Both the delivery decision and the normalization pipeline derive their tables from this
/// catalog, so a format can never be promised in a manifest without also being implementable by the pipeline.
/// </remarks>
internal static class PlaybackFormatCatalog
{
/// <summary>
/// Gets the formats the server can produce, in the order of the transcode codec preference and, within a codec, of the container preference.
/// </summary>
public static IReadOnlyList<NormalizedAudioFormatDto> Formats { get; } =
[
new("MP4", "AAC", "mp4", ".m4a", "aac", false),
new("AAC", "AAC", "adts", ".aac", "aac", false),
new("OGG", "OPUS", "ogg", ".ogg", "libopus", false),
new("MP3", "MP3", "mp3", ".mp3", "libmp3lame", false),
new("OGG", "VORBIS", "ogg", ".ogg", "libvorbis", false),
new("FLAC", "FLAC", "flac", ".flac", "flac", true),
new("WAV", "PCM", "wav", ".wav", "pcm_s16le", true)
];
/// <summary>
/// Gets the formats the server can produce, keyed by their canonical container and codec pair.
/// </summary>
public static FrozenDictionary<string, NormalizedAudioFormatDto> FormatsByPair { get; } = BuildFormatsByPair();
/// <summary>
/// Gets the containers the server can produce each codec in, in order of preference.
/// </summary>
public static FrozenDictionary<string, IReadOnlyList<string>> ProducibleContainersByCodec { get; } = BuildProducibleContainersByCodec();
/// <summary>
/// Gets the codecs the server can produce, in order of preference.
/// </summary>
public static IReadOnlyList<string> TranscodeCodecPreference { get; } = BuildTranscodeCodecPreference();
/// <summary>
/// Builds the key of a canonical container and codec pair.
/// </summary>
/// <param name="container">The container of the audio.</param>
/// <param name="codec">The codec of the audio.</param>
/// <returns>The canonical key of the pair.</returns>
public static string BuildPairKey(string container, string codec)
{
return (container ?? string.Empty).Trim().ToUpperInvariant() + "/" + (codec ?? string.Empty).Trim().ToUpperInvariant();
}
/// <summary>
/// Builds the map of the producible formats, keyed by their canonical container and codec pair.
/// </summary>
/// <returns>The producible formats, keyed by their canonical pair.</returns>
private static FrozenDictionary<string, NormalizedAudioFormatDto> BuildFormatsByPair()
{
return Formats.ToFrozenDictionary(format => BuildPairKey(format.Container, format.Codec), StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Builds the map of the containers the server can produce each codec in, preserving the order of the catalog.
/// </summary>
/// <returns>The containers of each producible codec, in order of preference.</returns>
private static FrozenDictionary<string, IReadOnlyList<string>> BuildProducibleContainersByCodec()
{
Dictionary<string, List<string>> containersByCodec = new(StringComparer.OrdinalIgnoreCase);
foreach (NormalizedAudioFormatDto format in Formats)
{
if (!containersByCodec.TryGetValue(format.Codec, out List<string>? containers))
{
containers = [];
containersByCodec[format.Codec] = containers;
}
if (!containers.Contains(format.Container, StringComparer.OrdinalIgnoreCase))
containers.Add(format.Container);
}
return containersByCodec.ToFrozenDictionary(entry => entry.Key, entry => (IReadOnlyList<string>)entry.Value, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Builds the codecs the server can produce, preserving the order in which they first appear in the catalog.
/// </summary>
/// <returns>The producible codecs, in order of preference.</returns>
private static IReadOnlyList<string> BuildTranscodeCodecPreference()
{
List<string> codecs = [];
foreach (NormalizedAudioFormatDto format in Formats)
if (!codecs.Contains(format.Codec, StringComparer.OrdinalIgnoreCase))
codecs.Add(format.Codec);
return codecs;
}
}
@@ -5,7 +5,6 @@ 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
@@ -25,22 +24,6 @@ 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>
@@ -101,7 +84,7 @@ internal sealed class PlaybackFormatService : IPlaybackFormatService
/// </returns>
private static PlaybackCapabilityDto? SelectFormatForCodec(IReadOnlyList<PlaybackCapabilityDto> capabilities, string codec)
{
if (codec.Length == 0 || !s_producibleContainersByCodec.TryGetValue(codec, out IReadOnlyList<string>? producibleContainers))
if (codec.Length == 0 || !PlaybackFormatCatalog.ProducibleContainersByCodec.TryGetValue(codec, out IReadOnlyList<string>? producibleContainers))
return null;
IReadOnlyList<string> advertisedContainers = [.. capabilities
@@ -124,7 +107,7 @@ internal sealed class PlaybackFormatService : IPlaybackFormatService
/// <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)
foreach (string preferredCodec in PlaybackFormatCatalog.TranscodeCodecPreference)
{
PlaybackCapabilityDto? format = SelectFormatForCodec(capabilities, preferredCodec);
if (format is not null)
@@ -0,0 +1,591 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Caching;
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Coordinates the process wide size accounting, eviction and reader protection of the normalized audio cache.
/// </summary>
/// <remarks>
/// Every cached entry and every running normalization job of a cache root is accounted for under one lock, so the cache size limit is a global limit
/// instead of a per job limit. An entry is protected from eviction while a reader holds a lease on it, and for a grace period after it was produced or
/// last served, so an entry that a request is about to read is never deleted by another job. Replacing and registering a produced entry is atomic under
/// the same lock, so an eviction can never delete a freshly published entry. Directories are never deleted under the lock: an entry that is evicted or
/// replaced is renamed to a unique tombstone under the lock and deleted by a background sweeper, so serving a segment or opening a manifest never waits
/// for a recursive delete. The size limit is enforced against live entries: a tombstone occupies disk until the sweeper removes it. The coordinator is
/// shared by every service instance of the process that uses the same cache root.
/// </remarks>
internal sealed class TranscodingCacheCoordinator
{
private static readonly ConcurrentDictionary<string, TranscodingCacheCoordinator> s_coordinators = new(StringComparer.Ordinal);
private static readonly Lock s_registrySync = new();
private readonly Lock _sync = new();
private readonly string _cacheRoot;
private readonly Dictionary<string, TranscodingCacheEntryDto> _entries = new(StringComparer.Ordinal);
private readonly Dictionary<string, long> _reservations = new(StringComparer.Ordinal);
private readonly Dictionary<string, int> _readerLeaseCounts = new(StringComparer.Ordinal);
// Read and written by request threads without _sync, so the index cache is a concurrent dictionary while the accounting dictionaries are guarded by _sync.
private readonly ConcurrentDictionary<string, NormalizedTrackIndexDto> _indexCache = new(StringComparer.Ordinal);
// Entries that were over capacity but still leased. The last lease release hands them to the sweeper.
private readonly HashSet<string> _pendingEvictions = new(StringComparer.Ordinal);
// Tombstones are consumed by one background reader, so a recursive delete never runs under _sync.
private readonly Channel<string> _deletionQueue = Channel.CreateUnbounded<string>(new UnboundedChannelOptions { SingleReader = true });
// The value is unused. Lazy is the once-only gate: the first caller runs the cache walk outside _sync and every other caller waits for it.
private readonly Lazy<bool> _initialization;
private int _referenceCount;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheCoordinator"/> class.
/// </summary>
/// <param name="cacheRoot">The absolute path of the cache root the coordinator accounts for.</param>
private TranscodingCacheCoordinator(string cacheRoot)
{
_cacheRoot = cacheRoot;
_initialization = new Lazy<bool>(InitializeCore, LazyThreadSafetyMode.ExecutionAndPublication);
_ = Task.Run(ProcessDeletionQueueAsync);
}
/// <summary>
/// Acquires the coordinator of a cache root, which is shared by every service instance of the process that uses the same root.
/// </summary>
/// <param name="cacheRoot">The absolute path of the cache root.</param>
/// <returns>The coordinator of the cache root. The caller must call <see cref="Release"/> when it no longer uses it.</returns>
public static TranscodingCacheCoordinator AcquireForRoot(string cacheRoot)
{
string normalizedRoot = Path.GetFullPath(cacheRoot);
lock (s_registrySync)
{
// The registry is process wide because two service instances that use the same cache root must share the same size and lease accounting.
// The reference count keeps the coordinator alive until the last service instance is disposed.
if (!s_coordinators.TryGetValue(normalizedRoot, out TranscodingCacheCoordinator? coordinator))
{
coordinator = new TranscodingCacheCoordinator(normalizedRoot);
s_coordinators[normalizedRoot] = coordinator;
}
coordinator._referenceCount++;
return coordinator;
}
}
/// <summary>
/// Releases the caller's use of the coordinator, removing it from the process registry when the last caller releases it.
/// </summary>
public void Release()
{
bool isUnused;
lock (s_registrySync)
{
if (_referenceCount > 0)
_referenceCount--;
isUnused = _referenceCount == 0;
if (isUnused)
s_coordinators.Remove(_cacheRoot, out _);
}
if (!isUnused)
return;
lock (_sync)
{
_entries.Clear();
_reservations.Clear();
_readerLeaseCounts.Clear();
_pendingEvictions.Clear();
_indexCache.Clear();
}
// The sweeper drains the tombstones it already owns and then stops. A deletion that is still in flight is finished, and a tombstone left by a
// deletion that cannot complete is removed by the startup cleanup.
_deletionQueue.Writer.TryComplete();
}
/// <summary>
/// Checks whether a value is a well formed opaque cache identifier.
/// </summary>
/// <param name="cacheId">The value to check.</param>
/// <returns><see langword="true"/> when the value is a well formed cache identifier, otherwise <see langword="false"/>.</returns>
public static bool IsValidCacheId(string cacheId)
{
return TranscodingCachePaths.IsValidCacheId(cacheId);
}
/// <summary>
/// Reserves capacity for the output of a normalization job, after evicting the entries that may be evicted to make room for it.
/// </summary>
/// <param name="requestedBytes">The estimated size of the output of the job, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
/// <param name="gracePeriod">The period during which a recently produced or served entry is protected from eviction.</param>
/// <param name="reservation">The reservation of the job, when capacity could be reserved.</param>
/// <returns><see langword="true"/> when capacity could be reserved, otherwise <see langword="false"/>.</returns>
public bool TryReserve(long requestedBytes, long maxCacheBytes, TimeSpan gracePeriod, out TranscodingCacheReservation? reservation)
{
reservation = null;
if (requestedBytes <= 0 || maxCacheBytes <= 0)
return false;
EnsureInitialized();
lock (_sync)
{
long currentSize = GetTotalSize();
if (requestedBytes > maxCacheBytes || !TryMakeRoom(requestedBytes, currentSize, excludedCacheId: null, maxCacheBytes, gracePeriod))
return false;
string reservationId = Guid.NewGuid().ToString("N");
_reservations[reservationId] = requestedBytes;
reservation = new TranscodingCacheReservation(this, reservationId);
return true;
}
}
/// <summary>
/// Grows the reservation of a running job to the number of bytes it has actually written, after evicting entries when it has to grow.
/// </summary>
/// <param name="reservationId">The identifier of the reservation.</param>
/// <param name="actualBytes">The number of bytes the job has actually written, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
/// <param name="gracePeriod">The period during which a recently produced or served entry is protected from eviction.</param>
/// <returns><see langword="true"/> when the reservation covers the actual size, otherwise <see langword="false"/>.</returns>
public bool TryGrow(string reservationId, long actualBytes, long maxCacheBytes, TimeSpan gracePeriod)
{
if (actualBytes < 0)
return false;
EnsureInitialized();
lock (_sync)
{
if (!_reservations.TryGetValue(reservationId, out long reservedBytes))
return false;
// A reservation is never shrunk while the job runs: a size of zero read before the first byte is written, or a size that fluctuates
// while a file is being appended, must not hand the reserved capacity to another job that the running job then cannot reclaim.
if (actualBytes <= reservedBytes)
return true;
if (actualBytes > maxCacheBytes)
return false;
long currentSize = GetTotalSize();
long requiredAdditionalBytes = actualBytes - reservedBytes;
if (!TryMakeRoom(requiredAdditionalBytes, currentSize, excludedCacheId: null, maxCacheBytes, gracePeriod))
return false;
_reservations[reservationId] = actualBytes;
return true;
}
}
/// <summary>
/// Publishes the cache entry a finished job produced, replacing any previous entry for the same identifier, and enforces the cache size limit.
/// </summary>
/// <param name="reservationId">The identifier of the reservation.</param>
/// <param name="cacheId">The identifier of the produced cache entry.</param>
/// <param name="temporaryPath">The temporary directory that holds the complete produced entry.</param>
/// <param name="size">The total size of the produced cache entry, in bytes.</param>
/// <param name="index">The validated index of the produced cache entry.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
/// <param name="gracePeriod">The period during which a recently produced or served entry is protected from eviction.</param>
/// <param name="isKeptOverCapacity">
/// <see langword="true"/> when the produced entry still exceeds the cache limit after every unprotected entry was detached, so it is kept readable and
/// becomes eligible for eviction later. The caller should report the production as successful and log the over-budget state.
/// </param>
/// <param name="isEntryInUse">
/// <see langword="true"/> when a reader still holds the previous entry of the same cache identifier, so the replacement was not attempted and the
/// caller should report a retryable failure instead of a production failure.
/// </param>
/// <returns>
/// <see langword="true"/> when the produced entry is readable and may be served, otherwise <see langword="false"/> when it was not published.
/// </returns>
public bool TryPublish(string reservationId, string cacheId, string temporaryPath, long size, NormalizedTrackIndexDto index, long maxCacheBytes, TimeSpan gracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse)
{
isKeptOverCapacity = false;
isEntryInUse = false;
EnsureInitialized();
lock (_sync)
{
// The reservation is consumed whether or not the entry is published, because the caller never releases it after this call.
_reservations.Remove(reservationId);
// The previous directory cannot be replaced while a reader holds it on every platform, so the production is reported as retryable and the
// previous entry stays intact. The next request retries the production after the reader is gone.
if (IsLeased(cacheId))
{
isEntryInUse = true;
return false;
}
string cachePath = Path.Combine(_cacheRoot, cacheId);
if (_entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? existingEntry))
{
if (!TryDetachEntryForDeletion(cacheId, existingEntry))
return false;
}
else if (!TryMoveToDeletion(cachePath))
return false;
_indexCache.TryRemove(cacheId, out _);
_pendingEvictions.Remove(cacheId);
try
{
Directory.Move(temporaryPath, cachePath);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return false;
}
// Defense in depth against a directory that an external actor removed between the move and the registration.
if (!Directory.Exists(cachePath))
return false;
_entries[cacheId] = new TranscodingCacheEntryDto(cachePath, size, DateTime.UtcNow, DateTime.UtcNow);
_indexCache[cacheId] = index;
long currentSize = GetTotalSize();
if (currentSize <= maxCacheBytes)
return true;
if (TryMakeRoom(0, currentSize, cacheId, maxCacheBytes, gracePeriod))
return true;
// The entry does not fit even after every other unprotected entry was detached. It is kept readable and becomes eligible for eviction once
// its grace period ends, so a production that already consumed a full job is not discarded because the estimate was exceeded.
isKeptOverCapacity = true;
return true;
}
}
/// <summary>
/// Releases the reservation of a job that did not produce a cache entry.
/// </summary>
/// <param name="reservationId">The identifier of the reservation.</param>
public void ReleaseReservation(string reservationId)
{
lock (_sync)
_reservations.Remove(reservationId);
}
/// <summary>
/// Records that a cache entry was served, so that the least recently used eviction and the eviction grace period keep it for longer.
/// </summary>
/// <param name="cacheId">The identifier of the cache entry.</param>
/// <param name="throttleInterval">
/// The minimum interval between two writes of the last use time. A value smaller than the eviction grace period keeps an actively used entry protected.
/// </param>
public void Touch(string cacheId, TimeSpan throttleInterval)
{
EnsureInitialized();
lock (_sync)
{
if (!_entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? entry))
return;
DateTime nowUtc = DateTime.UtcNow;
// A stream opens a segment every few seconds, so writing the last use time on every request would needlessly serialize the coordinator.
if (nowUtc - entry.LastUsedUtc < throttleInterval)
return;
_entries[cacheId] = entry with { LastUsedUtc = nowUtc };
}
}
/// <summary>
/// Acquires a lease that prevents a cache entry from being evicted while a reader holds it.
/// </summary>
/// <param name="cacheId">The identifier of the cache entry.</param>
/// <returns>The lease, which must be disposed when the reader is done with the entry.</returns>
public TranscodingCacheReaderLease AcquireReaderLease(string cacheId)
{
EnsureInitialized();
lock (_sync)
_readerLeaseCounts[cacheId] = _readerLeaseCounts.TryGetValue(cacheId, out int leaseCount) ? leaseCount + 1 : 1;
return new TranscodingCacheReaderLease(this, cacheId);
}
/// <summary>
/// Gets the validated index of a cache entry, when it was already read and validated by this process.
/// </summary>
/// <param name="cacheId">The identifier of the cache entry.</param>
/// <param name="index">The validated index of the cache entry, when it is cached.</param>
/// <returns><see langword="true"/> when the validated index is cached, otherwise <see langword="false"/>.</returns>
public bool TryGetIndex(string cacheId, out NormalizedTrackIndexDto? index)
{
return _indexCache.TryGetValue(cacheId, out index);
}
/// <summary>
/// Caches the validated index of a cache entry, so serving its segments does not re-read and re-validate the whole index on every request.
/// </summary>
/// <param name="cacheId">The identifier of the cache entry.</param>
/// <param name="index">The validated index of the cache entry.</param>
public void SetIndex(string cacheId, NormalizedTrackIndexDto index)
{
_indexCache[cacheId] = index;
}
/// <summary>
/// Releases a lease that a reader held on a cache entry.
/// </summary>
/// <param name="cacheId">The identifier of the cache entry.</param>
internal void ReleaseReaderLease(string cacheId)
{
lock (_sync)
{
if (!_readerLeaseCounts.TryGetValue(cacheId, out int leaseCount))
return;
if (leaseCount > 1)
{
_readerLeaseCounts[cacheId] = leaseCount - 1;
return;
}
_readerLeaseCounts.Remove(cacheId);
// An entry that could not be evicted while a reader was using it is detached only after the last reader is gone. The actual deletion is
// performed by the sweeper, outside this lock, so releasing a segment stream never waits for a recursive delete.
if (_pendingEvictions.Contains(cacheId) && _entries.TryGetValue(cacheId, out TranscodingCacheEntryDto? entry))
{
_pendingEvictions.Remove(cacheId);
if (!TryDetachEntryForDeletion(cacheId, entry))
_pendingEvictions.Add(cacheId);
}
}
}
/// <summary>
/// Gets the total size of a directory, in bytes, without letting a file that disappears mid-walk discard the rest of the measurement.
/// </summary>
/// <param name="directoryPath">The directory whose size is computed.</param>
/// <returns>The total size of the directory, in bytes.</returns>
internal static long GetDirectorySize(string directoryPath)
{
long size = 0;
Stack<string> pendingDirectories = new();
pendingDirectories.Push(directoryPath);
while (pendingDirectories.Count > 0)
{
string currentDirectory = pendingDirectories.Pop();
try
{
using (IEnumerator<string> fileEnumerator = Directory.EnumerateFiles(currentDirectory).GetEnumerator())
{
while (true)
{
bool hasNextFile;
try
{
hasNextFile = fileEnumerator.MoveNext();
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
break;
}
if (!hasNextFile)
break;
try
{
size += new FileInfo(fileEnumerator.Current).Length;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A file that disappears between enumeration and its size read is not counted; the walk continues with the next one.
}
}
}
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A directory that cannot be opened is skipped; the rest of the cache is still measured.
}
try
{
using (IEnumerator<string> directoryEnumerator = Directory.EnumerateDirectories(currentDirectory).GetEnumerator())
{
while (true)
{
bool hasNextDirectory;
try
{
hasNextDirectory = directoryEnumerator.MoveNext();
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
break;
}
if (!hasNextDirectory)
break;
pendingDirectories.Push(directoryEnumerator.Current);
}
}
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A directory that cannot be enumerated is skipped; the rest of the cache is still measured.
}
}
return size;
}
/// <summary>
/// Runs the once-only initialization of the entries that already exist in the cache root, outside the coordinator lock.
/// </summary>
private void EnsureInitialized()
{
_ = _initialization.Value;
}
/// <summary>
/// Reads the entries that already exist in the cache root, so a cache that survived a restart is still accounted for.
/// </summary>
/// <returns><see langword="true"/> when the accounting was populated.</returns>
/// <remarks>
/// The walk of the cache root happens outside the coordinator lock, because it stats every file of every entry. The result is published under the lock,
/// so a request never blocks a manifest or a segment open behind the walk.
/// </remarks>
private bool InitializeCore()
{
Dictionary<string, TranscodingCacheEntryDto> entries = new(StringComparer.Ordinal);
List<string> tombstones = [];
if (Directory.Exists(_cacheRoot))
{
try
{
foreach (string directoryPath in Directory.EnumerateDirectories(_cacheRoot))
{
string cacheId = Path.GetFileName(directoryPath);
if (cacheId.StartsWith(TranscodingCachePaths.DELETION_DIRECTORY_PREFIX, StringComparison.Ordinal))
{
// A tombstone left by a previous coordinator of the same process is handed to the sweeper instead of being accounted for.
tombstones.Add(directoryPath);
continue;
}
if (!IsValidCacheId(cacheId))
continue;
entries[cacheId] = new TranscodingCacheEntryDto(directoryPath, GetDirectorySize(directoryPath), Directory.GetLastWriteTimeUtc(directoryPath), DateTime.MinValue);
}
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
// A cache that cannot be enumerated is treated as empty for this run instead of being retried on every request.
}
}
lock (_sync)
foreach (KeyValuePair<string, TranscodingCacheEntryDto> entry in entries)
_entries[entry.Key] = entry.Value;
foreach (string tombstonePath in tombstones)
_deletionQueue.Writer.TryWrite(tombstonePath);
return true;
}
/// <summary>
/// Gets the combined size of the cached entries and the reservations of the running jobs, in bytes.
/// </summary>
/// <returns>The combined size of the cached entries and the reservations, in bytes.</returns>
private long GetTotalSize()
{
long entriesSize = _entries.Values.Sum(entry => entry.Size);
long reservationsSize = _reservations.Values.Sum();
return entriesSize + reservationsSize;
}
/// <summary>
/// Detaches the least recently used unprotected entries until the required number of bytes fits under the cache size limit.
/// </summary>
/// <param name="requiredBytes">The number of additional bytes that must fit.</param>
/// <param name="currentSize">The current combined size of the entries and reservations, in bytes.</param>
/// <param name="excludedCacheId">The cache entry that must never be evicted by this pass, or <see langword="null"/> when none is excluded.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
/// <param name="gracePeriod">The period during which a recently produced or served entry is protected from eviction.</param>
/// <returns><see langword="true"/> when the required number of bytes fits, otherwise <see langword="false"/>.</returns>
private bool TryMakeRoom(long requiredBytes, long currentSize, string? excludedCacheId, long maxCacheBytes, TimeSpan gracePeriod)
{
if (currentSize + requiredBytes <= maxCacheBytes)
return true;
DateTime nowUtc = DateTime.UtcNow;
foreach (TranscodingCacheEntryDto entry in _entries.Values.OrderBy(entry => entry.LastUsedUtc).ToList())
{
string cacheId = Path.GetFileName(entry.Path);
if (string.Equals(cacheId, excludedCacheId, StringComparison.Ordinal))
continue;
DateTime lastActivityUtc = entry.LastUsedUtc > entry.ProducedAtUtc ? entry.LastUsedUtc : entry.ProducedAtUtc;
if (nowUtc - lastActivityUtc < gracePeriod)
continue;
if (IsLeased(cacheId))
{
// A reader holds the entry, so it is detached when the last lease is released instead of failing the deletion under the lock.
_pendingEvictions.Add(cacheId);
continue;
}
if (!TryDetachEntryForDeletion(cacheId, entry))
continue;
currentSize -= entry.Size;
if (currentSize + requiredBytes <= maxCacheBytes)
return true;
}
return currentSize + requiredBytes <= maxCacheBytes;
}
/// <summary>
/// Checks whether a reader currently holds a cache entry.
/// </summary>
/// <param name="cacheId">The identifier of the cache entry.</param>
/// <returns><see langword="true"/> when at least one reader holds the entry, otherwise <see langword="false"/>.</returns>
private bool IsLeased(string cacheId)
{
return _readerLeaseCounts.TryGetValue(cacheId, out int leaseCount) && leaseCount > 0;
}
/// <summary>
/// Removes an entry from the cache accounting and schedules its directory for deletion.
/// </summary>
/// <param name="cacheId">The identifier of the cache entry.</param>
/// <param name="entry">The entry to detach.</param>
/// <returns><see langword="true"/> when the entry was detached, otherwise <see langword="false"/> when its directory could not be renamed.</returns>
private bool TryDetachEntryForDeletion(string cacheId, TranscodingCacheEntryDto entry)
{
if (!TryMoveToDeletion(entry.Path))
return false;
_entries.Remove(cacheId);
_pendingEvictions.Remove(cacheId);
_indexCache.TryRemove(cacheId, out _);
return true;
}
/// <summary>
/// Moves a directory out of the live cache and schedules it for deletion.
/// </summary>
/// <param name="directoryPath">The directory to detach.</param>
/// <returns><see langword="true"/> when the directory was detached or no longer exists, otherwise <see langword="false"/>.</returns>
private bool TryMoveToDeletion(string directoryPath)
{
if (!Directory.Exists(directoryPath))
return true;
string deletionPath = Path.Combine(_cacheRoot, TranscodingCachePaths.DELETION_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N"));
try
{
// A rename is a metadata operation, so it stays fast under the lock even for an entry with thousands of segments.
Directory.Move(directoryPath, deletionPath);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return false;
}
// A tombstone that cannot be enqueued because the coordinator was released is removed by the startup cleanup.
_deletionQueue.Writer.TryWrite(deletionPath);
return true;
}
/// <summary>
/// Deletes the directories that were detached from the cache.
/// </summary>
private async Task ProcessDeletionQueueAsync()
{
await foreach (string directoryPath in _deletionQueue.Reader.ReadAllAsync().ConfigureAwait(false))
TranscodingCachePaths.TryDeleteDirectory(directoryPath);
}
}
@@ -0,0 +1,220 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// A read stream over a cached segment that keeps the reader lease of its cache entry until the stream is disposed.
/// </summary>
internal sealed class TranscodingCacheLeaseStream : Stream
{
private readonly Stream _innerStream;
private readonly TranscodingCacheReaderLease _lease;
private bool _isDisposed;
/// <summary>
/// Gets whether the stream supports reading.
/// </summary>
public override bool CanRead => _innerStream.CanRead;
/// <summary>
/// Gets whether the stream supports seeking.
/// </summary>
public override bool CanSeek => _innerStream.CanSeek;
/// <summary>
/// Gets whether the stream supports writing.
/// </summary>
public override bool CanWrite => _innerStream.CanWrite;
/// <summary>
/// Gets the length of the stream, in bytes.
/// </summary>
public override long Length => _innerStream.Length;
/// <summary>
/// Gets or sets the position within the stream.
/// </summary>
public override long Position
{
get { return _innerStream.Position; }
set { _innerStream.Position = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheLeaseStream"/> class.
/// </summary>
/// <param name="innerStream">The stream over the cached segment.</param>
/// <param name="lease">The reader lease that protects the cache entry of the segment.</param>
internal TranscodingCacheLeaseStream(Stream innerStream, TranscodingCacheReaderLease lease)
{
_innerStream = innerStream;
_lease = lease;
}
/// <summary>
/// Clears the buffers of the stream.
/// </summary>
public override void Flush()
{
_innerStream.Flush();
}
/// <summary>
/// Reads a block of bytes from the stream.
/// </summary>
/// <param name="buffer">The buffer to read into.</param>
/// <param name="offset">The offset in the buffer at which to start writing.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <returns>The number of bytes read.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
return _innerStream.Read(buffer, offset, count);
}
/// <summary>
/// Reads a block of bytes from the stream.
/// </summary>
/// <param name="buffer">The buffer to read into.</param>
/// <returns>The number of bytes read.</returns>
public override int Read(Span<byte> buffer)
{
return _innerStream.Read(buffer);
}
/// <summary>
/// Reads a block of bytes from the stream asynchronously.
/// </summary>
/// <param name="buffer">The buffer to read into.</param>
/// <param name="offset">The offset in the buffer at which to start writing.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The number of bytes read.</returns>
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _innerStream.ReadAsync(buffer, offset, count, cancellationToken);
}
/// <summary>
/// Reads a block of bytes from the stream asynchronously.
/// </summary>
/// <param name="buffer">The buffer to read into.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The number of bytes read.</returns>
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
return _innerStream.ReadAsync(buffer, cancellationToken);
}
/// <summary>
/// Sets the position within the stream.
/// </summary>
/// <param name="offset">The offset relative to <paramref name="origin"/>.</param>
/// <param name="origin">The reference point used to obtain the new position.</param>
/// <returns>The new position within the stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
return _innerStream.Seek(offset, origin);
}
/// <summary>
/// Sets the length of the stream.
/// </summary>
/// <param name="value">The new length of the stream, in bytes.</param>
public override void SetLength(long value)
{
_innerStream.SetLength(value);
}
/// <summary>
/// Writes a block of bytes to the stream.
/// </summary>
/// <param name="buffer">The buffer to write from.</param>
/// <param name="offset">The offset in the buffer at which to start reading.</param>
/// <param name="count">The number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
_innerStream.Write(buffer, offset, count);
}
/// <summary>
/// Writes a block of bytes to the stream.
/// </summary>
/// <param name="buffer">The buffer to write from.</param>
public override void Write(ReadOnlySpan<byte> buffer)
{
_innerStream.Write(buffer);
}
/// <summary>
/// Writes a block of bytes to the stream asynchronously.
/// </summary>
/// <param name="buffer">The buffer to write from.</param>
/// <param name="offset">The offset in the buffer at which to start reading.</param>
/// <param name="count">The number of bytes to write.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
}
/// <summary>
/// Writes a block of bytes to the stream asynchronously.
/// </summary>
/// <param name="buffer">The buffer to write from.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
return _innerStream.WriteAsync(buffer, cancellationToken);
}
/// <summary>
/// Releases the inner stream and the reader lease.
/// </summary>
/// <param name="disposing">Whether the method is called from the <see cref="IDisposable.Dispose"/> method.</param>
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
_isDisposed = true;
try
{
_innerStream.Dispose();
}
finally
{
// The lease must be released even when disposing the stream throws, otherwise the entry stays protected from eviction forever.
_lease.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// Releases the inner stream and the reader lease asynchronously.
/// </summary>
/// <returns>A task that represents the asynchronous dispose operation.</returns>
public override async ValueTask DisposeAsync()
{
if (!_isDisposed)
{
_isDisposed = true;
try
{
await _innerStream.DisposeAsync().ConfigureAwait(false);
}
finally
{
// The lease must be released even when disposing the stream throws, otherwise the entry stays protected from eviction forever.
_lease.Dispose();
}
}
await base.DisposeAsync().ConfigureAwait(false);
}
}
@@ -0,0 +1,39 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents a reader's lease on a cache entry, which keeps the entry from being evicted until the lease is released.
/// </summary>
[DebuggerDisplay("CacheId: {_cacheId}")]
internal sealed class TranscodingCacheReaderLease : IDisposable
{
private readonly TranscodingCacheCoordinator _coordinator;
private readonly string _cacheId;
private bool _isDisposed;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheReaderLease"/> class.
/// </summary>
/// <param name="coordinator">The coordinator that accounts for the lease.</param>
/// <param name="cacheId">The identifier of the cache entry the lease holds.</param>
internal TranscodingCacheReaderLease(TranscodingCacheCoordinator coordinator, string cacheId)
{
_coordinator = coordinator;
_cacheId = cacheId;
}
/// <summary>
/// Releases the lease, so the cache entry may be evicted again.
/// </summary>
public void Dispose()
{
if (_isDisposed)
return;
_isDisposed = true;
_coordinator.ReleaseReaderLease(_cacheId);
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents the capacity a running normalization job reserved in the normalized audio cache, until it either produces an entry or is aborted.
/// </summary>
[DebuggerDisplay("Id: {Id}")]
internal sealed class TranscodingCacheReservation : IDisposable
{
private readonly TranscodingCacheCoordinator _coordinator;
private bool _isCompleted;
private bool _isDisposed;
/// <summary>
/// Gets the identifier of the reservation.
/// </summary>
internal string Id { get; }
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingCacheReservation"/> class.
/// </summary>
/// <param name="coordinator">The coordinator that accounts for the reservation.</param>
/// <param name="id">The identifier of the reservation.</param>
internal TranscodingCacheReservation(TranscodingCacheCoordinator coordinator, string id)
{
_coordinator = coordinator;
Id = id;
}
/// <summary>
/// Updates the reservation to the number of bytes the job has actually written, growing it when the output is larger than the estimate.
/// </summary>
/// <param name="actualBytes">The number of bytes the job has actually written, in bytes.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
/// <param name="gracePeriod">The period during which a recently produced or served entry is protected from eviction.</param>
/// <returns><see langword="true"/> when the reservation covers the actual size, otherwise <see langword="false"/>.</returns>
public bool TryUpdate(long actualBytes, long maxCacheBytes, TimeSpan gracePeriod)
{
if (_isCompleted || _isDisposed)
return false;
return _coordinator.TryGrow(Id, actualBytes, maxCacheBytes, gracePeriod);
}
/// <summary>
/// Replaces the reservation with the produced cache entry.
/// </summary>
/// <param name="cacheId">The identifier of the produced cache entry.</param>
/// <param name="temporaryPath">The temporary directory that holds the complete produced entry.</param>
/// <param name="size">The total size of the produced cache entry, in bytes.</param>
/// <param name="index">The validated index of the produced cache entry.</param>
/// <param name="maxCacheBytes">The maximum total size of the cache, in bytes.</param>
/// <param name="gracePeriod">The period during which a recently produced or served entry is protected from eviction.</param>
/// <param name="isKeptOverCapacity"><see langword="true"/> when the produced entry remains readable even though it exceeds the cache limit, otherwise <see langword="false"/>.</param>
/// <param name="isEntryInUse"><see langword="true"/> when a reader still holds the previous entry of the same cache identifier, so the replacement was not attempted.</param>
/// <returns><see langword="true"/> when the produced entry is readable and may be served, otherwise <see langword="false"/> when it was not published.</returns>
public bool TryComplete(string cacheId, string temporaryPath, long size, NormalizedTrackIndexDto index, long maxCacheBytes, TimeSpan gracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse)
{
isKeptOverCapacity = false;
isEntryInUse = false;
if (_isCompleted || _isDisposed)
return false;
bool isCompleted = _coordinator.TryPublish(Id, cacheId, temporaryPath, size, index, maxCacheBytes, gracePeriod, out isKeptOverCapacity, out isEntryInUse);
// The reservation is consumed even when the produced entry had to be removed, so it is never released a second time.
_isCompleted = true;
return isCompleted;
}
/// <summary>
/// Releases the reservation when the job did not produce a cache entry.
/// </summary>
public void Dispose()
{
if (_isDisposed)
return;
_isDisposed = true;
if (!_isCompleted)
_coordinator.ReleaseReservation(Id);
}
}
@@ -0,0 +1,125 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.IO;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Tracks the size of the temporary output of a running normalization job without walking the growing directory on every monitor tick.
/// </summary>
/// <remarks>
/// Segment files are written in sequence and only the last one grows. The tracker discovers each new segment once, keeps the size of the completed
/// segments, and only re-stats the current segment and the segment list on every tick, so the monitor stays O(1) per tick instead of O(n).
/// </remarks>
internal sealed class TranscodingOutputSizeTracker
{
private readonly string _directoryPath;
private readonly string _segmentFilePrefix;
private readonly string _segmentFileExtension;
private readonly string _segmentListPath;
private long _totalBytes;
private long _segmentListLength;
private long _lastSegmentLength;
private int _nextSegmentIndex;
private string? _lastSegmentPath;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingOutputSizeTracker"/> class.
/// </summary>
/// <param name="directoryPath">The temporary directory the job writes into.</param>
/// <param name="segmentFilePrefix">The prefix of the generated segment file names.</param>
/// <param name="segmentFileExtension">The file extension of a segment, including the leading dot.</param>
/// <param name="segmentListFileName">The file name of the segment list written by ffmpeg.</param>
internal TranscodingOutputSizeTracker(string directoryPath, string segmentFilePrefix, string segmentFileExtension, string segmentListFileName)
{
_directoryPath = directoryPath;
_segmentFilePrefix = segmentFilePrefix;
_segmentFileExtension = segmentFileExtension;
_segmentListPath = Path.Combine(directoryPath, segmentListFileName);
}
/// <summary>
/// Gets the current total size of the produced output, in bytes.
/// </summary>
/// <returns>The current total size of the produced output, in bytes.</returns>
public long GetCurrentSize()
{
// The previous tick's last segment may have grown before a new segment was started, so it is measured before new files are discovered.
RecalculateLastSegment();
RecalculateSegmentList();
DiscoverNewSegments();
RecalculateLastSegment();
return _totalBytes;
}
/// <summary>
/// Updates the total with the growth of the segment that is currently being written, when there is one.
/// </summary>
private void RecalculateLastSegment()
{
if (_lastSegmentPath is null)
return;
long currentLength = GetFileLength(_lastSegmentPath, _lastSegmentLength);
_totalBytes += currentLength - _lastSegmentLength;
_lastSegmentLength = currentLength;
}
/// <summary>
/// Updates the total with the growth of the segment list.
/// </summary>
private void RecalculateSegmentList()
{
long currentLength = GetFileLength(_segmentListPath, _segmentListLength);
_totalBytes += currentLength - _segmentListLength;
_segmentListLength = currentLength;
}
/// <summary>
/// Adds every segment that has appeared since the previous tick, in sequence, and leaves the last one as the growing segment.
/// </summary>
private void DiscoverNewSegments()
{
while (true)
{
string segmentPath = Path.Combine(_directoryPath, $"{_segmentFilePrefix}{_nextSegmentIndex:D6}{_segmentFileExtension}");
FileInfo segmentFile = new(segmentPath);
if (!segmentFile.Exists)
return;
long segmentLength;
try
{
segmentLength = segmentFile.Length;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return; // A file that cannot be measured yet is retried on the next tick.
}
_totalBytes += segmentLength;
_lastSegmentPath = segmentPath;
_lastSegmentLength = segmentLength;
_nextSegmentIndex++;
}
}
/// <summary>
/// Gets the length of a file, falling back to its last known length when it cannot currently be measured.
/// </summary>
/// <param name="filePath">The file to measure.</param>
/// <param name="fallbackLength">The length to use when the file cannot be measured.</param>
/// <returns>The current or fallback length of the file, in bytes.</returns>
private static long GetFileLength(string filePath, long fallbackLength)
{
try
{
FileInfo file = new(filePath);
return file.Exists ? file.Length : fallbackLength;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return fallbackLength;
}
}
}
@@ -0,0 +1,228 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Caching;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Startup component that owns the normalized audio cache lifecycle and verifies the ffmpeg toolchain before any playback request is served.
/// </summary>
/// <remarks>
/// The cache is cleaned and recreated with private permissions at startup, and the configured ffmpeg binary is probed for the encoders the catalog uses. The
/// cleanup only removes the entries the cache itself owns, and only from a directory that carries the cache marker or was empty, so a configured directory
/// that belongs to something else is never wiped. The cleanup is bounded, so a slow or network backed cache directory cannot delay host readiness without
/// limit. The probe outcome is recorded in <see cref="TranscodingToolchainStatus"/>, so normalized playback reports that it is unavailable for the affected
/// formats instead of failing per track. A failure of either step is logged and does not abort the host, so direct playback of the rest of the application
/// keeps working.
/// </remarks>
internal sealed class TranscodingStartupInitializer : IHostedService
{
private const int CACHE_CLEANUP_TIMEOUT_SECONDS = 30;
private const int FFMPEG_PROBE_TIMEOUT_SECONDS = 10;
private readonly TranscodingSettingsDto _settings;
private readonly TranscodingToolchainStatus _toolchainStatus;
private readonly ILogger<TranscodingStartupInitializer> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingStartupInitializer"/> class.
/// </summary>
/// <param name="options">The audio normalization configuration options.</param>
/// <param name="toolchainStatus">The status that records the outcome of the ffmpeg probe for the normalization service.</param>
/// <param name="logger">The logger for this startup component.</param>
public TranscodingStartupInitializer(IOptions<TranscodingSettingsDto> options, TranscodingToolchainStatus toolchainStatus, ILogger<TranscodingStartupInitializer> logger)
{
_settings = options.Value;
_toolchainStatus = toolchainStatus;
_logger = logger;
}
/// <summary>
/// Cleans and recreates the cache directory, then probes the ffmpeg binary for the encoders the pipeline uses.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous startup operation.</returns>
public async Task StartAsync(CancellationToken cancellationToken)
{
try
{
string cacheDirectory = TranscodingCachePaths.GetRootDirectory(_settings.CacheDirectory);
if (Directory.Exists(cacheDirectory))
{
// The permissions are verified before the directory is inspected, so a directory planted by another account is never used or cleaned.
TranscodingCachePaths.RestrictPermissions(cacheDirectory);
if (TranscodingCachePaths.HasCacheMarker(cacheDirectory))
{
// Only the entries the cache itself owns are removed, so a directory that was configured by mistake can never lose unrelated data.
// The cleanup is bounded and cancellable, because a network backed cache directory must not delay host readiness forever.
using (CancellationTokenSource cleanupTimeoutCancellationTokenSource = new(TimeSpan.FromSeconds(CACHE_CLEANUP_TIMEOUT_SECONDS)))
{
using (CancellationTokenSource linkedCleanupCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cleanupTimeoutCancellationTokenSource.Token))
{
try
{
TranscodingCachePaths.ClearCacheEntries(cacheDirectory, linkedCleanupCancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
if (!cancellationToken.IsCancellationRequested)
_logger.LogWarning("The normalized audio cache cleanup did not finish within {CleanupTimeoutSeconds} seconds. Whatever remains is accounted for by the coordinator and is removed by the next cleanup.", CACHE_CLEANUP_TIMEOUT_SECONDS);
}
}
}
}
else if (!Directory.EnumerateFileSystemEntries(cacheDirectory).Any())
TranscodingCachePaths.WriteCacheMarker(cacheDirectory); // An empty directory is adopted, so a cache directory created ahead of the first run works without manual preparation.
else // A non-empty directory without the marker was not created by this application. It is never wiped, because only the operator can tell whether its entries are safe to remove.
throw new IOException("The configured normalized audio cache directory exists, is not empty and does not carry the Lumina cache marker, so it was not wiped.");
}
else
TranscodingCachePaths.EnsureDirectoryExists(cacheDirectory);
_logger.LogInformation("The normalized audio cache uses the directory '{CacheDirectory}'.", cacheDirectory);
}
catch (Exception exception)
{
// A locked file, a read-only volume or a directory owned by another account must not stop the whole application; the coordinator accounts
// for whatever remains and the service reports normalized playback as unavailable when the directory still cannot be used.
_logger.LogError(exception, "The normalized audio cache could not be initialized (configured directory: '{CacheDirectory}'). Normalized playback may be unavailable.", _settings.CacheDirectory ?? "(default)");
}
try
{
await ProbeFfmpegAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
// The startup component promises never to abort the host, so an unexpected probe failure is contained and reported here.
_toolchainStatus.RecordUnavailable();
_logger.LogError(exception, "The ffmpeg startup probe failed unexpectedly. Normalized playback may be unavailable.");
}
}
/// <summary>
/// Stops the startup component, which has no resources of its own to release.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A completed task.</returns>
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
/// <summary>
/// Probes the ffmpeg binary for the encoders the catalog can produce, without failing the host when it is missing or incomplete.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that represents the asynchronous probe.</returns>
private async Task ProbeFfmpegAsync(CancellationToken cancellationToken)
{
try
{
using Process process = new();
process.StartInfo = new ProcessStartInfo
{
FileName = _settings.FfmpegPath,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
process.StartInfo.ArgumentList.Add("-hide_banner");
process.StartInfo.ArgumentList.Add("-encoders");
if (!process.Start())
{
_toolchainStatus.RecordUnavailable();
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' could not be started. Normalized playback will be unavailable.", _settings.FfmpegPath);
return;
}
using CancellationTokenSource timeoutCancellationTokenSource = new(TimeSpan.FromSeconds(FFMPEG_PROBE_TIMEOUT_SECONDS));
// The probe has two cancellation reasons: the host startup token and the probe timeout. Linking them gives the process wait and the pipe reads
// one token that means "this probe is over" for either reason. The parameter alone could not stop the reads on a timeout, and the timeout alone would ignore host shutdown.
using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token);
// Drain both pipes while the process runs. A child that fills a pipe buffer blocks until it is read, so waiting for exit first could deadlock.
// The linked token stops the reads as well, so a probe timeout or host shutdown does not leave them running against a killed child.
Task<string> standardOutputTask = process.StandardOutput.ReadToEndAsync(linkedCancellationTokenSource.Token);
Task<string> standardErrorTask = process.StandardError.ReadToEndAsync(linkedCancellationTokenSource.Token);
try
{
await process.WaitForExitAsync(linkedCancellationTokenSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
try
{
if (!process.HasExited)
process.Kill(entireProcessTree: true);
}
catch (Exception killException) when (killException is Win32Exception or InvalidOperationException or NotSupportedException)
{
_logger.LogDebug(killException, "The ffmpeg startup probe process could not be stopped.");
}
if (!cancellationToken.IsCancellationRequested)
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' did not respond to the startup probe.", _settings.FfmpegPath);
_toolchainStatus.RecordUnavailable();
return;
}
string encoderListing = await standardOutputTask.ConfigureAwait(false);
await standardErrorTask.ConfigureAwait(false);
if (process.ExitCode != 0)
{
_toolchainStatus.RecordUnavailable();
_logger.LogWarning("The ffmpeg binary '{FfmpegPath}' exited with code {ExitCode} during the startup probe. Normalized playback may be unavailable.", _settings.FfmpegPath, process.ExitCode);
return;
}
IReadOnlyList<string> requiredEncoders = [.. PlaybackFormatCatalog.Formats
.Select(format => format.EncoderName)
.Distinct(StringComparer.OrdinalIgnoreCase)];
List<string> missingEncoders = [.. requiredEncoders.Where(encoder => !ContainsEncoder(encoderListing, encoder))];
if (missingEncoders.Count > 0)
{
// An unpinned distribution package can change the encoder set without changing the application build, so this is reported at startup instead of surfacing as a per track playback failure.
_toolchainStatus.RecordMissingEncoders(missingEncoders);
_logger.LogError("The ffmpeg binary '{FfmpegPath}' is missing the encoders {MissingEncoders}. Normalized playback for those formats will be unavailable.", _settings.FfmpegPath, string.Join(", ", missingEncoders));
return;
}
_toolchainStatus.RecordAvailable();
_logger.LogInformation("The ffmpeg binary '{FfmpegPath}' provides every encoder the normalized audio pipeline uses.", _settings.FfmpegPath);
}
catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException or UnauthorizedAccessException or NotSupportedException)
{
_toolchainStatus.RecordUnavailable();
_logger.LogWarning(exception, "The ffmpeg binary '{FfmpegPath}' could not be probed. Normalized playback will be unavailable.", _settings.FfmpegPath);
}
}
/// <summary>
/// Checks whether the encoder listing of ffmpeg contains the provided encoder name.
/// </summary>
/// <param name="encoderListing">The output of the ffmpeg encoder listing.</param>
/// <param name="encoderName">The encoder name to look for.</param>
/// <returns><see langword="true"/> when the encoder is listed, otherwise <see langword="false"/>.</returns>
private static bool ContainsEncoder(string encoderListing, string encoderName)
{
foreach (string line in encoderListing.Split('\n'))
{
string[] tokens = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
// An encoder line is "<flags> <name> <description>"; the encoder name is always the second token.
if (tokens.Length >= 2 && string.Equals(tokens[1], encoderName, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
}
@@ -0,0 +1,73 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Records the outcome of the ffmpeg startup probe, so a missing toolchain or encoder is reported as a retryable unavailability instead of a production failure.
/// </summary>
/// <remarks>
/// The status starts as available, because a request that arrives before the probe completes is better served by attempting the work than by rejecting it. The
/// probe replaces the status with its outcome, and every later production consults it before it spends a job slot.
/// </remarks>
internal sealed class TranscodingToolchainStatus
{
// The startup probe writes these fields and request threads read them without a lock, so volatile makes each write visible to the readers.
private volatile bool _isTranscoderAvailable = true;
private volatile FrozenSet<string> _missingEncoders = [];
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingToolchainStatus"/> class, which starts as available until the startup probe records its outcome.
/// </summary>
public TranscodingToolchainStatus()
{
}
/// <summary>
/// Gets a value indicating whether the ffmpeg binary can run at all.
/// </summary>
public bool IsTranscoderAvailable => _isTranscoderAvailable;
/// <summary>
/// Records that the probe found a usable ffmpeg binary with every encoder the catalog needs.
/// </summary>
public void RecordAvailable()
{
// The set is cleared before the availability flag, so a reader never observes a missing encoder together with a fresh successful probe.
_missingEncoders = [];
_isTranscoderAvailable = true;
}
/// <summary>
/// Records that the ffmpeg binary could not be started or did not answer the probe.
/// </summary>
public void RecordUnavailable()
{
_isTranscoderAvailable = false;
_missingEncoders = [];
}
/// <summary>
/// Records that ffmpeg runs, but that some of the encoders the catalog needs are missing.
/// </summary>
/// <param name="missingEncoders">The names of the encoders the startup probe did not find.</param>
public void RecordMissingEncoders(IEnumerable<string> missingEncoders)
{
_missingEncoders = missingEncoders.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
_isTranscoderAvailable = true;
}
/// <summary>
/// Checks whether an encoder can be used for a lossy or lossless transcode.
/// </summary>
/// <param name="encoderName">The name of the ffmpeg encoder the delivery format needs.</param>
/// <returns><see langword="true"/> when ffmpeg runs and the encoder was found, otherwise <see langword="false"/>.</returns>
public bool IsEncoderAvailable(string encoderName)
{
return _isTranscoderAvailable && !_missingEncoders.Contains(encoderName);
}
}
@@ -26,6 +26,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Otp.NET" />
<PackageReference Include="QRCoder" />
@@ -17,6 +17,14 @@
"MaxSingleFileBytes": 6291456,
"MaxEntries": 250
},
"TranscodingSettings": {
"FfmpegPath": "ffmpeg",
"MaxConcurrentJobs": 2,
"MaxCacheBytes": 2147483648,
"JobTimeoutSeconds": 900,
"EvictionGraceSeconds": 120,
"CacheDirectory": null
},
"ConnectionStrings": {
"DefaultConnection": "Server=<host>;Database=<database>;User Id=<user>;Password=<password>;"
},
+6 -2
View File
@@ -1,10 +1,14 @@
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
# curl is used by the container healthcheck to probe the /health endpoints
# ffmpeg is used by the API server to remux or transcode audio the browser cannot play directly.
# The package comes from the base image distribution and is not version-pinned, so the encoder set can change with a base image rebuild.
# The API startup probe verifies the encoders the normalization catalog uses and reports a missing one at startup. Pin the base image digest
# or the package version when a fully reproducible toolchain is required.
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& apt-get install -y --no-install-recommends curl ffmpeg \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir /logs && chown -R app:app /logs
&& mkdir -p /app /logs && chown -R app:app /app /logs
USER app
WORKDIR /app
EXPOSE 5214
+1 -1
View File
@@ -8,8 +8,8 @@ using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Common.DependencyInjection;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Lumina.Infrastructure.Core.Scheduling.Notifications;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Infrastructure.Core.Scheduling.Notifications;
using Lumina.Presentation.Api.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.Middlewares;
using Lumina.Presentation.Api.Common.Utilities;
@@ -8,28 +8,29 @@ namespace Lumina.Presentation.Web.Common.Enums.AudioLibrary;
/// Enumeration for the quality cap applied to the audio the server normalizes (remuxes or transcodes) for a user.
/// </summary>
/// <remarks>
/// The caps apply only to audio the server has to change; a track that is played directly is always delivered as it was stored.
/// The caps apply only to audio the server re-encodes into a lossy codec. A track that is played directly is delivered as it was stored, a remux only
/// repackages the stored codec without re-encoding it, and a lossless transcode is not reduced, so none of those deliveries is capped.
/// </remarks>
[DebuggerDisplay("{ToString()}")]
public enum PlaybackStreamingQuality
{
/// <summary>
/// The server chooses the quality, with no explicit cap.
/// The server chooses the quality, with a default cap of 192 kbps for a lossy re-encode.
/// </summary>
Auto,
/// <summary>
/// Normalized audio is capped at 96 kbps.
/// A lossy normalized audio stream is capped at 96 kbps.
/// </summary>
Low,
/// <summary>
/// Normalized audio is capped at 160 kbps.
/// A lossy normalized audio stream is capped at 160 kbps.
/// </summary>
Medium,
/// <summary>
/// Normalized audio is capped at 320 kbps.
/// A lossy normalized audio stream is capped at 320 kbps.
/// </summary>
High,
}
@@ -1197,7 +1197,7 @@
// playhead, the streamed fraction and the scrubbing state while the audio keeps playing.
if (index === this.currentIndex)
return this.queueEntries[index].descriptor;
// Navigation history, repeat and shuffle belong to the queue model of step 18. This commit only moves the cursor.
// Navigation history, repeat and shuffle belong to the queue model, which is not part of this cursor movement.
const previousIndex = this.currentIndex;
this.currentIndex = index;
return this.applyTrackDescriptor(this.queueEntries[index].descriptor, previousIndex);