ffmpeg通过rtsp获取h264码流
处理过程
通过VLC播放器将本地文件进行rtsp推流,使用ffmpeg打开URL地址获取h264。
VLC rtsp推流
-
点击“媒体”,选择“流”
-
点击“添加”选择需要推流的文件,然后点击下面的“串流”
-
点击“下一步”,选择“RTSP",再点击”添加“,设置端口号和名称,默认的ip是电脑本机ip
-
点击”下一个“,设置推流格式为h264
-
然后点击“下一个”,点击“流”后即可推流
-
测试的话,可以使用VLC媒体中的打开网络串流进行播放,若能成功播放则推流成功。
ffmpeg获取rtsp
# ffmpeg需要链接库的顺序
avfilter avformat avcodec avutil swresample swscale avdevice z m pthread
获取其实很简单的,只给出代码,packet结构体中的data和size就是一帧h264数据(头部包含NALU)
extern "C"{
#include <stdio.h>
#include <signal.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
}
static volatile int flag_quit=0;
void signal_quit_handler(int sig)
{
flag_quit=1;
signal(SIGINT,SIG_DFL);
}
int rtsp_get_h264_test()
{
signal(SIGINT,signal_quit_handler);
AVFormatContext* format_context;
int video_index;
AVPacket *packet;
char file_path[]="rtsp://192.168.1.7:8554/live";
avformat_network_init();
format_context=avformat_alloc_context();
AVDictionary* options=NULL;
av_dict_set(&options,"buffer_size","102400",0);
av_dict_set(&options,"max_delay","500000",0);
av_dict_set(&options,"timeout","20000000",0);
av_dict_set(&options,"rtsp_transport","udp",0);
if(avformat_open_input(&format_context,file_path,NULL,&options)<0)
{
printf("Couldn't open input stream.\n");
return -1;
}
printf("Open stream success!\n");
if(avformat_find_stream_info(format_context,NULL)<0)
{
printf("Couldn't find stream information.\n");
return -1;
}
video_index=-1;
video_index=av_find_best_stream(format_context,AVMEDIA_TYPE_VIDEO,-1,-1,NULL,0);
if(video_index==-1)
{
printf("Couldn't find a stream video.\n");
return -1;
}
packet=av_packet_alloc();
while(!flag_quit)
{
if(av_read_frame(format_context,packet)>=0)
{
if(packet->stream_index==video_index){
printf("packet size %d\n",packet->size);
for(int i=0;i<8;i++)
{
printf("%d ",packet->data[i]);
}
printf("\n");
}
}
}
av_packet_free(&packet);
avformat_close_input(&format_context);
return 0;
}
int main(int argc, char **argv) {
printf("printf ffmpeg configuration: ");
printf("%s\n", avcodec_configuration());
rtsp_get_h264_test();
return 0;
}
其它
- 使用tcp打开的话会提示不支持
- 打开流后结束程序时最好关闭,不然会影响下一次的使用