--- 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 `` element or an `OffscreenCanvas`. For this, you can use the following methods: ```ts draw( context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, dx: number, dy: number, dWidth?: number, // defaults to displayWidth dHeight?: number, // defaults to displayHeight ): void; draw( context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth?: number, // defaults to sWidth dHeight?: number, // defaults to sHeight ): void; ``` These methods behave like [drawImage](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage) and paint the video frame at the given position with the given dimensions. This method will automatically draw the frame with the correct rotation and flip based on its `rotation` and `flip` properties. The `drawWithFit` method can be used to draw the video sample to fill an entire canvas with a specified fitting algorithm: ```ts drawWithFit( context: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, options: { fit: 'fill' | 'contain' | 'cover'; rotation?: Rotation; // Overrides the sample's rotation flip?: boolean; // Overrides the sample's flip crop?: CropRectangle; }, ): void; ``` If you want to draw the raw underlying image to a canvas directly (without respecting the rotation and flip metadata), then you can use the following method: ```ts videoSample.toCanvasImageSource(); // => VideoFrame | OffscreenCanvas; ``` This method returns a valid `CanvasImageSource` you can use with [drawImage](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage). ::: warning If this method returns a `VideoFrame`, you should use that frame immediately. This is because any internally-created video frames will automatically be closed in the next microtask. ::: *** Sometimes you may want direct access to the underlying pixel data. To do this, `VideoSample` allows you to copy this data into an `ArrayBuffer`. Use `allocationSize` to determine how many bytes are needed: ```ts const bytesNeeded = videoSample.allocationSize(); // => number ``` Then, use `copyTo` to copy the pixel data into the destination buffer: ```ts const bytes = new Uint8Array(bytesNeeded); const planeLayout = await videoSample.copyTo(bytes); ``` ::: info You can pass additional options to `allocationSize` and `copyTo` to extract data in a different pixel format. ::: *** You can transform a `VideoSample` to resize, rotate, flip, and/or crop it, producing a new `VideoSample`: ```ts const transformed = await videoSample.transform({ width: 640, height: 360, fit: 'cover', rotate: 90, flip: true, crop: { left: 0, top: 0, width: 1920, height: 1000 }, alpha: 'discard', }); ``` The operations are applied in this order: pixel aspect ratio normalization, rotation, flip, crop, resize. Rotation and flip are in addition to the sample's own `rotation` and `flip` metadata. In browser environments, the transform is performed using a canvas. In non-browser environments without `OffscreenCanvas` or `HTMLCanvasElement`, this method throws unless you register a custom transformer: ```ts import { registerVideoSampleTransformer } from 'mediabunny'; registerVideoSampleTransformer((sample, description) => { // Return a transformed VideoSample, or null to defer to the next transformer. }); ``` The [`@mediabunny/server`](./extensions/server) extension registers such a transformer. *** You can also clone a `VideoSample`: ```ts const clonedSample = videoSample.clone(); // => VideoSample ``` The cloned sample **must** be closed separately from the original sample. ### Closing video samples You must manually close a `VideoSample` after you've used it to free internally-held resources. Do this by calling the `close` method: ```ts videoSample.close(); ``` Try to close a `VideoSample` as soon as you don't need it anymore. Unclosed video samples can lead to high VRAM usage and decoder stalls. After a `VideoSample` has been closed, its data becomes unavailable and most of its methods will throw an error. ## `AudioSample` An audio sample represents a section of audio data. It can be created directly from raw audio data, or be the result of a decoding process. Its API is modeled after [AudioData](https://developer.mozilla.org/en-US/docs/Web/API/AudioData). ### Creating audio samples Audio samples can be constructed either from an `AudioData` instance, an initialization object, or an `AudioBuffer`: ```ts import { AudioSample } from 'mediabunny'; // From AudioData: const sample = new AudioSample(audioData); // From raw data: const sample = new AudioSample({ data: new Float32Array([...]), format: 'f32-planar', // Audio sample format numberOfChannels: 2, sampleRate: 44100, // in Hz timestamp: 0, // in seconds }); // From AudioBuffer: const timestamp = 0; // in seconds const samples = AudioSample.fromAudioBuffer(audioBuffer, timestamp); // => Returns multiple AudioSamples if the AudioBuffer is very long ``` The following audio sample formats are supported: * `'u8'`: 8-bit unsigned integer (interleaved) * `'u8-planar'`: 8-bit unsigned integer (planar) * `'s16'`: 16-bit signed integer (interleaved) * `'s16-planar'`: 16-bit signed integer (planar) * `'s32'`: 32-bit signed integer (interleaved) * `'s32-planar'`: 32-bit signed integer (planar) * `'f32'`: 32-bit floating point (interleaved) * `'f32-planar'`: 32-bit floating point (planar) Planar formats store each channel's data contiguously, while interleaved formats store the channels' data interleaved together: ![Planar vs. interleaved formats](../assets/planar_interleaved.svg) #### Custom resource constructor For advanced use cases (custom decoders, etc.), you can back an `AudioSample` with your own implementation of [`AudioSampleResource`](../api/AudioSampleResource): ```ts import { AudioSample, AudioSampleResource } from 'mediabunny'; class MyResource extends AudioSampleResource { // Implement getFormat(), getSampleRate(), getNumberOfFrames(), // getNumberOfChannels(), getTimestamp(), getDataPlane(), and close(). } const sample = new AudioSample(new MyResource()); ``` This allows you to back an `AudioSample` with your own data without having to copy it. ### Inspecting audio samples An `AudioSample` has several read-only properties: ```ts type AudioSampleFormat = 'u8' | 'u8-planar' | 's16' | 's16-planar' | 's32' | 's32-planar' | 'f32' | 'f32-planar'; audioSample.format; // => AudioSampleFormat audioSample.sampleRate; // => Sample rate in Hz audioSample.numberOfFrames; // => Number of frames per channel audioSample.numberOfChannels; // => Number of channels audioSample.timestamp; // => Presentation timestamp in seconds audioSample.duration; // => Duration in seconds (= numberOfFrames / sampleRate) // There also exist integer microsecond versions of timing info: audioSample.microsecondTimestamp; audioSample.microsecondDuration; ``` While all of these properties are read-only, you can use the `setTimestamp` method to modify the timestamp of the audio sample. ::: warning Timestamps can be [negative](#negative-timestamps). ::: ### Using audio samples Audio samples provide a couple of ways with which you can access its audio data. You can convert an audio sample to a WebCodecs [`AudioData`](https://developer.mozilla.org/en-US/docs/Web/API/AudioData) to pass it to an [`AudioEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/AudioEncoder): ```ts audioSample.toAudioData(); // => AudioData ``` This method is virtually free if the audio sample was constructed using an `AudioData`, as long as its timestamp wasn't modified using `setTimestamp`. ::: warning The `AudioData` returned by this method **must** be closed separately from the audio sample. ::: You can also easily convert the audio sample into an [`AudioBuffer`](https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer) for use with the Web Audio API: ```ts audioSample.toAudioBuffer(); // => AudioBuffer ``` *** You can also directly copy raw audio data from an `AudioSample` into an `ArrayBuffer`. For this, the `allocationSize` and `copyTo` methods can be used. The copying process is controlled by the following configuration object: ```ts type AudioSampleCopyToOptions = { planeIndex: number; format?: AudioSampleFormat; frameOffset?: number; frameCount?: number; }; ``` * `planeIndex` *(required)*\ The index identifying the plane to copy from. This must be 0 if using a non-planar (interleaved) output format. * `format`\ The output format for the destination data. Defaults to the `AudioSample`'s format. * `frameOffset`\ An offset into the source plane data indicating which frame to begin copying from. Defaults to 0. * `frameCount`\ The number of frames to copy. If not provided, the copy will include all frames in the plane beginning with `frameOffset`. Because the meaning of `planeIndex` depends on which format is being used for extraction, it's best to always explicitly specify a format. For example, here we're extracting the entire audio data as `f32`: ```ts const options = { planeIndex: 0, format: 'f32' }; const bytesNeeded = audioSample.allocationSize(options); const data = new Float32Array(bytesNeeded / 4); audioSample.copyTo(data, options); ``` Here, we're iterating over each plane in the `s16` format: ```ts // The size of the first plane is the size of all planes const bytesNeeded = audioSample.allocationSize({ planeIndex: 0, format: 's16-planar', }); const data = new Int16Array(bytesNeeded / 2); for (let i = 0; i < audioSample.numberOfChannels; i++) { audioSample.copyTo(data, { planeIndex: i, format: 's16-planar' }); // Do something with the data } ``` ::: info The behavior of `allocationSize` and `copyTo` exactly mirrors that of the WebCodecs API. However, the WebCodecs API specification only mandates support for converting to `f32-planar`, while Mediabunny's implementation supports conversion into all formats. Therefore, Mediabunny's methods are more powerful. ::: ### Closing audio samples You must manually close an `AudioSample` after you've used it to free internally-held resources. Do this by calling the `close` method: ```ts audioSample.close(); ``` Try to close an `AudioSample` as soon as you don't need it anymore. Unclosed audio samples can lead to high memory usage and decoder stalls. After an `AudioSample` has been closed, its data becomes unavailable and most of its methods will throw an error. --- --- url: /codec-registry/prores.md description: >- Apple ProRes video codec definition, defining legal codec strings, decoder configs, and packet data formats. --- # ProRes codec registration ## Description The Apple ProRes video codec, as specified in [SMPTE RDD 36](https://pub.smpte.org/doc/rdd36/). ## Codec ID ```ts 'prores' ``` ## `EncodedPacket` data The packet's data must be a `frame()` as defined in [SMPTE RDD 36](https://pub.smpte.org/doc/rdd36/). ## `EncodedPacket` type Since ProRes is intra-frame-only, every packet is a key frame and its type is therefore always `'key'`. ## `VideoDecoderConfig` codec string The codec string must be one of the six four-character codes identifying the ProRes profile: * `'ap4x'` - ProRes 4444 XQ * `'ap4h'` - ProRes 4444 * `'apch'` - ProRes 422 High Quality * `'apcn'` - ProRes 422 Standard Definition * `'apcs'` - ProRes 422 LT * `'apco'` - ProRes 422 Proxy ## `VideoDecoderConfig` description `description` is not used for this codec. --- --- url: /guide/quick-start.md description: >- A collection of short code snippets that showcase the most common operations that Mediabunny can do. --- # Quick start This page is a collection of short code snippets that showcase the most common operations you may use this library for. ## Read file metadata ```ts import { Input, ALL_FORMATS, BlobSource } from 'mediabunny'; const input = new Input({ formats: ALL_FORMATS, // Supporting all file formats source: new BlobSource(file), // Assuming a File instance }); const duration = await input.computeDuration(); // in seconds const allTracks = await input.getTracks(); // List of all tracks // Extract video metadata const videoTrack = await input.getPrimaryVideoTrack(); if (videoTrack) { await videoTrack.getDisplayWidth(); // in pixels await videoTrack.getDisplayHeight(); // in pixels await videoTrack.getRotation(); // in degrees clockwise // Estimate frame rate (FPS) const frameRateMetrics = await videoTrack.computeFrameRateMetrics(); const frameRate = frameRateMetrics.bestGuessFrameRate; } // Extract audio metadata const audioTrack = await input.getPrimaryAudioTrack(); if (audioTrack) { await audioTrack.getNumberOfChannels(); await audioTrack.getSampleRate(); // in Hz } // Extract metadata tags const tags = await input.getMetadataTags(); tags.title; // Title tags.date; // Release date tags.images[0]; // Cover art tags.raw['TBPM']; // Custom tags // ... ``` ::: info * Check out the Metadata extraction example for this code in action. * You can read from more than just `File` instances - check out [Input sources](./reading-media-files#input-sources) for more. ::: ## Read media data ```ts import { Input, ALL_FORMATS, BlobSource, VideoSampleSink, AudioSampleSink, } from 'mediabunny'; const input = new Input({ formats: ALL_FORMATS, source: new BlobSource(file), }); // Read video frames const videoTrack = await input.getPrimaryVideoTrack(); if (videoTrack) { const decodable = await videoTrack.canDecode(); if (decodable) { const sink = new VideoSampleSink(videoTrack); // Get the video frame at timestamp 5s const videoSample = await sink.getSample(5); videoSample.timestamp; // in seconds videoSample.duration; // in seconds // Draw the frame to a canvas videoSample.draw(ctx, 0, 0); // Loop over all frames in the first 30s of video for await (const sample of sink.samples(0, 30)) { // ... } } } // Read audio chunks const audioTrack = await input.getPrimaryAudioTrack(); if (audioTrack) { const decodable = await audioTrack.canDecode(); if (decodable) { const sink = new AudioSampleSink(audioTrack); // Get audio chunk at timestamp 5s; a short chunk of audio const audioSample = await sink.getSample(5); audioSample.timestamp; // in seconds audioSample.duration; // in seconds audioSample.numberOfFrames; // Convert to AudioBuffer for use with the Web Audio API const audioBuffer = audioSample.toAudioBuffer(); // Loop over all samples in the first 30s of audio for await (const sample of sink.samples(0, 30)) { // ... } } } ``` ::: info * Check out the Media player example for a demo built on this use case. * See [Media sinks](./media-sinks) for all the ways to extract media data from tracks. ::: ## Extract video thumbnails ```ts import { Input, ALL_FORMATS, BlobSource, CanvasSink, } from 'mediabunny'; const input = new Input({ formats: ALL_FORMATS, source: new BlobSource(file), }); const videoTrack = await input.getPrimaryVideoTrack(); if (videoTrack) { const decodable = await videoTrack.canDecode(); if (decodable) { const sink = new CanvasSink(videoTrack, { width: 320, // Automatically resize the thumbnails }); // Get the thumbnail at timestamp 10s const result = await sink.getCanvas(10); result.canvas; // HTMLCanvasElement | OffscreenCanvas result.timestamp; // in seconds result.duration; // in seconds // Generate five equally-spaced thumbnails through the video const startTimestamp = await videoTrack.getFirstTimestamp(); const endTimestamp = await videoTrack.computeDuration(); const timestamps = [0, 0.2, 0.4, 0.6, 0.8].map( (t) => startTimestamp + t * (endTimestamp - startTimestamp) ); // Loop over these timestamps for await (const result of sink.canvasesAtTimestamps(timestamps)) { // ... } } } ``` ::: info * Check out the Thumbnail generation example for this code in action. * You can further configure [`CanvasSink`](./media-sinks#canvassink). ::: ## Extract encoded packets ```ts import { Input, ALL_FORMATS, BlobSource, EncodedPacketSink, } from 'mediabunny'; const input = new Input({ formats: ALL_FORMATS, source: new BlobSource(file), }); const videoTrack = await input.getPrimaryVideoTrack(); if (videoTrack) { const sink = new EncodedPacketSink(videoTrack); // Get packet for timestamp 10s const packet = await sink.getPacket(10); packet.data; // Uint8Array packet.type; // 'key' | 'delta' packet.timestamp; // in seconds packet.duration; // in seconds // Get the closest key packet to timestamp 10s const keyPacket = await sink.getKeyPacket(10); // Get the following packet const nextPacket = await sink.getNextPacket(keyPacket); // Set up a manual decoder const decoderConfig = await videoTrack.getDecoderConfig(); const videoDecoder = new VideoDecoder({ output: console.log, error: console.error, }); videoDecoder.configure(decoderConfig); // Loop over all packets in decode order for await (const packet of sink.packets()) { videoDecoder.decode(packet.toEncodedVideoChunk()); } await videoDecoder.flush(); } ``` ::: info Check out [`EncodedPacketSink`](./media-sinks#encodedpacketsink) for the full documentation. ::: ## Create new media files ```ts import { AudioBufferSource, BufferTarget, CanvasSource, Mp4OutputFormat, Output, Quality, } from 'mediabunny'; // An Output represents a new media file const output = new Output({ format: new Mp4OutputFormat(), // The format of the file target: new BufferTarget(), // Where to write the file (here, to memory) }); // Example: add a video track driven by a canvas const videoSource = new CanvasSource(canvas, { codec: 'avc', quality: new Quality('high'), }); output.addVideoTrack(videoSource); // Example: add an audio track driven by AudioBuffers const audioSource = new AudioBufferSource({ codec: 'aac', quality: new Quality('high'), }); output.addAudioTrack(audioSource); // Set some metadata tags output.setMetadataTags({ title: 'My Movie', artist: 'Me', }); await output.start(); // Add some video frames for (let frame = 0; ...) { await videoSource.add(frame / 30, 1 / 30); } // Add some audio data await audioSource.add(audioBuffer1); await audioSource.add(audioBuffer2); await output.finalize(); const buffer = output.target.buffer; // ArrayBuffer containing the final MP4 file ``` ::: info * Check out the Procedural generation example for a demo of in-browser video generation. * You can create files of many different formats; check out [Output formats](./output-formats) for the full list. * Media data can be added from different sources, see [Media sources](./media-sources). ::: ## Write directly to disk ```ts import { Output, StreamTarget, } from 'mediabunny'; // File System API const handle = await window.showSaveFilePicker(); const writableStream = await handle.createWritable(); const output = new Output({ // `chunked: true` to batch disk operations target: new StreamTarget(writableStream, { chunked: true }), // ... }); // ... await output.finalize(); // The file has been fully written to disk ``` ## Stream over the network ```ts import { Output, AppendOnlyStreamTarget, Mp4OutputFormat, } from 'mediabunny'; const { writable, readable } = new TransformStream(); const output = new Output({ target: new AppendOnlyStreamTarget(writable), // We must use an append-only format here, such as fragmented MP4 format: new Mp4OutputFormat({ fastStart: 'fragmented' }), }); const uploadComplete = fetch('https://example.com/upload', { method: 'POST', body: readable, duplex: 'half', headers: { 'Content-Type': output.format.mimeType, }, }); await output.start(); // ... await output.finalize(); await uploadComplete; ``` ::: info * This code automatically handles the backpressure applied by a slow network. * Read more on [append-only formats](./output-formats#append-only-writing), a requirement for this pattern. ::: ## Record live media ```ts import { BufferTarget, MediaStreamAudioTrackSource, MediaStreamVideoTrackSource, Output, Quality, WebMOutputFormat, } from 'mediabunny'; const userMedia = await navigator.mediaDevices.getUserMedia({ video: true, audio: true, }); const videoTrack = userMedia.getVideoTracks()[0]; const audioTrack = userMedia.getAudioTracks()[0]; const output = new Output({ format: new WebMOutputFormat(), target: new BufferTarget(), }); if (videoTrack) { const source = new MediaStreamVideoTrackSource(videoTrack, { codec: 'vp9', quality: new Quality('medium'), }); output.addVideoTrack(source); } if (audioTrack) { const source = new MediaStreamAudioTrackSource(audioTrack, { codec: 'opus', quality: new Quality('medium'), }); output.addAudioTrack(source); } await output.start(); // Wait... await output.finalize(); ``` ::: info * Check out the Live recording demo for this code in action. * This is basically [`MediaRecorder`](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder), but less sucky. ::: ## Creating transparent video ```ts import { BufferTarget, CanvasSource, Output, Quality, WebMOutputFormat, } from 'mediabunny'; const output = new Output({ // Use a format that supports transparency: format: new WebMOutputFormat(), target: new BufferTarget(), }); const canvas = new OffscreenCanvas(1280, 720); const context = canvas.getContext('2d', { alpha: true })!; const source = new CanvasSource(canvas, { codec: 'vp9', quality: new Quality('medium'), alpha: 'keep', // => Also encode alpha data }); output.addVideoTrack(source); await output.start(); // Add data... await source.add(0, 1 / 30); // ... await output.finalize(); ``` ## Check encoding support ```ts import { MovOutputFormat, getFirstEncodableVideoCodec, getFirstEncodableAudioCodec, getEncodableVideoCodecs, getEncodableAudioCodecs, } from 'mediabunny'; const outputFormat = new MovOutputFormat(); // Find the best supported codec for the given container format const bestVideoCodec = await getFirstEncodableVideoCodec( outputFormat.getSupportedVideoCodecs(), // Optionally, constrained by these parameters: { width: 1920, height: 1080 }, ); const bestAudioCodec = await getFirstEncodableAudioCodec( outputFormat.getSupportedAudioCodecs(), ); // Find all supported codecs const supportedVideoCodecs = await getEncodableVideoCodecs(); const supportedAudioCodecs = await getEncodableAudioCodecs(); ``` ## Convert files ```ts import { Input, Output, Conversion, ALL_FORMATS, BlobSource, Mp4OutputFormat, } from 'mediabunny'; // Check the above snippets for more examples of Input and Output const input = new Input({ formats: ALL_FORMATS, source: new BlobSource(file), }); const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget(), }); const conversion = await Conversion.init({ input, output }); if (!conversion.isValid) { // The conversion isn't possible and would error upon execution. // Check `discardedTracks` for the reasons. return; } // List of tracks that won't make it into the output: conversion.discardedTracks; conversion.onProgress = (progress) => { progress; // Number between 0 and 1, inclusive }; await conversion.execute(); // Conversion is complete const buffer = output.target.buffer; // ArrayBuffer containing the final MP4 file ``` ::: info * This code will automatically transmux (copy media data) when possible, and transcode (re-encode media data) when necessary. * Refer to [Converting media files](./converting-media-files) for the full documentation. ::: ## Extract audio ```ts import { Input, Output, Conversion, WavOutputFormat, } from 'mediabunny'; const input = new Input(...); const output = new Output({ // Write to a .wav file, keeping only the audio track format: new WavOutputFormat(), // ... }); const conversion = await Conversion.init({ input, output, audio: { sampleRate: 16000, // Resample to 16 kHz }, }); await conversion.execute(); // Conversion is complete ``` ::: info * You can extract to other audio-only formats, such as .mp3, .ogg, or even .m4a. See [Output formats](./output-formats). ::: ## Compress media ```ts import { Conversion, Input, Output, Quality, } from 'mediabunny'; const input = new Input(...); const output = new Output(...); const conversion = await Conversion.init({ input, output, tracks: 'primary', // Keep only the first track of each type video: { width: 480, // Resize to 480p quality: new Quality('low'), }, audio: { numberOfChannels: 1, // Resample to mono quality: new Quality('low'), }, trim: { // Let's keep only the first 60 seconds start: 0, end: 60, }, tags: {}, // Remove any metadata tags }); await conversion.execute(); // Conversion is complete ``` ::: info * Check out the File compression example for this code in action. ::: ## Add a video overlay ```ts import { Input, Output, Conversion, } from 'mediabunny'; // For example, let's load a watermark image const watermark = new Image(); watermark.src = '/watermark.jpg'; await new Promise(resolve => watermark.onload = resolve); const input = new Input(...); const output = new Output(...); let ctx: CanvasRenderingContext2D | null = null; const conversion = await Conversion.init({ input, output, video: { process: (sample) => { if (!ctx) { // Create a canvas for image compositing const canvas = new OffscreenCanvas( sample.displayWidth, sample.displayHeight, ); ctx = canvas.getContext('2d')!; } ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); sample.draw(ctx, 0, 0); ctx.drawImage(watermark, 32, 32); return ctx.canvas; }, }, }); await conversion.execute(); // Conversion is complete ``` ## Combine multiple files into one ```ts import { Input, Output, Conversion, } from 'mediabunny'; // Let's take the video track from one file... const videoInput = new Input(...); // ...and the audio track from another const audioInput = new Input(...); const output = new Output(...); const videoConversion = await Conversion.init({ input: videoInput, output, composable: true, // Ensure the conversion doesn't own the output audio: { discard: true }, }); const audioConversion = await Conversion.init({ input: audioInput, output, composable: true, video: { discard: true }, }); await output.start(); await Promise.all([ videoConversion.execute(), audioConversion.execute(), ]); await output.finalize(); // Conversion is complete ``` ::: info See [Composable conversions](./converting-media-files#composable-conversions) for the full documentation. ::: ## Reading HLS playlists ```ts import { Input, UrlSource, HLS_FORMATS, desc } from 'mediabunny'; const input = new Input({ source: new UrlSource('https://example.com/master.m3u8'), formats: HLS_FORMATS, }); // Get all tracks const tracks = await input.getTracks(); // Get video tracks by quality const sortedVideoTracks = await input.getVideoTracks({ sortBy: async track => desc(await track.getDisplayHeight()), }); // Select a quality const bestVideoTrack = sortedVideoTracks[0]!; // Get a matching audio track const matchingAudioTrack = await bestVideoTrack.getPrimaryPairableAudioTrack(); // HLS tracks can be read like any other Mediabunny InputTrack // ... const isLive = await bestVideoTrack.isLive(); if (isLive) { // Poll some data using the refresh interval, for example duration let currentDuration: number | null = null; const poll = async () => { currentDuration = await bestVideoTrack.getDurationFromMetadata({ skipLiveWait: true, }); const refreshInterval = await bestVideoTrack.getLiveRefreshInterval(); if (refreshInterval === null) { return; // No longer live } setTimeout(poll, 1000 * refreshInterval); }; await poll(); } ``` ::: info See [Reading HLS](./reading-hls) for an in-depth guide. ::: --- --- url: /guide/reading-hls.md description: >- Use Mediabunny to read HLS (.m3u8) playlists, both VOD and live. Extract tracks, metadata, and media data efficiently and with precise control. --- # Reading HLS Mediabunny has full support for reading HLS (.m3u8) playlists, both VOD and live. This page will go into HLS-specific behavior and advice. For general information about how to read any media file (including HLS) in Mediabunny, refer to [Reading media files](./reading-media-files). ## Mental model Mediabunny exposes HLS playlists as if they were a single giant input file. Like with any other format, it does not ever expose the underlying structure (playlists, segments, decryption keys), but instead exposes an abstract, media data-centric view. Any code written to handle other Mediabunny inputs will automatically work on HLS inputs: they are also just a collection of tracks, and each track contains a linear sequence of media data. The multi-file, multi-playlist and multi-segment nature of HLS is abstracted away and completely hidden from the user. ## HLS inputs HLS playlists (master & media) are read through the same `Input` interface as all other media files in Mediabunny. HLS must read multiple files, meaning any [`PathedSource`](../api/PathedSource) (such as `UrlSource`) is required: ```ts import { Input, UrlSource, HLS_FORMATS } from 'mediabunny'; const input = new Input({ source: new UrlSource('https://example.com/master.m3u8'), formats: HLS_FORMATS, // HLS_FORMATS includes HLS as well as the commonly-used segment formats }); ``` You can supply any custom "path to data" resolution logic by using [`CustomPathedSource`](../api/CustomPathedSource). ## Reading tracks To retrieve all tracks: ```ts const tracks = await input.getTracks(); ``` Mediabunny flattens all tracks across all variants into a single flat array. If multiple variants reference the same underlying media playlist, the duplicated tracks will be deduplicated. Since Mediabunny lazy-loads all information, retrieving the list of all tracks is a cheap operation, as it only needs to fetch the master playlist. If you point Mediabunny directly at a media playlist, then the list of tracks is deduced by the tracks present in the first segment of the playlist. ### Track queries Mediabunny offers an [`InputTrackQuery`](../api/InputTrackQuery) system to aid with finding tracks in complex many-track inputs such as the ones common with HLS. Here's a holistic example that constructs an HLS quality ladder and then selects audio tracks based on language: ```ts import { desc, prefer } from 'mediabunny'; // Get video tracks sorted by their resolution (highest first) const videoTracks = await input.getVideoTracks({ sortBy: async track => [ desc(await track.getDisplayHeight()), // Tracks with matching resolution are sorted by bitrate desc(await track.getBitrate()), ], // Filter out #EXT-X-I-FRAME-STREAM-INF tracks filter: async track => !(await track.hasOnlyKeyPackets()), }); const availableQualities = videoTracks.length; // Get the best quality video track const video = videoTracks[0]; // Get the audio track that accompanies this video track const matchingAudioTrack = await video.getPrimaryPairableAudioTrack(); // Get all audio tracks const availableAudioTracks = await video.getPairableAudioTracks(); const availableLanguages = await Promise.all( availableAudioTracks.map(track => track.getLanguageCode()), ); // Get the Spanish audio track const matchingSpanishAudio = await video.getPrimaryPairableAudioTrack({ filter: async track => await track.getLanguageCode() === 'es', }); // Get the Spanish audio track if one exists, otherwise get // the next best thing const matchingAudioPreferSpanish = await video.getPrimaryPairableAudioTrack({ sortBy: async track => prefer(await track.getLanguageCode() === 'es'), }); ``` ### Reading track metadata For general reading of track metadata, see [Reading media files](./reading-media-files). Some notable metadata mappings for HLS are: ```ts // Returns the value of the BANDWIDTH attribute (peak bitrate). // If the track is used in multiple variants, this returns the // max of those bitrates. await track.getBitrate(); // Same as above, but AVERAGE-BANDWIDTH await track.getAverageBitrate(); // LANGUAGE attribute await track.getLanguageCode(); // NAME attribute await track.getName(); const disposition = await track.getDisposition(); disposition.primary; // => DEFAULT attribute (= primary in Mediabunny) disposition.default; // => AUTOSELECT attribute // Indicates an #EXT-X-I-FRAME-STREAM-INF track await track.hasOnlyKeyPackets(); ``` ## Track pairings In Mediabunny, two tracks are considered *pairable* if they can be presented together. HLS master playlists explicitly model pairability via variant streams and media renditions. Even though Mediabunny does not expose these structures and flattens out all tracks, the pairability graph implied by the master playlist is still available via: ```ts trackA.canBePairedWith(trackB); ``` Many other methods are available to query pairability and pairable tracks; see the [`InputTrack`](../api/InputTrack) API docs. ### Example Consider the following two master playlists: **Playlist #1:** ```m3u8 #EXTM3U #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=1280x720 video-and-audio-1.m3u8 #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=640x480 video-and-audio-2.m3u8 ``` **Playlist #2:** ```m3u8 #EXTM3U #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="audio",URI="audio-1.m3u8" #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="audio",URI="audio-2.m3u8" #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=1280x720,AUDIO="audio" video-1.m3u8 #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=640x480,AUDIO="audio" video-2.m3u8 ``` Both of these playlists define exactly four tracks: two video tracks, two audio tracks. *They differ only in their pairability:* * The first playlist has video-audio pairs. Video track #1 can only go with audio track #1, video track #2 can only go with audio track #2. * The second playlist is more open. Any video track can be paired with any audio track. That means, for playlist #1: ```ts const videoTrack = (await input.getVideoTracks())[0]; (await videoTrack.getPairableTracks()).length; // => 1 ``` For playlist #2: ```ts const videoTrack = (await input.getVideoTracks())[0]; (await videoTrack.getPairableTracks()).length; // => 2 ``` ## Lazy loading Track information is lazily loaded. This means this operation only loads the master playlist: ```ts const track = await input.getPrimaryVideoTrack(); ``` Then, operations that only require the media playlist will load only it: ```ts const duration = await track.getDurationFromMetadata(); ``` Finally, some operations require the first segment as well: ```ts const decoderConfig = await track.getDecoderConfig(); ``` Operations that access media data may load any segment necessary to fulfill that request, but not more: ```ts const sink = new EncodedPacketSink(videoTrack); // Get the packet somewhere in the middle of the stream at 300s const middlePacket = await sink.getPacket(300); ``` Some operations may load more or less data depending on the underlying file. For example, this code only requires the master playlist if the optional `RESOLUTION` attribute is present, but if it is not, Mediabunny has no choice but to dig into the underlying media data to determine the resolution: ```ts const width = await track.getDisplayWidth(); const height = await track.getDisplayHeight(); ``` *** Playlists are internally cached so they are never read more than once. Segments are only cached if they are still in use; unused segments are evicted to keep memory usage bounded. ## Unix-timestamped media Some HLS media playlists (especially the live ones) may look like this: ```m3u8 #EXTM3U #EXT-X-TARGETDURATION:10 #EXTINF:10, #EXT-X-PROGRAM-DATE-TIME:2024-01-01T00:00:00Z segment-1.ts #EXTINF:10, #EXT-X-PROGRAM-DATE-TIME:2024-01-01T00:00:10Z segment-2.ts #EXT-X-ENDLIST ``` Here, each segment is assigned a specific Unix timestamp, which clearly places media at a specific point in wall-clock time. Mediabunny does not expose these timestamps as out-of-band metadata. Instead, it shifts the whole track's timeline so that its timestamps *are* Unix timestamps. Specifically, this means for the above playlist: ```ts await track.getFirstTimestamp(); // => 1704067200 (Unix timestamp for 2024-01-01T00:00:00Z) await track.computeDuration(); // => 1704067220 (Unix timestamp for 2024-01-01T00:00:20Z) const sink = new EncodedPacketSink(track); (await sink.getPacket(1704067210))!.timestamp; // => 1704067210 (Unix timestamp for 2024-01-01T00:00:10Z) ``` To know if a track's timestamps are relative to the Unix epoch, use: ```ts await track.isRelativeToUnixEpoch(); // => boolean ``` ### Disabling Unix offsets If you don't want Mediabunny to offset packet timestamps to be in Unix time, you can set `offsetTimestampsByDateTime` to `false` in the input format options: ```ts const input = new Input({ // ... formatOptions: { hls: { offsetTimestampsByDateTime: false, }, }, }); ``` This way, track and packet timestamps behave as if no `#EXT-X-PROGRAM-DATE-TIME` tags existed. This also means that any date time gaps are completely collapsed. You will still be able to query the Unix time metadata via a mapping function on the `InputTrack`: ```ts const firstTimestamp = await inputTrack.getFirstTimestamp(); // => 0 await inputTrack.getUnixTimeForTimestamp(firstTimestamp); // => 1704067200 (Unix timestamp for 2024-01-01T00:00:00Z) ``` This function performs a piecewise-continuous mapping of timestamp space into Unix time space. If no wall-clock time information is available, `getUnixTimeForTimestamp()` will return `null`. You can check the presence of Unix time metadata via: ```ts await inputTrack.hasUnixTimeMapping(); // boolean ``` ## Live HLS HLS playlists may be live. You can check that a track is live via: ```ts await track.isLive(); // => boolean ``` Every live track also has a "refresh interval", which is the time in seconds after which new media data is probably available: ```ts await track.getLiveRefreshInterval(); // => number | null ``` ### Mental model Mediabunny has a very simple mental model for live tracks: they are treated like tracks where media data is continually being added to the end. That also means that the media data *at* the end is not yet known, because the end is not yet known. Another way to think of it is as input files that have not yet been fully written, where more data is still being added to the end. This works for streams of any length, including extremely long or non-stop live streams: timestamps stay continuous no matter how long the stream runs. The point at which the last piece of media data is currently known is called the **live edge**. ### Reading live media data This mental model implies that by default, Mediabunny will wait until any reading operation can be resolved, referred to as the "live wait". For example, this code only finishes when the live stream ends: ```ts const duration = await track.getDurationFromMetadata(); ``` This is because the duration can only be known when the live stream has ended. Similarly, this code will run as long as the live stream runs: ```ts const sink = new EncodedPacketSink(track); const iterator = sink.packets(); for await (const packet of iterator) { console.log(packet); } // Live stream has ended, all packets iterated! ``` *** Sometimes, this behavior is undesirable. Imagine we want to read the frame at the end of the *currently-known* data. Mediabunny allows you to treat live tracks as if all of the media data is already known. For this, the `skipLiveWait` flag is used: ```ts // Get the duration up until the current point in the live stream const currentDuration = await track.getDurationFromMetadata({ skipLiveWait: true }); // Loop over all currently known packets const sink = new EncodedPacketSink(track); const iterator = sink.packets(undefined, undefined, { skipLiveWait: true }); for await (const packet of iterator) { console.log(packet); } ``` You can combine `skipLiveWait` with the track's live refresh period to perform polling. For example, this code continually refreshes the currently known duration: ```ts let knownDuration: number | null = null; const poll = async () => { knownDuration = await track.getDurationFromMetadata({ skipLiveWait: true, }); const refreshInterval = await track.getLiveRefreshInterval(); if (refreshInterval === null) { return; // The track is no longer live } setTimeout(poll, 1000 * refreshInterval); }; await poll(); ``` ### Live playback Any media playback requires sampling the media data at a continually increasing timestamp. For live playback, the right timestamp must be found at which continual playback without interruptions can be guaranteed. A good rule of thumb is to use the following: ```ts const currentDuration = await track.getDurationFromMetadata({ skipLiveWait: true, }); const refreshInterval = await track.getLiveRefreshInterval(); const fac = 2; const playbackStartTime = currentDuration! - fac * refreshInterval!; ``` You can lower `fac` to move playback closer to the live edge (1.5 works fine too), although you should not lower it below 1. You can make `fac` larger to increase resilience against flaky internet or an unreliable media producer. ## Encrypted content Some HLS playlists carry encrypted media data. Mediabunny can read data that has been encoded with the following encryption schemes: * `'AES-128'` * `'SAMPLE-AES'` * `'SAMPLE-AES-CTR'` *** `'SAMPLE-AES'` and `'SAMPLE-AES-CTR'` are currently only supported for ISOBMFF media files. They are most commonly seen in DRM-encrypted content (Widevine, FairPlay, etc.) for which Mediabunny has no way of obtaining the decryption keys by itself, since commercial CDMs don't expose keys to userland (that's the whole point of DRM). Mediabunny is still able to decrypt the data if you provide it with the decryption keys directly using [`InputOptions.formatOptions.isobmff.resolveKeyId`](../api/IsobmffInputFormatOptions#resolvekeyid). An example: ```ts // Maps each key ID to a concrete decryption key const keyMap = new Map([ ['4d97930a3d7b55fa81d0028653f5e499', '429ec76475e7a952d224d8ef867f12b6'], ['d21373c0b8ab5ba9954742bcdfb5f48b', '150a6c7d7dee6a91b74dccfce5b31928'], ['6f1729072b4a5cd288c916e11846b89e', 'a84b4bd66901874556093454c075e2c6'], ['800aacaa522958ae888062b5695db6bf', '775dbf7289c4cc5847becd571f536ff2'], ['67b30c86756f57c5a0a38a23ac8c9178', 'efa2878c2ccf6dd47ab349fcf90e6259'], ]); using input = new Input({ source: new UrlSource( 'https://storage.googleapis.com/shaka-demo-assets/angel-one-widevine-hls/hls.m3u8', ), formats: ALL_FORMATS, formatOptions: { isobmff: { resolveKeyId: ({ keyId, psshBoxes }) => { // psshBoxes contains Protection System Specific Header boxes // relevant to this key ID. They can be used to obtain a // decryption key from a DRM license server. const key = keyMap.get(keyId); if (!key) { throw new Error('Unknown key ID.'); } return key; }, }, }, }); ``` ## Subtitles Reading subtitles from HLS playlists is not currently supported. Sorry! --- --- url: /guide/reading-media-files.md description: >- Efficiently extract metadata, video frames, and audio samples from any media file, such as MP4 or WebM. --- # Reading media files Mediabunny allows you to read media files with great control and efficiency. You can use it to extract metadata (such as duration or resolution), as well as to read actual media data from video and audio tracks with frame-accurate timing. Many commonly used [input file formats](./input-formats) are supported. Using [input sources](#input-sources), data can be read from multiple sources, such as directly from memory, from the user's disk, or even over the network. Files are always read partially ("lazily"), meaning only the bytes required to extract the requested information will be read, keeping performance high and memory usage low. Therefore, most methods for reading data are asynchronous and return promises. ::: info Not all data is extracted equally. Methods that are prefixed with `compute` instead of `get` indicate that the library might need to do more work to retrieve the requested data. ::: ## Creating a new input Reading media files in Mediabunny revolves around a central class, `Input`, from which all reading operations begin. One instance of `Input` represents one media file that we want to read. Start by creating a new instance of `Input`. Here, we're creating it with a [File](https://developer.mozilla.org/en-US/docs/Web/API/File) instance, meaning we'll be reading data directly from the user's disk: ```ts import { Input, ALL_FORMATS, BlobSource } from 'mediabunny'; const input = new Input({ formats: ALL_FORMATS, source: new BlobSource(file), }); ``` `source` specifies where the `Input` reads data from. See [Input sources](#input-sources) for a full list of available input sources. `formats` specifies the list of formats that the `Input` should support. This field is mainly used for tree shaking optimizations: Using `ALL_FORMATS` means we can load files of [any format that Mediabunny supports](./supported-formats-and-codecs#container-formats), but requires that we include the parsers for each of these formats. If we know we'll only be reading MP3 or WAVE files, then something like this will reduce the overall bundle size drastically: ```ts import { Input, MP3, WAVE } from 'mediabunny'; const input = new Input({ formats: [MP3, WAVE], // .... }); ``` Reading operations will throw an error if the file format could not be recognized. See [Input formats](./input-formats) for the full list of available input formats. ::: info Simply creating an instance of `Input` will perform zero reads and is practically free. The file will only be read once data is requested. ::: ## Reading file metadata With our instance of `Input` created, you can now start reading file-level metadata. You can check if Mediabunny can read the file: ```ts await input.canRead(); ``` You can query the concrete format of the file like this: ```ts await input.getFormat(); // => Mp4InputFormat ``` You can directly retrieve the full MIME type of the file, including track codecs: ```ts await input.getMimeType(); // => 'video/mp4; codecs="avc1.42c032, mp4a.40.2"' ``` Use `computeDuration` to get the full duration of the media file in seconds: ```ts await input.computeDuration(); // => 1905.4615 ``` More specifically, the duration is defined as the maximum end timestamp across all tracks. If you only need an approximate duration and want to avoid expensive scanning operations, you can read it directly from file metadata (where available): ```ts await input.getDurationFromMetadata(); // => number | null ``` This resolves to `null` if the file doesn't expose its duration as metadata. Both `computeDuration` and `getDurationFromMetadata` will not resolve if the underlying media is live (because the duration is not yet known!). To get the duration *up to the known point* (the live edge), do this: ```ts await input.computeDuration(undefined, { skipLiveWait: true }); await input.getDurationFromMetadata(undefined, { skipLiveWait: true }); ``` Since not all media files begin at time zero, you can also retrieve the *starting timestamp* of the media file in seconds: ```ts await input.getFirstTimestamp(); // => 0.0 ``` Mediabunny also lets you read descriptive metadata tags from media files, such as title, artist, or cover art: ```ts await input.getMetadataTags(); // => MetadataTags ``` For more info, see [`MetadataTags`](../api/MetadataTags). ## Reading track metadata ### Extracting tracks You can extract the list of all media tracks in the file like so: ```ts await input.getTracks(); // => InputTrack[] ``` There are additional utility methods for retrieving tracks that can be useful: ```ts await input.getVideoTracks(); // => InputVideoTrack[] await input.getAudioTracks(); // => InputAudioTrack[] await input.getPrimaryVideoTrack(); // => InputVideoTrack | null await input.getPrimaryAudioTrack(); // => InputAudioTrack | null ``` ::: info Subtitle tracks are currently not supported for reading. ::: These methods accept an optional [`InputTrackQuery`](../api/InputTrackQuery) parameter for filtering and sorting tracks. This query system is especially useful for inputs with many tracks such as HLS playlists. The helpers `asc`, `desc`, and `prefer` make it easy to express sorting logic. ```ts import { desc, prefer } from 'mediabunny'; // Get the highest-resolution video track: await input.getPrimaryVideoTrack({ sortBy: async track => [ desc(await track.getDisplayWidth()), desc(await track.getBitrate()), // If resolution matches, prefer the highest bitrate ], }); // Get only English audio tracks: await input.getAudioTracks({ filter: async track => await track.getLanguageCode() === 'eng', }); // Get an English track but only if one exists: await input.getAudioTracks({ sortBy: async track => prefer(await track.getLanguageCode() === 'eng'), }); ``` ### Common track metadata Once you have an `InputTrack`, you can start extracting metadata from it. ```ts // Get a unique ID for this track in the input file: track.id; // => number // Get the 1-based index of this track among all tracks of the same type // (e.g., first video track is 1, second video track is 2, etc.): track.number; // => number // Check the track's type: track.type; // => 'video' | 'audio' | 'subtitle'; // Alternatively, use these type predicate methods: track.isVideoTrack(); // => boolean track.isAudioTrack(); // => boolean // Retrieve the track's language as an ISO 639-2/T language code. // Resolves to 'und' (undetermined) if the language isn't known. await track.getLanguageCode(); // => string // A user-defined name for this track. await track.getName(); // => string | null // Information about the intended usage of the track // (default, commentary, hearing-impaired, visually-impaired, etc.) await track.getDisposition(); // TrackDisposition // The track's peak bitrate, if exposed by the file metadata: await track.getBitrate(); // => number | null // The track's average bitrate, if exposed by the file metadata: await track.getAverageBitrate(); // => number | null // Whether all packets in the track are key packets: await track.hasOnlyKeyPackets(); // => boolean // Whether the track is currently live (meaning new media data is still being added): await track.isLive(); // => boolean // If the track is live, returns the interval in seconds at which new data is expected: await track.getLiveRefreshInterval(); // => number | null ``` #### Codec information You can query metadata related to the track's codec: ```ts await track.getCodec(); // => MediaCodec | null ``` This field is `null` when the track's codec couldn't be recognized or is not supported by Mediabunny. See [Codecs](./supported-formats-and-codecs#codecs) for the full list of supported codecs. When Mediabunny doesn't recognize the format, you can still use the `internalCodecId` field to figure out the codec of the track, although its format depends on the container format used and is not homogenized by Mediabunny. You can also extract the full codec parameter string from the track, as specified in the [Mediabunny Codec Registry](/codec-registry/overview): ```ts await track.getCodecParameterString(); // => 'avc1.42001f' ``` Just because the codec is known doesn't mean the user's browser will be able to decode it. To check decodability, use `canDecode`: ```ts await track.canDecode(); // => boolean ``` ::: info This check also takes [custom decoders](./supported-formats-and-codecs#custom-decoders) into account. ::: #### Track timing info You can compute the track's specific duration in seconds like so: ```ts await track.computeDuration(); // => 1902.4615 ``` Analogous to the `Input`'s duration, this is identical to the end timestamp of the last sample. A track's duration may be shorter than the `Input`'s total duration if the `Input` has multiple tracks which differ in length. You can also retrieve the approximate duration based on metadata in the file: ```ts await track.getDurationFromMetadata(); // => number | null ``` You can also retrieve the track's *start timestamp* in seconds: ```ts await track.getFirstTimestamp(); // => 0.041666666666666664 ``` This is the opposite of *duration*: It's the start timestamp of the first sample. ::: warning A track's start timestamp does **NOT** need to be 0. It is typically close to zero, but it may be slightly positive, or even slightly negative. A *positive start timestamp* means the first sample is presented *after* the overall composition begins. If this is a video track, you may choose to either display a placeholder image (like a black screen), or to display the first frame as a freeze frame until the second frame starts. A *negative start timestamp* means the track begins *before* the composition does; this effectively means that some beginning section of the media data is "cut off". It is recommended not to display samples with negative timestamps. ::: Another metric related to track timing info is its *time resolution*, which is given in hertz: ```ts await track.getTimeResolution(); // => 24 ``` Intuitively, this is the maximum possible "frame rate" of the track (assuming that no two samples have the same timestamp). Mathematically, if $x$ is equal to a track's time resolution, then all timestamps and durations of that track can be expressed as: $$ \frac{k}{x},\quad k \in \mathbb{Z} $$ ::: info This field only gives an upper bound on a track's frame rate. To determine a video track's actual frame rate based on its frames, compute its [frame rate metrics](#frame-rate-metrics). ::: Some tracks (especially live tracks) have timestamps which are relative to the Unix epoch (Jan 1 1970, midnight UTC). In other words, their timestamps *are* Unix timestamps. This allows you to map the media data to a definitive point in wall-clock time. To see if this is the case, use: ```ts await track.isRelativeToUnixEpoch(); // => boolean ``` #### Packet statistics You can query aggregate statistics about a track's encoded packets: ```ts await track.computePacketStats(); // => PacketStats type PacketStats = { // The total number of packets. packetCount: number; // The average number of packets per second. // For video tracks, this will equal the average frame rate (FPS). averagePacketRate: number; // The average number of bits per second. averageBitrate: number; }; ``` For example, running this on the video track of a 1080p version of Big Buck Bunny returns this: ```ts { packetCount: 14315, averagePacketRate: 24, averageBitrate: 9282573.233670976, } ``` This means the video track has a total of 14315 frames, a frame rate of exactly 24 Hz, and an average bitrate of ~9.28 Mbps. **Note:** These statistics aren't simply read from file metadata but have to be computed, meaning this method may - depending on the file - need to perform many reads and might take several hundred milliseconds to resolve. To speed up computation, you can compute aggregate statistics for only a subset of packets by passing a parameter to the method: ```ts await track.computePacketStats(50); ``` This will only look at the first ~50 packets and then return the result. This is great for quickly getting an estimate of bitrate, without having to scan through the entire file. To determine a video track's frame rate, prefer using [frame rate metrics](#frame-rate-metrics) instead. ### Video track metadata In addition to the [common track metadata](#common-track-metadata), video tracks have additional metadata you can query: ```ts // Get the raw pixel dimensions of the track's coded samples: await videoTrack.getCodedWidth(); // => number await videoTrack.getCodedHeight(); // => number // Get the pixel dimensions of the track after aspect ratio adjustments, // but before rotation: await videoTrack.getSquarePixelWidth(); // => number await videoTrack.getSquarePixelHeight(); // => number // Get the displayed pixel dimensions of the track's samples, after // aspect ratio adjustments and rotation: await videoTrack.getDisplayWidth(); // => number await videoTrack.getDisplayHeight(); // => number // Get the clockwise rotation in degrees by which the // track's frames should be rotated: await videoTrack.getRotation(); // => 0 | 90 | 180 | 270 // Get whether the track's frames should be flipped horizontally // (after rotation): await videoTrack.getFlip(); // => boolean // Get the full transformation matrix that rotation and flip are // derived from: await videoTrack.getTransformationMatrix(); // => TransformationMatrix // Get the aspect ratio of the track's pixels (usually 1:1): await videoTrack.getPixelAspectRatio(); // => { num: number, den: number } ``` To determine a video track's frame rate (FPS), compute its [frame rate metrics](#frame-rate-metrics). You can retrieve the track's decoder configuration, which is a `VideoDecoderConfig` from the WebCodecs API for usage within `VideoDecoder`: ```ts await videoTrack.getDecoderConfig(); // => VideoDecoderConfig | null ``` This method can resolve to `null` if the track's codec isn't known. For example, here's the decoder configuration for a 1080p version of Big Buck Bunny: ```ts { codec: 'avc1.4d4029', codedWidth: 1920, codedHeight: 1080, description: new Uint8Array([ // Bytes of the AVCDecoderConfigurationRecord 1, 77, 64, 41, 255, 225, 0, 22, 39, 77, 64, 41, 169, 24, 15, 0, 68, 252, 184, 3, 80, 16, 16, 27, 108, 43, 94, 247, 192, 64, 1, 0, 4, 40, 222, 9, 200, ]), } ``` You can directly retrieve information about the video's color space: ```ts await videoTrack.getColorSpace(); // => VideoColorSpaceInit ``` The resulting object will contain `undefined` values if color space information is not known. You can also directly check if a video has a *high dynamic range* (HDR): ```ts await videoTrack.hasHighDynamicRange(); // => boolean ``` This method compares with the available color space metadata. If it resolves to `true`, then the video is HDR; if it resolves to `false`, the video may or may not be HDR. #### Frame rate metrics You can compute metrics about a video track's frame rate (FPS): ```ts const metrics = await videoTrack.computeFrameRateMetrics(); // => FrameRateMetrics metrics.bestGuessFrameRate; // => number ``` Frame rate is never determined from file metadata (which is unreliable) but is always deduced directly from the actual frame timestamps. See [`FrameRateMetrics`](../api/FrameRateMetrics) for more. By default, this method probes the first 256 packets of the track, which is enough for a reliable estimate. You can control this number using the `targetPacketCount` option, but note that increasing it makes the call more expensive: ```ts await videoTrack.computeFrameRateMetrics({ targetPacketCount: 1024 }); ``` ### Audio track metadata In addition to the [common track metadata](#common-track-metadata), audio tracks have additional metadata you can query: ```ts // Get the number of audio channels: await audioTrack.getNumberOfChannels(); // => number // Get the audio sample rate in hertz: await audioTrack.getSampleRate(); // => number ``` You can retrieve the track's decoder configuration, which is an `AudioDecoderConfig` from the WebCodecs API for usage within `AudioDecoder`: ```ts await audioTrack.getDecoderConfig(); // => AudioDecoderConfig | null ``` This method can resolve to `null` if the track's codec isn't known. For example, here's the decoder configuration for an AAC audio track: ```ts { codec: 'mp4a.40.2', numberOfChannels: 2, sampleRate: 44100, description: new Uint8Array([ // Bytes of the AudioSpecificConfig 17, 144, ]), } ``` ### Track pairability Mediabunny has a concept of "track pairability". Two different tracks are considered *pairable* if they are compatible with each other, meaning they can be presented together. For example, in a normal file, the video track can be paired with the audio track. If it has multiple audio tracks, the video track can be paired with each one of them, but the audio tracks cannot be paired with each other; they're not intended to be played at the same time. This concept is needed to model the more complex track configurations found in many-track formats such as HLS. Here, an audio track may be pairable with all video tracks or just one; it depends on the master playlist. These inter-track relations are exactly what track pairability describes. To see if two tracks are pairable, do: ```ts const canPair = trackA.canBePairedWith(trackB); ``` Each track also provides utilities that let you find its pairable tracks easily: ```ts // These return an array of tracks await track.getPairableTracks(); await track.getPairableVideoTracks(); await track.getPairableAudioTracks(); // These return one track or null await track.getPrimaryPairableVideoTrack(); await track.getPrimaryPairableAudioTrack(); // These resolve to booleans: await track.hasPairableTrack(); await track.hasPairableVideoTrack(); await track.hasPairableAudioTrack(); ``` ## Reading media data Mediabunny has the concept of *media sinks*, which are the way to read media data from an `InputTrack`. Media sinks differ in their API and in their level of abstraction, meaning you can pick whichever sink best fits your use case. See [Media sinks](./media-sinks) for a full list of sinks. ### Examples Loop over all raw encoded packets of a track: ```ts import { EncodedPacketSink } from 'mediabunny'; const videoTrack = await input.getPrimaryVideoTrack(); const sink = new EncodedPacketSink(videoTrack); for await (const packet of sink.packets()) { console.log(packet.timestamp); } ``` Here we iterate over all samples (frames) of a video track: ```ts import { VideoSampleSink } from 'mediabunny'; const videoTrack = await input.getPrimaryVideoTrack(); const sink = new VideoSampleSink(videoTrack); for await (const sample of sink.samples()) { // For example, let's draw the sample to a canvas: sample.draw(ctx, 0, 0); } ``` We can also use this sink in more concrete ways: ```ts // Loop over all frames between the timestamps of 300s and 305s for await (const sample of sink.samples(300, 305)) { // ... } // Get the frame that's displayed at timestamp 42s await sink.getSample(42); ``` We may want to extract downscaled thumbnails from a video track: ```ts import { CanvasSink } from 'mediabunny'; const videoTrack = await input.getPrimaryVideoTrack(); const sink = new CanvasSink(videoTrack, { width: 320, height: 180, }); const startTimestamp = await videoTrack.getFirstTimestamp(); const endTimestamp = await videoTrack.computeDuration(); // Let's generate five equally-spaced thumbnails: const thumbnailTimestamps = [0, 0.2, 0.4, 0.6, 0.8].map( (t) => startTimestamp + t * (endTimestamp - startTimestamp), ); for await (const result of sink.canvasesAtTimestamps(thumbnailTimestamps)) { // Add MrBeast's face to the thumbnail } ``` We may loop over a section of an audio track and play it using the Web Audio API: ```ts import { AudioBufferSink } from 'mediabunny'; const audioTrack = await input.getPrimaryAudioTrack(); const sink = new AudioBufferSink(audioTrack); for await (const { buffer, timestamp } of sink.buffers(5, 10)) { const node = audioContext.createBufferSource(); node.buffer = buffer; node.connect(audioContext.destination); node.start(timestamp); } ``` Or we may take the decoding process into our own hands: ```ts import { EncodedPacketSink } from 'mediabunny'; const videoTrack = await input.getPrimaryVideoTrack(); const sink = new EncodedPacketSink(videoTrack); const decoder = new VideoDecoder({ output: console.log, error: console.error, }); decoder.configure(await videoTrack.getDecoderConfig()); // Let's crank through all packets from timestamp 37s to 50s: let currentPacket = await sink.getKeyPacket(37); while (currentPacket && currentPacket.timestamp < 50) { decoder.decode(currentPacket.toEncodedVideoChunk()); currentPacket = await sink.getNextPacket(currentPacket); } await decoder.flush(); ``` As you can see, media sinks are incredibly versatile and allow for efficient, sparse reading of media data within the input file. ## Disposing inputs When you're not using them anymore, `Input` instances will automatically get cleaned up by garbage collection. However, sometimes you may want to prematurely dispose of an `Input` and all its connected resources, or cancel any ongoing operation. You can do it like so: ```ts input.dispose(); ``` When an `Input` is disposed, ongoing read operations will be canceled, all future read operations will fail, any open decoders will be closed, and all ongoing media sink operations will be canceled. Disallowed and canceled operations will throw an `InputDisposedError`. You are expected not to use an `Input` after disposing it. While some operations may still work, it is not specified and may change in any future update. `Input` also implements `Disposable`, meaning you can use it with JavaScript Explicit Resource Management features such as the [`using` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using): ```ts { using input = new Input(...); // `input` will automatically be disposed } ``` Using `using` is recommended over `const` if you only need the `Input` momentarily within a single scope. ## Input sources The *input source* determines where the `Input` reads data from. All sources have a `read` event you can use to inspect which areas of the file are being read: ```ts source.on('read', ({ start, end }) => { console.log(`Reading byte range [${start}, ${end})`); }); ``` You can derive a `RangedSource` representing only a sub-section of an existing source via `slice`: ```ts // A source over only the first 1024 bytes: const sliced = source.slice(0, 1024); // A source that starts 8192 bytes into the original source: const sliced2 = source.slice(8192); ``` *** This library offers a couple of sources: ### `BufferSource` This source uses an in-memory `ArrayBuffer` as the underlying source of data. ```ts import { BufferSource } from 'mediabunny'; // You can construct a BufferSource directly from ArrayBuffer: const source = new BufferSource(arrayBuffer); // Or also from a Uint8Array: const source = new BufferSource(uint8Array); ``` This source is the fastest but requires the entire input file to be held in memory. ### `BlobSource` This source is backed by an underlying [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object. Since [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) extends `Blob`, this source is perfect for reading data directly from disk (in the browser). ```ts import { BlobSource } from 'mediabunny'; fileInput.addEventListener('change', (event) => { const file = event.target.files[0]; const source = new BlobSource(file); }); ``` `BlobSource` accepts additional options as a second parameter: ```ts type BlobSourceOptions = { // The maximum number of bytes the cache is allowed to hold // in memory. Defaults to 8 MiB. maxCacheSize?: number; // Handles errors that occur while no read is pending handleUnhandledError?: (error: unknown) => unknown; }; ``` ### `UrlSource` This source fetches data from a remote URL, useful for reading files over the network. ```ts import { UrlSource } from 'mediabunny'; const source = new UrlSource('https://example.com/bigbuckbunny.mp4'); ``` `UrlSource` will do some pretty crazy stuff to prefetch data intelligently based on observed access patterns to minimize request count and latency. ::: warning If you're using this source in the browser and the URL is on a different origin, make sure [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) is properly configured. ::: `UrlSource` accepts a few options as its second parameter: ```ts type UrlSourceOptions = { requestInit?: RequestInit; getRetryDelay?: (previousAttempts: number, error: unknown, url: string | URL | Request) => number | null; // The maximum number of bytes the cache is allowed to hold // in memory. Defaults to 8 MiB. maxCacheSize?: number; // The maximum number of parallel requests to use for fetching. Defaults to 2. parallelism?: number; // Used to provide a custom fetch function fetchFn?: typeof fetch; // Handles errors that occur while no read is pending handleUnhandledError?: (error: unknown) => unknown; }; ``` You can use `requestInit` just like you would in the Fetch API to further customize the request: ```ts const source = new UrlSource('https://example.com/bigbuckbunny.mp4', { requestInit: { headers: { 'X-Custom-Header': 'my-value', }, }, }); ``` ::: info All `requestInit` fields are respected except for `signal`, which is overridden by Mediabunny. The same applies to the `signal` value of a `Request` passed as the first constructor argument. To cancel ongoing requests, [dispose of the input](#disposing-inputs). ::: `getRetryDelay` can be used to control the retry logic used should a request fail. When a request fails, `getRetryDelay` should return the time to wait in seconds before the request will be retried. Returning `null` prevents further retries. ```ts // UrlSource using retry logic with exponential backoff: const source = new UrlSource('https://example.com/bigbuckbunny.mp4', { getRetryDelay: (previousAttempts) => Math.min(2 ** previousAttempts, 16), }); ``` Not setting `getRetryDelay` will lead to the default being used: * Infinite exponential backoff pattern, capped at 16 seconds. * If a CORS error is suspected (`fetch()` did reject even though `navigator.onLine` is true and origin is different), no further retries will be made. *** Use `fetchFn` to provide a custom fetch function, usually for polyfill reasons. For example, React Native's `fetch` does not support streamable response bodies, a feature that `UrlSource` requires. In this case, you could use [Expo's `fetch` function](https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api) instead: ```ts import { UrlSource } from 'mediabunny'; import { fetch } from 'expo/fetch'; const source = new UrlSource('https://example.com/bigbuckbunny.mp4', { fetchFn: (input, init) => { if (typeof input !== 'string') { // Expo requires string URLs throw new Error('Expected a string URL.'); } return fetch(input, init); }, }); ``` ### `FilePathSource` This input source can be used to load data directly from a file, given a file path. It requires a server-side environment such as Node, Bun, or Deno. ```ts import { FilePathSource } from 'mediabunny'; const source = new FilePathSource('/home/david/Downloads/bigbuckbunny.mp4'); ``` `FilePathSource` accepts additional options as a second parameter: ```ts type FilePathSourceOptions = { // The maximum number of bytes the cache is allowed to hold // in memory. Defaults to 8 MiB. maxCacheSize?: number; // Handles errors that occur while no read is pending handleUnhandledError?: (error: unknown) => unknown; }; ``` ::: warning When using this source, make sure to manually [dispose of the Input](#disposing-inputs) when you are done with it to properly close the internal file handle held by this source. ::: ### `CustomSource` This is a general-purpose input source you can use to read data from anywhere. For example, here we're reading a file from disk using the Node.js file system (although you should use the existing [`FilePathSource`](#filepathsource) for that): ```ts import { CustomSource } from 'mediabunny'; import { open } from 'node:fs/promises'; const fileHandle = await open('bigbuckbunny.mp4', 'r'); const source = new CustomSource({ read: async (start, end) => { const buffer = Buffer.alloc(end - start); await fileHandle.read(buffer, 0, end - start, start); return buffer; }, getSize: async () => { const { size } = await fileHandle.stat(); return size; }, }); ``` The options of `CustomSource` have the following type: ```ts type CustomSourceOptions = { getSize: () => MaybePromise; read: (start: number, end: number) => MaybePromise>; dispose?: () => unknown; maxCacheSize?: number; prefetchProfile?: 'none' | 'fileSystem' | 'network'; handleUnhandledError?: (error: unknown) => unknown; }; type MaybePromise = T | Promise; ``` * `getSize`\ Called when the size of the entire file is requested. Must return or resolve to the size in bytes. This function is guaranteed to be called before `read`. * `read`\ Called when data is requested. Must return or resolve to the bytes from the specified byte range, or a stream that yields these bytes. You are guaranteed that `0 <= start < end < fileSize`. * `dispose`\ Called when the `Input` driven by this source is disposed. * `maxCacheSize`\ The maximum number of bytes the cache is allowed to hold in memory. Defaults to 8 MiB. * `prefetchProfile`\ Specifies the prefetch profile that the reader should use with this source. A prefetch propfile specifies the pattern with which bytes outside of the requested range are preloaded to reduce latency for future reads. * `'none'` (default): No prefetching; only the data needed in the moment is requested. * `'fileSystem'`: File system-optimized prefetching: a small amount of data is prefetched bidirectionally, aligned with page boundaries. * `'network'`: Network-optimized prefetching, or more generally, prefetching optimized for any high-latency environment: tries to minimize the amount of read calls and aggressively prefetches data when sequential access patterns are detected. * `handleUnhandledError`\ Handles errors that occur while no read is pending. By default, these become unhandled promise rejections. ::: info `CustomSource` was previously known as `StreamSource` and is still available under that alias, but usage of `StreamSource` is deprecated. ::: ### `ReadableStreamSource` This is a source backed by a `ReadableStream` of `Uint8Array`, representing an append-only byte stream of unknown length. This is the source to use for incrementally streaming in input files that are still being constructed and whose size we don't yet know. You could also use it to stream in existing files, but other sources (such as [`BlobSource`](#blobsource) or [`FilePathSource`](#filepathsource)) are recommended instead because they offer random access. ```ts import { ReadableStreamSource } from 'mediabunny'; const { writable, readable } = new TransformStream(); const source = new ReadableStreamSource(readable); // Append chunks of data const writer = writable.getWriter(); writer.write(chunk1); writer.write(chunk2); writer.close(); ``` This source is *unsized*, meaning calls to `.getSize()` will throw and readers are more limited due to the lack of random file access. You should only use this source with sequential access patterns, such as reading all packets from start to end or doing conversions. This source does not work well with random access patterns unless you increase its max cache size. ```ts type ReadableStreamSourceOptions = { // The maximum number of bytes the cache is allowed to hold // in memory. Defaults to 16 MiB. maxCacheSize?: number; // Handles errors that occur while no read is pending handleUnhandledError?: (error: unknown) => unknown; }; ``` #### Use with [`MediaRecorder`](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder) You can combine `MediaRecorder` with `ReadableStreamSource` to stream recorded data into Mediabunny while the recording is taking place. Here's an example where we pipe `MediaRecorder`'s output into Mediabunny's Conversion API to create a WAVE file: ```ts import { Input, Output, Conversion, ReadableStreamSource, ALL_FORMATS, WavOutputFormat, BufferTarget, } from 'mediabunny'; // Set up a TransformStream to convert MediaRecorder's Blobs into Uint8Arrays const { writable, readable } = new TransformStream({ async transform(chunk, controller) { const arrayBuffer = await chunk.arrayBuffer(); controller.enqueue(new Uint8Array(arrayBuffer)); }, }); const input = new Input({ source: new ReadableStreamSource(readable), formats: ALL_FORMATS, }); const output = new Output({ format: new WavOutputFormat(), target: new BufferTarget(), }); const conversionPromise = Conversion.init({ input, output }) .then(conversion => conversion.execute()); const micStream = await navigator.mediaDevices.getUserMedia({ audio: true }); const recorder = new MediaRecorder(micStream); const writer = writable.getWriter(); recorder.ondataavailable = e => writer.write(e.data); recorder.onstop = async () => { await writer.close(); await conversionPromise; // Get the final .wav file const wavFile = output.target.buffer!; // => ArrayBuffer }; recorder.start(1000); setTimeout(() => recorder.stop(), 10_000); // Stop recording after 10s ``` ### `PathedSource` Some media formats reference more than one file. For example, an HLS stream consists of a master playlist that points to one or more media playlists, each of which in turn references many media segment files. To read this kind of multi-file media, Mediabunny needs a way to resolve a source for each file path. This can be done with `PathedSource`. A `PathedSource` wraps a *root path* (the entry file of the media) together with a callback that produces a `Source` for each requested file path. It is an abstract class, so you can't use it directly, but it provides the necessary interface to read multi-file media. It is implemented by: * [`UrlSource`](#urlsource) * [`FilePathSource`](#filepathsource) * [`CustomPathedSource`](#custompathedsource) ### `CustomPathedSource` Allows you to implement a user-defined [`PathedSource`](#pathedsource) to provide an arbitrary "file path to data" mapping function. Useful when your data is stored in a custom structure, for example OPFS: ```ts import { Input, CustomPathedSource, BlobSource } from 'mediabunny'; const root = await navigator.storage.getDirectory(); const input = new Input({ source: new CustomPathedSource( 'master.m3u8', async ({ path }) => { const handle = await root.getFileHandle(path); const file = await handle.getFile(); return new BlobSource(file); }, ), // ... }); ``` The callback is called once per requested file (lazily, only when needed) and receives a `SourceRequest`: ```ts type SourceRequest = { path: FilePath; // The requested file path isRoot: boolean; // Whether the requested file is the root file }; ``` ## Init inputs Some file formats contain track initialization info in a *separate* file; CMAF is one example. To supply these to Mediabunny, load the initialization file as a separate `Input` and then pass it as an `initInput`: ```ts const initInput = new Input({ source: new FilePathSource('init.mp4'), formats: ALL_FORMATS, }); const input = new Input({ source: new FilePathSource('data.mp4'), formats: ALL_FORMATS, initInput, }); ``` --- --- url: /guide/supported-formats-and-codecs.md description: >- Mediabunny supports a wide range of media container formats (.mp4, .webm, .mp3, .wav, .m3u8, ...) and video/audio codecs (H.264, HEVC, VP9, AV1, AAC, Opus, FLAC, ...). --- # Supported formats & codecs ## Container formats Mediabunny supports many commonly used media container formats, all of which are supported bidirectionally (reading & writing): * ISOBMFF-based formats (.mp4, .m4v, .m4a, ...) * QuickTime File Format (.mov) * Segmented MP4 (CMAF) (.m4s) * Matroska (.mkv) * WebM (.webm) * Ogg (.ogg) * MP3 (.mp3) * WAVE (.wav) * ADTS (.aac) * FLAC (.flac) * MPEG Transport Stream (.ts) * HLS (.m3u8) ## Codecs Mediabunny supports a wide range of video, audio, and subtitle codecs. More specifically, it supports all codecs specified by the WebCodecs API and a few additional PCM codecs out of the box. The availability of the codecs provided by the WebCodecs API depends on the browser and thus cannot be guaranteed by this library. Mediabunny provides [special utility functions](#querying-codec-encodability) to check which codecs are able to be encoded. You can also specify [custom coders](#custom-coders) to provide your own encoder/decoder implementation if the browser doesn't support the codec natively. For precise definitions of each codec including the corresponding packet format, please refer to the [Mediabunny Codec Registry](/codec-registry/overview). ::: info Mediabunny ships with built-in decoders and encoders for all audio PCM codecs, meaning they are always supported. ::: ### Video codecs * `'avc'` - Advanced Video Coding (AVC) / H.264 * `'hevc'` - High Efficiency Video Coding (HEVC) / H.265 * `'vp8'` - VP8 * `'vp9'` - VP9 * `'av1'` - AOMedia Video 1 (AV1) * `'prores'` - Apple ProRes \[^prores] ### Audio codecs * `'aac'` - Advanced Audio Coding (AAC) \[^aac] * `'opus'` - Opus * `'mp3'` - MP3 \[^mp3] * `'vorbis'` - Vorbis * `'flac'` - Free Lossless Audio Codec (FLAC) \[^flac] * `'ac3'` - Dolby Digital (AC-3) \[^ac3] * `'eac3'` - Dolby Digital Plus (E-AC-3) \[^ac3] * `'dts'` - DTS Coherent Acoustics \[^dts] * `'truehd'` - Dolby TrueHD \[^truehd] * `'pcm-u8'` - 8-bit unsigned PCM * `'pcm-s8'` - 8-bit signed PCM * `'pcm-s16'` - 16-bit little-endian signed PCM * `'pcm-s16be'` - 16-bit big-endian signed PCM * `'pcm-s24'` - 24-bit little-endian signed PCM * `'pcm-s24be'` - 24-bit big-endian signed PCM * `'pcm-s32'` - 32-bit little-endian signed PCM * `'pcm-s32be'` - 32-bit big-endian signed PCM * `'pcm-f32'` - 32-bit little-endian float PCM * `'pcm-f32be'` - 32-bit big-endian float PCM * `'pcm-f64'` - 64-bit little-endian float PCM * `'pcm-f64be'` - 64-bit big-endian float PCM * `'ulaw'` - μ-law PCM * `'alaw'` - A-law PCM ### Subtitle codecs * `'webvtt'` - WebVTT ## Compatibility table Not all codecs can be used with all containers. The following table specifies the supported codec-container combinations: | | .mp4 | .mov | .mkv | .webm\[^webm] | .ogg | .mp3 | .wav | .aac | .flac | .ts | |:--------------:|:--------:|:-----:|:-----:|:---------:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:| | `'avc'` | ✓ | ✓ | ✓ | | | | | | | ✓ | | `'hevc'` | ✓ | ✓ | ✓ | | | | | | | ✓ | | `'vp8'` | ✓ | ✓ | ✓ | ✓ | | | | | | | | `'vp9'` | ✓ | ✓ | ✓ | ✓ | | | | | | | | `'av1'` | ✓ | ✓ | ✓ | ✓ | | | | | | | | `'prores'` | ✓ | ✓ | ✓ | | | | | | | | | `'aac'` | ✓ | ✓ | ✓ | | | | | ✓ | | ✓ | | `'opus'` | ✓ | ✓ | ✓ | ✓ | ✓ | | | | | | | `'mp3'` | ✓ | ✓ | ✓ | | | ✓ | | | | ✓ | | `'vorbis'` | ✓ | ✓ | ✓ | ✓ | ✓ | | | | | | | `'flac'` | ✓ | ✓ | ✓ | | | | | | ✓ | | | `'ac3'` | ✓ | ✓ | ✓ | | | | | | | ✓ | | `'eac3'` | ✓ | ✓ | ✓ | | | | | | | ✓ | | `'dts'` | ✓ | ✓ | ✓ | | | | | | | ✓ | | `'truehd'` | ✓ | ✓ | ✓ | | | | | | | | | `'pcm-u8'` | | ✓ | ✓ | | | | ✓ | | | | | `'pcm-s8'` | | ✓ | | | | | | | | | | `'pcm-s16'` | ✓ | ✓ | ✓ | | | | ✓ | | | | | `'pcm-s16be'` | ✓ | ✓ | ✓ | | | | | | | | | `'pcm-s24'` | ✓ | ✓ | ✓ | | | | ✓ | | | | | `'pcm-s24be'` | ✓ | ✓ | ✓ | | | | | | | | | `'pcm-s32'` | ✓ | ✓ | ✓ | | | | ✓ | | | | | `'pcm-s32be'` | ✓ | ✓ | ✓ | | | | | | | | | `'pcm-f32'` | ✓ | ✓ | ✓ | | | | ✓ | | | | | `'pcm-f32be'` | ✓ | ✓ | | | | | | | | | | `'pcm-f64'` | ✓ | ✓ | ✓ | | | | | | | | | `'pcm-f64be'` | ✓ | ✓ | | | | | | | | | | `'ulaw'` | | ✓ | | | | | ✓ | | | | | `'alaw'` | | ✓ | | | | | ✓ | | | | | `'webvtt'`\[^webvtt] | (✓) | | (✓) | (✓) | | | | | | | For HLS, the supported codecs depend on the segment format chosen. \[^prores]: ProRes is not supported by WebCodecs. To decode it, use the [`@mediabunny/prores`](./extensions/prores) extension package. The [`@mediabunny/server`](./extensions/server) extension package provides both decoding and encoding support for server-side environments. \[^aac]: In some browsers, AAC encoding is not supported by WebCodecs. You can polyfill it with the [`@mediabunny/aac-encoder`](./extensions/aac-encoder) extension package. \[^mp3]: MP3 encoding is not supported by WebCodecs. You can polyfill it with the [`@mediabunny/mp3-encoder`](./extensions/mp3-encoder) extension package. \[^flac]: FLAC encoding is not supported by WebCodecs. You can polyfill it with the [`@mediabunny/flac-encoder`](./extensions/flac-encoder) extension package. \[^ac3]: AC-3 and E-AC-3 are not natively supported by WebCodecs. To encode or decode these codecs, you can use the [`@mediabunny/ac3`](./extensions/ac3) extension package. \[^dts]: DTS is not natively supported by WebCodecs. To encode or decode it, you can use the [`@mediabunny/dts`](./extensions/dts) extension package. \[^truehd]: TrueHD is not natively supported by WebCodecs. To encode or decode it, you can use the [`@mediabunny/truehd`](./extensions/truehd) extension package. \[^webm]: WebM only supports a small subset of the codecs supported by Matroska. However, this library can technically read all codecs from a WebM that are supported by Matroska. \[^webvtt]: WebVTT can only be written, not read. ## Querying codec encodability Mediabunny provides utility functions that you can use to check if the browser can encode a given codec. Additionally, you can check if a codec is encodable with a specific *configuration*. `canEncode` tests whether a codec can be encoded using typical settings: ```ts import { canEncode } from 'mediabunny'; canEncode('avc'); // => Promise canEncode('opus'); // => Promise ``` Video codecs are checked using 1280x720, while audio codecs are checked using 2 channels at 48 kHz. You can also check encodability using specific configurations: ```ts import { canEncodeVideo, canEncodeAudio, Quality } from 'mediabunny'; canEncodeVideo('hevc', { width: 1920, height: 1080, frameRate: 60, quality: new Quality({ bitrate: 1e7 }) }); // => Promise canEncodeAudio('aac', { numberOfChannels: 1, sampleRate: 44100, quality: new Quality({ bitrate: 192e3 }) }); // => Promise ``` Additionally, most properties of [`VideoEncodingConfig`](./media-sources#video-encoding-config) and [`AudioEncodingConfig`](./media-sources#audio-encoding-config) can be used here as well. *** In addition, you can use the following functions to check encodability for multiple codecs at once, getting back a list of supported codecs: ```ts import { getEncodableCodecs, getEncodableVideoCodecs, getEncodableAudioCodecs, getEncodableSubtitleCodecs, Quality, } from 'mediabunny'; getEncodableCodecs(); // => Promise getEncodableVideoCodecs(); // => Promise getEncodableAudioCodecs(); // => Promise getEncodableSubtitleCodecs(); // => Promise // These functions also accept optional configuration options. // Here, we check which of AVC, HEVC and VP8 can be encoded at 1920x1080 @10Mbps: getEncodableVideoCodecs( ['avc', 'hevc', 'vp8'], { width: 1920, height: 1080, quality: new Quality({ bitrate: 1e7 }) }, ); // => Promise ``` *** If you simply want to find the best codec that the browser can encode, you can use these functions, which return the first codec supported by the browser: ```ts import { getFirstEncodableVideoCodec, getFirstEncodableAudioCodec, getFirstEncodableSubtitleCodec, Quality, } from 'mediabunny'; getFirstEncodableVideoCodec(['avc', 'vp9', 'av1']); // => Promise getFirstEncodableAudioCodec(['opus', 'aac']); // => Promise getFirstEncodableVideoCodec( ['avc', 'hevc', 'vp8'], { width: 1920, height: 1080, quality: new Quality({ bitrate: 1e7 }) }, ); // => Promise ``` If none of the listed codecs is supported, `null` is returned. These functions are especially useful in conjunction with an [output format](./output-formats) to retrieve the best codec that is supported both by the encoder as well as the container format: ```ts import { Mp4OutputFormat, getFirstEncodableVideoCodec, } from 'mediabunny'; const outputFormat = new Mp4OutputFormat(); const containableVideoCodecs = outputFormat.getSupportedVideoCodecs(); const bestVideoCodec = await getFirstEncodableVideoCodec(containableVideoCodecs); ``` ::: info Codec encodability checks take [custom encoders](#custom-encoders) into account. ::: ## Querying codec decodability If you already have an `InputTrack`, you can check its decodability using its [`canDecode`](./reading-media-files#codec-information) method, which uses the track's actual codec configuration: ```ts const canDecodeTrack = await inputTrack.canDecode(); // => boolean ``` However, you can also gauge decodability even in the absence of any concrete track. `canDecode` tests whether a codec can be decoded using typical settings: ```ts import { canDecode } from 'mediabunny'; canDecode('avc'); // => Promise canDecode('opus'); // => Promise ``` Video codecs are checked using 1280x720, while audio codecs are checked using 2 channels, 48 kHz. You can also check decodability using specific configurations: ```ts import { canDecodeVideo, canDecodeAudio } from 'mediabunny'; canDecodeVideo('hevc', { codedWidth: 1920, codedHeight: 1080 }); // => Promise canDecodeAudio('aac', { numberOfChannels: 1, sampleRate: 44100 }); // => Promise ``` All additional properties of [`VideoDecoderConfig`](https://developer.mozilla.org/en-US/docs/Web/API/VideoDecoder/configure#config) and [`AudioDecoderConfig`](https://developer.mozilla.org/en-US/docs/Web/API/AudioDecoder/configure#config) can be used here as well. *** In addition, you can use the following functions to check decodability for multiple codecs at once, getting back a list of supported codecs: ```ts import { getDecodableCodecs, getDecodableVideoCodecs, getDecodableAudioCodecs, } from 'mediabunny'; getDecodableCodecs(); // => Promise getDecodableVideoCodecs(); // => Promise getDecodableAudioCodecs(); // => Promise // These functions also accept optional configuration options. // Here, we check which of AVC, HEVC and VP8 can be decoded at 1920x1080: getDecodableVideoCodecs( ['avc', 'hevc', 'vp8'], { codedWidth: 1920, codedHeight: 1080 }, ); // => Promise ``` ::: info Codec decodability checks take [custom decoders](#custom-decoders) into account. ::: ## Custom coders Mediabunny allows you to register your own custom encoders and decoders - useful if you want to polyfill a codec that's not supported in all browsers, or want to use Mediabunny outside of an environment with WebCodecs (such as Node.js). Encoders and decoders can be registered for [all video and audio codecs](#codecs) supported by the library. It is not possible to add new codecs. ::: warning Mediabunny requires customs encoders and decoders to follow very specific implementation rules. Pay special attention to the parts labeled with "**must**" to ensure compatibility. ::: ### Custom encoders To create a custom video or audio encoder, you'll need to create a class which extends `CustomVideoEncoder` or `CustomAudioEncoder`. Then, you **must** register this class using `registerEncoder`: ```ts import { CustomAudioEncoder, registerEncoder } from 'mediabunny'; class MyAwesomeMp3Encoder extends CustomAudioEncoder { // ... } registerEncoder(MyAwesomeMp3Encoder); ``` The following properties are available on each encoder instance and are set by the library: ```ts class { // For video encoders: codec: VideoCodec; config: VideoEncoderConfig; onPacket: (packet: EncodedPacket, meta?: EncodedVideoChunkMetadata) => unknown; // For audio encoders: codec: AudioCodec; config: AudioEncoderConfig; onPacket: (packet: EncodedPacket, meta?: EncodedAudioChunkMetadata) => unknown; // For both: onError: (error: unknown) => void; } ``` `codec` and `config` specify the concrete codec configuration to use, and `onPacket` is a method that your code **must** call for each encoded packet it creates. `onError` is a method you can call to surface any out-of-band errors that occur outside of the regular method calls (such as from an asynchronous background task); these errors would otherwise go uncaught. You **must** implement the following methods in your custom encoder class: ```ts class { // For video encoders: static supports(codec: VideoCodec, config: VideoEncoderConfig): boolean; // For audio encoders: static supports(codec: AudioCodec, config: AudioEncoderConfig): boolean; init(): Promise | void; encode(sample: VideoSample, options: VideoEncoderEncodeOptions): Promise | void; // For video encode(sample: AudioSample): Promise | void; // For audio flush(): Promise | void; close(): Promise | void; } ``` * `supports`\ This is a *static* method that **must** return `true` if the encoder is able to encode the specified codec, and `false` if not. If it returns `true`, a new instance of your encoder class will be created by the library and will be used for encoding, taking precedence over the default encoders. * `init`\ Called by the library after your class is instantiated. Place any initialization logic here. * `encode`\ Called for each sample that is to be encoded. The resulting encoded packet **must** then be passed to the `onPacket` method. * `flush`\ Called when the encoder is expected to finish the encoding process for all remaining samples that haven't finished encoding yet. This method **must** return/resolve only once all samples passed to `encode` have been fully encoded. It **must** then reset its own internal state to be ready for the next encoding batch. * `close`\ Called when the encoder is no longer needed and can release its internal resources. ::: info All instance methods of the class can return promises. In this case, the library will make sure to *serialize* all method calls such that no two methods ever run concurrently. ::: ::: warning The packets passed to `onPacket` **must** be in [decode order](./media-sinks.md#decode-vs-presentation-order). ::: ### Custom decoders To create a custom video or audio decoder, you'll need to create a class which extends `CustomVideoDecoder` or `CustomAudioDecoder`. Then, you **must** register this class using `registerDecoder`: ```ts import { CustomAudioDecoder, registerDecoder } from 'mediabunny'; class MyAwesomeMp3Decoder extends CustomAudioDecoder { // ... } registerDecoder(MyAwesomeMp3Decoder); ``` The following properties are available on each decoder instance and are set by the library: ```ts class { // For video decoders: codec: VideoCodec; config: VideoDecoderConfig; onSample: (sample: VideoSample) => unknown; // For audio decoders: codec: AudioCodec; config: AudioDecoderConfig; onSample: (sample: AudioSample) => unknown; // For both: onError: (error: unknown) => void; } ``` `codec` and `config` specify the concrete codec configuration to use, and `onSample` is a method that your code **must** call for each video/audio sample it creates. `onError` is a method you can call to surface any out-of-band errors that occur outside of the regular method calls (such as from an asynchronous background task); these errors would otherwise go uncaught. You **must** implement the following methods in your custom decoder class: ```ts class { // For video decoders: static supports(codec: VideoCodec, config: VideoDecoderConfig): boolean; // For audio decoders: static supports(codec: AudioCodec, config: AudioDecoderConfig): boolean; init(): Promise | void; decode(packet: EncodedPacket): Promise | void; flush(): Promise | void; close(): Promise | void; } ``` * `supports`\ This is a *static* method that **must** return `true` if the decoder is able to decode the specified codec, and `false` if not. If it returns `true`, a new instance of your decoder class will be created by the library and will be used for decoding, taking precedence over the default decoders. * `init`\ Called by the library after your class is instantiated. Place any initialization logic here. * `decode`\ Called for each `EncodedPacket` that is to be decoded. The resulting video or audio sample **must** then be passed to the `onSample` method. * `flush`\ Called when the decoder is expected to finish the decoding process for all remaining packets that haven't finished decoding yet. This method **must** return/resolve only once all packets passed to `decode` have been fully decoded. It **must** then reset its own internal state to be ready for the next decoding batch. * `close`\ Called when the decoder is no longer needed and can release its internal resources. ::: info All instance methods of the class can return promises. In this case, the library will make sure to *serialize* all method calls such that no two methods ever run concurrently. ::: ::: warning The samples passed to `onSample` **must** be sorted by increasing timestamp. This especially means if the decoder is decoding a video stream that makes use of [B-frames](./media-sources.md#b-frames), the decoder **must** internally hold on to these frames so it can emit them sorted by presentation timestamp. This strict sorting requirement is reset each time `flush` is called. ::: --- --- url: /codec-registry/truehd.md description: >- Dolby TrueHD audio codec definition, defining legal codec strings, decoder configs, and packet data formats. --- # TrueHD codec registration ## Description The Dolby TrueHD lossless audio codec, as described in Dolby's *Dolby TrueHD (MLP) high-level bitstream description*. Its predecessor, Meridian Lossless Packing (MLP), is not covered by this registration. ## Codec ID ```ts 'truehd' ``` ## `EncodedPacket` data The packet's data must be exactly one access unit, beginning with the 4-byte access unit header that holds the access unit's length. ## `EncodedPacket` type If the packet's type is `'key'`, then the access unit is expected to carry a major sync, meaning its bytes 4 through 7 are `0xF8726FBA`. All other access units are of type `'delta'`. ## `AudioDecoderConfig` codec string ```ts 'mlpa' ``` ## `AudioDecoderConfig` description `description` is not used for this codec. --- --- url: /codec-registry/vorbis.md description: >- Vorbis audio codec definition, defining legal codec strings, decoder configs, and packet data formats. --- # Vorbis codec registration ## Description The Vorbis audio codec, specified in the [Vorbis I Specification](https://xiph.org/vorbis/doc/Vorbis_I_spec.html). ## Codec ID ```ts 'vorbis' ``` ## `EncodedPacket` data The packet's data must be an audio packet as described in Section 4.3 of the [Vorbis I Specification](https://xiph.org/vorbis/doc/Vorbis_I_spec.html). ## `EncodedPacket` type The packet's type is always `'key'`. ## `AudioDecoderConfig` codec string ```ts 'vorbis' ``` ## `AudioDecoderConfig` description `description` must contain Vorbis codec setup data in Xiph extradata format: the `page_segments` field, followed by the `segment_table` field, followed by the three Vorbis header packets (identification header, comments header, and setup header) as defined in Section 4.2 of the [Vorbis I Specification](https://xiph.org/vorbis/doc/Vorbis_I_spec.html). --- --- url: /codec-registry/vp8.md description: >- VP8 video codec definition, defining legal codec strings, decoder configs, and packet data formats. --- # VP8 codec registration ## Description The VP8 video codec, specified in [RFC 6386](https://www.rfc-editor.org/rfc/rfc6386). ## Codec ID ```ts 'vp8' ``` ## `EncodedPacket` data The packet's data must be a frame as described in Section 4 and Annex A of [RFC 6386](https://www.rfc-editor.org/rfc/rfc6386). ## `EncodedPacket` type If the packet's type is `'key'`, then the packet is expected to contain a frame where `key_frame` is `true`, as defined in Section 19.1 of [RFC 6386](https://www.rfc-editor.org/rfc/rfc6386). ## `VideoDecoderConfig` codec string ```ts 'vp8' ``` ## `VideoDecoderConfig` description `description` is not used for this codec. ## Quantizer range VP8 has no quantizer support. --- --- url: /codec-registry/vp9.md description: >- VP9 video codec definition, defining legal codec strings, decoder configs, and packet data formats. --- # VP9 codec registration ## Description The VP9 video codec, specified in the [VP9 Bitstream & Decoding Process Specification](https://storage.googleapis.com/downloads.webmproject.org/docs/vp9/vp9-bitstream-specification-v0.6-20160331-draft.pdf). ## Codec ID ```ts 'vp9' ``` ## `EncodedPacket` data The packet's data must be a frame as described in Section 6 of the [VP9 Bitstream & Decoding Process Specification](https://storage.googleapis.com/downloads.webmproject.org/docs/vp9/vp9-bitstream-specification-v0.6-20160331-draft.pdf). ## `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 7.2 of the [VP9 Bitstream & Decoding Process Specification](https://storage.googleapis.com/downloads.webmproject.org/docs/vp9/vp9-bitstream-specification-v0.6-20160331-draft.pdf). ## `VideoDecoderConfig` codec string The full codec string begins with the prefix `'vp09.'`, with a variable-length suffix as specified in the [VP Codec ISO Media File Format Binding](https://www.webmproject.org/vp9/mp4/). ## `VideoDecoderConfig` description `description` is not used for this codec. ## Quantizer range VP9 has quantizer support and supports quantizer values in the range \[0, 255]. --- --- url: /guide/writing-hls.md description: >- Mediabunny can create new HLS (.m3u8) playlists directly in the browser, both VOD and live. Define tracks, add media data, and upload directly to a server. --- # Writing HLS Mediabunny has full support for creating new HLS (.m3u8) playlists, both VOD and live. This page will go into HLS-specific behavior and advice. For general information about creating new media files (including HLS) in Mediabunny, refer to [Writing media files](./writing-media-files). ## Structure & mental model When Mediabunny writes HLS, it will always create the following files: * One master playlist * One or more media playlists * Zero or more media segment files Mediabunny takes care of creating the playlists and segmenting the media data. All you need to describe are the tracks, the relationships between them, and their media data. Media segments are always emitted as soon as they are complete. The master and media playlists are emitted upon [finalizing the output](../api/Output#finalize) when in VOD mode (the default). When in [live mode](#live-hls), they will be emitted each time they are updated. ## HLS outputs HLS playlists are created through the same `Output` interface as all other media files in Mediabunny. The difference is that HLS creates multiple files, meaning a `PathedTarget` is required: ```ts import { Output, PathedTarget, HlsOutputFormat, MpegTsOutputFormat } from 'mediabunny'; const output = new Output({ format: new HlsOutputFormat({ segmentFormat: new MpegTsOutputFormat(), // User-defined segment format }), target: new PathedTarget( 'master.m3u8', // The path to the entry file ({ path }) => { // Return a Target here }, ), }); ``` The `PathedTarget` requires that you return a [`Target`](../api/Target) for every file (identified by a [path](../api/FilePath)) that Mediabunny wants to write. ### No master playlist If you only want to write a media playlist and not a master playlist, make use of [`NullTarget`](../api/NullTarget): ```ts const output = new Output({ target: new PathedTarget( '', ({ path, isRoot }) => { if (isRoot) { return new NullTarget(); } // ... }, ), // ... }); ``` Note that this might write out multiple media playlists based on the configured track pairability; see [Track groups & pairings](#track-groups--pairings). ## Target examples You are free to use whichever target you want (see [list of targets](./writing-media-files#output-targets)), but here are some examples: ### Write to memory ```ts const writtenFiles = new Map(); const output = new Output({ target: new PathedTarget( 'master.m3u8', ({ path }) => new BufferTarget({ onFinalize: buffer => writtenFiles.set(path, buffer), }), ), // ... }); // ... await output.finalize(); // The final files: console.log(writtenFiles); ``` ### Write to OPFS ```ts const root = await navigator.storage.getDirectory(); const writePromises: Promise[] = []; const output = new Output({ target: new PathedTarget( 'master.m3u8', async ({ path }) => new BufferTarget({ onFinalize: (buffer) => { writePromises.push((async () => { const handle = await root.getFileHandle(path, { create: true }); const writable = await handle.createWritable(); await writable.write(buffer); await writable.close(); })()); }, }), ), onFinalize: () => Promise.all(writePromises), // ... }); // ... await output.finalize(); // Final files now reside in OPFS ``` ### Upload to a server #### Stream upload This code models a stream upload, where files are being uploaded *while* they are being created: ```ts const promises: Promise[] = []; const output = new Output({ target: new PathedTarget( 'master.m3u8', async ({ path, mimeType }) => { const { writable, readable } = new TransformStream< Uint8Array, Uint8Array, >(); const url = `/upload?file=${encodeURIComponent(path)}`; const promise = fetch(url, { method: 'POST', body: readable, duplex: 'half', headers: { 'Content-Type': mimeType, }, }); promises.push(promise); // Requires that all segments use an append-only format return new AppendOnlyStreamTarget(writable); }, ), onFinalize: () => Promise.all(promises), // ... }); // ... await output.finalize(); // All files have been uploaded to the server ``` #### Monolithic upload If streaming is not possible (e.g. when uploading to S3 via signed `PutObject`, which requires a known `Content-Length`), you can use [`BufferTarget`](../api/BufferTarget) with the [`onFinalize`](../api/BufferTargetOptions#onfinalize) option instead. You could call `fetch` directly but this would halt Mediabunny's internals until the upload has completed. Instead, using a [`ConcurrentRunner`](../api/ConcurrentRunner) allows Mediabunny to keep producing data internally while the upload is in flight, while also allowing multiple concurrent uploads: ```ts import { ConcurrentRunner, ... } from 'mediabunny'; // This Mediabunny utility class is used to allow up to two requests // to run concurrently. When this number is exceeded, backpressure is // automatically applied internally. const runner = new ConcurrentRunner(2); const output = new Output({ target: new PathedTarget( 'master.m3u8', ({ path, mimeType }) => new BufferTarget({ onFinalize: buffer => runner.run(() => fetch(`/upload?file=${encodeURIComponent(path)}`, { method: 'PUT', body: buffer, headers: { 'Content-Type': mimeType, }, }) ), }), ), onFinalize: () => runner.flush(), // ... }); await output.finalize(); // All files have been uploaded to the server ``` ## Adding tracks & media Output tracks can be registered using the usual approach by using [media sources](./media-sources): ```ts const videoSource = new VideoSampleSource(/* ... */); const audioSource = new AudioSampleSource(/* ... */); output.addVideoTrack(videoSource); output.addAudioTrack(audioSource); await output.start(); ``` Then, add media data like normal. Since Mediabunny takes care of segmentation automatically, it is required to perform [Packet buffering](./writing-media-files#packet-buffering) internally. Therefore, try writing media data in a quasi-interleaved fashion to keep memory usage bounded. ### Multiple resolutions A common pattern is to offer the same content in multiple resolutions and bitrates. This requires encoding the content multiple times, sometimes with additional downscaling. Mediabunny's [media sources](./media-sources) make this pattern a breeze. Let's suppose we have a 1080p main video stream. We want to provide a 1080p, 720p, 480p, and 360p variant in the HLS playlist. For that, use this pattern: ```ts const source1080p = new VideoSampleSource({ codec: 'avc', quality: new Quality('very-high'), }); const source720p = new VideoSampleSource({ codec: 'avc', quality: new Quality('high'), transform: { // Frames will be automatically resized to 720p before being encoded height: 720, }, }); const source480p = new VideoSampleSource({ codec: 'avc', quality: new Quality('medium'), transform: { height: 480, }, }); const source360p = new VideoSampleSource({ codec: 'avc', quality: new Quality('low'), transform: { height: 360, }, }); const sources = [source1080p, source720p, source480p, source360p]; for (const source of sources) { output.addVideoTrack(source); } await output.start(); // Then, when adding a new frame: const sample = // ... for (const source of sources) { await source.add(sample); } ``` You can extend this pattern to offer content in multiple codecs as well. For the full list of transformation options, see [`VideoTransformOptions`](../api/VideoTransformOptions) and [`AudioTransformOptions`](../api/AudioTransformOptions). *** If you're using the [Conversion API](./converting-media-files), you achieve the same thing using [output track fan-out](./converting-media-files#track-fan-out): ```ts const conversion = await Conversion.init({ input, output, video: [ { height: 1080, quality: new Quality('very-high') }, { height: 720, quality: new Quality('high') }, { height: 480, quality: new Quality('medium') }, { height: 360, quality: new Quality('low') }, ], }); ``` ### Track metadata Often you'll want to provide additional [track metadata](../api/BaseTrackMetadata) when dealing with multiple tracks. For example: ```ts output.addVideoTrack(videoSource); output.addAudioTrack(audioSourceEn, { languageCode: 'en', name: 'English' }); output.addAudioTrack(audioSourceDe, { languageCode: 'de', name: 'German' }); output.addAudioTrack(audioSourceEs, { languageCode: 'es', name: 'Spanish' }); ``` ### Track disposition You can control how a track is selected by players using the `disposition` option. The following fields map to HLS attributes on `#EXT-X-MEDIA`: * `disposition.primary` → `DEFAULT=YES` (only one per media rendition group is allowed; subsequent `primary` tracks in the same group are ignored) * `disposition.default` → `AUTOSELECT=YES` (also implied when `primary` is `true`) * `disposition.forced` → `FORCED=YES` For example: ```ts output.addAudioTrack(audioSourceEn, { languageCode: 'en', name: 'English', disposition: { primary: true }, }); output.addAudioTrack(audioSourceDe, { languageCode: 'es', name: 'Spanish', disposition: { default: false }, }); ``` When unspecified, `default` is `true` and `primary` and `forced` are `false`. ### I-frame only tracks A track registered like this will be emitted via `#EXT-X-I-FRAME-STREAM-INF`: ```ts output.addVideoTrack(videoSource, { hasOnlyKeyPackets: true }); ``` Note that it is an error to add non-key packets to a track like this. ### DATE-TIME tags In order to emit `#EXT-X-PROGRAM-DATE-TIME` tags in the media playlist, which map each media time to a definitive point in time, set `isRelativeToUnixEpoch` in the track metadata: ```ts output.addVideoTrack(videoSource, { isRelativeToUnixEpoch: true }); ``` This declares that the timestamps added by you are not relative to the composition start (0), but to the Unix epoch (1 Jan 1970, midnight UTC): ```ts const source = new EncodedVideoPacketSource('avc'); output.addVideoTrack(source, { isRelativeToUnixEpoch: true }); await output.start(); // 10 FPS starting on 1 Jan 2024, midnight UTC. // The timestamps *are* Unix timestamps: await source.add(new EncodedPacket(data, type, 1704067200.0, 0.1)); await source.add(new EncodedPacket(data, type, 1704067200.1, 0.1)); await source.add(new EncodedPacket(data, type, 1704067200.2, 0.1)); // ... ``` The above code will emit a media playlist like this: ```m3u8 #EXTM3U #EXT-X-VERSION:3 #EXT-X-PLAYLIST-TYPE:VOD #EXT-X-TARGETDURATION:2 #EXT-X-INDEPENDENT-SEGMENTS #EXTINF:2, #EXT-X-PROGRAM-DATE-TIME:2024-01-01T00:00:00.000Z segments-1-1.ts #EXTINF:2, #EXT-X-PROGRAM-DATE-TIME:2024-01-01T00:00:02.000Z segments-1-2.ts ... ``` ## Track groups & pairings Mediabunny allows you to add tracks to an HLS playlist in a flat way, but real HLS playlists are structured: Tracks are grouped into variants and media renditions, which imply a track pairability graph: some tracks can be paired with each other (can be presented together), others can't. You can control these track pairings using *track groups*. Tracks can be assigned to zero or more groups, and groups can be paired: ```ts import { OutputTrackGroup } from 'mediabunny'; const groupA = new OutputTrackGroup(); const groupB = new OutputTrackGroup(); const groupC = new OutputTrackGroup(); // Pairs A with C and C with A groupA.pairWith(groupC); // Track is in one group output.addVideoTrack(source, { group: groupA }); // Track is in multiple groups output.addVideoTrack(source, { group: [groupB, groupC] }); // Track is in no groups output.addVideoTrack(source, { group: [] }); ``` ### Pairing rule Two output tracks are considered *pairable* if at least one of these is true: * Both tracks are in the same group **and** have a different type (video, audio, subtitle) * They are in separate groups that have been paired with each other When not specified, all tracks are automatically assigned to [`Output.defaultTrackGroup`](../api/Output#defaulttrackgroup). This means that all tracks can be paired with any other track of a different type, but no two tracks of the same type can be paired. ### Examples #### Default pairing (n:k) Imagine this four-track configuration: ```ts output.addVideoTrack(source1); output.addVideoTrack(source2); output.addAudioTrack(source3); output.addAudioTrack(source4); ``` Since no track groups are specified, all tracks will be assigned to [`Output.defaultTrackGroup`](../api/Output#defaulttrackgroup). Assuming only one video and audio codec, this leads to a master playlist like this: ```m3u8 #EXTM3U #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio-1",NAME="audio-1",URI="audio-1.m3u8" #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio-1",NAME="audio-1",URI="audio-2.m3u8" #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=1280x720,AUDIO="audio-1" video-1.m3u8 #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=640x480,AUDIO="audio-1" video-2.m3u8 ``` To maintain the "every video track can be paired with every audio track" configuration, the audio tracks have been extracted into a media rendition group via `#EXT-X-MEDIA`. :::info Note that tracks in a media rendition group should differ in metadata. Thus, when creating tracks in this configuration, make sure to provide metadata options like `language` or `name` to differentiate the tracks. ::: #### Codec alternatives Imagine this configuration where we provide the audio track in two different codecs for broader support: ```ts output.addVideoTrack(source1); output.addVideoTrack(source2); // Different audio codecs: output.addAudioTrack(sourceAac); output.addAudioTrack(sourceAc3); ``` This will be emitted as a master playlist like this, which covers every video-audio track permutation: ```m3u8 #EXTM3U #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio-1",NAME="audio-1",URI="audio-1.m3u8" #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio-2",NAME="audio-2",URI="audio-2.m3u8" #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=1280x720,AUDIO="audio-1" video-1.m3u8 #EXT-X-STREAM-INF:CODECS="avc1.64001f,ac-3",RESOLUTION=1280x720,AUDIO="audio-2" video-1.m3u8 #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=640x480,AUDIO="audio-1" video-2.m3u8 #EXT-X-STREAM-INF:CODECS="avc1.64001f,ac-3",RESOLUTION=640x480,AUDIO="audio-2" video-2.m3u8 ``` #### One audio per video To achieve a 1:1 pairing between video and audio tracks, we can group tracks like this: ```ts const a = new OutputTrackGroup(); const b = new OutputTrackGroup(); output.addVideoTrack(source1, { group: a }); output.addVideoTrack(source2, { group: b }); output.addAudioTrack(source3, { group: a }); output.addAudioTrack(source4, { group: b }); ``` This will lead to a master playlist like this: ```m3u8 #EXTM3U #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=1280x720 video-and-audio-1.m3u8 #EXT-X-STREAM-INF:CODECS="avc1.64001f,mp4a.40.2",RESOLUTION=640x480 video-and-audio-2.m3u8 ``` #### Standalone tracks If all tracks are meant to be standalone, make sure no two are pairable with each other. One way to express this is: ```ts output.addVideoTrack(source1, { group: [] }); output.addVideoTrack(source2, { group: [] }); output.addAudioTrack(source3, { group: [] }); output.addAudioTrack(source4, { group: [] }); ``` This creates the following master playlist: ```m3u8 #EXTM3U #EXT-X-STREAM-INF:CODECS="avc1.64001f",RESOLUTION=1280x720 video-1.m3u8 #EXT-X-STREAM-INF:CODECS="avc1.64001f",RESOLUTION=640x480 video-2.m3u8 #EXT-X-STREAM-INF:CODECS="mp4a.40.2" audio-1.m3u8 #EXT-X-STREAM-INF:CODECS="mp4a.40.2" audio-2.m3u8 ``` #### Arbitrary pairings Any symmetric track pairability graph can be modeled using track groups. The construction is as follows: * Create one group per track * Assign every track $T\_i$ to $G\_i$ * If $T\_i$ and $T\_j$ should be pairable, pair $G\_i$ with $G\_j$ ### Illegal pairings Not all track pairings can be represented in HLS master playlists. Specifically, it is forbidden to pair tracks of the same type with each other: ```ts const a = new OutputTrackGroup(); const b = new OutputTrackGroup(); a.pairWith(b); output.addVideoTrack(source1, { group: a }); output.addVideoTrack(source2, { group: b }); ``` This will cause Mediabunny to raise a warning and treat the two tracks as unpaired. ## Output configuration Mediabunny offers various ways to configure the HLS output via [`HlsOutputFormatOptions`](../api/HlsOutputFormatOptions). ### Segment format For tree-shaking purposes, you must declare the format of each media segment yourself. Any [output format](./output-formats) works, although not all of them are spec-compliant with HLS. You should stick to the following, well-supported options: #### MPEG-TS Tried and true: ```ts new HlsOutputFormat({ segmentFormat: new MpegTsOutputFormat(), }); ``` #### CMAF ```ts new HlsOutputFormat({ segmentFormat: new CmafOutputFormat(), }); ``` Note that this format emits an init segment in addition to all of the media segments. #### MP3/ADTS/WAV These work fine when packaging a single track into a segment: ```ts // MP3: new HlsOutputFormat({ segmentFormat: new Mp3OutputFormat(), }); // ADTS: new HlsOutputFormat({ segmentFormat: new AdtsOutputFormat(), }); // WAV: new HlsOutputFormat({ segmentFormat: new WavOutputFormat({ metadataFormat: 'id3', // Recommended for correct media timestamping }), }); ``` #### Mixed formats You may want to package audio data into .aac files and video data into .ts files. For this, you can specify an array of output formats: ```ts new HlsOutputFormat({ segmentFormat: [ new AdtsOutputFormat(), // For audio segments new MpegTsOutputFormat(), // For video segments ], }); ``` Mediabunny will then use the first format that can contain all tracks of the segment. ### File names By default, Mediabunny will create the following file names: * Master playlist `pathedTarget.rootPath` (name specified by you) * Media playlist `'playlist-1.m3u8'` * Media segment `'segment-1-1.ts'` * Media segment `'segment-1-2.ts'` * ... * Media playlist `'playlist-2.m3u8'` * Init segment `'init-1.m4s'` (Emitted for some segment formats) * Media segment `'segment-2-1.m4s'` * Media segment `'segment-2-2.m4s'` * ... * Media playlist `'playlist-3.m3u8'` * Single-file segment `segments-3.ts` * ... You can fully customize these names using the following options: * [`getPlaylistPath`](../api/HlsOutputFormatOptions#getplaylistpath) * [`getSegmentPath`](../api/HlsOutputFormatOptions#getSegmentPath) * [`getInitPath`](../api/HlsOutputFormatOptions#getInitPath) ### Segment duration Use `targetDuration` to set the desired maximum duration for each segment: ```ts new HlsOutputFormat({ // ... targetDuration: 10, // Defaults to 2 (seconds) }); ``` Mediabunny will then try to maximize the length of each segment while making sure it doesn't exceed the target duration. Since Mediabunny will only create new segments on key frame boundaries, make sure to provide a key frame at least every `targetDuration` seconds. If you don't, it has no choice but to create longer segments. You can use [`VideoEncodingConfig.keyFrameInterval`](../api/VideoEncodingConfig#keyframeinterval) to control key frame rate. ### Single-file segments Since HLS supports byte subrange requests, you may want to package all media data into one giant monolithic segment file: ```ts new HlsOutputFormat({ // ... singleFilePerPlaylist: true, }); ``` This will emit media playlists like this: ```m3u8 #EXTM3U #EXT-X-VERSION:4 #EXT-X-PLAYLIST-TYPE:VOD #EXT-X-TARGETDURATION:2 #EXT-X-INDEPENDENT-SEGMENTS #EXTINF:2, #EXT-X-BYTERANGE:12345@0 segments-1.ts #EXTINF:2, #EXT-X-BYTERANGE:67890@12345 segments-1.ts ... ``` This option is special-cased when used in conjunction with a fragmented MP4 segment format: the resulting segments file will be a standalone valid fMP4 file. This way, you get both an HLS playlist as well as a single-file representation of the media. ### Media timestamp base The media inside the segments always starts at the same timestamp, regardless of the timestamps you add. Use `mediaTimestampBase` to set it: ```ts new HlsOutputFormat({ // ... mediaTimestampBase: 0, // Defaults to 10 (seconds) }); ``` The default leaves headroom for timestamps that lie slightly before the first packet (B-frames, audio priming). The timestamps in the playlists are not affected. ## Live HLS By default, created HLS playlists are assumed to be VODs. If you instead want to create HLS live streams that are to be consumed while they are being produced, you can use live mode: ```ts new HlsOutputFormat({ // ... live: true, }); ``` Compared to VOD mode, live mode has these main behavioral differences: * The `#EXT-X-PLAYLIST-TYPE:VOD` tag is omitted from media playlists * Media playlists will be emitted as soon as they have one finished segment * The master playlist will be emitted as soon as every media playlist has been emitted at least once * Media playlists will be re-emitted each time they are updated (new segment or stream ended) * The master playlist will be re-emitted each time a media playlist is updated (to refine bitrate values) * Media playlists will only have the `#EXT-X-ENDLIST` tag when the stream has ended Since master and media playlists will be written more than once, multiple targets will be requested for the same path. Make sure to return a different `Target` instance each time. ### Ending the stream Finalizing the output ends the stream for all media playlists and appends `#EXT-X-ENDLIST` to each one of them: ```ts await output.finalize(); ``` You can end the stream for a subset of tracks by closing tracks individually. When the last open track of any media playlist is closed (meaning no more media data can be added), that media playlist's stream will be ended: ```ts // Assuming a stream with video & audio: videoSource.close(); // Audio is still running, live stream keeps going audioSource.close(); // No more media data can come in, live stream has ended ``` ### Removing old segments By default, Mediabunny will keep appending new segments to media playlists without ever removing the old ones. This means that media playlists grow in size until the stream has ended. To set a cap on the maximum number of segments per playlist, and to tell Mediabunny to pop old segments off the playlist, use `maxLiveSegmentCount`: ```ts new HlsOutputFormat({ // ... maxLiveSegmentCount: 500, // Defaults to Infinity onSegmentPopped: (path, segmentInfo) => // ... }); ``` Whenever a segment is popped off the playlist in this fashion, the `onSegmentPopped` callback is called, which you can use to be notified of a segment being removed and to take action; for example, to delete the segment file. The callback is passed the path of the segment and [`HlsOutputSegmentInfo`](../api/HlsOutputSegmentInfo). ::: info `onSegmentPopped` is not called when `singleFilePerPlaylist` is enabled. ::: ## Subtitles Writing subtitles to HLS playlists is not currently supported. Sorry! --- --- url: /guide/writing-media-files.md description: >- Use Mediabunny to create new video and audio files of any size directly in the browser, and with full control over frame timing, tracks, and more. --- # Writing media files Mediabunny enables you to create media files with very fine levels of control. You can add an arbitrary number of video, audio and subtitle tracks to a media file, and precisely control the timing of media data. This library supports [many output file formats](./output-formats). Using [output targets](#output-targets), you can decide if you want to build up the entire file in memory or stream it out in chunks as it's being created - allowing you to create very large files. Mediabunny provides many ways to supply media data for output tracks, nicely integrating with the WebCodecs API, but also allowing you to use your own encoding stack if you wish. These [media sources](./media-sources) come in multiple levels of abstraction, enabling easy use for common use cases while still giving you fine-grained control if you need it. ## Creating an output Media file creation in Mediabunny revolves around a central class, `Output`. One instance of `Output` represents one media file you want to create. Start by creating a new instance of `Output` using the desired configuration of the file you want to create: ```ts import { Output, Mp4OutputFormat, BufferTarget } from 'mediabunny'; // In this example, we'll be creating an MP4 file in memory: const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget(), }); ``` See [Output formats](./output-formats) for a full list of available output formats.\ See [Output targets](#output-targets) for a full list of available output targets. You can always access `format` and `target` on the output: ```ts output.format; // => Mp4OutputFormat output.target; // => BufferTarget ``` ## Adding tracks There are a couple of methods on an `Output` that you can use to add tracks to it: ```ts output.addVideoTrack(videoSource); output.addAudioTrack(audioSource); output.addSubtitleTrack(subtitleSource); ``` For each track you want to add, you'll need to create a unique [media source](./media-sources) for it. You'll be able to add media data to the output via these media sources. A media source can only ever be used for one output track. These methods return the newly created `OutputTrack` instance. Optionally, you can specify additional track metadata when adding tracks: ```ts // This specifies that the video track should be rotated by 90 degrees // clockwise before being displayed by video players, and that a frame rate // of 30 FPS is expected. output.addVideoTrack(videoSource, { // Clockwise rotation in degrees rotation: 90, // Expected frame rate in hertz frameRate: 30, }); // This adds two audio tracks; one in English and one in German. output.addAudioTrack(audioSourceEng, { languageCode: 'eng', // ISO 639-2/T language code name: 'Developer Commentary', // Sets a user-defined track name disposition: { commentary: true }, // Sets additional flags in the file }); output.addAudioTrack(audioSourceGer, { languageCode: 'ger', }); // This adds multiple subtitle tracks, all for different languages. output.addSubtitleTrack(subtitleSourceEng, { languageCode: 'eng' }); output.addSubtitleTrack(subtitleSourceGer, { languageCode: 'ger' }); output.addSubtitleTrack(subtitleSourceSpa, { languageCode: 'spa' }); output.addSubtitleTrack(subtitleSourceFre, { languageCode: 'fre' }); output.addSubtitleTrack(subtitleSourceIta, { languageCode: 'ita' }); ``` ::: info The optional `frameRate` video track metadata option specifies the expected frame rate of the video. All timestamps and durations of frames that will be added to this track will be snapped to the specified frame rate. You should avoid adding frames more often than the rate permits, as this will lead to multiple frames having the same timestamp. To precisely achieve common fractional frame rates, make sure to use their exact fractional forms: $23.976 \rightarrow 24000/1001$\ $29.97 \rightarrow 30000/1001$\ $59.94 \rightarrow 60000/1001$ ::: As an example, let's add two tracks to our output: * A video track driven by the contents of a `` element, encoded using AVC * An audio track driven by the user's microphone input, encoded using AAC ```ts import { CanvasSource, MediaStreamAudioTrackSource, Quality } from 'mediabunny'; // Assuming `canvasElement` exists const videoSource = new CanvasSource(canvasElement, { codec: 'avc', quality: new Quality({ bitrate: 1e6 }), // 1 Mbps }); const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); const audioStreamTrack = stream.getAudioTracks()[0]; const audioSource = new MediaStreamAudioTrackSource(audioStreamTrack, { codec: 'aac', quality: new Quality({ bitrate: 128e3 }), // 128 kbps }); output.addVideoTrack(videoSource, { frameRate: 30 }); output.addAudioTrack(audioSource); ``` ::: warning Adding tracks to an `Output` will throw if the track is not compatible with the output format. Be sure to respect the [properties](./output-formats#format-properties) of the output format when adding tracks. ::: ### Track groups & pairability To control output track pairability (which tracks can be presented with which tracks), Mediabunny uses a concept called "track groups". Tracks are assigned to zero or more groups, and their group membership determines with which other tracks they can be paired. This system allows for the common pairability patterns to be described easily. For typical file formats, configuring track groups is not necessary and does nothing. It is relevant for configuring many-track formats such as HLS, where track groups affect the structure of the master playlist. Two output tracks are considered pairable if at least one of these is true: * They are part of the same group but have a different type (video, audio, subtitle) * They are in two different groups that have been paired with each other Create track groups like this: ```ts import { OutputTrackGroup } from 'mediabunny'; const groupA = new OutputTrackGroup(); const groupB = new OutputTrackGroup(); ``` You can optionally pair groups like this: ```ts // After this, any track in group A can be paired with any track in group B groupA.pairWith(groupB); // Automatically pairs B with A as well (symmetric operation) ``` Assign tracks to groups during track registration: ```ts output.addVideoTrack(videoSource, { group: groupA }); output.addAudioTrack(audioSource, { group: [groupA, groupB] }); ``` By default, when not specified, every track will be assigned to `Output.defaultTrackGroup`. This in turn means that the default track pairing rules are: * Tracks of different type (video, audio, subtitle) can always be paired with each other * No two tracks of the same type (e.g. two audio tracks) can be paired with each other ## Setting metadata tags Mediabunny lets you write additional descriptive metadata tags to an output file, such as title, artist, or cover art: ```ts output.setMetadataTags({ title: 'Big Buck Bunny', artist: 'Blender Foundation', date: new Date('2008-05-20'), images: [{ data: new Uint8Array([...]), mimeType: 'image/jpeg', kind: 'coverFront', }], }); ``` If you add metadata tags, you must call this method *before* starting the `Output`. For more info on which tags you can write, see [`MetadataTags`](../api/MetadataTags). ## Starting an output After all tracks have been added to the `Output`, you need to *start* it. Starting an output spins up the writing process, allowing you to now start sending media data to the output file. It also prevents you from adding any new tracks to it. ```ts await output.start(); // Resolves once the output is ready to receive media data ``` ## Adding media data After starting an `Output`, you can use the media sources you used to add tracks to pipe media data to the output file. The API for this is different for each [media source](./media-sources), but it typically looks something like this: ```ts mediaSource.add(...); ``` In our example, as soon as we called `start`, the user's microphone input will be piped to the output file. However, we still need to add the data from our canvas. We might do something like this: ```ts let framesAdded = 0; const intervalId = setInterval(() => { const timestampInSeconds = framesAdded / 30; const durationInSeconds = 1 / 30; // Captures the canvas state at the time of calling `add`: videoSource.add(timestampInSeconds, durationInSeconds); framesAdded++; }, 1000 / 30); ``` And then we'll let this run for as long as we want to capture media data. ## Finalizing an output Once all media data has been added, the `Output` needs to be *finalized*. Finalization finishes all remaining encoding work and writes the remaining data to create the final, playable media file. ```ts await output.finalize(); // Resolves once the output is finalized ``` ::: warning After calling `finalize`, adding more media data to the output results in an error. ::: In our example, we'll need to do this: ```ts clearInterval(intervalId); // Stops the canvas loop audioStreamTrack.stop(); // Stops capturing the user's microphone await output.finalize(); const file = output.target.buffer; // => Uint8Array ``` *** An optional [`onFinalize`](../api/OutputOptions#onfinalize) callback can be provided in the output options. This function will be called at the end of `.finalize()` and can be used to do work once the output has been completed. If it returns a promise, it will be awaited by the output. ## Canceling an output Sometimes, you may want to cancel the ongoing creation of an output file. For this, use the `cancel` method: ```ts await output.cancel(); // Resolves once the output is canceled ``` This automatically frees up all resources used by the output process, such as closing all encoders or releasing the writer. ::: warning After calling `cancel`, adding more media data to the output results in an error. ::: In our example, we would do this: ```ts clearInterval(intervalId); // Stops the canvas loop audioStreamTrack.stop(); // Stops capturing the user's microphone await output.cancel(); // The output is canceled ``` ## Checking output state You can always check the current state the output is in using its `state` property: ```ts output.state; // => 'pending' | 'started' | 'canceled' | 'finalizing' | 'finalized' ``` * `'pending'` - The output hasn't been started or canceled yet; new tracks can be added. * `'started'` - The output has been started and is ready to receive media data; tracks can no longer be added. * `'finalizing'` - `finalize` has been called but hasn't resolved yet; no more media data can be added. * `'finalized'` - The output has been finalized and is done writing the file. * `'canceled'` - The output has been canceled. ## Output targets The *output target* determines where the data created by the `Output` will be written. This library offers a couple of targets. *** All targets emit a `write` event you can listen to in order to monitor which byte regions are being written to: ```ts const stopListening = target.on('write', ({ start, end }) => { // ... }); ``` You can use this to track the size of the output file as it grows. But be warned, this event is chatty and gets fired *extremely* frequently. ### `BufferTarget` This target writes all data to a single, contiguous, in-memory `ArrayBuffer`. This buffer will automatically grow as the file becomes larger. Usage is straightforward: ```ts import { Output, BufferTarget } from 'mediabunny'; const output = new Output({ target: new BufferTarget(), // ... }); // ... output.target.buffer; // => null await output.finalize(); output.target.buffer; // => ArrayBuffer ``` This target is a great choice for small-ish files (< 100 MB), but since all data will be kept in memory, using it for large files is suboptimal. If the output gets very large, the page might crash due to memory exhaustion. For these cases, using `StreamTarget` is recommended. #### `onFinalize` callback `BufferTarget` accepts an `onFinalize` option, which is called with the complete buffer once the target has been finalized. Useful for uploading the final buffer to a server or object store (e.g. S3 `PutObject`, which requires a known `Content-Length`): ```ts const output = new Output({ target: new BufferTarget({ onFinalize: async (buffer) => { await fetch('/upload', { method: 'PUT', body: buffer }); }, }), // ... }); await output.finalize(); // The upload has completed by the time finalize resolves. ``` ### `StreamTarget` This target passes you the data written by the `Output` in small chunks, requiring you to pipe that data elsewhere to manually assemble the final file. Example use cases include writing the file directly to disk, or uploading it to a server over the network. `StreamTarget` makes use of the Streams API, meaning you'll need to pass it an instance of `WritableStream`: ```ts import { Output, StreamTarget, StreamTargetChunk } from 'mediabunny'; const writable = new WritableStream({ write(chunk: StreamTargetChunk) { chunk.data; // => Uint8Array chunk.position; // => number // Do something with the data... } }); const output = new Output({ target: new StreamTarget(writable), // ... }); ``` Each chunk written to the `WritableStream` represents a contiguous chunk of bytes of the output file, `data`, that is expected to be written at the given byte offset, `position`. The `WritableStream` will automatically be closed when `finalize` or `cancel` are called on the `Output`. ::: warning Note that some byte regions in the output file may be written to multiple times. It is therefore **incorrect** to construct the final file by simply concatenating all `Uint8Array`s together - you **must** write each chunk of data at the specified byte offset position *in the order* in which the chunks arrived. If you don't do this, your output file will likely be invalid or corrupted. Some [output formats](./output-formats) have *append-only* writing modes in which the byte offset of a written chunk will always be equal to the total number of bytes in all previously written chunks. In other words, when writing is append-only, simply concatenating all `Uint8Array`s yields the correct result. Some APIs (like `appendBuffer` of Media Source Extensions) require this, so make sure to configure your output format accordingly for those cases. ::: #### Chunked mode By default, data will be emitted by the `StreamTarget` as soon as it is available. In some formats, these may lead to hundreds of write events per second. If you want to reduce the frequency of writes, `StreamTarget` offers an alternative "chunked mode" in which data will first be accumulated into large chunks of a given size in memory, and then only be emitted once a chunk is completely full. ```ts new StreamTarget(writable, { chunked: true, chunkSize: 2 ** 20, // Optional; defaults to 16 MiB }); ``` #### Applying backpressure Sometimes, the `Output` may produce new data faster than you are able to write it. In this case, you want to communicate to the `Output` that it should "chill out" and slow down to match the pace that the `WritableStream` is able to handle. When using `StreamTarget`, the `Output` will automatically respect the backpressure applied by the `WritableStream`. For this, it is useful to understand the [Stream API concepts](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Concepts) of how to apply backpressure. For example, the writable may apply backpressure by returning a promise in `write`: ```ts const writable = new WritableStream({ write(chunk: StreamTargetChunk) { // Pretend writing out data takes 10 milliseconds: return new Promise(resolve => setTimeout(resolve, 10)); } }); ``` ::: info In order for the writable's backpressure to ripple through the entire pipeline, you must make sure to correctly respect the [backpressure applied by media sources](./media-sources#backpressure). ::: #### Usage with the File System API `StreamTargetChunk` is designed such that it is compatible with the File System API's `FileSystemWritableFileStream`. This means, if you want to write data directly to disk, you can simply do something like this: ```ts const handle = await window.showSaveFilePicker(); const writableStream = await handle.createWritable(); const output = new Output({ target: new StreamTarget(writableStream), // ... }); // ... await output.finalize(); // Will automatically close the writable stream ``` ### `AppendOnlyStreamTarget` Similar to a `StreamTarget` but for writing files in a purely append-only way: ```ts import { Output, AppendOnlyStreamTarget } from 'mediabunny'; const writable = new WritableStream({ write(data: Uint8Array) { // Do something with the data... }, }); const output = new Output({ target: new AppendOnlyStreamTarget(writable), // ... }); ``` Useful for consumers that can only read sequentially, like an HTTP server processing an incoming upload. ::: warning The underlying data source doesn't magically become append-only just because you use this source. Instead, you can only use this source when the underlying format is *append-only*. See [Output formats](./output-formats) to see which formats are append-only. ::: ### `FilePathTarget` This target writes to a file at the specified path. It is intended for server-side usage in Node, Bun, or Deno, and offers a simpler API than `StreamTarget` when you just want to write directly to a file path. ```ts import { Output, FilePathTarget } from 'mediabunny'; const output = new Output({ target: new FilePathTarget('/path/to/output.mp4'), // ... }); // ... await output.finalize(); // Will automatically close the file handle ``` The internally held file handle will be closed when `finalize` or `cancel` are called on the `Output`. Writing is chunked by default, for performance. Like `StreamTarget`, you can configure chunked mode options: ```ts new FilePathTarget('/path/to/output.mp4', { chunked: false, // Disable chunking (slower) chunkSize: 2 ** 20, // Optional; defaults to 16 MiB }); ``` ### `NullTarget` This target simply discards all data that is passed into it. It is useful for when you need an `Output` but extract data from it differently, for example through output format-specific callbacks or encoder events. As an example, here we create a fragmented MP4 file and directly handle the individual fragments: ```ts import { Output, NullTarget, Mp4OutputFormat } from 'mediabunny'; let ftyp: Uint8Array; let lastMoof: Uint8Array; const output = new Output({ target: new NullTarget(), format: new Mp4OutputFormat({ fastStart: 'fragmented', onFtyp: (data) => { ftyp = data; }, onMoov: (data) => { const header = new Uint8Array(ftyp.length + data.length); header.set(ftyp, 0); header.set(data, ftyp.length); // Do something with the header... }, onMoof: (data) => { lastMoof = data; }, onMdat: (data) => { const segment = new Uint8Array(lastMoof.length + data.length); segment.set(lastMoof, 0); segment.set(data, lastMoof.length); // Do something with the segment... }, }), }); ``` ## Pathed (multi-file) targets Some output formats write more than one file. For example, an [HLS](./output-formats#hls) output produces a master playlist alongside one or more media playlists and many media segment files. To write this kind of multi-file output, Mediabunny needs a way to resolve the paths it wants to write into [output targets](#output-targets). You can use `PathedTarget` for that. A `PathedTarget` wraps a *root path* (the entry file of the media) together with a callback that produces a `Target` for each requested file path: ```ts import { Output, PathedTarget, FilePathTarget, HlsOutputFormat } from 'mediabunny'; const output = new Output({ format: new HlsOutputFormat({ /* ... */ }), target: new PathedTarget( 'master.m3u8', ({ path, isRoot }) => new FilePathTarget(`/output/${path}`), ), }); ``` The callback is called once per file the format wants to write and receives a `TargetRequest`: ```ts type TargetRequest = { path: FilePath; // The requested file path isRoot: boolean; // Whether the requested file is the root file mimeType: string; // The MIME type of the file being requested }; ``` The kind of `Target` you create inside the callback is up to you - use `FilePathTarget` for files on disk, `StreamTarget` to upload chunks to a server, or any other target type that fits. ## Packet buffering All [output formats](./output-formats) that can hold multiple tracks require *packet buffering* for multi-track outputs. Packet buffering occurs because the `Output` must wait for data from all tracks for a given timestamp to continue writing data, as media data is written to the file in chronological order. For example, should you first encode all your video frames and then encode the audio afterward, the `Output` will have to hold all of the video frames in memory until the audio packets start coming in. This might lead to memory exhaustion should your video be very long. When there is only one media track, this issue does not arise. *** When writing a multi-track output, make sure to add media data in a somewhat interleaved way to keep memory usage low. For example, if you're creating a 5-minute file, add your data in chunks - 10 seconds of video, then 10 seconds of audio, then repeat - instead of first adding all 300 seconds of video followed by all 300 seconds of audio. ::: info If this kind of chunking isn't possible for your use case, try adding the media with the overall smaller data footprint first: First add the 300 seconds of audio, then add the 300 seconds of video. ::: ## Output MIME type Sometimes you may want to retrieve the MIME type of the file created by an `Output`. For example, when working with Media Source Extensions, [`addSourceBuffer`](https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer) requires the file's full MIME type, including codec strings. For this, use the following method: ```ts output.getMimeType(); // => Promise ``` This may resolve to a string like this: ``` video/mp4; codecs="avc1.42c032, mp4a.40.2" ``` ::: warning The promise returned by `getMimeType` only resolves once the precise codec strings for all tracks of the `Output` are known - meaning it potentially needs to wait for all encoders to be fully initialized. Therefore, make sure not to get yourself into a deadlock: Awaiting this method before adding media data to tracks will result in the promise never resolving. ::: If you don't care about specific track codecs, you can instead use the simpler [`mimeType`](./output-formats#output-format-properties) property on the `Output`'s format: ```ts output.format.mimeType; // => string ``` --- --- url: /codec-registry/ulaw.md description: >- μ-law companded PCM audio codec definition, defining legal codec strings, decoder configs, and packet data formats. --- # μ-law PCM codec registration ## Description The μ-law companded PCM audio codec, specified in [ITU-T G.711](https://www.itu.int/rec/T-REC-G.711) Tables 2a and 2b. ## Codec ID ```ts 'ulaw' ``` ## `EncodedPacket` data The packet's data must be a sequence of bytes of arbitrary length (divisible by the channel count), where each byte is 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 'ulaw' ``` ## `AudioDecoderConfig` description `description` is not used for this codec.