FFMpeg 如何使用多线程?

Wu *_* NL 5 multithreading ffmpeg

我想用ffmpeg解码H264,但最后我发现解码功能只使用了一个CPU核心

系统监视器

环境:Ubuntu 14.04 FFMpeg 3.2.4 CPU i7-7500U


因此,我搜索了 ffmpeg 多线程并决定使用所有 cpu 核心进行解码。
我将 AVCodecContext 设置为:

//Init works
//codecId=AV_CODEC_ID_H264;
avcodec_register_all();
pCodec = avcodec_find_decoder(codecId);
if (!pCodec)
{
    printf("Codec not found\n");
    return -1;
}
pCodecCtx = avcodec_alloc_context3(pCodec);
if (!pCodecCtx)
{
    printf("Could not allocate video codec context\n");
    return -1;
}

pCodecParserCtx=av_parser_init(codecId);
if (!pCodecParserCtx)
{
    printf("Could not allocate video parser context\n");
    return -1;
}
pCodecCtx->thread_count = 4;
pCodecCtx->thread_type = FF_THREAD_FRAME;

pCodec->capabilities &= CODEC_CAP_TRUNCATED;
pCodecCtx->flags |= CODEC_FLAG_TRUNCATED;

if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
{
    printf("Could not open codec\n");
    return -1;
}
av_log_set_level(AV_LOG_QUIET);
av_init_packet(&packet);
Run Code Online (Sandbox Code Playgroud)
//parse and decode
//after av_parser_parse2, the packet has a complete frame data
//in decode function, I just call avcodec_decode_video2 and do some frame copy work
while (cur_size>0)
{
    int len = av_parser_parse2(
                  pCodecParserCtx, pCodecCtx,
                  &packet.data, &packet.size,
                  cur_ptr, cur_size,
                  AV_NOPTS_VALUE, AV_NOPTS_VALUE, AV_NOPTS_VALUE);

    cur_ptr += len;
    cur_size -= len;
    if(GetPacketSize()==0)
        continue;

    AVFrame *pFrame = av_frame_alloc();
    int ret = Decode(pFrame);
    if (ret < 0)
    {
        continue;
    }
    if (ret)
    {
      //some works
    }
}
Run Code Online (Sandbox Code Playgroud)

但和以前没什么不同。
如何在 FFMpeg 中使用多线程?有什么建议吗?

Ron*_*tje 2

pCodec->功能 &= CODEC_CAP_TRUNCATED;

这就是你的错误。请删除此行。出于所有实际意图和目的, 的返回值avcodec_find_decoder()应被视为 const。

具体来说,此语句AV_CODEC_CAP_FRAME_THREADS从编解码器的功能中删除了该标志,从而有效地禁用了代码其余部分中的帧多线程。