Class: Encoder | NodeAV
Skip to content

node-av / api / Encoder

Class: Encoder

Defined in: src/api/encoder.ts:356

High-level encoder for audio and video streams.

Provides a simplified interface for encoding media frames to packets. Handles codec initialization, hardware acceleration setup, and packet management. Supports both synchronous frame-by-frame encoding and async iteration over packets. Essential component in media processing pipelines for converting raw frames to compressed data.

Examples

typescript
import { Encoder } from 'node-av/api';
import { AV_CODEC_ID_H264, FF_ENCODER_LIBX264 } from 'node-av/constants';

// Create H.264 encoder
const encoder = await Encoder.create(FF_ENCODER_LIBX264, {
  type: 'video',
  width: 1920,
  height: 1080,
  pixelFormat: AV_PIX_FMT_YUV420P,
  timeBase: { num: 1, den: 30 },
  frameRate: { num: 30, den: 1 }
}, {
  bitrate: '5M',
  gopSize: 60
});

// Encode frames
const packet = await encoder.encode(frame);
if (packet) {
  await output.writePacket(packet);
  packet.free();
}
typescript
// Hardware-accelerated encoding with lazy initialization
import { HardwareContext } from 'node-av/api';
import { FF_ENCODER_H264_VIDEOTOOLBOX } from 'node-av/constants';

const hw = HardwareContext.auto();
const encoderCodec = hw?.getEncoderCodec('h264') ?? FF_ENCODER_H264_VIDEOTOOLBOX;
const encoder = await Encoder.create(encoderCodec, {
  timeBase: video.timeBase,
  bitrate: '10M'
});

// Hardware context will be detected from first frame's hw_frames_ctx
for await (const packet of encoder.packets(frames)) {
  await output.writePacket(packet);
  packet.free();
}

See

Implements

  • Disposable

Accessors

codecFlags

Get Signature

get codecFlags(): AVCodecFlag

Defined in: src/api/encoder.ts:808

Codec flags.

Throws

If encoder is closed

Example
typescript
const flags = encoder.codecFlags;
console.log('Current flags:', flags);
See
Returns

AVCodecFlag

Current codec flags


isEncoderInitialized

Get Signature

get isEncoderInitialized(): boolean

Defined in: src/api/encoder.ts:787

Check if encoder has been initialized.

Returns true after first frame has been processed and encoder opened. Useful for checking if encoder has received frame properties.

Example
typescript
if (!encoder.isEncoderInitialized) {
  console.log('Encoder will initialize on first frame');
}
Returns

boolean

true if encoder has been initialized with frame data


isEncoderOpen

Get Signature

get isEncoderOpen(): boolean

Defined in: src/api/encoder.ts:768

Check if encoder is open.

Example
typescript
if (encoder.isEncoderOpen) {
  const packet = await encoder.encode(frame);
}
Returns

boolean

Methods

[dispose]()

[dispose](): void

Defined in: src/api/encoder.ts:2713

Dispose of encoder.

Implements Disposable interface for automatic cleanup. Equivalent to calling close().

Returns

void

Example

typescript
{
  using encoder = await Encoder.create(FF_ENCODER_LIBX264, { ... });
  // Encode frames...
} // Automatically closed

See

close For manual cleanup

Implementation of

Disposable.[dispose]


clearCodecFlags()

clearCodecFlags(...flags): void

Defined in: src/api/encoder.ts:863

Clear codec flags.

Parameters

flags

...AVCodecFlag[]

One or more flag values to clear

Returns

void

Throws

If encoder is already initialized or closed

Example

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

// Clear specific flag before initialization
encoder.clearCodecFlags(AV_CODEC_FLAG_QSCALE);

See


close()

close(): void

Defined in: src/api/encoder.ts:1891

Close encoder and free resources.

Releases codec context and internal packet buffer. Safe to call multiple times. Automatically called by Symbol.dispose.

Returns

void

Example

typescript
const encoder = await Encoder.create(FF_ENCODER_LIBX264, { ... });
try {
  // Use encoder
} finally {
  encoder.close();
}

See

Symbol.dispose For automatic cleanup


encode()

encode(frame): Promise<void>

Defined in: src/api/encoder.ts:992

Send a frame to the encoder.

Sends a raw frame to the encoder for encoding. Does not return encoded packets - use receive to retrieve packets. On first frame, automatically initializes encoder with frame properties. A single frame can produce zero, one, or multiple packets depending on codec buffering.

Important: This method only SENDS the frame to the encoder. You must call receive separately (potentially multiple times) to get encoded packets.

Direct mapping to avcodec_send_frame().

Parameters

frame

Frame | null

Raw frame to send to encoder, or null to flush

Returns

Promise<void>

Throws

If sending frame fails

Examples

typescript
// Send frame and receive packets
await encoder.encode(frame);

// Receive all available packets
while (true) {
  const packet = await encoder.receive();
  if (!packet) break;
  console.log(`Encoded packet with PTS: ${packet.pts}`);
  await output.writePacket(packet);
  packet.free();
}
typescript
for await (const frame of decoder.frames(input.packets())) {
  // Send frame
  await encoder.encode(frame);

  // Receive available packets
  let packet;
  while ((packet = await encoder.receive())) {
    await output.writePacket(packet);
    packet.free();
  }
  frame.free();
}

See


encodeAll()

encodeAll(frame): Promise<Packet[]>

Defined in: src/api/encoder.ts:1163

Encode a frame to packets.

Sends a frame to the encoder and receives all available encoded packets. Returns array of packets - may be empty if encoder needs more data. On first frame, automatically initializes encoder with frame properties. One frame can produce zero, one, or multiple packets depending on codec.

Direct mapping to avcodec_send_frame() and avcodec_receive_packet().

Parameters

frame

Frame | null

Raw frame to encode (or null to flush)

Returns

Promise<Packet[]>

Array of encoded packets (empty if more data needed or encoder is closed)

Throws

If encoding fails

Examples

typescript
const packets = await encoder.encodeAll(frame);
for (const packet of packets) {
  console.log(`Encoded packet with PTS: ${packet.pts}`);
  await output.writePacket(packet);
  packet.free();
}
typescript
// Encode loop
for await (const frame of decoder.frames(input.packets())) {
  const packets = await encoder.encodeAll(frame);
  for (const packet of packets) {
    await output.writePacket(packet);
    packet.free();
  }
  frame.free();
}

See


encodeAllSync()

encodeAllSync(frame): Packet[]

Defined in: src/api/encoder.ts:1222

Encode a frame to packets synchronously. Synchronous version of encodeAll.

Sends a frame to the encoder and receives all available encoded packets. Returns array of packets - may be empty if encoder needs more data. On first frame, automatically initializes encoder with frame properties. One frame can produce zero, one, or multiple packets depending on codec.

Direct mapping to avcodec_send_frame() and avcodec_receive_packet().

Parameters

frame

Frame | null

Raw frame to encode (or null to flush)

Returns

Packet[]

Array of encoded packets (empty if more data needed or encoder is closed)

Throws

If encoding fails

Examples

typescript
const packets = encoder.encodeAllSync(frame);
for (const packet of packets) {
  console.log(`Encoded packet with PTS: ${packet.pts}`);
  output.writePacketSync(packet);
  packet.free();
}
typescript
// Encode loop
for (const frame of decoder.framesSync(packets)) {
  const packets = encoder.encodeAllSync(frame);
  for (const packet of packets) {
    output.writePacketSync(packet);
    packet.free();
  }
  frame.free();
}

See


encodeSync()

encodeSync(frame): void

Defined in: src/api/encoder.ts:1075

Send a frame to the encoder synchronously. Synchronous version of encode.

Sends a raw frame to the encoder for encoding. Does not return encoded packets - use receiveSync to retrieve packets. On first frame, automatically initializes encoder with frame properties. A single frame can produce zero, one, or multiple packets depending on codec buffering.

Important: This method only SENDS the frame to the encoder. You must call receiveSync separately (potentially multiple times) to get encoded packets.

Direct mapping to avcodec_send_frame().

Parameters

frame

Frame | null

Raw frame to send to encoder, or null to flush

Returns

void

Throws

If sending frame fails

Example

typescript
// Send frame and receive packets
encoder.encodeSync(frame);

// Receive all available packets
let packet;
while ((packet = encoder.receiveSync())) {
  console.log(`Encoded packet with PTS: ${packet.pts}`);
  output.writePacketSync(packet);
  packet.free();
}

See


flush()

flush(): Promise<void>

Defined in: src/api/encoder.ts:1471

Flush encoder and signal end-of-stream.

Sends null frame to encoder to signal end-of-stream. Does nothing if encoder was never initialized or is closed. Must call receive() to get remaining buffered packets.

Direct mapping to avcodec_send_frame(NULL).

Returns

Promise<void>

Example

typescript
// Signal end of stream
await encoder.flush();

// Then get remaining packets
let packet;
while ((packet = await encoder.receive()) !== null) {
  console.log('Got buffered packet');
  await output.writePacket(packet);
  packet.free();
}

See


flushPackets()

flushPackets(): AsyncGenerator<Packet>

Defined in: src/api/encoder.ts:1594

Flush all buffered packets as async generator.

Convenient async iteration over remaining packets. Automatically handles flush and repeated receive calls. Returns immediately if encoder was never initialized or is closed.

Returns

AsyncGenerator<Packet>

Yields

Buffered packets

Example

typescript
// Flush at end of encoding
for await (const packet of encoder.flushPackets()) {
  console.log('Processing buffered packet');
  await output.writePacket(packet);
  packet.free();
}

See


flushPacketsSync()

flushPacketsSync(): Generator<Packet>

Defined in: src/api/encoder.ts:1630

Flush all buffered packets as generator synchronously. Synchronous version of flushPackets.

Convenient sync iteration over remaining packets. Automatically handles flush and repeated receive calls. Returns immediately if encoder was never initialized or is closed.

Returns

Generator<Packet>

Yields

Buffered packets

Example

typescript
// Flush at end of encoding
for (const packet of encoder.flushPacketsSync()) {
  console.log('Processing buffered packet');
  output.writePacketSync(packet);
  packet.free();
}

See


flushSync()

flushSync(): void

Defined in: src/api/encoder.ts:1536

Flush encoder and signal end-of-stream synchronously. Synchronous version of flush.

Sends null frame to encoder to signal end-of-stream. Does nothing if encoder was never initialized or is closed. Must call receiveSync() to get remaining buffered packets.

Direct mapping to avcodec_send_frame(NULL).

Returns

void

Example

typescript
// Signal end of stream
encoder.flushSync();

// Then get remaining packets
let packet;
while ((packet = encoder.receiveSync()) !== null) {
  console.log('Got buffered packet');
  output.writePacketSync(packet);
  packet.free();
}

See


getCodec()

getCodec(): Codec

Defined in: src/api/encoder.ts:1936

Internal

Get encoder codec.

Returns the codec used by this encoder. Useful for checking codec capabilities and properties.

Returns

Codec

Codec instance

See

Codec For codec details


getCodecContext()

getCodecContext(): CodecContext | null

Defined in: src/api/encoder.ts:1953

Internal

Get underlying codec context.

Returns the codec context for advanced operations. Useful for accessing low-level codec properties and settings. Returns null if encoder is closed or not initialized.

Returns

CodecContext | null

Codec context or null if closed/not initialized

See

CodecContext For context details


hasCodecFlags()

hasCodecFlags(...flags): boolean

Defined in: src/api/encoder.ts:897

Check if codec has specific flags.

Tests whether all specified codec flags are set using bitwise AND.

Parameters

flags

...AVCodecFlag[]

One or more flag values to check

Returns

boolean

true if all specified flags are set, false otherwise

Throws

If encoder is closed

Example

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

if (encoder.hasCodecFlags(AV_CODEC_FLAG_GLOBAL_HEADER)) {
  console.log('Global header flag is set');
}

See


isHardware()

isHardware(): boolean

Defined in: src/api/encoder.ts:918

Check if encoder uses hardware acceleration.

Returns

boolean

true if hardware-accelerated

Example

typescript
if (encoder.isHardware()) {
  console.log('Using GPU acceleration');
}

See

HardwareContext For hardware setup


isReady()

isReady(): boolean

Defined in: src/api/encoder.ts:934

Check if encoder is ready for processing.

Returns

boolean

true if initialized and ready

Example

typescript
if (encoder.isReady()) {
  const packet = await encoder.encode(frame);
}

packets()

packets(frames): AsyncGenerator<Packet | null>

Defined in: src/api/encoder.ts:1294

Encode frame stream to packet stream.

High-level async generator for complete encoding pipeline. Encoder is only flushed when EOF (null) signal is explicitly received. Primary interface for stream-based encoding.

EOF Handling:

  • Send null to flush encoder and get remaining buffered packets
  • Generator yields null after flushing when null is received
  • No automatic flushing - encoder stays open until EOF or close()

Parameters

frames

Frame | AsyncIterable<Frame | null, any, any> | null

Async iterable of frames, single frame, or null to flush

Returns

AsyncGenerator<Packet | null>

Yields

Encoded packets, followed by null when explicitly flushed

Throws

If encoding fails

Examples

typescript
// Stream of frames with automatic EOF propagation
for await (const packet of encoder.packets(decoder.frames(input.packets()))) {
  if (packet === null) {
    console.log('Encoder flushed');
    break;
  }
  await output.writePacket(packet);
  packet.free(); // Must free output packets
}
typescript
// Single frame - no automatic flush
for await (const packet of encoder.packets(singleFrame)) {
  await output.writePacket(packet);
  packet.free();
}
// Encoder remains open, buffered packets not flushed
typescript
// Explicit flush with EOF
for await (const packet of encoder.packets(null)) {
  if (packet === null) {
    console.log('All buffered packets flushed');
    break;
  }
  console.log('Buffered packet:', packet.pts);
  await output.writePacket(packet);
  packet.free();
}

See


packetsSync()

packetsSync(frames): Generator<Packet | null>

Defined in: src/api/encoder.ts:1396

Encode frame stream to packet stream synchronously. Synchronous version of packets.

High-level sync generator for complete encoding pipeline. Encoder is only flushed when EOF (null) signal is explicitly received. Primary interface for stream-based encoding.

EOF Handling:

  • Send null to flush encoder and get remaining buffered packets
  • Generator yields null after flushing when null is received
  • No automatic flushing - encoder stays open until EOF or close()

Parameters

frames

Frame | Iterable<Frame | null, any, any> | null

Iterable of frames, single frame, or null to flush

Returns

Generator<Packet | null>

Yields

Encoded packets, followed by null when explicitly flushed

Throws

If encoding fails

Examples

typescript
// Stream of frames with automatic EOF propagation
for (const packet of encoder.packetsSync(decoder.framesSync(packets))) {
  if (packet === null) {
    console.log('Encoder flushed');
    break;
  }
  output.writePacketSync(packet);
  packet.free(); // Must free output packets
}
typescript
// Single frame - no automatic flush
for (const packet of encoder.packetsSync(singleFrame)) {
  output.writePacketSync(packet);
  packet.free();
}
// Encoder remains open, buffered packets not flushed
typescript
// Explicit flush with EOF
for (const packet of encoder.packetsSync(null)) {
  if (packet === null) {
    console.log('All buffered packets flushed');
    break;
  }
  console.log('Buffered packet:', packet.pts);
  output.writePacketSync(packet);
  packet.free();
}

See


pipeTo()

pipeTo(target, streamIndex): SchedulerControl<Frame>

Defined in: src/api/encoder.ts:1855

Pipe encoded packets to muxer.

Parameters

target

Muxer

Media output component to write packets to

streamIndex

number

Stream index to write packets to

Returns

SchedulerControl<Frame>

Scheduler for continued chaining

Example

typescript
decoder.pipeTo(filter).pipeTo(encoder)

receive()

receive(): Promise<Packet | null | undefined>

Defined in: src/api/encoder.ts:1694

Receive packet from encoder.

Gets encoded packets from the codec's internal buffer. Handles packet cloning and error checking. Implements FFmpeg's send/receive pattern.

Return Values:

  • Packet - Successfully encoded packet (AVERROR >= 0)
  • null - Need more input frames (AVERROR_EAGAIN), or encoder not initialized
  • undefined - End of stream reached (AVERROR_EOF), or encoder is closed

Direct mapping to avcodec_receive_packet().

Returns

Promise<Packet | null | undefined>

Cloned packet, null if need more data, or undefined if stream ended

Throws

If receive fails with error other than AVERROR_EAGAIN or AVERROR_EOF

Throws

If packet cloning fails (out of memory)

Examples

typescript
// Process all buffered packets
while (true) {
  const packet = await encoder.receive();
  if (!packet) break; // Stop on EAGAIN or EOF
  console.log(`Got packet with PTS: ${packet.pts}`);
  await output.writePacket(packet);
  packet.free();
}
typescript
// Handle each return value explicitly
const packet = await encoder.receive();
if (packet === EOF) {
  console.log('Encoder stream ended');
} else if (packet === null) {
  console.log('Need more input frames');
} else {
  console.log(`Got packet: pts=${packet.pts}`);
  await output.writePacket(packet);
  packet.free();
}

See

  • encode For sending frames and receiving packets
  • flush For signaling end-of-stream
  • receiveSync For synchronous version
  • EOF For end-of-stream signal

receiveSync()

receiveSync(): Packet | null | undefined

Defined in: src/api/encoder.ts:1794

Receive packet from encoder synchronously. Synchronous version of receive.

Gets encoded packets from the codec's internal buffer. Handles packet cloning and error checking. Implements FFmpeg's send/receive pattern.

Return Values:

  • Packet - Successfully encoded packet (AVERROR >= 0)
  • null - Need more input frames (AVERROR_EAGAIN), or encoder not initialized
  • undefined - End of stream reached (AVERROR_EOF), or encoder is closed

Direct mapping to avcodec_receive_packet().

Returns

Packet | null | undefined

Cloned packet, null if need more data, or undefined if stream ended

Throws

If receive fails with error other than AVERROR_EAGAIN or AVERROR_EOF

Throws

If packet cloning fails (out of memory)

Examples

typescript
// Process all buffered packets
while (true) {
  const packet = encoder.receiveSync();
  if (!packet) break; // Stop on EAGAIN or EOF
  console.log(`Got packet with PTS: ${packet.pts}`);
  output.writePacketSync(packet);
  packet.free();
}
typescript
// Handle each return value explicitly
const packet = encoder.receiveSync();
if (packet === EOF) {
  console.log('Encoder stream ended');
} else if (packet === null) {
  console.log('Need more input frames');
} else {
  console.log(`Got packet: pts=${packet.pts}`);
  output.writePacketSync(packet);
  packet.free();
}

See


setCodecFlags()

setCodecFlags(...flags): void

Defined in: src/api/encoder.ts:834

Set codec flags.

Parameters

flags

...AVCodecFlag[]

One or more flag values to set

Returns

void

Throws

If encoder is already initialized or closed

Example

typescript
import { AV_CODEC_FLAG_GLOBAL_HEADER, AV_CODEC_FLAG_QSCALE } from 'node-av/constants';

// Set multiple flags before initialization
encoder.setCodecFlags(AV_CODEC_FLAG_GLOBAL_HEADER, AV_CODEC_FLAG_QSCALE);

See


create()

static create<C>(encoderCodec, options?): Promise<Encoder>

Defined in: src/api/encoder.ts:463

Create an encoder with specified codec and options.

Initializes an encoder with the appropriate codec and configuration. Uses lazy initialization - encoder is opened when first frame is received. Hardware context will be automatically detected from first frame if not provided.

Direct mapping to avcodec_find_encoder_by_name() or avcodec_find_encoder().

Type Parameters

C

C extends AVCodecID | Codec | FFEncoderCodec

Parameters

encoderCodec

C

Codec name, ID, or instance to use for encoding

options?

EncoderOptions<C> = {}

Optional encoder configuration options including required timeBase

Returns

Promise<Encoder>

Configured encoder instance

Throws

If encoder not found

Examples

typescript
// From decoder stream info
const encoder = await Encoder.create(FF_ENCODER_LIBX264, {
  timeBase: video.timeBase,
  bitrate: '5M',
  gopSize: 60,
  options: {
    preset: 'fast',
    crf: '23'
  }
});
typescript
// With custom stream info
const encoder = await Encoder.create(FF_ENCODER_AAC, {
  timeBase: audio.timeBase,
  bitrate: '192k'
});
typescript
// Hardware encoder
const hw = HardwareContext.auto();
const encoderCodec = hw?.getEncoderCodec('h264') ?? FF_ENCODER_H264_VIDEOTOOLBOX;
const encoder = await Encoder.create(encoderCodec, {
  timeBase: video.timeBase,
  bitrate: '8M'
});

See


createSync()

static createSync<C>(encoderCodec, options?): Encoder

Defined in: src/api/encoder.ts:594

Create an encoder with specified codec and options synchronously. Synchronous version of create.

Initializes an encoder with the appropriate codec and configuration. Uses lazy initialization - encoder is opened when first frame is received. Hardware context will be automatically detected from first frame if not provided.

Direct mapping to avcodec_find_encoder_by_name() or avcodec_find_encoder().

Type Parameters

C

C extends AVCodecID | Codec | FFEncoderCodec

Parameters

encoderCodec

C

Codec name, ID, or instance to use for encoding

options?

EncoderOptions<C> = {}

Optional encoder configuration options including required timeBase

Returns

Encoder

Configured encoder instance

Throws

If encoder not found or timeBase not provided

Throws

If codec allocation fails

Examples

typescript
// From decoder stream info
const encoder = await Encoder.create(FF_ENCODER_LIBX264, {
  timeBase: video.timeBase,
  bitrate: '5M',
  gopSize: 60,
  options: {
    preset: 'fast',
    crf: '23'
  }
});
typescript
// With custom stream info
const encoder = await Encoder.create(FF_ENCODER_AAC, {
  timeBase: audio.timeBase,
  bitrate: '192k'
});
typescript
// Hardware encoder
const hw = HardwareContext.auto();
const encoderCodec = hw?.getEncoderCodec('h264') ?? FF_ENCODER_H264_VIDEOTOOLBOX;
const encoder = await Encoder.create(encoderCodec, {
  timeBase: video.timeBase,
  bitrate: '8M'
});

See


encodeOne()

static encodeOne<C>(encoderCodec, frame, options?): Promise<Buffer<ArrayBufferLike>>

Defined in: src/api/encoder.ts:695

Encode a single frame into a self-contained image buffer.

One-shot, stateless helper for intra-only image codecs (MJPEG, PNG, WebP, ...). Creates a fresh encoder, encodes the frame, flushes and frees everything in one call. The encoder adopts dimensions, pixel format and hardware context from the frame, so any frame size works without reconfiguration.

Type Parameters

C

C extends AVCodecID | Codec | FFEncoderCodec

Parameters

encoderCodec

C

Encoder codec (name, ID, branded constant, or Codec)

frame

Frame

Frame to encode

options?

EncoderOptions<C> = {}

Optional encoder configuration (e.g. { options: { q: 3 } } for MJPEG quality)

Returns

Promise<Buffer<ArrayBufferLike>>

Encoded image bytes

Throws

If the encoder is not found or encoding fails

Throws

If the encoder produced no output

Example

typescript
const jpeg = await Encoder.encodeOne(FF_ENCODER_MJPEG, frame, { options: { q: 3 } });

See

EncoderPool For reusing encoders across recurring resolutions


encodeOneSync()

static encodeOneSync<C>(encoderCodec, frame, options?): Buffer

Defined in: src/api/encoder.ts:741

Encode a single frame into a self-contained image buffer synchronously. Synchronous version of encodeOne.

One-shot, stateless helper for intra-only image codecs (MJPEG, PNG, WebP, ...). Creates a fresh encoder, encodes the frame, flushes and frees everything in one call. The encoder adopts dimensions, pixel format and hardware context from the frame, so any frame size works without reconfiguration.

Type Parameters

C

C extends AVCodecID | Codec | FFEncoderCodec

Parameters

encoderCodec

C

Encoder codec (name, ID, branded constant, or Codec)

frame

Frame

Frame to encode

options?

EncoderOptions<C> = {}

Optional encoder configuration (e.g. { options: { q: 3 } } for MJPEG quality)

Returns

Buffer

Encoded image bytes

Throws

If the encoder is not found or encoding fails

Throws

If the encoder produced no output

Example

typescript
const jpeg = Encoder.encodeOneSync(FF_ENCODER_MJPEG, frame, { options: { q: 3 } });

See