diff --git a/docs/manual/installation/index.md b/docs/manual/installation/index.md index dc41f332..4054ee27 100644 --- a/docs/manual/installation/index.md +++ b/docs/manual/installation/index.md @@ -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: diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index a5496021..21555490 100644 --- a/docs/manual/using-lumina/index.md +++ b/docs/manual/using-lumina/index.md @@ -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. diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md index d7a638a7..41252610 100644 --- a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md +++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0016.md @@ -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 diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs new file mode 100644 index 00000000..16efa3e8 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackDto.cs @@ -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; + +/// +/// Data transfer object for the normalized audio of a track, produced and cached as a sequence of fixed duration segments. +/// +/// The Id of the track whose audio the cached entry holds, so the caller can verify that the entry is the one it authorized. +/// The opaque identifier of the cached entry that holds the normalized audio. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio. +/// The codec of the delivered audio. +/// The duration of each segment of the delivered audio, in seconds. +/// +/// 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. +/// +/// The segments that make up the delivered audio, in playback order. +[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 Segments +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs new file mode 100644 index 00000000..4e28eb18 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs @@ -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; + +/// +/// Data transfer object for the request to produce the normalized audio of a track, as the delivery decision of a playback manifest describes it. +/// +/// The Id of the track whose audio is normalized. It binds the produced cache entry to the track the caller authorized. +/// The file system path of the stored audio file of the track. +/// +/// 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. +/// +/// The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. Optional. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio, as chosen by the delivery decision. +/// The codec of the delivered audio, as chosen by the delivery decision. +/// The duration of each segment of the delivered audio, in seconds. +/// The duration of the audio of the track, in seconds. +/// The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. Optional. +/// The sample rate of the stored audio of the track, in Hz, used to estimate the size of a lossless delivery. +/// The number of audio channels of the track, used to estimate the size of a lossless delivery. +/// The bit depth of the stored audio of the track, if applicable, used to estimate the size of a lossless delivery. +/// The quality cap applied to the delivered audio when it has to be re-encoded. +[DebuggerDisplay("TrackId: {TrackId} Mode: {Mode} Container: {Container} Codec: {Codec}")] +public sealed record NormalizedTrackRequestDto( + Guid TrackId, + string SourcePath, + IReadOnlyList AllowedRoots, + string? SourceContainer, + PlaybackDeliveryMode Mode, + string Container, + string Codec, + int SegmentDurationSeconds, + int DurationInSeconds, + int? Bitrate, + int SampleRate, + int Channels, + int? BitDepth, + PlaybackStreamingQuality Quality +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs new file mode 100644 index 00000000..00c3cb1a --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDto.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for a single fixed duration segment of the normalized audio of a track. +/// +/// The zero based position of the segment in the delivered audio. +/// The time, in seconds from the start of the track, at which the segment starts. +/// The duration of the segment, in seconds. +/// The length of the segment, in bytes. +[DebuggerDisplay("Index: {Index} StartSeconds: {StartSeconds} DurationSeconds: {DurationSeconds}")] +public sealed record NormalizedTrackSegmentDto( + int Index, + decimal StartSeconds, + decimal DurationSeconds, + long Length +); diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs new file mode 100644 index 00000000..45c2f418 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs @@ -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; + +/// +/// Interface for the service that produces, caches and serves the normalized audio of a track, when the player cannot play the stored audio directly. +/// +/// +/// 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 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. +/// +public interface ITrackNormalizationService +{ + /// + /// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet. + /// + /// The track, the delivery decision, the source file and the quality cap the normalized audio is produced with. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the cached normalized audio of the track, or an error message. + /// + /// + /// Thrown when 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. + /// + Task> GetOrCreateNormalizedTrackAsync(NormalizedTrackRequestDto request, CancellationToken cancellationToken); + + /// + /// Opens a read stream over a single segment of a cached normalized track, after verifying that the entry belongs to the provided track. + /// + /// + /// 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 . 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 + /// . + /// + /// The opaque identifier of the cached entry that holds the normalized audio. + /// The Id of the track the caller authorized and whose segment is opened. + /// The zero based position of the segment in the delivered audio. + /// + /// An containing either a read stream over the segment, or an error message. The caller owns the returned stream. + /// + Result OpenNormalizedSegment(string cacheId, Guid trackId, int segmentIndex); +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs index 6350f42b..0e3ecd72 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Playback/PlaybackStreamingQuality.cs @@ -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. /// /// -/// 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. /// public enum PlaybackStreamingQuality { /// - /// 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. /// Auto, /// - /// Normalized audio is capped at 96 kbps. + /// A lossy normalized audio stream is capped at 96 kbps. /// Low, /// - /// Normalized audio is capped at 160 kbps. + /// A lossy normalized audio stream is capped at 160 kbps. /// Medium, /// - /// Normalized audio is capped at 320 kbps. + /// A lossy normalized audio stream is capped at 320 kbps. /// High, } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs index 8e4662fc..16292916 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs @@ -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)); } } diff --git a/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs b/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs new file mode 100644 index 00000000..29877a13 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Caching/TranscodingCachePaths.cs @@ -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; + +/// +/// Provides the location, the ownership marker and the permissions of the temporary directory into which the audio normalization pipeline writes the normalized audio. +/// +internal static class TranscodingCachePaths +{ + /// + /// The name of the temporary directory that is used when no cache directory is configured. + /// + public const string DEFAULT_DIRECTORY_NAME = "lumina-transcoding-cache"; + + /// + /// The name of the file that marks a directory as a normalized audio cache created and owned by this application. + /// + public const string CACHE_MARKER_FILE_NAME = ".lumina-transcoding-cache"; + + /// + /// The prefix of the temporary directories of the normalization jobs that have not been published to the cache yet. + /// + public const string TEMPORARY_DIRECTORY_PREFIX = "tmp-"; + + /// + /// The prefix of the tombstone directories that were detached from the cache and are waiting to be deleted. + /// + 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; + + /// + /// Gets the absolute path of the directory into which the audio normalization pipeline writes the normalized audio of the tracks. + /// + /// + /// The configured cache directory, relative to the application base directory when not rooted, or to use a private directory + /// under the system temporary directory. The default directory is scoped to the operating system account that runs the process. + /// + /// The absolute path of the transcoding cache directory. + 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()); + } + + /// + /// Checks whether a directory carries the marker of a normalized audio cache created by this application. + /// + /// The absolute path of the directory to check. + /// when the directory carries the cache marker, otherwise . + public static bool HasCacheMarker(string directoryPath) + { + return File.Exists(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME)); + } + + /// + /// Writes the marker that records the directory as a normalized audio cache created and owned by this application. + /// + /// The absolute path of the directory to mark. + /// + /// 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. + /// + 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); + } + + /// + /// Checks whether an entry name belongs to the namespace of the normalized audio cache. + /// + /// The name of the entry, without its directory. + /// when the name is a cache identifier, a temporary directory name or a deletion tombstone name, otherwise . + 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); + } + + /// + /// Checks whether a value is a well formed opaque cache identifier. + /// + /// The value to check. + /// when the value is a well formed cache identifier, otherwise . + 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; + } + + /// + /// Removes the entries of a directory that belong to the namespace of the normalized audio cache, and leaves every other entry untouched. + /// + /// The absolute path of the cache directory. + /// Cancellation token that can be used to stop the execution. + /// + /// 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. + /// + /// The cleanup was canceled. + /// An entry could not be deleted. + /// An entry could not be deleted because access was denied. + 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); + } + } + + /// + /// Deletes a directory and everything it contains. + /// + /// The directory to delete. + /// Cancellation token that can be used to stop the execution. + /// The deletion was canceled. + /// A file or directory could not be deleted. + /// A file or directory could not be deleted because access was denied. + 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); + } + + /// + /// Verifies that an existing cache directory is not a symbolic link and tightens its permissions to the private mode on Unix. + /// + /// The absolute path of the cache directory. + /// The path is a symbolic link or cannot be inspected. + /// The directory is owned by another user or cannot be changed. + 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); + } + + /// + /// Tightens the permissions of a file the cache created to owner read and write on Unix. + /// + /// The absolute path of the file. + /// The file permissions could not be changed. + /// The file is owned by another user or cannot be changed. + 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); + } + + /// + /// Creates a directory with private permissions on the platforms that support them. + /// + /// The absolute path of the directory to create. + /// The directory could not be created. + /// The directory could not be created because access was denied. + 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); + } + + /// + /// Creates the cache directory when it does not exist, or tightens an existing one, with private permissions on the platforms that support them. + /// + /// The absolute path of the cache directory. + /// + /// 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. + /// + /// The directory could not be created, or the path is a symbolic link. + /// The directory could not be created or changed because access was denied. + public static void EnsureDirectoryExists(string directoryPath) + { + RestrictPermissions(directoryPath); + bool isCreated = !Directory.Exists(directoryPath); + CreatePrivateDirectory(directoryPath); + if (isCreated) + WriteCacheMarker(directoryPath); + } + + /// + /// Deletes a directory, and reports whether it was deleted. + /// + /// The directory to delete. + /// when the directory no longer exists, otherwise . + 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; + } + } + + /// + /// 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. + /// + /// The account suffix used in the default cache directory name. + 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]; + } +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 4154b4a9..b36d8d58 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -152,6 +152,18 @@ public static class InfrastructureLayerServices // repackaged into another container, or re-encoded into another codec. services.AddSingleton(); + // 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(); + + // 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(); + + // 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(); + // Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents. // The enablement cache lets the reading service skip the per-request database read of the reader configurations. services.AddSingleton(); diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index afd1c2c7..ce2327d0 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -70,6 +70,11 @@ public static class SharedConfiguration .ValidateFluently() .ValidateOnStart(); + services.AddOptions() + .Bind(configuration.GetRequiredSection(TranscodingSettingsDto.SECTION_NAME)) + .ValidateFluently() + .ValidateOnStart(); + return services; } } diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index d5aa5e0e..b13262b8 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -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)); } } diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs new file mode 100644 index 00000000..a533f8e5 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.Configuration; + +/// +/// Data transfer object for deserializing the settings of the audio normalization pipeline. +/// +[DebuggerDisplay("Section name: {SECTION_NAME}")] +public sealed class TranscodingSettingsDto +{ + public const string SECTION_NAME = "TranscodingSettings"; + + /// + /// Gets or sets the file name or path of the ffmpeg binary, relative to the process search path when not rooted. + /// + public string FfmpegPath { get; set; } = "ffmpeg"; + + /// + /// Gets or sets the maximum number of normalization jobs that may run at the same time. + /// + public int MaxConcurrentJobs { get; set; } = 2; + + /// + /// Gets or sets the maximum total size of the normalized audio cache, in bytes. + /// + public long MaxCacheBytes { get; set; } = 2L * 1024 * 1024 * 1024; + + /// + /// Gets or sets the maximum duration of a single normalization job, in seconds, after which the job is stopped. + /// + public int JobTimeoutSeconds { get; set; } = 900; + + /// + /// Gets or sets the period, in seconds, during which a cache entry that was just produced or served is protected from eviction. + /// + public int EvictionGraceSeconds { get; set; } = 120; + + /// + /// 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. + /// + public string? CacheDirectory { get; set; } +} diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs new file mode 100644 index 00000000..996b3262 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedAudioFormatDto.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Describes how a single container and codec combination of the audio normalization pipeline is muxed and, when it has to be re-encoded, encoded. +/// +/// The canonical container of the delivered audio. +/// The canonical codec of the delivered audio. +/// The name of the ffmpeg muxer that writes the container. +/// The file extension of a single segment, including the leading dot. +/// The name of the ffmpeg encoder used when the audio is transcoded. +/// Whether the codec is lossless, in which case an encoder bitrate cap does not apply. +[DebuggerDisplay("Container: {Container} Codec: {Codec} Muxer: {MuxerName}")] +internal sealed record NormalizedAudioFormatDto( + string Container, + string Codec, + string MuxerName, + string FileExtension, + string EncoderName, + bool IsLossless +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs new file mode 100644 index 00000000..0190f027 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackIndexDto.cs @@ -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; + +/// +/// Represents the persisted description of a cached normalized track, which lets the cache be read without parsing the ffmpeg output again. +/// +/// The version of the index layout, so an index written by an older version is treated as a cache miss. +/// The Id of the track the cached audio belongs to, so a cache handle can be authorized against the track of the route. +/// The way the audio is delivered, which is a remux or a transcode. +/// The container of the delivered audio. +/// The codec of the delivered audio. +/// The duration of each segment of the delivered audio, in seconds. +/// +/// 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. +/// +/// The segments that make up the delivered audio, in playback order. +[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 Segments +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs new file mode 100644 index 00000000..d9ae324c --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentIndexDto.cs @@ -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; + +/// +/// Represents the persisted description of a single segment of a cached normalized track. +/// +/// The zero based position of the segment in the delivered audio. +/// The time, in seconds from the start of the track, at which the segment starts. +/// The duration of the segment, in seconds. +/// The file name of the segment inside the cache entry. +/// The length of the segment, in bytes. +[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 +); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs new file mode 100644 index 00000000..588a6c79 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheEntryDto.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents a single entry of the normalized audio cache, used to enforce the cache size limit. +/// +/// The absolute path of the directory that holds the entry. +/// The total size of the entry, in bytes. +/// The date and time, in UTC, when the entry was last produced or served. +/// The date and time, in UTC, when the entry was produced or, for an entry found on disk, the earliest representable time. +[DebuggerDisplay("Path: {Path} Size: {Size}")] +internal sealed record TranscodingCacheEntryDto( + string Path, + long Size, + DateTime LastUsedUtc, + DateTime ProducedAtUtc +); diff --git a/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs new file mode 100644 index 00000000..4d4d5213 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs @@ -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; + +/// +/// Validates the needed validation rules for the TranscodingSettings application configuration settings section. +/// +public class TranscodingSettingsDtoValidator : AbstractValidator +{ + 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; + + /// + /// Initializes a new instance of the class. + /// + /// The media settings, used to reject a cache directory that would be served by the media route. + /// The plugin settings, used to reject a cache directory that would overlap the plugins directory. + /// The service used to check whether two directories overlap. + public TranscodingSettingsDtoValidator(IOptions mediaSettings, IOptions 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)); + } + + /// + /// Checks whether the provided cache directory is a path the file system accepts. + /// + /// The configured cache directory, or when the default is used. + /// when the path is valid, otherwise . + 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; + } + } + + /// + /// Checks whether the configured cache directory is outside the media root, which is served without authentication at the media route. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the cache is outside the media root, otherwise . + 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; + } + } + + /// + /// Checks whether the configured cache directory does not contain the media root. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the cache does not contain the media root, otherwise . + 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; + } + } + + /// + /// Checks whether the configured cache directory is a location whose cleanup cannot damage the application or the host. + /// + /// The configured cache directory. It is already known to be a valid path. + /// when the location is safe, otherwise . + 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; + } + } + + /// + /// Checks whether the default cache directory, used when none is configured, is outside the media root. + /// + /// when the default cache is outside the media root, otherwise . + 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; + } + } + + /// + /// Checks whether a path is equal to, or is located inside, another path. + /// + /// The path to check. + /// The path that must contain, or be equal to, the checked path. + /// when the path is equal to or inside the parent path, otherwise . + 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); + } + + /// + /// Checks whether a path is the root of a file system, or of a volume, instead of a directory inside it. + /// + /// The absolute path to check. + /// when the path is a file system root, otherwise . + 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); + } + + /// + /// Gets the full form of a path, without a trailing separator unless the path itself is the root of a file system or volume. + /// + /// The path to normalize. + /// The normalized absolute path. + 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); + } + + /// + /// Gets the directories that the cache directory must never overlap: the logs directory and the plugins directory. + /// + /// The plugin settings, whose directory is resolved against the application base directory. + /// The absolute paths of the directories the cache must not overlap. + private static string[] BuildConflictingDirectories(PluginsSettingsDto pluginsSettings) + { + List 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]; + } + + /// + /// Adds the full form of a directory to the list of conflicting directories, when it can be resolved and is not already listed. + /// + /// The list of conflicting directories to add to. + /// The directory to add, or when it is not configured. + private static void AddConflictingDirectory(List 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. + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs new file mode 100644 index 00000000..8a1fe34f --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatCatalog.cs @@ -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; + +/// +/// The single catalog of the audio formats the server can produce, shared by the playback delivery decision and the audio normalization pipeline. +/// +/// +/// The order of 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. +/// +internal static class PlaybackFormatCatalog +{ + /// + /// Gets the formats the server can produce, in the order of the transcode codec preference and, within a codec, of the container preference. + /// + public static IReadOnlyList 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) + ]; + + /// + /// Gets the formats the server can produce, keyed by their canonical container and codec pair. + /// + public static FrozenDictionary FormatsByPair { get; } = BuildFormatsByPair(); + + /// + /// Gets the containers the server can produce each codec in, in order of preference. + /// + public static FrozenDictionary> ProducibleContainersByCodec { get; } = BuildProducibleContainersByCodec(); + + /// + /// Gets the codecs the server can produce, in order of preference. + /// + public static IReadOnlyList TranscodeCodecPreference { get; } = BuildTranscodeCodecPreference(); + + /// + /// Builds the key of a canonical container and codec pair. + /// + /// The container of the audio. + /// The codec of the audio. + /// The canonical key of the pair. + public static string BuildPairKey(string container, string codec) + { + return (container ?? string.Empty).Trim().ToUpperInvariant() + "/" + (codec ?? string.Empty).Trim().ToUpperInvariant(); + } + + /// + /// Builds the map of the producible formats, keyed by their canonical container and codec pair. + /// + /// The producible formats, keyed by their canonical pair. + private static FrozenDictionary BuildFormatsByPair() + { + return Formats.ToFrozenDictionary(format => BuildPairKey(format.Container, format.Codec), StringComparer.OrdinalIgnoreCase); + } + + /// + /// Builds the map of the containers the server can produce each codec in, preserving the order of the catalog. + /// + /// The containers of each producible codec, in order of preference. + private static FrozenDictionary> BuildProducibleContainersByCodec() + { + Dictionary> containersByCodec = new(StringComparer.OrdinalIgnoreCase); + foreach (NormalizedAudioFormatDto format in Formats) + { + if (!containersByCodec.TryGetValue(format.Codec, out List? 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)entry.Value, StringComparer.OrdinalIgnoreCase); + } + + /// + /// Builds the codecs the server can produce, preserving the order in which they first appear in the catalog. + /// + /// The producible codecs, in order of preference. + private static IReadOnlyList BuildTranscodeCodecPreference() + { + List codecs = []; + foreach (NormalizedAudioFormatDto format in Formats) + if (!codecs.Contains(format.Codec, StringComparer.OrdinalIgnoreCase)) + codecs.Add(format.Codec); + return codecs; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs index 3afe9bf2..61df12f3 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackFormatService.cs @@ -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 s_transcodeCodecPreference = ["AAC", "OPUS", "MP3", "VORBIS", "FLAC", "PCM"]; - - // The containers the server can produce each codec in, in order of preference. The delivered container is always chosen from - // this list, so a container the player named is only ever matched against it and never becomes the delivered container itself. - private static readonly FrozenDictionary> s_producibleContainersByCodec = new Dictionary>(StringComparer.OrdinalIgnoreCase) - { - { "AAC", ["MP4", "AAC"] }, - { "OPUS", ["OGG"] }, - { "VORBIS", ["OGG"] }, - { "MP3", ["MP3"] }, - { "FLAC", ["FLAC"] }, - { "PCM", ["WAV"] } - }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); - /// /// Decides how the audio of a track, described by , is delivered to a player that advertises . /// @@ -101,7 +84,7 @@ internal sealed class PlaybackFormatService : IPlaybackFormatService /// private static PlaybackCapabilityDto? SelectFormatForCodec(IReadOnlyList capabilities, string codec) { - if (codec.Length == 0 || !s_producibleContainersByCodec.TryGetValue(codec, out IReadOnlyList? producibleContainers)) + if (codec.Length == 0 || !PlaybackFormatCatalog.ProducibleContainersByCodec.TryGetValue(codec, out IReadOnlyList? producibleContainers)) return null; IReadOnlyList advertisedContainers = [.. capabilities @@ -124,7 +107,7 @@ internal sealed class PlaybackFormatService : IPlaybackFormatService /// The preferred producible container and codec, or when the player supports no producible codec. private static PlaybackCapabilityDto? SelectTranscodeFormat(IReadOnlyList capabilities) { - foreach (string preferredCodec in s_transcodeCodecPreference) + foreach (string preferredCodec in PlaybackFormatCatalog.TranscodeCodecPreference) { PlaybackCapabilityDto? format = SelectFormatForCodec(capabilities, preferredCodec); if (format is not null) diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs new file mode 100644 index 00000000..0fb9cfec --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs @@ -0,0 +1,1389 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using Lumina.Infrastructure.Common.Caching; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Concurrent; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Service that produces the normalized audio of a track with ffmpeg, caches it as fixed duration segments and serves it from the cache. +/// +/// +/// The normalized audio is written to a temporary directory that is wiped when the application starts. The number of jobs that run at the same time is +/// bounded, and a request that finds every slot occupied is reported as busy instead of being queued, so client requests cannot accumulate behind the +/// running jobs. Every child process is stopped when the application exits, and every job has a bounded duration. A production is shared by every request +/// for the same track and delivery: a request that disconnects stops waiting but does not stop the production, so repeated aborts converge to a cached entry. +/// A production is atomic: the entry is published only after ffmpeg finishes the whole track, so the first request waits for a complete production; the +/// produced segments are then served from the cache without buffering them into memory. The total size of the cache, including the output of the jobs that +/// are still running, is accounted for by a process wide coordinator, which evicts the least recently used entries that are neither freshly produced nor +/// being read. The command line is always built as a list of arguments, with the input protocol restricted to the file protocol, so a file path is never +/// interpolated into a command string and a probed file can never fetch a remote URL. Every component of a source path below a content location is checked +/// for reparse points, and ffmpeg consumes a private snapshot copied from the opened handle, so a path that is swapped after the open cannot redirect the +/// bytes that are transcoded. +/// +internal sealed class TrackNormalizationService : ITrackNormalizationService, IDisposable +{ + private const string CACHE_INDEX_FILE_NAME = "index.json"; + private const string SEGMENT_LIST_FILE_NAME = "segments.csv"; + private const string SOURCE_SNAPSHOT_FILE_NAME = "source"; + private const string SEGMENT_FILE_PREFIX = "segment-"; + private const string SEGMENT_FILE_NAME_PATTERN = SEGMENT_FILE_PREFIX + "%06d"; + private const string AUDIO_STREAM_MAP = "0:a:0"; + private const string NO_METADATA_MAP = "-1"; + private const string COPY_CODEC = "copy"; + private const string FILE_PROTOCOL = "file"; + private const long MAX_CACHE_INDEX_BYTES = 4 * 1024 * 1024; + private const long MAX_SEGMENT_LIST_BYTES = 4 * 1024 * 1024; + private const int CACHE_INDEX_VERSION = 2; + private const int MAX_SEGMENT_COUNT = 1_000_000; + private const int CACHE_SIZE_MONITOR_INTERVAL_MILLISECONDS = 500; + private const int PROCESS_EXIT_TIMEOUT_SECONDS = 5; + private const int PRODUCTION_DRAIN_TIMEOUT_SECONDS = 15; + private const int MAX_STANDARD_ERROR_CHARACTERS = 16 * 1024; + private const int AUTO_TRANSCODE_BITRATE_KBPS = 192; + private const int DEFAULT_SOURCE_BITRATE_KBPS = 320; + private const int DEFAULT_SAMPLE_RATE = 44100; + private const int DEFAULT_CHANNEL_COUNT = 2; + private const int DEFAULT_BIT_DEPTH = 16; + private const decimal FLAC_COMPRESSION_RATIO = 0.7m; + private const decimal REMUX_SIZE_MARGIN = 1.1m; + private const decimal SEGMENT_TIME_TOLERANCE_SECONDS = 0.001m; + private const decimal DURATION_TOLERANCE_MIN_SECONDS = 1m; + private const decimal DURATION_TOLERANCE_RATIO = 0.02m; + + // The demuxer of each container the probe can report. Pinning the demuxer stops ffmpeg from probing the content of the file and selecting a + // demuxer that can open a playlist or another indirection; the file protocol whitelist is the backstop for a container that is not listed here. + private static readonly FrozenDictionary s_sourceDemuxers = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["MP3"] = "mp3", + ["FLAC"] = "flac", + ["MP4"] = "mov", + ["M4A"] = "mov", + ["AAC"] = "aac", + ["ADTS"] = "aac", + ["OGG"] = "ogg", + ["OPUS"] = "ogg", + ["VORBIS"] = "ogg", + ["WAV"] = "wav", + ["WAVE"] = "wav", + ["AIFF"] = "aiff", + ["APE"] = "ape", + ["WAVPACK"] = "wv", + ["WV"] = "wv", + ["WMA"] = "asf", + ["ASF"] = "asf", + ["DSF"] = "dsf", + ["MATROSKA"] = "matroska", + ["MKA"] = "matroska", + ["WEBM"] = "matroska", + ["MPC"] = "mpc", + ["AA"] = "aa" + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + // The index is server written, but a tampered file is still parsed defensively: MaxDepth bounds the recursion of the deserializer. + private static readonly JsonSerializerOptions s_indexJsonOptions = new(JsonSerializerDefaults.Web) + { + PropertyNameCaseInsensitive = true, + MaxDepth = 8 + }; + + // The productions are shared by every request of the process for the same cache entry, so a request that disconnects never cancels the work that + // another request, or a later retry, is waiting for. The key includes the cache root, because two service instances configured with different cache + // directories must never join each other's production. A completed production is removed from the registry; a later request reads the cache instead. + private static readonly ConcurrentDictionary<(string CacheRoot, string CacheId), Lazy>>> s_normalizationJobs = new(); + + private readonly TranscodingSettingsDto _settings; + private readonly ILogger _logger; + private readonly IPathService _pathService; + private readonly TranscodingCacheCoordinator _cache; + private readonly TranscodingToolchainStatus _toolchainStatus; + private readonly TimeSpan _evictionGracePeriod; + private readonly TimeSpan _touchThrottleInterval; + private readonly SemaphoreSlim _jobSlots; + private readonly ConcurrentDictionary _runningProcesses = new(); + private readonly CancellationTokenSource _shutdownCancellation = new(); + private readonly Lock _lifecycleSync = new(); + private readonly ManualResetEventSlim _productionsDrained = new(initialState: true); + private readonly string _cacheRoot; + private int _activeProductionCount; + // Written under _lifecycleSync by Dispose and read without the lock by the request paths through Volatile.Read, so the write is observed promptly. + private bool _isDisposed; + + /// + /// Initializes a new instance of the class. + /// + /// The audio normalization configuration options. + /// The logger for this service. + /// The service used to validate that a cached segment is inside its cache entry. + /// The status that records whether the ffmpeg toolchain found at startup can produce a format. + public TrackNormalizationService(IOptions options, ILogger logger, IPathService pathService, TranscodingToolchainStatus toolchainStatus) + { + _settings = options.Value; + _logger = logger; + _pathService = pathService; + _toolchainStatus = toolchainStatus; + _jobSlots = new SemaphoreSlim(_settings.MaxConcurrentJobs, _settings.MaxConcurrentJobs); + _evictionGracePeriod = TimeSpan.FromSeconds(_settings.EvictionGraceSeconds); + // A touch is written at most every quarter of the eviction grace period, so a stream that opens many segments does not rewrite the cache + // entry for every request while an actively used entry stays protected from eviction. + _touchThrottleInterval = TimeSpan.FromSeconds(Math.Clamp(_settings.EvictionGraceSeconds / 4.0, 0.25, 30)); + _cacheRoot = TranscodingCachePaths.GetRootDirectory(_settings.CacheDirectory); + _cache = TranscodingCacheCoordinator.AcquireForRoot(_cacheRoot); + // A killed process must never outlive the application, so every child process that is still running is stopped when the process exits. The + // subscription is removed when the service is disposed, so a host that is shut down in the same process does not keep this instance rooted. + AppDomain.CurrentDomain.ProcessExit += OnApplicationStopping; + } + + /// + /// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet. + /// + /// The track, the delivery decision, the source file and the quality cap the normalized audio is produced with. + /// Cancellation token that can be used to stop the execution. + /// An containing either the cached normalized audio of the track, or an error message. + /// + /// Thrown when 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. + /// + public async Task> GetOrCreateNormalizedTrackAsync(NormalizedTrackRequestDto request, CancellationToken cancellationToken) + { + // Dispose sets _isDisposed under _lifecycleSync, but taking that lock on every request would serialize this hot path. The flag is therefore read + // without the lock. Volatile.Read keeps the read from being cached in a register, so a request observes the disposal flag once it is set and + // fails fast instead of using resources that Dispose has already released. + if (Volatile.Read(ref _isDisposed)) + return Errors.Playback.NormalizationUnavailable; + if (request.TrackId == Guid.Empty) + return Errors.Playback.NormalizationFailed; + if (string.IsNullOrWhiteSpace(request.SourcePath)) + return Errors.Music.TrackPathCannotBeEmpty; + // The caller authorizes the request, and the service re-validates the source path against the content locations carried by the request. A path + // that is outside every allowed root is reported as not found, never as a path error, so no file system detail is disclosed. + if (request.AllowedRoots is null || request.AllowedRoots.Count == 0 || !IsPathAllowed(request.SourcePath, request.AllowedRoots)) + return Errors.Music.TrackFileNotFound; + // Normalization only exists for audio the player cannot play as stored, so a direct play never reaches the pipeline. + if (request.Mode == PlaybackDeliveryMode.DirectPlay) + return Errors.Playback.NormalizationIsNotRequiredForDirectPlay; + if (request.SegmentDurationSeconds <= 0) + return Errors.Playback.SegmentDurationMustBePositive; + if (request.DurationInSeconds <= 0) + return Errors.Playback.TrackDurationMustBePositive; + // A delivery decision that names a pair the catalog does not implement is a disagreement between two server side tables. It must never be + // reported as a limitation of the player, which is what the forbidden NoSupportedPlaybackFormat means. + if (!PlaybackFormatCatalog.FormatsByPair.TryGetValue(PlaybackFormatCatalog.BuildPairKey(request.Container, request.Codec), out NormalizedAudioFormatDto? format)) + return Errors.Playback.PlaybackFormatNotImplemented; + + FileInfo sourceFile; + long sourceLength; + DateTime sourceLastModifiedUtc; + try + { + sourceFile = new FileInfo(request.SourcePath); + if (!sourceFile.Exists) + return Errors.Music.TrackFileNotFound; + // The length and the modification time of the source are read once, while the file is known to exist, and are used both for the cache + // identity and for the size estimate, so a file that disappears between two reads can never surface as an unhandled exception. + sourceLength = sourceFile.Length; + sourceLastModifiedUtc = sourceFile.LastWriteTimeUtc; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Music.TrackFileNotFound; // A file that cannot be read is indistinguishable, to the caller, from a file that does not exist. + } + + string cacheId = BuildCacheId(request, sourceFile.FullName, sourceLength, sourceLastModifiedUtc, format); + // The entry is touched before its index is read, so that a cache hit can never race an eviction that is deciding on the entry at the same time: + // an eviction that runs after the touch sees the entry as recently used, and one that ran before the touch makes the read miss and produce anew. + _cache.Touch(cacheId, _touchThrottleInterval); + if (TryReadCachedTrack(cacheId, out NormalizedTrackDto? cachedTrack) && cachedTrack is not null && cachedTrack.TrackId == request.TrackId) + return cachedTrack; + + // The production is shared by every request for this cache entry and is not tied to this request's token. This request only waits for it, so a + // disconnect stops this caller from waiting without destroying the work, and the next request either joins the same production or reads its result. + (string CacheRoot, string CacheId) normalizationJobKey = (_cacheRoot, cacheId); + // ExecutionAndPublication makes the factory run exactly once when several requests race to create the same job. + Lazy>> normalizationJob = s_normalizationJobs.GetOrAdd( + normalizationJobKey, + createdJobKey => new Lazy>>( + () => ProduceAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc), + LazyThreadSafetyMode.ExecutionAndPublication)); + Task> normalizationTask = normalizationJob.Value; + // Remove the job from the static registry when it finishes, so a completed result is not kept in memory forever. + _ = normalizationTask.ContinueWith( + completedTask => RemoveNormalizationJob(normalizationJobKey, normalizationJob), + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + + return await normalizationTask.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Opens a read stream over a single segment of a cached normalized track, after verifying that the entry belongs to the provided track. + /// + /// The opaque identifier of the cached entry that holds the normalized audio. + /// The Id of the track the caller authorized and whose segment is opened. + /// The zero based position of the segment in the delivered audio. + /// + /// An containing either a read stream over the segment, or an error message. The caller owns the returned stream. + /// + public Result OpenNormalizedSegment(string cacheId, Guid trackId, int segmentIndex) + { + // This runs for every segment request and must not take _lifecycleSync. Dispose writes _isDisposed under that lock, and Volatile.Read makes this + // lock free check observe the write instead of a value cached in a register, so segments stop being served as soon as the service is disposed. + if (Volatile.Read(ref _isDisposed)) + return Errors.Playback.NormalizationUnavailable; + if (trackId == Guid.Empty || !TranscodingCacheCoordinator.IsValidCacheId(cacheId) || segmentIndex < 0) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + // The lease is acquired before the index is read, so that an eviction that runs concurrently can never delete the entry between the read and + // the moment the segment stream starts. The lease is handed over to the stream and released when the caller disposes it. + TranscodingCacheReaderLease lease = _cache.AcquireReaderLease(cacheId); + bool isLeaseTransferred = false; + try + { + if (!TryReadIndex(cacheId, out NormalizedTrackIndexDto? index) || index is null) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + // The cache handle is not a capability: it is derived from the track and can be computed by anyone who knows the track. The entry is bound + // to the track it was produced for, so a handle can only ever serve the track the caller authorized against the route. + if (index.TrackId != trackId) + return Errors.Music.TrackNotFound; + + NormalizedTrackSegmentIndexDto? segment = index.Segments.FirstOrDefault(candidate => candidate.Index == segmentIndex); + if (segment is null) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + string cachePath = Path.Combine(_cacheRoot, cacheId); + string segmentPath = Path.Combine(cachePath, segment.FileName); + // The file name comes from the cache index, which only the server writes, but the resolved path is still confined to the cache entry so that a + // tampered index can never be used to read a file outside it. + if (!_pathService.IsPathWithin(segmentPath, cachePath)) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + // A cache entry is never reached through a reparse point. The index is only written by this application, but a tampered cache entry must not be + // able to redirect a segment outside the cache root. + if (HasReparsePointBelow(_cacheRoot, segmentPath)) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + FileInfo segmentFile = new(segmentPath); + if (!segmentFile.Exists || segmentFile.Length != segment.Length) + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + + _cache.Touch(cacheId, _touchThrottleInterval); + // A published entry is immutable, so every reader can share the file. Delete sharing is not granted: replacement is coordinated through the + // lease and the publication lock, never by deleting a file under a reader. + FileStream fileStream = new(segmentPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true); + try + { + // The handle is checked against the length from the index and against the reparse points again, so a file or an ancestor swapped between + // the check and the open is never handed to the caller. + if (fileStream.Length != segment.Length || HasReparsePointBelow(_cacheRoot, segmentPath)) + { + fileStream.Dispose(); + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + } + } + catch + { + fileStream.Dispose(); + throw; + } + TranscodingCacheLeaseStream leaseStream = new(fileStream, lease); + isLeaseTransferred = true; + return Result.Success(leaseStream); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Playback.NormalizedTrackCacheEntryNotFound; + } + finally + { + if (!isLeaseTransferred) + lease.Dispose(); + } + } + + /// + /// Opens the stored audio file of a track after re-validating that it is inside an allowed root, and re-checks the opened handle. + /// + /// + /// The caller has already authorized the request, but the path is still validated here as defense in depth. Every component between an allowed root and + /// the leaf is rejected when it is a reparse point, so a symbolic link inside a content location can never redirect the file outside it. The file is then + /// opened, and the opened handle is checked against the allowed roots and against the length and modification time the cache identity was built from. + /// The caller copies the opened handle into a private snapshot before the transcoder runs, so the transcoder reads exactly the bytes that were validated, + /// even when the path is replaced afterwards. The length is read from the handle; the modification time is a path based, best effort comparison. + /// + /// The request whose source path and allowed roots are validated. + /// The length of the stored audio file of the track, in bytes, read when the cache identity was built. + /// The date and time, in UTC, when the stored audio file of the track was last modified, read when the cache identity was built. + /// An containing either an open read stream over the authorized source file, or an error message. The caller owns the stream. + private Result OpenAuthorizedSource(NormalizedTrackRequestDto request, long sourceLength, DateTime sourceLastModifiedUtc) + { + try + { + FileInfo sourceFile = new(request.SourcePath); + if (!sourceFile.Exists || !IsPathAllowed(sourceFile.FullName, request.AllowedRoots)) + return Errors.Music.TrackFileNotFound; + + string resolvedPath = sourceFile.FullName; + FileStream sourceStream = new(resolvedPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true); + try + { + // The file is checked again after it has been opened, so a path that was swapped between the FileInfo read and the open is never handed + // to the transcoder. The length is read from the handle itself; the modification time must also still match the value the cache identity was built from. + FileInfo openedFile = new(resolvedPath); + if (!openedFile.Exists || + !IsPathAllowed(openedFile.FullName, request.AllowedRoots) || + sourceStream.Length != sourceLength || + openedFile.LastWriteTimeUtc != sourceLastModifiedUtc) + { + sourceStream.Dispose(); + return Errors.Music.TrackFileNotFound; + } + + return sourceStream; + } + catch + { + sourceStream.Dispose(); + throw; + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + return Errors.Music.TrackFileNotFound; + } + } + + /// + /// Checks whether a path is inside at least one of the allowed roots, without crossing a reparse point below that root. + /// + /// The path to check. + /// The roots the path is allowed to be inside. + /// when the path is inside an allowed root and no component below that root is a reparse point, otherwise . + private bool IsPathAllowed(string path, IReadOnlyList allowedRoots) + { + foreach (string allowedRoot in allowedRoots) + { + if (string.IsNullOrWhiteSpace(allowedRoot) || !_pathService.IsPathWithin(path, allowedRoot)) + continue; + // A reparse point inside the content location fails closed instead of being resolved, because its target is outside the root the caller authorized. + return !HasReparsePointBelow(allowedRoot, path); + } + return false; + } + + /// + /// Checks whether any component of a path below a root is a reparse point. + /// + /// The root below which the components are checked. + /// The path inside the root whose components are checked. + /// when a component below the root is a reparse point, otherwise . + private static bool HasReparsePointBelow(string rootPath, string path) + { + string normalizedRootPath = Path.GetFullPath(rootPath); + string normalizedPath = Path.GetFullPath(path); + string relativePath = Path.GetRelativePath(normalizedRootPath, normalizedPath); + if (relativePath == ".") + return false; + string currentPath = normalizedRootPath; + foreach (string segment in relativePath.Split([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries)) + { + // The lexical containment check already succeeded, so a relative escape means the two paths disagree; the file is rejected rather than trusted. + if (segment == "..") + return true; + if (segment == ".") + continue; + currentPath = Path.Combine(currentPath, segment); + if ((File.GetAttributes(currentPath) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) + return true; + } + return false; + } + + /// + /// Admits a production to the service lifetime, so that shutdown cancels it and disposes the process lifetime resources only after it has left. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// An containing either the normalized audio of the track, or an error message. + private async Task> ProduceAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc) + { + lock (_lifecycleSync) + { + // A production that arrives after shutdown has started must not touch the cancellation source, the job slots or the coordinator, because shutdown may already have disposed them. + if (_isDisposed) + return Errors.Playback.NormalizationUnavailable; + // Dispose waits on _productionsDrained before it releases the coordinator and job slots. Counting the production here closes the race + // between the disposal check above and the resources being released while the production is still using them. + _activeProductionCount++; + if (_activeProductionCount == 1) + _productionsDrained.Reset(); + } + + try + { + return await ProduceCoreAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc).ConfigureAwait(false); + } + finally + { + lock (_lifecycleSync) + { + _activeProductionCount--; + if (_activeProductionCount == 0) + _productionsDrained.Set(); + } + } + } + + /// + /// Produces the normalized audio of a track in the background, independent of any request that waits for it. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// An containing either the normalized audio of the track, or an error message. + private async Task> ProduceCoreAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc) + { + CancellationToken cancellationToken = _shutdownCancellation.Token; + + // The startup initializer owns the cache directory, but the service re-ensures it before every production so a directory removed at runtime or a + // failed startup wipe cannot turn into an unhandled exception or a partial write. + try + { + TranscodingCachePaths.EnsureDirectoryExists(_cacheRoot); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + _logger.LogError(exception, "The normalized audio cache directory '{CacheDirectory}' is not available for track {TrackId} in cache entry {CacheId}.", _cacheRoot, request.TrackId, cacheId); + return Errors.Playback.NormalizationUnavailable; + } + + try + { + // A production is admitted immediately or reported as busy. Queueing a task per distinct request would let a client saturate the pipeline + // and outlive its own timeout, while a started production is still allowed to outlive every disconnected waiter. + if (!_jobSlots.Wait(0)) + return Errors.Playback.NormalizationUnavailable; + try + { + // Another production for the same entry may have finished while this one was created, so the cache is checked again before spendingan admitted slot on work that is already done. + if (TryReadCachedTrack(cacheId, out NormalizedTrackDto? cachedTrack) && cachedTrack is not null && cachedTrack.TrackId == request.TrackId) + { + _cache.Touch(cacheId, _touchThrottleInterval); + return cachedTrack; + } + + // A cached entry is served even when the toolchain is broken, but a new production needs a usable ffmpeg and, for a transcode, the + // encoder of the delivery format. The startup probe recorded what is missing, so this is reported as unavailable instead of failing per track. + if (!_toolchainStatus.IsTranscoderAvailable || (request.Mode == PlaybackDeliveryMode.Transcode && !_toolchainStatus.IsEncoderAvailable(format.EncoderName))) + return Errors.Playback.NormalizationUnavailable; + + long estimatedSize = EstimateOutputSize(request, format); + if (!_cache.TryReserve(estimatedSize, _settings.MaxCacheBytes, _evictionGracePeriod, out TranscodingCacheReservation? reservation) || reservation is null) + return Errors.Playback.NormalizationCacheLimitExceeded; + + using (reservation) + return await NormalizeAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc, reservation, cancellationToken).ConfigureAwait(false); + } + finally + { + _jobSlots.Release(); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return Errors.Playback.NormalizationUnavailable; // The application is stopping, so the production cannot finish; it is reported instead of being left as an unobserved cancellation. + } + catch (Exception exception) + { + // The production is shared by requests that are no longer necessarily waiting, so every failure is turned into a result and observed here. + _logger.LogError(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be produced.", request.TrackId, cacheId); + return Errors.Playback.NormalizationFailed; + } + } + + /// + /// Produces the normalized audio of a track into a temporary directory, persists its index and asks the coordinator to publish it into the cache. + /// + /// The opaque identifier of the cache entry. + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// The capacity the job reserved in the cache. + /// Cancellation token that can be used to stop the execution. + /// An containing either the normalized audio of the track, or an error message. + private async Task> NormalizeAsync(string cacheId, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format, long sourceLength, DateTime sourceLastModifiedUtc, TranscodingCacheReservation reservation, CancellationToken cancellationToken) + { + string temporaryPath = Path.Combine(_cacheRoot, TranscodingCachePaths.TEMPORARY_DIRECTORY_PREFIX + Guid.NewGuid().ToString("N")); + string segmentListPath = Path.Combine(temporaryPath, SEGMENT_LIST_FILE_NAME); + + // The source is opened and re-validated here, immediately before the transcoder runs, and copied into a private snapshot that the transcoder reads. + // The snapshot is written from the validated handle, so the transcoder consumes exactly the bytes that were validated even when the path is replaced. + Result openResult = OpenAuthorizedSource(request, sourceLength, sourceLastModifiedUtc); + if (openResult.IsFailure) + return openResult.Errors; + + using (FileStream sourceStream = openResult.Value) + { + try + { + TranscodingCachePaths.CreatePrivateDirectory(temporaryPath); + string snapshotPath = Path.Combine(temporaryPath, SOURCE_SNAPSHOT_FILE_NAME); + bool isSnapshotComplete; + // The copy is bounded by the job timeout as well, so a source that never finishes reading cannot hold a job slot indefinitely. + using (CancellationTokenSource snapshotTimeoutCancellationTokenSource = new(TimeSpan.FromSeconds(_settings.JobTimeoutSeconds))) + { + using (CancellationTokenSource snapshotCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, snapshotTimeoutCancellationTokenSource.Token)) + { + try + { + isSnapshotComplete = await CopySourceSnapshotAsync(sourceStream, snapshotPath, sourceLength, snapshotCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return Errors.Playback.NormalizationTimedOut; + } + } + } + if (!isSnapshotComplete) + return Errors.Music.TrackFileNotFound; + + Result runResult; + try + { + runResult = await RunFfmpegAsync(cacheId, request, snapshotPath, format, temporaryPath, segmentListPath, reservation, cancellationToken).ConfigureAwait(false); + } + finally + { + // The snapshot is not part of the cache entry; it is removed before the entry is moved or the temporary directory is cleaned. + TryDeleteFile(snapshotPath); + } + if (runResult.IsFailure) + return runResult.Errors; + NormalizedTrackIndexDto index = runResult.Value; + // The csv is only an intermediate of the production; it is not part of the published entry and is never read again. + TryDeleteFile(segmentListPath); + // The entries are created under a private root, but each produced file is tightened as well instead of relying on the directory mode alone. + foreach (NormalizedTrackSegmentIndexDto segment in index.Segments) + TranscodingCachePaths.RestrictFilePermissions(Path.Combine(temporaryPath, segment.FileName)); + + // The index is written before the entry is published, so a cache hit never has to parse the ffmpeg output or probe the segments again. + string indexJson = JsonSerializer.Serialize(index, s_indexJsonOptions); + string temporaryIndexPath = Path.Combine(temporaryPath, CACHE_INDEX_FILE_NAME); + await File.WriteAllTextAsync(temporaryIndexPath, indexJson, cancellationToken).ConfigureAwait(false); + TranscodingCachePaths.RestrictFilePermissions(temporaryIndexPath); + // The segments were stat'ed by the index parser, so the size is the parsed lengths plus the index file instead of another walk of the entry. + long entrySize = index.Segments.Sum(segment => segment.Length) + Encoding.UTF8.GetByteCount(indexJson); + FileInfo remainingSegmentList = new(segmentListPath); + if (remainingSegmentList.Exists) + entrySize += remainingSegmentList.Length; + // The coordinator replaces the previous directory, moves this one into place and registers its index under one lock, so a concurrent + // eviction can never delete the freshly published entry and a reader is never served a mix of two productions. + if (!reservation.TryComplete(cacheId, temporaryPath, entrySize, index, _settings.MaxCacheBytes, _evictionGracePeriod, out bool isKeptOverCapacity, out bool isEntryInUse)) + { + if (isEntryInUse) + return Errors.Playback.NormalizationUnavailable; + return Errors.Playback.NormalizationFailed; + } + if (isKeptOverCapacity) + _logger.LogWarning("The normalized audio of track {TrackId} in cache entry {CacheId} was produced successfully but exceeds the configured normalized audio cache limit. It is kept readable and will be evicted when it is no longer in use.", request.TrackId, cacheId); + + return CreateNormalizedTrackDto(cacheId, index); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + _logger.LogWarning(exception, "The normalized audio of track {TrackId} in cache entry {CacheId} could not be cached.", request.TrackId, cacheId); + return Errors.Playback.NormalizationFailed; + } + finally + { + if (Directory.Exists(temporaryPath)) + TranscodingCachePaths.TryDeleteDirectory(temporaryPath); + } + } + } + + /// + /// Copies the validated source stream into a private snapshot file, so the transcoder reads exactly the bytes that were validated. + /// + /// The open, validated stream over the stored audio file of the track. + /// The path of the snapshot file to create. + /// The expected length of the source file, in bytes. + /// Cancellation token that can be used to stop the execution. + /// when the whole source was copied, otherwise . + private static async Task CopySourceSnapshotAsync(FileStream sourceStream, string snapshotPath, long expectedLength, CancellationToken cancellationToken) + { + using (FileStream snapshotStream = new(snapshotPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true)) + await sourceStream.CopyToAsync(snapshotStream, cancellationToken).ConfigureAwait(false); + // The snapshot is read from the open handle, so the comparison detects a source that was truncated or grew after the handle was validated. + return new FileInfo(snapshotPath).Length == expectedLength; + } + + /// + /// Runs ffmpeg to write the normalized audio of a track into a temporary directory, and builds the index of the produced segments. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The path of the private snapshot of the stored audio file, which was copied from the validated handle. + /// The container and codec combination the normalized audio is produced in. + /// The temporary directory the normalized audio is written into. + /// The file into which ffmpeg writes the list of produced segments. + /// The capacity the job reserved in the cache. + /// Cancellation token that can be used to stop the execution. + /// An containing either the index of the produced segments, or an error message. + private async Task> RunFfmpegAsync(string cacheId, NormalizedTrackRequestDto request, string inputPath, NormalizedAudioFormatDto format, string temporaryPath, string segmentListPath, TranscodingCacheReservation reservation, CancellationToken cancellationToken) + { + using Process process = new(); + process.StartInfo = new ProcessStartInfo + { + FileName = _settings.FfmpegPath, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardError = true, + RedirectStandardOutput = false + }; + foreach (string argument in BuildArguments(request, inputPath, format, temporaryPath, segmentListPath)) + process.StartInfo.ArgumentList.Add(argument); + + try + { + if (!process.Start()) + return Errors.Playback.NormalizationFailed; + } + catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or IOException) + { + _logger.LogError(exception, "The audio transcoder for track {TrackId} in cache entry {CacheId} could not be started.", request.TrackId, cacheId); + return Errors.Playback.NormalizationUnavailable; + } + + // The process is registered so the application exit handler can kill it even if the host stops without reaching this method's finally. + _runningProcesses[process.Id] = process; + try + { + // Start draining stderr before waiting. A child that fills the pipe buffer blocks until it is read, so waiting for the exit first could deadlock. + Task standardErrorTask = ReadBoundedStandardErrorAsync(process.StandardError); + using CancellationTokenSource timeoutCancellationTokenSource = new(TimeSpan.FromSeconds(_settings.JobTimeoutSeconds)); + using CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token); + // The callback kills ffmpeg as soon as the token fires, so a cancellation or timeout stops the child even while this thread is awaiting its + // exit. The catch below only observes the exit that the callback caused. + using CancellationTokenRegistration cancellationRegistration = linkedCancellationTokenSource.Token.Register(() => KillProcess(process)); + using CancellationTokenSource monitorCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(linkedCancellationTokenSource.Token); + TranscodingOutputSizeTracker outputSizeTracker = new(temporaryPath, SEGMENT_FILE_PREFIX, format.FileExtension, SEGMENT_LIST_FILE_NAME); + Task monitorTask = MonitorOutputSizeAsync(cacheId, request.TrackId, outputSizeTracker, reservation, process, monitorCancellationTokenSource.Token); + try + { + await process.WaitForExitAsync(linkedCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + KillProcess(process); + // The cancellation callback fired the kill without waiting. The exit is observed asynchronously here, so the temporary directory is + // cleaned up after the child has actually stopped, without pinning the thread that triggered the cancellation. + using CancellationTokenSource exitCancellationTokenSource = new(TimeSpan.FromSeconds(PROCESS_EXIT_TIMEOUT_SECONDS)); + try + { + await process.WaitForExitAsync(exitCancellationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + _logger.LogDebug("The audio transcoder did not exit within the process exit timeout."); + } + } + finally + { + // The monitor loops until it is canceled. Stop it before awaiting it, or a job that finished normally would wait forever. + monitorCancellationTokenSource.Cancel(); + } + + bool isCacheLimitExceeded = await monitorTask.ConfigureAwait(false); + // The read is bounded: a process that was killed but did not exit would otherwise keep the pipe open and park the job slot. + string standardError = await AwaitStandardErrorAsync(standardErrorTask).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + if (isCacheLimitExceeded) + return Errors.Playback.NormalizationCacheLimitExceeded; + if (timeoutCancellationTokenSource.IsCancellationRequested) + return Errors.Playback.NormalizationTimedOut; + if (process.ExitCode != 0) + { + _logger.LogWarning("The audio transcoder for track {TrackId} in cache entry {CacheId} exited with code {ExitCode}.", request.TrackId, cacheId, process.ExitCode); + if (!string.IsNullOrWhiteSpace(standardError)) + { + // The bounded stderr can contain the source path and media metadata. It is only written at Debug and never returned to a client. + string diagnostic = RedactPath(RedactPath(standardError, inputPath), request.SourcePath); + _logger.LogDebug("The audio transcoder for track {TrackId} in cache entry {CacheId} reported: {StandardError}", request.TrackId, cacheId, diagnostic); + } + return Errors.Playback.NormalizationFailed; + } + + return ParseSegmentIndex(cacheId, segmentListPath, temporaryPath, request, format); + } + finally + { + _runningProcesses.TryRemove(process.Id, out _); + KillProcess(process); + } + } + + /// + /// Builds the argument list of a single ffmpeg invocation, with one argument per list entry, so a path is never interpolated into a command line. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The path of the private snapshot of the stored audio file, which was copied from the validated handle. + /// The container and codec combination the normalized audio is produced in. + /// The temporary directory the normalized audio is written into. + /// The file into which ffmpeg writes the list of produced segments. + /// The argument list of the ffmpeg invocation. + private static IReadOnlyList BuildArguments(NormalizedTrackRequestDto request, string inputPath, NormalizedAudioFormatDto format, string temporaryPath, string segmentListPath) + { + List arguments = + [ + "-hide_banner", + "-loglevel", "error", + "-nostdin", + "-y", + "-protocol_whitelist", FILE_PROTOCOL + ]; + + // The demuxer is pinned to the container the probe stored, so ffmpeg never probes the content of the file and never selects a demuxer that + // can follow a playlist or another indirection. A container that is not known is still limited to the file protocol by the whitelist above. + if (TryResolveSourceDemuxer(request.SourceContainer, out string sourceDemuxer)) + { + arguments.Add("-f"); + arguments.Add(sourceDemuxer); + } + + arguments.AddRange( + [ + "-i", inputPath, + "-map", AUDIO_STREAM_MAP, + "-vn", + "-sn", + "-dn", + "-map_metadata", NO_METADATA_MAP + ]); + + // A remux only repackages the stored codec, while a transcode re-encodes it and applies the streaming quality cap when the codec is lossy. + arguments.Add("-c:a"); + if (request.Mode == PlaybackDeliveryMode.Remux) + arguments.Add(COPY_CODEC); + else + { + arguments.Add(format.EncoderName); + // A lossy transcode always carries an explicit bitrate, including Auto, so the emitted stream and the cache size estimate use the same number. + if (!format.IsLossless) + { + arguments.Add("-b:a"); + arguments.Add(GetTargetBitrateKbps(request.Quality).ToString(CultureInfo.InvariantCulture) + "k"); + } + } + + arguments.AddRange( + [ + "-f", "segment", + "-segment_time", request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + "-segment_format", format.MuxerName + ]); + + // MP4 writes the moov atom at the end by default, so a client that starts reading a segment before it is fully fetched would stall. The segments + // are written as files, so the muxer can move the atom to the front of each one. + if (string.Equals(format.MuxerName, "mp4", StringComparison.OrdinalIgnoreCase)) + { + arguments.Add("-segment_format_options"); + arguments.Add("movflags=+faststart"); + } + + arguments.AddRange( + [ + "-segment_start_number", "0", + "-reset_timestamps", "1", + "-segment_list", segmentListPath, + "-segment_list_type", "csv", + Path.Combine(temporaryPath, SEGMENT_FILE_NAME_PATTERN + format.FileExtension) + ]); + return arguments; + } + + /// + /// Parses the segment list ffmpeg wrote and turns it into the persisted index of the normalized audio. + /// + /// + /// Every line must describe a complete, readable segment. A malformed line is a hard failure instead of a skipped segment, because skipping a line + /// would produce an index over audio that has a hole in it. The index of a segment is taken from the number in its generated file name, and the + /// numbers must form a contiguous sequence starting at zero, so a missing segment can never be silently renumbered. A trailing segment with an empty + /// time range, which ffmpeg can emit when the last frame ends exactly on a segment boundary, is discarded instead of being indexed. The produced + /// duration is compared with the probed duration only for a shortfall, which is the truncation case; a production that is longer than the probe is + /// kept and logged, because a probe that estimates a duration from the bitrate can underestimate a variable bitrate file. The duration recorded in the + /// index is the produced end, rounded up to the next second, so the seek map of the cache entry always covers every produced segment. + /// + /// The opaque identifier of the cache entry. + /// The file into which ffmpeg wrote the list of produced segments. + /// The temporary directory the normalized audio was written into. + /// The track, the delivery decision and the quality cap the normalized audio was produced with. + /// The container and codec combination the normalized audio was produced in. + /// + /// An containing either the index of the produced segments, or an error message. + /// + private Result ParseSegmentIndex(string cacheId, string segmentListPath, string temporaryPath, NormalizedTrackRequestDto request, NormalizedAudioFormatDto format) + { + if (!File.Exists(segmentListPath)) + return Errors.Playback.NormalizationFailed; + if (new FileInfo(segmentListPath).Length > MAX_SEGMENT_LIST_BYTES) + return Errors.Playback.NormalizationFailed; + + List segments = []; + try + { + foreach (string line in File.ReadLines(segmentListPath)) + { + if (string.IsNullOrWhiteSpace(line)) + continue; + + // A csv entry is "file,start,end". The file name is generated by this application and never contains a comma, so the last two commas always delimit the two times. + int endSeparatorIndex = line.LastIndexOf(','); + if (endSeparatorIndex <= 0) + return Errors.Playback.NormalizationFailed; + int startSeparatorIndex = line.LastIndexOf(',', endSeparatorIndex - 1); + if (startSeparatorIndex <= 0) + return Errors.Playback.NormalizationFailed; + + string fileName = Path.GetFileName(line[..startSeparatorIndex].Trim()); + if (!TryGetSegmentNumber(fileName, format.FileExtension, out int segmentNumber)) + return Errors.Playback.NormalizationFailed; + + string startText = line[(startSeparatorIndex + 1)..endSeparatorIndex].Trim(); + string endText = line[(endSeparatorIndex + 1)..].Trim(); + if (!decimal.TryParse(startText, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal startSeconds)) + return Errors.Playback.NormalizationFailed; + if (!decimal.TryParse(endText, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal endSeconds)) + return Errors.Playback.NormalizationFailed; + if (startSeconds < 0 || endSeconds < startSeconds) + return Errors.Playback.NormalizationFailed; + + FileInfo segmentFile = new(Path.Combine(temporaryPath, fileName)); + decimal durationSeconds = endSeconds - startSeconds; + // ffmpeg can append a final segment whose time range is empty when the last frame ends exactly on a segment boundary. That segment is + // discarded after the list is sorted, but a zero duration anywhere else, or a missing or empty segment that is supposed to carry audio, is a malformed production. + if (durationSeconds == 0) + { + segments.Add(new NormalizedTrackSegmentIndexDto(segmentNumber, startSeconds, 0, fileName, segmentFile.Exists ? segmentFile.Length : 0)); + continue; + } + if (!segmentFile.Exists || segmentFile.Length <= 0) + return Errors.Playback.NormalizationFailed; + + segments.Add(new NormalizedTrackSegmentIndexDto(segmentNumber, startSeconds, durationSeconds, fileName, segmentFile.Length)); + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return Errors.Playback.NormalizationFailed; + } + + if (segments.Count == 0 || segments.Count > MAX_SEGMENT_COUNT) + return Errors.Playback.NormalizationFailed; + + // The number in the file name is the index, not the position of the line, and the numbers must be exactly the sequence from zero to count - 1. + // A gap, a duplicate or an out of order line would otherwise produce an index over audio that the player would map to the wrong time. + segments.Sort((left, right) => left.Index.CompareTo(right.Index)); + // The trailing segment with an empty time range carries no audio, so it is removed from the index and from the cache entry instead of being + // exposed as a segment that the player would seek to and find empty. + while (segments.Count > 0 && segments[^1].DurationSeconds == 0) + { + string trailingSegmentPath = Path.Combine(temporaryPath, segments[^1].FileName); + segments.RemoveAt(segments.Count - 1); + TryDeleteFile(trailingSegmentPath); + } + if (segments.Count == 0) + return Errors.Playback.NormalizationFailed; + + decimal previousEndSeconds = 0; + for (int position = 0; position < segments.Count; position++) + { + // A segment must start where the previous one ended, within the small tolerance of the csv times. Checking only that it does not start + // before the previous end would accept a leading gap or a gap in the middle of the track as long as the final end still matched. + decimal startDifferenceSeconds = segments[position].StartSeconds - previousEndSeconds; + if (segments[position].Index != position || + segments[position].DurationSeconds <= 0 || + startDifferenceSeconds < -SEGMENT_TIME_TOLERANCE_SECONDS || + startDifferenceSeconds > SEGMENT_TIME_TOLERANCE_SECONDS) + return Errors.Playback.NormalizationFailed; + previousEndSeconds = segments[position].StartSeconds + segments[position].DurationSeconds; + } + + // A shortfall is the truncation case this check exists for. A probe that estimates the duration from the bitrate can underestimate a variable + // bitrate file, so a production that is longer than the probe is accepted and logged instead of being rejected forever. + decimal expectedDurationSeconds = request.DurationInSeconds; + decimal durationToleranceSeconds = Math.Max(DURATION_TOLERANCE_MIN_SECONDS, expectedDurationSeconds * DURATION_TOLERANCE_RATIO); + if (previousEndSeconds < expectedDurationSeconds - durationToleranceSeconds) + return Errors.Playback.NormalizationFailed; + if (previousEndSeconds > expectedDurationSeconds + durationToleranceSeconds) + _logger.LogInformation("The normalized audio of track {TrackId} in cache entry {CacheId} is longer than the probed duration: produced {ProducedSeconds} seconds, probed {ExpectedSeconds} seconds. The production is kept because only a shortfall is treated as truncation.", request.TrackId, cacheId, previousEndSeconds, expectedDurationSeconds); + + // The index advertises the produced end, rounded up to the next second, instead of the probed duration. A probe can underestimate a variable + // bitrate file, and a seek map that is shorter than the audio would hide the tail of every segment after the underestimated end. + int producedDurationSeconds = previousEndSeconds >= int.MaxValue + ? int.MaxValue + : (int)Math.Ceiling(previousEndSeconds); + return new NormalizedTrackIndexDto(CACHE_INDEX_VERSION, request.TrackId, request.Mode, format.Container, format.Codec, request.SegmentDurationSeconds, producedDurationSeconds, segments); + } + + /// + /// Reads the persisted index of a cached normalized track, and validates that it is complete and that every segment it names still exists. + /// + /// The opaque identifier of the cache entry. + /// The index of the cached normalized track, when it could be read. + /// when a complete and consistent cache entry could be read, otherwise . + private bool TryReadIndex(string cacheId, out NormalizedTrackIndexDto? index) + { + index = null; + if (!TranscodingCacheCoordinator.IsValidCacheId(cacheId)) + return false; + + if (_cache.TryGetIndex(cacheId, out NormalizedTrackIndexDto? cachedIndex) && cachedIndex is not null) + { + index = cachedIndex; + return true; + } + + string cachePath = Path.Combine(_cacheRoot, cacheId); + string indexPath = Path.Combine(cachePath, CACHE_INDEX_FILE_NAME); + try + { + if (!File.Exists(indexPath)) + return false; + if (new FileInfo(indexPath).Length > MAX_CACHE_INDEX_BYTES) + return false; + + string indexJson = File.ReadAllText(indexPath); + NormalizedTrackIndexDto? storedIndex = JsonSerializer.Deserialize(indexJson, s_indexJsonOptions); + if (storedIndex is null || + storedIndex.Version != CACHE_INDEX_VERSION || + storedIndex.TrackId == Guid.Empty || + storedIndex.Mode is not (PlaybackDeliveryMode.Remux or PlaybackDeliveryMode.Transcode) || + storedIndex.SegmentDurationSeconds <= 0 || + storedIndex.DurationInSeconds <= 0 || + storedIndex.Segments is null || + storedIndex.Segments.Count == 0 || + storedIndex.Segments.Count > MAX_SEGMENT_COUNT || + !PlaybackFormatCatalog.FormatsByPair.TryGetValue(PlaybackFormatCatalog.BuildPairKey(storedIndex.Container, storedIndex.Codec), out NormalizedAudioFormatDto? format)) + return false; + + decimal previousEndSeconds = 0; + for (int position = 0; position < storedIndex.Segments.Count; position++) + { + NormalizedTrackSegmentIndexDto? segment = storedIndex.Segments[position]; + // The index must already be in playback order, name a supported generated file, describe a real segment and cover the track without a hole. + decimal startDifferenceSeconds = segment is null ? 0 : segment.StartSeconds - previousEndSeconds; + if (segment is null || + segment.Index != position || + !IsValidSegmentFileName(segment.FileName) || + !TryGetSegmentNumber(segment.FileName, format.FileExtension, out int segmentNumber) || + segmentNumber != position || + segment.StartSeconds < 0 || + segment.DurationSeconds <= 0 || + segment.Length <= 0 || + startDifferenceSeconds < -SEGMENT_TIME_TOLERANCE_SECONDS || + startDifferenceSeconds > SEGMENT_TIME_TOLERANCE_SECONDS || + !File.Exists(Path.Combine(cachePath, segment.FileName))) + return false; + previousEndSeconds = segment.StartSeconds + segment.DurationSeconds; + } + + // The advertised duration must cover the produced segments, otherwise a seek map built from the index would end before the audio does. New + // indexes are written with the produced end rounded up; an index that claims less is treated as a corrupt cache entry. + if (storedIndex.DurationInSeconds < previousEndSeconds) + return false; + + index = storedIndex; + _cache.SetIndex(cacheId, storedIndex); + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + return false; + } + } + + /// + /// Reads a cached normalized track, when a complete cache entry for it exists. + /// + /// The opaque identifier of the cache entry. + /// The cached normalized track, when it could be read. + /// when a complete cache entry could be read, otherwise . + private bool TryReadCachedTrack(string cacheId, out NormalizedTrackDto? normalizedTrack) + { + normalizedTrack = null; + if (!TryReadIndex(cacheId, out NormalizedTrackIndexDto? index) || index is null) + return false; + + normalizedTrack = CreateNormalizedTrackDto(cacheId, index); + return true; + } + + /// + /// Projects a validated cache index into the normalized track the caller receives. + /// + /// The opaque identifier of the cache entry that holds the normalized audio. + /// The validated index of the cache entry. + /// The normalized track described by the index. + private static NormalizedTrackDto CreateNormalizedTrackDto(string cacheId, NormalizedTrackIndexDto index) + { + return new NormalizedTrackDto( + index.TrackId, + cacheId, + index.Mode, + index.Container, + index.Codec, + index.SegmentDurationSeconds, + index.DurationInSeconds, + [.. index.Segments.Select(segment => new NormalizedTrackSegmentDto(segment.Index, segment.StartSeconds, segment.DurationSeconds, segment.Length))]); + } + + /// + /// Builds the opaque cache identifier of a normalized track, so that a replaced or changed source file, or another track, never reuses a stale entry. + /// + /// The track, the delivery decision and the quality cap the normalized audio is produced with. + /// The full path of the stored audio file of the track. + /// The length of the stored audio file of the track, in bytes. + /// The date and time, in UTC, when the stored audio file of the track was last modified. + /// The container and codec combination the normalized audio is produced in. + /// The opaque cache identifier. + private static string BuildCacheId(NormalizedTrackRequestDto request, string sourcePath, long sourceLength, DateTime sourceLastModifiedUtc, NormalizedAudioFormatDto format) + { + string identity = string.Join('\n', + [ + request.TrackId.ToString(), + sourcePath, + sourceLength.ToString(CultureInfo.InvariantCulture), + sourceLastModifiedUtc.Ticks.ToString(CultureInfo.InvariantCulture), + request.Mode.ToString(), + format.Container, + format.Codec, + request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + request.DurationInSeconds.ToString(CultureInfo.InvariantCulture), + // The quality cap only changes the output of a lossy transcode. A remux only repackages the stored codec, and a lossless transcode is not + // capped, so including the quality for them would only create byte-identical entries that compete for the same cache budget. + request.Mode == PlaybackDeliveryMode.Transcode && !format.IsLossless ? request.Quality.ToString() : string.Empty + ]); + // The identity is hashed so the cache entry name is a fixed length file name even when the source path is long, and so the source path is not + // exposed by the directory listing of the cache. + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity))).ToLowerInvariant(); + } + + /// + /// Resolves the ffmpeg demuxer of a stored container, so that the input is never probed by content. + /// + /// The container of the stored audio file, as captured by the probe. + /// The ffmpeg demuxer of the container, when it is known. + /// when the container maps to a known demuxer, otherwise . + private static bool TryResolveSourceDemuxer(string? sourceContainer, out string sourceDemuxer) + { + sourceDemuxer = string.Empty; + if (string.IsNullOrWhiteSpace(sourceContainer)) + return false; + if (!s_sourceDemuxers.TryGetValue(sourceContainer.Trim(), out string? demuxer) || string.IsNullOrEmpty(demuxer)) + return false; + sourceDemuxer = demuxer; + return true; + } + + /// + /// Gets the bitrate cap, in kbps, of a streaming quality setting. + /// + /// The streaming quality cap of the current user. + /// The bitrate cap in kbps. uses the server default cap. + private static int GetTargetBitrateKbps(PlaybackStreamingQuality quality) + { + return quality switch + { + PlaybackStreamingQuality.Low => 96, + PlaybackStreamingQuality.Medium => 160, + PlaybackStreamingQuality.High => 320, + _ => AUTO_TRANSCODE_BITRATE_KBPS + }; + } + + /// + /// Estimates the size of the normalized audio, so that the cache is trimmed before a job starts instead of only after it finished. + /// + /// + /// A lossless delivery is estimated from the sample rate, the channel count and the bit depth of the stored audio, because a hi-res track can be + /// several times larger than the uncompressed stereo audio at 44.1 kHz and 16 bits. A FLAC stream is compressed, so its initial estimate is a fraction + /// of the uncompressed size. A remux of a lossy codec is estimated from the stored audio bitrate, not from the length of the source container, so a + /// large video file with a small audio stream is not rejected as too big for the cache. The cache monitor grows the reservation when the actual output needs more room. + /// + /// The delivery decision and the quality cap the normalized audio is produced with. + /// The container and codec combination the normalized audio is produced in. + /// The estimated size of the normalized audio, in bytes. + private static long EstimateOutputSize(NormalizedTrackRequestDto request, NormalizedAudioFormatDto format) + { + if (format.IsLossless) + { + int sampleRate = request.SampleRate > 0 ? request.SampleRate : DEFAULT_SAMPLE_RATE; + int channelCount = request.Channels > 0 ? request.Channels : DEFAULT_CHANNEL_COUNT; + // The PCM encoder of the pipeline writes 16 bit samples, while the FLAC encoder keeps the sample format of the source, so the delivered + // bit depth is used instead of the stored one for PCM. The FLAC estimate is a fraction of the uncompressed size, because the stream is compressed. + int bitDepth = string.Equals(format.Container, "WAV", StringComparison.OrdinalIgnoreCase) + ? DEFAULT_BIT_DEPTH + : request.BitDepth is > 0 ? request.BitDepth.Value : DEFAULT_BIT_DEPTH; + long uncompressedBytesPerSecond = (long)sampleRate * channelCount * bitDepth / 8; + decimal compressionRatio = string.Equals(format.Container, "FLAC", StringComparison.OrdinalIgnoreCase) ? FLAC_COMPRESSION_RATIO : 1m; + return Math.Max((long)(uncompressedBytesPerSecond * request.DurationInSeconds * compressionRatio), 1); + } + + if (request.Mode == PlaybackDeliveryMode.Remux) + { + int sourceBitrateKbps = request.Bitrate is > 0 ? request.Bitrate.Value : DEFAULT_SOURCE_BITRATE_KBPS; + decimal estimatedBytes = request.DurationInSeconds * sourceBitrateKbps * 1000m / 8m * REMUX_SIZE_MARGIN; + return Math.Max((long)estimatedBytes, 1); + } + + int bitrateKbps = GetTargetBitrateKbps(request.Quality); + return Math.Max((long)request.DurationInSeconds * bitrateKbps * 1000 / 8, 1); + } + + /// + /// Checks whether a generated segment file name has the expected prefix and extension, and extracts the segment number from it. + /// + /// The file name of the segment. + /// The expected file extension of the segment, including the leading dot. + /// The number encoded in the file name, when the name is valid. + /// when the file name is a valid generated segment name, otherwise . + private static bool TryGetSegmentNumber(string fileName, string fileExtension, out int segmentNumber) + { + segmentNumber = -1; + if (string.IsNullOrEmpty(fileName) || + !fileName.StartsWith(SEGMENT_FILE_PREFIX, StringComparison.Ordinal) || + !fileName.EndsWith(fileExtension, StringComparison.Ordinal)) + return false; + + string numberText = fileName[SEGMENT_FILE_PREFIX.Length..^fileExtension.Length]; + return numberText.Length > 0 && + int.TryParse(numberText, NumberStyles.None, CultureInfo.InvariantCulture, out segmentNumber) && + segmentNumber >= 0; + } + + /// + /// Checks whether a value is a plain file name of a produced segment. + /// + /// The value to check. + /// when the value is a plain segment file name, otherwise . + private static bool IsValidSegmentFileName(string fileName) + { + return !string.IsNullOrWhiteSpace(fileName) && + string.Equals(fileName, Path.GetFileName(fileName), StringComparison.Ordinal) && + !fileName.Contains(Path.DirectorySeparatorChar) && + !fileName.Contains(Path.AltDirectorySeparatorChar); + } + + /// + /// Monitors the size of the temporary directory of a running job and keeps its cache reservation in step with the bytes it has actually written. + /// + /// The opaque identifier of the cache entry. + /// The Id of the track whose audio is normalized. + /// The tracker of the output size of the job. + /// The capacity the job reserved in the cache. + /// The ffmpeg process of the job. + /// Cancellation token that can be used to stop the execution. + /// when the job was stopped because it could not reserve enough cache capacity, otherwise . + private async Task MonitorOutputSizeAsync(string cacheId, Guid trackId, TranscodingOutputSizeTracker outputSizeTracker, TranscodingCacheReservation reservation, Process process, CancellationToken cancellationToken) + { + try + { + while (true) + { + await Task.Delay(CACHE_SIZE_MONITOR_INTERVAL_MILLISECONDS, cancellationToken).ConfigureAwait(false); + long actualBytes = outputSizeTracker.GetCurrentSize(); + if (!reservation.TryUpdate(actualBytes, _settings.MaxCacheBytes, _evictionGracePeriod)) + { + _logger.LogWarning("A normalization job for track {TrackId} in cache entry {CacheId} could not reserve enough space in the normalized audio cache and was stopped.", trackId, cacheId); + KillProcess(process); + return true; + } + } + } + catch (OperationCanceledException) + { + return false; + } + } + + /// + /// Waits for the bounded standard error of a finished process, without pinning the job when the pipe never closes. + /// + /// The task that reads the bounded standard error of the process. + /// The bounded standard error, or an empty string when the pipe did not close within the bounded wait. + private static async Task AwaitStandardErrorAsync(Task standardErrorTask) + { + try + { + return await standardErrorTask.WaitAsync(TimeSpan.FromSeconds(PROCESS_EXIT_TIMEOUT_SECONDS)).ConfigureAwait(false); + } + catch (TimeoutException) + { + // A kill that did not take effect leaves the pipe open. The job is finished without a diagnostic instead of holding a job slot forever; the + // read task ends when the process is disposed and its standard error stream is closed. + return string.Empty; + } + } + + /// + /// Reads the standard error of a running process while keeping only its last few kilobytes, so a crafted input cannot make the server buffer an unbounded diagnostic string over the whole job timeout. + /// + /// The standard error stream of the process. + /// The bounded tail of the standard error of the process. + private static async Task ReadBoundedStandardErrorAsync(StreamReader standardError) + { + char[] buffer = new char[4096]; + StringBuilder boundedStandardError = new(); + try + { + int read; + while ((read = await standardError.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) + { + boundedStandardError.Append(buffer, 0, read); + if (boundedStandardError.Length > MAX_STANDARD_ERROR_CHARACTERS * 2) + boundedStandardError.Remove(0, boundedStandardError.Length - MAX_STANDARD_ERROR_CHARACTERS); + } + } + catch (Exception exception) when (exception is IOException or ObjectDisposedException) + { + // The pipe is closed when the process is killed; the bytes read so far are still the useful diagnostic tail. + } + + if (boundedStandardError.Length > MAX_STANDARD_ERROR_CHARACTERS) + boundedStandardError.Remove(0, boundedStandardError.Length - MAX_STANDARD_ERROR_CHARACTERS); + return boundedStandardError.ToString(); + } + + /// + /// Replaces an absolute source path in a diagnostic message with a placeholder, so the path is not written to the application log. + /// + /// The diagnostic message. + /// The path to redact, or when there is none. + /// The diagnostic message with the path replaced. + private static string RedactPath(string diagnostic, string? path) + { + if (string.IsNullOrWhiteSpace(path)) + return diagnostic; + return diagnostic.Replace(path, "[source]", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes a completed production from the shared registry, unless a newer production replaced it. + /// + /// The cache root and cache entry the production belongs to. + /// The production that completed. + private static void RemoveNormalizationJob((string CacheRoot, string CacheId) normalizationJobKey, Lazy>> normalizationJob) + { + if (s_normalizationJobs.TryGetValue(normalizationJobKey, out Lazy>>? currentJob) && ReferenceEquals(currentJob, normalizationJob)) + s_normalizationJobs.TryRemove(normalizationJobKey, out _); + } + + /// + /// Deletes a file, ignoring a file that is already gone or cannot be deleted. + /// + /// The file to delete. + private static void TryDeleteFile(string filePath) + { + try + { + if (File.Exists(filePath)) + File.Delete(filePath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // The trailing empty segment is not indexed, so a failed deletion only leaves a small unreferenced file in the cache entry. + } + } + + /// + /// Stops a child process and its descendants without waiting for it, so a cancellation callback is never blocked; the caller that awaits the process observes its exit. + /// + /// The process to stop. + private void KillProcess(Process process) + { + try + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + } + catch (Exception exception) when (exception is InvalidOperationException or NotSupportedException or Win32Exception) + { + _logger.LogDebug(exception, "The audio transcoder process could not be stopped."); + } + } + + /// + /// Stops every child process that is still running when the application exits, and cancels the productions that are still waiting for a job slot. + /// + /// The source of the event. + /// The event data. + private void OnApplicationStopping(object? sender, EventArgs eventArguments) + { + _shutdownCancellation.Cancel(); + foreach (Process process in _runningProcesses.Values) + KillProcess(process); + } + + /// + /// Releases the resources of the service when its host is disposed, including the process exit subscription that would otherwise keep it alive. + /// + /// + /// The cancellation source, the job slots and the cache coordinator are process lifetime resources that a production uses until it leaves. Shutdown + /// cancels and kills first, then waits a bounded time for every admitted production to leave before disposing them, so a production that is finishing + /// during shutdown still reports its Result instead of faulting on a disposed primitive or re-registering into a released coordinator. If the drain + /// times out the resources are intentionally left undisposed: the process is exiting and faulting the in-flight task would be worse. + /// + public void Dispose() + { + lock (_lifecycleSync) + { + if (_isDisposed) + return; + _isDisposed = true; + } + AppDomain.CurrentDomain.ProcessExit -= OnApplicationStopping; + OnApplicationStopping(this, EventArgs.Empty); + if (!_productionsDrained.Wait(TimeSpan.FromSeconds(PRODUCTION_DRAIN_TIMEOUT_SECONDS))) + { + _logger.LogWarning("The normalized audio productions did not drain within {DrainTimeoutSeconds} seconds during shutdown. The process lifetime resources are left undisposed.", PRODUCTION_DRAIN_TIMEOUT_SECONDS); + return; + } + _cache.Release(); + _jobSlots.Dispose(); + _shutdownCancellation.Dispose(); + _productionsDrained.Dispose(); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs new file mode 100644 index 00000000..7eff1ad3 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheCoordinator.cs @@ -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; + +/// +/// Coordinates the process wide size accounting, eviction and reader protection of the normalized audio cache. +/// +/// +/// 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. +/// +internal sealed class TranscodingCacheCoordinator +{ + private static readonly ConcurrentDictionary s_coordinators = new(StringComparer.Ordinal); + private static readonly Lock s_registrySync = new(); + + private readonly Lock _sync = new(); + private readonly string _cacheRoot; + private readonly Dictionary _entries = new(StringComparer.Ordinal); + private readonly Dictionary _reservations = new(StringComparer.Ordinal); + private readonly Dictionary _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 _indexCache = new(StringComparer.Ordinal); + // Entries that were over capacity but still leased. The last lease release hands them to the sweeper. + private readonly HashSet _pendingEvictions = new(StringComparer.Ordinal); + // Tombstones are consumed by one background reader, so a recursive delete never runs under _sync. + private readonly Channel _deletionQueue = Channel.CreateUnbounded(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 _initialization; + private int _referenceCount; + + /// + /// Initializes a new instance of the class. + /// + /// The absolute path of the cache root the coordinator accounts for. + private TranscodingCacheCoordinator(string cacheRoot) + { + _cacheRoot = cacheRoot; + _initialization = new Lazy(InitializeCore, LazyThreadSafetyMode.ExecutionAndPublication); + _ = Task.Run(ProcessDeletionQueueAsync); + } + + /// + /// Acquires the coordinator of a cache root, which is shared by every service instance of the process that uses the same root. + /// + /// The absolute path of the cache root. + /// The coordinator of the cache root. The caller must call when it no longer uses it. + 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; + } + } + + /// + /// Releases the caller's use of the coordinator, removing it from the process registry when the last caller releases it. + /// + 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(); + } + + /// + /// Checks whether a value is a well formed opaque cache identifier. + /// + /// The value to check. + /// when the value is a well formed cache identifier, otherwise . + public static bool IsValidCacheId(string cacheId) + { + return TranscodingCachePaths.IsValidCacheId(cacheId); + } + + /// + /// Reserves capacity for the output of a normalization job, after evicting the entries that may be evicted to make room for it. + /// + /// The estimated size of the output of the job, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// The reservation of the job, when capacity could be reserved. + /// when capacity could be reserved, otherwise . + 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; + } + } + + /// + /// Grows the reservation of a running job to the number of bytes it has actually written, after evicting entries when it has to grow. + /// + /// The identifier of the reservation. + /// The number of bytes the job has actually written, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the reservation covers the actual size, otherwise . + 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; + } + } + + /// + /// Publishes the cache entry a finished job produced, replacing any previous entry for the same identifier, and enforces the cache size limit. + /// + /// The identifier of the reservation. + /// The identifier of the produced cache entry. + /// The temporary directory that holds the complete produced entry. + /// The total size of the produced cache entry, in bytes. + /// The validated index of the produced cache entry. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// + /// 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. + /// + /// + /// 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. + /// + /// + /// when the produced entry is readable and may be served, otherwise when it was not published. + /// + 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; + } + } + + /// + /// Releases the reservation of a job that did not produce a cache entry. + /// + /// The identifier of the reservation. + public void ReleaseReservation(string reservationId) + { + lock (_sync) + _reservations.Remove(reservationId); + } + + /// + /// Records that a cache entry was served, so that the least recently used eviction and the eviction grace period keep it for longer. + /// + /// The identifier of the cache entry. + /// + /// 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. + /// + 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 }; + } + } + + /// + /// Acquires a lease that prevents a cache entry from being evicted while a reader holds it. + /// + /// The identifier of the cache entry. + /// The lease, which must be disposed when the reader is done with the entry. + public TranscodingCacheReaderLease AcquireReaderLease(string cacheId) + { + EnsureInitialized(); + lock (_sync) + _readerLeaseCounts[cacheId] = _readerLeaseCounts.TryGetValue(cacheId, out int leaseCount) ? leaseCount + 1 : 1; + return new TranscodingCacheReaderLease(this, cacheId); + } + + /// + /// Gets the validated index of a cache entry, when it was already read and validated by this process. + /// + /// The identifier of the cache entry. + /// The validated index of the cache entry, when it is cached. + /// when the validated index is cached, otherwise . + public bool TryGetIndex(string cacheId, out NormalizedTrackIndexDto? index) + { + return _indexCache.TryGetValue(cacheId, out index); + } + + /// + /// 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. + /// + /// The identifier of the cache entry. + /// The validated index of the cache entry. + public void SetIndex(string cacheId, NormalizedTrackIndexDto index) + { + _indexCache[cacheId] = index; + } + + /// + /// Releases a lease that a reader held on a cache entry. + /// + /// The identifier of the cache entry. + 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); + } + } + } + + /// + /// Gets the total size of a directory, in bytes, without letting a file that disappears mid-walk discard the rest of the measurement. + /// + /// The directory whose size is computed. + /// The total size of the directory, in bytes. + internal static long GetDirectorySize(string directoryPath) + { + long size = 0; + Stack pendingDirectories = new(); + pendingDirectories.Push(directoryPath); + while (pendingDirectories.Count > 0) + { + string currentDirectory = pendingDirectories.Pop(); + try + { + using (IEnumerator 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 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; + } + + /// + /// Runs the once-only initialization of the entries that already exist in the cache root, outside the coordinator lock. + /// + private void EnsureInitialized() + { + _ = _initialization.Value; + } + + /// + /// Reads the entries that already exist in the cache root, so a cache that survived a restart is still accounted for. + /// + /// when the accounting was populated. + /// + /// 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. + /// + private bool InitializeCore() + { + Dictionary entries = new(StringComparer.Ordinal); + List 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 entry in entries) + _entries[entry.Key] = entry.Value; + foreach (string tombstonePath in tombstones) + _deletionQueue.Writer.TryWrite(tombstonePath); + return true; + } + + /// + /// Gets the combined size of the cached entries and the reservations of the running jobs, in bytes. + /// + /// The combined size of the cached entries and the reservations, in bytes. + private long GetTotalSize() + { + long entriesSize = _entries.Values.Sum(entry => entry.Size); + long reservationsSize = _reservations.Values.Sum(); + return entriesSize + reservationsSize; + } + + /// + /// Detaches the least recently used unprotected entries until the required number of bytes fits under the cache size limit. + /// + /// The number of additional bytes that must fit. + /// The current combined size of the entries and reservations, in bytes. + /// The cache entry that must never be evicted by this pass, or when none is excluded. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the required number of bytes fits, otherwise . + 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; + } + + /// + /// Checks whether a reader currently holds a cache entry. + /// + /// The identifier of the cache entry. + /// when at least one reader holds the entry, otherwise . + private bool IsLeased(string cacheId) + { + return _readerLeaseCounts.TryGetValue(cacheId, out int leaseCount) && leaseCount > 0; + } + + /// + /// Removes an entry from the cache accounting and schedules its directory for deletion. + /// + /// The identifier of the cache entry. + /// The entry to detach. + /// when the entry was detached, otherwise when its directory could not be renamed. + 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; + } + + /// + /// Moves a directory out of the live cache and schedules it for deletion. + /// + /// The directory to detach. + /// when the directory was detached or no longer exists, otherwise . + 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; + } + + /// + /// Deletes the directories that were detached from the cache. + /// + private async Task ProcessDeletionQueueAsync() + { + await foreach (string directoryPath in _deletionQueue.Reader.ReadAllAsync().ConfigureAwait(false)) + TranscodingCachePaths.TryDeleteDirectory(directoryPath); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs new file mode 100644 index 00000000..a840329e --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheLeaseStream.cs @@ -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; + +/// +/// A read stream over a cached segment that keeps the reader lease of its cache entry until the stream is disposed. +/// +internal sealed class TranscodingCacheLeaseStream : Stream +{ + private readonly Stream _innerStream; + private readonly TranscodingCacheReaderLease _lease; + private bool _isDisposed; + + /// + /// Gets whether the stream supports reading. + /// + public override bool CanRead => _innerStream.CanRead; + + /// + /// Gets whether the stream supports seeking. + /// + public override bool CanSeek => _innerStream.CanSeek; + + /// + /// Gets whether the stream supports writing. + /// + public override bool CanWrite => _innerStream.CanWrite; + + /// + /// Gets the length of the stream, in bytes. + /// + public override long Length => _innerStream.Length; + + /// + /// Gets or sets the position within the stream. + /// + public override long Position + { + get { return _innerStream.Position; } + set { _innerStream.Position = value; } + } + + /// + /// Initializes a new instance of the class. + /// + /// The stream over the cached segment. + /// The reader lease that protects the cache entry of the segment. + internal TranscodingCacheLeaseStream(Stream innerStream, TranscodingCacheReaderLease lease) + { + _innerStream = innerStream; + _lease = lease; + } + + /// + /// Clears the buffers of the stream. + /// + public override void Flush() + { + _innerStream.Flush(); + } + + /// + /// Reads a block of bytes from the stream. + /// + /// The buffer to read into. + /// The offset in the buffer at which to start writing. + /// The maximum number of bytes to read. + /// The number of bytes read. + public override int Read(byte[] buffer, int offset, int count) + { + return _innerStream.Read(buffer, offset, count); + } + + /// + /// Reads a block of bytes from the stream. + /// + /// The buffer to read into. + /// The number of bytes read. + public override int Read(Span buffer) + { + return _innerStream.Read(buffer); + } + + /// + /// Reads a block of bytes from the stream asynchronously. + /// + /// The buffer to read into. + /// The offset in the buffer at which to start writing. + /// The maximum number of bytes to read. + /// Cancellation token that can be used to stop the execution. + /// The number of bytes read. + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return _innerStream.ReadAsync(buffer, offset, count, cancellationToken); + } + + /// + /// Reads a block of bytes from the stream asynchronously. + /// + /// The buffer to read into. + /// Cancellation token that can be used to stop the execution. + /// The number of bytes read. + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + return _innerStream.ReadAsync(buffer, cancellationToken); + } + + /// + /// Sets the position within the stream. + /// + /// The offset relative to . + /// The reference point used to obtain the new position. + /// The new position within the stream. + public override long Seek(long offset, SeekOrigin origin) + { + return _innerStream.Seek(offset, origin); + } + + /// + /// Sets the length of the stream. + /// + /// The new length of the stream, in bytes. + public override void SetLength(long value) + { + _innerStream.SetLength(value); + } + + /// + /// Writes a block of bytes to the stream. + /// + /// The buffer to write from. + /// The offset in the buffer at which to start reading. + /// The number of bytes to write. + public override void Write(byte[] buffer, int offset, int count) + { + _innerStream.Write(buffer, offset, count); + } + + /// + /// Writes a block of bytes to the stream. + /// + /// The buffer to write from. + public override void Write(ReadOnlySpan buffer) + { + _innerStream.Write(buffer); + } + + /// + /// Writes a block of bytes to the stream asynchronously. + /// + /// The buffer to write from. + /// The offset in the buffer at which to start reading. + /// The number of bytes to write. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous write operation. + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return _innerStream.WriteAsync(buffer, offset, count, cancellationToken); + } + + /// + /// Writes a block of bytes to the stream asynchronously. + /// + /// The buffer to write from. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous write operation. + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + return _innerStream.WriteAsync(buffer, cancellationToken); + } + + /// + /// Releases the inner stream and the reader lease. + /// + /// Whether the method is called from the method. + 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); + } + + /// + /// Releases the inner stream and the reader lease asynchronously. + /// + /// A task that represents the asynchronous dispose operation. + 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); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs new file mode 100644 index 00000000..070246f6 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReaderLease.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Represents a reader's lease on a cache entry, which keeps the entry from being evicted until the lease is released. +/// +[DebuggerDisplay("CacheId: {_cacheId}")] +internal sealed class TranscodingCacheReaderLease : IDisposable +{ + private readonly TranscodingCacheCoordinator _coordinator; + private readonly string _cacheId; + private bool _isDisposed; + + /// + /// Initializes a new instance of the class. + /// + /// The coordinator that accounts for the lease. + /// The identifier of the cache entry the lease holds. + internal TranscodingCacheReaderLease(TranscodingCacheCoordinator coordinator, string cacheId) + { + _coordinator = coordinator; + _cacheId = cacheId; + } + + /// + /// Releases the lease, so the cache entry may be evicted again. + /// + public void Dispose() + { + if (_isDisposed) + return; + _isDisposed = true; + _coordinator.ReleaseReaderLease(_cacheId); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs new file mode 100644 index 00000000..6e7114f1 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingCacheReservation.cs @@ -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; + +/// +/// Represents the capacity a running normalization job reserved in the normalized audio cache, until it either produces an entry or is aborted. +/// +[DebuggerDisplay("Id: {Id}")] +internal sealed class TranscodingCacheReservation : IDisposable +{ + private readonly TranscodingCacheCoordinator _coordinator; + private bool _isCompleted; + private bool _isDisposed; + + /// + /// Gets the identifier of the reservation. + /// + internal string Id { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The coordinator that accounts for the reservation. + /// The identifier of the reservation. + internal TranscodingCacheReservation(TranscodingCacheCoordinator coordinator, string id) + { + _coordinator = coordinator; + Id = id; + } + + /// + /// Updates the reservation to the number of bytes the job has actually written, growing it when the output is larger than the estimate. + /// + /// The number of bytes the job has actually written, in bytes. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the reservation covers the actual size, otherwise . + public bool TryUpdate(long actualBytes, long maxCacheBytes, TimeSpan gracePeriod) + { + if (_isCompleted || _isDisposed) + return false; + return _coordinator.TryGrow(Id, actualBytes, maxCacheBytes, gracePeriod); + } + + /// + /// Replaces the reservation with the produced cache entry. + /// + /// The identifier of the produced cache entry. + /// The temporary directory that holds the complete produced entry. + /// The total size of the produced cache entry, in bytes. + /// The validated index of the produced cache entry. + /// The maximum total size of the cache, in bytes. + /// The period during which a recently produced or served entry is protected from eviction. + /// when the produced entry remains readable even though it exceeds the cache limit, otherwise . + /// when a reader still holds the previous entry of the same cache identifier, so the replacement was not attempted. + /// when the produced entry is readable and may be served, otherwise when it was not published. + 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; + } + + /// + /// Releases the reservation when the job did not produce a cache entry. + /// + public void Dispose() + { + if (_isDisposed) + return; + _isDisposed = true; + if (!_isCompleted) + _coordinator.ReleaseReservation(Id); + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs new file mode 100644 index 00000000..1e5870ba --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingOutputSizeTracker.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.IO; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Tracks the size of the temporary output of a running normalization job without walking the growing directory on every monitor tick. +/// +/// +/// 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). +/// +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; + + /// + /// Initializes a new instance of the class. + /// + /// The temporary directory the job writes into. + /// The prefix of the generated segment file names. + /// The file extension of a segment, including the leading dot. + /// The file name of the segment list written by ffmpeg. + internal TranscodingOutputSizeTracker(string directoryPath, string segmentFilePrefix, string segmentFileExtension, string segmentListFileName) + { + _directoryPath = directoryPath; + _segmentFilePrefix = segmentFilePrefix; + _segmentFileExtension = segmentFileExtension; + _segmentListPath = Path.Combine(directoryPath, segmentListFileName); + } + + /// + /// Gets the current total size of the produced output, in bytes. + /// + /// The current total size of the produced output, in bytes. + 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; + } + + /// + /// Updates the total with the growth of the segment that is currently being written, when there is one. + /// + private void RecalculateLastSegment() + { + if (_lastSegmentPath is null) + return; + long currentLength = GetFileLength(_lastSegmentPath, _lastSegmentLength); + _totalBytes += currentLength - _lastSegmentLength; + _lastSegmentLength = currentLength; + } + + /// + /// Updates the total with the growth of the segment list. + /// + private void RecalculateSegmentList() + { + long currentLength = GetFileLength(_segmentListPath, _segmentListLength); + _totalBytes += currentLength - _segmentListLength; + _segmentListLength = currentLength; + } + + /// + /// Adds every segment that has appeared since the previous tick, in sequence, and leaves the last one as the growing segment. + /// + 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++; + } + } + + /// + /// Gets the length of a file, falling back to its last known length when it cannot currently be measured. + /// + /// The file to measure. + /// The length to use when the file cannot be measured. + /// The current or fallback length of the file, in bytes. + 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; + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs new file mode 100644 index 00000000..93b69bc7 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingStartupInitializer.cs @@ -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; + +/// +/// Startup component that owns the normalized audio cache lifecycle and verifies the ffmpeg toolchain before any playback request is served. +/// +/// +/// 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 , 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. +/// +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 _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The audio normalization configuration options. + /// The status that records the outcome of the ffmpeg probe for the normalization service. + /// The logger for this startup component. + public TranscodingStartupInitializer(IOptions options, TranscodingToolchainStatus toolchainStatus, ILogger logger) + { + _settings = options.Value; + _toolchainStatus = toolchainStatus; + _logger = logger; + } + + /// + /// Cleans and recreates the cache directory, then probes the ffmpeg binary for the encoders the pipeline uses. + /// + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous startup operation. + 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."); + } + } + + /// + /// Stops the startup component, which has no resources of its own to release. + /// + /// Cancellation token that can be used to stop the execution. + /// A completed task. + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + /// + /// Probes the ffmpeg binary for the encoders the catalog can produce, without failing the host when it is missing or incomplete. + /// + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous probe. + 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 standardOutputTask = process.StandardOutput.ReadToEndAsync(linkedCancellationTokenSource.Token); + Task 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 requiredEncoders = [.. PlaybackFormatCatalog.Formats + .Select(format => format.EncoderName) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + List 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); + } + } + + /// + /// Checks whether the encoder listing of ffmpeg contains the provided encoder name. + /// + /// The output of the ffmpeg encoder listing. + /// The encoder name to look for. + /// when the encoder is listed, otherwise . + 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 " "; the encoder name is always the second token. + if (tokens.Length >= 2 && string.Equals(tokens[1], encoderName, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs new file mode 100644 index 00000000..d6e0e717 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TranscodingToolchainStatus.cs @@ -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; + +/// +/// 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. +/// +/// +/// 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. +/// +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 _missingEncoders = []; + + /// + /// Initializes a new instance of the class, which starts as available until the startup probe records its outcome. + /// + public TranscodingToolchainStatus() + { + } + + /// + /// Gets a value indicating whether the ffmpeg binary can run at all. + /// + public bool IsTranscoderAvailable => _isTranscoderAvailable; + + /// + /// Records that the probe found a usable ffmpeg binary with every encoder the catalog needs. + /// + 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; + } + + /// + /// Records that the ffmpeg binary could not be started or did not answer the probe. + /// + public void RecordUnavailable() + { + _isTranscoderAvailable = false; + _missingEncoders = []; + } + + /// + /// Records that ffmpeg runs, but that some of the encoders the catalog needs are missing. + /// + /// The names of the encoders the startup probe did not find. + public void RecordMissingEncoders(IEnumerable missingEncoders) + { + _missingEncoders = missingEncoders.ToFrozenSet(StringComparer.OrdinalIgnoreCase); + _isTranscoderAvailable = true; + } + + /// + /// Checks whether an encoder can be used for a lossy or lossless transcode. + /// + /// The name of the ffmpeg encoder the delivery format needs. + /// when ffmpeg runs and the encoder was found, otherwise . + public bool IsEncoderAvailable(string encoderName) + { + return _isTranscoderAvailable && !_missingEncoders.Contains(encoderName); + } +} diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 1ffd9bd4..68c0bb03 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -26,6 +26,7 @@ + diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index dfeb872c..b984fd84 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -17,6 +17,14 @@ "MaxSingleFileBytes": 6291456, "MaxEntries": 250 }, + "TranscodingSettings": { + "FfmpegPath": "ffmpeg", + "MaxConcurrentJobs": 2, + "MaxCacheBytes": 2147483648, + "JobTimeoutSeconds": 900, + "EvictionGraceSeconds": 120, + "CacheDirectory": null + }, "ConnectionStrings": { "DefaultConnection": "Server=;Database=;User Id=;Password=;" }, diff --git a/src/Lumina.Presentation.Api/Dockerfile b/src/Lumina.Presentation.Api/Dockerfile index 297fdfe6..65811f8c 100644 --- a/src/Lumina.Presentation.Api/Dockerfile +++ b/src/Lumina.Presentation.Api/Dockerfile @@ -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 diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 73d8fe89..ef9ecbbc 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -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; diff --git a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs index 283aabfe..345f01fa 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/AudioLibrary/PlaybackStreamingQuality.cs @@ -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. /// /// -/// 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. /// [DebuggerDisplay("{ToString()}")] public enum PlaybackStreamingQuality { /// - /// 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. /// Auto, /// - /// Normalized audio is capped at 96 kbps. + /// A lossy normalized audio stream is capped at 96 kbps. /// Low, /// - /// Normalized audio is capped at 160 kbps. + /// A lossy normalized audio stream is capped at 160 kbps. /// Medium, /// - /// Normalized audio is capped at 320 kbps. + /// A lossy normalized audio stream is capped at 320 kbps. /// High, } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js index 9d13c62a..a6428985 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -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);