2017-04-06 85 views
1

我想给的ffmpeg解码H264,但最后我发现了解码功能只用一个CPU核心FFMpeg如何使用多线程?

system monitor

ENV: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); 

//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 
    } 
} 

但没有与之前不同。
如何在FFMpeg中使用多线程?有任何建议吗?

+0

您将需要显示更多代码。你如何衡量使用了多少核心?你如何解码帧?什么版本的FFmpeg?你是如何分配pCodecParserCtx的? –

+0

Recv rtp流首先使用boost asio,然后用ffmpeg解码,用opengl显示。我添加了一些解析和解码代码。我只是看系统监视器来测量核心的用法,如果我只是解码视频和没有显示器,只有一个核心工作。 –

回答

1

pCodec-> capabilities & = CODEC_CAP_TRUNCATED;

这就是你的错误。请删除此行。 avcodec_find_decoder()的返回值应该适用于所有实际的意图和目的。

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

+0

你是对的,这是一个错误。 –