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

@@ -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