Encoder#

Encoder Class#

Encoder Overview#

The Encoder class provides hardware-accelerated video encoding using NVIDIA’s NVENC API. It encodes raw video frames into compressed bitstreams with support for multiple codecs, formats, and encoding configurations.

The Encoder is created using the CreateEncoder function with encoder configuration parameters.

Parameter

Type

Description

width

int

Width of input frames in pixels

height

int

Height of input frames in pixels

format

str

Input surface format (e.g., “NV12”, “YUV444”, “P010”, “ARGB”)

use_cpu_buffer

bool

True for CPU/host memory input, False for GPU/device memory input

gpu_id

int

GPU device ID for encoding (default: 0)

cuda_context

int

CUDA context pointer (default: 0 for automatic)

cuda_stream

int

CUDA stream pointer (default: 0 for automatic)

codec

str

Output codec: “h264”, “hevc”, or “av1” (default: “h264”)

preset

str

Encoding preset: “p1” through “p7” (higher values favor quality over speed)

bitrate

str

Target bitrate (e.g., “5M” for 5 Mbps)

fps

str

Frame rate (e.g., “30”, “60”)

rc

str

Rate control mode: “cbr” (Constant Bitrate), “vbr” (Variable Bitrate), “cqp” (Constant QP)

Supported Input Formats#

The encoder validates format support based on GPU capabilities:

  • Always Supported: NV12, YUV420 (IYUV), ARGB, ABGR

  • YUV444: Requires 4:4:4 encode support

  • P010: Requires 10-bit encode support

  • YUV444_10BIT, YUV444_16BIT: Requires both 4:4:4 and 10-bit encode support

  • NV16: Requires 4:2:2 encode support (Video Codec SDK 13.0+)

  • P210: Requires both 4:2:2 and 10-bit encode support (Video Codec SDK 13.0+)

Use GetEncoderCaps() to query format support for specific codecs and GPUs.

Methods#

Encode(frame)

Encodes a single frame and returns the compressed bitstream.

See Encode for detailed documentation.

EndEncode()

Flushes the encoder pipeline and retrieves any buffered frames.

See EndEncode for detailed documentation.

GetEncodeReconfigureParams()

Retrieves the current encoder reconfiguration parameters including bitrate, rate control mode, frame rate, and VBV buffer settings.

params = encoder.GetEncodeReconfigureParams()

Returns: structEncodeReconfigureParams object with properties:

  • rateControlMode: Current rate control mode

  • multiPass: Multi-pass encoding mode

  • averageBitrate: Average bitrate in bits per second

  • maxBitRate: Maximum bitrate for VBR mode

  • vbvBufferSize: VBV (Video Buffering Verifier) buffer size

  • vbvInitialDelay: VBV initial delay

  • frameRateNum: Frame rate numerator

  • frameRateDen: Frame rate denominator

Reconfigure(params)

Dynamically reconfigures the encoder parameters during encoding.

See Reconfigure for detailed documentation.

Encoder Capabilities#

GetEncoderCaps(codec, gpu_id=0)

Static method to query encoder hardware capabilities for a specific codec and GPU. Returns a dictionary of capability flags.

caps = nvc.GetEncoderCaps(codec="hevc", gpu_id=0)
print(f"Supports 4:4:4: {caps['support_yuv444_encode']}")
print(f"Supports 10-bit: {caps['support_10bit_encode']}")
print(f"Max width: {caps['width_max']}")
print(f"Max height: {caps['height_max']}")

Key Capability Flags:

  • support_yuv444_encode: YUV 4:4:4 format encoding support

  • support_10bit_encode: 10-bit encoding support

  • support_yuv422_encode: YUV 4:2:2 format encoding support (SDK 13.0+)

  • width_max, height_max: Maximum resolution support

  • width_min, height_min: Minimum resolution support

  • support_dyn_bitrate_change: Dynamic bitrate change support

  • support_dyn_res_change: Dynamic resolution change support

  • support_lossless_encode: Lossless encoding mode support

  • num_max_bframes: Maximum number of B-frames supported

  • support_lookahead: Lookahead support for better rate control

  • support_temporal_aq: Temporal adaptive quantization support

Encode#

Encodes a single frame and returns the compressed bitstream.

Description#

The Encode method is the core encoding operation that takes an uncompressed video frame and returns compressed bitstream data. It accepts frames from CPU memory (numpy arrays) or GPU memory (CUDA Array Interface/DLPack objects) and can optionally apply picture flags and SEI messages.

Syntax#

bitstream = encoder.Encode(frame)
bitstream = encoder.Encode(frame, pic_flags)
bitstream = encoder.Encode(frame, pic_flags, sei_messages)

Method Signatures#

Encode(frame) -> bytes

Encode(frame, pic_flags: int) -> bytes

Encode(frame, pic_flags: int, sei_messages: list) -> bytes

Parameters#

Parameter

Type

Description

frame

numpy.ndarray or GPU buffer

Input frame data (numpy array for CPU, CUDA Array Interface object for GPU)

pic_flags

int (optional)

NV_ENC_PIC_FLAGS enumeration value(s) to control encoding behavior

sei_messages

list (optional)

List of SEI (Supplemental Enhancement Information) messages to insert

Available Picture Flags:

  • FORCEINTRA: Force this frame to be encoded as an intra frame

  • FORCEIDR: Force this frame to be encoded as an IDR (Instantaneous Decoder Refresh) frame

  • OUTPUT_SPSPPS: Include SPS/PPS/VPS headers with this frame

  • EOS: Signal end of stream

Returns#

bytes - Encoded bitstream packet(s). May return multiple packets in a single call (e.g., B-frames).

See Also#

CreateEncoder#

Function for creating a hardware-accelerated video encoder.

Syntax#

CreateEncoder(
    width: int,
    height: int,
    fmt: str,
    usecpuinputbuffer: bool,
    **kwargs
) -> Encoder

Parameters#

Required Parameters:

  • width (int) - Width of the input frames in pixels.

  • height (int) - Height of the input frames in pixels.

  • fmt (str) - Input surface format: "NV12", "YUV444", "ARGB", "ABGR", etc.

  • usecpuinputbuffer (bool) - If True, accepts NumPy arrays (host memory). If False, accepts CUDA buffers (device memory).

Optional Keyword Arguments (kwargs):

  • cudacontext (int) - CUDA context handle. Default: 0 (use current context).

  • cudastream (int) - CUDA stream handle. Default: 0 (use default stream).

  • gpu_id (int) - GPU device ordinal. Default: 0.

  • codec (str) - Output codec: "h264", "hevc", or "av1". Default: "h264".

  • preset (str) - Quality/speed tradeoff: "p1" (fastest) to "p7" (best quality). Default: "p4".

  • tuning_info (str) - Optimization target: "high_quality", "low_latency", "ultra_low_latency", "lossless".

  • rc (str) - Rate control mode: "cbr", "vbr", "constqp".

  • bitrate (int/str) - Target bitrate in bits per second.

  • maxbitrate (int/str) - Maximum bitrate (for VBR mode).

  • vbvbufsize (int/str) - VBV buffer size in bits.

  • fps (int) - Target frame rate. Default: 30.

  • gop (int) - GOP (Group of Pictures) length. Default: 30.

  • bf (int) - Number of B-frames. Default: 0.

  • profile (str) - Codec profile (e.g., "main", "high").

  • slice_mode (int) - Slice mode configuration.

  • slice_data (int) - Slice data configuration.

  • num_unit_in_ticks (int) - Timing info: number of units in ticks.

  • timescale (int) - Timing info: timescale value.

Description#

Creates an Encoder instance for hardware-accelerated video encoding using NVIDIA NVENC. The encoder can compress raw frames into various video codecs (H.264, HEVC, AV1).

The function accepts required positional parameters for frame dimensions and format, followed by optional keyword arguments for encoder configuration. Nested parameters like slice and timinginfo are automatically flattened.

Example#

import PyNvVideoCodec as nvc

# Basic encoder with CPU input buffers
encoder = nvc.CreateEncoder(
    width=1920,
    height=1080,
    fmt="NV12",
    usecpuinputbuffer=True,
    codec="h264",
    preset="p4",
    bitrate=5000000
)

# Encoder with GPU input buffers and custom settings
encoder = nvc.CreateEncoder(
    width=3840,
    height=2160,
    fmt="NV12",
    usecpuinputbuffer=False,
    codec="hevc",
    preset="p6",
    tuning_info="high_quality",
    rc="vbr",
    bitrate=25000000,
    maxbitrate=30000000,
    fps=60,
    gop=120
)

Returns#

Encoder object configured with the specified parameters.

See Also#

EndEncode#

Flushes the encoder pipeline and retrieves any buffered frames.

Description#

The EndEncode method signals the end of the encoding session and flushes any frames remaining in the encoder’s internal buffer. This method must be called at the end of encoding to ensure all frames are properly encoded and output.

Syntax#

bitstream = encoder.EndEncode()

Method Signature#

EndEncode() -> bytes

Returns#

bytes - Remaining encoded bitstream packets from the encoder buffer.

See Also#

Reconfigure#

Dynamically reconfigures encoder parameters such as bitrate, rate control mode, and frame rate without recreating the encoder.

Description#

The Reconfigure method allows dynamic adjustment of encoder parameters during an encoding session. This is useful for adaptive bitrate streaming, changing quality targets, or adjusting frame rates based on system conditions.

Syntax#

encoder.Reconfigure(reconfig_params)

Method Signature#

Reconfigure(params: structEncodeReconfigureParams) -> None

Parameters#

params (structEncodeReconfigureParams)

Reconfiguration parameters object with properties:

  • rateControlMode: Rate control mode (CBR, VBR, CQP)

  • averageBitrate: Average bitrate in bits per second

  • maxBitrate: Maximum bitrate for VBR mode

  • vbvBufferSize: VBV buffer size in bits

  • vbvInitialDelay: VBV initial delay in bits

  • frameRateNum: Frame rate numerator

  • frameRateDen: Frame rate denominator

See Also#