ffmpeg avcodec_find_encoder_by_name 找不到编码器 h264_nvenc

ffmpeg avcodec_find_encoder_by_name failes to find encoder h264_nvenc

当我在终端中 运行 这个命令 "ffmpeg -h encoder=h264_nvenc" 它给我以下输出

我可以通过命令行界面使用编码器,但是当我尝试从以下源代码 运行 时出现问题。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>
#include <x264.h>
}

int main( int argc, char** argv )
{

    const AVCodec *codec;
    AVCodecContext *c= NULL;

    av_register_all();

    std::cout << "Loading codec" << std::endl;

//    codec = avcodec_find_encoder_by_name( "libx264" ); // works
    codec = avcodec_find_encoder_by_name( "h264_nvenc" );
   // codec = avcodec_find_decoder_by_name( "h264_cuvid" );
    if( !codec )
    {
        throw std::runtime_error( "Unable to find codec!" );
    }

    std::cout << "Allocating context" << std::endl;

    return 0;

}

您的代码可以在我的系统上运行(找到编码器)。确保您的 ffmpeg 源是最新的并且使用 --enable-nvenc.

配置和编译

更新: 您能否将上面的片段保存为 h264_nvenc.cpp 并使用此命令进行编译:

g++ h264_nvenc.cpp -o h264_nvenc `PKG_CONFIG_PATH=/path/ffmpeg/lib/pkgconfig/ pkg-config --cflags libavformat libswscale libswresample libavutil libavcodec` `PKG_CONFIG_PATH=/path/ffmpeg/lib/pkgconfig/ pkg-config --libs libavformat libswscale libswresample libavutil libavcodec` -std=gnu++11

然后将编译后的文件测试为 ./h264_nvenc

然后您应该会看到:

Loading codec
Allocating context

这里是这个最小示例的清晰 CMakeLists.txt 文件。请注意,如果使用 link_directories( /usr/local/lib ),则库链接不正确,因此我改用 add_library

此外,似乎没有必要包含 nvidia/cuda 库来访问 nvenc 编解码器。

cmake_minimum_required(VERSION 2.8)
project( opencv-test )

include_directories(/usr/local/include)

add_executable( h264_nvenc
  h264_nvenc.cpp 
)

# link_directories( /usr/local/lib ) # does not work

add_library( avformat SHARED IMPORTED )
set_target_properties( avformat PROPERTIES IMPORTED_LOCATION /usr/local/lib/libavformat.so )

add_library( avutil SHARED IMPORTED )
set_target_properties( avutil PROPERTIES IMPORTED_LOCATION /usr/local/lib/libavutil.so )

add_library( avcodec SHARED IMPORTED )
set_target_properties( avcodec PROPERTIES IMPORTED_LOCATION /usr/local/lib/libavcodec.so )

add_library( swscale SHARED IMPORTED )
set_target_properties( swscale PROPERTIES IMPORTED_LOCATION /usr/local/lib/libswscale.so )

add_library( swresample SHARED IMPORTED )
set_target_properties( swresample PROPERTIES IMPORTED_LOCATION /usr/local/lib/libswresample.so )

target_link_libraries( h264_nvenc avformat swscale swresample avutil avcodec)