利用ffmpeg從RTSP服務(wù)器拉流并保存各種格式文件

下面的代碼是我從網(wǎng)上找來的梅割,并且做了一些改進(jìn)继控,主要有:

  • 增加命令的選項(xiàng):
    • RTSP url
    • 視頻文件保存格式
    • 要保存的幀數(shù)
    • 第一幀是I幀

廢話少說求泰,上代碼:

#include<stdio.h>
#include<libavformat/avformat.h>
#include<libavutil/mathematics.h>
#include<libavutil/time.h>
#include <unistd.h>

#define USAGE   "rtsp2x -i <rtsp url> -t [avi | flv | mp4] -n <number of frames you want to save>"
#define OPTS    "i:t:n:h"

static void print_usage()
{
        printf("Usage: %s\n", USAGE);
        return;
}
int main(int argc,char **argv)
{
        AVOutputFormat *ofmt = NULL;
    AVFormatContext *ifmt_ctx = NULL,*ofmt_ctx = NULL;
    AVPacket pkt;
    const char in_filename[128] = {0}, out_filename[128] = {0};    
    int ret,i;
    int video_index=-1;
    int frame_index=0;
        int I_received = 0;

        int opt, frames_count = -1;

        while ((opt = getopt(argc, argv, OPTS)) != -1) {
                switch (opt) {
                case 'i':
                        strcpy(in_filename, optarg);
                        break;
                case 't':
                        if (strcmp(optarg, "avi") == 0)
                                strcpy(out_filename, "receive.avi");
                        else if (strcmp(optarg, "flv") == 0)
                                strcpy(out_filename, "receive.flv");
                        else if (strcmp(optarg, "mp4") == 0) 
                                strcpy(out_filename, "receive.mp4");
                        else {
                                return -1;
                        }
                        print_usage();
                        break;
                case 'n':
                        frames_count = atoi(optarg);
                        if (frames_count < 0) {
                                print_usage();
                                return -1;
                        }
                        printf("frames_count = %d\n", frames_count);
                        break;
                case 'h':
                default:
                        print_usage();
                        return -1;
                }
        }

        if (strlen(in_filename) == 0 || strlen(out_filename) == 0 || frames_count < 0) {
                print_usage();
                return -1;
        }

    av_register_all();
    avformat_network_init();

    //使用TCP連接打開RTSP卤唉,設(shè)置最大延遲時(shí)間
    AVDictionary *avdic=NULL;  
    char option_key[]="rtsp_transport";  
    char option_value[]="tcp";  
    av_dict_set(&avdic,option_key,option_value,0);  
    char option_key2[]="max_delay";  
    char option_value2[]="5000000";  
    av_dict_set(&avdic,option_key2,option_value2,0); 
    //打開輸入流
    if((ret=avformat_open_input(&ifmt_ctx,in_filename,0,&avdic))<0)
    {
        printf("Could not open input file.\n");
        goto end;
    }
    if((ret=avformat_find_stream_info(ifmt_ctx,0))<0)
    {
        printf("Failed to retrieve input stream information\n");
        goto end;
    }
    //nb_streams代表有幾路流备畦,一般是2路:即音頻和視頻低飒,順序不一定
    for(i=0;i<ifmt_ctx->nb_streams;i++){
        
        if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
        {
            //這一路是視頻流,標(biāo)記一下懂盐,以后取視頻流都從ifmt_ctx->streams[video_index]取
            video_index=i;
            break;
        }
    }

    av_dump_format(ifmt_ctx,0,in_filename,0);

    //打開輸出流
    avformat_alloc_output_context2(&ofmt_ctx,NULL,NULL,out_filename);
    
    if(!ofmt_ctx)
    {
        printf("Could not create output context\n");
        ret=AVERROR_UNKNOWN;
        goto end;
    }
    
    ofmt = ofmt_ctx->oformat;
    for(i=0;i<ifmt_ctx->nb_streams;i++)
    {    //根據(jù)輸入流創(chuàng)建輸出流
        AVStream *in_stream = ifmt_ctx->streams[i];
        AVStream *out_stream = avformat_new_stream(ofmt_ctx,in_stream->codec->codec);
        if(!out_stream)
        {
            printf("Failed allocating output stream.\n");
            ret = AVERROR_UNKNOWN;
            goto end;
        }

        //將輸出流的編碼信息復(fù)制到輸入流
        ret = avcodec_copy_context(out_stream->codec,in_stream->codec);
        if(ret<0)
        {
            printf("Failed to copy context from input to output stream codec context\n");
            goto end;
        }
        out_stream->codec->codec_tag = 0;
    
        if(ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
            out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;

    }

    //Dump format--------------------
    av_dump_format(ofmt_ctx,0,out_filename,1);
    //打開輸出文件
    if(!(ofmt->flags & AVFMT_NOFILE))
    {
        ret = avio_open(&ofmt_ctx->pb,out_filename,AVIO_FLAG_WRITE);
        if(ret<0)
        {
            printf("Could not open output URL '%s'",out_filename);
            goto end;
        }
    }

    //寫文件頭到輸出文件
    ret = avformat_write_header(ofmt_ctx,NULL);
    if(ret < 0)
    {
        printf("Error occured when opening output URL\n");
        goto end;
    }


    //while循環(huán)中持續(xù)獲取數(shù)據(jù)包逸嘀,不管音頻視頻都存入文件
    while(1)
    {
        AVStream *in_stream,*out_stream;
        //從輸入流獲取一個(gè)數(shù)據(jù)包
        ret = av_read_frame(ifmt_ctx,&pkt);
        if(ret<0)
            break;

        in_stream = ifmt_ctx->streams[pkt.stream_index];
        out_stream = ofmt_ctx->streams[pkt.stream_index];
        //copy packet
        //轉(zhuǎn)換 PTS/DTS 時(shí)序
        pkt.pts = av_rescale_q_rnd(pkt.pts,in_stream->time_base,out_stream->time_base,(enum AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (enum AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));  
        //printf("pts %d dts %d base %d\n",pkt.pts,pkt.dts, in_stream->time_base);
        pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base); 
        pkt.pos = -1;  

        //此while循環(huán)中并非所有packet都是視頻幀,當(dāng)收到視頻幀時(shí)記錄一下允粤,僅此而已
        if(pkt.stream_index==video_index)
        {
                        if ((pkt->flags & AV_PKT_FLAG_KEY) && (I_received == 0)) 
                                I_received = 1;
                        if (I_received == 0)
                                continue;

            printf("Receive %8d video frames from input URL\n",frame_index);
            frame_index++;
        } else {
                        continue;
                }

                if (frame_index == frames_count)
                        break;

        //將包數(shù)據(jù)寫入到文件崭倘。
        ret = av_interleaved_write_frame(ofmt_ctx,&pkt);
        if(ret < 0)
        {
            /**
            當(dāng)網(wǎng)絡(luò)有問題時(shí),容易出現(xiàn)到達(dá)包的先后不一致类垫,pts時(shí)序混亂會(huì)導(dǎo)致
            av_interleaved_write_frame函數(shù)報(bào) -22 錯(cuò)誤司光。暫時(shí)先丟棄這些遲來的幀吧
            若所大部分包都沒有pts時(shí)序,那就要看情況自己補(bǔ)上時(shí)序(比如較前一幀時(shí)序+1)再寫入悉患。
            */
            if(ret==-22){
                continue;
            }else{
                printf("Error muxing packet.error code %d\n" , ret);
                break;
            }
            
        }
        
        //av_free_packet(&pkt); //此句在新版本中已deprecated 由av_packet_unref代替
        av_packet_unref(&pkt);
    }


    //寫文件尾
    av_write_trailer(ofmt_ctx);

end:
    
    av_dict_free(&avdic);
    avformat_close_input(&ifmt_ctx);
    //Close input
    if(ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
        avio_close(ofmt_ctx->pb);
    avformat_free_context(ofmt_ctx);
    if(ret<0 && ret != AVERROR_EOF)
    {
        printf("Error occured.\n");
        return -1;
    }
    return 0;
    
}

編譯命令:

$ gcc -o rtsp2x rtsp2x.c -lavcodec -lavformat -lavutil

使用舉例:

./rtsp2x -i rtsp://admin:NRRMUY@192.168.0.100:554/h264/ch1/main/av_stream -t flv -n 120

執(zhí)行完成后就會(huì)在當(dāng)前目錄下產(chǎn)生一個(gè)receive.flv的視頻文件残家。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市售躁,隨后出現(xiàn)的幾起案子坞淮,更是在濱河造成了極大的恐慌,老刑警劉巖陪捷,帶你破解...
    沈念sama閱讀 219,110評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件回窘,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡市袖,警方通過查閱死者的電腦和手機(jī)啡直,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來苍碟,“玉大人酒觅,你說我怎么就攤上這事∥⒎澹” “怎么了舷丹?”我有些...
    開封第一講書人閱讀 165,474評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)蜓肆。 經(jīng)常有香客問我颜凯,道長(zhǎng)谋币,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,881評(píng)論 1 295
  • 正文 為了忘掉前任装获,我火速辦了婚禮瑞信,結(jié)果婚禮上厉颤,老公的妹妹穿的比我還像新娘穴豫。我一直安慰自己,他們只是感情好逼友,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,902評(píng)論 6 392
  • 文/花漫 我一把揭開白布精肃。 她就那樣靜靜地躺著,像睡著了一般帜乞。 火紅的嫁衣襯著肌膚如雪司抱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,698評(píng)論 1 305
  • 那天黎烈,我揣著相機(jī)與錄音习柠,去河邊找鬼。 笑死照棋,一個(gè)胖子當(dāng)著我的面吹牛资溃,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播烈炭,決...
    沈念sama閱讀 40,418評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼溶锭,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了符隙?” 一聲冷哼從身側(cè)響起趴捅,我...
    開封第一講書人閱讀 39,332評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎霹疫,沒想到半個(gè)月后拱绑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,796評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡丽蝎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,968評(píng)論 3 337
  • 正文 我和宋清朗相戀三年欺栗,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片征峦。...
    茶點(diǎn)故事閱讀 40,110評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡迟几,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出栏笆,到底是詐尸還是另有隱情类腮,我是刑警寧澤,帶...
    沈念sama閱讀 35,792評(píng)論 5 346
  • 正文 年R本政府宣布蛉加,位于F島的核電站蚜枢,受9級(jí)特大地震影響缸逃,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜厂抽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,455評(píng)論 3 331
  • 文/蒙蒙 一需频、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧筷凤,春花似錦昭殉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至卢厂,卻和暖如春乾蓬,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背慎恒。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評(píng)論 1 272
  • 我被黑心中介騙來泰國打工任内, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人融柬。 一個(gè)月前我還...
    沈念sama閱讀 48,348評(píng)論 3 373
  • 正文 我出身青樓死嗦,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親丹鸿。 傳聞我的和親對(duì)象是個(gè)殘疾皇子越走,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,047評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容