FFmpeg 获取RTSP传过来的视频数据并保存成文件

  废话不多说,直接上代码。

  需要注意的是,FFmpeg的版本很多,最新版本可能有些函数已经换成别的了。如果无法自行更改代码,可以找我以前相关FFmpeg的文章,下载我x64版本的工程包,里面就有这个版本的FFmpeg。

#ifndef INT64_C 
#define INT64_C(c) (c ## LL) 
#define UINT64_C(c) (c ## ULL) 
#endif 

extern "C" {
    /*Include ffmpeg header file*/
#include <libavformat/avformat.h> 
#include <libavcodec/avcodec.h> 
#include <libswscale/swscale.h> 

#include <libavutil/imgutils.h>  
#include <libavutil/opt.h>     
#include <libavutil/mathematics.h>   
#include <libavutil/samplefmt.h>
}

void main()
{
    //变量
    AVFormatContext *pFormatCtx;
    char filepath[] = "rtsp://192.168.50.171/live/stream0";
    AVPacket *packet;
    //初始化
    av_register_all();
    avformat_network_init();
    pFormatCtx = avformat_alloc_context();
    AVDictionary* options = NULL;
    av_dict_set(&options, "buffer_size", "102400", 0); //设置缓存大小,1080p可将值调大
    av_dict_set(&options, "rtsp_transport", "tcp", 0); //以udp方式打开,如果以tcp方式打开将udp替换为tcp
    av_dict_set(&options, "stimeout", "2000000", 0); //设置超时断开连接时间,单位微秒
    av_dict_set(&options, "max_delay", "500000", 0); //设置最大时延
    packet = (AVPacket *)av_malloc(sizeof(AVPacket));
    //打开网络流或文件流  
    if (avformat_open_input(&pFormatCtx, filepath, NULL, NULL) != 0)    
    {
        printf("Couldn't open input stream.\n");
        return;
    }
    //查找码流信息
    if (avformat_find_stream_info(pFormatCtx, NULL)<0)
    {
        printf("Couldn't find stream information.\n");
        return;
    }
    //查找码流中是否有视频流
    int videoindex = -1;
    for (int i = 0; i<pFormatCtx->nb_streams; i++)
        if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            videoindex = i;
            break;
        }
    if (videoindex == -1)
    {
        printf("Didn't find a video stream.\n");
        return;
    }
    //保存一段时间的视频流,写入文件中
    FILE *fpSave;
    fopen_s(&fpSave, "geth264.h264", "wb");
    for (int i = 0; i < 1000; i++)
    {  
        if (av_read_frame(pFormatCtx, packet) >= 0)
        {
            if (packet->stream_index == videoindex)
            {
                fwrite(packet->data, 1, packet->size, fpSave);//写数据到文件中  
            }
            av_packet_unref(packet);
        }
    }
    //释放内存
    fclose(fpSave);
    av_free(pFormatCtx);
    av_free(packet);
}

猜你喜欢

转载自blog.csdn.net/oHanTanYanYing/article/details/77513683