Adds seekable normalized audio track delivery

This commit is contained in:
BinaryAlley committed 2026-10-18 14:55:56 +03:00
1 parent 4e13b23f16
commit 45f9aa3bd5
57 files changed
+3452 -344

No files matched your search

@@ -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>
@@ -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;
}
}
@@ -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";
}
}
@@ -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;
@@ -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.");
@@ -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();
}
}
@@ -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;
}
}
@@ -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>
@@ -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 || {});
@@ -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();