mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 19:21:10 +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
+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 || {});
|
||||
Reference in new issue
Block a user