FFmpeg for video (v2.0)

Updated at:
Copy as MD

1. Overview

The SAIL SDK is compatible with the Nvidia Video Codec SDK, allowing you to directly use FFmpeg plugins like cuvid, nvenc, and libnpp for hardware acceleration without any code modifications. The following FFmpeg versions have been verified:

FFmpeg 8.0

Corresponds to nv-codec-headers 13.0.19.0

Requires Video Codec SDK 13.0 or later

The latest major release, which adds new filters such as pad_cuda.

FFmpeg 7.1.1

Corresponds to nv-codec-headers 12.2.72.0

Requires Video Codec SDK 12.2 or later

The latest official FFmpeg release with a stable software VVC decoder.

FFmpeg 7.0.1

Corresponds to nv-codec-headers 12.2.72.0

Requires Video Codec SDK 12.2 or later

The latest official FFmpeg release, which significantly improves parallel transcoding performance.

FFmpeg 6.1.2

Corresponds to nv-codec-headers 12.1.14.0

Requires Video Codec SDK 12.1 or later

Frameworks like PyAV depend on this version. It is also the most widely used version.

2. Compilation

Clone the code from the SAIL source code release repository. You do not need to apply any additional patches.

FFmpeg: https://github.com/FFmpeg/FFmpeg

nv-codec-headers: https://github.com/FFmpeg/nv-codec-headers

Important

Ensure that the FFmpeg version matches the corresponding nv-codec-headers version.

FFmpeg branch

Community release tag

nv-codec-headers branch

Community release tag

v8.0_release

n8.0

v13.0_release

n13.0.19.0

v7.1_release

n7.1.1

v12.2_release

n12.2.72.0

v7.0_release

n7.0.1

v12.2_release

n12.2.72.0

v6.1_release

n6.1.2

v12.1_release

n12.1.14.0

Before you compile, install the SAIL SDK and run envsetup.sh to configure the SDK environment.

2.1. Prepare FFmpeg source code

  1. FFmpeg 8.0:

    setup_ffmpeg.sh

    # Internal repository URL
    git clone -b v8.0_release git@gitlab.alibaba-inc.com:ppu_open_source/FFmpeg.git
    git clone -b v13.0_release git@gitlab.alibaba-inc.com:ppu_open_source/nv-codec-headers.git
    # External repository URL
    git clone -b v8.0_release git@codeup.aliyun.com:6853d0dd7f2c70c9af4bf48c/FFmpeg.git 
    git clone -b v13.0_release git@codeup.aliyun.com:6853d0dd7f2c70c9af4bf48c/nv-codec-headers.git 
    # FFmpeg open source community URL
    git clone -b n8.0 https://github.com/FFmpeg/FFmpeg.git
    pushd FFmpeg
    git apply ffmpeg8.patch
    popd
    git clone -b n13.0.19.0 https://github.com/FFmpeg/nv-codec-headers.git
    pushd nv-codec-headers
    git apply nvcodec13_0.patch
    popd
  2. FFmpeg 7.1.1:

    setup_ffmpeg.sh

    # Internal repository URL
    git clone -b v7.1_release git@gitlab.alibaba-inc.com:ppu_open_source/FFmpeg.git
    git clone -b v12.2_release git@gitlab.alibaba-inc.com:ppu_open_source/nv-codec-headers.git
    # External repository URL
    git clone -b v7.1_release git@codeup.aliyun.com:6853d0dd7f2c70c9af4bf48c/FFmpeg.git
    git clone -b v12.2_release git@codeup.aliyun.com:6853d0dd7f2c70c9af4bf48c/nv-codec-headers.git
    # FFmpeg open source community URL
    git clone -b n7.1.1 https://github.com/FFmpeg/FFmpeg.git 
    pushd FFmpeg
    git apply ffmpeg7.patch
    popd
    git clone -b n12.2.72.0 https://github.com/FFmpeg/nv-codec-headers.git
    pushd nv-codec-headers
    git apply nvcodec12_2.patch
    popd
  1. FFmpeg 7.0.1:

    setup_ffmpeg.sh

    # Internal repository URL
    git clone -b v7.0_release git@gitlab.alibaba-inc.com:ppu_open_source/FFmpeg.git 
    git clone -b v12.2_release git@gitlab.alibaba-inc.com:ppu_open_source/nv-codec-headers.git 
    # External repository URL
    git clone -b v7.0_release git@codeup.aliyun.com:6853d0dd7f2c70c9af4bf48c/FFmpeg.git 
    git clone -b v12.2_release git@codeup.aliyun.com:6853d0dd7f2c70c9af4bf48c/nv-codec-headers.git 
    # FFmpeg open source community URL
    git clone -b n7.0.1 https://github.com/FFmpeg/FFmpeg.git
    pushd FFmpeg
    git apply ffmpeg7.patch
    popd
    git clone -b n12.2.72.0 https://github.com/FFmpeg/nv-codec-headers.git
    pushd nv-codec-headers
    git apply nvcodec12_2.patch
    popd
  2. FFmpeg 6.1.2:

    setup_ffmpeg.sh

    # Internal repository URL
    git clone -b v6.1_release git@gitlab.alibaba-inc.com:ppu_open_source/FFmpeg.git
    git clone -b v12.1_release git@gitlab.alibaba-inc.com:ppu_open_source/nv-codec-headers.git
    # External repository URL
    git clone -b v6.1_release git@codeup.aliyun.com:6853d0dd7f2c70c9af4bf48c/FFmpeg.git
    git clone -b v12.1_release git@codeup.aliyun.com:6853d0dd7f2c70c9af4bf48c/nv-codec-headers.git
    # FFmpeg open source community URL
    git clone -b n6.1.2 https://github.com/FFmpeg/FFmpeg.git
    pushd FFmpeg
    git apply ffmpeg6.patch
    popd
    git clone -b n12.1.14.0 https://github.com/FFmpeg/nv-codec-headers.git
    pushd nv-codec-headers
    git apply nvcodec12_1.patch
    popd

(Optional) If you download the source code from the FFmpeg open source community, apply the corresponding patch for your FFmpeg version.

Patch List:

FFmpeg patch

nv-codec-headers patch

FFmpeg 8.0

ffmpeg8.patch

nvcodec13_0.patch

FFmpeg 7.1.1

ffmpeg7.patch

nvcodec12_2.patch

FFmpeg 7.0.1

ffmpeg7.patch

nvcodec12_2.patch

FFmpeg 6.1.2

ffmpeg6.patch

nvcodec12_1.patch

2.2. Build FFmpeg

build_ffmpeg.sh:

apt install nasm pkgconf 
apt install libdav1d-dev # On Ubuntu, install via the apt repository or compile from source code. 
                         # Repo: https://code.videolan.org/videolan/dav1d.git
mkdir output
cd ffmpeg
export PKG_CONFIG_PATH=$(pwd)/../nv-codec-headers:$PKG_CONFIG_PATH
./configure --enable-shared \
    --enable-nonfree --enable-gpl \
    --enable-cuvid --enable-nvenc --enable-libnpp --enable-libdav1d --enable-cuda-nvcc \
    --extra-cflags="-I$(pwd)/../nv-codec-headers/include -I$CUDA_HOME/include" \
    --extra-ldflags="-L$CUDA_HOME/lib64" \
    --prefix=$(pwd)/../output
    
make -j16 && make install
Note

The --prefix option specifies the installation directory. If you do not set this option, FFmpeg is installed in the /usr/local directory by default.

After a successful compilation and installation, the bin, include, lib, and share directories are generated in the installation directory. The lib directory contains a pkgconfig directory. To view the version number, run the pkg-config --modversion libavcodec command.

3. Commit history

To ensure compatibility and provide custom features, we have made several commits to the open source FFmpeg and nv-codec-headers code. The changes are listed below in chronological order:

  1. Added support for libnpp filters in CUDA 13.0+: The libnpp filters in the open source FFmpeg community do not currently support CUDA 13.0 or later. They have been adapted for compatibility.

  2. Customized cuvid to support rgb24 format output: This feature leverages hardware decoding for inline color conversion, enabling the FFmpeg cuvid plugin to output the rgb24 format. The following command is an example:

    ffmpeg -hwaccel cuvid -hwaccel_output_format cuda -c:v h264_cuvid -csc rgb24 -i test.mp4 -f rawvideo -
  3. The FFmpeg application supports raw nvdec mode decoding: it converts user nvdec requests into nv cuvid dec requests. This allows existing FFmpeg commands that specify only -hwaccel cuda without -cuvid to decode correctly, eliminating the need to modify higher-level commands.

    ffmpeg -hwaccel cuda -i test.mp4 -frames 10 -y out-dec-h264.yuv
  4. Fixed a potential corruption issue when using the transpose function of the scale_npp filter.

  5. Adapted the code for SAIL SDK compilation: This commit removes definitions of unsupported CUDA runtime APIs from nv-codec-headers to enable a successful compilation.

4. Usage examples

cd ../output
export LD_LIBRARY_PATH=lib:$LD_LIBRARY_PATH

# Test FFmpeg decoding with cuvid
bin/ffmpeg -vcodec h264_cuvid -i 640x360_y8c8.h264 -frames 10 -y out-dec-h264.yuv
bin/ffmpeg -hwaccel cuda -i 640x360_y8c8.mp4 -frames 10 -y out-dec-h264.yuv  # This command requires the patch for raw nvdec mode support.

# Test FFmpeg transcoding with cuvid and nvenc
bin/ffmpeg -hwaccel_output_format cuda -vcodec h264_cuvid -i 640x360_y8c8.h264 -vcodec hevc_nvenc -r 30.0 -b:v 15000000 -preset p4 output.hevc
# Alternatively, if the raw nvdec mode patch is applied, you can use:
bin/ffmpeg -hwaccel cuda -hwaccel_output_format cuda -i 640x360_y8c8.h264 -vcodec hevc_nvenc -r 30.0 -b:v 15000000 -preset p4 output.hevc

# Test FFmpeg transcoding with cuvid and nvenc, with resizing accelerated by NPP
bin/ffmpeg -hwaccel_output_format cuda -vcodec h264_cuvid -i input.h264 -vcodec hevc_nvenc -frames 300 -preset p7 -acodec copy -y output.h265

5. FAQ

Q: What hardware acceleration capabilities does FFmpeg support on this platform?

A: You can use h264_cuvid, hevc_cuvid, av1_cuvid, and vp9_cuvid for hardware decoding. If you require AVS2 support, you can request an additional patch. For hardware encoding, h264_nvenc, hevc_nvenc, and av1_nvenc are supported. Additionally, transpose, color-conversion, and scale_npp operations are accelerated.

Q: What are the current limitations when using FFmpeg?

A: Video decoding does not support raw nvdec mode by default. If you use the FFmpeg application, it includes a customization that enables raw nvdec mode directly. If you are developing by calling the libavcodec API directly, you can refer to the following example (sample.cpp) to enable it:

sample.cpp

#include <iostream>
extern "C"
{
	#include <libavformat/avformat.h>
	#include <libavcodec/avcodec.h>
	#include <libswscale/swscale.h>
}

static enum AVPixelFormat get_hw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) {
    for (const enum AVPixelFormat *p = pix_fmts; *p != -1; p++) {
        if (*p == AV_PIX_FMT_CUDA)
		{
			std::cout<<"receive cuda fmt"<<std::endl;
            return *p;
		}
    }
    return AV_PIX_FMT_NONE;
}

static const char* get_cuvid_decoder_name(AVCodecID codec_id) {
    switch(codec_id) {
        case AV_CODEC_ID_H264:
            return "h264_cuvid";
        case AV_CODEC_ID_HEVC:
            return "hevc_cuvid";
        case AV_CODEC_ID_VP9:
            return "vp9_cuvid";
        case AV_CODEC_ID_AV1:
            return "av1_cuvid";
        default:
            return "";
    }
}

int main(int argc, char** argv) {
    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " <input.hevc>" << std::endl;
        return -1;
    }


    AVFormatContext* fmt_ctx = nullptr;
    if (avformat_open_input(&fmt_ctx, argv[1], nullptr, nullptr) != 0) {
        std::cout << "Could not open input file" << std::endl;
        return -1;
    }

    if (avformat_find_stream_info(fmt_ctx, nullptr) < 0) {
        std::cout << "Could not find stream information" << std::endl;
        avformat_close_input(&fmt_ctx);
        return -1;
    }


    int video_stream_idx = -1;
    AVCodecParameters* codec_params = nullptr;
    for (unsigned int i = 0; i < fmt_ctx->nb_streams; i++) {
        if (fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            video_stream_idx = i;
            codec_params = fmt_ctx->streams[i]->codecpar;
            break;
        }
    }

    if (video_stream_idx == -1) {
        std::cout << "Could not find video stream" << std::endl;
        avformat_close_input(&fmt_ctx);
        return -1;
    }

    AVHWDeviceType type = av_hwdevice_find_type_by_name("cuda");
    if (type == AV_HWDEVICE_TYPE_NONE) {
        std::cout << "Could not support cuda hw" << std::endl;
        avformat_close_input(&fmt_ctx);
        return -1;
    }

    AVBufferRef *hw_device_ctx = NULL;
    int err = av_hwdevice_ctx_create(&hw_device_ctx, type, NULL, NULL, 0);
    if (err < 0) {
        std::cout << "Could not create hw context"<<std::endl;
		avformat_close_input(&fmt_ctx);
		return -1;
    }
	


    const char* cuvid_decoder = get_cuvid_decoder_name(codec_params->codec_id);
    const AVCodec* codec = NULL;
    if (!cuvid_decoder) {
        codec = avcodec_find_decoder(codec_params->codec_id);
    } else {
        codec = avcodec_find_decoder_by_name(cuvid_decoder);
    }
    if (!codec) {
        std::cout << "Unsupported codec!" << std::endl;
        avformat_close_input(&fmt_ctx);
        return -1;
    }


    AVCodecContext* codec_ctx = avcodec_alloc_context3(codec);
    if (avcodec_parameters_to_context(codec_ctx, codec_params) < 0) {
        std::cout << "Could not initialize codec context" << std::endl;
        avcodec_free_context(&codec_ctx);
        avformat_close_input(&fmt_ctx);
        return -1;
    }

    //set buf to hwbuffer
    codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
	
	if (!codec_ctx->hw_device_ctx) {
        std::cout << "Failed to set hardware device context." << std::endl;
        avcodec_free_context(&codec_ctx);
        av_buffer_unref(&hw_device_ctx);
		avformat_close_input(&fmt_ctx);
        return -1;
    }
	codec_ctx->get_format = get_hw_format;


    if (avcodec_open2(codec_ctx, codec, nullptr) < 0) {
        std::cout << "Could not open codec" << std::endl;
        avcodec_free_context(&codec_ctx);
        avformat_close_input(&fmt_ctx);
		av_buffer_unref(&hw_device_ctx);
        return -1;
    }


    AVFrame* frame = av_frame_alloc();
    AVPacket* pkt = av_packet_alloc();

	
	int frame_count = 0;
    while (av_read_frame(fmt_ctx, pkt) >= 0) {
        if (pkt->stream_index == video_stream_idx) {

            int ret = avcodec_send_packet(codec_ctx, pkt);
            if (ret < 0) {
                std::cout << "Error sending packet to decoder" << std::endl;
                break;
            }


            while (ret >= 0) {
                ret = avcodec_receive_frame(codec_ctx, frame);
                if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
                    break;
                } else if (ret < 0) {
                    std::cout << "Error during decoding" << std::endl;
                    break;
                }
				frame_count++;
                std::cout << "Decoded frame " << frame_count << std::endl;
            }
        }
        av_packet_unref(pkt);
    }

    av_frame_free(&frame);
    avcodec_free_context(&codec_ctx);
    avformat_close_input(&fmt_ctx);

    return 0;
}

6. Appendix: FFmpeg ecosystem

6.1. ffmpeg-python

Official website: https://github.com/kkroening/ffmpeg-python

ffmpeg-python constructs and executes an FFmpeg command from your input parameters. Therefore, FFmpeg must be installed in your runtime environment, or the bin and lib directories of your FFmpeg installation must be configured in your system path.

Example:

import ffmpeg
import sys

probe = ffmpeg.probe('input.mp4')
video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)

if video_stream is None or video_stream['codec_name'] is None:
    sys.exit()

out, _ = (
    ffmpeg.input('input.mp4', hwaccel='cuda')
    .output('output.rgb', format='rawvideo', pix_fmt='rgb24')
    .run()
)

ffmpeg-python is essentially a wrapper for FFmpeg commands. In addition to files, it can also process input and output data via pipe: (stdin, stdout). This approach processes data on the CPU while encoding and decoding occur on the GPU, which inevitably requires a data copy. For this reason, this approach is not recommended.

6.2. PyAV

Torchvision supports three backends: PyAV, video_reader, and cuda. The default backend is PyAV. The video_reader backend performs CPU-only encoding and decoding, while the cuda backend uses a GPU decoder. PyAV calls FFmpeg to perform encoding and decoding. Therefore, PyAV relies on the native hardware acceleration capabilities of FFmpeg, and you must compile and install a version of FFmpeg that supports hardware acceleration.

Note

As of this writing, PyAV does not support FFmpeg 7.0. You must compile the FFmpeg 6.1 version as described in the Compilation Guide section.

PyAV official website: https://github.com/PyAV-Org/PyAV

Call path 1: pytorch -> torchvision -> PyAV -> ffmpeg

To enable hardware decoding support, you must modify the Torchvision source code in torchvision/io/video_reader.py:

--- a/torchvision/io/video_reader.py
+++ b/torchvision/io/video_reader.py
@@ -280,6 +280,13 @@ class VideoReader:
         if self.backend == "pyav":
             stream_type = stream.split(":")[0]
             stream_id = 0 if len(stream.split(":")) == 1 else int(stream.split(":")[1])
+            video_stream = self.container.streams.video[stream_id]
+            # Setting up the codec with cuvid
+            if video_stream.codec.name in ('h264', 'hevc', 'av1', 'vp9'):
+                codec_name = f'{video_stream.codec.name}_cuvid'
+            else:
+                codec_name = video_stream.codec.name  # Fallback to software decoding
+            video_stream.codec_context = av.codec.CodecContext.create(codec_name, 'r')
             self.pyav_stream = {stream_type: stream_id}
             self._c = self.container.decode(**self.pyav_stream)

By default, PyAV outputs data in TCHW format.

Hardware encoding is supported without modifying Torchvision code, but you must specify the nvenc codec name in the function call:

from torchvision.io import write_video
# You must explicitly specify the codec name. We currently support h264_nvenc, av1_nvenc, and hevc_nvenc.
write_video(save_path, frames, fps=fps, video_codec="h264_nvenc")

Call path 2: pytorch -> torchaudio -> PyAV -> ffmpeg

Torchaudio also supports PyAV as a backend for hardware decoding. No code changes are needed for Torchaudio, but you must explicitly specify the cuvid decoder name:

import torch
import torchaudio

from torchaudio.io import StreamReader
from torchaudio.utils import ffmpeg_utils

s = StreamReader(src)
# You must explicitly specify the cuvid decoder. We currently support h264_cuvid, av1_cuvid, hevc_cuvid, and vp9_cuvid.
s.add_video_stream(int(s.get_src_stream_info(0).frame_rate), decoder="h264_cuvid")
s.fill_buffer()
(video,) = s.pop_chunks()

Note: You can use torchvision.get_video_backend() to get the current backend and torchvision.set_video_backend("pyav") to set the default backend for torchvision. However, the default installation of torchvision does not support the "cuda" backend. You need to manually compile and install torchvision.

6.3. TorchCodec

Official documentation: https://meta-pytorch.org/torchcodec/stable/index.html

Project repository: https://github.com/pytorch/torchcodec

Call path: pytorch -> torchcodec -> ffmpeg

The SAIL repository provides pip packages for TorchCodec 0.2.1 and 0.4. We recommend installing TorchCodec directly from the SAIL repository.

TorchCodec version compatibility with PyTorch is as follows:

TorchCodec

Torch

Python

main / nightly

main / nightly

>=3.9, <=3.13

0.7

2.8

>=3.9, <=3.13

0.6

2.8

>=3.9, <=3.13

0.5

2.7

>=3.9, <=3.13

0.4

2.7

>=3.9, <=3.13

0.3

2.7

>=3.9, <=3.13

0.2.1

2.6

>=3.9, <=3.13

0.2.0

2.6

>=3.9, <=3.13

0.1.1

2.5

>=3.9, <=3.12

(Optional) The following shows how to compile and install TorchCodec from source:

  1. Install the FFmpeg dependency (FFmpeg 6.1.2 or 7.0.1).

  2. Compile the source code and install the package:

# release_tag: v0.7.0, v0.4.0, or v0.2.1
git clone -b <release_tag> https://github.com/pytorch/torchcodec.git
cd torchcodec/
git apply torchcodec_<release_tag>.patch
ENABLE_CUDA=1 I_CONFIRM_THIS_IS_NOT_A_LICENSE_VIOLATION=1 pip install . --no-build-isolation

The patch files are as follows:

torchcodec_v0.7.0.patch

diff --git a/src/torchcodec/_core/SingleStreamDecoder.cpp b/src/torchcodec/_core/SingleStreamDecoder.cpp
index 865179a..b5788e7 100644
--- a/src/torchcodec/_core/SingleStreamDecoder.cpp
+++ b/src/torchcodec/_core/SingleStreamDecoder.cpp
@@ -27,6 +27,17 @@ int64_t secondsToClosestPts(double seconds, const AVRational& timeBase) {
       std::round(seconds * timeBase.den / timeBase.num));
 }
 
+inline char* find_codec(const char* input) {
+    const char* codecs[] = {"h264", "hevc", "av1", "vp9"};
+    size_t codec_len = sizeof(codecs) / sizeof(codecs[0]);
+    for (size_t i = 0; i < codec_len; ++i) {
+        if (strstr(input, codecs[i])) {
+            return (char*)codecs[i];
+        }
+    }
+    return NULL;
+}
+
 // Some videos aren't properly encoded and do not specify pts values for
 // packets, and thus for frames. Unset values correspond to INT64_MIN. When that
 // happens, we fallback to the dts value which hopefully exists and is correct.
@@ -425,9 +436,22 @@ void SingleStreamDecoder::addStream(
   // addStream() which is supposed to be generic
   if (mediaType == AVMEDIA_TYPE_VIDEO) {
     if (deviceInterface_) {
-      avCodec = makeAVCodecOnlyUseForCallingAVFindBestStream(
-          deviceInterface_->findCodec(streamInfo.stream->codecpar->codec_id)
-              .value_or(avCodec));
+      if (device.type() != torch::kCUDA) {
+        avCodec = makeAVCodecOnlyUseForCallingAVFindBestStream(
+            deviceInterface_->findCodec(streamInfo.stream->codecpar->codec_id)
+                .value_or(avCodec));
+      }
+      else {
+        const char* cuvid_suffix = "_cuvid";
+        char* codec_name = find_codec(avCodec->name);
+        size_t cuvid_length = std::strlen(codec_name) + std::strlen(cuvid_suffix) + 1;
+        char* cuvid_name = new char[cuvid_length];
+        std::strcpy(cuvid_name, codec_name);
+        std::strcat(cuvid_name, cuvid_suffix);
+        avCodec = avcodec_find_decoder_by_name(cuvid_name);
+        delete[] cuvid_name;
+        TORCH_CHECK(avCodec != nullptr);
+      }
     }
   }
 

torchcodec_v0.4.0.patch

diff --git a/src/torchcodec/_core/SingleStreamDecoder.cpp b/src/torchcodec/_core/SingleStreamDecoder.cpp
index b73f703..0222087 100644
--- a/src/torchcodec/_core/SingleStreamDecoder.cpp
+++ b/src/torchcodec/_core/SingleStreamDecoder.cpp
@@ -26,6 +26,17 @@ int64_t secondsToClosestPts(double seconds, const AVRational& timeBase) {
       std::round(seconds * timeBase.den / timeBase.num));
 }
 
+inline char* find_codec(const char* input) {
+    const char* codecs[] = {"h264", "hevc", "av1", "vp9"};
+    size_t codec_len = sizeof(codecs) / sizeof(codecs[0]);
+    for (size_t i = 0; i < codec_len; ++i) {
+        if (strstr(input, codecs[i])) {
+            return (char*)codecs[i];
+        }
+    }
+    return NULL;
+}
+
 // Some videos aren't properly encoded and do not specify pts values for
 // packets, and thus for frames. Unset values correspond to INT64_MIN. When that
 // happens, we fallback to the dts value which hopefully exists and is correct.
@@ -388,9 +399,22 @@ void SingleStreamDecoder::addStream(
   // addStream() which is supposed to be generic
   if (mediaType == AVMEDIA_TYPE_VIDEO) {
     if (deviceInterface_) {
-      avCodec = makeAVCodecOnlyUseForCallingAVFindBestStream(
-          deviceInterface_->findCodec(streamInfo.stream->codecpar->codec_id)
-              .value_or(avCodec));
+      if (device.type() != torch::kCUDA) {
+          avCodec = makeAVCodecOnlyUseForCallingAVFindBestStream(
+              deviceInterface_->findCodec(streamInfo.stream->codecpar->codec_id)
+                  .value_or(avCodec));
+      }
+      else {
+        const char* cuvid_suffix = "_cuvid";
+        char* codec_name = find_codec(avCodec->name);
+        size_t cuvid_length = std::strlen(codec_name) + std::strlen(cuvid_suffix) + 1;
+        char* cuvid_name = new char[cuvid_length];
+        std::strcpy(cuvid_name, codec_name);
+        std::strcat(cuvid_name, cuvid_suffix);
+        avCodec = avcodec_find_decoder_by_name(cuvid_name);
+        delete[] cuvid_name;
+        TORCH_CHECK(avCodec != nullptr);
+      }
     }
   }
 
@@ -417,6 +441,12 @@ void SingleStreamDecoder::addStream(
     throw std::invalid_argument(getFFMPEGErrorStringFromErrorCode(retVal));
   }
 
+  if (device.type() == torch::kCUDA) {
+    codecContext->hw_frames_ctx = av_hwframe_ctx_alloc(codecContext->hw_device_ctx);
+    AVHWFramesContext* hwframe_ctx = (AVHWFramesContext*)codecContext->hw_frames_ctx->data;
+    // in avcodec_open2, cuvid will not set sw_format until sequence callback in avcodec_send_packet()
+    hwframe_ctx->sw_format = codecContext->sw_pix_fmt;
+  }
   codecContext->time_base = streamInfo.stream->time_base;
   containerMetadata_.allStreamMetadata[activeStreamIndex_].codecName =
       std::string(avcodec_get_name(codecContext->codec_id));

torchcodec_v0.2.1.patch

diff --git a/src/torchcodec/decoders/_core/VideoDecoder.cpp b/src/torchcodec/decoders/_core/VideoDecoder.cpp
index 97214ce..c88c581 100644
--- a/src/torchcodec/decoders/_core/VideoDecoder.cpp
+++ b/src/torchcodec/decoders/_core/VideoDecoder.cpp
@@ -40,6 +40,17 @@ int64_t secondsToClosestPts(double seconds, const AVRational& timeBase) {
   return static_cast<int64_t>(std::round(seconds * timeBase.den));
 }
 
+inline char* find_codec(const char* input) {
+    const char* codecs[] = {"h264", "hevc", "av1", "vp9"};
+    size_t codec_len = sizeof(codecs) / sizeof(codecs[0]);
+    for (size_t i = 0; i < codec_len; ++i) {
+        if (strstr(input, codecs[i])) {
+            return (char*)codecs[i];
+        }
+    }
+    return NULL;
+}
+
 std::vector<std::string> splitStringWithDelimiters(
     const std::string& str,
     const std::string& delims) {
@@ -449,9 +460,15 @@ void VideoDecoder::addStream(
   // TODO_CODE_QUALITY it's pretty meh to have a video-specific logic within
   // addStream() which is supposed to be generic
   if (mediaType == AVMEDIA_TYPE_VIDEO && device.type() == torch::kCUDA) {
-    avCodec = makeAVCodecOnlyUseForCallingAVFindBestStream(
-        findCudaCodec(device, streamInfo.stream->codecpar->codec_id)
-            .value_or(avCodec));
+    const char* cuvid_suffix = "_cuvid";
+    char* codec_name = find_codec(avCodec->name);
+    size_t cuvid_length = std::strlen(codec_name) + std::strlen(cuvid_suffix) + 1;
+    char* cuvid_name = new char[cuvid_length];
+    std::strcpy(cuvid_name, codec_name);
+    std::strcat(cuvid_name, cuvid_suffix);
+    avCodec = avcodec_find_decoder_by_name(cuvid_name);
+    delete[] cuvid_name;
+    TORCH_CHECK(avCodec != nullptr);
   }
 
   AVCodecContext* codecContext = avcodec_alloc_context3(avCodec);
@@ -474,6 +491,12 @@ void VideoDecoder::addStream(
     throw std::invalid_argument(getFFMPEGErrorStringFromErrorCode(retVal));
   }
 
+  if (device.type() == torch::kCUDA) {
+    codecContext->hw_frames_ctx = av_hwframe_ctx_alloc(codecContext->hw_device_ctx);
+    AVHWFramesContext* hwframe_ctx = (AVHWFramesContext*)codecContext->hw_frames_ctx->data;
+    // in avcodec_open2, cuvid will not set sw_format until sequence callback in avcodec_send_packet()
+    hwframe_ctx->sw_format = codecContext->sw_pix_fmt;
+  }
   codecContext->time_base = streamInfo.stream->time_base;
   containerMetadata_.allStreamMetadata[activeStreamIndex_].codecName =
       std::string(avcodec_get_name(codecContext->codec_id));

Usage Example:

python sample_torchcodec.py
import torch

print(f"{torch.__version__=}")
print(f"{torch.cuda.is_available()=}")
print(f"{torch.cuda.get_device_properties(0)=}")

import torchcodec
from torchcodec.decoders import VideoDecoder

decoder = VideoDecoder("sample.mp4", device="cuda")
frame = decoder[0]

6.4. imageio-ffmpeg

imageio-ffmpeg is a plugin for imageio that provides a wrapper for FFmpeg. Similar to ffmpeg-python, it constructs and executes an FFmpeg command from your input parameters. This requires FFmpeg to be installed in your runtime environment. We do not recommend using this plugin. The official documentation states: "You should probably use PyAV instead; it is faster and offers more features."

imageio-ffmpeg: https://github.com/imageio/imageio-ffmpeg

Usage Example:

import imageio

video_reader = imageio.get_reader('input.mp4', 'ffmpeg', ffmpeg_params=['-c:v', 'h264_cuvid'])
frame_list = []
for i, frame in enumerate(video_reader):
    frame_list.append(frame)
imageio.mimsave('out.mp4', frame_list)

6.5. Decord

The default installation of Decord is a CPU-only version and does not support hardware acceleration. To enable GPU support, you must compile and install it from source.

Decord depends on FFmpeg, but only for its demuxing capabilities. You do not need to compile a special build of FFmpeg with hardware acceleration enabled.

Older versions of FFmpeg have an issue that can cause a deadlock in Decord. This issue was resolved in FFmpeg 7. To avoid this problem, compile and install FFmpeg 7.0.1 or FFmpeg 7.1.1.

Download Decord:

git clone -b v0.6.0 --depth 1 --recursive https://github.com/dmlc/decord
cd decord
git apply decord_ffmpeg7.patch

The patch updates Decord's FFmpeg dependency from version 4.2 to FFmpeg 7.0.1 or FFmpeg 7.1.1:

decord_ffmpeg7.patch

diff --git a/src/audio/audio_reader.cc b/src/audio/audio_reader.cc
index be706f1..78c62fb 100644
--- a/src/audio/audio_reader.cc
+++ b/src/audio/audio_reader.cc
@@ -128,7 +128,11 @@ namespace decord {
                 pCodecParameters = tempCodecParameters;
                 originalSampleRate = tempCodecParameters->sample_rate;
                 if (targetSampleRate == -1) targetSampleRate = originalSampleRate;
+#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100)
+                numChannels = tempCodecParameters->ch_layout.nb_channels;
+#else
                 numChannels = tempCodecParameters->channels;
+#endif
                 break;
             }
         }
@@ -229,7 +233,11 @@ namespace decord {
         // allocate resample buffer
         float** outBuffer;
         int outLinesize = 0;
+#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100)
+        int outNumChannels = mono ? AV_CH_LAYOUT_MONO : pFrame->ch_layout.nb_channels;
+#else
         int outNumChannels = av_get_channel_layout_nb_channels(mono ? AV_CH_LAYOUT_MONO : pFrame->channel_layout);
+#endif
         numChannels = outNumChannels;
         int outNumSamples = av_rescale_rnd(pFrame->nb_samples,
                                            this->targetSampleRate, pFrame->sample_rate, AV_ROUND_UP);
@@ -281,11 +289,17 @@ namespace decord {
         if (!this->swr) {
             LOG(FATAL) << "ERROR Failed to allocate resample context";
         }
+#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 28, 100)
+        av_channel_layout_default(&pCodecContext->ch_layout, pCodecContext->ch_layout.nb_channels);
+        av_opt_set_chlayout(this->swr, "in_channel_layout",  &pCodecContext->ch_layout, 0);
+        av_opt_set_chlayout(this->swr, "out_channel_layout", &pCodecContext->ch_layout, 0);
+#else
         if (pCodecContext->channel_layout == 0) {
             pCodecContext->channel_layout = av_get_default_channel_layout( pCodecContext->channels );
         }
         av_opt_set_channel_layout(this->swr, "in_channel_layout",  pCodecContext->channel_layout, 0);
         av_opt_set_channel_layout(this->swr, "out_channel_layout", mono ? AV_CH_LAYOUT_MONO : pCodecContext->channel_layout,  0);
+#endif
         av_opt_set_int(this->swr, "in_sample_rate",     pCodecContext->sample_rate,                0);
         av_opt_set_int(this->swr, "out_sample_rate",    this->targetSampleRate,                0);
         av_opt_set_sample_fmt(this->swr, "in_sample_fmt",  pCodecContext->sample_fmt, 0);
diff --git a/src/video/ffmpeg/ffmpeg_common.h b/src/video/ffmpeg/ffmpeg_common.h
index b0b973f..f0f7316 100644
--- a/src/video/ffmpeg/ffmpeg_common.h
+++ b/src/video/ffmpeg/ffmpeg_common.h
@@ -21,6 +21,7 @@
 extern "C" {
 #endif
 #include <libavcodec/avcodec.h>
+#include <libavcodec/bsf.h>
 #include <libavformat/avformat.h>
 #include <libavformat/avio.h>
 #include <libavfilter/avfilter.h>
diff --git a/src/video/nvcodec/cuda_threaded_decoder.cc b/src/video/nvcodec/cuda_threaded_decoder.cc
index 62bc7ee..957a90d 100644
--- a/src/video/nvcodec/cuda_threaded_decoder.cc
+++ b/src/video/nvcodec/cuda_threaded_decoder.cc
@@ -17,7 +17,7 @@ namespace decord {
 namespace cuda {
 using namespace runtime;
 
-CUThreadedDecoder::CUThreadedDecoder(int device_id, AVCodecParameters *codecpar, AVInputFormat *iformat)
+CUThreadedDecoder::CUThreadedDecoder(int device_id, AVCodecParameters *codecpar, const AVInputFormat *iformat)
     : device_id_(device_id), stream_({device_id, false}), device_{}, ctx_{}, parser_{}, decoder_{},
     pkt_queue_{}, frame_queue_{},
     run_(false), frame_count_(0), draining_(false),
@@ -70,7 +70,7 @@ CUThreadedDecoder::CUThreadedDecoder(int device_id, AVCodecParameters *codecpar,
     }
 }
 
-void CUThreadedDecoder::InitBitStreamFilter(AVCodecParameters *codecpar, AVInputFormat *iformat) {
+void CUThreadedDecoder::InitBitStreamFilter(AVCodecParameters *codecpar, const AVInputFormat *iformat) {
     const char* bsf_name = nullptr;
     if (AV_CODEC_ID_H264 == codecpar->codec_id) {
         // H.264
diff --git a/src/video/nvcodec/cuda_threaded_decoder.h b/src/video/nvcodec/cuda_threaded_decoder.h
index d7e6fcd..61958a1 100644
--- a/src/video/nvcodec/cuda_threaded_decoder.h
+++ b/src/video/nvcodec/cuda_threaded_decoder.h
@@ -46,7 +46,7 @@ class CUThreadedDecoder final : public ThreadedDecoderInterface {
     using FrameOrderQueuePtr = std::unique_ptr<FrameOrderQueue>;
 
     public:
-        CUThreadedDecoder(int device_id, AVCodecParameters *codecpar, AVInputFormat *iformat);
+        CUThreadedDecoder(int device_id, AVCodecParameters *codecpar, const AVInputFormat *iformat);
         void SetCodecContext(AVCodecContext *dec_ctx, int width = -1, int height = -1, int rotation = 0);
         bool Initialized() const;
         void Start();
@@ -70,7 +70,7 @@ class CUThreadedDecoder final : public ThreadedDecoderInterface {
         void LaunchThreadImpl();
         void RecordInternalError(std::string message);
         void CheckErrorStatus();
-        void InitBitStreamFilter(AVCodecParameters *codecpar, AVInputFormat *iformat);
+        void InitBitStreamFilter(AVCodecParameters *codecpar, const AVInputFormat *iformat);

         int device_id_;
         CUStream stream_;
diff --git a/src/video/video_reader.cc b/src/video/video_reader.cc
index af4858d..99c9635 100644
--- a/src/video/video_reader.cc
+++ b/src/video/video_reader.cc
@@ -145,7 +145,7 @@ VideoReader::~VideoReader(){

 void VideoReader::SetVideoStream(int stream_nb) {
     if (!fmt_ctx_) return;
-    AVCodec *dec;
+    const AVCodec *dec;
     int st_nb = av_find_best_stream(fmt_ctx_.get(), AVMEDIA_TYPE_VIDEO, stream_nb, -1, &dec, 0);
     // LOG(INFO) << "find best stream: " << st_nb;
     CHECK_GE(st_nb, 0) << "ERROR cannot find video stream with wanted index: " << stream_nb;

Compile Decord:

mkdir build && cd build
cmake .. -DUSE_CUDA=ON -DCMAKE_BUILD_TYPE=Release
make

Install Decord:

cd ../python
python3 setup.py install --user

Usage Example:

import decord
import torch
from decord import gpu, cpu

video_path="input.mp4"
vr = decord.VideoReader(video_path, ctx=gpu(0))
nframes = 40
total_frames = 500
idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
video = vr.get_batch(idx).asnumpy()