【问题标题】:Saving frames from a network camera (RTSP) to a mp4 file将来自网络摄像机 (RTSP) 的帧保存到 mp4 文件
【发布时间】:2013-12-29 15:37:33
【问题描述】:

我对如何将视频流保存为 mp4 文件感到很困惑。我正在使用 ffmpeg。让我解释一下问题:

  1. 我通过 RTSP(H.264 流)使用 avformat_open_input()、avformat_find_stream_info()、av_read_play() 连接到网络摄像机,并使用 av_read_frame() 获取帧。
  2. 每次我使用 av_read_frame() 获得一个帧时,我都会将相应的 AVPacket 存储在一个循环缓冲区中。
  3. 在我的应用程序的某些点中,选择了此循环缓冲区的范围。我找到了一个用来开始的关键帧。
  4. 一旦我有一个从关键帧开始的 AVPacket 列表,我就会编写标题、帧和尾部,如下面的代码中所述。

问题在于,如果我尝试使用 VLC、Windows Media Player 或其他软件观看,生成的 mp4 视频会有瑕疵。

我也意识到那些数据包的pts不是连续的,而dts是连续的。我知道 B 帧,但这对我来说是个问题吗?

// Prepare the output
AVFormatContext* oc = avformat_alloc_context();
oc->oformat = av_guess_format(NULL, "video.mp4", NULL);

// Must write header, packets, and trailing
avio_open2(&oc->pb, "video.mp4", AVIO_FLAG_WRITE, NULL, NULL);

// Write header
AVStream* stream = avformat_new_stream(oc, (AVCodec*) context->streams[video_stream_index]->codec->codec);
avcodec_copy_context(stream->codec, context->streams[video_stream_index]->codec);
stream->sample_aspect_ratio = context->streams[video_stream_index]->codec->sample_aspect_ratio;
avformat_write_header(oc, NULL);

// FOR EACH FRAME...
... av_write_frame(oc, circular[k]); ...

// Write trailer and close the file
av_write_trailer(oc);
avcodec_close(stream->codec);
avio_close(oc->pb);
avformat_free_context(oc);

非常感谢,

【问题讨论】:

标签: c++ ffmpeg rtsp libav


【解决方案1】:

首先:当您使用相机时,最好通过 RTP over TCP(TCP 作为传输协议)工作。 要启用此功能:

AVDictionary *ifmtdict;
av_dict_set(&ifmtdict, "rtsp_transport", "tcp", 0);
...
avformat_open_input (..., &ifmtdict);

第二: 数据包开始到来后,等待第一个关键帧,从这一刻开始写入文件。

【讨论】:

  • 另外,我正在编写来自许多 IP 摄像机的许多视频流。一切都好 :) 对不起我的英语。
猜你喜欢
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-03
  • 2021-12-31
相关资源
最近更新 更多