From c05978fac080957d5bd17e954b3cfa0516f59a44 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Fri, 16 Oct 2026 22:10:21 +0300 Subject: [PATCH] Adds the audio player container demuxers. --- .../Views/Shared/_ThemeLayoutScripts.cshtml | 7 + .../audio-player/audio-player-capabilities.js | 87 +- .../js/audio-player/audio-player-decode.js | 49 +- .../audio-player-demux-aac.js | 367 ++++++ .../audio-player-demux-capabilities.js | 363 ++++++ .../audio-player-demux-common.js | 1016 +++++++++++++++ .../audio-player-demux-flac.js | 1064 ++++++++++++++++ .../audio-player-demux-mp3.js | 443 +++++++ .../audio-player-demux-ogg.js | 1113 +++++++++++++++++ .../audio-player-demux-wav.js | 303 +++++ .../js/audio-player/audio-player-download.js | 26 +- .../js/audio-player/audio-player-errors.js | 19 +- .../js/audio-player/audio-player-events.js | 7 + .../js/audio-player/audio-player-utils.js | 53 +- 14 files changed, 4838 insertions(+), 79 deletions(-) create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-aac.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-common.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-flac.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-mp3.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-ogg.js create mode 100644 src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-wav.js diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml index 02b961cb..67256666 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -71,5 +71,12 @@ + + + + + + + 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 index 38e5b477..2614d8fe 100644 --- 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 @@ -22,19 +22,59 @@ }); /** - * 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. + * The representative decoder configuration of every audio codec the player supports, keyed by the canonical codec name + * a demuxer registers itself with. It is the single source of truth for those configurations: the capability report + * below probes them, and each demuxer registers its own descriptor with the entry for its codec, so the report and the + * per demuxer check can never silently disagree. + * @readonly + * @type {Object} + */ + LuminaAudioPlayer.AUDIO_CODEC_PROBES = Object.freeze({ + MP3: Object.freeze({ codec: 'mp3', sampleRate: 44100, numberOfChannels: 2 }), + FLAC: Object.freeze({ codec: 'flac', sampleRate: 44100, numberOfChannels: 2 }), + OPUS: Object.freeze({ codec: 'opus', sampleRate: 48000, numberOfChannels: 2 }), + AAC: Object.freeze({ codec: 'mp4a.40.2', sampleRate: 44100, numberOfChannels: 2 }), + VORBIS: Object.freeze({ codec: 'vorbis', sampleRate: 44100, numberOfChannels: 2 }), + PCM: Object.freeze({ codec: 'pcm-s16', sampleRate: 44100, numberOfChannels: 2 }) + }); + + /** + * The codec configurations probed with AudioDecoder.isConfigSupported, one per audio codec the demuxers of the player + * can recognize. It is derived from {@link LuminaAudioPlayer.AUDIO_CODEC_PROBES}, so the same configuration answers + * both this report and the per demuxer check. * @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 }) }) - ]); + LuminaAudioPlayer.PROBED_AUDIO_CODECS = Object.freeze(Object.keys(LuminaAudioPlayer.AUDIO_CODEC_PROBES) + .map((name) => Object.freeze({ name: name.toLowerCase(), config: LuminaAudioPlayer.AUDIO_CODEC_PROBES[name] }))); + + /** + * Builds a stable fingerprint of the codec private data of a configuration, so that two configurations that differ + * only in their description bytes are never answered from the same cache entry. The decoder can depend on the + * description, because it overrides values of the configuration itself, for example the bit depth a FLAC STREAMINFO + * states or the channel count an OpusHead states, so the bytes matter and not merely whether they are present. + * @param {*} value - The description, as an ArrayBuffer, a view over one, or nothing. + * @returns {string} A fingerprint that combines the length and a 32 bit FNV-1a hash of the bytes. + */ + function fingerprintDescription(value) { + if (value === null || value === undefined) + return 'none'; + let bytes; + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) + bytes = new Uint8Array(value); + else if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value)) + bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + else + return 'unknown'; + let hash = 0x811c9dc5; + for (let index = 0; index < bytes.length; index++) { + hash ^= bytes[index]; + // 0x811c9dc5 is the FNV offset basis and 0x01000193 the FNV prime; the multiply is done modulo 2^32 by the + // unsigned shift, so the hash is a plain 32 bit value whatever the platform's number type. + hash = (hash * 0x01000193) >>> 0; + } + return `${bytes.length}:${hash.toString(16)}`; + } /** * Detects the browser capabilities the audio player relies on, and caches the result. @@ -50,6 +90,14 @@ this.report = null; /** @type {Promise|null} */ this.pendingReport = null; + /** + * The answers the browser already gave for a configuration, keyed by the shape of the configuration. The answer + * cannot change while the page lives, so it is memoized: enumerating many tracks, each with its own exact + * configuration, would otherwise be one browser round trip per track. The pending promise is cached rather than + * the settled value, so concurrent probes of the same configuration share one round trip. + * @type {Map>} + */ + this.configSupportCache = new Map(); } /** @@ -86,6 +134,25 @@ async supportsAudioConfigAsync(config) { if (!this.hasAudioDecoder()) return false; + // The key covers the whole configuration, including a fingerprint of the description bytes: the decoder can + // depend on them, so two configurations that differ only in their codec private data must not share an answer. + const key = config + ? `${config.codec}|${config.sampleRate}|${config.numberOfChannels}|${fingerprintDescription(config.description)}` + : String(config); + const cached = this.configSupportCache.get(key); + if (cached) + return await cached; + const probe = this.runAudioConfigProbeAsync(config); + this.configSupportCache.set(key, probe); + return await probe; + } + + /** + * Performs one configuration probe against the browser, without consulting the cache. + * @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 runAudioConfigProbeAsync(config) { 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 diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js index 25f37265..cd6b41ff 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-decode.js @@ -216,16 +216,6 @@ return null; } - /** - * Checks whether a value is the AbortError a reset or a close rejects a pending flush with. An AbortError is tested - * by name rather than by type, because in a browser it is a DOMException, which is not an Error. - * @param {*} error - The value to check. - * @returns {boolean} True when the value is an AbortError. - */ - function isAbortError(error) { - return !!error && error.name === 'AbortError'; - } - /** * Checks whether a scheduler refused a frame because its own scheduled ahead ceiling is tighter than the decoder's. * That is backpressure, not corruption: the scheduler refused the frame before scheduling it, so the pipeline can keep @@ -255,41 +245,6 @@ return duration === null ? 0 : Math.max(0, duration) / 1000000; } - /** - * Merges two error detail objects into a new one, so that a details object a component owns is never mutated in place. - * @param {Object|null} base - The existing details. - * @param {Object|null} extra - The details to add. - * @returns {Object|null} The merged details, or null when both are absent. - */ - function mergeErrorDetails(base, extra) { - const hasBase = base !== null && base !== undefined; - const hasExtra = extra !== null && extra !== undefined; - if (!hasBase && !hasExtra) - return null; - if (!hasExtra) - return Object.assign({}, base); - if (!hasBase) - return Object.assign({}, extra); - return Object.assign({}, base, extra); - } - - /** - * Builds an error this decoder owns. A PlayerError raised by another component is copied rather than adopted, so its - * details are never mutated and the decoder failure never aliases the error the raising component keeps for itself. - * @param {*} error - The failure to own. - * @param {string} fallbackCode - The code to use when the failure is not already a player error. - * @param {Object|null} details - Optional details to merge in. - * @returns {LuminaAudioPlayer.PlayerError} The owned typed error. - */ - function toOwnedError(error, fallbackCode, details) { - if (error instanceof LuminaAudioPlayer.PlayerError) - return new LuminaAudioPlayer.PlayerError(error.code, error.message, mergeErrorDetails(error.details, details)); - const typed = LuminaAudioPlayer.PlayerError.from(error, fallbackCode); - if (!details) - return typed; - return new LuminaAudioPlayer.PlayerError(typed.code, typed.message, mergeErrorDetails(typed.details, details)); - } - /** * Creates the WebCodecs audio decoder of the player through the browser constructor. * @param {{ output: Function, error: Function }} handlers - The output and error callbacks the decoder is created with. @@ -608,7 +563,7 @@ } catch (error) { // A reset or a close interrupts a pending flush; that is a teardown of the decode pipeline, not a failure // of the track, so it is observed as a clean stop. - if (this.destroyed || this.error || isAbortError(error)) + if (this.destroyed || this.error || LuminaAudioPlayer.isAbortError(error)) return; throw this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DECODE_FAILED, { reason: 'flush-failed' }); } @@ -1063,7 +1018,7 @@ return this.error; // The error is owned by this decoder: a PlayerError raised elsewhere is copied rather than adopted, so its // details are never mutated and getError never returns an object the raising component still holds. - const typed = toOwnedError(error, code, details); + const typed = LuminaAudioPlayer.toOwnedPlayerError(error, code, details); this.error = typed; this.clearCapacityTimer(); this.closeDecoder(); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-aac.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-aac.js new file mode 100644 index 00000000..e7828002 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-aac.js @@ -0,0 +1,367 @@ +/** + * AAC (ADTS) demuxer of the audio player. + * + * A raw AAC file is a stream of ADTS frames, each one a short header followed by one or more raw AAC data blocks. Unlike + * an MP3 frame the header does not state the bitrate: it states the length of the whole ADTS frame in bytes, which is + * what makes the frame directly addressable, together with the Audio Object Type, the sample rate index, the channel + * configuration and the number of raw data blocks the frame carries. This demuxer walks those frames and hands each one + * to the decoder as an encoded packet. + * + * Framing and the codec private data + * ---------------------------------- + * The WebCodecs AAC registration accepts either an ADTS streamed form, where each EncodedAudioChunk is a whole ADTS frame + * and no description is given, or a raw form, where each chunk is a raw AAC frame and the description is the + * AudioSpecificConfig. This demuxer uses the first, because the ADTS header is already the per frame configuration and + * carrying it in each frame means a frame can be decoded even after a seek that lands in the middle of the stream without + * re-deriving the AudioSpecificConfig. The configuration therefore carries the codec string, the sample rate and the + * channel count, and no description. + * + * Duration + * -------- + * An AAC frame decodes to 1024 samples per raw data block, and the number of raw data blocks is stated by the two bit + * field of the header, so the duration of a packet is 1024 times that count, divided by the sample rate. The total + * duration of the stream is not stated anywhere in an ADTS header, so it is estimated from the average byte rate of the + * frames read so far once the stream is past its beginning, and only once the end is reached is it exact. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The number of bytes of an ADTS header without the optional CRC. + * @readonly + * @type {number} + */ + const ADTS_HEADER_BYTES = 7; + + /** + * The number of bytes of an ADTS header with the optional CRC. + * @readonly + * @type {number} + */ + const ADTS_HEADER_CRC_BYTES = 9; + + /** + * The sample rates, in Hz, indexed by the four bit sample rate index of an AAC header. + * @readonly + * @type {Array} + */ + const SAMPLE_RATES = Object.freeze([96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]); + + /** + * The number of samples one raw AAC data block decodes to. + * @readonly + * @type {number} + */ + const SAMPLES_PER_BLOCK = 1024; + + /** + * The twelve bit ADTS frame sync, as the two byte prefix a scan matches on. The mask covers the top nibble of the + * second byte, so a scan rejects a byte pattern that is not a sync by a comparison instead of by an awaited header + * parse. + * @readonly + * @type {Array} + */ + const ADTS_SYNC_PREFIX = Object.freeze([0xFF, 0xF0]); + + /** + * The byte mask of {@link ADTS_SYNC_PREFIX}, matching the twelve bit sync exactly. + * @readonly + * @type {Array} + */ + const ADTS_SYNC_MASK = Object.freeze([0xFF, 0xF0]); + + /** + * The number of channels each channel configuration of an ADTS header names, indexed by its three bit value. Index 0 + * means the channels are described by a program configuration element, which this demuxer refuses, and index 7 is eight + * channels (7.1), not seven, so the raw value cannot be used as a channel count. + * @readonly + * @type {Array} + */ + const CHANNEL_CONFIGURATIONS = Object.freeze([0, 1, 2, 3, 4, 5, 6, 8]); + + /** + * Parses the header of an ADTS frame. + * @param {Uint8Array} bytes - The bytes to read the header from. + * @param {number} offset - The offset of the first header byte. + * @returns {Object|null} The parsed header, or null when the bytes are not a valid ADTS header. + */ + function parseAdtsHeader(bytes, offset) { + if (!bytes || offset < 0 || offset + ADTS_HEADER_BYTES > bytes.length) + return null; + // An ADTS header is a bit packed big endian structure. The fields this demuxer reads are laid out as: + // bytes 0-1: the twelve bit sync, then the MPEG version, two layer bits that are always zero, and the + // protection-absent flag that says whether a two byte CRC follows the header + // byte 2: the two bit Audio Object Type, the four bit sample rate index, and the top bit of the channel + // configuration + // byte 3: the low two bits of the channel configuration, then the top two bits of the frame length + // byte 4: the middle eight bits of the frame length + // byte 5: the low three bits of the frame length, then the buffer fullness + // byte 6: the two bit count of raw data blocks + // Every field below is extracted from that layout, which is why the shifts and masks cross byte boundaries. + if (bytes[offset] !== 0xFF || (bytes[offset + 1] & 0xF0) !== 0xF0) + return null; + // The layer field of an ADTS header is always zero; a non zero layer is a false sync. + if (((bytes[offset + 1] >> 1) & 0x03) !== 0) + return null; + const protectionAbsent = (bytes[offset + 1] & 0x01) === 1; + // The Audio Object Type is one more than the two bit field, and the raw data block count is one more than its + // two bit field, because both are stored biased by one. + const objectType = ((bytes[offset + 2] >> 6) & 0x03) + 1; + const sampleRateIndex = (bytes[offset + 2] >> 2) & 0x0F; + if (sampleRateIndex >= SAMPLE_RATES.length) + return null; + const channelConfiguration = ((bytes[offset + 2] & 0x01) << 2) | ((bytes[offset + 3] >> 6) & 0x03); + const frameLength = ((bytes[offset + 3] & 0x03) * 2048) + + (bytes[offset + 4] * 8) + + ((bytes[offset + 5] >> 5) & 0x07); + const headerBytes = protectionAbsent ? ADTS_HEADER_BYTES : ADTS_HEADER_CRC_BYTES; + if (frameLength < headerBytes) + return null; + const rawDataBlocks = (bytes[offset + 6] & 0x03) + 1; + return Object.freeze({ + objectType, + sampleRate: SAMPLE_RATES[sampleRateIndex], + sampleRateIndex, + channelConfiguration, + frameLength, + headerBytes, + rawDataBlocks + }); + } + + /** + * Demuxes an AAC stream that is framed as ADTS. + */ + class AacDemuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of AacDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.offset = 0; + this.dataStart = 0; + this.timelineMicros = 0; + /** @type {Object|null} */ + this.header = null; + this.durationSeconds = null; + this.reachedEnd = false; + // The first audio frame, the anchor the average byte rate is estimated from while the end of the stream is unknown. + this.firstFrameOffset = 0; + } + + //+======================================================================================+ + //| Initialization | + //+======================================================================================+ + + /** + * Skips an ID3v2 tag if the file carries one and positions the read cursor on the first ADTS frame. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not an ADTS stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + const dataStart = await this.skipId3v2Async(0); + const end = this.reader.getLength(); + const firstFrame = await LuminaAudioPlayer.scanForFrameAsync(this.reader, dataStart, end, ADTS_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: ADTS_SYNC_MASK }); + if (firstFrame < 0) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The bytes do not contain an ADTS frame.', { reason: 'no-adts-frame' }); + const header = await this.parseHeaderAtAsync(firstFrame); + if (!header) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The ADTS frame header could not be parsed.', { reason: 'no-adts-frame' }); + if (header.channelConfiguration === 0) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The AAC stream describes its channels in a program configuration this demuxer does not read.', { reason: 'unsupported-channel-config' }); + this.dataStart = firstFrame; + this.firstFrameOffset = firstFrame; + this.offset = firstFrame; + this.header = header; + this.durationSeconds = null; + this.timelineMicros = 0; + this.reachedEnd = false; + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.header) + return null; + return { + codec: `mp4a.40.${this.header.objectType}`, + sampleRate: this.header.sampleRate, + numberOfChannels: CHANNEL_CONFIGURATIONS[this.header.channelConfiguration] + }; + } + + /** + * Gets the best known duration of the stream, which is exact only once the last frame was read. + * @returns {number|null} The duration in seconds, or null when it is not known yet. + */ + getDuration() { + return this.durationSeconds; + } + + //+======================================================================================+ + //| Reading | + //+======================================================================================+ + + /** + * Reads the next ADTS frame as an encoded packet. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + if (this.reachedEnd) + return null; + try { + const header = await this.parseHeaderAtAsync(this.offset); + if (!header) + return await this.resyncAsync(); + const data = await this.reader.readAsync(this.offset, header.frameLength); + if (data.length < header.frameLength) { + this.reachedEnd = true; + this.updateEstimatedDuration(); + return null; + } + // The duration is kept unrounded while the timeline accumulates it, so that rounding it per packet does not + // make the timeline drift; only the packet the decoder receives carries a whole number of microseconds. + const duration = ((SAMPLES_PER_BLOCK * header.rawDataBlocks) / header.sampleRate) * 1000000; + const packet = LuminaAudioPlayer.createDemuxerPacket(data.slice(), this.timelineMicros, duration); + this.timelineMicros += duration; + this.offset += header.frameLength; + this.updateEstimatedDuration(); + return packet; + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Rescans for the next ADTS frame after a byte that is not the start of one. + * @returns {Promise} The next packet, or null when no further frame is found. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async resyncAsync() { + const end = this.reader.getLength(); + const next = await LuminaAudioPlayer.scanForFrameAsync(this.reader, this.offset + 1, end, ADTS_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: ADTS_SYNC_MASK }); + if (next < 0) { + this.reachedEnd = true; + this.updateEstimatedDuration(); + return null; + } + this.offset = next; + return await this.readPacketAsync(); + } + + /** + * Repositions the read cursor to the ADTS frame that covers a time. An ADTS stream has no seek table, so the + * byte position is estimated from the average byte rate of the frames read so far, and then scanned forward to + * the next real frame. A seek to the start is answered exactly even on a fresh demuxer, whose frames have not been + * walked yet, because the first frame is already known from initialization. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a frame gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const end = this.reader.getLength(); + if (end === null || !Number.isFinite(seconds) || seconds < 0) + return null; + if (seconds <= 0) { + this.offset = this.firstFrameOffset; + this.reachedEnd = false; + this.timelineMicros = 0; + return this.firstFrameOffset; + } + const elapsedBytes = this.offset - this.firstFrameOffset; + const elapsedMicros = this.timelineMicros; + if (elapsedBytes <= 0 || elapsedMicros <= 0) + return null; + const bytesPerSecond = elapsedBytes / (elapsedMicros / 1000000); + const estimate = this.firstFrameOffset + Math.floor(seconds * bytesPerSecond); + const start = Math.max(this.firstFrameOffset, Math.min(end - 1, estimate)); + const frame = await LuminaAudioPlayer.scanForFrameAsync(this.reader, start, end, ADTS_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: ADTS_SYNC_MASK }); + if (frame < 0) + return null; + this.offset = frame; + this.reachedEnd = false; + // The exact sample position of the frame is not known without walking the stream from its start, so the + // timeline is set to the requested time, which the seek stage uses as the target to trim the first packet to. + this.timelineMicros = Math.max(0, seconds) * 1000000; + return frame; + } + + //+======================================================================================+ + //| Internal helpers | + //+======================================================================================+ + + /** + * Reads the header of an ADTS frame at an offset. + * @param {number} offset - The offset of the frame. + * @returns {Promise} The parsed header, or null when the bytes are not a valid ADTS header. + */ + async parseHeaderAtAsync(offset) { + const bytes = await this.reader.readAsync(offset, ADTS_HEADER_BYTES); + if (bytes.length < ADTS_HEADER_BYTES) + return null; + return parseAdtsHeader(bytes, 0); + } + + /** + * Checks whether a candidate offset is the start of a real ADTS frame, by parsing its header and, when the next + * frame fits in the stream, by requiring it to parse with the same sample rate and channel configuration too. + * @param {number} offset - The candidate offset. + * @returns {Promise} True when the offset is the start of a real frame. + */ + async isValidFrameAtAsync(offset) { + const header = await this.parseHeaderAtAsync(offset); + if (!header) + return false; + const end = this.reader.getLength(); + const next = offset + header.frameLength; + if (end !== null && next + ADTS_HEADER_BYTES > end) + return true; + const nextHeader = await this.parseHeaderAtAsync(next); + if (!nextHeader) + return false; + return nextHeader.sampleRate === header.sampleRate + && nextHeader.channelConfiguration === header.channelConfiguration; + } + + /** + * Refreshes the estimated duration from the average byte rate of the frames read so far. It is exact only once + * the last frame was read, because an ADTS stream states no duration. + */ + updateEstimatedDuration() { + const bytes = this.offset - this.firstFrameOffset; + const micros = this.timelineMicros; + if (bytes <= 0 || micros <= 0) + return; + const end = this.reader.getLength(); + if (end === null) + return; + const remaining = end - this.firstFrameOffset; + const totalMicros = (remaining / bytes) * micros; + this.durationSeconds = totalMicros / 1000000; + } + } + + LuminaAudioPlayer.AacDemuxer = AacDemuxer; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.AAC, + codec: LuminaAudioPlayer.DemuxerCodec.AAC, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.AAC, + create: (options) => new AacDemuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js new file mode 100644 index 00000000..9b8f3321 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js @@ -0,0 +1,363 @@ +/** + * Demux capability module of the audio player. + * + * The server decides, before any audio is fetched, whether a track is a direct play or has to be normalized (remuxed or + * transcoded), from the container and the codec the player advertises. This module produces that advertisement from the + * demuxers that loaded and the codecs the browser can decode, and it resolves the two halves of the client side of the + * same decision: which demuxer handles the container and codec of a track, and whether the browser can decode the codec + * it produces. + * + * Matching a manifest to a demuxer + * -------------------------------- + * The manifest carries the container and the codec of the stored audio as free form descriptions taken from the probe + * result, so they are canonicalized here exactly as the server canonicalizes them, and matched against the demuxer + * registry. A pair no registered demuxer handles is a track the bundled player cannot play directly. + * + * Verifying with the browser + * -------------------------- + * A demuxer existing for a format is not proof that the browser can decode it: the codec may be missing from this + * browser, or the codec might be refused for the sample rate or channel count of the track. Two checks are therefore + * offered, in increasing cost and precision: + * - a cheap check against a representative configuration of the codec, which answers whether the browser can decode + * that codec at all, using the same probes the capability detector already runs; + * - a full check against the real configuration the demuxer extracted from the file, which is exact but requires the + * header of the track to have been read already. + * The convenience factories below use the full check when they initialize the demuxer, and fall back to a clear + * 'needs normalization' event whenever a demuxer is missing, the bytes cannot be parsed, or the browser refuses the + * configuration, so a consumer can ask the server to normalize the track instead of failing. + * + * Advertising capabilities + * ------------------------ + * The 'capabilities' query parameter of the manifest request is documented as the container and codec pairs the player can + * demux and decode, so the advertisement is filtered by the cheap browser check, and a codec this browser cannot decode is + * never advertised. Advertising it would make the server mark such a track a direct play, and the client would discover + * the gap only after fetching the manifest and would have to normalize in a second round trip. The unfiltered, demux only + * set is available for a caller with no detector, and it is what the server already assumes when it applies its default. + * + * The needs normalization event + * ----------------------------- + * It is published on the player event bus as {@link LuminaAudioPlayer.PlayerEvent.NEEDS_NORMALIZATION}, with the payload + * { container, codec, reason }, plus directPlay when the caller supplied it, where the reason is one of the + * {@link LuminaAudioPlayer.PlayerErrorReason} values NO_DEMUXER, CODEC_UNSUPPORTED or DEMUXER_FAILED. A consumer that + * asked for a normalized delivery uses it to request one. A normalized manifest, whose directPlay flag is false, is + * refused by {@link LuminaAudioPlayer.createDemuxerForManifest} without an event, because the server already normalized + * such a track on purpose and its stream is not in the stored container. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * Resolves the demuxer descriptors, the browser capabilities and the event bus a capability module works with. Only + * the registry has a process wide default, because it is the one collaborator whose contents are the registry itself; + * the capability detector and the event bus are injected by the caller, like every other collaborator of the player, + * so that this module never reaches into a running player whose instance comes and goes. + * @param {Object} [options] - The options to resolve from. + * @returns {Object} The resolved registry, capabilities and events. + */ + function resolveDependencies(options = {}) { + const settings = options || {}; + return { + registry: settings.registry || LuminaAudioPlayer.demuxerRegistry, + capabilities: settings.capabilities || null, + events: settings.events || null + }; + } + + /** + * Requires an injected collaborator, failing loudly rather than silently degrading when it is missing. + * @param {*} value - The collaborator to check. + * @param {string} name - The name of the collaborator, for the message. + * @returns {*} The collaborator. + * @throws {TypeError} When the collaborator was not injected. + */ + function requireInjected(value, name) { + if (!value) + throw new TypeError(`The demux capability resolver requires an injected ${name}.`); + return value; + } + + /** + * Publishes the need for a normalized delivery on the event bus. + * @param {Object} events - The event bus. + * @param {string} container - The canonical container of the track. + * @param {string} codec - The canonical codec of the track. + * @param {string} reason - One of the {@link LuminaAudioPlayer.PlayerErrorReason} values. + * @param {boolean} [directPlay] - The direct play flag of the manifest, when the caller has one. + */ + function publishNeedsNormalization(events, container, codec, reason, directPlay) { + if (!events || !LuminaAudioPlayer.PlayerEvent || typeof events.emit !== 'function') + return; + const payload = { + container: LuminaAudioPlayer.canonicalizeDemuxerContainer(container), + codec: LuminaAudioPlayer.canonicalizeDemuxerCodec(codec), + reason + }; + // The direct play flag is carried only when the caller supplied it: an omitted flag means the caller does not + // know, which is not the same as a false flag, the documented signal that the server already normalized the + // track. Coercing an omitted flag to false would make every caller that has no manifest look like one whose + // track the server chose to normalize. + if (directPlay !== undefined) + payload.directPlay = directPlay === true; + events.emit(LuminaAudioPlayer.PlayerEvent.NEEDS_NORMALIZATION, Object.freeze(payload)); + } + + /** + * Detects the demuxers the bundled player loaded and the browser configurations it can decode, and answers whether a track can be played directly. + */ + class DemuxerCapabilities { + /** + * Creates an instance of DemuxerCapabilities. + * @param {Object} [options] - The options. + * @param {LuminaAudioPlayer.DemuxerRegistry} [options.registry] - The demuxer registry. Defaults to the process wide registry, the one collaborator that is not injected. + * @param {LuminaAudioPlayer.PlayerCapabilities} [options.capabilities] - The browser capability detector, injected by the caller. A method that probes without it fails loudly. + * @param {Object} [options.events] - The player event bus, injected by the caller. + */ + constructor(options = {}) { + const resolved = resolveDependencies(options); + this.registry = resolved.registry; + this.capabilities = resolved.capabilities; + this.events = resolved.events; + } + + /** + * Finds the demuxer descriptor of a container and codec pair. + * @param {string} container - The container of the track, in any casing or as a free form description. + * @param {string} codec - The codec of the track, in any casing or as a free form description. + * @returns {Object|null} The descriptor, or null when no demuxer handles the pair. + */ + match(container, codec) { + return this.registry ? this.registry.find(container, codec) : null; + } + + /** + * Finds the demuxer descriptor of the stored format of a playback manifest. + * @param {Object} manifest - The playback manifest. + * @returns {Object|null} The descriptor, or null when no demuxer handles the stored format. + */ + matchManifest(manifest) { + if (!manifest) + return null; + return this.match(manifest.sourceContainer, manifest.sourceCodec); + } + + /** + * Asks the browser whether it can decode a codec at all, through the representative probe the descriptor carries. + * It is the cheap check, usable before any byte of the track is read. The probe is read from the descriptor rather + * than looked up by name, so the check never depends on a demuxer being named in the registry. + * @param {Object} descriptor - A demuxer descriptor. + * @returns {Promise} True when the browser can decode the codec. + * @throws {TypeError} When no capability detector was injected. + */ + async isCodecSupportedAsync(descriptor) { + if (!descriptor) + return false; + const capabilities = requireInjected(this.capabilities, 'capability detector'); + return await capabilities.supportsAudioConfigAsync(descriptor.probe); + } + + /** + * Asks the browser whether it can decode the exact configuration a demuxer extracted from a track. It is the + * exact check, usable once the demuxer was initialized. + * @param {Object} configuration - A configuration, per {@link LuminaAudioPlayer.Demuxer#getConfiguration}. + * @returns {Promise} True when the browser can decode the configuration. + * @throws {TypeError} When no capability detector was injected. + */ + async isConfigurationSupportedAsync(configuration) { + if (!configuration) + return false; + const capabilities = requireInjected(this.capabilities, 'capability detector'); + return await capabilities.supportsAudioConfigAsync(configuration); + } + + /** + * Resolves whether a track can be played directly, using the cheap representative check. It publishes the needs + * normalization event and resolves false when no demuxer handles the format or the browser cannot decode it. The + * event carries the reason the caller acts on, so the event bus is required rather than optional: a missing bus + * would silently drop the only signal that says which delivery to request. + * @param {string} container - The container of the track. + * @param {string} codec - The codec of the track. + * @param {boolean} [directPlay] - The direct play flag of the manifest, carried into the event. + * @returns {Promise} True when a demuxer exists and the browser can decode the codec. + * @throws {TypeError} When no capability detector or no event bus was injected. It is a composition error, not a + * property of the track, so it rejects rather than classifying the track. + */ + async canPlayDirectlyAsync(container, codec, directPlay) { + const events = requireInjected(this.events, 'event bus'); + const descriptor = this.match(container, codec); + if (!descriptor) { + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, directPlay); + return false; + } + if (!await this.isCodecSupportedAsync(descriptor)) { + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, directPlay); + return false; + } + return true; + } + + /** + * Resolves whether the stored format of a manifest can be played directly. + * @param {Object} manifest - The playback manifest. + * @returns {Promise} True when a demuxer exists and the browser can decode the codec. + * @throws {TypeError} When no capability detector or no event bus was injected. + */ + async canPlayManifestDirectlyAsync(manifest) { + if (!manifest) + return false; + return await this.canPlayDirectlyAsync(manifest.sourceContainer, manifest.sourceCodec, manifest.directPlay); + } + + /** + * Builds the value of the 'capabilities' query parameter of the manifest request from the demuxers that loaded, + * without consulting the browser. It is the set the player can demux, which is what the server already assumes + * when it applies its own default; a caller that needs the set the player can also decode uses + * {@link LuminaAudioPlayer.DemuxerCapabilities#describeFormatsAsync}. + * @returns {string} A comma separated list of container/codec pairs. + */ + describeFormats() { + if (!this.registry) + return ''; + return this.registry.getDescriptors() + .map((descriptor) => `${descriptor.container.toLowerCase()}/${descriptor.codec.toLowerCase()}`) + .join(','); + } + + /** + * Builds the value of the 'capabilities' query parameter of the manifest request from the demuxers whose codec the + * browser can actually decode. The parameter is documented as the pairs the player can demux and decode, so a + * codec the browser cannot decode must not be promised to the server: otherwise the server marks such a track a + * direct play, and the client only discovers the gap after fetching the manifest and has to normalize in a second + * round trip. With the memoizing capability detector, this is one probe per codec, once. + * @returns {Promise} A promise resolving to a comma separated list of container/codec pairs. + * @throws {TypeError} When no capability detector was injected. + */ + async describeFormatsAsync() { + const capabilities = requireInjected(this.capabilities, 'capability detector'); + if (!this.registry) + return ''; + const pairs = []; + for (const descriptor of this.registry.getDescriptors()) { + if (await capabilities.supportsAudioConfigAsync(descriptor.probe)) + pairs.push(`${descriptor.container.toLowerCase()}/${descriptor.codec.toLowerCase()}`); + } + return pairs.join(','); + } + } + + LuminaAudioPlayer.DemuxerCapabilities = DemuxerCapabilities; + + /** + * Creates a demux capability resolver. See {@link LuminaAudioPlayer.DemuxerCapabilities} for the options. + * @param {Object} [options] - The options. + * @returns {LuminaAudioPlayer.DemuxerCapabilities} The resolver. + */ + LuminaAudioPlayer.createDemuxerCapabilities = function (options) { + return new DemuxerCapabilities(options); + }; + + /** + * Creates and verifies the demuxer of a container and codec pair. + * + * It resolves the demuxer, initializes it, and asks the browser whether it can decode the exact configuration the + * demuxer extracted. A failure to parse the bytes or to decode the codec is an expected negotiation outcome, not a + * playback failure, so the demuxer is created as a probe with the caller's error callback detached and that callback + * is attached only once the demuxer proved usable. Anything that makes the pair unplayable (no demuxer, unparseable + * bytes, or a codec the browser refuses) resolves to null and publishes a needs normalization event, so a caller can + * request a normalized delivery instead of failing, and never receives both a player failure and a normalization + * request for the same unplayable file. + * + * The one failure that resolves to null without publishing is an intentional download stop: a teardown that crossed + * the header probe is not a track the server has to normalize. A caller that must tell the two nulls apart therefore + * checks whether it received a needs normalization event, or its own teardown state, rather than the null itself. + * @param {string} container - The container of the track. + * @param {string} codec - The codec of the track. + * @param {Object} [options] - The demuxer options, plus the injected capabilities and events, per {@link LuminaAudioPlayer.DemuxerCapabilities}. + * @returns {Promise} The ready demuxer, or null when the pair must be normalized. + * @throws {TypeError} When no event bus was injected. It is a composition error, not a property of the track, so it + * rejects rather than resolving to a null the caller would have to classify without an event to classify it by. + */ + LuminaAudioPlayer.createDemuxerFor = async function (container, codec, options) { + const settings = options || {}; + const dependencies = resolveDependencies(settings); + // The event bus is required rather than optional, because a caller tells a track that must be normalized from an + // intentional teardown by whether a needs normalization event arrived, and a missing bus would silently drop that + // only signal and make the two nulls indistinguishable. + const events = requireInjected(dependencies.events, 'event bus'); + const descriptor = dependencies.registry ? dependencies.registry.find(container, codec) : null; + if (!descriptor) { + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.NO_DEMUXER, settings.directPlay); + return null; + } + let demuxer = null; + try { + demuxer = descriptor.create(Object.assign({}, settings, { onError: null })); + await demuxer.initializeAsync(); + } catch (error) { + console.debug('Audio player: the demuxer of the track failed to initialize.', error); + if (demuxer && typeof demuxer.destroyAsync === 'function') + await demuxer.destroyAsync(); + // An intentional download stop, a teardown that crossed the header probe, is not a track the server has to + // normalize, so it is not published as one; the demuxer already reports it as a normal stop everywhere else. + if (!LuminaAudioPlayer.isDownloadAbort(error)) + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.DEMUXER_FAILED, settings.directPlay); + return null; + } + const configuration = demuxer.getConfiguration(); + let isConfigurationSupported = false; + try { + const resolver = new DemuxerCapabilities(dependencies); + isConfigurationSupported = await resolver.isConfigurationSupportedAsync(configuration); + } catch (error) { + // A wiring failure (a missing injected capability detector) is not a property of the track, so the just built + // demuxer is released and the failure is propagated, never swallowed as a normalization request. + await demuxer.destroyAsync(); + throw error; + } + if (!isConfigurationSupported) { + await demuxer.destroyAsync(); + publishNeedsNormalization(events, container, codec, LuminaAudioPlayer.PlayerErrorReason.CODEC_UNSUPPORTED, settings.directPlay); + return null; + } + // The demuxer is usable, so the caller's error callback is attached from here on: a failure while reading is a + // playback failure and reaches it, while a failure during the probe above never did. + demuxer.onError = typeof settings.onError === 'function' ? settings.onError : null; + return demuxer; + }; + + /** + * Creates and verifies the demuxer of the stored format of a direct play manifest. It uses the source container and + * codec, because that is the format the capability negotiation is about. Only a direct play manifest has its stored + * format as its stream: a manifest whose direct play flag is false describes a delivery in a different container, so + * resolving its stored format would build a demuxer for the wrong bytes, and the failure to initialize it would + * publish a normalization request for a track the server already normalized, a normalization loop. Such a manifest + * therefore resolves to null here, silently, and a caller that has one runs the normalized pipeline instead. + * @param {Object} manifest - The playback manifest. + * @param {Object} [options] - The demuxer options, per {@link LuminaAudioPlayer.createDemuxerFor}. + * @returns {Promise} The ready demuxer, or null for a manifest that is not a direct play, or one that must be normalized. + */ + LuminaAudioPlayer.createDemuxerForManifest = function (manifest, options) { + if (!manifest || manifest.directPlay !== true) + return Promise.resolve(null); + return LuminaAudioPlayer.createDemuxerFor(manifest.sourceContainer, manifest.sourceCodec, Object.assign({}, options, { directPlay: true })); + }; + + /** + * Builds the value of the 'capabilities' query parameter of the manifest request from the process wide registry, + * without consulting the browser. See {@link LuminaAudioPlayer.describeDemuxerFormatsAsync} for the decode aware set. + * @returns {string} A comma separated list of container/codec pairs. + */ + LuminaAudioPlayer.describeDemuxerFormats = function () { + return new DemuxerCapabilities().describeFormats(); + }; + + /** + * Builds the value of the 'capabilities' query parameter of the manifest request from the process wide registry, + * keeping only the pairs whose codec the browser can decode, which is the set the parameter is documented to carry. + * @param {Object} [options] - The options, with the injected capability detector and event bus, per {@link LuminaAudioPlayer.DemuxerCapabilities}. + * @returns {Promise} A promise resolving to a comma separated list of container/codec pairs. + * @throws {TypeError} When no capability detector was injected. + */ + LuminaAudioPlayer.describeDemuxerFormatsAsync = function (options) { + return new DemuxerCapabilities(options).describeFormatsAsync(); + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-common.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-common.js new file mode 100644 index 00000000..abac5067 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-common.js @@ -0,0 +1,1016 @@ +/** + * Common foundation of the audio player demuxers. + * + * WebCodecs cannot decode a file: an AudioDecoder consumes a configuration (a codec, a sample rate, a channel count and + * the codec private data the container carries) and a stream of EncodedAudioChunk objects. Something must therefore parse + * the bytes the download engine brings in, recognize the container, extract that configuration and split the audio into + * packets, each with a presentation timestamp and a duration in microseconds. That is what a demuxer does, and this + * module holds everything the per format demuxers (MP3, AAC/ADTS, FLAC, OGG and WAV) share, so that each one only + * implements its own container grammar. + * + * What lives here + * --------------- + * - The canonical names of the containers and codecs the bundled player supports, and the canonicalizers that map the + * free form descriptions the probe stores to those names. Both canonicalizers mirror the server on the same values + * (containers by trimming and upper casing, as PlaybackFormatService.CanonicalizeContainer does; codecs by the + * distinctive token of the description, as CanonicalizeCodec does), so the two sides agree on what a track holds and + * on which tracks are a direct play. Neither adds an alias the server does not, because a container the server's + * direct-play gate would reject must not resolve a demuxer here. + * - A byte source adapter that turns the range downloading TrackDownloader of the download engine into a flat, + * random access byte source that answers a read at an absolute offset and reports end of file instead of rejecting. + * - A windowing reader over that source, which keeps one read ahead window so that a parser that walks byte by byte + * does not issue one request per byte. + * - A bit reader for the big endian bitstream headers of MPEG, FLAC and OGG. + * - The packet factory, so every demuxer emits the same frozen packet shape the decode pipeline consumes. + * - The base class of a demuxer, which owns the reader, the recorded failure and the error callback, and the demuxer + * registry the format modules register themselves into. + * + * The demuxer contract + * -------------------- + * Every demuxer (audio-player-demux-mp3.js and its siblings) exposes: + * - initializeAsync(): reads the header(s) of the stream and prepares getConfiguration(); resolves when the stream is + * ready to be read, and rejects with a typed error when the bytes are not a stream of this format. + * - getConfiguration(): the AudioDecoderConfig like value { codec, sampleRate, numberOfChannels, description? } after + * initializeAsync resolved, and null before that. + * - readPacketAsync(): the next encoded packet as { data, timestamp, duration, type }, where the timestamp and the + * duration are in microseconds, or null once the stream ended. It is incremental: it reads only the bytes of the + * packet it returns, never the whole file. + * - getDuration(): the duration of the whole stream in seconds, and null when no demuxer of the format can state one. A + * format whose duration only becomes exact once the whole stream is read (AAC, OGG) returns a progressive estimate in + * the meantime, so a caller must treat a non null value as an estimate that may still be refined, not as a final one. + * - seekToTimeAsync(seconds): repositions the read cursor to a packet boundary at or before the given time, so that the + * next readPacketAsync returns the packet that covers it. It returns the byte offset it repositioned to, or null when + * the format cannot be repositioned by time. How the first packet after a seek is trimmed to the exact target is the + * concern of the seek stage, not of the demuxer. + * - destroyAsync(): releases every resource, including the reader. + * + * A demuxer is a sub component, like the download engine and the decoder: it never moves the player state machine and + * never emits on the event bus itself. A failure it cannot recover from is recorded on the instance for polling through + * getError, is reported to the onError callback as a {@link LuminaAudioPlayer.PlayerError} with the DEMUX_FAILED code, and + * makes the awaited calls (initializeAsync, readPacketAsync, seekToTimeAsync) reject with that same error. An engine must + * forward onError to host.reportError, exactly as it forwards the download engine's and the decoder's, so the failure + * reaches the player. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The size, in bytes, of the read ahead window the reader keeps. It is large enough that a parser walking a frame + * header byte by byte issues one read per window rather than one per byte, and small enough to stay cheap to hold. + * @readonly + * @type {number} + */ + const WINDOW_SIZE_BYTES = 65536; + + /** + * The largest number of bytes a single read may ask for. It bounds the window a malformed stream can make the reader + * allocate, so a corrupt length field can never turn a read into an unbounded allocation. + * @readonly + * @type {number} + */ + const MAX_READ_BYTES = 16 * 1024 * 1024; + + /** + * The size, in bytes, of a scan chunk. A scan for the next frame of a format reads at most this many bytes at a time. + * @readonly + * @type {number} + */ + const SCAN_CHUNK_BYTES = 65536; + + /** + * Enum-like object for the canonical names of the containers the bundled player demuxes. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.DemuxerContainer = Object.freeze({ + MP3: 'MP3', + AAC: 'AAC', + OGG: 'OGG', + FLAC: 'FLAC', + WAV: 'WAV' + }); + + /** + * Enum-like object for the canonical names of the codecs the bundled player decodes. + * @readonly + * @enum {string} + */ + LuminaAudioPlayer.DemuxerCodec = Object.freeze({ + MP3: 'MP3', + AAC: 'AAC', + OPUS: 'OPUS', + VORBIS: 'VORBIS', + FLAC: 'FLAC', + PCM: 'PCM' + }); + + /** + * Canonicalizes the container of an audio file by trimming and upper casing it, exactly as the server canonicalizes + * the container of the same probe result. It deliberately adds no aliases: a container the server's direct-play gate + * would not match against the advertised set must not resolve a demuxer here either, so the two sides agree on which + * tracks are a direct play. Keeping the mapping identical to the server's is what makes a rename on either side a + * matching change rather than a client that plays a track the server decided to remux. + * @param {string|null|undefined} container - The container to canonicalize. + * @returns {string} The canonical container, or an empty string when there is none. + */ + function canonicalizeContainer(container) { + if (typeof container !== 'string') + return ''; + return container.trim().toUpperCase(); + } + + /** + * Canonicalizes the codec of an audio file, mapping the free form descriptions the probe reports to the canonical codec + * names the player advertises. It mirrors the mapping of the server, so that the demuxer the player selects for a track + * is the one the server expected when it decided the delivery. The most specific tokens are matched first, and the MPEG + * layer is matched by its layer number only, so 'MPEG-1 Layer 2' is not mistaken for an MP3. + * @param {string|null|undefined} codec - The codec to canonicalize. + * @returns {string} The canonical codec, or an empty string when there is none. + */ + function canonicalizeCodec(codec) { + if (typeof codec !== 'string') + return ''; + const normalized = codec.trim().toUpperCase(); + if (normalized === '') + return ''; + if (normalized.includes('VORBIS')) + return 'VORBIS'; + if (normalized.includes('OPUS')) + return 'OPUS'; + if (normalized.includes('FLAC')) + return 'FLAC'; + if (normalized.includes('ALAC') || normalized.includes('APPLE LOSSLESS')) + return 'ALAC'; + if (normalized.includes('AAC')) + return 'AAC'; + if (normalized.includes('MP3') || normalized.includes('LAYER 3') || normalized.includes('LAYER III')) + return 'MP3'; + if (normalized.includes('PCM') || normalized.includes('UNCOMPRESSED') || normalized.includes('LINEAR')) + return 'PCM'; + if (normalized.includes('WINDOWS MEDIA') || normalized.includes('WMA')) + return 'WMA'; + return normalized; + } + + LuminaAudioPlayer.canonicalizeDemuxerContainer = canonicalizeContainer; + LuminaAudioPlayer.canonicalizeDemuxerCodec = canonicalizeCodec; + + /** + * Converts a count of samples to microseconds at a sample rate, the unit of every packet timestamp of the player. + * @param {number} samples - The number of samples. + * @param {number} sampleRate - The sample rate, in Hz. + * @returns {number} The duration, in microseconds, rounded to the nearest microsecond. + */ + function samplesToMicroseconds(samples, sampleRate) { + if (!Number.isFinite(samples) || !Number.isFinite(sampleRate) || sampleRate <= 0 || samples <= 0) + return 0; + return Math.round((samples / sampleRate) * 1000000); + } + + LuminaAudioPlayer.samplesToMicroseconds = samplesToMicroseconds; + + /** + * Checks whether a run of bytes at an offset spells out an ASCII string. It is the check every magic number of a + * container is recognized by. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the run. + * @param {string} text - The expected ASCII text. + * @returns {boolean} True when the bytes spell out the text at the offset. + */ + function bytesEqualAscii(bytes, offset, text) { + if (!bytes || offset < 0 || offset + text.length > bytes.length) + return false; + for (let index = 0; index < text.length; index++) + if (bytes[offset + index] !== text.charCodeAt(index)) + return false; + return true; + } + + /** + * Reads an unsigned integer from a run of bytes in big endian order. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the integer. + * @param {number} length - The number of bytes of the integer, between 1 and 6. + * @returns {number|null} The value, or null when the run is truncated. + */ + function readUintBE(bytes, offset, length) { + if (!bytes || offset < 0 || offset + length > bytes.length || length < 1 || length > 6) + return null; + let value = 0; + for (let index = 0; index < length; index++) + value = value * 256 + bytes[offset + index]; + return value; + } + + /** + * Reads an unsigned integer from a run of bytes in little endian order. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the integer. + * @param {number} length - The number of bytes of the integer, between 1 and 6. + * @returns {number|null} The value, or null when the run is truncated. + */ + function readUintLE(bytes, offset, length) { + if (!bytes || offset < 0 || offset + length > bytes.length || length < 1 || length > 6) + return null; + let value = 0; + let factor = 1; + for (let index = 0; index < length; index++) { + value += bytes[offset + index] * factor; + factor *= 256; + } + return value; + } + + /** + * Reads a signed integer from a run of bytes in little endian order, two's complement. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the integer. + * @param {number} length - The number of bytes of the integer, between 1 and 4. + * @returns {number|null} The value, or null when the run is truncated. + */ + function readIntLE(bytes, offset, length) { + const value = readUintLE(bytes, offset, length); + if (value === null) + return null; + const limit = Math.pow(2, 8 * length); + return value >= limit / 2 ? value - limit : value; + } + + LuminaAudioPlayer.demuxReadUintBE = readUintBE; + LuminaAudioPlayer.demuxReadUintLE = readUintLE; + LuminaAudioPlayer.demuxReadIntLE = readIntLE; + LuminaAudioPlayer.demuxBytesEqualAscii = bytesEqualAscii; + + /** + * Reads a little endian signed 64 bit integer from a run of bytes, used by the granule position of an OGG page. The + * value is built from two 32 bit halves so that it stays exact for every granule a real stream can carry. + * @param {Uint8Array} bytes - The bytes to inspect. + * @param {number} offset - The first byte of the integer. + * @returns {number|null} The value, or null when the run is truncated. + */ + function readInt64LE(bytes, offset) { + const low = readUintLE(bytes, offset, 4); + const high = readIntLE(bytes, offset + 4, 4); + if (low === null || high === null) + return null; + // A granule position is a signed 64 bit value; a page that has not completed a packet carries -1, and the two + // halves are combined without a bitwise shift, which would truncate to 32 bits. This is exact, because a granule + // is a sample count that never approaches the 2^53 range a double can represent. + return high * 4294967296 + low; + } + + LuminaAudioPlayer.demuxReadInt64LE = readInt64LE; + + /** + * Reads a big endian sync safe integer, the size encoding an ID3v2 tag uses, where the top bit of each of its four + * bytes is zero. It is shared by the MP3 and AAC demuxers, which may both carry a leading ID3v2 tag. + * @param {Uint8Array} bytes - The bytes to read from. + * @param {number} offset - The offset of the first size byte. + * @returns {number} The value. + */ + function readSyncSafe(bytes, offset) { + // Each byte contributes seven bits, so the multipliers are 128, 128 squared and 128 cubed, and the top bit of + // every byte is masked off. + return ((bytes[offset] & 0x7F) * 2097152) + + ((bytes[offset + 1] & 0x7F) * 16384) + + ((bytes[offset + 2] & 0x7F) * 128) + + (bytes[offset + 3] & 0x7F); + } + + LuminaAudioPlayer.demuxReadSyncSafe = readSyncSafe; + + /** + * Builds the byte-at-a-time lookup table of a non-reflected CRC, so that a checksum over a run of bytes costs one + * table lookup and one shift per byte instead of one iteration per bit. The checksum it produces is identical to the + * bit-by-bit form, because it is the same polynomial, initial value and bit order, only evaluated a byte at a time. + * @param {number} polynomial - The CRC polynomial, without its leading term (0x04C11DB7, 0x8005, 0x07, ...). + * @param {number} width - The width of the checksum in bits: 8, 16 or 32. + * @returns {Uint32Array} The 256 entry table, indexed by byte value. + */ + function buildCrcTable(polynomial, width) { + const table = new Uint32Array(256); + const mask = width === 32 ? 0xFFFFFFFF : (1 << width) - 1; + const topBit = 1 << (width - 1); + for (let index = 0; index < 256; index++) { + let crc = (index << (width - 8)) & mask; + for (let bit = 0; bit < 8; bit++) + crc = (crc & topBit) !== 0 ? ((crc << 1) ^ polynomial) & mask : (crc << 1) & mask; + table[index] = crc >>> 0; + } + return table; + } + + LuminaAudioPlayer.demuxBuildCrcTable = buildCrcTable; + + /** + * A bit reader over a run of big endian bytes, for the bit packed headers of MPEG, FLAC and OGG. + */ + class DemuxerBitReader { + /** + * Creates an instance of DemuxerBitReader. + * @param {Uint8Array} bytes - The bytes to read from. + */ + constructor(bytes) { + this.bytes = bytes instanceof Uint8Array ? bytes : new Uint8Array(0); + this.bitPosition = 0; + } + + /** + * Reads an unsigned integer of up to 53 bits. The accumulation is done in floating point, so the value is exact up + * to 2^53, which covers every field a container header holds, including the 36 bit total sample count of FLAC. + * @param {number} count - The number of bits to read, up to 53. + * @returns {number} The value. + * @throws {RangeError} When the bytes end before the requested bits are read. + */ + readBits(count) { + let value = 0; + for (let index = 0; index < count; index++) { + const byteIndex = this.bitPosition >> 3; + if (byteIndex >= this.bytes.length) + throw new RangeError('The demuxer bit reader ran past the end of its bytes.'); + const shift = 7 - (this.bitPosition & 7); + value = value * 2 + ((this.bytes[byteIndex] >> shift) & 1); + this.bitPosition++; + } + return value; + } + + /** + * Gets the number of whole bytes consumed so far. + * @returns {number} The byte position. + */ + getBytePosition() { + return this.bitPosition >> 3; + } + } + + LuminaAudioPlayer.DemuxerBitReader = DemuxerBitReader; + + /** + * A random access byte source that answers a read at an absolute offset and reports end of file as a short read + * instead of a failure. The demuxers read through this interface, so a test injects a plain in memory implementation + * and never a downloader. + */ + class DemuxerByteSource { + /** + * Creates an instance of DemuxerByteSource over a range downloading downloader. + * @param {Object} downloader - The TrackDownloader of the download engine, with readBytesAsync, getTotalBytes, getRanges, isComplete and getError. + */ + constructor(downloader) { + this.downloader = downloader; + } + + /** + * Gets the total size of the stream, when the download already discovered it. + * @returns {number|null} The length in bytes, or null when it is not known yet. + */ + getLength() { + const total = this.downloader && this.downloader.getTotalBytes ? this.downloader.getTotalBytes() : null; + return Number.isInteger(total) && total >= 0 ? total : null; + } + + /** + * Reads a window of bytes at an absolute offset, waiting for it when the download has not fetched it yet. A window + * that reaches past the end of the file is shortened, and a window entirely past it reads as empty, so a parser + * sees end of file as a short read. + * @param {number} offset - The first byte of the window. + * @param {number} length - The number of bytes of the window. + * @returns {Promise} The bytes, possibly fewer than requested at the end of the stream. + */ + async readAsync(offset, length) { + const start = Math.max(0, Math.floor(offset)); + let size = Math.max(0, Math.floor(length)); + if (size === 0) + return new Uint8Array(0); + const total = this.getLength(); + if (total !== null) { + if (start >= total) + return new Uint8Array(0); + size = Math.min(size, total - start); + } + try { + const bytes = await this.downloader.readBytesAsync(start, size); + return bytes && bytes.length > 0 ? bytes.subarray(0, size) : new Uint8Array(0); + } catch (error) { + // The read rejects when the window can no longer be filled. That is end of file when the window simply + // reaches past the last downloaded byte and the download has drained: the bytes that are there are still + // returned, and only the tail is shortened. + if (!isWindowUnavailableError(error)) + throw error; + const coveredEnd = this.getCoveredEnd(start); + if (coveredEnd > start) { + const available = Math.min(size, coveredEnd - start); + const bytes = await this.downloader.readBytesAsync(start, available); + return bytes && bytes.length > 0 ? bytes.subarray(0, available) : new Uint8Array(0); + } + return new Uint8Array(0); + } + } + + /** + * Gets the end of the contiguous run of downloaded bytes that covers an offset. + * @param {number} offset - The offset to look up. + * @returns {number} The exclusive end of the covering run, or the offset itself when it is not covered. + */ + getCoveredEnd(offset) { + if (!this.downloader || typeof this.downloader.getRanges !== 'function') + return offset; + const ranges = this.downloader.getRanges(); + for (const range of ranges) + if (offset >= range.start && offset < range.end) + return range.end; + return offset; + } + } + + /** + * Checks whether a value is the failure the downloader reports for a window it can never fill, which a byte source + * reads as end of file. + * @param {*} error - The value to check. + * @returns {boolean} True when it is a window unavailable failure. + */ + function isWindowUnavailableError(error) { + return !!error + && error.code === LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED + && !!error.details + && error.details.reason === LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE; + } + + /** + * Checks whether a value is the stop a download reports when it is intentionally aborted or destroyed. The download + * module treats such a stop as a normal teardown, not as a failure of the track, so a demuxer must not record it. + * @param {*} error - The value to check. + * @returns {boolean} True when the value is an intentional download stop. + */ + function isDownloadAbort(error) { + if (!error) + return false; + if (error.code === LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED) + return true; + // A raw fetch abort is also an intentional stop, so a DOMException named AbortError is treated the same way. + return LuminaAudioPlayer.isAbortError(error); + } + + LuminaAudioPlayer.isDownloadAbort = isDownloadAbort; + + /** + * Adapts a byte source for a demuxer: a caller passes the TrackDownloader of the download engine, an object that + * already implements readAsync and getLength, or nothing. + * @param {*} source - The source to adapt. + * @returns {Object} An object with getLength and readAsync. + */ + function toByteSource(source) { + if (source && typeof source.readAsync === 'function' && typeof source.getLength === 'function') + return source; + if (source && typeof source.readBytesAsync === 'function') + return new DemuxerByteSource(source); + return { + getLength: () => null, + readAsync: async () => new Uint8Array(0) + }; + } + + LuminaAudioPlayer.DemuxerByteSource = DemuxerByteSource; + LuminaAudioPlayer.createDemuxerByteSource = toByteSource; + + /** + * A windowing reader over a byte source. A parser walks the stream with absolute offsets, and the reader keeps the + * last window it loaded, so that a sequence of nearby small reads is served from memory and issues one request per + * window rather than one per read. + */ + class DemuxerReader { + /** + * Creates an instance of DemuxerReader. + * @param {Object} source - The byte source, per {@link LuminaAudioPlayer.createDemuxerByteSource}. + * @param {Object} [options] - The reader options. + * @param {number} [options.windowSize] - The number of bytes kept in the read ahead window. Defaults to 64 KiB. + */ + constructor(source, options = {}) { + this.source = toByteSource(source); + this.windowSize = Number.isInteger(options.windowSize) && options.windowSize > 0 ? options.windowSize : WINDOW_SIZE_BYTES; + this.windowStart = 0; + /** @type {Uint8Array} */ + this.windowBytes = new Uint8Array(0); + this.windowLength = 0; + // Set by destroy; a destroyed reader is never nulled out from under a caller, it only stops returning bytes. + this.destroyed = false; + } + + /** + * Releases the byte source of the reader, so that the downloader it holds is no longer referenced. The reader is + * deliberately left in place as a dead reader rather than being cleared by its owner: an operation that was in + * flight when the demuxer was destroyed keeps a reference to it and reads from it, so a freed object would turn + * that continuation into a TypeError, which the operation would record as a failure of a track that was in fact + * torn down. Every read after this returns an empty array and the length reads as unknown instead. + * @returns {void} + */ + destroy() { + this.destroyed = true; + this.source = null; + this.windowStart = 0; + this.windowBytes = new Uint8Array(0); + this.windowLength = 0; + } + + /** + * Gets the total size of the stream, when it is known. + * @returns {number|null} The length in bytes, or null. + */ + getLength() { + return this.source ? this.source.getLength() : null; + } + + /** + * Reads up to a number of bytes at an absolute offset. The returned view may be shorter than requested at the end + * of the stream, and is empty past it. It is a view over the read ahead window, so a caller must not mutate it and + * must not hold it across the end of the stream, though keeping it is safe while the reader is alive because a + * reload replaces the window rather than reusing its buffer. + * @param {number} offset - The first byte to read. + * @param {number} length - The number of bytes to read. + * @returns {Promise} The bytes, or an empty array when the offset is at or past the end of the stream. + * @throws {RangeError} When the length is past the limit of a single read. It is refused rather than truncated, + * because a caller treats a short read as the end of the stream, so a truncated read would be misread as EOF. + */ + async readAsync(offset, length) { + // A destroyed reader reads as an empty stream, so an operation still in flight ends at an end of stream rather + // than on a released reader. + if (this.destroyed) + return new Uint8Array(0); + const start = Math.max(0, Math.floor(offset)); + const requested = Math.max(0, Math.floor(length)); + if (requested > MAX_READ_BYTES) + throw new RangeError(`A single demuxer read cannot exceed ${MAX_READ_BYTES} bytes.`); + const size = requested; + if (size === 0) + return new Uint8Array(0); + if (start >= this.windowStart && start + size <= this.windowStart + this.windowLength) + return this.windowBytes.subarray(start - this.windowStart, start - this.windowStart + size); + const loadSize = Math.max(this.windowSize, size); + const bytes = await this.source.readAsync(start, loadSize); + this.windowStart = start; + this.windowBytes = bytes; + this.windowLength = bytes ? bytes.length : 0; + if (this.windowLength === 0) + return new Uint8Array(0); + return this.windowLength >= size ? this.windowBytes.subarray(0, size) : this.windowBytes; + } + + /** + * Reads a window of bytes and copies it, so that the caller owns bytes that do not alias the read ahead window. + * It is used for the codec private data a demuxer hands to the decoder. + * @param {number} offset - The first byte to read. + * @param {number} length - The number of bytes to read. + * @returns {Promise} A copy of the bytes, possibly shorter than requested at the end of the stream. + */ + async copyAsync(offset, length) { + const bytes = await this.readAsync(offset, length); + return bytes.length === 0 ? bytes : bytes.slice(); + } + + /** + * Reads the last bytes of the stream, when its length is known. It is how a demuxer reads a trailer, such as the + * last OGG page, without walking the whole stream. + * @param {number} maxLength - The maximum number of trailing bytes to read. + * @returns {Promise<{ bytes: Uint8Array, offset: number }|null>} The trailing bytes and their absolute offset, or null when the length is unknown or the stream is empty. + */ + async readTailAsync(maxLength) { + const total = this.getLength(); + if (total === null || total <= 0) + return null; + const size = Math.min(Math.max(1, Math.floor(maxLength)), total); + const offset = total - size; + const bytes = await this.copyAsync(offset, size); + return bytes.length > 0 ? { bytes, offset } : null; + } + } + + LuminaAudioPlayer.DemuxerReader = DemuxerReader; + + /** + * Coerces a value to a whole, non negative number of microseconds, so that a packet the decoder receives always + * carries a finite timestamp and duration. A non finite value becomes zero rather than passing through, because this + * is the last point before the decoder and a NaN or an Infinity there would corrupt the decode timeline silently. + * @param {number} value - The value to coerce. + * @returns {number} The whole, non negative microsecond value. + */ + function toMicroseconds(value) { + return Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0; + } + + /** + * Builds the frozen packet shape the decode pipeline consumes. + * @param {Uint8Array} data - The encoded bytes of the packet. + * @param {number} timestamp - The presentation timestamp of the first sample, in microseconds. + * @param {number} duration - The duration of the packet, in microseconds. + * @returns {Object} The frozen packet. + */ + function createPacket(data, timestamp, duration) { + return Object.freeze({ + data, + timestamp: toMicroseconds(timestamp), + duration: toMicroseconds(duration), + type: 'key' + }); + } + + LuminaAudioPlayer.createDemuxerPacket = createPacket; + + /** + * The number of candidate positions a single scan will validate before it gives up. A validator is an awaited read, so + * a stream whose body is filled with byte patterns that look like a sync, but are not, would otherwise make one scan + * do one awaited read per pattern. The cap is far above what any real stream needs, because a real frame or page is + * found within one frame or page length of the start, so it only ever refuses a crafted or badly corrupt region. + * @readonly + * @type {number} + */ + const SCAN_MAX_CANDIDATES = 65536; + + /** + * Scans a stream for the next offset whose bytes start with a prefix and pass a validator. It reads forward in + * chunks and only calls the validator on the offsets that match the prefix, so a byte that merely looks like a frame + * sync costs one comparison while a real header is validated in full. The validator reads the extra bytes it needs + * itself, so it is not limited by the size of a scan chunk. + * + * The prefix may carry a mask per byte, so a format whose sync is shorter than a whole byte can reject most false + * candidates with a comparison rather than with the awaited validator; and the number of candidates a scan validates + * is capped, so a crafted region cannot turn a scan into an unbounded number of awaited reads. A scan that reaches + * that cap throws rather than returning the same -1 it uses for end of stream, so a refused region is reported as a + * demux failure instead of ending playback silently. + * @param {LuminaAudioPlayer.DemuxerReader} reader - The reader to scan through. + * @param {number} start - The offset to start the scan at. + * @param {number|null} end - The exclusive end of the scan, or null to scan to the end of the stream. + * @param {Array} prefix - The bytes a candidate must start with. + * @param {Function} [validateAsync] - An async validator that receives the absolute offset of a candidate and returns whether it is a real frame header. When omitted, the prefix match alone accepts a candidate. + * @param {Object} [options] - The scan options. + * @param {Array} [options.prefixMask] - A mask per prefix byte; a candidate matches when each byte matches under its mask. Defaults to an exact comparison of every byte. + * @returns {Promise} The offset of the first accepted candidate, or -1 when the scan reaches the end of the stream without one. + * @throws {LuminaAudioPlayer.PlayerError} With {@link LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED} and details.reason === 'scan-budget-exhausted' when the scan evaluated its candidate budget without finding a frame, which is a corrupt or crafted region rather than an end of stream. + */ + async function scanForFrameAsync(reader, start, end, prefix, validateAsync, options = {}) { + const settings = options || {}; + const prefixMask = settings.prefixMask || null; + let remaining = SCAN_MAX_CANDIDATES; + const limit = end === null ? Number.POSITIVE_INFINITY : Math.floor(end); + const overlap = Math.max(0, prefix.length - 1); + let position = Math.max(0, Math.floor(start)); + // The outer loop walks the stream forward one chunk at a time: each iteration reads one chunk at `position`, + // examines its candidates, and then advances `position` past it (less the overlap), until the scan limit or the + // end of the stream is reached. + while (position < limit) { + const requested = Math.min(SCAN_CHUNK_BYTES, limit - position); + const bytes = await reader.readAsync(position, requested); + if (bytes.length === 0) + return -1; + // A candidate must fit entirely inside the chunk, so the last start offset is the one where a whole prefix still fits; the `<=` below includes it. + const lastCandidate = bytes.length - prefix.length; + // The middle loop tries every byte offset of the chunk as the start of a candidate frame. + for (let index = 0; index <= lastCandidate; index++) { + let matches = true; + // The inner loop matches the candidate against the prefix, byte by byte and under each byte's mask, + // stopping at the first mismatch. This is the cheap filter: only a candidate that matches the whole + // prefix is worth the awaited validator, which reads further bytes. + for (let prefixIndex = 0; prefixIndex < prefix.length; prefixIndex++) { + const mask = prefixMask ? prefixMask[prefixIndex] : 0xFF; + if ((bytes[index + prefixIndex] & mask) !== (prefix[prefixIndex] & mask)) { + matches = false; + break; + } + } + if (!matches) + continue; + // The prefix matched, so this offset is a full candidate: it costs one unit of the scan budget, and the validator, when there is one, decides whether it is a real frame header. + if (remaining <= 0) + throw new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The scan evaluated its candidate budget without finding a frame.', { reason: 'scan-budget-exhausted' }); + remaining--; + const offset = position + index; + if (!validateAsync || await validateAsync(offset)) + return offset; + } + // When the chunk came back short the stream ended, so there is nothing beyond it to scan. + if (bytes.length < requested) + return -1; + // The next chunk overlaps this one by one byte less than the prefix, so a candidate that straddles the boundary is still validated instead of being skipped. + position += Math.max(1, bytes.length - overlap); + } + return -1; + } + + LuminaAudioPlayer.scanForFrameAsync = scanForFrameAsync; + + /** + * Copies a run of bytes into a new array. It is used when a packet is assembled from more than one read, so that the + * bytes the decoder receives do not alias a read ahead window. + * @param {Array} parts - The runs to concatenate, in order. + * @returns {Uint8Array} The concatenated bytes. + */ + function concatBytes(parts) { + let total = 0; + for (const part of parts) + total += part.byteLength; + const result = new Uint8Array(total); + let offset = 0; + for (const part of parts) { + result.set(part, offset); + offset += part.byteLength; + } + return result; + } + + LuminaAudioPlayer.concatDemuxerBytes = concatBytes; + + /** + * The base class of a demuxer. It owns the byte reader, the recorded failure and the error callback, and it defines the interface every per format demuxer implements. + */ + class Demuxer { + /** + * Creates an instance of Demuxer. + * @param {Object} options - The demuxer options. + * @param {*} options.source - The byte source, per {@link LuminaAudioPlayer.createDemuxerByteSource}. + * @param {LuminaAudioPlayer.DemuxerReader} [options.reader] - An existing reader to use instead of building one from the source. + * @param {Function} [options.onError] - Called with a {@link LuminaAudioPlayer.PlayerError} when the demuxer fails. + * @param {number} [options.windowSize] - The size of the read ahead window of the reader. + */ + constructor(options = {}) { + const settings = options || {}; + this.reader = settings.reader instanceof DemuxerReader ? settings.reader : new DemuxerReader(settings.source, settings); + this.onError = typeof settings.onError === 'function' ? settings.onError : null; + /** @type {LuminaAudioPlayer.PlayerError|null} */ + this.error = null; + this.destroyed = false; + this.initialized = false; + } + + /** + * Checks whether the stream was initialized and can be read. + * @returns {boolean} True when the stream is initialized. + */ + isInitialized() { + return this.initialized && !this.destroyed && this.error === null; + } + + /** + * Checks whether the demuxer can no longer read, because it was destroyed or failed. + * @returns {boolean} True when the demuxer has stopped. + */ + isStopped() { + return this.destroyed || this.error !== null; + } + + /** + * Checks whether the demuxer was destroyed. + * @returns {boolean} True when the demuxer was destroyed. + */ + isDestroyed() { + return this.destroyed; + } + + /** + * Gets the last failure the demuxer recorded, or null. + * @returns {LuminaAudioPlayer.PlayerError|null} The recorded failure. + */ + getError() { + return this.error; + } + + /** + * Builds a typed error without recording it. + * @param {string} code - One of the {@link LuminaAudioPlayer.PlayerErrorCode} values. + * @param {string} message - The developer facing description of the failure. + * @param {Object} [details] - Optional structured details. + * @returns {LuminaAudioPlayer.PlayerError} The typed error. + */ + createError(code, message, details = null) { + return new LuminaAudioPlayer.PlayerError(code || LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, message, details || null); + } + + /** + * Records a fatal failure, stops the demuxer and notifies the error callback. The first failure wins, so a burst + * of failures after the demuxer stopped never overwrites the cause or reports twice. A failure that another + * component already typed with a player error keeps that component's code. + * @param {*} error - The failure to record. + * @param {string} [code] - The code to use when the failure is not already a player error. + * @param {Object} [details] - Optional structured details. + * @returns {LuminaAudioPlayer.PlayerError} The recorded typed error. + */ + fail(error, code = LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, details = null) { + if (this.error) + return this.error; + const typed = LuminaAudioPlayer.toOwnedPlayerError(error, code, details); + this.error = typed; + this.initialized = false; + if (this.onError) { + try { + this.onError(typed); + } catch (callbackError) { + console.error('Audio player: the demuxer error callback threw.', callbackError); + } + } + return typed; + } + + /** + * Skips an ID3v2 tag at an offset, when one is present. The MP3 and AAC demuxers both use it, because a stream of + * either may carry a leading ID3v2 tag before its first frame. + * @param {number} offset - The offset to look for the tag at. + * @returns {Promise} The offset just past the tag, or the given offset when there is none. + */ + async skipId3v2Async(offset) { + const bytes = await this.reader.readAsync(offset, 10); + if (bytes.length < 10 || !LuminaAudioPlayer.demuxBytesEqualAscii(bytes, 0, 'ID3')) + return offset; + const flags = bytes[5]; + const size = LuminaAudioPlayer.demuxReadSyncSafe(bytes, 6); + // A tag may carry a ten byte footer, which is not counted in the size. + return offset + 10 + size + ((flags & 0x10) !== 0 ? 10 : 0); + } + + /** + * Records a fatal failure through {@link LuminaAudioPlayer.Demuxer#fail}, with two exceptions: an intentional + * download stop, which is a normal teardown and not a failure of the track, is returned typed without being + * recorded or reported; and a failure that another component already typed with a structured reason keeps its + * own reason instead of the generic one of the caller. + * @param {*} error - The failure to record. + * @param {string} reason - The structured reason to attach when the failure carries none. + * @returns {LuminaAudioPlayer.PlayerError} The typed error, recorded unless it is an intentional stop. + */ + recordFailure(error, reason) { + // A failure observed after the demuxer was destroyed belongs to the teardown of the operation, not to the track, + // so it is returned typed as an abort and is neither recorded nor reported as a track failure. + if (this.destroyed) + return LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED); + // An intentional stop is returned typed but not recorded, and it is wrapped with the abort code rather than + // the demux code, so that a caller which classifies the failure again, as the capability module does, still + // sees it as an abort and not as a track that has to be normalized. + if (isDownloadAbort(error)) + return LuminaAudioPlayer.PlayerError.from(error, LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED); + if (error instanceof LuminaAudioPlayer.PlayerError && error.details && error.details.reason !== undefined) + return this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED); + return this.fail(error, LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, { reason }); + } + + /** + * Reads the header(s) of the stream and prepares the configuration. It must be called before reading any packet. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not a stream of this format. + */ + async initializeAsync() { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This demuxer does not implement initializeAsync.'); + } + + /** + * Reads the next encoded packet of the stream. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This demuxer does not implement readPacketAsync.'); + } + + /** + * Gets the decoder configuration of the stream, available after initializeAsync resolved. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + return null; + } + + /** + * Gets the duration of the whole stream, when the header states it. + * @returns {number|null} The duration in seconds, or null when it is not known from the header. + */ + getDuration() { + return null; + } + + /** + * Repositions the read cursor to a packet boundary at or before a time. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the format cannot be repositioned by time. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a frame gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + return null; + } + + /** + * Releases every resource of the demuxer. It is safe to call more than once. It releases the reader, and through + * it the byte source that holds the download engine, without clearing the reader reference itself, because an + * operation that is still in flight holds that reference and reads through it; the released reader reads as an + * empty stream, so the operation ends at an end of stream instead of on a freed object. It also gives a subclass + * the chance to release its own queued state through onDestroy. + * @returns {Promise} A promise resolving when the demuxer is released. + */ + async destroyAsync() { + this.destroyed = true; + this.initialized = false; + if (typeof this.onDestroy === 'function') + this.onDestroy(); + if (this.reader && typeof this.reader.destroy === 'function') + this.reader.destroy(); + } + + /** + * Ensures the stream was initialized before it is read. + * @returns {void} + * @throws {LuminaAudioPlayer.PlayerError} When the demuxer was destroyed, failed, or was not initialized. + */ + ensureInitialized() { + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + if (this.error) + throw this.error; + if (!this.initialized) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer is not initialized.'); + } + } + + LuminaAudioPlayer.Demuxer = Demuxer; + + /** + * A registry of demuxer descriptors, keyed by the canonical container and codec pair a demuxer handles. + */ + class DemuxerRegistry { + /** + * Creates an instance of DemuxerRegistry. + */ + constructor() { + /** @type {Map} */ + this.descriptors = new Map(); + } + + /** + * Builds the key a container and codec pair is registered and looked up under. + * @param {string} container - The canonical container name. + * @param {string} codec - The canonical codec name. + * @returns {string} The registry key. + */ + static buildKey(container, codec) { + return `${container}/${codec}`; + } + + /** + * Registers a demuxer descriptor. + * @param {Object} descriptor - The descriptor, with a container, a codec, a representative decoder probe and a create function that receives the demuxer options and returns a demuxer. + * @returns {LuminaAudioPlayer.DemuxerRegistry} This registry, for chaining. + * @throws {TypeError} When the descriptor is incomplete, including when it carries no representative probe. The probe is required so that the browser check of the demux capability module never has to guess from a name, which would silently report a supported codec as unsupported. + */ + register(descriptor) { + if (!descriptor || typeof descriptor.create !== 'function') + throw new TypeError('A demuxer descriptor must carry a create function.'); + const container = canonicalizeContainer(descriptor.container); + const codec = canonicalizeCodec(descriptor.codec); + if (container === '' || codec === '') + throw new TypeError('A demuxer descriptor must name a container and a codec.'); + const probe = descriptor.probe; + if (!probe + || typeof probe.codec !== 'string' || probe.codec === '' + || !Number.isInteger(probe.sampleRate) || probe.sampleRate <= 0 + || !Number.isInteger(probe.numberOfChannels) || probe.numberOfChannels <= 0) + throw new TypeError('A demuxer descriptor must carry a representative decoder probe with a codec string, a sample rate and a channel count.'); + this.descriptors.set(DemuxerRegistry.buildKey(container, codec), Object.freeze({ + container, + codec, + probe: Object.freeze({ codec: probe.codec, sampleRate: probe.sampleRate, numberOfChannels: probe.numberOfChannels }), + create: descriptor.create + })); + return this; + } + + /** + * Finds the demuxer descriptor of a container and codec pair, matching canonicalized names. + * @param {string} container - The container name, in any casing. + * @param {string} codec - The codec name, in any casing or as a free form probe description. + * @returns {Object|null} The descriptor, or null when no demuxer handles the pair. + */ + find(container, codec) { + const key = DemuxerRegistry.buildKey(canonicalizeContainer(container), canonicalizeCodec(codec)); + return this.descriptors.get(key) || null; + } + + /** + * Lists the registered descriptors, in registration order. + * @returns {Array} The descriptors. + */ + getDescriptors() { + return [...this.descriptors.values()]; + } + } + + LuminaAudioPlayer.DemuxerRegistry = DemuxerRegistry; + + /** + * The process wide registry the per format modules register their demuxers into. It exists as soon as this module + * loads, so a format module loaded after it can always register, whatever the load order among the formats. + * @type {LuminaAudioPlayer.DemuxerRegistry} + */ + LuminaAudioPlayer.demuxerRegistry = new DemuxerRegistry(); + + /** + * Registers a demuxer descriptor into the process wide registry. + * @param {Object} descriptor - The descriptor, per {@link LuminaAudioPlayer.DemuxerRegistry#register}. + * @returns {LuminaAudioPlayer.DemuxerRegistry} The process wide registry, for chaining. + */ + LuminaAudioPlayer.registerDemuxer = function (descriptor) { + return LuminaAudioPlayer.demuxerRegistry.register(descriptor); + }; +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-flac.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-flac.js new file mode 100644 index 00000000..974ba8e6 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-flac.js @@ -0,0 +1,1064 @@ +/** + * FLAC demuxer of the audio player. + * + * A FLAC file is the four byte magic 'fLaC', a sequence of metadata blocks whose first is the mandatory STREAMINFO + * block, and then a stream of audio frames. STREAMINFO states the sample rate, the channel count, the bit depth and the + * total number of samples of the whole stream, so the duration is known up front, which no other container here gives. + * Each frame header states its own block size, sample rate, channel assignment and sample size, plus a CRC-8 over the + * header, and the frame number or sample number it starts at. + * + * Finding the exact frame boundary + * -------------------------------- + * A FLAC frame does not state its own compressed length. This demuxer computes it the way the format defines it, by + * walking the frame's bitstream: the frame header, then one subframe per channel, then zero padding to the next byte + * boundary, then the 16 bit frame CRC. Each subframe is parsed to its exact end without decoding it, whatever it holds: + * - a constant subframe is one tail of bits-per-sample bits; + * - a verbatim subframe is a whole block of bits-per-sample bits; + * - a fixed or an LPC subframe is a run of warm-up samples, the LPC parameters when it is LPC, and then a coded + * residual; + * - a coded residual is one or more Rice partitions, each either Rice coded with a per-partition parameter, or, under + * the escape code, a run of raw bits. Walking a partition means walking every coded value of it, because a Rice code + * is not a fixed width, so the parser reads the unary prefix and the remainder of each value. + * The 16 bit frame CRC closes the frame, and it is verified against the bytes that were walked, so a frame that was + * framed wrongly, or that is corrupt, is reported rather than handed to the decoder. The frame header CRC-8 is verified + * too, so a byte pattern that merely looks like a sync cannot start a frame. + * + * The codec private data + * ---------------------- + * The WebCodecs FLAC registration requires a description that is the bytes of a FLAC bitstream up to the first frame, + * at least the 'fLaC' magic followed by the STREAMINFO metadata block. This demuxer builds exactly that: the magic and + * the STREAMINFO block, header included, without the other metadata blocks of the file, so the description stays small + * whatever a file carries. + * + * Seeking and resynchronization + * ----------------------------- + * A frame boundary is located from a distance by scanning for a frame header whose CRC-8 and stream parameters match, + * which is what a seek uses to land on a frame before parsing it exactly, and what a resynchronization uses after a + * corrupted region. A FLAC stream may carry a SEEKTABLE, but this demuxer does not need one: it estimates the byte + * position of a time from its proportion of the total samples and then scans to the next frame header, whose coded frame + * or sample number gives the position back exactly. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The four byte magic every FLAC stream starts with. + * @readonly + * @type {string} + */ + const FLAC_MAGIC = 'fLaC'; + + /** + * The number of bytes of the STREAMINFO metadata block body. + * @readonly + * @type {number} + */ + const STREAMINFO_BODY_BYTES = 34; + + /** + * The number of header bytes read to parse a frame header. A FLAC frame header is at most seventeen bytes long. + * @readonly + * @type {number} + */ + const FRAME_HEADER_WINDOW_BYTES = 20; + + /** + * The number of bytes held in the read ahead window of the frame bitstream reader. It is at least a whole FLAC + * subframe for the common configurations, so the parser issues one read per window rather than one per bit. + * @readonly + * @type {number} + */ + const FRAME_WINDOW_BYTES = 65536; + + /** + * The byte budget a frame is allowed to consume when neither the maximum frame size of STREAMINFO nor the length of + * the stream is known. It is above the largest frame the format can produce, so a parser never stops a valid frame, + * while a corrupt one cannot make it read without bound. + * @readonly + * @type {number} + */ + const DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024; + + /** + * The sample rates, in Hz, named directly by the sample rate codes of a FLAC frame header. + * @readonly + * @type {Object} + */ + const SAMPLE_RATE_CODES = Object.freeze({ + 1: 88200, + 2: 176400, + 3: 192000, + 4: 8000, + 5: 16000, + 6: 22050, + 7: 24000, + 8: 32000, + 9: 44100, + 10: 48000, + 11: 96000 + }); + + /** + * The bits-per-sample each sample size code names, with zero meaning 'from STREAMINFO'. + * @readonly + * @type {Array} + */ + const SAMPLE_SIZE_CODES = Object.freeze([0, 8, 12, 0, 16, 20, 24, 32]); + + /** + * The fourteen bit frame sync of a FLAC frame, as the two byte prefix a scan matches on. The mask covers the top six + * bits of the second byte, so a scan rejects a byte pattern that is not a sync by a comparison instead of by an + * awaited header parse. + * @readonly + * @type {Array} + */ + const FLAC_SYNC_PREFIX = Object.freeze([0xFF, 0xF8]); + + /** + * The byte mask of {@link FLAC_SYNC_PREFIX}, matching the fourteen bit sync exactly. + * @readonly + * @type {Array} + */ + const FLAC_SYNC_MASK = Object.freeze([0xFF, 0xFC]); + + /** + * The number of metadata blocks the demuxer will walk past STREAMINFO before it refuses the stream. Real files carry a + * handful, and the walk is bounded by this cap rather than by the length of the stream. + * @readonly + * @type {number} + */ + const MAX_METADATA_BLOCKS = 4096; + + /** + * The lookup table of the FLAC frame checksum, built once. It turns the checksum from eight bit iterations to one byte + * lookup per byte of a frame. + * @readonly + * @type {Uint32Array} + */ + const CRC16_TABLE = LuminaAudioPlayer.demuxBuildCrcTable(0x8005, 16); + + /** + * The lookup table of the FLAC frame header checksum, built once. + * @readonly + * @type {Uint32Array} + */ + const CRC8_TABLE = LuminaAudioPlayer.demuxBuildCrcTable(0x07, 8); + + /** + * Computes the CRC-16 of a run of bytes, with the polynomial 0x8005 and an initial value of zero, the checksum a + * FLAC frame ends with. + * @param {Uint8Array} bytes - The bytes to checksum. + * @returns {number} The checksum. + */ + function computeCrc16(bytes) { + let crc = 0; + for (let index = 0; index < bytes.length; index++) + crc = ((crc << 8) ^ CRC16_TABLE[((crc >> 8) ^ bytes[index]) & 0xFF]) & 0xFFFF; + return crc & 0xFFFF; + } + + /** + * Computes the CRC-8 of a run of bytes, with the polynomial 0x07 and an initial value of zero, the checksum a FLAC + * frame header ends with. + * @param {Uint8Array} bytes - The bytes to checksum. + * @returns {number} The checksum. + */ + function computeCrc8(bytes) { + let crc = 0; + for (let index = 0; index < bytes.length; index++) + crc = CRC8_TABLE[(crc ^ bytes[index]) & 0xFF]; + return crc; + } + + /** + * Reads the UTF-8 style coded number a FLAC frame header uses for the frame number or the sample number. + * @param {LuminaAudioPlayer.DemuxerBitReader} reader - The bit reader positioned on the first byte of the number. + * @returns {number} The decoded number. + * @throws {RangeError} When the coded number is malformed. + */ + function readCodedNumber(reader) { + const first = reader.readBits(8); + if ((first & 0x80) === 0) + return first; + // The number is coded the way UTF-8 codes a code point: the run of leading one bits in the first byte states how + // many bytes the number spans, and each following byte starts with a '10' prefix and contributes six more bits. + let leadingOnes = 0; + let mask = 0x80; + while (mask !== 0 && (first & mask) !== 0) { + leadingOnes++; + mask >>= 1; + } + if (leadingOnes < 2 || leadingOnes > 7) + throw new RangeError('The FLAC coded number is malformed.'); + let value = first & (0x7F >> leadingOnes); + for (let index = 1; index < leadingOnes; index++) { + const continuation = reader.readBits(8); + if ((continuation & 0xC0) !== 0x80) + throw new RangeError('The FLAC coded number is malformed.'); + value = value * 64 + (continuation & 0x3F); + } + return value; + } + + /** + * Resolves the block size a FLAC frame header names. + * @param {number} code - The four bit block size code. + * @param {LuminaAudioPlayer.DemuxerBitReader} reader - The bit reader, positioned after the coded number, from which the variable codes read their extra bytes. + * @returns {number|null} The block size in samples, or null when the code is invalid. + */ + function resolveBlockSize(code, reader) { + // Codes 2 to 5 are powers of two starting at 576 samples, codes 6 and 7 store the size minus one in the one or + // two bytes that follow, and codes 8 to 15 are powers of two starting at 256. + if (code === 0) + return null; + if (code === 1) + return 192; + if (code >= 2 && code <= 5) + return 576 * Math.pow(2, code - 2); + if (code === 6) + return reader.readBits(8) + 1; + if (code === 7) + return reader.readBits(16) + 1; + return 256 * Math.pow(2, code - 8); + } + + /** + * Resolves the sample rate a FLAC frame header names. It distinguishes the code that means "take it from STREAMINFO" + * from the reserved code, which a frame may never use: collapsing the two into null would accept a frame header that + * names a reserved sample rate code, leaving only the header checksum to reject a false sync. + * @param {number} code - The four bit sample rate code. + * @param {LuminaAudioPlayer.DemuxerBitReader} reader - The bit reader, positioned after the block size, from which the variable codes read their extra bytes. + * @returns {{ rate: number|null, isValid: boolean }} The sample rate in Hz, or null to mean 'from STREAMINFO', together with whether the code is one the format defines. + */ + function resolveFrameSampleRate(code, reader) { + if (code === 0) + return { rate: null, isValid: true }; + if (Object.prototype.hasOwnProperty.call(SAMPLE_RATE_CODES, code)) + return { rate: SAMPLE_RATE_CODES[code], isValid: true }; + if (code === 12) + return { rate: reader.readBits(8) * 1000, isValid: true }; + if (code === 13) + return { rate: reader.readBits(16), isValid: true }; + if (code === 14) + return { rate: reader.readBits(16) * 10, isValid: true }; + return { rate: null, isValid: false }; + } + + /** + * Parses the header of a FLAC frame. + * @param {Uint8Array} bytes - The bytes holding the header. + * @param {number} offset - The offset of the frame's first byte. + * @param {Object} streamInfo - The STREAMINFO fields of the stream. + * @returns {Object|null} The parsed header, or null when the bytes are not a valid frame header. + */ + function parseFrameHeader(bytes, offset, streamInfo) { + if (!bytes || offset < 0 || offset + 4 > bytes.length) + return null; + try { + const reader = new LuminaAudioPlayer.DemuxerBitReader(bytes.subarray(offset)); + // A frame header is bit packed: a fourteen bit sync (0x3FFE), a reserved bit that must be zero, a blocking + // strategy bit, a four bit block size code, a four bit sample rate code, a four bit channel assignment, a + // three bit sample size code, a second reserved bit, the coded frame or sample number, and finally the eight + // bit header checksum. The fields are validated against STREAMINFO so a byte pattern inside frame data is + // rejected as a header. + if (reader.readBits(14) !== 0x3FFE) + return null; + if (reader.readBits(1) !== 0) + return null; + const blockingStrategy = reader.readBits(1); + const blockSizeCode = reader.readBits(4); + const sampleRateCode = reader.readBits(4); + const channelAssignment = reader.readBits(4); + const sampleSizeCode = reader.readBits(3); + if (reader.readBits(1) !== 0) + return null; + const codedNumber = readCodedNumber(reader); + const blockSize = resolveBlockSize(blockSizeCode, reader); + if (blockSize === null) + return null; + const frameSampleRate = resolveFrameSampleRate(sampleRateCode, reader); + if (!frameSampleRate.isValid) + return null; + const sampleRate = frameSampleRate.rate === null ? streamInfo.sampleRate : frameSampleRate.rate; + if (sampleRate !== streamInfo.sampleRate) + return null; + const channels = channelAssignment <= 7 ? channelAssignment + 1 : channelAssignment <= 10 ? 2 : null; + if (channels === null || channels !== streamInfo.channels) + return null; + // Assignments 0 to 7 mean that many independent channels minus one, and 8, 9 and 10 are the three stereo + // decorrelation modes (left/side, right/side and mid/side), which still carry two channels. + if (sampleSizeCode === 3) + return null; + const bitsPerSample = sampleSizeCode === 0 ? streamInfo.bitsPerSample : SAMPLE_SIZE_CODES[sampleSizeCode]; + if (bitsPerSample !== streamInfo.bitsPerSample) + return null; + const crcPosition = reader.getBytePosition(); + const expectedCrc = reader.readBits(8); + const computedCrc = computeCrc8(bytes.subarray(offset, offset + crcPosition)); + if (expectedCrc !== computedCrc) + return null; + return Object.freeze({ + blockSize, + sampleRate, + channels, + channelAssignment, + bitsPerSample, + blockingStrategy, + codedNumber, + headerBytes: reader.getBytePosition() + }); + } catch (error) { + // A header that runs past the bytes read so far, or a malformed coded number, is not a frame header. + return null; + } + } + + /** + * A bit reader over the byte source, used to walk a whole FLAC frame without holding it in memory. It reads through a + * window that it reloads as the walk crosses it, and it enforces a bit budget, so a corrupt bitstream cannot make it + * read without bound. + * + * The reader has an awaited surface (readBitsAsync, readUnaryAsync, skipBitsAsync) and a synchronous one + * (tryReadBits, walkRiceSamples) that runs over the resident window without a promise. The synchronous surface is the + * hot path of a lossless frame: a coded residual holds thousands of values, and awaiting one promise per value, each + * resolving from bytes already in the window, is pure overhead on a realtime path. A caller therefore reloads the + * window with refillAsync and then walks as many values as fit, which costs one reload per window instead of one + * promise per value; the awaited surface remains for the fields that span a window, which are rare and tiny. + */ + class FlacBitstreamReader { + /** + * Creates an instance of FlacBitstreamReader. + * @param {LuminaAudioPlayer.DemuxerReader} reader - The windowing reader over the track. + * @param {Object} options - The options. + * @param {number} options.startOffset - The absolute byte offset the bitstream starts at. + * @param {number} options.maxBitOffset - The number of bits the walk may consume before the frame is refused. + */ + constructor(reader, options) { + this.reader = reader; + this.base = options.startOffset; + this.maxBitOffset = options.maxBitOffset; + this.bitOffset = 0; + /** @type {Uint8Array} */ + this.windowBytes = new Uint8Array(0); + this.windowStart = 0; + this.windowLength = 0; + } + + /** + * Gets the absolute byte offset the walk reached. It is meaningful while the walk is byte aligned. + * @returns {number} The absolute byte offset. + */ + getBytePosition() { + return this.base + (this.bitOffset >> 3); + } + + /** + * Gets the number of bits the walk consumed. + * @returns {number} The bit offset relative to the start of the bitstream. + */ + getBitOffset() { + return this.bitOffset; + } + + /** + * Makes sure a run of bytes is available in the window, reloading it when it is not. It throws when the run + * reaches past the end of the stream, which means the frame is truncated, and when the walk exceeded its budget. + * @param {number} relativeStart - The first byte of the run, relative to the start offset. + * @param {number} byteCount - The number of bytes of the run. + * @returns {Promise} A promise resolving when the run is available. + * @throws {RangeError} With an isEof or an isBound flag when the walk cannot continue. + */ + async ensureRangeAsync(relativeStart, byteCount) { + const absoluteStart = this.base + relativeStart; + const absoluteEnd = absoluteStart + byteCount - 1; + if (absoluteStart >= this.windowStart && absoluteEnd < this.windowStart + this.windowLength) + return; + const bytes = await this.reader.readAsync(absoluteStart, Math.max(FRAME_WINDOW_BYTES, byteCount)); + this.windowStart = absoluteStart; + this.windowBytes = bytes; + this.windowLength = bytes ? bytes.length : 0; + if (this.windowLength === 0 || absoluteEnd >= this.windowStart + this.windowLength) { + const error = new RangeError('The FLAC frame bitstream ended before the frame did.'); + error.isEof = true; + throw error; + } + } + + /** + * Refuses to read past the frame's bit budget. + * @param {number} extraBits - The number of bits about to be consumed. + * @throws {RangeError} With an isBound flag when the budget is exceeded. + */ + checkBudget(extraBits) { + if (this.maxBitOffset !== null && this.bitOffset + extraBits > this.maxBitOffset) { + const error = new RangeError('The FLAC frame exceeded the size it may occupy.'); + error.isBound = true; + throw error; + } + } + + /** + * Reads an unsigned integer of up to 32 bits. + * @param {number} count - The number of bits to read. + * @returns {Promise} The value. + * @throws {RangeError} When the walk cannot continue. + */ + async readBitsAsync(count) { + if (count <= 0) + return 0; + this.checkBudget(count); + const firstByte = this.bitOffset >> 3; + const lastByte = (this.bitOffset + count - 1) >> 3; + await this.ensureRangeAsync(firstByte, lastByte - firstByte + 1); + let value = 0; + for (let index = 0; index < count; index++) { + const local = this.base + (this.bitOffset >> 3) - this.windowStart; + const bit = 7 - (this.bitOffset & 7); + value = value * 2 + ((this.windowBytes[local] >> bit) & 1); + this.bitOffset++; + } + return value; + } + + /** + * Reads a unary coded value: the number of zero bits before the terminating one. + * @returns {Promise} The number of zero bits read. + * @throws {RangeError} When the walk cannot continue. + */ + async readUnaryAsync() { + let zeros = 0; + for (;;) { + this.checkBudget(1); + const byteIndex = this.bitOffset >> 3; + await this.ensureRangeAsync(byteIndex, 1); + const local = this.base + byteIndex - this.windowStart; + const startBit = 7 - (this.bitOffset & 7); + const byte = this.windowBytes[local]; + for (let bit = startBit; bit >= 0; bit--) { + if (((byte >> bit) & 1) !== 0) { + zeros += startBit - bit; + this.bitOffset += startBit - bit + 1; + return zeros; + } + } + // The rest of the byte is zeros, so it is consumed and the scan continues on the next byte. + zeros += startBit + 1; + this.bitOffset += startBit + 1; + } + } + + /** + * Skips a number of bits, verifying that the last skipped byte exists so that a truncated frame is detected. + * @param {number} count - The number of bits to skip. + * @returns {Promise} A promise resolving when the bits were skipped. + * @throws {RangeError} When the walk cannot continue. + */ + async skipBitsAsync(count) { + if (count <= 0) + return; + this.checkBudget(count); + const newOffset = this.bitOffset + count; + await this.ensureRangeAsync((newOffset - 1) >> 3, 1); + this.bitOffset = newOffset; + } + + //+=======================================================================================+ + //| Synchronous fast path | + //+=======================================================================================+ + + /** + * Checks whether the byte the walk is on is already resident in the window, so that a caller can tell whether a + * read would need to await a reload before it awaits one. + * @returns {boolean} True when the current byte is in the window. + */ + isResident() { + const absolute = this.base + (this.bitOffset >> 3); + return absolute >= this.windowStart && absolute < this.windowStart + this.windowLength; + } + + /** + * Loads the window so that it starts at the current byte, when it does not already cover it, or always when it is + * forced. It is the single awaited step of the residual fast path: the walk below it runs synchronously until the + * window runs out, so a frame costs one reload per window rather than one promise per coded value. + * @param {boolean} [force] - True to reload even when the current byte is already resident. + * @returns {Promise} A promise resolving when the window covers the current byte. + * @throws {RangeError} When the bitstream ended. + */ + async refillAsync(force) { + const absolute = this.base + (this.bitOffset >> 3); + if (!force && absolute >= this.windowStart && absolute < this.windowStart + this.windowLength) + return; + const bytes = await this.reader.readAsync(absolute, FRAME_WINDOW_BYTES); + this.windowStart = absolute; + this.windowBytes = bytes; + this.windowLength = bytes ? bytes.length : 0; + if (this.windowLength === 0) { + const error = new RangeError('The FLAC frame bitstream ended before the frame did.'); + error.isEof = true; + throw error; + } + this.checkBudget(0); + } + + /** + * Reads an unsigned integer of up to 32 bits without awaiting, when the bits are already resident. It never + * advances the walk when it returns null, so a caller can reload the window and try again. + * @param {number} count - The number of bits to read. + * @returns {number|null} The value, or null when the bits are not all resident yet. + */ + tryReadBits(count) { + if (count <= 0) + return 0; + if (this.base + ((this.bitOffset + count - 1) >> 3) >= this.windowStart + this.windowLength) + return null; + let value = 0; + for (let index = 0; index < count; index++) { + const local = this.base + (this.bitOffset >> 3) - this.windowStart; + const bit = 7 - (this.bitOffset & 7); + value = value * 2 + ((this.windowBytes[local] >> bit) & 1); + this.bitOffset++; + } + // The synchronous path advances the walk itself, so it enforces the budget itself, exactly, rather than + // leaving the overshoot to the next awaited read. + this.checkBudget(0); + return value; + } + + /** + * Walks a run of Rice coded residual values synchronously over the resident window. This is the hot path of a + * lossless frame: the unary prefix is scanned byte by byte and the remainder is stepped over in one move, with no + * promise per value. It returns the number of values it completed, and leaves a value whose bits reach past the + * window untouched, so the walk resumes exactly on that value's first bit once the window is reloaded. + * @param {number} parameter - The Rice parameter of the partition. + * @param {number} maxSamples - The number of values still to walk in the partition. + * @returns {number} The number of values completed, between zero and maxSamples. + */ + walkRiceSamples(parameter, maxSamples) { + this.checkBudget(0); + const windowEndBit = (this.windowStart + this.windowLength - this.base) * 8; + let completed = 0; + // One iteration per residual value of the partition, until the partition is walked or a value turns out not to fit the resident window. + while (completed < maxSamples) { + const valueStart = this.bitOffset; + let found = false; + // Walk the unary prefix of this value: every zero bit is skipped and the first one bit ends the prefix. + // The window bytes are scanned directly, so the prefix costs no promise per bit. + while (this.bitOffset < windowEndBit) { + const local = this.base + (this.bitOffset >> 3) - this.windowStart; + const startBit = 7 - (this.bitOffset & 7); + const byte = this.windowBytes[local]; + let hit = false; + // Within this byte, the bits are examined from the current bit down to bit 0, looking for the one bit. that ends the unary prefix. + for (let bit = startBit; bit >= 0; bit--) { + if (((byte >> bit) & 1) !== 0) { + this.bitOffset += startBit - bit + 1; + hit = true; + break; + } + } + if (hit) { + found = true; + break; + } + this.bitOffset += startBit + 1; + // The synchronous walk enforces the budget after every advance, so a corrupt value cannot overshoot it. + this.checkBudget(0); + } + if (!found || (parameter > 0 && this.bitOffset + parameter > windowEndBit)) { + // The value does not fit the window; it is left untouched for a reload or the spanning reader. + this.bitOffset = valueStart; + break; + } + this.bitOffset += parameter; + completed++; + this.checkBudget(0); + } + return completed; + } + } + + /** + * Demuxes a FLAC stream. + */ + class FlacDemuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of FlacDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.offset = 0; + this.dataStart = 0; + this.timelineMicros = 0; + /** @type {Object|null} */ + this.streamInfo = null; + /** @type {Uint8Array|null} */ + this.description = null; + this.totalSamples = 0; + this.maxFrameSize = 0; + this.durationSeconds = null; + this.reachedEnd = false; + } + + //+=======================================================================================+ + //| Initialization | + //+=======================================================================================+ + + /** + * Reads the STREAMINFO block and the metadata blocks that follow it, builds the codec private data, and positions the read cursor on the first audio frame. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not a FLAC stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + const magic = await this.reader.readAsync(0, 4); + if (!LuminaAudioPlayer.demuxBytesEqualAscii(magic, 0, FLAC_MAGIC)) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The bytes are not a native FLAC stream.', { reason: 'no-flac-magic' }); + const streamInfo = await this.readStreamInfoAsync(); + if (!streamInfo) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The FLAC stream carries no STREAMINFO block.', { reason: 'no-streaminfo' }); + this.streamInfo = streamInfo; + this.dataStart = streamInfo.dataStart; + this.description = streamInfo.description; + this.totalSamples = streamInfo.totalSamples; + this.maxFrameSize = streamInfo.maxFrameSize; + this.durationSeconds = streamInfo.sampleRate > 0 && streamInfo.totalSamples > 0 + ? streamInfo.totalSamples / streamInfo.sampleRate + : null; + this.offset = this.dataStart; + this.timelineMicros = 0; + this.reachedEnd = false; + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream, including the required FLAC description. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.streamInfo) + return null; + return { + codec: 'flac', + sampleRate: this.streamInfo.sampleRate, + numberOfChannels: this.streamInfo.channels, + description: this.description + }; + } + + /** + * Gets the duration of the stream, from the total sample count STREAMINFO states. + * @returns {number|null} The duration in seconds, or null when it is not stated. + */ + getDuration() { + return this.durationSeconds; + } + + //+=======================================================================================+ + //| Reading | + //+=======================================================================================+ + + /** + * Reads the next FLAC frame as an encoded packet, by walking its bitstream to its exact end. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + if (this.reachedEnd) + return null; + try { + let header = await this.parseHeaderAtAsync(this.offset); + if (!header) { + const resynced = await this.resyncAsync(); + if (resynced < 0) { + this.reachedEnd = true; + return null; + } + header = await this.parseHeaderAtAsync(this.offset); + if (!header) { + this.reachedEnd = true; + return null; + } + } + const frameEnd = await this.measureFrameEndAsync(this.offset, header); + const length = frameEnd - this.offset; + const data = await this.reader.copyAsync(this.offset, length); + if (data.length < length) { + // The bytes of the frame are not all there, which is the end of a truncated stream. + this.reachedEnd = true; + return null; + } + this.verifyFrameCrc16(data); + // The duration is kept unrounded while the timeline accumulates it, so that rounding it per packet does not + // make the timeline drift; only the packet the decoder receives carries a whole number of microseconds. + const duration = (header.blockSize / header.sampleRate) * 1000000; + const packet = LuminaAudioPlayer.createDemuxerPacket(data, this.timelineMicros, duration); + this.timelineMicros += duration; + this.offset = frameEnd; + return packet; + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Repositions the read cursor to the frame that covers a time, using the sample proportion as a byte estimate and + * then scanning to the next frame header, whose coded number states the exact sample it starts at. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a frame gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const end = this.reader.getLength(); + const streamInfo = this.streamInfo; + if (end === null || !streamInfo || !Number.isFinite(seconds) || seconds < 0 || streamInfo.sampleRate <= 0) + return null; + const targetSample = Math.floor(seconds * streamInfo.sampleRate); + let estimate; + if (this.totalSamples > 0) { + const fraction = LuminaAudioPlayer.clamp(targetSample / this.totalSamples, 0, 1); + estimate = this.dataStart + Math.floor(fraction * (end - this.dataStart)); + } else + estimate = this.dataStart + Math.floor((seconds / (this.durationSeconds || 1)) * (end - this.dataStart)); + const start = Math.max(this.dataStart, Math.min(end - 1, estimate)); + const frame = await this.findNextFrameAsync(start, end); + if (frame < 0) + return null; + const header = await this.parseHeaderAtAsync(frame); + this.offset = frame; + this.reachedEnd = false; + // The coded number is the frame number on a fixed blocking stream and the sample number on a variable one, so + // the sample the frame starts at is exact in both cases once the block size of the frame is known. + if (header) { + const sample = header.blockingStrategy === 1 ? header.codedNumber : header.codedNumber * header.blockSize; + // The exact time of the sample the frame starts at, kept unrounded so the timeline it seeds does not drift. + this.timelineMicros = Math.max(0, (sample / streamInfo.sampleRate) * 1000000); + } else + this.timelineMicros = Math.max(0, seconds) * 1000000; + return frame; + } + + //+=======================================================================================+ + //| Frame measurement | + //+=======================================================================================+ + + /** + * Walks a frame from its header to its footer and returns the offset just past it. The walk reads the subframes + * of every channel and the coded residuals they hold, then steps over the zero padding to the byte boundary and + * the 16 bit frame CRC. + * @param {number} frameStart - The absolute offset of the frame's first byte. + * @param {Object} header - The parsed header of the frame. + * @returns {Promise} The absolute offset just past the frame. + * @throws {RangeError} When the frame is malformed, truncated, or longer than its budget. + */ + async measureFrameEndAsync(frameStart, header) { + const base = frameStart + header.headerBytes; + const end = this.reader.getLength(); + const budget = this.maxFrameSize > 0 + ? this.maxFrameSize + FRAME_HEADER_WINDOW_BYTES + : (end !== null ? Math.max(1, end - base) : DEFAULT_MAX_FRAME_BYTES); + const reader = new FlacBitstreamReader(this.reader, { startOffset: base, maxBitOffset: budget * 8 }); + await this.walkSubframesAsync(reader, header); + const misaligned = reader.getBitOffset() % 8; + if (misaligned !== 0) + await reader.skipBitsAsync(8 - misaligned); + await reader.readBitsAsync(16); + return reader.getBytePosition(); + } + + /** + * Walks the subframes of a frame, one per channel, using the bit width each channel's subframe carries under the channel assignment of the frame. + * @param {LuminaAudioPlayer.FlacBitstreamReader} reader - The frame bitstream reader. + * @param {Object} header - The parsed header of the frame. + * @returns {Promise} A promise resolving when every subframe was walked. + */ + async walkSubframesAsync(reader, header) { + const assignment = header.channelAssignment; + const subframes = assignment <= 7 ? assignment + 1 : 2; + for (let index = 0; index < subframes; index++) { + let bitsPerSample = header.bitsPerSample; + // The side channel of a decorrelated stereo pair carries one bit more than the stream's bit depth. + if ((assignment === 8 && index === 1) || (assignment === 9 && index === 0) || (assignment === 10 && index === 1)) + bitsPerSample += 1; + await this.walkSubframeAsync(reader, header.blockSize, bitsPerSample); + } + } + + /** + * Walks one subframe to its end. + * @param {LuminaAudioPlayer.FlacBitstreamReader} reader - The frame bitstream reader. + * @param {number} blockSize - The number of samples of the frame. + * @param {number} sampleBits - The bit width of the subframe, before its wasted bits. + * @returns {Promise} A promise resolving when the subframe was walked. + * @throws {RangeError} When the subframe type is reserved or its parameters are invalid. + */ + async walkSubframeAsync(reader, blockSize, sampleBits) { + const padding = await reader.readBitsAsync(1); + if (padding !== 0) + throw new RangeError('The FLAC subframe does not begin with a zero padding bit.'); + const type = await reader.readBitsAsync(6); + const hasWastedBits = await reader.readBitsAsync(1); + let wastedBits = 0; + if (hasWastedBits !== 0) + wastedBits = (await reader.readUnaryAsync()) + 1; + const bitsPerSample = sampleBits - wastedBits; + if (bitsPerSample <= 0) + throw new RangeError('The FLAC subframe has no bits per sample left.'); + if (type === 0) { + // Constant: one sample value. + await reader.readBitsAsync(bitsPerSample); + return; + } + if (type === 1) { + // Verbatim: every sample, unencoded. + await reader.skipBitsAsync(blockSize * bitsPerSample); + return; + } + if (type >= 8 && type <= 12) { + // Fixed predictor: the order is the low three bits, and it is followed by a coded residual. + const order = type - 8; + await reader.skipBitsAsync(order * bitsPerSample); + await this.walkResidualAsync(reader, blockSize, order); + return; + } + if (type >= 32) { + // LPC: the order is the low five bits plus one, with a precision, a shift and the coefficients before the residual. + const order = (type & 0x1F) + 1; + await reader.skipBitsAsync(order * bitsPerSample); + const precision = (await reader.readBitsAsync(4)) + 1; + if (precision === 16) + throw new RangeError('The FLAC LPC subframe names an invalid coefficient precision.'); + await reader.readBitsAsync(5); + await reader.skipBitsAsync(order * precision); + await this.walkResidualAsync(reader, blockSize, order); + return; + } + throw new RangeError('The FLAC subframe names a reserved type.'); + } + + /** + * Walks the coded residual of a fixed or LPC subframe, partition by partition. Each partition is walked by the + * synchronous fast path of the reader, so the per value awaits that a naive walk would pay are replaced by one + * reload per window; only a value longer than a whole window falls back to the awaited readers. + * @param {LuminaAudioPlayer.FlacBitstreamReader} reader - The frame bitstream reader. + * @param {number} blockSize - The number of samples of the frame. + * @param {number} predictorOrder - The order of the predictor that produced the residual. + * @returns {Promise} A promise resolving when the residual was walked. + * @throws {RangeError} When the residual coding method or its partition sizes are invalid. + */ + async walkResidualAsync(reader, blockSize, predictorOrder) { + const method = await reader.readBitsAsync(2); + if (method > 1) + throw new RangeError('The FLAC residual names a reserved coding method.'); + const parameterBits = method === 0 ? 4 : 5; + const escape = method === 0 ? 15 : 31; + const partitionOrder = await reader.readBitsAsync(4); + const partitions = 1 << partitionOrder; + if (blockSize % partitions !== 0) + throw new RangeError('The FLAC residual partitions do not divide the block evenly.'); + const partitionSamples = blockSize / partitions; + for (let partition = 0; partition < partitions; partition++) { + // Walk each partition in turn; the first one also holds the warm-up samples of the predictor, which are + // not coded as residual values and are therefore skipped from its count. + const count = partition === 0 ? partitionSamples - predictorOrder : partitionSamples; + if (count < 0) + throw new RangeError('The FLAC residual partition is shorter than the predictor order.'); + let parameter = reader.tryReadBits(parameterBits); + if (parameter === null) { + await reader.refillAsync(false); + parameter = reader.tryReadBits(parameterBits); + if (parameter === null) + parameter = await reader.readBitsAsync(parameterBits); + } + if (parameter === escape) { + let rawBits = reader.tryReadBits(5); + if (rawBits === null) { + await reader.refillAsync(false); + rawBits = reader.tryReadBits(5); + if (rawBits === null) + rawBits = await reader.readBitsAsync(5); + } + await reader.skipBitsAsync(count * rawBits); + continue; + } + let remaining = count; + while (remaining > 0) { + if (!reader.isResident()) + await reader.refillAsync(false); + let completed = reader.walkRiceSamples(parameter, remaining); + if (completed === 0) { + // The value was left untouched by a window boundary, so it is retried against a fresh window. + await reader.refillAsync(true); + completed = reader.walkRiceSamples(parameter, remaining); + } + if (completed === 0) { + // A single value longer than a whole window, which only a pathological stream produces: it is walked with the awaited readers, which span windows. + await reader.readUnaryAsync(); + if (parameter > 0) + await reader.readBitsAsync(parameter); + completed = 1; + } + remaining -= completed; + } + } + } + + /** + * Verifies the 16 bit frame CRC against the bytes that were walked. + * @param {Uint8Array} frameBytes - The bytes of the whole frame, ending with the CRC. + * @returns {void} + * @throws {LuminaAudioPlayer.PlayerError} When the checksum does not match. + */ + verifyFrameCrc16(frameBytes) { + if (frameBytes.length < 3) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The FLAC frame is too short to carry a checksum.', { reason: 'frame-crc-mismatch' }); + const length = frameBytes.length; + const expected = LuminaAudioPlayer.demuxReadUintBE(frameBytes, length - 2, 2); + const computed = computeCrc16(frameBytes.subarray(0, length - 2)); + if (expected !== computed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The FLAC frame checksum does not match.', { reason: 'frame-crc-mismatch' }); + } + + //+=======================================================================================+ + //| Internal helpers | + //+=======================================================================================+ + + /** + * Reads the STREAMINFO block and walks the remaining metadata blocks to find where the audio frames begin. + * @returns {Promise} The stream information, or null when STREAMINFO is missing. + */ + async readStreamInfoAsync() { + const blockHeader = await this.reader.readAsync(4, 4); + if (blockHeader.length < 4) + return null; + // The first byte of a metadata block header is the last-block flag in its top bit and the seven bit block type + // below it; the next three bytes are the big endian length of the block body. + const isLast = (blockHeader[0] & 0x80) !== 0; + const blockType = blockHeader[0] & 0x7F; + const length = LuminaAudioPlayer.demuxReadUintBE(blockHeader, 1, 3); + if (blockType !== 0 || length !== STREAMINFO_BODY_BYTES) + return null; + const body = await this.reader.readAsync(8, STREAMINFO_BODY_BYTES); + if (body.length < STREAMINFO_BODY_BYTES) + return null; + const reader = new LuminaAudioPlayer.DemuxerBitReader(body); + const minBlockSize = reader.readBits(16); + const maxBlockSize = reader.readBits(16); + reader.readBits(24); + const maxFrameSize = reader.readBits(24); + const sampleRate = reader.readBits(20); + const channels = reader.readBits(3) + 1; + const bitsPerSample = reader.readBits(5) + 1; + const totalSamples = reader.readBits(36); + if (sampleRate <= 0 || channels <= 0 || minBlockSize < 16 || maxBlockSize < minBlockSize) + return null; + const description = LuminaAudioPlayer.concatDemuxerBytes([ + await this.reader.copyAsync(0, 4), + blockHeader.slice(), + body.slice() + ]); + const dataStart = await this.walkMetadataBlocksAsync(isLast, 4 + 4 + length); + return { + sampleRate, + channels, + bitsPerSample, + totalSamples: totalSamples > 0 ? totalSamples : 0, + maxFrameSize, + description, + dataStart + }; + } + + /** + * Walks the metadata blocks that follow STREAMINFO, to find where the audio frames begin. Like the equivalent walk + * of the WAV demuxer, the number of blocks it will consider is capped, so a stream of zero length blocks that never + * sets the last block flag cannot make the walk do one read per four bytes of the file. + * @param {boolean} isStreamInfoLast - True when STREAMINFO is the last metadata block. + * @param {number} offset - The offset just past the STREAMINFO block. + * @returns {Promise} The offset of the first audio frame. + * @throws {LuminaAudioPlayer.PlayerError} When the stream has more metadata blocks than the player accepts. + */ + async walkMetadataBlocksAsync(isStreamInfoLast, offset) { + let cursor = offset; + let isLast = isStreamInfoLast; + const end = this.reader.getLength(); + let blocks = 0; + while (!isLast && blocks < MAX_METADATA_BLOCKS) { + if (end !== null && cursor >= end) + return cursor; + const header = await this.reader.readAsync(cursor, 4); + if (header.length < 4) + return cursor; + // The same metadata block header as STREAMINFO: the last-block flag is the top bit of the first byte, and the next three bytes are the big endian body length. + isLast = (header[0] & 0x80) !== 0; + const length = LuminaAudioPlayer.demuxReadUintBE(header, 1, 3); + cursor += 4 + length; + blocks++; + } + if (!isLast) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The FLAC stream has more metadata blocks than the player accepts.', { reason: 'metadata-too-many' }); + return cursor; + } + + /** + * Reads the header of a frame at an offset. + * @param {number} offset - The offset of the frame. + * @returns {Promise} The parsed header, or null when the bytes are not a valid frame header. + */ + async parseHeaderAtAsync(offset) { + if (!this.streamInfo) + return null; + const bytes = await this.reader.readAsync(offset, FRAME_HEADER_WINDOW_BYTES); + if (bytes.length < 6) + return null; + return parseFrameHeader(bytes, 0, this.streamInfo); + } + + /** + * Scans for the next frame header consistent with the stream, starting at an offset. It is used from a distance, + * by a seek or a resynchronization, before the frame is walked exactly. + * @param {number} start - The offset to start the scan at. + * @param {number|null} end - The exclusive end of the scan, or null to scan to the end of the stream. + * @returns {Promise} The offset of the next frame header, or -1 when there is none. + * @throws {LuminaAudioPlayer.PlayerError} When the scan gives up on a corrupt or crafted region. + */ + async findNextFrameAsync(start, end) { + return await LuminaAudioPlayer.scanForFrameAsync(this.reader, start, end, FLAC_SYNC_PREFIX, async (offset) => { + const header = await this.parseHeaderAtAsync(offset); + return header !== null; + }, { prefixMask: FLAC_SYNC_MASK }); + } + + /** + * Rescans for the next frame after the current offset deviated from a frame boundary, so that a corrupted or + * partially downloaded region does not stop the stream. + * @returns {Promise} The offset of the next frame header, or -1 when there is none. + * @throws {LuminaAudioPlayer.PlayerError} When the scan gives up on a corrupt or crafted region. + */ + async resyncAsync() { + const end = this.reader.getLength(); + const next = await this.findNextFrameAsync(this.offset + 1, end); + if (next >= 0) + this.offset = next; + return next; + } + } + + LuminaAudioPlayer.FlacDemuxer = FlacDemuxer; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.FLAC, + codec: LuminaAudioPlayer.DemuxerCodec.FLAC, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.FLAC, + create: (options) => new FlacDemuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-mp3.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-mp3.js new file mode 100644 index 00000000..b5b7cd11 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-mp3.js @@ -0,0 +1,443 @@ +/** + * MP3 demuxer of the audio player. + * + * An MP3 file is a stream of MPEG audio frames, each one a self contained frame whose four byte header fully describes + * it: the MPEG version, the layer, the bitrate and the sample rate of the frame, so its length can be computed without + * reading it, and the number of samples it decodes to is fixed by the version and the layer. This demuxer walks those + * frames, hands each one to the decoder as an encoded packet, and derives the sample rate, the channel count and the + * duration from the headers themselves. + * + * The header, and what is read from it + * ------------------------------------ + * The header of a frame gives the MPEG version (MPEG-1, MPEG-2 or MPEG-2.5), the layer (I, II or III), the bitrate, the + * sample rate, whether the frame is padded, and the channel mode. From the version and the layer come the samples per + * frame (1152 for MPEG-1 Layer III, 576 for MPEG-2 or MPEG-2.5 Layer III, and so on), and from those, the bitrate and the + * sample rate comes the length of the frame, which is what makes the next frame directly addressable. Only Layer III is a + * stream the WebCodecs 'mp3' codec decodes, so a file that names another layer is refused as unsupported rather than + * handed to a decoder that cannot decode it, which routes it to server normalization. + * + * Encoder padding and seeking + * --------------------------- + * VBR MP3 files carry an extra, silent MPEG frame at the very start (the Xing/Info header) that holds the frame count, + * the byte count and a 100 entry table of percentage positions, or a VBRI header at a fixed offset instead. The Xing + * frame is not audio: the first real frame follows it, so this demuxer reads it for the duration and the seek table and + * skips it. Without a Xing or VBRI table the stream is assumed to be CBR and the duration is estimated from the file size + * and the bitrate of the first frame. Seeking without a table maps a time to a byte position through that same estimate, + * which is exact for CBR and approximate for a VBR file that lost its table; either way the demuxer then scans forward to + * the next real frame, so the byte it lands on is always a frame boundary. + * + * The codec private data + * ---------------------- + * The WebCodecs 'mp3' codec takes no description: each packet is a whole MPEG frame, header included, and the decoder + * reads the frame header itself. The configuration therefore carries only the codec string, the sample rate and the + * channel count. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The number of header bytes every MPEG frame starts with. + * @readonly + * @type {number} + */ + const MPEG_HEADER_BYTES = 4; + + /** + * The bitrates, in kbps, of the MPEG-1 and MPEG-2/MPEG-2.5 layers, indexed by the four bit bitrate index of the frame + * header. Index 0 is the free format, which this demuxer refuses, and index 15 is invalid and is never looked up. + * @readonly + * @type {Object>>} + */ + const BITRATES = Object.freeze({ + // MPEG-1, indexed by layer (1 = Layer III, 2 = Layer II, 3 = Layer I). + mpeg1: Object.freeze({ + 1: Object.freeze([0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]), + 2: Object.freeze([0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384]), + 3: Object.freeze([0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448]) + }), + // MPEG-2 and MPEG-2.5. + mpeg2: Object.freeze({ + 1: Object.freeze([0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]), + 2: Object.freeze([0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]), + 3: Object.freeze([0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256]) + }) + }); + + /** + * The sample rates, in Hz, indexed by the two bit sample rate index of the frame header, per MPEG version. + * @readonly + * @type {Object>} + */ + const SAMPLE_RATES = Object.freeze({ + mpeg1: Object.freeze([44100, 48000, 32000]), + mpeg2: Object.freeze([22050, 24000, 16000]), + mpeg25: Object.freeze([11025, 12000, 8000]) + }); + + /** + * The eleven bit frame sync of an MPEG audio frame, as the two byte prefix a scan matches on. The mask covers the + * three sync bits of the second byte, so a scan rejects a byte pattern that is not a sync by a comparison instead of + * by an awaited header parse, which matters because a scan's prefix is what decides how many candidates it validates. + * @readonly + * @type {Array} + */ + const MP3_SYNC_PREFIX = Object.freeze([0xFF, 0xE0]); + + /** + * The byte mask of {@link MP3_SYNC_PREFIX}, matching the eleven bit sync exactly. + * @readonly + * @type {Array} + */ + const MP3_SYNC_MASK = Object.freeze([0xFF, 0xE0]); + + /** + * Parses the four byte header of an MPEG audio frame. + * @param {Uint8Array} bytes - The bytes to read the header from. + * @param {number} offset - The offset of the first header byte. + * @returns {Object|null} The parsed header, or null when the bytes are not a valid frame header this demuxer supports. + */ + function parseMpegHeader(bytes, offset) { + if (!bytes || offset < 0 || offset + MPEG_HEADER_BYTES > bytes.length) + return null; + const first = bytes[offset]; + const second = bytes[offset + 1]; + const third = bytes[offset + 2]; + const fourth = bytes[offset + 3]; + // The header is a bit packed big endian structure: eleven sync bits (all ones), two version bits, two layer bits, + // a protection bit that is zero when a CRC follows, the four bit bitrate index and the two bit sample rate index + // in the third byte, a padding bit and a private bit, the two bit channel mode in the top of the fourth byte, and + // then the mode extension, the copyright and original bits and the emphasis. The fields this demuxer needs are + // extracted below, which is why the shifts and masks split the second, third and fourth bytes. + // The eleven bit frame sync is all ones; the two following bits are the version and the next two the layer. + if (first !== 0xFF || (second & 0xE0) !== 0xE0) + return null; + const versionBits = (second >> 3) & 0x03; + const layerBits = (second >> 1) & 0x03; + const bitrateIndex = (third >> 4) & 0x0F; + const sampleRateIndex = (third >> 2) & 0x03; + if (versionBits === 1 || layerBits === 0 || bitrateIndex === 0 || bitrateIndex === 15 || sampleRateIndex === 3) + return null; + const isMpeg1 = versionBits === 3; + const versionKey = isMpeg1 ? 'mpeg1' : 'mpeg2'; + const sampleRateKey = isMpeg1 ? 'mpeg1' : versionBits === 2 ? 'mpeg2' : 'mpeg25'; + const bitrate = BITRATES[versionKey][layerBits][bitrateIndex]; + const sampleRate = SAMPLE_RATES[sampleRateKey][sampleRateIndex]; + if (!bitrate || !sampleRate) + return null; + // Layer III decodes to 1152 samples on MPEG-1 and 576 on MPEG-2 and MPEG-2.5; Layer II always to 1152 and Layer I to 384. + let samplesPerFrame; + if (layerBits === 1) + samplesPerFrame = isMpeg1 ? 1152 : 576; + else if (layerBits === 2) + samplesPerFrame = 1152; + else + samplesPerFrame = 384; + const padding = (third >> 1) & 0x01; + // Layer I pads in four byte slots; the other layers pad in single byte slots. + const frameLength = layerBits === 3 + ? Math.floor((12 * bitrate * 1000) / sampleRate) * 4 + padding * 4 + : Math.floor(((samplesPerFrame / 8) * bitrate * 1000) / sampleRate) + padding; + if (!Number.isFinite(frameLength) || frameLength < MPEG_HEADER_BYTES) + return null; + const channelMode = (fourth >> 6) & 0x03; + const channels = channelMode === 3 ? 1 : 2; + return Object.freeze({ + version: versionBits, + layer: layerBits, + isMpeg1, + samplesPerFrame, + sampleRate, + bitrate, + channels, + frameLength, + crcProtected: (second & 0x01) === 0 + }); + } + + /** + * Demuxes an MP3 (MPEG Layer III) stream. + */ + class Mp3Demuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of Mp3Demuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.offset = 0; + this.dataStart = 0; + this.timelineMicros = 0; + /** @type {Object|null} */ + this.header = null; + this.durationSeconds = null; + this.reachedEnd = false; + /** @type {Uint8Array|null} */ + this.xingToc = null; + } + + //+=======================================================================================+ + //| Initialization | + //+=======================================================================================+ + + /** + * Reads the ID3v2 tag, the first MPEG frame with its Xing or VBRI metadata, and the duration they state, and + * positions the read cursor on the first real audio frame. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not an MP3 stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + const dataStart = await this.skipId3v2Async(0); + const end = this.reader.getLength(); + const firstFrame = await LuminaAudioPlayer.scanForFrameAsync(this.reader, dataStart, end, MP3_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: MP3_SYNC_MASK }); + if (firstFrame < 0) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The bytes do not contain an MPEG audio frame.', { reason: 'no-mpeg-frame' }); + const header = await this.parseHeaderAtAsync(firstFrame); + if (!header) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The MPEG frame header could not be parsed.', { reason: 'no-mpeg-frame' }); + if (header.layer !== 1) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The MPEG stream uses a layer the player does not decode.', { reason: 'unsupported-layer' }); + const metadata = await this.readVariableRateMetadataAsync(firstFrame, header); + this.dataStart = metadata ? firstFrame + header.frameLength : firstFrame; + this.offset = this.dataStart; + this.header = header; + this.durationSeconds = this.resolveDuration(header, metadata, end); + this.xingToc = metadata && metadata.toc ? metadata.toc : null; + this.timelineMicros = 0; + this.reachedEnd = false; + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.header) + return null; + return { + codec: 'mp3', + sampleRate: this.header.sampleRate, + numberOfChannels: this.header.channels + }; + } + + /** + * Gets the duration of the stream, from the Xing or VBRI frame count when there is one and from the file size + * otherwise. + * @returns {number|null} The duration in seconds, or null when it cannot be derived. + */ + getDuration() { + return this.durationSeconds; + } + + //+=======================================================================================+ + //| Reading | + //+=======================================================================================+ + + /** + * Reads the next MPEG frame as an encoded packet. A byte that is not the start of a valid frame is skipped by + * rescanning for the next frame sync, so a corrupted or partially downloaded region does not stop the stream. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + if (this.reachedEnd) + return null; + try { + const header = await this.parseHeaderAtAsync(this.offset); + if (!header) { + return await this.resyncAsync(); + } + const data = await this.reader.readAsync(this.offset, header.frameLength); + if (data.length < header.frameLength) { + // The last frame is incomplete, which is the end of a partially downloaded or truncated stream. + this.reachedEnd = true; + return null; + } + // The duration is kept unrounded while the timeline accumulates it, so that rounding it per packet does not + // make the timeline drift; only the packet the decoder receives carries a whole number of microseconds. + const duration = (header.samplesPerFrame / header.sampleRate) * 1000000; + const packet = LuminaAudioPlayer.createDemuxerPacket(data.slice(), this.timelineMicros, duration); + this.timelineMicros += duration; + this.offset += header.frameLength; + return packet; + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Rescans for the next valid frame after a byte that is not the start of one. + * @returns {Promise} The next packet, or null when no further frame is found. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async resyncAsync() { + const end = this.reader.getLength(); + const next = await LuminaAudioPlayer.scanForFrameAsync(this.reader, this.offset + 1, end, MP3_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: MP3_SYNC_MASK }); + if (next < 0) { + this.reachedEnd = true; + return null; + } + this.offset = next; + return await this.readPacketAsync(); + } + + /** + * Repositions the read cursor to the frame that covers a time, using the Xing table when the stream has one and + * the constant bitrate estimate otherwise, and then scanning to the next real frame. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a frame gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const end = this.reader.getLength(); + if (end === null || !Number.isFinite(seconds) || this.durationSeconds === null || this.durationSeconds <= 0) + return null; + const fraction = LuminaAudioPlayer.clamp(seconds / this.durationSeconds, 0, 1); + let estimate; + if (this.xingToc) { + const index = Math.min(99, Math.floor(fraction * 100)); + const byteFraction = this.xingToc[index] / 256; + estimate = this.dataStart + Math.floor(byteFraction * (end - this.dataStart)); + } else { + const bitrate = this.header ? this.header.bitrate * 1000 : 128000; + estimate = this.dataStart + Math.floor((seconds * bitrate) / 8); + } + const start = Math.max(this.dataStart, Math.min(end - 1, estimate)); + const frame = await LuminaAudioPlayer.scanForFrameAsync(this.reader, start, end, MP3_SYNC_PREFIX, (offset) => this.isValidFrameAtAsync(offset), { prefixMask: MP3_SYNC_MASK }); + if (frame < 0) + return null; + this.offset = frame; + this.reachedEnd = false; + // The exact sample position of the frame is not known without walking the stream from the start, so the + // timeline is seeded with the requested time, kept unrounded so the timeline it starts does not drift, and the + // seek stage uses it as the target to trim the first packet to. + this.timelineMicros = Math.max(0, seconds) * 1000000; + return frame; + } + + //+=======================================================================================+ + //| Internal helpers | + //+=======================================================================================+ + + /** + * Reads the header of a frame at an offset. + * @param {number} offset - The offset of the frame. + * @returns {Promise} The parsed header, or null when the bytes are not a valid frame header. + */ + async parseHeaderAtAsync(offset) { + const bytes = await this.reader.readAsync(offset, MPEG_HEADER_BYTES); + if (bytes.length < MPEG_HEADER_BYTES) + return null; + return parseMpegHeader(bytes, 0); + } + + /** + * Checks whether a candidate offset is the start of a real frame, by parsing its header and, unless it is the + * last frame of a known length stream, by requiring the frame that follows it to parse as well with the same + * version, layer and sample rate. That second frame is what rejects a byte pattern inside frame data. + * @param {number} offset - The candidate offset. + * @returns {Promise} True when the offset is the start of a real frame. + */ + async isValidFrameAtAsync(offset) { + const header = await this.parseHeaderAtAsync(offset); + if (!header || header.layer !== 1) + return false; + const end = this.reader.getLength(); + const next = offset + header.frameLength; + if (end !== null && next + MPEG_HEADER_BYTES > end) + return true; + const nextHeader = await this.parseHeaderAtAsync(next); + if (!nextHeader) + return false; + return nextHeader.version === header.version + && nextHeader.layer === header.layer + && nextHeader.sampleRate === header.sampleRate; + } + + /** + * Reads the Xing, Info or VBRI metadata of the first frame, when that frame is a metadata frame rather than audio. + * @param {number} frameStart - The offset of the first frame. + * @param {Object} header - The parsed header of the first frame. + * @returns {Promise} The metadata, with the frame count and the seek table, or null when the first frame is real audio. + */ + async readVariableRateMetadataAsync(frameStart, header) { + const crcBytes = header.crcProtected ? 2 : 0; + const sideInfoBytes = header.isMpeg1 ? (header.channels === 1 ? 17 : 32) : (header.channels === 1 ? 9 : 17); + // The Xing or Info tag sits right after the header and the side info; the VBRI tag sits at a fixed offset from + // the frame start. Both are read from one window so neither field is fetched twice. + const window = await this.reader.readAsync(frameStart, header.frameLength); + if (window.length < MPEG_HEADER_BYTES) + return null; + const xingOffset = MPEG_HEADER_BYTES + crcBytes + sideInfoBytes; + const isXing = LuminaAudioPlayer.demuxBytesEqualAscii(window, xingOffset, 'Xing') + || LuminaAudioPlayer.demuxBytesEqualAscii(window, xingOffset, 'Info'); + let cursor = -1; + if (isXing) + cursor = xingOffset + 4; + else if (LuminaAudioPlayer.demuxBytesEqualAscii(window, MPEG_HEADER_BYTES + 32, 'VBRI')) + cursor = MPEG_HEADER_BYTES + 32 + 4 + 2 + 2 + 2; + if (cursor < 0) + return null; + const isVbri = !isXing; + let frameCount = null; + let toc = null; + if (isVbri) // VBRI: bytes (4), frames (4), then a two entry-per-percent table this demuxer does not use. + frameCount = LuminaAudioPlayer.demuxReadUintBE(window, cursor + 4, 4); + else { + const flags = LuminaAudioPlayer.demuxReadUintBE(window, cursor, 4) || 0; + cursor += 4; + if ((flags & 0x01) !== 0) { + frameCount = LuminaAudioPlayer.demuxReadUintBE(window, cursor, 4); + cursor += 4; + } + if ((flags & 0x02) !== 0) // The byte count the tag may carry is not needed, but its four bytes still shift the seek table. + cursor += 4; + if ((flags & 0x04) !== 0) { + const raw = await this.reader.copyAsync(frameStart + cursor, 100); + if (raw.length === 100) + toc = raw; + } + } + return { frameCount, toc }; + } + + /** + * Resolves the duration of the stream from the metadata of its first frame, or from the file size and the first frame's bitrate when the stream carries no metadata. + * @param {Object} header - The parsed header of the first real frame. + * @param {Object|null} metadata - The Xing or VBRI metadata, or null. + * @param {number|null} end - The length of the stream, or null when it is unknown. + * @returns {number|null} The duration in seconds, or null when it cannot be derived. + */ + resolveDuration(header, metadata, end) { + if (metadata && Number.isFinite(metadata.frameCount) && metadata.frameCount > 0) + return (metadata.frameCount * header.samplesPerFrame) / header.sampleRate; + if (end === null) + return null; + const bytes = end - this.dataStart; + const bitrate = header.bitrate * 1000; + if (bitrate <= 0 || bytes <= 0) + return null; + return (bytes * 8) / bitrate; + } + } + + LuminaAudioPlayer.Mp3Demuxer = Mp3Demuxer; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.MP3, + codec: LuminaAudioPlayer.DemuxerCodec.MP3, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.MP3, + create: (options) => new Mp3Demuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-ogg.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-ogg.js new file mode 100644 index 00000000..00552480 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-ogg.js @@ -0,0 +1,1113 @@ +/** + * OGG demuxer of the audio player, for the Opus and Vorbis codecs. + * + * An OGG file is a sequence of pages, each one a header followed by a segment table and the page's data. The segmented + * data is not framed by bytes but by lacing: a run of lacing values of 255 means the packet continues, and a value below + * 255 ends a packet, so a packet may span several pages and a page may hold several packets. A page also carries a + * granule position, which is the position, in the codec's own sample unit, of the last packet that completed on the page, + * a serial number, so that several logical streams can be multiplexed into one physical stream, and a CRC-32 over the + * whole page, which this demuxer verifies so that a corrupt page, or a byte pattern that merely looks like a page + * capture, is never read as data. + * + * This module owns the page and packet assembly once, in the OggDemuxer base, and the two codec specific demuxers only + * describe their identification headers, the codec private data WebCodecs needs, and how a packet's duration is measured. + * The registry maps both the OGG/OPUS and the OGG/VORBIS pair to their demuxer. + * + * Telling the two apart + * --------------------- + * The first packet of the logical stream identifies the codec: it begins with 'OpusHead' for Opus and, for Vorbis, with + * a packet type byte of 0x01 followed by 'vorbis'. Everything after the identification header is a codec header packet + * (OpusTags for Opus, the comment and setup headers for Vorbis) that is not audio, and this demuxer consumes those during + * initialization, so the first packet readPacketAsync returns is audio. + * + * Timestamps and the granule position + * ----------------------------------- + * A granule is a count of samples for Vorbis and a count of 48 kHz samples, including the pre-skip the encoder inserted, + * for Opus. The page granule gives the end position of its last completed packet exactly, so this demuxer anchors the + * timeline to it at every page boundary and derives the packets that precede it, on the same page, by summing their own + * durations from the packed packet header (the table of contents byte of an Opus packet, the block size bit of a Vorbis + * packet). The pre-skip of an Opus stream is subtracted, because the WebCodecs decoder discards those priming samples + * itself when the description carries the OpusHead, so the first decoded sample is reported at time zero. + * + * Seeking + * ------- + * Page granule positions are non decreasing, so seeking is a bisection over the byte offsets of the stream: it reads the + * page at the middle of the search interval and narrows the interval by its granule, which converges to the first page + * whose granule is at or after the target in a logarithmic number of page reads, and never walks the stream. When that + * page carries the continuation flag, its first packet began on the previous page, so the seek steps back one page, whose + * exact end was verified, so that the packet is assembled from its true start. A seek never lands on a page of codec + * headers either: the cursor is brought forward to the first page that holds audio, and a page that still carries a header + * packet, which can happen when a setup header shares a page with audio, has that packet filtered out as well. + * + * The codec private data + * ---------------------- + * - Opus: the description is the OpusHead identification header, which also tells the decoder the pre-skip to discard. + * - Vorbis: the description is the Xiph extradata format the WebCodecs registration requires: a byte with the count of + * lacing values, the lacing values themselves, and then the identification, comment and setup header packets. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The four byte capture pattern every OGG page starts with. + * @readonly + * @type {Array} + */ + const OGG_CAPTURE_PATTERN = Object.freeze([0x4F, 0x67, 0x67, 0x53]); + + /** + * The number of bytes of an OGG page header, before the segment table. + * @readonly + * @type {number} + */ + const OGG_PAGE_HEADER_BYTES = 27; + + /** + * The offset of the CRC field of an OGG page header, which is zeroed while the checksum is computed. + * @readonly + * @type {number} + */ + const OGG_CRC_OFFSET = 22; + + /** + * The largest size a single OGG page can have: the fixed header, the largest segment table, and the largest payload + * the lacing values can describe. A candidate that claims more is not a page, and the bound is what keeps a crafted + * length field from making a scan read and checksum an arbitrarily large span. + * @readonly + * @type {number} + */ + const OGG_MAX_PAGE_BYTES = OGG_PAGE_HEADER_BYTES + 255 + 255 * 255; + + /** + * The number of candidate pages a single scan may read in full and checksum before it gives up. A stream whose body is + * filled with the capture pattern, with header fields crafted to pass the cheap structural checks, can surround a real + * page with thousands of false candidates; the cheap checks reject most of them, and this budget bounds the rest, so a + * scan can never be turned into unbounded checksum and allocation work. + * @readonly + * @type {number} + */ + const OGG_MAX_SCAN_VALIDATIONS = 1024; + + /** + * The number of pages a single seek may step back over when the page it landed on is a continuation of a packet that + * began earlier. A packet that spans this many pages is far past anything a real stream produces, so the bound only + * stops a pathological one; the shared validation budget of the seek bounds the work underneath it. + * @readonly + * @type {number} + */ + const OGG_MAX_CONTINUED_STEPS = 255; + + /** + * The number of bytes a single page lookup scans before it gives up. A valid stream has no gaps between pages, so the + * page at or after any offset starts within one page length of it; the bound keeps a stream whose middle is filled + * with the capture pattern from making one lookup walk an arbitrarily long region. + * @readonly + * @type {number} + */ + const OGG_SCAN_SPAN_BYTES = OGG_MAX_PAGE_BYTES * 2; + + /** + * The largest packet this demuxer will assemble. A packet may span any number of pages, and the parts of one are held + * until it is complete, so without a cap a crafted stream could make a single packet hold the whole stream in memory. + * The cap is far past any real audio packet of the supported codecs, so it only ever refuses a crafted one. + * @readonly + * @type {number} + */ + const OGG_MAX_PACKET_BYTES = 16 * 1024 * 1024; + + /** + * Draws one unit from a shared scan budget, reporting whether a unit was available. Every unit of work a seek does + * that is proportional to the bytes or the page patterns of the stream draws from the same budget: the window read + * that precedes a scan, each cheap header probe, and each full page validation. That is what keeps a crafted stream + * from multiplying the work of a seek by the number of its steps. + * @param {{ remaining: number }} budget - The shared budget. + * @returns {boolean} True when a unit was available and was consumed. + */ + function consumeBudget(budget) { + if (budget.remaining <= 0) + return false; + budget.remaining--; + return true; + } + + /** + * The number of bytes of the tail read to find the last page of a stream. + * @readonly + * @type {number} + */ + const OGG_TAIL_BYTES = 65536; + + /** + * The number of bytes read before a page to find the page that precedes it when a seek lands on a continued page. + * @readonly + * @type {number} + */ + const OGG_PREVIOUS_WINDOW_BYTES = 131072; + + /** + * The number of samples per second a granule of an Opus stream counts at, fixed by the Opus format. + * @readonly + * @type {number} + */ + const OPUS_GRANULE_RATE = 48000; + + /** + * The duration, in milliseconds, of one Opus frame per configuration number, indexed by the five bit configuration + * of the packet's table of contents byte (RFC 6716, table 2). + * @readonly + * @type {Array} + */ + const OPUS_FRAME_DURATION_MS = Object.freeze([ + 10, 20, 40, 60, 10, 20, 40, 60, 10, 20, 40, 60, + 10, 20, 10, 20, + 2.5, 5, 10, 20, 2.5, 5, 10, 20, 2.5, 5, 10, 20, 2.5, 5, 10, 20 + ]); + + /** + * The header type flag of an OGG page that marks a continued packet. + * @readonly + * @type {number} + */ + const OGG_CONTINUED_FLAG = 0x01; + + /** + * The lookup table of the OGG page checksum, built once for the life of the page. It turns the checksum from eight + * bit iterations to one byte lookup per byte of a page. + * @readonly + * @type {Uint32Array} + */ + const OGG_CRC_TABLE = LuminaAudioPlayer.demuxBuildCrcTable(0x04C11DB7, 32); + + /** + * Computes the CRC-32 of an OGG page, with the polynomial 0x04C11DB7 and an initial value of zero, over the page + * with its CRC field read as zero, as the framing specification defines it. The zeroed field is passed as a range + * rather than applied to a copy, so a page is never duplicated just to compute its checksum. + * @param {Uint8Array} bytes - The page bytes. + * @param {number} [zeroStart] - The first byte of the field to read as zero, or -1 for none. + * @param {number} [zeroLength] - The number of bytes of the field to read as zero. + * @returns {number} The checksum. + */ + function computeOggCrc(bytes, zeroStart = -1, zeroLength = 0) { + const zeroEnd = zeroStart + zeroLength; + let crc = 0; + for (let index = 0; index < bytes.length; index++) { + const byte = index >= zeroStart && index < zeroEnd ? 0 : bytes[index]; + crc = ((crc << 8) ^ OGG_CRC_TABLE[((crc >>> 24) ^ byte) & 0xFF]) >>> 0; + } + return crc >>> 0; + } + + /** + * Demuxes an OGG logical stream, owning the page and packet assembly and leaving the codec specifics to a subclass. + */ + class OggDemuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of OggDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.pageOffset = 0; + this.currentSerial = null; + // The offset of the last page read from the logical stream, and the offset of the first page that holds audio. + this.lastPageOffset = null; + this.audioStartOffset = null; + /** @type {Array} */ + this.pendingParts = []; + // The number of bytes the parts of the packet being assembled hold, so the assembled packet size is bounded without having to concatenate them first. + this.pendingLength = 0; + /** @type {Array<{ data: Uint8Array, granule: number|null }>} */ + this.pendingPackets = []; + this.lastGranule = null; + this.durationSeconds = null; + // True once the duration was taken from the last page, so that the granule of an intermediate page, which is + // the position reached and not the length of the stream, never overwrites it. + this.durationIsFinal = false; + this.reachedEnd = false; + this.seekResync = false; + this.timelineMicros = 0; + } + + //+=======================================================================================+ + //| Reading | + //+=======================================================================================+ + + /** + * Reads the next packet of the logical stream, assembling it across pages when it spans them. + * @returns {Promise<{ data: Uint8Array, granule: number|null }|null>} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the page structure is corrupt. + */ + async readRawPacketAsync() { + while (this.pendingPackets.length === 0) { + if (this.reachedEnd) + return null; + await this.readNextPageAsync(); + } + return this.pendingPackets.shift(); + } + + /** + * Reads the next audio packet of the logical stream as a demuxer packet, skipping any codec header packet it + * meets. Initialization consumes the header packets of a stream once, but a seek may reposition the read cursor + * onto a page that also carries them, so they are filtered here as well rather than only during initialization. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the page structure is corrupt. + */ + async readNextAudioPacketAsync() { + let packet = await this.readRawPacketAsync(); + while (packet && this.isHeaderPacket(packet.data)) + packet = await this.readRawPacketAsync(); + if (!packet) + return null; + const duration = this.computePacketDurationMicros(packet.data); + const timestamp = packet.granule !== null + ? Math.max(0, this.granuleToMicros(packet.granule) - duration) + : this.timelineMicros; + this.timelineMicros = timestamp + duration; + return LuminaAudioPlayer.createDemuxerPacket(packet.data, timestamp, duration); + } + + /** + * Reads the next page and turns its lacing values into queued packets, carrying a packet that spans pages over to the next one. + * @returns {Promise} A promise resolving when the page was consumed. + * @throws {LuminaAudioPlayer.PlayerError} When the page structure is corrupt. + */ + async readNextPageAsync() { + const page = await this.readPageAsync(this.pageOffset); + if (!page) { + this.reachedEnd = true; + return; + } + this.pageOffset = page.nextOffset; + if (this.currentSerial === null) + this.currentSerial = page.serial; + // A physical stream can multiplex several logical streams; only the one this demuxer locked onto is read. + if (page.serial !== this.currentSerial) + return; + this.lastPageOffset = page.offset; + if (page.granule !== null) { + this.lastGranule = page.granule; + // Only an unknown length is tracked from page to page; when the last page was already probed, the granule + // of an intermediate page would replace the total with the position reached so far. + if (!this.durationIsFinal) + this.refreshDuration(); + } + const isContinued = (page.headerType & OGG_CONTINUED_FLAG) !== 0; + if (isContinued !== (this.pendingParts.length > 0)) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG page continuation flags do not line up.', { reason: 'invalid-continuation' }); + const completions = []; + let dataOffset = 0; + // The segment table is a list of lacing values. A value of 255 means the packet continues into the next + // segment, and possibly the next page, while any value below 255 ends the packet it belongs to, so a packet + // completes exactly when such a value is reached. + for (const lace of page.segments) { + const slice = page.data.subarray(dataOffset, dataOffset + lace); + dataOffset += lace; + this.pendingParts.push(slice); + this.pendingLength += lace; + if (lace < 255) { + completions.push(LuminaAudioPlayer.concatDemuxerBytes(this.pendingParts)); + this.pendingParts = []; + this.pendingLength = 0; + } + } + // A packet can span any number of pages, and its parts are held until it completes, so its size is bounded here + // rather than left to whatever the stream claims. + if (this.pendingLength > OGG_MAX_PACKET_BYTES) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG packet being assembled exceeds the size the player accepts.', { reason: 'packet-too-large' }); + const lastCompletion = completions.length - 1; + for (let index = 0; index < completions.length; index++) + this.pendingPackets.push({ data: completions[index], granule: index === lastCompletion ? page.granule : null }); + } + + /** + * Reads and validates the fixed part of a page header, without reading the segment table or the payload. It is the + * cheap structural gate a scan runs on every capture pattern: the version and the reserved header type bits reject + * a false capture before any page sized buffer is allocated or any checksum computed. The page size bound depends + * on the lacing values, so it can only be enforced once the segment table is read, in {@link LuminaAudioPlayer.OggDemuxer#finishPageAsync}. + * @param {number} offset - The offset of the candidate capture pattern. + * @returns {Promise} An object with a kind of 'page', 'not-a-page' or 'unsupported-version', and, for a page, the parsed header fields. + */ + async readPageHeaderAsync(offset) { + if (offset < 0) + return { kind: 'not-a-page' }; + const header = await this.reader.readAsync(offset, OGG_PAGE_HEADER_BYTES); + if (header.length < OGG_PAGE_HEADER_BYTES || !LuminaAudioPlayer.demuxBytesEqualAscii(header, 0, 'OggS')) + return { kind: 'not-a-page' }; + if (header[4] !== 0) + return { kind: 'unsupported-version' }; + // Only the three defined header type flags may be set; any other bit is reserved, which marks a false capture. + if ((header[5] & 0xF8) !== 0) + return { kind: 'not-a-page' }; + // The fixed part of a page header is the four byte capture pattern, one byte version, one byte header type + // flags, the eight byte granule position, the four byte serial, the four byte sequence number, the four byte + // checksum and one byte segment count; the segment table and the payload follow it. + return { + kind: 'page', + headerType: header[5], + granule: LuminaAudioPlayer.demuxReadInt64LE(header, 6), + serial: LuminaAudioPlayer.demuxReadUintLE(header, 14, 4), + storedCrc: LuminaAudioPlayer.demuxReadUintLE(header, OGG_CRC_OFFSET, 4), + pageSegments: header[26] + }; + } + + /** + * Reads and validates one OGG page, including its CRC-32. + * @param {number} offset - The offset of the page's capture pattern. + * @param {Object} [options] - The options. + * @param {boolean} [options.strict] - True to treat a checksum mismatch or an unsupported version as a failure; false to report it as 'not a page'. Defaults to true, and a probe or a scan uses false. + * @param {number|null} [options.serial] - The serial a page must carry to be accepted, or null to accept any. A scan passes the serial of its logical stream. + * @returns {Promise} The page, or null at the end of the stream, at a truncated page, or at a page a non strict read refused. + * @throws {LuminaAudioPlayer.PlayerError} When a strict read finds an unsupported version or a checksum mismatch. + */ + async readPageAsync(offset, options = {}) { + const strict = options.strict !== false; + const probe = await this.readPageHeaderAsync(offset); + if (probe.kind === 'not-a-page') + return null; + if (probe.kind === 'unsupported-version') { + if (!strict) + return null; + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG page uses an unsupported version.', { reason: 'unsupported-ogg-version' }); + } + if (options.serial !== undefined && options.serial !== null && probe.serial !== options.serial) + return null; + return await this.finishPageAsync(offset, probe, strict); + } + + /** + * Reads the segment table and the payload of a page whose header a caller already validated, computes the + * checksum over the page with its own CRC field read as zero, and returns the page. The data a page carries is + * exposed as a view of the one buffer that was read, so validating a page allocates a single page sized buffer. + * @param {number} offset - The offset of the page's capture pattern. + * @param {Object} probe - The parsed header, per {@link LuminaAudioPlayer.OggDemuxer#readPageHeaderAsync}. + * @param {boolean} strict - True to treat a checksum mismatch as a failure, false to report it as 'not a page'. + * @returns {Promise} The page, or null when it is truncated or refused. + * @throws {LuminaAudioPlayer.PlayerError} When a strict read finds a checksum mismatch. + */ + async finishPageAsync(offset, probe, strict) { + const segmentTable = await this.reader.readAsync(offset + OGG_PAGE_HEADER_BYTES, probe.pageSegments); + if (segmentTable.length < probe.pageSegments) + return null; + let dataLength = 0; + for (let index = 0; index < probe.pageSegments; index++) + dataLength += segmentTable[index]; + // The length is bounded by the page structure itself: at most 255 lacing values of at most 255 bytes each, so it can never exceed OGG_MAX_PAGE_BYTES and needs no separate check. + const totalLength = OGG_PAGE_HEADER_BYTES + probe.pageSegments + dataLength; + const pageBytes = await this.reader.copyAsync(offset, totalLength); + if (pageBytes.length < totalLength) + return null; + if (computeOggCrc(pageBytes, OGG_CRC_OFFSET, 4) !== (probe.storedCrc >>> 0)) { + if (!strict) + return null; + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG page checksum does not match.', { reason: 'page-crc-mismatch' }); + } + return Object.freeze({ + offset, + headerType: probe.headerType, + granule: probe.granule !== null && probe.granule >= 0 ? probe.granule : null, + serial: probe.serial, + segments: segmentTable.slice(), + data: pageBytes.subarray(OGG_PAGE_HEADER_BYTES + probe.pageSegments), + nextOffset: offset + totalLength + }); + } + + /** + * Finds the first page whose capture pattern is at or after an offset and before a limit, skipping a pattern that + * is not a valid page. A candidate is filtered by the cheap structural gate first, and only a candidate that + * passes it is read in full and checksummed, drawing from the caller's budget, so that a whole seek shares one + * bound instead of giving each of its steps a fresh one. + * @param {number} offset - The offset to start the search at. + * @param {number|null} [limit] - The exclusive end of the search, or null to search to the end of the stream. + * @param {{ remaining: number }} [budget] - The shared validation budget, or null for a fresh one. + * @returns {Promise} The page, or null when there is none before the limit. + * @throws {LuminaAudioPlayer.PlayerError} When the scan gives up on a corrupt or crafted region. + */ + async findPageAtOrAfterAsync(offset, limit, budget) { + const end = this.reader.getLength(); + let scanLimit; + if (limit === null || limit === undefined) + scanLimit = end; + else + scanLimit = end === null ? limit : Math.min(limit, end); + const shared = budget || { remaining: OGG_MAX_SCAN_VALIDATIONS }; + // The scan itself reads a window, so it draws a unit before it does anything. + if (!consumeBudget(shared)) + return null; + let cursor = Math.max(0, Math.floor(offset)); + // A capture pattern that turns out not to be a valid page is skipped and the search resumes just past it, so + // the loop repeats until a page is accepted or the cursor reaches the end of the search limit. + while (scanLimit === null || cursor < scanLimit) { + const found = await LuminaAudioPlayer.scanForFrameAsync(this.reader, cursor, scanLimit, OGG_CAPTURE_PATTERN, async (candidate) => { + // A cheap header probe is a unit of work too, so a stream whose body is tiled with capture patterns + // that fail the gate cannot make a seek do an unbounded number of probes. + if (!consumeBudget(shared)) + return false; + const probe = await this.readPageHeaderAsync(candidate); + return probe.kind === 'page' && (this.currentSerial === null || probe.serial === this.currentSerial); + }); + if (found < 0) + return null; + if (!consumeBudget(shared)) + return null; + const page = await this.readPageAsync(found, { strict: false, serial: this.currentSerial }); + if (page) + return page; + cursor = found + 1; + } + return null; + } + + /** + * Finds the page that ends exactly at an offset, used to step back over a continued packet. Each candidate is + * filtered by the cheap structural gate, and the full reads draw from the caller's shared budget. + * @param {number} offset - The offset a page ends at. + * @param {{ remaining: number }} [budget] - The shared validation budget, or null for a fresh one. + * @returns {Promise} The preceding page, or null when it cannot be found. + */ + async findPreviousPageAsync(offset, budget) { + const start = Math.max(0, offset - OGG_PREVIOUS_WINDOW_BYTES); + if (offset <= start) + return null; + const shared = budget || { remaining: OGG_MAX_SCAN_VALIDATIONS }; + // The window read is a unit of work, so it draws one before it is done. + if (!consumeBudget(shared)) + return null; + const bytes = await this.reader.copyAsync(start, offset - start); + for (let index = bytes.length - OGG_CAPTURE_PATTERN.length; index >= 0; index--) { + if (!LuminaAudioPlayer.demuxBytesEqualAscii(bytes, index, 'OggS')) + continue; + const candidateOffset = start + index; + if (!consumeBudget(shared)) + return null; + const probe = await this.readPageHeaderAsync(candidateOffset); + if (probe.kind !== 'page' || (this.currentSerial !== null && probe.serial !== this.currentSerial)) + continue; + if (!consumeBudget(shared)) + return null; + const candidate = await this.finishPageAsync(candidateOffset, probe, false); + if (candidate && candidate.nextOffset === offset) + return candidate; + } + return null; + } + + //+=======================================================================================+ + //| Duration | + //+=======================================================================================+ + + /** + * Gets the duration of the logical stream. When the total length of the stream is known, it is the exact duration, + * taken from the granule of the last page. When the length is unknown, it is a progressive estimate from the granule + * of the last page read so far, so it grows as more of the stream is read and is only final once the last page has + * been seen; durationIsFinal reports which of the two it is. + * @returns {number|null} The duration in seconds, or null when no page with a granule has been read yet. + */ + getDuration() { + return this.durationSeconds; + } + + /** + * Refreshes the known duration from the last granule read. + */ + refreshDuration() { + if (this.lastGranule === null) + return; + const micros = this.granuleToMicros(this.lastGranule); + if (Number.isFinite(micros) && micros >= 0) + this.durationSeconds = micros / 1000000; + } + + /** + * Reads the granule position of the last page of the stream, when the length of the stream is known. It is what + * gives the duration before the end of the stream is reached. A candidate is filtered by the cheap structural gate + * first, and only a candidate that passes it is read in full and checksummed; the tail is bounded, and the cheap + * probes and the full validations both draw from one budget, so a tail filled with the capture pattern cannot turn + * this into unbounded work. + * @returns {Promise} The last granule, or null when it cannot be read. + */ + async probeLastGranuleAsync() { + const tail = await this.reader.readTailAsync(OGG_TAIL_BYTES); + if (!tail) + return null; + const bytes = tail.bytes; + const budget = { remaining: OGG_MAX_SCAN_VALIDATIONS }; + for (let index = bytes.length - OGG_CAPTURE_PATTERN.length; index >= 0; index--) { + if (!LuminaAudioPlayer.demuxBytesEqualAscii(bytes, index, 'OggS')) + continue; + const offset = tail.offset + index; + if (!consumeBudget(budget)) + return null; + const probe = await this.readPageHeaderAsync(offset); + if (probe.kind !== 'page' || (this.currentSerial !== null && probe.serial !== this.currentSerial)) + continue; + if (!consumeBudget(budget)) + return null; + const candidate = await this.finishPageAsync(offset, probe, false); + if (candidate && candidate.granule !== null) { + this.currentSerial = candidate.serial; + return candidate.granule; + } + } + return null; + } + + //+=======================================================================================+ + //| Seeking | + //+=======================================================================================+ + + /** + * Repositions the read cursor to the page that holds a time. Page granule positions are non decreasing, so the + * offset of the first page that ends at or after the target is found by a lower bound binary search over byte + * offsets: each step reads the page at or after the middle of the search interval and narrows it by whether that + * page already reaches the target. Every step shares one validation budget, and each page lookup only scans a + * bounded span, so the whole seek is bounded even against a stream whose middle is filled with the capture pattern. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + * @throws {LuminaAudioPlayer.PlayerError} When the scan for a page gives up on a corrupt or crafted region. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const end = this.reader.getLength(); + if (end === null || !Number.isFinite(seconds) || seconds < 0) + return null; + // The target is clamped to the duration only when that duration is final. While the total length of the stream + // is unknown, the duration is a progressive estimate from the pages read so far, and clamping to it would land + // the seek short of the requested time; without a clamp the binary search positions on the granules themselves. + const targetMicros = this.durationIsFinal && this.durationSeconds > 0 + ? Math.min(seconds, this.durationSeconds) * 1000000 + : seconds * 1000000; + // One budget for the whole seek, shared by the binary search and the step back over a continued packet. + const budget = { remaining: OGG_MAX_SCAN_VALIDATIONS }; + let low = 0; + let high = end - 1; + let iterations = 0; + while (low < high && iterations < 64 && budget.remaining > 0) { + iterations++; + const middle = Math.floor((low + high) / 2); + const page = await this.findPageAtOrAfterAsync(middle, Math.min(end, middle + OGG_SCAN_SPAN_BYTES), budget); + // A page that is missing past the last page start means the interval is past the end, which counts as + // reaching the target, so the lower bound narrows onto the last page rather than running past it. + const reachesTarget = page === null || (page.granule !== null && this.granuleToMicros(page.granule) >= targetMicros); + if (reachesTarget) + high = middle; + else + low = middle + 1; + } + let result = await this.findPageAtOrAfterAsync(low, Math.min(end, low + OGG_SCAN_SPAN_BYTES), budget); + if (!result) + result = await this.findPageAtOrAfterAsync(0, Math.min(end, OGG_SCAN_SPAN_BYTES), budget); + if (!result) + return null; + // A seek must never land on a page of codec headers: the identification, comment and setup packets are not + // audio, so the cursor is brought forward to the first page that holds audio. + if (this.audioStartOffset !== null && result.offset < this.audioStartOffset) { + const firstAudioPage = await this.findPageAtOrAfterAsync(this.audioStartOffset, Math.min(end, this.audioStartOffset + OGG_SCAN_SPAN_BYTES), budget); + if (firstAudioPage) + result = firstAudioPage; + } + // A continued page starts in the middle of a packet, so the walk steps back over every continued page until it + // reaches the page that actually starts the packet, so a packet that spans more than two pages is assembled + // from its true start. The walk is allowed to cross the first page that holds audio, because a large setup + // header can continue into that page, and the codec header packets it would then read there are filtered out + // on the read path by isHeaderPacket, so crossing can never re-emit a header as audio. + let steps = 0; + while ((result.headerType & OGG_CONTINUED_FLAG) !== 0 && steps < OGG_MAX_CONTINUED_STEPS) { + const previous = await this.findPreviousPageAsync(result.offset, budget); + if (!previous) + break; + result = previous; + steps++; + } + this.pageOffset = result.offset; + this.pendingPackets = []; + this.pendingParts = []; + this.pendingLength = 0; + this.reachedEnd = false; + // The page granule gives the end of its last completed packet; the packets before it on the page are placed by + // the seek resync, once the page was read, so they are all emitted with an absolute, correct timeline. + this.seekResync = true; + return result.offset; + } + + /** + * Prepares the first page read after a seek, so that every packet of that page is emitted with an absolute + * timestamp derived from the page granule rather than from the requested time. It reads the page when the queue is + * empty and sets the timeline so that the page's last audio packet ends at its granule. The page duration is + * measured without touching any per packet state, so the packets are then emitted with the very same durations + * they were measured with. + * @returns {Promise} A promise resolving when the timeline is set. + */ + async prepareAfterSeekAsync() { + this.seekResync = false; + if (this.pendingPackets.length === 0) + await this.readNextPageAsync(); + const packets = this.pendingPackets; + if (packets.length === 0) + return; + const total = this.measurePacketsDurationMicros(packets); + // The granule of the last audio packet of the page is the page's granule; a header packet that shares the page does not carry it. + let granule = null; + for (let index = packets.length - 1; index >= 0; index--) { + if (!this.isHeaderPacket(packets[index].data)) { + granule = packets[index].granule; + break; + } + } + this.timelineMicros = granule !== null + ? Math.max(0, this.granuleToMicros(granule) - total) + : Math.max(0, this.timelineMicros); + } + + //+=======================================================================================+ + //| Abstract surface | + //+=======================================================================================+ + + /** + * Gets the duration, in microseconds, of one packet of this codec. A codec must implement it: the base throws, + * because a default of zero would freeze the timeline of the codec that forgot to override it, and the failure + * would be silent. + * @param {Uint8Array} data - The packet bytes. + * @returns {number} The duration in microseconds. + * @throws {LuminaAudioPlayer.PlayerError} When the codec does not implement it. + */ + computePacketDurationMicros(data) { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This OGG demuxer does not implement computePacketDurationMicros.'); + } + + /** + * Converts a granule position to a media time, in microseconds. A codec must implement it: the base throws, + * because the raw granule is in the codec's own sample unit and is not a media time, so a default that returned it + * unchanged would report a wrong timeline for the codec that forgot to override it. + * @param {number} granule - The granule position. + * @returns {number} The media time in microseconds. + * @throws {LuminaAudioPlayer.PlayerError} When the codec does not implement it. + */ + granuleToMicros(granule) { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This OGG demuxer does not implement granuleToMicros.'); + } + + /** + * Records the offset of the first page that holds audio, once every codec header packet was consumed. It is what + * keeps a seek from landing on a page of identification or comment headers and emitting them as audio. + * @returns {void} + */ + beginAudio() { + this.audioStartOffset = this.pendingPackets.length > 0 ? this.lastPageOffset : this.pageOffset; + } + + /** + * Releases the queued packet state of the demuxer when it is destroyed, so a torn down stream does not keep the pages it had already read alive. + * @returns {void} + */ + onDestroy() { + this.pendingPackets = []; + this.pendingParts = []; + this.pendingLength = 0; + } + + /** + * Checks whether a packet is a codec header packet rather than audio, so that a page that carries headers, which + * a seek can land on, does not emit them. The default is that every packet is audio. + * @param {Uint8Array} data - The packet bytes. + * @returns {boolean} True when the packet is a codec header. + */ + isHeaderPacket(data) { + return false; + } + + /** + * Measures the total duration, in microseconds, of a list of packets, without advancing any per packet state, so + * that measuring a page never disturbs the state the packets are then emitted with. A codec must implement it + * together with computePacketDurationMicros, because the base throws rather than defaulting to a loop that calls + * computePacketDurationMicros directly: for a codec whose packet duration depends on the packet before it, that + * loop mutates the state, so the first page after a seek would then be emitted with the durations the measurement + * left behind rather than the ones it measured. + * @param {Array<{ data: Uint8Array, granule: number|null }>} packets - The packets to measure. + * @returns {number} The total duration in microseconds. + * @throws {LuminaAudioPlayer.PlayerError} When the codec does not implement it. + */ + measurePacketsDurationMicros(packets) { + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'This OGG demuxer does not implement measurePacketsDurationMicros.'); + } + } + + /** + * Computes the number of samples one Opus packet decodes to, from its table of contents byte. + * @param {Uint8Array} data - The Opus packet. + * @returns {number} The number of samples at 48 kHz. + */ + function getOpusPacketSamples(data) { + if (!data || data.length < 1) + return 0; + const toc = data[0]; + // The table of contents byte is a five bit configuration, which selects the frame duration, and a two bit code, which states how many frames the packet holds. + const config = toc >> 3; + const code = toc & 0x03; + let frameCount; + if (code === 0) + frameCount = 1; + else if (code === 1 || code === 2) + frameCount = 2; + else { + if (data.length < 2) + return 0; + frameCount = data[1] & 0x3F; + if (frameCount <= 0) + return 0; + } + const frameMilliseconds = OPUS_FRAME_DURATION_MS[config]; + if (!Number.isFinite(frameMilliseconds)) + return 0; + return Math.round(frameMilliseconds * OPUS_GRANULE_RATE / 1000) * frameCount; + } + + /** + * Builds the Xiph extradata of a Vorbis stream: the count of lacing values, the lacing values, and the three header packets, in order. + * @param {Array} packets - The identification, comment and setup header packets. + * @returns {Uint8Array|null} The extradata, or null when the headers are too large to be laced into a single byte count. + */ + function buildXiphExtradata(packets) { + const lacing = []; + for (const packet of packets) { + let length = packet.length; + while (length >= 255) { + lacing.push(255); + length -= 255; + } + lacing.push(length); + } + if (lacing.length > 255) + return null; + const total = 1 + lacing.length; + let payload = 0; + for (const packet of packets) + payload += packet.length; + const result = new Uint8Array(total + payload); + result[0] = lacing.length; + for (let index = 0; index < lacing.length; index++) + result[1 + index] = lacing[index]; + let offset = total; + for (const packet of packets) { + result.set(packet, offset); + offset += packet.length; + } + return result; + } + + /** + * Demuxes an OGG Opus stream. + */ + class OggOpusDemuxer extends OggDemuxer { + /** + * Creates an instance of OggOpusDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + /** @type {Uint8Array|null} */ + this.description = null; + this.preSkip = 0; + this.channels = 0; + } + + /** + * Reads the OpusHead and the OpusTags packets and positions the read cursor on the first audio packet. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not an OGG Opus stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + this.pageOffset = 0; + this.pendingParts = []; + this.pendingLength = 0; + this.pendingPackets = []; + this.currentSerial = null; + const head = await this.readRawPacketAsync(); + if (!head || !LuminaAudioPlayer.demuxBytesEqualAscii(head.data, 0, 'OpusHead')) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG stream is not an Opus stream.', { reason: 'no-opus-head' }); + if (head.data.length < 19) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OpusHead packet is too short.', { reason: 'invalid-opus-head' }); + this.channels = head.data[9]; + this.preSkip = LuminaAudioPlayer.demuxReadIntLE(head.data, 10, 2) || 0; + if (this.channels <= 0) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OpusHead packet names no channels.', { reason: 'invalid-opus-head' }); + this.description = head.data.slice(); + // The mapping requires the OpusTags comment packet after the identification header; any further packet is audio. + const tags = await this.readRawPacketAsync(); + if (tags && !LuminaAudioPlayer.demuxBytesEqualAscii(tags.data, 0, 'OpusTags')) + // A stream that skips its comment packet is malformed, but the packet is kept so it is not lost. + this.pendingPackets.unshift(tags); + const lastGranule = await this.probeLastGranuleAsync(); + if (lastGranule !== null) { + this.lastGranule = lastGranule; + this.durationIsFinal = true; + this.refreshDuration(); + } + this.beginAudio(); + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.description) + return null; + return { + codec: 'opus', + sampleRate: OPUS_GRANULE_RATE, + numberOfChannels: this.channels, + description: this.description + }; + } + + /** + * Checks whether a packet is one of the Opus header packets, which are not audio. + * @param {Uint8Array} data - The packet bytes. + * @returns {boolean} True when the packet is the identification or the comment header. + */ + isHeaderPacket(data) { + return LuminaAudioPlayer.demuxBytesEqualAscii(data, 0, 'OpusHead') + || LuminaAudioPlayer.demuxBytesEqualAscii(data, 0, 'OpusTags'); + } + + /** + * Reads the next Opus audio packet. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + try { + if (this.seekResync) + await this.prepareAfterSeekAsync(); + return await this.readNextAudioPacketAsync(); + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Gets the duration, in microseconds, of one Opus packet. + * @param {Uint8Array} data - The packet bytes. + * @returns {number} The duration in microseconds. + */ + computePacketDurationMicros(data) { + return LuminaAudioPlayer.samplesToMicroseconds(getOpusPacketSamples(data), OPUS_GRANULE_RATE); + } + + /** + * Measures the total duration of a list of Opus packets. An Opus packet's duration is self contained, so summing + * the per packet durations touches no state and is exact. + * @param {Array<{ data: Uint8Array, granule: number|null }>} packets - The packets to measure. + * @returns {number} The total duration in microseconds. + */ + measurePacketsDurationMicros(packets) { + let total = 0; + for (const packet of packets) { + if (this.isHeaderPacket(packet.data)) + continue; + total += this.computePacketDurationMicros(packet.data); + } + return total; + } + + /** + * Converts an Opus granule position to a media time, subtracting the pre-skip the decoder discards. + * @param {number} granule - The granule position. + * @returns {number} The media time in microseconds. + */ + granuleToMicros(granule) { + return LuminaAudioPlayer.samplesToMicroseconds(Math.max(0, granule - this.preSkip), OPUS_GRANULE_RATE); + } + } + + /** + * Demuxes an OGG Vorbis stream. + */ + class OggVorbisDemuxer extends OggDemuxer { + /** + * Creates an instance of OggVorbisDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + /** @type {Uint8Array|null} */ + this.description = null; + this.channels = 0; + this.sampleRate = 0; + this.blockSizes = [0, 0]; + this.lastBlockSize = null; + } + + /** + * Reads the identification, comment and setup header packets and positions the read cursor on the first audio packet. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not an OGG Vorbis stream. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + this.pageOffset = 0; + this.pendingParts = []; + this.pendingLength = 0; + this.pendingPackets = []; + this.currentSerial = null; + const identification = await this.readRawPacketAsync(); + if (!identification || identification.data.length < 30 + || identification.data[0] !== 0x01 + || !LuminaAudioPlayer.demuxBytesEqualAscii(identification.data, 1, 'vorbis')) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The OGG stream is not a Vorbis stream.', { reason: 'no-vorbis-identification' }); + this.channels = identification.data[11]; + this.sampleRate = LuminaAudioPlayer.demuxReadUintLE(identification.data, 12, 4) || 0; + // The block size byte of the identification header holds the two base-two exponents of the short and the long block size, one per nibble, so the sizes themselves are powers of two. + const blockSizeByte = identification.data[28]; + this.blockSizes = [1 << (blockSizeByte & 0x0F), 1 << ((blockSizeByte >> 4) & 0x0F)]; + if (this.channels <= 0 || this.sampleRate <= 0 || this.blockSizes[0] < 16 || this.blockSizes[1] < this.blockSizes[0]) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The Vorbis identification header is invalid.', { reason: 'invalid-vorbis-identification' }); + const comment = await this.readRawPacketAsync(); + const setup = await this.readRawPacketAsync(); + if (!comment || !setup) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The Vorbis stream is missing its header packets.', { reason: 'missing-vorbis-headers' }); + const description = buildXiphExtradata([identification.data, comment.data, setup.data]); + if (!description) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The Vorbis header packets are too large for the codec private data format.', { reason: 'vorbis-headers-too-large' }); + this.description = description; + const lastGranule = await this.probeLastGranuleAsync(); + if (lastGranule !== null) { + this.lastGranule = lastGranule; + this.durationIsFinal = true; + this.refreshDuration(); + } + this.lastBlockSize = null; + this.beginAudio(); + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream, including the required Vorbis description. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.description) + return null; + return { + codec: 'vorbis', + sampleRate: this.sampleRate, + numberOfChannels: this.channels, + description: this.description + }; + } + + /** + * Checks whether a packet is one of the three Vorbis header packets, which are not audio. + * @param {Uint8Array} data - The packet bytes. + * @returns {boolean} True when the packet is the identification, comment or setup header. + */ + isHeaderPacket(data) { + if (!data || data.length < 7) + return false; + const type = data[0]; + return (type === 0x01 || type === 0x03 || type === 0x05) && LuminaAudioPlayer.demuxBytesEqualAscii(data, 1, 'vorbis'); + } + + /** + * Measures the total duration of a list of Vorbis packets without touching the block size state, so that the + * durations the packets are then emitted with are exactly the ones they were measured with. + * @param {Array<{ data: Uint8Array, granule: number|null }>} packets - The packets to measure. + * @returns {number} The total duration in microseconds. + */ + measurePacketsDurationMicros(packets) { + let total = 0; + let previous = this.lastBlockSize; + for (const packet of packets) { + if (this.isHeaderPacket(packet.data) || !packet.data || packet.data.length < 1) + continue; + const blockSize = this.blockSizes[(packet.data[0] >> 7) & 0x01]; + const prior = previous === null ? blockSize : previous; + total += LuminaAudioPlayer.samplesToMicroseconds(Math.floor((prior + blockSize) / 4), this.sampleRate); + previous = blockSize; + } + return total; + } + + /** + * Reads the next Vorbis audio packet. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + try { + if (this.seekResync) + await this.prepareAfterSeekAsync(); + return await this.readNextAudioPacketAsync(); + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Gets the duration, in microseconds, of one Vorbis packet. The first bit of an audio packet selects one of the + * two block sizes of the stream, and a packet produces the average of its own block size and the previous one, + * which is the amount of audio the overlap of two windows covers. + * @param {Uint8Array} data - The packet bytes. + * @returns {number} The duration in microseconds. + */ + computePacketDurationMicros(data) { + if (!data || data.length < 1) + return 0; + const blockFlag = (data[0] >> 7) & 0x01; + const blockSize = this.blockSizes[blockFlag]; + const previous = this.lastBlockSize === null ? blockSize : this.lastBlockSize; + this.lastBlockSize = blockSize; + const samples = Math.floor((previous + blockSize) / 4); + return LuminaAudioPlayer.samplesToMicroseconds(samples, this.sampleRate); + } + + /** + * Converts a Vorbis granule position to a media time. A Vorbis granule counts decoded samples. + * @param {number} granule - The granule position. + * @returns {number} The media time in microseconds. + */ + granuleToMicros(granule) { + return LuminaAudioPlayer.samplesToMicroseconds(Math.max(0, granule), this.sampleRate); + } + } + + LuminaAudioPlayer.OggDemuxer = OggDemuxer; + LuminaAudioPlayer.OggOpusDemuxer = OggOpusDemuxer; + LuminaAudioPlayer.OggVorbisDemuxer = OggVorbisDemuxer; + LuminaAudioPlayer.computeOggCrc = computeOggCrc; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.OGG, + codec: LuminaAudioPlayer.DemuxerCodec.OPUS, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.OPUS, + create: (options) => new OggOpusDemuxer(options) + }); + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.OGG, + codec: LuminaAudioPlayer.DemuxerCodec.VORBIS, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.VORBIS, + create: (options) => new OggVorbisDemuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-wav.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-wav.js new file mode 100644 index 00000000..20090143 --- /dev/null +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-demux/audio-player-demux-wav.js @@ -0,0 +1,303 @@ +/** + * WAV (RIFF) demuxer of the audio player. + * + * A WAV file is a RIFF container: the four byte magic 'RIFF', a size, the four byte form 'WAVE', and then a sequence of + * tagged chunks, of which the 'fmt ' chunk describes the audio and the 'data' chunk holds it. The audio is uncompressed, + * so the payload of the data chunk is the samples themselves, interleaved by channel. There is no framing inside the + * payload at all: this demuxer invents packets by cutting the payload into fixed size blocks of whole frames, which is + * what makes the stream seekable to an exact byte and therefore to an exact sample. + * + * The codec private data and the codec string + * ------------------------------------------- + * WebCodecs decodes uncompressed audio under the PCM codec strings, one per sample format ('pcm-u8', 'pcm-s16', + * 'pcm-s24', 'pcm-s32', 'pcm-f32'), each packet being raw interleaved samples and no description. This demuxer maps the + * sample format and the bits per sample of the fmt chunk to the matching codec string: a 8 bit PCM stream is unsigned + * (as RIFF defines 8 bit samples), an integer stream of 16, 24 or 32 bits is signed, and a 32 bit IEEE float stream is + * 'pcm-f32'. A format or a bit depth the player has no codec string for is refused as unsupported. + */ +(function (LuminaAudioPlayer) { + 'use strict'; + + /** + * The number of frames a WAV packet holds. The payload is uncompressed, so the block only has to be small enough to + * keep a packet light and large enough to keep the call overhead low. + * @readonly + * @type {number} + */ + const FRAMES_PER_PACKET = 4096; + + /** + * The format tag RIFF uses for integer PCM. + * @readonly + * @type {number} + */ + const FORMAT_PCM = 1; + + /** + * The format tag RIFF uses for IEEE float PCM. + * @readonly + * @type {number} + */ + const FORMAT_FLOAT = 3; + + /** + * The format tag RIFF uses for an extensible format, whose real format is in a subformat GUID. + * @readonly + * @type {number} + */ + const FORMAT_EXTENSIBLE = 0xFFFE; + + /** + * Resolves the WebCodecs PCM codec string of a WAV sample format. + * @param {number} audioFormat - The format tag of the fmt chunk, after resolving an extensible format. + * @param {number} bitsPerSample - The bits per sample of the fmt chunk. + * @returns {string|null} The codec string, or null when the player has no codec string for the format. + */ + function resolvePcmCodec(audioFormat, bitsPerSample) { + if (audioFormat === FORMAT_FLOAT) + return bitsPerSample === 32 ? 'pcm-f32' : null; + if (audioFormat !== FORMAT_PCM) + return null; + if (bitsPerSample === 8) + return 'pcm-u8'; + if (bitsPerSample === 16) + return 'pcm-s16'; + if (bitsPerSample === 24) + return 'pcm-s24'; + if (bitsPerSample === 32) + return 'pcm-s32'; + return null; + } + + /** + * Demuxes a WAV (RIFF) stream. + */ + class WavDemuxer extends LuminaAudioPlayer.Demuxer { + /** + * Creates an instance of WavDemuxer. + * @param {Object} options - The demuxer options, per {@link LuminaAudioPlayer.Demuxer}. + */ + constructor(options = {}) { + super(options); + this.offset = 0; + this.dataStart = 0; + this.dataEnd = 0; + this.timelineMicros = 0; + /** @type {Object|null} */ + this.format = null; + this.durationSeconds = null; + this.reachedEnd = false; + } + + //+=======================================================================================+ + //| Initialization | + //+=======================================================================================+ + + /** + * Reads the RIFF header and walks the chunks to find the fmt chunk and the data chunk. + * @returns {Promise} A promise resolving when the stream is ready to be read. + * @throws {LuminaAudioPlayer.PlayerError} When the bytes are not a WAV stream the player decodes. + */ + async initializeAsync() { + if (this.isInitialized()) + return; + if (this.destroyed) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.INVALID_STATE, 'The demuxer was destroyed.'); + try { + const riff = await this.reader.readAsync(0, 12); + if (!LuminaAudioPlayer.demuxBytesEqualAscii(riff, 0, 'RIFF') || !LuminaAudioPlayer.demuxBytesEqualAscii(riff, 8, 'WAVE')) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The bytes are not a WAV stream.', { reason: 'no-riff-magic' }); + const result = await this.readChunksAsync(); + if (result.formatResult === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The WAV stream carries no format chunk.', { reason: 'no-format-chunk' }); + if (result.formatResult.status === 'invalid') + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The WAV format chunk is too short or malformed to describe the audio.', { reason: 'invalid-format-chunk' }); + if (result.formatResult.status === 'unsupported') + // The chunk is present and well formed, but it names a format or a bit depth the player decodes no PCM + // codec string for, which is a different outcome from a chunk that is missing, and is reported as such. + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The WAV stream holds an audio format the player does not decode.', { + reason: 'unsupported-format', + audioFormat: result.formatResult.audioFormat, + bitsPerSample: result.formatResult.bitsPerSample + }); + if (result.dataStart === null) + throw this.createError(LuminaAudioPlayer.PlayerErrorCode.DEMUX_FAILED, 'The WAV stream carries no data chunk.', { reason: 'no-data-chunk' }); + const format = result.formatResult.format; + this.format = format; + this.dataStart = result.dataStart; + this.dataEnd = result.dataEnd; + this.durationSeconds = format.byteRate > 0 ? (this.dataEnd - this.dataStart) / format.byteRate : null; + this.offset = this.dataStart; + this.timelineMicros = 0; + this.reachedEnd = false; + this.initialized = true; + } catch (error) { + throw this.recordFailure(error, 'initialize-failed'); + } + } + + /** + * Gets the decoder configuration of the stream. + * @returns {Object|null} The configuration, or null before initialization. + */ + getConfiguration() { + if (!this.format) + return null; + return { + codec: this.format.codec, + sampleRate: this.format.sampleRate, + numberOfChannels: this.format.channels + }; + } + + /** + * Gets the duration of the stream, computed from the size of the data chunk and the byte rate of the format. + * @returns {number|null} The duration in seconds, or null when it cannot be derived. + */ + getDuration() { + return this.durationSeconds; + } + + //+=======================================================================================+ + //| Reading | + //+=======================================================================================+ + + /** + * Reads the next block of whole frames from the data chunk as an encoded packet. + * @returns {Promise} The packet, or null once the stream ended. + * @throws {LuminaAudioPlayer.PlayerError} When the stream can no longer be parsed. + */ + async readPacketAsync() { + this.ensureInitialized(); + if (this.reachedEnd) + return null; + try { + const format = this.format; + const remaining = this.dataEnd - this.offset; + if (remaining < format.blockAlign) { + this.reachedEnd = true; + return null; + } + const frames = Math.min(FRAMES_PER_PACKET, Math.floor(remaining / format.blockAlign)); + const length = frames * format.blockAlign; + const data = await this.reader.copyAsync(this.offset, length); + if (data.length < length) { // A short read means the stream was truncated below the data chunk size it declared. + this.reachedEnd = true; + return null; + } + // The duration is kept unrounded while the timeline accumulates it, so that rounding it per packet does not + // make the timeline drift; only the packet the decoder receives carries a whole number of microseconds. + const duration = (frames / format.sampleRate) * 1000000; + const packet = LuminaAudioPlayer.createDemuxerPacket(data, this.timelineMicros, duration); + this.timelineMicros += duration; + this.offset += length; + if (this.offset + format.blockAlign > this.dataEnd) + this.reachedEnd = true; + return packet; + } catch (error) { + throw this.recordFailure(error, 'read-failed'); + } + } + + /** + * Repositions the read cursor to the exact frame that covers a time. The payload is uncompressed and frame aligned, so the position is computed rather than scanned. + * @param {number} seconds - The target time, in seconds. + * @returns {Promise} The byte offset it repositioned to, or null when the stream cannot be seeked. + */ + async seekToTimeAsync(seconds) { + this.ensureInitialized(); + const format = this.format; + if (!format || !Number.isFinite(seconds) || seconds < 0) + return null; + const frame = Math.floor(seconds * format.sampleRate); + const offset = Math.min(this.dataEnd, this.dataStart + frame * format.blockAlign); + const aligned = this.dataStart + Math.floor((offset - this.dataStart) / format.blockAlign) * format.blockAlign; + this.offset = aligned; + this.reachedEnd = this.offset >= this.dataEnd; + // The exact time of the requested frame, kept unrounded so the timeline it seeds does not drift. + this.timelineMicros = ((aligned - this.dataStart) / format.blockAlign / format.sampleRate) * 1000000; + return aligned; + } + + //+=======================================================================================+ + //| Internal helpers | + //+=======================================================================================+ + + /** + * Walks the RIFF chunks, parsing the format chunk and locating the data chunk. + * @returns {Promise} The result of the format chunk, and the offset and end of the data chunk. The format result distinguishes an absent chunk from an unsupported one. + */ + async readChunksAsync() { + const end = this.reader.getLength(); + let cursor = 12; + /** @type {Object|null} */ + let formatResult = null; + let dataStart = null; + let dataEnd = null; + // The chunk list is bounded so a malformed size field cannot make this walk forever. + for (let count = 0; count < 4096; count++) { + if (end !== null && cursor + 8 > end) + break; + const header = await this.reader.readAsync(cursor, 8); + if (header.length < 8) + break; + const id = String.fromCharCode(header[0], header[1], header[2], header[3]); + const size = LuminaAudioPlayer.demuxReadUintLE(header, 4, 4) || 0; + const bodyStart = cursor + 8; + if (id === 'fmt ') + formatResult = await this.parseFormatChunkAsync(bodyStart, size); + else if (id === 'data') { + dataStart = bodyStart; + dataEnd = end === null ? bodyStart + size : Math.min(bodyStart + size, end); + } + // A RIFF chunk body is padded to an even length, and the pad byte is not counted in the size. + cursor = bodyStart + size + (size % 2); + } + return { formatResult, dataStart, dataEnd }; + } + + /** + * Parses the fmt chunk of a WAV stream. + * @param {number} offset - The offset of the chunk body. + * @param {number} size - The number of bytes of the chunk body. + * @returns {Promise} A result whose status is 'ok' with the parsed format, 'unsupported' with the format tag and bit depth the player decodes no PCM codec string for, or 'invalid' when the chunk is too short or malformed. The three are distinguished so that a present but unsupported format is not reported as a missing chunk. + */ + async parseFormatChunkAsync(offset, size) { + if (size < 16) + return { status: 'invalid' }; + const bytes = await this.reader.readAsync(offset, Math.min(size, 40)); + if (bytes.length < 16) + return { status: 'invalid' }; + // The first sixteen bytes of a fmt chunk are the format tag, the channel count, the sample rate, the byte rate, + // the block alignment and the bits per sample, in that order, every one little endian. + let audioFormat = LuminaAudioPlayer.demuxReadUintLE(bytes, 0, 2); + const channels = LuminaAudioPlayer.demuxReadUintLE(bytes, 2, 2); + const sampleRate = LuminaAudioPlayer.demuxReadUintLE(bytes, 4, 4); + const byteRate = LuminaAudioPlayer.demuxReadUintLE(bytes, 8, 4); + let blockAlign = LuminaAudioPlayer.demuxReadUintLE(bytes, 12, 2); + const bitsPerSample = LuminaAudioPlayer.demuxReadUintLE(bytes, 14, 2); + // An extensible format names its real format in the first two bytes of the subformat GUID. + if (audioFormat === FORMAT_EXTENSIBLE && size >= 40 && bytes.length >= 40) + audioFormat = LuminaAudioPlayer.demuxReadUintLE(bytes, 24, 2); + if (!channels || channels <= 0 || !sampleRate || sampleRate <= 0 || !bitsPerSample) + return { status: 'invalid' }; + const codec = resolvePcmCodec(audioFormat, bitsPerSample); + if (!codec) + return { status: 'unsupported', audioFormat, bitsPerSample }; + const sampleBytes = bitsPerSample / 8; + // A stream whose block alignment disagrees with its channels and bit depth cannot be sliced into frames, so the computed alignment is used and the declared one is only a fallback. + if (!blockAlign || blockAlign <= 0 || blockAlign % sampleBytes !== 0 || blockAlign % channels !== 0) + blockAlign = channels * sampleBytes; + return { status: 'ok', format: Object.freeze({ codec, channels, sampleRate, byteRate: byteRate || sampleRate * blockAlign, blockAlign, bitsPerSample }) }; + } + } + + LuminaAudioPlayer.WavDemuxer = WavDemuxer; + + LuminaAudioPlayer.registerDemuxer({ + container: LuminaAudioPlayer.DemuxerContainer.WAV, + codec: LuminaAudioPlayer.DemuxerCodec.PCM, + probe: LuminaAudioPlayer.AUDIO_CODEC_PROBES.PCM, + create: (options) => new WavDemuxer(options) + }); +})(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {}); diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js index 14d26630..1642eb2a 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-download.js @@ -69,7 +69,7 @@ * the reads that are waiting for a window, with {@link LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_ABORTED}, so a seek * teardown is never mistaken for a stream failure. A read therefore resolves once the buffer covers its window, and is * rejected when the window can no longer be filled: on a destroy or an abort (DOWNLOAD_ABORTED), with the recorded failure - * when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason === 'window-unavailable' when + * when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE} when * the file completed or the loop ended with no gap left to fill. A read that is waiting while the download is merely * paused, or before it has started, is left pending, because a resume or a start can still fill it. The loop callbacks and * getError only ever see DOWNLOAD_FAILED. @@ -130,16 +130,6 @@ return { start, end, total }; } - /** - * Checks whether a value is the AbortError a cancelled fetch or stream read rejects with. It is tested by name rather - * than by type, because in a browser an AbortError is a DOMException, which is not an Error. - * @param {*} error - The value to check. - * @returns {boolean} True when the value is an AbortError. - */ - function isAbortError(error) { - return !!error && error.name === 'AbortError'; - } - /** * Checks whether a Content-Type is one the track stream may answer with: an audio type, or the generic binary type * the stream endpoint falls back to for a container it cannot name. Any other type, in particular the text/html of a @@ -777,7 +767,7 @@ * @param {number} offset - The first byte of the window. * @param {number} length - The length of the window, in bytes. * @returns {Promise} A copy of the requested bytes. - * @throws {LuminaAudioPlayer.PlayerError} The rejection of {@link LuminaAudioPlayer.TrackDownloader#whenRangeAvailableAsync}, which a read propagates, or DOWNLOAD_FAILED with details.reason === 'window-unavailable' if the window was released without ever arriving. + * @throws {LuminaAudioPlayer.PlayerError} The rejection of {@link LuminaAudioPlayer.TrackDownloader#whenRangeAvailableAsync}, which a read propagates, or DOWNLOAD_FAILED with details.reason {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE} if the window was released without ever arriving. */ async readBytesAsync(offset, length) { const direct = this.buffer.read(offset, length); @@ -794,8 +784,8 @@ * Resolves once a window of bytes has been downloaded. * @param {number} offset - The first byte of the window. * @param {number} length - The length of the window, in bytes. - * @returns {Promise} A promise that resolves once the buffer covers the window. It is rejected when the window can no longer be filled: on a destroy or an abort, with the recorded failure when the loop stopped after a failure, or with the window-unavailable error when the file completed or the loop ended with no gap left to fill. A read issued while the download is merely paused, or before it has started, stays pending, because a resume or a start can still fill it. - * @throws {LuminaAudioPlayer.PlayerError} With DOWNLOAD_ABORTED when the downloader is destroyed or was aborted, with the recorded failure when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason === 'window-unavailable' when the file completed or the loop ended with no gap left to fill. + * @returns {Promise} A promise that resolves once the buffer covers the window. It is rejected when the window can no longer be filled: on a destroy or an abort, with the recorded failure when the loop stopped after a failure, or with the {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE} error when the file completed or the loop ended with no gap left to fill. A read issued while the download is merely paused, or before it has started, stays pending, because a resume or a start can still fill it. + * @throws {LuminaAudioPlayer.PlayerError} With DOWNLOAD_ABORTED when the downloader is destroyed or was aborted, with the recorded failure when the loop stopped after a failure, or with DOWNLOAD_FAILED and details.reason {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE} when the file completed or the loop ended with no gap left to fill. */ whenRangeAvailableAsync(offset, length) { if (this.buffer.covers(offset, length)) @@ -1034,7 +1024,7 @@ this.noteTotal(resolved.total); return await this.readResponseIntoBufferAsync(response, resolved, controller, spec.stopOnPause === true, spec.openEnded === true); } catch (error) { - if (isAbortError(error)) + if (LuminaAudioPlayer.isAbortError(error)) return { isAborted: true, isFailed: false, isDestroyed: this.destroyed }; // The failure left the response body unread, so it is discarded and the request is aborted to release the // connection instead of waiting for the browser to drop the stream. @@ -1156,7 +1146,7 @@ try { result = await reader.read(); } catch (error) { - if (isAbortError(error)) { + if (LuminaAudioPlayer.isAbortError(error)) { isStopped = true; break; } @@ -1359,10 +1349,10 @@ * Builds the single error used whenever a byte window can no longer be filled: a completed file, a loop that * drained with nothing left to fetch, or a window that was released without ever arriving. Every path that reports * this outcome uses it, so a consumer sees one consistent code and reason. - * @returns {LuminaAudioPlayer.PlayerError} The window unavailable error, with details.reason === 'window-unavailable'. + * @returns {LuminaAudioPlayer.PlayerError} The window unavailable error, with details.reason === {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE}. */ createWindowUnavailableError() { - return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The requested byte window can no longer be filled.', { reason: 'window-unavailable' }); + return new LuminaAudioPlayer.PlayerError(LuminaAudioPlayer.PlayerErrorCode.DOWNLOAD_FAILED, 'The requested byte window can no longer be filled.', { reason: LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE }); } } diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js index 9fc8d704..c40509cd 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-errors.js @@ -34,6 +34,8 @@ DOWNLOAD_FAILED: 'download-failed', // The download of a track was intentionally stopped, by an abort or a destroy, so a reader can tell a teardown apart from a stream failure. DOWNLOAD_ABORTED: 'download-aborted', + // The container of a track could not be parsed into encoded packets, or the bytes it holds do not describe a stream the demuxer supports. + DEMUX_FAILED: 'demux-failed', // The stored playback preferences of the user could not be read. PREFERENCES_LOAD_FAILED: 'preferences-load-failed' }); @@ -56,7 +58,22 @@ // A scheduler's scheduled ahead ceiling is smaller than one frame plus its scheduling lead, so it can never accept a // frame at all. Unlike SCHEDULED_AHEAD_LIMIT, which is recoverable backpressure, this is terminal: the decode // pipeline stops because it can never make progress. - SCHEDULED_AHEAD_UNSATISFIABLE: 'scheduled-ahead-unsatisfiable' + SCHEDULED_AHEAD_UNSATISFIABLE: 'scheduled-ahead-unsatisfiable', + // The bundled demuxers have no demuxer for the container of a track, so the server must change the container or the + // codec of the track before the player can play it. Published by the demux capability module, which a consumer reads + // to ask for a normalized delivery instead of failing. + NO_DEMUXER: 'no-demuxer', + // A demuxer exists for the container of a track, but the browser cannot decode the codec of the track, so the server + // must re-encode it. Published by the demux capability module alongside NO_DEMUXER. + CODEC_UNSUPPORTED: 'codec-unsupported', + // A demuxer exists for the container of a track, but the bytes of the track could not be parsed, so the file is + // treated as one the bundled player cannot play directly rather than as a fatal player failure. + DEMUXER_FAILED: 'demuxer-failed', + // A read asked the download engine for a byte window it can never fill, because the file completed or the loop + // stopped with no gap left to fill. Published by the download engine and recognized by the demuxer byte source, + // which reads it as end of file rather than as a failure, so a rename on either side cannot silently turn a + // drained window into a fatal read error. + WINDOW_UNAVAILABLE: 'window-unavailable' }); /** 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 index 39e8305b..ac8b61b8 100644 --- 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 @@ -39,6 +39,13 @@ CAPABILITIES_CHANGED: 'capabilitieschange', // The stored playback preferences of the user were loaded. Payload: the preferences object. PREFERENCES_CHANGED: 'preferenceschange', + // A track cannot be demuxed and decoded directly by the bundled player, so the server has to normalize it (remux or + // transcode) before it can play. Payload: { container, codec, reason }, where reason is one of the + // {@link LuminaAudioPlayer.PlayerErrorReason} values NO_DEMUXER, CODEC_UNSUPPORTED or DEMUXER_FAILED, and, when the + // caller supplied one, directPlay, the direct play flag of the manifest it asked about, so a consumer can tell a + // client-side capability gap from a track the server already decided to normalize. The flag is absent, not false, + // when the caller had no manifest. + NEEDS_NORMALIZATION: 'needsnormalization', // The player bar became visible or hidden. Payload: { isVisible }. 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' diff --git a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js index d77a2463..c85efe06 100644 --- a/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js +++ b/src/Lumina.Presentation.Web/wwwroot/js/audio-player/audio-player-utils.js @@ -2,9 +2,10 @@ * Shared helpers of the audio player. * * This module has no dependency on any other player module, and it is loaded before them, so it is the home of the small - * numeric helpers several modules need. Keeping one implementation here avoids the copies that otherwise drift apart, and - * because this file is a dedicated, dependency free util, no consumer depends on the load order of a feature module such - * as the event bus or the download engine. + * numeric and error helpers several modules need. Keeping one implementation here avoids the copies that otherwise drift + * apart, and because this file is a dedicated, dependency free util, no consumer depends on the load order of a feature + * module such as the event bus or the download engine. The error helpers read {@link LuminaAudioPlayer.PlayerError} at + * call time rather than at load time, so they do not depend on the error module being loaded first either. */ (function (LuminaAudioPlayer) { 'use strict'; @@ -21,4 +22,50 @@ return minimum; return Math.min(maximum, Math.max(minimum, value)); }; + + /** + * Checks whether a value is the AbortError a reset, a close or an aborted fetch rejects with. An AbortError is tested + * by name rather than by type, because in a browser it is a DOMException, which is not an Error. + * @param {*} error - The value to check. + * @returns {boolean} True when the value is an AbortError. + */ + LuminaAudioPlayer.isAbortError = function isAbortError(error) { + return !!error && error.name === 'AbortError'; + }; + + /** + * Merges two error detail objects into a new one, so that a details object a component owns is never mutated in place. + * @param {Object|null} base - The existing details. + * @param {Object|null} extra - The details to add. + * @returns {Object|null} The merged details, or null when both are absent. + */ + LuminaAudioPlayer.mergeErrorDetails = function mergeErrorDetails(base, extra) { + const hasBase = base !== null && base !== undefined; + const hasExtra = extra !== null && extra !== undefined; + if (!hasBase && !hasExtra) + return null; + if (!hasExtra) + return Object.assign({}, base); + if (!hasBase) + return Object.assign({}, extra); + return Object.assign({}, base, extra); + }; + + /** + * Copies a failure into a {@link LuminaAudioPlayer.PlayerError} that the caller owns, so that a player error raised by + * another component is never aliased and its details are never mutated. A failure that is already a player error keeps + * its own code, which is more specific than the fallback the caller would give it. + * @param {*} error - The failure to own. + * @param {string} [fallbackCode] - The code to use when the failure is not already a player error. + * @param {Object|null} [details] - Optional details to merge in. + * @returns {LuminaAudioPlayer.PlayerError} The owned typed error. + */ + LuminaAudioPlayer.toOwnedPlayerError = function toOwnedPlayerError(error, fallbackCode, details) { + if (error instanceof LuminaAudioPlayer.PlayerError) + return new LuminaAudioPlayer.PlayerError(error.code, error.message, LuminaAudioPlayer.mergeErrorDetails(error.details, details || null)); + const typed = LuminaAudioPlayer.PlayerError.from(error, fallbackCode); + if (!details) + return typed; + return new LuminaAudioPlayer.PlayerError(typed.code, typed.message, LuminaAudioPlayer.mergeErrorDetails(typed.details, details)); + }; })(window.LuminaAudioPlayer = window.LuminaAudioPlayer || {});