使用ffmpeg获取视频流后如何封装存储成mp4文件

时间:2021-09-29 10:04:24
int main(int argc,char *argv[])
02 {
03  AVFormatContext *pFormatCtx;
04  int i,videoStream;
05  AVCodecContext *pCodecCtx;
06  AVPacket packet;
07  //H264Context *h;
08  int type=0;
09  //Open video file
10  char rtsp[100]="";
11  char filename[150]="";
12  char *p=NULL;
13  char camid[6]="";
14  char log[100]="";
15  char new_file[200]="";
16  char command[200]="";
17  char file_jpg[200]="";
18  
19  if(argc!=3)
20  {
21   exit(1);
22  }
23   
24  strcpy(rtsp,argv[1]);
25  strcpy(filename,argv[2]);
26  p=strstr(filename,"cam");
27  memcpy(camid,p,5);
28  
29  signal(SIGTERM,recv_signal);
30  signal(SIGUSR1,recv_signal);
31  signal(SIGHUP,recv_signal);
32  signal(SIGSEGV,recv_signal);
33  strcpy(File_Name,filename);
34  
35  //Register all formats and codecs
36  av_register_all();
37  avformat_network_init();
38  
39  if(av_open_input_file(&pFormatCtx,rtsp,NULL,0,NULL)!=0)
40  {
41   sprintf(log,"%s [%s] %s","The ",rtsp," stream open error\n");
42   write_log(camid,log);
43   exit(1);
44  }
45  
46  //Retrieve stream information
47  if(av_find_stream_info(pFormatCtx)<0)
48  {
49   sprintf(log,"%s","Video Flow information check error\n");
50   write_log(camid,log);
51   return -1;
52  }
53  
54  //Dump information about file onto standard error
55  av_dump_format(pFormatCtx,0,rtsp,0);
56  
57  //Find the first video stream
58  videoStream=-1;
59  for(i=0;i<pFormatCtx->nb_streams;i++)
60  {
61   if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
62   {
63    videoStream=i;
64    break;
65   }
66  }
67  
68  if(videoStream==-1)
69  {
70   sprintf(log,"%s","Didn't find a video stram\n");
71   write_log(camid,log);
72   return -1;
73  }
74  
75  pCodecCtx=pFormatCtx->streams[videoStream]->codec;
76  //open file
77  FILE *fp=NULL;
78  //char *filename="/home/MEDIA/project/linux/test.mp4";
79  
80  if((fp=fopen(filename,"wb"))==NULL)
81  {
82   sprintf(log,"%s%s",filename," open failed\n");
83   write_log(camid,log);
84   exit(1);
85  }
86 /*这里打开了一个test.mp4的文件,下面怎么封装存储就不知道了,请各位大哥指导!帮助指点下封装成mp4文件的主要函数部分*/