Adds audio player seeking, resync, underrun recovery and gapless transitions.

- Adds the media pipeline engine, seek-aware byte source, schedulers and manifest client.

- Implements seeking, resync, underrun recovery, bounded gapless prefetch and clean failure handling.

- Pins manifest, stream and configuration requests to validated page-origin routes.

- Adds why comments to the complex pipeline and download paths.
This commit is contained in:
BinaryAlley committed 2026-10-17 15:11:30 +03:00
1 parent c05978fac0
commit e6fa85f7c6
14 files changed
+3958 -85

No files matched your search

@@ -1,7 +1,7 @@
namespace Lumina.Presentation.Web.Common.Services;
/// <summary>
/// Interface for the service for generating absolute URLs from the application route templates, with URL localization.
/// Interface for the service for generating URLs from the application route templates, with URL localization.
/// </summary>
public interface IUrlService
{
@@ -12,4 +12,13 @@ public interface IUrlService
/// <param name="additionalRouteValues">Optional additional route values, like route parameters.</param>
/// <returns>An absolute URL to the specified route.</returns>
string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null);
/// <summary>
/// Generates a root relative URL for the specified route template, including the path base and the culture, but not the scheme or the host.
/// A browser resolves it against the origin of the page, so it does not depend on how the server sees its own host behind a proxy.
/// </summary>
/// <param name="routeTemplate">The route template of the target page or endpoint, taken from the <see cref="Lumina.Presentation.Web.Common.Routes.WebRoutes"/> constants.</param>
/// <param name="additionalRouteValues">Optional additional route values, like route parameters.</param>
/// <returns>A root relative URL to the specified route.</returns>
string? GetRelativeUrl(string routeTemplate, object? additionalRouteValues = null);
}
@@ -38,7 +38,20 @@ public class UrlService : IUrlService
/// <exception cref="ArgumentException">Thrown when <paramref name="routeTemplate"/> is not one of the route templates defined in the <see cref="WebRoutes"/> constants.</exception>
public string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null)
{
// fail fast when the route template is not one of the ones defined in the WebRoutes constants, instead of silently generating a broken URL
string? path = GetRelativeUrl(routeTemplate, additionalRouteValues);
if (path is null)
return null;
HttpContext? httpContext = _httpContextAccessor.HttpContext;
if (httpContext is null)
return null;
// Build the absolute URL from the request's scheme, host and the already localized path base.
return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{path}";
}
/// <inheritdoc />
public string? GetRelativeUrl(string routeTemplate, object? additionalRouteValues = null)
{
// Fail fast when the route template is not one of the ones defined in the WebRoutes constants, instead of silently generating a broken URL.
if (!s_knownRouteTemplates.Contains(routeTemplate))
throw new ArgumentException($"The route template '{routeTemplate}' is not defined in the WebRoutes constants.", nameof(routeTemplate));
@@ -50,11 +63,12 @@ public class UrlService : IUrlService
if (additionalRouteValues is not null)
foreach (PropertyInfo property in additionalRouteValues.GetType().GetProperties())
path = path.Replace($"{{{property.Name}}}", property.GetValue(additionalRouteValues)?.ToString(), StringComparison.OrdinalIgnoreCase);
// ensure the path starts with a slash, so that it is relative to the server root when concatenated with the host and the path base
// Ensure the path starts with a slash, so that it is relative to the server root when concatenated with the path base.
if (!path.StartsWith('/'))
path = "/" + path;
// build the absolute URL from the request's scheme, host and path base
return $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.PathBase}{path}";
// The scheme and host are deliberately omitted. A browser resolves this against its own origin, so the value stays
// correct behind a reverse proxy even when the request headers do not describe the origin the browser used.
return $"{httpContext.Request.PathBase}{path}";
}
/// <summary>
@@ -33,13 +33,16 @@
error: '@localizer["Error"]',
information: '@localizer["Information"]'
};
// The endpoints the audio player reads the stored playback preferences of the user from, and writes the volume and
// mute state it changes back to. The routes are the culture aware web routes, so the player never hardcodes a path,
// and it never reaches the API server directly.
// The endpoints the audio player reads the stored playback preferences of the user from, writes the volume and mute
// state it changes back to, and fetches the playback manifest of a track from, together with the stream route
// template the manifest path must match. The routes are the culture aware web routes, so the player never hardcodes
// a path, and it never reaches the API server directly.
var audioPlayerConfiguration = {
getUserSettingsUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)',
getPlaybackStateUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_PLAYBACK_STATE)',
updatePlaybackStateUrl: '@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_PLAYBACK_STATE)',
getUserSettingsUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.GET_USER_SETTINGS)',
getPlaybackStateUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.GET_PLAYBACK_STATE)',
updatePlaybackStateUrl: '@_urlService.GetRelativeUrl(WebRoutes.Settings.UPDATE_PLAYBACK_STATE)',
getPlaybackManifestUrl: '@_urlService.GetRelativeUrl(WebRoutes.Music.GET_PLAYBACK_MANIFEST)',
streamTrackRouteTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Music.STREAM_TRACK)',
strings: {
play: '@localizer["AudioPlayerPlay"]',
pause: '@localizer["AudioPlayerPause"]',
@@ -80,3 +83,7 @@
<script defer src="~/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-engine.js" asp-append-version="true"></script>
<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-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>
@@ -266,15 +266,18 @@
* request a normalized delivery instead of failing, and never receives both a player failure and a normalization
* request for the same unplayable file.
*
* The one failure that resolves to null without publishing is an intentional download stop: a teardown that crossed
* the header probe is not a track the server has to normalize. A caller that must tell the two nulls apart therefore
* checks whether it received a needs normalization event, or its own teardown state, rather than the null itself.
* The failures that resolve to null without publishing are the ones that say nothing about the format: an intentional
* download stop, a teardown that crossed the header probe, and a transport failure. A transport failure is propagated
* instead of being turned into a normalization request, because the server cannot make a track it could not fetch
* playable. A caller distinguishes the nulls by its own teardown state and by whether it received a needs
* normalization event, rather than by the null itself.
* @param {string} container - The container of the track.
* @param {string} codec - The codec of the track.
* @param {Object} [options] - The demuxer options, plus the injected capabilities and events, per {@link LuminaAudioPlayer.DemuxerCapabilities}.
* @returns {Promise<LuminaAudioPlayer.Demuxer|null>} The ready demuxer, or null when the pair must be normalized.
* @returns {Promise<LuminaAudioPlayer.Demuxer|null>} The ready demuxer, or null when the pair must be normalized or the probe was stopped intentionally.
* @throws {TypeError} When no event bus was injected. It is a composition error, not a property of the track, so it
* rejects rather than resolving to a null the caller would have to classify without an event to classify it by.
* @throws {LuminaAudioPlayer.PlayerError} When the bytes could not be fetched because of a transport failure, which is not a format the server could normalize.
*/
LuminaAudioPlayer.createDemuxerFor = async function (container, codec, options) {
const settings = options || {};
@@ -298,8 +301,13 @@
await demuxer.destroyAsync();
// An intentional download stop, a teardown that crossed the header probe, is not a track the server has to
// normalize, so it is not published as one; the demuxer already reports it as a normal stop everywhere else.
if (!LuminaAudioPlayer.isDownloadAbort(error))
publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.directPlay);
if (LuminaAudioPlayer.isDownloadAbort(error))
return null;
// A transport failure says nothing about the format of the track either: the server must not normalize a file
// 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);
return null;
}
const configuration = demuxer.getConfiguration();
@@ -41,7 +41,7 @@
* durationInSeconds: manifest.durationInSeconds,
* shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused,
* events: host.events,
* onProgress: (progress) => host.reportProgress(progress.downloadedFraction),
* onProgress: (downloadedFraction) => host.reportProgress(downloadedFraction),
* onError: (error) => host.reportError(error)
* });
* // Fire and forget: the promise settles only when the loop stops, which is when the whole file is downloaded, the region
@@ -86,6 +86,24 @@
(function (LuminaAudioPlayer) {
'use strict';
/**
* The timeout, in milliseconds, of an explicit one shot range request. The loop request is deliberately not bounded by
* a total timeout, because it is an open ended transfer; a one shot read is a small, bounded window, so a server that
* never answers it is a failure rather than a reason to hold a seek open forever.
* @readonly
* @type {number}
*/
const ONE_SHOT_REQUEST_TIMEOUT_MS = 15000;
/**
* The lookahead, in bytes, within which a read is considered covered by the active loop request even though the loop
* has not received those bytes yet. It lets the first read of the loop wait for the bytes it is about to deliver,
* without making a seek at a distant offset wait for the sequential download to reach it.
* @readonly
* @type {number}
*/
const LOOP_IN_FLIGHT_LOOKAHEAD_BYTES = 256 * 1024;
/**
* Clamps a number into an inclusive range, through the shared helper on the namespace. The reference is resolved on
* every call rather than captured at load time, so this module does not depend on the load order of the util.
@@ -98,6 +116,15 @@
return LuminaAudioPlayer.clamp(value, minimum, maximum);
}
/**
* Builds the failure of a one shot range request that exceeded its timeout. It is a failed request, not an intentional
* abort, so the seek recovery does not retry it with another full timeout.
* @returns {LuminaAudioPlayer.PlayerError} The timeout failure.
*/
function createRangeTimeoutError() {
return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The range request timed out.', { reason: LuminaAudioPlayer.PlayerErrorReason.REQUEST_TIMEOUT });
}
/**
* Parses the total byte count of a Content-Length header.
* @param {string|null} value - The header value.
@@ -306,6 +333,8 @@
const size = Math.max(0, Math.floor(length));
if (size === 0)
return new Uint8Array(0);
// Touching segments are merged on append, so a requested window is always contained by exactly one segment.
// Finding that segment is enough; a window that crosses a boundary means the buffer has a real gap.
let segmentIndex = -1;
for (let index = 0; index < this.segments.length; index++) {
const candidate = this.segments[index];
@@ -321,6 +350,8 @@
if (segmentIndex === -1)
return null;
const segment = this.segments[segmentIndex];
// local is the offset of the requested window inside the segment. position is the segment offset of the chunk
// the loop is looking at, and filled is how many requested bytes were already copied.
const local = start - segment.start;
const result = new Uint8Array(size);
let filled = 0;
@@ -338,6 +369,8 @@
position += chunk.byteLength;
continue;
}
// Clip the chunk to the part that intersects the requested window: from is the first byte to copy out of
// this chunk, take is how many bytes still fit in the result.
const from = Math.max(0, local - position);
const take = Math.min(chunk.byteLength - from, size - filled);
result.set(chunk.subarray(from, from + take), filled);
@@ -348,6 +381,8 @@
}
position += chunk.byteLength;
}
// The segment promised the window by its length, but its chunks did not cover it. Treat it as a gap instead of
// returning a partially filled buffer the caller could play as if it were complete.
return null;
}
@@ -389,6 +424,8 @@
const segmentEnd = segment.start + segment.length;
if (segmentEnd <= position)
continue;
// The first segment that starts after the position is the gap that ends the run. Touching segments were
// merged on append, so no adjacency check is needed here.
if (segment.start > position)
break;
position = Math.max(position, segmentEnd);
@@ -431,7 +468,7 @@
* @param {string} [options.credentials] - The credentials mode of the request. Defaults to 'same-origin', so the session cookie is sent.
* @param {Object} [options.events] - The player event bus. When provided, the 'keep downloading while paused' preference is kept current from it.
* @param {boolean} [options.shouldKeepDownloadingWhilePaused] - The value of the 'keep downloading while paused' setting, seeded by the engine from host.getPreferences(). It is the initial value; later PREFERENCES_CHANGED events and setKeepDownloadingWhilePaused override it.
* @param {Function} [options.onProgress] - Called with the progress snapshot every time the buffer grows.
* @param {Function} [options.onProgress] - Called with the downloaded fraction every time the buffer grows. The full snapshot is only produced once, by the completion callback.
* @param {Function} [options.onComplete] - Called once when every byte of the file has been downloaded.
* @param {Function} [options.onError] - Called with a {@link LuminaAudioPlayer.PlayerError} when the download fails.
*/
@@ -471,8 +508,15 @@
this.isUnusable = false;
this.error = null;
// A downloader may have one loop request and, at most, an explicit one shot range request in flight at the same
// time, so every controller is tracked and an abort or a destroy cancels all of them, not just the newest.
// time. They are tracked apart: a pause or a pivot only cancels the loop request, while an abort or a destroy
// cancels every request, including an explicit range read such as the one a demuxer seek performs.
this.abortControllers = new Set();
this.oneShotControllers = new Set();
// The byte range of the loop request that is currently being read, so a seek aware source can tell whether a
// window it needs is already being fetched and does not need a duplicate one shot request. The cursor is the
// exclusive end of the bytes the loop has actually received, so a far window is not mistaken for in flight.
this.activeLoopRange = null;
this.activeLoopCursor = null;
this.loopPromise = null;
this.waiters = [];
this.unsubscribePreferences = null;
@@ -605,7 +649,7 @@
*/
abort() {
this.isAborted = true;
this.cancelActiveRequest();
this.abortAllRequests();
// The download is stopping and no byte will append until it is started again, so a reader that is waiting for a
// byte window is released with the aborted code instead of waiting forever.
this.rejectWaiters(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The track download was aborted.'));
@@ -619,7 +663,7 @@
async destroyAsync() {
this.destroyed = true;
this.isAborted = true;
this.cancelActiveRequest();
this.abortAllRequests();
if (this.unsubscribePreferences) {
this.unsubscribePreferences();
this.unsubscribePreferences = null;
@@ -648,6 +692,69 @@
return this.buffer.getRanges();
}
/**
* Checks whether the download buffer already holds a byte window, without allocating a range list. It is the
* allocation-free equivalent of searching getRanges and is safe to call on every demuxer read.
* @param {number} offset - The first byte of the window.
* @param {number} length - The length of the window, in bytes.
* @returns {boolean} True when the window is fully buffered.
*/
isRangeCovered(offset, length) {
const start = Math.max(0, Math.floor(offset));
const size = Math.max(0, Math.floor(length));
return this.buffer.covers(start, size);
}
/**
* Gets the byte position the download loop fetches from, or will fetch from once it is allowed to run.
* @returns {number} The loop target byte.
*/
getTargetByte() {
return this.targetByte;
}
/**
* Gets the exclusive end of the contiguous run of downloaded bytes that starts at or after an offset. A seek aware
* source uses it to start a range request after the bytes it already has instead of re-requesting a whole block.
* @param {number} offset - The byte to start from.
* @returns {number} The exclusive end of the contiguous run.
*/
getContiguousEnd(offset) {
return this.buffer.getContiguousEnd(offset);
}
/**
* Gets the progress of the active loop request, so a seek aware source can tell a slow loop from a stalled one.
* The range start and the received cursor are both reported, because a new request can start at the same cursor a previous one was abandoned at.
* @returns {{ start: number, cursor: number }|null} The request start and its received cursor, or null when no loop request is active.
*/
getLoopProgress() {
if (!this.activeLoopRange || this.activeLoopCursor === null)
return null;
return { start: this.activeLoopRange.start, cursor: this.activeLoopCursor };
}
/**
* Checks whether the loop request that is currently in flight is reading a range that covers a byte window. A seek
* aware source uses it to wait for the bytes that are already on their way instead of issuing a duplicate request.
* @param {number} offset - The first byte of the window.
* @param {number} length - The length of the window, in bytes.
* @returns {boolean} True when the active loop request covers the window.
*/
isRangeBeingFetched(offset, length) {
if (!this.activeLoopRange || this.activeLoopCursor === null || this.destroyed || this.isAborted)
return false;
const start = Math.max(0, Math.floor(offset));
const end = start + Math.max(0, Math.floor(length));
// The loop covers a window only when it starts at or before the window, the window has been reached by the
// received cursor or lies within the first fetch block of the loop, and the window is inside the response. A
// window far ahead of the cursor is fetched as a one-shot instead of waiting for the sequential download.
const reachable = Math.max(this.activeLoopCursor, this.activeLoopRange.start + LOOP_IN_FLIGHT_LOOKAHEAD_BYTES);
return this.activeLoopRange.start <= start
&& start <= reachable
&& end <= this.activeLoopRange.end;
}
/**
* Gets the downloaded time ranges, mapped through either the known total size and the duration or, when the size
* is not known yet, through the bytes themselves once the whole file is in the buffer.
@@ -666,6 +773,28 @@
}));
}
/**
* Checks whether a time position is already downloaded, without allocating a time range list. It maps the position
* to a byte through the same total size and duration proportion the time ranges use, and it matches the inclusive
* end of those ranges instead of testing one isolated byte.
* @param {number} seconds - The position to check, in seconds.
* @returns {boolean} True when the position is inside a stored run or at the inclusive end of one.
*/
coversTime(seconds) {
const value = Number(seconds);
const total = this.resolveTotalForMapping();
if (!Number.isFinite(value) || total === null || total <= 0 || this.duration <= 0)
return false;
const fraction = clamp(value / this.duration, 0, 1);
const byte = Math.floor(fraction * total);
if (this.buffer.covers(byte, 1))
return true;
// getTimeRanges maps the exclusive end of a byte range to an inclusive time end, so the player treats a
// position exactly at the end of a buffered run as buffered. Checking the end of the run that covers the
// previous byte reproduces that inclusive end without allocating the range list.
return byte > 0 && this.buffer.getContiguousEnd(byte - 1) >= byte;
}
/**
* Gets the fraction of the track that has been downloaded, between 0 and 1.
*
@@ -820,7 +949,7 @@
* @returns {Promise<Object>} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}.
*/
downloadRangeAsync(start, end) {
return this.performFetchAsync({ start, end });
return this.performFetchAsync({ start, end, isOneShot: true });
}
/**
@@ -830,7 +959,7 @@
* @returns {Promise<Object>} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}.
*/
downloadOpenEndedAsync(start) {
return this.performFetchAsync({ start, openEnded: true });
return this.performFetchAsync({ start, openEnded: true, isOneShot: true });
}
/**
@@ -840,7 +969,7 @@
* @returns {Promise<Object>} The outcome, per {@link LuminaAudioPlayer.TrackDownloader#performFetchAsync}.
*/
downloadSuffixAsync(length) {
return this.performFetchAsync({ suffix: length });
return this.performFetchAsync({ suffix: length, isOneShot: true });
}
//+======================================================================================+
@@ -888,13 +1017,33 @@
}
/**
* Cancels every in flight request through its AbortController. A pause, a pivot, an abort and a destroy all route
* here, so no request, and no connection, is left open behind one that another controller replaced.
* Cancels the in flight requests of the download loop through their AbortControllers. A pause, a resume and a
* pivot route here, and they deliberately leave explicit one shot range requests alone: a demuxer that is scanning
* for a seek target must not be interrupted by a pause that happens while the scan is running.
*/
cancelActiveRequest() {
if (this.abortControllers.size === 0)
this.abortRequests(this.abortControllers);
}
/**
* Cancels every in flight request, including explicit one shot range requests. An intentional abort, a destroy and
* the start of a new seek route here, so no stale read and no connection is left behind.
*/
abortAllRequests() {
this.activeLoopRange = null;
this.activeLoopCursor = null;
this.abortRequests(this.abortControllers);
this.abortRequests(this.oneShotControllers);
}
/**
* Aborts every controller in one of the request sets.
* @param {Set<AbortController>} controllers - The controllers to abort.
*/
abortRequests(controllers) {
if (controllers.size === 0)
return;
for (const controller of [...this.abortControllers]) {
for (const controller of [...controllers]) {
try {
controller.abort();
} catch (error) {
@@ -995,17 +1144,37 @@
* @param {number} [spec.suffix] - The number of trailing bytes to request.
* @param {boolean} [spec.openEnded] - True to request an open ended range, from start to the end of the file.
* @param {boolean} [spec.stopOnPause] - True when a paused player must stop this request at the next chunk. The download loop sets it; a one shot range request does not, so an explicit request always completes.
* @param {boolean} [spec.isOneShot] - True for an explicit range request. Such a request is tracked apart from the
* loop request and is not cancelled by a pause or a pivot, only by abort() or destroyAsync().
* @returns {Promise<Object>} The outcome, one of: <c>{ isFailed: true, error }</c> when the request failed, <c>{ isAborted: true }</c> when it was aborted, <c>{ isDestroyed: true }</c> when the downloader was destroyed, <c>{ isSatisfied: true }</c> when the range was already satisfied, or <c>{ isAborted, isFailed: false, isDestroyed, isStopped }</c> for a read that ended. It never rejects.
*/
async performFetchAsync(spec = {}) {
if (this.destroyed)
return { isDestroyed: true, isAborted: false, isFailed: false };
// An explicit range request must not reopen a request after an intentional abort. startAsync clears the aborted
// state before it starts the loop again, so a request issued for a live timeline still runs.
if (this.isAborted)
return { isAborted: true, isFailed: false, isDestroyed: false };
if (this.fetchImpl === null || this.url === '') {
this.isUnusable = true;
return { isFailed: true, error: new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The download request could not be built.') };
}
const controller = new AbortController();
this.abortControllers.add(controller);
// An explicit range request is not cancelled by a pause or a pivot, because a seek scan must be able to read
// its windows while playback is paused. Only abort(), destroyAsync() or its own timeout cancel it.
const controllers = spec.isOneShot === true ? this.oneShotControllers : this.abortControllers;
controllers.add(controller);
let didTimeout = false;
const timeoutTimer = spec.isOneShot === true
? setTimeout(() => {
didTimeout = true;
try {
controller.abort();
} catch (error) {
console.debug('Audio player: the timed out range request could not be aborted.', error);
}
}, ONE_SHOT_REQUEST_TIMEOUT_MS)
: null;
let response = null;
try {
response = await this.fetchImpl(this.url, {
@@ -1022,8 +1191,44 @@
return { isAborted: false, isFailed: false, isDestroyed: this.destroyed, isSatisfied: true };
}
this.noteTotal(resolved.total);
return await this.readResponseIntoBufferAsync(response, resolved, controller, spec.stopOnPause === true, spec.openEnded === true);
if (spec.isOneShot !== true) {
// The loop request is open ended in practice, and this is the range it is actually reading. A window
// inside it is already being fetched, so a seek aware source can simply wait for it.
this.activeLoopRange = {
start: resolved.start,
end: resolved.endInclusive === null ? Number.POSITIVE_INFINITY : resolved.endInclusive
};
this.activeLoopCursor = resolved.start;
}
// A bounded one shot request keeps the exact window it asked for, so a server or proxy that ignores Range
// and answers with a 200 cannot make the read store the whole resource. The window is only used for a 200
// response; a 206 already carries its own range.
let readWindow = null;
if (spec.isOneShot === true && Number.isFinite(Number(spec.start)) && Number.isFinite(Number(spec.end))) {
const windowStart = Math.max(0, Math.floor(Number(spec.start)));
const windowEnd = Math.max(windowStart, Math.floor(Number(spec.end)));
readWindow = { start: windowStart, length: windowEnd - windowStart + 1 };
} else if (spec.isOneShot === true && Number.isFinite(Number(spec.suffix)) && resolved.total !== null) {
const windowLength = Math.min(resolved.total, Math.max(1, Math.floor(Number(spec.suffix))));
readWindow = { start: resolved.total - windowLength, length: windowLength };
}
const outcome = await this.readResponseIntoBufferAsync(response, resolved, controller, spec.stopOnPause === true, spec.openEnded === true, readWindow, spec.isOneShot !== true);
// A timeout that fires during the body read is caught inside the read and reported as an abort. It is still
// a failed request, so it is mapped to the same timeout failure as a timeout before the body started, and
// a seek does not retry it with another full deadline.
if (didTimeout && outcome.isAborted) {
this.discardResponseBody(response);
return { isFailed: true, isAborted: false, isDestroyed: this.destroyed, error: createRangeTimeoutError() };
}
return outcome;
} catch (error) {
// A timeout is not an intentional stop: it is a failed request, so a seek does not retry it with another
// full timeout and the bar does not stay in its loading state for double the deadline. The check comes
// first because an abort can surface as an AbortError or as a body read error, depending on the browser.
if (didTimeout) {
this.discardResponseBody(response);
return { isFailed: true, isAborted: false, isDestroyed: this.destroyed, error: createRangeTimeoutError() };
}
if (LuminaAudioPlayer.isAbortError(error))
return { isAborted: true, isFailed: false, isDestroyed: this.destroyed };
// The failure left the response body unread, so it is discarded and the request is aborted to release the
@@ -1037,7 +1242,13 @@
}
return { isFailed: true, error: LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED) };
} finally {
this.abortControllers.delete(controller);
if (timeoutTimer !== null)
clearTimeout(timeoutTimer);
if (spec.isOneShot !== true) {
this.activeLoopRange = null;
this.activeLoopCursor = null;
}
controllers.delete(controller);
}
}
@@ -1122,16 +1333,24 @@
* @param {AbortController} controller - The controller of the request, aborted when the loop must stop.
* @param {boolean} stopOnPause - True when a paused player must stop the read at the next chunk boundary.
* @param {boolean} openEnded - True when the request asked for a range that runs to the end of the file. Such a read is driven to the end of the body, and that end proves the end of the file, rather than the range the response happens to declare.
* @param {{ start: number, length: number }|null} [readWindow] - The bounded window a one shot request asked for. When the server answered with a 200 instead of a range, the body is read up to the end of this window, only the bytes of the window are stored, and the rest of the body is discarded.
* @param {boolean} [isLoopRequest=false] - True when this read belongs to the download loop. The received cursor of the loop is advanced per chunk so a seek aware source only waits for windows the loop is actually reaching.
* @returns {Promise<Object>} The outcome of the read.
* @throws {LuminaAudioPlayer.PlayerError} When the response carries no readable body.
*/
async readResponseIntoBufferAsync(response, range, controller, stopOnPause, openEnded) {
async readResponseIntoBufferAsync(response, range, controller, stopOnPause, openEnded, readWindow = null, isLoopRequest = false) {
if (!response.body || typeof response.body.getReader !== 'function')
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The stream response carried no readable body.');
const reader = response.body.getReader();
let offset = range.start;
if (isLoopRequest)
this.activeLoopCursor = offset;
let isStopped = false;
let hasReachedEnd = false;
// A 200 response means the server ignored the range. A bounded one shot request then stores only its own window
// and can stop reading as soon as that window is complete, instead of pulling the whole resource into memory.
const isFullResourceWindow = readWindow !== null && range.endInclusive === null;
const readWindowEnd = readWindow !== null ? readWindow.start + readWindow.length : null;
// True when a bounded request read its whole declared range and stopped before the body ended, so any remaining
// bytes are discarded. An open ended request instead reads the body to its end, because that end, and not the
// range the response happens to declare, is the only signal that proves the end of the file.
@@ -1159,15 +1378,35 @@
const value = result.value;
if (!value || value.byteLength === 0)
continue;
this.buffer.append(offset, value);
offset += value.byteLength;
this.notifyProgress();
this.resolveWaiters();
// A bounded request stops once it has read the range it asked for, while an open ended request reads on
// to the end of the body, so a capped response is not mistaken for the end of the file.
if (!openEnded && range.endInclusive !== null && offset > range.endInclusive) {
isStoppedAtRangeEnd = true;
break;
if (isFullResourceWindow) {
// The body starts at the beginning of the resource, so the bytes before the requested window are
// consumed and dropped, and only the requested window is stored, at its absolute offset.
const chunkStart = offset;
const from = Math.max(chunkStart, readWindow.start);
const to = Math.min(chunkStart + value.byteLength, readWindowEnd);
if (to > from) {
this.buffer.append(from, value.subarray(from - chunkStart, to - chunkStart));
this.notifyProgress();
this.resolveWaiters();
}
offset += value.byteLength;
if (offset >= readWindowEnd) {
isStoppedAtRangeEnd = true;
break;
}
} else {
this.buffer.append(offset, value);
offset += value.byteLength;
if (isLoopRequest)
this.activeLoopCursor = offset;
this.notifyProgress();
this.resolveWaiters();
// A bounded request stops once it has read the range it asked for, while an open ended request reads
// on to the end of the body, so a capped response is not mistaken for the end of the file.
if (!openEnded && range.endInclusive !== null && offset > range.endInclusive) {
isStoppedAtRangeEnd = true;
break;
}
}
}
} finally {
@@ -1264,7 +1503,9 @@
if (!this.onProgress)
return;
try {
this.onProgress(this.getProgress());
// Only the fraction is built per chunk: the full snapshot allocates range lists and is reserved for the
// completion callback, where it is produced once per track.
this.onProgress(this.getDownloadedFraction());
} catch (error) {
console.error('Audio player: the download progress callback threw.', error);
}
@@ -10,7 +10,9 @@
* --------------------
* An engine is created by a factory that receives the engine host (see below) and returns an object
* with these methods, all of them returning a Promise:
* - loadAsync(descriptor): prepares the resources of a track (opens its stream, configures a decoder).
* - loadAsync(descriptor, options): prepares the resources of a track (opens its stream, configures a decoder).
* options.keepBuffering keeps a loading state the player handed to the load, used by an automatic continuation so the
* teardown of the previous track does not clear it during the end gap.
* - playAsync(): starts, or resumes, audible playback.
* - pauseAsync(): suspends audible playback, keeping the current position.
* - seekAsync(seconds): moves the playhead to the given position, in seconds, fetching the range of that position
@@ -19,15 +21,38 @@
* - getBufferedTimeRanges(): the time ranges, in seconds, the engine already downloaded, as a list of objects with
* a 'start' and an 'end'. It is optional: an engine that does not implement it makes the player unable to tell
* whether a seek target is buffered, in which case the player never shows a loading state for a seek.
* - discardCurrentAsync() (optional): releases the currently prepared track without destroying the engine, so a stop
* during an automatic continuation does not leave the track it started loaded behind an idle player.
* - destroyAsync(): releases every resource the engine holds, including any audio context.
*
* The engine host
* ---------------
* The factory also receives a host object that the engine uses to talk back to the controller, so
* that the controller stays the single source of truth:
* - host.events: the player event bus, for {@link LuminaAudioPlayer.PlayerEvent} values the engine emits itself.
* - host.events: the player event bus, for {@link LuminaAudioPlayer.PlayerEvent} values the engine emits itself. It is
* also the inbound channel: an engine and the renderer subscribe to PREFERENCES_CHANGED to follow a gapless or
* ReplayGain preference that changes while a track is playing.
* - host.getPreferences(): the playback preferences of the user the player currently holds, for example the
* 'keep downloading while paused' setting an engine's downloader honors.
* - host.getConfiguration(): the endpoint configuration of the player, so an engine never keeps a second copy of it.
* - host.fetchJsonAsync(url, signal, label): the player's JSON transport. The optional signal cancels the request, the
* label describes it in the failure log, and an expired session redirect is followed to the sign in page and reported
* through the player's REDIRECTED marker, so an engine request behaves like the player's other background requests.
* - host.getCapabilityDetector(): the browser capability detector of the player, so an engine does not run a second
* capability detection.
* - host.getNextDescriptor(): { entryId, descriptor } of the queue entry that follows the current one, or null at the
* end of the queue. It is the player's own queue cursor, so an engine never re-implements queue traversal or picks
* the wrong repeated track.
* - host.advanceQueueTo(entryId): moves the player queue cursor to the entry with that identity without starting
* playback, which an engine uses for a gapless transition whose audio is already scheduled immediately after the current
* track. The advance is refused when the identity is no longer part of the queue, so the bar never describes a track
* that is not playing. A linear advance, a wrap and a reordered queue all use this same commit.
* - host.requestNextTrackAsync(reason): asks the player to start the next queue entry through its own play path, which
* owns the player state, the pause intent and the capability gate. An engine uses it when a gapless handoff could not
* be prepared, instead of starting a playback session itself. The returned Promise<boolean> resolves true when the
* player took ownership of the transition, including a load it will report as failed, and false when it declined the
* request because the player is paused, stopped, or has no next entry. An engine must not report an end for a
* transition the player owns, and keeps the end it just reported when the promise resolves false.
* - host.reportTime(currentTime, duration): reports the playhead and the known duration.
* - host.reportDuration(duration): reports a duration discovered after loading.
* - host.reportProgress(downloadedFraction): reports how much of the track has been downloaded, between 0 and 1.
@@ -42,9 +67,10 @@
*
* Registering and selecting an engine
* -----------------------------------
* Engines are registered on a registry by name, and the player runs the engine selected by name. The silent engine
* is registered under NULL_ENGINE_NAME and is the default, so the player is usable before the real pipeline exists.
* The singleton is created automatically when the module loads, so the way to plug a real engine into the running
* Engines are registered on a registry by name, and the player runs the engine selected by name. The silent engine is
* registered under NULL_ENGINE_NAME and is the default of a bare player, but the shipped composition installs the media
* pipeline engine when that module loads and selects it, so the running application plays through the pipeline. The
* singleton is created automatically when the core module loads, so the way to plug a different engine into the running
* application is the instance seam:
* - window.LuminaAudioPlayer.instance.registerEngine(name, factory) registers a factory of the shape (host) => engine.
* - window.LuminaAudioPlayer.instance.useEngine(name) selects a registered engine; it takes effect on the next load,
@@ -66,10 +92,11 @@
/**
* An engine that fulfills the engine interface without producing any audio.
*
* It is the default engine of the core module, so that the control API, the state machine, the
* lifecycle and the bar are fully callable before the download, decode and render pipeline is
* wired up. It tracks a playhead so that a seek, a pause and a resume report the position the
* player expects, but it never loads, decodes or plays a byte.
* It is the default engine of a bare player, so that the control API, the state machine, the
* lifecycle and the bar are fully callable before, or without, the media pipeline. The shipped
* composition selects the pipeline when that module loads. This engine tracks a playhead so that
* a seek, a pause and a resume report the position the player expects, but it never loads,
* decodes or plays a byte.
*/
class NullPlayerEngine {
/**
@@ -73,7 +73,20 @@
// stopped with no gap left to fill. Published by the download engine and recognized by the demuxer byte source,
// 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'
WINDOW_UNAVAILABLE: 'window-unavailable',
// 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.
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.
LOAD_SUPERSEDED: 'load-superseded',
// The session expired while a manifest was requested, and the player is already navigating to the sign in page.
// The player ignores it, because it is an expected outcome of an expired session, not a playback failure.
SESSION_EXPIRED: 'session-expired'
});
/**
@@ -0,0 +1,321 @@
/**
* Playback manifest client of the audio player.
*
* It owns the transport concerns of a playback manifest: expanding the manifest route template with the Ids of a play
* descriptor, appending the capability query, applying the request timeout, following the player's redirect policy, and
* validating the stream path before a request that sends the session cookie is made. The playback engine and the later
* normalized delivery pipeline both consume it, so the route, capability and same-origin rules are defined once.
*/
(function (LuminaAudioPlayer) {
'use strict';
/**
* The timeout, in milliseconds, of a playback manifest request.
* @readonly
* @type {number}
*/
const MANIFEST_REQUEST_TIMEOUT_MS = 20000;
/**
* Checks whether a value is a Guid, the only form the manifest route accepts for its Ids.
* @param {*} value - The value to check.
* @returns {boolean} True when the value is a Guid string.
*/
function isGuid(value) {
return typeof value === 'string'
&& /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
}
/**
* Gets the origin this module resolves relative URLs against. The page origin is used in a browser; a fixed local
* origin keeps the route and origin checks testable in a host without a DOM.
* @returns {string} The base origin.
*/
function getBaseOrigin() {
return typeof window !== 'undefined' && window.location && window.location.origin
? window.location.origin
: 'http://localhost';
}
/**
* Checks whether the module can compare a URL against the page origin.
* @returns {boolean} True when a page origin is available.
*/
function hasWindowOrigin() {
return typeof window !== 'undefined' && !!window.location && !!window.location.origin;
}
/**
* Resolves and validates a path that a request carrying the session cookie will fetch.
*
* The value is built by the server, but it is validated again here as defense in depth: it must be a root relative
* path on this origin, with no backslash, control character, fragment, userinfo, dot segment, or encoded path
* separator that a browser could normalize into another location. The resolved absolute URL is returned, pinned to
* this origin by construction, so a base element can never redirect the fetch to another origin.
* @param {*} value - The path to validate.
* @returns {{ href: string, url: URL }} The validated resolved path and its parsed URL.
* @throws {LuminaAudioPlayer.PlayerError} When the path is not a safe same-origin root relative path.
*/
function resolveSameOriginUrl(value) {
if (typeof value !== 'string' || value.length === 0)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The request carries no path.');
if (!value.startsWith('/') || value.startsWith('//'))
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path is not a root relative path.');
if (/[\u0000-\u001f\u007f\\#]/.test(value))
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path carries a forbidden character.');
const queryIndex = value.indexOf('?');
const path = queryIndex >= 0 ? value.slice(0, queryIndex) : value;
// Decode every segment before judging it. The browser normalizes %2e%2e, %2f and %5c after the string is accepted,
// so checking only the raw text would let an encoded separator or dot segment through.
for (const segment of path.split('/')) {
if (segment === '')
continue;
let decoded;
try {
decoded = decodeURIComponent(segment);
} catch (error) {
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path carries an invalid escape.', { cause: error });
}
if (decoded === '.' || decoded === '..' || decoded.includes('/') || decoded.includes('\\')
|| /[\u0000-\u001f\u007f]/.test(decoded))
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path carries a traversal segment.');
}
// Resolve last, so the returned href is absolute and a base element cannot change where the fetch goes. A host
// without a DOM uses the synthetic base only for parsing and keeps the raw path.
let resolved;
try {
resolved = new URL(value, getBaseOrigin());
} catch (error) {
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path is not a valid URL.', { cause: error });
}
// A request with credentials or a non-http scheme is not one this player is allowed to make, and an origin other
// than the page origin would send the session cookie somewhere it must never go.
if ((resolved.protocol !== 'http:' && resolved.protocol !== 'https:')
|| (hasWindowOrigin() && resolved.origin !== window.location.origin)
|| resolved.username !== ''
|| resolved.password !== '')
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The path is not on this origin.');
return { href: hasWindowOrigin() ? resolved.href : value, url: resolved };
}
/**
* Checks that a resolved stream path matches the stream route template this application emitted and belongs to the
* expected track and library. The template is the single source of truth for the route's static segments, their order
* and its placeholders, so a server route rename or an inserted segment does not need a matching client edit. The
* same-origin check alone is not enough: the session cookie and the Range header are sent before the response is
* inspected, so a state changing GET route on this origin must never be reachable as a stream.
* @param {URL} url - The resolved stream URL.
* @param {Object} descriptor - The play descriptor the manifest belongs to.
* @param {Object} configuration - The endpoints configuration of the player.
* @throws {LuminaAudioPlayer.PlayerError} When the route template is missing, is on another origin, or the path does not match the route or the expected track and library Ids.
*/
function validateStreamRoute(url, descriptor, configuration) {
const templateValue = configuration && configuration.streamTrackRouteTemplate;
if (typeof templateValue !== 'string' || templateValue.length === 0)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The 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 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 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 stream path does not match the stream route.');
for (let index = 0; index < templateSegments.length; index++) {
let templateSegment;
try {
// The URL parser percent-encodes braces, so a template segment has to be decoded before it can be recognized as a placeholder.
templateSegment = decodeURIComponent(templateSegments[index]);
} catch (error) {
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream route template carries an invalid escape.', { cause: error });
}
const placeholder = /^\{([A-Za-z0-9_]+)\}$/.exec(templateSegment);
if (placeholder) {
const name = placeholder[1];
if (!Object.prototype.hasOwnProperty.call(expectedIds, name))
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream 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 });
const actual = streamSegments[index];
// The path must describe the track of this descriptor, not merely another track of the same library.
if (!isGuid(actual) || actual.toLowerCase() !== expected.toLowerCase())
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream path does not belong to the expected track.');
continue;
}
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 stream path carries an invalid escape.', { cause: error });
}
if (templateSegment !== actualSegment)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The stream path does not match the stream 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 stream path does not belong to the expected library.');
}
/**
* Resolves the stream path of a playback manifest into the URL the player fetches, after checking that it points at
* the stream route of the expected track and library.
* @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.
* @returns {string} The validated resolved stream URL.
* @throws {LuminaAudioPlayer.PlayerError} When the manifest carries no safe stream path or the path is not the
* stream route of the expected track and library.
*/
function resolveStreamUrl(manifest, descriptor, configuration) {
const resolved = resolveSameOriginUrl(manifest && manifest.streamPath);
validateStreamRoute(resolved.url, descriptor, configuration);
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.
* @param {Object} descriptor - The play descriptor of the track.
* @param {string} capabilities - The comma separated container and codec capability list, or an empty string.
* @returns {string} The absolute manifest URL, pinned to this origin.
* @throws {LuminaAudioPlayer.PlayerError} When the descriptor or the configuration is incomplete, or the endpoint is not on this origin.
*/
function buildManifestUrl(configuration, descriptor, capabilities) {
const template = configuration && configuration.getPlaybackManifestUrl;
if (!template)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest endpoint is not configured.');
const ids = {
artistId: descriptor.artistId,
albumId: descriptor.albumId,
trackId: descriptor.trackId,
libraryId: descriptor.libraryId
};
for (const name of Object.keys(ids)) {
if (!ids[name])
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, `The play descriptor carries no ${name}.`, { field: name });
// The manifest route only accepts Guids, and a value that is not a Guid must never be interpolated into a path the browser resolves against this origin.
if (!isGuid(ids[name]))
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, `The play descriptor carries an invalid ${name}.`, { field: name });
}
let url = String(template)
.split('{artistId}').join(encodeURIComponent(ids.artistId))
.split('{albumId}').join(encodeURIComponent(ids.albumId))
.split('{trackId}').join(encodeURIComponent(ids.trackId));
const separator = url.includes('?') ? '&' : '?';
url = `${url}${separator}libraryId=${encodeURIComponent(ids.libraryId)}`;
if (capabilities)
url = `${url}&capabilities=${encodeURIComponent(capabilities)}`;
// The manifest template is request derived, and the manifest is the response that controls the next fetches, so
// it is resolved against this origin and a different origin is refused instead of being requested.
let resolved;
try {
resolved = new URL(url, getBaseOrigin());
} catch (error) {
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest endpoint is not a valid URL.', { cause: error });
}
if ((resolved.protocol !== 'http:' && resolved.protocol !== 'https:')
|| (hasWindowOrigin() && resolved.origin !== window.location.origin)
|| resolved.username !== ''
|| resolved.password !== '')
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest endpoint is not on this origin.');
return resolved.href;
}
/**
* Creates an AbortSignal for a manifest request that aborts on the external signal or after the manifest timeout.
* @param {AbortSignal} [externalSignal] - The signal of the caller, for example the load or prefetch signal.
* @returns {{ signal: AbortSignal|undefined, dispose: Function }} The signal to use, and the cleanup that clears the timeout and the external listener.
*/
function createTimedRequestSignal(externalSignal) {
// A host without AbortController cannot combine a timeout with the caller's signal, so it passes that signal through. Cancellation still belongs to the caller in that case.
if (typeof AbortController !== 'function')
return { signal: externalSignal, dispose: () => {} };
const controller = new AbortController();
const abort = () => {
try {
controller.abort();
} catch (error) {
console.debug('Audio player: the manifest request could not be aborted.', error);
}
};
const onExternalAbort = () => abort();
if (externalSignal) {
if (externalSignal.aborted)
abort();
else
// A cancelled load or prefetch must cancel the manifest request too, otherwise a superseded prefetch keeps
// a connection and its timeout alive.
externalSignal.addEventListener('abort', onExternalAbort, { once: true });
}
// A manifest that never answers must not hold a load forever. The deadline is independent of the caller's signal, so a stalled server cannot leave the player loading indefinitely.
const timer = setTimeout(abort, MANIFEST_REQUEST_TIMEOUT_MS);
return {
signal: controller.signal,
dispose: () => {
clearTimeout(timer);
// Remove the listener on both success and failure, so a long lived external signal does not retain this request after it settled.
if (externalSignal)
externalSignal.removeEventListener('abort', onExternalAbort);
}
};
}
/**
* Fetches the playback manifest of a track from the web application.
* @param {Object} options - The request options.
* @param {Object} options.configuration - The endpoints configuration of the player.
* @param {Object} options.descriptor - The play descriptor of the track.
* @param {string} options.capabilities - The comma separated capability list, or an empty string.
* @param {Function} options.transport - The JSON transport, in the shape of the player's fetchJsonAsync. It receives the
* URL, an optional signal, a label and a request options object with <c>redirect: 'manual'</c>, so a redirect target is validated before the browser follows it.
* @param {AbortSignal} [options.signal] - An optional signal that cancels the request, used by a cancelled prefetch.
* @returns {Promise<Object>} The playback manifest.
* @throws {LuminaAudioPlayer.PlayerError} When the descriptor is incomplete, the session expired, or the manifest could not be read.
*/
async function fetchPlaybackManifestAsync(options) {
const settings = options || {};
const transport = settings.transport;
if (typeof transport !== 'function')
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest transport is not configured.');
const url = buildManifestUrl(settings.configuration, settings.descriptor, settings.capabilities || '');
const request = createTimedRequestSignal(settings.signal);
try {
let data;
try {
data = await transport(url, request.signal, 'a playback manifest request', { redirect: 'manual' });
} catch (error) {
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest of the track could not be requested.', { cause: error });
}
if (data === LuminaAudioPlayer.REDIRECTED)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The session expired while the playback manifest was requested.', { reason: LuminaAudioPlayer.PlayerErrorReason.SESSION_EXPIRED });
if (data === undefined)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest of the track could not be requested.');
if (!data || typeof data !== 'object')
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The playback manifest of the track carried no data.');
return data;
} finally {
request.dispose();
}
}
LuminaAudioPlayer.resolveStreamUrl = resolveStreamUrl;
LuminaAudioPlayer.fetchPlaybackManifestAsync = fetchPlaybackManifestAsync;
})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {});
@@ -0,0 +1,352 @@
/**
* Seek-aware byte source of the audio player pipeline.
*
* It fetches an uncovered demuxer window on demand, coalesced into an aligned block, while a seek or a gapless prefetch
* needs bytes the regular download loop is not fetching, and it never issues a duplicate request for a window the running loop is already reading.
*/
(function (LuminaAudioPlayer) {
'use strict';
/**
* The block size, in bytes, of an on-demand range fetch. A demuxer seek reads small windows one after another, so a
* request per window would pay a network round trip for each read; the windows are coalesced into aligned blocks of
* this size, which are still bounded and are stored in the same buffer the demuxer reads from.
* @readonly
* @type {number}
*/
const SEEK_FETCH_BLOCK_BYTES = 256 * 1024;
/**
* How long the received cursor of the download loop may stay unchanged before a read that is waiting for that loop
* falls back to a one-shot range request, in milliseconds. A loop response that sends headers and then stalls has no
* deadline of its own, so without this bound a seek near the loop frontier would wait until the user resumes or aborts.
* @readonly
* @type {number}
*/
const LOOP_STALL_FALLBACK_MS = 3000;
/**
* How often the progress of the download loop is checked while a read waits for it, in milliseconds.
* @readonly
* @type {number}
*/
const LOOP_STALL_POLL_MS = 100;
/**
* A byte source for a demuxer that fetches an uncovered window on demand instead of waiting for a download loop.
*
* It serves two situations. A demuxer seek is not a sequential read: OGG binary-searches the byte range, and MP3 and
* AAC scan forward from an estimate that may lie below the target. Those reads can fall into a gap below the byte
* target the download loop is fetching, and a plain downloader read would then wait for a window the loop never
* fetches, in practice for the rest of the file. A gapless prefetch has no download loop at all, by design, so that it
* never runs a second open-ended download next to the current one. In both cases an uncovered window is fetched as a
* one-shot bounded range, coalesced with its neighbours into an aligned block of a few hundred kilobytes, and stored
* in the download buffer, so the demuxer can continue immediately and a later sequential read finds the same bytes in
* the buffer instead of fetching them again. A window that the running download loop is already fetching is awaited
* instead of being requested twice. The on-demand mode is switched off when a seek has scheduled its first frame, or
* when a prefetch is handed over and its download loop starts.
*/
class SeekAwareByteSource {
/**
* Creates an instance of SeekAwareByteSource.
* @param {LuminaAudioPlayer.TrackDownloader} downloader - The downloader of the track.
*/
constructor(downloader) {
this.downloader = downloader;
// The regular byte source owns the end-of-stream behavior of a downloader read: a window that reaches past the
// end is shortened, and a window that can no longer be filled reads as the end of the file. Delegating to it
// keeps that behavior identical whether the window came from a one-shot seek fetch or from the download loop.
this.standard = new LuminaAudioPlayer.DemuxerByteSource(downloader);
this.isSeeking = false;
this.destroyed = false;
// Incremented by every new seek, so a read that is still waiting for a previous seek can tell that a newer seek
// owns the timeline and release the demuxer operation instead of fetching a window for the outdated one.
this.seekGeneration = 0;
}
/**
* Sets whether the demuxer is currently resolving a seek, which enables the on-demand range fetch. Every new seek
* starts a new generation, which invalidates the reads of the seek it replaced.
* @param {boolean} value - True while a seek is being resolved.
*/
setSeeking(value) {
const next = value === true;
if (next)
this.seekGeneration += 1;
this.isSeeking = next;
}
/**
* Gets the total size of the stream, when the downloader knows it.
* @returns {number|null} The length in bytes, or null.
*/
getLength() {
return this.standard.getLength();
}
/**
* Reads a window of bytes, fetching it with a one-shot range request when a seek needs a window below the byte
* target of the download loop.
* @param {number} offset - The first byte to read.
* @param {number} length - The number of bytes to read.
* @returns {Promise<Uint8Array>} The bytes, possibly shorter at the end of the stream.
* @throws {LuminaAudioPlayer.PlayerError} When the seek range cannot be fetched, or the read was aborted.
*/
async readAsync(offset, length) {
if (this.destroyed)
return new Uint8Array(0);
const seekGeneration = this.seekGeneration;
if (this.isDownloaderAborted())
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.');
const start = Math.max(0, Math.floor(offset));
let size = Math.max(0, Math.floor(length));
if (size === 0)
return new Uint8Array(0);
const total = this.downloader.getTotalBytes();
if (total !== null) {
if (start >= total)
return new Uint8Array(0);
size = Math.min(size, total - start);
}
const targetByte = typeof this.downloader.getTargetByte === 'function'
? this.downloader.getTargetByte()
: (Number.isInteger(this.downloader.targetByte) ? this.downloader.targetByte : null);
// The read offset alone never ends the on-demand mode: a demuxer seek can probe far ahead of the seek target, and
// the loop will not reach such a window for a long time. The engine clears the mode once the target's first frame
// is scheduled; until then isWindowCovered and isRangeBeingFetched decide whether a one-shot is needed, and reads
// behind the loop frontier stay on demand through isBelowLoopTarget.
const isBelowLoopTarget = targetByte !== null && start < targetByte;
// Serve the read from the cheapest source that can complete it: the buffer, the download loop that is already
// reading the same region, or a bounded one-shot. The order matters: a covered read must not touch the network,
// and a loop-covered read must not be requested twice.
if ((this.isSeeking || isBelowLoopTarget) && !this.isWindowCovered(start, size)) {
if (this.isLoopFetching(start, size)) {
// The regular read registers an event driven waiter that resolves the moment the loop stores the window,
// so a normal delivery adds no polling delay. A watchdog races it only to bound a loop that stalls or is replaced by a newer seek.
if (typeof this.downloader.getLoopProgress === 'function')
return this.readWhileLoopAsync(start, size, seekGeneration, total);
return this.standard.readAsync(start, size);
}
return this.fetchOnDemandAsync(start, size, total, seekGeneration);
}
return this.standard.readAsync(start, size);
}
/**
* Reads a window the download loop is already fetching, racing the regular event driven read against a watchdog
* for a stalled, aborted or superseded loop. The read wins immediately when the loop delivers the window.
* @param {number} start - The first byte of the window.
* @param {number} size - The number of bytes of the window.
* @param {number} seekGeneration - The seek generation the read belongs to.
* @param {number|null} total - The total size of the stream, or null when it is unknown.
* @returns {Promise<Uint8Array>} The bytes, possibly shorter at the end of the stream.
*/
async readWhileLoopAsync(start, size, seekGeneration, total) {
const readPromise = this.standard.readAsync(start, size);
const readOutcome = readPromise.then(
(bytes) => ({ isRead: true, bytes }),
(error) => ({ isRead: false, error })
);
const watchdog = this.createLoopStallWatchdog(start, size, seekGeneration);
let result;
try {
result = await Promise.race([
readOutcome,
watchdog.promise.then((reason) => ({ isWatchdog: true, reason }))
]);
} finally {
watchdog.dispose();
}
if (result.isRead)
return result.bytes;
if (!result.isWatchdog) {
// A read that the loop can no longer fill falls back to a one-shot, exactly like a watchdog that saw the
// loop stop fetching. Any other failure, including an abort, propagates.
if (!result.error)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The seek range request failed.');
if (LuminaAudioPlayer.isDownloadAbort(result.error)
|| !result.error.details
|| result.error.details.reason !== LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE)
throw result.error;
if (this.isDownloaderAborted() || this.seekGeneration !== seekGeneration)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.');
if (this.isWindowCovered(start, size))
return this.standard.readAsync(start, size);
return this.fetchOnDemandAsync(start, size, total, seekGeneration);
}
// The regular read stays pending until the fallback one-shot stores the same window, or until the downloader is
// torn down and rejects it. It must not become an unhandled rejection in either case.
readPromise.catch(() => {});
if (result.reason === 'aborted' || result.reason === 'superseded'
|| this.isDownloaderAborted() || this.seekGeneration !== seekGeneration)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.');
if (this.isWindowCovered(start, size))
return this.standard.readAsync(start, size);
return this.fetchOnDemandAsync(start, size, total, seekGeneration);
}
/**
* Checks whether the download buffer already holds the whole requested window, without allocating a range list.
* @param {number} start - The first byte of the window.
* @param {number} size - The number of bytes of the window.
* @returns {boolean} True when the window is fully buffered.
*/
isWindowCovered(start, size) {
if (typeof this.downloader.isRangeCovered === 'function')
return this.downloader.isRangeCovered(start, size);
const end = start + size;
return this.downloader.getRanges().some((range) => range.start <= start && range.end >= end);
}
/**
* Checks whether the download loop is already reading a range that covers the window, in which case the read waits for those bytes instead of issuing a duplicate request.
* @param {number} start - The first byte of the window.
* @param {number} size - The number of bytes of the window.
* @returns {boolean} True when the active loop request covers the window.
*/
isLoopFetching(start, size) {
return typeof this.downloader.isRangeBeingFetched === 'function'
&& this.downloader.isRangeBeingFetched(start, size);
}
/**
* Checks whether the downloader was intentionally aborted or torn down, so an on-demand read must not start a request for a timeline nobody owns anymore.
* @returns {boolean} True when the downloader is aborted or destroyed.
*/
isDownloaderAborted() {
return this.destroyed
|| this.downloader.destroyed === true
|| this.downloader.isAborted === true;
}
/**
* Creates a watchdog for a read that waits for the download loop. It resolves with the reason the wait must end
* when the downloader is aborted, a newer seek took the timeline, the loop stopped fetching the window, or its
* received cursor has not advanced for the stall bound. It stays pending while the loop is making progress, and the
* caller disposes it as soon as the regular read resolves.
* @param {number} start - The first byte of the window.
* @param {number} size - The number of bytes of the window.
* @param {number} seekGeneration - The seek generation the read belongs to.
* @returns {{ promise: Promise<string>, dispose: Function }} The watchdog promise and its cleanup.
*/
createLoopStallWatchdog(start, size, seekGeneration) {
let disposed = false;
let timer = null;
let lastMarker = null;
let lastProgressAt = Date.now();
const promise = new Promise((resolve) => {
const check = () => {
if (disposed)
return;
if (this.isDownloaderAborted()) {
resolve('aborted');
return;
}
if (this.seekGeneration !== seekGeneration) {
resolve('superseded');
return;
}
if (!this.isLoopFetching(start, size)) {
resolve('not-fetching');
return;
}
const progress = this.downloader.getLoopProgress();
const now = Date.now();
if (progress) {
const marker = `${progress.start}:${progress.cursor}`;
if (lastMarker === null || marker !== lastMarker) {
lastMarker = marker;
lastProgressAt = now;
}
}
if (now - lastProgressAt >= LOOP_STALL_FALLBACK_MS) {
resolve('stalled');
return;
}
timer = setTimeout(check, LOOP_STALL_POLL_MS);
};
check();
});
return {
promise,
dispose: () => {
disposed = true;
if (timer !== null)
clearTimeout(timer);
}
};
}
/**
* Fetches an uncovered window as a bounded one-shot range request and then reads it through the regular source.
* @param {number} start - The first byte of the window.
* @param {number} size - The number of bytes of the window.
* @param {number|null} total - The total size of the stream, or null when it is unknown.
* @param {number} seekGeneration - The seek generation the read belongs to.
* @returns {Promise<Uint8Array>} The bytes, possibly shorter at the end of the stream.
*/
async fetchOnDemandAsync(start, size, total, seekGeneration) {
if (this.isDownloaderAborted() || this.seekGeneration !== seekGeneration)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.');
const window = this.getFetchWindow(start, size, total);
if (window === null)
return new Uint8Array(0);
// A probe far ahead of the loop frontier can duplicate bytes that the loop's open ended response will also
// deliver. That duplication is accepted: without the one-shot an OGG binary search can wait for the rest of
// the file, while the byte buffer merges the overlapping ranges.
const outcome = await this.downloader.downloadRangeAsync(window.start, window.end);
if (outcome.isAborted || outcome.isDestroyed)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The seek range request was aborted.');
if (outcome.isFailed)
throw outcome.error || new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The seek range request failed.');
// Every one-shot fetch is validated, not only a satisfied response: a short body or a changed file must not fall
// through to a read that waits for a loop window below its target that will never be fetched.
if (!this.isWindowCovered(start, size) && total !== null)
throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The seek range did not cover the requested window.');
return this.standard.readAsync(start, size);
}
/**
* Expands a small demuxer read into an aligned block, so a seek that scans the stream does not pay one network round
* trip per small window. The block never extends past the end of the file and is bounded to one aligned block around the requested window.
* @param {number} start - The first byte of the requested window.
* @param {number} size - The number of bytes of the requested window.
* @param {number|null} total - The total size of the stream, or null when it is unknown.
* @returns {{ start: number, end: number }|null} The inclusive byte range to fetch, or null when it is empty.
*/
getFetchWindow(start, size, total) {
if (size <= 0)
return null;
const blockStart = Math.floor(start / SEEK_FETCH_BLOCK_BYTES) * SEEK_FETCH_BLOCK_BYTES;
let blockEndExclusive = Math.ceil((start + size) / SEEK_FETCH_BLOCK_BYTES) * SEEK_FETCH_BLOCK_BYTES;
if (!Number.isFinite(blockEndExclusive) || blockEndExclusive <= blockStart)
blockEndExclusive = blockStart + SEEK_FETCH_BLOCK_BYTES;
if (total !== null)
blockEndExclusive = Math.min(total, blockEndExclusive);
if (blockEndExclusive <= blockStart)
return null;
// Start after the contiguous buffered run that covers the block start, so a seek into a partially buffered
// block does not request a whole block of bytes the buffer already holds.
let fetchStart = blockStart;
if (typeof this.downloader.getContiguousEnd === 'function')
fetchStart = Math.max(blockStart, this.downloader.getContiguousEnd(blockStart));
// A run that already reaches the end of the requested window would have made isWindowCovered true; the clamp is
// only a guard against asking for an empty or reversed range in an inconsistent buffer state.
if (fetchStart >= start + size)
fetchStart = start;
if (fetchStart >= blockEndExclusive)
fetchStart = blockStart;
return { start: fetchStart, end: blockEndExclusive - 1 };
}
/**
* Releases the source, so a late read of a released track returns an end of stream instead of touching the
* downloader.
*/
destroy() {
this.destroyed = true;
}
}
LuminaAudioPlayer.SeekAwareByteSource = SeekAwareByteSource;
})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {});
@@ -0,0 +1,390 @@
/**
* Schedulers of the audio player pipeline.
*
* The seekable scheduler trims the first decoded frame after a seek to the requested position before it reaches the
* renderer. The buffering scheduler holds the decoded audio of a gapless prefetch until the handoff appends it to the
* shared schedule. They are the only pipeline stages that know how decoded AudioData is shaped and laid on the timeline.
*/
(function (LuminaAudioPlayer) {
'use strict';
/**
* The duration, in seconds, of the next track that is pre-decoded for a gapless transition.
* @readonly
* @type {number}
*/
const GAPLESS_PRELOAD_SECONDS = 2;
/**
* The scheduled ahead ceiling, in seconds, of the scheduler that receives the pre-decoded audio of the next track. It
* bounds how much decoded audio is retained before the handoff, and it is lifted when the pre-decoded audio is appended to the renderer.
* @readonly
* @type {number}
*/
const GAPLESS_BUFFER_CEILING_SECONDS = GAPLESS_PRELOAD_SECONDS + 1;
/**
* The tolerance, in seconds, within which the first frame after a seek counts as beginning at the seek target, so that a frame is not trimmed for a rounding error.
* @readonly
* @type {number}
*/
const SEEK_TRIM_EPSILON_SECONDS = 0.001;
/**
* Coerces a value to a finite number, or null when it is absent or not finite.
* @param {*} value - The value to coerce.
* @returns {number|null} The finite number, or null.
*/
function toFiniteNumber(value) {
return LuminaAudioPlayer.toFiniteNumber(value);
}
/**
* Reads the media duration of a decoded frame, in seconds.
* @param {AudioData} audioData - The decoded frame.
* @returns {number} The duration, in seconds, or zero when it cannot be read.
*/
function getAudioDataDurationSeconds(audioData) {
const frames = toFiniteNumber(audioData && audioData.numberOfFrames);
const sampleRate = toFiniteNumber(audioData && audioData.sampleRate);
if (frames === null || sampleRate === null || frames <= 0 || sampleRate <= 0)
return 0;
return frames / sampleRate;
}
/**
* Releases the native memory of a decoded frame. It is safe to call on a frame that was already closed.
* @param {AudioData} audioData - The frame to close.
*/
function closeAudioData(audioData) {
if (!audioData || typeof audioData.close !== 'function')
return;
try {
audioData.close();
} catch (error) {
console.debug('Audio player: a decoded frame could not be released.', error);
}
}
/**
* Trims the leading frames of a decoded frame, so that the audio it carries starts exactly at a target position.
*
* The decoded frame is a planar 32 bit float frame, because that is what the decode pipeline copies and what the
* renderer consumes. The trimmed frame is a new AudioData whose timestamp is the target position, so the renderer
* adopts the requested seek position as the origin of the audio. The original frame is closed by this function when a trimmed frame is produced.
* @param {AudioData} audioData - The decoded frame to trim.
* @param {number} offsetSeconds - The number of seconds to remove from the start of the frame.
* @returns {AudioData|null} The trimmed frame, or null when the frame cannot be rebuilt.
*/
function trimAudioData(audioData, offsetSeconds) {
// Read the WebCodecs constructor at call time, so a host without AudioData (or a test) can fall back to scheduling
// the untrimmed frame instead of failing at module load.
const AudioDataConstructor = typeof window !== 'undefined' && typeof window.AudioData === 'function'
? window.AudioData
: null;
if (!AudioDataConstructor || !audioData || typeof audioData.copyTo !== 'function')
return null;
// AudioData exposes readonly typed properties. Read them through the shared helper so a missing or non numeric
// value rejects the trim instead of producing a frame with NaN dimensions.
const frames = toFiniteNumber(audioData.numberOfFrames);
const channels = toFiniteNumber(audioData.numberOfChannels);
const sampleRate = toFiniteNumber(audioData.sampleRate);
const timestamp = toFiniteNumber(audioData.timestamp);
if (frames === null || channels === null || sampleRate === null || timestamp === null)
return null;
if (frames <= 0 || channels <= 0 || sampleRate <= 0)
return null;
// Round to the nearest sample. The offset is a time difference, so flooring it could leave a fraction of a sample
// of audio from before the seek target audible.
const framesToTrim = Math.round(offsetSeconds * sampleRate);
// AudioData can only hold whole frames. Drop any partial trailing sample from the source count.
const keptFrames = Math.floor(frames) - framesToTrim;
// Nothing to remove, or nothing left to play. The caller keeps the original frame, which is the safer fallback for
// a frame that starts at the target or ends exactly at it.
if (framesToTrim <= 0 || keptFrames <= 0)
return null;
// One planar block holds every channel back to back. The subarray per channel is exactly the layout AudioData
// expects for f32-planar, and it avoids one allocation per channel.
const samples = new Float32Array(keptFrames * Math.floor(channels));
try {
for (let channel = 0; channel < channels; channel++) {
const destination = samples.subarray(channel * keptFrames, (channel + 1) * keptFrames);
// Skip the pre-target frames and copy only the kept tail. copyTo is the only way to read the native
// AudioData memory without holding on to the original frame.
audioData.copyTo(destination, {
planeIndex: channel,
frameOffset: framesToTrim,
frameCount: keptFrames,
format: 'f32-planar'
});
}
// The trimmed frame starts at the seek target, and WebCodecs timestamps are integer microseconds. Keeping the
// original timestamp plus the removed audio keeps the frame on the same absolute timeline.
const trimmed = new AudioDataConstructor({
format: 'f32-planar',
sampleRate: sampleRate,
numberOfFrames: keptFrames,
numberOfChannels: Math.floor(channels),
timestamp: Math.round(timestamp + offsetSeconds * 1000000),
data: samples
});
// The original is released only after the replacement exists. If the constructor above throws, ownership stays
// with the caller, which then schedules the original frame.
closeAudioData(audioData);
return trimmed;
} catch (error) {
// Returning null rather than throwing lets the scheduler play the original frame. A seek may then be a packet
// early, but a browser that refuses to construct an AudioData never turns the seek into silence.
console.debug('Audio player: the first decoded frame after a seek could not be trimmed.', error);
return null;
}
}
/**
* A scheduler proxy over the renderer that trims the first decoded frame after a seek to the requested position.
*
* A demuxer repositions to a packet boundary at or before the seek target, so the first decoded frame may carry audio
* from before the target. The renderer adopts the requested position as the origin of the first buffer it receives and
* cannot correct an offset it is not told about, so the offset is removed here, before the frame reaches the renderer.
*/
class SeekableScheduler {
/**
* Creates an instance of SeekableScheduler.
* @param {Object} target - The scheduler the frames are handed to, normally the renderer.
* @param {Function} [onScheduled] - Called once, when the first frame is handed to the target after a seek or a load.
*/
constructor(target, onScheduled) {
this.target = target;
this.onScheduled = typeof onScheduled === 'function' ? onScheduled : null;
this.hasScheduled = false;
// The absolute media position the first frame after a seek must start at, or null when no trim is pending.
this.trimTargetSeconds = null;
// A scheduler of a released item drops every frame that is still emitted, so a decoder that was destroyed with
// frames in flight can never schedule audio for a track that is no longer playing.
this.stopped = false;
// While a seek owns the timeline, frames that the old decode loop still emits are dropped instead of being laid
// at the new position before the decoder reset takes effect.
this.suppressed = false;
}
/**
* Sets whether frames are dropped instead of scheduled, which a seek uses until every stage is repositioned.
* @param {boolean} value - True to drop frames, false to schedule them again.
*/
setSuppressed(value) {
this.suppressed = value === true;
}
/**
* Marks the position the next decoded frame must begin at, removing any audio that a demuxer landed before it.
* @param {number} seconds - The absolute media position of the seek target, in seconds.
*/
setSeekTarget(seconds) {
const value = toFiniteNumber(seconds);
this.trimTargetSeconds = value === null ? null : Math.max(0, value);
}
/**
* Re-arms the first frame notification, so the state of a fresh seek or a fresh track is observed again.
*/
rearm() {
this.hasScheduled = false;
}
/**
* Stops the scheduler, so every later frame is dropped instead of being handed to the target. It is used when the item that owns the scheduler is released or fails.
*/
stop() {
this.stopped = true;
}
/**
* Hands a decoded frame to the target, trimming it when it carries audio from before the pending seek target.
* @param {AudioData} audioData - The decoded frame. Ownership transfers to this scheduler, which always closes it.
* @returns {number} The media position at the end of the frame, or the target position when the frame was dropped.
*/
schedule(audioData) {
if (this.stopped || this.suppressed) {
closeAudioData(audioData);
return 0;
}
let frame = audioData;
const target = this.trimTargetSeconds;
if (target !== null) {
const frameStart = toFiniteNumber(frame.timestamp);
const frameDuration = getAudioDataDurationSeconds(frame);
if (frameStart !== null && frameDuration > 0) {
// WebCodecs reports the frame timestamp in microseconds, while the scheduler and the renderer work in
// seconds.
const secondsStart = frameStart / 1000000;
const secondsEnd = secondsStart + frameDuration;
if (secondsEnd <= target + SEEK_TRIM_EPSILON_SECONDS) {
// The whole frame is before the target, so it is dropped instead of played early.
closeAudioData(frame);
return target;
}
if (secondsStart < target - SEEK_TRIM_EPSILON_SECONDS) {
const trimmed = trimAudioData(frame, target - secondsStart);
if (trimmed) {
frame = trimmed;
} else {
// A frame that cannot be rebuilt is scheduled from its own start rather than dropped, so a
// browser that refuses to construct an AudioData never turns a seek into a gap. The offset is at most one packet long.
this.trimTargetSeconds = null;
}
}
}
// Only the first frame after a seek can straddle the target. Later frames already start after it, so a
// pending trim must not leak into the next seek.
this.trimTargetSeconds = null;
}
if (!this.hasScheduled) {
this.hasScheduled = true;
if (this.onScheduled)
this.onScheduled();
}
return this.target.schedule(frame);
}
/**
* Attaches the scheduler to the target it was buffering for, which is how a prefetch becomes the audio that plays.
* @param {Object} target - The scheduler the frames are handed to from now on.
*/
attach(target) {
const previous = this.target;
this.target = target;
// A buffering target flushes the audio it pre-decoded into the new target, which is the renderer. A renderer target has no attach method and is simply replaced.
if (previous && typeof previous.attach === 'function')
previous.attach(target);
}
/**
* Gets the scheduled ahead duration the current target reports.
* @returns {number} The scheduled ahead duration, in seconds.
*/
getScheduledAheadSeconds() {
return typeof this.target.getScheduledAheadSeconds === 'function' ? this.target.getScheduledAheadSeconds() : 0;
}
/**
* Gets the scheduled ahead ceiling the current target publishes, or null when it publishes none.
* @returns {number|null} The ceiling, in seconds.
*/
getMaxScheduledAheadSeconds() {
return typeof this.target.getMaxScheduledAheadSeconds === 'function' ? this.target.getMaxScheduledAheadSeconds() : null;
}
/**
* Gets the playback rate of the current target, which is one when the target does not report it.
* @returns {number} The playback rate.
*/
getPlaybackRate() {
return typeof this.target.getPlaybackRate === 'function' ? this.target.getPlaybackRate() : 1;
}
/**
* Releases the audio a buffering target still holds. A renderer target is left untouched, because it is shared.
*/
dispose() {
if (this.target && typeof this.target.close === 'function')
this.target.close();
}
}
/**
* A scheduler that holds the decoded audio of a prefetched track until the current track hands over to it.
*
* While it is detached it reports the duration it holds as its scheduled ahead duration, so the decoder paces itself
* against the buffer instead of decoding the whole next track, and it publishes a ceiling that bounds that buffer.
* Once attached, it flushes the buffered frames into the target in order and delegates every later frame to it.
*/
class BufferingScheduler {
/**
* Creates an instance of BufferingScheduler.
*/
constructor() {
this.target = null;
this.buffer = [];
this.bufferedSeconds = 0;
}
/**
* Stores a decoded frame until the scheduler is attached, or hands it to the target once it is.
* @param {AudioData} audioData - The decoded frame. Ownership transfers to this scheduler.
* @returns {number} The buffered duration in seconds while detached, or the target position after attaching.
*/
schedule(audioData) {
if (this.target)
return this.target.schedule(audioData);
const duration = getAudioDataDurationSeconds(audioData);
this.buffer.push(audioData);
this.bufferedSeconds += duration;
return this.bufferedSeconds;
}
/**
* Attaches the scheduler to the target it buffered for: the buffered frames are appended to the target in order,
* so the next track starts exactly at the end of the audio of the current one.
* @param {Object} target - The scheduler to hand the buffered and later frames to.
*/
attach(target) {
this.target = target;
const pending = this.buffer;
let index = 0;
try {
for (; index < pending.length; index++)
target.schedule(pending[index]);
} catch (error) {
// The target owns and closes the frame it refused; every frame after it is still buffered and must be
// released here, or up to the whole pre-decode window is retained as native audio until garbage collection.
console.debug('Audio player: a pre-decoded frame could not be scheduled.', error);
for (let remaining = index + 1; remaining < pending.length; remaining++)
closeAudioData(pending[remaining]);
} finally {
this.buffer = [];
this.bufferedSeconds = 0;
}
}
/**
* Gets the buffered duration while detached, or the scheduled ahead duration of the target once attached.
* @returns {number} The scheduled ahead duration, in seconds.
*/
getScheduledAheadSeconds() {
return this.target ? this.target.getScheduledAheadSeconds() : this.bufferedSeconds;
}
/**
* Gets the ceiling the decoder paces itself against. While detached it bounds the prefetch buffer, and once attached it is the ceiling of the target.
* @returns {number|null} The ceiling, in seconds.
*/
getMaxScheduledAheadSeconds() {
if (this.target)
return typeof this.target.getMaxScheduledAheadSeconds === 'function' ? this.target.getMaxScheduledAheadSeconds() : null;
return GAPLESS_BUFFER_CEILING_SECONDS;
}
/**
* Gets the playback rate of the target, or one while detached.
* @returns {number} The playback rate.
*/
getPlaybackRate() {
return this.target && typeof this.target.getPlaybackRate === 'function' ? this.target.getPlaybackRate() : 1;
}
/**
* Releases every frame that was buffered and never scheduled.
*/
close() {
for (const audioData of this.buffer)
closeAudioData(audioData);
this.buffer = [];
this.bufferedSeconds = 0;
}
}
LuminaAudioPlayer.GAPLESS_PRELOAD_SECONDS = GAPLESS_PRELOAD_SECONDS;
LuminaAudioPlayer.SEEK_TRIM_EPSILON_SECONDS = SEEK_TRIM_EPSILON_SECONDS;
LuminaAudioPlayer.SeekableScheduler = SeekableScheduler;
LuminaAudioPlayer.BufferingScheduler = BufferingScheduler;
})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {});
@@ -109,7 +109,7 @@
* const renderer = LuminaAudioPlayer.createTrackRenderer({
* replayGainMode: host.getPreferences().replayGainMode,
* events: host.events,
* onTimeUpdate: (time, duration) => host.reportTime(time, duration),
* onTimeUpdate: (time, trackDuration, timelineDuration) => host.reportTime(time, trackDuration),
* onEnded: () => host.reportEnded()
* });
* renderer.configure(manifest);
@@ -240,6 +240,14 @@
*/
const TRACK_GAIN_RAMP_SECONDS = 0.05;
/**
* The ramp, in seconds, of the ReplayGain change at a gapless boundary. It is scheduled at the context time the next
* track starts, so it is short enough to be inaudible as a blend and long enough not to click.
* @readonly
* @type {number}
*/
const TRACK_GAIN_HANDOFF_RAMP_SECONDS = 0.01;
/**
* The interval, in milliseconds, the reporter falls back to when the page has no requestAnimationFrame.
* @readonly
@@ -370,7 +378,9 @@
* @param {number} [options.playbackRate] - The playback rate, within the accepted playback rate range. Defaults to 1.
* @param {number} [options.maxScheduledAheadSeconds] - An optional ceiling, in seconds, on how far ahead of the audio clock the schedule may run. Scheduling beyond it is refused with a typed error, so a caller that never paces itself cannot grow the schedule without bound. Leave the option out to disable the ceiling; a value of zero is a real ceiling that refuses every buffer, not a way to disable it.
* @param {Object} [options.events] - The player event bus. When provided, the renderer follows the player's ReplayGain mode changes.
* @param {Function} [options.onTimeUpdate] - Called with the current time and the duration, in seconds, while the audio plays.
* @param {Function} [options.onTimeUpdate] - Called while the audio plays with the absolute timeline position, the
* duration of the current track, and the duration of the whole shared timeline, in seconds. The position is always
* on the timeline, so the timeline duration is the value that bounds a seek; the track duration is the one the bar shows for the current item.
* @param {Function} [options.onEnded] - Called once per configured track when its scheduled audio has been fully played. Audio scheduled after the end, without a configure or a seek, continues the same logical track and does not report the end again.
*/
constructor(options = {}) {
@@ -400,7 +410,12 @@
this.trackGain = null;
this.manifest = null;
this.duration = 0;
// The media duration of the whole shared timeline. It equals the duration of the current track until a gapless
// handoff appends another track, which is why it is kept apart from the duration of the current track.
this.timelineDuration = 0;
this.trackGainValue = 1;
// The ReplayGain change of a gapless handoff, scheduled at the context time the next track starts, or null.
this.pendingGainChange = null;
this.error = null;
// The scheduled sources, in media order, each one holding the audio buffer it plays so a playback rate change
@@ -464,6 +479,7 @@
this.duration = this.manifest && toFiniteNumber(this.manifest.durationInSeconds) !== null
? Math.max(0, Number(this.manifest.durationInSeconds))
: 0;
this.timelineDuration = this.duration;
this.mediaCursor = 0;
this.nextStartTime = 0;
this.pausedMediaTime = 0;
@@ -472,11 +488,117 @@
this.streamComplete = false;
this.anchorContextTime = this.context.currentTime;
this.anchorMediaTime = 0;
// A new track replaces any scheduled handoff gain of the previous one.
this.pendingGainChange = null;
this.applyTrackGain(0);
this.applyMasterGain(0);
return this;
}
/**
* Adopts the manifest of a track that continues the current schedule without resetting it, which is how a gapless
* transition applies the ReplayGain values of the next track. The schedule, the playhead and the completion state
* are left untouched, because the audio of the next track is already appended after the current one.
* @param {Object} manifest - The playback manifest of the continuing track.
* @param {boolean} [isGainAlreadyScheduled=false] - True when scheduleManifestGain already scheduled the ReplayGain
* change at the boundary, so applying it again with a late ramp is skipped.
* @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining.
* @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed.
*/
adoptManifest(manifest, isGainAlreadyScheduled = false) {
if (this.destroyed)
throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The renderer was destroyed.'));
this.manifest = manifest || null;
this.duration = this.manifest && toFiniteNumber(this.manifest.durationInSeconds) !== null
? Math.max(0, Number(this.manifest.durationInSeconds))
: this.duration;
this.pendingGainChange = null;
// The gapless handoff schedules the gain automation at the exact boundary context time, so the manifest is
// adopted without applying a second, late ramp when that automation was accepted.
if (isGainAlreadyScheduled) {
this.trackGainValue = this.computeTrackGain(this.manifest);
} else {
this.applyTrackGain(TRACK_GAIN_RAMP_SECONDS);
}
return this;
}
/**
* Schedules the ReplayGain change of the next track at the context time that track starts, instead of applying it
* when the boundary is detected up to a reporter tick later. The schedule is stored, so a ReplayGain mode change
* before the boundary can reschedule it, and it is cleared when the handoff is abandoned.
* @param {Object} manifest - The playback manifest of the next track.
* @param {number} whenContextTime - The context time, in seconds, at which the next track starts.
* @returns {boolean} True when the automation was scheduled, false when the parameter cannot automate.
* @throws {LuminaAudioPlayer.PlayerError} When the renderer was destroyed.
*/
scheduleManifestGain(manifest, whenContextTime) {
if (this.destroyed)
throw this.raise(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The renderer was destroyed.'));
this.ensureContext();
// A call that cannot schedule anything must not leave a previous handoff change pending.
this.pendingGainChange = null;
const when = toFiniteNumber(whenContextTime);
if (when === null || !this.trackGain || !this.trackGain.gain)
return false;
const param = this.trackGain.gain;
if (typeof param.setValueAtTime !== 'function' || typeof param.linearRampToValueAtTime !== 'function')
return false;
const start = Math.max(this.context.currentTime, when);
const gain = this.computeTrackGain(manifest);
try {
if (typeof param.cancelAndHoldAtTime === 'function') {
// Holding at the boundary samples the value the automation actually has at that time, including a ramp
// that is still in progress because the ReplayGain mode changed after the handoff was scheduled.
param.cancelAndHoldAtTime(start);
} else {
const current = Number.isFinite(param.value) ? param.value : 1;
param.setValueAtTime(current, start);
}
param.linearRampToValueAtTime(gain, start + TRACK_GAIN_HANDOFF_RAMP_SECONDS);
this.pendingGainChange = { manifest: manifest || null, when: start };
return true;
} catch (error) {
this.pendingGainChange = null;
console.debug('Audio player: the ReplayGain change of the next track could not be scheduled.', error);
return false;
}
}
/**
* Cancels a scheduled gapless ReplayGain change and restores the gain of the current manifest. It is used when the
* handoff is abandoned before the next track starts.
* @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining.
*/
cancelTrackGainChange() {
this.pendingGainChange = null;
if (this.trackGain && this.trackGain.gain && this.context
&& typeof this.trackGain.gain.cancelScheduledValues === 'function') {
try {
this.trackGain.gain.cancelScheduledValues(this.context.currentTime);
} catch (error) {
console.debug('Audio player: the scheduled ReplayGain change could not be cancelled.', error);
}
}
if (!this.destroyed)
this.applyTrackGain(0);
return this;
}
/**
* Extends the media duration of the shared timeline, so that a seek into a gapless chain is bounded by the audio
* that is actually scheduled rather than by the duration of the first track of the chain. The duration is only
* used to bound a seek and to report the timeline length; the end of the audio is detected from the schedule.
* @param {number} duration - The media duration of the whole timeline, in seconds.
* @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining.
*/
setTimelineDuration(duration) {
const value = toFiniteNumber(duration);
if (value !== null && value >= 0)
this.timelineDuration = value;
return this;
}
/**
* Releases every resource of the renderer: the schedule, the gain nodes, the event subscriptions and, when the
* renderer owns it, the audio context.
@@ -486,6 +608,7 @@
this.destroyed = true;
this.playing = false;
this.paused = false;
this.pendingGainChange = null;
this.stopReporter();
for (const unsubscribe of this.unsubscribers) {
try {
@@ -656,7 +779,11 @@
if (next === this.replayGainMode)
return this.replayGainMode;
this.replayGainMode = next;
// The current gain is applied first, which cancels the scheduled handoff change, so a scheduled change is put back with the values of the new mode.
const pending = this.pendingGainChange;
this.applyTrackGain(TRACK_GAIN_RAMP_SECONDS);
if (pending)
this.scheduleManifestGain(pending.manifest, pending.when);
return this.replayGainMode;
}
@@ -803,7 +930,10 @@
return this.mediaCursor;
this.ensureContext();
const position = Math.max(0, request);
const bounded = this.duration > 0 ? Math.min(position, this.duration) : position;
// A track whose duration is not known has no timeline bound to clamp against; clamping to the end of the
// previous track would silently restart it at its base position.
const limit = this.duration > 0 ? (this.timelineDuration > 0 ? this.timelineDuration : this.duration) : 0;
const bounded = limit > 0 ? Math.min(position, limit) : position;
this.stopAllSources();
this.mediaCursor = bounded;
this.nextStartTime = 0;
@@ -824,6 +954,17 @@
this.streamComplete = true;
}
/**
* Clears the stream-complete state, so a drained schedule is treated as an underrun gap again instead of the end
* of the track. It is used when a gapless handoff appends the next track after the end of the current decode was
* already recorded: the schedule then carries more audio, and a slow download of that audio must pause and resume rather than end the second track early.
* @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining.
*/
clearStreamComplete() {
this.streamComplete = false;
return this;
}
//+======================================================================================+
//| Query surface |
//+======================================================================================+
@@ -846,6 +987,21 @@
return clamp(media, 0, upperBound);
}
/**
* Converts an absolute media position of the shared timeline into the context time at which it will play. The
* renderer owns the anchor, the playback rate and the lead time of the schedule, so a caller that needs to schedule
* something at a media position must use this conversion instead of repeating the anchor math.
* @param {number} mediaSeconds - The absolute media position, in seconds.
* @returns {number} The context time, in seconds, or zero when the renderer has no context.
*/
getContextTimeForMediaPosition(mediaSeconds) {
const target = toFiniteNumber(mediaSeconds);
if (target === null || !this.context)
return 0;
const rate = this.playbackRate > 0 ? this.playbackRate : 1;
return this.context.currentTime + Math.max(0, (target - this.getCurrentTime()) / rate);
}
/**
* Gets the duration of the current track, from its playback manifest.
* @returns {number} The duration, in seconds, or zero when it is unknown.
@@ -854,6 +1010,15 @@
return this.duration;
}
/**
* Gets the duration of the whole shared timeline, which is longer than the current track when a gapless handoff
* has appended another track. It is the value a seek is bounded by.
* @returns {number} The timeline duration, in seconds, or zero when it is unknown.
*/
getTimelineDuration() {
return this.timelineDuration;
}
/**
* Gets the output volume, which is independent of the mute state.
* @returns {number} The volume, between 0 and 1.
@@ -1067,13 +1232,22 @@
* @param {number} rampSeconds - The duration of the ramp to the new value, in seconds. Zero applies it at once.
*/
applyTrackGain(rampSeconds) {
const values = resolveReplayGain(this.manifest, this.replayGainMode);
this.trackGainValue = computeReplayGainLinearGain(values.gainDb, values.peak);
this.trackGainValue = this.computeTrackGain(this.manifest);
if (!this.trackGain || !this.trackGain.gain)
return;
this.setAudioParamValue(this.trackGain.gain, this.trackGainValue, rampSeconds);
}
/**
* Computes the linear ReplayGain value a manifest and the current mode select.
* @param {Object|null} manifest - The playback manifest.
* @returns {number} The linear gain, one when nothing is selected.
*/
computeTrackGain(manifest) {
const values = resolveReplayGain(manifest, this.replayGainMode);
return computeReplayGainLinearGain(values.gainDb, values.peak);
}
/**
* Applies a value to an audio parameter, ramping to it so a change never clicks.
* @param {AudioParam} param - The audio parameter to change.
@@ -1210,6 +1384,8 @@
const ratio = outputLength / channelData.length;
const output = new Float32Array(outputLength);
for (let index = 0; index < outputLength; index++) {
// Map each output sample back to its fractional position in the input. The neighbours are clamped at the
// end of the source, so the last sample repeats instead of reading past the array or turning into zero.
const position = index / ratio;
const lower = Math.floor(position);
const fraction = position - lower;
@@ -1380,6 +1556,41 @@
this.endReported = false;
}
/**
* Removes every scheduled source whose audio begins at or after a media position, keeping the audio before it. It is
* used when a gapless handoff is abandoned after the next track was already appended: the appended audio is stopped
* and released, the media frontier is moved back to the boundary, and the current track can end normally there
* instead of being followed by a transition the user disabled.
*
* Call it while the boundary is still ahead of getCurrentTime(), after the gain change of the next track was
* cancelled and before markStreamComplete(). Truncating behind the playhead would move the media cursor backwards
* and replay audio that already played, so the caller checks getCurrentTime() first and leaves a handoff that has already begun alone.
* @param {number} mediaPosition - The absolute media position from which scheduled audio is removed.
* @returns {LuminaAudioPlayer.TrackRenderer} This renderer, for chaining.
*/
truncateScheduleAt(mediaPosition) {
const target = toFiniteNumber(mediaPosition);
if (this.destroyed || target === null)
return this;
const kept = [];
for (let index = 0; index < this.scheduledSources.length; index++) {
const entry = this.scheduledSources[index];
if (index >= this.firstLiveIndex && entry.bufferMediaStart >= target)
this.releaseSource(entry.source);
else
kept.push(entry);
}
this.scheduledSources = kept;
if (this.firstLiveIndex > kept.length)
this.firstLiveIndex = kept.length;
this.mediaCursor = Math.max(0, target);
const last = kept[kept.length - 1];
this.nextStartTime = last ? last.when + last.mediaDuration / last.rate : 0;
if (this.pausedMediaTime > this.mediaCursor)
this.pausedMediaTime = this.mediaCursor;
return this;
}
/**
* Releases the scheduled sources whose audio has finished playing. The entries are held in media order, so the
* finished ones are always a prefix; the cursor of the first live entry is advanced over that prefix instead of the
@@ -1496,7 +1707,7 @@
return;
if (this.onTimeUpdate) {
try {
this.onTimeUpdate(this.getCurrentTime(), this.getDuration());
this.onTimeUpdate(this.getCurrentTime(), this.getDuration(), this.getTimelineDuration());
} catch (error) {
console.error('Audio player: the renderer time callback threw.', error);
}
@@ -23,6 +23,18 @@
return Math.min(maximum, Math.max(minimum, value));
};
/**
* Coerces a value to a finite number, or null when it is absent or not finite.
* @param {*} value - The value to coerce.
* @returns {number|null} The finite number, or null.
*/
LuminaAudioPlayer.toFiniteNumber = function toFiniteNumber(value) {
if (value === null || value === undefined || value === '')
return null;
const number = Number(value);
return Number.isFinite(number) ? number : null;
};
/**
* Checks whether a value is the AbortError a reset, a close or an aborted fetch rejects with. An AbortError is tested
* by name rather than by type, because in a browser it is a DOMException, which is not an Error.
@@ -68,4 +80,14 @@
return typed;
return new LuminaAudioPlayer.PlayerError(typed.code, typed.message, LuminaAudioPlayer.mergeErrorDetails(typed.details, details));
};
/**
* The result of a background request whose answer was a redirect, which means the session expired and the page is
* being sent to the sign in page. It is distinct from a missing value, which is a failure, so that a caller does not
* report an error for a redirect it is already handling. It lives in this dependency free module, which is loaded
* before every feature module, so a consumer can recognize it even when the controller is not loaded.
* @readonly
* @type {Object}
*/
LuminaAudioPlayer.REDIRECTED = Object.freeze({ redirected: true });
})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {});
@@ -30,8 +30,15 @@
* - toggleVisibility(): shows or hides the bar.
* - on(event, handler): subscribes to a player event, returns an unsubscribe function.
* - once(event, handler), off(event, handler): one shot subscribe, and unsubscribe.
* - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(), getVolume(), isMuted(),
* isBuffering(), getBufferedTimeRanges(), getPreferences(), getCapabilities(), getLastError(), getSubTemplates().
* - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(), getVolume(),
* isMuted(), isBuffering(), getBufferedTimeRanges(), getPreferences(), getCapabilities(), getLastError(),
* getSubTemplates().
* - getNextDescriptor(): the identity and descriptor of the next queue entry, or null.
* - advanceQueueTo(entryId): moves the queue cursor to the entry with that identity without starting playback, so a
* linear advance, a wrap, a reordered queue and a gapless handoff share one commit. The advance
* is refused when the identity is no longer part of the queue.
* - requestNextTrackAsync(reason): starts the next queue entry through the player's own play path, used by the engine
* when a gapless handoff could not be prepared.
* - destroyAsync(): releases every resource of the player. It is only used for an explicit teardown, never
* by a navigation, because the navigation manager never recreates the player.
* - registerEngine(name, factory): registers an engine factory on this player, by name.
@@ -81,14 +88,9 @@
error: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR]
});
/**
* The result of a background request whose answer was a redirect, which means the session expired and the page is
* being sent to the sign in page. It is distinct from a missing value, which is a failure, so that a caller does not
* report an error for a redirect it is already handling.
* @readonly
* @type {Object}
*/
const REDIRECTED = Object.freeze({ redirected: true });
// The redirect sentinel belongs to the dependency free utils module, so a consumer that is loaded without this
// controller, such as the manifest client, can still recognize it. The local name keeps the references readable.
const REDIRECTED = LuminaAudioPlayer.REDIRECTED;
/**
* Follows a server redirect, but only when the target is an http or https URL on the same origin and protocol as
@@ -127,6 +129,42 @@
}
}
/**
* Checks whether a response is a redirect that was not followed because the request asked for manual redirects.
* @param {Response} response - The response to check.
* @returns {boolean} True when the response is a redirect.
*/
function isRedirectResponse(response) {
if (!response)
return false;
if (response.type === 'opaqueredirect')
return true;
const status = Number(response.status);
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
}
/**
* Resolves a configured endpoint URL against the origin of the page, so a root relative configuration value is always
* requested from the page's own origin and not from whatever the server saw as its host or a base element points at.
* @param {string} url - The configured URL.
* @returns {string|null} The resolved absolute URL, or null when it is missing or not on this origin.
*/
function resolveConfiguredUrl(url) {
if (typeof url !== 'string' || url.length === 0)
return null;
try {
const resolved = new URL(url, window.location.origin);
if ((resolved.protocol !== 'http:' && resolved.protocol !== 'https:')
|| resolved.origin !== window.location.origin
|| resolved.username !== ''
|| resolved.password !== '')
return null;
return resolved.href;
} catch (error) {
return null;
}
}
/**
* The attribute that marks an element as a play trigger the player handles by event delegation.
* @readonly
@@ -403,8 +441,15 @@
this.state = LuminaAudioPlayer.PlayerState.IDLE;
this.descriptor = null;
this.queue = [];
// The queue entries are the single queue: each entry carries an identity per occurrence, so a repeated track is
// distinguishable from another occurrence of the same track, and the descriptor the public API exposes. Every
// traversal, advance and render derives from this array, so the cursor can never disagree with the queue.
this.queueEntries = [];
this.entrySequence = 0;
this.currentIndex = 0;
// The order the queue list was last rendered in, so a future shuffle or reorder that changes queueEntries
// without rendering the list is detected instead of updating the wrong items in place.
this.renderedQueueOrder = [];
this.currentTime = 0;
this.duration = 0;
this.downloadedFraction = 0;
@@ -666,10 +711,12 @@
this.scrubRatio = null;
this.endScrub();
this.endVolumeAdjust();
// clearBuffering also clears any pending seek of the previous timeline.
this.clearBuffering();
// An album or artist descriptor carries no track id of its own, so the queue starts at its first item in that case.
this.queue = descriptor.queue && descriptor.queue.length > 0 ? [...descriptor.queue] : [descriptor];
this.currentIndex = Math.max(0, this.queue.findIndex(item => item.trackId === descriptor.trackId));
const descriptors = descriptor.queue && descriptor.queue.length > 0 ? [...descriptor.queue] : [descriptor];
this.queueEntries = descriptors.map((entry) => ({ entryId: this.createQueueEntryId(), descriptor: entry }));
this.currentIndex = Math.max(0, this.queueEntries.findIndex((entry) => entry.descriptor.trackId === descriptor.trackId));
// The bar is shown and the state moves to loading before the engine is touched, so a slow engine still gives the user
// immediate feedback that the request was accepted.
@@ -679,17 +726,50 @@
this.showBar();
this.setState(LuminaAudioPlayer.PlayerState.LOADING);
this.events.emit(LuminaAudioPlayer.PlayerEvent.DESCRIPTOR_CHANGED, descriptor);
this.events.emit(LuminaAudioPlayer.PlayerEvent.QUEUE_CHANGED, this.queue);
this.events.emit(LuminaAudioPlayer.PlayerEvent.QUEUE_CHANGED, this.getQueue());
return this.startLoadedDescriptorAsync(descriptor);
}
/**
* Starts the engine load and playback of a descriptor the player has already made current and set to its loading
* state. The player state is checked again after each await, so a stop that happens while a load is running keeps
* its intent instead of being overwritten by the load or by the engine.
* @param {Object} descriptor - The descriptor that is already current on the player.
* @param {Object} [options] - The load options.
* @param {boolean} [options.keepBuffering] - True to keep a loading state that was handed to the load, used by an
* automatic continuation so the gap before the manifest and header probe shows a loading state.
* @returns {Promise<boolean>} True when playback started, false when it was stopped or failed.
*/
async startLoadedDescriptorAsync(descriptor, options = {}) {
let engine = null;
try {
// The state follows the engine step by step, so a consumer can tell preparation apart from actual playback.
const engine = await this.ensureEngineAsync();
await engine.loadAsync(descriptor);
engine = await this.ensureEngineAsync();
await engine.loadAsync(descriptor, options);
if (this.state !== LuminaAudioPlayer.PlayerState.LOADING) {
// A stop during the load already paused the engine; a newer request owns the player state and must not be touched by this stale continuation.
if (this.state === LuminaAudioPlayer.PlayerState.IDLE)
await this.pauseEngineQuietlyAsync(engine);
return false;
}
this.setState(LuminaAudioPlayer.PlayerState.READY);
await engine.playAsync();
if (this.state !== LuminaAudioPlayer.PlayerState.READY) {
if (this.state === LuminaAudioPlayer.PlayerState.IDLE)
await this.pauseEngineQuietlyAsync(engine);
return false;
}
this.setState(LuminaAudioPlayer.PlayerState.PLAYING);
this.renderTransportState();
} catch (error) {
// A load that a newer play request overtook, and a session that expired and is already navigating to the
// sign in page, are expected outcomes. They must not move the player to its error state, and they must not
// let this stale continuation set READY or PLAYING over the request that now owns the player.
const reason = error && error.details ? error.details.reason : null;
if (reason === LuminaAudioPlayer.PlayerErrorReason.LOAD_SUPERSEDED
|| reason === LuminaAudioPlayer.PlayerErrorReason.SESSION_EXPIRED)
return false;
// A failure before playback starts is a load failure; later failures are reported by the engine through its host.
this.fail(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED);
return false;
@@ -697,6 +777,66 @@
return true;
}
/**
* Pauses an engine after a load that the user stopped, without letting a pause failure disturb the player state.
* @param {Object} engine - The engine to pause.
* @returns {Promise<void>} A promise that completes when the pause was attempted.
*/
async pauseEngineQuietlyAsync(engine) {
if (!engine || typeof engine.pauseAsync !== 'function')
return;
try {
await engine.pauseAsync();
} catch (error) {
console.debug('Audio player: the engine could not be paused after a stopped load.', error);
}
}
/**
* Requests the next queue entry as a new playback, with the player's own state machine owning the transition. It is
* the seam the engine uses for the end of a track when a gapless handoff could not be prepared.
* @param {string} [reason] - A developer facing reason for the request, for diagnostics.
* @returns {Promise<boolean>} True when the player took ownership of the request, false when it declined it because the player is paused, stopped, or has no next entry.
*/
async requestNextTrackAsync(reason) {
// A paused or stopped player has made an explicit choice that the end of a track must not override.
if (this.state !== LuminaAudioPlayer.PlayerState.PLAYING)
return false;
const next = this.getNextDescriptor();
if (!next)
return false;
// The capability gate is part of the player's play path, so an auto advance never starts a track the browser
// cannot decode.
const report = await this.capabilitiesReady;
if (this.state !== LuminaAudioPlayer.PlayerState.PLAYING)
return false;
if (report && !report.isSupported) {
this.fail(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'The browser is missing a capability the player requires.',
{ missing: report.missing }), LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING);
return true;
}
const advanced = this.advanceQueueTo(next.entryId);
if (!advanced)
return false;
this.setState(LuminaAudioPlayer.PlayerState.LOADING);
this.renderTransportState();
// The player owns the outcome from here, including a load that fails: returning true keeps the engine from
// reporting an end over a state the player has already set. The loading state is kept across the engine
// teardown, so the end gap shows that the next track is being prepared.
const hasStarted = await this.startLoadedDescriptorAsync(advanced, { keepBuffering: true });
if (!hasStarted && this.state === LuminaAudioPlayer.PlayerState.IDLE
&& this.engine && typeof this.engine.discardCurrentAsync === 'function') {
// A stop during the continuation load owns the outcome. The prepared track is released, so a stopped
// player does not keep a track loaded that was started only to continue a queue.
try {
await this.engine.discardCurrentAsync();
} catch (error) {
console.debug('Audio player: the stopped continuation track could not be released.', error);
}
}
return true;
}
/**
* Suspends playback, keeping the current position.
* @returns {Promise<void>} A promise that completes when the engine paused.
@@ -781,9 +921,17 @@
* @returns {Promise<void>} A promise that completes when the seek was requested.
*/
async seekAsync(seconds) {
// Without a descriptor there is no timeline to seek in.
if (!this.descriptor)
// Without a descriptor there is no timeline to seek in. A finished, failed or still loading track is not
// seekable either: its pipeline is either released or not yet the one the seek would address. Seeking a
// finished track is deliberately a no-op rather than a replay, and no resume is reported for it; a new play starts the next timeline.
if (!this.descriptor
|| this.state === LuminaAudioPlayer.PlayerState.IDLE
|| this.state === LuminaAudioPlayer.PlayerState.ENDED
|| this.state === LuminaAudioPlayer.PlayerState.ERROR
|| this.state === LuminaAudioPlayer.PlayerState.LOADING) {
this.clearSeekPending();
return;
}
// A known duration bounds the target, while without one the position is only kept non negative, so a seek is never
// silently snapped to zero just because the duration has not been reported yet.
const request = Number(seconds);
@@ -1004,7 +1152,84 @@
* @returns {Array<Object>} The ordered play descriptors.
*/
getQueue() {
return [...this.queue];
return this.queueEntries.map((entry) => entry.descriptor);
}
/**
* Creates the identity of a new queue entry. Every occurrence in the queue gets its own identity, so two entries
* that repeat the same track are never confused.
* @returns {string} The new entry Id.
*/
createQueueEntryId() {
this.entrySequence += 1;
return `queue-entry-${this.entrySequence}`;
}
/**
* Gets the queue entry that follows the current one.
* @returns {{ entryId: string, descriptor: Object }|null} The identity and descriptor of the next entry, or null at the end of the queue.
*/
getNextDescriptor() {
if (this.currentIndex + 1 >= this.queueEntries.length)
return null;
const entry = this.queueEntries[this.currentIndex + 1];
return { entryId: entry.entryId, descriptor: entry.descriptor };
}
/**
* Advances the queue to the entry with the given identity, without starting a new playback. It is the single commit
* of a queue transition: a gapless handoff passes the identity the engine already scheduled, and a non-gapless
* continuation passes the identity the player selected. The entry is found by identity rather than by position, so
* a linear advance, a wrap to the first entry and a reordered queue all share one path.
* @param {string} entryId - The identity of the queue entry to make current.
* @returns {Object|null} The descriptor the player advanced to, or null when the player is not playing or the entry is not part of the queue.
*/
advanceQueueTo(entryId) {
// A gapless boundary or a continuation only exists while the player is playing. In another state, for example
// while a new play request is loading, the queue cursor belongs to that request and must not be moved by the old timeline.
if (!entryId || this.state !== LuminaAudioPlayer.PlayerState.PLAYING)
return null;
const index = this.queueEntries.findIndex((entry) => entry.entryId === entryId);
// An entry that is no longer part of the queue is not a track this player can describe.
if (index < 0)
return null;
// Moving to the entry that is already current is not a transition. Applying its descriptor again would reset the
// playhead, the streamed fraction and the scrubbing state while the audio keeps playing.
if (index === this.currentIndex)
return this.queueEntries[index].descriptor;
// Navigation history, repeat and shuffle belong to the queue model of step 18. This commit only moves the cursor.
const previousIndex = this.currentIndex;
this.currentIndex = index;
return this.applyTrackDescriptor(this.queueEntries[index].descriptor, previousIndex);
}
/**
* Applies a descriptor as the playing track without changing the queue cursor. It is the shared body of the
* validated queue advance and the scheduled-track adoption.
* @param {Object} descriptor - The descriptor to show as the playing track.
* @param {number|null} [previousIndex] - The queue position that was current before the cursor moved, when the
* commit knows it. It lets the queue update only the items whose current or played state changed.
* @returns {Object} The applied descriptor.
*/
applyTrackDescriptor(descriptor, previousIndex = null) {
this.descriptor = descriptor;
this.currentTime = 0;
this.downloadedFraction = 0;
this.scrubRatio = null;
this.endScrub();
this.endVolumeAdjust();
this.clearBuffering();
// The duration of the next track is reported by its manifest as soon as the engine plays it, so the descriptor value is used here only until that report arrives.
this.duration = Number.isFinite(descriptor.durationInSeconds) && descriptor.durationInSeconds > 0 ? descriptor.durationInSeconds : 0;
this.renderDescriptor();
this.renderProgress();
if (Number.isInteger(previousIndex))
this.updateQueueSelection(previousIndex);
else
this.renderQueue();
this.events.emit(LuminaAudioPlayer.PlayerEvent.DESCRIPTOR_CHANGED, descriptor);
this.events.emit(LuminaAudioPlayer.PlayerEvent.QUEUE_CHANGED, this.getQueue());
return descriptor;
}
/**
@@ -1300,6 +1525,17 @@
events: this.events,
// A shallow frozen copy, so an engine or a test cannot mutate the controller state through the host.
getPreferences: () => Object.freeze({ ...this.preferences }),
// The engine shares the player's endpoint configuration, JSON transport and capability detector, so an
// expired session redirect is followed by the same code that follows it for every other background
// request, and the engine never keeps a second copy of the configuration.
getConfiguration: () => this.getConfiguration(),
fetchJsonAsync: (url, signal, label, options) => this.fetchJsonAsync(url, signal, label, options),
getCapabilityDetector: () => this.capabilities,
// The queue cursor is read from the player for the gapless handoff, so the engine never re-implements the
// traversal and can never pick the wrong occurrence of a repeated track.
getNextDescriptor: () => this.getNextDescriptor(),
advanceQueueTo: (entryId) => this.advanceQueueTo(entryId),
requestNextTrackAsync: (reason) => this.requestNextTrackAsync(reason),
reportTime: (currentTime, duration) => this.handleEngineTime(currentTime, duration),
reportDuration: (duration) => this.handleEngineDuration(duration),
reportProgress: (fraction) => this.handleEngineProgress(fraction),
@@ -1410,6 +1646,11 @@
* Handles the end of the current track reported by the engine.
*/
handleEngineEnded() {
// A player that the user stopped, that already failed, or that is preparing a new track is not moved to ended by a late end report of the previous timeline.
if (this.state === LuminaAudioPlayer.PlayerState.IDLE
|| this.state === LuminaAudioPlayer.PlayerState.ERROR
|| this.state === LuminaAudioPlayer.PlayerState.LOADING)
return;
this.setState(LuminaAudioPlayer.PlayerState.ENDED);
this.renderTransportState();
this.events.emit(LuminaAudioPlayer.PlayerEvent.ENDED);
@@ -1499,18 +1740,52 @@
* An expired session is answered by the server with a redirect to the login page, so the redirect is followed
* here, exactly like the application API helper does it, instead of being mistaken for a failed request.
* @param {string} url - The endpoint URL. Nothing is requested when it is empty.
* @param {AbortSignal} [signal] - An optional signal that cancels the request, used by an engine's prefetch.
* @param {string} [label] - The description used in the failure log, so a caller such as the engine reports its own request rather than a preferences request.
* @param {Object} [options] - The request options.
* @param {string} [options.redirect='follow'] - 'manual' to keep the browser from following a redirect before its target is validated.
* @returns {Promise<*|null|undefined|Object>} The unwrapped data, null when the endpoint answered without data, undefined when the request failed, or the REDIRECTED marker when the session expired and the page is navigating away.
*/
async fetchJsonAsync(url) {
async fetchJsonAsync(url, signal, label = 'a preferences request', options = {}) {
if (!url)
return null;
const requestUrl = resolveConfiguredUrl(url);
if (!requestUrl) {
console.error(`Audio player: ${label} has an endpoint that is not on this origin.`);
return undefined;
}
try {
const response = await fetch(url, {
const request = {
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
signal: signal
};
if (options.redirect === 'manual')
request.redirect = 'manual';
const response = await fetch(requestUrl, request);
if (options.redirect === 'manual' && isRedirectResponse(response)) {
// The browser did not follow the redirect, so the request cannot reach a target that was not validated.
// When the environment exposes the target, it goes through the same origin policy as a followed
// redirect; otherwise the request is reported as a session redirect without requesting the unknown target.
let location = null;
try {
location = response.headers && typeof response.headers.get === 'function'
? response.headers.get('location')
: null;
} catch (error) {
console.debug('Audio player: the redirect target of the request could not be read.', error);
}
});
if (location) {
try {
navigateToRedirect(new URL(location, requestUrl).href);
} catch (error) {
console.debug('Audio player: the redirect target of the request could not be resolved.', error);
}
}
return REDIRECTED;
}
if (response.redirected) {
// The session expired and the server answered with the login page; follow it, and report the redirect, not a failure.
navigateToRedirect(response.url);
@@ -1521,7 +1796,11 @@
const payload = await response.json();
return payload && payload.success === true ? payload.data : null;
} catch (error) {
console.error('Audio player: a preferences request failed.', error);
// A request that a cancelled prefetch, a superseded load or a timeout aborted is an expected stop, not a
// failed request, so it is reported with the same undefined result but without a console error.
if (LuminaAudioPlayer.isAbortError(error))
return undefined;
console.error(`Audio player: ${label} failed.`, error);
return undefined;
}
}
@@ -1538,6 +1817,11 @@
async postJsonAsync(url, data, options = {}) {
if (!url)
return null;
const requestUrl = resolveConfiguredUrl(url);
if (!requestUrl) {
console.error('Audio player: the playback state endpoint is not on this origin.');
return undefined;
}
try {
const headers = {
'Content-Type': 'application/json',
@@ -1549,7 +1833,7 @@
const token = document.querySelector('input[name="__RequestVerificationToken"]');
if (token && token.value)
headers['RequestVerificationToken'] = token.value;
const response = await fetch(url, {
const response = await fetch(requestUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(data ?? {}),
@@ -2271,12 +2555,48 @@
if (!this.dom.queue)
return;
this.dom.queue.innerHTML = '';
const items = this.queue.length > 1 ? this.queue : [];
const items = this.queueEntries.length > 1 ? this.queueEntries : [];
for (let index = 0; index < items.length; index++) {
const entry = this.renderQueueItem(items[index], index, items.length);
const entry = this.renderQueueItem(items[index].descriptor, index, items.length);
if (entry)
this.dom.queue.appendChild(entry);
}
this.renderedQueueOrder = items.map((entry) => entry.entryId);
}
/**
* Updates only the queue items whose current or played state changed after the cursor moved, so a gapless handoff
* of a large play context does not rebuild the whole list at the transition. It falls back to a full render when
* the DOM does not match the queue, for example before the first render or in a host that cannot replace a child.
* @param {number} previousIndex - The zero based queue position that was current before the advance.
*/
updateQueueSelection(previousIndex) {
if (!this.dom.queue)
return;
const total = this.queueEntries.length;
const children = this.dom.queue.children;
// A changed order means the rendered child at an index no longer describes the entry at that index, so the
// list is rebuilt instead of updating the wrong items. The same fallback covers a list that was never rendered.
const hasSameOrder = this.renderedQueueOrder.length === total
&& this.renderedQueueOrder.every((entryId, index) => entryId === this.queueEntries[index].entryId);
if (total <= 1 || !children || children.length !== total || !hasSameOrder
|| typeof this.dom.queue.replaceChild !== 'function') {
this.renderQueue();
return;
}
const from = Math.min(previousIndex, this.currentIndex);
const to = Math.max(previousIndex, this.currentIndex);
if (!Number.isInteger(from) || from < 0 || to >= total) {
this.renderQueue();
return;
}
// isPlayed flips for every position between the old and the new cursor, inclusive, and isCurrent flips at
// both ends, so that inclusive range is exactly the set of items whose state changed.
for (let index = from; index <= to; index++) {
const item = this.renderQueueItem(this.queueEntries[index].descriptor, index, total);
if (item)
this.dom.queue.replaceChild(item, children[index]);
}
}
/**