我正在尝试使用以下代码记录h.264实时流:
AVOutputFormat* fmt = av_guess_format(NULL, "test.mpeg", NULL);
AVFormatContext* oc = avformat_alloc_context();
oc->oformat = fmt;
avio_open2(&oc->pb, "test.mpeg", AVIO_FLAG_WRITE, NULL, NULL);
AVStream* stream = NULL;
...
while(!done)
{
// Read a frame
if(av_read_frame(inputStreamFormatCtx, &packet)<0)
return false;
if(packet.stream_index==correct_index)
{
////////////////////////////////////////////////////////////////////////
// Is this a packet from the video stream -> decode video frame
if (stream == NULL){//create stream in file
stream = avformat_new_stream(oc, pFormatCtx->streams[videoStream]->codec->codec);
avcodec_copy_context(stream->codec, pFormatCtx->streams[videoStream]->codec);
stream->sample_aspect_ratio = pFormatCtx->streams[videoStream]->codec->sample_aspect_ratio;
stream->sample_aspect_ratio.num = pFormatCtx->streams[videoStream]->codec->sample_aspect_ratio.num;
stream->sample_aspect_ratio.den = pFormatCtx->streams[videoStream]->codec->sample_aspect_ratio.den;
// Assume r_frame_rate is accurate
stream->r_frame_rate = pFormatCtx->streams[videoStream]->r_frame_rate;
stream->avg_frame_rate = stream->r_frame_rate;
stream->time_base = av_inv_q(stream->r_frame_rate);
stream->codec->time_base = stream->time_base;
avformat_write_header(oc, NULL);
}
av_write_frame(oc, &packet);
...
}
}
但是,ffmpeg说
encoder did not produce proper pts making some up
当代码运行到av_write_frame()时;这是什么问题?
最佳答案
首先,请确保inputStreamFormatCtx
分配并填充了正确的值(这是90%的解胶/重新胶粘问题的原因)-在互联网上检查一些样本,以了解u应该如何分配和设置其值。
该错误告诉我们正在发生的事情,似乎只是一个警告。
PTS(演示时间戳)是一个基于stream->time_base
的数字,它告诉我们何时应该显示此数据包的解码帧。当您通过网络获取实时流时,可能是服务器没有为数据包的PTS设置有效的数字,并且当您接收到数据时,它具有无效的PTS(您可以通过阅读packet.pts
并检查其是否为AV_NOPTS_VALUE
)。因此,libav会尝试根据流的帧速率和time_base生成正确的pt。这是一个有用的尝试,如果录制的文件可以真实动作(fps方式)播放,您应该很高兴。如果录制的文件将以快速或慢动作(fps方式)播放,则会出现问题,您将无法再依靠libav来更正fps。因此,您应该通过解码数据包来计算正确的fps,然后根据stream->time_base
计算正确的pts并将其设置为packet.pts
。