FFMPEG視頻開發:Windows下使用FFMPEG獲取攝像頭數據保存爲MP4文件存放到本地(使用FFMPEG本身接口獲取攝像頭數據)

一、環境介紹

操作系統:win10  64位

FFMPEG版本:  4.2.2

QT版本:  5.12  

攝像頭:筆記本電腦自帶攝像頭

 

win32下使用FFMPEG 4.2.2庫下載地址:https://download.csdn.net/download/xiaolong1126626497/12321684

二、工程介紹

工程使用 QT Creator 創建,選擇控制檯模板,沒有使用QT的UI框架。

三、下載FFMPEG庫

下載地址:http://ffmpeg.org/

選擇windows版本下載:

根據自己的編譯器位數下載,我這裏使用的minigw32位編譯器,分別下載Shared+Dev兩個包,待用。

其中Shared目錄裏包含的是程序運行時需要的庫。

Dev目錄裏包含的是程序編譯時需要的庫和頭文件。

 

下載之後解壓,將要使用的庫加入到系統環境變量裏,方便程序運行時能找到庫。

將bin目錄加到系統環境變量裏。

四、FFMPEG在MinGW編譯報錯解決

/////新增////////////
#ifndef INT64_C
#define INT64_C(c) (c ## LL)
#define UINT64_C(c) (c ## ULL)
#endif

#if defined __cplusplus
#define __STDC_CONSTANT_MACROS  //common.h中的錯誤
#define __STDC_FORMAT_MACROS    //timestamp.h中的錯誤
#endif

五、核心代碼

代碼裏選擇當前筆記本電腦的自帶攝像頭進行錄製10秒的視頻保存在當前目錄下。名稱爲:  123.mp4

#include <QCoreApplication>

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

//聲明引用C的頭文件
extern "C"
{
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <math.h>

    #include <libavutil/avassert.h>
    #include <libavutil/channel_layout.h>
    #include <libavutil/opt.h>
    #include <libavutil/mathematics.h>
    #include <libavutil/timestamp.h>
    #include <libavutil/imgutils.h>
    #include <libavformat/avformat.h>
    #include <libswscale/swscale.h>
    #include <libswresample/swresample.h>
    #include "libavfilter/avfilter.h"
    #include <libavdevice/avdevice.h>
    #include "libavutil/avassert.h"
    #include "libavutil/channel_layout.h"
    #include "libavutil/common.h"
    #include "libavutil/opt.h"
}

#define STREAM_DURATION   10.0 /*錄製視頻的持續時間  秒*/
#define STREAM_FRAME_RATE 15 	/* images/s  這裏可以根據攝像頭的採集速度來設置幀率 */
#define STREAM_PIX_FMT    AV_PIX_FMT_YUV420P /* default pix_fmt */
#define SCALE_FLAGS SWS_BICUBIC

//存放視頻的寬度和高度
int video_width;
int video_height;

// 單個輸出AVStream的包裝器
typedef struct OutputStream
{
    AVStream *st;
    AVCodecContext *enc;
    /*下一幀的點數*/
    int64_t next_pts;
    int samples_count;
    AVFrame *frame;
    AVFrame *tmp_frame;
    float t, tincr, tincr2;
    struct SwsContext *sws_ctx;
    struct SwrContext *swr_ctx;
}OutputStream;


typedef struct IntputDev
{
    AVCodecContext  *pCodecCtx;
    AVCodec         *pCodec;
    AVFormatContext *v_ifmtCtx;
    int  videoindex;
    struct SwsContext *img_convert_ctx;
    AVPacket *in_packet;
    AVFrame *pFrame,*pFrameYUV;
}IntputDev;

static int write_frame(AVFormatContext *fmt_ctx, const AVRational *time_base, AVStream *st, AVPacket *pkt)
{
    /* 將輸出數據包時間戳值從編解碼器重新調整爲流時基 */
    av_packet_rescale_ts(pkt, *time_base, st->time_base);
    pkt->stream_index = st->index;

    /*將壓縮的幀寫入媒體文件。*/
    return av_interleaved_write_frame(fmt_ctx, pkt);
}

/*添加輸出流。 */
static void add_stream(OutputStream *ost, AVFormatContext *oc,AVCodec **codec,enum AVCodecID codec_id)
{
    AVCodecContext *c;
    int i;
    /* find the encoder */
    *codec = avcodec_find_encoder(codec_id);
    if (!(*codec))
    {
        qDebug()<<"avcodec_find_encoder error.";
        exit(1);
    }
    ost->st = avformat_new_stream(oc, nullptr);

    if (!ost->st)
    {
        qDebug()<<"Could not allocate stream.";
        exit(1);
    }
    ost->st->id = oc->nb_streams-1;
    c = avcodec_alloc_context3(*codec);
    if (!c)
    {
        qDebug()<<"Could not alloc an encoding context";
        exit(1);
    }
    ost->enc = c;
    switch((*codec)->type)
    {
        case AVMEDIA_TYPE_AUDIO:
            c->sample_fmt  = (*codec)->sample_fmts ?
                (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
            c->bit_rate    = 64000;
            c->sample_rate = 44100;
            if ((*codec)->supported_samplerates) {
                c->sample_rate = (*codec)->supported_samplerates[0];
                for (i = 0; (*codec)->supported_samplerates[i]; i++) {
                    if ((*codec)->supported_samplerates[i] == 44100)
                        c->sample_rate = 44100;
                }
            }
            c->channels        = av_get_channel_layout_nb_channels(c->channel_layout);
            c->channel_layout = AV_CH_LAYOUT_STEREO;
            if ((*codec)->channel_layouts) {
                c->channel_layout = (*codec)->channel_layouts[0];
                for (i = 0; (*codec)->channel_layouts[i]; i++) {
                    if ((*codec)->channel_layouts[i] == AV_CH_LAYOUT_STEREO)
                        c->channel_layout = AV_CH_LAYOUT_STEREO;
                }
            }
            c->channels        = av_get_channel_layout_nb_channels(c->channel_layout);
            ost->st->time_base = (AVRational){ 1, c->sample_rate };
            break;

        case AVMEDIA_TYPE_VIDEO:
            c->codec_id = codec_id;
            c->bit_rate = 2500000;  //平均比特率,例子代碼默認值是400000
            /* 分辨率必須是2的倍數。*/
            c->width=video_width;
            c->height=video_height;
            /*時基:這是基本的時間單位(以秒爲單位)
             *表示其中的幀時間戳。 對於固定fps內容,
             *時基應爲1 /framerate,時間戳增量應爲
             *等於1。*/
            ost->st->time_base = (AVRational){1,STREAM_FRAME_RATE};  //幀率設置
            c->time_base       = ost->st->time_base;
            c->gop_size      = 12; /* 最多每十二幀發射一幀內幀 */
            c->pix_fmt       = STREAM_PIX_FMT;
            if(c->codec_id == AV_CODEC_ID_MPEG2VIDEO)
            {
                /* 只是爲了測試,我們還添加了B幀 */
                c->max_b_frames = 2;
            }
            if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO)
            {
                /*需要避免使用其中一些係數溢出的宏塊。
                 *普通視頻不會發生這種情況,因爲
                 *色度平面的運動與亮度平面不匹配。 */
                c->mb_decision = 2;
            }
        break;

        default:
            break;
    }

    /* 某些格式希望流頭分開。 */
    if (oc->oformat->flags & AVFMT_GLOBALHEADER)
        c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}

static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
{
    AVFrame *picture;
    int ret;
    picture = av_frame_alloc();
    if (!picture)
        return nullptr;
    picture->format = pix_fmt;
    picture->width  = width;
    picture->height = height;

    /* 爲幀數據分配緩衝區 */
    ret = av_frame_get_buffer(picture, 32);
    if(ret<0)
    {
        qDebug()<<"爲幀數據分配緩衝區錯誤.";
        exit(1);
    }
    return picture;
}

static void open_video(AVFormatContext *oc, AVCodec *codec, OutputStream *ost, AVDictionary *opt_arg)
{
    int ret;
    AVCodecContext *c = ost->enc;
    AVDictionary *opt = nullptr;

    av_dict_copy(&opt, opt_arg, 0);

    /* open the codec */
    ret = avcodec_open2(c, codec, &opt);
    av_dict_free(&opt);
    if (ret < 0)
    {
        exit(1);
    }

    /* 分配並初始化可重用框架 */
    ost->frame = alloc_picture(c->pix_fmt, c->width, c->height);
    if (!ost->frame)
    {
        qDebug()<<"Could not allocate video frame";
        exit(1);
    }
    printf("ost->frame alloc success fmt=%d w=%d h=%d\n",c->pix_fmt,c->width, c->height);

    /*如果輸出格式不是YUV420P,則爲臨時YUV420P
    *也需要圖片。 然後將其轉換爲所需的
    *輸出格式。 */
    ost->tmp_frame = nullptr;
    if(c->pix_fmt != AV_PIX_FMT_YUV420P)
    {
        ost->tmp_frame = alloc_picture(AV_PIX_FMT_YUV420P, c->width, c->height);
        if (!ost->tmp_frame)
        {
            fprintf(stderr, "Could not allocate temporary picture\n");
            exit(1);
        }
    }

    /* 將流參數複製到多路複用器*/
    ret=avcodec_parameters_from_context(ost->st->codecpar, c);
    if(ret<0)
    {
        fprintf(stderr, "Could not copy the stream parameters\n");
        exit(1);
    }
}

/*
  *編碼一個視頻幀
  *編碼完成後返回1,否則返回0
  */
static int write_video_frame(AVFormatContext *oc, OutputStream *ost,AVFrame *frame)
{
    int ret;
    AVCodecContext *c;
    int got_packet=0;
    AVPacket pkt={0};
    if(frame==nullptr)
        return 1;
    c = ost->enc;
    av_init_packet(&pkt);
    /* 編碼圖像*/
    ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
    if(ret<0)
    {
        exit(1);
    }

    if(got_packet)
    {
        ret = write_frame(oc, &c->time_base, ost->st, &pkt);
    }else
    {
        ret = 0;
    }
    if(ret<0)
    {
        exit(1);
    }
    return (frame || got_packet) ? 0 : 1;
}


static AVFrame *get_video_frame(OutputStream *ost,IntputDev* input,int *got_pic)
{
    int ret, got_picture;
    AVCodecContext *c = ost->enc;
    AVFrame * ret_frame=nullptr;
    if(av_compare_ts(ost->next_pts, c->time_base,STREAM_DURATION, (AVRational){1,1})>=0)
        return nullptr;

    /*當我們將幀傳遞給編碼器時,它可能會保留對它的引用
    *內部,確保我們在這裏不覆蓋它*/
    if (av_frame_make_writable(ost->frame)<0)
        exit(1);
    if(av_read_frame(input->v_ifmtCtx, input->in_packet)>=0)
    {
        if(input->in_packet->stream_index==input->videoindex)
        {
            ret = avcodec_decode_video2(input->pCodecCtx, input->pFrame, &got_picture, input->in_packet);
            *got_pic=got_picture;
            if(ret<0)
            {
                printf("Decode Error.\n");
                av_packet_unref(input->in_packet);
                return nullptr;
            }
            if(got_picture)
            {
                sws_scale(input->img_convert_ctx, (const unsigned char* const*)input->pFrame->data, input->pFrame->linesize, 0, input->pCodecCtx->height, ost->frame->data,  ost->frame->linesize);
                ost->frame->pts =ost->next_pts++;
                ret_frame= ost->frame;
            }
        }
        av_packet_unref(input->in_packet);
    }
    return ret_frame;
}
static void close_stream(AVFormatContext *oc, OutputStream *ost)
{
    avcodec_free_context(&ost->enc);
    av_frame_free(&ost->frame);
    av_frame_free(&ost->tmp_frame);
    sws_freeContext(ost->sws_ctx);
    swr_free(&ost->swr_ctx);
}

//顯示當前電腦上的攝像頭設備
void show_dshow_device()
{
    AVFormatContext *pFormatCtx = avformat_alloc_context();
    AVDictionary* options = nullptr;
    av_dict_set(&options,"list_devices","true",0);
    AVInputFormat *iformat = av_find_input_format("dshow");
    printf("Device Info=============\n");
    avformat_open_input(&pFormatCtx,"video=dummy",iformat,&options);
    printf("========================\n");
}


//Show VFW Device
void show_vfw_device()
{
    AVFormatContext *pFormatCtx = avformat_alloc_context();
    AVInputFormat *iformat = av_find_input_format("vfwcap");
    printf("========VFW Device Info======\n");
    avformat_open_input(&pFormatCtx,"list",iformat,NULL);
    printf("=============================\n");
}

/*
採集攝像頭數據編碼成MP4視頻
*/
int Save_Video()
{
    OutputStream video_st = { 0 }, audio_st = { 0 };
    const char *filename;
    AVOutputFormat *fmt;
    AVFormatContext *oc;
    AVCodec *audio_codec, *video_codec;
    int ret;
    int have_video = 0, have_audio = 0;
    int encode_video = 0, encode_audio = 0;
    AVDictionary *opt = nullptr;
    int i;

    filename = "123.mp4";

    printf("當前存儲的視頻文件名稱:%s\n",filename);
    /*分配輸出媒體環境*/
    avformat_alloc_output_context2(&oc, nullptr, nullptr, filename);
    if(!oc)
    {
        printf("無法從文件擴展名推斷出輸出格式:使用MPEG。\n");
        avformat_alloc_output_context2(&oc, nullptr, "mpeg", filename);
    }
    if(!oc)return 1;
    //添加攝像頭----------------------------------
    IntputDev video_input;
    AVCodecContext  *pCodecCtx;
    AVCodec         *pCodec;
    AVFormatContext *v_ifmtCtx;
    avdevice_register_all(); //註冊輸入設備
    avcodec_register_all();

    v_ifmtCtx = avformat_alloc_context();

    show_dshow_device();
   // show_vfw_device();

    //windows下指定攝像頭信息
    AVInputFormat *ifmt=av_find_input_format("dshow");
    if(ifmt==nullptr)
    {
        printf("輸入格式查找失敗.\n");
        return 0;
    }
    /*
        windows下輸入
        ffmpeg -list_devices true -f dshow -i dummy
        命令查詢可用的輸入設備
        這裏的攝像頭的名稱要根據自己電腦上的名稱進行修改.
    */
    if(avformat_open_input(&v_ifmtCtx,"video=Integrated Camera",ifmt,nullptr)!=0)
    {
        printf("無法打開輸入流.\n");
        return -1;
    }
    if(avformat_find_stream_info(v_ifmtCtx,nullptr)<0)
    {
        printf("找不到流信息.\n");
        return -1;
    }
    int videoindex=-1;
    for(i=0; i<v_ifmtCtx->nb_streams; i++)
    if(v_ifmtCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
    {
        videoindex=i;
        printf("videoindex=%d\n",videoindex);
        break;
    }
    if(videoindex==-1)
    {
        printf("找不到視頻流。\n");
        return -1;
    }
    pCodecCtx=v_ifmtCtx->streams[videoindex]->codec;
    pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
    if(pCodec==nullptr)
    {
        printf("找不到編解碼器。\n");
        return -1;
    }
    if(avcodec_open2(pCodecCtx, pCodec,nullptr)<0)
    {
        printf("無法打開編解碼器。\n");
        return -1;
    }

    AVFrame *pFrame,*pFrameYUV;
    pFrame=av_frame_alloc();
    pFrameYUV=av_frame_alloc();

    unsigned char *out_buffer=(unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height,16));

    av_image_fill_arrays(pFrameYUV->data,
                         pFrameYUV->linesize,
                         out_buffer,
                         AV_PIX_FMT_YUV420P,
                         pCodecCtx->width,
                         pCodecCtx->height,
                         16);

    printf("攝像頭尺寸(WxH): %d x %d \n",pCodecCtx->width, pCodecCtx->height);
    video_width=pCodecCtx->width;
    video_height=pCodecCtx->height;
    struct SwsContext *img_convert_ctx;
    img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
    AVPacket *in_packet=(AVPacket *)av_malloc(sizeof(AVPacket));
    video_input.img_convert_ctx=img_convert_ctx;
    video_input.in_packet=in_packet;
    video_input.pCodecCtx=pCodecCtx;
    video_input.pCodec=pCodec;
    video_input.v_ifmtCtx=v_ifmtCtx;
    video_input.videoindex=videoindex;
    video_input.pFrame=pFrame;
    video_input.pFrameYUV=pFrameYUV;
    //-----------------------------添加攝像頭結束
    fmt=oc->oformat;
    /*使用默認格式的編解碼器添加音頻和視頻流並初始化編解碼器。*/
    printf("fmt->video_codec = %d\n", fmt->video_codec);
    if(fmt->video_codec != AV_CODEC_ID_NONE)
    {
        add_stream(&video_st,oc,&video_codec,fmt->video_codec);
        have_video=1;
        encode_video=1;
    }
    /*現在已經設置了所有參數,可以打開音頻並視頻編解碼器,並分配必要的編碼緩衝區。*/
    if(have_video)open_video(oc, video_codec, &video_st, opt);
    av_dump_format(oc,0,filename,1);
    /* 打開輸出文件(如果需要) */
    if(!(fmt->flags & AVFMT_NOFILE))
    {
        ret=avio_open(&oc->pb,filename,AVIO_FLAG_WRITE);
        if(ret<0)
        {
           // fprintf(stderr, "打不開'%s': %s\n", filename,av_err2str(ret));
            return 1;
        }
    }
    /* 編寫流頭(如果有)*/
    ret=avformat_write_header(oc, &opt);
    if(ret<0)
    {
        //fprintf(stderr, "打開輸出文件時發生錯誤: %s\n",av_err2str(ret));
        return 1;
    }
    int got_pic;
    while(encode_video)
    {
        /*選擇要編碼的流*/
        AVFrame *frame=get_video_frame(&video_st,&video_input,&got_pic);
        if(!got_pic)
        {
            continue;
        }
        encode_video=!write_video_frame(oc,&video_st,frame);
    }
    av_write_trailer(oc);
    sws_freeContext(video_input.img_convert_ctx);
    avcodec_close(video_input.pCodecCtx);
    av_free(video_input.pFrameYUV);
    av_free(video_input.pFrame);
    avformat_close_input(&video_input.v_ifmtCtx);
    /*關閉每個編解碼器*/
    if (have_video)close_stream(oc, &video_st);
    /*關閉輸出文件*/
    if (!(fmt->flags & AVFMT_NOFILE))avio_closep(&oc->pb);
    /*釋放流*/
    avformat_free_context(oc);
    return 0;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Save_Video();
    return a.exec();
}

 

在windows下要記得把攝像頭名稱換成自己電腦的名稱。

xxx.pro文件:

#win32---mingw32
INCLUDEPATH += C:/FFMPEG_WIN32_LIB_4.2.2/include

#win32---mingw32
LIBS += C:/FFMPEG_WIN32_LIB_4.2.2/lib/avcodec.lib \
        C:/FFMPEG_WIN32_LIB_4.2.2/lib/avdevice.lib \
        C:/FFMPEG_WIN32_LIB_4.2.2/lib/avfilter.lib \
        C:/FFMPEG_WIN32_LIB_4.2.2/lib/avformat.lib \
        C:/FFMPEG_WIN32_LIB_4.2.2/lib/avutil.lib \
        C:/FFMPEG_WIN32_LIB_4.2.2/lib/postproc.lib \
        C:/FFMPEG_WIN32_LIB_4.2.2/lib/swresample.lib \
        C:/FFMPEG_WIN32_LIB_4.2.2/lib/swscale.lib

下面公衆號裏有全套的C/C++/QT/單片機的教程--歡迎關注:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章