diff --git a/docs/manual/installation/index.md b/docs/manual/installation/index.md index 4054ee27..f2a933f3 100644 --- a/docs/manual/installation/index.md +++ b/docs/manual/installation/index.md @@ -115,14 +115,14 @@ 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. | +| `TranscodingSettings:FfmpegPath`, `MaxConcurrentJobs`, `MaxConcurrentJobsPerUser`, `MaxCacheBytes`, `JobTimeoutSeconds`, `EvictionGraceSeconds`, `CacheDirectory` | API server | Where the ffmpeg binary is, how many audio normalization jobs may run at once in total and per user, 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. +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. Playback delivery handles are also process local: in a load balanced multi-instance deployment, a track's manifest and its subsequent segment requests must reach the same API instance, so configure sticky routing for them as described for SignalR below. 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 diff --git a/docs/manual/using-lumina/index.md b/docs/manual/using-lumina/index.md index 21555490..bcdc3981 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. 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). +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 (for a track the server has to normalize, this keeps its bounded one-segment lookahead filled rather than downloading the whole file), 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/api/library/audio-library/music-library/Api.Tracks.md b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md index a518e8a3..4c5a0b53 100644 --- a/docs/technical/api/library/audio-library/music-library/Api.Tracks.md +++ b/docs/technical/api/library/audio-library/music-library/Api.Tracks.md @@ -11,6 +11,9 @@ - [Stream Track](#stream-track) - [Stream Track Request](#stream-track-request) - [Stream Track Response](#stream-track-response) + - [Stream Track Segment](#stream-track-segment) + - [Stream Track Segment Request](#stream-track-segment-request) + - [Stream Track Segment Response](#stream-track-segment-response) - [Get Playback Manifest](#get-playback-manifest) - [Get Playback Manifest Request](#get-playback-manifest-request) - [Get Playback Manifest Response](#get-playback-manifest-response) @@ -347,6 +350,32 @@ Accept-Ranges: bytes The response is the raw bytes of the audio file, served with the media type of the file when it is an audio type, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private` and `Vary: Authorization`, together with a `Last-Modified` and an `ETag` derived from the size and the modification time of the file. +### Stream Track Segment + +#### Stream Track Segment Request + +```js +GET api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0 +Authorization: Bearer +``` + +Streams one segment of the normalized audio of the track identified by the route. A track the player cannot play as it is stored is delivered as time addressed segments instead of bytes: the server produces the whole track into a temporary cache with a target segment duration of `segmentDurationSeconds` seconds, cutting at the first packet at or after each target boundary, and serves each produced segment as an independent container file. A real segment start can therefore differ from an exact multiple of the target duration, and a consumer must use the start the response reports rather than assume the grid. The segment index is zero based. + +The `deliveryId` is the opaque handle the playback manifest reported in `deliveryId`. It is bound to the user the manifest was issued to and to the track it describes, and it captures the delivery decision, the quality cap, the source file version and the library content locations the manifest declared. The segment route resolves that handle instead of recomputing the delivery from a capability list, so the segments always belong to exactly the delivery the manifest declared. Library ownership is re-evaluated on every segment request, so revoked access stops playback immediately; the track membership and the content locations are the ones captured at manifest time, so a deleted track row whose file remains, or a removed content location, stays streamable until the handle expires, within 12 hours. A handle that is unknown, expired, or was issued to another user or track is reported as not found. A track the manifest declared as a direct play has no delivery handle at all, so a segment request for it is also reported as not found with `PlaybackDeliveryNotFound`, never as the end of the audio. A source file that changed since the manifest declared the delivery is reported as a conflict instead of starting a second production. The handle is exactly 32 lowercase hexadecimal characters, and a value that does not match that format is rejected rather than normalized into another handle. + +A byte range cannot be mapped to a time in this delivery, so a player seeks by choosing the segment that covers the target time. A segment is a small independent container file that is already fetched as a whole, so the player reads it from its first packet and discards the packets that end before the target; it never seeks inside the container itself, because a container that numbers its frames across the whole track would then add that number to the segment offset twice. The playback manifest reports the root relative path of this route in `segmentStreamPathTemplate`, with `{deliveryId}` and `{segmentIndex}` placeholders, and the player expands both from the manifest. A segment is served to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track. + +#### Stream Track Segment Response + +```js +200 Ok +Content-Type: audio/aac +Content-Length: 240128 +``` + +The response is the raw bytes of one produced segment, served with the media type of the delivered container when the server can name it, or `application/octet-stream` otherwise. Every response carries `X-Content-Type-Options: nosniff`, `Cache-Control: private, no-store`, `Vary: Authorization`, `X-Lumina-Segment-Count`, the number of segments the production holds, and `X-Segment-Start-Seconds`, the exact start of the segment on the track timeline, in seconds. The count tells a player where the audio ends without probing for the end with a request that returns not found, and the start lets it offset the packets of a container that numbers its frames from the start of the track, instead of assuming that a segment starts at an exact multiple of its duration. Range requests are not used: the segment is the addressing unit, and the next segment is a separate request. The first request for a track can take longer than the following ones, because the whole normalized audio is produced and cached before its first segment is published. A segment index that the production does not hold is reported as not found with the `NormalizedTrackSegmentNotFound` detail, which is the only not-found answer that means the end of the audio. A track, library or audio file that disappeared, a delivery handle that is unknown, expired, or was issued to another user or track, and a cache entry that was evicted, are reported with their own not-found details instead, and a request that arrives while every normalization job slot is in use is reported as unavailable (`503`), because it is a transient condition that a player retries. A delivery handle whose captured shape is not time addressed segments is a conflict (`409`), because the segment route cannot index it. + + ### Get Playback Manifest #### Get Playback Manifest Request @@ -377,17 +406,36 @@ Returns the playback manifest of the track identified by the route: the format o "replayGainTrackPeak": 0.9877, "replayGainAlbumGain": -6.8, "replayGainAlbumPeak": 0.9999, - "directPlay": true, + "isDirectPlay": true, "deliveryContainer": null, "deliveryCodec": null, "deliveryShape": null, "segmentDurationSeconds": null, - "seekable": true, - "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream" + "isSeekable": true, + "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream", + "deliveryId": null, + "segmentStreamPathTemplate": null } ``` -When the player can play the stored audio as it is, `directPlay` is `true`, and `deliveryContainer`, `deliveryCodec`, `deliveryShape` and `segmentDurationSeconds` are `null`, because the delivery is the stored file itself. When it cannot, `directPlay` is `false`, and those fields name the container, the codec, the addressing the server produces instead, and the length in seconds of each of its time addressed segments. A normalized delivery is always addressed as `TimeAddressedSegments`, and `segmentDurationSeconds` is the length of each of its segments, so that the server that produces the segments and the player that consumes them agree on it without duplicating the value on both sides. `seekable` reports whether the delivered audio can be seeked by the player. `streamPath` is relative to the API, without a host or a scheme, so that a client reaches the stream through its own application rather than the API server directly. +When the player can play the stored audio as it is, `isDirectPlay` is `true`, and `deliveryContainer`, `deliveryCodec`, `deliveryShape`, `segmentDurationSeconds`, `deliveryId` and `segmentStreamPathTemplate` are `null`, because the delivery is the stored file itself, addressed and seeked by byte range. When it cannot, `isDirectPlay` is `false`, and those fields name the container, the codec, the addressing the server produces instead, the length in seconds of each of its time addressed segments, the opaque handle of the delivery, and the root relative path template of the segment route, with `{deliveryId}` and `{segmentIndex}` placeholders. `durationInSeconds` is the probed duration; a normalized production can be slightly longer or shorter, and its exact produced duration is reported by the `X-Lumina-Track-Duration-Seconds` header of its segments. A normalized delivery is always addressed as `TimeAddressedSegments`, and `segmentDurationSeconds` is the nominal length of each of its segments, so that the server that produces the segments and the player that consumes them agree on the target without duplicating the value on both sides. The `deliveryId` binds the delivery to the user and the track, and it captures the quality cap and the source file version that were in effect when the manifest was read, so a segment request addresses exactly that delivery instead of recomputing it. A player that cannot play a track directly fetches each segment from that template in index order and seeks by segment index, never by byte range. `isSeekable` reports whether the delivered audio can be seeked by the player. `streamPath` is relative to the API, without a host or a scheme, so that a client reaches the stream through its own application rather than the API server directly. + +For example, a delivery of a track the player cannot decode is declared as follows: + +```json +{ + "trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f", + "isDirectPlay": false, + "deliveryContainer": "AAC", + "deliveryCodec": "AAC", + "deliveryShape": "TimeAddressedSegments", + "segmentDurationSeconds": 6, + "isSeekable": true, + "streamPath": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream", + "deliveryId": "8f14e45fceea167a5a36dedd4bea2543", + "segmentStreamPathTemplate": "/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/stream/deliveries/{deliveryId}/segments/{segmentIndex}" +} +``` ### Update Track 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 41252610..f438f466 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 @@ -43,7 +43,20 @@ GET /api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{tr ### Delivery shape -The `TimeAddressedSegments` delivery shape is a sequence of fixed duration segments addressed and seeked by time, so that finding a time never requires mapping a byte range to it. The segment duration is 6 seconds, and it is carried in the delivery decision so that the producer of the segments and the player agree on it. Direct play is `ByteRangeSeekable`, because the original file is served by the existing range-capable stream endpoint. +The `TimeAddressedSegments` delivery shape is a sequence of approximately fixed duration segments addressed and seeked by time, so that finding a time never requires mapping a byte range to it. The nominal segment duration is 6 seconds, and it is carried in the delivery decision so that the producer of the segments and the player agree on it. A segment is cut at the first packet at or after its nominal boundary, so its real start is not always an exact multiple of the nominal duration; the producer records the real start in its index, and the segment route reports it in a response header. Direct play is `ByteRangeSeekable`, because the original file is served by the existing range-capable stream endpoint. + +### Segment addressing + +The segments are exposed through a dedicated segment route, `.../stream/deliveries/{deliveryId}/segments/{segmentIndex}`, which extends the track stream endpoint's contract. The playback manifest carries its relative path in `segmentStreamPathTemplate`, with `{deliveryId}` and `{segmentIndex}` placeholders, and the web application rewrites that path to its own segment proxy so that the browser never reaches the API server. The manifest also reports the opaque `deliveryId` the placeholders are expanded with. + +- An index addresses a whole segment, so no byte range is ever sent for a normalized delivery. +- The delivery handle the manifest issued is the only authority on the delivery of the segments. It is a random, opaque value bound to the user and the track, and it captures the delivery decision, the quality cap and the source file version the manifest declared. The segment route resolves it instead of recomputing the decision from a capability list, rereading the user's quality setting, or restating a file that may have changed. A changed file is rejected as a conflict rather than starting a second production whose segments would be mixed with the declared one. +- Library ownership is still evaluated on every segment request, so revoked access stops playback immediately. The track membership and the library content locations are the ones captured when the manifest was issued, so deleting a track row while its file remains, or removing a content location, can keep that media streamable until the handle expires. That is the deliberate trade-off for not reloading the track and library graph for every six second segment; the handle lifetime is bounded to 12 hours. +- The handles are process local, like the normalized audio cache they address. They expire after a bounded lifetime, are bounded globally and per user, and a repeated manifest for the same delivery inputs reuses the existing handle, so the registry cannot grow without bound. Expired handles are removed in issue order from a queue, so the sweep is amortized constant time rather than a scan of every handle. +- A production is atomic: the first segment request may wait for the whole normalized track to be produced and cached, and the following segment requests are served from that cache. +- The player keeps a bounded lookahead of one segment ahead of the segment the demuxer consumed, so the link is not idle between segments and the streamed indicator can run ahead. The lookahead stops while playback is paused unless the user enabled the keep-downloading-while-paused preference, and it never advances itself, so it cannot turn into a full download of the track. +- Gapless prefetch starts only near the end of the current track, not at load time. A normalized next track therefore transitions without a gap only when its production is already cached or finishes within that lead; otherwise it starts normally at the boundary. The lead is deliberately shorter than a long production, because holding a normalization slot for a track the user may never reach is worse than a small gap. +- The player keeps every segment it has fetched for the lifetime of the track, so seeking back into a fetched segment does not fetch it again. A seek reads the target segment from its first packet and drops the packets that end before the target, instead of seeking inside the segment: a container that numbers its frames across the whole track would otherwise add that number to the segment offset twice. A segment is short, so reading it from its start is exact for every delivered container. ## Consequences @@ -63,7 +76,7 @@ The `TimeAddressedSegments` delivery shape is a sequence of fixed duration segme |---|---| | The probe reports a codec as a free form description that does not name the codec the player advertises | The stored description is canonicalized to the advertised codec names before comparison, and the MPEG layer is matched by its layer number, so a description that names no decodable codec is left unmatched and forces a transcode | | A player advertises a container the server cannot produce | The delivered container is always chosen from the containers the server produces the codec in, never from the container the player names, so a client supplied container never reaches the transcoder or a cache name; a codec the player cannot be served in any server container is not used | -| The segment duration drifts between the server and the player | It is part of the delivery decision carried by the manifest, not a constant duplicated on both sides | +| The real segment start drifts from the nominal grid | The nominal duration is carried by the manifest, and the exact indexed start of each segment is reported in `X-Segment-Start-Seconds` and used by the player, so neither side assumes an exact grid | ## Alternatives Considered diff --git a/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http new file mode 100644 index 00000000..2bd235ae --- /dev/null +++ b/docs/technical/requests/library/audio-library/music-library/tracks/StreamTrackSegment.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/{{$guid}}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0 +Authorization: Bearer {{ACCESS_TOKEN}} 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 index 4e28eb18..358f52de 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackRequestDto.cs @@ -11,25 +11,29 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.P /// 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 Id of the user whose request starts the production. It is used for the per-user admission limit, and never for the cache identity. /// 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 container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. /// 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 stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. /// 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. +/// The length the source file had when the delivery was declared, in bytes. The production is rejected when the file no longer matches. +/// The last modification time the source file had when the delivery was declared. The production is rejected when the file no longer matches. [DebuggerDisplay("TrackId: {TrackId} Mode: {Mode} Container: {Container} Codec: {Codec}")] public sealed record NormalizedTrackRequestDto( Guid TrackId, + Guid UserId, string SourcePath, IReadOnlyList AllowedRoots, string? SourceContainer, @@ -42,5 +46,7 @@ public sealed record NormalizedTrackRequestDto( int SampleRate, int Channels, int? BitDepth, - PlaybackStreamingQuality Quality + PlaybackStreamingQuality Quality, + long SourceLength, + DateTime SourceLastModifiedUtc ); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs new file mode 100644 index 00000000..1b767175 --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/NormalizedTrackSegmentDataDto.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +using System.IO; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for a single produced segment of the normalized audio of a track, ready to be written to the response. +/// +/// +/// The segment owns a live stream over a leased cache entry, so it is an internal delivery object of the API rather than a serializable +/// contract. The caller must dispose the stream once the response is written, which releases the cache reader lease. +/// +/// The read stream over the segment, which the caller owns and must release once the response is written. +/// The length of the segment, in bytes, taken from the index of the normalized audio. +/// The exact start of the segment on the track timeline, in seconds, taken from the index of the normalized audio. +/// The container of the delivered audio, used to resolve the media type of the segment. +/// The number of segments the production holds, so the caller can tell the end of the audio from a missing segment. +/// The duration of the produced normalized audio, in seconds, which can differ from the probed duration. +[DebuggerDisplay("Length: {Length} StartSeconds: {StartSeconds} Container: {Container} SegmentCount: {SegmentCount}")] +public sealed record NormalizedTrackSegmentDataDto( + Stream Content, + long Length, + decimal StartSeconds, + string Container, + int SegmentCount, + int DurationInSeconds +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs new file mode 100644 index 00000000..5ba7674d --- /dev/null +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleDto.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Data transfer object for the delivery a playback manifest issued to a user. It composes the exact normalization request the delivery declares, +/// so a new production input is added in one place and can never drift between the cache identity and the handle. +/// +/// The complete normalization request the delivery declares, including its user, track, decision, quality and source identity. +/// The shape the delivered audio is addressed by, which must be time addressed segments for a segment route. +/// The Id of the library the track belongs to, so the segment route can scope the delivery without querying it again. +/// The Id of the album the track belongs to, so the segment route can scope the delivery without querying it again. +/// The Id of the artist that owns the album, so the segment route can scope the delivery without querying it again. +[DebuggerDisplay("TrackId: {Request.TrackId} Mode: {Request.Mode} Container: {Request.Container} Codec: {Request.Codec}")] +public sealed record PlaybackDeliveryHandleDto( + NormalizedTrackRequestDto Request, + PlaybackDeliveryShape Shape, + Guid LibraryId, + Guid AlbumId, + Guid ArtistId +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs index 08a3d50a..c9059377 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackPlaybackManifestDto.cs @@ -7,56 +7,30 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T /// /// Data transfer object for the stored probe result of a track, containing only the fields a playback manifest is built from. /// +/// The file system path of the stored audio file of the track, used to bind a normalized delivery to the file version it was declared for. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. +/// The audio codec used by the audio file of the track, if applicable. +/// The duration of the audio of the track in seconds. +/// The sample rate of the audio of the track in Hz. +/// The number of audio channels of the track. +/// The bit depth of the audio of the track, if applicable. +/// The bitrate of the audio of the track, in kbps, if applicable. +/// The ReplayGain track gain of the track, in decibels, if applicable. +/// The ReplayGain track peak of the track, if applicable. +/// The ReplayGain album gain of the track, in decibels, if applicable. +/// The ReplayGain album peak of the track, if applicable. [DebuggerDisplay("Container: {Container} Codec: {AudioCodec}")] -public sealed record TrackPlaybackManifestDto -{ - /// - /// Gets the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. - /// - public string? Container { get; init; } - - /// - /// Gets the audio codec used by the audio file of the track, if applicable. - /// - public string? AudioCodec { get; init; } - - /// - /// Gets the duration of the audio of the track in seconds. - /// - public int DurationInSeconds { get; init; } - - /// - /// Gets the sample rate of the audio of the track in Hz. - /// - public int SampleRate { get; init; } - - /// - /// Gets the number of audio channels of the track. - /// - public int Channels { get; init; } - - /// - /// Gets the bit depth of the audio of the track, if applicable. - /// - public int? BitDepth { get; init; } - - /// - /// Gets the ReplayGain track gain of the track, in decibels, if applicable. - /// - public decimal? ReplayGainTrackGain { get; init; } - - /// - /// Gets the ReplayGain track peak of the track, if applicable. - /// - public decimal? ReplayGainTrackPeak { get; init; } - - /// - /// Gets the ReplayGain album gain of the track, in decibels, if applicable. - /// - public decimal? ReplayGainAlbumGain { get; init; } - - /// - /// Gets the ReplayGain album peak of the track, if applicable. - /// - public decimal? ReplayGainAlbumPeak { get; init; } -} +public sealed record TrackPlaybackManifestDto( + string Path, + string? Container, + string? AudioCodec, + int DurationInSeconds, + int SampleRate, + int Channels, + int? BitDepth, + int? Bitrate, + decimal? ReplayGainTrackGain, + decimal? ReplayGainTrackPeak, + decimal? ReplayGainAlbumGain, + decimal? ReplayGainAlbumPeak +); diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs index 3ecc0f97..bef2ea79 100644 --- a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs +++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDto.cs @@ -7,55 +7,27 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T /// /// Data transfer object for a track, containing the data needed to stream, or to describe the streaming of, its audio file. /// -public sealed record TrackStreamDto -{ - /// - /// Gets the file system path of the track. - /// - public required string Path { get; init; } - - /// - /// Gets the Id of the media library the track belongs to. - /// - public required Guid LibraryId { get; init; } - - /// - /// Gets the Id of the album the track belongs to. - /// - public required Guid AlbumId { get; init; } - - /// - /// Gets the Id of the artist that owns the album the track belongs to. - /// - public required Guid ArtistId { get; init; } - - /// - /// Gets the audio codec used by the audio file of the track, if applicable. - /// - public string? AudioCodec { get; init; } - - /// - /// Gets the duration of the audio of the track in seconds. - /// - public int DurationInSeconds { get; init; } - - /// - /// Gets the sample rate of the audio of the track in Hz. - /// - public int SampleRate { get; init; } - - /// - /// Gets the number of audio channels of the track. - /// - public int Channels { get; init; } - - /// - /// Gets the bit depth of the audio of the track, if applicable. - /// - public int? BitDepth { get; init; } - - /// - /// Gets the bitrate of the audio of the track in kbps, if applicable. - /// - public int? Bitrate { get; init; } -} +/// The file system path of the track. +/// The Id of the media library the track belongs to. +/// The Id of the album the track belongs to. +/// The Id of the artist that owns the album the track belongs to. +/// The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable. +/// The audio codec used by the audio file of the track, if applicable. +/// The duration of the audio of the track in seconds. +/// The sample rate of the audio of the track in Hz. +/// The number of audio channels of the track. +/// The bit depth of the audio of the track, if applicable. +/// The bitrate of the audio of the track, in kbps, if applicable. +public sealed record TrackStreamDto( + string Path, + Guid LibraryId, + Guid AlbumId, + Guid ArtistId, + string? Container, + string? AudioCodec, + int DurationInSeconds, + int SampleRate, + int Channels, + int? BitDepth, + int? Bitrate +); diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs new file mode 100644 index 00000000..4fb828d0 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/IPlaybackDeliveryHandleService.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Primitives; +using System; +using Lumina.Domain.Common.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Interface for the service that issues and resolves the opaque delivery handles of the playback manifest. +/// +/// +/// A delivery handle binds the delivery decision, the quality cap, the source file identity and the user to one opaque value, so the segment route +/// never recomputes them from inputs that can change while the track plays. A handle is only accepted from the user it was issued to, and only for +/// the track it describes, so it is not a capability that can be transferred to another user or track. Its format is exactly 32 lowercase +/// hexadecimal characters, the N format of a , and that format is the only rule every producer and consumer applies: a value +/// that does not match it is rejected, never normalized into another handle. +/// +public interface IPlaybackDeliveryHandleService +{ + /// + /// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle. + /// + /// The delivery, its source file identity, its quality cap and its user. + /// The opaque delivery handle. + string IssueDeliveryId(PlaybackDeliveryHandleDto delivery); + + /// + /// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track. + /// + /// The opaque delivery handle reported by the playback manifest. + /// The Id of the current user, which the handle must have been issued to. + /// The Id of the track named by the route, which the handle must describe. + /// + /// An containing either the delivery, or when the handle is unknown, expired, or belongs to another user or track. + /// + Result GetDelivery(string? deliveryId, Guid userId, Guid trackId); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs index 45c2f418..998ab9cc 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/ITrackNormalizationService.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.Errors; using System; using System.IO; using System.Threading; @@ -20,18 +21,18 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playbac /// 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. +/// 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, and a single +/// user can only occupy a configured number of those slots, so a prefetch or a burst of requests from one user cannot make another user's playback fail. +/// 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 exposes the produced segments to the player through the segment route of the track stream contract. /// 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. + /// The track, the requesting user, 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. @@ -47,10 +48,9 @@ public interface ITrackNormalizationService /// /// /// 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 + /// 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 - /// . + /// 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. diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs new file mode 100644 index 00000000..655ad28d --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryId.cs @@ -0,0 +1,31 @@ +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Defines the format of the opaque delivery handle of a playback manifest. +/// +/// +/// A handle is a rendered with the N format: exactly 32 lowercase hexadecimal characters, with no separator. Every producer +/// and consumer of a handle uses this rule, so a handle is never silently normalized into another value. +/// +public static class PlaybackDeliveryId +{ + /// + /// The number of characters of a delivery handle. + /// + public const int CHARACTER_COUNT = 32; + + /// + /// Checks whether a value has the format of a delivery handle. + /// + /// The value to check. + /// when the value is exactly 32 lowercase hexadecimal characters, otherwise . + public static bool IsValid(string? value) + { + if (value is null || value.Length != CHARACTER_COUNT) + return false; + foreach (char character in value) + if (!((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'))) + return false; + return true; + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs index d72cda22..469ff1c9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQuery.cs @@ -14,6 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks. /// The unique identifier of the track whose playback manifest is retrieved, taken from the route. /// The container and codec pairs the player advertises it can demux and decode directly, taken from the request, or when it advertises none. /// The path of the track stream, relative to the API, taken from the endpoint so that it always matches the stream route. +/// The path template of the segment route, relative to the API, with a {deliveryId} and a {segmentIndex} placeholder, taken from the endpoint so that it always matches the segment route. [DebuggerDisplay("TrackId: {TrackId}")] public record GetPlaybackManifestQuery( string? LibraryId, @@ -21,5 +22,6 @@ public record GetPlaybackManifestQuery( string? AlbumId, string? TrackId, string? Capabilities, - string StreamPath + string StreamPath, + string SegmentStreamPathTemplate ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs index 9c20966e..b3d33cca 100644 --- a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryHandler.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; @@ -11,9 +13,12 @@ using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Contracts.Responses.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 System; using System.Collections.Generic; +using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -28,8 +33,10 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler _validator; /// @@ -37,15 +44,19 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler /// Injected unit of work for interacting with the data access layer repositories. /// Injected service for deciding how a track's audio is delivered to a player. + /// Injected service that issues the opaque delivery handles of a normalized manifest. /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. /// Injected validator for application validation rules. - public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator validator) + public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) { _unitOfWork = unitOfWork; _playbackFormatService = playbackFormatService; + _playbackDeliveryHandleService = playbackDeliveryHandleService; _authorizationService = authorizationService; _currentUserService = currentUserService; + _pathService = pathService; _validator = validator; } @@ -102,6 +113,80 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false); + if (getSettingsResult.IsFailure) + return getSettingsResult.Errors; + if (getSettingsResult.Value is not null) + quality = getSettingsResult.Value.StreamingQuality; + + // The content locations are captured with the delivery, so the segment route does not have to load the library and the track again + // for every six second segment, and it still re-checks path containment on every request. + Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + if (getLibraryResult.Value is null) + return Errors.Library.LibraryNotFound; + IReadOnlyList allowedRoots = [.. getLibraryResult.Value.ContentLocations.Select(contentLocation => contentLocation.Path)]; + // The containment invariant is enforced before the file is even stat'ed, exactly as the stream route does, so a normalized manifest never + // touches a path outside the content locations of its library. A path that is not inside them is not stat'ed, and the segment route is + // what rejects it when it tries to resolve the delivery. + bool isInsideContentLocation = allowedRoots.Count > 0 && allowedRoots.Any(contentLocation => _pathService.IsPathWithin(track.Path, contentLocation)); + + // The identity is captured only when the path is inside the library's content locations. A normalized delivery declared for a missing, + // unreadable or out-of-root file records no identity, and the segment route is the authority that rejects it when the delivery is resolved. + long sourceLength = 0; + DateTime sourceLastModifiedUtc = DateTime.MinValue; + if (isInsideContentLocation) + { + try + { + FileInfo sourceFile = new(track.Path); + if (sourceFile.Exists) + { + sourceLength = sourceFile.Length; + sourceLastModifiedUtc = sourceFile.LastWriteTimeUtc; + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) + { + sourceLength = 0; + sourceLastModifiedUtc = DateTime.MinValue; + } + } + + NormalizedTrackRequestDto normalizationRequest = new( + trackId, + userId, + track.Path, + allowedRoots, + track.Container, + decision.Mode, + decision.Container, + decision.Codec, + decision.SegmentDurationSeconds, + track.DurationInSeconds, + track.Bitrate, + track.SampleRate, + track.Channels, + track.BitDepth, + quality, + sourceLength, + sourceLastModifiedUtc); + PlaybackDeliveryHandleDto delivery = new( + normalizationRequest, + decision.Shape, + libraryId, + albumId, + artistId); + deliveryId = _playbackDeliveryHandleService.IssueDeliveryId(delivery); + } + return new PlaybackManifestResponse( trackId, track.DurationInSeconds, @@ -120,6 +205,8 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler +/// Query for getting a single segment of the normalized audio of a track, for streaming. +/// +/// The unique identifier of the media library the track belongs to, taken from the route. +/// The unique identifier of the artist the album of the track belongs to, taken from the route. +/// The unique identifier of the album the track belongs to, taken from the route. +/// The unique identifier of the track whose normalized audio is streamed, taken from the route. +/// The opaque handle of the normalized delivery the segment belongs to, taken from the route. +/// The zero based index of the segment of the normalized audio, taken from the route. +[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")] +public record GetTrackSegmentQuery( + string? LibraryId, + string? ArtistId, + string? AlbumId, + string? TrackId, + string? DeliveryId, + string? SegmentIndex +) : IQuery; diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs new file mode 100644 index 00000000..fc80f5b5 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryHandler.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +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 System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; + +/// +/// Handler for the query to get a single segment of the normalized audio of a track, for streaming. +/// +public class GetTrackSegmentQueryHandler : IQueryHandler> +{ + private readonly ITrackNormalizationService _trackNormalizationService; + private readonly IPlaybackDeliveryHandleService _playbackDeliveryHandleService; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IPathService _pathService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service that produces, caches and serves the normalized audio of a track. + /// Injected service that resolves the opaque delivery handle of the playback manifest. + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected service for file system path related functionality. + /// Injected validator for application validation rules. + public GetTrackSegmentQueryHandler(ITrackNormalizationService trackNormalizationService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator validator) + { + _trackNormalizationService = trackNormalizationService; + _playbackDeliveryHandleService = playbackDeliveryHandleService; + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _pathService = pathService; + _validator = validator; + } + + /// + /// Handles the query to get a single segment of the normalized audio of a track, for streaming. + /// + /// The query to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the data of the requested segment, or an error message. + /// + public async Task> HandleAsync(GetTrackSegmentQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // An authenticated request must always carry a user identity. + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // The validator guarantees that the route identifiers and the segment index are well formed before this point. + Guid libraryId = Guid.Parse(query.LibraryId!); + Guid artistId = Guid.Parse(query.ArtistId!); + Guid albumId = Guid.Parse(query.AlbumId!); + Guid trackId = Guid.Parse(query.TrackId!); + int segmentIndex = int.Parse(query.SegmentIndex!); + + // Admins can stream the tracks of all libraries; for everyone else, only the tracks of the libraries they own. This is the only database + // read of a segment request: the track, library and delivery context were resolved at manifest time and are carried by the delivery handle. + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + // The delivery handle is the only authority on the delivery of the segments: it was issued to this user for this track, and it holds the + // decision, the quality cap, the source file version and the library context the manifest declared. It is never recomputed from a capability + // list, a setting or a file that may have changed since the manifest was read. + Result getDeliveryResult = _playbackDeliveryHandleService.GetDelivery(query.DeliveryId, userId, trackId); + if (getDeliveryResult.IsFailure) + return getDeliveryResult.Errors; + PlaybackDeliveryHandleDto delivery = getDeliveryResult.Value; + if (delivery.LibraryId != libraryId || delivery.AlbumId != albumId || delivery.ArtistId != artistId) + return Errors.Playback.PlaybackDeliveryNotFound; + // A direct play is served by the stream route itself, so a delivery handle for it has no segment. The delivery must also be addressed as + // time addressed segments with a positive segment duration, or the segment route has nothing it can index. + if (delivery.Request.Mode == PlaybackDeliveryMode.DirectPlay) + return Errors.Playback.NormalizationIsNotRequiredForDirectPlay; + if (delivery.Shape != PlaybackDeliveryShape.TimeAddressedSegments || delivery.Request.SegmentDurationSeconds <= 0) + return Errors.Playback.PlaybackDeliveryChanged; + + // The audio file is only handed to the normalization pipeline when it is stored inside one of the content locations of its library, so + // that a stored path can never be used to read an arbitrary file of the host; the failure is reported as not found without the path. + if (!delivery.Request.AllowedRoots.Any(contentLocation => _pathService.IsPathWithin(delivery.Request.SourcePath, contentLocation))) + return Errors.Music.TrackFileNotFound; + + NormalizedTrackRequestDto normalizationRequest = delivery.Request; + + // The segment is read from a cached production, or the whole track is produced and cached first. A production is atomic, so the first + // segment request waits for the complete normalized audio, and every later segment request is served from the cache. A file that changed + // since the manifest declared the delivery is rejected by the service instead of starting a second, incompatible production. + Result normalizedTrackResult = await _trackNormalizationService.GetOrCreateNormalizedTrackAsync(normalizationRequest, cancellationToken).ConfigureAwait(false); + if (normalizedTrackResult.IsFailure) + return normalizedTrackResult.Errors; + NormalizedTrackDto normalizedTrack = normalizedTrackResult.Value; + + NormalizedTrackSegmentDto? segment = normalizedTrack.Segments.FirstOrDefault(candidate => candidate.Index == segmentIndex); + if (segment is null) + return Errors.Playback.NormalizedTrackSegmentNotFound; + + Result openSegmentResult = _trackNormalizationService.OpenNormalizedSegment(normalizedTrack.CacheId, trackId, segmentIndex); + if (openSegmentResult.IsFailure) + return openSegmentResult.Errors; + + return new NormalizedTrackSegmentDataDto(openSegmentResult.Value, segment.Length, segment.StartSeconds, normalizedTrack.Container, normalizedTrack.Segments.Count, normalizedTrack.DurationInSeconds); + } +} diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs new file mode 100644 index 00000000..9e80e4e7 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackSegment/GetTrackSegmentQueryValidator.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment; + +/// +/// Validates the needed validation rules for . +/// +public class GetTrackSegmentQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackSegmentQueryValidator() + { + // Validates the identifier of the media library the track belongs to, taken from the route. + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + RuleFor(query => query.LibraryId) + .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty) + .When(query => query.LibraryId is not null && query.LibraryId.Length > 0) + .WithError(Errors.Library.LibraryIdCannotBeEmpty); + + // Validates the identifier of the artist the album of the track belongs to, taken from the route. + RuleFor(query => query.ArtistId) + .NotEmpty() + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + RuleFor(query => query.ArtistId) + .Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty) + .When(query => query.ArtistId is not null && query.ArtistId.Length > 0) + .WithError(Errors.Music.ArtistIdCannotBeEmpty); + + // Validates the identifier of the album the track belongs to, taken from the route. + RuleFor(query => query.AlbumId) + .NotEmpty() + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + RuleFor(query => query.AlbumId) + .Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty) + .When(query => query.AlbumId is not null && query.AlbumId.Length > 0) + .WithError(Errors.Music.AlbumIdCannotBeEmpty); + + // Validates the identifier of the track whose normalized audio is streamed, taken from the route. + RuleFor(query => query.TrackId) + .NotEmpty() + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + RuleFor(query => query.TrackId) + .Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty) + .When(query => query.TrackId is not null && query.TrackId.Length > 0) + .WithError(Errors.Music.TrackIdCannotBeEmpty); + + // Validates the opaque delivery handle the segment belongs to, taken from the route. + RuleFor(query => query.DeliveryId) + .NotEmpty() + .WithError(Errors.Playback.DeliveryIdCannotBeEmpty); + + RuleFor(query => query.DeliveryId) + .Must(PlaybackDeliveryId.IsValid) + .When(query => query.DeliveryId is not null && query.DeliveryId.Length > 0) + .WithError(Errors.Playback.DeliveryIdIsInvalid); + + // Validates the index of the segment of the normalized audio, taken from the route. + RuleFor(query => query.SegmentIndex) + .NotEmpty() + .WithError(Errors.Playback.SegmentIndexCannotBeEmpty); + + RuleFor(query => query.SegmentIndex) + .Must(segmentIndex => int.TryParse(segmentIndex, out int parsedSegmentIndex) && parsedSegmentIndex >= 0) + .When(query => query.SegmentIndex is not null && query.SegmentIndex.Length > 0) + .WithError(Errors.Playback.SegmentIndexMustBeValid); + } +} diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs index d817359d..54642b46 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackManifestResponse.cs @@ -11,7 +11,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Play /// requesting player, and the path of the track stream, so that a player is told what to fetch and how before it fetches any audio. /// /// The Id of the track the manifest describes. -/// The duration of the audio of the track, in seconds. +/// The duration of the audio of the track, in seconds, as stored by the probe. A normalized production can differ slightly; its exact produced duration is reported by the segment responses. /// The container of the audio file of the track, as stored by the probe, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional. /// The codec of the audio of the track, as stored by the probe. Optional. /// The sample rate of the audio of the track, in Hz. @@ -21,14 +21,22 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Play /// The ReplayGain track peak of the track. Optional. /// The ReplayGain album gain of the track, in decibels. Optional. /// The ReplayGain album peak of the track. Optional. -/// Whether the player can play the stored audio as it is, without the server changing its container or its codec. +/// Whether the player can play the stored audio as it is, without the server changing its container or its codec. /// The container of the audio the server delivers, when the delivery is not a direct play. for a direct play. /// The codec of the audio the server delivers, when the delivery is not a direct play. for a direct play. /// The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. for a direct play. /// The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. otherwise. -/// Whether the delivered audio can be seeked by the player. +/// Whether the delivered audio can be seeked by the player. /// The path of the track stream, relative to the API, without a host or a scheme, so that a client never reaches the API directly. -[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")] +/// +/// The opaque handle of the normalized delivery, which the segment route accepts in place of a capability list, so the delivery the +/// manifest declared cannot be recomputed from inputs that change while the track plays. for a direct play. +/// +/// +/// The path of the segment route of the normalized delivery, relative to the API and without a host or a scheme, with a {deliveryId} and a +/// {segmentIndex} placeholder. for a direct play, whose delivery is addressed by byte range. +/// +[DebuggerDisplay("TrackId: {TrackId} IsDirectPlay: {IsDirectPlay}")] public sealed record PlaybackManifestResponse( Guid TrackId, int DurationInSeconds, @@ -41,11 +49,13 @@ public sealed record PlaybackManifestResponse( decimal? ReplayGainTrackPeak, decimal? ReplayGainAlbumGain, decimal? ReplayGainAlbumPeak, - bool DirectPlay, + bool IsDirectPlay, string? DeliveryContainer, string? DeliveryCodec, PlaybackDeliveryShape? DeliveryShape, int? SegmentDurationSeconds, - bool Seekable, - string StreamPath + bool IsSeekable, + string StreamPath, + string? DeliveryId, + string? SegmentStreamPathTemplate ); diff --git a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs index 5151f37a..54f35802 100644 --- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/TrackRepository.cs @@ -341,19 +341,18 @@ internal sealed class TrackRepository : ITrackRepository return await _luminaDbContext.Tracks .AsNoTracking() .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) - .Select(track => new TrackStreamDto - { - Path = track.Path, - LibraryId = track.LibraryId, - AlbumId = track.AlbumId, - ArtistId = track.Album!.ArtistId, - AudioCodec = track.AudioCodec, - DurationInSeconds = track.DurationInSeconds, - SampleRate = track.SampleRate, - Channels = track.Channels, - BitDepth = track.BitDepth, - Bitrate = track.Bitrate - }) + .Select(track => new TrackStreamDto( + track.Path, + track.LibraryId, + track.AlbumId, + track.Album!.ArtistId, + track.Container, + track.AudioCodec, + track.DurationInSeconds, + track.SampleRate, + track.Channels, + track.BitDepth, + track.Bitrate)) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); } @@ -378,19 +377,19 @@ internal sealed class TrackRepository : ITrackRepository return await _luminaDbContext.Tracks .AsNoTracking() .Where(track => track.Id == trackId && track.LibraryId == libraryId && track.AlbumId == albumId && track.Album!.ArtistId == artistId) - .Select(track => new TrackPlaybackManifestDto - { - Container = track.Container, - AudioCodec = track.AudioCodec, - DurationInSeconds = track.DurationInSeconds, - SampleRate = track.SampleRate, - Channels = track.Channels, - BitDepth = track.BitDepth, - ReplayGainTrackGain = track.ReplayGainTrackGain, - ReplayGainTrackPeak = track.ReplayGainTrackPeak, - ReplayGainAlbumGain = track.ReplayGainAlbumGain, - ReplayGainAlbumPeak = track.ReplayGainAlbumPeak - }) + .Select(track => new TrackPlaybackManifestDto( + track.Path, + track.Container, + track.AudioCodec, + track.DurationInSeconds, + track.SampleRate, + track.Channels, + track.BitDepth, + track.Bitrate, + track.ReplayGainTrackGain, + track.ReplayGainTrackPeak, + track.ReplayGainAlbumGain, + track.ReplayGainAlbumPeak)) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs index 16292916..c18c8c5a 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Playback.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Playback.cs @@ -12,14 +12,21 @@ public static partial class Errors public static class Playback { public static Error NoSupportedPlaybackFormat => Error.Forbidden(description: nameof(NoSupportedPlaybackFormat)); + public static Error PlaybackDeliveryChanged => Error.Conflict(description: nameof(PlaybackDeliveryChanged)); + public static Error PlaybackDeliveryNotFound => Error.NotFound(description: nameof(PlaybackDeliveryNotFound)); + public static Error DeliveryIdCannotBeEmpty => Error.Validation(description: nameof(DeliveryIdCannotBeEmpty)); + public static Error DeliveryIdIsInvalid => Error.Validation(description: nameof(DeliveryIdIsInvalid)); public static Error PlaybackFormatNotImplemented => Error.Internal(description: nameof(PlaybackFormatNotImplemented)); public static Error NormalizedTrackCacheEntryNotFound => Error.NotFound(description: nameof(NormalizedTrackCacheEntryNotFound)); + public static Error NormalizedTrackSegmentNotFound => Error.NotFound(description: nameof(NormalizedTrackSegmentNotFound)); 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 NormalizationIsNotRequiredForDirectPlay => Error.Conflict(description: nameof(NormalizationIsNotRequiredForDirectPlay)); public static Error SegmentDurationMustBePositive => Error.Validation(description: nameof(SegmentDurationMustBePositive)); + public static Error SegmentIndexCannotBeEmpty => Error.Validation(description: nameof(SegmentIndexCannotBeEmpty)); + public static Error SegmentIndexMustBeValid => Error.Validation(description: nameof(SegmentIndexMustBeValid)); public static Error TrackDurationMustBePositive => Error.Validation(description: nameof(TrackDurationMustBePositive)); } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index b36d8d58..06a35358 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -152,12 +152,16 @@ public static class InfrastructureLayerServices // repackaged into another container, or re-encoded into another codec. services.AddSingleton(); + // Music playback: issues and resolves the opaque delivery handles reported by a playback manifest, so the segment route never has to + // recompute the delivery decision, the quality cap or the source file identity from values that can change while the track plays. + 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. + // segments and serves it from the cache, bounded in concurrency, cancellable and capped in disk usage. The segment route of the + // playback stream surface is its consumer. services.AddSingleton(); // Music playback: owns the normalized audio cache lifecycle and verifies the ffmpeg encoders at startup, so a missing or changed toolchain diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index b13262b8..ff960a4d 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -36,6 +36,9 @@ public static partial class Errors 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 TranscodingMaxConcurrentJobsPerUserMustBePositive => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserMustBePositive)); + public static Error TranscodingMaxConcurrentJobsPerUserIsTooLarge => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserIsTooLarge)); + public static Error TranscodingMaxConcurrentJobsPerUserExceedsGlobal => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsPerUserExceedsGlobal)); 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)); diff --git a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs index a533f8e5..140a1771 100644 --- a/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs +++ b/src/Lumina.Infrastructure/Common/Models/DTO/Configuration/TranscodingSettingsDto.cs @@ -22,6 +22,12 @@ public sealed class TranscodingSettingsDto /// public int MaxConcurrentJobs { get; set; } = 2; + /// + /// Gets or sets the maximum number of normalization jobs a single user may have running at the same time. A production that was + /// started by another user can still be waited for, because it is shared by every request for the same track and delivery. + /// + public int MaxConcurrentJobsPerUser { get; set; } = 1; + /// /// Gets or sets the maximum total size of the normalized audio cache, in bytes. /// diff --git a/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs index 4d4d5213..7ad7a3db 100644 --- a/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/TranscodingSettingsDtoValidator.cs @@ -53,6 +53,19 @@ public class TranscodingSettingsDtoValidator : AbstractValidator maxConcurrentJobs <= MAX_CONCURRENT_JOBS) .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge); + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .GreaterThan(0) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserMustBePositive); + + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .Must(maxConcurrentJobsPerUser => maxConcurrentJobsPerUser <= MAX_CONCURRENT_JOBS) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge); + + // A per-user limit above the global one can never be reached, and would hide a misconfiguration that looks like a working cap. + RuleFor(settings => settings.MaxConcurrentJobsPerUser) + .Must((settings, maxConcurrentJobsPerUser) => maxConcurrentJobsPerUser <= settings.MaxConcurrentJobs) + .WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsPerUserExceedsGlobal); + RuleFor(settings => settings.MaxCacheBytes) .GreaterThan(0) .WithError(Errors.Errors.Configuration.TranscodingMaxCacheBytesMustBePositive); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs new file mode 100644 index 00000000..1ae2e490 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/PlaybackDeliveryHandleService.cs @@ -0,0 +1,251 @@ +#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 System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; + +/// +/// Issues and resolves the opaque delivery handles of the playback manifest, which bind a normalized delivery to the user, the track and the inputs the delivery was declared with. +/// +/// +/// The handles are process local, like the normalized audio cache they address. An API process must therefore keep handling both the manifest and +/// the segments of a track for a handle to resolve, which is the deployment the cache already requires: a single API process per cache directory. +/// A handle expires after a bounded lifetime, and the registry is bounded both globally and per user. Expired entries are removed from a queue in +/// issue order, so the sweep is amortized constant time and does not scan every handle. A repeated manifest for the same delivery inputs reuses the +/// handle that already exists for them, so reloading a manifest does not grow the registry. +/// +internal sealed class PlaybackDeliveryHandleService : IPlaybackDeliveryHandleService +{ + private const int MAX_DELIVERIES = 20_000; + private const int MAX_DELIVERIES_PER_USER = 64; + private static readonly TimeSpan s_deliveryLifetime = TimeSpan.FromHours(12); + + private readonly Lock _deliveryLock = new(); + // These dictionaries share one logical invariant: a delivery handle is split across the delivery map, its signature map, its per-user queue and count, + // and the global expiry queue. ConcurrentDictionary would make each collection thread-safe on its own, but not the multi-step issue, reuse, evict and remove sequences, + // which must see all of them consistently. The Lock is held only for short, O(1), non-awaiting work, so replacing these collections with concurrent ones would add + // complexity without removing the lock. Do not "fix" this without redesigning the state into one atomically updated map. + private readonly Dictionary _deliveries = []; + private readonly Dictionary _deliveryIdsBySignature = []; + private readonly Dictionary> _deliveryIdsByUser = []; + private readonly Dictionary _deliveryCountsByUser = []; + private readonly Queue<(string DeliveryId, DateTimeOffset ExpiresAtUtc)> _expiryQueue = []; + + /// + /// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle. + /// + /// The delivery, its source file identity, its quality cap and its user. + /// The opaque delivery handle. + public string IssueDeliveryId(PlaybackDeliveryHandleDto delivery) + { + string signature = BuildSignature(delivery); + lock (_deliveryLock) + { + DateTimeOffset now = DateTimeOffset.UtcNow; + RemoveExpiredDeliveries(now); + if (_deliveryIdsBySignature.TryGetValue(signature, out string? existingDeliveryId) + && _deliveries.TryGetValue(existingDeliveryId, out StoredDelivery? existingDelivery) + && existingDelivery.ExpiresAtUtc > now) + return existingDeliveryId; + if (existingDeliveryId is not null) + RemoveDelivery(existingDeliveryId); + + EnforceUserLimit(delivery.Request.UserId); + EnforceGlobalLimit(); + + // The handle is a random opaque value, not a derived one, so it cannot be computed from the track or the file by a caller. + string deliveryId = Guid.NewGuid().ToString("N"); + DateTimeOffset expiresAtUtc = now.Add(s_deliveryLifetime); + _deliveries[deliveryId] = new StoredDelivery(delivery, signature, expiresAtUtc); + _deliveryIdsBySignature[signature] = deliveryId; + _deliveryCountsByUser[delivery.Request.UserId] = _deliveryCountsByUser.GetValueOrDefault(delivery.Request.UserId) + 1; + if (!_deliveryIdsByUser.TryGetValue(delivery.Request.UserId, out Queue? userDeliveryIds)) + { + userDeliveryIds = []; + _deliveryIdsByUser[delivery.Request.UserId] = userDeliveryIds; + } + userDeliveryIds.Enqueue(deliveryId); + _expiryQueue.Enqueue((deliveryId, expiresAtUtc)); + return deliveryId; + } + } + + /// + /// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track. + /// + /// The opaque delivery handle reported by the playback manifest. + /// The Id of the current user, which the handle must have been issued to. + /// The Id of the track named by the route, which the handle must describe. + /// + /// An containing either the delivery, or when the handle + /// is unknown, expired, or belongs to another user or track. + /// + public Result GetDelivery(string? deliveryId, Guid userId, Guid trackId) + { + if (string.IsNullOrWhiteSpace(deliveryId)) + return Errors.Playback.PlaybackDeliveryNotFound; + + lock (_deliveryLock) + { + if (!_deliveries.TryGetValue(deliveryId, out StoredDelivery? entry)) + return Errors.Playback.PlaybackDeliveryNotFound; + if (entry.ExpiresAtUtc <= DateTimeOffset.UtcNow) + { + RemoveDelivery(deliveryId); + return Errors.Playback.PlaybackDeliveryNotFound; + } + // A handle is not a capability: it is only valid for the user it was issued to and the track it describes, so a leaked handle + // cannot be used to read another user's track or another track of the same user. + if (entry.Delivery.Request.UserId != userId || entry.Delivery.Request.TrackId != trackId) + return Errors.Playback.PlaybackDeliveryNotFound; + return entry.Delivery; + } + } + + /// + /// Enforces the per-user handle limit by evicting the oldest handles of that user. + /// + /// The Id of the user whose handles are bounded. + private void EnforceUserLimit(Guid userId) + { + while (_deliveryCountsByUser.GetValueOrDefault(userId) >= MAX_DELIVERIES_PER_USER) + if (!TryEvictOldestForUser(userId)) + break; + } + + /// + /// Enforces the global handle limit by evicting the oldest handle. + /// + private void EnforceGlobalLimit() + { + while (_deliveries.Count >= MAX_DELIVERIES) + if (!TryEvictOldestDelivery()) + break; + } + + /// + /// Evicts the oldest handle that is still registered for a user. + /// + /// The Id of the user whose oldest handle is evicted. + /// when a handle was evicted, otherwise . + private bool TryEvictOldestForUser(Guid userId) + { + if (!_deliveryIdsByUser.TryGetValue(userId, out Queue? userDeliveryIds)) + return false; + while (userDeliveryIds.Count > 0) + { + string deliveryId = userDeliveryIds.Dequeue(); + if (!_deliveries.ContainsKey(deliveryId)) + continue; + RemoveDelivery(deliveryId); + return true; + } + _deliveryIdsByUser.Remove(userId); + return false; + } + + /// + /// Evicts the oldest handle that is still registered, using the expiry queue as the age order. + /// + /// when a handle was evicted, otherwise . + private bool TryEvictOldestDelivery() + { + while (_expiryQueue.Count > 0) + { + (string deliveryId, DateTimeOffset expiresAtUtc) = _expiryQueue.Dequeue(); + if (!_deliveries.TryGetValue(deliveryId, out StoredDelivery? storedDelivery) || storedDelivery.ExpiresAtUtc != expiresAtUtc) + continue; + RemoveDelivery(deliveryId); + return true; + } + return false; + } + + /// + /// Removes the deliveries whose lifetime ended, in expiry order, so the sweep does not scan the registry. + /// + /// The current time, in UTC. + private void RemoveExpiredDeliveries(DateTimeOffset now) + { + while (_expiryQueue.Count > 0) + { + (string deliveryId, DateTimeOffset expiresAtUtc) = _expiryQueue.Peek(); + if (expiresAtUtc > now) + return; + _expiryQueue.Dequeue(); + if (_deliveries.TryGetValue(deliveryId, out StoredDelivery? storedDelivery) && storedDelivery.ExpiresAtUtc == expiresAtUtc) + RemoveDelivery(deliveryId); + } + } + + /// + /// Removes one delivery and its signature and per-user accounting. + /// + /// The opaque handle of the delivery to remove. + private void RemoveDelivery(string deliveryId) + { + if (!_deliveries.Remove(deliveryId, out StoredDelivery? storedDelivery)) + return; + if (_deliveryIdsBySignature.TryGetValue(storedDelivery.Signature, out string? mappedDeliveryId) && mappedDeliveryId == deliveryId) + _deliveryIdsBySignature.Remove(storedDelivery.Signature); + if (_deliveryCountsByUser.TryGetValue(storedDelivery.Delivery.Request.UserId, out int count)) + { + if (count <= 1) + _deliveryCountsByUser.Remove(storedDelivery.Delivery.Request.UserId); + else + _deliveryCountsByUser[storedDelivery.Delivery.Request.UserId] = count - 1; + } + } + + /// + /// Builds the key that identifies a delivery for de-duplication, from every input that changes the handle's meaning. + /// + /// The delivery to key. + /// The signature of the delivery. + private static string BuildSignature(PlaybackDeliveryHandleDto delivery) + { + return string.Join('\u001F', new string[] + { + delivery.Request.UserId.ToString("N"), + delivery.Request.TrackId.ToString("N"), + delivery.LibraryId.ToString("N"), + delivery.AlbumId.ToString("N"), + delivery.ArtistId.ToString("N"), + ((int)delivery.Request.Mode).ToString(CultureInfo.InvariantCulture), + ((int)delivery.Shape).ToString(CultureInfo.InvariantCulture), + delivery.Request.SourceContainer ?? string.Empty, + delivery.Request.Container, + delivery.Request.Codec, + delivery.Request.SegmentDurationSeconds.ToString(CultureInfo.InvariantCulture), + delivery.Request.DurationInSeconds.ToString(CultureInfo.InvariantCulture), + delivery.Request.Bitrate?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + delivery.Request.SampleRate.ToString(CultureInfo.InvariantCulture), + delivery.Request.Channels.ToString(CultureInfo.InvariantCulture), + delivery.Request.BitDepth?.ToString(CultureInfo.InvariantCulture) ?? string.Empty, + ((int)delivery.Request.Quality).ToString(CultureInfo.InvariantCulture), + delivery.Request.SourcePath, + delivery.Request.SourceLength.ToString(CultureInfo.InvariantCulture), + delivery.Request.SourceLastModifiedUtc.Ticks.ToString(CultureInfo.InvariantCulture), + string.Join('\u001E', delivery.Request.AllowedRoots) + }); + } + + /// + /// A registered delivery, its de-duplication signature and its expiry. + /// + /// The delivery the handle addresses. + /// The signature of every input that changes the handle's meaning. + /// The time, in UTC, after which the handle is no longer accepted. + private sealed record StoredDelivery( + PlaybackDeliveryHandleDto Delivery, + string Signature, + DateTimeOffset ExpiresAtUtc + ); +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs index 0fb9cfec..1ac540be 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/AudioLibrary/MusicLibrary/Playback/TrackNormalizationService.cs @@ -73,6 +73,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID 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; + private const int MAX_TRACK_PROJECTIONS = 1024; // 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. @@ -124,8 +125,15 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID private readonly TimeSpan _touchThrottleInterval; private readonly SemaphoreSlim _jobSlots; private readonly ConcurrentDictionary _runningProcesses = new(); + // The projection of a cache index is reused between segment requests, so a cached track is not re-projected for every segment. The bound keeps + // the retained metadata small; a cleared cache is repopulated lazily from the index on the next request. + private readonly ConcurrentDictionary<(string CacheRoot, string CacheId), NormalizedTrackDto> _trackProjections = new(); private readonly CancellationTokenSource _shutdownCancellation = new(); private readonly Lock _lifecycleSync = new(); + // The global job slots are shared, but one user must not be able to take all of them and block another user's playback. These two fields guard + // the per-user admission count; they are not part of the cache identity, because a production is shared by every user that requests it. + private readonly Lock _userProductionLock = new(); + private readonly Dictionary _activeProductionsPerUser = []; private readonly ManualResetEventSlim _productionsDrained = new(initialState: true); private readonly string _cacheRoot; private int _activeProductionCount; @@ -176,6 +184,8 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID return Errors.Playback.NormalizationUnavailable; if (request.TrackId == Guid.Empty) return Errors.Playback.NormalizationFailed; + if (request.UserId == 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 @@ -212,6 +222,11 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID return Errors.Music.TrackFileNotFound; // A file that cannot be read is indistinguishable, to the caller, from a file that does not exist. } + // The delivery was declared against a specific version of the source file. A file that changed since then would produce a new cache + // entry with a different identity, so its segments would be mixed with the segments of the declared delivery. It is rejected instead. + if (request.SourceLength != sourceLength || request.SourceLastModifiedUtc != sourceLastModifiedUtc) + return Errors.Playback.PlaybackDeliveryChanged; + 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. @@ -433,30 +448,79 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID /// 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(); - } + // The global job slots are shared by every user, so a user who starts many productions at once could occupy all of them and make + // another user's playback fail. The per-user admission happens before the production is registered, and a request that joins a + // production another user already started does not reach this method, so a shared production is never charged twice. + if (!TryAcquireUserProductionSlot(request.UserId)) + return Errors.Playback.NormalizationUnavailable; try { - return await ProduceCoreAsync(cacheId, request, format, sourceLength, sourceLastModifiedUtc).ConfigureAwait(false); + 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(); + } + } } finally { - lock (_lifecycleSync) - { - _activeProductionCount--; - if (_activeProductionCount == 0) - _productionsDrained.Set(); - } + ReleaseUserProductionSlot(request.UserId); + } + } + + /// + /// Reserves one of the per-user production slots before a production is admitted, so one user can never occupy every global job slot. + /// + /// The Id of the user whose request starts the production. + /// when the slot was reserved, otherwise. + private bool TryAcquireUserProductionSlot(Guid userId) + { + lock (_userProductionLock) + { + if (userId == Guid.Empty) + return false; + int activeProductions = _activeProductionsPerUser.GetValueOrDefault(userId); + if (activeProductions >= _settings.MaxConcurrentJobsPerUser) + return false; + _activeProductionsPerUser[userId] = activeProductions + 1; + return true; + } + } + + /// + /// Releases a per-user production slot that was reserved by . + /// + /// The Id of the user whose production ended. + private void ReleaseUserProductionSlot(Guid userId) + { + lock (_userProductionLock) + { + if (!_activeProductionsPerUser.TryGetValue(userId, out int activeProductions)) + return; + if (activeProductions <= 1) + _activeProductionsPerUser.Remove(userId); + else + _activeProductionsPerUser[userId] = activeProductions - 1; } } @@ -616,7 +680,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID 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); + return GetOrCreateTrackProjection(cacheId, index); } catch (OperationCanceledException) { @@ -1047,10 +1111,29 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID if (!TryReadIndex(cacheId, out NormalizedTrackIndexDto? index) || index is null) return false; - normalizedTrack = CreateNormalizedTrackDto(cacheId, index); + normalizedTrack = GetOrCreateTrackProjection(cacheId, index); return true; } + /// + /// Projects a validated cache index once and reuses the projection for the following segment requests of the same cached track. + /// + /// 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 NormalizedTrackDto GetOrCreateTrackProjection(string cacheId, NormalizedTrackIndexDto index) + { + (string CacheRoot, string CacheId) key = (_cacheRoot, cacheId); + if (_trackProjections.TryGetValue(key, out NormalizedTrackDto? existing) && existing.TrackId == index.TrackId) + return existing; + NormalizedTrackDto projection = CreateNormalizedTrackDto(cacheId, index); + // The projection is metadata only, but unbounded retention is not useful: when the bound is reached, the cache is dropped and rebuilt lazily. + if (_trackProjections.Count >= MAX_TRACK_PROJECTIONS) + _trackProjections.Clear(); + _trackProjections[key] = projection; + return projection; + } + /// /// Projects a validated cache index into the normalized track the caller receives. /// diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index b984fd84..59f643fd 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -20,6 +20,7 @@ "TranscodingSettings": { "FfmpegPath": "ffmpeg", "MaxConcurrentJobs": 2, + "MaxConcurrentJobsPerUser": 1, "MaxCacheBytes": 2147483648, "JobTimeoutSeconds": 900, "EvictionGraceSeconds": 120, diff --git a/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs b/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs index 1102517f..50cbda20 100644 --- a/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs +++ b/src/Lumina.Presentation.Api/Common/MimeTypes/MusicMimeTypes.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; using System.Collections.Frozen; using System.Collections.Generic; #endregion @@ -29,6 +30,20 @@ public static class MusicMimeTypes { AudioFileFormat.MATROSKA, "audio/x-matroska" } }.ToFrozenDictionary(); + // Container names are mapped to the file format enumeration instead of to their own media type strings, so the media type table above stays the + // single source of truth and a new format only needs one entry. + private static readonly FrozenDictionary s_containerToAudioFileFormat = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "MP3", AudioFileFormat.MP3 }, + { "FLAC", AudioFileFormat.FLAC }, + { "MP4", AudioFileFormat.M4A }, + { "M4A", AudioFileFormat.M4A }, + { "AAC", AudioFileFormat.AAC }, + { "OGG", AudioFileFormat.OGG }, + { "OPUS", AudioFileFormat.OPUS }, + { "WAV", AudioFileFormat.WAV } + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + /// /// Gets the MIME content type of . /// @@ -38,4 +53,16 @@ public static class MusicMimeTypes { return s_audioFileFormatToMimeType.TryGetValue(format, out string? mimeType) ? mimeType : "application/octet-stream"; } + + /// + /// Gets the MIME content type of an audio container, as named by the delivery decision of a playback manifest. + /// + /// The canonical container of the delivered audio, for example MP4, AAC, OGG, MP3, FLAC or WAV. + /// The MIME content type of , or application/octet-stream when the container is unknown. + public static string GetContainerMimeType(string? container) + { + return !string.IsNullOrWhiteSpace(container) && s_containerToAudioFileFormat.TryGetValue(container.Trim(), out AudioFileFormat format) + ? GetMimeType(format) + : "application/octet-stream"; + } } diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs index 34ab9696..963c3c17 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.Tracks.cs @@ -15,6 +15,7 @@ public static partial class ApiRoutes public const string UPDATE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string STREAM_TRACK = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + public const string STREAM_TRACK_SEGMENT = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs index 2074be09..fb6404fb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Common/BaseEndpoint.cs @@ -45,16 +45,20 @@ public abstract class BaseEndpoint : Endpoint extensionsDictionary = []; - int statusCode = error.Type switch - { - ErrorType.Validation => StatusCodes.Status400BadRequest, - ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in) - ErrorType.Failure => StatusCodes.Status403Forbidden, - ErrorType.Forbidden => StatusCodes.Status403Forbidden, - ErrorType.NotFound => StatusCodes.Status404NotFound, - ErrorType.Conflict => StatusCodes.Status409Conflict, - _ => StatusCodes.Status500InternalServerError, - }; + // A resource that is temporarily unavailable is a transient condition of the server, not an unexpected failure, so it is reported as + // unavailable rather than as an internal error. A client can retry it, and the playback player does. + int statusCode = error is ResourceUnavailableError + ? StatusCodes.Status503ServiceUnavailable + : error.Type switch + { + ErrorType.Validation => StatusCodes.Status400BadRequest, + ErrorType.Unauthorized => StatusCodes.Status403Forbidden, // DO NOT return Status401Unauthorized, that actually means lack of valid authentication credentials (not logged in) + ErrorType.Failure => StatusCodes.Status403Forbidden, + ErrorType.Forbidden => StatusCodes.Status403Forbidden, + ErrorType.NotFound => StatusCodes.Status404NotFound, + ErrorType.Conflict => StatusCodes.Status409Conflict, + _ => StatusCodes.Status500InternalServerError, + }; extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier; @@ -79,15 +83,11 @@ public abstract class BaseEndpoint : Endpoint +/// A response result that writes an owned stream to the response without buffering it and releases the stream once the response is complete. +/// +/// +/// The result owns the stream, so a lease protected resource that is served through it is always released, including when the client disconnects +/// before the whole content was written. Unlike a result built from bytes, it never materializes the content in memory. +/// +public sealed class DisposingStreamResult : IResult +{ + private readonly Stream _content; + private readonly string _contentType; + private readonly long? _contentLength; + + /// + /// Initializes a new instance of the class. + /// + /// The stream to write, which this result owns and releases after the response is complete. + /// The media type of the content. + /// The length of the content, in bytes, or when it is not known in advance. + public DisposingStreamResult(Stream content, string contentType, long? contentLength) + { + _content = content; + _contentType = contentType; + _contentLength = contentLength; + } + + /// + /// Writes the content stream to the response. + /// + /// The HTTP context of the request being answered. + public async Task ExecuteAsync(HttpContext httpContext) + { + if (_contentLength.HasValue) + httpContext.Response.ContentLength = _contentLength.Value; + httpContext.Response.ContentType = _contentType; + await using (_content) + await _content.CopyToAsync(httpContext.Response.Body, httpContext.RequestAborted).ConfigureAwait(false); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs index ddef6938..15ac1aeb 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs @@ -62,8 +62,23 @@ public class GetPlaybackManifestEndpoint : BaseEndpoint .Replace("{artistId}", artistId, StringComparison.Ordinal) .Replace("{albumId}", albumId, StringComparison.Ordinal) .Replace("{trackId}", trackId, StringComparison.Ordinal); - GetPlaybackManifestQuery query = new(libraryId, artistId, albumId, trackId, capabilities, streamPath); + // The segment route is filled in from the same route values, and its delivery handle and segment index placeholders are kept for the player + // to expand, so the manifest and the segment route can never disagree on the shape of the path either. The delivery handle is what binds + // the segments to the delivery this manifest declared; the capabilities are not repeated in the path. + string segmentStreamPathTemplate = ApiRoutes.Tracks.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", libraryId, StringComparison.Ordinal) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + GetPlaybackManifestQuery query = new(libraryId, artistId, albumId, trackId, capabilities, streamPath, segmentStreamPathTemplate); Result result = await _getPlaybackManifestQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); - return result.Match(success => TypedResults.Ok(success), Problem); + return result.Match(success => + { + // The manifest carries delivery metadata specific to the authenticated user, so no intermediary may store it and every response varies by + // the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + return TypedResults.Ok(success); + }, Problem); } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs index b5e5c781..14e54f8f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs @@ -34,13 +34,15 @@ public class GetPlaybackManifestEndpointSummary : Summary(r => r.ReplayGainTrackPeak, "The ReplayGain track peak of the track, if applicable."); ResponseParam(r => r.ReplayGainAlbumGain, "The ReplayGain album gain of the track, in decibels, if applicable."); ResponseParam(r => r.ReplayGainAlbumPeak, "The ReplayGain album peak of the track, if applicable."); - ResponseParam(r => r.DirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec."); + ResponseParam(r => r.IsDirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec."); ResponseParam(r => r.DeliveryContainer, "The container of the audio the server delivers, when the delivery is not a direct play."); ResponseParam(r => r.DeliveryCodec, "The codec of the audio the server delivers, when the delivery is not a direct play."); ResponseParam(r => r.DeliveryShape, "The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play."); ResponseParam(r => r.SegmentDurationSeconds, "The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments."); - ResponseParam(r => r.Seekable, "Whether the delivered audio can be seeked by the player."); + ResponseParam(r => r.IsSeekable, "Whether the delivered audio can be seeked by the player."); ResponseParam(r => r.StreamPath, "The path of the track stream, relative to the API, without a host or a scheme."); + ResponseParam(r => r.DeliveryId, "The opaque handle of the normalized delivery, which the segment route accepts. Null for a direct play."); + ResponseParam(r => r.SegmentStreamPathTemplate, "The path template of the segment route of the normalized delivery, relative to the API, with {deliveryId} and {segmentIndex} placeholders. Null for a direct play."); Response(200, "The playback manifest of the track is returned.", example: new PlaybackManifestResponse( @@ -55,13 +57,15 @@ public class GetPlaybackManifestEndpointSummary : Summary +/// API endpoint for the /libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex} route. +/// +public class GetTrackSegmentEndpoint : BaseEndpoint +{ + // The name is repeated in the web client application, which is a separate project that keeps its own contracts, so both sides must change together. + private const string SEGMENT_COUNT_HEADER_NAME = "X-Lumina-Segment-Count"; + private const string SEGMENT_START_SECONDS_HEADER_NAME = "X-Segment-Start-Seconds"; + private const string TRACK_DURATION_SECONDS_HEADER_NAME = "X-Lumina-Track-Duration-Seconds"; + + private readonly IQueryHandler> _getTrackSegmentQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get track segment queries. + public GetTrackSegmentEndpoint(IQueryHandler> getTrackSegmentQueryHandler) + { + _getTrackSegmentQueryHandler = getTrackSegmentQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Tracks.STREAM_TRACK_SEGMENT); + Version(1); + DontCatchExceptions(); + // The segment stream is limited per user with the same concurrency limiter as the track stream, and it is excluded from the eventual + // consistency pipeline, because a long lived response would otherwise hold the request's database transaction open for its whole duration. + Options(builder => builder + .RequireRateLimiting(PresentationApiLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY) + .WithMetadata(new SkipEventualConsistencyMetadata())); + } + + /// + /// Streams one segment of the normalized audio of the track identified by the route. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // Take unique identifiers and the segment index from the route. + string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString(); + string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString(); + string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString(); + string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString(); + string? deliveryId = HttpContext.Request.RouteValues["deliveryId"]?.ToString(); + string? segmentIndex = HttpContext.Request.RouteValues["segmentIndex"]?.ToString(); + GetTrackSegmentQuery query = new(libraryId, artistId, albumId, trackId, deliveryId, segmentIndex); + Result result = await _getTrackSegmentQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false); + if (result.IsFailure) + return Problem(result.Errors); + + // The produced segment is private to the authenticated user and is served from a temporary cache, so it must never be stored by an + // intermediary, and content sniffing stays disabled, so a segment can never be interpreted as active content. + HttpContext.Response.Headers["X-Content-Type-Options"] = "nosniff"; + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; + // The count lets the player stop at the end of the production instead of probing for it with a request that cannot be told apart + // from a track that was deleted or moved. It is sent on every segment, because any segment can be the first one a player fetches. + HttpContext.Response.Headers[SEGMENT_COUNT_HEADER_NAME] = result.Value.SegmentCount.ToString(); + // The real start of the segment, because ffmpeg cuts at the first packet at or after a segment boundary and a container can number its + // frames from the start of the track. The player offsets the packets by this value instead of assuming an exact multiple of the duration. + HttpContext.Response.Headers[SEGMENT_START_SECONDS_HEADER_NAME] = result.Value.StartSeconds.ToString(CultureInfo.InvariantCulture); + // The produced duration can differ from the probed duration, so the player uses this value for its timeline and progress bar. + HttpContext.Response.Headers[TRACK_DURATION_SECONDS_HEADER_NAME] = result.Value.DurationInSeconds.ToString(CultureInfo.InvariantCulture); + // The length comes from the index of the production, so the response is length delimited without reading the segment into memory first. + return new DisposingStreamResult(result.Value.Content, MusicMimeTypes.GetContainerMimeType(result.Value.Container), result.Value.Length); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs new file mode 100644 index 00000000..342dc56a --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackSegment/GetTrackSegmentEndpointSummary.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTrackSegmentEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTrackSegmentEndpointSummary() + { + Summary = "Streams one segment of the normalized audio of a track."; + Description = "Streams a single fixed duration segment of the normalized audio of the track identified by the route. A track that is not a direct play is delivered as fixed duration, time addressed segments, so a player seeks by segment index and never maps a byte range to a time. The delivery handle is the opaque value the playback manifest reports in its deliveryId, and the segment index is zero based; together they name a segment of exactly the delivery the manifest declared, including its quality cap and the source file version it was declared for. Library ownership is re-evaluated on every request, while track membership and content locations are those captured at manifest time, so a deleted track row whose file remains can stay streamable until the handle expires. The first request for a track may wait for the whole normalized audio to be produced and cached. The segment is streamed to an Admin, who can stream the tracks of all libraries, or to the owner of the library of the track."; + + Response(200, "The requested segment is streamed, with the media type of the delivered container, or application/octet-stream when the container is not an audio type, with the length of the segment as its content length, and with the segment count and its exact start time on the track timeline as the X-Lumina-Segment-Count and X-Segment-Start-Seconds headers.", "*/*"); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Authentication failed", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Unauthorized", + status = 403, + detail = "NotAuthorized", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the delivery handle is unknown, expired, or was issued to another user or track, the track or its media library does not exist, the track does not belong to the library, album and artist named by the route, the audio file of the track is outside the content locations of its library, missing, or unreadable, or the requested segment does not exist. Only the NormalizedTrackSegmentNotFound detail means the end of the normalized audio; every other not found detail is a playback failure.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "TrackNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "PlaybackDeliveryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "NormalizedTrackSegmentNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/999", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + }, + new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "NormalizedTrackCacheEntryNotFound", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/999", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + } + ); + + Response(409, "The delivery handle does not describe time addressed segments, or the source file changed since the manifest declared the delivery. The player must request the playback manifest again.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.10", + title = "General.Conflict", + status = 409, + detail = "PlaybackDeliveryChanged", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/not-a-handle/segments/-1", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "ArtistIdCannotBeEmpty", + "AlbumIdCannotBeEmpty", + "TrackIdCannotBeEmpty", + "DeliveryIdCannotBeEmpty", + "DeliveryIdIsInvalid", + "SegmentIndexMustBeValid" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + + Response(503, "Every normalization job slot, globally or for this user, is in use. The condition is transient and the request can be retried.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.6.4", + title = "General.ResourceUnavailable", + status = 503, + detail = "NormalizationUnavailable", + instance = $"/api/v1/libraries/{Guid.NewGuid()}/artists/{Guid.NewGuid()}/albums/{Guid.NewGuid()}/tracks/{Guid.NewGuid()}/stream/deliveries/8f14e45fceea167a5a36dedd4bea2543/segments/0", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs b/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs index b7889d22..a68ff3cc 100644 --- a/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs +++ b/src/Lumina.Presentation.Web/Common/Api/ApiStreamResult.cs @@ -1,6 +1,9 @@ #region ========================================================================= USING ===================================================================================== using System; +using System.Collections.Generic; +using System.Globalization; using System.IO; +using System.Linq; using System.Net; using System.Net.Http; using System.Threading; @@ -15,6 +18,21 @@ namespace Lumina.Presentation.Web.Common.Api; /// public sealed class ApiStreamResult : IAsyncDisposable { + /// + /// The response header that carries the number of segments of a normalized audio production. It must match the name the API sends. + /// + public const string SEGMENT_COUNT_HEADER_NAME = "X-Lumina-Segment-Count"; + + /// + /// The response header that carries the exact start of a segment on the track timeline, in seconds. It must match the name the API sends. + /// + public const string SEGMENT_START_SECONDS_HEADER_NAME = "X-Segment-Start-Seconds"; + + /// + /// The response header that carries the produced duration of the normalized track, in seconds. It must match the name the API sends. + /// + public const string TRACK_DURATION_SECONDS_HEADER_NAME = "X-Lumina-Track-Duration-Seconds"; + private readonly HttpResponseMessage _response; /// @@ -62,6 +80,22 @@ public sealed class ApiStreamResult : IAsyncDisposable /// public string? CacheControl { get; } + /// + /// Gets the number of segments the normalized audio production holds, when the response is a segment of one and declares it. + /// + public int? SegmentCount { get; } + + /// + /// Gets the exact start of the segment on the track timeline, in seconds, as declared by the API, or when the response + /// declares none. + /// + public string? SegmentStartSeconds { get; } + + /// + /// Gets the produced duration of the normalized track, in seconds, as declared by the API, or when the response declares none. + /// + public int? TrackDurationSeconds { get; } + /// /// Initializes a new instance of the class. /// @@ -79,6 +113,22 @@ public sealed class ApiStreamResult : IAsyncDisposable ETag = response.Headers.ETag?.ToString(); LastModified = response.Content.Headers.LastModified; CacheControl = response.Headers.CacheControl?.ToString(); + // The count is optional, because the same result also represents a track stream, which has no segments. A malformed or negative + // value is treated as absent instead of being passed to a caller that would use it to decide where the audio ends. + SegmentCount = response.Headers.TryGetValues(SEGMENT_COUNT_HEADER_NAME, out IEnumerable? segmentCountValues) + && int.TryParse(segmentCountValues.FirstOrDefault(), NumberStyles.None, CultureInfo.InvariantCulture, out int parsedSegmentCount) + && parsedSegmentCount >= 0 + ? parsedSegmentCount + : null; + // The start is forwarded as the API wrote it, so the web hop never reinterprets a decimal with the culture of this application. + SegmentStartSeconds = response.Headers.TryGetValues(SEGMENT_START_SECONDS_HEADER_NAME, out IEnumerable? segmentStartValues) + ? segmentStartValues.FirstOrDefault() + : null; + TrackDurationSeconds = response.Headers.TryGetValues(TRACK_DURATION_SECONDS_HEADER_NAME, out IEnumerable? trackDurationValues) + && int.TryParse(trackDurationValues.FirstOrDefault(), NumberStyles.None, CultureInfo.InvariantCulture, out int parsedTrackDuration) + && parsedTrackDuration > 0 + ? parsedTrackDuration + : null; } /// diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs index 0e4b2a53..0fa128aa 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlaybackManifestDto.cs @@ -9,7 +9,7 @@ namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; /// /// Data transfer object for the playback manifest of a track, describing the format of its stored audio, the delivery the server decided on for the requesting player, and the path of its stream. /// -[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")] +[DebuggerDisplay("TrackId: {TrackId} IsDirectPlay: {IsDirectPlay}")] public class PlaybackManifestDto { /// @@ -70,7 +70,7 @@ public class PlaybackManifestDto /// /// Gets or sets whether the player can play the stored audio as it is, without the server changing its container or its codec. /// - public bool DirectPlay { get; set; } + public bool IsDirectPlay { get; set; } /// /// Gets or sets the container of the audio the server delivers, when the delivery is not a direct play. @@ -95,11 +95,24 @@ public class PlaybackManifestDto /// /// Gets or sets whether the delivered audio can be seeked by the player. /// - public bool Seekable { get; set; } + public bool IsSeekable { get; set; } /// /// Gets or sets the path of the track stream. The API returns it relative to itself; this web application replaces it with /// the URL of its own streaming proxy, so that the browser never reaches the API server directly. /// public string StreamPath { get; set; } = string.Empty; + + /// + /// Gets or sets the opaque handle of the normalized delivery. The API returns it so the segment route can address exactly the delivery + /// the manifest declared. It is for a direct play. + /// + public string? DeliveryId { get; set; } + + /// + /// Gets or sets the path template of the segment route of the normalized delivery. The API returns it relative to itself with a + /// {deliveryId} and a {segmentIndex} placeholder; this web application replaces it with the URL of its own segment proxy, so + /// that the browser never reaches the API server directly. It is for a direct play. + /// + public string? SegmentStreamPathTemplate { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs b/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs new file mode 100644 index 00000000..6e6ca03f --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Http/ApiStreamProxy.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Microsoft.AspNetCore.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Common.Http; + +/// +/// Writes a streamed API response to the browser, so the direct track stream and the normalized segment proxy share the same status, header, caching and body forwarding rules and cannot drift apart. +/// +public static class ApiStreamProxy +{ + /// + /// Copies the streamed API response to the response sent to the browser, without buffering its content. + /// + /// The response sent to the browser. + /// The streamed response of the API. + /// Cancellation token that can be used to stop the copy when the client disconnects. + /// A that represents the asynchronous copy operation. + public static async Task WriteAsync(HttpResponse response, ApiStreamResult streamResult, CancellationToken cancellationToken) + { + response.StatusCode = (int)streamResult.StatusCode; + if (!string.IsNullOrEmpty(streamResult.ContentType)) + response.ContentType = streamResult.ContentType; + if (streamResult.ContentLength.HasValue) + response.ContentLength = streamResult.ContentLength.Value; + SetHeader(response, "Content-Range", streamResult.ContentRange); + SetHeader(response, "Accept-Ranges", streamResult.AcceptRanges); + SetHeader(response, "ETag", streamResult.ETag); + SetHeader(response, "Last-Modified", streamResult.LastModified?.ToString("R")); + if (streamResult.SegmentCount.HasValue) + SetHeader(response, ApiStreamResult.SEGMENT_COUNT_HEADER_NAME, streamResult.SegmentCount.Value.ToString()); + SetHeader(response, ApiStreamResult.SEGMENT_START_SECONDS_HEADER_NAME, streamResult.SegmentStartSeconds); + if (streamResult.TrackDurationSeconds.HasValue) + SetHeader(response, ApiStreamResult.TRACK_DURATION_SECONDS_HEADER_NAME, streamResult.TrackDurationSeconds.Value.ToString()); + // The response is private to the cookie that authenticates this hop, and it never becomes publicly cacheable, whatever the API declared. + response.Headers["Cache-Control"] = BuildCacheControl(streamResult.CacheControl); + response.Headers["Vary"] = "Cookie"; + await streamResult.Content.CopyToAsync(response.Body, cancellationToken).ConfigureAwait(false); + } + + /// + /// Sets a response header to the given value, unless the value is missing. + /// + /// The response to set the header on. + /// The name of the header. + /// The value of the header, or when the API did not send it. + private static void SetHeader(HttpResponse response, string name, string? value) + { + if (!string.IsNullOrEmpty(value)) + response.Headers[name] = value; + } + + /// + /// Builds the caching instructions of the browser response from the instructions of the API. + /// + /// + /// A streamed media response is specific to the authenticated user, so it must never be stored by a shared cache. Every other instruction of + /// the API, like a maximum age for the private cache of the browser or a no-store, is kept, so the web hop never silently ignores a caching + /// decision the API made for the resource. + /// + /// The caching instructions of the API response, or when it declared none. + /// The caching instructions of the response sent to the browser. + private static string BuildCacheControl(string? apiCacheControl) + { + if (!CacheControlHeaderValue.TryParse(apiCacheControl, out CacheControlHeaderValue? cacheControl)) + cacheControl = new CacheControlHeaderValue(); + cacheControl.Public = false; + cacheControl.Private = true; + return cacheControl.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs b/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs new file mode 100644 index 00000000..6a897aa6 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Playback/PlaybackDeliveryId.cs @@ -0,0 +1,31 @@ +namespace Lumina.Presentation.Web.Common.Playback; + +/// +/// Defines the format of the opaque delivery handle of a playback manifest. +/// +/// +/// The web application is a separate project that keeps its own contracts, so it repeats the API's rule rather than sharing a type: a handle is +/// exactly 32 lowercase hexadecimal characters, the N format of a GUID. A value that does not match it is rejected, never normalized. +/// +public static class PlaybackDeliveryId +{ + /// + /// The number of characters of a delivery handle. + /// + public const int CHARACTER_COUNT = 32; + + /// + /// Checks whether a value has the format of a delivery handle. + /// + /// The value to check. + /// when the value is exactly 32 lowercase hexadecimal characters, otherwise . + public static bool IsValid(string? value) + { + if (value is null || value.Length != CHARACTER_COUNT) + return false; + foreach (char character in value) + if (!((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'))) + return false; + return true; + } +} diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs new file mode 100644 index 00000000..b87294e8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegmentRequest.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Represents a request to stream one segment of the normalized audio of a track. +/// +/// The unique identifier of the artist the album belongs to, taken from the route. Required. +/// The unique identifier of the album the track belongs to, taken from the route. Required. +/// The unique identifier of the track to stream, taken from the route. Required. +/// The opaque handle of the normalized delivery, taken from the route. Required. +/// The zero based index of the segment of the normalized audio, taken from the route. Required. +/// The Id of the media library the track belongs to. Required. +[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")] +public record StreamMusicTrackSegmentRequest( + string ArtistId, + string AlbumId, + string TrackId, + string DeliveryId, + int SegmentIndex, + Guid LibraryId +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs index ad360ddd..01222527 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Music.cs @@ -25,6 +25,7 @@ public static partial class ApiRoutes public const string UPDATE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string DELETE_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}"; public const string STREAM_TRACK = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + public const string STREAM_TRACK_SEGMENT = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/playback-manifest"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs index 490c65fb..d320d927 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.Music.cs @@ -29,6 +29,7 @@ public static partial class WebRoutes public const string SAVE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-save-track"; public const string DELETE_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-delete-track"; public const string STREAM_TRACK = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track"; + public const string STREAM_TRACK_SEGMENT = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}"; public const string GET_PLAYBACK_MANIFEST = "{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-get-playback-manifest"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs index 9048d86c..793a1a81 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpoint.cs @@ -4,10 +4,10 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary; using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Playback; using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Net; @@ -72,9 +72,31 @@ public class GetPlaybackManifestEndpoint : BaseEndpoint + /// Builds the browser facing relative path template of the segment streaming proxy of this application for the track identified by the given Ids. + /// + /// + /// The placeholders of the route template are replaced with the Ids the manifest was requested for, and the delivery handle and segment index + /// placeholders are kept for the player to expand. The player substitutes the handle the manifest reported, so the segment request addresses + /// exactly the delivery that manifest declared, and the path is built exactly like the track stream path, so it can only ever point at this origin. + /// + /// The Id of the media library the track belongs to. + /// The normalized Id of the artist the album belongs to. + /// The normalized Id of the album the track belongs to. + /// The normalized Id of the track. + /// The root relative path template the browser fetches a segment from, on its own origin. + private string BuildBrowserSegmentStreamPath(Guid libraryId, string artistId, string albumId, string trackId) + { + string culture = IsSafePathSegment(Culture) ? Culture : "en-US"; + string pathBase = IsSafePathBase(HttpContext.Request.PathBase.ToString()) ? HttpContext.Request.PathBase.ToString().TrimEnd('/') : string.Empty; + string segmentPath = WebRoutes.Music.STREAM_TRACK_SEGMENT + .Replace("{culture}", culture, StringComparison.OrdinalIgnoreCase) + .Replace("{artistId}", artistId, StringComparison.Ordinal) + .Replace("{albumId}", albumId, StringComparison.Ordinal) + .Replace("{trackId}", trackId, StringComparison.Ordinal); + return $"{pathBase}/{segmentPath}?libraryId={libraryId}"; + } + /// /// Checks whether a value can be used safely as a single segment of a path the browser resolves against its own origin. /// /// The value to check. /// when the value cannot introduce a path separator, a query, a fragment, or a control character, otherwise. - private static bool IsSafePathSegment(string value) + private static bool IsSafePathSegment(string? value) { if (string.IsNullOrEmpty(value)) return false; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs index 8b201df0..7cc4d6bf 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointSummary.cs @@ -18,7 +18,7 @@ public class GetPlaybackManifestEndpointSummary : Summary r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs index eb8b455b..4d2c40ef 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Http; using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; @@ -10,7 +11,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; -using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; #endregion @@ -76,16 +76,8 @@ public class StreamMusicTrackEndpoint : BaseEndpoint 0 && !string.IsNullOrWhiteSpace(value.ToString())) headers[name] = value.ToString(); } - - /// - /// Copies the status and resource headers of the streamed API response to the response sent to the browser. - /// - /// The response sent to the browser. - /// The streamed response of the API. - private static void CopyResponseHeaders(HttpResponse response, ApiStreamResult streamResult) - { - if (!string.IsNullOrEmpty(streamResult.ContentType)) - response.ContentType = streamResult.ContentType; - if (streamResult.ContentLength.HasValue) - response.ContentLength = streamResult.ContentLength.Value; - SetHeader(response, "Content-Range", streamResult.ContentRange); - SetHeader(response, "Accept-Ranges", streamResult.AcceptRanges); - SetHeader(response, "ETag", streamResult.ETag); - SetHeader(response, "Last-Modified", streamResult.LastModified?.ToString("R")); - } - - /// - /// Sets a response header to the given value, unless the value is missing. - /// - /// The response to set the header on. - /// The name of the header. - /// The value of the header, or when the API did not send it. - private static void SetHeader(HttpResponse response, string name, string? value) - { - if (!string.IsNullOrEmpty(value)) - response.Headers[name] = value; - } - - /// - /// Builds the caching instructions of the response sent to the browser from the instructions of the API. - /// - /// - /// A stream is specific to the authenticated user, so it must never be stored by a shared cache. Every other instruction of the API, - /// like a maximum age for the private cache of the browser or a no-store, is kept, so that the web hop never silently ignores a caching - /// decision the API made for the resource. - /// - /// The caching instructions of the API response, or when it declared none. - /// The caching instructions of the response sent to the browser. - private static string BuildCacheControl(string? apiCacheControl) - { - if (!CacheControlHeaderValue.TryParse(apiCacheControl, out CacheControlHeaderValue? cacheControl)) - cacheControl = new CacheControlHeaderValue(); - cacheControl.Public = false; - cacheControl.Private = true; - return cacheControl.ToString(); - } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs new file mode 100644 index 00000000..51b377ab --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpoint.cs @@ -0,0 +1,99 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Playback; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment; + +/// +/// API endpoint for the /{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex} route. +/// +public class StreamMusicTrackSegmentEndpoint : BaseEndpoint +{ + private readonly IStreamingApiHttpClient _streamingApiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for streaming interactions with the API. + public StreamMusicTrackSegmentEndpoint(IStreamingApiHttpClient streamingApiHttpClient) + { + _streamingApiHttpClient = streamingApiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.Music.STREAM_TRACK_SEGMENT); + DontAutoTag(); + // The segment stream is bounded per user with the same concurrency limit as the track stream, so a single user can never hold an + // unbounded number of long lived responses open at once and exhaust the connections towards the API. + Options(options => options + .WithTags("Music") + .RequireRateLimiting(PresentationWebLayerServices.TRACK_STREAM_RATE_LIMIT_POLICY)); + } + + /// + /// Streams one segment of the normalized audio of the track identified by through the API, without buffering it. + /// + /// The request containing the Ids of the artist, album, track and media library, the delivery handle, and the segment index. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(StreamMusicTrackSegmentRequest request, CancellationToken cancellationToken) + { + // The route values are normalized to Guids before they are substituted into the upstream URL, so that a crafted route value can never + // escape its URL segment, and an unparseable id is reported by the API as a missing id. + string normalizedArtistId = Guid.TryParse(request.ArtistId, out Guid parsedArtistId) ? parsedArtistId.ToString() : Guid.Empty.ToString(); + string normalizedAlbumId = Guid.TryParse(request.AlbumId, out Guid parsedAlbumId) ? parsedAlbumId.ToString() : Guid.Empty.ToString(); + string normalizedTrackId = Guid.TryParse(request.TrackId, out Guid parsedTrackId) ? parsedTrackId.ToString() : Guid.Empty.ToString(); + // The handle has exactly one accepted format, so it is never normalized into another value that would silently address a different delivery. + if (!PlaybackDeliveryId.IsValid(request.DeliveryId)) + { + HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound; + HttpContext.Response.ContentLength = 0; + return Results.Empty; + } + string endpoint = ApiRoutes.Music.STREAM_TRACK_SEGMENT + .Replace("{libraryId}", request.LibraryId.ToString()) + .Replace("{artistId}", normalizedArtistId) + .Replace("{albumId}", normalizedAlbumId) + .Replace("{trackId}", normalizedTrackId) + .Replace("{deliveryId}", request.DeliveryId) + .Replace("{segmentIndex}", request.SegmentIndex.ToString()); + + // The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading. + ApiStreamResult streamResult; + try + { + streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, new Dictionary(), cancellationToken).ConfigureAwait(false); + } + catch (ApiException apiException) when (apiException.HttpStatusCode is HttpStatusCode.ServiceUnavailable or HttpStatusCode.TooManyRequests) + { + // A busy normalization pipeline or the stream concurrency limit is an expected, transient condition that the player retries. It is + // answered with a bare status instead of being logged as an unexpected API failure with a stack trace. + HttpContext.Response.StatusCode = (int)apiException.HttpStatusCode; + HttpContext.Response.ContentLength = 0; + return Results.Empty; + } + await using (streamResult) // The proxy owns the status, header, caching and body rules shared with the direct track stream proxy. + await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false); + return Results.Empty; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs new file mode 100644 index 00000000..eb9bc92c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrackSegment/StreamMusicTrackSegmentEndpointSummary.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrackSegment; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackSegmentEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public StreamMusicTrackSegmentEndpointSummary() + { + Summary = "Streams one segment of the normalized audio of a music track."; + Description = "Streams one fixed duration segment of the normalized audio of the music track identified by the route, through the API. A track the player cannot play directly is delivered as time addressed segments, so the player seeks by segment index instead of by byte range. The delivery handle is the opaque value the playback manifest reported, and it binds the segment to exactly the delivery that manifest declared."; + + RequestParam(r => r.ArtistId, "The unique identifier of the artist the album belongs to. Required."); + RequestParam(r => r.AlbumId, "The unique identifier of the album the track belongs to. Required."); + RequestParam(r => r.TrackId, "The unique identifier of the track to stream. Required."); + RequestParam(r => r.DeliveryId, "The opaque handle of the normalized delivery, reported by the playback manifest. Required."); + RequestParam(r => r.SegmentIndex, "The zero based index of the segment of the normalized audio. Required."); + RequestParam(r => r.LibraryId, "The unique identifier of the media library the track belongs to. Required."); + + Response(200, "The requested segment of the normalized audio of the track is streamed."); + Response(401, "The user is not authenticated."); + Response(403, "The user is not allowed to stream the track of the media library."); + Response(404, "The track, the album, the artist, the media library, the delivery handle, or the requested segment was not found, or is out of the scope of the route."); + Response(409, "The delivery handle no longer describes the delivery, or the source file changed. The player requests the manifest again."); + Response(429, "The user is already holding the maximum number of concurrent track streams."); + Response(502, "The remote API did not return the segment of the normalized audio of the track."); + Response(503, "The normalization pipeline is temporarily busy. The player retries the request."); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 5485eb9b..2ff409f0 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -43,6 +43,7 @@ updatePlaybackStateUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.UPDATE_PLAYBACK_STATE)', getPlaybackManifestUrl: '@_urlService.GetRelativeUrl(WebRoutes.Music.GET_PLAYBACK_MANIFEST)', streamTrackRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Music.STREAM_TRACK)', + streamTrackSegmentRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Music.STREAM_TRACK_SEGMENT)', strings: { play: '@localizer["AudioPlayerPlay"]', pause: '@localizer["AudioPlayerPause"]', @@ -85,5 +86,6 @@ + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js index 25da12a3..05fc64b7 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js @@ -37,11 +37,13 @@ * The needs normalization event * ----------------------------- * It is published on the player event bus as {@link LuminaAudioPlayer.PlayerEvent.NEEDS_NORMALIZATION}, with the payload - * { container, codec, reason }, plus directPlay when the caller supplied it, where the reason is one of the + * { container, codec, reason }, plus isDirectPlay when the caller supplied it, where the reason is one of the * {@link LuminaAudioPlayer.PlayerErrorReason} values NO_DEMUXER, CODEC_UNSUPPORTED or DEMUXER_FAILED. A consumer that - * asked for a normalized delivery uses it to request one. A normalized manifest, whose directPlay flag is false, is + * asked for a normalized delivery uses it to request one. A normalized manifest, whose isDirectPlay flag is false, is * refused by {@link LuminaAudioPlayer.createDemuxerForManifest} without an event, because the server already normalized - * such a track on purpose and its stream is not in the stored container. + * such a track on purpose and its stream is not in the stored container. The normalized delivery is parsed by + * {@link LuminaAudioPlayer.NormalizedSegmentDemuxer}, which builds one of these same demuxers per segment from the + * delivery container and codec of the manifest. */ (function (LuminaAudioPlayer) { 'use strict'; @@ -82,9 +84,9 @@ * @param {string} container - The canonical container of the track. * @param {string} codec - The canonical codec of the track. * @param {string} reason - One of the {@link LuminaAudioPlayer.PlayerErrorReason} values. - * @param {boolean} [directPlay] - The direct play flag of the manifest, when the caller has one. + * @param {boolean} [isDirectPlay] - The direct play flag of the manifest, when the caller has one. */ - function publishNeedsNormalization(events, container, codec, reason, directPlay) { + function publishNeedsNormalization(events, container, codec, reason, isDirectPlay) { if (!events || !LuminaAudioPlayer.PlayerEvent || typeof events.emit !== 'function') return; const payload = { @@ -96,8 +98,8 @@ // know, which is not the same as a false flag, the documented signal that the server already normalized the // track. Coercing an omitted flag to false would make every caller that has no manifest look like one whose // track the server chose to normalize. - if (directPlay !== undefined) - payload.directPlay = directPlay === true; + if (isDirectPlay !== undefined) + payload.isDirectPlay = isDirectPlay === true; events.emit(LuminaAudioPlayer.PlayerEvent.NEEDS_NORMALIZATION, Object.freeze(payload)); } @@ -176,20 +178,20 @@ * would silently drop the only signal that says which delivery to request. * @param {string} container - The container of the track. * @param {string} codec - The codec of the track. - * @param {boolean} [directPlay] - The direct play flag of the manifest, carried into the event. + * @param {boolean} [isDirectPlay] - The direct play flag of the manifest, carried into the event. * @returns {Promise} True when a demuxer exists and the browser can decode the codec. * @throws {TypeError} When no capability detector or no event bus was injected. It is a composition error, not a * property of the track, so it rejects rather than classifying the track. */ - async canPlayDirectlyAsync(container, codec, directPlay) { + async canPlayDirectlyAsync(container, codec, isDirectPlay) { const events = requireInjected(this.events, 'event bus'); const descriptor = this.match(container, codec); if (!descriptor) { - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, isDirectPlay); return false; } if (!await this.isCodecSupportedAsync(descriptor)) { - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, isDirectPlay); return false; } return true; @@ -204,7 +206,7 @@ async canPlayManifestDirectlyAsync(manifest) { if (!manifest) return false; - return await this.canPlayDirectlyAsync(manifest.sourceContainer, manifest.sourceCodec, manifest.directPlay); + return await this.canPlayDirectlyAsync(manifest.sourceContainer, manifest.sourceCodec, manifest.isDirectPlay); } /** @@ -288,7 +290,7 @@ const events = requireInjected(dependencies.events, 'event bus'); const descriptor = dependencies.registry ? dependencies.registry.find(container, codec) : null; if (!descriptor) { - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, settings.directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, settings.isDirectPlay); return null; } let demuxer = null; @@ -307,7 +309,7 @@ // whose bytes could not be fetched, so the failure is propagated and reported as the download failure it is. if (error instanceof LuminaAudioPlayer.PlayerError && error.code === LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED) throw error; - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.isDirectPlay); return null; } const configuration = demuxer.getConfiguration(); @@ -323,7 +325,7 @@ } if (!isConfigurationSupported) { await demuxer.destroyAsync(); - publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, settings.directPlay); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, settings.isDirectPlay); return null; } // The demuxer is usable, so the caller's error callback is attached from here on: a failure while reading is a @@ -344,9 +346,9 @@ * @returns {Promise} The ready demuxer, or null for a manifest that is not a direct play, or one that must be normalized. */ LuminaAudioPlayer.createDemuxerForManifest = function (manifest, options) { - if (!manifest || manifest.directPlay !== true) + if (!manifest || manifest.isDirectPlay !== true) return Promise.resolve(null); - return LuminaAudioPlayer.createDemuxerFor(manifest.sourceContainer, manifest.sourceCodec, Object.assign({}, options, { directPlay: true })); + return LuminaAudioPlayer.createDemuxerFor(manifest.sourceContainer, manifest.sourceCodec, Object.assign({}, options, { isDirectPlay: true })); }; /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js index b513f41d..13b03307 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -74,12 +74,25 @@ // which reads it as end of file rather than as a failure, so a rename on either side cannot silently turn a // drained window into a fatal read error. WINDOW_UNAVAILABLE: 'window-unavailable', + // A normalized segment that the production says exists could not be read, because the track, the library or the + // audio file is gone, or the cache entry was evicted. Unlike the end of the audio, which is declared by the + // segment count of the production, this is a playback failure; the player refreshes the manifest once and resumes. + SEGMENT_NOT_FOUND: 'segment-not-found', + // A normalized segment belongs to a delivery the server no longer accepts, because the delivery handle expired or the source changed. + // The player refetches the manifest and resumes at the current position instead of failing the track. + PLAYBACK_DELIVERY_CHANGED: 'playback-delivery-changed', + // Every normalization job slot was in use for the whole retry window, so the segment of a normalized track could + // not be produced in time. The request is transient and a later play can succeed. + NORMALIZATION_UNAVAILABLE: 'normalization-unavailable', + // A segment request failed for an HTTP reason that is neither a transient normalization limit nor a missing segment. + // Unlike WINDOW_UNAVAILABLE, which the demuxer byte source reads as end of file, this is always a playback failure. + HTTP_REQUEST_FAILED: 'http-request-failed', // A range request exceeded its timeout. Unlike an intentional abort, this is a failed request and is not retried // by the seek recovery. REQUEST_TIMEOUT: 'request-timeout', - // The playback manifest says the track is not a direct play, so the server has to normalize its container or its - // codec before the bundled player can play it. Published by the media pipeline engine while the normalized - // delivery pipeline does not exist yet, instead of playing the stored bytes. + // The stored format of a track cannot be demuxed and decoded by the bundled player, so the server has to normalize + // its container or its codec. Published by the media pipeline engine instead of playing bytes whose format the + // bundled demuxers cannot read; a normalized manifest is played through the segment pipeline. NORMALIZED_DELIVERY_REQUIRED: 'normalized-delivery-required', // A load was overtaken by a newer play request before it finished. The player ignores it, because the newer // request owns the player state and the queue. diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js index ac8b61b8..6b887568 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js @@ -42,7 +42,7 @@ // A track cannot be demuxed and decoded directly by the bundled player, so the server has to normalize it (remux or // transcode) before it can play. Payload: { container, codec, reason }, where reason is one of the // {@link LuminaAudioPlayer.PlayerErrorReason} values NO_DEMUXER, CODEC_UNSUPPORTED or DEMUXER_FAILED, and, when the - // caller supplied one, directPlay, the direct play flag of the manifest it asked about, so a consumer can tell a + // caller supplied one, isDirectPlay, the direct play flag of the manifest it asked about, so a consumer can tell a // client-side capability gap from a track the server already decided to normalize. The flag is absent, not false, // when the caller had no manifest. NEEDS_NORMALIZATION: 'needsnormalization', diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js index e3d37771..c676f31b 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js @@ -190,6 +190,119 @@ return resolved.href; } + /** + * Checks that a resolved segment path matches the segment route template this application emitted and belongs to the expected track, library and segment index. + * @param {URL} url - The resolved segment URL. + * @param {Object} descriptor - The play descriptor the manifest belongs to. + * @param {Object} configuration - The endpoints configuration of the player. + * @param {number} segmentIndex - The zero based index of the segment. + * @param {string} deliveryId - The opaque delivery handle the manifest reported. + * @throws {LuminaAudioPlayer.PlayerError} When the route template is missing, is on another origin, or the path does not + * match the route, the expected track and library, the expected segment index, or the expected delivery handle. + */ + function validateSegmentStreamRoute(url, descriptor, configuration, segmentIndex, deliveryId) { + const templateValue = configuration && configuration.streamTrackSegmentRouteTemplate; + if (typeof templateValue !== 'string' || templateValue.length === 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment stream route template is not configured.'); + let template; + try { + template = new URL(templateValue, getBaseOrigin()); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment stream route template is not a valid URL.', { cause: error }); + } + if ((template.protocol !== 'http:' && template.protocol !== 'https:') + || (hasWindowOrigin() && template.origin !== window.location.origin) + || template.origin !== url.origin + || template.username !== '' + || template.password !== '') + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment stream route template is not on this origin.'); + const expectedIds = { + artistId: descriptor && descriptor.artistId, + albumId: descriptor && descriptor.albumId, + trackId: descriptor && descriptor.trackId + }; + const templateSegments = template.pathname.split('/'); + const streamSegments = url.pathname.split('/'); + if (templateSegments.length !== streamSegments.length) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not match the segment route.'); + for (let index = 0; index < templateSegments.length; index++) { + let templateSegment; + try { + templateSegment = decodeURIComponent(templateSegments[index]); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment route template carries an invalid escape.', { cause: error }); + } + const placeholder = /^\{([A-Za-z0-9_]+)\}$/.exec(templateSegment); + let actualSegment; + try { + // Decode the actual segment too, so a path base or a static segment that contains an encoded character still compares equal to the template it came from. + actualSegment = decodeURIComponent(streamSegments[index]); + } catch (error) { + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path carries an invalid escape.', { cause: error }); + } + if (placeholder) { + const name = placeholder[1]; + if (name === 'segmentIndex') { + if (!Number.isInteger(segmentIndex) || segmentIndex < 0 || actualSegment !== String(segmentIndex)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not belong to the expected segment index.'); + continue; + } + if (name === 'deliveryId') { + // The path must name the delivery handle the manifest reported, not another delivery of the same track. + if (typeof deliveryId !== 'string' || actualSegment !== deliveryId) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not belong to the expected delivery.'); + continue; + } + if (!Object.prototype.hasOwnProperty.call(expectedIds, name)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment route template carries an unknown placeholder.'); + const expected = expectedIds[name]; + if (!isGuid(expected)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, `The play descriptor carries no valid ${name}.`, { field: name }); + // The path must describe the track of this descriptor, not merely another track of the same library. + if (!isGuid(actualSegment) || actualSegment.toLowerCase() !== expected.toLowerCase()) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not belong to the expected track.'); + continue; + } + if (templateSegment !== actualSegment) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not match the segment route.'); + } + const libraryId = descriptor && descriptor.libraryId; + if (!isGuid(libraryId)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, 'The play descriptor carries no valid library Id.', { field: 'libraryId' }); + const requestedLibraryIds = url.searchParams.getAll('libraryId'); + if (requestedLibraryIds.length !== 1 || requestedLibraryIds[0].toLowerCase() !== libraryId.toLowerCase()) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment path does not belong to the expected library.'); + } + + /** + * Resolves the segment path template of a normalized playback manifest into the URL of one segment. + * @param {Object} manifest - The playback manifest. + * @param {Object} descriptor - The play descriptor the manifest belongs to. + * @param {Object} configuration - The endpoints configuration of the player. + * @param {number} segmentIndex - The zero based index of the segment to fetch. + * @returns {string} The validated resolved segment URL. + * @throws {LuminaAudioPlayer.PlayerError} When the manifest carries no safe segment path, the index is invalid, or the + * path is not the segment route of the expected track, library and index. + */ + function resolveSegmentStreamUrl(manifest, descriptor, configuration, segmentIndex) { + if (!Number.isInteger(segmentIndex) || segmentIndex < 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The segment index is not valid.'); + const deliveryId = manifest && manifest.deliveryId; + // The delivery handle is an opaque server issued token, so it is confined to the characters a path segment can carry and never contains a + // separator, a query, a fragment or a control character that could change the route it is substituted into. + if (typeof deliveryId !== 'string' || !/^[0-9a-f]{32}$/.test(deliveryId)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The manifest carries no valid delivery handle.'); + const template = manifest && manifest.segmentStreamPathTemplate; + if (typeof template !== 'string' || !template.includes('{deliveryId}') || !template.includes('{segmentIndex}')) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The manifest carries no segment stream path template.'); + const value = template + .split('{deliveryId}').join(deliveryId) + .split('{segmentIndex}').join(String(segmentIndex)); + const resolved = resolveSameOriginUrl(value); + validateSegmentStreamRoute(resolved.url, descriptor, configuration, segmentIndex, deliveryId); + return resolved.href; + } + /** * Builds the URL of the playback manifest endpoint for a descriptor, including the capability list. * @param {Object} configuration - The endpoints configuration of the player. @@ -317,5 +430,6 @@ } LuminaAudioPlayer.resolveStreamUrl = resolveStreamUrl; + LuminaAudioPlayer.resolveSegmentStreamUrl = resolveSegmentStreamUrl; LuminaAudioPlayer.fetchPlaybackManifestAsync = fetchPlaybackManifestAsync; })(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js index e80cc0b9..04941933 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js @@ -40,13 +40,13 @@ * * Gapless transitions * ------------------- - * When the user enabled gapless playback and the player queue holds another item, the engine prefetches the next item as - * soon as the current one is loaded: it fetches the next manifest, opens its demuxer, and pre-decodes the first seconds of - * its audio into memory. The prefetch does not run an open-ended download next to the current one: it fetches only the - * windows its pre-decode needs, as bounded range requests, and leaves the sequential download of the next track stopped - * until the handoff. Once the current decoder has scheduled its last frame, the pre-decoded audio is appended to the - * renderer schedule, exactly after the audio of the current track, the download of the next track resumes from its first - * missing byte, and the rest of the track is decoded into the same schedule. The engine then switches the current item at the exact media position where the next + * When the user enabled gapless playback and the player queue holds another item, the engine waits until the current track is within a short lead + * of its end, then fetches the next manifest and pre-decodes its first audio. Nothing is requested at load time: a normalized next track would start + * a full server side production that is expensive and bounded in concurrency, and a direct track would hold bytes for a track the user may never + * reach. Normalized gapless therefore only happens when the production is already cached or finishes within the lead; otherwise the next track + * starts normally at the boundary. Once the current decoder has scheduled its last frame, the pre-decoded audio is appended to the renderer + * schedule, exactly after the audio of the current track, the download of the next track resumes from its first missing byte, and the rest of the + * track is decoded into the same schedule. The engine then switches the current item at the exact media position where the next * audio starts, reports the new duration and asks the player to advance its queue, so the bar shows the new track while * the audio never stops. Only the last track of a continuous chain declares the stream complete, which is what keeps the * renderer from reporting an end between two gapless items. @@ -56,10 +56,11 @@ * A download, demux or decode failure that happens mid-stream is reported once, through host.reportError, and stops the * pipeline cleanly; it never escapes as an unhandled rejection and never leaves the renderer or the downloader running. * A failure of a prefetch is dropped instead, because it must not interrupt the track that is playing. A track whose - * manifest is not a direct play needs the normalized delivery pipeline, which this engine does not implement yet, so it - * is reported as an engine load failure with the {@link LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED} - * reason. A play descriptor must name a track, not an album or an artist, because the manifest endpoint is addressed by the - * track and its album and artist; expanding an album or an artist context into its tracks is the queue engine's job. + * manifest is not a direct play is played from the fixed duration segments the server produces, through the normalized + * delivery pipeline (audio-player-pipeline-normalized.js), and it is seeked by segment index exactly like a direct play is + * seeked by byte range. A play descriptor must name a track, not an album or an artist, because the manifest endpoint is + * addressed by the track and its album and artist; expanding an album or an artist context into its tracks is the queue + * engine's job. */ (function (LuminaAudioPlayer) { 'use strict'; @@ -108,6 +109,15 @@ */ const PREFETCH_HANDOFF_MAX_WAIT_SECONDS = 5; + /** + * The playback time, in seconds, before the end of the current track at which the next item is prefetched. A direct play needs a few seconds + * to pre-decode its first audio, and a normalized production is expensive and bounded in concurrency, so starting either at load time would + * hold resources for a track the user may never reach. + * @readonly + * @type {number} + */ + const PREFETCH_LEAD_SECONDS = 15; + /** * Coerces a value to a finite number, or null when it is absent or not finite. * @param {*} value - The value to coerce. @@ -195,10 +205,6 @@ const manifest = await this.fetchManifestAsync(descriptor, signal); if (!this.isLoadCurrent(token)) throw this.createSupersededLoadError(); - if (manifest.directPlay !== true) { - // The normalized delivery pipeline is a later stage; until it exists, the track is reported instead of being played as its stored bytes, which would produce noise or a decoder error. - throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The track needs a normalized delivery the player does not support yet.', { reason: LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED }); - } this.renderer.configure(manifest); const item = await this.buildItemAsync(descriptor, manifest, false); if (!this.isLoadCurrent(token) || this.destroyed) { @@ -705,39 +711,83 @@ disposed: false, failed: false, stopped: false, - hasScheduledAudio: false + hasScheduledAudio: false, + // A delivery refresh is attempted once per item. If the refreshed handle is rejected again, the failure is terminal, so a stale or + // broken delivery cannot make the player refetch the manifest forever. + deliveryRecoveryAttempted: false, + deliveryRecoveryInProgress: false }; - const streamPath = LuminaAudioPlayer.resolveStreamUrl(manifest, descriptor, this.getConfiguration()); - item.downloader = LuminaAudioPlayer.createTrackDownloader({ - url: streamPath, - durationInSeconds: duration, - shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, - events: this.events, - onProgress: (downloadedFraction) => { - if (item === this.current) - this.host.reportProgress(downloadedFraction); - }, - onError: (error) => this.handleDownloadFailure(item, error) - }); - if (typeof onItemCreated === 'function') - onItemCreated(item); - // The demuxer reads through the seek aware source, so a seek can fetch a window below the byte target of the download loop instead of waiting for bytes the loop never fetches. - item.source = new LuminaAudioPlayer.SeekAwareByteSource(item.downloader); - if (isPrefetch) { - // A prefetch fetches only the windows its pre-decode needs, through one-shot range requests, instead of - // running a second open-ended download from the moment the current track starts. Its sequential download is - // started at the handoff, from the first byte that is still missing. - item.source.setSeeking(true); - } else { - item.downloader.startAsync(); - } try { - const demuxer = await LuminaAudioPlayer.createDemuxerForManifest(manifest, { - source: item.source, - capabilities: this.capabilities, - events: this.events, - onError: (error) => this.failItem(item, error) - }); + const isNormalizedDelivery = manifest.isDirectPlay !== true; + let demuxer = null; + if (isNormalizedDelivery) { + const segmentDurationSeconds = Number(manifest.segmentDurationSeconds); + if (!manifest.deliveryContainer || !manifest.deliveryCodec || !Number.isInteger(segmentDurationSeconds) || segmentDurationSeconds <= 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The normalized delivery of the track is incomplete.'); + const configuration = this.getConfiguration(); + item.downloader = LuminaAudioPlayer.createNormalizedSegmentDownloader({ + durationInSeconds: duration, + segmentDurationSeconds: segmentDurationSeconds, + urlBuilder: (segmentIndex) => LuminaAudioPlayer.resolveSegmentStreamUrl(manifest, descriptor, configuration, segmentIndex), + shouldRetryUnavailable: !isPrefetch, + shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, + events: this.events, + onProgress: (downloadedFraction) => { + if (item === this.current) + this.host.reportProgress(downloadedFraction); + }, + onError: (error) => this.handleDownloadFailure(item, error) + }); + if (typeof onItemCreated === 'function') + onItemCreated(item); + // The normalized demuxer fetches complete segments itself, so it needs no byte source. The engine still drives a source on + // seek and teardown, so a no-op source of the same shape keeps that path uniform without a download loop behind it. + item.source = { + setSeeking: () => {}, + destroy: () => {} + }; + if (!isPrefetch) + item.downloader.startAsync(); + demuxer = await LuminaAudioPlayer.createNormalizedSegmentDemuxer(manifest, { + downloader: item.downloader, + capabilities: this.capabilities, + events: this.events, + onError: (error) => this.failItem(item, error) + }); + } else { + const streamPath = LuminaAudioPlayer.resolveStreamUrl(manifest, descriptor, this.getConfiguration()); + item.downloader = LuminaAudioPlayer.createTrackDownloader({ + url: streamPath, + durationInSeconds: duration, + shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, + events: this.events, + onProgress: (downloadedFraction) => { + if (item === this.current) + this.host.reportProgress(downloadedFraction); + }, + onError: (error) => this.handleDownloadFailure(item, error) + }); + if (typeof onItemCreated === 'function') + onItemCreated(item); + // The demuxer reads through the seek aware source, so a seek can fetch a window below the byte target of the download loop instead of waiting for bytes the loop never fetches. + item.source = new LuminaAudioPlayer.SeekAwareByteSource(item.downloader); + if (isPrefetch) { + // A prefetch fetches only the windows its pre-decode needs, through one-shot range requests, instead of + // running a second open-ended download from the moment the current track starts. Its sequential download is + // started at the handoff, from the first byte that is still missing. + item.source.setSeeking(true); + } else { + item.downloader.startAsync(); + } + } + if (!demuxer) { + demuxer = await LuminaAudioPlayer.createDemuxerForManifest(manifest, { + source: item.source, + capabilities: this.capabilities, + events: this.events, + onError: (error) => this.failItem(item, error) + }); + } if (!demuxer) { // A cancelled or aborted header probe and a transport failure are not properties of the track, so // they are reported as themselves. Only a probe that actually concluded the bundled player cannot @@ -1112,9 +1162,14 @@ item.prefetch = token; const phase = (async () => { try { + // The prefetch waits for the monitor to report that the current track is close enough to its end. No manifest is requested and no + // normalized production is started before then, so a skipped or abandoned track never holds a delivery handle or a normalization slot. + const isWindowOpen = await this.waitForPrefetchWindowAsync(item, token); + if (!isWindowOpen) + return null; const signal = token.abortController ? token.abortController.signal : undefined; const manifest = await this.fetchManifestAsync(nextDescriptor, signal); - if (token.cancelled || this.destroyed || item.stopped || manifest.directPlay !== true) + if (token.cancelled || this.destroyed || item.stopped) return null; const prefetched = await this.buildItemAsync(nextDescriptor, manifest, true, (created) => { token.item = created; @@ -1157,6 +1212,70 @@ }); } + /** + * Waits until the current track is close enough to its end for the prefetch to start. The wait is resolved by the playback monitor when it + * crosses the lead, and is rejected as false when the prefetch is cancelled, so no timer polls the whole track and a paused track starts nothing until it resumes near the end. + * @param {Object} item - The current item whose successor is prefetched. + * @param {Object} token - The prefetch token of the current item. + * @returns {Promise} True when the prefetch window opened, false when the prefetch was cancelled or the item stopped. + */ + waitForPrefetchWindowAsync(item, token) { + return new Promise((resolve) => { + token.windowResolve = resolve; + this.tryOpenPrefetchWindow(item, token); + }); + } + + /** + * Opens the prefetch window when the current track is within the lead of its end, or closes it when the prefetch is no longer wanted. + * @param {Object} item - The current item whose successor is prefetched. + * @param {Object} token - The prefetch token of the current item. + */ + tryOpenPrefetchWindow(item, token) { + if (!token || !token.windowResolve) + return; + if (token.cancelled || this.destroyed || !item || item.stopped || item.disposed || this.current !== item) { + this.closePrefetchWindow(token); + return; + } + // A completion that already fell back to a normal next-track start has no use for a prefetch, so it is not started only to be thrown away. + if (item.continueToEntry) { + this.closePrefetchWindow(token); + return; + } + if (this.getRemainingPlaybackSeconds(item) > PREFETCH_LEAD_SECONDS) + return; + const resolve = token.windowResolve; + token.windowResolve = null; + resolve(true); + } + + /** + * Closes a pending prefetch window as false, so the prefetch phase ends instead of waiting for a track that is no longer current. + * @param {Object} token - The prefetch token whose window is closed. + */ + closePrefetchWindow(token) { + if (!token || !token.windowResolve) + return; + const resolve = token.windowResolve; + token.windowResolve = null; + resolve(false); + } + + /** + * Gets how much playback time is left in an item, from the shared renderer playhead. + * @param {Object} item - The item whose remaining time is read. + * @returns {number} The remaining time, in seconds, or zero when the duration is unknown or already reached. + */ + getRemainingPlaybackSeconds(item) { + const duration = Number(item && item.duration); + if (!Number.isFinite(duration) || duration <= 0) + return 0; + const absolute = Number(this.renderer.getCurrentTime()); + const local = Number.isFinite(absolute) ? Math.max(0, absolute - Number(item.base || 0)) : 0; + return Math.max(0, duration - local); + } + /** * Appends the pre-decoded audio of the next item to the renderer schedule, exactly after the audio of the current * track, and lets its decode continue into the same schedule. The current item stays current until the media position of the next item begins. @@ -1180,6 +1299,10 @@ next.downloader.setPlaybackPaused(false); next.downloader.startAsync(); } + // Prefetches are built with retries disabled, because an unavailable production abandons the prefetch instead of holding it open. + // After the handoff this item is the track that owns the playhead, so a temporarily unavailable segment is retried like any current track. + if (typeof next.downloader.setShouldRetryUnavailable === 'function') + next.downloader.setShouldRetryUnavailable(true); // The end of the scheduled audio of the current track is the exact media position the next track starts at. next.base = this.renderer.getScheduledMediaDuration(); this.nextItem = next; @@ -1350,6 +1473,8 @@ return; item.prefetch = null; token.cancelled = true; + // A prefetch that is still waiting for its window is released immediately instead of keeping the teardown open. + this.closePrefetchWindow(token); if (token.abortController) { try { token.abortController.abort(); @@ -1426,6 +1551,7 @@ // the monitor neither pauses the renderer nor advances a boundary of the timeline that is being replaced. if (this.current.isSeeking || this.isLoadingTrack) return; + this.tryOpenPrefetchWindow(this.current, this.current.prefetch); this.isMonitoring = true; try { const absolute = this.renderer.getCurrentTime(); @@ -1603,6 +1729,138 @@ this.failItem(item, error); } + /** + * Checks whether a failure is a delivery that the server no longer accepts, which the player can fix by fetching the manifest again. + * @param {Object} item - The item that failed. + * @param {*} error - The failure. + * @returns {boolean} True when the delivery should be refreshed and playback resumed at the current position. + */ + shouldRecoverDelivery(item, error) { + if (!item || item !== this.current || item.deliveryRecoveryAttempted || item.deliveryRecoveryInProgress || this.destroyed) + return false; + if (!error || error.code !== LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED || !error.details) + return false; + const reason = error.details.reason; + return reason === LuminaAudioPlayer.PlayerErrorReason.SEGMENT_NOT_FOUND + || reason === LuminaAudioPlayer.PlayerErrorReason.PLAYBACK_DELIVERY_CHANGED; + } + + /** + * Refetches the manifest of the current track and rebuilds the normalized pipeline at the current playback position, used when the + * delivery handle expired, the API restarted, or the source file changed since the manifest was read. + * @param {Object} item - The item whose delivery must be refreshed. + * @param {*} originalError - The failure that triggered the refresh. + * @returns {Promise} A promise that completes when playback resumed on the refreshed delivery. + */ + async recoverDeliveryAsync(item, originalError) { + // The attempt is marked before the first await, because the teardown below can raise failures, and a second recovery started + // from one of them would race this one for the same item. + item.deliveryRecoveryInProgress = true; + item.deliveryRecoveryAttempted = true; + // An underrun pause is a temporary buffer stall, not a user pause, so it must be resumed after the refresh just like active playback. + const wasPlaying = !this.isUserPaused && (this.renderer.isPlaying() || this.isUnderrunPaused); + // The renderer time is shared by the whole queue, while the position to resume at is relative to this track. + const position = Math.max(0, Number(this.renderer.getCurrentTime()) - Number(item.base || 0)); + // Stop observing the old pipeline before pausing it, so the monitor does not treat the intentional pause as an underrun and does + // not schedule more work against the delivery that is being replaced. + this.stopMonitor(); + this.isUnderrunPaused = false; + this.host.reportBuffering(true); + try { + await this.renderer.pauseAsync(); + } catch (pauseError) { + // The old item is released below regardless, so a renderer that refuses to pause must not abort the recovery. + console.debug('Audio player: the renderer could not be paused before refreshing the delivery.', pauseError); + } + // A prefetched successor was built from the old manifest, so keeping it would hand off to the expired delivery handle. + this.cancelPrefetchWait(item); + if (item.prefetch) { + try { + await this.cancelPrefetchAsync(item); + } catch (prefetchError) { + console.debug('Audio player: the prefetch of the failed delivery could not be released.', prefetchError); + } + } + // An already attached next track may have audio scheduled from the old delivery, so it is released before the new manifest + // is read instead of letting two deliveries meet at the track boundary. + if (this.nextItem) { + const attachedNextItem = this.nextItem; + this.nextItem = null; + await this.disposeItemAsync(attachedNextItem).catch((disposeError) => { + console.debug('Audio player: the attached next track of the failed delivery could not be released.', disposeError); + }); + } + // The old decode loop and downloads must stop before the replacement is built, because their aborts and failures belong to the + // delivery being replaced and must not be mistaken for failures of the new one. + item.loopToken = null; + if (item.downloader) + item.downloader.abort(); + + let manifest; + try { + manifest = await this.fetchManifestAsync(item.descriptor); + } catch (manifestError) { + // The user needs the failure that interrupted playback, not the recovery attempt that also failed. + console.debug('Audio player: the manifest of the failed delivery could not be refreshed.', manifestError); + throw originalError; + } + // The awaits above can be overtaken by a new load or by teardown, and recovery must never touch a different current item. + if (this.destroyed || this.current !== item) + return; + if (manifest.isDirectPlay === true) { + // The server now considers the track a direct play. Converting the running normalized pipeline to the direct stream is a different + // transition, so the track ends with the original failure instead of playing mixed deliveries. + throw originalError; + } + try { + // ReplayGain and timeline metadata can change with the refreshed manifest, so the renderer is configured before the + // replacement pipeline starts producing audio. + this.renderer.configure(manifest); + } catch (configureError) { + console.debug('Audio player: the renderer could not be configured for the refreshed delivery.', configureError); + throw originalError; + } + + let replacement; + try { + // The replacement owns fresh downloader, demuxer and decoder state bound to the new delivery handle. + replacement = await this.buildItemAsync(item.descriptor, manifest, false); + } catch (buildError) { + console.debug('Audio player: the refreshed delivery could not be prepared.', buildError); + throw originalError; + } + // Building the replacement took another await, so it is discarded if the user left this track in the meantime. + if (this.destroyed || this.current !== item) { + await this.disposeItemAsync(replacement); + return; + } + // The replacement starts at the beginning of this track on the shared timeline. The attempted flag is carried over so a delivery + // that is still rejected after the refresh cannot make the player refetch the manifest forever. + replacement.base = 0; + replacement.deliveryRecoveryAttempted = true; + this.current = replacement; + if (replacement.duration > 0) + this.renderer.setTimelineDuration(replacement.duration); + this.host.reportDuration(replacement.duration); + await this.disposeItemAsync(item); + // A seek rebuilds every stage at the requested position. At zero there is nothing to seek, so the decode loop and its prefetch are started explicitly. + if (position > 0) + await this.seekAsync(position); + else { + this.startDecodeLoop(replacement); + this.startGaplessPrefetch(replacement); + } + // Seeking is asynchronous, so the user may have paused, stopped or replaced the track while it ran. Do not resume a pipeline that no longer owns the playhead. + if (this.current !== replacement || replacement.failed || replacement.stopped || this.destroyed) + return; + // Resume only if audio was actually being heard before the refresh and the user has not paused since. A user pause must stay a pause, while an underrun pause is restored. + if (wasPlaying && !this.isUserPaused) { + await this.renderer.playAsync(); + this.startMonitor(); + } + this.host.reportBuffering(false); + } + /** * Records a failure of an item once and reports it to the player when the item is the current one. * @param {Object} item - The item that failed. @@ -1613,6 +1871,17 @@ return; if (LuminaAudioPlayer.isDownloadAbort(error)) return; + // Errors raised by the old pipeline while it is being replaced by a refreshed delivery belong to that teardown, not to a new failure. + if (item.deliveryRecoveryInProgress) + return; + if (this.shouldRecoverDelivery(item, error)) { + this.recoverDeliveryAsync(item, error).catch((recoveryError) => { + console.debug('Audio player: the refreshed delivery could not be applied.', recoveryError); + item.deliveryRecoveryInProgress = false; + this.failItem(item, error); + }); + return; + } item.failed = true; item.stopped = true; try { @@ -1719,10 +1988,12 @@ async disposeItemAsync(item) { if (!item || item.disposed) return; + // The flags are set before any await, so callbacks raised by the teardown itself see the item as dead instead of failing it again. item.disposed = true; item.stopped = true; item.loopToken = null; this.cancelPrefetchWait(item); + // Stop scheduling before the decoder is torn down, so a frame produced during teardown can never enter the renderer schedule. if (item.scheduler) item.scheduler.stop(); // The item may itself have prefetched the track after it, which must not keep downloading or decoding once the @@ -1751,6 +2022,7 @@ } } await this.waitForDecodeLoopAsync(item); + // The loop has exited, so the scheduler and the demuxer it could still touch are released next. if (item.scheduler) { try { item.scheduler.dispose(); @@ -1767,6 +2039,7 @@ } if (item.source) item.source.destroy(); + // The downloader is destroyed last, because the demuxer and the byte source may hold its reads until they are released. if (item.downloader) { try { await item.downloader.destroyAsync(); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js new file mode 100644 index 00000000..b714a167 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js @@ -0,0 +1,1204 @@ +/** + * Normalized delivery pipeline of the audio player. + * + * A track the player cannot play as stored is produced by the server as a sequence of fixed duration, time addressed + * segments. A byte range cannot be mapped to a time in such a delivery, so the player addresses it by segment index + * instead: the playback manifest carries a segment path template, the downloader fetches one complete segment at a time, + * and the segment demuxer parses each segment with the demuxer of the delivered container and codec, presenting them to + * the decode pipeline as one continuous timeline. + * + * What it owns + * ------------ + * - NormalizedSegmentDownloader fetches the segments named by the manifest, keeps every fetched segment in memory for + * the lifetime of the track so a seek back into a segment never fetches it again, and reports the downloaded time + * ranges and fraction to the player. A segment is an independent container file, so it is fetched whole; the server + * has already cut it at a fixed duration, which is what makes a segment a seek unit. The end of the audio is declared + * by the segment count header of every response, so a segment that returns not found is a failure (a deleted track, a + * moved file or an evicted cache entry), never a silent end of stream. A response that reports every normalization job + * slot busy is retried with backoff while the track is playing, because the production is bounded and shared. + * A bounded lookahead of one segment keeps the next segment in memory before the decoder needs it. It stops while + * playback is paused unless the keep-downloading-while-paused preference is on, and it never advances past the window, + * so the whole track is not downloaded at once. + * - NormalizedSegmentDemuxer wraps the per segment demuxers behind the same interface the bundled demuxers expose. It + * initializes the demuxer of the delivered container, offsets every packet timestamp by the start of its segment, drops + * the packets that end before a seek target, and moves to the next segment when the current one ends. + * + * Seeking + * ------- + * A seek selects the segment that covers the target time, reloads it from its first byte, seeks inside it when the + * container supports a time seek, and reports a segment covering position so the engine's existing seek trim applies. No + * range request is ever issued for a segment, and no byte range is mapped to a time. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The response header that carries the number of segments a normalized audio production holds. + * @readonly + * @type {string} + */ + const SEGMENT_COUNT_HEADER = 'X-Lumina-Segment-Count'; + + /** + * The response header that carries the exact start of a segment on the track timeline, in seconds. + * @readonly + * @type {string} + */ + const SEGMENT_START_SECONDS_HEADER = 'X-Segment-Start-Seconds'; + + /** + * The response header that carries the produced duration of the normalized track, in seconds. + * @readonly + * @type {string} + */ + const TRACK_DURATION_SECONDS_HEADER = 'X-Lumina-Track-Duration-Seconds'; + + /** + * The delays, in milliseconds, between the attempts of a segment request that the server answered as temporarily unavailable. + * The production that serves a segment is bounded in concurrency and shared by every user, so a request that arrives while every + * job slot is in use is a transient condition, not a failure of the track. + * @readonly + * @type {ReadonlyArray} + */ + const UNAVAILABLE_RETRY_DELAYS_MS = Object.freeze([500, 1000, 2000, 4000, 8000, 16000, 30000]); + + /** + * The longest time, in milliseconds, a playing segment waits for a normalization slot before the request becomes a playback failure. It is + * longer than the default normalization job timeout, so a production that legitimately started before this request is not reported as an error. + * @readonly + * @type {number} + */ + const MAX_UNAVAILABLE_RETRY_MS = 16 * 60 * 1000; + + /** + * The number of segments kept fetched ahead of the segment the demuxer is reading. A segment is about six seconds and the + * decoder schedules about five seconds ahead, so one segment of lookahead is enough to keep the link busy and to have the + * next segment ready before it is needed, while keeping the concurrent stream requests and the memory bounded. + * @readonly + * @type {number} + */ + const LOOKAHEAD_SEGMENTS = 1; + + /** + * Converts a time in seconds to whole microseconds, the unit of every packet timestamp of the player. + * @param {number} seconds - The time in seconds. + * @returns {number} The time in microseconds. + */ + function toMicroseconds(seconds) { + const value = Number(seconds); + return Number.isFinite(value) && value > 0 ? Math.round(value * 1000000) : 0; + } + + /** + * Checks whether a Content-Type is one a segment stream may answer with: an audio type, or the generic binary type + * the API falls back to for a container it cannot name. Any other type, in particular the text/html of a sign in page, is not the segment. + * @param {string|null} value - The Content-Type header value. + * @returns {boolean} True when the value is an audio type or application/octet-stream. + */ + function isStreamContentType(value) { + if (!value) + return false; + const type = value.split(';', 1)[0].trim().toLowerCase(); + return type.startsWith('audio/') || type === 'application/octet-stream'; + } + + /** + * Parses the number of segments a normalized audio production declares. + * @param {string|null} value - The header value. + * @returns {number|null} The segment count, or null when the value is absent or malformed. + */ + function parseSegmentCount(value) { + if (typeof value !== 'string' || value.trim() === '') + return null; + const count = Number(value.trim()); + return Number.isInteger(count) && count >= 0 ? count : null; + } + + /** + * Parses the exact start of a segment on the track timeline. + * @param {string|null} value - The header value. + * @returns {number|null} The start in seconds, or null when the value is absent or malformed. + */ + function parseSegmentStartSeconds(value) { + if (typeof value !== 'string' || value.trim() === '') + return null; + const seconds = Number(value.trim()); + return Number.isFinite(seconds) && seconds >= 0 ? seconds : null; + } + + /** + * A random access byte source over the bytes of one segment, so the bundled demuxer of the delivered container reads the segment exactly as it would read a file. + */ + class SegmentByteSource { + /** + * Creates an instance of SegmentByteSource. + * @param {Uint8Array} bytes - The complete bytes of the segment. + */ + constructor(bytes) { + this.bytes = bytes instanceof Uint8Array ? bytes : new Uint8Array(0); + } + + /** + * Gets the length of the segment. + * @returns {number} The length in bytes. + */ + getLength() { + return this.bytes.length; + } + + /** + * Reads a window of the segment at an absolute offset. + * @param {number} offset - The first byte of the window. + * @param {number} length - The number of bytes of the window. + * @returns {Promise} The bytes, possibly shorter at the end of the segment. + */ + async readAsync(offset, length) { + const start = Math.max(0, Math.floor(Number(offset) || 0)); + const size = Math.max(0, Math.floor(Number(length) || 0)); + if (size === 0 || start >= this.bytes.length) + return new Uint8Array(0); + return this.bytes.subarray(start, Math.min(this.bytes.length, start + size)); + } + } + + /** + * Fetches, keeps and reports the fixed duration segments of a normalized track. + */ + class NormalizedSegmentDownloader { + /** + * Creates an instance of NormalizedSegmentDownloader. + * @param {Object} options - The downloader options. + * @param {Function} options.urlBuilder - Builds the URL of a segment from its zero based index. + * @param {number} options.durationInSeconds - The duration of the track, in seconds. + * @param {number} options.segmentDurationSeconds - The duration of one segment, in seconds. + * @param {Function} [options.onProgress] - Called with the downloaded fraction, between 0 and 1. + * @param {Function} [options.onError] - Called with a typed error when a segment cannot be fetched. + * @param {boolean} [options.shouldRetryUnavailable=true] - Whether a request the server reports as temporarily unavailable is retried with backoff. + * @param {boolean} [options.shouldKeepDownloadingWhilePaused=false] - Whether the lookahead keeps fetching while playback is paused. + * @param {Object} [options.events] - The player event bus, used to follow a change of the keep-downloading-while-paused preference. + */ + constructor(options) { + const settings = options || {}; + this.urlBuilder = settings.urlBuilder; + this.durationInSeconds = Math.max(0, Number(settings.durationInSeconds) || 0); + this.segmentDurationSeconds = Math.max(0, Number(settings.segmentDurationSeconds) || 0); + this.onProgress = typeof settings.onProgress === 'function' ? settings.onProgress : null; + this.onError = typeof settings.onError === 'function' ? settings.onError : null; + this.events = settings.events || null; + this.shouldRetryUnavailable = settings.shouldRetryUnavailable !== false; + this.shouldKeepDownloadingWhilePaused = settings.shouldKeepDownloadingWhilePaused === true; + this.isPlaybackPaused = false; + // The last segment the demuxer actually consumed. The lookahead is measured from it, so background fetches can never + // advance it and turn the bounded read ahead into a full download of the track. + this.lookaheadAnchor = -1; + this.unsubscribePreferences = null; + // The production states how many segments it holds, so the end of the audio is known without a request that returns not found. + // Until the first segment response states it, the count is unknown and a missing segment is a failure, never an end of stream. + this.segmentCount = null; + // The server reports the produced duration, which can differ from the probed duration in the manifest. It is kept separately so the + // progress bar and the seek clamp use what was actually produced once the first segment response arrives. + this.producedDurationSeconds = null; + /** @type {Map} */ + this.segmentStartTimes = new Map(); + /** @type {Map} */ + this.segments = new Map(); + /** @type {Map>} */ + this.pending = new Map(); + // Every request has its own controller and all of them are aborted together, because a seek or a teardown must cancel + // requests whose headers have arrived and whose bodies are still being read, not only the newest one. + this.controllers = new Set(); + this.error = null; + this.isAborted = false; + // A set, not one handle, because a required read and a speculative lookahead can be waiting on a retry at the same time and an abort + // must release both immediately. + this.retryWaitCancels = new Set(); + // Incremented by every abort, so a request that was in flight when the downloader stopped can be told apart from a + // request that was started after it, which must be allowed to proceed. + this.abortGeneration = 0; + this.destroyed = false; + this.subscribeToPreferences(); + } + + /** + * Gets the start of a segment on the timeline of the track. The exact start the server indexed is used when it is known, because ffmpeg + * cuts at the first packet at or after a segment boundary, so a segment does not always start at an exact multiple of the duration. + * @param {number} index - The zero based index of the segment. + * @returns {number} The start, in seconds. + */ + getSegmentStartSeconds(index) { + const declaredStart = this.segmentStartTimes.get(index); + if (declaredStart !== undefined) + return declaredStart; + return Math.max(0, index) * this.segmentDurationSeconds; + } + + /** + * Selects the segment that covers a time from the exact starts the server declared, falling back to the nominal grid only for segments whose start is not known yet. + * @param {number} seconds - The time to locate, in seconds. + * @returns {number} The zero based index of the covering segment. + */ + findSegmentIndexForTime(seconds) { + const value = Number(seconds); + const target = Number.isFinite(value) && value > 0 ? value : 0; + if (this.segmentDurationSeconds <= 0) + return 0; + let index = Math.max(0, Math.floor(target / this.segmentDurationSeconds)); + while (index > 0 && this.segmentStartTimes.has(index) && this.segmentStartTimes.get(index) > target) + index--; + while (this.segmentStartTimes.has(index + 1) && this.segmentStartTimes.get(index + 1) <= target) + index++; + return index; + } + + /** + * Gets the duration of a segment on the timeline of the track, from the start of the next segment when it is known, otherwise from the configured segment duration and the end of the track. + * @param {number} index - The zero based index of the segment. + * @returns {number} The duration, in seconds. + */ + getSegmentDurationSeconds(index) { + const start = this.getSegmentStartSeconds(index); + const nextStart = this.segmentStartTimes.get(index + 1); + if (nextStart !== undefined) + return Math.max(0, nextStart - start); + const totalDuration = this.getTotalDurationSeconds(); + if (totalDuration <= 0) + return this.segmentDurationSeconds; + return Math.max(0, Math.min(this.segmentDurationSeconds, totalDuration - start)); + } + + /** + * Gets the duration of the produced normalized audio, which can differ from the probed duration reported by the manifest. + * @returns {number|null} The produced duration in seconds, or null when no segment response has declared it. + */ + getProducedDurationSeconds() { + return this.producedDurationSeconds; + } + + /** + * Gets the duration used for progress, preferring the produced duration over the probed one. + * @returns {number} The duration in seconds, or zero when it is not known. + */ + getTotalDurationSeconds() { + const producedDuration = Number(this.producedDurationSeconds); + if (Number.isFinite(producedDuration) && producedDuration > 0) + return producedDuration; + return this.durationInSeconds; + } + + /** + * Gets one segment, from memory when it was already fetched, otherwise from the segment route. + * @param {number} index - The zero based index of the segment. + * @returns {Promise} The bytes of the segment, or null when the index is past the produced audio. + * @throws {LuminaAudioPlayer.PlayerError} When the segment cannot be fetched, or the download was aborted. + */ + async getSegmentAsync(index) { + if (this.destroyed) + throw this.createAbortError(); + if (!Number.isInteger(index) || index < 0) + throw this.recordError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The segment index is not valid.')); + // The production stated how many segments it holds, so an index at or past that count is the end of the audio and needs no request. + if (this.segmentCount !== null && index >= this.segmentCount) + return null; + let bytes; + if (this.segments.has(index)) + bytes = this.segments.get(index); + else if (this.pending.has(index)) // The segment may already be in flight as lookahead, so the read waits for that request instead of starting a second one. + bytes = await this.pending.get(index); + else + bytes = await this.createSegmentRequest(index, false); + if (bytes) // Only a segment the demuxer actually consumed moves the anchor, so the read ahead stays bounded to the lookahead window. + this.advanceLookaheadAnchor(index); + return bytes; + } + + /** + * Starts a segment request and records it as pending, so a concurrent read or a lookahead never asks for the same segment twice. + * @param {number} index - The zero based index of the segment. + * @param {boolean} isSpeculative - True for a background lookahead, whose failure must not become the failure of the track. + * @returns {Promise} The bytes of the segment, or null when it does not exist. + */ + createSegmentRequest(index, isSpeculative) { + const request = this.fetchSegmentAsync(index, isSpeculative); + this.pending.set(index, request); + request.then( + () => { + if (this.pending.get(index) === request) + this.pending.delete(index); + }, + () => { + // A failed request is forgotten, so a later read of the same segment can try again. The failure itself reaches the + // caller that awaited it, and is only reported through onError when it belongs to the track that is playing. + if (this.pending.get(index) === request) + this.pending.delete(index); + } + ); + return request; + } + + /** + * Moves the read ahead anchor to a consumed segment and starts the lookahead that follows it. + * @param {number} index - The zero based index of the segment the demuxer consumed. + */ + advanceLookaheadAnchor(index) { + if (index <= this.lookaheadAnchor) + return; + this.lookaheadAnchor = index; + this.scheduleLookahead(); + } + + /** + * Fetches up to the configured number of segments after the consumed one, so the next segment is already in memory when the + * decoder needs it. The lookahead is bounded, and it stops while playback is paused unless the user kept downloading enabled. + */ + scheduleLookahead() { + if (this.destroyed || this.isAborted || this.segmentCount === null || this.lookaheadAnchor < 0) + return; + if (this.isPlaybackPaused && !this.shouldKeepDownloadingWhilePaused) + return; + for (let offset = 1; offset <= LOOKAHEAD_SEGMENTS; offset++) { + const index = this.lookaheadAnchor + offset; + if (index >= this.segmentCount) + return; + if (this.segments.has(index) || this.pending.has(index)) + continue; + this.createSegmentRequest(index, true); + } + } + + /** + * Subscribes to the preference changes of the player, so a change of the keep-downloading-while-paused setting is applied to + * the lookahead of a track that is already loaded. + */ + subscribeToPreferences() { + if (!this.events || !LuminaAudioPlayer.PlayerEvent || typeof this.events.on !== 'function') + return; + this.unsubscribePreferences = this.events.on(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, (preferences) => { + if (preferences && typeof preferences.shouldKeepDownloadingWhilePaused === 'boolean') + this.setKeepDownloadingWhilePaused(preferences.shouldKeepDownloadingWhilePaused); + }); + } + + /** + * Fetches one complete segment and stores it, so it is never fetched again for this track. + * @param {number} index - The zero based index of the segment. + * @param {boolean} [isSpeculative=false] - True for a background lookahead, whose failure must not be recorded as the failure of the track. + * @returns {Promise} The bytes of the segment, or null when the server reports no such segment. + * @throws {LuminaAudioPlayer.PlayerError} When the request fails or is aborted. + */ + async fetchSegmentAsync(index, isSpeculative = false) { + if (this.destroyed) + throw this.createAbortError(); + // The generation is captured for the whole call, so an abort or restart invalidates every retry and the body read, even when a later attempt uses a new controller. + const abortGeneration = this.abortGeneration; + // The retry window starts at the first attempt, not at each retry, so a production that stays unavailable cannot keep this request alive indefinitely. + const retryStartedAt = Date.now(); + let attempt = 0; + // Only a transient unavailable status loops back here; every other result leaves through a return or a throw below. + while (true) { + if (this.destroyed || this.abortGeneration !== abortGeneration) + throw this.createAbortError(); + const controller = typeof AbortController === 'function' ? new AbortController() : null; + // The controller stays registered until the body has been read, so an abort during arrayBuffer cancels the transfer instead + // of leaving it to download the discarded segment in full while holding a stream slot on both hops. + if (controller) + this.controllers.add(controller); + try { + let response; + try { + const url = typeof this.urlBuilder === 'function' ? this.urlBuilder(index) : null; + if (typeof url !== 'string' || url.length === 0) + throw this.createRequestFailure('The segment URL is not configured.', null, isSpeculative, LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED); + response = await fetch(url, { + method: 'GET', + credentials: 'same-origin', + redirect: 'manual', + headers: { 'Accept': 'audio/*, application/octet-stream' }, + signal: controller ? controller.signal : undefined + }); + } catch (error) { + if (LuminaAudioPlayer.isAbortError(error) || this.destroyed || this.abortGeneration !== abortGeneration) + throw this.createAbortError(); + // A speculative read must not record the first failure, because the required read that follows owns the + // track's error state; the recorded failure is the one the user should see. + if (error instanceof LuminaAudioPlayer.PlayerError) + throw isSpeculative ? error : this.recordError(error); + throw this.createRequestFailure('The segment could not be requested.', { cause: error }, isSpeculative); + } + if (!response) + throw this.createRequestFailure('The segment request returned no response.', null, isSpeculative); + // Redirects are not followed: an expired session answers with a redirect to the login page, whose HTML must never be parsed as audio. + if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) + throw this.createRequestFailure('The session expired while a segment was requested.', { reason: LuminaAudioPlayer.PlayerErrorReason.SESSION_EXPIRED }, isSpeculative); + if (!response.ok) { + const status = response.status; + // Every non-success path discards the body first, so the connection is released instead of being held by a response nobody reads. + await this.discardResponseAsync(response); + // Every job slot can be in use because productions are shared and bounded, so a temporarily unavailable segment is + // retried for the track that is playing. A prefetch does not retry: it is abandoned and the track starts normally. + if (this.shouldRetryUnavailable && (status === 503 || status === 429) + && Date.now() - retryStartedAt < MAX_UNAVAILABLE_RETRY_MS) { + // The last delay is reused after the array ends, so the backoff stays bounded while the retry window runs. + const delay = UNAVAILABLE_RETRY_DELAYS_MS[Math.min(attempt, UNAVAILABLE_RETRY_DELAYS_MS.length - 1)]; + attempt++; + await this.waitBeforeRetryAsync(delay, abortGeneration); + continue; + } + // The reason is part of the error contract: the engine uses SEGMENT_NOT_FOUND and PLAYBACK_DELIVERY_CHANGED + // to refresh the manifest, and reports the other reasons as ordinary playback failures. + const reason = status === 503 + ? LuminaAudioPlayer.PlayerErrorReason.NORMALIZATION_UNAVAILABLE + : (status === 409 + ? LuminaAudioPlayer.PlayerErrorReason.PLAYBACK_DELIVERY_CHANGED + : (status === 404 ? LuminaAudioPlayer.PlayerErrorReason.SEGMENT_NOT_FOUND : LuminaAudioPlayer.PlayerErrorReason.HTTP_REQUEST_FAILED)); + throw this.createRequestFailure('The segment request failed.', { reason, status }, isSpeculative); + } + // A proxy or an error page can answer 200 with a non-audio body, so the media type is checked before the bytes ever reach a demuxer. + if (!isStreamContentType(response.headers.get('Content-Type'))) { + await this.discardResponseAsync(response); + throw this.createRequestFailure('The segment response is not audio.', null, isSpeculative); + } + // The production declares how many segments exist. It is required, because a player cannot tell a missing + // final segment from the end of the track without it. + const declaredSegmentCount = parseSegmentCount(response.headers.get(SEGMENT_COUNT_HEADER)); + if (declaredSegmentCount === null) { + await this.discardResponseAsync(response); + throw this.createRequestFailure('The segment response carried no segment count.', null, isSpeculative); + } + // A response beyond the declared count means the handle and the production disagree, not that the track ended. + if (index >= declaredSegmentCount) { + await this.discardResponseAsync(response); + throw this.createRequestFailure('The segment response is outside the declared production.', null, isSpeculative); + } + if (this.segmentCount !== null && this.segmentCount !== declaredSegmentCount) { + // A production is immutable, so a different count means the audio was replaced under the track. Mixing the two + // productions would corrupt the timeline, so the track fails instead of playing a splice of both. + await this.discardResponseAsync(response); + throw this.createRequestFailure('The normalized production changed during playback.', null, isSpeculative); + } + this.segmentCount = declaredSegmentCount; + // The produced duration and the exact start of this segment come from the server, because the probe duration and + // the nominal index times can differ slightly after transcoding. + const declaredDuration = parseSegmentStartSeconds(response.headers.get(TRACK_DURATION_SECONDS_HEADER)); + if (declaredDuration !== null) + this.producedDurationSeconds = declaredDuration; + const declaredStart = parseSegmentStartSeconds(response.headers.get(SEGMENT_START_SECONDS_HEADER)); + if (declaredStart !== null) + this.segmentStartTimes.set(index, declaredStart); + let bytes; + try { + // The controller is still registered here, so an abort now cancels this body read instead of after it completed. + bytes = new Uint8Array(await response.arrayBuffer()); + } catch (error) { + if (LuminaAudioPlayer.isAbortError(error) || this.destroyed || this.abortGeneration !== abortGeneration) + throw this.createAbortError(); + throw this.createRequestFailure('The segment body could not be read.', { cause: error }, isSpeculative); + } + if (this.destroyed || this.abortGeneration !== abortGeneration) + throw this.createAbortError(); + // The bytes are cached only after the whole body was read, so a transfer that failed halfway can never be mistaken for a complete segment. + this.segments.set(index, bytes); + this.reportProgress(); + return bytes; + } finally { + if (controller) + this.controllers.delete(controller); + } + } + } + + /** + * Discards the body of a response that is not used, so a connection that will not be read is released. + * @param {Response} response - The response whose body is discarded. + * @returns {Promise} A promise that completes when the body was discarded. + */ + async discardResponseAsync(response) { + try { + if (response && response.body && typeof response.body.cancel === 'function') + await response.body.cancel(); + } catch (error) { + console.debug('Audio player: the unused segment response could not be discarded.', error); + } + } + + /** + * Waits before the next attempt of a temporarily unavailable segment request, unless the downloader is aborted first. + * @param {number} delay - The delay, in milliseconds. + * @param {number} abortGeneration - The abort generation the attempt belongs to. + * @returns {Promise} A promise that completes when the delay elapsed. + * @throws {LuminaAudioPlayer.PlayerError} When the downloader was aborted or released during the delay. + */ + waitBeforeRetryAsync(delay, abortGeneration) { + return new Promise((resolve, reject) => { + let isSettled = false; + let timer = null; + const finish = (isAborted) => { + if (isSettled) + return; + isSettled = true; + if (timer !== null) + clearTimeout(timer); + this.retryWaitCancels.delete(cancel); + if (isAborted) + reject(this.createAbortError()); + else + resolve(); + }; + const cancel = () => finish(true); + timer = setTimeout(() => finish(false), delay); + this.retryWaitCancels.add(cancel); + if (this.destroyed || this.abortGeneration !== abortGeneration) + cancel(); + }); + } + + /** + * Reports the downloaded fraction of the track, mapped through the manifest duration so the streamed indicator is + * time accurate. + */ + reportProgress() { + if (!this.onProgress) + return; + try { + this.onProgress(this.getDownloadedFraction()); + } catch (error) { + console.debug('Audio player: the downloaded fraction of a normalized track could not be reported.', error); + } + } + + /** + * Gets the fraction of the track that was fetched, by the duration of the fetched segments. + * @returns {number} The fraction, between 0 and 1. + */ + getDownloadedFraction() { + const totalDuration = this.getTotalDurationSeconds(); + if (totalDuration <= 0 || this.segmentDurationSeconds <= 0) + return 0; + let downloadedSeconds = 0; + for (const index of this.segments.keys()) + downloadedSeconds += this.getSegmentDurationSeconds(index); + return Math.min(1, Math.max(0, downloadedSeconds / totalDuration)); + } + + /** + * Gets the time ranges of the track that were already fetched, so the three state progress bar can show the + * streamed part and a seek into it needs no loading state. + * @returns {Array<{ start: number, end: number }>} The downloaded time ranges, in seconds. + */ + getTimeRanges() { + const indexes = Array.from(this.segments.keys()).sort((first, second) => first - second); + const ranges = []; + for (const index of indexes) { + const start = this.getSegmentStartSeconds(index); + const end = start + this.getSegmentDurationSeconds(index); + const last = ranges[ranges.length - 1]; + if (last && Math.abs(last.end - start) < 0.000001) + last.end = end; + else + ranges.push({ start, end }); + } + return ranges; + } + + /** + * Checks whether a time is covered by a fetched segment, so the player knows a seek into it needs no loading state. + * @param {number} seconds - The time to check, in seconds. + * @returns {boolean} True when the segment that covers the time was fetched. + */ + coversTime(seconds) { + if (this.segmentDurationSeconds <= 0) + return false; + const value = Number(seconds); + if (!Number.isFinite(value) || value < 0) + return false; + // When the exact starts are known, the segment that covers the time is the one with the greatest declared start at or before it, + // not necessarily the one the assumed grid would pick. + let candidateIndex = null; + let candidateStart = -1; + for (const [index, start] of this.segmentStartTimes) { + if (start <= value && start > candidateStart) { + candidateIndex = index; + candidateStart = start; + } + } + if (candidateIndex !== null && value <= candidateStart + this.getSegmentDurationSeconds(candidateIndex)) + return this.segments.has(candidateIndex); + return this.segments.has(Math.floor(value / this.segmentDurationSeconds)); + } + + /** + * Sets whether playback is paused. The lookahead keeps fetching while paused only when the user enabled the + * keep-downloading-while-paused preference; a request that is already in flight is left to finish, so pausing never + * turns a segment the decoder is waiting for into a failure. + * @param {boolean} isPaused - Whether playback is paused. + */ + setPlaybackPaused(isPaused) { + const next = isPaused === true; + if (next === this.isPlaybackPaused) + return; + this.isPlaybackPaused = next; + if (!next || this.shouldKeepDownloadingWhilePaused) + this.scheduleLookahead(); + } + + /** + * Sets the keep-downloading-while-paused preference. When it is enabled while playback is paused, the lookahead resumes; + * when it is disabled, no new lookahead is started, while a request that is already in flight is left to finish. + * @param {boolean} shouldKeepDownloading - Whether downloading should continue while paused. + */ + setKeepDownloadingWhilePaused(shouldKeepDownloading) { + const next = shouldKeepDownloading === true; + if (next === this.shouldKeepDownloadingWhilePaused) + return; + this.shouldKeepDownloadingWhilePaused = next; + if (next) + this.scheduleLookahead(); + } + + /** + * Enables or disables the retry of a temporarily unavailable segment request. A prefetch starts with it disabled, so an + * unavailable production is abandoned instead of held; the item enables it when it becomes the track that is playing. + * @param {boolean} shouldRetry - Whether a temporarily unavailable request is retried with backoff. + */ + setShouldRetryUnavailable(shouldRetry) { + this.shouldRetryUnavailable = shouldRetry === true; + } + + /** + * Starts, or resumes, the downloader after an abort. It clears the abort flag and resumes the lookahead, because a seek and a resume both call it. + * @returns {Promise} A promise that completes when the downloader is usable again. + */ + async startAsync() { + this.isAborted = false; + this.scheduleLookahead(); + } + + /** + * Moves the read ahead anchor to the segment that covers a seek target, so the lookahead around the new position is fetched + * before the decoder reaches it. The segment of the target itself is fetched by the demuxer. + * @param {number} seconds - The target position, in seconds. + */ + seek(seconds) { + if (this.segmentDurationSeconds <= 0) + return; + const value = Number(seconds); + const target = Number.isFinite(value) && value > 0 ? value : 0; + this.lookaheadAnchor = this.findSegmentIndexForTime(target); + this.scheduleLookahead(); + } + + /** + * Aborts the segment request that is in flight, if any, and rejects the reads that are waiting for it. + */ + abort() { + this.isAborted = true; + // Every pending read belongs to the request that is being stopped, so the entries are dropped here; a read that starts after + // this abort is a new request and is not rejected by the abort that precedes it. + this.abortGeneration += 1; + this.pending.clear(); + for (const cancelRetryWait of this.retryWaitCancels) { + try { + cancelRetryWait(); + } catch (error) { + console.debug('Audio player: a segment retry wait could not be cancelled.', error); + } + } + this.retryWaitCancels.clear(); + // Every request is aborted, including one whose headers arrived and whose body is still being read. The controllers stay + // registered until each body read finishes, which is what makes this cancellation effective on a slow link. + for (const controller of this.controllers) { + try { + controller.abort(); + } catch (error) { + console.debug('Audio player: a segment request could not be aborted.', error); + } + } + this.controllers.clear(); + } + + /** + * Gets the last failure the downloader recorded, or null. + * @returns {LuminaAudioPlayer.PlayerError|null} The recorded failure. + */ + getError() { + return this.error; + } + + /** + * Gets the total size of the track in bytes, which the segment delivery does not expose as a stream length. + * @returns {null} Always null. + */ + getTotalBytes() { + return null; + } + + /** + * Builds the typed failure of a segment request. A failure of a background lookahead is returned without being recorded, so a + * speculative request that is not needed yet can never make the track that is playing fail. + * @param {string} message - The developer facing description of the failure. + * @param {Object|null} details - Optional structured details. + * @param {boolean} isSpeculative - True when the failure belongs to a background lookahead. + * @param {string} [code] - The player error code. Defaults to DOWNLOAD_FAILED. + * @returns {LuminaAudioPlayer.PlayerError} The typed failure, recorded when it is not speculative. + */ + createRequestFailure(message, details, isSpeculative, code = LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED) { + const error = new LuminaAudioPlayer.PlayerError(code, message, details); + return isSpeculative ? error : this.recordError(error); + } + + /** + * Records a failure once and reports it to the caller, so a failed segment is never retried silently and never overwrites the cause of the first failure. + * @param {LuminaAudioPlayer.PlayerError} error - The failure to record. + * @returns {LuminaAudioPlayer.PlayerError} The recorded failure. + */ + recordError(error) { + if (this.error) + return this.error; + this.error = error; + if (this.onError) { + try { + this.onError(error); + } catch (callbackError) { + console.error('Audio player: the normalized download error callback threw.', callbackError); + } + } + return error; + } + + /** + * Creates the typed abort of an intentionally stopped segment request. + * @returns {LuminaAudioPlayer.PlayerError} The abort. + */ + createAbortError() { + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The segment request was aborted.'); + } + + /** + * Releases every fetched segment and aborts the request that is in flight. + * @returns {Promise} A promise that completes when the downloader was released. + */ + async destroyAsync() { + if (this.destroyed) + return; + this.destroyed = true; + if (this.unsubscribePreferences) { + try { + this.unsubscribePreferences(); + } catch (error) { + console.debug('Audio player: the normalized download preference subscription could not be removed.', error); + } + this.unsubscribePreferences = null; + } + this.abort(); + this.segments.clear(); + this.pending.clear(); + } + } + + /** + * Presents the segments of a normalized track to the decode pipeline as one continuous stream. + */ + class NormalizedSegmentDemuxer { + /** + * Creates an instance of NormalizedSegmentDemuxer. + * @param {Object} options - The demuxer options. + * @param {Object} options.manifest - The playback manifest of the normalized track. + * @param {LuminaAudioPlayer.NormalizedSegmentDownloader} options.downloader - The downloader of the segments. + * @param {Object} [options.registry] - The demuxer registry. Defaults to the process wide registry. + * @param {Object} [options.capabilities] - The browser capability detector. + * @param {Object} [options.events] - The player event bus. + * @param {Function} [options.onError] - Called with a typed error when the normalized stream cannot be read. + */ + constructor(options) { + const settings = options || {}; + const manifest = settings.manifest || {}; + this.manifest = manifest; + this.downloader = settings.downloader; + this.registry = settings.registry || LuminaAudioPlayer.demuxerRegistry; + this.capabilities = settings.capabilities || null; + this.events = settings.events || null; + this.onError = typeof settings.onError === 'function' ? settings.onError : null; + this.container = LuminaAudioPlayer.canonicalizeDemuxerContainer(manifest.deliveryContainer); + this.codec = LuminaAudioPlayer.canonicalizeDemuxerCodec(manifest.deliveryCodec); + this.segmentDurationSeconds = Math.max(0, Number(manifest.segmentDurationSeconds) || 0); + this.durationInSeconds = Math.max(0, Number(manifest.durationInSeconds) || 0); + this.inner = null; + this.innerIndex = -1; + this.initialized = false; + this.destroyed = false; + this.error = null; + // Set only when the produced segment count is exhausted, so an ordinary read failure is never treated as the end of the track. + this.hasReachedEnd = false; + this.seekTargetMicros = null; + } + + /** + * Gets the start of a segment on the timeline of the track, from the exact value the server indexed when it is known. + * @param {number} index - The zero based index of the segment. + * @returns {number} The start, in seconds. + */ + getSegmentStartSeconds(index) { + if (this.downloader && typeof this.downloader.getSegmentStartSeconds === 'function') + return this.downloader.getSegmentStartSeconds(index); + return Math.max(0, index) * this.segmentDurationSeconds; + } + + /** + * Loads the demuxer of one segment, replacing the previous one. + * @param {number} index - The zero based index of the segment. + * @param {boolean} [forceReload=false] - True to reload a segment that is already open, used by a seek. + * @returns {Promise} True when the segment was loaded, false when it does not exist. + * @throws {LuminaAudioPlayer.PlayerError} When the segment or its format cannot be read. + */ + async loadSegmentAsync(index, forceReload = false) { + if (this.destroyed) + throw this.createAbortError(); + // A normal sequential read reuses the open segment. A seek forces a reload even for the same index, because its demuxer must + // restart at the first packet so readPacketAsync can drop the frames before the new target. + if (!forceReload && this.inner && this.innerIndex === index) + return true; + // The old segment is detached before it is awaited, so a failure while releasing it can never leave the wrapper pointing at a demuxer that is being destroyed. + const previous = this.inner; + this.inner = null; + this.innerIndex = -1; + if (previous) { + try { + await previous.destroyAsync(); + } catch (error) { + console.debug('Audio player: the previous normalized segment could not be released.', error); + } + } + // A seek can move back before the produced end, so the end marker is only valid until the next forced load. + if (forceReload) + this.hasReachedEnd = false; + if (this.hasReachedEnd) + return false; + let bytes; + try { + bytes = await this.downloader.getSegmentAsync(index); + } catch (error) { + if (LuminaAudioPlayer.isDownloadAbort(error)) + throw this.createAbortError(); + // The downloader has already classified the failure, but this wrapper owns the stream error that the decode pipeline + // reads, so the failure is recorded with the download code before it is thrown. + this.recordFailure(LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED)); + throw this.error; + } + if (bytes === null) { + // No bytes for this index is the declared end of the production, not a corrupt segment. + this.hasReachedEnd = true; + return false; + } + const descriptor = this.registry ? this.registry.find(this.container, this.codec) : null; + if (!descriptor) { + this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The bundled player has no demuxer for the normalized delivery.', { reason: LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER })); + throw this.error; + } + // The inner demuxer reads only from this segment's bytes. Its error callback is left null because this wrapper records and classifies every failure itself. + const inner = descriptor.create({ + source: new SegmentByteSource(bytes), + capabilities: this.capabilities, + events: this.events, + onError: null + }); + try { + await inner.initializeAsync(); + } catch (error) { + // A demuxer that failed to initialize may still hold its byte source or parser state, so it is released before the wrapper records the failure. + try { + await inner.destroyAsync(); + } catch (destroyError) { + console.debug('Audio player: the failed normalized segment could not be released.', destroyError); + } + if (LuminaAudioPlayer.isDownloadAbort(error)) + throw this.createAbortError(); + this.recordFailure(LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED)); + throw this.error; + } + // Initialization is asynchronous, so the stream may have been released while it ran. The new demuxer must be released too, + // and the caller must see an abort rather than a segment that belongs to a track nobody is playing anymore. + if (this.destroyed) { + try { + await inner.destroyAsync(); + } catch (destroyError) { + console.debug('Audio player: the normalized segment of a released stream could not be released.', destroyError); + } + throw this.createAbortError(); + } + // The segment becomes current only after every check and await succeeded, so a failed load never leaves a half usable inner demuxer in place. + this.inner = inner; + this.innerIndex = index; + return true; + } + + /** + * Loads the first segment and prepares the decoder configuration of the normalized stream. + * @returns {Promise} A promise that completes when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the first segment does not exist or is not in the delivered format. + */ + async initializeAsync() { + if (this.destroyed) + throw this.createAbortError(); + if (this.segmentDurationSeconds <= 0) + throw this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The normalized delivery has no segment duration.')); + const loaded = await this.loadSegmentAsync(0); + if (!loaded || !this.inner) + throw this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The normalized delivery has no segments.')); + const configuration = this.inner.getConfiguration(); + if (!configuration) { + const failure = this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The normalized delivery reported no decoder configuration.')); + // The wrapper is not returned to the engine after a failed initialization, so the already opened segment and its demuxer are + // released here instead of waiting for garbage collection. + await this.destroyAsync(); + throw failure; + } + if (this.capabilities && typeof this.capabilities.supportsAudioConfigAsync === 'function') { + const isSupported = await this.capabilities.supportsAudioConfigAsync(configuration); + if (!isSupported) { + const failure = this.recordFailure(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The browser cannot decode the normalized delivery.', { reason: LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED })); + await this.destroyAsync(); + throw failure; + } + } + this.initialized = true; + } + + /** + * Gets the decoder configuration of the normalized stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + return this.inner ? this.inner.getConfiguration() : null; + } + + /** + * Gets the duration of the whole normalized stream. The produced duration reported by the server takes precedence over the probed duration + * of the manifest, because a production can run past the probe. + * @returns {number|null} The duration in seconds, or null when it is not known. + */ + getDuration() { + if (this.downloader && typeof this.downloader.getProducedDurationSeconds === 'function') { + const producedDuration = Number(this.downloader.getProducedDurationSeconds()); + if (Number.isFinite(producedDuration) && producedDuration > 0) + return producedDuration; + } + return this.durationInSeconds > 0 ? this.durationInSeconds : null; + } + + /** + * Reads the next encoded packet of the normalized stream, moving to the next segment when the current one ends. + * @returns {Promise} The packet with an absolute timestamp, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When a segment cannot be read. + */ + async readPacketAsync() { + this.ensureInitialized(); + // The loop only continues when a segment boundary is crossed; every packet returned to the decoder leaves through the return at the bottom. + while (!this.destroyed) { + if (!this.inner) { + // This happens after a forced seek load failed or before the first packet. A missing next segment is the end of the production, not an error. + const loaded = await this.loadSegmentAsync(this.innerIndex + 1); + if (!loaded) + return null; + } + const packet = await this.inner.readPacketAsync(); + // The index is captured before moving on, because the packet timestamp is relative to the segment that produced it, even after the next segment was loaded. + const currentIndex = this.innerIndex; + if (packet === null) { + // The current segment is fully drained. Load the following one and continue reading without exposing a null packet + // to the decoder, because null means the whole track ended. + const loaded = await this.loadSegmentAsync(currentIndex + 1); + if (!loaded) + return null; + continue; + } + // Demuxers report timestamps relative to their own segment. Adding the exact start the server indexed places the packet + // on the shared track timeline, so a boundary does not jump or overlap after transcoding. + const startMicros = toMicroseconds(this.getSegmentStartSeconds(currentIndex)); + const timestamp = packet.timestamp + startMicros; + if (this.seekTargetMicros !== null) { + // A demuxer that could not reposition by time starts the segment at its first frame. The frames that end + // before the target belong to audio the user already skipped, so they are dropped before the decoder sees them. + if (timestamp + packet.duration <= this.seekTargetMicros) + continue; + this.seekTargetMicros = null; + } + return { + data: packet.data, + timestamp: timestamp, + duration: packet.duration, + type: packet.type + }; + } + return null; + } + + /** + * Repositions the normalized stream to the segment that covers a time, from the start of that segment. + * @param {number} seconds - The target position, in seconds. + * @returns {Promise} Zero, which is not a byte offset: the normalized stream is always repositioned by loading a new segment + * and dropping the packets before the target, so no container level byte seek is left for the engine to perform. + * @throws {LuminaAudioPlayer.PlayerError} When the target segment cannot be read. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const value = Number(seconds); + const requested = Number.isFinite(value) && value > 0 ? value : 0; + const knownDuration = Number(this.getDuration()); + const target = Number.isFinite(knownDuration) && knownDuration > 0 ? Math.min(requested, knownDuration) : requested; + const index = this.downloader && typeof this.downloader.findSegmentIndexForTime === 'function' + ? this.downloader.findSegmentIndexForTime(target) + : Math.max(0, Math.floor(target / this.segmentDurationSeconds)); + this.seekTargetMicros = toMicroseconds(target); + let loaded = await this.loadSegmentAsync(index, true); + if (!loaded && index > 0) { + // The produced end of the normalized audio can be shorter than the probed duration, so a seek at the very end + // falls back to the last segment that was actually produced instead of ending the track silently. + loaded = await this.loadSegmentAsync(index - 1, true); + } + if (!loaded || !this.inner) + return 0; + // A segment starts at the first packet at or after its boundary, so a target in the gap just before that packet belongs to the + // previous segment. The exact start the server indexed is known now, so the seek does not lose the frame at the boundary. + const loadedIndex = this.innerIndex; + if (this.getSegmentStartSeconds(loadedIndex) > target && loadedIndex > 0) { + const previousLoaded = await this.loadSegmentAsync(loadedIndex - 1, true); + if (!previousLoaded) + await this.loadSegmentAsync(loadedIndex, true); + } + // A segment is at most a few seconds long and is already in memory, so it is always read from its first packet. A segment + // is an independent container file, and a demuxer that seeds its timeline from a frame number counts that number across + // the whole track, so an inner seek would double the offset the segment already carries. Reading from the start and + // dropping the packets that end before the target in readPacketAsync is exact for every container. + return 0; + } + + /** + * Checks whether the stream was initialized and can be read. + * @returns {boolean} True when the stream is initialized. + */ + isInitialized() { + return this.initialized && !this.destroyed && this.error === null; + } + + /** + * Checks whether the stream can no longer be read, because it was destroyed or failed. + * @returns {boolean} True when the stream stopped. + */ + isStopped() { + return this.destroyed || this.error !== null; + } + + /** + * Checks whether the stream was destroyed. + * @returns {boolean} True when the stream was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Gets the last failure the stream recorded, or null. + * @returns {LuminaAudioPlayer.PlayerError|null} The recorded failure. + */ + getError() { + return this.error; + } + + /** + * Records a failure once and reports it to the caller, so the decode pipeline stops with a typed error. + * @param {LuminaAudioPlayer.PlayerError} error - The failure to record. + * @returns {LuminaAudioPlayer.PlayerError} The recorded failure. + */ + recordFailure(error) { + if (this.error) + return this.error; + const typed = LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED); + this.error = typed; + this.initialized = false; + if (this.onError) { + try { + this.onError(typed); + } catch (callbackError) { + console.error('Audio player: the normalized demux error callback threw.', callbackError); + } + } + return typed; + } + + /** + * Creates the typed abort of an intentionally stopped normalized stream. + * @returns {LuminaAudioPlayer.PlayerError} The abort. + */ + createAbortError() { + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The normalized segment stream was aborted.'); + } + + /** + * Ensures the stream was initialized before it is read. + * @returns {void} + * @throws {LuminaAudioPlayer.PlayerError} When the stream was destroyed, failed, or was not initialized. + */ + ensureInitialized() { + if (this.destroyed) + throw this.createAbortError(); + if (this.error) + throw this.error; + if (!this.initialized) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The normalized segment stream is not initialized.'); + } + + /** + * Releases the segment demuxer that is open. + * @returns {Promise} A promise that completes when the stream was released. + */ + async destroyAsync() { + if (this.destroyed) + return; + this.destroyed = true; + this.initialized = false; + if (this.inner) { + const inner = this.inner; + this.inner = null; + try { + await inner.destroyAsync(); + } catch (error) { + console.debug('Audio player: the normalized segment demuxer could not be released.', error); + } + } + } + } + + LuminaAudioPlayer.NormalizedSegmentDownloader = NormalizedSegmentDownloader; + LuminaAudioPlayer.NormalizedSegmentDemuxer = NormalizedSegmentDemuxer; + + /** + * Creates the downloader of the segments of a normalized track. + * @param {Object} options - The downloader options, per {@link LuminaAudioPlayer.NormalizedSegmentDownloader}. + * @returns {LuminaAudioPlayer.NormalizedSegmentDownloader} The downloader. + */ + LuminaAudioPlayer.createNormalizedSegmentDownloader = function (options) { + return new NormalizedSegmentDownloader(options); + }; + + /** + * Creates and initializes the demuxer of a normalized playback manifest. + * @param {Object} manifest - The playback manifest of the normalized track. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.NormalizedSegmentDemuxer}. + * @returns {Promise} The ready demuxer. + * @throws {LuminaAudioPlayer.PlayerError} When the normalized delivery cannot be read. + */ + LuminaAudioPlayer.createNormalizedSegmentDemuxer = async function (manifest, options) { + const demuxer = new NormalizedSegmentDemuxer(Object.assign({}, options, { manifest: manifest })); + try { + await demuxer.initializeAsync(); + return demuxer; + } catch (error) { + // A partially initialized wrapper still holds segment 0 and its demuxer, so it is released before the failure is reported. + try { + await demuxer.destroyAsync(); + } catch (cleanupError) { + console.debug('Audio player: the partially initialized normalized demuxer could not be released.', cleanupError); + } + throw error; + } + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.sln b/src/Lumina.sln index f9cafda0..590b0893 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -288,6 +288,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657 ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\DeleteTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\GetPlaybackManifest.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetPlaybackManifest.http ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\GetTrack.http + ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrackSegment.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrackSegment.http ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\StreamTrack.http ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http EndProjectSection diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs index 04d2d75a..6db9f0b4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetPlaybackManifest/GetPlaybackManifestEndpointTests.cs @@ -82,7 +82,7 @@ public class GetPlaybackManifestEndpointTests : IClassFixture