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


測試環境:windows10 

開發工具:VS2013

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

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

 

 
//引用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;
			}
		    
		    
		}
    }
}

    其他的視頻教程資料可以參考

C++ FFMpeg+Qt5開發播放器

http://edu.51cto.com/sd/07beb

http://ffmpeg.club/xiacaojun.html


免責聲明!

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



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