Adds the audio player core module, control API, capability detection and bar.

This commit is contained in:
BinaryAlley committed 2026-10-15 23:13:26 +03:00
1 parent dd76309ded
commit b7ed83c82f
11 files changed
+2225 -23

No files matched your search

+37
View File
@@ -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:
@@ -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");
}
<div class="audio-player-container">
<video controls
preload="auto"
height="50" width="600">
<source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
</video>
<a id="audio-player-full-height-toggle">@localizer["ToggleFullHeight"]</a>
<a id="audio-player-close">@localizer["ToggleVisibility"]</a>
@*
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.
*@
<div class="audio-player-container not-shown" hidden>
<!-- Expanded area: cover art, and the queue when the play context holds more than one track. -->
<div class="audio-player-expanded">
<img class="audio-player-cover-image" data-audio-player-cover-image alt="" />
<ul class="audio-player-queue" data-audio-player-queue></ul>
</div>
<!-- Condensed bar: transport control, progress bar and track name. -->
<div class="audio-player-bar">
<img class="audio-player-cover-thumbnail" data-audio-player-cover-thumbnail alt="" />
<span class="audio-player-track-name" data-audio-player-track-name></span>
<span class="audio-player-time audio-player-current-time" data-audio-player-current-time>0:00</span>
<div class="audio-player-progress" data-audio-player-progress>
<div class="audio-player-progress-downloaded" data-audio-player-progress-downloaded></div>
<div class="audio-player-progress-played" data-audio-player-progress-played></div>
</div>
<span class="audio-player-time audio-player-total-time" data-audio-player-total-time>--:--</span>
<div class="audio-player-transport">
<button type="button" class="audio-player-button audio-player-play-pause" data-audio-player-play-pause>
<span class="audio-player-play-pause-icon"></span>
</button>
</div>
<div class="audio-player-controls">
<a id="audio-player-full-height-toggle">@localizer["ToggleFullHeight"]</a>
<a id="audio-player-close">@localizer["ToggleVisibility"]</a>
</div>
</div>
</div>
@@ -46,12 +46,12 @@ else
<title>@ViewData["Title"] - Lumina</title>
@await Html.PartialAsync("_ThemeLayoutHead")
</head>
<body>
<body class="application-fallback-layout">
<div id="page">
<header>
@await Html.PartialAsync("_NavMenu")
</header>
<main role="main" style="@(User?.Identity?.IsAuthenticated == false ? "bottom: 0px;" : string.Empty)">
<main role="main" class="audio-player-not-shown" style="@(User?.Identity?.IsAuthenticated == false ? "bottom: 0px;" : string.Empty)">
<article class="h-100">
@Html.Raw(bodyHtml)
<div id="modal-background-article"></div>
@@ -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<ServerConfigurationDto> _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)'
};
</script>
<script src="~/libs/microsoft-signalr/signalr.min.js" asp-append-version="true"></script>
<script defer src="~/js/notifications.js" asp-append-version="true"></script>
<script defer src="~/js/dialogs.js" asp-append-version="true"></script>
<script defer src="~/js/image-viewer.js" asp-append-version="true"></script>
<script defer src="~/js/site.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-errors.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-events.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-capabilities.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-engine.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player.js" asp-append-version="true"></script>
@@ -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;
}
@@ -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<Object>|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<boolean>} 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<boolean>} 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:
* <code>{ webCodecs, audioDecoder, audioContext, codecs, missing, supported }</code>, where <code>codecs</code> maps each probed codec name to a boolean, <code>missing</code> lists the
* {@link LuminaAudioPlayer.PlayerCapability} values that are absent, and <code>supported</code> is true only when every required capability is present.
* @returns {Promise<Object>} 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<Object>} 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 || {});
@@ -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<void>} 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<void>} 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<void>} 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<void>} 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<void>} A promise that always resolves.
*/
async setVolumeAsync(volume) {
}
/**
* Releases nothing, because nothing was acquired.
* @returns {Promise<void>} 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<string, Function>} */
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<string>} 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 || {});
@@ -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 || {});
@@ -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<string, Set<Function>>} */
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 || {});
File diff suppressed because it is too large. Load diff
+14 -11
View File
@@ -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)