FFMPEG系列課程(一)打開視頻解碼器

測試環境:windows10 

開發工具:VS2013

        從今天開始準備些FFmpeg的系列教程,今天是第一課我們研究下打開視頻文件和視頻解碼器。演示環境在windows上,在linux上代碼也是一樣。

       windows上可以不編譯ffmpeg源碼,後面我會分別講解在linux和在windows上如何編譯ffmpeg,直接在FFmpeg官網下載已經編譯好的dll和lib文件,下載地址https://ffmpeg.zeranoe.com/builds/ 裏面有32位和64位的,我下載的32位。或者直接到ffmpeg中文網站下載Windows 32位的開發環境http://www.ffmpeg.club


//引用ffmpeg頭文件,我這邊是C++必須加上extern "C",ffmpeg都是c語言函數,
//不加會鏈接失敗,找不到定義
extern "C"
{
#include<libavformat/avformat.h>
}
//引用lib庫,也可以在項目中設置,打開視頻只需要用到這三個庫
#pragma comment(lib,"avformat.lib")
#pragma comment(lib,"avutil.lib")
#pragma comment(lib,"avcodec.lib")
#include <iostream>
using namespace std;
int main(int argc,char *argv[])
{
//初始化所以ffmpeg的解碼器
av_register_all();
char path[1024] = "video.mp4";
//用來存放打開的視頻流信息
AVFormatContext *ic = NULL;
//用來存儲視頻流索引
int videoStream = 0;
//打開視頻播放流
//path參數表示打開的視頻路徑,這個路徑可以包括各種視頻文件
//也包括rtsp和http網絡視頻流
//第三個參數表示傳入的視頻格式,我這邊不傳遞有FFmpeg內部獲取
//最後一個參數是設置,我們這裏也不傳遞
int re = avformat_open_input(&ic, path, 0, 0);
if (re != 0)
{
//獲取到FFmpeg的錯誤信息
char errorbuf[1024] = {0};
av_strerror(re, errorbuf, sizeof(errorbuf));
printf("open %s failed: %s\n", path, errorbuf);
return -1;
}
//遍歷視頻流,裏面包含音頻流,視頻流,或者字母流,我們這裏只處理視頻
for (int i = 0; i < ic->nb_streams; i++)
{
AVCodecContext *enc = ic->streams[i]->codec;
//確認是視頻流
if (enc->codec_type == AVMEDIA_TYPE_VIDEO)
{
//存放視頻流索引,後面的代碼要用到
videoStream = i;
//找到解碼器,比如H264,解碼器的信息也是ffmpeg內部獲取的
AVCodec *codec = avcodec_find_decoder(enc->codec_id);
if (!codec)
{
printf("video code not find!\n");
return -2;
}
//打開視頻解碼器,打開音頻解碼器用的也是同一個函數
int err = avcodec_open2(enc, codec, NULL);
if (err != 0)
{
char buf[1024] = { 0 };
av_strerror(err, buf, sizeof(buf));
printf(buf);
return -3;
}
}
}
}



更多的資料也可以關注我csdn上的視頻課程
夏老師課程專欄http://edu.csdn.net/lecturer/961


http://edu.csdn.net/course/detail/3300


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