个人觉得ffmpeg中的难点在于音视频的同步以及时间戳,这个时间戳不仅仅说是你通过av_rescale_q_rnd函数来获取就可以处理的了的,有时候格式不一样,出现的问题也是不同的。比如今天我就碰到了这个问题,我先用av_rescale_q_rnd函数来对时间戳设置,生成的h264文件正常,但是没有显示时长吗,不知道是不是h264文件本身就是这种情况??然后把h264换成MP4格式,录了视频有大概30秒,结果生成的MP4文件时长只有4秒,帧率竟然达到了90,吃惊了。 h264文件时间戳的设置如下
//下面是我对h264文件时间戳的处理
void captureFrame()
{
......
......
//以上省略一些代码,这里只关注时间戳
//视频时间戳
pkt.pts = av_rescale_q_rnd(pkt.pts, infmt_ctx->streams[pkt.stream_index]->time_base, outfmt_ctx->streams[pkt.stream_index]->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
//解码时间戳
pkt.dts = av_rescale_q_rnd(pkt.dts, infmt_ctx->streams[pkt.stream_index]->time_base, outfmt_ctx->streams[pkt.stream_index]->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
//时长
pkt.duration = av_rescale_q(pkt.duration, infmt_ctx->streams[pkt.stream_index]->time_base, outfmt_ctx->streams[pkt.stream_index]->time_base);
pkt.pos = -1;
.....
.....
}
int main(void)
{
//初始化
av_register_all();
avformat_network_init();
avcodec_register_all();
avdevice_register_all();
captureFrame();
return 0;
}
但是上面的代码如果用在MP4文件上却是问题非常大,生成的文件播放速度非常快,明显异常。接着我做如下处理:
pkt.pts = pkt.dts = Count * (ofmt_ctx->streams[stream_index]->time_base.den) /ofmt_ctx->streams[stream_index]->time_base.num / 10;
Count++;
结果mp4视频文件就正常了,上面这段代码其实是基于时间基来重新设置新的时间戳。