我想通过ffmpeg解码H264,但最后我发现解码功能只使用了一个cpu核心
system monitor
环境: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 中使用多线程?有什么建议吗?
最佳答案
pCodec->capabilities &= CODEC_CAP_TRUNCATED;
那是你的错误。请删除此行。
avcodec_find_decoder()
的返回值出于所有实际意图和目的,应将其视为 const。具体来说,此语句删除了
AV_CODEC_CAP_FRAME_THREADS
从编解码器的功能中标记,从而有效地禁用其余代码中的帧多线程。
关于multithreading - FFMpeg 如何使用多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251612/