mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds seekable normalized audio track delivery
This commit is contained in:
1 parent
4e13b23f16
commit
45f9aa3bd5
57 files changed
+3452
-344
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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 <token>
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
+15
-2
@@ -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
|
||||
|
||||
|
||||
+2
@@ -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}}
|
||||
+9
-3
@@ -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.
|
||||
/// </summary>
|
||||
/// <param name="TrackId">The Id of the track whose audio is normalized. It binds the produced cache entry to the track the caller authorized.</param>
|
||||
/// <param name="UserId">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.</param>
|
||||
/// <param name="SourcePath">The file system path of the stored audio file of the track.</param>
|
||||
/// <param name="AllowedRoots">
|
||||
/// The content locations the source path is allowed to be inside. The service validates the path against them and re-checks it after opening, so a
|
||||
/// caller that forgets to enforce containment cannot hand an arbitrary path to the transcoder.
|
||||
/// </param>
|
||||
/// <param name="SourceContainer">The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer. Optional.</param>
|
||||
/// <param name="SourceContainer">The container of the stored audio file, as captured by the probe, used to pin the ffmpeg demuxer.</param>
|
||||
/// <param name="Mode">The way the audio is delivered, which is a remux or a transcode.</param>
|
||||
/// <param name="Container">The container of the delivered audio, as chosen by the delivery decision.</param>
|
||||
/// <param name="Codec">The codec of the delivered audio, as chosen by the delivery decision.</param>
|
||||
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the audio of the track, in seconds.</param>
|
||||
/// <param name="Bitrate">The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec. Optional.</param>
|
||||
/// <param name="Bitrate">The stored audio bitrate of the track, in kbps, used to estimate a remux of a lossy codec.</param>
|
||||
/// <param name="SampleRate">The sample rate of the stored audio of the track, in Hz, used to estimate the size of a lossless delivery.</param>
|
||||
/// <param name="Channels">The number of audio channels of the track, used to estimate the size of a lossless delivery.</param>
|
||||
/// <param name="BitDepth">The bit depth of the stored audio of the track, if applicable, used to estimate the size of a lossless delivery.</param>
|
||||
/// <param name="Quality">The quality cap applied to the delivered audio when it has to be re-encoded.</param>
|
||||
/// <param name="SourceLength">The length the source file had when the delivery was declared, in bytes. The production is rejected when the file no longer matches.</param>
|
||||
/// <param name="SourceLastModifiedUtc">The last modification time the source file had when the delivery was declared. The production is rejected when the file no longer matches.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId} Mode: {Mode} Container: {Container} Codec: {Codec}")]
|
||||
public sealed record NormalizedTrackRequestDto(
|
||||
Guid TrackId,
|
||||
Guid UserId,
|
||||
string SourcePath,
|
||||
IReadOnlyList<string> 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
|
||||
);
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a single produced segment of the normalized audio of a track, ready to be written to the response.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="Content">The read stream over the segment, which the caller owns and must release once the response is written.</param>
|
||||
/// <param name="Length">The length of the segment, in bytes, taken from the index of the normalized audio.</param>
|
||||
/// <param name="StartSeconds">The exact start of the segment on the track timeline, in seconds, taken from the index of the normalized audio.</param>
|
||||
/// <param name="Container">The container of the delivered audio, used to resolve the media type of the segment.</param>
|
||||
/// <param name="SegmentCount">The number of segments the production holds, so the caller can tell the end of the audio from a missing segment.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the produced normalized audio, in seconds, which can differ from the probed duration.</param>
|
||||
[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
|
||||
);
|
||||
+25
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="Request">The complete normalization request the delivery declares, including its user, track, decision, quality and source identity.</param>
|
||||
/// <param name="Shape">The shape the delivered audio is addressed by, which must be time addressed segments for a segment route.</param>
|
||||
/// <param name="LibraryId">The Id of the library the track belongs to, so the segment route can scope the delivery without querying it again.</param>
|
||||
/// <param name="AlbumId">The Id of the album the track belongs to, so the segment route can scope the delivery without querying it again.</param>
|
||||
/// <param name="ArtistId">The Id of the artist that owns the album, so the segment route can scope the delivery without querying it again.</param>
|
||||
[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
|
||||
);
|
||||
+26
-52
@@ -7,56 +7,30 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T
|
||||
/// <summary>
|
||||
/// Data transfer object for the stored probe result of a track, containing only the fields a playback manifest is built from.
|
||||
/// </summary>
|
||||
/// <param name="Path">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.</param>
|
||||
/// <param name="Container">The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.</param>
|
||||
/// <param name="AudioCodec">The audio codec used by the audio file of the track, if applicable.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the audio of the track in seconds.</param>
|
||||
/// <param name="SampleRate">The sample rate of the audio of the track in Hz.</param>
|
||||
/// <param name="Channels">The number of audio channels of the track.</param>
|
||||
/// <param name="BitDepth">The bit depth of the audio of the track, if applicable.</param>
|
||||
/// <param name="Bitrate">The bitrate of the audio of the track, in kbps, if applicable.</param>
|
||||
/// <param name="ReplayGainTrackGain">The ReplayGain track gain of the track, in decibels, if applicable.</param>
|
||||
/// <param name="ReplayGainTrackPeak">The ReplayGain track peak of the track, if applicable.</param>
|
||||
/// <param name="ReplayGainAlbumGain">The ReplayGain album gain of the track, in decibels, if applicable.</param>
|
||||
/// <param name="ReplayGainAlbumPeak">The ReplayGain album peak of the track, if applicable.</param>
|
||||
[DebuggerDisplay("Container: {Container} Codec: {AudioCodec}")]
|
||||
public sealed record TrackPlaybackManifestDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.
|
||||
/// </summary>
|
||||
public string? Container { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the audio codec used by the audio file of the track, if applicable.
|
||||
/// </summary>
|
||||
public string? AudioCodec { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the audio of the track in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the sample rate of the audio of the track in Hz.
|
||||
/// </summary>
|
||||
public int SampleRate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of audio channels of the track.
|
||||
/// </summary>
|
||||
public int Channels { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bit depth of the audio of the track, if applicable.
|
||||
/// </summary>
|
||||
public int? BitDepth { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ReplayGain track gain of the track, in decibels, if applicable.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainTrackGain { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ReplayGain track peak of the track, if applicable.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainTrackPeak { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ReplayGain album gain of the track, in decibels, if applicable.
|
||||
/// </summary>
|
||||
public decimal? ReplayGainAlbumGain { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ReplayGain album peak of the track, if applicable.
|
||||
/// </summary>
|
||||
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
|
||||
);
|
||||
+24
-52
@@ -7,55 +7,27 @@ namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.T
|
||||
/// <summary>
|
||||
/// Data transfer object for a track, containing the data needed to stream, or to describe the streaming of, its audio file.
|
||||
/// </summary>
|
||||
public sealed record TrackStreamDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the file system path of the track.
|
||||
/// </summary>
|
||||
public required string Path { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library the track belongs to.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the album the track belongs to.
|
||||
/// </summary>
|
||||
public required Guid AlbumId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the artist that owns the album the track belongs to.
|
||||
/// </summary>
|
||||
public required Guid ArtistId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the audio codec used by the audio file of the track, if applicable.
|
||||
/// </summary>
|
||||
public string? AudioCodec { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the duration of the audio of the track in seconds.
|
||||
/// </summary>
|
||||
public int DurationInSeconds { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the sample rate of the audio of the track in Hz.
|
||||
/// </summary>
|
||||
public int SampleRate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of audio channels of the track.
|
||||
/// </summary>
|
||||
public int Channels { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bit depth of the audio of the track, if applicable.
|
||||
/// </summary>
|
||||
public int? BitDepth { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bitrate of the audio of the track in kbps, if applicable.
|
||||
/// </summary>
|
||||
public int? Bitrate { get; init; }
|
||||
}
|
||||
/// <param name="Path">The file system path of the track.</param>
|
||||
/// <param name="LibraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="AlbumId">The Id of the album the track belongs to.</param>
|
||||
/// <param name="ArtistId">The Id of the artist that owns the album the track belongs to.</param>
|
||||
/// <param name="Container">The container of the audio file of the track, for example MP3, FLAC, OGG, AAC, MP4 or WAV, if applicable.</param>
|
||||
/// <param name="AudioCodec">The audio codec used by the audio file of the track, if applicable.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the audio of the track in seconds.</param>
|
||||
/// <param name="SampleRate">The sample rate of the audio of the track in Hz.</param>
|
||||
/// <param name="Channels">The number of audio channels of the track.</param>
|
||||
/// <param name="BitDepth">The bit depth of the audio of the track, if applicable.</param>
|
||||
/// <param name="Bitrate">The bitrate of the audio of the track, in kbps, if applicable.</param>
|
||||
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
|
||||
);
|
||||
+39
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service that issues and resolves the opaque delivery handles of the playback manifest.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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 <c>N</c> format of a <see cref="Guid"/>, 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.
|
||||
/// </remarks>
|
||||
public interface IPlaybackDeliveryHandleService
|
||||
{
|
||||
/// <summary>
|
||||
/// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle.
|
||||
/// </summary>
|
||||
/// <param name="delivery">The delivery, its source file identity, its quality cap and its user.</param>
|
||||
/// <returns>The opaque delivery handle.</returns>
|
||||
string IssueDeliveryId(PlaybackDeliveryHandleDto delivery);
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track.
|
||||
/// </summary>
|
||||
/// <param name="deliveryId">The opaque delivery handle reported by the playback manifest.</param>
|
||||
/// <param name="userId">The Id of the current user, which the handle must have been issued to.</param>
|
||||
/// <param name="trackId">The Id of the track named by the route, which the handle must describe.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the delivery, or <see cref="Errors.Playback.PlaybackDeliveryNotFound"/> when the handle is unknown, expired, or belongs to another user or track.
|
||||
/// </returns>
|
||||
Result<PlaybackDeliveryHandleDto> GetDelivery(string? deliveryId, Guid userId, Guid trackId);
|
||||
}
|
||||
+9
-9
@@ -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 <see cref="Domain.Common.Errors.Errors.Playback.NormalizationUnavailable"/> as well, while an entry that is already
|
||||
/// cached is still served. The playback stream surface that exposes the produced segments is the intended consumer of this contract; no API request path
|
||||
/// calls it yet.
|
||||
/// 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 <see cref="Errors.Playback.NormalizationUnavailable"/> 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.
|
||||
/// </remarks>
|
||||
public interface ITrackNormalizationService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the normalized audio of a track from the cache, or produces it and caches it when it is not cached yet.
|
||||
/// </summary>
|
||||
/// <param name="request">The track, the delivery decision, the source file and the quality cap the normalized audio is produced with.</param>
|
||||
/// <param name="request">The track, the requesting user, the delivery decision, the source file and the quality cap the normalized audio is produced with.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the cached normalized audio of the track, or an error message.
|
||||
@@ -47,10 +48,9 @@ public interface ITrackNormalizationService
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A missing or evicted cache entry, a segment that is no longer present, an entry that cannot be read, or a value that is not a well formed handle is
|
||||
/// reported with <see cref="Domain.Common.Errors.Errors.Playback.NormalizedTrackCacheEntryNotFound"/>. That is the caller's signal to request the
|
||||
/// reported with <see cref="Errors.Playback.NormalizedTrackCacheEntryNotFound"/>. That is the caller's signal to request the
|
||||
/// playback manifest again, or to trigger a new production, instead of treating the result as a broken transcode. A genuine production failure keeps
|
||||
/// its own error. A service that has already been disposed reports
|
||||
/// <see cref="Domain.Common.Errors.Errors.Playback.NormalizationUnavailable"/>.
|
||||
/// its own error. A service that has already been disposed reports <see cref="Errors.Playback.NormalizationUnavailable"/>.
|
||||
/// </remarks>
|
||||
/// <param name="cacheId">The opaque identifier of the cached entry that holds the normalized audio.</param>
|
||||
/// <param name="trackId">The Id of the track the caller authorized and whose segment is opened.</param>
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Defines the format of the opaque delivery handle of a playback manifest.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A handle is a <see cref="Guid"/> rendered with the <c>N</c> 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.
|
||||
/// </remarks>
|
||||
public static class PlaybackDeliveryId
|
||||
{
|
||||
/// <summary>
|
||||
/// The number of characters of a delivery handle.
|
||||
/// </summary>
|
||||
public const int CHARACTER_COUNT = 32;
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a value has the format of a delivery handle.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to check.</param>
|
||||
/// <returns><see langword="true"/> when the value is exactly 32 lowercase hexadecimal characters, otherwise <see langword="false"/>.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -14,6 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.
|
||||
/// <param name="TrackId">The unique identifier of the track whose playback manifest is retrieved, taken from the route.</param>
|
||||
/// <param name="Capabilities">The container and codec pairs the player advertises it can demux and decode directly, taken from the request, or <see langword="null"/> when it advertises none.</param>
|
||||
/// <param name="StreamPath">The path of the track stream, relative to the API, taken from the endpoint so that it always matches the stream route.</param>
|
||||
/// <param name="SegmentStreamPathTemplate">The path template of the segment route, relative to the API, with a <c>{deliveryId}</c> and a <c>{segmentIndex}</c> placeholder, taken from the endpoint so that it always matches the segment route.</param>
|
||||
[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;
|
||||
+89
-2
@@ -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<GetPlaybackManifest
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IPlaybackFormatService _playbackFormatService;
|
||||
private readonly IPlaybackDeliveryHandleService _playbackDeliveryHandleService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<GetPlaybackManifestQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
@@ -37,15 +44,19 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler<GetPlaybackManifest
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="playbackFormatService">Injected service for deciding how a track's audio is delivered to a player.</param>
|
||||
/// <param name="playbackDeliveryHandleService">Injected service that issues the opaque delivery handles of a normalized manifest.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="pathService">Injected service for file system path related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IValidator<GetPlaybackManifestQuery> validator)
|
||||
public GetPlaybackManifestQueryHandler(IUnitOfWork unitOfWork, IPlaybackFormatService playbackFormatService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator<GetPlaybackManifestQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_playbackFormatService = playbackFormatService;
|
||||
_playbackDeliveryHandleService = playbackDeliveryHandleService;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
@@ -102,6 +113,80 @@ public class GetPlaybackManifestQueryHandler : IQueryHandler<GetPlaybackManifest
|
||||
// Whether the delivered audio can be seeked is a property of the shape it is delivered in, so the rule lives on the shape itself.
|
||||
bool isSeekable = decision.Shape.IsSeekable();
|
||||
|
||||
string? deliveryId = null;
|
||||
if (!isDirectPlay)
|
||||
{
|
||||
// The quality cap and the source file version are captured now, so the segment route never recomputes the delivery from a
|
||||
// setting the user may change, or from a file that may be replaced, while the track is playing.
|
||||
PlaybackStreamingQuality quality = PlaybackStreamingQuality.Auto;
|
||||
Result<UserSettingsEntity?> 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<LibraryEntity?> 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<string> 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<GetPlaybackManifest
|
||||
isDirectPlay ? null : decision.Shape,
|
||||
decision.Shape == PlaybackDeliveryShape.TimeAddressedSegments ? decision.SegmentDurationSeconds : null,
|
||||
isSeekable,
|
||||
query.StreamPath);
|
||||
query.StreamPath,
|
||||
deliveryId,
|
||||
deliveryId is null ? null : query.SegmentStreamPathTemplate);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting a single segment of the normalized audio of a track, for streaming.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library the track belongs to, taken from the route.</param>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album of the track belongs to, taken from the route.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track whose normalized audio is streamed, taken from the route.</param>
|
||||
/// <param name="DeliveryId">The opaque handle of the normalized delivery the segment belongs to, taken from the route.</param>
|
||||
/// <param name="SegmentIndex">The zero based index of the segment of the normalized audio, taken from the route.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")]
|
||||
public record GetTrackSegmentQuery(
|
||||
string? LibraryId,
|
||||
string? ArtistId,
|
||||
string? AlbumId,
|
||||
string? TrackId,
|
||||
string? DeliveryId,
|
||||
string? SegmentIndex
|
||||
) : IQuery;
|
||||
+130
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a single segment of the normalized audio of a track, for streaming.
|
||||
/// </summary>
|
||||
public class GetTrackSegmentQueryHandler : IQueryHandler<GetTrackSegmentQuery, Result<NormalizedTrackSegmentDataDto>>
|
||||
{
|
||||
private readonly ITrackNormalizationService _trackNormalizationService;
|
||||
private readonly IPlaybackDeliveryHandleService _playbackDeliveryHandleService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IPathService _pathService;
|
||||
private readonly IValidator<GetTrackSegmentQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackSegmentQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="trackNormalizationService">Injected service that produces, caches and serves the normalized audio of a track.</param>
|
||||
/// <param name="playbackDeliveryHandleService">Injected service that resolves the opaque delivery handle of the playback manifest.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="pathService">Injected service for file system path related functionality.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetTrackSegmentQueryHandler(ITrackNormalizationService trackNormalizationService, IPlaybackDeliveryHandleService playbackDeliveryHandleService, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IPathService pathService, IValidator<GetTrackSegmentQuery> validator)
|
||||
{
|
||||
_trackNormalizationService = trackNormalizationService;
|
||||
_playbackDeliveryHandleService = playbackDeliveryHandleService;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_pathService = pathService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a single segment of the normalized audio of a track, for streaming.
|
||||
/// </summary>
|
||||
/// <param name="query">The query to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the data of the requested segment, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<NormalizedTrackSegmentDataDto>> HandleAsync(GetTrackSegmentQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<ILibraryOwnershipPolicy>(
|
||||
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<PlaybackDeliveryHandleDto> 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<NormalizedTrackDto> 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<Stream> 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);
|
||||
}
|
||||
}
|
||||
+81
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetTrackSegmentQuery"/>.
|
||||
/// </summary>
|
||||
public class GetTrackSegmentQueryValidator : AbstractValidator<GetTrackSegmentQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackSegmentQueryValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+17
-7
@@ -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.
|
||||
/// </summary>
|
||||
/// <param name="TrackId">The Id of the track the manifest describes.</param>
|
||||
/// <param name="DurationInSeconds">The duration of the audio of the track, in seconds.</param>
|
||||
/// <param name="DurationInSeconds">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.</param>
|
||||
/// <param name="SourceContainer">The container of the audio file of the track, as stored by the probe, for example MP3, FLAC, OGG, AAC, MP4 or WAV. Optional.</param>
|
||||
/// <param name="SourceCodec">The codec of the audio of the track, as stored by the probe. Optional.</param>
|
||||
/// <param name="SampleRate">The sample rate of the audio of the track, in Hz.</param>
|
||||
@@ -21,14 +21,22 @@ namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Play
|
||||
/// <param name="ReplayGainTrackPeak">The ReplayGain track peak of the track. Optional.</param>
|
||||
/// <param name="ReplayGainAlbumGain">The ReplayGain album gain of the track, in decibels. Optional.</param>
|
||||
/// <param name="ReplayGainAlbumPeak">The ReplayGain album peak of the track. Optional.</param>
|
||||
/// <param name="DirectPlay">Whether the player can play the stored audio as it is, without the server changing its container or its codec.</param>
|
||||
/// <param name="IsDirectPlay">Whether the player can play the stored audio as it is, without the server changing its container or its codec.</param>
|
||||
/// <param name="DeliveryContainer">The container of the audio the server delivers, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
|
||||
/// <param name="DeliveryCodec">The codec of the audio the server delivers, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
|
||||
/// <param name="DeliveryShape">The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play. <see langword="null"/> for a direct play.</param>
|
||||
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments. <see langword="null"/> otherwise.</param>
|
||||
/// <param name="Seekable">Whether the delivered audio can be seeked by the player.</param>
|
||||
/// <param name="IsSeekable">Whether the delivered audio can be seeked by the player.</param>
|
||||
/// <param name="StreamPath">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.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")]
|
||||
/// <param name="DeliveryId">
|
||||
/// 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. <see langword="null"/> for a direct play.
|
||||
/// </param>
|
||||
/// <param name="SegmentStreamPathTemplate">
|
||||
/// The path of the segment route of the normalized delivery, relative to the API and without a host or a scheme, with a <c>{deliveryId}</c> and a
|
||||
/// <c>{segmentIndex}</c> placeholder. <see langword="null"/> for a direct play, whose delivery is addressed by byte range.
|
||||
/// </param>
|
||||
[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
|
||||
);
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -152,12 +152,16 @@ public static class InfrastructureLayerServices
|
||||
// repackaged into another container, or re-encoded into another codec.
|
||||
services.AddSingleton<IPlaybackFormatService, PlaybackFormatService>();
|
||||
|
||||
// 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<IPlaybackDeliveryHandleService, PlaybackDeliveryHandleService>();
|
||||
|
||||
// Music playback: records the outcome of the ffmpeg probe, so a missing binary or encoder is reported as unavailable for the affected formats.
|
||||
services.AddSingleton<TranscodingToolchainStatus>();
|
||||
|
||||
// Music playback: produces the normalized (remuxed or transcoded) audio of a track with ffmpeg, caches it as fixed duration
|
||||
// segments and serves it from the cache, bounded in concurrency, cancellable and capped in disk usage. The playback stream surface
|
||||
// is its intended consumer; no API request path calls it yet.
|
||||
// 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<ITrackNormalizationService, TrackNormalizationService>();
|
||||
|
||||
// Music playback: owns the normalized audio cache lifecycle and verifies the ffmpeg encoders at startup, so a missing or changed toolchain
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -22,6 +22,12 @@ public sealed class TranscodingSettingsDto
|
||||
/// </summary>
|
||||
public int MaxConcurrentJobs { get; set; } = 2;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int MaxConcurrentJobsPerUser { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum total size of the normalized audio cache, in bytes.
|
||||
/// </summary>
|
||||
|
||||
@@ -53,6 +53,19 @@ public class TranscodingSettingsDtoValidator : AbstractValidator<TranscodingSett
|
||||
.Must(maxConcurrentJobs => 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);
|
||||
|
||||
+251
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
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<string, StoredDelivery> _deliveries = [];
|
||||
private readonly Dictionary<string, string> _deliveryIdsBySignature = [];
|
||||
private readonly Dictionary<Guid, Queue<string>> _deliveryIdsByUser = [];
|
||||
private readonly Dictionary<Guid, int> _deliveryCountsByUser = [];
|
||||
private readonly Queue<(string DeliveryId, DateTimeOffset ExpiresAtUtc)> _expiryQueue = [];
|
||||
|
||||
/// <summary>
|
||||
/// Issues an opaque handle for a delivery, which the playback manifest reports so its segments can be addressed by that handle.
|
||||
/// </summary>
|
||||
/// <param name="delivery">The delivery, its source file identity, its quality cap and its user.</param>
|
||||
/// <returns>The opaque delivery handle.</returns>
|
||||
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<string>? userDeliveryIds))
|
||||
{
|
||||
userDeliveryIds = [];
|
||||
_deliveryIdsByUser[delivery.Request.UserId] = userDeliveryIds;
|
||||
}
|
||||
userDeliveryIds.Enqueue(deliveryId);
|
||||
_expiryQueue.Enqueue((deliveryId, expiresAtUtc));
|
||||
return deliveryId;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the delivery a handle addresses, after verifying that it was issued to the provided user and describes the provided track.
|
||||
/// </summary>
|
||||
/// <param name="deliveryId">The opaque delivery handle reported by the playback manifest.</param>
|
||||
/// <param name="userId">The Id of the current user, which the handle must have been issued to.</param>
|
||||
/// <param name="trackId">The Id of the track named by the route, which the handle must describe.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the delivery, or <see cref="Errors.Playback.PlaybackDeliveryNotFound"/> when the handle
|
||||
/// is unknown, expired, or belongs to another user or track.
|
||||
/// </returns>
|
||||
public Result<PlaybackDeliveryHandleDto> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enforces the per-user handle limit by evicting the oldest handles of that user.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose handles are bounded.</param>
|
||||
private void EnforceUserLimit(Guid userId)
|
||||
{
|
||||
while (_deliveryCountsByUser.GetValueOrDefault(userId) >= MAX_DELIVERIES_PER_USER)
|
||||
if (!TryEvictOldestForUser(userId))
|
||||
break;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enforces the global handle limit by evicting the oldest handle.
|
||||
/// </summary>
|
||||
private void EnforceGlobalLimit()
|
||||
{
|
||||
while (_deliveries.Count >= MAX_DELIVERIES)
|
||||
if (!TryEvictOldestDelivery())
|
||||
break;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evicts the oldest handle that is still registered for a user.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose oldest handle is evicted.</param>
|
||||
/// <returns><see langword="true"/> when a handle was evicted, otherwise <see langword="false"/>.</returns>
|
||||
private bool TryEvictOldestForUser(Guid userId)
|
||||
{
|
||||
if (!_deliveryIdsByUser.TryGetValue(userId, out Queue<string>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evicts the oldest handle that is still registered, using the expiry queue as the age order.
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when a handle was evicted, otherwise <see langword="false"/>.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the deliveries whose lifetime ended, in expiry order, so the sweep does not scan the registry.
|
||||
/// </summary>
|
||||
/// <param name="now">The current time, in UTC.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes one delivery and its signature and per-user accounting.
|
||||
/// </summary>
|
||||
/// <param name="deliveryId">The opaque handle of the delivery to remove.</param>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the key that identifies a delivery for de-duplication, from every input that changes the handle's meaning.
|
||||
/// </summary>
|
||||
/// <param name="delivery">The delivery to key.</param>
|
||||
/// <returns>The signature of the delivery.</returns>
|
||||
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)
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A registered delivery, its de-duplication signature and its expiry.
|
||||
/// </summary>
|
||||
/// <param name="Delivery">The delivery the handle addresses.</param>
|
||||
/// <param name="Signature">The signature of every input that changes the handle's meaning.</param>
|
||||
/// <param name="ExpiresAtUtc">The time, in UTC, after which the handle is no longer accepted.</param>
|
||||
private sealed record StoredDelivery(
|
||||
PlaybackDeliveryHandleDto Delivery,
|
||||
string Signature,
|
||||
DateTimeOffset ExpiresAtUtc
|
||||
);
|
||||
}
|
||||
+103
-20
@@ -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<int, Process> _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<Guid, int> _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
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the normalized audio of the track, or an error message.</returns>
|
||||
private async Task<Result<NormalizedTrackDto>> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reserves one of the per-user production slots before a production is admitted, so one user can never occupy every global job slot.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose request starts the production.</param>
|
||||
/// <returns><see langword="true"/> when the slot was reserved, <see langword="false"/> otherwise.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases a per-user production slot that was reserved by <see cref="TryAcquireUserProductionSlot"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose production ended.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Projects a validated cache index once and reuses the projection for the following segment requests of the same cached track.
|
||||
/// </summary>
|
||||
/// <param name="cacheId">The opaque identifier of the cache entry that holds the normalized audio.</param>
|
||||
/// <param name="index">The validated index of the cache entry.</param>
|
||||
/// <returns>The normalized track described by the index.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Projects a validated cache index into the normalized track the caller receives.
|
||||
/// </summary>
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"TranscodingSettings": {
|
||||
"FfmpegPath": "ffmpeg",
|
||||
"MaxConcurrentJobs": 2,
|
||||
"MaxConcurrentJobsPerUser": 1,
|
||||
"MaxCacheBytes": 2147483648,
|
||||
"JobTimeoutSeconds": 900,
|
||||
"EvictionGraceSeconds": 120,
|
||||
|
||||
@@ -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<string, AudioFileFormat> s_containerToAudioFileFormat = new Dictionary<string, AudioFileFormat>(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);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the MIME content type of <paramref name="format"/>.
|
||||
/// </summary>
|
||||
@@ -38,4 +53,16 @@ public static class MusicMimeTypes
|
||||
{
|
||||
return s_audioFileFormatToMimeType.TryGetValue(format, out string? mimeType) ? mimeType : "application/octet-stream";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the MIME content type of an audio container, as named by the delivery decision of a playback manifest.
|
||||
/// </summary>
|
||||
/// <param name="container">The canonical container of the delivered audio, for example MP4, AAC, OGG, MP3, FLAC or WAV.</param>
|
||||
/// <returns>The MIME content type of <paramref name="container"/>, or <c>application/octet-stream</c> when the container is unknown.</returns>
|
||||
public static string GetContainerMimeType(string? container)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(container) && s_containerToAudioFileFormat.TryGetValue(container.Trim(), out AudioFileFormat format)
|
||||
? GetMimeType(format)
|
||||
: "application/octet-stream";
|
||||
}
|
||||
}
|
||||
+1
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -45,16 +45,20 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
|
||||
protected IResult Problem(Error error)
|
||||
{
|
||||
Dictionary<string, object?> 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<TRequest, TResponse> : Endpoint<TRequest, TRe
|
||||
|
||||
// populate the errors dictionary with error codes and their descriptions
|
||||
foreach (Error error in errors)
|
||||
{
|
||||
if (!errorsDictionary.TryGetValue(error.Code, out string[]? value))
|
||||
errorsDictionary.Add(error.Code, [error.Description]);
|
||||
else
|
||||
{
|
||||
if (!errorsDictionary[error.Code].Contains(error.Description))
|
||||
errorsDictionary[error.Code] = [.. value, error.Description];
|
||||
}
|
||||
}
|
||||
|
||||
// add trace identifier to the extensions dictionary for tracing purposes
|
||||
extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
|
||||
/// <summary>
|
||||
/// A response result that writes an owned stream to the response without buffering it and releases the stream once the response is complete.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public sealed class DisposingStreamResult : IResult
|
||||
{
|
||||
private readonly Stream _content;
|
||||
private readonly string _contentType;
|
||||
private readonly long? _contentLength;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DisposingStreamResult"/> class.
|
||||
/// </summary>
|
||||
/// <param name="content">The stream to write, which this result owns and releases after the response is complete.</param>
|
||||
/// <param name="contentType">The media type of the content.</param>
|
||||
/// <param name="contentLength">The length of the content, in bytes, or <see langword="null"/> when it is not known in advance.</param>
|
||||
public DisposingStreamResult(Stream content, string contentType, long? contentLength)
|
||||
{
|
||||
_content = content;
|
||||
_contentType = contentType;
|
||||
_contentLength = contentLength;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the content stream to the response.
|
||||
/// </summary>
|
||||
/// <param name="httpContext">The HTTP context of the request being answered.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+17
-2
@@ -62,8 +62,23 @@ public class GetPlaybackManifestEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
.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<PlaybackManifestResponse> 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);
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -34,13 +34,15 @@ public class GetPlaybackManifestEndpointSummary : Summary<GetPlaybackManifestEnd
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainTrackPeak, "The ReplayGain track peak of the track, if applicable.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainAlbumGain, "The ReplayGain album gain of the track, in decibels, if applicable.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.ReplayGainAlbumPeak, "The ReplayGain album peak of the track, if applicable.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.IsDirectPlay, "Whether the player can play the stored audio as it is, without the server changing its container or its codec.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryContainer, "The container of the audio the server delivers, when the delivery is not a direct play.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryCodec, "The codec of the audio the server delivers, when the delivery is not a direct play.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryShape, "The shape the delivered audio is addressed and seeked by, when the delivery is not a direct play.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.SegmentDurationSeconds, "The duration of each segment of the delivered audio, in seconds, when the delivery is addressed as time addressed segments.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.Seekable, "Whether the delivered audio can be seeked by the player.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.IsSeekable, "Whether the delivered audio can be seeked by the player.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.StreamPath, "The path of the track stream, relative to the API, without a host or a scheme.");
|
||||
ResponseParam<PlaybackManifestResponse>(r => r.DeliveryId, "The opaque handle of the normalized delivery, which the segment route accepts. Null for a direct play.");
|
||||
ResponseParam<PlaybackManifestResponse>(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<GetPlaybackManifestEnd
|
||||
ReplayGainTrackPeak: 0.9877m,
|
||||
ReplayGainAlbumGain: -6.8m,
|
||||
ReplayGainAlbumPeak: 0.9999m,
|
||||
DirectPlay: false,
|
||||
IsDirectPlay: false,
|
||||
DeliveryContainer: "MP3",
|
||||
DeliveryCodec: "MP3",
|
||||
DeliveryShape: PlaybackDeliveryShape.TimeAddressedSegments,
|
||||
SegmentDurationSeconds: 6,
|
||||
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: "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}"
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackSegment;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Api.Common.Http;
|
||||
using Lumina.Presentation.Api.Common.MimeTypes;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Globalization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackSegment;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream/deliveries/{deliveryId}/segments/{segmentIndex}</c> route.
|
||||
/// </summary>
|
||||
public class GetTrackSegmentEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
// 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<GetTrackSegmentQuery, Result<NormalizedTrackSegmentDataDto>> _getTrackSegmentQueryHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="getTrackSegmentQueryHandler">Injected service for handling get track segment queries.</param>
|
||||
public GetTrackSegmentEndpoint(IQueryHandler<GetTrackSegmentQuery, Result<NormalizedTrackSegmentDataDto>> getTrackSegmentQueryHandler)
|
||||
{
|
||||
_getTrackSegmentQueryHandler = getTrackSegmentQueryHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
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()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Streams one segment of the normalized audio of the track identified by the route.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> 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<NormalizedTrackSegmentDataDto> 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);
|
||||
}
|
||||
}
|
||||
+145
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetTrackSegmentEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTrackSegmentEndpointSummary : Summary<GetTrackSegmentEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTrackSegmentEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
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<string, string[]>
|
||||
{
|
||||
{
|
||||
"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"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
/// </summary>
|
||||
public sealed class ApiStreamResult : IAsyncDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The response header that carries the number of segments of a normalized audio production. It must match the name the API sends.
|
||||
/// </summary>
|
||||
public const string SEGMENT_COUNT_HEADER_NAME = "X-Lumina-Segment-Count";
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public const string SEGMENT_START_SECONDS_HEADER_NAME = "X-Segment-Start-Seconds";
|
||||
|
||||
/// <summary>
|
||||
/// The response header that carries the produced duration of the normalized track, in seconds. It must match the name the API sends.
|
||||
/// </summary>
|
||||
public const string TRACK_DURATION_SECONDS_HEADER_NAME = "X-Lumina-Track-Duration-Seconds";
|
||||
|
||||
private readonly HttpResponseMessage _response;
|
||||
|
||||
/// <summary>
|
||||
@@ -62,6 +80,22 @@ public sealed class ApiStreamResult : IAsyncDisposable
|
||||
/// </summary>
|
||||
public string? CacheControl { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of segments the normalized audio production holds, when the response is a segment of one and declares it.
|
||||
/// </summary>
|
||||
public int? SegmentCount { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the exact start of the segment on the track timeline, in seconds, as declared by the API, or <see langword="null"/> when the response
|
||||
/// declares none.
|
||||
/// </summary>
|
||||
public string? SegmentStartSeconds { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the produced duration of the normalized track, in seconds, as declared by the API, or <see langword="null"/> when the response declares none.
|
||||
/// </summary>
|
||||
public int? TrackDurationSeconds { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiStreamResult"/> class.
|
||||
/// </summary>
|
||||
@@ -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<string>? 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<string>? segmentStartValues)
|
||||
? segmentStartValues.FirstOrDefault()
|
||||
: null;
|
||||
TrackDurationSeconds = response.Headers.TryGetValues(TRACK_DURATION_SECONDS_HEADER_NAME, out IEnumerable<string>? trackDurationValues)
|
||||
&& int.TryParse(trackDurationValues.FirstOrDefault(), NumberStyles.None, CultureInfo.InvariantCulture, out int parsedTrackDuration)
|
||||
&& parsedTrackDuration > 0
|
||||
? parsedTrackDuration
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+16
-3
@@ -9,7 +9,7 @@ namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("TrackId: {TrackId} DirectPlay: {DirectPlay}")]
|
||||
[DebuggerDisplay("TrackId: {TrackId} IsDirectPlay: {IsDirectPlay}")]
|
||||
public class PlaybackManifestDto
|
||||
{
|
||||
/// <summary>
|
||||
@@ -70,7 +70,7 @@ public class PlaybackManifestDto
|
||||
/// <summary>
|
||||
/// Gets or sets whether the player can play the stored audio as it is, without the server changing its container or its codec.
|
||||
/// </summary>
|
||||
public bool DirectPlay { get; set; }
|
||||
public bool IsDirectPlay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <summary>
|
||||
/// Gets or sets whether the delivered audio can be seeked by the player.
|
||||
/// </summary>
|
||||
public bool Seekable { get; set; }
|
||||
public bool IsSeekable { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public string StreamPath { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see langword="null"/> for a direct play.
|
||||
/// </summary>
|
||||
public string? DeliveryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path template of the segment route of the normalized delivery. The API returns it relative to itself with a
|
||||
/// <c>{deliveryId}</c> and a <c>{segmentIndex}</c> 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 <see langword="null"/> for a direct play.
|
||||
/// </summary>
|
||||
public string? SegmentStreamPathTemplate { get; set; }
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class ApiStreamProxy
|
||||
{
|
||||
/// <summary>
|
||||
/// Copies the streamed API response to the response sent to the browser, without buffering its content.
|
||||
/// </summary>
|
||||
/// <param name="response">The response sent to the browser.</param>
|
||||
/// <param name="streamResult">The streamed response of the API.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the copy when the client disconnects.</param>
|
||||
/// <returns>A <see cref="Task"/> that represents the asynchronous copy operation.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a response header to the given value, unless the value is missing.
|
||||
/// </summary>
|
||||
/// <param name="response">The response to set the header on.</param>
|
||||
/// <param name="name">The name of the header.</param>
|
||||
/// <param name="value">The value of the header, or <see langword="null"/> when the API did not send it.</param>
|
||||
private static void SetHeader(HttpResponse response, string name, string? value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
response.Headers[name] = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the caching instructions of the browser response from the instructions of the API.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="apiCacheControl">The caching instructions of the API response, or <see langword="null"/> when it declared none.</param>
|
||||
/// <returns>The caching instructions of the response sent to the browser.</returns>
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace Lumina.Presentation.Web.Common.Playback;
|
||||
|
||||
/// <summary>
|
||||
/// Defines the format of the opaque delivery handle of a playback manifest.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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 <c>N</c> format of a GUID. A value that does not match it is rejected, never normalized.
|
||||
/// </remarks>
|
||||
public static class PlaybackDeliveryId
|
||||
{
|
||||
/// <summary>
|
||||
/// The number of characters of a delivery handle.
|
||||
/// </summary>
|
||||
public const int CHARACTER_COUNT = 32;
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a value has the format of a delivery handle.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to check.</param>
|
||||
/// <returns><see langword="true"/> when the value is exactly 32 lowercase hexadecimal characters, otherwise <see langword="false"/>.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to stream one segment of the normalized audio of a track.
|
||||
/// </summary>
|
||||
/// <param name="ArtistId">The unique identifier of the artist the album belongs to, taken from the route. Required.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album the track belongs to, taken from the route. Required.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track to stream, taken from the route. Required.</param>
|
||||
/// <param name="DeliveryId">The opaque handle of the normalized delivery, taken from the route. Required.</param>
|
||||
/// <param name="SegmentIndex">The zero based index of the segment of the normalized audio, taken from the route. Required.</param>
|
||||
/// <param name="LibraryId">The Id of the media library the track belongs to. Required.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId} DeliveryId: {DeliveryId} SegmentIndex: {SegmentIndex}")]
|
||||
public record StreamMusicTrackSegmentRequest(
|
||||
string ArtistId,
|
||||
string AlbumId,
|
||||
string TrackId,
|
||||
string DeliveryId,
|
||||
int SegmentIndex,
|
||||
Guid LibraryId
|
||||
);
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
+51
-4
@@ -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<GetPlaybackManifestReque
|
||||
Detail = "InternalServerError",
|
||||
Status = StatusCodes.Status502BadGateway
|
||||
}, HttpStatusCode.BadGateway, endpoint);
|
||||
// The API only knows the relative path of its own stream endpoint, and the browser only reaches this application, so the path is
|
||||
// replaced with the path of the streaming proxy of this application, which is the URL the player actually consumes.
|
||||
// The API only knows the relative paths of its own stream and segment endpoints, and the browser only reaches this application, so
|
||||
// they are replaced with the paths of the streaming proxies of this application, which are the URLs the player actually consumes.
|
||||
manifest.StreamPath = BuildBrowserStreamPath(request.LibraryId, normalizedArtistId, normalizedAlbumId, normalizedTrackId);
|
||||
if (string.IsNullOrEmpty(manifest.SegmentStreamPathTemplate))
|
||||
{
|
||||
manifest.DeliveryId = null;
|
||||
manifest.SegmentStreamPathTemplate = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The API decides how its delivery is addressed: the web app only rewrites the path it reported, and only requires the opaque
|
||||
// handle the path needs. It never infers the addressing from the direct play flag.
|
||||
if (!PlaybackDeliveryId.IsValid(manifest.DeliveryId))
|
||||
throw new ApiException(new ProblemDetailsDto
|
||||
{
|
||||
Title = "General.Failure",
|
||||
Detail = "InternalServerError",
|
||||
Status = StatusCodes.Status502BadGateway
|
||||
}, HttpStatusCode.BadGateway, endpoint);
|
||||
manifest.SegmentStreamPathTemplate = BuildBrowserSegmentStreamPath(request.LibraryId, normalizedArtistId, normalizedAlbumId, normalizedTrackId);
|
||||
}
|
||||
// The manifest is specific to the authenticated user and carries a stateful delivery handle, so the browser hop never stores it publicly and
|
||||
// it varies by the cookie that authenticates this hop.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
return JsonSuccess(manifest);
|
||||
}
|
||||
|
||||
@@ -104,12 +126,37 @@ public class GetPlaybackManifestEndpoint : BaseEndpoint<GetPlaybackManifestReque
|
||||
return $"{pathBase}/{streamPath}?libraryId={libraryId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the browser facing relative path template of the segment streaming proxy of this application for the track identified by the given Ids.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
|
||||
/// <param name="artistId">The normalized Id of the artist the album belongs to.</param>
|
||||
/// <param name="albumId">The normalized Id of the album the track belongs to.</param>
|
||||
/// <param name="trackId">The normalized Id of the track.</param>
|
||||
/// <returns>The root relative path template the browser fetches a segment from, on its own origin.</returns>
|
||||
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}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a value can be used safely as a single segment of a path the browser resolves against its own origin.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to check.</param>
|
||||
/// <returns><see langword="true"/> when the value cannot introduce a path separator, a query, a fragment, or a control character, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsSafePathSegment(string value)
|
||||
private static bool IsSafePathSegment(string? value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
return false;
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ public class GetPlaybackManifestEndpointSummary : Summary<GetPlaybackManifestEnd
|
||||
public GetPlaybackManifestEndpointSummary()
|
||||
{
|
||||
Summary = "Retrieves the playback manifest of a music track.";
|
||||
Description = "Retrieves the playback manifest of the music track identified by the route, with the stream path replaced by the URL of the streaming proxy of this application.";
|
||||
Description = "Retrieves the playback manifest of the music track identified by the route, with the stream path and the segment path template replaced by the URLs of the streaming proxies of this application. A normalized delivery also carries the opaque delivery handle the segment proxy forwards, so the segments are addressed by the delivery the 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.");
|
||||
|
||||
+3
-59
@@ -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<StreamMusicTrackRequest, IR
|
||||
|
||||
// The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading.
|
||||
await using (ApiStreamResult streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, forwardHeaders, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
HttpContext.Response.StatusCode = (int)streamResult.StatusCode;
|
||||
CopyResponseHeaders(HttpContext.Response, streamResult);
|
||||
// The caching instructions of the API are forwarded, so that the web hop never silently ignores a caching decision the API made,
|
||||
// but the response is always private to the user, and it varies by the cookie that authenticates this hop: the browser never sends
|
||||
// the bearer token the API sees.
|
||||
HttpContext.Response.Headers["Cache-Control"] = BuildCacheControl(streamResult.CacheControl);
|
||||
HttpContext.Response.Headers["Vary"] = "Cookie";
|
||||
// The body is copied straight from the API to the client, with no intermediate buffering, and the copy is abandoned when the client disconnects.
|
||||
await streamResult.Content.CopyToAsync(HttpContext.Response.Body, cancellationToken).ConfigureAwait(false);
|
||||
{ // The proxy owns the status, header, caching and body rules shared with the normalized segment proxy.
|
||||
await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
return Results.Empty;
|
||||
}
|
||||
@@ -101,52 +93,4 @@ public class StreamMusicTrackEndpoint : BaseEndpoint<StreamMusicTrackRequest, IR
|
||||
if (value.Count > 0 && !string.IsNullOrWhiteSpace(value.ToString()))
|
||||
headers[name] = value.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the status and resource headers of the streamed API response to the response sent to the browser.
|
||||
/// </summary>
|
||||
/// <param name="response">The response sent to the browser.</param>
|
||||
/// <param name="streamResult">The streamed response of the API.</param>
|
||||
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"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a response header to the given value, unless the value is missing.
|
||||
/// </summary>
|
||||
/// <param name="response">The response to set the header on.</param>
|
||||
/// <param name="name">The name of the header.</param>
|
||||
/// <param name="value">The value of the header, or <see langword="null"/> when the API did not send it.</param>
|
||||
private static void SetHeader(HttpResponse response, string name, string? value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
response.Headers[name] = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the caching instructions of the response sent to the browser from the instructions of the API.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="apiCacheControl">The caching instructions of the API response, or <see langword="null"/> when it declared none.</param>
|
||||
/// <returns>The caching instructions of the response sent to the browser.</returns>
|
||||
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();
|
||||
}
|
||||
}
|
||||
+99
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/{culture}/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track-segment/{deliveryId}/{segmentIndex}</c> route.
|
||||
/// </summary>
|
||||
public class StreamMusicTrackSegmentEndpoint : BaseEndpoint<StreamMusicTrackSegmentRequest, IResult>
|
||||
{
|
||||
private readonly IStreamingApiHttpClient _streamingApiHttpClient;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackSegmentEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="streamingApiHttpClient">Injected service for streaming interactions with the API.</param>
|
||||
public StreamMusicTrackSegmentEndpoint(IStreamingApiHttpClient streamingApiHttpClient)
|
||||
{
|
||||
_streamingApiHttpClient = streamingApiHttpClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the endpoint.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Streams one segment of the normalized audio of the track identified by <paramref name="request"/> through the API, without buffering it.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the Ids of the artist, album, track and media library, the delivery handle, and the segment index.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> 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<string, string>(), 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;
|
||||
}
|
||||
}
|
||||
+39
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="StreamMusicTrackSegmentEndpoint"/> endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StreamMusicTrackSegmentEndpointSummary : Summary<StreamMusicTrackSegmentEndpoint, StreamMusicTrackSegmentRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamMusicTrackSegmentEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
}
|
||||
@@ -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 @@
|
||||
<script defer src="~/js/audio-player/audio-player.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-manifest.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-pipeline/audio-player-pipeline-normalized.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js" asp-append-version="true"></script>
|
||||
+19
-17
@@ -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<boolean>} 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<LuminaAudioPlayer.Demuxer|null>} 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 }));
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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 || {});
|
||||
+320
-47
@@ -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<boolean>} 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<void>} 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();
|
||||
|
||||
+1204
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
|
||||
+4
-4
@@ -82,7 +82,7 @@ public class GetPlaybackManifestEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
PlaybackManifestResponse? manifest = await ReadManifestAsync(response);
|
||||
Assert.NotNull(manifest);
|
||||
Assert.Equal(trackId, manifest!.TrackId);
|
||||
Assert.True(manifest.DirectPlay);
|
||||
Assert.True(manifest.IsDirectPlay);
|
||||
Assert.Equal("FLAC", manifest.SourceContainer);
|
||||
Assert.Equal("FLAC", manifest.SourceCodec);
|
||||
Assert.Equal(-7.5m, manifest.ReplayGainTrackGain);
|
||||
@@ -93,7 +93,7 @@ public class GetPlaybackManifestEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
Assert.Null(manifest.DeliveryCodec);
|
||||
Assert.Null(manifest.DeliveryShape);
|
||||
Assert.Null(manifest.SegmentDurationSeconds);
|
||||
Assert.True(manifest.Seekable);
|
||||
Assert.True(manifest.IsSeekable);
|
||||
Assert.Equal($"/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream", manifest.StreamPath);
|
||||
Assert.DoesNotContain("http", manifest.StreamPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -113,12 +113,12 @@ public class GetPlaybackManifestEndpointTests : IClassFixture<AuthenticatedLumin
|
||||
PlaybackManifestResponse? manifest = await ReadManifestAsync(response);
|
||||
Assert.NotNull(manifest);
|
||||
Assert.Equal(trackId, manifest!.TrackId);
|
||||
Assert.False(manifest.DirectPlay);
|
||||
Assert.False(manifest.IsDirectPlay);
|
||||
Assert.Equal("MP3", manifest.DeliveryContainer);
|
||||
Assert.Equal("MP3", manifest.DeliveryCodec);
|
||||
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, manifest.DeliveryShape);
|
||||
Assert.Equal(6, manifest.SegmentDurationSeconds);
|
||||
Assert.True(manifest.Seekable);
|
||||
Assert.True(manifest.IsSeekable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
Reference in new issue
Block a user