Skip to content

node-av / lib / FormatContext

Class: FormatContext

Defined in: src/lib/format-context.ts:64

Container format context for reading/writing multimedia files.

Central structure for demuxing (reading) and muxing (writing) media files. Manages streams, packets, metadata, and format-specific operations. Supports both file-based and custom I/O through IOContext. Essential for all file-based media operations.

Direct mapping to FFmpeg's AVFormatContext.

Example

typescript
import { FormatContext, FFmpegError } from 'node-av';
import { AVMEDIA_TYPE_VIDEO } from 'node-av/constants';

// Open input file
const ctx = new FormatContext();
let ret = await ctx.openInput('input.mp4');
FFmpegError.throwIfError(ret, 'openInput');

ret = await ctx.findStreamInfo();
FFmpegError.throwIfError(ret, 'findStreamInfo');

// Find video stream
const videoIndex = ctx.findBestStream(AVMEDIA_TYPE_VIDEO);
if (videoIndex < 0) {
  throw new Error('No video stream found');
}

// Read packets
const packet = new Packet();
packet.alloc();
while ((ret = await ctx.readFrame(packet)) >= 0) {
  if (packet.streamIndex === videoIndex) {
    // Process video packet
  }
  packet.unref();
}

// Cleanup
await ctx.closeInput();

See

Extends

Implements

Constructors

Constructor

new FormatContext(): FormatContext

Defined in: src/lib/format-context.ts:68

Returns

FormatContext

Overrides

OptionMember<NativeFormatContext>.constructor

Properties

native

protected native: NativeFormatContext

Defined in: src/lib/option.ts:1030

Inherited from

OptionMember.native

Accessors

bitRate

Get Signature

get bitRate(): bigint

Defined in: src/lib/format-context.ts:120

Total stream bitrate.

Bitrate in bits per second. 0 if unknown.

Direct mapping to AVFormatContext->bit_rate.

Returns

bigint


duration

Get Signature

get duration(): bigint

Defined in: src/lib/format-context.ts:108

Duration of the stream.

Total stream duration in microseconds. AV_NOPTS_VALUE if unknown.

Direct mapping to AVFormatContext->duration.

Returns

bigint


flags

Get Signature

get flags(): AVFormatFlag

Defined in: src/lib/format-context.ts:132

Format-specific flags.

Combination of AVFMT_FLAG_* values controlling format behavior (e.g., AVFMT_FLAG_GENPTS).

Direct mapping to AVFormatContext->flags.

Returns

AVFormatFlag

Set Signature

set flags(value): void

Defined in: src/lib/format-context.ts:136

Parameters
value

AVFormatFlag

Returns

void


iformat

Get Signature

get iformat(): InputFormat | null

Defined in: src/lib/format-context.ts:235

Input format descriptor.

Format used for demuxing. Null for output contexts.

Direct mapping to AVFormatContext->iformat.

Returns

InputFormat | null


maxAnalyzeDuration

Get Signature

get maxAnalyzeDuration(): bigint

Defined in: src/lib/format-context.ts:164

Maximum duration to analyze streams.

Time in microseconds to spend analyzing streams. Larger values improve stream detection accuracy.

Direct mapping to AVFormatContext->max_analyze_duration.

Returns

bigint

Set Signature

set maxAnalyzeDuration(value): void

Defined in: src/lib/format-context.ts:168

Parameters
value

bigint

Returns

void


maxInterleaveDelta

Get Signature

get maxInterleaveDelta(): bigint

Defined in: src/lib/format-context.ts:188

Maximum buffering duration for interleaving.

Specifies the maximum difference between the timestamps of the first and the last packet in the muxing queue, above which libavformat will output a packet regardless of whether it has queued a packet for all the streams.

Set to 0 for unlimited buffering

Default: 10000000 (10 seconds in microseconds)

Muxing only, set before avformat_write_header().

Direct mapping to AVFormatContext->max_interleave_delta.

Returns

bigint

Set Signature

set maxInterleaveDelta(value): void

Defined in: src/lib/format-context.ts:192

Parameters
value

bigint

Returns

void


maxStreams

Get Signature

get maxStreams(): number

Defined in: src/lib/format-context.ts:325

Maximum number of streams.

Limit on stream count for security/resource reasons.

Direct mapping to AVFormatContext->max_streams.

Returns

number

Set Signature

set maxStreams(value): void

Defined in: src/lib/format-context.ts:329

Parameters
value

number

Returns

void


metadata

Get Signature

get metadata(): Dictionary | null

Defined in: src/lib/format-context.ts:203

Container metadata.

Key-value pairs of metadata (title, author, etc.).

Direct mapping to AVFormatContext->metadata.

Returns

Dictionary | null

Set Signature

set metadata(value): void

Defined in: src/lib/format-context.ts:223

Parameters
value

Dictionary | null

Returns

void


nbPrograms

Get Signature

get nbPrograms(): number

Defined in: src/lib/format-context.ts:340

Number of programs.

For containers with multiple programs (e.g., MPEG-TS).

Direct mapping to AVFormatContext->nb_programs.

Returns

number


nbStreams

Get Signature

get nbStreams(): number

Defined in: src/lib/format-context.ts:283

Number of streams in the container.

Direct mapping to AVFormatContext->nb_streams.

Returns

number


oformat

Get Signature

get oformat(): OutputFormat | null

Defined in: src/lib/format-context.ts:250

Output format descriptor.

Format used for muxing. Null for input contexts.

Direct mapping to AVFormatContext->oformat.

Returns

OutputFormat | null

Set Signature

set oformat(value): void

Defined in: src/lib/format-context.ts:258

Parameters
value

OutputFormat | null

Returns

void


pb

Get Signature

get pb(): IOContext | null

Defined in: src/lib/format-context.ts:269

Custom I/O context.

For custom I/O operations instead of file I/O.

Direct mapping to AVFormatContext->pb.

Returns

IOContext | null

Set Signature

set pb(value): void

Defined in: src/lib/format-context.ts:273

Parameters
value

IOContext | null

Returns

void


pbBytes

Get Signature

get pbBytes(): bigint

Defined in: src/lib/format-context.ts:349

Number of bytes read/written through I/O context.

Direct mapping to avio_tell(AVFormatContext->pb).

Returns

bigint


probeScore

Get Signature

get probeScore(): number

Defined in: src/lib/format-context.ts:361

Format probe score.

Confidence score from format detection (0-100). Higher values indicate more confident detection.

Direct mapping to AVFormatContext->probe_score.

Returns

number


probesize

Get Signature

get probesize(): bigint

Defined in: src/lib/format-context.ts:148

Maximum bytes to probe for format detection.

Larger values improve format detection accuracy but increase startup time.

Direct mapping to AVFormatContext->probesize.

Returns

bigint

Set Signature

set probesize(value): void

Defined in: src/lib/format-context.ts:152

Parameters
value

bigint

Returns

void


startTime

Get Signature

get startTime(): bigint

Defined in: src/lib/format-context.ts:96

Start time of the stream.

Position of the first frame in microseconds. AV_NOPTS_VALUE if unknown.

Direct mapping to AVFormatContext->start_time.

Returns

bigint


streams

Get Signature

get streams(): Stream[]

Defined in: src/lib/format-context.ts:294

Array of streams in the container.

All audio, video, subtitle, and data streams.

Direct mapping to AVFormatContext->streams.

Returns

Stream[]


strictStdCompliance

Get Signature

get strictStdCompliance(): number

Defined in: src/lib/format-context.ts:310

Strictness level for standards compliance.

FF_COMPLIANCE_* value controlling how strictly to follow specifications.

Direct mapping to AVFormatContext->strict_std_compliance.

Returns

number

Set Signature

set strictStdCompliance(value): void

Defined in: src/lib/format-context.ts:314

Parameters
value

number

Returns

void


url

Get Signature

get url(): string | null

Defined in: src/lib/format-context.ts:80

URL or filename of the media.

For input: the opened file path. For output: the target file path.

Direct mapping to AVFormatContext->url.

Returns

string | null

Set Signature

set url(value): void

Defined in: src/lib/format-context.ts:84

Parameters
value

string | null

Returns

void

Methods

[asyncDispose]()

[asyncDispose](): Promise<void>

Defined in: src/lib/format-context.ts:1502

Dispose of the format context.

Implements the AsyncDisposable interface for automatic cleanup. Closes input/output and frees resources.

Returns

Promise<void>

Promise that resolves when disposed

Example

typescript
{
  await using ctx = new FormatContext();
  await ctx.openInput('input.mp4');
  // Use context...
} // Automatically closed and freed

Implementation of

AsyncDisposable.[asyncDispose]


allocContext()

allocContext(): void

Defined in: src/lib/format-context.ts:380

Allocate a format context.

Allocates the context structure. Usually not needed as openInput/allocOutputContext2 handle this.

Direct mapping to avformat_alloc_context().

Returns

void

Example

typescript
const ctx = new FormatContext();
ctx.allocContext();
// Context is now allocated

allocOutputContext2()

allocOutputContext2(oformat, formatName, filename): number

Defined in: src/lib/format-context.ts:414

Allocate an output format context.

Allocates and configures context for writing. Format is determined by parameters in priority order.

Direct mapping to avformat_alloc_output_context2().

Parameters

oformat

Specific output format to use

OutputFormat | null

formatName

Format name (e.g., 'mp4', 'mkv')

string | null

filename

Filename to guess format from extension

string | null

Returns

number

0 on success, negative AVERROR on error:

  • AVERROR_ENOMEM: Memory allocation failure
  • AVERROR_EINVAL: Invalid parameters

Example

typescript
import { FFmpegError } from 'node-av';

const ctx = new FormatContext();
const ret = ctx.allocOutputContext2(null, 'mp4', 'output.mp4');
FFmpegError.throwIfError(ret, 'allocOutputContext2');

See


clearFlags()

clearFlags(...flags): void

Defined in: src/lib/format-context.ts:1327

Clear format flags.

Clears one or more flags using bitwise AND NOT. Allows clearing multiple flags without manually performing bitwise operations.

Parameters

flags

...AVFormatFlag[]

One or more flag values to clear

Returns

void

Example

typescript
import { AVFMT_FLAG_IGNIDX } from 'node-av/constants';

// Clear specific flag
formatContext.clearFlags(AVFMT_FLAG_IGNIDX);

See


closeInput()

closeInput(): Promise<void>

Defined in: src/lib/format-context.ts:622

Close an input format context.

Closes input file and releases resources.

Direct mapping to avformat_close_input().

Returns

Promise<void>

Promise that resolves when closed

Example

typescript
await ctx.closeInput();
// Input closed and context freed

See

openInput To open input


closeInputSync()

closeInputSync(): void

Defined in: src/lib/format-context.ts:642

Close an input format context synchronously. Synchronous version of closeInput.

Closes input file and releases resources.

Direct mapping to avformat_close_input().

Returns

void

Example

typescript
ctx.closeInputSync();
// Input closed and context freed

See

closeInput For async version


closeOutput()

closeOutput(): Promise<void>

Defined in: src/lib/format-context.ts:513

Close output file.

Closes the output file and releases I/O resources.

Direct mapping to avio_closep().

Returns

Promise<void>

Promise that resolves when closed

Example

typescript
await ctx.closeOutput();
// Output file closed

See

openOutput To open output


closeOutputSync()

closeOutputSync(): void

Defined in: src/lib/format-context.ts:533

Close output file synchronously. Synchronous version of closeOutput.

Closes the output file and releases I/O resources.

Direct mapping to avio_closep().

Returns

void

Example

typescript
ctx.closeOutputSync();
// Output file closed

See

closeOutput For async version


dumpFormat()

dumpFormat(index, url, isOutput): void

Defined in: src/lib/format-context.ts:1185

Print format information.

Dumps human-readable format info to stderr. Useful for debugging.

Direct mapping to av_dump_format().

Parameters

index

number

Stream index to highlight (-1 for none)

url

string

URL to display

isOutput

boolean

True for output format, false for input

Returns

void

Example

typescript
// Dump input format info
ctx.dumpFormat(0, 'input.mp4', false);

// Dump output format info
ctx.dumpFormat(0, 'output.mp4', true);

findBestStream()

Call Signature

findBestStream(type, wantedStreamNb?, relatedStream?): number

Defined in: src/lib/format-context.ts:1219

Find the best stream of a given type.

Selects the most suitable stream (e.g., default audio/video).

Direct mapping to av_find_best_stream().

Parameters
type

AVMediaType

Media type to find (AVMEDIA_TYPE_*)

wantedStreamNb?

number

Preferred stream index (-1 for auto)

relatedStream?

number

Related stream for audio/video sync (-1 for none)

Returns

number

Stream index, or negative AVERROR if not found

Example
typescript
import { AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO } from 'node-av/constants';

const videoIndex = ctx.findBestStream(AVMEDIA_TYPE_VIDEO);
if (videoIndex >= 0) {
  console.log(`Best video stream: ${videoIndex}`);
}

const audioIndex = ctx.findBestStream(AVMEDIA_TYPE_AUDIO);
if (audioIndex >= 0) {
  console.log(`Best audio stream: ${audioIndex}`);
}

Call Signature

findBestStream(type, wantedStreamNb, relatedStream, wantDecoder, flags?): object

Defined in: src/lib/format-context.ts:1235

Find the best stream and its decoder.

Parameters
type

AVMediaType

Media type to find

wantedStreamNb

number

Preferred stream index

relatedStream

number

Related stream index

wantDecoder

true

True to also find decoder

flags?

number

Reserved flags

Returns

object

Object with stream index and decoder

decoder

decoder: Codec | null

streamIndex

streamIndex: number


findStreamInfo()

findStreamInfo(options): Promise<number>

Defined in: src/lib/format-context.ts:671

Analyze streams to get stream info.

Reads packet headers to fill in stream information. Should be called after openInput for accurate stream data.

Direct mapping to avformat_find_stream_info().

Parameters

options

Per-stream options array

Dictionary[] | null

Returns

Promise<number>

=0 on success, negative AVERROR on error:

  • AVERROR_EOF: End of file reached
  • AVERROR_ENOMEM: Memory allocation failure

Example

typescript
import { FFmpegError } from 'node-av';

const ret = await ctx.findStreamInfo();
FFmpegError.throwIfError(ret, 'findStreamInfo');
console.log(`Found ${ctx.nbStreams} streams`);

See

openInput Must be called first


findStreamInfoSync()

findStreamInfoSync(options): number

Defined in: src/lib/format-context.ts:701

Analyze streams to get stream info synchronously. Synchronous version of findStreamInfo.

Reads packet headers to fill in stream information. Should be called after openInputSync for accurate stream data.

Direct mapping to avformat_find_stream_info().

Parameters

options

Options dictionary (single, not array for sync version)

Dictionary | null

Returns

number

=0 on success, negative AVERROR on error:

  • AVERROR_EOF: End of file reached
  • AVERROR_ENOMEM: Memory allocation failure

Example

typescript
import { FFmpegError } from 'node-av';

const ret = ctx.findStreamInfoSync();
FFmpegError.throwIfError(ret, 'findStreamInfoSync');
console.log(`Found ${ctx.nbStreams} streams`);

See

findStreamInfo For async version


flush()

flush(): Promise<void>

Defined in: src/lib/format-context.ts:1138

Flush buffered data.

Flushes any buffered packets in muxers.

Direct mapping to avio_flush().

Returns

Promise<void>

Example

typescript
await ctx.flush();
// Buffered data written to output

flushSync()

flushSync(): void

Defined in: src/lib/format-context.ts:1158

Flush buffered data synchronously. Synchronous version of flush.

Flushes any buffered packets in muxers.

Direct mapping to avio_flush().

Returns

void

Example

typescript
ctx.flushSync();
// Buffered data written to output

See

flush For async version


freeContext()

freeContext(): void

Defined in: src/lib/format-context.ts:437

Free the format context.

Releases all resources. The context becomes invalid.

Direct mapping to avformat_free_context().

Returns

void

Example

typescript
ctx.freeContext();
// Context is now invalid

See

Symbol.asyncDispose For automatic cleanup


getNative()

getNative(): NativeFormatContext

Defined in: src/lib/format-context.ts:1481

Internal

Get the underlying native FormatContext object.

Returns

NativeFormatContext

The native FormatContext binding object

Implementation of

NativeWrapper.getNative


getOption()

Get an option value from this object.

Uses the AVOption API to retrieve options.

Direct mapping to av_opt_get* functions.

Param

Option name

Param

Option type (defaults to AV_OPT_TYPE_STRING)

Param

Search flags (default: AV_OPT_SEARCH_CHILDREN)

Example

typescript
import { AV_OPT_TYPE_STRING, AV_OPT_TYPE_RATIONAL, AV_OPT_TYPE_PIXEL_FMT, AV_OPT_TYPE_INT64 } from 'node-av/constants';

// String options (default)
const preset = obj.getOption('preset');
const codec = obj.getOption('codec', AV_OPT_TYPE_STRING);

// Typed options
const framerate = obj.getOption('framerate', AV_OPT_TYPE_RATIONAL); // Returns {num, den}
const pixFmt = obj.getOption('pix_fmt', AV_OPT_TYPE_PIXEL_FMT); // Returns AVPixelFormat
const bitrate = obj.getOption('bitrate', AV_OPT_TYPE_INT64); // Returns bigint

Call Signature

getOption(name, type?, searchFlags?): string | null

Defined in: src/lib/option.ts:1259

Parameters
name

string

type?

AVOptionTypeString

searchFlags?

AVOptionSearchFlags

Returns

string | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): string | null

Defined in: src/lib/option.ts:1260

Parameters
name

string

type

AVOptionTypeColor

searchFlags?

AVOptionSearchFlags

Returns

string | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): number | null

Defined in: src/lib/option.ts:1263

Parameters
name

string

type

AVOptionTypeInt

searchFlags?

AVOptionSearchFlags

Returns

number | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): bigint | null

Defined in: src/lib/option.ts:1264

Parameters
name

string

type

AVOptionTypeInt64

searchFlags?

AVOptionSearchFlags

Returns

bigint | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): number | null

Defined in: src/lib/option.ts:1265

Parameters
name

string

type

AVOptionTypeUint

searchFlags?

AVOptionSearchFlags

Returns

number | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): bigint | null

Defined in: src/lib/option.ts:1266

Parameters
name

string

type

AVOptionTypeUint64

searchFlags?

AVOptionSearchFlags

Returns

bigint | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): number | null

Defined in: src/lib/option.ts:1267

Parameters
name

string

type

AVOptionTypeFlags

searchFlags?

AVOptionSearchFlags

Returns

number | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): boolean | null

Defined in: src/lib/option.ts:1268

Parameters
name

string

type

AVOptionTypeBool

searchFlags?

AVOptionSearchFlags

Returns

boolean | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): number | null

Defined in: src/lib/option.ts:1269

Parameters
name

string

type

AVOptionTypeDuration

searchFlags?

AVOptionSearchFlags

Returns

number | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): number | null

Defined in: src/lib/option.ts:1270

Parameters
name

string

type

AVOptionTypeConst

searchFlags?

AVOptionSearchFlags

Returns

number | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): number | null

Defined in: src/lib/option.ts:1273

Parameters
name

string

type

AVOptionTypeDouble

searchFlags?

AVOptionSearchFlags

Returns

number | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): number | null

Defined in: src/lib/option.ts:1274

Parameters
name

string

type

AVOptionTypeFloat

searchFlags?

AVOptionSearchFlags

Returns

number | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): IRational | null

Defined in: src/lib/option.ts:1277

Parameters
name

string

type

AVOptionTypeRational

searchFlags?

AVOptionSearchFlags

Returns

IRational | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): IRational | null

Defined in: src/lib/option.ts:1278

Parameters
name

string

type

AVOptionTypeVideoRate

searchFlags?

AVOptionSearchFlags

Returns

IRational | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): AVPixelFormat | null

Defined in: src/lib/option.ts:1279

Parameters
name

string

type

AVOptionTypePixelFmt

searchFlags?

AVOptionSearchFlags

Returns

AVPixelFormat | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): AVSampleFormat | null

Defined in: src/lib/option.ts:1280

Parameters
name

string

type

AVOptionTypeSampleFmt

searchFlags?

AVOptionSearchFlags

Returns

AVSampleFormat | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): IDimension | null

Defined in: src/lib/option.ts:1281

Parameters
name

string

type

AVOptionTypeImageSize

searchFlags?

AVOptionSearchFlags

Returns

IDimension | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): ChannelLayout | null

Defined in: src/lib/option.ts:1282

Parameters
name

string

type

AVOptionTypeChLayout

searchFlags?

AVOptionSearchFlags

Returns

ChannelLayout | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): Dictionary | null

Defined in: src/lib/option.ts:1283

Parameters
name

string

type

AVOptionTypeDict

searchFlags?

AVOptionSearchFlags

Returns

Dictionary | null

Inherited from

OptionMember.getOption

Call Signature

getOption(name, type, searchFlags?): string | null

Defined in: src/lib/option.ts:1284

Parameters
name

string

type

AVOptionTypeBinary

searchFlags?

AVOptionSearchFlags

Returns

string | null

Inherited from

OptionMember.getOption


getRTSPStreamInfo()

getRTSPStreamInfo(): RTSPStreamInfo[] | null

Defined in: src/lib/format-context.ts:1393

Get RTSP stream information.

Returns information about all RTSP streams including codec details. Only works with RTSP input contexts.

Returns

RTSPStreamInfo[] | null

Array of stream information objects with codec details, or null if not RTSP

Example

typescript
const ctx = new FormatContext();
await ctx.openInput('rtsp://camera/stream?backchannel=1');

const rtspStreams = ctx.getRTSPStreamInfo();
if (rtspStreams) {
  // Find sendonly stream (backchannel)
  const backchannel = rtspStreams.find(s => s.direction === 'sendonly');
  if (backchannel) {
    console.log(`Transport: ${backchannel.transport}`);
    console.log(`Codec ID: ${backchannel.codecId}`);
    console.log(`MIME Type: ${backchannel.mimeType}`);
    console.log(`Payload Type: ${backchannel.payloadType}`);
    if (backchannel.sampleRate) {
      console.log(`Audio: ${backchannel.sampleRate}Hz, ${backchannel.channels} channels`);
    }
  }
}

hasFlags()

hasFlags(...flags): boolean

Defined in: src/lib/format-context.ts:1355

Check if format context has specific flags.

Tests whether all specified flags are set using bitwise AND.

Parameters

flags

...AVFormatFlag[]

One or more flag values to check

Returns

boolean

true if all specified flags are set, false otherwise

Example

typescript
import { AVFMT_FLAG_GENPTS } from 'node-av/constants';

if (formatContext.hasFlags(AVFMT_FLAG_GENPTS)) {
  console.log('GENPTS flag is set');
}

See


interleavedWriteFrame()

interleavedWriteFrame(pkt): Promise<number>

Defined in: src/lib/format-context.ts:1036

Write packet with automatic interleaving.

Writes packet with proper interleaving for muxing. Preferred method for writing packets.

Direct mapping to av_interleaved_write_frame().

Parameters

pkt

Packet to write (null to flush)

Packet | null

Returns

Promise<number>

0 on success, negative AVERROR on error:

  • AVERROR_EINVAL: Invalid packet
  • AVERROR_EIO: I/O error

Example

typescript
import { FFmpegError } from 'node-av';

// Write with proper interleaving
const ret = await ctx.interleavedWriteFrame(packet);
FFmpegError.throwIfError(ret, 'interleavedWriteFrame');

// Flush buffered packets
await ctx.interleavedWriteFrame(null);

See

writeFrame For direct writing


interleavedWriteFrameSync()

interleavedWriteFrameSync(pkt): number

Defined in: src/lib/format-context.ts:1069

Write packet with automatic interleaving synchronously. Synchronous version of interleavedWriteFrame.

Writes packet with proper interleaving for muxing. Preferred method for writing packets.

Direct mapping to av_interleaved_write_frame().

Parameters

pkt

Packet to write (null to flush)

Packet | null

Returns

number

0 on success, negative AVERROR on error:

  • AVERROR_EINVAL: Invalid parameters
  • AVERROR(EIO): I/O error

Example

typescript
import { FFmpegError } from 'node-av';

// Write packet
const ret = ctx.interleavedWriteFrameSync(packet);
FFmpegError.throwIfError(ret, 'interleavedWriteFrameSync');

// Flush interleaved packets
ctx.interleavedWriteFrameSync(null);

See

interleavedWriteFrame For async version


listOptions()

listOptions(): OptionInfo[]

Defined in: src/lib/option.ts:1400

List all available options for this object.

Uses the AVOption API to enumerate all options. Useful for discovering available settings and their types.

Direct mapping to av_opt_next() iteration.

Returns

OptionInfo[]

Array of option information objects

Example

typescript
const options = obj.listOptions();
for (const opt of options) {
  console.log(`${opt.name}: ${opt.help}`);
  console.log(`  Type: ${opt.type}, Default: ${opt.defaultValue}`);
  console.log(`  Range: ${opt.min} - ${opt.max}`);
}

See

OptionInfo For option metadata structure

Inherited from

OptionMember.listOptions


newStream()

newStream(c): Stream

Defined in: src/lib/format-context.ts:1276

Add a new stream to output context.

Creates a new stream for writing.

Direct mapping to avformat_new_stream().

Parameters

c

Codec for the stream (optional)

Codec | null

Returns

Stream

New stream instance

Example

typescript
import { Codec } from 'node-av';
import { AV_CODEC_ID_H264 } from 'node-av/constants';

const codec = Codec.findEncoder(AV_CODEC_ID_H264);
const stream = ctx.newStream(codec);
stream.id = ctx.nbStreams - 1;

See

Stream For stream configuration


openInput()

openInput(url, fmt, options): Promise<number>

Defined in: src/lib/format-context.ts:567

Open input file for reading.

Opens and probes the input file, detecting format automatically unless specified.

Direct mapping to avformat_open_input().

Parameters

url

string

URL or file path to open

fmt

Force specific input format (null for auto-detect)

InputFormat | null

options

Format-specific options

Dictionary | null

Returns

Promise<number>

0 on success, negative AVERROR on error:

  • AVERROR_ENOENT: File not found
  • AVERROR_INVALIDDATA: Invalid file format
  • AVERROR_EIO: I/O error

Example

typescript
import { FFmpegError } from 'node-av';

const ret = await ctx.openInput('input.mp4');
FFmpegError.throwIfError(ret, 'openInput');

See


openInputSync()

openInputSync(url, fmt, options): number

Defined in: src/lib/format-context.ts:601

Open an input file or URL synchronously. Synchronous version of openInput.

Opens a media file or stream for reading. The format is auto-detected if not specified.

Direct mapping to avformat_open_input().

Parameters

url

string

File path or URL to open

fmt

Force specific format (null for auto-detect)

InputFormat | null

options

Format-specific options

Dictionary | null

Returns

number

0 on success, negative AVERROR on error:

  • AVERROR_EINVAL: Invalid arguments
  • AVERROR(EIO): I/O error
  • AVERROR(ENOMEM): Memory allocation failure

Example

typescript
import { FFmpegError } from 'node-av';

const ret = ctx.openInputSync('input.mp4');
FFmpegError.throwIfError(ret, 'openInputSync');

See

openInput For async version


openOutput()

openOutput(): Promise<number>

Defined in: src/lib/format-context.ts:465

Open output file for writing.

Opens the output file specified in url. Must call allocOutputContext2 first.

Direct mapping to avio_open2().

Returns

Promise<number>

0 on success, negative AVERROR on error:

  • AVERROR_ENOENT: File not found
  • AVERROR_EACCES: Permission denied
  • AVERROR_EIO: I/O error

Example

typescript
import { FFmpegError } from 'node-av';

const ret = await ctx.openOutput();
FFmpegError.throwIfError(ret, 'openOutput');

See


openOutputSync()

openOutputSync(): number

Defined in: src/lib/format-context.ts:492

Open output file synchronously. Synchronous version of openOutput.

Opens output file for writing. I/O context must be set before calling.

Direct mapping to avio_open2().

Returns

number

0 on success, negative AVERROR on error:

  • AVERROR(EIO): I/O error
  • AVERROR(ENOMEM): Memory allocation failure

Example

typescript
import { FFmpegError } from 'node-av';

const ret = ctx.openOutputSync();
FFmpegError.throwIfError(ret, 'openOutputSync');

See

openOutput For async version


readFrame()

readFrame(pkt): Promise<number>

Defined in: src/lib/format-context.ts:741

Read next packet from the input.

Reads and returns the next packet in the stream. Packet must be unreferenced after use.

Direct mapping to av_read_frame().

Parameters

pkt

Packet

Packet to read into

Returns

Promise<number>

0 on success, negative AVERROR on error:

  • AVERROR_EOF: End of file
  • AVERROR_EAGAIN: Temporarily unavailable

Example

typescript
import { FFmpegError } from 'node-av';
import { AVERROR_EOF } from 'node-av';

const packet = new Packet();
packet.alloc();

let ret;
while ((ret = await ctx.readFrame(packet)) >= 0) {
  // Process packet
  console.log(`Stream ${packet.streamIndex}, PTS: ${packet.pts}`);
  packet.unref();
}

if (ret !== AVERROR_EOF) {
  FFmpegError.throwIfError(ret, 'readFrame');
}

See

seekFrame To seek before reading


readFrameSync()

readFrameSync(pkt): number

Defined in: src/lib/format-context.ts:782

Read next packet from the input synchronously. Synchronous version of readFrame.

Reads and returns the next packet in the stream. Packet must be unreferenced after use.

Direct mapping to av_read_frame().

Parameters

pkt

Packet

Packet to read into

Returns

number

0 on success, negative AVERROR on error:

  • AVERROR_EOF: End of file
  • AVERROR_EAGAIN: Temporarily unavailable

Example

typescript
import { FFmpegError } from 'node-av';
import { AVERROR_EOF } from 'node-av';

const packet = new Packet();
packet.alloc();

let ret;
while ((ret = ctx.readFrameSync(packet)) >= 0) {
  // Process packet
  console.log(`Stream ${packet.streamIndex}, PTS: ${packet.pts}`);
  packet.unref();
}

if (ret !== AVERROR_EOF) {
  FFmpegError.throwIfError(ret, 'readFrameSync');
}

See

readFrame For async version


seekFile()

seekFile(streamIndex, minTs, ts, maxTs, flags): Promise<number>

Defined in: src/lib/format-context.ts:891

Seek to timestamp with bounds.

More precise seeking with min/max timestamp bounds.

Direct mapping to avformat_seek_file().

Parameters

streamIndex

number

Stream to seek in (-1 for default)

minTs

bigint

Minimum acceptable timestamp

ts

bigint

Target timestamp

maxTs

bigint

Maximum acceptable timestamp

flags

AVSeekFlag = AVFLAG_NONE

Seek flags

Returns

Promise<number>

=0 on success, negative AVERROR on error

Example

typescript
import { FFmpegError } from 'node-av';

// Seek to 10s with 0.5s tolerance
const target = 10000n;
const ret = await ctx.seekFile(
  -1,
  target - 500n,
  target,
  target + 500n
);
FFmpegError.throwIfError(ret, 'seekFile');

See

seekFrame For simpler seeking


seekFrame()

seekFrame(streamIndex, timestamp, flags): Promise<number>

Defined in: src/lib/format-context.ts:815

Seek to timestamp in stream.

Seeks to the keyframe at or before the given timestamp.

Direct mapping to av_seek_frame().

Parameters

streamIndex

number

Stream to seek in (-1 for default)

timestamp

bigint

Target timestamp in stream time base

flags

AVSeekFlag = AVFLAG_NONE

Seek flags (AVSEEK_FLAG_*)

Returns

Promise<number>

=0 on success, negative AVERROR on error:

  • AVERROR_EINVAL: Invalid parameters
  • AVERROR_EOF: Seek beyond file

Example

typescript
import { FFmpegError } from 'node-av';
import { AVSEEK_FLAG_BACKWARD } from 'node-av/constants';

// Seek to 10 seconds (assuming 1/1000 time base)
const ret = await ctx.seekFrame(videoStreamIndex, 10000n, AVSEEK_FLAG_BACKWARD);
FFmpegError.throwIfError(ret, 'seekFrame');

See

seekFile For more precise seeking


seekFrameSync()

seekFrameSync(streamIndex, timestamp, flags): number

Defined in: src/lib/format-context.ts:851

Seek to timestamp in stream synchronously. Synchronous version of seekFrame.

Seeks to closest keyframe at or before timestamp. Timestamp is in stream timebase units.

Direct mapping to av_seek_frame().

Parameters

streamIndex

number

Stream to seek in (-1 for default)

timestamp

bigint

Target timestamp in stream timebase

flags

AVSeekFlag = AVFLAG_NONE

Seek flags (AVSEEK_FLAG_*)

Returns

number

=0 on success, negative AVERROR on error:

  • AVERROR_EINVAL: Invalid arguments
  • AVERROR(EIO): I/O error

Example

typescript
import { FFmpegError } from 'node-av';
import { AVSEEK_FLAG_BACKWARD } from 'node-av/constants';

// Seek to 10 seconds
const timestamp = 10n * 1000000n; // Assuming microsecond timebase
const ret = ctx.seekFrameSync(-1, timestamp, AVSEEK_FLAG_BACKWARD);
FFmpegError.throwIfError(ret, 'seekFrameSync');

See

seekFrame For async version


sendRTSPPacket()

sendRTSPPacket(streamIndex, rtpData): Promise<number>

Defined in: src/lib/format-context.ts:1431

Send RTP packet to RTSP stream (supports both TCP and UDP)

Automatically handles transport-specific packet formatting:

  • TCP: Sends with interleaved header ($channelId + length + RTP)
  • UDP: Sends raw RTP packet directly to UDP socket

Used for backchannel/talkback audio streaming. Only works with RTSP input contexts.

Parameters

streamIndex

number

RTSP stream index

rtpData

Buffer

Raw RTP packet data (12-byte header + payload)

Returns

Promise<number>

Promise resolving to number of bytes written on success, negative AVERROR on failure

Example

typescript
// Get backchannel stream info
const streams = ctx.getRTSPStreamInfo();
const backchannel = streams.find(s => s.direction === 'sendonly');

if (backchannel) {
  // Send to camera (works with both TCP and UDP)
  const ret = await ctx.sendRTSPPacket(backchannel.streamIndex, rtpPacket);
  if (ret < 0) {
    throw new Error(`Failed to send: ${ret}`);
  }
}

See


sendRTSPPacketSync()

sendRTSPPacketSync(streamIndex, rtpData): number

Defined in: src/lib/format-context.ts:1470

Send RTP packet to RTSP stream (supports both TCP and UDP) synchronously. Synchronous version of sendRTSPPacket.

Automatically handles transport-specific packet formatting:

  • TCP: Sends with interleaved header ($channelId + length + RTP)
  • UDP: Sends raw RTP packet directly to UDP socket

Used for backchannel/talkback audio streaming. Only works with RTSP input contexts.

Parameters

streamIndex

number

RTSP stream index

rtpData

Buffer

Raw RTP packet data (12-byte header + payload)

Returns

number

Number of bytes written on success, negative AVERROR on failure

Example

typescript
// Get backchannel stream info
const streams = ctx.getRTSPStreamInfo();
const backchannel = streams.find(s => s.direction === 'sendonly');

if (backchannel) {
  // Send to camera (works with both TCP and UDP)
  const ret = ctx.sendRTSPPacketSync(backchannel.streamIndex, rtpPacket);
  if (ret < 0) {
    throw new Error(`Failed to send: ${ret}`);
  }
}

See


setFlags()

setFlags(...flags): void

Defined in: src/lib/format-context.ts:1301

Set format flags.

Sets one or more flags using bitwise OR. Allows setting multiple flags without manually performing bitwise operations.

Parameters

flags

...AVFormatFlag[]

One or more flag values to set

Returns

void

Example

typescript
import { AVFMT_FLAG_GENPTS, AVFMT_FLAG_IGNIDX } from 'node-av/constants';

// Set multiple flags at once
formatContext.setFlags(AVFMT_FLAG_GENPTS, AVFMT_FLAG_IGNIDX);

See


setOption()

Set an option on this object.

Uses the AVOption API to set options. Available options depend on the specific object type.

Direct mapping to av_opt_set* functions.

Param

Option name

Param

Option value

Param

Option type (defaults to AV_OPT_TYPE_STRING)

Param

Search flags (default: AV_OPT_SEARCH_CHILDREN)

Example

typescript
import { FFmpegError } from 'node-av';
import { AV_OPT_TYPE_STRING, AV_OPT_TYPE_INT64, AV_OPT_TYPE_RATIONAL, AV_OPT_TYPE_PIXEL_FMT } from 'node-av/constants';

// String options (default)
let ret = obj.setOption('preset', 'fast');
FFmpegError.throwIfError(ret, 'set preset');

ret = obj.setOption('codec', 'h264', AV_OPT_TYPE_STRING);
FFmpegError.throwIfError(ret, 'set codec');

// Integer options
ret = obj.setOption('bitrate', 2000000, AV_OPT_TYPE_INT64);
FFmpegError.throwIfError(ret, 'set bitrate');

ret = obj.setOption('threads', 4, AV_OPT_TYPE_INT);
FFmpegError.throwIfError(ret, 'set threads');

// Complex types with proper types
ret = obj.setOption('framerate', {num: 30, den: 1}, AV_OPT_TYPE_RATIONAL);
FFmpegError.throwIfError(ret, 'set framerate');

ret = obj.setOption('pix_fmt', AV_PIX_FMT_YUV420P, AV_OPT_TYPE_PIXEL_FMT);
FFmpegError.throwIfError(ret, 'set pixel format');

Call Signature

setOption(name, value): number

Defined in: src/lib/option.ts:1037

Parameters
name

string

value

string | number | bigint | boolean | null | undefined

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1038

Parameters
name

string

value

string

type

AVOptionTypeString

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1039

Parameters
name

string

value

string

type

AVOptionTypeColor

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1042

Parameters
name

string

value

number

type

AVOptionTypeInt

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1043

Parameters
name

string

value

bigint

type

AVOptionTypeInt64

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1044

Parameters
name

string

value

number

type

AVOptionTypeUint

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1045

Parameters
name

string

value

bigint

type

AVOptionTypeUint64

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1046

Parameters
name

string

value

number

type

AVOptionTypeFlags

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1047

Parameters
name

string

value

boolean

type

AVOptionTypeBool

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1048

Parameters
name

string

value

number

type

AVOptionTypeDuration

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1049

Parameters
name

string

value

number

type

AVOptionTypeConst

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1052

Parameters
name

string

value

number

type

AVOptionTypeDouble

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1053

Parameters
name

string

value

number

type

AVOptionTypeFloat

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1056

Parameters
name

string

value

IRational

type

AVOptionTypeRational

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1057

Parameters
name

string

value

IRational

type

AVOptionTypeVideoRate

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1058

Parameters
name

string

value

AVPixelFormat

type

AVOptionTypePixelFmt

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1059

Parameters
name

string

value

AVSampleFormat

type

AVOptionTypeSampleFmt

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1060

Parameters
name

string

value

IDimension

type

AVOptionTypeImageSize

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1061

Parameters
name

string

value

number | bigint

type

AVOptionTypeChLayout

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1062

Parameters
name

string

value

Buffer

type

AVOptionTypeBinary

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1063

Parameters
name

string

value

number[]

type

AVOptionTypeBinaryIntArray

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption

Call Signature

setOption(name, value, type, searchFlags?): number

Defined in: src/lib/option.ts:1064

Parameters
name

string

value

Dictionary

type

AVOptionTypeDict

searchFlags?

AVOptionSearchFlags

Returns

number

Inherited from

OptionMember.setOption


writeFrame()

writeFrame(pkt): Promise<number>

Defined in: src/lib/format-context.ts:977

Write packet to output.

Writes a packet directly without interleaving. Caller must handle correct interleaving.

Direct mapping to av_write_frame().

Parameters

pkt

Packet to write (null to flush)

Packet | null

Returns

Promise<number>

0 on success, negative AVERROR on error:

  • AVERROR_EINVAL: Invalid packet
  • AVERROR_EIO: I/O error

Example

typescript
import { FFmpegError } from 'node-av';

const ret = await ctx.writeFrame(packet);
FFmpegError.throwIfError(ret, 'writeFrame');

See

interleavedWriteFrame For automatic interleaving


writeFrameSync()

writeFrameSync(pkt): number

Defined in: src/lib/format-context.ts:1004

Write packet to output synchronously. Synchronous version of writeFrame.

Writes a packet directly without interleaving. Caller must handle correct interleaving.

Direct mapping to av_write_frame().

Parameters

pkt

Packet to write (null to flush)

Packet | null

Returns

number

0 on success, negative AVERROR on error

Example

typescript
import { FFmpegError } from 'node-av';

const ret = ctx.writeFrameSync(packet);
FFmpegError.throwIfError(ret, 'writeFrameSync');

See

writeFrame For async version


writeHeader()

writeHeader(options): Promise<number>

Defined in: src/lib/format-context.ts:921

Write file header.

Writes the file header and initializes output. Must be called before writing packets.

Direct mapping to avformat_write_header().

Parameters

options

Muxer-specific options

Dictionary | null

Returns

Promise<number>

0 on success, negative AVERROR on error:

  • AVERROR_EINVAL: Invalid parameters
  • AVERROR_EIO: I/O error

Example

typescript
import { FFmpegError } from 'node-av';

const ret = await ctx.writeHeader();
FFmpegError.throwIfError(ret, 'writeHeader');
// Now ready to write packets

See


writeHeaderSync()

writeHeaderSync(options): number

Defined in: src/lib/format-context.ts:949

Write file header synchronously. Synchronous version of writeHeader.

Writes format header to output file. Must be called before writing packets.

Direct mapping to avformat_write_header().

Parameters

options

Muxer-specific options

Dictionary | null

Returns

number

0 on success, negative AVERROR on error:

  • AVERROR_EINVAL: Invalid parameters

Example

typescript
import { FFmpegError } from 'node-av';

const ret = ctx.writeHeaderSync();
FFmpegError.throwIfError(ret, 'writeHeaderSync');

See

writeHeader For async version


writeTrailer()

writeTrailer(): Promise<number>

Defined in: src/lib/format-context.ts:1095

Write file trailer.

Finalizes the output file, writing index and metadata. Must be called to properly close output files.

Direct mapping to av_write_trailer().

Returns

Promise<number>

0 on success, negative AVERROR on error:

  • AVERROR_EIO: I/O error

Example

typescript
import { FFmpegError } from 'node-av';

const ret = await ctx.writeTrailer();
FFmpegError.throwIfError(ret, 'writeTrailer');
// File is now finalized

See

writeHeader Must be called first


writeTrailerSync()

writeTrailerSync(): number

Defined in: src/lib/format-context.ts:1121

Write file trailer synchronously. Synchronous version of writeTrailer.

Finalizes the output file, writing index and metadata. Must be called to properly close output files.

Direct mapping to av_write_trailer().

Returns

number

0 on success, negative AVERROR on error

Example

typescript
import { FFmpegError } from 'node-av';

const ret = ctx.writeTrailerSync();
FFmpegError.throwIfError(ret, 'writeTrailerSync');
// File is now finalized

See

writeTrailer For async version