From e6fa85f7c60e8350d00e4f1e07b1f25a3ec182ae Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sat, 17 Oct 2026 15:08:52 +0300 Subject: [PATCH] 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. --- .../Common/Services/IUrlService.cs | 11 +- .../Common/Services/UrlService.cs | 22 +- .../Views/Shared/_ThemeLayoutScripts.cshtml | 19 +- .../audio-player-demux-capabilities.js | 20 +- .../js/audio-player/audio-player-download.js | 293 ++- .../js/audio-player/audio-player-engine.js | 45 +- .../js/audio-player/audio-player-errors.js | 15 +- .../js/audio-player/audio-player-manifest.js | 321 +++ .../audio-player-pipeline-byte-source.js | 352 +++ .../audio-player-pipeline-engine.js | 1938 +++++++++++++++++ .../audio-player-pipeline-schedulers.js | 390 ++++ .../js/audio-player/audio-player-render.js | 223 +- .../js/audio-player/audio-player-utils.js | 22 + .../wwwroot/js/audio-player/audio-player.js | 372 +++- 14 files changed, 3958 insertions(+), 85 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js diff --git a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs index 93663e4d..dda5ac04 100644 --- a/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/IUrlService.cs @@ -1,7 +1,7 @@ namespace Lumina.Presentation.Web.Common.Services; /// -/// 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. /// public interface IUrlService { @@ -12,4 +12,13 @@ public interface IUrlService /// Optional additional route values, like route parameters. /// An absolute URL to the specified route. string? GetAbsoluteUrl(string routeTemplate, object? additionalRouteValues = null); + + /// + /// 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. + /// + /// The route template of the target page or endpoint, taken from the constants. + /// Optional additional route values, like route parameters. + /// A root relative URL to the specified route. + string? GetRelativeUrl(string routeTemplate, object? additionalRouteValues = null); } diff --git a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs index acc29775..2c6ac95a 100644 --- a/src/Lumina.Presentation.Web/Common/Services/UrlService.cs +++ b/src/Lumina.Presentation.Web/Common/Services/UrlService.cs @@ -38,7 +38,20 @@ public class UrlService : IUrlService /// Thrown when is not one of the route templates defined in the constants. 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}"; + } + + /// + 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}"; } /// diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 67256666..5485eb9b 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -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 @@ + + + + diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js index 9b8f3321..25da12a3 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js @@ -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} The ready demuxer, or null when the pair must be normalized. + * @returns {Promise} 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(); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js index 1642eb2a..dbe093fd 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js @@ -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} 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} 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} 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} 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} The outcome, one of: { isFailed: true, error } when the request failed, { isAborted: true } when it was aborted, { isDestroyed: true } when the downloader was destroyed, { isSatisfied: true } when the range was already satisfied, or { isAborted, isFailed: false, isDestroyed, isStopped } 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} 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); } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js index 673ff0bd..8fe463fe 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js @@ -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 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 { /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js index c40509cd..b513f41d 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -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' }); /** diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js new file mode 100644 index 00000000..e3d37771 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-manifest.js @@ -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 redirect: 'manual', 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} 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 || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js new file mode 100644 index 00000000..1a7691fc --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-byte-source.js @@ -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} 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} 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, 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} 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 || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js new file mode 100644 index 00000000..e80cc0b9 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-engine.js @@ -0,0 +1,1938 @@ +/** + * Media pipeline engine of the audio player: the engine that actually plays a track. + * + * The controller of the player owns the state machine, the play descriptor, the queue and the bar, but it produces no + * audio. This module is the engine the player runs with: it composes the download engine, the container demuxers, the + * WebCodecs decode pipeline and the Web Audio scheduler into one pipeline, and implements the engine interface documented + * in audio-player-engine.js. It is registered under {@link LuminaAudioPlayer.PIPELINE_ENGINE_NAME} and installed on the + * application singleton when this module loads, so the bar drives a real pipeline instead of the silent engine. + * + * What it owns + * ------------ + * A track is represented by a pipeline item: the playback manifest of the track, the downloader that fetches its bytes, + * the demuxer that turns the bytes into encoded packets, the decoder that turns the packets into decoded audio, and the + * scheduler that hands the decoded audio to the renderer. The renderer itself is shared by every track, because it owns + * the AudioContext, the master gain and the ReplayGain gain, and because a gapless transition is produced by appending + * the next track to the schedule of the current one instead of resetting it. + * + * Seeking + * ------- + * A seek is a coordinated reset of every stage. The in flight download request is aborted so the demuxer read that is + * waiting on it is released, the decode loop is stopped, the decoder is reset, the scheduler is moved to the new media + * position, the demuxer is repositioned to the packet boundary that covers that position, and the decode loop is started + * again from there. The renderer adopts the requested position as the media origin of the first buffer it receives, so the + * first decoded frame after a seek is trimmed to the requested position when the demuxer reported a timeline that starts + * before it. A container that seeds the packet timeline with the requested time, such as MP3 or AAC, needs no trim; a + * container that reports the real frame time, such as FLAC, OGG or WAV, is trimmed. A demuxer seek is not sequential: OGG + * binary-searches the byte range, and the MP3 and AAC estimates can land below the target, so the demuxer may read a gap + * below the byte position the download loop fetches. The seek aware byte source serves such a window with a one-shot + * bounded range request, so the demuxer scan never waits for a download that would only reach the gap at the end of the + * file. Seeks into bytes that are already downloaded do not fetch them again: the downloader keeps every byte it already + * has, as the download engine documents. + * + * Underrun + * -------- + * A decoder that catches the download frontier leaves the schedule empty while the track is still playing. The engine + * watches the scheduled ahead duration of the renderer: when it reaches zero before the stream is complete, the engine + * suspends the renderer and reports buffering through the host, then resumes the renderer as soon as enough audio has been + * scheduled again. A draining schedule at the very end of the track is not an underrun, because the renderer reports the + * end on its own once the decode pipeline declared the stream complete. + * + * Gapless transitions + * ------------------- + * When the user enabled gapless playback and the player queue holds another item, the engine prefetches the next item as + * soon as the current one is loaded: it fetches the next manifest, opens its demuxer, and pre-decodes the first seconds of + * its audio into memory. The prefetch does not run an open-ended download next to the current one: it fetches only the + * windows its pre-decode needs, as bounded range requests, and leaves the sequential download of the next track stopped + * until the handoff. Once the current decoder has scheduled its last frame, the pre-decoded audio is appended to the + * renderer schedule, exactly after the audio of the current track, the download of the next track resumes from its first + * missing byte, and the rest of the track is decoded into the same schedule. The engine then switches the current item at the exact media position where the next + * audio starts, reports the new duration and asks the player to advance its queue, so the bar shows the new track while + * the audio never stops. Only the last track of a continuous chain declares the stream complete, which is what keeps the + * renderer from reporting an end between two gapless items. + * + * Failures + * -------- + * A download, demux or decode failure that happens mid-stream is reported once, through host.reportError, and stops the + * pipeline cleanly; it never escapes as an unhandled rejection and never leaves the renderer or the downloader running. + * A failure of a prefetch is dropped instead, because it must not interrupt the track that is playing. A track whose + * manifest is not a direct play needs the normalized delivery pipeline, which this engine does not implement yet, so it + * is reported as an engine load failure with the {@link LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED} + * reason. A play descriptor must name a track, not an album or an artist, because the manifest endpoint is addressed by the + * track and its album and artist; expanding an album or an artist context into its tracks is the queue engine's job. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The name the media pipeline engine is registered and selected under. + * @readonly + * @type {string} + */ + LuminaAudioPlayer.PIPELINE_ENGINE_NAME = 'pipeline'; + + /** + * The scheduled ahead duration, in seconds, below which a playing renderer is treated as having underrun. + * @readonly + * @type {number} + */ + const UNDERRUN_THRESHOLD_SECONDS = 0.05; + + /** + * The scheduled ahead duration, in seconds, that must be reached again before an underrun pause is resumed. + * @readonly + * @type {number} + */ + const UNDERRUN_RESUME_SECONDS = 0.25; + + /** + * The interval, in milliseconds, of the monitor that detects underruns and gapless track boundaries. + * @readonly + * @type {number} + */ + const MONITOR_INTERVAL_MS = 150; + + /** + * The margin, in seconds, that is kept between the end of the scheduled audio and the deadline for a gapless prefetch. + * The handoff must be appended before the current audio drains, so the wait never runs to the very end of the schedule. + * @readonly + * @type {number} + */ + const PREFETCH_HANDOFF_MARGIN_SECONDS = 0.15; + + /** + * The longest, in seconds, that the end of a decode waits for a gapless prefetch. A prefetch that is not ready by this + * deadline is abandoned and the track ends normally, so a stalled next track can never hold the current one open. + * @readonly + * @type {number} + */ + const PREFETCH_HANDOFF_MAX_WAIT_SECONDS = 5; + + /** + * 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); + } + + /** + * The media pipeline engine. See the module documentation for its behavior. It fulfills the engine interface + * documented in audio-player-engine.js. + */ + class MediaPipelineEngine { + /** + * Creates an instance of MediaPipelineEngine. + * @param {Object} host - The engine host provided by the player controller. + * @param {Object} [options] - The engine options, for injection in a test. + * @param {LuminaAudioPlayer.TrackRenderer} [options.renderer] - The renderer to use instead of creating one. + * @param {LuminaAudioPlayer.PlayerCapabilities} [options.capabilities] - The capability detector to use. + * @param {Object} [options.configuration] - The endpoints configuration. It overrides the host configuration and exists as an injection seam for a test or a composition that provides its own transport. + * @param {Function} [options.fetchJsonAsync] - The JSON transport to use instead of the host transport, as an injection seam. It has the signature of the host method. + */ + constructor(host, options = {}) { + this.host = host; + this.options = options || {}; + this.events = host.events; + // The player's detector is reused when the host exposes it, so the engine never runs a second, independent capability detection or keeps a second memoization cache. + this.capabilities = this.options.capabilities + || (typeof host.getCapabilityDetector === 'function' ? host.getCapabilityDetector() : null) + || new LuminaAudioPlayer.PlayerCapabilities(); + this.renderer = this.options.renderer || new LuminaAudioPlayer.TrackRenderer({ + events: this.events, + replayGainMode: host.getPreferences().replayGainMode, + onTimeUpdate: (currentTime) => this.handleTimeUpdate(currentTime), + onEnded: () => this.handleEnded() + }); + // The current track of the pipeline. The renderer is shared by every track. + this.current = null; + // The next item whose audio was already appended to the renderer schedule but whose media position has not started yet. It becomes current at the exact position its audio begins. + this.nextItem = null; + this.monitorTimer = null; + this.isMonitoring = false; + this.isUserPaused = false; + this.isUnderrunPaused = false; + this.destroyed = false; + // The token of the load that owns the pipeline, so a second load that overtakes the first one stops it. + this.loadToken = null; + // True while a load is between the start of its teardown and the installation of its item. The old gapless timeline must not advance its queue or end under a load that is about to replace it. + this.isLoadingTrack = false; + this.unsubscribePreferences = null; + this.subscribeToPreferences(); + } + + //+======================================================================================+ + //| Engine interface | + //+======================================================================================+ + + /** + * Loads a track: fetches its playback manifest, prepares its download, demux and decode stages, and starts decoding + * ahead. Playback itself is started by playAsync, so the caller can keep the preparation and the audio separate. + * @param {Object} descriptor - The play descriptor of the track, per {@link LuminaAudioPlayer.createPlayDescriptor}. + * @param {Object} [options] - The load options. + * @param {boolean} [options.keepBuffering] - True to keep a loading state that was handed to the load by the player, used by an automatic continuation so the teardown of the previous track does not clear it. + * @returns {Promise} A promise that completes when the track is ready to play. + * @throws {LuminaAudioPlayer.PlayerError} When the manifest cannot be read, the track cannot be played directly, or a stage of the pipeline cannot be created. + */ + async loadAsync(descriptor, options = {}) { + if (this.destroyed) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The media pipeline engine was destroyed.'); + // The manifest request of the load that is being replaced is aborted, so a slow session never keeps a stale request alive behind the track that the newer load owns. + this.abortLoad(this.loadToken); + const token = { + abortController: typeof AbortController === 'function' ? new AbortController() : null + }; + this.loadToken = token; + this.isLoadingTrack = true; + try { + await this.teardownPlaybackAsync(null, token, options.keepBuffering === true); + if (!this.isLoadCurrent(token)) + throw this.createSupersededLoadError(); + this.isUserPaused = false; + this.isUnderrunPaused = false; + const signal = token.abortController ? token.abortController.signal : undefined; + const manifest = await this.fetchManifestAsync(descriptor, signal); + if (!this.isLoadCurrent(token)) + throw this.createSupersededLoadError(); + if (manifest.directPlay !== true) { + // The normalized delivery pipeline is a later stage; until it exists, the track is reported instead of being played as its stored bytes, which would produce noise or a decoder error. + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The track needs a normalized delivery the player does not support yet.', { reason: LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED }); + } + this.renderer.configure(manifest); + const item = await this.buildItemAsync(descriptor, manifest, false); + if (!this.isLoadCurrent(token) || this.destroyed) { + await this.disposeItemAsync(item); + throw this.createSupersededLoadError(); + } + item.base = 0; + this.current = item; + this.isLoadingTrack = false; + if (item.duration > 0) + this.renderer.setTimelineDuration(item.duration); + this.host.reportDuration(item.duration); + this.startDecodeLoop(item); + this.startGaplessPrefetch(item); + } catch (error) { + // A failure of a load that was overtaken by a newer one belongs to a playback the user already replaced, so it is reported as a superseded load, which the player ignores, + // instead of surfacing an error over the track that the newer load owns. The rejection also stops the stale playAsync continuation before it can set READY or PLAYING over + // the newer request.A stale load leaves the loading flag to the newer load. + if (!this.isLoadCurrent(token)) + throw this.createSupersededLoadError(); + this.isLoadingTrack = false; + throw error; + } + } + + /** + * Creates the typed error that tells the player a load was overtaken by a newer play request. + * @returns {LuminaAudioPlayer.PlayerError} The superseded load error. + */ + createSupersededLoadError() { + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The load was superseded by a newer play request.', { reason: LuminaAudioPlayer.PlayerErrorReason.LOAD_SUPERSEDED }); + } + + /** + * Aborts the manifest request of a load, so a teardown or a newer load never leaves a stale request running. + * @param {Object|null} token - The load token whose request is aborted. + */ + abortLoad(token) { + if (!token || !token.abortController) + return; + try { + token.abortController.abort(); + } catch (error) { + console.debug('Audio player: the manifest request of the replaced load could not be aborted.', error); + } + } + + /** + * Checks whether a load is still the one that owns the pipeline. + * @param {Object} token - The token of the load. + * @returns {boolean} True when this load is still current and the engine was not destroyed. + */ + isLoadCurrent(token) { + return !this.destroyed && this.loadToken === token; + } + + /** + * Releases the currently prepared track without destroying the engine, which keeps its renderer and audio context for a later play. + * The player calls it when a stop arrives while an automatic continuation is loading: the stopped player should not keep a track loaded that it started only to continue a queue. + * @returns {Promise} A promise that completes when the prepared track was released. + */ + async discardCurrentAsync() { + if (this.destroyed) + return; + await this.teardownPlaybackAsync(null, null, false); + } + + /** + * Starts, or resumes, audible playback. + * @returns {Promise} A promise that completes when the renderer is running. + */ + async playAsync() { + this.isUserPaused = false; + this.isUnderrunPaused = false; + this.host.reportBuffering(false); + if (this.current) + this.current.downloader.setPlaybackPaused(false); + // An attached next item is about to own the playhead, so its sequential download resumes with playback. The detached prefetch stays stopped until the handoff and is never started by a resume. + if (this.nextItem && this.nextItem.downloader) { + this.nextItem.downloader.setPlaybackPaused(false); + this.nextItem.downloader.startAsync(); + if (!this.nextItem.isDecodeComplete) + this.resumeDecodeAfterSettledLoopAsync(this.nextItem); + } + await this.renderer.playAsync(); + this.startMonitor(); + } + + /** + * Suspends audible playback, keeping the position. The downloader stops with the pause only when the stored 'keep downloading while paused' preference is off, which the download engine enforces itself. + * @returns {Promise} A promise that completes when playback was suspended. + */ + async pauseAsync() { + this.isUserPaused = true; + this.isUnderrunPaused = false; + this.stopMonitor(); + this.host.reportBuffering(false); + if (this.current) + this.current.downloader.setPlaybackPaused(true); + // The attached next item started its sequential download at the handoff preparation, so it follows the same + // pause policy as the current item. The detached prefetch is deliberately not touched: it has no sequential + // download, and forwarding the paused state to it would start one when keep-downloading-while-paused is enabled. + if (this.nextItem && this.nextItem.downloader) + this.nextItem.downloader.setPlaybackPaused(true); + await this.renderer.pauseAsync(); + } + + /** + * Moves the playhead to a position of the current track. A position that is already downloaded is not fetched + * again; a position that is not downloaded triggers the range fetch of the download engine. + * @param {number} seconds - The target position of the current track, in seconds. + * @param {boolean} [isRetry=false] - True when this is the one automatic retry after an interrupted seek. + * @returns {Promise} A promise that completes when the decode pipeline resumed at the target. + */ + async seekAsync(seconds, isRetry = false) { + const item = this.current; + if (!item || this.destroyed) + return; + // The order is deliberate: stop the old timeline, reset the decoder, reposition the demuxer, and only then let + // the decode loop schedule frames at the target. Every await is followed by an isSeekCurrent check, so a newer + // seek can abandon this one without touching the pipeline the newer seek already owns. + // Every seek owns a token, so a seek that is overtaken by a newer one returns at its next await instead of + // resetting the demuxer, the decoder or the shared renderer that the newer seek is already using. + const token = {}; + item.seekToken = token; + // A decode completion that is parked while it waits for a prefetch is released at once, so the seek never waits for a stalled next track that is kept across the seek. + this.cancelPrefetchWait(item); + // A seek is a resume when the audio was playing or when an underrun had paused it. A seek requested by a user + // pause stays paused, and a seek in the ended state is refused by the player. The state is captured before the seek resets it. + const wasPlaying = this.renderer.isPlaying(); + const shouldResume = !this.isUserPaused && (wasPlaying || this.isUnderrunPaused); + const requested = Math.max(0, toFiniteNumber(seconds) === null ? 0 : Number(seconds)); + const position = item.duration > 0 ? Math.min(requested, item.duration) : requested; + const nextEntry = this.getNextQueueEntry(); + // From here until the target is scheduled, the seek owns the timeline: the monitor does not pause it and a boundary crossing of the old timeline does not advance the queue under it. + item.isSeeking = true; + item.isDecodeComplete = false; + item.continueToEntry = null; + item.skipUntilSeconds = null; + item.hasScheduledAudio = false; + item.scheduler.setSuppressed(true); + // A seek into bytes that are already downloaded needs no loading state: the player's own buffered range check already knows the target is available, so only an uncovered target reports engine buffering. + if (!this.isSeekTargetBuffered(item, position)) + this.host.reportBuffering(true); + + // The old sources are stopped and the playhead is moved before any teardown is awaited, so the seek is heard immediately and the prefetch teardown cannot extend the latency of the reposition. + item.loopToken = null; + item.downloader.abort(); + let decoderReset = null; + let decoderResetError = null; + try { + decoderReset = item.decoder.resetAsync(); + } catch (error) { + decoderResetError = error; + } + try { + this.renderer.seekTo(item.base + position); + } catch (error) { + this.failItem(item, error); + return; + } + + // An attached next item had its audio in the schedule that the reset above stopped, so it is released and a fresh prefetch is started after the seek. + // A detached prefetch does not touch the renderer, and it still describes the same successor, so it is kept without being torn down and rebuilt. + if (this.nextItem) { + const detached = this.nextItem; + this.nextItem = null; + this.renderer.cancelTrackGainChange(); + await this.disposeItemAsync(detached); + if (!this.isSeekCurrent(item, token)) + return; + } + if (item.prefetch && !this.canKeepPrefetch(item.prefetch, nextEntry)) { + await this.cancelPrefetchAsync(item); + if (!this.isSeekCurrent(item, token)) + return; + } + if (decoderResetError) { + if (LuminaAudioPlayer.isDownloadAbort(decoderResetError)) + return this.recoverInterruptedSeekAsync(item, token, position, isRetry); + this.failItem(item, decoderResetError); + return; + } + if (decoderReset) { + try { + await decoderReset; + } catch (error) { + if (LuminaAudioPlayer.isDownloadAbort(error)) + return this.recoverInterruptedSeekAsync(item, token, position, isRetry); + this.failItem(item, error); + return; + } + } + if (!this.isSeekCurrent(item, token)) + return; + await this.waitForDecodeLoopAsync(item); + if (!this.isSeekCurrent(item, token)) + return; + // The old loop may have reached the end of the stream while it was being stopped, after the seek already cleared + // the flag. It is cleared again here, so the new loop is not mistaken for one whose decode already finished. + item.isDecodeComplete = false; + // The loading state belongs to the frames of the seek target only, so the first frame notification is re-armed + // once the old decode loop has definitively stopped, and the frames of that loop are no longer dropped. + item.scheduler.rearm(); + item.scheduler.setSeekTarget(position); + item.scheduler.setSuppressed(false); + if (item.source) + item.source.setSeeking(true); + item.downloader.seek(position); + // startAsync clears the aborted state that the abort above set. The sequential loop only runs when playback is + // active and the keep-downloading-while-paused preference allows it, but the seek itself does not depend on it: + // the seek aware source fetches every window the demuxer needs for the target with bounded range requests. + item.downloader.startAsync(); + const seekOutcome = await this.runDemuxerOperationAsync(item, token, () => item.demuxer.seekToTimeAsync(position)); + if (seekOutcome.skipped) + return; + if (seekOutcome.error) { + if (!this.isSeekCurrent(item, token)) + return; + if (LuminaAudioPlayer.isDownloadAbort(seekOutcome.error)) + return this.recoverInterruptedSeekAsync(item, token, position, isRetry); + this.failItem(item, seekOutcome.error); + return; + } + if (!this.isSeekCurrent(item, token)) + return; + if (seekOutcome.value === null) { + // A stream the demuxer cannot reposition, for example one whose length is not known, is re-read from its + // start and the packets that end before the target are dropped, which still lands on the requested audio. + const rebuildOutcome = await this.runDemuxerOperationAsync(item, token, () => this.rebuildDemuxerAsync(item)); + if (rebuildOutcome.skipped) + return; + if (rebuildOutcome.error) { + if (!this.isSeekCurrent(item, token)) + return; + if (LuminaAudioPlayer.isDownloadAbort(rebuildOutcome.error)) + return this.recoverInterruptedSeekAsync(item, token, position, isRetry); + this.failItem(item, rebuildOutcome.error); + return; + } + item.skipUntilSeconds = position; + } + if (!this.isSeekCurrent(item, token)) + return; + // A resume requested while the seek was running also counts, which is why the renderer is consulted again: a + // paused track that the user resumed during the seek is playing even though the seek started without playback. + const shouldResumeNow = !this.isUserPaused && (shouldResume || this.renderer.isPlaying()); + if (shouldResumeNow) { + // A seek requested while the audio was playing, or while an underrun had paused it, resumes the renderer, + // so the schedule of the new position actually advances the playhead and reports its end. A pause that the user requested while the seek was being resolved still wins. + this.isUnderrunPaused = false; + try { + await this.renderer.playAsync(); + } catch (error) { + this.failItem(item, error); + return; + } + if (!this.isSeekCurrent(item, token)) + return; + this.startMonitor(); + } + this.startDecodeLoop(item); + // The decode of the seek may already have reached the end of the track, in which case the completion has + // already made its end decision and a prefetch started now would never be appended. + if (!item.isDecodeComplete) + this.startGaplessPrefetch(item); + } + + /** + * Runs an operation that mutates the demuxer of an item under a gate, so two seeks of the same track can never + * reposition or rebuild the same demuxer at the same time. A seek that is overtaken while it waits for the gate returns without running its operation. + * @param {Object} item - The item whose demuxer is operated on. + * @param {Object} token - The token of the seek that requests the operation. + * @param {Function} operation - The operation to run, returning a value or a promise of one. + * @returns {Promise} The outcome, with a value, an error, or the skipped flag when a newer seek owns the item. + */ + async runDemuxerOperationAsync(item, token, operation) { + // A demuxer is not safe to reposition or rebuild concurrently. A previous seek may still be operating on it, so + // the new operation waits for that gate before it reads the current seek token and takes the gate itself. + if (item.demuxerOperation) { + try { + await item.demuxerOperation; + } catch (error) { + // The gate never rejects, so this is only a teardown of the operation that held it. + } + } + if (!this.isSeekCurrent(item, token)) + return { skipped: true }; + let release = null; + // The gate resolves rather than rejects. One seek's failure must not become the next seek's failure just + // because the next seek was waiting behind it. + const gate = new Promise((resolve) => { + release = resolve; + }); + item.demuxerOperation = gate; + try { + return { value: await operation() }; + } catch (error) { + return { error }; + } finally { + // Clear the handle only if it is still ours. A newer seek may already have replaced it, and clearing that + // newer gate would let a third operation run concurrently with it. + if (item.demuxerOperation === gate) + item.demuxerOperation = null; + // Release in every outcome, including a failed operation, or the next seek waits forever. + release(); + } + } + + /** + * Checks whether a seek is still the one that owns the current track, so a seek that was overtaken by a newer one stops before it touches shared state. + * @param {Object} item - The item the seek was requested on. + * @param {Object} token - The token of the seek. + * @returns {boolean} True when this seek is still the current one. + */ + isSeekCurrent(item, token) { + return !this.destroyed && this.current === item && item.seekToken === token + && !item.failed && !item.stopped && !item.disposed; + } + + /** + * Checks whether a position of an item is already covered by its downloaded time ranges, so a seek into it does not need to report engine buffering. + * @param {Object} item - The item whose downloaded ranges are checked. + * @param {number} seconds - The position to check. + * @returns {boolean} True when the position is already downloaded. + */ + isSeekTargetBuffered(item, seconds) { + if (!item || !item.downloader) + return false; + const value = Number(seconds); + if (!Number.isFinite(value)) + return false; + // The fraction check answers from the byte buffer without allocating a time range list, which matters because this runs on a seek rather than on a network chunk. + if (typeof item.downloader.coversTime === 'function') { + try { + return item.downloader.coversTime(value); + } catch (error) { + console.debug('Audio player: the buffered state of the seek target could not be read.', error); + return false; + } + } + if (typeof item.downloader.getTimeRanges !== 'function') + return false; + try { + return item.downloader.getTimeRanges().some((range) => + Number.isFinite(range.start) && Number.isFinite(range.end) + && value >= range.start && value <= range.end); + } catch (error) { + console.debug('Audio player: the downloaded ranges of the seek target could not be read.', error); + return false; + } + } + + /** + * Recovers an interrupted seek. The seek is retried once, which succeeds when the interruption was a transient + * request abort such as a pause that reached the downloader; if the retry is interrupted too, the seek is reported + * as a clean download failure instead of leaving the item in a silent, permanently buffering state. + * @param {Object} item - The item whose seek was interrupted. + * @param {Object} token - The token of the interrupted seek. + * @param {number} position - The seek target, in seconds. + * @param {boolean} isRetry - True when the interrupted seek was already the automatic retry. + * @returns {Promise} A promise that completes when the seek was retried or failed. + */ + async recoverInterruptedSeekAsync(item, token, position, isRetry) { + if (!this.isSeekCurrent(item, token)) + return; + this.clearSeekState(item); + if (!isRetry) { + await this.seekAsync(position, true); + return; + } + this.failItem(item, new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The seek was interrupted before its target could be read.')); + } + + /** + * Clears the state a seek owns, so a seek that cannot continue leaves a pipeline that can be resumed or retried instead of an item whose monitor, boundary and end checks all return early. + * @param {Object} item - The item whose seek state is cleared. + */ + clearSeekState(item) { + this.cancelPrefetchWait(item); + item.isSeeking = false; + if (item.scheduler) { + item.scheduler.setSuppressed(false); + item.scheduler.rearm(); + } + if (item.source) + item.source.setSeeking(false); + } + + /** + * Sets the output volume. The player folds the mute state into the volume it sends, so the renderer receives zero while the player is muted. + * @param {number} volume - The output volume, between 0 and 1. + * @returns {Promise} A promise that completes when the renderer applied the volume. + */ + async setVolumeAsync(volume) { + await this.renderer.setVolumeAsync(volume); + } + + /** + * Gets the time ranges of the current track that were already downloaded, so the player can tell whether a seek + * target is buffered and can show the streamed part of the progress bar. + * @returns {Array<{ start: number, end: number }>} The downloaded time ranges, in seconds. + */ + getBufferedTimeRanges() { + if (!this.current) + return []; + try { + return this.current.downloader.getTimeRanges(); + } catch (error) { + console.debug('Audio player: the downloaded ranges of the current track could not be read.', error); + return []; + } + } + + /** + * Checks whether the engine was destroyed. + * @returns {boolean} True when the engine was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Reports the downloaded fraction of an item to the player once, used at a gapless handoff where the prefetched downloader has nothing left to emit. + * @param {Object} item - The item whose progress is reported. + */ + reportItemProgress(item) { + if (!item || !item.downloader) + return; + try { + const fraction = Number(item.downloader.getDownloadedFraction()); + if (Number.isFinite(fraction)) + this.host.reportProgress(Math.min(1, Math.max(0, fraction))); + } catch (error) { + console.debug('Audio player: the downloaded fraction of the next track could not be read.', error); + } + } + + /** + * Releases every resource of the engine, including the audio context of the renderer. + * @returns {Promise} A promise that completes when every resource was released. + */ + async destroyAsync() { + if (this.destroyed) + return; + this.destroyed = true; + this.isLoadingTrack = false; + this.stopMonitor(); + if (this.unsubscribePreferences) { + this.unsubscribePreferences(); + this.unsubscribePreferences = null; + } + await this.teardownPlaybackAsync(this.loadToken, null); + try { + await this.renderer.destroyAsync(); + } catch (error) { + console.error('Audio player: the media pipeline renderer could not be destroyed.', error); + } + } + + //+======================================================================================+ + //| Pipeline setup | + //+======================================================================================+ + + /** + * Builds the pipeline item of a track: its downloader, its demuxer, its decoder and its scheduler. + * @param {Object} descriptor - The play descriptor of the track. + * @param {Object} manifest - The playback manifest of the track. + * @param {boolean} isPrefetch - True to build the item for a gapless prefetch, which buffers instead of scheduling. + * @param {Function} [onItemCreated] - Called with the item as soon as its downloader exists, so a cancellation can + * stop the prefetch before the rest of its stages were built. + * @returns {Promise} The prepared item. + */ + async buildItemAsync(descriptor, manifest, isPrefetch, onItemCreated) { + // Build in dependency order: downloader and byte source first, then demuxer, scheduler and decoder. The catch + // below disposes the partial item if a later stage fails, so a failed load never leaves a half-built pipeline. + const preferences = this.host.getPreferences(); + const duration = this.resolveDuration(manifest, descriptor, null); + const item = { + descriptor, + // The identity of the queue entry this item represents, when it came from a gapless prefetch. + entryId: null, + manifest, + downloader: null, + source: null, + demuxer: null, + decoder: null, + scheduler: null, + base: 0, + duration: duration, + isDecodeComplete: false, + isPreloading: isPrefetch, + isGainScheduled: false, + isSeeking: false, + seekToken: null, + demuxerOperation: null, + // The next queue entry to start normally when a gapless handoff could not be prepared before the track ended, so a slow or failed prefetch never strands the queue. + continueToEntry: null, + skipUntilSeconds: null, + loopToken: null, + loopPromise: null, + prefetch: null, + prefetchWaitCancel: null, + disposed: false, + failed: false, + stopped: false, + hasScheduledAudio: false + }; + const streamPath = LuminaAudioPlayer.resolveStreamUrl(manifest, descriptor, this.getConfiguration()); + item.downloader = LuminaAudioPlayer.createTrackDownloader({ + url: streamPath, + durationInSeconds: duration, + shouldKeepDownloadingWhilePaused: preferences.shouldKeepDownloadingWhilePaused, + events: this.events, + onProgress: (downloadedFraction) => { + if (item === this.current) + this.host.reportProgress(downloadedFraction); + }, + onError: (error) => this.handleDownloadFailure(item, error) + }); + if (typeof onItemCreated === 'function') + onItemCreated(item); + // The demuxer reads through the seek aware source, so a seek can fetch a window below the byte target of the download loop instead of waiting for bytes the loop never fetches. + item.source = new LuminaAudioPlayer.SeekAwareByteSource(item.downloader); + if (isPrefetch) { + // A prefetch fetches only the windows its pre-decode needs, through one-shot range requests, instead of + // running a second open-ended download from the moment the current track starts. Its sequential download is + // started at the handoff, from the first byte that is still missing. + item.source.setSeeking(true); + } else { + item.downloader.startAsync(); + } + try { + const demuxer = await LuminaAudioPlayer.createDemuxerForManifest(manifest, { + source: item.source, + capabilities: this.capabilities, + events: this.events, + onError: (error) => this.failItem(item, error) + }); + if (!demuxer) { + // A cancelled or aborted header probe and a transport failure are not properties of the track, so + // they are reported as themselves. Only a probe that actually concluded the bundled player cannot + // handle the bytes is reported as a track the server has to normalize. + if (item.downloader.isAborted || item.stopped || item.disposed) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED, 'The header probe of the track was aborted.'); + const downloadError = item.downloader.getError(); + if (downloadError) + throw downloadError; + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The track cannot be demuxed and decoded by the bundled player.', { reason: LuminaAudioPlayer.PlayerErrorReason.NORMALIZED_DELIVERY_REQUIRED }); + } + item.demuxer = demuxer; + const configuration = demuxer.getConfiguration(); + if (!configuration) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The demuxer of the track reported no decoder configuration.'); + const schedulerTarget = isPrefetch ? new LuminaAudioPlayer.BufferingScheduler() : this.renderer; + item.scheduler = new LuminaAudioPlayer.SeekableScheduler(schedulerTarget, () => { + item.hasScheduledAudio = true; + // The first frame of a seek is what ends its loading state, not the moment the seek was requested. The same point ends the on-demand range fetch mode of the source: + // from here the demuxer reads forward from the seek target, which the regular download loop fetches. A prefetch keeps its on-demand mode until + // the handoff, because its download loop does not run while it pre-decodes. + if (item.source && item === this.current) + item.source.setSeeking(false); + if (item.isSeeking) { + item.isSeeking = false; + if (item === this.current) + this.host.reportBuffering(false); + } + }); + item.decoder = LuminaAudioPlayer.createTrackDecoder({ + scheduler: item.scheduler, + config: configuration, + onError: (error) => this.failItem(item, error) + }); + item.duration = this.resolveDuration(manifest, descriptor, demuxer); + return item; + } catch (error) { + await this.disposeItemAsync(item); + throw error; + } + } + + /** + * Resolves the duration of a track: the exact duration the demuxer stated, then the manifest duration, then the duration of the play descriptor. + * @param {Object} manifest - The playback manifest of the track. + * @param {Object} descriptor - The play descriptor of the track. + * @param {LuminaAudioPlayer.Demuxer|null} demuxer - The demuxer of the track, or null before it exists. + * @returns {number} The duration in seconds, or zero when no source knows it. + */ + resolveDuration(manifest, descriptor, demuxer) { + const candidates = [ + demuxer ? demuxer.getDuration() : null, + manifest && manifest.durationInSeconds, + descriptor && descriptor.durationInSeconds + ]; + for (const candidate of candidates) { + const value = toFiniteNumber(candidate); + if (value !== null && value > 0) + return value; + } + return 0; + } + + /** + * Starts the decode loop of an item when one is not already running. + * @param {Object} item - The item to decode. + * @returns {Promise|null} The loop promise, or null when the loop was already running or the item stopped. + */ + startDecodeLoop(item) { + if (!item || item.stopped || item.disposed || this.destroyed) + return null; + if (item.loopPromise) + return item.loopPromise; + const token = {}; + item.loopToken = token; + const loop = this.runDecodeLoopAsync(item, token); + item.loopPromise = loop; + loop.finally(() => { + if (item.loopToken === token) + item.loopToken = null; + if (item.loopPromise === loop) + item.loopPromise = null; + }).catch(() => { + // The loop reports its own failures through the engine, so a rejection is only a teardown and is swallowed + // here, so the bookkeeping promise can never surface as an unhandled rejection. + }); + return loop; + } + + /** + * Resumes the decode of an attached next item after its previous loop settles. A pause may have cancelled the loop + * request, and the loop is still finishing when the user resumes; starting a second loop immediately would return the dying one and never decode the track. + * @param {Object} item - The next item whose decode is resumed. + */ + resumeDecodeAfterSettledLoopAsync(item) { + if (!item || item.isDecodeComplete || item.stopped || item.failed || this.destroyed) + return; + const pending = item.loopPromise; + if (!pending) { + this.startDecodeLoop(item); + return; + } + Promise.resolve(pending).catch(() => {}).finally(() => { + // The item may have advanced to the playhead while its old loop was settling, so it is resumed when it is either still the attached next item or the current one. + if ((this.nextItem === item || this.current === item) && !item.isDecodeComplete && !item.stopped + && !item.failed && !this.destroyed && !this.isUserPaused) + this.startDecodeLoop(item); + }).catch(() => { + console.debug('Audio player: the resumed next track decode could not be started.'); + }); + } + + /** + * Runs the decode loop of an item: it reads encoded packets from the demuxer, feeds them to the decoder, and stops + * when the stream ends, the preload of a gapless prefetch is satisfied, or the item is stopped. + * @param {Object} item - The item to decode. + * @param {Object} token - The token that identifies this loop, so a seek can retire it. + * @returns {Promise} A promise that completes when the loop stops. + */ + async runDecodeLoopAsync(item, token) { + try { + while (!this.destroyed && !item.stopped && !item.failed && item.loopToken === token) { + if (item.isPreloading && item.scheduler.getScheduledAheadSeconds() >= LuminaAudioPlayer.GAPLESS_PRELOAD_SECONDS) + return; + if (item.isDecodeComplete) + return; + const packet = await item.demuxer.readPacketAsync(); + if (item.loopToken !== token || item.stopped || item.failed || this.destroyed) + return; + if (packet === null) { + await item.decoder.flushAsync(); + // A seek can retire the loop while the final flush is pending, and the decoder reset makes that + // flush resolve normally instead of rejecting. The completion must not be recorded for a loop that + // no longer owns the item, or the fresh seek loop would exit immediately at the completed flag. + if (item.loopToken !== token || item.stopped || item.failed || this.destroyed) + return; + item.isDecodeComplete = true; + await this.handleDecodeCompleteAsync(item, token); + return; + } + if (this.shouldSkipPacket(item, packet)) + continue; + const accepted = await item.decoder.decodeAsync(packet); + if (!accepted) { + if (item.decoder.isStopped() && item.decoder.getError()) + this.failItem(item, item.decoder.getError()); + return; + } + } + } catch (error) { + if (this.destroyed || item.stopped || LuminaAudioPlayer.isDownloadAbort(error)) + return; + this.failItem(item, error); + } + } + + /** + * Checks whether a packet of a demuxer that was restarted from the beginning ends before the seek target, in which + * case it is dropped. The packet that covers the target arms the trim of the scheduler. + * @param {Object} item - The item the packet belongs to. + * @param {Object} packet - The encoded packet. + * @returns {boolean} True when the packet must be skipped. + */ + shouldSkipPacket(item, packet) { + if (item.skipUntilSeconds === null) + return false; + const target = item.skipUntilSeconds; + const start = toFiniteNumber(packet.timestamp) === null ? 0 : Number(packet.timestamp) / 1000000; + const duration = toFiniteNumber(packet.duration) === null ? 0 : Number(packet.duration) / 1000000; + if (start + duration <= target + LuminaAudioPlayer.SEEK_TRIM_EPSILON_SECONDS) + return true; + item.skipUntilSeconds = null; + item.scheduler.setSeekTarget(target); + return false; + } + + /** + * Handles the end of the decode of an item. A prefetched item only records it; the current item either hands over + * to the prefetched next track or declares the stream complete, which is what lets the renderer report the end. + * @param {Object} item - The item whose decode ended. + * @param {Object} [loopToken] - The token of the decode loop that reached the end, when the completion was observed + * by that loop. It is omitted when the completion is re-evaluated for an item that already became current. + * @returns {Promise} A promise that completes when the completion was handled or abandoned as stale. + */ + async handleDecodeCompleteAsync(item, loopToken) { + // The state of the item at the moment the completion was observed, so a seek that overtakes the possibly long wait for a gapless prefetch is detected before it is acted on. + const seekToken = item.seekToken; + if (item !== this.current) { + // A prefetched item records its own completion; the handoff that consumes it decides when that matters. + item.isDecodeComplete = true; + item.isPreloading = false; + return; + } + if (!this.isCompletionCurrent(item, loopToken, seekToken)) + return; + item.isDecodeComplete = true; + item.isPreloading = false; + if (item.isSeeking) { + // A seek whose decode produced no frame, for example one to the very end of the track, has nothing left to + // schedule, so its loading state is cleared and the track is reported as ended instead of spinning. + item.isSeeking = false; + if (item.source) + item.source.setSeeking(false); + this.host.reportBuffering(false); + if (!item.hasScheduledAudio) { + item.downloader.abort(); + this.stopMonitor(); + this.renderer.markStreamComplete(); + this.renderer.pauseAsync().catch((error) => { + console.debug('Audio player: the renderer could not be paused after an empty seek.', error); + }); + // The track ended and a finished pipeline is not retained: its decoder, demuxer, downloader and byte + // buffer are released. The disposal is scheduled after this callback because the decode loop that is calling it is the loop the disposal waits for. + this.current = null; + this.host.reportEnded(); + Promise.resolve().then(() => this.disposeItemAsync(item)).catch((error) => { + console.debug('Audio player: the track that ended at an empty seek could not be released.', error); + }); + return; + } + } + if (this.nextItem) + return; + const preferences = this.host.getPreferences(); + if (preferences.isGaplessPlaybackEnabled) { + // The fallback and the completion are recorded before the wait, so a stalled prefetch can never hold the + // track open: the renderer ends at the end of the scheduled audio and the player starts the fallback track + // non-gaplessly. The wait only tries to improve that into a seamless handoff. + if (!this.nextItem) + item.continueToEntry = this.getNextQueueEntry(); + this.renderer.markStreamComplete(); + const token = item.prefetch; + if (token && !token.cancelled && !token.consumed) { + const prefetched = await this.waitForPrefetchAsync(item, token, loopToken, seekToken); + if (!this.isCompletionCurrent(item, loopToken, seekToken)) + return; + if (prefetched && this.isPrefetchUsable(prefetched) && !this.nextItem) + this.attachNextItem(item, prefetched); + } + return; + } + if (!this.isCompletionCurrent(item, loopToken, seekToken)) + return; + this.renderer.markStreamComplete(); + } + + /** + * Checks whether a decode completion still belongs to the current item and to the decode loop and seek that + * observed it, so a completion that was overtaken while it waited is abandoned instead of acted on. + * @param {Object} item - The item whose completion is checked. + * @param {Object} [loopToken] - The token of the decode loop that observed the completion, when there is one. + * @param {Object|null} seekToken - The seek token the item carried when the completion was observed. + * @returns {boolean} True when the completion is still current. + */ + isCompletionCurrent(item, loopToken, seekToken) { + return !this.destroyed && this.current === item && !item.stopped && !item.failed && !item.disposed + && item.seekToken === seekToken + && (loopToken === undefined || item.loopToken === loopToken); + } + + /** + * Waits for a gapless prefetch, bounded by the remaining scheduled audio and by a short maximum. A seek cancels the + * wait immediately through {@link LuminaAudioPlayer.MediaPipelineEngine#cancelPrefetchWait}, so a seek never waits for a stalled next track that is kept across it. + * @param {Object} item - The current item whose decode completion is waiting. + * @param {Object} token - The prefetch token of the current item. + * @param {Object} [loopToken] - The token of the decode loop that observed the completion. + * @param {Object|null} seekToken - The seek token the item carried when the completion was observed. + * @returns {Promise} The ready prefetched item, or null when it is not ready in time. + */ + waitForPrefetchAsync(item, token, loopToken, seekToken) { + if (!token || token.cancelled || token.consumed) + return Promise.resolve(null); + if (token.ready) + return Promise.resolve(token.item); + if (!token.promise) + return Promise.resolve(null); + const deadline = this.getPrefetchWaitSeconds(); + if (deadline <= 0) + return Promise.resolve(null); + return new Promise((resolve) => { + let hasSettled = false; + let timer = null; + const finish = (value) => { + if (hasSettled) + return; + hasSettled = true; + clearTimeout(timer); + if (item.prefetchWaitCancel === cancel) + item.prefetchWaitCancel = null; + resolve(value && token.ready && !token.cancelled && !token.consumed ? value : null); + }; + const cancel = () => finish(null); + item.prefetchWaitCancel = cancel; + timer = setTimeout(() => finish(null), deadline * 1000); + token.promise.then((prefetched) => { + // A completion that a seek already overtook is not handed over, even if the prefetch finished in time. + if (item.seekToken !== seekToken || (loopToken !== undefined && item.loopToken !== loopToken)) + finish(null); + else + finish(prefetched || null); + }, () => finish(null)); + }); + } + + /** + * Gets how long the end of a decode may wait for a gapless prefetch: the remaining scheduled audio minus the handoff margin, capped by the maximum wait. + * @returns {number} The wait, in seconds, never below zero. + */ + getPrefetchWaitSeconds() { + const ahead = Number(this.renderer.getScheduledAheadSeconds()); + const remaining = Number.isFinite(ahead) && ahead > 0 ? ahead : 0; + return Math.max(0, Math.min(PREFETCH_HANDOFF_MAX_WAIT_SECONDS, remaining - PREFETCH_HANDOFF_MARGIN_SECONDS)); + } + + /** + * Releases a decode completion that is waiting for a gapless prefetch, used when a seek takes over the timeline. + * @param {Object} item - The item whose prefetch wait is cancelled. + */ + cancelPrefetchWait(item) { + if (!item || !item.prefetchWaitCancel) + return; + const cancel = item.prefetchWaitCancel; + item.prefetchWaitCancel = null; + cancel(); + } + + /** + * Checks whether a prefetched item can be appended to the current schedule: it is ready, still alive, and holds + * decoded audio that can be handed to the renderer. + * @param {Object} prefetched - The prefetched item. + * @returns {boolean} True when the item can be handed over. + */ + isPrefetchUsable(prefetched) { + return Boolean(prefetched) && !prefetched.failed && !prefetched.stopped && !prefetched.disposed + && prefetched.scheduler + && prefetched.scheduler.getScheduledAheadSeconds() > 0; + } + + //+======================================================================================+ + //| Gapless transitions | + //+======================================================================================+ + + /** + * Starts prefetching the next item of the player queue for a gapless transition, when the stored preference is on. + * The prefetch is dropped silently when it fails, because it must never interrupt the track that is playing. + * @param {Object} item - The item whose next queue entry is prefetched. + */ + startGaplessPrefetch(item) { + // Only the item that owns the playhead can have a successor to prefetch. The item that is merely attached as + // the next handoff starts its own prefetch when it becomes current, so the queue is never traversed by hand. + if (this.destroyed || !item || item !== this.current || item.stopped || item.disposed || item.prefetch) + return; + // A completed decode is not rejected here. A short track, or a short remainder after a seek, can finish its decode before its prefetch is started, and the handoff re-evaluation still consumes a prefetch for it. + // The paths where completion really makes a handoff impossible, the seek completion and a preference change, check completion before calling this method. + const preferences = this.host.getPreferences(); + if (!preferences.isGaplessPlaybackEnabled) + return; + const nextEntry = this.getNextQueueEntry(); + if (!nextEntry) + return; + const nextDescriptor = nextEntry.descriptor; + const token = { + cancelled: false, + consumed: false, + ready: false, + entryId: nextEntry.entryId, + descriptor: nextDescriptor, + item: null, + promise: null, + abortController: typeof AbortController === 'function' ? new AbortController() : null + }; + item.prefetch = token; + const phase = (async () => { + try { + const signal = token.abortController ? token.abortController.signal : undefined; + const manifest = await this.fetchManifestAsync(nextDescriptor, signal); + if (token.cancelled || this.destroyed || item.stopped || manifest.directPlay !== true) + return null; + const prefetched = await this.buildItemAsync(nextDescriptor, manifest, true, (created) => { + token.item = created; + }); + prefetched.entryId = token.entryId; + token.item = prefetched; + // The prefetch downloader is deliberately not started here, even when the player is paused with keep + // downloading enabled: its pre-decode was fetched on demand, and its sequential download starts only at the handoff. + if (token.cancelled || this.destroyed || item.stopped) { + await this.disposeItemAsync(prefetched); + return null; + } + await this.startDecodeLoop(prefetched); + if (token.cancelled || prefetched.failed || prefetched.stopped) + return null; + // The pre-decode window is buffered, so no more bytes are fetched until the handoff. The downloader + // never ran for a prefetch, and the abort clears any range request that was still completing, while + // keeping the bytes that were fetched. The sequential download starts at the handoff. + if (prefetched.source) + prefetched.source.setSeeking(false); + try { + prefetched.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the prefetch download could not be stopped after pre-decoding.', abortError); + } + // Ready means the preload loop has stopped and the buffered audio can be appended to the shared schedule without two decode loops feeding the same item. + token.ready = true; + return prefetched; + } catch (error) { + if (!token.cancelled && !this.destroyed && !LuminaAudioPlayer.isDownloadAbort(error)) + console.debug('Audio player: the gapless prefetch of the next track failed.', error); + return null; + } + })(); + token.promise = phase.then((prefetched) => { + // A prefetch that settled without a usable item is forgotten, so a later preference change or a later decode completion can try again after a transient manifest or network failure. + if (!prefetched && item.prefetch === token) + item.prefetch = null; + return prefetched; + }); + } + + /** + * Appends the pre-decoded audio of the next item to the renderer schedule, exactly after the audio of the current + * track, and lets its decode continue into the same schedule. The current item stays current until the media position of the next item begins. + * @param {Object} current - The item that is finishing. + * @param {Object} next - The prefetched item that hands over. + */ + attachNextItem(current, next) { + const token = current.prefetch; + if (token) { + token.consumed = true; + next.entryId = token.entryId; + } + current.prefetch = null; + current.continueToEntry = null; + next.isPreloading = false; + // The prefetch fetched only the windows its pre-decode needed, so the sequential download of the next track starts now: the decode loop that continues after the buffered frames needs those bytes. + if (next.source) + next.source.setSeeking(false); + // The sequential download of the next track starts only when the player is not paused. While paused it stays stopped, keeping its bytes, and is started by the next resume or by the handoff. + if (!this.isUserPaused) { + next.downloader.setPlaybackPaused(false); + next.downloader.startAsync(); + } + // The end of the scheduled audio of the current track is the exact media position the next track starts at. + next.base = this.renderer.getScheduledMediaDuration(); + this.nextItem = next; + // The current decode completion marked the stream complete before it waited for the prefetch. The handoff + // appends more audio after the current track, so completion must be cleared: a drained schedule from here on + // is an underrun that the monitor pauses and resumes, not the end of the next track. + this.renderer.clearStreamComplete(); + if (next.duration > 0) + this.renderer.setTimelineDuration(next.base + next.duration); + // The ReplayGain change is scheduled at the context time the next track starts, so it is not applied a reporter tick late after the boundary was detected. + next.isGainScheduled = false; + try { + next.isGainScheduled = this.renderer.scheduleManifestGain(next.manifest, this.getContextTimeForMediaPosition(next.base)); + } catch (error) { + console.debug('Audio player: the ReplayGain change of the next track could not be scheduled.', error); + } + next.scheduler.attach(this.renderer); + this.startDecodeLoop(next); + } + + /** + * Switches the current item to the next one at the media position its audio already started at. It reports the new + * descriptor to the player queue and applies the ReplayGain values of the new track. + */ + advanceToNextItem() { + if (this.isLoadingTrack) + return; + const previous = this.current; + const next = this.nextItem; + if (!next) + return; + // The audio of the next track is already scheduled, so the handoff is bookkeeping: move the engine cursor, move + // the player cursor by identity, release the previous item and adopt the renderer manifest. The audio cannot be + // rolled back, so a failure is handled on the new item rather than by undoing the transition. + this.nextItem = null; + if (next.failed || next.disposed || next.stopped) { + // A next track that failed after it was attached can no longer be switched to, so the chain ends with the + // audio that is already in the schedule instead of advancing the player to a dead item. + this.disposeItemAsync(next).catch((error) => { + console.debug('Audio player: the failed handoff track could not be released.', error); + }); + this.renderer.cancelTrackGainChange(); + this.renderer.markStreamComplete(); + return; + } + this.current = next; + // A loading state that belonged to the previous track does not follow the gapless handoff, unless the next track is itself waiting for a seek target to arrive. + if (!next.isSeeking) + this.host.reportBuffering(false); + // The audio of the previous track is already in the schedule of the renderer, so its pipeline can be released + // without affecting the transition, and it is released before anything that can fail below can leak it. + if (previous) + this.disposeItemAsync(previous).catch((error) => { + console.debug('Audio player: the finished track of the pipeline could not be released.', error); + }); + // The handoff is committed against the queue entry identity that was actually scheduled. If the player queue + // changed under it, the bar is moved to that entry instead of describing a different track. + const scheduledEntryId = next.entryId; + // The gapless handoff and a normal continuation use the same identity based commit, so a failed advance can never succeed through a second adoption call. + const advanced = this.host.advanceQueueTo + ? this.host.advanceQueueTo(scheduledEntryId) + : null; + if (advanced) + next.descriptor = advanced; + // If the item was attached while the player was paused, a resume that happened before the handoff still left its downloader aborted. It is started now that the item owns the playhead. + if (!this.isUserPaused && next.downloader) + next.downloader.startAsync(); + try { + this.renderer.adoptManifest(next.manifest, next.isGainScheduled === true); + } catch (error) { + this.failItem(next, error); + return; + } + next.isGainScheduled = false; + if (next.duration > 0) + this.renderer.setTimelineDuration(next.base + next.duration); + this.host.reportDuration(next.duration); + // The prefetched downloader fetched its pre-decode window before the handoff, and it may already have all of + // it, so it will emit no further progress after the player reset the streamed indicator for the new track. The + // fraction is reported once here so the three-state bar starts at the real streamed state of the new item. + this.reportItemProgress(next); + const absolute = this.renderer.getCurrentTime(); + const local = Math.max(0, absolute - next.base); + this.host.reportTime(next.duration > 0 ? Math.min(local, next.duration) : local, next.duration); + // The item now owns the engine's playhead, but its successor can only be prefetched when the player queue + // actually moved to it. If the commit was refused, the player cursor still points at the previous entry, so + // resolving its next entry would prefetch the track that just started as its own successor. + if (advanced) + this.startGaplessPrefetch(next); + if (next.isDecodeComplete) { + this.handleDecodeCompleteAsync(next).catch((error) => { + console.debug('Audio player: the completion of the handed off track could not be handled.', error); + }); + } else { + this.startDecodeLoop(next); + } + } + + /** + * Gets the queue entry that follows the current item, from the player's own queue cursor. The entry carries its + * identity and its descriptor, so two occurrences of the same track are never confused. + * @returns {{ entryId: string, descriptor: Object }|null} The following entry, or null at the end of the queue. + */ + getNextQueueEntry() { + if (typeof this.host.getNextDescriptor !== 'function') + return null; + try { + return this.host.getNextDescriptor() || null; + } catch (error) { + console.debug('Audio player: the next queue entry could not be read.', error); + return null; + } + } + + /** + * Checks whether a prefetch can survive a seek. A detached prefetch never touched the renderer schedule, so a seek + * can keep it as long as it still describes the same queue entry identity. + * @param {Object} token - The prefetch token of the current item. + * @param {{ entryId: string, descriptor: Object }|null} nextEntry - The successor of the current track after the seek. + * @returns {boolean} True when the prefetch is still valid and must not be cancelled. + */ + canKeepPrefetch(token, nextEntry) { + if (!token || token.cancelled || token.consumed || !token.entryId || !nextEntry) + return false; + const prefetched = token.item; + if (prefetched && (prefetched.failed || prefetched.stopped || prefetched.disposed)) + return false; + return token.entryId === nextEntry.entryId; + } + + /** + * Converts an absolute media position of the shared renderer into the context time at which it will play, so a + * change can be scheduled to happen exactly at a track boundary rather than when the boundary is noticed. + * @param {number} mediaTime - The absolute media position, in seconds. + * @returns {number} The context time, in seconds. Zero when the renderer has no context yet. + */ + getContextTimeForMediaPosition(mediaTime) { + // The renderer owns the anchor, the rate and the schedule lead, so the conversion is delegated to it instead of + // being derived a second time with values that can drift from the audio clock. + return typeof this.renderer.getContextTimeForMediaPosition === 'function' + ? this.renderer.getContextTimeForMediaPosition(mediaTime) + : 0; + } + + /** + * Checks whether the media position that the next item starts at was reached, and switches to it when it was. + * @param {number} absoluteTime - The absolute media position of the shared renderer, in seconds. + */ + checkForTrackBoundary(absoluteTime) { + // A seek owns the timeline until it has repositioned every stage, so a boundary that the old timeline crosses + // during the seek must not invalidate it. A load in progress owns the queue and the player state, so the old timeline must not advance under it either. + if (!this.nextItem || this.isLoadingTrack || (this.current && this.current.isSeeking)) + return; + const value = toFiniteNumber(absoluteTime); + if (value === null || value < this.nextItem.base) + return; + this.advanceToNextItem(); + } + + /** + * Cancels and releases the prefetch of an item, including a prefetched item that was never attached. + * @param {Object} item - The item whose prefetch is cancelled. + * @returns {Promise} A promise that completes when the prefetch was released. + */ + async cancelPrefetchAsync(item) { + const token = item ? item.prefetch : null; + if (!token) + return; + item.prefetch = null; + token.cancelled = true; + if (token.abortController) { + try { + token.abortController.abort(); + } catch (abortError) { + console.debug('Audio player: the manifest request of the cancelled prefetch could not be aborted.', abortError); + } + } + let prefetched = token.item; + // A prefetch that is already built is stopped before its promise is awaited, so a decode that is waiting for + // bytes of a track nobody wants anymore is released instead of holding the teardown open. + if (prefetched && !prefetched.disposed && !token.consumed) { + prefetched.stopped = true; + if (prefetched.scheduler) + prefetched.scheduler.stop(); + try { + prefetched.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the prefetched download could not be aborted.', abortError); + } + // Destroying the decoder releases a decode that is waiting for room, which a prefetch whose buffer is full + // would otherwise wait for forever, because its schedule is never consumed while it is detached. + if (prefetched.decoder) { + try { + await prefetched.decoder.destroyAsync(); + } catch (decodeError) { + console.debug('Audio player: the prefetched decoder could not be destroyed.', decodeError); + } + } + } + try { + prefetched = (await token.promise) || prefetched; + } catch (error) { + // The prefetch reports its own failures and resolves null, so a rejection is only a teardown. + } + if (token.consumed || !prefetched) + return; + await this.disposeItemAsync(prefetched); + } + + //+======================================================================================+ + //| Playback monitoring | + //+======================================================================================+ + + /** + * Starts the monitor that detects underruns and gapless track boundaries. It is idempotent. + */ + startMonitor() { + if (this.monitorTimer !== null || this.destroyed) + return; + this.monitorTimer = setInterval(() => { + this.monitorPlayback(); + }, MONITOR_INTERVAL_MS); + } + + /** + * Stops the playback monitor. + */ + stopMonitor() { + if (this.monitorTimer === null) + return; + clearInterval(this.monitorTimer); + this.monitorTimer = null; + } + + /** + * Inspects the schedule and the shared timeline: it switches to the next track at its media position and it pauses + * and resumes the renderer around an underrun. It never runs while the user paused the player. + * @returns {Promise} A promise that completes when the monitor pass is done. + */ + async monitorPlayback() { + if (this.isMonitoring || this.destroyed || this.isUserPaused || !this.current) + return; + // A seek owns the timeline until its first frame is scheduled, and a load in progress owns the player state, so + // the monitor neither pauses the renderer nor advances a boundary of the timeline that is being replaced. + if (this.current.isSeeking || this.isLoadingTrack) + return; + this.isMonitoring = true; + try { + const absolute = this.renderer.getCurrentTime(); + this.checkForTrackBoundary(absolute); + if (this.isUnderrunPaused) { + if (this.renderer.getScheduledAheadSeconds() >= UNDERRUN_RESUME_SECONDS) { + this.isUnderrunPaused = false; + this.host.reportBuffering(false); + await this.renderer.playAsync(); + } + return; + } + if (!this.renderer.isPlaying()) + return; + if (this.renderer.getScheduledAheadSeconds() > UNDERRUN_THRESHOLD_SECONDS) + return; + // A drained schedule that is also declared complete is the end of the track, not an underrun. + if (this.renderer.isStreamComplete() && this.current.isDecodeComplete) + return; + // Before the first frame of a freshly loaded or seeked track there is nothing to play yet. Pausing that + // state would only flap the renderer between paused and playing, so the pause waits for audio to have been scheduled at least once. + if (!this.current.hasScheduledAudio) + return; + // A seek that started while this pass was running owns the timeline, so the pass does not pause it. + if (this.current.isSeeking) + return; + this.isUnderrunPaused = true; + this.host.reportBuffering(true); + await this.renderer.pauseAsync(); + } catch (error) { + if (!this.destroyed) + this.failItem(this.current, error); + } finally { + this.isMonitoring = false; + } + } + + /** + * Handles a playhead report from the renderer. The report is on the shared timeline, so it is translated to the + * position of the current track and the boundary of the next track is checked first. + * @param {number} absoluteTime - The absolute media position of the shared renderer, in seconds. + */ + handleTimeUpdate(absoluteTime) { + if (this.destroyed) + return; + this.checkForTrackBoundary(absoluteTime); + const item = this.current; + if (!item) + return; + const local = Math.max(0, Number(absoluteTime) - item.base); + const bounded = item.duration > 0 ? Math.min(local, item.duration) : local; + this.host.reportTime(bounded, item.duration); + } + + /** + * Handles the end of the scheduled audio reported by the renderer. + */ + handleEnded() { + if (this.destroyed) + return; + // An end of the timeline that a new load is replacing is not reported: the load owns the player state now. + if (this.isLoadingTrack) + return; + // An end that the old timeline reports while a seek is repositioning the pipeline belongs to the timeline the seek is replacing, not to the target it is moving to. + if (this.current && this.current.isSeeking) + return; + this.stopMonitor(); + this.isUnderrunPaused = false; + const current = this.current; + // The next entry is re-resolved at the end, not taken from the value cached at decode completion: a queue that + // changed in between may no longer offer a successor, in which case the track simply ends. + const nextEntry = this.getNextQueueEntry(); + if (current && current.continueToEntry && nextEntry && !this.isUserPaused + && typeof this.host.requestNextTrackAsync === 'function') { + // The engine reports the structural fact and lets the player's own play path start the next entry, so the + // controller keeps ownership of the state, the pause and stop intent, and the capability gate. The loading + // state spans the end gap: the continuation load keeps it across the teardown of the finished track. + current.continueToEntry = null; + this.host.reportBuffering(true); + Promise.resolve(this.host.requestNextTrackAsync('gapless-prefetch-failed')) + .then((hasTakenOwnership) => { + if (!hasTakenOwnership) + this.finishEndedTrack(current); + }) + .catch((error) => { + console.debug('Audio player: the player could not start the next track after a gapless fallback.', error); + this.finishEndedTrack(current); + }); + return; + } + this.host.reportBuffering(false); + if (current) + this.finishEndedTrack(current); + else + this.host.reportEnded(); + } + + /** + * Releases a finished item and reports the end to the player, unless a newer load already took ownership of the pipeline in the meantime. + * @param {Object} item - The item that ended. + */ + finishEndedTrack(item) { + if (this.current !== item) + return; + this.current = null; + this.host.reportBuffering(false); + this.host.reportEnded(); + this.disposeItemAsync(item).catch((error) => { + console.debug('Audio player: the ended track of the pipeline could not be released.', error); + }); + } + + /** + * Follows the stored playback preferences. Gapless playback is honored from the moment it is turned on, and a + * prefetch that becomes unwanted is released before its audio is appended to the schedule. + * @param {Object} preferences - The preferences payload of the player. + */ + handlePreferencesChanged(preferences) { + if (this.destroyed || !preferences || typeof preferences.isGaplessPlaybackEnabled !== 'boolean') + return; + const item = this.current; + if (!item) + return; + if (preferences.isGaplessPlaybackEnabled === false) { + this.cancelPrefetchAsync(item).catch((error) => { + console.debug('Audio player: the disabled gapless prefetch could not be released.', error); + }); + // A next item that was already appended to the schedule is cancelled too: the appended audio is removed, the + // current track is allowed to end at the boundary, and the player then starts the next entry non-gaplessly. + // The boundary may already be behind the playhead, in which case the next track is already audible and + // truncating it would rewind the timeline and replay audio that has played. That transition is left alone. + const next = this.nextItem; + if (next && typeof this.renderer.truncateScheduleAt === 'function' + && next.base > this.renderer.getCurrentTime()) { + this.nextItem = null; + this.renderer.cancelTrackGainChange(); + this.renderer.truncateScheduleAt(next.base); + item.continueToEntry = this.getNextQueueEntry(); + this.renderer.markStreamComplete(); + this.disposeItemAsync(next).catch((error) => { + console.debug('Audio player: the disabled gapless handoff could not be released.', error); + }); + } + return; + } + // A decode that has already completed made its end decision before gapless was enabled, so a prefetch started now could never be appended to the schedule. + if (!this.nextItem && !item.isDecodeComplete) + this.startGaplessPrefetch(item); + } + + /** + * Subscribes the engine to the stored preference changes of the player. + */ + subscribeToPreferences() { + if (!this.events || !LuminaAudioPlayer.PlayerEvent || typeof this.events.on !== 'function') + return; + this.unsubscribePreferences = this.events.on(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, (preferences) => { + this.handlePreferencesChanged(preferences); + }); + } + + //+======================================================================================+ + //| Failures and teardown | + //+======================================================================================+ + + /** + * Handles a download failure of an item. A prefetch failure is dropped; the failure of the current track is + * reported to the player, which moves to its error state without the pipeline leaving anything running. + * @param {Object} item - The item that failed. + * @param {*} error - The failure. + */ + handleDownloadFailure(item, error) { + if (LuminaAudioPlayer.isDownloadAbort(error)) + return; + this.failItem(item, error); + } + + /** + * Records a failure of an item once and reports it to the player when the item is the current one. + * @param {Object} item - The item that failed. + * @param {*} error - The failure. + */ + failItem(item, error) { + if (!item || item.failed || item.stopped || item.disposed || this.destroyed) + return; + if (LuminaAudioPlayer.isDownloadAbort(error)) + return; + item.failed = true; + item.stopped = true; + try { + item.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the failed download could not be aborted.', abortError); + } + if (item === this.nextItem) { + // The next track was already appended to the schedule but has not started yet, so the chain ends with the + // audio that is already scheduled and the player is not advanced to an item that can no longer play. + this.nextItem = null; + this.renderer.cancelTrackGainChange(); + this.renderer.markStreamComplete(); + this.host.reportBuffering(false); + this.disposeItemAsync(item).catch((disposeError) => { + console.debug('Audio player: the failed handoff track could not be released.', disposeError); + }); + return; + } + if (item !== this.current) { + console.debug('Audio player: a prefetched track of the pipeline failed.', error); + // A failed prefetch is released here instead of waiting for the next load or for the teardown, so its + // decoder, demuxer, downloader and buffered frames never outlive the failure. + this.disposeItemAsync(item).catch((disposeError) => { + console.debug('Audio player: the failed prefetch could not be released.', disposeError); + }); + return; + } + this.stopMonitor(); + this.isUnderrunPaused = false; + item.isSeeking = false; + if (item.scheduler) + item.scheduler.stop(); + if (item.source) + item.source.setSeeking(false); + this.host.reportBuffering(false); + // The audio that is already scheduled is suspended before the failure is reported, so a failed track never keeps playing while the player shows its error state. + this.renderer.pauseAsync().catch((pauseError) => { + console.debug('Audio player: the renderer could not be paused after a failure.', pauseError); + }); + this.host.reportError(LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR)); + // The failed item is not retained in the error state: its decoder, demuxer, downloader, prefetch and scheduled + // sources are released now. The player refuses seeks and resumes in the error state anyway, and a replay starts + // a fresh load. + if (this.current === item) + this.current = null; + this.disposeItemAsync(item).catch((disposeError) => { + console.debug('Audio player: the failed track could not be released.', disposeError); + }); + } + + /** + * Waits for the decode loop of an item to stop. + * @param {Object} item - The item whose loop is awaited. + * @returns {Promise} A promise that completes when the loop stopped. + */ + async waitForDecodeLoopAsync(item) { + const loop = item.loopPromise; + if (!loop) + return; + try { + await loop; + } catch (error) { + // The loop reports its own failures, so a teardown never surfaces them. + } + } + + /** + * Rebuilds the demuxer of an item from the beginning of its stream, used when a seek cannot be performed by time. + * @param {Object} item - The item whose demuxer is rebuilt. + * @returns {Promise} A promise that completes when the new demuxer is ready. + */ + async rebuildDemuxerAsync(item) { + const previous = item.demuxer; + item.demuxer = null; + if (previous) + await previous.destroyAsync(); + if (item.stopped || item.disposed) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The track was released while its demuxer was rebuilt.'); + const demuxer = await LuminaAudioPlayer.createDemuxerForManifest(item.manifest, { + source: item.source || item.downloader, + capabilities: this.capabilities, + events: this.events, + onError: (error) => this.failItem(item, error) + }); + if (!demuxer) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, 'The track cannot be demuxed again after a seek.'); + if (item.stopped || item.disposed) { + // The item was released while the demuxer probed its header, so the new demuxer must not be installed after the disposal already walked past a null demuxer. + await demuxer.destroyAsync(); + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The track was released while its demuxer was rebuilt.'); + } + item.demuxer = demuxer; + const configuration = demuxer.getConfiguration(); + if (configuration) + item.decoder.configure(configuration); + } + + /** + * Releases every resource of a pipeline item. It is idempotent. + * @param {Object} item - The item to release. + * @returns {Promise} A promise that completes when the item was released. + */ + async disposeItemAsync(item) { + if (!item || item.disposed) + return; + item.disposed = true; + item.stopped = true; + item.loopToken = null; + this.cancelPrefetchWait(item); + if (item.scheduler) + item.scheduler.stop(); + // The item may itself have prefetched the track after it, which must not keep downloading or decoding once the + // item is released, for example when a seek drops a whole gapless chain. + if (item.prefetch) { + try { + await this.cancelPrefetchAsync(item); + } catch (error) { + console.debug('Audio player: the prefetch of a released track could not be released.', error); + } + } + if (item.downloader) { + try { + item.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the download of a released track could not be aborted.', abortError); + } + } + // The decoder is destroyed before the decode loop is awaited, because destroying it releases a decode that is + // waiting for room, which is the only thing that can keep the loop from noticing the item stopped. + if (item.decoder) { + try { + await item.decoder.destroyAsync(); + } catch (error) { + console.debug('Audio player: the decoder of a released track could not be destroyed.', error); + } + } + await this.waitForDecodeLoopAsync(item); + if (item.scheduler) { + try { + item.scheduler.dispose(); + } catch (error) { + console.debug('Audio player: the scheduler of a released track could not be released.', error); + } + } + if (item.demuxer) { + try { + await item.demuxer.destroyAsync(); + } catch (error) { + console.debug('Audio player: the demuxer of a released track could not be destroyed.', error); + } + } + if (item.source) + item.source.destroy(); + if (item.downloader) { + try { + await item.downloader.destroyAsync(); + } catch (error) { + console.debug('Audio player: the downloader of a released track could not be destroyed.', error); + } + } + } + + /** + * Releases the item that is playing, the prefetch that feeds it and the item that was already attached to the renderer schedule, without touching the renderer itself. + * @param {Object|null} [loadTokenToAbort] - A load token whose manifest request must be aborted, used by the + * destroy path. A load never aborts its own token here, because the request it is about to make belongs to it. + * @param {Object|null} [loadToken] - The token of the load that owns this teardown. Shared state is only touched + * after the awaited disposals when this is still the current token. + * @param {boolean} [keepBuffering=false] - True to keep a loading state that was handed to the load by the player, + * used by an automatic continuation so the end gap keeps showing that the next track is being prepared. + * @returns {Promise} A promise that completes when the playback resources were released. + */ + async teardownPlaybackAsync(loadTokenToAbort = null, loadToken = null, keepBuffering = false) { + // The items are captured and detached synchronously, so a teardown that is overtaken while it awaits can only + // release the pipeline it captured and can never null or dispose the item a newer load installed. + const current = this.current; + const next = this.nextItem; + this.current = null; + this.nextItem = null; + const prefetchedInFlight = current && current.prefetch ? current.prefetch.item : null; + this.abortLoad(loadTokenToAbort); + this.stopMonitor(); + this.isUnderrunPaused = false; + // Every stage is stopped before the renderer is reset: the schedulers drop the frames that are still in flight, + // the downloaders release the reads that are waiting, and only then does the shared renderer stop its schedule, + // so a decoder cannot append a frame of the replaced track after the reset. + for (const item of [current, next, prefetchedInFlight]) { + if (!item) + continue; + item.stopped = true; + item.loopToken = null; + if (item.scheduler) + item.scheduler.stop(); + if (item.downloader) { + try { + item.downloader.abort(); + } catch (abortError) { + console.debug('Audio player: the download of the replaced track could not be aborted.', abortError); + } + } + } + try { + this.renderer.cancelTrackGainChange(); + } catch (error) { + console.debug('Audio player: the scheduled ReplayGain change of the replaced track could not be cleared.', error); + } + try { + this.renderer.seekTo(0); + } catch (error) { + console.debug('Audio player: the schedule of the replaced track could not be stopped.', error); + } + // The captured items are released even when this teardown was overtaken, because the newer teardown already saw + // a null current and would otherwise leak them. No shared state is read or written after these awaits. + if (next) + await this.disposeItemAsync(next); + if (current) + await this.disposeItemAsync(current); + if (!keepBuffering && (!loadToken || this.loadToken === loadToken)) + this.host.reportBuffering(false); + } + + //+======================================================================================+ + //| Manifest access | + //+======================================================================================+ + + /** + * Fetches the playback manifest of a track from the web application. + * @param {Object} descriptor - The play descriptor of the track. + * @param {AbortSignal} [signal] - An optional signal that cancels the request, used by a cancelled prefetch. + * @returns {Promise} The playback manifest. + * @throws {LuminaAudioPlayer.PlayerError} When the descriptor is incomplete, the session expired, or the manifest + * could not be read. + */ + async fetchManifestAsync(descriptor, signal) { + // The injected transport wins over the host, exactly like the injected configuration does. + const transport = (typeof this.options.fetchJsonAsync === 'function') + ? this.options.fetchJsonAsync + : ((this.host && typeof this.host.fetchJsonAsync === 'function') + ? (requestUrl, requestSignal, label, requestOptions) => this.host.fetchJsonAsync(requestUrl, requestSignal, label, requestOptions) + : null); + return LuminaAudioPlayer.fetchPlaybackManifestAsync({ + configuration: this.getConfiguration(), + descriptor: descriptor, + capabilities: await this.describeCapabilitiesAsync(), + transport: transport, + signal: signal + }); + } + + /** + * Describes the container and codec pairs the browser can play directly, which the playback format service uses to decide between direct play, remux and transcode. + * @returns {Promise} The comma separated capability list, or an empty string when it cannot be built. + */ + async describeCapabilitiesAsync() { + if (typeof LuminaAudioPlayer.describeDemuxerFormatsAsync !== 'function') + return ''; + try { + return await LuminaAudioPlayer.describeDemuxerFormatsAsync({ + capabilities: this.capabilities, + events: this.events + }); + } catch (error) { + // The list is an optimization of the delivery decision, so a failed probe falls back to the static registry rather than making the track unplayable. + console.debug('Audio player: the decode aware capability list could not be built.', error); + return typeof LuminaAudioPlayer.describeDemuxerFormats === 'function' ? LuminaAudioPlayer.describeDemuxerFormats() : ''; + } + } + + /** + * Gets the endpoints configuration of the player. + * @returns {Object} The endpoints configuration. + */ + getConfiguration() { + if (this.options.configuration) + return this.options.configuration; + return this.host && typeof this.host.getConfiguration === 'function' ? this.host.getConfiguration() : {}; + } + + } + + LuminaAudioPlayer.MediaPipelineEngine = MediaPipelineEngine; + + /** + * Creates a media pipeline engine. See {@link LuminaAudioPlayer.MediaPipelineEngine} for the options. + * @param {Object} host - The engine host provided by the player controller. + * @param {Object} [options] - The engine options. + * @returns {LuminaAudioPlayer.MediaPipelineEngine} The created engine. + */ + LuminaAudioPlayer.createMediaPipelineEngine = function (host, options) { + return new MediaPipelineEngine(host, options); + }; + + /** + * Registers the media pipeline engine on a player and makes it the selected engine. The player is the singleton of + * the application, so this is what turns the control API and the bar into an actually audible player. + * @param {LuminaAudioPlayer.AudioPlayer} player - The player to install the engine on. + * @returns {LuminaAudioPlayer.AudioPlayer} The same player, for chaining. + */ + LuminaAudioPlayer.installMediaPipelineEngine = function (player) { + if (!player) + return player; + player.registerEngine(LuminaAudioPlayer.PIPELINE_ENGINE_NAME, (host) => new MediaPipelineEngine(host)); + return player.useEngine(LuminaAudioPlayer.PIPELINE_ENGINE_NAME); + }; + + /** + * Creates the singleton player when it does not exist yet and installs the media pipeline engine on it. It is the one + * composition point of the engine, and it requires the player module to be loaded first, which is the order the layout + * uses. When the player module is absent the install is skipped instead of throwing, so loading this module early is harmless; the engine is then simply not selected. + */ + function installOnDefaultPlayer() { + if (typeof LuminaAudioPlayer.createDefaultPlayer !== 'function') + return; + const player = LuminaAudioPlayer.createDefaultPlayer(); + LuminaAudioPlayer.installMediaPipelineEngine(player); + } + + if (document.readyState === 'loading') + document.addEventListener('DOMContentLoaded', installOnDefaultPlayer); + else + installOnDefaultPlayer(); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js new file mode 100644 index 00000000..9f269757 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-pipeline/audio-player-pipeline-schedulers.js @@ -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 || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js index 594a3a36..2ae0156e 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-render.js @@ -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); } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js index c85efe06..07d38275 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js @@ -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 || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js index 8fb6736c..9d13c62a 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -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} 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} 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} 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} A promise that completes when the engine paused. @@ -781,9 +921,17 @@ * @returns {Promise} 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} 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]); + } } /**