ffmpeg學習(二) 通過rtsp獲取H264裸流並保存到mp4文件


本篇將使用上節http://www.cnblogs.com/wenjingu/p/3977015.html中編譯好的庫文件通過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:12345@192.168.10.76: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文件可以用任意支持該格式的播放器播放。現在還無法做到一邊存儲一邊回放錄像,下篇再完善吧。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM