<div dir="ltr">Hi all,<br><br>I am quite confused about how to save a video stream into a mp4 file. Let me explain the problem:<br><br>1. I connect to a network camera via RTSP (H.264 stream) with avformat_open_input(), avformat_find_stream_info(), av_read_play(), and I get frames with av_read_frame().<div>

2. Each time I get a frame with av_read_frame(), I store the corresponding AVPacket in a circular buffer.</div><div>3. In some points in my application, a range of this circular buffer is selected. I find a key frame used to start from.</div>

<div>4. Once I have a list of AVPacket's starting from a key frame, I write header, frames, and tail, as I described below in the code.</div><div><br></div><div>The problem is that the resulting mp4 video has artifacts if I try to watch it using VLC, Windows Media Player, or another one.</div>

<div><br></div><div>I have also realized that the pts of that packets are not continuous, while dts are continuous. I know about B frames, but is this a problem in my case?</div><div><br></div><div><div>// Prepare the output</div>

<div><div>AVFormatContext* oc = avformat_alloc_context();</div><div>oc->oformat = av_guess_format(NULL, "video.mp4", NULL);</div><div><br></div><div>// Must write header, packets, and trailing</div><div>avio_open2(&oc->pb, "video.mp4", AVIO_FLAG_WRITE, NULL, NULL);</div>

<div><br></div><div>// Write header</div><div>AVStream* stream = avformat_new_stream(oc, (AVCodec*) context->streams[video_stream_index]->codec->codec);</div><div>avcodec_copy_context(stream->codec, context->streams[video_stream_index]->codec);</div>

<div>stream->sample_aspect_ratio = context->streams[video_stream_index]->codec->sample_aspect_ratio;</div><div>avformat_write_header(oc, NULL);</div></div><div><br></div><div>// FOR EACH FRAME...</div><div>... av_write_frame(oc, circular[k]); ...<br>

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

</div><div>Thank you so much,</div><br>--<br>Dídac Pérez<br></div></div>