---
url: /guide/extensions/aac-encoder.md
description: >-
The @mediabunny/aac-encoder extension provides a fast AAC encoder polyfill for
use in the browser and on the server.
---
# @mediabunny/aac-encoder
Some browsers lack support for AAC encoding in their WebCodecs implementations. This extension package provides a reliable AAC-LC encoder for use with Mediabunny. It is implemented using Mediabunny's [custom coder API](../supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [FFmpeg](https://ffmpeg.org/)'s AAC encoder under the hood.
## Installation
This library peer-depends on Mediabunny. Install both using npm:
```bash
npm install mediabunny @mediabunny/aac-encoder
```
Alternatively, directly include them using a script tag:
```html
```
This will expose the global objects `Mediabunny` and `MediabunnyAacEncoder`. Use `mediabunny-aac-encoder.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
## Usage
```ts
import { registerAacEncoder } from '@mediabunny/aac-encoder';
registerAacEncoder();
```
That's it - Mediabunny now uses the registered AAC encoder automatically.
If you want to be more correct, check for native browser support first:
```ts
import { canEncodeAudio } from 'mediabunny';
import { registerAacEncoder } from '@mediabunny/aac-encoder';
if (!(await canEncodeAudio('aac'))) {
registerAacEncoder();
}
```
## Example
Here, we convert an input file to an MP4 with AAC audio:
```ts
import {
Input,
ALL_FORMATS,
BlobSource,
Output,
BufferTarget,
Mp4OutputFormat,
canEncodeAudio,
Conversion,
} from 'mediabunny';
import { registerAacEncoder } from '@mediabunny/aac-encoder';
if (!(await canEncodeAudio('aac'))) {
// Only register the custom encoder if there's no native support
registerAacEncoder();
}
const input = new Input({
source: new BlobSource(file), // From a file picker, for example
formats: ALL_FORMATS,
});
const output = new Output({
format: new Mp4OutputFormat(),
target: new BufferTarget(),
});
const conversion = await Conversion.init({
input,
output,
});
await conversion.execute();
output.target.buffer; // => ArrayBuffer containing the MP4 file
```
---
---
url: /guide/extensions/ac3.md
description: >-
The @mediabunny/ac3 extension provides fast AC-3 and E-AC-3 decoders and
encoders for both browser and server environments.
---
# @mediabunny/ac3
Browsers have no support for AC-3 (Dolby Digital) or E-AC-3 (Dolby Digital Plus) in their WebCodecs implementations. This extension package provides both a decoder and encoder for use with Mediabunny, allowing you to decode and encode these codecs directly in the browser. It is implemented using Mediabunny's [custom coder API](../supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [FFmpeg](https://ffmpeg.org/)'s AC-3 and E-AC-3 coders under the hood.
## Installation
This library peer-depends on Mediabunny. Install both using npm:
```bash
npm install mediabunny @mediabunny/ac3
```
Alternatively, directly include them using a script tag:
```html
```
This will expose the global objects `Mediabunny` and `MediabunnyAc3`. Use `mediabunny-ac3.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
## Usage
```ts
import { registerAc3Decoder, registerAc3Encoder } from '@mediabunny/ac3';
registerAc3Decoder();
registerAc3Encoder();
```
That's it - Mediabunny now uses the registered AC-3/E-AC-3 decoder and encoder automatically.
---
---
url: /guide/extensions/dts.md
description: >-
The @mediabunny/dts extension provides fast DTS decoders and encoders for both
browser and server environments.
---
# @mediabunny/dts
Browsers have no support for the DTS audio codec in their WebCodecs implementations. This extension package provides both a decoder and encoder for use with Mediabunny, allowing you to decode and encode this codec directly in the browser. It is implemented using Mediabunny's [custom coder API](../supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [FFmpeg](https://ffmpeg.org/)'s DTS coders under the hood.
## Installation
This library peer-depends on Mediabunny. Install both using npm:
```bash
npm install mediabunny @mediabunny/dts
```
Alternatively, directly include them using a script tag:
```html
```
This will expose the global objects `Mediabunny` and `MediabunnyDts`. Use `mediabunny-dts.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
## Usage
```ts
import { registerDtsDecoder, registerDtsEncoder } from '@mediabunny/dts';
registerDtsDecoder();
registerDtsEncoder();
```
That's it - Mediabunny now uses the registered DTS decoder and encoder automatically.
---
---
url: /guide/extensions/flac-encoder.md
description: >-
The @mediabunny/flac-encoder extension provides a highly-performant FLAC
encoder polyfill for use in the browser and on the server.
---
# @mediabunny/flac-encoder
No browser currently supports FLAC encoding in their WebCodecs implementations. This extension package provides a reliable FLAC encoder for use with Mediabunny. It is implemented using Mediabunny's [custom coder API](../supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [libFLAC](https://github.com/xiph/flac) under the hood.
## Installation
This library peer-depends on Mediabunny. Install both using npm:
```bash
npm install mediabunny @mediabunny/flac-encoder
```
Alternatively, directly include them using a script tag:
```html
```
This will expose the global objects `Mediabunny` and `MediabunnyFlacEncoder`. Use `mediabunny-flac-encoder.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
## Usage
```ts
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
registerFlacEncoder();
```
That's it - Mediabunny now uses the registered FLAC encoder automatically.
If you want to be more correct, check for native browser support first:
```ts
import { canEncodeAudio } from 'mediabunny';
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
if (!(await canEncodeAudio('flac'))) {
registerFlacEncoder();
}
```
## Example
Here, we convert an input file to a FLAC file:
```ts
import {
Input,
ALL_FORMATS,
BlobSource,
Output,
BufferTarget,
FlacOutputFormat,
canEncodeAudio,
Conversion,
} from 'mediabunny';
import { registerFlacEncoder } from '@mediabunny/flac-encoder';
if (!(await canEncodeAudio('flac'))) {
registerFlacEncoder();
}
const input = new Input({
source: new BlobSource(file), // From a file picker, for example
formats: ALL_FORMATS,
});
const output = new Output({
format: new FlacOutputFormat(),
target: new BufferTarget(),
});
const conversion = await Conversion.init({
input,
output,
});
await conversion.execute();
output.target.buffer; // => ArrayBuffer containing the FLAC file
```
---
---
url: /guide/extensions/mp3-encoder.md
description: >-
The @mediabunny/mp3-encoder extension provides a highly-performant MP3 encoder
polyfill for use in the browser and on the server.
---
# @mediabunny/mp3-encoder
Browsers typically have no support for MP3 encoding in their WebCodecs implementations. Given the ubiquity of the format, this extension package provides an MP3 encoder for use with Mediabunny. It is implemented using Mediabunny's [custom coder API](../supported-formats-and-codecs#custom-coders) and uses a highly-performant WASM build of the [LAME MP3 Encoder](https://lame.sourceforge.io/) under the hood.
## Installation
This library peer-depends on Mediabunny. Install both using npm:
```bash
npm install mediabunny @mediabunny/mp3-encoder
```
Alternatively, directly include them using a script tag:
```html
```
This will expose the global objects `Mediabunny` and `MediabunnyMp3Encoder`. Use `mediabunny-mp3-encoder.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
## Usage
```ts
import { registerMp3Encoder } from '@mediabunny/mp3-encoder';
registerMp3Encoder();
```
That's it - Mediabunny now uses the registered MP3 encoder automatically.
If you want to be more correct, check for native browser support first:
```ts
import { canEncodeAudio } from 'mediabunny';
import { registerMp3Encoder } from '@mediabunny/mp3-encoder';
if (!(await canEncodeAudio('mp3'))) {
registerMp3Encoder();
}
```
## Example
Here, we convert an input file to an MP3:
```ts
import {
Input,
ALL_FORMATS,
BlobSource,
Output,
BufferTarget,
Mp3OutputFormat,
canEncodeAudio,
Conversion,
} from 'mediabunny';
import { registerMp3Encoder } from '@mediabunny/mp3-encoder';
if (!(await canEncodeAudio('mp3'))) {
// Only register the custom encoder if there's no native support
registerMp3Encoder();
}
const input = new Input({
source: new BlobSource(file), // From a file picker, for example
formats: ALL_FORMATS,
});
const output = new Output({
format: new Mp3OutputFormat(),
target: new BufferTarget(),
});
const conversion = await Conversion.init({
input,
output,
});
await conversion.execute();
output.target.buffer; // => ArrayBuffer containing the MP3 file
```
## Implementation details
This library implements an MP3 encoder by registering a custom encoder class with Mediabunny. This class, when initialized, spawns a worker which then immediately loads a WASM build of the LAME MP3 encoder. Then, raw data is sent to the worker and encoded data is received from it. These encoded chunks are then concatenated in the main thread and properly split into separate MP3 frames.
Great care was put into ensuring maximum compatibility of this package; it works with bundlers, directly in the browser, as well as in Node, Deno, and Bun. All code (including worker & WASM) are bundled into a single file, eliminating the need for CDNs or WASM path arguments. This packages therefore serves as a reference implementation of WASM-based encoder extensions for Mediabunny.
The WASM build itself is a performance-optimized, SIMD-enabled build of LAME 3.100, with all unneeded features disabled. Because maximum performance was the priority, the build is slighter bigger, but ~130 kB gzipped is still very reasonable in my opinion. In my tests, it encodes 5 seconds of audio in ~90 milliseconds (55x real-time speed).
---
---
url: /guide/extensions/prores.md
description: >-
The @mediabunny/prores extension provides an extremely fast Apple ProRes
decoder for the browser.
---
# @mediabunny/prores
Browsers have no support for Apple ProRes in their WebCodecs implementations. This extension package provides a decoder for use with Mediabunny, allowing you to decode ProRes directly in the browser at unprecedented speed. It is implemented using Mediabunny's [custom coder API](https://mediabunny.dev/guide/supported-formats-and-codecs#custom-coders) and uses [TurboRes](https://github.com/Vanilagy/turbores), an extremely fast WASM-based ProRes decoder, under the hood.
## Installation
This library peer-depends on Mediabunny. Install both using npm:
```bash
npm install mediabunny @mediabunny/prores
```
Alternatively, directly include them using a script tag:
```html
```
This will expose the global objects `Mediabunny` and `MediabunnyProres`. Use `mediabunny-prores.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
## Setup
`@mediabunny/prores` can make use of shared-memory multithreading to achieve maximum performance. To enable this in browsers, your website must be cross-origin isolated by setting the following response headers:
```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
Alternatively, you can use:
```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: credentialless
```
which is generally more permissive but is not supported in Safari (of course).
***
If you cannot enable cross-origin isolation, `@mediabunny/prores` will fall back to a slower multithreading algorithm.
## Usage
```ts
import { registerProresDecoder } from '@mediabunny/prores';
registerProresDecoder();
```
That's it - Mediabunny now uses the registered ProRes decoder automatically.
---
---
url: /guide/extensions/server.md
description: >-
Add full video and audio decoder and encoder support for use in server-side
environments, like Node, Bun, or Deno.
---
# @mediabunny/server
By default, Mediabunny requires a browser environment for full access to decoders, encoders, and video processing features. `@mediabunny/server` uses [NodeAV](https://github.com/seydx/node-av) to polyfill this functionality for server-side environments such as Node, Bun, or Deno, enabling the usage of all Mediabunny features on the server. The result is a server-side media processing API that integrates naturally with TypeScript as opposed to the awkwardness and inefficiencies of calling out to the FFmpeg CLI.
Features added by this package include:
* Video decoders and encoders for AVC (H.264), HEVC (H.265), VP8, VP9, AV1, and ProRes. Supports both length-prefixed and Annex B AVC/HEVC as well as transparent video via VP9 and ProRes.
* Audio decoders and encoders for AAC, MP3, Vorbis, Opus, FLAC, AC-3, E-AC-3 and DTS. Supports AAC in both AAC and ADTS formats.
* Video frame transformation support (resize, rotate, flip, crop)
* Automatic hardware acceleration on all platforms (macOS, Linux, Windows)
* Built-in multithreading
* Zero-copy decode and encode paths
## Installation
This library peer-depends on Mediabunny. Install both using npm:
```bash
npm install mediabunny @mediabunny/server
```
## Usage
```ts
import { registerMediabunnyServer } from '@mediabunny/server';
registerMediabunnyServer();
```
That's it - you now have access to the full Mediabunny feature set on the server.
***
An optional `options` parameter is available for further configuration:
```ts
import { registerMediabunnyServer } from '@mediabunny/server';
import * as NodeAv from 'node-av';
registerMediabunnyServer({
// Use a specific hardware rendering device:
hardwareContext: NodeAv.HardwareContext.create(
NodeAv.AV_HWDEVICE_TYPE_VAAPI,
'/dev/dri/renderD128',
),
});
```
## Upload media compression example
Here, we set up a simple media compression server in Node.js. The client's request body is streamed to Mediabunny, the media gets processed, and the output is streamed directly to the disk. Memory usage is O(1) due to pipelining, and an overly fast uploader is automatically slowed down due to stream backpressure.
```ts
import { ALL_FORMATS, Conversion, FilePathTarget, Input, Mp4OutputFormat, Output, Quality, ReadableStreamSource } from "mediabunny";
import { registerMediabunnyServer } from "@mediabunny/server";
import { Readable } from "node:stream";
import http from "node:http";
registerMediabunnyServer();
const server = http.createServer(async (req, res) => {
// Read the request body as a stream
const stream = Readable.toWeb(req) as ReadableStream;
const input = new Input({
source: new ReadableStreamSource(stream),
formats: ALL_FORMATS,
});
// Stream the output directly to the disk, could also stream to S3 etc.
const output = new Output({
format: new Mp4OutputFormat(),
target: new FilePathTarget(`./converted-${crypto.randomUUID()}.mp4`),
});
try {
const conversion = await Conversion.init({
input,
output,
video: async track => ({
codec: 'avc',
height: Math.min(720, await track.getDisplayHeight()),
quality: new Quality('medium'),
}),
});
await conversion.execute();
res.statusCode = 204;
res.end();
} catch (error) {
res.statusCode = 500;
res.end();
console.error("Error processing media:", error);
}
});
server.listen(3000);
```
For all the other ways to use Mediabunny, refer to its [guide](https://mediabunny.dev/guide/introduction).
## Performance
`@mediabunny/server` is extremely performant as it is a thin wrapper around [NodeAV](https://github.com/seydx/node-av), which itself is a thin wrapper around the FFmpeg C API. All decoders and encoders automatically run on separate threads, keeping the main thread unblocked. Hardware acceleration is automatically detected and utilized on all operating systems whenever available (unless explicitly disabled using `hardwareAcceleration: 'prefer-software'`). Video frame and audio sample data is never copied from FFmpeg unless explicitly requested via `VideoSample.copyTo()` and `AudioSample.copyTo()`, and zero-copy GPU decode -> encode paths are used automatically whenever possible.
## Advanced usage
### Usage with NodeAV
`@mediabunny/server` provides `AvFrameVideoSampleResource` and `AvFrameAudioSampleResource` as a means to create `VideoSample` and `AudioSample` instances that are directly backed by data residing in NodeAV's [`Frame`](https://seydx.github.io/node-av/api/lib/classes/Frame.html) (and therefore FFmpeg's `AVFrame`) without ever having to copy data to or from JavaScript. Reading NodeAV's documentation can help you make full use of this integration.
To convert between Mediabunny and NodeAV (FFmpeg) worlds, you can do this:
```ts
import { VideoSample, AudioSample } from 'mediabunny';
import { AvFrameVideoSampleResource, AvFrameAudioSampleResource, toAvFrame } from '@mediabunny/server';
// Frame -> VideoSample
new VideoSample(new AvFrameVideoSampleResource(frame), { timestamp });
// Frame -> AudioSample
new AudioSample(new AvFrameAudioSampleResource(frame));
// (uses the timestamp in the frame)
// VideoSample -> Frame
await toAvFrame(videoSample, frame);
// AudioSample -> Frame
await toAvFrame(audioSample, frame);
```
#### Electron example
For example, when using Electron, we may want to capture the app's contents without moving video data from the GPU to the CPU:
```ts
import { VideoSample } from 'mediabunny';
import { AvFrameVideoSampleResource } from '@mediabunny/server';
import { HardwareContext, SharedTexture, AV_HWDEVICE_TYPE_VIDEOTOOLBOX } from 'node-av';
// Create hardware context (platform-specific)
const hw = HardwareContext.create(AV_HWDEVICE_TYPE_VIDEOTOOLBOX);
using sharedTexture = SharedTexture.create(hw);
// In Electron paint event with offscreen rendering
offscreen.webContents.on('paint', (event) => {
const texture = event.texture;
if (!texture?.textureInfo) {
return;
}
// Import as hardware frame (zero-copy)
const frame = sharedTexture.importTexture(texture.textureInfo, { pts: 0n });
const sample = new VideoSample(new AvFrameVideoSampleResource(frame), {
timestamp: 0,
duration: 0,
});
texture.release();
});
```
#### Microphone recording example
Here, we're using NodeAV's Device API to access the user's microphone:
```ts
import { AudioSample } from 'mediabunny';
import { AvFrameAudioSampleResource } from '@mediabunny/server';
import { DeviceAPI, Decoder } from 'node-av';
await using mic = await DeviceAPI.openMicrophone();
const audioStream = mic.audio()!;
using decoder = await Decoder.create(audioStream);
let firstTimestamp: number | null = null;
for await (const frame of decoder.frames(mic.packets(audioStream.index))) {
if (!frame) {
break;
}
const sample = new AudioSample(new AvFrameAudioSampleResource(frame));
if (firstTimestamp === null) {
firstTimestamp = sample.timestamp;
}
// Offset timestamps so they start at 0
sample.setTimestamp(sample.timestamp - firstTimestamp);
// Do something with the sample now, like passing it to an AudioSampleSource
// ...
}
```
### Video and audio processing
Browser environments ship with many API goodies such as the Canvas 2D API which are a naturally great fit for doing video frame processing, and they integrate well with Mediabunny. On the server, these APIs don't exist, so other approaches must be used:
#### VideoSample.transform()
This method allows for simple transformations on `VideoSample` instances and works when `@mediabunny/server` has been registered:
```ts
const transformed = await sample.transform({
width: 640,
height: 360,
fit: 'cover',
});
```
#### NodeAV filter graphs
FFmpeg's `libavfilter` is an incredibly powerful and generic media processing library, and all of it is directly accessible via NodeAV. It works for both video as well as audio data.
For example, here we combine Mediabunny's Conversion API with a filter graph to grayscale a video:
```ts
import { Conversion } from 'mediabunny';
import { AvFrameVideoSampleResource, toAvFrame } from '@mediabunny/server';
import { Frame, FilterAPI } from 'node-av';
async function* one(f: Frame) { yield f; }
const conversion = await Conversion.init({
// ...
video: {
process: async (sample) => {
// VideoSample -> Frame
using inFrame = new Frame();
inFrame.alloc();
await toAvFrame(sample, inFrame);
// Frame -> filter -> AvFrameVideoSampleResource
using filter = FilterAPI.create('format=gray');
for await (const outFrame of filter.frames(one(inFrame))) {
return outFrame && new AvFrameVideoSampleResource(outFrame);
}
return null;
},
},
// ...
});
await conversion.execute();
```
#### Canvas API polyfills
Libraries like [Skia Canvas](https://github.com/samizdatco/skia-canvas) provide GPU-enabled polyfills for the Canvas 2D API. Using it with Mediabunny is simply a matter of converting from and to the Canvas API:
```ts
const width = videoSample.displayWidth;
const height = videoSample.displayHeight;
const canvas = new Canvas(width, height);
const ctx = canvas.getContext('2d');
// Copy data from VideoSample
const imageData = ctx.createImageData(width, height);
await videoSample.copyTo(imageData.data, { format: 'RGBA' });
ctx.putImageData(imageData, 0, 0);
// Issue draw commands
ctx.fillStyle = 'red';
ctx.fillRect(20, 20, 100, 60);
// Convert to VideoSample again
const pixels = ctx.getImageData(0, 0, width, height).data;
return new VideoSample(pixels, {
format: 'RGBA',
codedWidth: width,
codedHeight: height,
timestamp: videoSample.timestamp,
duration: videoSample.duration,
});
```
## Controlling logging
Especially in command-line applications you usually don't want Mediabunny interfering with your stdout and stderr output. Mediabunny provides ways to control its console output:
```ts
import { Logging, LogLevel } from 'mediabunny';
// The default: Mediabunny can log errors, warnings, and information messages.
Logging.level = LogLevel.Info;
// Only log warnings and errors.
Logging.level = LogLevel.Warnings;
// Only log errors.
Logging.level = LogLevel.Errors;
// Don't log anything at all.
Logging.level = LogLevel.Silent;
```
You can also hook into log events:
```ts
Logging.on('error', (args: unknown[]) => {
// Handle error message
});
Logging.on('warn', (args: unknown[]) => {
// Handle warning message
});
Logging.on('info', (args: unknown[]) => {
// Handle info message
});
```
## Implementation details
`@mediabunny/server` uses [NodeAV](https://github.com/seydx/node-av) under the hood which provides N-API C bindings to FFmpeg's C API. Using NodeAV, this package implements [custom decoders and encoders](https://mediabunny.dev/guide/supported-formats-and-codecs#custom-coders) by directly using the APIs provided by `libavcodec`.
For encoding, video frames and audio samples are transferred to FFmpeg by converting them to an `AVFrame` and are then passed to the correct encoder. The resulting packets are then normalized into the format expected by WebCodecs and the [Mediabunny Codec Registry](https://mediabunny.dev/codec-registry/overview). For decoding, the above process is inverted: packets and decoder metadata are passed to the correct decoder, and the resulting `AVFrame` instances are wrapped in `VideoSample` or `AudioSample` instances. Video frame transformations (resize, rotate, flip, crop) are implemented using the `libavfilter` API.
Whenever possible, `AVFrame`s are never copied over to JavaScript unless explicitly needed. This enables zero-copy decode -> transformation -> encode paths.
---
---
url: /guide/extensions/truehd.md
description: >-
The @mediabunny/truehd extension provides fast Dolby TrueHD decoders and
encoders for both browser and server environments.
---
# @mediabunny/truehd
Browsers have no support for the Dolby TrueHD audio codec in their WebCodecs implementations. This extension package provides both a decoder and encoder for use with Mediabunny, allowing you to decode and encode this codec directly in the browser. It is implemented using Mediabunny's [custom coder API](../supported-formats-and-codecs#custom-coders) and uses a fast, size-optimized WASM build of [FFmpeg](https://ffmpeg.org/)'s TrueHD coders under the hood.
## Installation
This library peer-depends on Mediabunny. Install both using npm:
```bash
npm install mediabunny @mediabunny/truehd
```
Alternatively, directly include them using a script tag:
```html
```
This will expose the global objects `Mediabunny` and `MediabunnyTrueHd`. Use `mediabunny-truehd.d.ts` to provide types for these globals. You can download the built distribution files from the [releases page](https://github.com/Vanilagy/mediabunny/releases).
## Usage
```ts
import { registerTrueHdDecoder, registerTrueHdEncoder } from '@mediabunny/truehd';
registerTrueHdDecoder();
registerTrueHdEncoder();
```
That's it - Mediabunny now uses the registered TrueHD decoder and encoder automatically.
---
---
url: /codec-registry/alaw.md
description: >-
A-law companded PCM audio codec definition, defining legal codec strings,
decoder configs, and packet data formats.
---
# A-law PCM codec registration
## Description
The A-law companded PCM audio codec, specified in [ITU-T G.711](https://www.itu.int/rec/T-REC-G.711) Tables 1a and 1b.
## Codec ID
```ts
'alaw'
```
## `EncodedPacket` data
The packet's data must be a sequence of bytes of arbitrary length (divisible by the channel count), where each byte is an A-law encoded PCM sample. For multichannel audio, samples from different channels are interleaved.
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
```ts
'alaw'
```
## `AudioDecoderConfig` description
`description` is not used for this codec.
---
---
url: /codec-registry/aac.md
description: >-
Advanced Audio Coding (AAC) audio codec definition, defining legal codec
strings, decoder configs, and packet data formats.
---
# AAC codec registration
## Description
The Advanced Audio Coding (AAC) audio codec, specified in [ISO/IEC 14496-3](https://www.iso.org/standard/76383.html).
An AAC bitstream can have either of two formats:
* *AAC* (raw), where packets contain raw AAC frames (syntax element `raw_data_block()`) as defined in [ISO/IEC 14496-3](https://www.iso.org/standard/76383.html) Section 4.4.2.1. Here, codec metadata is provided out-of-band.
* *ADTS*, where packets contain ADTS frames as defined in [ISO/IEC 14496-3](https://www.iso.org/standard/76383.html) Section 1.A.3.2. Here, codec metadata is provided in-band in each ADTS frame header.
All packets within the bitstream must have the same format.
## Codec ID
```ts
'aac'
```
## `EncodedPacket` data
If the bitstream is in the *AAC* (raw) format, the packet's data must be a raw AAC frame (syntax element `raw_data_block()`) as defined in [ISO/IEC 14496-3](https://www.iso.org/standard/76383.html) Section 4.4.2.1.
If the bitstream is in the *ADTS* format, the packet's data must be an ADTS frame as defined in [ISO/IEC 14496-3](https://www.iso.org/standard/76383.html) Section 1.A.3.2.
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
The following fully qualified codec strings are recognized:
* `'mp4a.40.2'` — MPEG-4 AAC-LC
* `'mp4a.40.02'` — MPEG-4 AAC-LC (leading zero for Aud-OTI compatibility)
* `'mp4a.40.5'` — MPEG-4 HE-AAC v1 (AAC-LC + SBR)
* `'mp4a.40.05'` — MPEG-4 HE-AAC v1 (leading zero for Aud-OTI compatibility)
* `'mp4a.40.29'` — MPEG-4 HE-AAC v2 (AAC-LC + SBR + PS)
* `'mp4a.67'` — MPEG-2 AAC-LC
## `AudioDecoderConfig` description
If the bitstream is in the *AAC* (raw) format, `description` must be an `AudioSpecificConfig` as defined in [ISO/IEC 14496-3](https://www.iso.org/standard/76383.html) Section 1.6.2.1.
If the bitstream is in the *ADTS* format, `description` must be undefined.
---
---
url: /codec-registry/ac3.md
description: >-
Dolby Digital (AC-3) audio codec definition, defining legal codec strings,
decoder configs, and packet data formats.
---
# AC-3 codec registration
## Description
The Dolby Digital (AC-3) audio codec, specified in [ETSI TS 102 366](https://www.etsi.org/deliver/etsi_ts/102300_102399/102366/01.04.01_60/ts_102366v010401p.pdf).
## Codec ID
```ts
'ac3'
```
## `EncodedPacket` data
The packet's data must be a sync frame (syntactic element `syncframe()`) as defined in Section 4.3 of [ETSI TS 102 366](https://www.etsi.org/deliver/etsi_ts/102300_102399/102366/01.04.01_60/ts_102366v010401p.pdf), beginning with the sync word `0x0B77`.
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
```ts
'ac-3'
```
## `AudioDecoderConfig` description
`description` is not used for this codec.
---
---
url: /codec-registry/av1.md
description: >-
AOMedia Video 1 (AV1) video codec definition, defining legal codec strings,
decoder configs, and packet data formats.
---
# AV1 codec registration
## Description
The AOMedia Video 1 (AV1) video codec, specified in the [AV1 Bitstream & Decoding Process Specification](https://aomediacodec.github.io/av1-spec/).
## Codec ID
```ts
'av1'
```
## `EncodedPacket` data
The packet's data must comply with the low-overhead bitstream format as defined in Section 5 of the [AV1 Bitstream & Decoding Process Specification](https://aomediacodec.github.io/av1-spec/).
## `EncodedPacket` type
If the packet's type is `'key'`, then the packet is expected to contain a frame with `frame_type` of `KEY_FRAME`, as defined in Section 6.8.2 of the [AV1 Bitstream & Decoding Process Specification](https://aomediacodec.github.io/av1-spec/).
## `VideoDecoderConfig` codec string
The full codec string begins with the prefix `'av01.'`, with a variable-length suffix as specified in Section 5 of the [AV1 Codec ISO Media File Format Binding](https://aomediacodec.github.io/av1-isobmff/).
## `VideoDecoderConfig` description
`description` is not used for this codec.
## Quantizer range
AV1 has quantizer support and supports quantizer values in the range \[0, 255].
---
---
url: /codec-registry/avc.md
description: >-
Advanced Video Coding (H.264) video codec definition, defining legal codec
strings, decoder configs, and packet data formats.
---
# AVC (H.264) codec registration
## Description
The Advanced Video Coding (H.264) video codec, specified in [Rec. ITU-T H.264](https://www.itu.int/rec/T-REC-H.264) / [ISO/IEC 14496-10](https://www.iso.org/standard/87574.html).
An AVC bitstream can have either of two formats:
* *Canonical* (length-prefixed), as defined in [ISO/IEC 14496-15](https://www.iso.org/standard/89118.html) Section 5.3.2. Here, video parameter sets (SPS/PPS) are provided out-of-band.
* *Annex B*, as defined in [Rec. ITU-T H.264](https://www.itu.int/rec/T-REC-H.264) Annex B. Here, video parameter sets (SPS/PPS) must be provided in-band in the respective NALUs.
All packets within the bitstream must have the same format.
## Codec ID
```ts
'avc'
```
## `EncodedPacket` data
The packet's data must be an access unit as defined in [Rec. ITU-T H.264](https://www.itu.int/rec/T-REC-H.264) Section 7.4.1.2, in either *canonical* or *Annex B* format.
## `EncodedPacket` type
If the packet's type is `'key'`, then the packet is expected to contain a primary coded picture from which decoding can begin. Additionally, if the bitstream's format is *Annex B*, then this packet is also expected to contain the necessary video parameter sets to initialize the decoder.
## `VideoDecoderConfig` codec string
The full codec string begins with the prefix `'avc1.'` or `'avc3.'`, with a suffix of 6 characters as described respectively in Section 3.4 of [RFC 6381](https://www.rfc-editor.org/rfc/rfc6381) and Section 5.4.1 of [ISO/IEC 14496-15](https://www.iso.org/standard/89118.html).
## `VideoDecoderConfig` description
If the bitstream is in the *canonical* (length-prefixed) format, `description` must be an `AVCDecoderConfigurationRecord` as defined in [ISO/IEC 14496-15](https://www.iso.org/standard/89118.html) Section 5.3.3.1.
If the bitstream is in the *Annex B* format, `description` must be undefined.
## Quantizer range
AVC has quantizer support and supports quantizer values in the range \[0, 51].
---
---
url: /guide/converting-media-files.md
description: >-
Efficiently convert any media file to any format, directly in the browser.
Optionally apply trimming, video resizing, rotation, custom overlays, and
more.
---
# Converting media files
The [reading](./reading-media-files) and [writing](./writing-media-files) primitives in Mediabunny provide everything you need to convert media files. However, since this is such a common operation and the details can be tricky, Mediabunny ships with a built-in file conversion abstraction.
It has the following features:
* Transmuxing (changing the container format while copying media data)
* Transcoding (changing a track's codec)
* Track removal
* Compression
* Trimming
* Video resizing & fitting
* Video rotation
* Video cropping
* Video frame rate adjustment
* Video transparency removal/preservation
* Audio resampling
* Audio up/downmixing
* User-defined video & audio processing
The conversion API was built to be simple, versatile, composable and performant.
## Basic usage
### Running a conversion
Each conversion process is represented by an instance of `Conversion`. Create a new instance using `Conversion.init(...)`, then run the conversion using `.execute()`.
Here, we're converting to WebM:
```ts
import {
Input,
Output,
WebMOutputFormat,
BufferTarget,
Conversion,
} from 'mediabunny';
const input = new Input({ ... });
const output = new Output({
format: new WebMOutputFormat(),
target: new BufferTarget(),
});
const conversion = await Conversion.init({ input, output });
if (!conversion.isValid) {
// Conversion is invalid and cannot be executed without error.
// This field gives reasons for why tracks were discarded:
conversion.discardedTracks; // => DiscardedTrack[]
return;
}
await conversion.execute();
// output.target.buffer contains the final file
```
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). 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:
* Copying media data whenever possible, otherwise transcoding it
* Dropping tracks that aren't supported in the output format
You should consider inspecting `isValid` and the [discarded tracks](#discarded-tracks) before executing a `Conversion`.
### Monitoring progress
To monitor the progress of a `Conversion`, set its `onProgress` property *before* calling `execute`:
```ts
const conversion = await Conversion.init({ input, output });
conversion.onProgress = (progress: number) => {
// `progress` is a number between 0 and 1 (inclusive)
};
await conversion.execute();
```
This callback is called each time the progress of the conversion advances.
::: warning
A progress of `1` doesn't indicate the conversion has finished; the conversion is only finished once the promise returned by `.execute()` resolves.
:::
::: warning
Tracking conversion progress can slightly affect performance as it requires knowledge of the input file's total duration. This is usually negligible but should be avoided when using append-only input sources such as [`ReadableStreamSource`](./reading-media-files#readablestreamsource).
:::
If you want to monitor the output size of the conversion (in bytes), simply use the `write` event on your `Target`:
```ts
let currentFileSize = 0;
const stopListening = output.target.on('write', ({ start, end }) => {
currentFileSize = Math.max(currentFileSize, end);
});
```
### Canceling a conversion
Sometimes, you may want to cancel an ongoing conversion process. For this, use the `cancel` method:
```ts
await conversion.cancel(); // Resolves once the conversion is canceled
```
This automatically frees up all resources used by the conversion process and will cause any ongoing call to `execute` to throw a `ConversionCanceledError`.
If the conversion is [composable](#composable-conversions), the corresponding `Output` is not canceled and remains usable after conversion cancellation.
### Pausing a conversion
You can pause a conversion mid-execution and resume it later. For this, pass a pause signal to the `execute` method:
```ts
const controller = new AbortController();
button.onclick = () => controller.abort();
await conversion.execute({
pauseSignal: controller.signal,
});
if (conversion.state === 'idle') {
// Paused before completion
} else if (conversion.state === 'done') {
// Ran to completion
}
```
An unfinished conversion can simply be resumed with another call to `execute`:
```ts
await conversion.execute();
```
### Partial execution
Instead of running a conversion in full, you can execute it only until a certain timestamp is reached:
```ts
await conversion.execute({
// Pauses execution once an output timestamp of 10 seconds is reached
until: 10,
});
```
The conversion can then be resumed and continued by calling `execute` again. This feature is especially useful for [composable conversions](#composable-conversions).
## Video options
You can set the `video` property in the conversion options to configure the converter's behavior for video tracks. The options are:
```ts
type ConversionVideoOptions = {
discard?: boolean;
width?: number;
height?: number;
fit?: 'fill' | 'contain' | 'cover';
rotate?: 0 | 90 | 180 | 270;
flip?: boolean;
allowTransformationMetadata?: boolean;
crop?: { left: number; top: number; width: number; height: number };
frameRate?: number;
codec?: VideoCodec;
quality?: Quality;
alpha?: 'discard' | 'keep'; // Defaults to 'discard'
hardwareAcceleration?: 'no-preference' | 'prefer-hardware' | 'prefer-software';
keyFrameInterval?: number;
forceTranscode?: boolean;
process?: (sample: VideoSample) => MaybePromise<
CanvasImageSource | VideoSample | (CanvasImageSource | VideoSample)[] | null
>;
processedWidth?: number;
processedHeight?: number;
group?: OutputTrackGroup | OutputTrackGroup[];
maximumPacketCount?: number;
};
type MaybePromise = T | Promise;
```
For example, here we resize the video track to 720p:
```ts
const conversion = await Conversion.init({
input,
output,
video: {
width: 1280,
height: 720,
fit: 'contain',
},
});
```
::: info
The provided configuration will apply equally to all video tracks of the input. If you want to apply a separate configuration to each video track, check [track-specific options](#track-specific-options).
:::
### Discarding video
If you want to get rid of the video track, use `discard: true`.
### Resizing video
The `width`, `height` and `fit` properties control how the video is resized. If only `width` or `height` is provided, the other value is deduced automatically to preserve the video's original aspect ratio. If both are used, `fit` must be set to control the fitting algorithm:
* `'fill'` will stretch the image to fill the entire box, potentially altering aspect ratio.
* `'contain'` will contain the entire image within the box while preserving aspect ratio. This may lead to letterboxing.
* `'cover'` will scale the image until the entire box is filled, while preserving aspect ratio.
If `width` or `height` is used in conjunction with `rotate`, `flip` or `crop`, they control the post-rotation, post-flip, post-crop dimensions.
If you want to apply max/min constraints to a video's dimensions, check out [track-specific options](#track-specific-options).
In the rare case that the input video changes size over time, the `fit` field can be used to control the size change behavior (see [`VideoEncodingConfig`](./media-sources#video-encoding-config)). When unset, the behavior is `'passThrough'`.
### Rotating and flipping video
`rotate` rotates the video by the specified number of degrees clockwise. This rotation is applied on top of any rotation metadata in the original input file and happens before flipping, cropping and resizing.
`flip` flips the video horizontally (about the vertical axis). This flip is applied on top of any flip metadata in the original input file and happens after rotation but before cropping and resizing.
By default, Mediabunny will try to make use of rotation and flip metadata in the output file to perform the rotation and flip whenever possible. However, if you don't want this to happen, or you want to use Mediabunny to strip all such metadata from a file, you can set `allowTransformationMetadata` to `false`.
### Cropping video
`crop` can be used to extract a rectangular region from the original video. The rectangle is specified using `left`, `top`, `width` and `height` and is clamped to the dimensions of the video. Cropping is applied after rotation and flip but before resizing.
### Adjusting frame rate
The `frameRate` property can be used to set the frame rate of the output video in Hz. If not specified, the original input frame rate will be used (which may be variable).
### Transcoding video
Use the `codec` property to control the codec of the output track. This should be set to a [codec](./supported-formats-and-codecs#video-codecs) supported by the output file, or else the track will be [discarded](#discarded-tracks). When not set and transcoding needs to happen, Mediabunny will automatically pick a codec that the environment can encode and the output format can contain.
Use the `quality` property to control the quality of the output video. For example, you can use this field to compress the video track. See [Encoding quality](./media-sources#encoding-quality) for more. If this property is set, transcoding will always happen. If this property is not set but transcoding is still required, `new Quality('high')` will be used as the value.
Use the `keyFrameInterval` property to control the maximum interval in seconds between key frames in the output video. Setting this fields forces a transcode.
If you want to prevent direct copying of media data and force a transcoding step, use `forceTranscode: true`.
Use the `hardwareAcceleration` property to control whether hardware or software acceleration is used for video transcoding. It applies to both the decoding and the encoding of the video.
### Processing video
The `process` property can be used to define a custom video sample processing function, e.g. for [applying overlays](./quick-start#add-a-video-overlay), color transformations, or timestamp modifications. You are expected to perform this processing yourself, for example using the Canvas API.
An example:
```ts
let ctx: CanvasRenderingContext2D | null = null;
const conversion = await Conversion.init({
video: {
process: (sample) => {
if (!ctx) {
const canvas = new OffscreenCanvas(
sample.displayWidth,
sample.displayHeight,
);
ctx = canvas.getContext('2d')!;
// Convert the video to grayscale
ctx.filter = 'saturate(0)';
}
sample.draw(ctx, 0, 0);
return ctx.canvas;
},
},
});
```
The function is called for each input video sample after transformations and frame rate corrections. It must return a [`VideoSample`](./packets-and-samples#videosample), something that can convert to a `VideoSample`, an array of them, or `null` for dropping the frame.
This function can also be used to manually resize frames. When doing so, you should signal the post-process dimensions using the `processedWidth` and `processedHeight` fields, which enables the encoder to better know what to expect.
## Audio options
You can set the `audio` property in the conversion options to configure the converter's behavior for audio tracks. The options are:
```ts
type ConversionAudioOptions = {
discard?: boolean;
codec?: AudioCodec;
quality?: Quality;
numberOfChannels?: number;
sampleRate?: number;
sampleFormat?: 'u8' | 's16' | 's32' | 'f32';
forceTranscode?: boolean;
process?: (sample: AudioSample) => MaybePromise<
AudioSample | AudioSample[] | null
>;
processedNumberOfChannels?: number;
processedSampleRate?: number;
maximumPacketCount?: number;
};
type MaybePromise = T | Promise;
```
For example, here we convert the audio track to mono and set a specific sample rate:
```ts
const conversion = await Conversion.init({
input,
output,
audio: {
numberOfChannels: 1,
sampleRate: 48000,
},
});
```
::: info
The provided configuration will apply equally to all audio tracks of the input. If you want to apply a separate configuration to each audio track, check [track-specific options](#track-specific-options).
:::
### Discarding audio
If you want to get rid of the audio track, use `discard: true`.
### Resampling audio
The `numberOfChannels` property controls the channel count of the output audio (e.g., 1 for mono, 2 for stereo). If this value differs from the number of channels in the input track, Mediabunny will perform up/downmixing of the channel data using [the same algorithm as the Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#audio_channels).
The `sampleRate` property controls the sample rate in Hz (e.g., 44100, 48000). If this value differs from the input track's sample rate, Mediabunny will resample the audio.
### Transcoding audio
Use the `codec` property to control the codec of the output track. This should be set to a [codec](./supported-formats-and-codecs#audio-codecs) supported by the output file, or else the track will be [discarded](#discarded-tracks). When not set and transcoding needs to happen, Mediabunny will automatically pick a codec that the environment can encode and the output format can contain.
Use the `quality` property to control the quality of the output audio. For example, you can use this field to compress the audio track. See [Encoding quality](./media-sources#encoding-quality) for more. If this property is set, transcoding will always happen. If this property is not set but transcoding is still required, `new Quality('high')` will be used as the value.
If you want to prevent direct copying of media data and force a transcoding step, use `forceTranscode: true`.
### Processing audio
The `process` property can be used to define a custom audio sample processing function, e.g. for applying audio effects, transformations, or timestamp modifications. You are expected to perform this processing yourself.
The function is called for each input audio sample after remixing and resampling. It must return an [`AudioSample`](./packets-and-samples#audiosample), an array of them, or `null` for dropping the sample.
This function can also be used to manually perform remixing or resampling. When doing so, you should signal the post-process parameters using the `processedNumberOfChannels` and `processedSampleRate` fields, which enables the encoder to better know what to expect.
## Track-specific options
You may want to configure your video and audio options differently depending on the specifics of the input track. Or, in case a media file has multiple video or audio tracks, you may want to discard only specific tracks or configure each track separately.
For this, instead of passing an object for `video` and `audio`, you can instead pass a function:
```ts
const conversion = await Conversion.init({
input,
output,
// Function gets invoked for each video track:
video: async (videoTrack) => {
if (videoTrack.number > 1) {
// Keep only the first video track
return { discard: true };
}
return {
// Shrink width to 640 only if the track is wider
width: Math.min(await videoTrack.getDisplayWidth(), 640),
};
},
// Async functions work too:
audio: async (audioTrack) => {
if (await audioTrack.getLanguageCode() !== 'rus') {
// Keep only Russian audio tracks
return { discard: true };
}
return {
codec: 'aac',
};
},
});
```
For documentation about the properties of video and audio tracks, refer to [Reading track metadata](./reading-media-files#reading-track-metadata).
## Track fan-out
You can also set (or return) an array of options for a single input track, which causes Mediabunny to create one output track per entry, or, in other words, multiple output tracks from one input track (fan-out).
This is useful for producing multiple renditions at different qualities, e.g. for [HLS](./output-formats#hls):
```ts
const conversion = await Conversion.init({
input,
output,
video: [
{ height: 1080, quality: new Quality('high') },
{ height: 720, quality: new Quality('medium') },
{ height: 480, quality: new Quality('low') },
],
});
```
## Trimming
Use the `trim` property in the conversion options to extract only a section of the input file into the output file:
```ts
type ConversionOptions = {
// ...
trim?: {
start: number; // in seconds
end: number; // in seconds
};
// ...
};
```
For example, here we extract a clip from 10s to 25s:
```ts
const conversion = await Conversion.init({
input,
output,
trim: {
start: 10,
end: 25,
},
});
```
In this case, the output will be 15 seconds long.
If only `start` is set, the clip will run until the end of the input file. If only `end` is set, the clip will start at the beginning of the input file.
Note that when using the trimming defaults, the resulting media file will always begin at timestamp 0. If your input file has a start time offset (like is common with MPEG-TS files) and you want to retain that, use `trim: { start: 0 }` to ensure timestamps don't get shifted.
***
You can even use negative trimming values to offset the start of the media:
```ts
const conversion = await Conversion.init({
// ...
trim: {
start: -2, // Two seconds of no media data (freeze frame / silence) at the start
},
// ...
});
```
::: warning
Setting `start` to a value other than the default will currently force a *transcode* of both video and audio.
In a future version of Mediabunny, the fast "packet copy path" that is currently reachable by leaving `start` unset, may be made available for any arbitrary trim range.
:::
## Copying media data
In media conversions, media data can either be copied directly from the old file to the new file or go through a transcoding step. If you're coming from FFmpeg, you may know the copy path by `-c copy`. Mediabunny differs from FFmpeg in that it will always try to perform a copy conversion by default, if the config permits. Copy conversions are often desirable because they are fast and lossless.
There are a few major factors that decide if a copy conversion is possible:
* No transcode-forcing operations (resizing, rotation, resampling, codec changes, etc.)
* Output format must be able to contain the input codecs
* Output format must support timestamps flexible enough
If you're converting to MP4, copy conversions are usually possible due to the wide range of codecs supported by that format plus the support for negative timestamps via edit lists which allow you to model any arbitrary trim range. Simpler formats such as MP3 are more restrictive and may require transcoding or timestamp offsetting to realize a copy conversion.
***
You can fully configure Mediabunny's behavior via the `copy` conversion option:
```ts
type ConversionCopyOptions = {
mode?: 'forced' | 'preferred';
shiftTolerance?: number;
boundaryPolicy?: 'expand' | 'shrink';
boundaryTolerance?: number;
};
```
* `mode`\
Controls whether media copying is preferred or required. Defaults to `'preferred'`.
* `'forced'`: Copy encoded media where possible and discard tracks that cannot possibly be copied.
* `'preferred'`: Copy encoded media when possible, and transcode tracks that cannot be copied.
* `shiftTolerance`\
The maximum absolute shift, in seconds, that may be applied to the media to be able to copy it into the output format. Defaults to `0`, which permits no additional shift. Set to `Infinity` to permit any shift.
A shift of `0` gives you perfect *timeline sync*: output timestamps will match input timestamps exactly (only offset by the trim region). Any non-zero shift will break this property but will still, under all circumstances, maintain perfect cross-track and audio-video sync.
* `boundaryPolicy`\
Controls which media region will be copied to satisfy the requested trim range. Defaults to `'expand'`.
* `'expand'`: Include at least all media in the requested range. This may require expanding the media region due to key frames and packet boundaries, and thus may include media outside of your trim range. The region is always minimally expanded to satisfy the copy criteria.
* `'shrink'`: Only include media that lies entirely within the requested trim range. This may require shrinking the media region due to key frames and packet boundaries, and thus may exclude media inside of your trim range. The region is always minimally shrunk to satisfy the copy criteria.
Use `expand` if you don't want to lose any media; use `shrink` to never expose any media outside of the trim region.
* `boundaryTolerance`\
The maximum amount, in seconds, by which the copied media region may deviate from the requested trim range at its start, as caused by `boundaryPolicy`. Defaults to `Infinity`, which permits any deviation.
In other words, this field sets how many seconds of media the conversion is allowed to add/remove to make a copy path possible.
***
You can disable copy conversions entirely by setting the field to `false`:
```ts
await Conversion.init({
copy: false,
// ...
});
```
## Metadata tags
By default, any [descriptive metadata tags](../api/MetadataTags.md) of the input will be copied to the output. If you want to further control the metadata tags written to the output, you can use the `tags` options:
```ts
// Set your own metadata:
const conversion = await Conversion.init({
// ...
tags: {
title: 're:Turning',
artist: 'Alexander Panos',
},
// ...
});
// Or, augment the input's metadata:
const conversion = await Conversion.init({
// ...
tags: (inputTags) => ({
...inputTags, // Keep the existing metadata
images: [{ // And add cover art
data: new Uint8Array(...),
mimeType: 'image/jpeg',
kind: 'coverFront',
}],
comment: undefined, // And remove any comments
}),
// ...
});
// Or, remove all metadata
const conversion = await Conversion.init({
// ...
tags: {},
// ...
});
```
## Selecting tracks
Use the `tracks` option to control which input tracks are considered for conversion:
```ts
const conversion = await Conversion.init({
input,
output,
tracks: 'primary', // Only the primary video and audio tracks
});
```
Accepted values are `'all'` or `'primary'`. The default is `'all'`, unless the input format is HLS, then it is `'primary'`. This is because HLS typically has multiple renditions of a track, and converting all of them is (usually) not desired.
For a more granular selection, use the `discard` field on the tracks.
## Discarded tracks
If an input track is excluded from the output file, it is considered *discarded*. The list of discarded tracks can be accessed after initializing a `Conversion`:
```ts
const conversion = await Conversion.init({ input, output });
conversion.discardedTracks; // => DiscardedTrack[]
type DiscardedTrack = {
// The track that was discarded
track: InputTrack;
// The reason for discarding the track
reason:
| 'discarded_by_user'
| 'max_track_count_reached'
| 'max_track_count_of_type_reached'
| 'unknown_source_codec'
| 'undecodable_source_codec'
| 'no_encodable_target_codec'
| 'cannot_copy'
| 'unknown_maximum_packet_count';
// The options that were provided for this track, or {} if none were provided
trackOptions: ConversionVideoOptions | ConversionAudioOptions;
};
```
Since you can inspect this list before executing a `Conversion`, this gives you the option to decide if you still want to move forward with the conversion process.
If `isValid` is `false`, then the discarded tracks caused the `Conversion` to become invalid. For example, this can happen when a format requires a specific codec but that codec cannot be encoded.
***
The following reasons exist:
* `discarded_by_user`\
You discarded this track by setting `discard: true`.
* `max_track_count_reached`\
The output had no more room for another track.
* `max_track_count_of_type_reached`\
The output had no more room for another track of this type, or the output doesn't support this track type at all.
* `unknown_source_codec`\
We don't know the codec of the input track and therefore don't know what to do with it.
* `undecodable_source_codec`\
The input track's codec is known, but we are unable to decode it.
* `no_encodable_target_codec`\
We can't find a codec that we are able to encode and that can be contained within the output format. This reason can be hit if the environment doesn't support the necessary encoders, or if you requested a codec that cannot be contained within the output format.
* `cannot_copy`\
The copy mode was set to `'forced'` but the track could not be copied with the given copy configuration because it would require a transcode instead.
* `unknown_maximum_packet_count`\
The output format requires a maximum packet count (like MP4 with `fastStart: 'reserve'`), but it can't be estimated because the track is live and no trim end is set. Set it manually using the `maximumPacketCount` track option.
***
On the flip side, you can always query which input tracks made it into the output:
```ts
const conversion = await Conversion.init({ input, output });
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',
quality: new Quality({ 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();
```
### Running in lockstep
To prevent high memory usage due to buffering needs, it's important to add media data at roughly the same speed across all tracks. To achieve this, you can step the conversion deliberately by calling `execute` multiple times:
```ts
await output.start();
for (using sample of generateAudioSamples()) {
await audioSource.add(sample);
await conversion.execute({ until: sample.timestamp });
}
// Convert whatever's left
await conversion.execute();
await output.finalize();
```
When running multiple composable conversions that target the same output, you can use a pattern like this:
```ts
await output.start();
for (let until = 1; true; until += 1) {
await Promise.all([
conversion1.execute({ until }),
conversion2.execute({ until }),
]);
if (conversion1.state === 'done' && conversion2.state === 'done') {
break;
}
}
await output.finalize();
```
## 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.
If you only want to convert a part of the live stream instead of waiting until it has ended, you can [trim](#trimming) the conversion. For example, here we're capturing the next 60 seconds of the live stream:
```ts
// Get the live edge
const currentDuration = await input.getDurationFromMetadata(undefined, {
skipLiveWait: true,
});
const conversion = await Conversion.init({
input,
output,
trim: {
// Start at the current live edge
start: currentDuration,
// End at most 60 seconds later
end: currentDuration + 60,
},
});
```
---
---
url: /codec-registry/dts.md
description: >-
DTS audio codec definition, defining legal codec strings, decoder configs, and
packet data formats.
---
# DTS codec registration
## Description
The DTS audio codec (DTS Coherent Acoustics), specified in [ETSI TS 102 114](https://www.etsi.org/deliver/etsi_ts/102100_102199/102114/01.06.01_60/ts_102114v010601p.pdf).
## Codec ID
```ts
'dts'
```
## `EncodedPacket` data
The packet's data must be a core substream frame as defined in Section 5 of [ETSI TS 102 114](https://www.etsi.org/deliver/etsi_ts/102100_102199/102114/01.06.01_60/ts_102114v010601p.pdf), beginning with the sync word `0x7FFE8001`, followed by any number of extension substreams as defined in Section 7.4.1 of [ETSI TS 102 114](https://www.etsi.org/deliver/etsi_ts/102100_102199/102114/01.06.01_60/ts_102114v010601p.pdf), each beginning with the sync word `0x64582025`. The core substream frame may be omitted.
The bitstream must use 16-bit big-endian packing.
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
The codec string must be one of the four four-character codes identifying which substreams the bitstream is built from:
* `'dtsc'` - a core substream only
* `'dtsh'` - a core substream with extension substreams
* `'dtsl'` - extension substreams carrying lossless audio, with no core substream
* `'dtse'` - DTS Express
## `AudioDecoderConfig` description
`description` is not used for this codec.
---
---
url: /codec-registry/eac3.md
description: >-
Dolby Digital Plus (E-AC-3) audio codec definition, defining legal codec
strings, decoder configs, and packet data formats.
---
# E-AC-3 codec registration
## Description
The Dolby Digital Plus (E-AC-3) audio codec, specified in [ETSI TS 102 366](https://www.etsi.org/deliver/etsi_ts/102300_102399/102366/01.04.01_60/ts_102366v010401p.pdf).
## Codec ID
```ts
'eac3'
```
## `EncodedPacket` data
The packet's data must be a sync frame as defined in Section E.1.2.0 of [ETSI TS 102 366](https://www.etsi.org/deliver/etsi_ts/102300_102399/102366/01.04.01_60/ts_102366v010401p.pdf), beginning with the sync word `0x0B77`.
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
```ts
'ec-3'
```
## `AudioDecoderConfig` description
`description` is not used for this codec.
---
---
url: /codec-registry/flac.md
description: >-
Free Lossless Audio Codec (FLAC) audio codec definition, defining legal codec
strings, decoder configs, and packet data formats.
---
# FLAC codec registration
## Description
The Free Lossless Audio Codec (FLAC), specified in the [FLAC Format Specification](https://xiph.org/flac/format.html).
## Codec ID
```ts
'flac'
```
## `EncodedPacket` data
The packet's data must be a FLAC frame as described in the [FLAC Format Specification](https://xiph.org/flac/format.html).
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
```ts
'flac'
```
## `AudioDecoderConfig` description
`description` must contain the bytes `0x66 0x4C 0x61 0x43` (the ASCII string `'fLaC'`), followed by a `STREAMINFO` metadata block as defined in Section 7 of the [FLAC Format Specification](https://xiph.org/flac/format.html).
---
---
url: /codec-registry/hevc.md
description: >-
High Efficiency Video Coding (H.265) video codec definition, defining legal
codec strings, decoder configs, and packet data formats.
---
# HEVC (H.265) codec registration
## Description
The High Efficiency Video Coding (H.265) video codec, specified in [Rec. ITU-T H.265](https://www.itu.int/rec/T-REC-H.265) / [ISO/IEC 23008-2](https://www.iso.org/standard/75484.html).
An HEVC bitstream can have either of two formats:
* *Canonical* (length-prefixed), as defined in [ISO/IEC 14496-15](https://www.iso.org/standard/89118.html) Section 8.3.2. Here, video parameter sets (VPS/SPS/PPS) are provided out-of-band.
* *Annex B*, as defined in [Rec. ITU-T H.265](https://www.itu.int/rec/T-REC-H.265) Annex B. Here, video parameter sets (VPS/SPS/PPS) must be provided in-band in the respective NALUs.
All packets within the bitstream must have the same format.
## Codec ID
```ts
'hevc'
```
## `EncodedPacket` data
The packet's data must be an access unit as defined in [Rec. ITU-T H.265](https://www.itu.int/rec/T-REC-H.265) Section 7.4.2.4, containing exactly one base layer coded picture, in either *canonical* or *Annex B* format.
## `EncodedPacket` type
If the packet's type is `'key'`, then the packet is expected to contain an IDR, CRA, or BLA picture. Additionally, if the bitstream's format is *Annex B*, then this packet is also expected to contain the necessary video parameter sets to initialize the decoder.
## `VideoDecoderConfig` codec string
The full codec string begins with the prefix `'hev1.'` or `'hvc1.'`, with a variable-length suffix of four dot-separated fields as specified in Section E.3 of [ISO/IEC 14496-15](https://www.iso.org/standard/89118.html).
## `VideoDecoderConfig` description
If the bitstream is in the *canonical* (length-prefixed) format, `description` must be an `HEVCDecoderConfigurationRecord` as defined in [ISO/IEC 14496-15](https://www.iso.org/standard/89118.html) Section 8.3.3.1.
If the bitstream is in the *Annex B* format, `description` must be undefined.
## Quantizer range
HEVC has quantizer support and supports quantizer values in the range \[0, 51].
---
---
url: /guide/input-formats.md
description: >-
Mediabunny supports a wide range of media input formats, such as MP4, WebM,
MP3, HLS, and many more.
---
# Input formats
Mediabunny supports a wide variety of commonly used container formats for reading input files. These *input formats* are used in two ways:
* When creating an `Input`, they are used to specify the list of supported container formats. See [Creating a new input](./reading-media-files#creating-a-new-input) for more.
* Given an existing `Input`, its `getFormat` method returns the *actual* format of the file as an `InputFormat`.
## Input format properties
Retrieve the full written name of the format like this:
```ts
inputFormat.name; // => 'MP4'
```
You can also retrieve the format's base MIME type:
```ts
inputFormat.mimeType; // => 'video/mp4'
```
If you want a file's full MIME type, which depends on track codecs, use [`getMimeType`](./reading-media-files#reading-file-metadata) on `Input` instead.
## Input format singletons
Since input formats don't require any additional configuration, each input format is directly available as an exported singleton instance:
```ts
import {
MP4, // MP4 input format singleton
QTFF, // QuickTime File Format input format singleton
MATROSKA, // Matroska input format singleton
WEBM, // WebM input format singleton
MP3, // MP3 input format singleton
WAVE, // WAVE input format singleton
OGG, // Ogg input format singleton
ADTS, // ADTS input format singleton
FLAC, // FLAC input format singleton
MPEG_TS, // MPEG-TS input format singleton
HLS, // HLS input format singleton
} from 'mediabunny';
```
You can use these singletons when creating an input:
```ts
import { Input, MP3, WAVE, OGG } from 'mediabunny';
const input = new Input({
formats: [MP3, WAVE, OGG],
// ...
});
```
You can also use them for checking the actual format of an `Input`:
```ts
import { MP3 } from 'mediabunny';
const isMp3 = (await input.getFormat()) === MP3;
```
There is a special `ALL_FORMATS` constant exported by Mediabunny which contains every input format singleton. Use this constant if you want to support as many formats as possible:
```ts
import { Input, ALL_FORMATS } from 'mediabunny';
const input = new Input({
formats: ALL_FORMATS,
// ...
});
```
::: info
Using `ALL_FORMATS` means [demuxers](https://en.wikipedia.org/wiki/Demultiplexer_\(media_file\)) for all formats must be included in the bundle, which can increase the bundle size significantly. Use it only if you need to support all formats.
:::
## Input format class hierarchy
In addition to singletons, input format classes are structured hierarchically:
* `InputFormat` (abstract)
* `IsobmffInputFormat` (abstract)
* `Mp4InputFormat`
* `QuickTimeInputFormat`
* `MatroskaInputFormat`
* `WebMInputFormat`
* `Mp3InputFormat`
* `WaveInputFormat`
* `OggInputFormat`
* `AdtsInputFormat`
* `FlacInputFormat`
* `MpegTsInputFormat`
* `HlsInputFormat`
This means you can also perform input format checks using `instanceof` instead of `===` comparisons. For example:
```ts
import { Mp3InputFormat } from 'mediabunny';
// Check if the file is MP3:
(await input.getFormat()) instanceof Mp3InputFormat;
// Check if the file is Matroska (MKV + WebM):
(await input.getFormat()) instanceof MatroskaInputFormat;
// Check if the file is MP4 or QuickTime:
(await input.getFormat()) instanceof IsobmffInputFormat;
```
::: info
Well, actually 🤓☝️, the QuickTime File Format is technically not an instance of the ISO Base Media File Format (ISOBMFF) - instead, ISOBMFF is a standard originally inspired by QTFF. However, as the two are extremely similar and are used in the same way, we consider QTFF an instance of `IsobmffInputFormat` for convenience.
:::
---
---
url: /guide/installation.md
description: >-
Install Mediabunny using npm (or your favorite package manager), or include it
directly as a
```
This will add a `Mediabunny` object to the global scope. You can provide types for this global using `mediabunny.d.ts`.
You can download a built distribution file from the [releases page](https://github.com/Vanilagy/mediabunny/releases). Use the `*.cjs` builds for normal script tag inclusion, or the `*.mjs` builds for script tags with `type="module"` or direct imports via ESM. Including the `mediabunny.d.ts` declaration file in your TypeScript project will declare a global `Mediabunny` namespace.
---
---
url: /guide/introduction.md
description: >-
Mediabunny is a zero-dependency, tree-shakable TypeScript library for reading,
writing and converting media files in the browser. Like FFmpeg, but for the
web.
---
# Introduction
Mediabunny is a JavaScript library for reading, writing, and converting media files (like MP4 or WebM), directly in the browser. It aims to be a complete toolkit for high-performance media operations on the web. It's written from scratch in pure TypeScript, has zero dependencies, and is extremely tree-shakable, meaning you only include what you use. You can think of it a bit like [FFmpeg](https://ffmpeg.org/), but built for the web's needs.
## Features
Here's a long list of stuff this library does:
* Reading metadata from media files
* Extracting media data from media files
* Creating new media files
* Converting media files
* Hardware-accelerated decoding & encoding (via the WebCodecs API)
* Support for multiple video, audio and subtitle tracks
* Read & write support for many container formats (.mp4, .mov, .webm, .mkv, .mp3, .wav, .ogg, .aac, .flac, .ts), including variations such as MP4 with Fast Start, fragmented MP4, streamable Matroska, transparent WebM, etc.
* Read & write support for HLS, both VOD and live
* Support for 25 different codecs
* Lazy, optimized, on-demand file reading
* Input and output streaming, arbitrary file size support
* File location independence (memory, disk, network, ...)
* Utilities for compression, resizing, rotation, cropping, resampling, trimming
* Metadata tag reading & writing (title, artist, cover art, custom tags, attached files, etc.)
* Transmuxing and transcoding
* Microsecond-accurate reading and writing precision
* Efficient seeking through time
* Pipelined design for efficient hardware usage and automatic backpressure
* Custom encoder & decoder support for polyfilling
* Low- & high-level abstractions for different use cases
* Performant everything
* Server-side support (Node, Bun, Deno) via `@mediabunny/server`
...and there's probably more.
## Use cases
Mediabunny is a general-purpose toolkit and can be used in infinitely many ways. But, here are a few ideas:
* File conversion & compression
* Displaying file metadata (duration, dimensions, ...)
* Extracting thumbnails
* Creating videos in the browser
* Building a video editor
* Live recording & streaming
* Efficient, sample-accurate playback of large files via the Web Audio API
Check out the [Examples](/examples) page for demo implementations of many of these ideas!
## Getting started
To get going with Mediabunny, here are some starting points:
* Check out [Quick start](./quick-start) for a collection of useful code snippets
* Start with [Reading media files](./reading-media-files) if you want to do read operations.
* Start with [Writing media files](./writing-media-files) if you want to do write operations.
* Start with [Converting media files](./converting-media-files) if you care about file conversions.
* Dive into [Packets & samples](./packets-and-samples) for a deeper understanding of the concepts underlying this library.
## Server-side usage
Mediabunny's simple yet flexible API provides a modern alternative to traditional server-side media processing pipelines which may involve calling out to FFmpeg's CLI manually. Mediabunny was primarily built for client-side environments, but when combined with the [`@mediabunny/server`](./extensions/server) extension, the full Mediabunny feature set is available in server-side environments such as Node, Bun, and Deno.
The extension enables:
* Video decoders and encoders for AVC (H.264), HEVC (H.265), VP8, VP9, and AV1. Supports both length-prefixed and Annex B AVC/HEVC as well as transparent video via VP9.
* Audio decoders and encoders for AAC, MP3, Vorbis, Opus, FLAC, AC-3, E-AC-3 and DTS. Supports AAC in both AAC and ADTS formats.
* Video frame transformation support (resize, rotate, crop)
* Automatic hardware acceleration on all platforms (macOS, Linux, Windows)
* Built-in multithreading
* Zero-copy decode and encode paths
For more, see [the corresponding guide](./extensions/server).
## Motivation
Mediabunny is the evolution of my previous libraries, [mp4-muxer](https://github.com/Vanilagy/mp4-muxer) and [webm-muxer](https://github.com/Vanilagy/webm-muxer), which were both created due to the advent of the WebCodecs API. While they fulfilled their job just fine, I saw a few pain points:
* Lots of duplicated code between the two libraries, otherwise very similar API.
* No help with the difficulties of navigating the WebCodecs API & related browser APIs.
* "mp4-demuxer when??"
This library is the result of unifying these libraries into one, solving all the above issues, and expanding the scope. Now:
* Changing the output file format is a single-line change; the rest of the API is identical.
* Lots of abstractions on top of the WebCodecs API & browser APIs are provided.
* mp4-demuxer now.
Due to tree shaking, if you only need an MP4 or WebM muxer, this library's bundle size will still be very small.
### Migration
If you're coming from mp4-muxer or webm-muxer, you should migrate to Mediabunny. For that, refer to these guides:
* [Guide: Migrating from mp4-muxer to Mediabunny](https://github.com/Vanilagy/mp4-muxer/blob/main/MIGRATION-GUIDE.md)
* [Guide: Migrating from webm-muxer to Mediabunny](https://github.com/Vanilagy/webm-muxer/blob/main/MIGRATION-GUIDE.md)
## Technical overview
At its core, Mediabunny is a collection of multiplexers and demultiplexers, one of each for every container format. Demultiplexers stream data from *sources*, while multiplexers stream data to *targets*. Every demultiplexer is capable of extracting file metadata as well as compressed media data, while multiplexers write metadata and encoded media data into a new file.
Mediabunny then provides several wrappers around the WebCodecs API to simplify usage: for reading, it creates decoders with the correct codec configuration and efficiently decodes media data in a pipelined way. For writing, it figures out the necessary codec configuration and sets up encoders which are then used to encode raw media data, while respecting the backpressure applied by the encoder. Extracting the right decoder configuration from a media file can be tricky and sometimes involves diving into encoded media packet bitstreams.
The conversion abstraction is built on top of Mediabunny's reading and writing primitives and combines them both in a heavily-pipelined way, making sure reading and writing happen in lockstep. It also consists of a lot of conditional logic probing output track compatibility, decoding support, and finding encodable codec configurations. It makes use of the Canvas API for video processing operations, and uses a custom implementation for audio resampling and up/downmixing.
---
---
url: /codec-registry/pcm.md
description: >-
PCM audio codec definitions, defining legal codec strings, decoder configs,
and packet data formats.
---
# Linear PCM codecs registration
## Description
A family of linear pulse-code modulation (PCM) audio codecs of various bit depths and byte orders.
## Codec IDs
| Codec ID | Description |
| --- | --- |
| `'pcm-u8'` | Unsigned 8-bit integer |
| `'pcm-s8'` | Signed 8-bit integer |
| `'pcm-s16'` | Signed 16-bit integer, little-endian |
| `'pcm-s16be'` | Signed 16-bit integer, big-endian |
| `'pcm-s24'` | Signed 24-bit integer, little-endian |
| `'pcm-s24be'` | Signed 24-bit integer, big-endian |
| `'pcm-s32'` | Signed 32-bit integer, little-endian |
| `'pcm-s32be'` | Signed 32-bit integer, big-endian |
| `'pcm-f32'` | 32-bit float, little-endian |
| `'pcm-f32be'` | 32-bit float, big-endian |
| `'pcm-f64'` | 64-bit float, little-endian |
| `'pcm-f64be'` | 64-bit float, big-endian |
## `EncodedPacket` data
The packet's data must be a sequence of bytes of arbitrary length (divisible by the size of one frame), with each sample occupying the number of bits defined by the codec ID. For multichannel audio, samples from different channels are interleaved.
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
The codec string is the same as the codec ID (e.g. `'pcm-s16'`, `'pcm-f32'`).
## `AudioDecoderConfig` description
`description` is not used for this codec.
---
---
url: /guide/media-sinks.md
description: >-
Media sinks enable different ways to extract video and audio data from files,
from built-in decoding to manual per-packet control.
---
# Media sinks
## Introduction
*Media sinks* offer ways to extract media data from an `InputTrack`. Different media sinks provide different levels of abstraction and cater to different use cases.
For information on how to obtain input tracks, or how to generally read data from media files, refer to [Reading media files](./reading-media-files).
### General usage
> General usage patterns of media sinks will be demonstrated using a fictional `FooSink`.
Media sinks are like miniature "namespaces" for retrieving media data, scoped to a specific track. This means that you'll typically only need to construct one sink per type for a track.
```ts
const track = await input.getPrimaryVideoTrack();
const sink = new FooSink(track);
```
Constructing the sink is virtually free and does not perform any media data reads.
To read media data, each sink offers a different set of methods. You can call these methods as many times as you want; their calls will be independent since media sinks are stateless\[^1].
```ts
await sink.getFoo(1);
await sink.getFoo(2);
await sink.getFoo(3);
```
\[^1]: Almost: `CanvasSink` becomes stateful when using a [canvas pool](#canvas-pool).
### Async iterators
Media sinks make heavy use of [async iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator). They allow you to iterate over a set of media data (like all frames in a video track) efficiently, only having to read small sections of the file at any given point.
Async iterators are extremely ergonomic with `for await...of` loops:
```ts
for await (const foo of sink.foos()) {
console.log(foo.timestamp);
}
```
Just like in regular `for` loops, the `break` statement can be used to exit the loop early. This will automatically clean up any internal resources (such as decoders) used by the async iterator:
```ts
// Loop only over the first 5 foos
let count = 0;
for await (const foo of sink.foos()) {
console.log(foo.timestamp);
if (++count === 5) break;
}
```
Async iterators are also useful outside of `for` loops. Here, the `next` method is used to retrieve the next item in the iteration:
```ts
const foos = sink.foos();
const foo1Result = await foos.next();
const foo2Result = await foos.next();
const foo1 = foo1Result.value; // Might be `undefined` if the iteration is complete
```
::: warning
When you manually use async iterators, make sure to call `return` on them once you're done:
```ts
await foos.return();
```
This ensures all internally held resources are freed.
:::
### Decode vs. presentation order
Packets may appear out-of-order in the file, meaning the order in which they are decoded does not correspond to the order in which the decoded data is displayed (see [B-frames](./media-sources#b-frames)). The methods on media sinks differ with respect to which ordering they use to query and retrieve packets. So, just keep these definitions in mind:
* **Presentation order:** The order in which the data is to be presented; sorted by timestamp.
* **Decode order:** The order in which packets must be decoded; not always sorted by timestamp.
### Live tracks
Some tracks (like in HLS) may be *live*, meaning new media data is still being produced. Check it like this:
```ts
await track.isLive();
```
Mediabunny's mental model for live tracks is simple: it treats them like any other track, just one where the media data at the end is not available yet.
This means that any reading operation that attempts to read media data from the "unavailable" section at the end will wait until the media data becomes available or the live stream ends. Mediabunny calls this the "live wait".
Sometimes, you may want to *skip* the live wait and pretend like the media data ends at the currently-known latest point. For this, you can pass the `skipLiveWait: true` option to all media sinks. For example:
```ts
import { EncodedPacketSink } from 'mediabunny';
const packetSink = new EncodedPacketSink(track);
const lastPacket = await packetSink.getPacket(Infinity, { skipLiveWait: true });
```
## General sinks
There is one media sink which can be used with any `InputTrack`:
### `EncodedPacketSink`
This sink can be used to extract raw, [encoded packets](./packets-and-samples#encodedpacket) from media files and is the most elementary media sink. `EncodedPacketSink` is useful if you don't care about the decoded media data (for example, you're only interested in timestamps), or if you want to roll your own decoding logic.
Start by constructing the sink from any `InputTrack`:
```ts
import { EncodedPacketSink } from 'mediabunny';
const sink = new EncodedPacketSink(track);
```
You can retrieve specific packets given a timestamp in seconds:
```ts
await sink.getPacket(5); // => EncodedPacket | null
// Or, retrieving only packets with type 'key':
await sink.getKeyPacket(5); // => EncodedPacket | null
```
When retrieving a packet using a timestamp, the last packet (in [presentation order](#decode-vs-presentation-order)) with a timestamp less than or equal to the search timestamp will be returned. The methods return `null` if there exists no such packet.
There are special methods for retrieving the first packet (in [decode order](#decode-vs-presentation-order)):
```ts
await sink.getFirstPacket(); // => EncodedPacket | null
// The first packet is typically a key frame, but this is not required.
// This method returns the first key frame:
await sink.getFirstKeyPacket(); // => EncodedPacket | null
```
The last packet (in [presentation order](#decode-vs-presentation-order)) can be retrieved like so:
```ts
await sink.getPacket(Infinity); // => EncodedPacket | null
```
Once you have a packet, you can retrieve the packet's successor (in [decode order](#decode-vs-presentation-order)) like so:
```ts
await sink.getNextPacket(packet); // => EncodedPacket | null
// Or jump straight to the next packet with type 'key':
await sink.getNextKeyPacket(packet); // => EncodedPacket | null
```
These methods return `null` if there is no next packet.
These methods can be combined to iterate over a range of packets. Starting from an initial packet, call `getNextPacket` in a loop to iterate over packets:
```ts
let currentPacket = await sink.getFirstPacket();
while (currentPacket) {
console.log('Packet:', currentPacket);
// Do something with the packet
currentPacket = await sink.getNextPacket(currentPacket);
}
```
While this approach works, `EncodedPacketSink` also provides a dedicated `packets` iterator function, which iterates over packets in [decode order](#decode-vs-presentation-order):
```ts
for await (const packet of sink.packets()) {
// ...
}
```
You can also constrain the iteration using a packet range, where the iteration will go from the starting packet up to (but excluding) the end packet:
```ts
const start = await sink.getPacket(5);
const end = await sink.getPacket(10, { metadataOnly: true });
for await (const packet of sink.packets(start, end)) {
// ...
}
```
The `packets` method is more performant than manual iteration as it will intelligently preload future packets before they are needed.
#### Verifying key packets
By default, packet types are determined using the metadata provided by the containing file. Some files can erroneously label some delta packets as key packets, leading to potential decoder errors. To be guaranteed that a key packet is actually a key packet, you can enable the `verifyKeyPackets` option:
```ts
// If the packet returned by this method has type: 'key', it's guaranteed
// to be a key packet.
await sink.getPacket(5, { verifyKeyPackets: true });
// Returned packets are guaranteed to be key packets
await sink.getKeyPacket(10, { verifyKeyPackets: true });
await sink.getNextKeyPacket(packet, { verifyKeyPackets: true });
// Also works for the iterator:
for await (const packet of sink.packets(
undefined,
undefined,
{ verifyKeyPackets: true },
)) {
// ...
}
```
::: info
`verifyKeyPackets` only works when `metadataOnly` is not also enabled.
:::
#### Metadata-only packet retrieval
Sometimes, you're only interested in a packet's metadata (timestamp, duration, type, ...) and not in its encoded media data. All methods on `EncodedPacketSink` accept a final `options` parameter which you can use to retrieve [metadata-only packets](./packets-and-samples#metadata-only-packets):
```ts
const packet = await sink.getPacket(5, { metadataOnly: true });
packet.isMetadataOnly; // => true
packet.data; // => Uint8Array([])
```
Retrieving metadata-only packets is more efficient for some input formats: Only the metadata section of the file must be read, not the media data section.
## Video data sinks
These sinks can only be used with an `InputVideoTrack`.
### `VideoSampleSink`
Use this sink to extract decoded [video samples](./packets-and-samples#videosample) (frames) from a video track. The sink will automatically handle the decoding internally.
::: info
All operations of this sink use [presentation order](#decode-vs-presentation-order).
:::
Create the sink like so:
```ts
import { VideoSampleSink } from 'mediabunny';
const sink = new VideoSampleSink(videoTrack);
// Optionally, configure the decoder:
const sink = new VideoSampleSink(videoTrack, {
hardwareAcceleration: 'prefer-software',
});
```
#### Single retrieval
You can retrieve the sample presented at a given timestamp in seconds:
```ts
await sink.getSample(5);
// Extracting the first sample:
await sink.getSample(await videoTrack.getFirstTimestamp());
// Extracting the last sample:
await sink.getSample(Infinity);
```
This method returns the last sample with a timestamp less than or equal to the search timestamp, or `null` if there is no such sample.
#### Range iteration
You can use the `samples` iterator method to iterate over a contiguous range of samples:
```ts
// Iterate over all samples:
for await (const sample of sink.samples()) {
console.log('Sample:', sample);
// Do something with the sample
sample.close();
}
// Iterate over all samples in a specific time range:
for await (const sample of sink.samples(5, 10)) {
// ...
sample.close();
}
```
The `samples` iterator yields the samples in [presentation order](#decode-vs-presentation-order) (sorted by timestamp).
#### Sparse iteration
Sometimes, you may want to retrieve the samples for multiple timestamps at once (for example, for generating thumbnails). While you could call `getSample` multiple times, the `samplesAtTimestamps` method provides a more efficient way:
```ts
for await (const sample of sink.samplesAtTimestamps([0, 1, 2, 3, 4, 5])) {
// `sample` is either VideoSample or null
sample.close();
}
// Any timestamp sequence is allowed:
sink.samplesAtTimestamps([1, 2, 3]);
sink.samplesAtTimestamps([4, 5, 5, 5]);
sink.samplesAtTimestamps([10, -2, 3]);
```
This method is more efficient than multiple calls to `getSample` because it avoids decoding the same packet twice.
In addition to arrays, you can pass any iterable into this method:
```ts
sink.samplesAtTimestamps(new Set([2, 3, 3, 4]));
sink.samplesAtTimestamps((function* () {
for (let i = 0; i < 5; i++) {
yield i;
}
})());
sink.samplesAtTimestamps((async function* () {
const firstTimestamp = await videoTrack.getFirstTimestamp();
const lastTimestamp = await videoTrack.computeDuration();
for (let i = 0; i <= 100; i++) {
yield firstTimestamp + (lastTimestamp - firstTimestamp) * i / 100;
}
})());
```
Passing an async iterable is especially useful when paired with `EncodedPacketSink`. Imagine you want to retrieve every key frame. A naive implementation might look like this:
```ts
// Naive, bad implementation: // [!code error]
const packetSink = new EncodedPacketSink(videoTrack);
const keyFrameTimestamps: number[] = [];
let currentPacket = await packetSink.getFirstPacket();
while (currentPacket) {
keyFrameTimestamps.push(currentPacket.timestamp);
currentPacket = await packetSink.getNextKeyPacket(currentPacket);
}
const sampleSink = new VideoSampleSink(videoTrack);
const keyFrameSamples = sampleSink.samplesAtTimestamps(keyFrameTimestamps);
for await (const sample of keyFrameSamples) {
// ...
sample.close();
}
```
The issue with this implementation is that it first iterates over all key packets before yielding the first sample. The better implementation is this:
```ts
// Better implementation:
const packetSink = new EncodedPacketSink(videoTrack);
const sampleSink = new VideoSampleSink(videoTrack);
const keyFrameSamples = sampleSink.samplesAtTimestamps((async function* () {
let currentPacket = await packetSink.getFirstPacket();
while (currentPacket) {
yield currentPacket.timestamp;
currentPacket = await packetSink.getNextKeyPacket(currentPacket);
}
})());
for await (const sample of keyFrameSamples) {
// ...
sample.close();
}
```
### `CanvasSink`
While `VideoSampleSink` extracts raw decoded video samples, you can use `CanvasSink` to extract these samples as canvases instead. In doing so, certain operations such as scaling, rotating, and cropping can also be handled by the sink. The downside is the additional VRAM requirements for the canvases' framebuffers.
::: info
This sink yields `HTMLCanvasElement` whenever possible, and falls back to `OffscreenCanvas` otherwise (in Worker contexts, for example).
:::
Create the sink like so:
```ts
import { CanvasSink } from 'mediabunny';
const sink = new CanvasSink(videoTrack, options);
```
Here, `options` has the following type:
```ts
type CanvasSinkOptions = {
width?: number;
height?: number;
fit?: 'fill' | 'contain' | 'cover';
rotation?: 0 | 90 | 180 | 270;
flip?: boolean;
crop?: { left: number; top: number; width: number; height: number };
poolSize?: number;
alpha?: boolean;
decoderOptions?: VideoSinkDecoderOptions;
};
```
* `width`\
The width of the output canvas in pixels. When omitted but `height` is set, the width will be calculated automatically to maintain the original aspect ratio. Otherwise, the width will be set to the original width of the video.
* `height`\
The height of the output canvas in pixels. When omitted but `width` is set, the height will be calculated automatically to maintain the original aspect ratio. Otherwise, the height will be set to the original height of the video.
* `fit`\
*Required* when both `width` and `height` are set, this option sets the fitting algorithm to use.
* `'fill'` will stretch the image to fill the entire box, potentially altering aspect ratio.
* `'contain'` will contain the entire image within the box while preserving aspect ratio. This may lead to letterboxing.
* `'cover'` will scale the image until the entire box is filled, while preserving aspect ratio.
* `rotation`\
The clockwise rotation by which to rotate the raw video frame. Defaults to the rotation set in the file metadata. Rotation is applied before flipping, cropping and resizing.
* `flip`\
Whether to flip the raw video frame horizontally (about the vertical axis). Defaults to the flip set in the file metadata. The flip is applied after rotation but before cropping and resizing.
* `crop`\
Specifies the rectangular region of the input video to crop to. The crop region will automatically be clamped to the dimensions of the input video track. Cropping is performed after rotation and flip but before resizing. The crop region is in the *display pixel space* of the underlying video data.
* `poolSize`\
See [Canvas pool](#canvas-pool).
* `alpha`\
Whether the output canvases should have transparency instead of a black background. Defaults to `false`. Set this to `true` when using this sink to read transparent videos.
* `decoderOptions`\
Additional preferences for the underlying video decoder.
Some examples:
```ts
// This sink yields canvases with the unaltered display dimensions of the track,
// and respecting the track's rotation and flip metadata.
new CanvasSink(videoTrack);
// This sink yields canvases with a width of 1280 and a height that maintains the
// original display aspect ratio.
new CanvasSink(videoTrack, {
width: 1280,
});
// This sink yields square canvases, with the video frame scaled to completely
// cover the canvas.
new CanvasSink(videoTrack, {
width: 512,
height: 512,
fit: 'cover',
});
// This sink yields canvases with the unrotated dimensions of the track,
// and without applying any rotation or flip.
new CanvasSink(videoTrack, {
rotation: 0,
flip: false,
});
```
The methods for retrieving canvases are analogous to those on `VideoSampleSink`:
* `getCanvas`\
Gets the canvas for a given timestamp; see [Single retrieval](#single-retrieval).
* `canvases`\
Iterates over a range of canvases; see [Range iteration](#range-iteration).
* `canvasesAtTimestamps`\
Iterates over canvases at specific timestamps; see [Sparse iteration](#sparse-iteration).
These methods yield `WrappedCanvas` instances:
```ts
type WrappedCanvas = {
// A canvas element or offscreen canvas.
canvas: HTMLCanvasElement | OffscreenCanvas;
// The timestamp of the corresponding video sample, in seconds.
timestamp: number;
// The duration of the corresponding video sample, in seconds.
duration: number;
};
```
#### Canvas pool
By default, a new canvas is created for every canvas yielded by this sink. If you know you'll keep only a few canvases around at any given time, you should make use of the `poolSize` option. This integer value specifies the number of canvases in the pool; these canvases are then reused in a ring buffer / round-robin type fashion. This keeps the amount of allocated VRAM constant and relieves the browser from constantly allocating/deallocating canvases. A pool size of 0 or `undefined` disables the pool.
An illustration using a pool size of 3:
```ts
const sink = new CanvasSink(videoTrack, { poolSize: 3 });
const a = await sink.getCanvas(42);
const b = await sink.getCanvas(42);
const c = await sink.getCanvas(42);
const d = await sink.getCanvas(42);
const e = await sink.getCanvas(42);
const f = await sink.getCanvas(42);
assert(a.canvas === d.canvas);
assert(b.canvas === e.canvas);
assert(c.canvas === f.canvas);
assert(a.canvas !== b.canvas);
assert(a.canvas !== c.canvas);
```
For closed iterators, a pool size of 1 is sufficient:
```ts
const sink = new CanvasSink(videoTrack, { poolSize: 1 });
const canvases = sink.canvases();
for await (const { canvas, timestamp } of canvases) {
// ...
}
```
## Audio data sinks
These sinks can only be used with an `InputAudioTrack`.
### `AudioSampleSink`
Use this sink to extract decoded [audio samples](./packets-and-samples#audiosample) from an audio track. The sink will automatically handle the decoding internally.
Create the sink like so:
```ts
import { AudioSampleSink } from 'mediabunny';
const sink = new AudioSampleSink(audioTrack);
```
The methods for retrieving samples are analogous to those on `VideoSampleSink`.
* `getSample`\
Gets the sample for a given timestamp; see [Single retrieval](#single-retrieval).
* `samples`\
Iterates over a range of samples; see [Range iteration](#range-iteration).
* `samplesAtTimestamps`\
Iterates over samples at specific timestamps; see [Sparse iteration](#sparse-iteration).
These methods yield [`AudioSample`](./packets-and-samples#audiosample) instances.
For example, let's use this sink to calculate the average loudness of an audio track using [root mean square](https://en.wikipedia.org/wiki/Root_mean_square):
```ts
const sink = new AudioSampleSink(audioTrack);
let sumOfSquares = 0;
let totalSampleCount = 0;
for await (const sample of sink.samples()) {
const bytesNeeded = sample.allocationSize({ format: 'f32', planeIndex: 0 });
const floats = new Float32Array(bytesNeeded / 4);
sample.copyTo(floats, { format: 'f32', planeIndex: 0 });
for (let i = 0; i < floats.length; i++) {
sumOfSquares += floats[i] ** 2;
}
totalSampleCount += floats.length;
}
const averageLoudness = Math.sqrt(sumOfSquares / totalSampleCount);
```
### `AudioBufferSink`
While `AudioSampleSink` extracts raw decoded audio samples, you can use `AudioBufferSink` to directly extract [`AudioBuffer`](https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer) instances instead. This is particularly useful when working with the Web Audio API.
Create the sink like so:
```ts
import { AudioBufferSink } from 'mediabunny';
const sink = new AudioBufferSink(audioTrack);
```
The methods for retrieving audio buffers are analogous to those on `VideoSampleSink`:
* `getBuffer`\
Gets the buffer for a given timestamp; see [Single retrieval](#single-retrieval).
* `buffers`\
Iterates over a range of buffers; see [Range iteration](#range-iteration).
* `buffersAtTimestamps`\
Iterates over buffers at specific timestamps; see [Sparse iteration](#sparse-iteration).
These methods yield `WrappedAudioBuffer` instances:
```ts
type WrappedAudioBuffer = {
// An AudioBuffer that can be used with the Web Audio API.
buffer: AudioBuffer;
// The timestamp of the corresponding audio sample, in seconds.
timestamp: number;
// The duration of the corresponding audio sample, in seconds.
duration: number;
};
```
For example, let's use this sink to play the last 10 seconds of an audio track:
```ts
const sink = new AudioBufferSink(audioTrack);
const audioContext = new AudioContext();
const lastTimestamp = await audioTrack.computeDuration();
const baseTime = audioContext.currentTime;
for await (const { buffer, timestamp } of sink.buffers(lastTimestamp - 10)) {
const source = audioContext.createBufferSource();
source.buffer = buffer;
source.connect(audioContext.destination);
source.start(baseTime + timestamp);
}
```
---
---
url: /guide/media-sources.md
description: >-
Media sources enable multiple ways to add media data to new media files, from
built-in encoding to manual per-packet control.
---
# Media sources
## Introduction
*Media sources* provide APIs for adding media data to an output file. Different media sources provide different levels of abstraction and cater to different use cases.
For information on how to use media sources to create output tracks, check [Writing media files](./writing-media-files).
Most media sources follow this code pattern to add media data:
```ts
await mediaSource.add(...);
```
### Closing sources
When you're done using the source, meaning no additional media data will be added, it's best to close the source as soon as possible:
```ts
mediaSource.close();
```
Closing sources manually is *technically* not required and will happen automatically when finalizing the `Output`. However, if your `Output` has multiple tracks and not all of them finish supplying their data at the same time (for example, adding all audio first and then all video), closing sources early will improve performance and lower memory usage. This is because the `Output` can better "plan ahead", knowing it doesn't have to wait for certain tracks anymore (see [Packet buffering](./writing-media-files#packet-buffering)). Therefore, it is good practice to always manually close all media sources as soon as you are done using them.
### Backpressure
Media sources are the means by which backpressure is propagated from the output pipeline into your application logic. The `Output` may want to apply backpressure if the encoders or the [StreamTarget](./writing-media-files#streamtarget)'s writable can't keep up.
Backpressure is communicated by media sources via promises. All media sources with an `add` method return a promise:
```ts
mediaSource.add(...); // => Promise
```
This promise resolves when the source is ready to receive more data. In most cases, the promise will resolve instantly, but if some part of the output pipeline is overworked, it will remain pending until the output is ready to continue. Therefore, by awaiting this promise, you automatically propagate backpressure into your application logic:
```ts
// Wrong: // [!code error]
while (notDone) { // [!code error]
mediaSource.add(...); // [!code error]
} // [!code error]
// Correct:
while (notDone) {
await mediaSource.add(...);
}
```
### Video encoding config
All video sources that handle encoding internally require you to specify a `VideoEncodingConfig`, specifying the codec configuration to use:
```ts
type VideoEncodingConfig = {
codec: VideoCodec;
quality: Quality;
alpha?: 'discard' | 'keep';
latencyMode?: 'quality' | 'realtime';
keyFrameInterval?: number;
fullCodecString?: string;
hardwareAcceleration?: 'no-preference' | 'prefer-hardware' | 'prefer-software';
scalabilityMode?: string;
contentHint?: string;
sizeChangeBehavior?: 'deny' | 'passThrough' | 'fill' | 'contain' | 'cover';
transform?: {
width?: number;
height?: number;
fit?: 'fill' | 'contain' | 'cover';
rotate?: 0 | 90 | 180 | 270;
flip?: boolean;
crop?: { left: number; top: number; width: number; height: number };
frameRate?: number;
process?: (sample: VideoSample) => MaybePromise<
CanvasImageSource | VideoSample | (CanvasImageSource | VideoSample)[] | null
>;
force?: boolean;
};
onEncodedPacket?: (
packet: EncodedPacket,
meta: EncodedVideoChunkMetadata | undefined
) => unknown;
onEncoderConfig?: (
config: VideoEncoderConfig
) => unknown;
};
```
* `codec`: The [video codec](./supported-formats-and-codecs#video-codecs) used for encoding.
* `quality`: The desired quality of the encoded video. See [Encoding quality](#encoding-quality).
* `alpha`: What to do with alpha data contained in the video samples.
* `'discard'` (default): Only the samples' color data is kept; the video is opaque.
* `'keep'`: The samples' alpha data is also encoded as side data. Make sure to pair this mode with a container format that supports transparency (such as WebM or Matroska).
* `latencyMode`: The latency mode as specified by the WebCodecs API. Browsers default to `quality`. Media stream-driven video sources will automatically use the `realtime` setting.
* `keyFrameInterval`: The maximum interval in seconds between two adjacent key frames. Defaults to 2 seconds. More frequent key frames improve seeking behavior but increase file size. When using multiple video tracks, this value should be set to the same value for all tracks.
* `fullCodecString`: Allows you to optionally specify the full codec string used by the video encoder, as specified in the [Mediabunny Codec Registry](/codec-registry/overview). For example, you may set it to `'avc1.42001f'` when using AVC. Keep in mind that the codec string must still match the codec specified in `codec`. If you don't set this field, a codec string will be generated automatically.
* `hardwareAcceleration`: A hint that configures the hardware acceleration method of this codec. This is best left on `'no-preference'`.
* `scalabilityMode`: An encoding scalability mode identifier as defined by [WebRTC-SVC](https://w3c.github.io/webrtc-svc/#scalabilitymodes*).
* `contentHint`: An encoding video content hint as defined by [mst-content-hint](https://w3c.github.io/mst-content-hint/#video-content-hints).
* `sizeChangeBehavior`: Video frames may change size over time. This field controls the behavior in case this happens. Defaults to `'deny'`.
* `transform`: Optional transformations to apply to the video frames before they are passed to the encoder.
* `width`: The width in pixels to resize the frames to. If `height` is not set, it will be deduced automatically based on aspect ratio.
* `height`: The height in pixels to resize the frames to. If `width` is not set, it will be deduced automatically based on aspect ratio.
* `fit`: The fitting algorithm in case both `width` and `height` are set. To avoid ambiguity, this field must not be set when `sizeChangeBehavior` is `'fill'`, `'contain'` or `'deny'`, since `sizeChangeBehavior` already determines the fitting algorithm.
* `'fill'` will stretch the image to fill the entire box, potentially altering aspect ratio.
* `'contain'` will contain the entire image within the box while preserving aspect ratio. This may lead to letterboxing.
* `'cover'` will scale the image until the entire box is filled, while preserving aspect ratio.
* `rotate`: The clockwise rotation by which to rotate the frames, in addition to each frame's own rotation. Rotation is applied before flipping.
* `flip`: Whether to flip the frames horizontally (about the vertical axis), in addition to each frame's own flip. The flip is applied after rotation but before cropping and resizing.
* `crop`: Specifies the rectangular region of the frames to crop to. The crop region will automatically be clamped to the dimensions of the frame. Cropping is performed after rotation and flip but before resizing.
* `frameRate`: The frame rate in hertz to normalize the video frame stream to.
* `process`: Allows for custom user-defined processing of video frames, e.g. for applying overlays, color transformations, or timestamp modifications. Will be called for each video frame after transformations and frame rate corrections. Must return a `VideoSample` or a `CanvasImageSource`, an array of them, or `null` for dropping the frame. When non-timestamped data is returned, the timestamp and duration from the input sample will be used.
* `force`: Forces every video frame through the transformation step even if no transformation properties are defined. This can be used, for example, to bake rotation and flip into the encoded video frames.
* `onEncodedPacket`: Called for each successfully encoded packet. Useful for determining encoding progress.
* `onEncoderConfig`: Called when the internal encoder config, as used by the WebCodecs API, is created. You can use this to introspect the full codec string.
### Audio encoding config
All audio sources that handle encoding internally require you to specify an `AudioEncodingConfig`, specifying the codec configuration to use:
```ts
type AudioEncodingConfig = {
codec: AudioCodec;
quality?: Quality;
fullCodecString?: string;
transform?: {
numberOfChannels?: number;
sampleRate?: number;
process?: (sample: AudioSample) => MaybePromise<
AudioSample | AudioSample[] | null
>;
};
onEncodedPacket?: (
packet: EncodedPacket,
meta: EncodedAudioChunkMetadata | undefined
) => unknown;
onEncoderConfig?: (
config: AudioEncoderConfig
) => unknown;
};
```
* `codec`: The [audio codec](./supported-formats-and-codecs#audio-codecs) used for encoding. Can be omitted for uncompressed PCM codecs.
* `quality`: The desired quality of the encoded audio; unused for PCM codecs. See [Encoding quality](#encoding-quality).
* `fullCodecString`: Allows you to optionally specify the full codec string used by the audio encoder, as specified in the [Mediabunny Codec Registry](/codec-registry/overview). For example, you may set it to `'mp4a.40.2'` when using AAC. Keep in mind that the codec string must still match the codec specified in `codec`. If you don't set this field, a codec string will be generated automatically.
* `transform`: Optional transformations to apply to the audio samples before they are passed to the encoder.
* `numberOfChannels`: The desired number of output channels to up/downmix to.
* `sampleRate`: The desired output sample rate in hertz to resample to.
* `process`: Allows for custom user-defined processing of audio samples, e.g. for applying audio effects or timestamp modifications. Called for each audio sample after resampling and remixing. Must return an `AudioSample`, an array of them, or `null` for dropping the sample.
* `onEncodedPacket`: Called for each successfully encoded packet. Useful for determining encoding progress.
* `onEncoderConfig`: Called when the internal encoder config, as used by the WebCodecs API, is created. You can use this to introspect the full codec string.
### Encoding quality
Mediabunny provides the [`Quality`](../api/Quality) class as a way to describe the desired encoding quality, i.e. how much the media should be compressed.
#### Qualitative quality
Qualitative qualities are defined abstractly will automatically map to an underlying bitrate or quantizer based on codec and media parameters (such as video dimensions).
```ts
import { Quality } from 'mediabunny';
// A Quality can be created from these five pre-defined values
new Quality('very-low');
new Quality('low');
new Quality('medium');
new Quality('high');
new Quality('very-high');
// Or from a quality value from 0 to 1. Here, 0 represents the worst quality and
// 1 the best.
new Quality(0.6);
```
#### Quantitative quality
Quantitative qualities allow explicit control over compression parameters.
```ts
import { Quality } from 'mediabunny';
// 1 Mbps bitrate (variable)
new Quality({
bitrate: 1e6,
});
// 1 Mbps bitrate (constant)
new Quality({
bitrate: 1e6,
bitrateMode: 'constant',
});
// Specific quantizer value to use. The valid range of values depends on each
// codec and is defined in the Mediabunny Codec Registry. Throws if quantizer
// mode is unavailable.
new Quality({
quantizer: 32,
});
// Quantizer and bitrate combined, with bitrate used as a fallback
new Quality({
quantizer: 32,
bitrate: 1e6,
});
```
## Video sources
Video sources feed data to video tracks on an `Output`. They all extend the abstract `VideoSource` class.
### `VideoSampleSource`
This source takes [video samples](./packets-and-samples#videosample), encodes them, and passes the encoded data to the output.
```ts
import { VideoSampleSource, Quality } from 'mediabunny';
const sampleSource = new VideoSampleSource({
codec: 'avc',
quality: new Quality({ bitrate: 1e6 }),
});
await sampleSource.add(videoSample);
videoSample.close(); // If it's not needed anymore
// You may optionally force samples to be encoded as key frames:
await sampleSource.add(videoSample, { keyFrame: true });
```
### `CanvasSource`
This source simplifies a common pattern: A single canvas is repeatedly updated in a render loop and each frame is added to the output file.
```ts
import { CanvasSource, Quality } from 'mediabunny';
const canvasSource = new CanvasSource(canvasElement, {
codec: 'av1',
quality: new Quality('medium'),
});
await canvasSource.add(0.0, 0.1); // Timestamp, duration (in seconds)
await canvasSource.add(0.1, 0.1);
await canvasSource.add(0.2, 0.1);
// You may optionally force frames to be encoded as key frames:
await canvasSource.add(0.3, 0.1, { keyFrame: true });
```
### `MediaStreamVideoTrackSource`
This is a source for use with the [Media Capture and Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Media_Capture_and_Streams_API). Use this source if you want to pipe a real-time video source (such as a webcam or screen recording) to an output file.
```ts
import { MediaStreamVideoTrackSource, Quality } from 'mediabunny';
// Get the user's screen
const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];
const videoTrackSource = new MediaStreamVideoTrackSource(videoTrack, {
codec: 'vp9',
quality: new Quality({ bitrate: 1e7 }),
});
// Make sure to allow any internal errors to properly bubble up
videoTrackSource.errorPromise.catch((error) => ...);
```
This source requires no additional method calls; data will automatically be captured and piped to the output file as soon as `start()` is called on the `Output`. Make sure to `stop()` on `videoTrack` after finalizing the `Output` if you don't need the user's media anymore.
If you want to temporarily stop capturing video frames from this source, you can use the `pause()` and `resume()` methods:
```ts
videoTrackSource.pause();
// Later:
videoTrackSource.resume();
```
While paused, video frames emitted by the stream will be ignored. When resumed, video frames are let through again, offset in timestamp such that the result plays back continuously with no gap in playback. Note that pausing does *not* stop the underlying media stream.
::: info
If this source is the only MediaStreamTrack source in the `Output`, then the first video sample added by it starts at timestamp 0. If there are multiple, then the earliest media sample across all tracks starts at timestamp 0, and all tracks will be perfectly synchronized with each other.
:::
::: warning
`MediaStreamVideoTrackSource`'s internals are detached from the typical code flow but can still throw, so make sure to utilize `errorPromise` to deal with any errors and to stop the `Output`.
:::
### `EncodedVideoPacketSource`
The most barebones of all video sources, this source can be used to directly pipe [encoded packets](./packets-and-samples#encodedpacket) of video data to the output. This source requires that you take care of the encoding process yourself, which enables you to use the WebCodecs API manually or to plug in your own encoding stack. Alternatively, you may retrieve the encoded packets directly by reading them from another media file, allowing you to skip decoding and reencoding video data.
```ts
import { EncodedVideoPacketSource } from 'mediabunny';
// You must specify the codec name:
const packetSource = new EncodedVideoPacketSource('vp9');
await packetSource.add(packet1);
await packetSource.add(packet2);
```
> \[!IMPORTANT]
> You must add the packets in decode order.
You will need to provide additional metadata alongside your first call to `add` to give the `Output` more information about the shape and form of the video data. This metadata must be in the form of the WebCodecs API's `EncodedVideoChunkMetadata`. It might look like this:
```ts
await packetSource.add(firstPacket, {
decoderConfig: {
codec: 'vp09.00.31.08',
codedWidth: 1280,
codedHeight: 720,
colorSpace: {
primaries: 'bt709',
transfer: 'iec61966-2-1',
matrix: 'smpte170m',
fullRange: false,
},
description: undefined,
},
});
```
`codec`, `codedWidth`, and `codedHeight` are required for all codecs, whereas `description` is required for some codecs. Additional fields, such as `colorSpace`, are optional. The [Mediabunny Codec Registry](/codec-registry/overview) specifies the formats of `codec` and `description` for each video codec, which you **must** adhere to.
#### B-frames
Some video codecs use *B-frames*, which are frames that require both the previous and the next frame to be decoded. For example, you may have something like this:
```md
Frame 1: 0.0s, I-frame (key frame)
Frame 2: 0.1s, B-frame
Frame 3: 0.2s, P-frame
```
The decode order for these frames will be:
```md
Frame 1 -> Frame 3 -> Frame 2
```
Some file formats have an explicit notion of both a "decode timestamp" and a "presentation timestamp" to model B-frames or out-of-order decoding. However, Mediabunny packets only specify their *presentation timestamp*. Decode order is determined by the order in which you add the packets, so in our example, you must add the packets like this:
```ts
await packetSource.add(packetForFrame1); // 0.0s
await packetSource.add(packetForFrame3); // 0.2s
await packetSource.add(packetForFrame2); // 0.1s
```
You are allowed to provide wildly out-of-order presentation timestamp sequences, but there is a hard constraint:
> \[!IMPORTANT]
> A packet you add must not have a smaller timestamp than the largest timestamp you added before adding the last key frame.
This is quite a mouthful, so this example will hopefully clarify it:
```md
# Legal:
Packet 1: 0.0s, key frame
Packet 2: 0.3s, delta frame
Packet 3: 0.2s, delta frame
Packet 4: 0.1s, delta frame
Packet 5: 0.4s, key frame
Packet 6: 0.5s, delta frame
# Also legal:
Packet 1: 0.0s, key frame
Packet 2: 0.3s, delta frame
Packet 3: 0.2s, delta frame
Packet 4: 0.1s, delta frame
Packet 5: 0.4s, key frame
Packet 6: 0.35s, delta frame
Packet 7: 0.3s, delta frame
Packet 8: 0.5s, delta frame
# Illegal:
Packet 1: 0.0s, key frame
Packet 2: 0.3s, delta frame
Packet 3: 0.2s, delta frame
Packet 4: 0.1s, delta frame
Packet 5: 0.4s, key frame
Packet 6: 0.25s, delta frame
```
## Audio sources
Audio sources feed data to audio tracks on an `Output`. They all extend the abstract `AudioSource` class.
### `AudioSampleSource`
This source takes [audio samples](./packets-and-samples#audiosample), encodes them, and passes the encoded data to the output.
```ts
import { AudioSampleSource, Quality } from 'mediabunny';
const sampleSource = new AudioSampleSource({
codec: 'aac',
quality: new Quality({ bitrate: 128e3 }),
});
await sampleSource.add(audioSample);
audioSample.close(); // If it's not needed anymore
```
### `AudioBufferSource`
This source directly accepts instances of `AudioBuffer` as data, simplifying usage with the Web Audio API. The first AudioBuffer will be played at timestamp 0, and any subsequent AudioBuffer will be appended after all previous AudioBuffers.
```ts
import { AudioBufferSource, Quality } from 'mediabunny';
const bufferSource = new AudioBufferSource({
codec: 'opus',
quality: new Quality('medium'),
});
await bufferSource.add(audioBuffer1);
await bufferSource.add(audioBuffer2);
await bufferSource.add(audioBuffer3);
```
### `MediaStreamAudioTrackSource`
This is a source for use with the [Media Capture and Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Media_Capture_and_Streams_API). Use this source if you want to pipe a real-time audio source (such as a microphone or audio from the user's computer) to an output file.
```ts
import { MediaStreamAudioTrackSource, Quality } from 'mediabunny';
// Get the user's microphone
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const audioTrack = stream.getAudioTracks()[0];
const audioTrackSource = new MediaStreamAudioTrackSource(audioTrack, {
codec: 'opus',
quality: new Quality({ bitrate: 128e3 }),
});
// Make sure to allow any internal errors to properly bubble up
audioTrackSource.errorPromise.catch((error) => ...);
```
This source requires no additional method calls; data will automatically be captured and piped to the output file as soon as `start()` is called on the `Output`. Make sure to `stop()` on `audioTrack` after finalizing the `Output` if you don't need the user's media anymore.
If you want to temporarily stop capturing audio data from this source, you can use the `pause()` and `resume()` methods:
```ts
audioTrackSource.pause();
// Later:
audioTrackSource.resume();
```
While paused, audio data emitted by the stream will be ignored. When resumed, audio data are let through again, offset in timestamp such that the result plays back continuously with no gap in playback. Note that pausing does *not* stop the underlying media stream.
::: info
If this source is the only MediaStreamTrack source in the `Output`, then the first audio sample added by it starts at timestamp 0. If there are multiple, then the earliest media sample across all tracks starts at timestamp 0, and all tracks will be perfectly synchronized with each other.
:::
::: warning
`MediaStreamAudioTrackSource`'s internals are detached from the typical code flow but can still throw, so make sure to utilize `errorPromise` to deal with any errors and to stop the `Output`.
:::
### `EncodedAudioPacketSource`
The most barebones of all audio sources, this source can be used to directly pipe [encoded packets](./packets-and-samples#encodedpacket) of audio data to the output. This source requires that you take care of the encoding process yourself, which enables you to use the WebCodecs API manually or to plug in your own encoding stack. Alternatively, you may retrieve the encoded packets directly by reading them from another media file, allowing you to skip decoding and reencoding audio data.
```ts
import { EncodedAudioPacketSource } from 'mediabunny';
// You must specify the codec name:
const packetSource = new EncodedAudioPacketSource('aac');
await packetSource.add(packet);
```
You will need to provide additional metadata alongside your first call to `add` to give the `Output` more information about the shape and form of the audio data. This metadata must be in the form of the WebCodecs API's `EncodedAudioChunkMetadata`. It might look like this:
```ts
await packetSource.add(firstPacket, {
decoderConfig: {
codec: 'mp4a.40.2',
numberOfChannels: 2,
sampleRate: 48000,
description: new Uint8Array([17, 144]),
},
});
```
`codec`, `numberOfChannels`, and `sampleRate` are required for all codecs, whereas `description` is required for some codecs. The [Mediabunny Codec Registry](/codec-registry/overview) specifies the formats of `codec` and `description` for each audio codec, which you must adhere to.
## Subtitle sources
Subtitle sources feed data to subtitle tracks on an `Output`. They all extend the abstract `SubtitleSource` class.
### `TextSubtitleSource`
This source feeds subtitle cues to the output from a text file in which the subtitles are defined.
```ts
import { TextSubtitleSource } from 'mediabunny';
const textSource = new TextSubtitleSource('webvtt');
const text =
`WEBVTT
00:00:00.000 --> 00:00:02.000
This is your last chance.
00:00:02.500 --> 00:00:04.000
After this, there is no turning back.
00:00:04.500 --> 00:00:06.000
If you take the blue pill, the story ends.
00:00:06.500 --> 00:00:08.000
You wake up in your bed and believe whatever you want to believe.
00:00:08.500 --> 00:00:10.000
If you take the red pill, you stay in Wonderland
00:00:10.500 --> 00:00:12.000
and I show you how deep the rabbit hole goes.
`;
await textSource.add(text);
```
If you add the entire subtitle file at once, make sure to [close the source](#closing-sources) immediately after:
```ts
textSource.close();
```
You can also add cues individually in small chunks:
```ts
import { TextSubtitleSource } from 'mediabunny';
const textSource = new TextSubtitleSource('webvtt');
await textSource.add('WEBVTT\n\n');
await textSource.add('00:00:00.000 --> 00:00:02.000\nHello there!\n\n');
await textSource.add('00:00:02.500 --> 00:00:04.000\nChunky chunks.\n\n');
```
The chunks have certain constraints: A cue must be fully contained within a chunk and cannot be split across multiple smaller chunks (although a chunk can contain multiple cues). Also, the WebVTT preamble must be added first and all at once.
::: info
For QuickTime to display WebVTT subtitles, it typically expects alignment information to be specified:
```
00:00:00.000 --> 00:00:02.000 align:center
This is your last chance.
```
:::
---
---
url: /api.md
description: >-
Detailed documentation for all classes, functions, constants and types exposed
by Mediabunny's public API.
---
# Mediabunny API reference
Here you can find detailed documentation for all classes, functions, constants and types exposed by Mediabunny's public API.
## Samples
Raw, unencoded chunks of media data, such as video frames or sections of audio.
* [AudioSample](./AudioSample.md)
* [AudioSampleInit](./AudioSampleInit.md)
* [AudioSampleCopyToOptions](./AudioSampleCopyToOptions.md)
* [AudioSampleResource](./AudioSampleResource.md)
* [VideoSample](./VideoSample.md)
* [VideoSampleInit](./VideoSampleInit.md)
* [VideoSamplePixelFormat](./VideoSamplePixelFormat.md)
* [VideoSampleColorSpace](./VideoSampleColorSpace.md)
* [VideoSampleResource](./VideoSampleResource.md)
* [VideoSampleTransformOptions](./VideoSampleTransformOptions.md)
* [VideoSampleTransformationDescription](./VideoSampleTransformationDescription.md)
* [VIDEO\_SAMPLE\_PIXEL\_FORMATS](./VIDEO_SAMPLE_PIXEL_FORMATS.md)
* [VideoDataPlane](./VideoDataPlane.md)
* [registerVideoSampleTransformer](./registerVideoSampleTransformer.md)
## Packets
Chunks of encoded media data.
* [EncodedPacket](./EncodedPacket.md)
* [EncodedPacketSideData](./EncodedPacketSideData.md)
* [PacketType](./PacketType.md)
## Input files & tracks
Read input files and their tracks; demuxer API.
* [Input](./Input.md)
* [InputOptions](./InputOptions.md)
* [InputEvents](./InputEvents.md)
* [InputDisposedError](./InputDisposedError.md)
* [UnsupportedInputFormatError](./UnsupportedInputFormatError.md)
* [DurationMetadataRequestOptions](./DurationMetadataRequestOptions.md)
* [InputTrack](./InputTrack.md)
* [InputVideoTrack](./InputVideoTrack.md)
* [InputAudioTrack](./InputAudioTrack.md)
* [InputTrackQuery](./InputTrackQuery.md)
* [FrameRateMetrics](./FrameRateMetrics.md)
* [FrameRateMetricsOptions](./FrameRateMetricsOptions.md)
* [PacketStats](./PacketStats.md)
* [asc](./asc.md)
* [desc](./desc.md)
* [prefer](./prefer.md)
## Input formats
Container formats that Mediabunny can read.
* [InputFormat](./InputFormat.md)
* [InputFormatOptions](./InputFormatOptions.md)
* [AdtsInputFormat](./AdtsInputFormat.md)
* [FlacInputFormat](./FlacInputFormat.md)
* [IsobmffInputFormat](./IsobmffInputFormat.md)
* [IsobmffInputFormatOptions](./IsobmffInputFormatOptions.md)
* [HlsInputFormat](./HlsInputFormat.md)
* [HlsInputFormatOptions](./HlsInputFormatOptions.md)
* [MatroskaInputFormat](./MatroskaInputFormat.md)
* [Mp3InputFormat](./Mp3InputFormat.md)
* [Mp4InputFormat](./Mp4InputFormat.md)
* [MpegTsInputFormat](./MpegTsInputFormat.md)
* [OggInputFormat](./OggInputFormat.md)
* [QuickTimeInputFormat](./QuickTimeInputFormat.md)
* [WaveInputFormat](./WaveInputFormat.md)
* [WebMInputFormat](./WebMInputFormat.md)
* [ALL\_FORMATS](./ALL_FORMATS.md)
* [HLS\_FORMATS](./HLS_FORMATS.md)
* [ADTS](./ADTS.md)
* [FLAC](./FLAC.md)
* [HLS](./HLS.md)
* [MATROSKA](./MATROSKA.md)
* [MP3](./MP3.md)
* [MP4](./MP4.md)
* [MPEG\_TS](./MPEG_TS.md)
* [OGG](./OGG.md)
* [QTFF](./QTFF.md)
* [WAVE](./WAVE.md)
* [WEBM](./WEBM.md)
## Input sources
The sources that can provide data to an `Input`.
* [Source](./Source.md)
* [SourceEvents](./SourceEvents.md)
* [SourceRef](./SourceRef.md)
* [SourceRequest](./SourceRequest.md)
* [BlobSource](./BlobSource.md)
* [BlobSourceOptions](./BlobSourceOptions.md)
* [BufferSource](./BufferSource.md)
* [CustomPathedSource](./CustomPathedSource.md)
* [CustomSource](./CustomSource.md)
* [CustomSourceOptions](./CustomSourceOptions.md)
* [FilePathSource](./FilePathSource.md)
* [FilePathSourceOptions](./FilePathSourceOptions.md)
* [PathedSource](./PathedSource.md)
* [StreamSource](./StreamSource.md)
* [StreamSourceOptions](./StreamSourceOptions.md)
* [RangedSource](./RangedSource.md)
* [ReadableStreamSource](./ReadableStreamSource.md)
* [ReadableStreamSourceOptions](./ReadableStreamSourceOptions.md)
* [UrlSource](./UrlSource.md)
* [UrlSourceOptions](./UrlSourceOptions.md)
## Output files
Create and write new media files; muxer API.
* [Output](./Output.md)
* [OutputOptions](./OutputOptions.md)
* [OutputTrack](./OutputTrack.md)
* [OutputVideoTrack](./OutputVideoTrack.md)
* [OutputAudioTrack](./OutputAudioTrack.md)
* [OutputSubtitleTrack](./OutputSubtitleTrack.md)
* [OutputTrackGroup](./OutputTrackGroup.md)
* [BaseTrackMetadata](./BaseTrackMetadata.md)
* [VideoTrackMetadata](./VideoTrackMetadata.md)
* [AudioTrackMetadata](./AudioTrackMetadata.md)
* [SubtitleTrackMetadata](./SubtitleTrackMetadata.md)
* [OutputEvents](./OutputEvents.md)
## Output formats
Container formats that Mediabunny can write.
* [OutputFormat](./OutputFormat.md)
* [AdtsOutputFormat](./AdtsOutputFormat.md)
* [AdtsOutputFormatOptions](./AdtsOutputFormatOptions.md)
* [CmafOutputFormat](./CmafOutputFormat.md)
* [CmafOutputFormatOptions](./CmafOutputFormatOptions.md)
* [FlacOutputFormat](./FlacOutputFormat.md)
* [FlacOutputFormatOptions](./FlacOutputFormatOptions.md)
* [HlsOutputFormat](./HlsOutputFormat.md)
* [HlsOutputFormatOptions](./HlsOutputFormatOptions.md)
* [HlsOutputPlaylistInfo](./HlsOutputPlaylistInfo.md)
* [HlsOutputSegmentInfo](./HlsOutputSegmentInfo.md)
* [IsobmffOutputFormat](./IsobmffOutputFormat.md)
* [IsobmffOutputFormatOptions](./IsobmffOutputFormatOptions.md)
* [MkvOutputFormat](./MkvOutputFormat.md)
* [MkvOutputFormatOptions](./MkvOutputFormatOptions.md)
* [MovOutputFormat](./MovOutputFormat.md)
* [Mp3OutputFormat](./Mp3OutputFormat.md)
* [Mp3OutputFormatOptions](./Mp3OutputFormatOptions.md)
* [Mp4OutputFormat](./Mp4OutputFormat.md)
* [MpegTsOutputFormat](./MpegTsOutputFormat.md)
* [MpegTsOutputFormatOptions](./MpegTsOutputFormatOptions.md)
* [OggOutputFormat](./OggOutputFormat.md)
* [OggOutputFormatOptions](./OggOutputFormatOptions.md)
* [WavOutputFormat](./WavOutputFormat.md)
* [WavOutputFormatOptions](./WavOutputFormatOptions.md)
* [WebMOutputFormat](./WebMOutputFormat.md)
* [WebMOutputFormatOptions](./WebMOutputFormatOptions.md)
* [TrackCountLimits](./TrackCountLimits.md)
## Output targets
The targets where `Output` writes data to.
* [Target](./Target.md)
* [TargetEvents](./TargetEvents.md)
* [TargetRequest](./TargetRequest.md)
* [AppendOnlyStreamTarget](./AppendOnlyStreamTarget.md)
* [BufferTarget](./BufferTarget.md)
* [BufferTargetOptions](./BufferTargetOptions.md)
* [FilePathTarget](./FilePathTarget.md)
* [FilePathTargetOptions](./FilePathTargetOptions.md)
* [NullTarget](./NullTarget.md)
* [PathedTarget](./PathedTarget.md)
* [RangedTarget](./RangedTarget.md)
* [StreamTarget](./StreamTarget.md)
* [StreamTargetOptions](./StreamTargetOptions.md)
* [StreamTargetChunk](./StreamTargetChunk.md)
## Media sinks
Methods for extracting media data from input files.
* [AudioBufferSink](./AudioBufferSink.md)
* [AudioSampleSink](./AudioSampleSink.md)
* [BaseMediaSampleSink](./BaseMediaSampleSink.md)
* [CanvasSink](./CanvasSink.md)
* [CanvasSinkOptions](./CanvasSinkOptions.md)
* [EncodedPacketSink](./EncodedPacketSink.md)
* [PacketRetrievalOptions](./PacketRetrievalOptions.md)
* [VideoSampleSink](./VideoSampleSink.md)
* [VideoSinkDecoderOptions](./VideoSinkDecoderOptions.md)
* [WrappedAudioBuffer](./WrappedAudioBuffer.md)
* [WrappedCanvas](./WrappedCanvas.md)
## Media sources
Methods for adding media data to output files.
* [MediaSource](./MediaSource.md)
* [VideoSource](./VideoSource.md)
* [AudioSource](./AudioSource.md)
* [SubtitleSource](./SubtitleSource.md)
* [AudioBufferSource](./AudioBufferSource.md)
* [AudioBufferSourceOptions](./AudioBufferSourceOptions.md)
* [AudioSampleSource](./AudioSampleSource.md)
* [CanvasSource](./CanvasSource.md)
* [EncodedAudioPacketSource](./EncodedAudioPacketSource.md)
* [EncodedVideoPacketSource](./EncodedVideoPacketSource.md)
* [MediaStreamAudioTrackSource](./MediaStreamAudioTrackSource.md)
* [MediaStreamAudioTrackSourceOptions](./MediaStreamAudioTrackSourceOptions.md)
* [MediaStreamVideoTrackSource](./MediaStreamVideoTrackSource.md)
* [MediaStreamVideoTrackSourceOptions](./MediaStreamVideoTrackSourceOptions.md)
* [TextSubtitleSource](./TextSubtitleSource.md)
* [VideoSampleSource](./VideoSampleSource.md)
## Conversion
A simple API for converting and transforming media files.
* [Conversion](./Conversion.md)
* [ConversionOptions](./ConversionOptions.md)
* [ConversionVideoOptions](./ConversionVideoOptions.md)
* [ConversionAudioOptions](./ConversionAudioOptions.md)
* [ConversionCopyOptions](./ConversionCopyOptions.md)
* [ConversionExecuteOptions](./ConversionExecuteOptions.md)
* [ConversionCanceledError](./ConversionCanceledError.md)
* [DiscardedTrack](./DiscardedTrack.md)
## Metadata tags
Descriptive metadata tags attached to media files.
* [MetadataTags](./MetadataTags.md)
* [AttachedImage](./AttachedImage.md)
* [RichImageData](./RichImageData.md)
* [AttachedFile](./AttachedFile.md)
## Codecs
Codecs understood by Mediabunny.
* [MediaCodec](./MediaCodec.md)
* [VideoCodec](./VideoCodec.md)
* [AudioCodec](./AudioCodec.md)
* [SubtitleCodec](./SubtitleCodec.md)
* [VIDEO\_CODECS](./VIDEO_CODECS.md)
* [AUDIO\_CODECS](./AUDIO_CODECS.md)
* [PCM\_AUDIO\_CODECS](./PCM_AUDIO_CODECS.md)
* [NON\_PCM\_AUDIO\_CODECS](./NON_PCM_AUDIO_CODECS.md)
* [SUBTITLE\_CODECS](./SUBTITLE_CODECS.md)
## Encoding
Encoder configuration and encodability checks.
* [VideoEncodingConfig](./VideoEncodingConfig.md)
* [VideoEncodingAdditionalOptions](./VideoEncodingAdditionalOptions.md)
* [VideoTransformOptions](./VideoTransformOptions.md)
* [AudioEncodingConfig](./AudioEncodingConfig.md)
* [AudioEncodingAdditionalOptions](./AudioEncodingAdditionalOptions.md)
* [AudioTransformOptions](./AudioTransformOptions.md)
* [canEncode](./canEncode.md)
* [canEncodeVideo](./canEncodeVideo.md)
* [canEncodeAudio](./canEncodeAudio.md)
* [canEncodeSubtitles](./canEncodeSubtitles.md)
* [getEncodableCodecs](./getEncodableCodecs.md)
* [getEncodableVideoCodecs](./getEncodableVideoCodecs.md)
* [getEncodableAudioCodecs](./getEncodableAudioCodecs.md)
* [getEncodableSubtitleCodecs](./getEncodableSubtitleCodecs.md)
* [getFirstEncodableVideoCodec](./getFirstEncodableVideoCodec.md)
* [getFirstEncodableAudioCodec](./getFirstEncodableAudioCodec.md)
* [getFirstEncodableSubtitleCodec](./getFirstEncodableSubtitleCodec.md)
* [Quality](./Quality.md)
* [QualityOptions](./QualityOptions.md)
* [QualitativeQualityOptions](./QualitativeQualityOptions.md)
* [QuantitativeQualityOptions](./QuantitativeQualityOptions.md)
* [QualityLevel](./QualityLevel.md)
* [QUALITY\_VERY\_LOW](./QUALITY_VERY_LOW.md)
* [QUALITY\_LOW](./QUALITY_LOW.md)
* [QUALITY\_MEDIUM](./QUALITY_MEDIUM.md)
* [QUALITY\_HIGH](./QUALITY_HIGH.md)
* [QUALITY\_VERY\_HIGH](./QUALITY_VERY_HIGH.md)
## Decoding
Decoder configuration and decodability checks.
* [canDecode](./canDecode.md)
* [canDecodeVideo](./canDecodeVideo.md)
* [canDecodeAudio](./canDecodeAudio.md)
* [getDecodableCodecs](./getDecodableCodecs.md)
* [getDecodableVideoCodecs](./getDecodableVideoCodecs.md)
* [getDecodableAudioCodecs](./getDecodableAudioCodecs.md)
## Custom coders
API for adding custom encoders and decoders.
* [CustomVideoDecoder](./CustomVideoDecoder.md)
* [CustomVideoEncoder](./CustomVideoEncoder.md)
* [CustomAudioDecoder](./CustomAudioDecoder.md)
* [CustomAudioEncoder](./CustomAudioEncoder.md)
* [registerDecoder](./registerDecoder.md)
* [registerEncoder](./registerEncoder.md)
## Logging
Control over what Mediabunny logs to the console.
* [Logging](./Logging.md)
* [LogLevel](./LogLevel.md)
* [LoggingEvents](./LoggingEvents.md)
## Miscellaneous
Whatever's left.
* [InclusiveIntegerRange](./InclusiveIntegerRange.md)
* [AnyIterable](./AnyIterable.md)
* [ConcurrentRunner](./ConcurrentRunner.md)
* [DeepReadonly](./DeepReadonly.md)
* [EventEmitter](./EventEmitter.md)
* [EventListenerOptions](./EventListenerOptions.md)
* [FilePath](./FilePath.md)
* [MaybePromise](./MaybePromise.md)
* [PsshBox](./PsshBox.md)
* [Rational](./Rational.md)
* [Rectangle](./Rectangle.md)
* [Rotation](./Rotation.md)
* [SetOptional](./SetOptional.md)
* [SetRequired](./SetRequired.md)
* [TransformationMatrix](./TransformationMatrix.md)
* [TrackType](./TrackType.md)
* [ALL\_TRACK\_TYPES](./ALL_TRACK_TYPES.md)
* [CropRectangle](./CropRectangle.md)
* [TrackDisposition](./TrackDisposition.md)
## @mediabunny/server
Adds full video/audio decoder and encoder support to Mediabunny running in server-side environments such as Node, Bun, or Deno.
* [registerMediabunnyServer](./registerMediabunnyServer.md)
* [MediabunnyServerOptions](./MediabunnyServerOptions.md)
* [AvFrameVideoSampleResource](./AvFrameVideoSampleResource.md)
* [AvFrameAudioSampleResource](./AvFrameAudioSampleResource.md)
* [toAvFrame](./toAvFrame.md)
## @mediabunny/mp3-encoder
Adds MP3 encoder support to Mediabunny.
* [registerMp3Encoder](./registerMp3Encoder.md)
## @mediabunny/ac3
Adds AC-3/E-AC-3 decoder and encoder support to Mediabunny.
* [registerAc3Decoder](./registerAc3Decoder.md)
* [registerAc3Encoder](./registerAc3Encoder.md)
## @mediabunny/dts
Adds DTS decoder and encoder support to Mediabunny.
* [registerDtsDecoder](./registerDtsDecoder.md)
* [registerDtsEncoder](./registerDtsEncoder.md)
## @mediabunny/truehd
Adds Dolby TrueHD decoder and encoder support to Mediabunny.
* [registerTrueHdDecoder](./registerTrueHdDecoder.md)
* [registerTrueHdEncoder](./registerTrueHdEncoder.md)
## @mediabunny/aac-encoder
Polyfills AAC encoder support to Mediabunny.
* [registerAacEncoder](./registerAacEncoder.md)
## @mediabunny/flac-encoder
Adds FLAC encoder support to Mediabunny.
* [registerFlacEncoder](./registerFlacEncoder.md)
## @mediabunny/prores
Adds Apple ProRes decoder support to Mediabunny.
* [registerProresDecoder](./registerProresDecoder.md)
---
---
url: /codec-registry/overview.md
description: >-
The Mediabunny Codec Registry formalizes the precise definitions of all video
and audio codecs supported by Mediabunny, like expected codec string and
packet data format.
---
# Mediabunny Codec Registry
The Mediabunny Codec Registry formalizes the precise definitions of all video and audio codecs supported by Mediabunny. More specifically, for any given codec, it describes the format that `EncodedPacket`, `VideoDecoderConfig` and `AudioDecoderConfig` must adhere to. All packets coming out of or going into Mediabunny are expected to adhere to this registry.
The registry is an extension of the [WebCodecs Codec Registry](https://www.w3.org/TR/webcodecs-codec-registry/). Mediabunny's registry matches that of WebCodecs for all codecs supported by both.
## Video codecs
* [AVC (H.264)](./avc)
* [HEVC (H.265)](./hevc)
* [VP8](./vp8)
* [VP9](./vp9)
* [AV1](./av1)
* [ProRes](./prores)
## Audio codecs
* [AAC](./aac)
* [Opus](./opus)
* [MP3](./mp3)
* [Vorbis](./vorbis)
* [FLAC](./flac)
* [AC-3](./ac3)
* [E-AC-3](./eac3)
* [DTS](./dts)
* [TrueHD](./truehd)
* [Linear PCM](./pcm)
* [μ-law PCM](./ulaw)
* [A-law PCM](./alaw)
---
---
url: /codec-registry/mp3.md
description: >-
MP3 (MPEG-1/2 Audio Layer III) audio codec definition, defining legal codec
strings, decoder configs, and packet data formats.
---
# MP3 codec registration
## Description
The MP3 audio codec (MPEG-1/2 Audio Layer III), specified in [ISO/IEC 13818-3](https://www.iso.org/standard/26797.html).
## Codec ID
```ts
'mp3'
```
## `EncodedPacket` data
The packet's data must be an MP3 frame as described in Section 2.4.2.2 of [ISO/IEC 13818-3](https://www.iso.org/standard/26797.html).
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
```ts
'mp3'
```
## `AudioDecoderConfig` description
`description` is not used for this codec.
---
---
url: /codec-registry/opus.md
description: >-
Opus audio codec definition, defining legal codec strings, decoder configs,
and packet data formats.
---
# Opus codec registration
## Description
The Opus audio codec, specified in [RFC 6716](https://www.rfc-editor.org/rfc/rfc6716).
## Codec ID
```ts
'opus'
```
## `EncodedPacket` data
The packet's data must be an Opus packet as described in Section 3 of [RFC 6716](https://www.rfc-editor.org/rfc/rfc6716).
## `EncodedPacket` type
The packet's type is always `'key'`.
## `AudioDecoderConfig` codec string
```ts
'opus'
```
## `AudioDecoderConfig` description
If present, `description` must be an Identification Header as defined in Section 5.1 of [RFC 7845](https://www.rfc-editor.org/rfc/rfc7845).
---
---
url: /guide/output-formats.md
description: >-
Mediabunny can write a wide range of media output formats, including MP4,
WebM, MP3, HLS, and many more.
---
# Output formats
## Introduction
An *output format* specifies the container format of the data written by an `Output`. Mediabunny supports many commonly used container formats, each having format-specific options.
Many formats also offer *data callbacks*, which are special callbacks that fire for specific data regions in the output file.
### Output format properties
All output formats have a common set of properties you can query.
```ts
// Get the format's file extension:
format.fileExtension; // => '.mp4'
// Get the format's base MIME type:
format.mimeType; // => 'video/mp4'
// Check which codecs can be contained by the format:
format.getSupportedCodecs(); // => MediaCodec[]
format.getSupportedVideoCodecs(); // => VideoCodec[]
format.getSupportedAudioCodecs(); // => AudioCodec[]
format.getSupportedSubtitleCodecs(); // => SubtitleCodec[]
// Check if the format supports video tracks with rotation and flip metadata:
format.supportsVideoTransformationMetadata; // => boolean
```
Refer to the [compatibility table](./supported-formats-and-codecs.md#compatibility-table) to see which codecs can be used with which output format.
Formats also differ in the amount and types of tracks they can contain. You can retrieve this information using:
```ts
format.getSupportedTrackCounts(); // => TrackCountLimits
type TrackCountLimits = {
video: { min: number, max: number },
audio: { min: number, max: number },
subtitle: { min: number, max: number },
total: { min: number, max: number },
};
```
### Append-only writing
Some output format configurations write in an *append-only* fashion. This means they only ever add new data to the end, and never have to seek back to overwrite a previously-written section of the file. Or, put formally: the byte offset of any write is exactly equal to the number of bytes written before it.
Append-only formats, in combination with [`StreamTarget`](./writing-media-files#streamtarget), have some useful properties. They enable use with [Media Source Extensions](https://developer.mozilla.org/en-US/docs/Web/API/Media_Source_Extensions_API) and allow for trivial streaming across the network, such as for file uploads.
## MP4
This output format creates MP4 files.
```ts
import { Output, Mp4OutputFormat } from 'mediabunny';
const output = new Output({
format: new Mp4OutputFormat(options),
// ...
});
```
The following options are available:
```ts
type IsobmffOutputFormatOptions = {
fastStart?: false | 'in-memory' | 'reserve' | 'fragmented';
minimumFragmentDuration?: number;
metadataFormat?: 'mdir' | 'mdta' | 'udta' | 'auto';
onFtyp?: (data: Uint8Array, position: number) => unknown;
onMoov?: (data: Uint8Array, position: number) => unknown;
onMdat?: (data: Uint8Array, position: number) => unknown;
onMoof?: (data: Uint8Array, position: number, timestamp: number) => unknown;
};
```
* `fastStart`\
Controls the placement of metadata in the file. Placing metadata at the start of the file is known as "Fast Start" and provides certain benefits: The file becomes easier to stream over the web without range requests, and sites like YouTube can start processing the video while it's uploading. However, placing metadata at the start of the file can require more processing and memory in the writing step. This library provides full control over the placement of metadata by setting `fastStart` to one of these options:
* `false`\
Disables Fast Start, placing the metadata at the end of the file. Fastest and uses the least memory.
* `'in-memory'`\
Produces a file with Fast Start by keeping all media chunks in memory until the file is finalized. This produces a high-quality and compact output at the cost of a more expensive finalization step and higher memory requirements.
::: info
This option ensures [append-only writing](#append-only-writing), although all the writing happens in bulk, at the end.
:::
* `'reserve'`\
Produces a file with Fast Start by reserving space at the start of the file into which the metadata will be written later. This requires knowledge about the expected length of the file beforehand. When using this option, you must set the [`maximumPacketCount`](../api/BaseTrackMetadata#maximumpacketcount) field in the track metadata for all tracks. [Conversions](./converting-media-files) estimate this count automatically if no override is provided.
* `'fragmented'`\
Produces a *fragmented MP4 (fMP4)* file, evenly placing sample metadata throughout the file by grouping it into "fragments" (short sections of media), while placing general metadata at the beginning of the file. Fragmented files are ideal in streaming contexts, as each fragment can be played individually without requiring knowledge of the other fragments. Furthermore, they remain lightweight to create no matter how large the file becomes, as they don't require media to be kept in memory for very long. However, fragmented files are not as widely and wholly supported as regular MP4 files, and some players don't provide seeking functionality for them.
::: info
This option ensures [append-only writing](#append-only-writing).
:::
* `undefined`\
The default option; it behaves like `'in-memory'` when using [`BufferTarget`](./writing-media-files#buffertarget) and like `false` otherwise.
* `minimumFragmentDuration`\
Only relevant when `fastStart` is `'fragmented'`. Sets the minimum duration in seconds a fragment must have to be finalized and written to the file. Defaults to 1 second.
* `metadataFormat`\
The metadata format to use for writing metadata tags.
* `'auto'` (default): Behaves like `'mdir'` for MP4 and like `'udta'` for QuickTime, matching FFmpeg's default behavior.
* `'mdir'`: Write tags into `moov/udta/meta` using the 'mdir' handler format.
* `'mdta'`: Write tags into `moov/udta/meta` using the 'mdta' handler format, equivalent to FFmpeg's `use_metadata_tags` flag. This allows for custom keys of arbitrary length.
* `'udta'`: Write tags directly into `moov/udta`.
* `onFtyp`\
Will be called once the ftyp (File Type) box of the output file has been written.
* `onMoov`\
Will be called once the moov (Movie) box of the output file has been written.
* `onMdat`\
Will be called for each finalized mdat (Media Data) box of the output file. Usage of this callback is not recommended when not using `fastStart: 'fragmented'`, as there will be one monolithic mdat box which might require large amounts of memory.
* `onMoof`\
Will be called for each finalized moof (Movie Fragment) box of the output file. The fragment's start timestamp in seconds is also passed.
## QuickTime File Format (.mov)
This output format creates QuickTime files (.mov).
```ts
import { Output, MovOutputFormat } from 'mediabunny';
const output = new Output({
format: new MovOutputFormat(options),
// ...
});
```
The available options are the same `IsobmffOutputFormatOptions` used by [MP4](#mp4).
## CMAF
This output format creates a single Common Media Application Format (CMAF) segment (.m4s).
```ts
import { Output, CmafOutputFormat } from 'mediabunny';
const output = new Output({
format: new CmafOutputFormat(options),
initTarget: new BufferTarget(), // For example
// ...
});
```
A CMAF segment requires a separate init segment, which is written to the target specified by [`OutputOptions.initTarget`](../api/OutputOptions#inittarget).
The available options are the same `IsobmffOutputFormatOptions` used by [MP4](#mp4), but with the `fastStart` option removed and with `minimumFragmentDuration` defaulting to `Infinity`.
CMAF is mainly intended for use as the segment format of [HLS](#hls).
## WebM
This output format creates WebM files.
```ts
import { Output, WebMOutputFormat } from 'mediabunny';
const output = new Output({
format: new WebMOutputFormat(options),
// ...
});
```
The following options are available:
```ts
type MkvOutputFormatOptions = {
appendOnly?: boolean;
minimumClusterDuration?: number;
onEbmlHeader?: (data: Uint8Array, position: number) => void;
onSegmentHeader?: (data: Uint8Array, position: number) => unknown;
onCluster?: (data: Uint8Array, position: number, timestamp: number) => unknown;
};
```
* `appendOnly`\
Configures the output to write data in an append-only fashion. This is useful for live-streaming the output as it's being created. Note that when enabled, certain features like file duration or seeking will be disabled or impacted, so don't use this option when you want to write out a media file for later use.
::: info
This option ensures [append-only writing](#append-only-writing).
:::
* `minimumClusterDuration`\
Sets the minimum duration in seconds a cluster must have to be finalized and written to the file. Defaults to 1 second.
* `onEbmlHeader`\
Will be called once the EBML header of the output file has been written.
* `onSegmentHeader`\
Will be called once the header part of the Matroska Segment element has been written. The header data includes the Segment element and everything inside it, up to (but excluding) the first Matroska Cluster.
* `onCluster`\
Will be called for each finalized Matroska Cluster of the output file. The cluster's start timestamp in seconds is also passed.
## Matroska (.mkv)
This output format creates Matroska files (.mkv).
```ts
import { Output, MkvOutputFormat } from 'mediabunny';
const output = new Output({
format: new MkvOutputFormat(options),
// ...
});
```
The available options are the same `MkvOutputFormatOptions` used by [WebM](#webm).
## Ogg
This output format creates Ogg files.
```ts
import { Output, OggOutputFormat } from 'mediabunny';
const output = new Output({
format: new OggOutputFormat(options),
// ...
});
```
::: info
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.
## MP3
This output format creates MP3 files.
```ts
import { Output, Mp3OutputFormat } from 'mediabunny';
const output = new Output({
format: new Mp3OutputFormat(options),
// ...
});
```
The following options are available:
```ts
type Mp3OutputFormatOptions = {
xingHeader?: boolean;
onXingFrame?: (data: Uint8Array, position: number) => unknown;
};
```
* `xingHeader`\
Controls whether the Xing header, which contains additional metadata as well as an index, is written to the start of the MP3 file. Defaults to `true`.
::: info
When set to `false`, this option ensures [append-only writing](#append-only-writing).
:::
* `onXingFrame`\
Will be called once the Xing metadata frame is finalized, which happens at the end of the writing process. This callback only fires if `xingHeader` isn't set to `false`.
::: info
Most browsers don't support encoding MP3. Use the official [`@mediabunny/mp3-encoder`](./extensions/mp3-encoder) package to polyfill an encoder.
:::
## WAVE
This output format creates WAVE (.wav) files.
```ts
import { Output, WavOutputFormat } from 'mediabunny';
const output = new Output({
format: new WavOutputFormat(options),
// ...
});
```
The following options are available:
```ts
type WavOutputFormatOptions = {
large?: boolean;
metadataFormat?: 'info' | 'id3';
onHeader?: (data: Uint8Array, position: number) => unknown;
};
```
* `large`\
When enabled, an RF64 file be written, allowing for file sizes to exceed 4 GiB, which is otherwise not possible for regular WAVE files.
* `metadataFormat`\
The metadata format to use for writing metadata tags.
* `'info'` (default): Writes metadata into a RIFF INFO LIST chunk, the default way to contain metadata tags within WAVE. Only allows for a limited subset of tags to be written.
* `'id3'`: Writes metadata into an ID3 chunk. Non-default, but used by many taggers in practice. Allows for a much larger and richer set of tags to be written.
* `onHeader`\
Will be called once the file header is written. The header consists of the RIFF header, the format chunk, and the start of the data chunk (with a placeholder size of 0).
## ADTS
This output format creates ADTS (.aac) files.
```ts
import { Output, AdtsOutputFormat } from 'mediabunny';
const output = new Output({
format: new AdtsOutputFormat(options),
// ...
});
```
::: info
This format ensures [append-only writing](#append-only-writing).
:::
The following options are available:
```ts
type AdtsOutputFormatOptions = {
onFrame?: (data: Uint8Array, position: number) => unknown;
};
```
* `onFrame`\
Will be called for each ADTS frame that is written.
## FLAC
This output format creates FLAC (.flac) files.
```ts
import { Output, FlacOutputFormat } from 'mediabunny';
const output = new Output({
format: new FlacOutputFormat(options),
// ...
});
```
The following options are available:
```ts
type FlacOutputFormatOptions = {
appendOnly?: boolean;
onFrame?: (data: Uint8Array, position: number) => unknown;
};
```
* `appendOnly`\
Configures the output to only append new data at the end, useful for live-streaming the file as it's being created. When enabled, the STREAMINFO block will not be finalized with accurate min/max block sizes, frame sizes, or total sample count, so don't use this option when you want to write out a clean file for later use.
::: info
This option ensures [append-only writing](#append-only-writing).
:::
* `onFrame`\
Will be called for each FLAC frame that is written.
## MPEG-TS
This output format creates MPEG Transport Stream (.ts) files.
```ts
import { Output, MpegTsOutputFormat } from 'mediabunny';
const output = new Output({
format: new MpegTsOutputFormat(options),
// ...
});
```
::: info
This format ensures [append-only writing](#append-only-writing).
:::
The following options are available:
```ts
type MpegTsOutputFormatOptions = {
onPacket?: (data: Uint8Array, position: number) => unknown;
};
```
* `onPacket`\
Will be called for each 188-byte Transport Stream packet that is written.
## HLS
This output format creates media files compatible with the HTTP Live Streaming (HLS) protocol. HLS media is represented by a set of .m3u8 playlist files and media segment files, meaning this format writes out multiple files, requiring the use of a *pathed Output*.
This output format creates the following files:
* A master playlist .m3u8 file, containing the list of available playlists. A master playlist is always emitted, written to the root path.
* One .m3u8 file for each playlist, each containing a list of media segments.
* Many media segments, containing the actual media data.
To emit media playlists that use the `#EXT-X-PROGRAM-DATE-TIME` tag to map segment timestamps to real-world time, set `BaseTrackMetadata.isRelativeToUnixEpoch` to `true` for all output tracks.
```ts
import { Output, PathedTarget, MpegTsOutputFormat } from 'mediabunny';
const output = new Output({
format: new HlsOutputFormat(options),
target: new PathedTarget('master.m3u8', ({ path }) => {
// Return a target
}),
});
```
::: info
This format ensures [append-only writing](#append-only-writing) for master and media playlists; for media segments it depends on the media segment format.
:::
The following options are available:
```ts
export type HlsOutputFormatOptions = {
segmentFormat: OutputFormat | OutputFormat[];
targetDuration?: number;
singleFilePerPlaylist?: boolean;
live?: boolean;
maxLiveSegmentCount?: number;
getPlaylistPath?: (info: HlsOutputPlaylistInfo) => MaybePromise;
getSegmentPath?: (info: HlsOutputSegmentInfo) => MaybePromise;
getInitPath?: (info: HlsOutputPlaylistInfo) => MaybePromise;
onMaster?: (content: string) => unknown;
onPlaylist?: (content: string, info: HlsOutputPlaylistInfo) => unknown;
onSegment?: (target: Target, info: HlsOutputSegmentInfo) => unknown;
onInit?: (target: Target, info: HlsOutputPlaylistInfo) => unknown;
};
```
* `segmentFormat`\
**Required.** Specifies the file format of each media segment. Not all formats are supported by all players; prefer sticking to the most commonly used ones: `MpegTsOutputFormat`, `CmafOutputFormat`, `AdtsOutputFormat`, and `Mp3OutputFormat`.
When an array of formats is specified, for each playlist, the first format that can contain all of the playlist's tracks is chosen. This allows you to, for example, package audio into .aac files and video into .ts files.
* `targetDuration`\
Specifies the target (max) duration in seconds for each media segment, defaulting to 2 seconds.
Mediabunny will try not to emit media segments longer than the target duration, but it is forced to if key frames are provided with a longer period than the target duration. Therefore, make sure to encode a key frame at least every `targetDuration` seconds to guarantee segment length, controllable via [`VideoEncodingConfig.keyFrameInterval`](../api/VideoEncodingConfig#keyframeinterval).
* `singleFilePerPlaylist`\
Whether to bundle all media segments for a playlist into a single file. Individual segments are then extracted via range requests.
* `live`\
If `true`, the muxer will be in "live mode", continuously emitting updated playlists as new segments are created. The master playlist will be emitted as soon as all playlists have been emitted at least once, and will continue to be emitted each time a segment is finalized to further refine the accuracy of the `BANDWIDTH` attribute.
When `false` (the default), all playlists will only be emitted once, upon output finalization.
* `maxLiveSegmentCount`\
When in live mode, this controls the maximum number of segments contained in each playlist. Defaults to `Infinity`, meaning playlists continually grow in size.
* `getPlaylistPath`\
Returns the file path for a given media playlist. If the returned path is relative, it is relative to the root path.
Defaults to `'playlist-{n}.m3u8'`, where `n` is the 1-based index of the media playlist in the master playlist.
* `getSegmentPath`\
Returns the file path for a given media segment. If the returned path is relative, it is relative to the path of the containing playlist.
Defaults to `'segment-{n}-{k}{ext}'`, where `n` is the 1-based index of the containing media playlist in the master playlist, `k` is the 1-based index of the segment in its playlist, and `ext` is the file extension of the segment format (including the leading dot).
If `singleFilePerPlaylist` is true, it defaults to `'segments-{n}{ext}'` instead.
* `getInitPath`\
Returns the file path for a given media init segment. If the returned path is relative, it is relative to the path of the containing playlist.
Only necessary for segment formats that require an init file, such as `CmafOutputFormat`.
Defaults to `'init-{n}{ext}'`, where `n` is the 1-based index of the containing media playlist in the master playlist and `ext` is the file extension of the segment format (including the leading dot).
* `onMaster`\
Called whenever the master playlist is written.
* `onPlaylist`\
Called whenever a media playlist is written.
* `onSegment`\
Called whenever a media segment has been fully written. In single-file mode, this function will only be called once when the playlist is finalized.
* `onInit`\
Called when a media playlist is initialized, before any segments have been written. In single-file mode, this function is never called.
---
---
url: /guide/packets-and-samples.md
description: >-
Learn about how packets carry encoded media data, samples carry raw decoded
media data, and the operations you can perform on them.
---
# Packets & samples
## Introduction
Media data in Mediabunny is present in two different forms:
* **Packet:** Encoded media data, the result of an encoding process
* **Sample:** Raw, uncompressed, presentable media data
In addition to data, both packets and samples carry additional metadata, such as timestamp, duration, width, etc.
Packets are represented with the `EncodedPacket` class, which is used for both video and audio packets. Samples are represented with the `VideoSample` and `AudioSample` classes:
* `VideoSample`: Represents a single frame of video.
* `AudioSample`: Represents a (typically short) section of audio.
Samples can be encoded into packets, and packets can be decoded into samples:
```mermaid
flowchart LR
A[VideoSample]
B[AudioSample]
C[EncodedPacket]
D[VideoSample]
E[AudioSample]
A -- encode --> C
B -- encode --> C
C -- decode --> D
C -- decode --> E
```
### Connection to WebCodecs
Packets and samples in Mediabunny correspond directly with concepts of the [WebCodecs API](https://w3c.github.io/webcodecs/):
* `EncodedPacket`\
-> `EncodedVideoChunk` for video packets\
-> `EncodedAudioChunk` for audio packets
* `VideoSample`
-> `VideoFrame`
* `AudioSample`
-> `AudioData`
Since Mediabunny makes heavy use of WebCodecs API, its own classes are typically used as wrappers around the WebCodecs classes. However, this wrapping comes with a few benefits:
1. **Independence:** This library remains functional even if the WebCodecs API isn't available. Encoders and decoders can be polyfilled using [custom coders](./supported-formats-and-codecs#custom-coders), and the library can run in non-browser contexts such as Node.js.
2. **Extensibility:** The wrappers serve as a namespace for additional operations, such as `toAudioBuffer()` on `AudioSample`, or `draw()` on `VideoSample`.
3. **Consistency:** While WebCodecs uses integer microsecond timestamps, Mediabunny uses floating-point second timestamps everywhere. With these wrappers, all timing information is always in seconds and the user doesn't need to think about unit conversions.
Conversion is easy:
```ts
import { EncodedPacket, VideoSample, AudioSample } from 'mediabunny';
// EncodedPacket to WebCodecs chunks:
encodedPacket.toEncodedVideoChunk(); // => EncodedVideoChunk
encodedPacket.toEncodedAudioChunk(); // => EncodedAudioChunk
// WebCodecs chunks to EncodedPacket:
EncodedPacket.fromEncodedChunk(videoChunk); // => EncodedPacket
EncodedPacket.fromEncodedChunk(audioChunk); // => EncodedPacket
// VideoSample to VideoFrame:
videoSample.toVideoFrame(); // => VideoFrame
// VideoFrame to VideoSample:
new VideoSample(videoFrame); // => VideoSample
// AudioSample to AudioData:
audioSample.toAudioData(); // => AudioData
// AudioData to AudioSample:
new AudioSample(audioData); // => AudioSample
```
::: info
`VideoSample`/`AudioSample` instances created from their WebCodecs API counterpart are very efficient; they simply maintain a reference to the underlying WebCodecs API instance and do not perform any unnecessary copying.
:::
### Negative timestamps
While packet and sample durations cannot be negative, packet and sample timestamps can.
A negative timestamp represents a sample that starts playing before the composition does (the composition always starts at 0). Negative timestamps are typically a result of a track being trimmed at the start, either to cut off a piece of media or to synchronize it with the other tracks. Therefore, you should avoid presenting any sample with a negative timestamp.
## `EncodedPacket`
An encoded packet represents encoded media data of any type (video or audio). They are the result of an *encoding process*, and you can turn encoded packets into actual media data using a *decoding process*.
### Creating packets
To create an `EncodedPacket`, you can use its constructor:
```ts
constructor(
data: Uint8Array,
type: 'key' | 'delta',
timestamp: number, // in seconds
duration: number, // in seconds
sequenceNumber?: number,
byteLength?: number,
);
```
When creating a packet for a given codec, you *must* adhere to the data format specified in the [Mediabunny Codec Registry](/codec-registry/overview).
::: info
You probably won't ever need to set `sequenceNumber` or `byteLength` in the constructor.
:::
For example, here we're creating a packet from some encoded video data:
```ts
import { EncodedPacket } from 'mediabunny';
const encodedVideoData = new Uint8Array([...]);
const encodedPacket = new EncodedPacket(encodedVideoData, 'key', 5, 1/24);
```
Alternatively, if you're coming from WebCodecs encoded chunks, you can create an `EncodedPacket` from them:
```ts
import { EncodedPacket } from 'mediabunny';
// From EncodedVideoChunk:
const encodedPacket = EncodedPacket.fromEncodedChunk(encodedVideoChunk);
// From EncodedAudioChunk:
const encodedPacket = EncodedPacket.fromEncodedChunk(encodedAudioChunk);
```
### Inspecting packets
Encoded packets have a bunch of read-only data you can inspect. You can get the encoded data like so:
```ts
encodedPacket.data; // => Uint8Array
```
You can query the type of packet:
```ts
encodedPacket.type; // => PacketType ('key' | 'delta')
```
* A *key packet* can be decoded directly, independently of other packets.
* A *delta packet* can only be decoded after the packet before it has been decoded.
For example, in a video track, it is common to have a key frame about every few seconds. When seeking, if the user seeks to a position shortly after a key frame, the decoded data can be shown quickly; if they seek far away from a key frame, the decoder must first crunch through many delta frames before it can show anything.
#### Determining a packet's actual type
The `type` field is derived from metadata in the containing file, which can sometimes (in rare cases) be incorrect. To determine a packet's actual type with certainty, you can do this:
```ts
// `packet` must come from the InputTrack `track`
const type = await track.determinePacketType(packet); // => PacketType | null
```
This determines the packet's type by looking into its bitstream. `null` is returned when the type couldn't be determined.
***
You can query the packet's timing information:
```ts
encodedPacket.timestamp; // => Presentation timestamp in seconds
encodedPacket.duration; // => Duration in seconds
// There also exist integer microsecond versions of these:
encodedPacket.microsecondTimestamp;
encodedPacket.microsecondDuration;
```
`timestamp` and `duration` are both given as floating-point numbers.
::: warning
Timestamps can be [negative](#negative-timestamps).
:::
***
A packet also has a quantity known as a *sequence number*:
```ts
encodedPacket.sequenceNumber; // => number
```
When [reading packets from an input file](./media-sinks#encodedpacketsink), this number specifies the relative ordering of packets. If packet $A$ has a lower sequence number than packet $B$, then packet $A$ comes first (in [decode order](./media-sinks#decode-vs-presentation-order)). If two packets have the same sequence number, then they represent the same media sample.
Sequence numbers have no meaning on their own and only make sense when comparing them to other sequence numbers. If a packet has sequence number $n$, it does not mean that it is the $n$th packet of the track.
Negative sequence numbers mean the packet's ordering is undefined. When creating an `EncodedPacket`, the sequence number defaults to -1.
### Cloning packets
Use the `clone` method to create a new packet from an existing packet. While doing so, you can partially change its data.
```ts
// Creates a clone identical to the original:
packet.clone();
// Creates a clone with the timestamp set to 10 seconds:
packet.clone({ timestamp: 10 });
```
### Metadata-only packets
[`EncodedPacketSink`](./media-sinks#encodedpacketsink) can create *metadata-only* packets:
```ts
await sink.getFirstPacket({ metadataOnly: true });
```
Metadata-only packets contain all the metadata of the full packet, but do not contain any data:
```ts
packet.data; // => Uint8Array([])
```
You can still retrieve the *size* that the data would have:
```ts
packet.byteLength; // => number
```
Given a packet, you can check if it is metadata-only like so:
```ts
packet.isMetadataOnly; // => boolean
```
## `VideoSample`
A video sample represents a single frame of video. It can be created directly from an image source, or be the result of a decoding process. Its API is modeled after [VideoFrame](https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame).
### Creating video samples
Video samples have an image source constructor and a raw constructor.
::: info
The constructor of `VideoSample` is very similar to [`VideoFrame`'s constructor](https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame/VideoFrame), but uses second timestamps instead of microsecond timestamps.
:::
#### Image source constructor
This constructor creates a `VideoSample` from a `CanvasImageSource`:
```ts
import { VideoSample } from 'mediabunny';
// Creates a sample from a canvas element
const sample = new VideoSample(canvas, {
timestamp: 3, // in seconds
duration: 1/24, // in seconds
});
// Creates a sample from an image element, with some added rotation and flip
const sample = new VideoSample(imageElement, {
timestamp: 5, // in seconds
rotation: 90, // in degrees clockwise
flip: true, // horizontal flip, applied after rotation
});
// Creates a sample from a VideoFrame (timestamp will be copied)
const sample = new VideoSample(videoFrame);
```
#### Raw constructor
This constructor creates a `VideoSample` from raw pixel data given in an `ArrayBuffer`:
```ts
import { VideoSample } from 'mediabunny';
// Creates a sample from pixel data in the RGBX format
const sample = new VideoSample(buffer, {
format: 'RGBX',
codedWidth: 1280,
codedHeight: 720,
timestamp: 0,
});
// Creates a sample from pixel data in the YUV 4:2:0 format
const sample = new VideoSample(buffer, {
format: 'I420',
codedWidth: 1280,
codedHeight: 720,
timestamp: 0,
});
```
See [`VideoPixelFormat`](https://w3c.github.io/webcodecs/#enumdef-videopixelformat) for a list of pixel formats supported by WebCodecs.
#### Custom resource constructor
For advanced use cases (custom decoders, GPU-backed frames, etc.), you can back a `VideoSample` with your own implementation of [`VideoSampleResource`](../api/VideoSampleResource):
```ts
import { VideoSample, VideoSampleResource } from 'mediabunny';
class MyResource extends VideoSampleResource {
// Implement getFormat(), getCodedWidth(), getCodedHeight(),
// getSquarePixelWidth(), getSquarePixelHeight(), getColorSpace(),
// getDataPlanes(), toRgbSample(), and close().
}
const sample = new VideoSample(new MyResource(), {
timestamp: 0,
});
```
This allows you to back a `VideoSample` with your own data without having to copy it.
### Inspecting video samples
A `VideoSample` has several read-only properties:
```ts
// The internal pixel format in which the frame is stored
videoSample.format; // => VideoPixelFormat | null
// Raw dimensions of the sample
videoSample.codedWidth; // => number
videoSample.codedHeight; // => number
// Pixel aspect ratio-corrected dimensions of the sample
videoSample.squarePixelWidth;
videoSample.squarePixelHeight;
// Transformed display dimensions of the sample (after rotation and flip)
videoSample.displayWidth; // => number
videoSample.displayHeight; // => number
// Rotation of the sample in degrees clockwise. The raw sample should be
// rotated by this amount when it is presented.
videoSample.rotation; // => 0 | 90 | 180 | 270
// Whether the raw sample should be flipped horizontally when it is presented,
// after rotation.
videoSample.flip; // => boolean
// The sample's pixel aspect ratio
videoSample.pixelAspectRatio; // => { num: number, den: number }
// Timing information
videoSample.timestamp; // => Presentation timestamp in seconds
videoSample.duration; // => Duration in seconds
videoSample.microsecondTimestamp; // => Presentation timestamp in microseconds
videoSample.microsecondDuration; // => Duration in microseconds
// Color space of the sample
videoSample.colorSpace; // => VideoColorSpace
videoSample.visibleRect; // Rectangle
// Encode options used when this sample is passed to an encoder
videoSample.encodeOptions; // => VideoEncoderEncodeOptions (defaults to {})
```
While all of these properties are read-only, you can use the `setTimestamp`, `setDuration`, `setRotation`, `setFlip` and `setEncodeOptions` methods to modify some of the metadata of the video sample.
::: warning
Timestamps can be [negative](#negative-timestamps).
:::
### Using video samples
Video samples provide a couple of ways with which you can access its frame data.
You can convert a video sample to a WebCodecs [`VideoFrame`](https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame) to access additional data or to pass it to a [`VideoEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/VideoEncoder):
```ts
videoSample.toVideoFrame(); // => VideoFrame
```
This method is virtually free if the video sample was constructed using a `VideoFrame`.
::: warning
The `VideoFrame` returned by this method **must** be closed separately from the video sample.
:::
***
It's also common to draw video samples to a `