XBMC原始碼分析 4:視訊播放器(dvdplayer)-解碼器(以ffmpeg為例)
XBMC分析系列文章:
本文我們分析XBMC中視訊播放器(dvdplayer)中的解碼器部分。由於解碼器種類很多,不可能一一分析,因此以ffmpeg解碼器為例進行分析。
XBMC解碼器部分檔案目錄如下圖所示:
解碼器分為音訊解碼器和視訊解碼器。在這裡我們看一下視訊解碼器中的FFMPEG解碼器。對應DVDVideoCodecFFmpeg.h和DVDVideoCodecFFmpeg.cpp。
DVDVideoCodecFFmpeg.h原始碼如下所示:
該類中以下幾個函式包含了解碼器的幾種功能:/* * 雷霄驊 * [email protected] * 中國傳媒大學/數字電視技術 * */ #include "DVDVideoCodec.h" #include "DVDResource.h" #include "DllAvCodec.h" #include "DllAvFormat.h" #include "DllAvUtil.h" #include "DllSwScale.h" #include "DllAvFilter.h" #include "DllPostProc.h" class CCriticalSection; //封裝的FFMPEG視訊解碼器 class CDVDVideoCodecFFmpeg : public CDVDVideoCodec { public: class IHardwareDecoder : public IDVDResourceCounted<IHardwareDecoder> { public: IHardwareDecoder() {} virtual ~IHardwareDecoder() {}; virtual bool Open (AVCodecContext* avctx, const enum PixelFormat, unsigned int surfaces) = 0; virtual int Decode (AVCodecContext* avctx, AVFrame* frame) = 0; virtual bool GetPicture(AVCodecContext* avctx, AVFrame* frame, DVDVideoPicture* picture) = 0; virtual int Check (AVCodecContext* avctx) = 0; virtual void Reset () {} virtual unsigned GetAllowedReferences() { return 0; } virtual const std::string Name() = 0; virtual CCriticalSection* Section() { return NULL; } }; CDVDVideoCodecFFmpeg(); virtual ~CDVDVideoCodecFFmpeg(); virtual bool Open(CDVDStreamInfo &hints, CDVDCodecOptions &options);//開啟 virtual void Dispose();//關閉 virtual int Decode(uint8_t* pData, int iSize, double dts, double pts);//解碼 virtual void Reset(); bool GetPictureCommon(DVDVideoPicture* pDvdVideoPicture); virtual bool GetPicture(DVDVideoPicture* pDvdVideoPicture); virtual void SetDropState(bool bDrop); virtual unsigned int SetFilters(unsigned int filters); virtual const char* GetName() { return m_name.c_str(); }; // m_name is never changed after open virtual unsigned GetConvergeCount(); virtual unsigned GetAllowedReferences(); bool IsHardwareAllowed() { return !m_bSoftware; } IHardwareDecoder * GetHardware() { return m_pHardware; }; void SetHardware(IHardwareDecoder* hardware) { SAFE_RELEASE(m_pHardware); m_pHardware = hardware; UpdateName(); } protected: static enum PixelFormat GetFormat(struct AVCodecContext * avctx, const PixelFormat * fmt); int FilterOpen(const CStdString& filters, bool scale); void FilterClose(); int FilterProcess(AVFrame* frame); void UpdateName() { if(m_pCodecContext->codec->name) m_name = CStdString("ff-") + m_pCodecContext->codec->name; else m_name = "ffmpeg"; if(m_pHardware) m_name += "-" + m_pHardware->Name(); } AVFrame* m_pFrame; AVCodecContext* m_pCodecContext; CStdString m_filters; CStdString m_filters_next; AVFilterGraph* m_pFilterGraph; AVFilterContext* m_pFilterIn; AVFilterContext* m_pFilterOut; #if defined(LIBAVFILTER_AVFRAME_BASED) AVFrame* m_pFilterFrame; #else AVFilterBufferRef* m_pBufferRef; #endif int m_iPictureWidth; int m_iPictureHeight; int m_iScreenWidth; int m_iScreenHeight; int m_iOrientation;// orientation of the video in degress counter clockwise unsigned int m_uSurfacesCount; //封裝Dll的各種類 DllAvCodec m_dllAvCodec; DllAvUtil m_dllAvUtil; DllSwScale m_dllSwScale; DllAvFilter m_dllAvFilter; DllPostProc m_dllPostProc; std::string m_name; bool m_bSoftware; bool m_isHi10p; IHardwareDecoder *m_pHardware; int m_iLastKeyframe; double m_dts; bool m_started; std::vector<PixelFormat> m_formats; };
virtual bool Open(CDVDStreamInfo &hints, CDVDCodecOptions &options);//開啟
virtual void Dispose();//關閉
virtual int Decode(uint8_t* pData, int iSize, double dts, double pts);//解碼
virtual void Reset();//復位
為了說明這一點,我們可以看一下視訊解碼器中的libmpeg2解碼器,對應DVDVideoCodecLibMpeg2.h。可以看出這幾個函式是一樣的。
DVDVideoCodecLibMpeg2.h原始碼如下:
/* * 雷霄驊 * [email protected] * 中國傳媒大學/數字電視技術 * */ #include "DVDVideoCodec.h" #include "DllLibMpeg2.h" class CDVDVideoCodecLibMpeg2 : public CDVDVideoCodec { public: CDVDVideoCodecLibMpeg2(); virtual ~CDVDVideoCodecLibMpeg2(); virtual bool Open(CDVDStreamInfo &hints, CDVDCodecOptions &options); virtual void Dispose(); virtual int Decode(uint8_t* pData, int iSize, double dts, double pts); virtual void Reset(); virtual bool GetPicture(DVDVideoPicture* pDvdVideoPicture); virtual bool GetUserData(DVDVideoUserData* pDvdVideoUserData); virtual void SetDropState(bool bDrop); virtual const char* GetName() { return "libmpeg2"; } protected: DVDVideoPicture* GetBuffer(unsigned int width, unsigned int height); inline void ReleaseBuffer(DVDVideoPicture* pPic); inline void DeleteBuffer(DVDVideoPicture* pPic); static int GuessAspect(const mpeg2_sequence_t *sequence, unsigned int *pixel_width, unsigned int *pixel_height); mpeg2dec_t* m_pHandle; const mpeg2_info_t* m_pInfo; DllLibMpeg2 m_dll; unsigned int m_irffpattern; bool m_bFilm; //Signals that we have film material bool m_bIs422; int m_hurry; double m_dts; double m_dts2; //The buffer of pictures we need DVDVideoPicture m_pVideoBuffer[3]; DVDVideoPicture* m_pCurrentBuffer; };
現在回到DVDVideoCodecFFmpeg.h。我們可以看一下上文所示的4個函式。
Open()
//開啟
bool CDVDVideoCodecFFmpeg::Open(CDVDStreamInfo &hints, CDVDCodecOptions &options)
{
AVCodec* pCodec;
if(!m_dllAvUtil.Load()
|| !m_dllAvCodec.Load()
|| !m_dllSwScale.Load()
|| !m_dllPostProc.Load()
|| !m_dllAvFilter.Load()
) return false;
//註冊解碼器
m_dllAvCodec.avcodec_register_all();
m_dllAvFilter.avfilter_register_all();
m_bSoftware = hints.software;
m_iOrientation = hints.orientation;
for(std::vector<ERenderFormat>::iterator it = options.m_formats.begin(); it != options.m_formats.end(); ++it)
{
m_formats.push_back((PixelFormat)CDVDCodecUtils::PixfmtFromEFormat(*it));
if(*it == RENDER_FMT_YUV420P)
m_formats.push_back(PIX_FMT_YUVJ420P);
}
m_formats.push_back(PIX_FMT_NONE); /* always add none to get a terminated list in ffmpeg world */
pCodec = NULL;
m_pCodecContext = NULL;
if (hints.codec == AV_CODEC_ID_H264)
{
switch(hints.profile)
{
case FF_PROFILE_H264_HIGH_10:
case FF_PROFILE_H264_HIGH_10_INTRA:
case FF_PROFILE_H264_HIGH_422:
case FF_PROFILE_H264_HIGH_422_INTRA:
case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
case FF_PROFILE_H264_HIGH_444_INTRA:
case FF_PROFILE_H264_CAVLC_444:
// this is needed to not open the decoders
m_bSoftware = true;
// this we need to enable multithreading for hi10p via advancedsettings
m_isHi10p = true;
break;
}
}
//查詢解碼器
if(pCodec == NULL)
pCodec = m_dllAvCodec.avcodec_find_decoder(hints.codec);
if(pCodec == NULL)
{
CLog::Log(LOGDEBUG,"CDVDVideoCodecFFmpeg::Open() Unable to find codec %d", hints.codec);
return false;
}
CLog::Log(LOGNOTICE,"CDVDVideoCodecFFmpeg::Open() Using codec: %s",pCodec->long_name ? pCodec->long_name : pCodec->name);
if(m_pCodecContext == NULL)
m_pCodecContext = m_dllAvCodec.avcodec_alloc_context3(pCodec);
m_pCodecContext->opaque = (void*)this;
m_pCodecContext->debug_mv = 0;
m_pCodecContext->debug = 0;
m_pCodecContext->workaround_bugs = FF_BUG_AUTODETECT;
m_pCodecContext->get_format = GetFormat;
m_pCodecContext->codec_tag = hints.codec_tag;
/* Only allow slice threading, since frame threading is more
* sensitive to changes in frame sizes, and it causes crashes
* during HW accell - so we unset it in this case.
*
* When we detect Hi10p and user did not disable hi10pmultithreading
* via advancedsettings.xml we keep the ffmpeg default thread type.
* */
if(m_isHi10p && !g_advancedSettings.m_videoDisableHi10pMultithreading)
{
CLog::Log(LOGDEBUG,"CDVDVideoCodecFFmpeg::Open() Keep default threading for Hi10p: %d",
m_pCodecContext->thread_type);
}
else if (CSettings::Get().GetBool("videoplayer.useframemtdec"))
{
CLog::Log(LOGDEBUG,"CDVDVideoCodecFFmpeg::Open() Keep default threading %d by videoplayer.useframemtdec",
m_pCodecContext->thread_type);
}
else
m_pCodecContext->thread_type = FF_THREAD_SLICE;
#if defined(TARGET_DARWIN_IOS)
// ffmpeg with enabled neon will crash and burn if this is enabled
m_pCodecContext->flags &= CODEC_FLAG_EMU_EDGE;
#else
if (pCodec->id != AV_CODEC_ID_H264 && pCodec->capabilities & CODEC_CAP_DR1
&& pCodec->id != AV_CODEC_ID_VP8
)
m_pCodecContext->flags |= CODEC_FLAG_EMU_EDGE;
#endif
// if we don't do this, then some codecs seem to fail.
m_pCodecContext->coded_height = hints.height;
m_pCodecContext->coded_width = hints.width;
m_pCodecContext->bits_per_coded_sample = hints.bitsperpixel;
if( hints.extradata && hints.extrasize > 0 )
{
m_pCodecContext->extradata_size = hints.extrasize;
m_pCodecContext->extradata = (uint8_t*)m_dllAvUtil.av_mallocz(hints.extrasize + FF_INPUT_BUFFER_PADDING_SIZE);
memcpy(m_pCodecContext->extradata, hints.extradata, hints.extrasize);
}
// advanced setting override for skip loop filter (see avcodec.h for valid options)
// TODO: allow per video setting?
if (g_advancedSettings.m_iSkipLoopFilter != 0)
{
m_pCodecContext->skip_loop_filter = (AVDiscard)g_advancedSettings.m_iSkipLoopFilter;
}
// set any special options
for(std::vector<CDVDCodecOption>::iterator it = options.m_keys.begin(); it != options.m_keys.end(); ++it)
{
if (it->m_name == "surfaces")
m_uSurfacesCount = std::atoi(it->m_value.c_str());
else
m_dllAvUtil.av_opt_set(m_pCodecContext, it->m_name.c_str(), it->m_value.c_str(), 0);
}
int num_threads = std::min(8 /*MAX_THREADS*/, g_cpuInfo.getCPUCount());
if( num_threads > 1 && !hints.software && m_pHardware == NULL // thumbnail extraction fails when run threaded
&& ( pCodec->id == AV_CODEC_ID_H264
|| pCodec->id == AV_CODEC_ID_MPEG4 ))
m_pCodecContext->thread_count = num_threads;
//開啟解碼器
if (m_dllAvCodec.avcodec_open2(m_pCodecContext, pCodec, NULL) < 0)
{
CLog::Log(LOGDEBUG,"CDVDVideoCodecFFmpeg::Open() Unable to open codec");
return false;
}
//初始化AVFrame
m_pFrame = m_dllAvCodec.avcodec_alloc_frame();
if (!m_pFrame) return false;
#if defined(LIBAVFILTER_AVFRAME_BASED)
m_pFilterFrame = m_dllAvUtil.av_frame_alloc();
if (!m_pFilterFrame) return false;
#endif
UpdateName();
return true;
}
Dispose()//關閉
void CDVDVideoCodecFFmpeg::Dispose()
{
//釋放
if (m_pFrame) m_dllAvUtil.av_free(m_pFrame);
m_pFrame = NULL;
#if defined(LIBAVFILTER_AVFRAME_BASED)
m_dllAvUtil.av_frame_free(&m_pFilterFrame);
#endif
if (m_pCodecContext)
{
//關閉解碼器
if (m_pCodecContext->codec) m_dllAvCodec.avcodec_close(m_pCodecContext);
if (m_pCodecContext->extradata)
{
m_dllAvUtil.av_free(m_pCodecContext->extradata);
m_pCodecContext->extradata = NULL;
m_pCodecContext->extradata_size = 0;
}
m_dllAvUtil.av_free(m_pCodecContext);
m_pCodecContext = NULL;
}
SAFE_RELEASE(m_pHardware);
FilterClose();
m_dllAvCodec.Unload();
m_dllAvUtil.Unload();
m_dllAvFilter.Unload();
m_dllPostProc.Unload();
}
Decode()
//解碼
int CDVDVideoCodecFFmpeg::Decode(uint8_t* pData, int iSize, double dts, double pts)
{
int iGotPicture = 0, len = 0;
if (!m_pCodecContext)
return VC_ERROR;
if(pData)
m_iLastKeyframe++;
shared_ptr<CSingleLock> lock;
if(m_pHardware)
{
CCriticalSection* section = m_pHardware->Section();
if(section)
lock = shared_ptr<CSingleLock>(new CSingleLock(*section));
int result;
if(pData)
result = m_pHardware->Check(m_pCodecContext);
else
result = m_pHardware->Decode(m_pCodecContext, NULL);
if(result)
return result;
}
if(m_pFilterGraph)
{
int result = 0;
if(pData == NULL)
result = FilterProcess(NULL);
if(result)
return result;
}
m_dts = dts;
m_pCodecContext->reordered_opaque = pts_dtoi(pts);
//初始化AVPacket
AVPacket avpkt;
m_dllAvCodec.av_init_packet(&avpkt);
avpkt.data = pData;
avpkt.size = iSize;
/* We lie, but this flag is only used by pngdec.c.
* Setting it correctly would allow CorePNG decoding. */
avpkt.flags = AV_PKT_FLAG_KEY;
//解碼
len = m_dllAvCodec.avcodec_decode_video2(m_pCodecContext, m_pFrame, &iGotPicture, &avpkt);
if(m_iLastKeyframe < m_pCodecContext->has_b_frames + 2)
m_iLastKeyframe = m_pCodecContext->has_b_frames + 2;
if (len < 0)
{
CLog::Log(LOGERROR, "%s - avcodec_decode_video returned failure", __FUNCTION__);
return VC_ERROR;
}
if (!iGotPicture)
return VC_BUFFER;
if(m_pFrame->key_frame)
{
m_started = true;
m_iLastKeyframe = m_pCodecContext->has_b_frames + 2;
}
/* put a limit on convergence count to avoid huge mem usage on streams without keyframes */
if(m_iLastKeyframe > 300)
m_iLastKeyframe = 300;
/* h264 doesn't always have keyframes + won't output before first keyframe anyway */
if(m_pCodecContext->codec_id == AV_CODEC_ID_H264
|| m_pCodecContext->codec_id == AV_CODEC_ID_SVQ3)
m_started = true;
if(m_pHardware == NULL)
{
bool need_scale = std::find( m_formats.begin()
, m_formats.end()
, m_pCodecContext->pix_fmt) == m_formats.end();
bool need_reopen = false;
if(!m_filters.Equals(m_filters_next))
need_reopen = true;
if(m_pFilterIn)
{
if(m_pFilterIn->outputs[0]->format != m_pCodecContext->pix_fmt
|| m_pFilterIn->outputs[0]->w != m_pCodecContext->width
|| m_pFilterIn->outputs[0]->h != m_pCodecContext->height)
need_reopen = true;
}
// try to setup new filters
if (need_reopen || (need_scale && m_pFilterGraph == NULL))
{
m_filters = m_filters_next;
if(FilterOpen(m_filters, need_scale) < 0)
FilterClose();
}
}
int result;
if(m_pHardware)
result = m_pHardware->Decode(m_pCodecContext, m_pFrame);
else if(m_pFilterGraph)
result = FilterProcess(m_pFrame);
else
result = VC_PICTURE | VC_BUFFER;
if(result & VC_FLUSHED)
Reset();
return result;
}
Reset()//復位
void CDVDVideoCodecFFmpeg::Reset()
{
m_started = false;
m_iLastKeyframe = m_pCodecContext->has_b_frames;
m_dllAvCodec.avcodec_flush_buffers(m_pCodecContext);
if (m_pHardware)
m_pHardware->Reset();
m_filters = "";
FilterClose();
}
相關推薦
XBMC原始碼分析 4:視訊播放器(dvdplayer)-解碼器(以ffmpeg為例)
XBMC分析系列文章: 本文我們分析XBMC中視訊播放器(dvdplayer)中的解碼器部分。由於解碼器種類很多,不可能一一分析,因此以ffmpeg解碼器為例進行分析。 XBMC解碼器部分檔案目錄如下圖所示: 解碼器分為音訊解碼器和視訊解碼器。在這裡我們看一下視訊
XBMC原始碼分析 6:視訊播放器(dvdplayer)-檔案頭(以ffmpeg為例)
XBMC分析系列文章: XBMC原始碼簡析 5:視訊播放器(dvdplayer)-解複用器(以ffmpeg為例)本文我們分析XBMC中視訊播放器(dvdplayer)中的檔案頭部分。檔案頭部分裡包含的是封裝Dll用到的標頭檔案。由於檔案頭種類很多,不可能一一分析,
ffdshow 原始碼分析 8: 視訊解碼器類(TvideoCodecDec)
=====================================================ffdshow原始碼分析系列文章列表:=====================================================前面兩篇文章介紹了ffds
WebRTC原始碼分析四:視訊模組結構
本文在上篇的基礎上介紹WebRTC視訊部分的模組結構,以進一步瞭解其實現框架,只有瞭解了整體框架結構,對區域性演算法修改才能夠胸有成竹。 一、對外介面 對外介面有ViEBase,ViECapture,ViECodec,ViEEncryption,V
WebRTC原始碼分析三:視訊處理流程
文字介紹視訊的處理流程。圖1中顯示了兩路視訊會話視訊訊號流過程。 圖1 視訊流程示意圖 以一路視訊會話為例,主要分為以下幾個執行緒: 1)視訊源產生執行緒:Camera生產視訊畫面,封裝成視訊幀,以一定幀率投遞到下一個模組。; 2)採集執行緒:由Capturer負責採集視訊幀,並對視訊幀進行一定處理,如
XBMC原始碼分析 1:整體結構以及編譯方法
XBMC(全稱是XBOX Media Center)是一個開源的媒體中心軟體。XBMC最初為Xbox而開發,可以執行在Linux、OSX、Windows、Android4.0系統。我自己下載了一個然後體驗了一下,感覺確實不錯,和Windows自帶的媒體中心差不多。 XB
SDL2原始碼分析4:紋理(SDL_Texture)
=====================================================SDL原始碼分析系列文章列表:=====================================================上一篇文章分析了SDL中建立渲染器
leveldb原始碼分析4:SkipList
skiplist思想可以具體參考這: // Create a new SkipList object that will use "cmp" for comparing keys, // and will allocate memory using "*ar
Android 5.0 Camera系統原始碼分析(4):Camera預覽流程資料流
1. 前言 上一篇講了怎麼讓Camera進入預覽模式,提到了DisplayClient負責顯示影象資料,而CamAdapter負責提供影象資料,這裡主要記錄了CamAdapter怎麼獲取影象,然後DisplayClient怎麼將影象顯示在螢幕上。 2.
SpringMVC原始碼分析4:DispatcherServlet如何找到正確的Controller
SpringMVC是目前主流的Web MVC框架之一。 我們使用瀏覽器通過地址 http://ip:port/contextPath/path進行訪問,SpringMVC是如何得知使用者到底是訪問哪個Controller中的方法,這期間到底發生了什麼。 本文將分析SpringMVC是如何處理請求與
DevOps之旅:運維人員閱讀原始碼的實用技巧(以OpenStack為例)
作者簡介 陳晨 基礎架構工程師,目前就職於中國銀聯。主要負責IaaS平臺、容器平臺以及運維管理平臺的建設工作。 在昨天的文章中,我們初步講解了一些關於學習原始碼的基礎知識,今天我們著重介紹一下學習原始碼的一些技巧。原文連結如下: 一、準備階段 1. 制定計劃 讀原始碼和讀書一樣,必須有時間計劃,d
linux驅動由淺入深系列:塊裝置驅動之三(塊裝置驅動結構分析,以mmc為例)
linux驅動由淺入深系列:塊裝置驅動之一(高通eMMC分割槽例項)前一篇文章介紹了塊裝置驅動在linux框架張的位置關係,本文來分析一下驅動本身。塊裝置驅動的模型還是基本基於字元裝置驅動的,可以簡單理解為塊裝置僅僅增加了操作緩衝區,對使用者操作請求進行佇列重排。因此只在有了
原創:PHP利用session,實現用戶登錄後回到點擊的頁面(本文以TP為例)
con gop query php代碼 自帶 ttr strpos 手機 roo 1、以下內容純屬原創,請謹慎選擇: ①目的:用戶登錄超時,session過期,點擊後跳轉到登錄頁,登錄成功再跳轉到鼠標點擊的頁面。 ②流程:用戶登錄---session過期---點擊跳
OpenGL學習(五) 著色器渲染(以Android為例)
back lse setw %d 編譯 clas ddr attr type 一、Android平臺上下文環境的創建及初始化 1. 首先實例化Android上下文環境,即EGL的初始化。 bool EGLCore::init(EGLContext sharedContex
天地圖專題七:行政區域標記,熱力圖(以廣西為例)
天地圖方面的文章已很久不寫。 主要是因為上一個專案結束,基本就不用天地圖了。用百度地圖的可能更大一些。 最近上個專案甲方想搞一個類似熱力圖,熱點圖的東西。在天地圖API上沒有找到類似的直接畫熱力圖的介面,只好用了一些替代的方法。 天地圖行政區域,行政區劃直接介面也沒找到,用
[GIS演算法] DEM相關處理 - 視窗分析(以平均值為例)| 裁剪 - C語言實現
#include<stdio.h> #include<stdlib.h> typedef struct{ double x0,y0; //左下角點的座標值 int dx,dy; //柵格單元大小 int ycount,xcount; //行列號 doub
如何在二維或三維地圖中疊加一個視訊(以mapboxgl為例)
手上有一個交通分析結果視訊,正射視角,來自遙感衛星視訊,通過加工形成交通流量視訊分析成果,現在需要把分析結果放在地圖中進行視覺化展示 mapboxgl的地圖如下 map = new mapboxgl.Map({ contai
Arduino核心檔案分析(以Stm32duino為例)
這篇部落格主要是分析stm32duino的底層檔案結構,來分析stm32duino 的實現原理和它的基本框架。 使用的工具是Source Insight ,新建工程,新增原始碼路徑之後可以進行分析。 開啟工程原始碼的資料夾後,有四個資料夾,我們主要分
視窗分析(以平均值為例)| 裁剪
#include<stdio.h> #include<stdlib.h> typedef struct{ double x0,y0; //左下角點的座標值 int dx,dy; //柵格單元大小 int ycount,xcount
【Python專案】基於文字情感分析的電商評論重排序(以京東為例)(附程式碼)
一、背景 隨著網際網路的普及,網路購物已經成了人們購物的首選。使用者只需在電商平臺搜尋商品名,便可得到成百上千條商品資訊。商品資訊的排序演算法很複雜,但總的說來基本上都是根據與搜尋關鍵詞的關聯度和商品的人氣或商家排名來排序最終對使用者進行展示的。而好評率即是排