diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index 3712232a..b22ec44a 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -13,6 +13,7 @@ The web client of Lumina is a themed shell: every page is rendered inside the te - [Safety Limits](#safety-limits) - [Template Resolution](#template-resolution) - [The Layout Template (shared/layout)](#the-layout-template-sharedlayout) + - [The Audio Player Bar](#the-audio-player-bar) - [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu) - [Page Templates](#page-templates) - [The Scripts Section](#the-scripts-section) @@ -222,6 +223,42 @@ The layout template of the bundled theme shows the intended shape: The rendered page content, navigation and scripts are inserted unescaped with `{{&...}}`, because they are trusted application HTML. The layout is best effort: when the theme cannot be loaded or rendered, the application falls back to its built-in layout, so a broken theme never takes the whole site down. +### The Audio Player Bar + +Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar is hidden until the user starts playback of a track, album or artist, and the global audio player script shows it, expands it and hides it again. The theming work that turns the bar into a theme template (a `shared/audio-player` page key with sub templates) is not part of this contract yet; until it lands, the bar is the application fallback markup, passed in as the `audioPlayer` field. + +The bar is fixed to the bottom of the viewport, so the theme owns the room reserved for it on the main content element. A layout must keep these element hooks, which the audio player drives (the two id controls are bound by the global site script, which routes them to the audio player): + +| Element | Hook | Meaning | +| --- | --- | --- | +| The bar container, with the `audio-player-container` class | `not-shown` class | The bar is hidden, and its height collapses. | +| The bar container | `full-height` class | The bar is expanded to its full height form. | +| The main content element | `audio-player-not-shown` class | The bar is hidden, so the content area uses the full height. | +| The main content element | `audio-player-full-height` class | The bar is expanded, so the content area gives it the full height. | +| The full height control | `id="audio-player-full-height-toggle"` | Expands or collapses the bar. | +| The close control | `id="audio-player-close"` | Stops playback, and hides the bar while it is condensed. | + +A theme must reserve the space for the bar itself, as the bundled themes do: + +```css +main { + bottom: 50px; + transition: bottom 1s ease, height 1s ease; +} + +main.audio-player-not-shown { + bottom: 0; +} + +main.audio-player-full-height { + bottom: calc(100% - 22px); /* full height minus the menu height */ +} +``` + +The application fallback layout, which renders when the active theme cannot be loaded, reserves the room itself, because the application stylesheet does not position the content area of a theme. A theme that omits the rules above leaves the fixed bar overlapping the bottom of the page. + +The markup inside the bar exposes the hook attributes the audio player script binds, such as `data-audio-player-play-pause`, `data-audio-player-progress`, `data-audio-player-current-time` and `data-audio-player-track-name`. A theme that replaces the bar markup must keep those attributes, and the play affordances of the pages use the `data-audio-player-play` trigger attribute. + ### The Navigation Template (shared/nav-menu) The navigation template renders the menu of the active theme. Its model contains the site name and two menu structures, one for the mobile menu and one for the desktop menu bar: diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml index 65f7ceaa..61363d5b 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml @@ -1,4 +1,4 @@ -@using Microsoft.Extensions.Localization +@using Microsoft.Extensions.Localization @inject IStringLocalizerFactory _stringLocalizerFactory @@ -6,12 +6,55 @@ IStringLocalizer localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); } -
- - @localizer["ToggleFullHeight"] - @localizer["ToggleVisibility"] +@* + APPLICATION FALLBACK AUDIO PLAYER BAR - READ BEFORE EDITING + + This partial renders the audio player bar into the layout of the application and of every theme, for an + authenticated visitor. It is only the markup: the behavior lives in the global audio player script + (wwwroot/js/audio-player/), which binds to the hooks documented below. + + The bar is hidden by default. The 'hidden' attribute keeps it unrendered until the audio player script takes over, + so a page load never shows the bar, not even for a frame while the stylesheets settle. The script then hands the bar + to the 'not-shown' class, which keeps it hidden until playback starts. + + The DOM contract a theme must preserve is: + - The container element with the 'audio-player-container' class, carrying 'not-shown' while the bar is hidden, + and 'full-height' while it is expanded. The audio player toggles both classes. + - The main content element, carrying 'audio-player-not-shown' while the bar is hidden, and 'audio-player-full-height' + while it is expanded. The audio player toggles both classes on it as well. + - The elements with the ids 'audio-player-full-height-toggle' and 'audio-player-close', which the global site script + binds and routes to the audio player. + - The hook attributes the audio player binds: 'data-audio-player-play-pause', '-progress', '-progress-played', + '-progress-downloaded', '-current-time', '-total-time', '-track-name', '-cover-thumbnail', '-cover-image' and '-queue'. + + The play affordances the pages hand to the player use the 'data-audio-player-play' trigger attribute. The + 'The Audio Player Bar' section of docs/technical/theming/Theming.md documents this contract for theme authors. +*@ + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml index 538e66af..f04be11b 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml @@ -46,12 +46,12 @@ else @ViewData["Title"] - Lumina @await Html.PartialAsync("_ThemeLayoutHead") - +
@await Html.PartialAsync("_NavMenu")
-
+
@Html.Raw(bodyHtml)
diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 436d303c..499c5a2d 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -1,9 +1,12 @@ @using Lumina.Presentation.Web.Common.DTO.Configuration +@using Lumina.Presentation.Web.Common.Routes +@using Lumina.Presentation.Web.Common.Services @using Microsoft.Extensions.Localization @using Microsoft.Extensions.Options @inject IStringLocalizerFactory _stringLocalizerFactory @inject IOptions _serverConfigurationModel +@inject IUrlService _urlService @{ IStringLocalizer localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); @@ -30,9 +33,20 @@ error: '@localizer["Error"]', information: '@localizer["Information"]' }; + // The endpoints the audio player reads the stored playback preferences of the user from. 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)' + }; + + + + + diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css index a0b95d58..a53b68e9 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/site.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css @@ -1,4 +1,4 @@ -html, +html, body { margin: 0px; padding: 0px; @@ -1250,3 +1250,202 @@ body { .artwork-carousel-item:hover { border-color: #FFFFFF; } + +/* Audio player bar. This is the application fallback styling: the themes own the final look, and the + audio player script owns the state. The 'not-shown' and 'full-height' classes on the container, and + the matching 'audio-player-not-shown' and 'audio-player-full-height' classes on main, are the contract. */ +.audio-player-container { + position: fixed; + left: 0px; + right: 0px; + bottom: 0px; + z-index: 997; + display: flex; + flex-direction: column; + height: 50px; + overflow: hidden; + background-color: #1C1C1C; + border-top: 1px solid #444444; + transition: height 0.4s ease; +} + +.audio-player-container.not-shown { + height: 0px; + border-top-width: 0px; +} + +/* The 'hidden' attribute keeps the bar unrendered until the audio player script takes over, so that a page load + never shows it, not even for a frame while the stylesheets settle. The script removes it once the bar is already + in its hidden state, so the removal is never visible. */ +.audio-player-container[hidden] { + display: none !important; +} + +/* While the audio player applies its initial hidden state, its transitions, and the offset transition of the content + area, are suppressed, so that a page load never slides the bar or the content into place. The player removes the + marker once it is initialized, and later show, hide and expand transitions work normally. */ +html.audio-player-initializing main, +html.audio-player-initializing .audio-player-container { + transition: none !important; +} + +/* The fallback layout has no theme to position the content area, so it reserves room for the bar itself, consuming the + same classes a theme consumes on main. A themed layout positions main itself and does not carry this class. */ +.application-fallback-layout main { + padding-bottom: 50px; + transition: padding-bottom 0.4s ease; +} + +.application-fallback-layout main.audio-player-not-shown { + padding-bottom: 0px; +} + +.audio-player-container.full-height { + height: calc(100% - 22px); /* full height minus the height of the menu bar */ +} + +.audio-player-bar { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: 8px; + height: 50px; + padding: 0px 10px; + color: #E6E6E6; +} + +.audio-player-cover-thumbnail { + flex: 0 0 auto; + width: 36px; + height: 36px; + object-fit: cover; +} + +.audio-player-track-name { + flex: 1 1 20%; + min-width: 0px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.audio-player-time { + flex: 0 0 auto; + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +.audio-player-progress { + position: relative; + flex: 2 1 40%; + min-width: 40px; + height: 6px; + background-color: #333333; + cursor: pointer; +} + +/* The bar exposes three distinct states a theme can style: the not yet downloaded track, the downloaded + part ('audio-player-progress-downloaded'), and the played part ('audio-player-progress-played'). */ +.audio-player-progress-played, +.audio-player-progress-downloaded { + position: absolute; + top: 0px; + left: 0px; + width: 0%; + height: 100%; +} + +.audio-player-progress-downloaded { + background-color: #5A6B78; +} + +.audio-player-progress-played { + background-color: #6DCBFE; +} + +.audio-player-transport { + flex: 0 0 auto; + display: flex; + align-items: center; +} + +.audio-player-play-pause { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0px; + background-color: transparent; + border: 0px; + cursor: pointer; +} + +/* The play affordance is a right pointing triangle, and the pause affordance two bars, both drawn with CSS + so that a theme can restyle them without an image. */ +.audio-player-play-pause-icon { + display: block; + width: 0px; + height: 0px; + border-style: solid; + border-width: 6px 0px 6px 10px; + border-color: transparent transparent transparent #E6E6E6; +} + +.audio-player-play-pause.is-playing .audio-player-play-pause-icon { + width: 10px; + height: 12px; + border-width: 0px; + border-right: 3px solid #E6E6E6; + border-left: 3px solid #E6E6E6; +} + +.audio-player-controls { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 10px; +} + +.audio-player-expanded { + display: none; + flex: 1 1 auto; + min-height: 0px; + gap: 16px; + padding: 16px; + overflow-y: auto; +} + +.audio-player-container.full-height .audio-player-expanded { + display: flex; + flex-direction: row; +} + +.audio-player-cover-image { + flex: 0 0 auto; + width: 240px; + height: 240px; + object-fit: cover; +} + +.audio-player-queue { + flex: 1 1 auto; + margin: 0px; + padding: 0px; + overflow-y: auto; + list-style: none; +} + +.audio-player-queue-item { + display: flex; + justify-content: space-between; + gap: 12px; + padding: 6px 8px; + border-bottom: 1px solid #333333; +} + +.audio-player-queue-item-title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js new file mode 100644 index 00000000..5a33dcdb --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-capabilities.js @@ -0,0 +1,190 @@ +/** + * Capability detection of the audio player. + * + * The player decodes with WebCodecs and outputs through the Web Audio API, so before it can play anything it must know which of those browser capabilities exist, and which audio codecs the + * browser can decode. The report is produced once, is cached, and is published through the event bus, so that a consumer can present a clear failure instead of a silent, broken player. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Enum-like object for the browser capabilities the player requires. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerCapability = Object.freeze({ + // The WebCodecs API, the family of decoders the player feeds. + WEB_CODECS: 'webCodecs', + // WebCodecs.AudioDecoder, the audio decoder the player actually consumes. + AUDIO_DECODER: 'audioDecoder', + // The Web Audio API, used for output. + AUDIO_CONTEXT: 'audioContext' + }); + + /** + * The codec configurations probed with AudioDecoder.isConfigSupported, one per audio codec the demuxers of the player can recognize. + * Each entry is a representative configuration; the returned report says whether the browser can decode that codec at all. + * @readonly + * @type {ReadonlyArray<{ name: string, config: Object }>} + */ + LuminaAudioPlayer.PROBED_AUDIO_CODECS = Object.freeze([ + Object.freeze({ name: 'mp3', config: Object.freeze({ codec: 'mp3', sampleRate: 44100, numberOfChannels: 2 }) }), + Object.freeze({ name: 'flac', config: Object.freeze({ codec: 'flac', sampleRate: 44100, numberOfChannels: 2 }) }), + Object.freeze({ name: 'opus', config: Object.freeze({ codec: 'opus', sampleRate: 48000, numberOfChannels: 2 }) }), + Object.freeze({ name: 'aac', config: Object.freeze({ codec: 'mp4a.40.2', sampleRate: 44100, numberOfChannels: 2 }) }), + Object.freeze({ name: 'vorbis', config: Object.freeze({ codec: 'vorbis', sampleRate: 44100, numberOfChannels: 2 }) }), + Object.freeze({ name: 'pcm', config: Object.freeze({ codec: 'pcm-s16', sampleRate: 44100, numberOfChannels: 2 }) }) + ]); + + /** + * Detects the browser capabilities the audio player relies on, and caches the result. + */ + class PlayerCapabilities { + /** + * Creates an instance of PlayerCapabilities. + * @param {Window} [targetWindow] - The window whose capabilities are inspected. Defaults to the current window. + */ + constructor(targetWindow = window) { + this.window = targetWindow; + /** @type {Object|null} */ + this.report = null; + /** @type {Promise|null} */ + this.pendingReport = null; + } + + /** + * Checks whether the WebCodecs API is present. + * @returns {boolean} True when the browser exposes at least one WebCodecs decoder. + */ + hasWebCodecs() { + // The audio side of WebCodecs is what the player feeds, but any decoder of the family implies the API is exposed + // at all; the precise check of the decoder the player consumes is hasAudioDecoder below. + return typeof this.window.AudioDecoder === 'function' || typeof this.window.VideoDecoder === 'function'; + } + + /** + * Checks whether WebCodecs.AudioDecoder is present. + * @returns {boolean} True when the audio decoder the player consumes exists. + */ + hasAudioDecoder() { + return typeof this.window.AudioDecoder === 'function'; + } + + /** + * Checks whether the Web Audio API is present. + * @returns {boolean} True when an AudioContext constructor exists. + */ + hasAudioContext() { + return typeof this.window.AudioContext === 'function' || typeof this.window.webkitAudioContext === 'function'; + } + + /** + * Asks the browser whether it can decode a single audio configuration. + * @param {Object} config - An AudioDecoderConfig like value, with codec, sampleRate and numberOfChannels. + * @returns {Promise} True when the configuration is decodable, false otherwise or when it cannot be probed. + */ + async supportsAudioConfigAsync(config) { + if (!this.hasAudioDecoder()) + return false; + try { + const result = await this.window.AudioDecoder.isConfigSupported(config); + // The isConfigSupported call resolves with a result object; a missing result and a false supported flag both + // mean the browser cannot decode this configuration, so the answer is returned as a single boolean. + return result !== null && result !== undefined && result.supported === true; + } catch (error) { + // An unsupported codec string can make isConfigSupported reject; that is a "no", not a failure of the player. + console.debug('Audio player: the codec configuration was rejected by the browser.', config, error); + return false; + } + } + + /** + * Reports whether the browser can decode a codec, by probing it with AudioDecoder.isConfigSupported. + * @param {Object} config - An AudioDecoderConfig like value, with codec, sampleRate and numberOfChannels. + * @returns {Promise} True when the configuration is decodable, false otherwise. + */ + async supportsCodecAsync(config) { + return await this.supportsAudioConfigAsync(config); + } + + /** + * Detects every capability the player needs, in parallel, and caches the report. + * + * The returned report has the shape: + * { webCodecs, audioDecoder, audioContext, codecs, missing, supported }, where codecs maps each probed codec name to a boolean, missing lists the + * {@link LuminaAudioPlayer.PlayerCapability} values that are absent, and supported is true only when every required capability is present. + * @returns {Promise} The capability report. + */ + async detectAsync() { + // The report is immutable and expensive to build, so it is cached for the life of the player; while the first + // detection is still running, later callers share its promise instead of starting a second round of probes. + if (this.report) + return this.report; + if (this.pendingReport) + return this.pendingReport; + this.pendingReport = this.runDetectionAsync(); + try { + this.report = await this.pendingReport; + } finally { + this.pendingReport = null; + } + return this.report; + } + + /** + * Runs the actual detection, once. + * @returns {Promise} The capability report. + */ + async runDetectionAsync() { + const webCodecs = this.hasWebCodecs(); + const audioDecoder = this.hasAudioDecoder(); + const audioContext = this.hasAudioContext(); + + const codecs = {}; + if (audioDecoder) { + // Each isConfigSupported is an independent round trip to the browser, so they are probed in parallel; the + // results are folded in afterwards, in probe order, so the report never depends on which probe finishes first. + const probeResults = await Promise.all(LuminaAudioPlayer.PROBED_AUDIO_CODECS.map(async (probe) => { + return { name: probe.name, supported: await this.supportsAudioConfigAsync(probe.config) }; + })); + for (const probeResult of probeResults) + codecs[probeResult.name] = probeResult.supported; + } else { + // Without a decoder nothing can be probed, but every codec key is still reported as false, so that a + // consumer reads the same shape whether the decoder exists or not, instead of testing for a missing key. + for (const probe of LuminaAudioPlayer.PROBED_AUDIO_CODECS) + codecs[probe.name] = false; + } + + // Only the three hard capabilities decide whether the player can run at all; a codec the browser cannot decode is + // not fatal here, because the server can normalize such a track, which the delivery decision handles at play time. + const missing = []; + if (!webCodecs) + missing.push(LuminaAudioPlayer.PlayerCapability.WEB_CODECS); + if (!audioDecoder) + missing.push(LuminaAudioPlayer.PlayerCapability.AUDIO_DECODER); + if (!audioContext) + missing.push(LuminaAudioPlayer.PlayerCapability.AUDIO_CONTEXT); + + // The report is shared and cached, so it is frozen to stop one consumer from mutating what every other consumer reads. + return Object.freeze({ + webCodecs, + audioDecoder, + audioContext, + codecs: Object.freeze(codecs), + missing: Object.freeze(missing), + supported: missing.length === 0 + }); + } + + /** + * Gets the cached capability report, or null when detection has not run yet. + * @returns {Object|null} The capability report, or null. + */ + getReport() { + return this.report; + } + } + + LuminaAudioPlayer.PlayerCapabilities = PlayerCapabilities; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); 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 new file mode 100644 index 00000000..f74f6723 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-engine.js @@ -0,0 +1,203 @@ +/** + * Engine interface of the audio player, and the registry of its implementations. + * + * The player controller owns the state machine, the play descriptor, the queue and the bar, but it + * produces no audio itself. Audio is produced by an engine, a swappable implementation of the + * interface documented below. This keeps the controller stable while the audio pipeline is built up, + * and lets a test drive the controller with a scripted engine instead of a real sound card. + * + * The engine interface + * -------------------- + * 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). + * - 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. + * - setVolumeAsync(volume): sets the output volume, as a value between 0 and 1, with 0 meaning silence. + * - 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.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. + * - host.reportEnded(): reports that the current track reached its end. + * - host.reportError(error): reports an engine failure, wrapped into a {@link LuminaAudioPlayer.PlayerError}. + * + * 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 + * 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, + * and it returns the player to idle when an engine instance is already running. + * A player can also be created directly with a selected engine and a populated registry through the constructor + * ({ engineName, engineRegistry }); LuminaAudioPlayer.createDefaultPlayer(options) forwards those options only for the + * first creation of the singleton, for a composition that creates the player itself, such as a test. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The name under which the silent engine that ships with the core module is registered. + * @readonly + * @type {string} + */ + LuminaAudioPlayer.NULL_ENGINE_NAME = 'null'; + + /** + * 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. + */ + class NullPlayerEngine { + /** + * Creates an instance of NullPlayerEngine. + * @param {Object} host - The engine host provided by the player controller. + */ + constructor(host) { + this.host = host; + this.descriptor = null; + this.currentTime = 0; + } + + /** + * Accepts a play descriptor without preparing any resource, and resets the tracked playhead. + * @param {Object} descriptor - The play descriptor of the requested track. + * @returns {Promise} A promise that always resolves. + */ + async loadAsync(descriptor) { + this.descriptor = descriptor; + this.currentTime = 0; + } + + /** + * Reports the tracked playhead without producing any audio, so that a resume keeps the position a pause left. + * @returns {Promise} A promise that always resolves. + */ + async playAsync() { + this.host.reportTime(this.currentTime, this.getDuration()); + } + + /** + * Reports the suspension of playback without producing any audio, keeping the tracked playhead. + * @returns {Promise} A promise that always resolves. + */ + async pauseAsync() { + } + + /** + * Records and reports the requested playhead without producing any audio. + * @param {number} seconds - The requested position, in seconds. + * @returns {Promise} A promise that always resolves. + */ + async seekAsync(seconds) { + const position = Number(seconds); + this.currentTime = Number.isFinite(position) && position > 0 ? position : 0; + this.host.reportTime(this.currentTime, this.getDuration()); + } + + /** + * Accepts an output volume without applying it to any output. + * @param {number} volume - The requested output volume, between 0 and 1. + * @returns {Promise} A promise that always resolves. + */ + async setVolumeAsync(volume) { + } + + /** + * Releases nothing, because nothing was acquired. + * @returns {Promise} A promise that always resolves. + */ + async destroyAsync() { + this.descriptor = null; + this.currentTime = 0; + } + + /** + * Gets the duration of the loaded descriptor, or zero when nothing is loaded. + * @returns {number} The known duration, in seconds. + */ + getDuration() { + return this.descriptor && Number.isFinite(this.descriptor.durationInSeconds) + ? this.descriptor.durationInSeconds + : 0; + } + } + + /** + * A registry of engine factories, keyed by name, used to resolve the engine the player runs with. + * The later stages of the player register the real download, decode and render engine here; the + * core module only registers the silent engine. + */ + class PlayerEngineRegistry { + /** + * Creates an instance of PlayerEngineRegistry. + */ + constructor() { + /** @type {Map} */ + this.factories = new Map(); + } + + /** + * Registers an engine factory. + * @param {string} name - The name the engine is resolved by. + * @param {Function} factory - A factory that receives the engine host and returns an engine. + * @returns {LuminaAudioPlayer.PlayerEngineRegistry} This registry, for chaining. + */ + register(name, factory) { + if (typeof factory !== 'function') + throw new TypeError('A player engine factory must be a function.'); + this.factories.set(name, factory); + return this; + } + + /** + * Checks whether an engine is registered under the given name. + * @param {string} name - The name of the engine. + * @returns {boolean} True when an engine is registered under that name, false otherwise. + */ + hasEngine(name) { + return this.factories.has(name); + } + + /** + * Creates an engine by name. + * @param {string} name - The name of the engine. + * @param {Object} host - The engine host provided by the player controller. + * @returns {Object|null} The created engine, or null when no engine with that name is registered. + */ + create(name, host) { + const factory = this.factories.get(name); + return factory ? factory(host) : null; + } + + /** + * Lists the names of the registered engines. + * @returns {Array} The registered engine names. + */ + getNames() { + return [...this.factories.keys()]; + } + } + + /** + * Creates a registry holding only the silent engine, the default of the core module. + * @returns {LuminaAudioPlayer.PlayerEngineRegistry} The default engine registry. + */ + LuminaAudioPlayer.createDefaultEngineRegistry = function () { + return new PlayerEngineRegistry().register(LuminaAudioPlayer.NULL_ENGINE_NAME, (host) => new NullPlayerEngine(host)); + }; + + LuminaAudioPlayer.NullPlayerEngine = NullPlayerEngine; + LuminaAudioPlayer.PlayerEngineRegistry = PlayerEngineRegistry; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); 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 new file mode 100644 index 00000000..da237cf1 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -0,0 +1,65 @@ +/** + * Typed errors of the audio player. + * + * The player never throws raw strings: every failure is reported through the event bus as a + * {@link LuminaAudioPlayer.PlayerError}, so that a consumer can branch on a stable code instead of + * matching a message, and so that a UI can present the failure without the player leaking + * implementation details, file paths, or secrets. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Enum-like object for the stable codes carried by a {@link LuminaAudioPlayer.PlayerError}. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerErrorCode = Object.freeze({ + // The browser is missing a capability the player requires (WebCodecs, AudioDecoder or AudioContext). + CAPABILITY_MISSING: 'capability-missing', + // The play descriptor handed to the player is missing a required value, or carries an invalid one. + INVALID_DESCRIPTOR: 'invalid-descriptor', + // The requested operation is not valid in the current player state. + INVALID_STATE: 'invalid-state', + // The engine could not be created, loaded or configured. + ENGINE_LOAD_FAILED: 'engine-load-failed', + // The engine reported a failure while decoding, buffering or rendering audio. + ENGINE_ERROR: 'engine-error', + // The stored playback preferences of the user could not be read. + PREFERENCES_LOAD_FAILED: 'preferences-load-failed' + }); + + /** + * An error raised by the player, carrying a stable code and optional structured details. + */ + class PlayerError extends Error { + /** + * Creates an instance of PlayerError. + * @param {string} code - One of the {@link LuminaAudioPlayer.PlayerErrorCode} values. + * @param {string} message - A developer facing description of the failure. It must never contain a file path, a token, or any other value that must not reach a log. + * @param {Object} [details] - Optional structured details about the failure, for example the missing capabilities. + */ + constructor(code, message, details = null) { + super(message); + this.name = 'PlayerError'; + this.code = code; + this.details = details; + } + + /** + * Wraps any value into a {@link LuminaAudioPlayer.PlayerError}, so that reported failures are always typed. + * @param {*} error - The value to wrap, typically an Error, a rejection reason, or a string. + * @param {string} [fallbackCode] - The code to use when the value is not already a player error. + * @returns {LuminaAudioPlayer.PlayerError} The typed player error. + */ + static from(error, fallbackCode = LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) { + if (error instanceof PlayerError) + return error; + if (error instanceof Error) + return new PlayerError(fallbackCode, error.message, { cause: error }); + return new PlayerError(fallbackCode, String(error)); + } + } + + LuminaAudioPlayer.PlayerError = PlayerError; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js new file mode 100644 index 00000000..eb325ddf --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-events.js @@ -0,0 +1,135 @@ +/** + * Event bus of the audio player. + * + * The player is decoupled from its consumers (the player bar, the transport UI, the queue panel, themes) through a single observable. + * Every module of the player publishes to this bus, and every consumer subscribes to it, so that no module needs a direct reference to another one. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Enum-like object for the events published by the player. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerEvent = Object.freeze({ + // The state machine moved to another state. Payload: { previousState, state }. + STATE_CHANGED: 'statechange', + // The currently playing track changed. Payload: the play descriptor. + DESCRIPTOR_CHANGED: 'descriptorchange', + // The queue changed. Payload: the ordered list of play descriptors. + QUEUE_CHANGED: 'queuechange', + // The playhead moved. Payload: { currentTime, duration }. + TIME_UPDATE: 'timeupdate', + // The duration of the current track became known or changed. Payload: { duration }. + DURATION_CHANGED: 'durationchange', + // The output volume changed. Payload: { volume, muted, effectiveVolume }. + VOLUME_CHANGED: 'volumechange', + // The mute state changed. Payload: { volume, muted, effectiveVolume }. + MUTE_CHANGED: 'mutechange', + // The downloaded fraction of the current track changed. Payload: { downloadedFraction }. + PROGRESS: 'progress', + // The current track reached its end. + ENDED: 'ended', + // A {@link LuminaAudioPlayer.PlayerError} was raised. Payload: the player error. + ERROR: 'error', + // Capability detection completed. Payload: the capability report. + CAPABILITIES_CHANGED: 'capabilitieschange', + // The stored playback preferences of the user were loaded. Payload: the preferences object. + PREFERENCES_CHANGED: 'preferenceschange', + // The player bar became visible or hidden. Payload: { visible }. The value is deliberately not 'visibilitychange', + // which is the name of the DOM page visibility event, so that the two can never be confused. + VISIBILITY_CHANGED: 'barvisibilitychange' + }); + + /** + * A minimal synchronous event bus with subscribe, unsubscribe and one-shot subscribe. + */ + class PlayerEventBus { + /** + * Creates an instance of PlayerEventBus. + */ + constructor() { + /** @type {Map>} */ + this.listeners = new Map(); + } + + /** + * Subscribes a handler to an event. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler invoked with the event payload. + * @returns {Function} A function that unsubscribes the handler. + */ + on(event, handler) { + if (typeof handler !== 'function') + throw new TypeError('The player event handler must be a function.'); + let handlers = this.listeners.get(event); + if (!handlers) { + handlers = new Set(); + this.listeners.set(event, handlers); + } + handlers.add(handler); + return () => this.off(event, handler); + } + + /** + * Subscribes a handler to an event, removing it after the first emission. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler invoked once with the event payload. + * @returns {Function} A function that unsubscribes the handler. + */ + once(event, handler) { + const unsubscribe = this.on(event, (payload) => { + unsubscribe(); + handler(payload); + }); + return unsubscribe; + } + + /** + * Unsubscribes a handler from an event. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler to remove. + */ + off(event, handler) { + const handlers = this.listeners.get(event); + if (handlers) + handlers.delete(handler); + } + + /** + * Publishes an event to every subscribed handler. + * + * A handler that throws does not prevent the remaining handlers from running: the failure is + * logged and swallowed, because a misbehaving consumer must never break the player. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {*} [payload] - The payload passed to each handler. + */ + emit(event, payload) { + const handlers = this.listeners.get(event); + if (!handlers || handlers.size === 0) + return; + // Copy the set, so that a handler that subscribes or unsubscribes during the emission does not affect this run. + for (const handler of [...handlers]) { + try { + handler(payload); + } catch (error) { + console.error(`Audio player: a handler of '${event}' threw.`, error); + } + } + } + + /** + * Removes every handler of an event, or of every event when none is provided. + * @param {string} [event] - One of the {@link LuminaAudioPlayer.PlayerEvent} values, or nothing to clear all. + */ + clear(event) { + if (event === undefined) + this.listeners.clear(); + else + this.listeners.delete(event); + } + } + + LuminaAudioPlayer.PlayerEventBus = PlayerEventBus; +})(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 new file mode 100644 index 00000000..fdecfbf3 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player.js @@ -0,0 +1,1313 @@ +/** + * The audio player of Lumina: state machine, play descriptor, lifecycle, bar and the public control API. + * + * The player is a singleton created once, in the application layout, outside the content area that the + * in-place navigation manager swaps. Because it is never torn down by a page swap, playback and its + * UI survive navigation. It produces no audio itself: audio is delegated to a swappable engine that + * fulfills the interface documented in audio-player-engine.js. This module only owns the state machine, the + * event bus, capability detection, the play descriptor, the bar and the public API; the download, + * decode and render pipeline is plugged in as an engine by the later stages. + * + * Public control API (window.LuminaAudioPlayer.instance) + * ---------------------------------------- + * Methods: + * - playAsync(descriptor): starts playback of a track. The descriptor is documented by createPlayDescriptor. + * When the descriptor carries a queue, that queue becomes the player queue. + * - pauseAsync(): suspends playback, keeping the position. + * - resumeAsync(): resumes playback from the current position. + * - toggleAsync(): pauses when playing, resumes otherwise. + * - stopAsync(): stops playback. While the bar is condensed, it also hides the bar; while the bar is + * expanded, it stays on screen. + * - seekAsync(seconds): moves the playhead to an absolute position, in seconds. + * - setVolumeAsync(volume): sets the output volume, between 0 and 1. + * - setMutedAsync(muted): sets the mute state. Volume and mute are independent: unmuting restores the volume. + * - toggleMuteAsync(): flips the mute state. + * - toggleFullHeight(): expands or collapses the bar. + * - 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(), getPreferences(), getCapabilities(), getLastError(). + * - 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. + * - useEngine(name): selects a registered engine; it takes effect on the next load. + * - getEngineName(): the name of the engine the player runs with. + * Properties: + * - capabilitiesReady: a Promise resolving to the capability report. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Enum-like object for the states of the player state machine. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.PlayerState = Object.freeze({ + // Nothing is loaded. This is also the state a stop returns to. + IDLE: 'idle', + // A track is being prepared. The download engine opens its stream here. + LOADING: 'loading', + // A track is prepared and can start producing audio. + READY: 'ready', + // Audio is being produced. + PLAYING: 'playing', + // Playback is suspended, and the position is kept. + PAUSED: 'paused', + // The current track reached its end. + ENDED: 'ended', + // A failure moved the player out of a normal state. + ERROR: 'error' + }); + + /** + * The states each state may move to. A transition outside this map is applied anyway, but it is + * logged, because it signals a bug in the caller rather than a recoverable condition. + * @readonly + * @type {Object>} + */ + const STATE_TRANSITIONS = Object.freeze({ + idle: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.ERROR], + loading: [LuminaAudioPlayer.PlayerState.READY, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + ready: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.PLAYING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + playing: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.PAUSED, LuminaAudioPlayer.PlayerState.ENDED, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + paused: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.PLAYING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + ended: [LuminaAudioPlayer.PlayerState.LOADING, LuminaAudioPlayer.PlayerState.PLAYING, LuminaAudioPlayer.PlayerState.IDLE, LuminaAudioPlayer.PlayerState.ERROR], + 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 attribute that marks an element as a play trigger the player handles by event delegation. + * @readonly + * @type {string} + */ + LuminaAudioPlayer.PLAY_DESCRIPTOR_ATTRIBUTE = 'data-audio-player-play'; + + /** + * Maps each play descriptor field to the data attribute the pages set on a play trigger, so the + * pages and the player share a single documented set of names. + * @readonly + * @type {Object} + */ + LuminaAudioPlayer.PLAY_DESCRIPTOR_DATA_KEYS = Object.freeze({ + trackId: 'trackId', + albumId: 'albumId', + artistId: 'artistId', + libraryId: 'libraryId', + title: 'title', + durationInSeconds: 'duration', + coverArtPath: 'coverArtPath', + coverArtUrl: 'coverArtUrl' + }); + + /** + * The marker shown in place of a duration that is not known, so that an absent duration reads as unknown + * instead of as a real zero. + * @readonly + * @type {string} + */ + const UNKNOWN_TIME = '--:--'; + + /** + * Formats a known, positive time in seconds as m:ss, or h:mm:ss when it is an hour or longer. + * @param {number} totalSeconds - The time to format, in seconds. + * @returns {string} The formatted time. + */ + function formatClock(totalSeconds) { + const seconds = Math.floor(totalSeconds % 60); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const hours = Math.floor(totalSeconds / 3600); + const paddedSeconds = String(seconds).padStart(2, '0'); + if (hours > 0) + return `${hours}:${String(minutes).padStart(2, '0')}:${paddedSeconds}`; + return `${minutes}:${paddedSeconds}`; + } + + /** + * Formats a playhead in seconds as m:ss, or h:mm:ss when it is an hour or longer. A playhead is always known, + * so a missing or negative value is the start of the track, and it is formatted as 0:00. + * @param {number} totalSeconds - The playhead to format, in seconds. + * @returns {string} The formatted playhead. + */ + function formatTime(totalSeconds) { + const value = Number(totalSeconds); + return Number.isFinite(value) && value > 0 ? formatClock(value) : '0:00'; + } + + /** + * Formats a duration in seconds as m:ss, or h:mm:ss when it is an hour or longer, and shows the unknown time + * marker while the duration is not known. + * @param {number} totalSeconds - The duration to format, in seconds. + * @returns {string} The formatted duration, or --:-- when the duration is not known. + */ + function formatDuration(totalSeconds) { + const value = Number(totalSeconds); + return Number.isFinite(value) && value > 0 ? formatClock(value) : UNKNOWN_TIME; + } + + /** + * Clamps a number into an inclusive range. + * @param {number} value - The value to clamp. + * @param {number} minimum - The inclusive lower bound. + * @param {number} maximum - The inclusive upper bound. + * @returns {number} The clamped value. + */ + function clamp(value, minimum, maximum) { + if (!Number.isFinite(value)) + return minimum; + return Math.min(maximum, Math.max(minimum, value)); + } + + /** + * Resolves the cover art of a track against the base URL of the API server, using the same artwork path the album page uses. + * + * Artwork is served by the API server, so a value is resolved against the API server base (or, when no base is + * configured, against the origin of the page) and is accepted only when it ends up on that same origin. A value on + * any other origin, a protocol relative value, any scheme other than http or https, and any value carrying a control + * character are rejected. This keeps a crafted cover art value from making the page fetch an image from a third + * party, which would leak the location of the user, and, by association, what they listen to. + * @param {string} value - The relative artwork path, or an absolute cover art URL on the API server. + * @returns {string} The normalized cover art URL, or an empty string when the value is missing or rejected. + */ + function resolveCoverArtUrl(value) { + if (!value) + return ''; + const raw = String(value).trim(); + if (raw === '') + return ''; + // A control character is rejected, a protocol relative value is rejected, and any scheme that is not http or + // https is rejected: the URL parser strips leading control characters, so a value such as "\0//host" would + // otherwise be treated as a different reference than the checks above see. + if (/[\u0000-\u001f\u007f]/.test(raw) || raw.startsWith('//') || (/^[a-z][a-z0-9+.-]*:/i.test(raw) && !/^https?:/i.test(raw))) + return ''; + const configuredBase = (window.globalConfiguration && window.globalConfiguration.serverBasePath) || ''; + const base = configuredBase || (window.location && window.location.origin) || ''; + // Without a base there is nothing to check the value against, so it is rejected rather than trusted. + if (!base) + return ''; + try { + const resolved = new URL(raw, base); + if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') + return ''; + // The artwork of a library must stay on the server that serves it, so the resolved origin is compared to the + // origin of the base the value was resolved against, and anything else is dropped instead of being loaded. + const allowedOrigin = new URL(base).origin; + return resolved.origin === allowedOrigin ? resolved.href : ''; + } catch (error) { + console.debug('Audio player: a cover art value could not be resolved.', error); + return ''; + } + } + + /** + * Normalizes a play descriptor, a plain object that describes what to play. + * + * Field rules: + * - libraryId (string, required): the Id of the media library the context belongs to. + * - trackId (string, required for a single track): the Id of the track. + * - albumId (string, optional): the Id of the album. A descriptor without a track Id describes an album play context. + * - artistId (string, optional): the Id of the artist. A descriptor without a track or album Id describes an artist play context. + * - title (string, optional): the display title of the track or context. + * - durationInSeconds (number, optional): the duration of the track, in seconds. + * - coverArtPath (string, optional): the relative artwork path of the album, resolved against the server base path. + * - coverArtUrl (string, optional): an absolute cover art URL, or a relative artwork path. + * - queue (Array, optional): the ordered track descriptors of the play context, used to render the expanded bar. + * @param {Object} input - The descriptor to normalize. + * @returns {Object|null} The normalized descriptor, or null when it identifies no library, or no track, album or artist. + */ + function createPlayDescriptor(input) { + if (!input || typeof input !== 'object') + return null; + const trackId = toIdString(input.trackId); + const albumId = toIdString(input.albumId); + const artistId = toIdString(input.artistId); + const libraryId = toIdString(input.libraryId); + // A track descriptor carries its track Id, while an album or artist context descriptor carries only the Id it is built from. + if (!libraryId || (!trackId && !albumId && !artistId)) + return null; + const coverArtSource = input.coverArtUrl || input.coverArtPath || ''; + const descriptor = { + trackId, + libraryId, + albumId, + artistId, + title: typeof input.title === 'string' ? input.title : '', + durationInSeconds: Number.isFinite(Number(input.durationInSeconds)) ? Number(input.durationInSeconds) : 0, + coverArtPath: typeof input.coverArtPath === 'string' ? input.coverArtPath : '', + coverArtUrl: resolveCoverArtUrl(coverArtSource) + }; + if (Array.isArray(input.queue)) { + const queue = input.queue.map(item => createPlayDescriptor(item)).filter(item => item !== null); + descriptor.queue = Object.freeze(queue); + } + return Object.freeze(descriptor); + } + + /** + * Coerces an Id into a non empty string, or an empty string when it carries no value. + * @param {*} value - The Id to coerce. + * @returns {string} The Id as a string, or an empty string. + */ + function toIdString(value) { + if (value === null || value === undefined) + return ''; + const text = String(value).trim(); + return text === '' ? '' : text; + } + + /** + * Reads a play descriptor from the data attributes of a play trigger element, per + * {@link LuminaAudioPlayer.PLAY_DESCRIPTOR_DATA_KEYS}. + * @param {Element} element - The element carrying the descriptor attributes. + * @returns {Object|null} The normalized descriptor, or null when the element does not describe a valid track. + */ + function readPlayDescriptorFromElement(element) { + if (!element || !element.dataset) + return null; + const keys = LuminaAudioPlayer.PLAY_DESCRIPTOR_DATA_KEYS; + return createPlayDescriptor({ + trackId: element.dataset[keys.trackId], + albumId: element.dataset[keys.albumId], + artistId: element.dataset[keys.artistId], + libraryId: element.dataset[keys.libraryId], + title: element.dataset[keys.title], + durationInSeconds: element.dataset[keys.durationInSeconds], + coverArtPath: element.dataset[keys.coverArtPath], + coverArtUrl: element.dataset[keys.coverArtUrl] + }); + } + + /** + * The audio player. See the module documentation for the public control API. + */ + class AudioPlayer { + /** + * Creates an instance of AudioPlayer. + * @param {Object} [options] - The player options. + * @param {HTMLElement} [options.container] - The player bar element. Defaults to the first element with the audio-player-container class. + * @param {HTMLElement} [options.main] - The main content element, whose class tracks the bar visibility. Defaults to the first main element. + * @param {LuminaAudioPlayer.PlayerEventBus} [options.events] - The event bus to publish to. A new one is created when omitted. + * @param {LuminaAudioPlayer.PlayerCapabilities} [options.capabilities] - The capability detector. A new one is created when omitted. + * @param {LuminaAudioPlayer.PlayerEngineRegistry} [options.engineRegistry] - The engine registry. The default registry is created when omitted. + * @param {string} [options.engineName] - The name of the engine to run. Defaults to the silent engine. + * @param {Object} [options.configuration] - The endpoints configuration. Defaults to window.audioPlayerConfiguration. + */ + constructor(options = {}) { + this.options = options; + this.events = options.events || new LuminaAudioPlayer.PlayerEventBus(); + this.capabilities = options.capabilities || new LuminaAudioPlayer.PlayerCapabilities(); + this.engineRegistry = options.engineRegistry || LuminaAudioPlayer.createDefaultEngineRegistry(); + this.engineName = options.engineName || LuminaAudioPlayer.NULL_ENGINE_NAME; + + this.state = LuminaAudioPlayer.PlayerState.IDLE; + this.descriptor = null; + this.queue = []; + this.currentIndex = 0; + this.currentTime = 0; + this.duration = 0; + this.downloadedFraction = 0; + this.volume = 1; + this.muted = false; + this.lastError = null; + this.preferences = { + shouldKeepDownloadingWhilePaused: false, + shouldAutoplay: false, + isGaplessPlaybackEnabled: false, + replayGainMode: 'Off', + streamingQuality: 'Auto' + }; + this.capabilityReport = null; + this.capabilitiesReady = null; + this.engine = null; + this.available = false; + this.initialized = false; + this.container = null; + this.main = null; + this.dom = {}; + this.descriptorClickHandler = null; + this.controlHandlers = []; + this.progressRenderScheduled = false; + } + + /** + * Binds the player to the bar in the layout, prepares the hidden state, and starts capability + * detection and the load of the stored playback preferences. + * + * The method is idempotent: a second call returns immediately. When the layout does not render + * a bar (an unauthenticated visitor), the player marks itself unavailable and every control + * method becomes a no-op. + * @returns {LuminaAudioPlayer.AudioPlayer} This player, for chaining. + */ + initialize() { + if (this.initialized) + return this; + this.initialized = true; + + this.container = this.options.container || document.querySelector('.audio-player-container'); + this.main = this.options.main || document.querySelector('main'); + if (!this.container) { + this.available = false; + return this; + } + this.available = true; + + this.collectDomReferences(); + this.bindPlaybackControls(); + this.bindDescriptorDelegation(); + // The bar is hidden until the user starts playback, so a refresh never flashes an empty player. + this.suppressInitialTransitions(); + this.applyHiddenState(); + this.releaseInitialHiddenState(); + + this.capabilitiesReady = this.detectCapabilitiesAsync(); + // The stored preferences are read in the background; a slow or failing request never blocks the bar. + this.loadPreferencesAsync(); + return this; + } + + /** + * Collects the references to the bar elements the player drives, once, so that a navigation + * that swaps the content area never invalidates them. + */ + collectDomReferences() { + const query = (selector) => this.container.querySelector(selector); + this.dom.trackName = query('[data-audio-player-track-name]'); + this.dom.coverThumbnail = query('[data-audio-player-cover-thumbnail]'); + this.dom.coverImage = query('[data-audio-player-cover-image]'); + this.dom.currentTime = query('[data-audio-player-current-time]'); + this.dom.totalTime = query('[data-audio-player-total-time]'); + this.dom.progress = query('[data-audio-player-progress]'); + this.dom.progressPlayed = query('[data-audio-player-progress-played]'); + this.dom.progressDownloaded = query('[data-audio-player-progress-downloaded]'); + this.dom.playPause = query('[data-audio-player-play-pause]'); + this.dom.queue = query('[data-audio-player-queue]'); + } + + /** + * Binds the transport controls the player owns. The full height and close affordances are bound + * by the global site script, which delegates them to this player, so that a single click never + * toggles them twice. + */ + bindPlaybackControls() { + if (this.dom.playPause) + this.addControlHandler(this.dom.playPause, 'click', () => this.toggleAsync()); + if (this.dom.progress) + this.addControlHandler(this.dom.progress, 'click', (event) => this.handleProgressClick(event)); + } + + /** + * Adds a click handler to a bar element, and remembers it so that an explicit teardown can remove it. + * @param {HTMLElement} element - The element to bind. + * @param {string} event - The DOM event to listen to. + * @param {Function} handler - The handler to invoke. + */ + addControlHandler(element, event, handler) { + element.addEventListener(event, handler); + this.controlHandlers.push({ element, event, handler }); + } + + /** + * Binds the global click delegation that turns an element carrying the play trigger attribute + * into a play request, so that pages never need a direct reference to the player. + */ + bindDescriptorDelegation() { + this.descriptorClickHandler = (event) => { + if (!(event.target instanceof Element)) + return; + const trigger = event.target.closest(`[${LuminaAudioPlayer.PLAY_DESCRIPTOR_ATTRIBUTE}]`); + if (!trigger) + return; + event.preventDefault(); + const descriptor = readPlayDescriptorFromElement(trigger); + this.playAsync(descriptor).catch((error) => this.raiseError(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR)); + }; + document.addEventListener('click', this.descriptorClickHandler); + } + + /** + * Starts playback of a track, and shows the bar. + * @param {Object} descriptorInput - The play descriptor to play, per {@link LuminaAudioPlayer.createPlayDescriptor}. + * @returns {Promise} True when playback started, false when the request was rejected. + */ + async playAsync(descriptorInput) { + // The player is only available when the layout rendered the bar, so a caller on a page without one is ignored instead of failing. + if (!this.available) + return false; + const descriptor = createPlayDescriptor(descriptorInput); + if (!descriptor) { + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.INVALID_DESCRIPTOR, 'The play descriptor identifies no library, or no track, album or artist.')); + return false; + } + // Capability detection runs in the background while the page loads, so the first play waits for its answer instead + // of starting a track the browser may not be able to decode. + const report = await this.capabilitiesReady; + if (report && !report.supported) { + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'The browser is missing a capability the player requires.', + { missing: report.missing })); + return false; + } + + // A new descriptor starts a new timeline, so the playhead and the progress of the previous track are dropped. + this.descriptor = descriptor; + this.duration = descriptor.durationInSeconds; + this.currentTime = 0; + this.downloadedFraction = 0; + // 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)); + + // 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. + this.renderDescriptor(); + this.renderProgress(); + this.renderQueue(); + this.showBar(); + this.setState(LuminaAudioPlayer.PlayerState.LOADING); + this.events.emit(LuminaAudioPlayer.PlayerEvent.DESCRIPTOR_CHANGED, descriptor); + this.events.emit(LuminaAudioPlayer.PlayerEvent.QUEUE_CHANGED, this.queue); + + 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); + this.setState(LuminaAudioPlayer.PlayerState.READY); + await engine.playAsync(); + this.setState(LuminaAudioPlayer.PlayerState.PLAYING); + this.renderTransportState(); + } catch (error) { + // 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; + } + return true; + } + + /** + * Suspends playback, keeping the current position. + * @returns {Promise} A promise that completes when the engine paused. + */ + async pauseAsync() { + // Pausing anything that is not playing is a no-op, so the pause and close controls stay harmless when clicked twice. + if (this.state !== LuminaAudioPlayer.PlayerState.PLAYING) + return; + if (this.engine) + await this.engine.pauseAsync(); + this.setState(LuminaAudioPlayer.PlayerState.PAUSED); + this.renderTransportState(); + } + + /** + * Resumes playback from the current position. + * @returns {Promise} A promise that completes when the engine resumed. + */ + async resumeAsync() { + // A ready track has not started yet, and a paused one keeps its position, so both can resume. + if (this.state !== LuminaAudioPlayer.PlayerState.PAUSED && this.state !== LuminaAudioPlayer.PlayerState.READY) + return; + // Without an engine there is nothing to resume; the next play builds one and applies the stored volume. + if (!this.engine) + return; + await this.engine.playAsync(); + this.setState(LuminaAudioPlayer.PlayerState.PLAYING); + this.renderTransportState(); + } + + /** + * Pauses when playing, resumes when paused or ready, and replays the current track when idle. + * @returns {Promise} A promise that completes when the toggle was applied. + */ + async toggleAsync() { + if (this.state === LuminaAudioPlayer.PlayerState.PLAYING) + await this.pauseAsync(); + else if (this.state === LuminaAudioPlayer.PlayerState.PAUSED || this.state === LuminaAudioPlayer.PlayerState.READY) + await this.resumeAsync(); + else if (this.descriptor) + await this.playAsync(this.descriptor); + } + + /** + * Stops playback. While the bar is condensed, it slides out of view; while the bar is expanded, + * it stays on screen with the current track, and only playback stops. + * @returns {Promise} A promise that completes when playback stopped. + */ + async stopAsync() { + if (this.engine) { + try { + // The engine is paused rather than destroyed, because it is reused for the next track and rebuilding it would + // drop resources such as the audio context that a user gesture is needed to resume. + await this.engine.pauseAsync(); + } catch (error) { + // A failure while stopping must not prevent the player from returning to idle. + console.error('Audio player: the engine failed while stopping.', error); + } + } + // The playhead and the progress are reset while the descriptor is kept, so the bar can still show what was stopped. + this.currentTime = 0; + this.downloadedFraction = 0; + this.renderProgress(); + this.setState(LuminaAudioPlayer.PlayerState.IDLE); + this.renderTransportState(); + // A condensed bar slides out when playback stops, while an expanded one stays so the user keeps the track and its queue in view. + if (!this.isExpanded()) + this.hideBar(); + } + + /** + * Moves the playhead to an absolute position. + * @param {number} seconds - The target position, in seconds. + * @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) + 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); + const position = this.duration > 0 + ? clamp(request, 0, this.duration) + : Math.max(0, Number.isFinite(request) ? request : 0); + this.currentTime = position; + if (this.engine) { + try { + await this.engine.seekAsync(position); + } catch (error) { + this.raiseError(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + } + // The engine reports the new playhead itself, so the render is coalesced with that report instead of racing it. + this.scheduleProgressRender(); + } + + /** + * Sets the output volume. Mute is independent of the volume: a muted player remembers the volume. + * @param {number} volume - The output volume, between 0 and 1. + * @returns {Promise} The applied volume. + */ + async setVolumeAsync(volume) { + const value = clamp(Number(volume), 0, 1); + this.volume = value; + await this.applyVolumeAsync(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.VOLUME_CHANGED, this.buildVolumePayload()); + return this.volume; + } + + /** + * Sets the mute state. + * @param {boolean} muted - True to mute the output, false to unmute it. + * @returns {Promise} A promise that completes when the mute was applied. + */ + async setMutedAsync(muted) { + this.muted = muted === true; + await this.applyVolumeAsync(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.MUTE_CHANGED, this.buildVolumePayload()); + } + + /** + * Flips the mute state. + * @returns {Promise} A promise that completes when the mute was applied. + */ + async toggleMuteAsync() { + await this.setMutedAsync(!this.muted); + } + + /** + * Expands the bar into its full height form, or collapses it back to the condensed bar. + * @returns {boolean} True when the bar is expanded after the toggle. + */ + toggleFullHeight() { + if (!this.container) + return false; + const expanded = this.container.classList.toggle('full-height'); + if (this.main) + this.main.classList.toggle('audio-player-full-height', expanded); + return expanded; + } + + /** + * Shows the bar when it is hidden, and hides it when it is visible. + * @returns {boolean} True when the bar is visible after the toggle. + */ + toggleVisibility() { + if (!this.container) + return false; + if (this.container.classList.contains('not-shown')) + this.showBar(); + else + this.hideBar(); + return !this.container.classList.contains('not-shown'); + } + + /** + * Shows the bar and reflows the content area around it. A bar that is already shown is left untouched, and no + * visibility event is emitted, so a consumer is never asked to animate a change that did not happen. + */ + showBar() { + if (!this.container) + return; + const wasHidden = this.container.classList.contains('not-shown'); + this.container.removeAttribute('hidden'); + this.container.classList.remove('not-shown'); + if (this.main) + this.main.classList.remove('audio-player-not-shown'); + if (wasHidden) + this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { visible: true }); + } + + /** + * Hides the bar and reflows the content area over it. A bar that is already hidden is left untouched, and no + * visibility event is emitted, so a consumer is never asked to animate a change that did not happen. + */ + hideBar() { + if (!this.container) + return; + if (this.container.classList.contains('not-shown')) + return; + this.container.classList.add('not-shown'); + if (this.main) + this.main.classList.add('audio-player-not-shown'); + this.events.emit(LuminaAudioPlayer.PlayerEvent.VISIBILITY_CHANGED, { visible: false }); + } + + /** + * Checks whether the bar is in its expanded form. + * @returns {boolean} True when the bar is expanded. + */ + isExpanded() { + return this.container !== null && this.container.classList.contains('full-height'); + } + + /** + * Gets the current state of the state machine. + * @returns {string} One of the {@link LuminaAudioPlayer.PlayerState} values. + */ + getState() { + return this.state; + } + + /** + * Gets the descriptor of the track the player last started. + * @returns {Object|null} The play descriptor, or null. + */ + getDescriptor() { + return this.descriptor; + } + + /** + * Gets the ordered queue of the current play context. + * @returns {Array} The ordered play descriptors. + */ + getQueue() { + return [...this.queue]; + } + + /** + * Gets the playhead of the current track. + * @returns {number} The playhead, in seconds. + */ + getCurrentTime() { + return this.currentTime; + } + + /** + * Gets the known duration of the current track. + * @returns {number} The duration, in seconds. + */ + getDuration() { + return this.duration; + } + + /** + * Gets the output volume, which is independent of the mute state. + * @returns {number} The volume, between 0 and 1. + */ + getVolume() { + return this.volume; + } + + /** + * Gets the mute state. + * @returns {boolean} True when the output is muted. + */ + isMuted() { + return this.muted; + } + + /** + * Gets the stored playback preferences loaded for the user. + * @returns {Object} The preferences. + */ + getPreferences() { + return this.preferences; + } + + /** + * Gets the last capability report, or null when detection has not completed yet. + * @returns {Object|null} The capability report. + */ + getCapabilities() { + return this.capabilityReport; + } + + /** + * Gets the last typed error the player raised. + * @returns {LuminaAudioPlayer.PlayerError|null} The last error, or null. + */ + getLastError() { + return this.lastError; + } + + /** + * Subscribes to a player event. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler invoked with the event payload. + * @returns {Function} A function that unsubscribes the handler. + */ + on(event, handler) { + return this.events.on(event, handler); + } + + /** + * Subscribes to a player event once. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler invoked once with the event payload. + * @returns {Function} A function that unsubscribes the handler. + */ + once(event, handler) { + return this.events.once(event, handler); + } + + /** + * Unsubscribes a handler from a player event. + * @param {string} event - One of the {@link LuminaAudioPlayer.PlayerEvent} values. + * @param {Function} handler - The handler to remove. + */ + off(event, handler) { + this.events.off(event, handler); + } + + /** + * Releases every resource the player holds. It is intended for an explicit teardown only: the + * in-place navigation manager never destroys the player, so that playback survives navigation. + * @returns {Promise} A promise that completes when the engine was destroyed. + */ + async destroyAsync() { + if (this.descriptorClickHandler) { + document.removeEventListener('click', this.descriptorClickHandler); + this.descriptorClickHandler = null; + } + for (const control of this.controlHandlers) + control.element.removeEventListener(control.event, control.handler); + this.controlHandlers = []; + if (this.engine) { + try { + await this.engine.destroyAsync(); + } catch (error) { + console.error('Audio player: the engine failed to destroy itself.', error); + } + this.engine = null; + } + this.events.clear(); + this.setState(LuminaAudioPlayer.PlayerState.IDLE); + // The singleton is no longer usable, so it is cleared, and a later createDefaultPlayer builds a fresh one. + if (LuminaAudioPlayer.instance === this) + LuminaAudioPlayer.instance = null; + } + + //+======================================================================================+ + //| Internal helpers | + //+======================================================================================+ + + /** + * Moves the state machine to another state and publishes the change. + * @param {string} nextState - One of the {@link LuminaAudioPlayer.PlayerState} values. + */ + setState(nextState) { + if (this.state === nextState) + return; + const previousState = this.state; + const allowed = STATE_TRANSITIONS[previousState] || []; + if (!allowed.includes(nextState)) + console.warn(`Audio player: the transition '${previousState}' -> '${nextState}' is not part of the state machine.`); + this.state = nextState; + this.events.emit(LuminaAudioPlayer.PlayerEvent.STATE_CHANGED, { previousState, state: nextState }); + } + + /** + * Raises a typed error without moving the state machine. + * @param {*} error - The error to raise, wrapped into a {@link LuminaAudioPlayer.PlayerError}. + * @param {string} [code] - The code to use when the error is not already typed. + * @returns {LuminaAudioPlayer.PlayerError} The raised typed error. + */ + raiseError(error, code = LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) { + const typed = LuminaAudioPlayer.PlayerError.from(error, code); + this.lastError = typed; + console.error(`Audio player: ${typed.code}.`, typed.message); + this.events.emit(LuminaAudioPlayer.PlayerEvent.ERROR, typed); + return typed; + } + + /** + * Raises a typed error and moves the state machine to the error state. + * @param {*} error - The error to raise. + * @param {string} [code] - The code to use when the error is not already typed. + * @returns {LuminaAudioPlayer.PlayerError} The raised typed error. + */ + fail(error, code = LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) { + const typed = this.raiseError(error, code); + this.setState(LuminaAudioPlayer.PlayerState.ERROR); + return typed; + } + + /** + * Registers an engine factory on this player, by name. + * + * This is the documented seam through which the later stages plug the real download, decode and render + * engine into the player, without reaching into its internals. + * @param {string} name - The name the engine is selected by, later passed to {@link LuminaAudioPlayer.AudioPlayer#useEngine}. + * @param {Function} factory - A factory that receives the engine host and returns an engine. + * @returns {LuminaAudioPlayer.AudioPlayer} This player, for chaining. + */ + registerEngine(name, factory) { + this.engineRegistry.register(name, factory); + return this; + } + + /** + * Selects the registered engine the player runs with. The selection takes effect on the next load. + * + * When an engine instance is already created, it is destroyed and dropped, so that the next load builds the + * newly selected engine. Selecting an engine while a track plays therefore stops that track and returns the + * player to its idle state, so it is meant to be called during setup, before playback starts. + * @param {string} name - The name of a registered engine. + * @returns {LuminaAudioPlayer.AudioPlayer} This player, for chaining. + * @throws {LuminaAudioPlayer.PlayerError} When no engine with that name is registered. + */ + useEngine(name) { + if (name === this.engineName) + return this; + if (!this.engineRegistry.hasEngine(name)) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, `No player engine named '${name}' is registered.`); + this.engineName = name; + if (this.engine) { + const previous = this.engine; + this.engine = null; + // The engine that was playing is gone, so the player returns to idle instead of claiming it is still playing. + if (this.state !== LuminaAudioPlayer.PlayerState.IDLE) { + this.setState(LuminaAudioPlayer.PlayerState.IDLE); + this.renderTransportState(); + } + try { + Promise.resolve(previous.destroyAsync()).catch((error) => console.error('Audio player: the previous engine failed to destroy itself.', error)); + } catch (error) { + console.error('Audio player: the previous engine failed to destroy itself.', error); + } + } + return this; + } + + /** + * Gets the name of the engine the player runs with. + * @returns {string} The selected engine name. + */ + getEngineName() { + return this.engineName; + } + + /** + * Ensures an engine exists, creating it from the registry on first use. + * @returns {Promise} The engine. + */ + async ensureEngineAsync() { + if (this.engine) + return this.engine; + this.engine = this.engineRegistry.create(this.engineName, this.createEngineHost()); + if (!this.engine) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.ENGINE_LOAD_FAILED, `No player engine named '${this.engineName}' is registered.`); + // The stored volume is applied at creation, so the very first track starts at the volume the user last chose. + await this.applyVolumeAsync(); + return this.engine; + } + + /** + * Builds the host object through which an engine reports back to the player. + * @returns {Object} The engine host. + */ + createEngineHost() { + return { + events: this.events, + reportTime: (currentTime, duration) => this.handleEngineTime(currentTime, duration), + reportDuration: (duration) => this.handleEngineDuration(duration), + reportProgress: (fraction) => this.handleEngineProgress(fraction), + reportEnded: () => this.handleEngineEnded(), + reportError: (error) => this.fail(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR) + }; + } + + /** + * Handles a playhead report from the engine. + * + * The report only updates the player state and schedules the render, so that a burst of reports coalesces into + * a single set of DOM writes and a single event emission per animation frame. + * @param {number} currentTime - The current playhead, in seconds. + * @param {number} duration - The known duration, in seconds. + */ + handleEngineTime(currentTime, duration) { + this.handleEngineDuration(duration); + const position = Number(currentTime); + this.currentTime = Number.isFinite(position) && position > 0 ? position : 0; + this.scheduleProgressRender(); + } + + /** + * Handles a duration report from the engine. + * @param {number} duration - The known duration, in seconds. + */ + handleEngineDuration(duration) { + const value = Number(duration); + if (!Number.isFinite(value) || value <= 0 || value === this.duration) + return; + this.duration = value; + // The total time is written by the coalesced progress render, so it is not written twice for one report. + this.scheduleProgressRender(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.DURATION_CHANGED, { duration: this.duration }); + } + + /** + * Handles a download progress report from the engine. + * @param {number} fraction - The downloaded fraction, between 0 and 1. + */ + handleEngineProgress(fraction) { + const value = clamp(Number(fraction), 0, 1); + this.downloadedFraction = value; + this.scheduleProgressRender(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.PROGRESS, { downloadedFraction: value }); + } + + /** + * Coalesces the progress bar DOM writes and the playhead event into a single animation frame, so that a + * high frequency stream of engine reports does not turn into a high frequency stream of DOM writes. + */ + scheduleProgressRender() { + if (this.progressRenderScheduled) + return; + this.progressRenderScheduled = true; + const render = () => { + this.progressRenderScheduled = false; + this.renderProgress(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.TIME_UPDATE, { currentTime: this.currentTime, duration: this.duration }); + }; + if (typeof requestAnimationFrame === 'function') + requestAnimationFrame(render); + else + render(); + } + + /** + * Handles the end of the current track reported by the engine. + */ + handleEngineEnded() { + this.setState(LuminaAudioPlayer.PlayerState.ENDED); + this.renderTransportState(); + this.events.emit(LuminaAudioPlayer.PlayerEvent.ENDED); + } + + /** + * Detects the browser capabilities and publishes a typed error when one is missing. + * @returns {Promise} The capability report. + */ + async detectCapabilitiesAsync() { + const report = await this.capabilities.detectAsync(); + this.capabilityReport = report; + this.events.emit(LuminaAudioPlayer.PlayerEvent.CAPABILITIES_CHANGED, report); + if (!report.supported) { + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.CAPABILITY_MISSING, 'The browser is missing a capability the player requires.', + { missing: report.missing })); + } + return report; + } + + /** + * Reads the stored playback preferences of the user: the behavior preferences from the user + * settings endpoint, and the last volume and mute state from the playback state endpoint. + * @returns {Promise} A promise that completes when the preferences were read. + */ + async loadPreferencesAsync() { + const configuration = this.getConfiguration(); + const [settings, playbackState] = await Promise.all([ + this.fetchJsonAsync(configuration.getUserSettingsUrl), + this.fetchJsonAsync(configuration.getPlaybackStateUrl) + ]); + // A redirect means the session expired and the page is already navigating to the sign in page, so nothing is + // reported and nothing is applied, instead of treating an expected outcome as a failure. + if (settings === REDIRECTED || playbackState === REDIRECTED) + return; + if (settings === undefined || playbackState === undefined) + this.raiseError(new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.PREFERENCES_LOAD_FAILED, 'The stored playback preferences of the user could not be read.')); + if (settings) { + this.preferences = { + shouldKeepDownloadingWhilePaused: settings.shouldKeepDownloadingWhilePaused === true, + shouldAutoplay: settings.shouldAutoplay === true, + isGaplessPlaybackEnabled: settings.isGaplessPlaybackEnabled === true, + replayGainMode: settings.replayGainMode || 'Off', + streamingQuality: settings.streamingQuality || 'Auto' + }; + this.events.emit(LuminaAudioPlayer.PlayerEvent.PREFERENCES_CHANGED, this.preferences); + } + if (playbackState) { + if (Number.isFinite(Number(playbackState.volume))) + await this.setVolumeAsync(clamp(Number(playbackState.volume), 0, 1)); + if (typeof playbackState.isMuted === 'boolean') + await this.setMutedAsync(playbackState.isMuted); + } + } + + /** + * Gets the endpoints configuration of the player. + * @returns {Object} The endpoints configuration. + */ + getConfiguration() { + return this.options.configuration || window.audioPlayerConfiguration || {}; + } + + /** + * Reads a JSON payload from a web endpoint, without surfacing a notification on failure, because + * the request is a background one that must never disturb the page. + * + * 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. + * @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) { + if (!url) + return null; + try { + const response = await fetch(url, { + headers: { + 'Accept': 'application/json', + 'X-Requested-With': 'XMLHttpRequest' + } + }); + if (response.redirected) { + // The session expired and the server answered with the login page; follow it, and report the redirect, not a failure. + window.location.href = response.url; + return REDIRECTED; + } + if (!response.ok) + return undefined; + const payload = await response.json(); + return payload && payload.success === true ? payload.data : null; + } catch (error) { + console.error('Audio player: a preferences request failed.', error); + return undefined; + } + } + + /** + * Applies the effective volume to the engine. + * @returns {Promise} A promise that completes when the engine received the volume. + */ + async applyVolumeAsync() { + // Before the first play there is no engine to receive the volume, so it is remembered and applied when the engine is + // created, which keeps a volume set before playback from being lost. + if (!this.engine) + return; + try { + await this.engine.setVolumeAsync(this.getEffectiveVolume()); + } catch (error) { + this.raiseError(error, LuminaAudioPlayer.PlayerErrorCode.ENGINE_ERROR); + } + } + + /** + * Gets the volume actually sent to the output, which is zero while muted. + * @returns {number} The effective volume, between 0 and 1. + */ + getEffectiveVolume() { + return this.muted ? 0 : this.volume; + } + + /** + * Builds the payload shared by the volume and mute events. + * @returns {Object} The volume payload. + */ + buildVolumePayload() { + return { volume: this.volume, muted: this.muted, effectiveVolume: this.getEffectiveVolume() }; + } + + /** + * Handles a click on the progress bar as a seek to the clicked ratio. + * @param {MouseEvent} event - The click event on the progress bar. + */ + handleProgressClick(event) { + if (!this.descriptor || this.duration <= 0 || !this.dom.progress) + return; + const bounds = this.dom.progress.getBoundingClientRect(); + if (bounds.width <= 0) + return; + const ratio = clamp((event.clientX - bounds.left) / bounds.width, 0, 1); + this.seekAsync(ratio * this.duration); + } + + /** + * Ensures the bar starts hidden, so that a page load never flashes an empty player. + */ + applyHiddenState() { + this.container.classList.add('not-shown'); + if (this.main) + this.main.classList.add('audio-player-not-shown'); + } + + /** + * Suppresses the transitions of the bar and of the content area while the initial hidden state is applied, so + * that a page load never slides either of them into place. The suppression is removed after the next frame, + * once the hidden state is already in effect, so later show and hide transitions keep working. + */ + suppressInitialTransitions() { + const root = document.documentElement; + if (!root || !root.classList) + return; + root.classList.add('audio-player-initializing'); + const release = () => root.classList.remove('audio-player-initializing'); + if (typeof requestAnimationFrame === 'function') + requestAnimationFrame(() => requestAnimationFrame(release)); + else + release(); + } + + /** + * Removes the initial 'hidden' attribute of the bar, now that the 'not-shown' class already keeps it hidden. + * + * The markup ships the bar with the 'hidden' attribute, so that it cannot be painted before this script runs, + * no matter how the stylesheets settle. By the time the attribute is removed the bar is already at its hidden + * height, so the removal is never visible; the class that remains is what later show and hide transitions act on. + */ + releaseInitialHiddenState() { + const release = () => { + if (this.container) + this.container.removeAttribute('hidden'); + }; + if (typeof requestAnimationFrame === 'function') + requestAnimationFrame(release); + else + release(); + } + + /** + * Renders the track name, the cover art and the total time of the current descriptor. + */ + renderDescriptor() { + const descriptor = this.descriptor; + if (this.dom.trackName) + this.dom.trackName.textContent = descriptor ? descriptor.title : ''; + const coverArtUrl = descriptor && descriptor.coverArtUrl + ? descriptor.coverArtUrl + : '/images/ui/music-placeholder.svg'; + if (this.dom.coverThumbnail) + this.dom.coverThumbnail.src = coverArtUrl; + if (this.dom.coverImage) + this.dom.coverImage.src = coverArtUrl; + if (this.dom.totalTime) + this.dom.totalTime.textContent = formatDuration(this.duration); + this.renderTransportState(); + } + + /** + * Renders the three state progress bar: the played part, the downloaded part, and the remainder. + */ + renderProgress() { + if (this.dom.currentTime) + this.dom.currentTime.textContent = formatTime(this.currentTime); + if (this.dom.totalTime) + this.dom.totalTime.textContent = formatDuration(this.duration); + const playedRatio = this.duration > 0 ? clamp(this.currentTime / this.duration, 0, 1) : 0; + const downloadedRatio = clamp(this.downloadedFraction, 0, 1); + if (this.dom.progressPlayed) + this.dom.progressPlayed.style.width = `${playedRatio * 100}%`; + if (this.dom.progressDownloaded) + this.dom.progressDownloaded.style.width = `${downloadedRatio * 100}%`; + } + + /** + * Renders the play or pause affordance of the transport control. + */ + renderTransportState() { + const playing = this.state === LuminaAudioPlayer.PlayerState.PLAYING; + if (this.dom.playPause) + this.dom.playPause.classList.toggle('is-playing', playing); + } + + /** + * Renders the ordered queue in the expanded bar. The list is only shown when the play context + * holds more than one track, so that a single track never renders a one item list. + */ + renderQueue() { + if (!this.dom.queue) + return; + this.dom.queue.innerHTML = ''; + const items = this.queue.length > 1 ? this.queue : []; + for (const item of items) { + const entry = document.createElement('li'); + entry.className = 'audio-player-queue-item'; + entry.dataset.trackId = item.trackId; + const title = document.createElement('span'); + title.className = 'audio-player-queue-item-title'; + title.textContent = item.title || ''; + const duration = document.createElement('span'); + duration.className = 'audio-player-queue-item-duration'; + duration.textContent = formatDuration(item.durationInSeconds); + entry.appendChild(title); + entry.appendChild(duration); + this.dom.queue.appendChild(entry); + } + } + } + + LuminaAudioPlayer.AudioPlayer = AudioPlayer; + + // Expose the descriptor helpers on the namespace, so that a page or a test builds a descriptor the same way the player does. + LuminaAudioPlayer.createPlayDescriptor = createPlayDescriptor; + LuminaAudioPlayer.resolveCoverArtUrl = resolveCoverArtUrl; + LuminaAudioPlayer.readPlayDescriptorFromElement = readPlayDescriptorFromElement; + LuminaAudioPlayer.formatPlayerTime = formatTime; + LuminaAudioPlayer.formatPlayerDuration = formatDuration; + LuminaAudioPlayer.UNKNOWN_TIME = UNKNOWN_TIME; + + /** + * Creates the singleton player of the application, binds it to the layout bar, and exposes it as + * window.LuminaAudioPlayer.instance. The player is created exactly once: the in-place navigation + * manager swaps the content area only, so the player and its playback survive every navigation. + * + * This function is invoked automatically when the module loads, so the singleton is already created before any + * other script runs. The instance seam is therefore the way to configure it afterwards: + * window.LuminaAudioPlayer.instance.registerEngine(name, factory).useEngine(name). The optional + * options are honored only when this is the first creation of the player, for a composition that creates the + * player itself, such as a test. + * @param {Object} [options] - The player options, per the {@link LuminaAudioPlayer.AudioPlayer} constructor. Honored only on the first creation. + * @returns {LuminaAudioPlayer.AudioPlayer} The singleton player. + */ + LuminaAudioPlayer.createDefaultPlayer = function (options) { + if (LuminaAudioPlayer.instance) + return LuminaAudioPlayer.instance; + const player = new AudioPlayer(options); + player.initialize(); + LuminaAudioPlayer.instance = player; + return player; + }; + + if (document.readyState === 'loading') + document.addEventListener('DOMContentLoaded', () => LuminaAudioPlayer.createDefaultPlayer()); + else + LuminaAudioPlayer.createDefaultPlayer(); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/site.js b/src/Lumina.Presentation.Web/wwwroot/js/site.js index 27911a61..6b278ab1 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/site.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/site.js @@ -1,4 +1,4 @@ -const scrollbarHeight = getScrollbarHeight(); +const scrollbarHeight = getScrollbarHeight(); const scrollbarWidth = getScrollbarWidth(); const progressIndicator = document.getElementById('progress-indicator'); const progressIndicatorValue = document.getElementById('progress-indicator-value'); @@ -648,23 +648,26 @@ function getElementOffset(id) { } /** - * Toggles the visibility of the audio player. + * Closes the audio player, by routing to the audio player that owns the bar. + * + * The player bar is the single owner of its own classes, its state and its visibility, so this control, and the full + * height control below, only route to it. The two controls exist only when the bar is rendered, which is only for an + * authenticated visitor, for whom the audio player is always created, so there is no separate no-player fallback to + * keep in sync with the player. */ function toggleAudioPlayerVisibility() { - const playerContainer = document.querySelector('.audio-player-container'); - const contentContainer = document.querySelector('main'); - playerContainer.classList.toggle('not-shown'); - contentContainer.classList.toggle('audio-player-not-shown'); + const player = window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance; + if (player && typeof player.stopAsync === 'function') + player.stopAsync(); } /** - * Toggles the display of the audio player as collapsed player, or full height player. + * Expands the audio player into its full height form, or collapses it back, by routing to the audio player that owns the bar. */ function toggleAudioPlayerFullHeight() { - const playerContainer = document.querySelector('.audio-player-container'); - const contentContainer = document.querySelector('main'); - playerContainer.classList.toggle('full-height'); - contentContainer.classList.toggle('audio-player-full-height'); + const player = window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance; + if (player && typeof player.toggleFullHeight === 'function') + player.toggleFullHeight(); } if (audioPlayerFullHeightToggle)