Class: FormatContext
Defined in: src/lib/format-context.ts:63
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
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
- AVFormatContext - FFmpeg Doxygen
- InputFormat For supported input formats
- OutputFormat For supported output formats
- Stream For stream management
Extends
Implements
AsyncDisposable
NativeWrapper
<NativeFormatContext
>
Constructors
Constructor
new FormatContext():
FormatContext
Defined in: src/lib/format-context.ts:66
Returns
FormatContext
Overrides
OptionMember<NativeFormatContext>.constructor
Properties
native
protected
native:NativeFormatContext
Defined in: src/lib/option.ts:999
Inherited from
Accessors
bitRate
Get Signature
get bitRate():
bigint
Defined in: src/lib/format-context.ts:118
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:106
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:130
Format-specific flags.
Combination of AVFMT_FLAG_* values controlling format behavior (e.g., AVFMT_FLAG_GENPTS).
Direct mapping to AVFormatContext->flags.
Returns
Set Signature
set flags(
value
):void
Defined in: src/lib/format-context.ts:134
Parameters
value
Returns
void
iformat
Get Signature
get iformat():
null
|InputFormat
Defined in: src/lib/format-context.ts:196
Input format descriptor.
Format used for demuxing. Null for output contexts.
Direct mapping to AVFormatContext->iformat.
Returns
null
| InputFormat
maxAnalyzeDuration
Get Signature
get maxAnalyzeDuration():
bigint
Defined in: src/lib/format-context.ts:162
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:166
Parameters
value
bigint
Returns
void
maxStreams
Get Signature
get maxStreams():
number
Defined in: src/lib/format-context.ts:286
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:290
Parameters
value
number
Returns
void
metadata
Get Signature
get metadata():
null
|Dictionary
Defined in: src/lib/format-context.ts:177
Container metadata.
Key-value pairs of metadata (title, author, etc.).
Direct mapping to AVFormatContext->metadata.
Returns
null
| Dictionary
Set Signature
set metadata(
value
):void
Defined in: src/lib/format-context.ts:185
Parameters
value
null
| Dictionary
Returns
void
nbPrograms
Get Signature
get nbPrograms():
number
Defined in: src/lib/format-context.ts:301
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:244
Number of streams in the container.
Direct mapping to AVFormatContext->nb_streams.
Returns
number
oformat
Get Signature
get oformat():
null
|OutputFormat
Defined in: src/lib/format-context.ts:211
Output format descriptor.
Format used for muxing. Null for input contexts.
Direct mapping to AVFormatContext->oformat.
Returns
null
| OutputFormat
Set Signature
set oformat(
value
):void
Defined in: src/lib/format-context.ts:219
Parameters
value
null
| OutputFormat
Returns
void
pb
Get Signature
get pb():
null
|IOContext
Defined in: src/lib/format-context.ts:230
Custom I/O context.
For custom I/O operations instead of file I/O.
Direct mapping to AVFormatContext->pb.
Returns
null
| IOContext
Set Signature
set pb(
value
):void
Defined in: src/lib/format-context.ts:234
Parameters
value
null
| IOContext
Returns
void
pbBytes
Get Signature
get pbBytes():
bigint
Defined in: src/lib/format-context.ts:310
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:322
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:146
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:150
Parameters
value
bigint
Returns
void
startTime
Get Signature
get startTime():
bigint
Defined in: src/lib/format-context.ts:94
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():
null
|Stream
[]
Defined in: src/lib/format-context.ts:255
Array of streams in the container.
All audio, video, subtitle, and data streams.
Direct mapping to AVFormatContext->streams.
Returns
null
| Stream
[]
strictStdCompliance
Get Signature
get strictStdCompliance():
number
Defined in: src/lib/format-context.ts:271
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:275
Parameters
value
number
Returns
void
url
Get Signature
get url():
null
|string
Defined in: src/lib/format-context.ts:78
URL or filename of the media.
For input: the opened file path. For output: the target file path.
Direct mapping to AVFormatContext->url.
Returns
null
| string
Set Signature
set url(
value
):void
Defined in: src/lib/format-context.ts:82
Parameters
value
null
| string
Returns
void
Methods
[asyncDispose]()
[asyncDispose]():
Promise
<void
>
Defined in: src/lib/format-context.ts:1270
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
{
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:341
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
const ctx = new FormatContext();
ctx.allocContext();
// Context is now allocated
allocOutputContext2()
allocOutputContext2(
oformat
,formatName
,filename
):number
Defined in: src/lib/format-context.ts:375
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
null
| OutputFormat
formatName
Format name (e.g., 'mp4', 'mkv')
null
| string
filename
Filename to guess format from extension
null
| string
Returns
number
0 on success, negative AVERROR on error:
- AVERROR_ENOMEM: Memory allocation failure
- AVERROR_EINVAL: Invalid parameters
Example
import { FFmpegError } from 'node-av';
const ctx = new FormatContext();
const ret = ctx.allocOutputContext2(null, 'mp4', 'output.mp4');
FFmpegError.throwIfError(ret, 'allocOutputContext2');
See
- openOutput To open output file
- writeHeader To write file header
closeInput()
closeInput():
Promise
<void
>
Defined in: src/lib/format-context.ts:583
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
await ctx.closeInput();
// Input closed and context freed
See
openInput To open input
closeInputSync()
closeInputSync():
void
Defined in: src/lib/format-context.ts:603
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
ctx.closeInputSync();
// Input closed and context freed
See
closeInput For async version
closeOutput()
closeOutput():
Promise
<void
>
Defined in: src/lib/format-context.ts:474
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
await ctx.closeOutput();
// Output file closed
See
openOutput To open output
closeOutputSync()
closeOutputSync():
void
Defined in: src/lib/format-context.ts:494
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
ctx.closeOutputSync();
// Output file closed
See
closeOutput For async version
dumpFormat()
dumpFormat(
index
,url
,isOutput
):void
Defined in: src/lib/format-context.ts:1146
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
// 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:1180
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
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
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:1196
Find the best stream and its decoder.
Parameters
type
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:
null
|Codec
streamIndex
streamIndex:
number
findStreamInfo()
findStreamInfo(
options
):Promise
<number
>
Defined in: src/lib/format-context.ts:632
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
null
| Dictionary
[]
Returns
Promise
<number
>
=0 on success, negative AVERROR on error:
- AVERROR_EOF: End of file reached
- AVERROR_ENOMEM: Memory allocation failure
Example
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:662
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)
null
| Dictionary
Returns
number
=0 on success, negative AVERROR on error:
- AVERROR_EOF: End of file reached
- AVERROR_ENOMEM: Memory allocation failure
Example
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:1099
Flush buffered data.
Flushes any buffered packets in muxers.
Direct mapping to avio_flush().
Returns
Promise
<void
>
Example
await ctx.flush();
// Buffered data written to output
flushSync()
flushSync():
void
Defined in: src/lib/format-context.ts:1119
Flush buffered data synchronously. Synchronous version of flush.
Flushes any buffered packets in muxers.
Direct mapping to avio_flush().
Returns
void
Example
ctx.flushSync();
// Buffered data written to output
See
flush For async version
freeContext()
freeContext():
void
Defined in: src/lib/format-context.ts:398
Free the format context.
Releases all resources. The context becomes invalid.
Direct mapping to avformat_free_context().
Returns
void
Example
ctx.freeContext();
// Context is now invalid
See
Symbol.asyncDispose For automatic cleanup
getNative()
getNative():
NativeFormatContext
Defined in: src/lib/format-context.ts:1249
Internal
Get the underlying native FormatContext object.
Returns
The native FormatContext binding object
Implementation of
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
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?
):null
|string
Defined in: src/lib/option.ts:1217
Parameters
name
string
type?
searchFlags?
Returns
null
| string
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|string
Defined in: src/lib/option.ts:1218
Parameters
name
string
type
searchFlags?
Returns
null
| string
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|number
Defined in: src/lib/option.ts:1221
Parameters
name
string
type
searchFlags?
Returns
null
| number
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|bigint
Defined in: src/lib/option.ts:1222
Parameters
name
string
type
searchFlags?
Returns
null
| bigint
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|number
Defined in: src/lib/option.ts:1223
Parameters
name
string
type
searchFlags?
Returns
null
| number
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|bigint
Defined in: src/lib/option.ts:1224
Parameters
name
string
type
searchFlags?
Returns
null
| bigint
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|number
Defined in: src/lib/option.ts:1225
Parameters
name
string
type
searchFlags?
Returns
null
| number
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|boolean
Defined in: src/lib/option.ts:1226
Parameters
name
string
type
searchFlags?
Returns
null
| boolean
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|number
Defined in: src/lib/option.ts:1227
Parameters
name
string
type
searchFlags?
Returns
null
| number
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|number
Defined in: src/lib/option.ts:1228
Parameters
name
string
type
searchFlags?
Returns
null
| number
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|number
Defined in: src/lib/option.ts:1231
Parameters
name
string
type
searchFlags?
Returns
null
| number
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|number
Defined in: src/lib/option.ts:1232
Parameters
name
string
type
searchFlags?
Returns
null
| number
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|IRational
Defined in: src/lib/option.ts:1235
Parameters
name
string
type
searchFlags?
Returns
null
| IRational
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|IRational
Defined in: src/lib/option.ts:1236
Parameters
name
string
type
searchFlags?
Returns
null
| IRational
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|AVPixelFormat
Defined in: src/lib/option.ts:1237
Parameters
name
string
type
searchFlags?
Returns
null
| AVPixelFormat
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|AVSampleFormat
Defined in: src/lib/option.ts:1238
Parameters
name
string
type
searchFlags?
Returns
null
| AVSampleFormat
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
| {height
:number
;width
:number
; }
Defined in: src/lib/option.ts:1239
Parameters
name
string
type
searchFlags?
Returns
null
| { height
: number
; width
: number
; }
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|ChannelLayout
Defined in: src/lib/option.ts:1240
Parameters
name
string
type
searchFlags?
Returns
null
| ChannelLayout
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|Dictionary
Defined in: src/lib/option.ts:1241
Parameters
name
string
type
searchFlags?
Returns
null
| Dictionary
Inherited from
Call Signature
getOption(
name
,type
,searchFlags?
):null
|string
Defined in: src/lib/option.ts:1242
Parameters
name
string
type
searchFlags?
Returns
null
| string
Inherited from
interleavedWriteFrame()
interleavedWriteFrame(
pkt
):Promise
<number
>
Defined in: src/lib/format-context.ts:997
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)
null
| Packet
Returns
Promise
<number
>
0 on success, negative AVERROR on error:
- AVERROR_EINVAL: Invalid packet
- AVERROR_EIO: I/O error
Example
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:1030
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)
null
| Packet
Returns
number
0 on success, negative AVERROR on error:
- AVERROR_EINVAL: Invalid parameters
- AVERROR(EIO): I/O error
Example
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:1358
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
Array of option information objects
Example
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
newStream()
newStream(
c
):Stream
Defined in: src/lib/format-context.ts:1237
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)
null
| Codec
Returns
New stream instance
Example
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:528
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)
null
| InputFormat
options
Format-specific options
null
| Dictionary
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
import { FFmpegError } from 'node-av';
const ret = await ctx.openInput('input.mp4');
FFmpegError.throwIfError(ret, 'openInput');
See
- findStreamInfo To analyze streams after opening
- closeInput To close input
openInputSync()
openInputSync(
url
,fmt
,options
):number
Defined in: src/lib/format-context.ts:562
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)
null
| InputFormat
options
Format-specific options
null
| Dictionary
Returns
number
0 on success, negative AVERROR on error:
- AVERROR_EINVAL: Invalid arguments
- AVERROR(EIO): I/O error
- AVERROR(ENOMEM): Memory allocation failure
Example
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:426
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
import { FFmpegError } from 'node-av';
const ret = await ctx.openOutput();
FFmpegError.throwIfError(ret, 'openOutput');
See
- allocOutputContext2 Must be called first
- closeOutput To close output
openOutputSync()
openOutputSync():
number
Defined in: src/lib/format-context.ts:453
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
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:702
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 to read into
Returns
Promise
<number
>
0 on success, negative AVERROR on error:
- AVERROR_EOF: End of file
- AVERROR_EAGAIN: Temporarily unavailable
Example
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:743
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 to read into
Returns
number
0 on success, negative AVERROR on error:
- AVERROR_EOF: End of file
- AVERROR_EAGAIN: Temporarily unavailable
Example
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:852
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
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:776
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
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:812
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
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
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
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
,type?
,searchFlags?
):number
Defined in: src/lib/option.ts:1006
Parameters
name
string
value
string
type?
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1007
Parameters
name
string
value
string
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1010
Parameters
name
string
value
number
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1011
Parameters
name
string
value
bigint
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1012
Parameters
name
string
value
number
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1013
Parameters
name
string
value
bigint
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1014
Parameters
name
string
value
number
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1015
Parameters
name
string
value
boolean
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1016
Parameters
name
string
value
number
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1017
Parameters
name
string
value
number
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1020
Parameters
name
string
value
number
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1021
Parameters
name
string
value
number
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1024
Parameters
name
string
value
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1025
Parameters
name
string
value
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1026
Parameters
name
string
value
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1027
Parameters
name
string
value
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1028
Parameters
name
string
value
height
number
width
number
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1029
Parameters
name
string
value
number
| bigint
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1030
Parameters
name
string
value
Buffer
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1031
Parameters
name
string
value
number
[]
type
searchFlags?
Returns
number
Inherited from
Call Signature
setOption(
name
,value
,type
,searchFlags?
):number
Defined in: src/lib/option.ts:1032
Parameters
name
string
value
type
searchFlags?
Returns
number
Inherited from
writeFrame()
writeFrame(
pkt
):Promise
<number
>
Defined in: src/lib/format-context.ts:938
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)
null
| Packet
Returns
Promise
<number
>
0 on success, negative AVERROR on error:
- AVERROR_EINVAL: Invalid packet
- AVERROR_EIO: I/O error
Example
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:965
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)
null
| Packet
Returns
number
0 on success, negative AVERROR on error
Example
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:882
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
null
| Dictionary
Returns
Promise
<number
>
0 on success, negative AVERROR on error:
- AVERROR_EINVAL: Invalid parameters
- AVERROR_EIO: I/O error
Example
import { FFmpegError } from 'node-av';
const ret = await ctx.writeHeader();
FFmpegError.throwIfError(ret, 'writeHeader');
// Now ready to write packets
See
- writeTrailer To finalize file
- writeFrame To write packets
writeHeaderSync()
writeHeaderSync(
options
):number
Defined in: src/lib/format-context.ts:910
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
null
| Dictionary
Returns
number
0 on success, negative AVERROR on error:
- AVERROR_EINVAL: Invalid parameters
Example
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:1056
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
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:1082
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
import { FFmpegError } from 'node-av';
const ret = ctx.writeTrailerSync();
FFmpegError.throwIfError(ret, 'writeTrailerSync');
// File is now finalized
See
writeTrailer For async version