Add composable conversions

* Add non-owning conversions via ConversionOptions.ownsOutput

A conversion with ownsOutput: false only adds tracks to the output and
drives their media data; starting, finalizing, and metadata tags remain
the caller's responsibility. This lets multiple conversions and
directly-added user tracks compose on a single Output (see upstream
issue #436).

- ownsOutput: false allows a pre-populated output (state must still be
  'pending') and seeds track-capacity accounting from existing tracks
- execute() requires the output to be started and never finalizes it
- cancel() closes only the conversion's own sources, releasing internal
  synchronizer waiters, and leaves the output usable
- tags cannot be combined with ownsOutput: false
- isValid requires at least one contributed track instead of the
  format's minimum track counts

Prototype for API discussion; default (owning) behavior is unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AJdfnbY9AFh9i9dKgtrj6E

* Add external-audio example using a non-owning conversion

Demonstrates composing a user-owned audio track (synthesized voiceover
via OfflineAudioContext + AudioBufferSource) onto a picked video with
Conversion.init({ ownsOutput: false }), including progress reporting
and playback/download of the result.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AJdfnbY9AFh9i9dKgtrj6E

* Release synchronizer waiters when canceling during output finalization

A non-owning conversion's cancel() previously no-oped entirely when the
output (owned by someone else) was already finalizing or finalized,
leaving pump loops parked in the track synchronizer and hanging
execute() forever. Now it still marks the conversion canceled and
releases parked waiters in that state, without force-closing sources
(finalization owns flushing them at that point).

Also adds coverage: non-owning onProgress monotonicity, canceling one
of two sibling conversions, capacity seeding across sequential inits,
exact metadata exclusivity, and cancel-before-execute.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AJdfnbY9AFh9i9dKgtrj6E

* Document non-owning conversions on the converting-media-files guide page

Adds the doc section requested in #436: what ownsOutput: false does, the
required choreography (add tracks -> output.start() before execute() ->
run the conversion concurrently with your own sources -> finalize), the
cancellation split (conversion.cancel() leaves the output alive; cancel
both for a full abort and tear the output down on error paths), isValid
semantics in this mode, and the tags restriction with the
setMetadataTags() alternative. Also cross-links the fresh-output rule to
the new section. VitePress build passes with dead-link checking on.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* Clean up conversion logic, add Output.tracks and .hasEnoughTracks(), move new conversion tests around, remove external audio example

* non-owning -> composable, and update docs

* Update

---------

Co-authored-by: Claude <[email protected]>
Co-authored-by: Vanilagy <[email protected]>
This commit is contained in:
Saurabh Nandwana
2026-07-22 08:42:19 +00:00
committed by GitHub
co-authored by Claude Opus 4.8 Vanilagy
parent 794b84884f
commit f41eef0937
9 changed files with 475 additions and 86 deletions
+55 -2
View File
@@ -22,7 +22,7 @@ It has the following features:
- Audio up/downmixing
- User-defined video & audio processing
The conversion API was built to be simple, versatile and extremely performant.
The conversion API was built to be simple, versatile, composable and performant.
## Basic usage
@@ -63,7 +63,7 @@ await conversion.execute();
That's it! A `Conversion` simply takes an instance of `Input` and `Output`, then reads the data from the input and writes it to the output. If you're unfamiliar with [`Input`](./reading-media-files) and [`Output`](./writing-media-files), check out their respective guides.
::: info
The `Output` passed to the `Conversion` must be *fresh*; that is, it must have no added tracks or metadata tags and be in the `'pending'` state (not started yet).
The `Output` passed to the `Conversion` must be *fresh*; that is, it must have no added tracks or metadata tags and be in the `'pending'` state (not started yet). This requirement is relaxed for [composable conversions](#composable-conversions), which allows you to combine the conversion with other tracks.
:::
Unconfigured, the conversion process handles all the details automatically, such as:
@@ -506,6 +506,59 @@ conversion.utilizedTracks; // => InputTrack[]
```
A track may appear multiple times in this list when [fan-out](#track-fan-out) produces multiple output tracks from it.
## Composable conversions
By default, a `Conversion` takes full ownership of its `Output`: it requires a fresh output, then starts it, adds data, and finalizes it for you. Sometimes, however, you want a conversion to be just *one* of several contributors to a single output file - for example, to keep an input's video track while attaching your own, externally-produced audio track. For this, set `composable: true`.
A composable conversion only adds its own tracks to the output and pumps their media data while `execute()` runs. Everything else about the output's lifecycle is yours: you add any additional tracks, set any metadata tags, and call `start()` and `finalize()` yourself. This enables you to add additional tracks outside of the conversion, or even have multiple conversions target a single `Output`.
To use it, initialize everything, then start the `Output`, and then execute the conversion:
```ts
import {
Input,
Output,
Mp4OutputFormat,
BufferTarget,
Conversion,
AudioBufferSource,
} from 'mediabunny';
const input = new Input({ ... });
const output = new Output({
format: new Mp4OutputFormat(),
target: new BufferTarget(),
});
// Use the conversion only to copy over the video
const conversion = await Conversion.init({
input,
output,
audio: { discard: true },
composable: true,
});
// Add our own audio track directly
const audioSource = new AudioBufferSource({ codec: 'aac', bitrate: 128e3 });
output.addAudioTrack(audioSource);
// Start the output
await output.start();
// Run the conversion concurrently with feeding our own audio
await Promise.all([
conversion.execute(),
audioSource.add(myAudioBuffer).then(() => audioSource.close()),
]);
// Finalize the output
await output.finalize();
```
### Cancellation
[Canceling](#canceling-a-conversion) a composable conversion does *not* cancel the output, it only stops media data from being added and closes its tracks. For a full abort, you must cancel the output manually.
## Converting live streams
Live inputs, like HLS live streams, can also be used with the Conversion API. In this case, by default, the conversion will run until the live stream has ended.
+81 -31
View File
@@ -48,7 +48,7 @@ import {
promiseWithResolvers,
Rotation,
} from './misc';
import { Output, OutputTrackGroup, TrackType } from './output';
import { Output, OutputTrackGroup } from './output';
import { Mp4OutputFormat } from './output-format';
import {
AudioSample,
@@ -146,6 +146,18 @@ export type ConversionOptions = {
* want to keep the console output clean.
*/
showWarnings?: boolean;
/**
* Whether this conversion is composable, defaults to `false`. A non-composable conversion takes full ownership of
* the output: it requires a fresh output and controls its entire lifecycle, meaning it starts it, writes its
* metadata tags, and finalizes it.
*
* A composable conversion only adds tracks to the output and drives their media data; starting and finalizing
* the output is an outside responsibility. This is useful when only some output tracks should be driven by a
* conversion, and other are to be driven manually. Additionally, it can be used to have multiple conversions target
* the same output.
*/
composable?: boolean;
};
/**
@@ -546,15 +558,6 @@ export class Conversion {
/** @internal */
_endTimestamp!: number;
/** @internal */
_addedCounts: Record<TrackType, number> = {
video: 0,
audio: 0,
subtitle: 0,
};
/** @internal */
_totalTrackCount = 0;
/** @internal */
_nextOutputTrackId = 0;
/** @internal */
@@ -564,6 +567,8 @@ export class Conversion {
/** @internal */
_trackPromises: Promise<void>[] = [];
/** @internal */
_composable = false;
/** @internal */
_started: Promise<void>;
@@ -600,7 +605,8 @@ export class Conversion {
/**
* Whether this conversion, as it has been configured, is valid and can be executed. If this field is `false`, check
* the `discardedTracks` field for reasons.
* the `discardedTracks` field for reasons. Composable conversions are always valid, even if they utilize
* zero tracks.
*
* Note: a conversion having discarded tracks does not automatically mean it is invalid; if the remaining, utilized
* tracks make for a valid output file, the conversion is still allowed.
@@ -642,13 +648,31 @@ export class Conversion {
'options.tracks, when provided, must be either \'all\' or \'primary\'.',
);
}
if (options.composable !== undefined && typeof options.composable !== 'boolean') {
throw new TypeError('options.composable, when provided, must be a boolean.');
}
const composable = options.composable ?? false;
if (!composable) {
if (
options.output._tracks.length > 0
options.output.tracks.length > 0
|| Object.keys(options.output._metadataTags).length > 0
|| options.output.state !== 'pending'
) {
throw new TypeError('options.output must be fresh: no tracks or metadata tags added and not started.');
}
} else {
if (options.tags !== undefined) {
throw new TypeError(
'options.tags cannot be set by a composable conversion; set metadata directly on the output'
+ ' instead.',
);
}
if (options.output.state !== 'pending') {
throw new TypeError('options.output must not have been started yet.');
}
}
if (options.video !== undefined && typeof options.video !== 'function') {
if (Array.isArray(options.video)) {
@@ -704,6 +728,7 @@ export class Conversion {
}
this._options = options;
this._composable = composable;
this.input = options.input;
this.output = options.output;
@@ -857,7 +882,7 @@ export class Conversion {
const options = filteredTrackOptions[i]!;
for (const option of options) {
if (this._totalTrackCount === outputTrackCounts.total.max) {
if (this.output.tracks.length === outputTrackCounts.total.max) {
this.discardedTracks.push({
track,
reason: 'max_track_count_reached',
@@ -866,7 +891,12 @@ export class Conversion {
continue;
}
if (this._addedCounts[track.type] === outputTrackCounts[track.type].max) {
const addedCountOfType = this.output.tracks.reduce(
(count, t) => count + (t.type === track.type ? 1 : 0),
0,
);
if (addedCountOfType === outputTrackCounts[track.type].max) {
this.discardedTracks.push({
track,
reason: 'max_track_count_of_type_reached',
@@ -906,8 +936,10 @@ export class Conversion {
}
}
// Now, let's deal with metadata tags
// Now, let's deal with metadata tags. A composable conversion does not touch the output's metadata tags; that
// remains the responsibility of whoever owns the output.
if (!this._composable) {
const inputTags = await this.input.getMetadataTags();
let outputTags: MetadataTags;
@@ -927,18 +959,21 @@ export class Conversion {
const rawTagsAreUnchanged = inputTags.raw === outputTags.raw;
if (inputTags.raw && rawTagsAreUnchanged && !inputAndOutputFormatMatch) {
// If the input and output formats aren't the same, copying over raw metadata tags makes no sense and only
// results in junk tags, so let's cut them out.
// If the input and output formats aren't the same, copying over raw metadata tags makes no sense and
// only results in junk tags, so let's cut them out.
delete outputTags.raw;
}
this.output.setMetadataTags(outputTags);
}
// Let's check if the conversion can actually be executed
this.isValid = this._totalTrackCount >= outputTrackCounts.total.min
&& this._addedCounts.video >= outputTrackCounts.video.min
&& this._addedCounts.audio >= outputTrackCounts.audio.min
&& this._addedCounts.subtitle >= outputTrackCounts.subtitle.min;
if (!this._composable) {
this.isValid = this.output.hasEnoughTracks();
} else {
// Checking Output start validity is not up to us. We consider even zero-track conversions to be valid
this.isValid = true;
}
if (this._options.showWarnings ?? true) {
const warnElements: unknown[] = [];
@@ -1054,6 +1089,13 @@ export class Conversion {
);
}
if (this._composable && this.output.state === 'pending') {
throw new Error(
'A composable conversion requires the output to be started. Call start() on the output before executing'
+ ' the conversion.',
);
}
if (this._executed) {
throw new Error('Conversion cannot be executed twice.');
}
@@ -1088,7 +1130,10 @@ export class Conversion {
this.onProgress?.(0, 0);
}
if (!this._composable) {
await this.output.start();
}
this._start();
try {
@@ -1106,7 +1151,9 @@ export class Conversion {
throw new ConversionCanceledError();
}
if (!this._composable) {
await this.output.finalize();
}
if (this._computeProgress) {
const minTimestamp = Math.min(...this._maxTimestamps.values());
@@ -1129,8 +1176,11 @@ export class Conversion {
}
this._canceled = true;
if (!this._composable) {
await this.output.cancel();
}
}
/** @internal */
async _processVideoTrack(track: InputVideoTrack, trackOptions: ConversionVideoOptions, outputTrackId: number) {
@@ -1219,7 +1269,7 @@ export class Conversion {
for await (const packet of sink.packets(undefined, undefined, { verifyKeyPackets: true })) {
if (this._canceled) {
return;
break;
}
if (packet.timestamp >= this._endTimestamp) {
@@ -1377,7 +1427,7 @@ export class Conversion {
for await (using sample of sink.samples(this._startTimestamp, this._endTimestamp)) {
if (this._canceled) {
return;
break;
}
const adjustedSampleTimestamp = Math.max(sample.timestamp - this._startTimestamp, 0);
@@ -1400,7 +1450,9 @@ export class Conversion {
}
let ownGroup: OutputTrackGroup | null = null;
if (!trackOptions.group) {
if (!trackOptions.group && !this._composable) {
// Create per-track groups to replicate the input's pairability graph. Don't do this for composable
// conversions.
ownGroup = new OutputTrackGroup();
}
@@ -1414,8 +1466,6 @@ export class Conversion {
rotation: outputTrackRotation,
group: ownGroup ?? trackOptions.group,
});
this._addedCounts.video++;
this._totalTrackCount++;
this.utilizedTracks.push(track);
this._outputTrackIds.push(outputTrackId);
@@ -1474,7 +1524,7 @@ export class Conversion {
for await (const packet of sink.packets()) {
if (this._canceled) {
return;
break;
}
if (packet.timestamp >= this._endTimestamp) {
@@ -1595,7 +1645,7 @@ export class Conversion {
const sink = new AudioSampleSink(track);
for await (using sample of sink.samples(this._startTimestamp, this._endTimestamp)) {
if (this._canceled) {
return;
break;
}
if (needsPadding) {
@@ -1663,7 +1713,9 @@ export class Conversion {
}
let ownGroup: OutputTrackGroup | null = null;
if (!trackOptions.group) {
if (!trackOptions.group && !this._composable) {
// Create per-track groups to replicate the input's pairability graph. Don't do this for composable
// conversions.
ownGroup = new OutputTrackGroup();
}
@@ -1675,8 +1727,6 @@ export class Conversion {
disposition: await track.getDisposition(),
group: ownGroup ?? trackOptions.group,
});
this._addedCounts.audio++;
this._totalTrackCount++;
this.utilizedTracks.push(track);
this._outputTrackIds.push(outputTrackId);
+5 -5
View File
@@ -148,8 +148,8 @@ export class HlsMuxer extends Muxer {
async start(): Promise<void> {
const release = await this.mutex.acquire();
const someRelative = this.output._tracks.some(t => t.metadata.isRelativeToUnixEpoch);
const someNotRelative = this.output._tracks.some(t => !t.metadata.isRelativeToUnixEpoch);
const someRelative = this.output.tracks.some(t => t.metadata.isRelativeToUnixEpoch);
const someNotRelative = this.output.tracks.some(t => !t.metadata.isRelativeToUnixEpoch);
if (someRelative && someNotRelative) {
throw new Error(
'All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some'
@@ -180,14 +180,14 @@ export class HlsMuxer extends Muxer {
let keyPacketsOnlyPairingWarned = false;
// First, let's build the "sibling" groups induced by track pairability
for (const track of this.output._tracks) {
for (const track of this.output.tracks) {
if (track.type === 'video') {
hasVideo = true;
}
const pairableGroups = new Map<MediaCodec, OutputTrack[]>();
for (const otherTrack of this.output._tracks) {
for (const otherTrack of this.output.tracks) {
if (track === otherTrack) {
continue;
}
@@ -264,7 +264,7 @@ export class HlsMuxer extends Muxer {
const unpairedAudioTracks: OutputTrack[] = [];
// Now, create the top-level variant streams
for (const track of this.output._tracks) {
for (const track of this.output.tracks) {
const assignedGroupKeys = groupAssignment.get(track);
if (assignedGroupKeys) {
assert(assignedGroupKeys.length > 0);
+3 -3
View File
@@ -248,7 +248,7 @@ export class IsobmffMuxer extends Muxer {
this.initBoxWriter = new IsobmffBoxWriter(initWriter);
}
const holdsAvc = this.output._tracks.some(x => x.isVideoTrack() && x.source._codec === 'avc');
const holdsAvc = this.output.tracks.some(x => x.isVideoTrack() && x.source._codec === 'avc');
// Write the header
{
@@ -282,7 +282,7 @@ export class IsobmffMuxer extends Muxer {
// We're write at finalization
} else if (this.fastStart === 'reserve') {
// Validate that all tracks have set maximumPacketCount
for (const track of this.output._tracks) {
for (const track of this.output.tracks) {
if (track.metadata.maximumPacketCount === undefined) {
throw new Error(
'All tracks must specify maximumPacketCount in their metadata when using'
@@ -312,7 +312,7 @@ export class IsobmffMuxer extends Muxer {
}
private allTracksAreKnown() {
for (const track of this.output._tracks) {
for (const track of this.output.tracks) {
if (!track.source._closed && !this.trackDatas.some(x => x.track === track)) {
return false; // We haven't seen a sample from this open track yet
}
+1 -1
View File
@@ -691,7 +691,7 @@ export class MatroskaMuxer extends Muxer {
}
private allTracksAreKnown() {
for (const track of this.output._tracks) {
for (const track of this.output.tracks) {
if (!track.source._closed && !this.trackDatas.some(x => x.track === track)) {
return false; // We haven't seen a sample from this open track yet
}
+1 -1
View File
@@ -451,7 +451,7 @@ export class MpegTsMuxer extends Muxer {
}
private allTracksAreKnown() {
for (const track of this.output._tracks) {
for (const track of this.output.tracks) {
if (!track.source._closed && !this.trackDatas.some(x => x.track === track)) {
return false;
}
+1 -1
View File
@@ -297,7 +297,7 @@ export class OggMuxer extends Muxer {
}
allTracksAreKnown() {
for (const track of this.output._tracks) {
for (const track of this.output.tracks) {
if (!track.source._closed && !this.trackDatas.some(x => x.track === track)) {
return false; // We haven't seen a sample from this open track yet
}
+41 -13
View File
@@ -372,6 +372,11 @@ export class Output<
*/
readonly defaultTrackGroup = new OutputTrackGroup();
/**
* The tracks that have been added to this output. Treat it as a readonly field; to add tracks, use the methods.
*/
readonly tracks: OutputTrack[] = [];
/** @internal */
private _initTarget: T | (() => MaybePromise<T>) | null;
/** @internal */
@@ -383,8 +388,6 @@ export class Output<
/** @internal */
_rootWriterPromise: Promise<Writer> | null = null;
/** @internal */
_tracks: OutputTrack[] = [];
/** @internal */
_startPromise: Promise<void> | null = null;
/** @internal */
_cancelPromise: Promise<void> | null = null;
@@ -619,7 +622,7 @@ export class Output<
metadataCopy.group ??= this.defaultTrackGroup;
return this._addTrack(new OutputVideoTrack(
this._tracks.length + 1, this, source, metadataCopy,
this.tracks.length + 1, this, source, metadataCopy,
));
}
@@ -634,7 +637,7 @@ export class Output<
metadataCopy.group ??= this.defaultTrackGroup;
return this._addTrack(new OutputAudioTrack(
this._tracks.length + 1, this, source, metadataCopy,
this.tracks.length + 1, this, source, metadataCopy,
));
}
@@ -649,7 +652,7 @@ export class Output<
metadataCopy.group ??= this.defaultTrackGroup;
return this._addTrack(new OutputSubtitleTrack(
this._tracks.length + 1, this, source, metadataCopy,
this.tracks.length + 1, this, source, metadataCopy,
));
}
@@ -680,7 +683,7 @@ export class Output<
// Verify maximum track count constraints
const supportedTrackCounts = this.format.getSupportedTrackCounts();
const presentTracksOfThisType = this._tracks.reduce(
const presentTracksOfThisType = this.tracks.reduce(
(count, t) => count + (t.type === track.type ? 1 : 0),
0,
);
@@ -694,7 +697,7 @@ export class Output<
);
}
const maxTotalCount = supportedTrackCounts.total.max;
if (this._tracks.length === maxTotalCount) {
if (this.tracks.length === maxTotalCount) {
throw new Error(
`${this.format._name} does not support more than ${maxTotalCount} tracks`
+ `${maxTotalCount === 1 ? '' : 's'} in total.`,
@@ -748,12 +751,37 @@ export class Output<
}
}
this._tracks.push(track);
this.tracks.push(track);
track.source._connectedTrack = track;
return track;
}
/**
* Whether the output has enough tracks (of the correct type) to be started, based on the requirements of the output
* format.
*/
hasEnoughTracks() {
const supportedTrackCounts = this.format.getSupportedTrackCounts();
for (const trackType of ALL_TRACK_TYPES) {
const presentTracksOfThisType = this.tracks.reduce(
(count, track) => count + (track.type === trackType ? 1 : 0),
0,
);
const minCount = supportedTrackCounts[trackType].min;
if (presentTracksOfThisType < minCount) {
return false;
}
}
const totalMinCount = supportedTrackCounts.total.min;
if (this.tracks.length < totalMinCount) {
return false;
}
return true;
}
/**
* Starts the creation of the output file. This method should be called after all tracks have been added. Only after
* the output has started can media samples be added to the tracks.
@@ -764,7 +792,7 @@ export class Output<
// Verify minimum track count constraints
const supportedTrackCounts = this.format.getSupportedTrackCounts();
for (const trackType of ALL_TRACK_TYPES) {
const presentTracksOfThisType = this._tracks.reduce(
const presentTracksOfThisType = this.tracks.reduce(
(count, track) => count + (track.type === trackType ? 1 : 0),
0,
);
@@ -780,7 +808,7 @@ export class Output<
}
}
const totalMinCount = supportedTrackCounts.total.min;
if (this._tracks.length < totalMinCount) {
if (this.tracks.length < totalMinCount) {
throw new Error(
totalMinCount === supportedTrackCounts.total.max
? (`${this.format._name} requires exactly ${totalMinCount} track`
@@ -807,7 +835,7 @@ export class Output<
try {
await this._muxer.start();
const promises = this._tracks.map(track => track.source._start());
const promises = this.tracks.map(track => track.source._start());
await Promise.all(promises);
} finally {
release();
@@ -850,7 +878,7 @@ export class Output<
const release = await this._mutex.acquire();
try {
const promises = this._tracks.map(x => x.source._flushOrWaitForOngoingClose(true)); // Force close
const promises = this.tracks.map(x => x.source._flushOrWaitForOngoingClose(true)); // Force close
await Promise.all(promises);
await Promise.all([...this._unfinalizedTargets].map(target => target._close()));
@@ -883,7 +911,7 @@ export class Output<
const release = await this._mutex.acquire();
try {
const promises = this._tracks.map(x => x.source._flushOrWaitForOngoingClose(false));
const promises = this.tracks.map(x => x.source._flushOrWaitForOngoingClose(false));
await Promise.all(promises);
await this._muxer.finalize();
+259 -1
View File
@@ -11,7 +11,7 @@ import { Output, OutputTrackGroup } from '../../src/output.js';
import { BufferSource, CustomPathedSource, UrlSource } from '../../src/source.js';
import { expect, test } from 'vitest';
import { BufferTarget, PathedTarget } from '../../src/target.js';
import { Conversion } from '../../src/conversion.js';
import { Conversion, ConversionCanceledError } from '../../src/conversion.js';
import { assert } from '../../src/misc.js';
import { InputVideoTrack } from '../../src/input-track.js';
import { CanvasSource, EncodedAudioPacketSource } from '../../src/media-source.js';
@@ -402,3 +402,261 @@ test('Fractional audio sample boundary', async () => {
});
await conversion.execute();
});
test('Non-composable conversion requires a fresh output', async () => {
using input = new Input({
source: new UrlSource('/video.mp4'),
formats: ALL_FORMATS,
});
const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
output.addAudioTrack(new EncodedAudioPacketSource('aac')); // Makes the output non-fresh
await expect(Conversion.init({ input, output })).rejects.toThrow(/must be fresh/);
});
test('Composable init works on an output that already has a track, but not on a started one', async () => {
using input = new Input({
source: new UrlSource('/video.mp4'),
formats: ALL_FORMATS,
});
const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
output.addAudioTrack(new EncodedAudioPacketSource('aac')); // A user-added track
const conversion = await Conversion.init({
input,
output,
composable: true,
audio: { discard: true }, // Only contribute the video track
showWarnings: false,
});
expect(conversion.isValid).toBe(true);
expect(conversion.utilizedTracks).toHaveLength(1);
expect(conversion.utilizedTracks[0]!.type).toBe('video');
const startedOutput = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
startedOutput.addAudioTrack(new EncodedAudioPacketSource('aac'));
await startedOutput.start();
await expect(Conversion.init({ input, output: startedOutput, composable: true }))
.rejects.toThrow(/not have been started/);
await startedOutput.cancel();
});
test('Composable conversion rejects tags', async () => {
using input = new Input({
source: new UrlSource('/video.mp4'),
formats: ALL_FORMATS,
});
const makeOutput = () => new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
await expect(Conversion.init({
input,
output: makeOutput(),
composable: true,
tags: { title: 'Not allowed' },
})).rejects.toThrow(/tags cannot be set by a composable conversion/);
});
test('Composable conversion composes with a user-added track', async () => {
using input = new Input({
source: new UrlSource('/video.mp4'),
formats: ALL_FORMATS,
});
const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
const conversion = await Conversion.init({
input,
output,
composable: true,
audio: { discard: true }, // The user provides their own audio track
showWarnings: false,
});
expect(conversion.utilizedTracks).toHaveLength(1);
const audioSource = new EncodedAudioPacketSource('aac');
output.addAudioTrack(audioSource);
await output.start();
await Promise.all([
conversion.execute(),
(async () => {
await addAacPackets(audioSource, 5);
audioSource.close();
})(),
]);
// The composable conversion must not have finalized the output
expect(output.state).toBe('started');
await output.finalize();
expect(output.state).toBe('finalized');
using result = new Input({ source: new BufferSource(output.target.buffer!), formats: ALL_FORMATS });
const tracks = await result.getTracks();
expect(tracks.map(t => t.type).sort()).toEqual(['audio', 'video']);
const videoTrack = await result.getPrimaryVideoTrack();
const audioTrack = await result.getPrimaryAudioTrack();
expect(videoTrack).not.toBeNull();
expect(audioTrack).not.toBeNull();
expect(await videoTrack!.getCodec()).toBe('avc');
expect(await audioTrack!.getCodec()).toBe('aac');
expect(await videoTrack!.computeDuration()).toBeGreaterThan(4);
});
test('Two composable conversions compose into one output', async () => {
using input = new Input({
source: new UrlSource('/video.mp4'),
formats: ALL_FORMATS,
});
const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
const videoConversion = await Conversion.init({
input,
output,
composable: true,
audio: { discard: true },
showWarnings: false,
});
const audioConversion = await Conversion.init({
input,
output,
composable: true,
video: { discard: true },
showWarnings: false,
});
expect(videoConversion.utilizedTracks).toHaveLength(1);
expect(videoConversion.utilizedTracks[0]!.type).toBe('video');
expect(audioConversion.utilizedTracks).toHaveLength(1);
expect(audioConversion.utilizedTracks[0]!.type).toBe('audio');
await output.start();
await Promise.all([videoConversion.execute(), audioConversion.execute()]);
expect(output.state).toBe('started');
await output.finalize();
using result = new Input({ source: new BufferSource(output.target.buffer!), formats: ALL_FORMATS });
const tracks = await result.getTracks();
expect(tracks.map(t => t.type).sort()).toEqual(['audio', 'video']);
expect(await (await result.getPrimaryVideoTrack())!.getCodec()).toBe('avc');
expect(await (await result.getPrimaryAudioTrack())!.getCodec()).toBe('aac');
});
test('Composable conversion does not write metadata tags', async () => {
using input = new Input({
source: new UrlSource('/video.mp4'),
formats: ALL_FORMATS,
});
// Sanity check: this input carries metadata tags that a non-composable conversion would copy over
const inputTags = await input.getMetadataTags();
expect(inputTags.comment).toBeDefined();
const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
const conversion = await Conversion.init({
input,
output,
composable: true,
audio: { discard: true },
showWarnings: false,
});
// The conversion must not have touched the output's metadata tags
expect(Object.keys(output._metadataTags)).toHaveLength(0);
const audioSource = new EncodedAudioPacketSource('aac');
output.addAudioTrack(audioSource);
// The user sets their own tags; these must survive
output.setMetadataTags({ comment: 'User-owned' });
await output.start();
await Promise.all([
conversion.execute(),
(async () => {
await addAacPackets(audioSource, 5);
audioSource.close();
})(),
]);
await output.finalize();
using result = new Input({ source: new BufferSource(output.target.buffer!), formats: ALL_FORMATS });
const outTags = await result.getMetadataTags();
// Only the user's tag is present; the input's tags were not copied
expect(outTags.comment).toBe('User-owned');
});
test('Canceling a composable conversion leaves the output usable', async () => {
using input = new Input({
source: new UrlSource('/video.mp4'),
formats: ALL_FORMATS,
});
const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget() });
const conversion = await Conversion.init({
input,
output,
composable: true,
audio: { discard: true },
showWarnings: false,
});
const audioSource = new EncodedAudioPacketSource('aac');
output.addAudioTrack(audioSource);
await output.start();
const executePromise = conversion.execute();
void conversion.cancel();
await expect(executePromise).rejects.toBeInstanceOf(ConversionCanceledError);
// The output must not have been canceled by the composable conversion
expect(output.state).toBe('started');
// The user's own track can still finish, and the output can still be finalized
await addAacPackets(audioSource, 2);
audioSource.close();
await output.finalize();
expect(output.state).toBe('finalized');
using result = new Input({ source: new BufferSource(output.target.buffer!), formats: ALL_FORMATS });
const audioTrack = await result.getPrimaryAudioTrack();
expect(audioTrack).not.toBeNull();
expect(await audioTrack!.getCodec()).toBe('aac');
});
test('Track capacity works correctly with composable conversions', async () => {
using input = new Input({
source: new UrlSource('/video.mp4'),
formats: ALL_FORMATS,
});
const output = new Output({ format: new WavOutputFormat(), target: new BufferTarget() });
// The user already occupies the single audio slot that WAVE allows
output.addAudioTrack(new EncodedAudioPacketSource('pcm-s16'));
const conversion = await Conversion.init({
input,
output,
composable: true,
showWarnings: false,
});
// The conversion's audio track has no room left, so it gets discarded
expect(conversion.isValid).toBe(true);
expect(conversion.utilizedTracks).toHaveLength(0);
expect(conversion.discardedTracks).toHaveLength(2);
// WAVE allows only one track in total, so the total-count check fires before the per-type one
expect(conversion.discardedTracks[0]!.reason).toBe('max_track_count_reached');
});