FFMPEG硬件编解码器使用

星夢妙者
发布: 2025-09-03 08:58:02
原创
911人浏览过

在前文《视频编解码硬件方案漫谈》中,我们探讨了硬件视频编解码的一般方案。本文将进一步探讨如何在ffmpeg中利用显卡硬件加速音视频编解码。

FFMPEG硬件编解码器使用

一、基本概况

ffmpeg通过对显卡厂商的SDK进行封装和集成,实现了部分硬件编解码功能。

NVIDIA AMD INTEL
编码器 xxx_nvenc xxx_amf xxxx_qsv
解码器 xxx_cuvid 暂未实现 xxxx_qsv

其中,xxx代表编码类型,如h264、h265、mpeg2、vp8、vp9等。此外,ffmpeg中的软件编解码器也可以实现相关硬件加速。例如,在h264解码器中可以使用cuda加速、qsv加速、dxva2加速、d3d11va加速和opencl加速等。

cuda qsv dxva2/d3d11va opencl
应用场景 适用于NVIDIA显卡平台,但跨操作系统 适用于Intel显卡平台,但跨操作系统 适用于Windows操作系统,但跨硬件平台 仅支持opencl的硬件平台

二、命令行的使用

在ffmpeg中,如果使用

-vcodec xxx
登录后复制
指定硬件编解码器,否则将使用软件编解码。例如:

ffplay -x 800 -y 600 -vcodec h264_qsv h264.mp4
ffplay -x 800 -y 600 -vcodec hevc_qsv 4k_hevc.mp4
ffmpeg.exe -i test.ts -vcodec hevc_amf -s 1280x720 output.ts
登录后复制

三、代码中使用

1)使用特定的编解码器

编解码器包由AVCodec描述,其中ID代表一类编码器或解码器。例如,

AV_CODEC_ID_H264
登录后复制
代表h264编解码器,而name代表特定编码器或解码器。通常我们使用
avcodec_find_decoder(ID)
登录后复制
avcodec_find_encoder(ID)
登录后复制
来查找解码器和编码器,默认使用软件编解码。如果需要使用硬件编解码,则使用
avcodec_find_encoder_by_name(name)
登录后复制
avcodec_find_decoder_by_name(name)
登录后复制
来指定编码器。其余代码流程与软件编解码一致。

AI图像编辑器
AI图像编辑器

使用文本提示编辑、变换和增强照片

AI图像编辑器 46
查看详情 AI图像编辑器

例如:

//codec = avcodec_find_decoder(AV_CODEC_ID_H264);
codec = avcodec_find_decoder_by_name("h264_cuvid");
if (!codec) {
    fprintf(stderr, "Codec not found\n");
    exit(1);
}
登录后复制

2)使用硬件加速

使用特定编解码器的好处是跨操作系统,无论是Windows还是Linux都使用同一套代码,但缺点是不跨硬件,不同显卡厂商使用不同的编解码器。基于软件编码器的硬件加速则跨硬件显卡,如Windows上的d3d11va硬件加速,无论底层是AMD、Intel还是NVIDIA显卡都适用,相当于Windows系统屏蔽了硬件细节,我们只需调用Windows的API即可。以下是一个基于硬件加速的示例代码:

static AVBufferRef* hw_device_ctx = NULL;
static enum AVPixelFormat hw_pix_fmt;
static FILE* output_file = NULL;
<p>//硬件加速初始化
static int hw_decoder_init(AVCodecContext* ctx, const enum AVHWDeviceType type) {
int err = 0;
//创建一个硬件设备上下文
if ((err = av_hwdevice_ctx_create(&hw_device_ctx, type, NULL, NULL, 0)) < 0) {
fprintf(stderr, "Failed to create specified HW device.\n");
return err;
}
ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
return err;
}</p><p>//获取GPU硬件解码帧的格式
static enum AVPixelFormat get_hw_format(AVCodecContext<em> ctx, const enum AVPixelFormat</em> pix_fmts) {
const enum AVPixelFormat<em> p;
for (p = pix_fmts; </em>p != -1; p++) {
if (<em>p == hw_pix_fmt)
return </em>p;
}
fprintf(stderr, "Failed to get HW surface format.\n");
return AV_PIX_FMT_NONE;
}</p><p>//解码后数据格式转换,GPU到CPU拷贝,YUV数据dump到文件
static int decode_write(AVCodecContext<em> avctx, AVPacket</em> packet) {
AVFrame<em> frame = NULL, </em>sw_frame = NULL;
AVFrame<em> tmp_frame = NULL;
uint8_t</em> buffer = NULL;
int size;
int ret = 0;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">ret = avcodec_send_packet(avctx, packet);
if (ret < 0) {
    fprintf(stderr, "Error sending a packet for decoding\n");
    return ret;
}

while (ret >= 0) {
    if (!(frame = av_frame_alloc()) || !(sw_frame = av_frame_alloc())) {
        fprintf(stderr, "Can not alloc frame\n");
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    ret = avcodec_receive_frame(avctx, frame);
    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
        av_frame_free(&frame);
        av_frame_free(&sw_frame);
        return 0;
    } else if (ret < 0) {
        fprintf(stderr, "Error during decoding\n");
        goto fail;
    }

    if (frame->format == hw_pix_fmt) {
        /* 将解码后的数据从GPU内存格式转为CPU内存格式,并完成GPU到CPU内存的拷贝*/
        if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {
            fprintf(stderr, "Error transferring the data to system memory\n");
            goto fail;
        }
        tmp_frame = sw_frame;
    } else {
        tmp_frame = frame;
    }

    size = av_image_get_buffer_size((AVPixelFormat)tmp_frame->format, tmp_frame->width, tmp_frame->height, 1);
    //分配内存
    buffer = (uint8_t *)av_malloc(size);
    if (!buffer) {
        fprintf(stderr, "Can not alloc buffer\n");
        ret = AVERROR(ENOMEM);
        goto fail;
    }

    //将图片数据拷贝到buffer中(按行拷贝)
    ret = av_image_copy_to_buffer(buffer, size, (const uint8_t* const*)tmp_frame->data, (const int*)tmp_frame->linesize, (AVPixelFormat)tmp_frame->format, tmp_frame->width, tmp_frame->height, 1);
    if (ret < 0) {
        fprintf(stderr, "Can not copy image to buffer\n");
        goto fail;
    }

    fwrite(buffer, 1, size, output_file);
    av_frame_free(&frame);
    av_frame_free(&sw_frame);
    av_free(buffer);
}
登录后复制

fail: av_frame_free(&frame); av_frame_free(&sw_frame); av_free(buffer); return ret; }

int main(int argc, char argv[]) { AVFormatContext input_ctx = NULL; AVCodecContext decoder_ctx = NULL; AVCodec decoder = NULL; AVPacket packet; enum AVHWDeviceType type; int video_stream = -1; AVCodecParameters video = NULL; AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE; const AVCodecHWConfig config = NULL;

<pre class="brush:php;toolbar:false;">if (argc < 4) {
    fprintf(stderr, "Usage: %s <device type> <input file> <output file>\n", argv[0]);
    return -1;
}

// 设备类型为:cuda dxva2 qsv d3d11va opencl,通常在windows使用d3d11va或者dxva2
type = av_hwdevice_find_type_by_name(argv[1]);
if (type == AV_HWDEVICE_TYPE_NONE) {
    fprintf(stderr, "Device type %s is not supported.\n", argv[1]);
    fprintf(stderr, "Available device types:");
    while ((type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE)
        fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
    fprintf(stderr, "\n");
    return -1;
}

/* open the input file */
if (avformat_open_input(&input_ctx, argv[2], NULL, NULL) != 0) {
    fprintf(stderr, "Cannot open input file '%s'\n", argv[2]);
    return -1;
}

if (avformat_find_stream_info(input_ctx, NULL) < 0) {
    fprintf(stderr, "Cannot find stream information\n");
    return -1;
}

for (int i = 0; i < input_ctx->nb_streams; i++) {
    if (input_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
        video_stream = i;
        break;
    }
}

if (video_stream == -1) {
    fprintf(stderr, "No video stream found\n");
    return -1;
}

decoder = avcodec_find_decoder(input_ctx->streams[video_stream]->codecpar->codec_id);
if (!decoder) {
    fprintf(stderr, "Failed to find %s codec\n", av_get_media_type_string(AVMEDIA_TYPE_VIDEO));
    return -1;
}

while ((config = avcodec_get_hw_config(decoder, config ? config->config_id + 1 : 0))) {
    if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
        config->device_type == type) {
        hw_pix_fmt = config->pix_fmt;
        break;
    }
}

if (!(decoder_ctx = avcodec_alloc_context3(decoder)))
    return AVERROR(ENOMEM);

video = input_ctx->streams[video_stream];
if (avcodec_parameters_to_context(decoder_ctx, video->codecpar) < 0)
    return -1;

decoder_ctx->get_format = get_hw_format;

//硬件加速初始化
if (hw_decoder_init(decoder_ctx, type) < 0)
    return -1;

if (avcodec_open2(decoder_ctx, decoder, NULL) < 0)
    return -1;

output_file = fopen(argv[3], "wb");
if (!output_file) {
    fprintf(stderr, "Could not open %s\n", argv[3]);
    return -1;
}

av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;

while (av_read_frame(input_ctx, &packet) >= 0) {
    if (packet.stream_index == video_stream) {
        ret = decode_write(decoder_ctx, &packet);
        if (ret < 0)
            goto end;
    }
    av_packet_unref(&packet);
}

// Flush the decoder
packet.data = NULL;
packet.size = 0;
ret = decode_write(decoder_ctx, &packet);
if (ret < 0)
    goto end;
登录后复制

end: fclose(output_file); avcodec_free_context(&decoder_ctx); avformat_close_input(&input_ctx); av_buffer_unref(&hw_device_ctx);

<pre class="brush:php;toolbar:false;">return ret;
登录后复制

}

编译后生成

hw_decoder.exe
登录后复制
,解码生成YUV文件如下:

hw_decoder.exe dxva2 D:\videos\hevcdemo.ts test.yuv
登录后复制

FFMPEG硬件编解码器使用

由此可见,GPU解码器的利用率高,CPU占用率极低,硬件加速成功。

以上就是FFMPEG硬件编解码器使用的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号