mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the audio player container demuxers.
This commit is contained in:
1 parent
fbc67c81c3
commit
c05978fac0
14 files changed
+4838
-79
No files matched your search
@@ -71,5 +71,12 @@
|
||||
<script defer src="~/js/audio-player/audio-player-render.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-decode.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-capabilities.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-demux/audio-player-demux-common.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-demux/audio-player-demux-mp3.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-demux/audio-player-demux-aac.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-demux/audio-player-demux-flac.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-demux/audio-player-demux-ogg.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-demux/audio-player-demux-wav.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-demux/audio-player-demux-capabilities.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player-engine.js" asp-append-version="true"></script>
|
||||
<script defer src="~/js/audio-player/audio-player.js" asp-append-version="true"></script>
|
||||
@@ -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<string, { codec: string, sampleRate: number, numberOfChannels: number }>}
|
||||
*/
|
||||
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<Object>|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<string, Promise<boolean>>}
|
||||
*/
|
||||
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<boolean>} 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
|
||||
|
||||
@@ -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();
|
||||
|
||||
+367
@@ -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<number>}
|
||||
*/
|
||||
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<number>}
|
||||
*/
|
||||
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<number>}
|
||||
*/
|
||||
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<number>}
|
||||
*/
|
||||
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<void>} 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<Object|null>} 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<Object|null>} 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<number|null>} 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<Object|null>} 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<boolean>} 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 || {});
|
||||
+363
@@ -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<boolean>} 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<boolean>} 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<boolean>} 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<boolean>} 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<string>} 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<LuminaAudioPlayer.Demuxer|null>} 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<LuminaAudioPlayer.Demuxer|null>} 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<string>} 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 || {});
|
||||
+1016
File diff suppressed because it is too large.
Load diff
+1064
File diff suppressed because it is too large.
Load diff
+443
@@ -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<string, Array<Array<number>>>}
|
||||
*/
|
||||
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<string, Array<number>>}
|
||||
*/
|
||||
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<number>}
|
||||
*/
|
||||
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<number>}
|
||||
*/
|
||||
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<void>} 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<Object|null>} 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<Object|null>} 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<number|null>} 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<Object|null>} 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<boolean>} 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<Object|null>} 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 || {});
|
||||
+1113
File diff suppressed because it is too large.
Load diff
+303
@@ -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<void>} 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<Object|null>} 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<number|null>} 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<Object>} 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<Object>} 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 || {});
|
||||
@@ -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 <c>details.reason === 'window-unavailable'</c> when
|
||||
* when the loop stopped after a failure, or with DOWNLOAD_FAILED and <c>details.reason</c> {@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<Uint8Array>} A copy of the requested bytes.
|
||||
* @throws {LuminaAudioPlayer.PlayerError} The rejection of {@link LuminaAudioPlayer.TrackDownloader#whenRangeAvailableAsync}, which a read propagates, or <c>DOWNLOAD_FAILED</c> with <c>details.reason === 'window-unavailable'</c> if the window was released without ever arriving.
|
||||
* @throws {LuminaAudioPlayer.PlayerError} The rejection of {@link LuminaAudioPlayer.TrackDownloader#whenRangeAvailableAsync}, which a read propagates, or <c>DOWNLOAD_FAILED</c> with <c>details.reason</c> {@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<void>} 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 <c>DOWNLOAD_ABORTED</c> when the downloader is destroyed or was aborted, with the recorded failure when the loop stopped after a failure, or with <c>DOWNLOAD_FAILED</c> and <c>details.reason === 'window-unavailable'</c> when the file completed or the loop ended with no gap left to fill.
|
||||
* @returns {Promise<void>} 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 <c>DOWNLOAD_ABORTED</c> when the downloader is destroyed or was aborted, with the recorded failure when the loop stopped after a failure, or with <c>DOWNLOAD_FAILED</c> and <c>details.reason</c> {@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 <c>details.reason === 'window-unavailable'</c>.
|
||||
* @returns {LuminaAudioPlayer.PlayerError} The window unavailable error, with <c>details.reason === {@link LuminaAudioPlayer.PlayerErrorReason.WINDOW_UNAVAILABLE}</c>.
|
||||
*/
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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'
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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 || {});
|
||||
Reference in new issue
Block a user