利用 FFmpeg4.1 进行视频硬件解码

前言

通过CPU进行视频软解码很消耗CPU性能,通常CPU还有其它的任务需要处理,可以利用空闲的GPU进行硬件解码,减轻CPU的压力。

这里由于自己是第一次接触视频解码的知识,网上关于硬解的资料又寥寥无几,基本都是软解教程,故在此记录下自己的心路历程,一来做个总结,二来记录下来方便以后参考。

实现步骤

1. 从相机获取视频码流
这里自己走了很多弯路,最后发现可以直接走rtsp协议进行拉流。
```
    char rtsp[] = "rtsp://admin:[email protected]:554/h264/ch1/main/av_stream";

AVDictionary* options = NULL;
av_dict_set(&options, "stimeout", "20000", 0);  // 连接超时
av_dict_set(&options, "rtsp_transport", "tcp", 0);  // 设置tcp连接,udp可能会丢帧

    // 打开视频源
if (avformat_open_input(&m_pFmtCtx, rtsp, NULL, &options) != 0)
{
    return FALSE;
}

    // 获取数据流信息
if (avformat_find_stream_info(m_pFmtCtx, NULL) < 0) 
{
    return FALSE;
}

    // 筛选出视频流
m_videoIndex = av_find_best_stream(m_pFmtCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &m_pDecoder, 0);
if (m_videoIndex < 0)
{
    VX_LOG_ERROR("Find video stream failed!");
    return FALSE;
}
else
{
    m_pVideoStream = m_pFmtCtx->streams[m_videoIndex];
}

    // 为解码器上下文申请内存
m_pDecoderCtx = avcodec_alloc_context3(m_pDecoder);
if (!m_pDecoderCtx)
{
    VX_LOG_ERROR("Alloc decoder context failed!");
    return FALSE;
}

     // 初始化解码器上下文
if (avcodec_parameters_to_context(m_pDecoderCtx, m_pVideoStream->codecpar) != 0)
{
    VX_LOG_ERROR("Decoder parameters pass to decoder context failed!");
    return FALSE;
}

     // 打开解码器
if (avcodec_open2(m_pDecoderCtx, m_pDecoder, NULL) != 0)
{
    VX_LOG_ERROR("Open decoder failed!");
    return FALSE;
}

```


2、解码数据

猜你喜欢

转载自www.cnblogs.com/huluwa508/p/10283285.html