diff --git a/docs/guide/output-formats.md b/docs/guide/output-formats.md index 6e125cb..0e151b4 100644 --- a/docs/guide/output-formats.md +++ b/docs/guide/output-formats.md @@ -194,9 +194,12 @@ This format ensures [append-only writing](#append-only-writing). The following options are available: ```ts type OggOutputFormatOptions = { + maximumPageDuration?: number; onPage?: (data: Uint8Array, position: number, source: MediaSource) => unknown; }; ``` +- `maximumPageDuration`\ + The maximum duration in seconds of each Ogg page. Pages will be flushed early if adding another packet would cause the page to exceed this duration. This is useful for streaming contexts where more frequent page output is desired. By default, pages are only flushed when they exceed a certain size. - `onPage`\ Will be called for each finalized Ogg page of the output file. The [media source](./media-sources) backing the page's track (logical bitstream) is also passed. diff --git a/src/ogg/ogg-muxer.ts b/src/ogg/ogg-muxer.ts index 91ee535..b47f86e 100644 --- a/src/ogg/ogg-muxer.ts +++ b/src/ogg/ogg-muxer.ts @@ -47,12 +47,13 @@ type OggTrackData = { currentPageData: Uint8Array[]; currentPageSize: number; currentPageStartsWithFreshPacket: boolean; + currentPageStartTimestampInSamples: number; }; type Packet = { data: Uint8Array; - endGranulePosition: number; - timestamp: number; + timestampInSamples: number; + durationInSamples: number; forcePageFlush: boolean; }; @@ -132,6 +133,7 @@ export class OggMuxer extends Muxer { currentPageData: [], currentPageSize: 27, currentPageStartsWithFreshPacket: true, + currentPageStartTimestampInSamples: 0, }; this.queueHeaderPackets(newTrackData, meta); @@ -199,18 +201,18 @@ export class OggMuxer extends Muxer { trackData.packetQueue.push({ data: identificationHeader, - endGranulePosition: 0, - timestamp: 0, + timestampInSamples: 0, + durationInSamples: 0, forcePageFlush: true, }, { data: commentHeader, - endGranulePosition: 0, - timestamp: 0, + timestampInSamples: 0, + durationInSamples: 0, forcePageFlush: false, }, { data: setupHeader, - endGranulePosition: 0, - timestamp: 0, + timestampInSamples: 0, + durationInSamples: 0, forcePageFlush: true, // The last header packet must flush the page }); @@ -239,13 +241,13 @@ export class OggMuxer extends Muxer { trackData.packetQueue.push({ data: identificationHeader, - endGranulePosition: 0, - timestamp: 0, + timestampInSamples: 0, + durationInSamples: 0, forcePageFlush: true, }, { data: commentHeader, - endGranulePosition: 0, - timestamp: 0, + timestampInSamples: 0, + durationInSamples: 0, forcePageFlush: true, // The last header packet must flush the page }); @@ -275,8 +277,8 @@ export class OggMuxer extends Muxer { trackData.packetQueue.push({ data: packet.data, - endGranulePosition: trackData.currentTimestampInSamples, - timestamp: currentTimestampInSamples / trackData.internalSampleRate, + timestampInSamples: currentTimestampInSamples, + durationInSamples, forcePageFlush: false, }); @@ -338,10 +340,10 @@ export class OggMuxer extends Muxer { if ( trackData.packetQueue.length > 0 - && trackData.packetQueue[0]!.timestamp < minTimestamp + && trackData.packetQueue[0]!.timestampInSamples < minTimestamp ) { trackWithMinTimestamp = trackData; - minTimestamp = trackData.packetQueue[0]!.timestamp; + minTimestamp = trackData.packetQueue[0]!.timestampInSamples; } } @@ -361,6 +363,20 @@ export class OggMuxer extends Muxer { } writePacket(trackData: OggTrackData, packet: Packet, isFinalPacket: boolean) { + const packetEndTimestampInSamples = packet.timestampInSamples + packet.durationInSamples; + + if (this.format._options.maximumPageDuration !== undefined) { + const maxDurationInSamples = this.format._options.maximumPageDuration * trackData.internalSampleRate; + + if ( + trackData.currentLacingValues.length > 0 + && packetEndTimestampInSamples - trackData.currentPageStartTimestampInSamples > maxDurationInSamples + ) { + // Flush the current page early to avoid exceeding the maximum page duration + this.writePage(trackData, false); + } + } + let remainingLength = packet.data.length; let dataStartOffset = 0; let dataOffset = 0; @@ -401,7 +417,7 @@ export class OggMuxer extends Muxer { const slice = packet.data.subarray(dataStartOffset); trackData.currentPageData.push(slice); trackData.currentPageSize += slice.length; - trackData.currentGranulePosition = packet.endGranulePosition; + trackData.currentGranulePosition = packetEndTimestampInSamples; if (trackData.currentPageSize >= PAGE_SIZE_TARGET || packet.forcePageFlush) { this.writePage(trackData, isFinalPacket); @@ -452,6 +468,7 @@ export class OggMuxer extends Muxer { trackData.currentPageData.length = 0; trackData.currentPageSize = 27; trackData.currentPageStartsWithFreshPacket = true; + trackData.currentPageStartTimestampInSamples = trackData.currentGranulePosition; if (this.format._options.onPage) { this.writer.startTrackingWrites(); diff --git a/src/output-format.ts b/src/output-format.ts index de50fe3..bd32b6c 100644 --- a/src/output-format.ts +++ b/src/output-format.ts @@ -725,6 +725,12 @@ export class WavOutputFormat extends OutputFormat { * @public */ export type OggOutputFormatOptions = { + /** + * The maximum duration of each Ogg page, in seconds. This is useful for streaming contexts where more frequent page + * output is desired. By default, pages are only flushed when they exceed a certain size. + */ + maximumPageDuration?: number; + /** * Will be called for each Ogg page that is written. * @@ -749,6 +755,12 @@ export class OggOutputFormat extends OutputFormat { if (!options || typeof options !== 'object') { throw new TypeError('options must be an object.'); } + if ( + options.maximumPageDuration !== undefined + && (!Number.isFinite(options.maximumPageDuration) || options.maximumPageDuration <= 0) + ) { + throw new TypeError('options.maximumPageDuration, when provided, must be a positive number.'); + } if (options.onPage !== undefined && typeof options.onPage !== 'function') { throw new TypeError('options.onPage, when provided, must be a function.'); } diff --git a/test/browser/ogg-muxer.test.ts b/test/browser/ogg-muxer.test.ts new file mode 100644 index 0000000..ea982e1 --- /dev/null +++ b/test/browser/ogg-muxer.test.ts @@ -0,0 +1,57 @@ +import { expect, test } from 'vitest'; +import { Output } from '../../src/output.js'; +import { OggOutputFormat } from '../../src/output-format.js'; +import { NullTarget } from '../../src/target.js'; +import { AudioBufferSource } from '../../src/media-source.js'; + +test('maximumPageDuration option', async () => { + const sampleRate = 48000; + const durationSeconds = 2; + const audioBuffer = new AudioBuffer({ numberOfChannels: 1, length: sampleRate * durationSeconds, sampleRate }); + + // First, create an Ogg file without the maximumPageDuration option + let pageCountWithoutOption = 0; + { + const output = new Output({ + format: new OggOutputFormat({ + onPage: () => { + pageCountWithoutOption++; + }, + }), + target: new NullTarget(), + }); + + const audioSource = new AudioBufferSource({ codec: 'opus', bitrate: 64000 }); + output.addAudioTrack(audioSource); + + await output.start(); + await audioSource.add(audioBuffer); + audioSource.close(); + await output.finalize(); + } + + // Then, create an Ogg file with maximumPageDuration set to 0.1 seconds + let pageCountWithOption = 0; + { + const output = new Output({ + format: new OggOutputFormat({ + maximumPageDuration: 0.1, + onPage: () => { + pageCountWithOption++; + }, + }), + target: new NullTarget(), + }); + + const audioSource = new AudioBufferSource({ codec: 'opus', bitrate: 64000 }); + output.addAudioTrack(audioSource); + + await output.start(); + await audioSource.add(audioBuffer); + audioSource.close(); + await output.finalize(); + } + + expect(pageCountWithoutOption).toBe(3); + expect(pageCountWithOption).toBe(23); // It created more pages +});