我試圖用FFmpeg libavformat從Axis相機記錄RTSP流。 我可以從文件抓取視頻,然後將其保存到另一個文件,這是好的。但相機發送奇怪的數據,FPS爲100,相機每隔4幀發送一次,因此結果FPS約爲25.但libavformat爲90000幀/秒(默認值?)設置數據包的DTS/PTS,新文件流的幀數爲100fps。結果是隻有100幀的一小時視頻。使用FFmpeg libavformat記錄RTSP流
這裏是我的代碼
#include <stdio.h>
#include <stdlib.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
int main(int argc, char** argv) {
AVFormatContext* context = avformat_alloc_context();
int video_stream_index;
av_register_all();
avcodec_register_all();
avformat_network_init();
//open rtsp
if(avformat_open_input(&context, "rtsp://195.200.199.8/mpeg4/media.amp",NULL,NULL) != 0){
return EXIT_FAILURE;
}
if(avformat_find_stream_info(context,NULL) < 0){
return EXIT_FAILURE;
}
//search video stream
for(int i =0;i<context->nb_streams;i++){
if(context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
video_stream_index = i;
}
AVPacket packet;
av_init_packet(&packet);
//open output file
AVOutputFormat* fmt = av_guess_format(NULL,"test2.avi",NULL);
AVFormatContext* oc = avformat_alloc_context();
oc->oformat = fmt;
avio_open2(&oc->pb, "test.avi", AVIO_FLAG_WRITE,NULL,NULL);
AVStream* stream=NULL;
int cnt = 0;
//start reading packets from stream and write them to file
av_read_play(context);//play RTSP
while(av_read_frame(context,&packet)>=0 && cnt <100){//read 100 frames
if(packet.stream_index == video_stream_index){//packet is video
if(stream == NULL){//create stream in file
stream = avformat_new_stream(oc,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);
}
packet.stream_index = stream->id;
av_write_frame(oc,&packet);
cnt++;
}
av_free_packet(&packet);
av_init_packet(&packet);
}
av_read_pause(context);
av_write_trailer(oc);
avio_close(oc->pb);
avformat_free_context(oc);
return (EXIT_SUCCESS);
}
結果文件是在這裏:http://dl.dropbox.com/u/1243577/test.avi
感謝您的任何意見
在你的代碼中,你只記錄前100幀,這是打算? – ciphor 2012-02-13 03:56:43
相機的格式是什麼?是h.264嗎? – ransh 2015-06-14 16:53:32
另請參閱https://stackoverflow.com/questions/10715170/receiving-rtsp-stream-using-ffmpeg-library – rogerdpack 2017-08-17 22:43:17