Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/Vanilagy/mediabunny/llms.txt

Use this file to discover all available pages before exploring further.

The Conversion class provides a high-level API for converting one media file into another. It supports transcoding, resizing, rotating, trimming, and processing video and audio tracks.

Static methods

Conversion.init()

static async init(options: ConversionOptions): Promise<Conversion>
Initializes a new conversion process without starting the conversion. This method analyzes the input file, determines which tracks can be converted, and prepares the output configuration.
options
ConversionOptions
required
Configuration for the conversion

Properties

input
Input
The input file.
output
Output
The output file.
isValid
boolean
Whether this conversion, as it has been configured, is valid and can be executed. If this field is false, check the discardedTracks field for reasons.
utilizedTracks
InputTrack[]
The list of tracks that are included in the output file.
discardedTracks
DiscardedTrack[]
The list of tracks from the input file that have been discarded, alongside the discard reason.
onProgress
(progress: number) => unknown
A callback that is fired whenever the conversion progresses. Returns a number between 0 and 1, indicating the completion of the conversion. Must be set before execute() is called for progress to be computed.

Methods

execute()

async execute(): Promise<void>
Executes the conversion process. Resolves once conversion is complete. Will throw if isValid is false.

cancel()

async cancel(): Promise<void>
Cancels the conversion process, causing any ongoing execute call to throw a ConversionCanceledError. Does nothing if the conversion is already complete.

Video options

ConversionVideoOptions

discard
boolean
If true, all video tracks will be discarded and will not be present in the output.
width
number
The desired width of the output video in pixels, defaulting to the video’s natural display width. If height is not set, it will be deduced automatically based on aspect ratio.
height
number
The desired height of the output video in pixels, defaulting to the video’s natural display height. If width is not set, it will be deduced automatically based on aspect ratio.
fit
'fill' | 'contain' | 'cover'
The fitting algorithm in case both width and height are set:
  • '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
Rotation
The angle in degrees to rotate the input video by, clockwise. Must be 0, 90, 180, or 270. Rotation is applied before cropping and resizing. This rotation is in addition to the natural rotation of the input video.
allowRotationMetadata
boolean
default:"true"
When enabled, Mediabunny will use the rotation metadata in the output file to perform video rotation whenever possible. Set this field to false if you want to ensure the output file does not make use of rotation metadata.
crop
object
Specifies the rectangular region of the input video to crop to
frameRate
number
The desired frame rate of the output video, in hertz. If not specified, the original input frame rate will be used (which may be variable).
codec
VideoCodec
The desired output video codec.
bitrate
number | Quality
The desired bitrate of the output video.
alpha
'discard' | 'keep'
default:"'discard'"
Whether to discard or keep the transparency information of the input video. Note that for 'keep' to produce a transparent video, you must use an output config that supports it, such as WebM with VP9.
keyFrameInterval
number
default:"5"
The interval, in seconds, of how often frames are encoded as a key frame. Frequent key frames improve seeking behavior but increase file size.
hardwareAcceleration
'no-preference' | 'prefer-hardware' | 'prefer-software'
default:"'no-preference'"
A hint that configures the hardware acceleration method used when transcoding.
forceTranscode
boolean
When true, video will always be re-encoded instead of directly copying over the encoded samples.
process
Function
Allows for custom user-defined processing of video frames, e.g. for applying overlays, color transformations, or timestamp modifications. Will be called for each input video sample after transformations and frame rate corrections.
processedWidth
number
An optional hint specifying the width of video samples returned by the process function, for better encoder configuration.
processedHeight
number
An optional hint specifying the height of video samples returned by the process function, for better encoder configuration.

Audio options

ConversionAudioOptions

discard
boolean
If true, all audio tracks will be discarded and will not be present in the output.
numberOfChannels
number
The desired channel count of the output audio.
sampleRate
number
The desired sample rate of the output audio, in hertz.
codec
AudioCodec
The desired output audio codec.
bitrate
number | Quality
The desired bitrate of the output audio.
forceTranscode
boolean
When true, audio will always be re-encoded instead of directly copying over the encoded samples.
process
Function
Allows for custom user-defined processing of audio samples, e.g. for applying audio effects, transformations, or timestamp modifications. Will be called for each input audio sample after remixing and resampling.
processedNumberOfChannels
number
An optional hint specifying the channel count of audio samples returned by the process function, for better encoder configuration.
processedSampleRate
number
An optional hint specifying the sample rate of audio samples returned by the process function, for better encoder configuration.

Example

import { Conversion, Input, Output, FileSource, StreamTarget } from '@mediabunny/browser';
import { Mp4InputFormat, Mp4OutputFormat } from '@mediabunny/browser';

const input = new Input({
  formats: [Mp4InputFormat],
  source: new FileSource(inputFile)
});

const output = new Output({
  format: Mp4OutputFormat,
  target: new StreamTarget()
});

const conversion = await Conversion.init({
  input,
  output,
  video: {
    width: 1280,
    height: 720,
    fit: 'contain',
    codec: 'avc',
    bitrate: 2_000_000,
    frameRate: 30
  },
  audio: {
    codec: 'aac',
    bitrate: 128_000,
    sampleRate: 48000,
    numberOfChannels: 2
  },
  trim: {
    start: 10,
    end: 60
  },
  tags: (inputTags) => ({
    ...inputTags,
    title: 'Converted Video'
  })
});

if (!conversion.isValid) {
  console.error('Conversion is invalid:', conversion.discardedTracks);
  return;
}

conversion.onProgress = (progress) => {
  console.log(`Progress: ${(progress * 100).toFixed(1)}%`);
};

try {
  await conversion.execute();
  console.log('Conversion complete!');
} catch (error) {
  console.error('Conversion failed:', error);
}

Per-track options

You can provide different options for each track by passing a function instead of an object:
const conversion = await Conversion.init({
  input,
  output,
  video: (track, n) => {
    if (track.number === 1) {
      // Main video track - high quality
      return {
        width: 1920,
        height: 1080,
        bitrate: 5_000_000
      };
    } else {
      // Additional tracks - lower quality
      return {
        width: 1280,
        height: 720,
        bitrate: 2_000_000
      };
    }
  },
  audio: (track, n) => {
    if (track.languageCode === 'eng') {
      return { codec: 'aac', bitrate: 192_000 };
    } else {
      // Discard non-English audio tracks
      return { discard: true };
    }
  }
});

Build docs developers (and LLMs) love