Skip to main content

python-nvidia-codec

A Pythonic library for NVIDIA Video Codec (NVDEC).

The project is still in active development; expect breaking changes.

Requirements

  • Python 3.10+
  • NVIDIA GPU with NVDEC support
  • NVIDIA driver with libnvcuvid.so
  • FFmpeg 9.x (for demuxing)

Installation

pip install nvidia-codec

Or from source:

git clone https://github.com/riaqn/python-nvidia-codec.git
cd python-nvidia-codec
pip install -e .

Usage

Decode all frames

from nvidia_codec.utils import Player
import torch

# Simplest: decode at native resolution
player = Player('/path/to/video.mp4')

for timestamp, frame in player.frames(torch.uint8):
    # frame is a torch tensor on GPU (CHW format)
    print(f'{timestamp}: {frame.shape}')

frames() without start continues from the demuxer's current position; it only begins at the first frame on a freshly opened player. After a screenshot() or a previous frames() pass, pass start=timedelta(0) to decode from the beginning again.

Screenshot (single frame extraction)

from nvidia_codec.utils import Player
from datetime import timedelta
import torch

with Player('/path/to/video.mp4') as player:
    print(f'Duration: {player.duration}')

    # Get frame at 10 seconds (fast keyframe seek by default)
    timestamp, frame = player.screenshot(timedelta(seconds=10), torch.uint8)

    # For precise frame timing, use accurate=True (slower)
    timestamp, frame = player.screenshot(timedelta(seconds=10), torch.uint8, accurate=True)

Advanced: crop, scale, and letterbox in hardware

All post-processing is done by the NVDEC hardware during decoding — no extra GPU passes needed.

from nvidia_codec.utils import Player
import torch

player = Player(
    '/path/to/video.mp4',
    # Crop 100px from left/right, 50px from top/bottom
    cropping=lambda h, w: {'left': 100, 'top': 50, 'right': w - 100, 'bottom': h - 50},
    # Output buffer dimensions
    target_size=lambda h, w: (384, 384),
    # Place frame centered vertically; scaled to fit this rect, black bars outside
    target_rect=lambda h, w: {'left': 0, 'top': 36, 'right': 384, 'bottom': 348},
)

for timestamp, frame in player.frames(torch.float32):
    # frame is [3, 384, 384] with letterboxing
    process(frame)

Supported Codecs

Codec support depends on your GPU:

  • H.264 (AVC)
  • H.265 (HEVC)
  • VP9
  • AV1 (Ampere+)
  • VC1/WMV3 (older GPUs only, removed in Turing)

Why another Python library for NVIDIA Codec?

Comparison to Video-Processing-Framework (VPF)

Methodologies: VPF is written fully in C++ and uses pybind to expose Python interfaces. PNC is written fully in Python and uses ctypes to access NVIDIA C interfaces. Our code tends to be more concise, less duplicative and easier to read and write. It also allows better interoperability with other Python libraries.

Performance: Preliminary tests show little to no difference in performance, because the heavy lifting is done on the GPU anyway. Both libraries can saturate the GPU decoder. PNC uses more CPU than VPF as expected from Python vs. C++, but still negligible (less than 10% of Ryzen 3100 single core for 8K×4K HEVC).

Resource Management:

  • In VPF, Surface given to user is not owned by the user. It will be overwritten by new frames which is counter-intuitive. Picture is not exposed to user at all - they are always mapped (post-processed and copied) to Surface so the picture can be ready for new frames. The latter is inefficient when only a subset of Pictures are needed (e.g., screenshots).
  • VPF allocates the bare minimum of resources needed for most decoding tasks. PNC allows the user to specify the amount of resources to be allocated for advanced applications. Users own the resources and decide when and whether to deal with them.
  • Managing resources is not painful: similar to pycuda, we shift the burden of managing host/device resources to the Python garbage collector. Resources (such as Picture and Surface) are automatically freed when the user drops the reference.

Limitations

  • One consumer per Decoder. A Decoder/Player instance serves one frames(), screenshots() or screenshot() call at a time. Use separate instances (from any threads) for concurrent decodes of the same or different files.
  • No mid-stream resolution or codec changes. The NVDEC decoder is created from the first sequence header; a later sequence with a different coded size, chroma format or bit depth raises decoder already initialized with different format. Split such files per segment.
  • Timestamp-less elementary streams (e.g. raw Annex-B .h264/.hevc) carry no pts: frames() yields AV_NOPTS_VALUE for every frame, pts2time returns None, and screenshot() cannot locate a time. Mux into a container first.
  • Embedded cover art (attached_pic streams) is skipped by Player and reported by VideoTrack.attached_pic from parse().

Roadmap

  • Decoding
  • Color Conversion
    • Source Format: NV12, P016, YUV444, YUV444_16Bit
    • Target Format: RGB24, RGB48, RGB444P, RGB444P16
    • Color Ranges: MPEG (limited), JPEG (full)
    • Color Space: BT.601, BT.709, BT.2020
  • Built-in cropping and scaling via NV decoder
  • Thread-friendly (one consumer per decoder; decoders are independent)
  • Encoder
  • PyTorch integration

Acknowledgements

  • Many thanks to @rarzumanyan for all the help and explanations!
  • The blog posts from myMusing are very helpful.

Metadata

Release files for nvidia-codec 0.0.24

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nvidia-codec 0.0.24
File Size Uploaded Provenance Actions
nvidia_codec-0.0.24.tar.gz 55.0 kB Without provenance Details for nvidia_codec-0.0.24.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nvidia-codec 0.0.24
File Interpreter ABI Platform Actions
nvidia_codec-0.0.24-py3-none-any.whl Python 3 none any Details for nvidia_codec-0.0.24-py3-none-any.whl

Total release size: 111.7 kB

Release files / nvidia_codec-0.0.24.tar.gz

Download URL nvidia_codec-0.0.24.tar.gz
Size 55.0 kB
Tags Source
SHA-256 checksum
How to use checksums
71a710f613f9230ac9ebfa1bff6bbfea91ad424f440c6b9683926a6ae7fcd13a
BLAKE2b-256 checksum
How to use checksums
877f8e1260d88b3ea4f2ab825b72e3cdd0a298fb784e01f1168a544cf0d012ba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.8

Release files / nvidia_codec-0.0.24-py3-none-any.whl

Download URL nvidia_codec-0.0.24-py3-none-any.whl
Size 56.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6859103268768c8073f2536b95a6037911dd89bc005874f193334fd8ca1f0338
BLAKE2b-256 checksum
How to use checksums
ec3b8f66fa9cdc6ecbb4ddeb74144207db0ee4dfc78b78dcda3e8776c57b9098
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.8

Security for nvidia-codec 0.0.24

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page