ffmpeg录制h264直播流出错

ffmpeg recording h264 live stream got error

我正在尝试使用以下代码录制 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 分配并填充了正确的值(这是造成 demuxing/remuxing 问题的 90% 的原因)- 在互联网上查看一些示例以了解您应该如何分配并设置它的值。

该错误告诉我们发生了什么,它似乎只是一个警告。 PTS(Presentation Time Stamp)是一个基于 stream->time_base 的数字,它告诉我们什么时候应该显示这个数据包的解码帧。当您通过网络获得实时流时,服务器可能没有为数据包的 PTS 设置有效数字,当您收到数据时,它有一个无效的 PTS(您可以通过阅读 packet.pts 并检查是否它是 AV_NOPTS_VALUE)。因此 libav 会尝试根据帧速率和流的 time_base 生成正确的点。这是一次有益的尝试,如果录制的文件可以真实运动(fps-wise)播放,您应该会很高兴。如果录制的文件将以快动作或慢动作(fps-wise)播放,你就会遇到问题,你不能再依赖 libav 来纠正 fps。那么你应该通过解码数据包来计算正确的 fps,然后根据 stream->time_base 计算正确的 pts 并将其设置为 packet.pts.