1. 程式人生 > >通過rtsp獲取H264裸流並儲存到mp4檔案

通過rtsp獲取H264裸流並儲存到mp4檔案

1、VS2010建立VC++  win32控制檯專案

2、在工程目錄下建立lib目錄和include目錄,將已編譯好的lib拷打lib下,include拷到include下,dll拷到Debug目錄下

3、工程屬性--配置屬性--VC++目錄--包含目錄,新增ffmpeg標頭檔案目錄及其他第三方標頭檔案目錄

                                             連結器--常規--附加庫目錄,新增lib目錄

                                             連結器--輸入--附加依賴項,新增各個lib名

4、設計和實現:

4.1 設計思路:

       元件和網路初始化——>開啟網路流——>獲取網路流資訊——>根據網路流資訊初始化輸出流資訊——>建立並開啟mp4檔案——>寫mp4檔案頭

                    ——>迴圈讀取輸入流並寫入mp4檔案——>寫檔案尾——>關閉流,關閉檔案

4.2 關鍵資料結構:

       AVFormatContext,AVStream,AVCodecContext,AVPacket,AVFrame等,它們的關係解釋如下:

       一個AVFormatContext包含多個AVStream,每個碼流包含了AVCodec和AVCodecContext,AVPicture是AVFrame的一個子集,

他們都是資料流在編解過程中用來儲存資料快取的對像,從資料流讀出的資料首先是儲存在AVPacket裡,也可以理解為一個AVPacket最多隻包含一個AVFrame,

而一個AVFrame可能包含好幾個AVPacket,AVPacket是種資料流分包的概念。

4.3 關鍵函式:

int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options); //開啟網路流或檔案流

int avformat_write_header(AVFormatContext *s, AVDictionary **options);//根據檔名的字尾寫相應格式的檔案頭

int av_read_frame(AVFormatContext *s, AVPacket *pkt);//從輸入流中讀取一個分包

int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt);//往輸出流中寫一個分包

int av_write_trailer(AVFormatContext *s);//寫輸出流(檔案)的檔案尾

4.4 程式碼:

複製程式碼
#include "stdafx.h"

#ifdef __cplusplus 
extern "C" { 
#endif

#include <libavcodec/avcodec.h> 
#include <libavdevice/avdevice.h> 
#include <libavformat/avformat.h> 
#include <libavfilter/avfilter.h> 
#include <libavutil/avutil.h> 
#include <libswscale/swscale.h>

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <math.h>

#ifdef __cplusplus 
} 
#endif
複製程式碼

 以上為引用C庫和ffmpeg庫的標頭檔案。

複製程式碼
static AVFormatContext *i_fmt_ctx;
static AVStream *i_video_stream;

static AVFormatContext *o_fmt_ctx;
static AVStream *o_video_stream;

static bool bStop = false;

static unsigned __stdcall rtsp2mp4(void * pThis)
{
    avcodec_register_all();
    av_register_all();
    avformat_network_init();

    /* should set to NULL so that avformat_open_input() allocate a new one */
    i_fmt_ctx = NULL;
    char rtspUrl[] = "rtsp://admin:[email protected]:554";
    const char *filename = "1.mp4";
    if (avformat_open_input(&i_fmt_ctx, rtspUrl, NULL, NULL)!=0)
    {
        fprintf(stderr, "could not open input file\n");
        return -1;
    }

    if (avformat_find_stream_info(i_fmt_ctx, NULL)<0)
    {
        fprintf(stderr, "could not find stream info\n");
        return -1;
    }

    //av_dump_format(i_fmt_ctx, 0, argv[1], 0);

    /* find first video stream */
    for (unsigned i=0; i<i_fmt_ctx->nb_streams; i++)
    {
        if (i_fmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            i_video_stream = i_fmt_ctx->streams[i];
            break;
        }
    }
    if (i_video_stream == NULL)
    {
        fprintf(stderr, "didn't find any video stream\n");
        return -1;
    }

    avformat_alloc_output_context2(&o_fmt_ctx, NULL, NULL, filename);

    /*
    * since all input files are supposed to be identical (framerate, dimension, color format, ...)
    * we can safely set output codec values from first input file
    */
    o_video_stream = avformat_new_stream(o_fmt_ctx, NULL);
    {
        AVCodecContext *c;
        c = o_video_stream->codec;
        c->bit_rate = 400000;
        c->codec_id = i_video_stream->codec->codec_id;
        c->codec_type = i_video_stream->codec->codec_type;
        c->time_base.num = i_video_stream->time_base.num;
        c->time_base.den = i_video_stream->time_base.den;
        fprintf(stderr, "time_base.num = %d time_base.den = %d\n", c->time_base.num, c->time_base.den);
        c->width = i_video_stream->codec->width;
        c->height = i_video_stream->codec->height;
        c->pix_fmt = i_video_stream->codec->pix_fmt;
        printf("%d %d %d", c->width, c->height, c->pix_fmt);
        c->flags = i_video_stream->codec->flags;
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;
        c->me_range = i_video_stream->codec->me_range;
        c->max_qdiff = i_video_stream->codec->max_qdiff;

        c->qmin = i_video_stream->codec->qmin;
        c->qmax = i_video_stream->codec->qmax;

        c->qcompress = i_video_stream->codec->qcompress;
    }

    avio_open(&o_fmt_ctx->pb, filename, AVIO_FLAG_WRITE);

    avformat_write_header(o_fmt_ctx, NULL);

    int last_pts = 0;
    int last_dts = 0;

    int64_t pts, dts;
    while (!bStop)
    {
        AVPacket i_pkt;
        av_init_packet(&i_pkt);
        i_pkt.size = 0;
        i_pkt.data = NULL;
        if (av_read_frame(i_fmt_ctx, &i_pkt) <0 )
            break;
        /*
        * pts and dts should increase monotonically
        * pts should be >= dts
        */
        i_pkt.flags |= AV_PKT_FLAG_KEY;
        pts = i_pkt.pts;
        i_pkt.pts += last_pts;
        dts = i_pkt.dts;
        i_pkt.dts += last_dts;
        i_pkt.stream_index = 0;

        //printf("%lld %lld\n", i_pkt.pts, i_pkt.dts);
        static int num = 1;
        printf("frame %d\n", num++);
        av_interleaved_write_frame(o_fmt_ctx, &i_pkt);
        //av_free_packet(&i_pkt);
        //av_init_packet(&i_pkt);
         Sleep(10);
    }
    last_dts += dts;
    last_pts += pts;

    avformat_close_input(&i_fmt_ctx);

    av_write_trailer(o_fmt_ctx);

    avcodec_close(o_fmt_ctx->streams[0]->codec);
    av_freep(&o_fmt_ctx->streams[0]->codec);
    av_freep(&o_fmt_ctx->streams[0]);

    avio_close(o_fmt_ctx->pb);
    av_free(o_fmt_ctx);

    return 0;
}

int _tmain(int argc, char **argv)
{
    //ffplayer();
    bStop = false;
    HANDLE   hth;  
    unsigned  uiThreadID;  
  
    hth = (HANDLE)_beginthreadex( NULL,         // security  
                                   0,            // stack size  
                                   rtsp2mp4,  
                                   NULL,           // arg list  
                                   0,  //CREATE_SUSPENDED so we can later call ResumeThread()  
                                   &uiThreadID );  
  
    if ( hth == 0 ) 
    {
        printf("Failed to create thread\n"); 
        return -1;
    }

    printf("按任意鍵停止錄影\n");
    getchar();
    bStop = true;
    printf("按任意鍵退出\n");
    getchar();
       
    return 0;
}
複製程式碼

原來的程式碼沒有為儲存流功能單獨開執行緒,會導致寫檔案尾的語句執行不到,現在改為用一個單獨的執行緒來執行。

5、測試

1

如上圖為儲存視訊流過程中程式的列印結果。生成的mp4檔案可以用任意支援該格式的播放器播放。