FFmpeg 開發(02):FFmpeg + ANativeWindow 實現視頻解碼播放

FFmpeg + ANativeWindow 實現視頻解碼播放

該原創文章首發於微信公衆號:字節流動

本文將利用 FFmpeg 對一個 Mp4 文件的視頻流進行解碼,然後使用 libswscale 將解碼後的 YUV 幀轉換爲 RGBA 幀,最後使用 ANativeWindow 進行渲染。

在這裏插入圖片描述

FFmpeg 視頻解碼

雷霄華博士的音視頻處理流程圖

參考雷霄驊博士的音視頻處理流程圖,我們大概瞭解了本節的處理流程:(Mp4文件)解協議->解封裝->視頻解碼->縮放或格式轉換->渲染。

關於 FFmpeg 需要了解的幾個結構體:

  • AVFormatContext:解封裝功能的結構體,包含文件名、音視頻流、時長、比特率等信息;
  • AVCodecContext:編解碼器上下文,編碼和解碼時必須用到的結構體,包含編解碼器類型、視頻寬高、音頻通道數和採樣率等信息;
  • AVCodec:存儲編解碼器信息的結構體;
  • AVStream:存儲音頻或視頻流信息的結構體;
  • AVPacket:存儲音頻或視頻編碼數據;
  • AVFrame:存儲音頻或視頻解碼數據(原始數據);

FFmpeg 視頻解碼播放流程

視頻解碼流程:

//1.創建封裝格式上下文
m_AVFormatContext = avformat_alloc_context();

//2.打開輸入文件,解封裝
if(avformat_open_input(&m_AVFormatContext, m_Url, NULL, NULL) != 0)
{
    LOGCATE("DecoderBase::InitFFDecoder avformat_open_input fail.");
    break;
}

//3.獲取音視頻流信息
if(avformat_find_stream_info(m_AVFormatContext, NULL) < 0) {
    LOGCATE("DecoderBase::InitFFDecoder avformat_find_stream_info fail.");
    break;
}

//4.獲取音視頻流索引
for(int i=0; i < m_AVFormatContext->nb_streams; i++) {
    if(m_AVFormatContext->streams[i]->codecpar->codec_type == m_MediaType) {
        m_StreamIndex = i;
        break;
    }
}

if(m_StreamIndex == -1) {
    LOGCATE("DecoderBase::InitFFDecoder Fail to find stream index.");
    break;
}
//5.獲取解碼器參數
AVCodecParameters *codecParameters = m_AVFormatContext->streams[m_StreamIndex]->codecpar;

//6.根據 codec_id 獲取解碼器
m_AVCodec = avcodec_find_decoder(codecParameters->codec_id);
if(m_AVCodec == nullptr) {
    LOGCATE("DecoderBase::InitFFDecoder avcodec_find_decoder fail.");
    break;
}

//7.創建解碼器上下文
m_AVCodecContext = avcodec_alloc_context3(m_AVCodec);
if(avcodec_parameters_to_context(m_AVCodecContext, codecParameters) != 0) {
    LOGCATE("DecoderBase::InitFFDecoder avcodec_parameters_to_context fail.");
    break;
}

//8.打開解碼器
result = avcodec_open2(m_AVCodecContext, m_AVCodec, NULL);
if(result < 0) {
    LOGCATE("DecoderBase::InitFFDecoder avcodec_open2 fail. result=%d", result);
    break;
}

//9.創建存儲編碼數據和解碼數據的結構體
m_Packet = av_packet_alloc(); //創建 AVPacket 存放編碼數據
m_Frame = av_frame_alloc(); //創建 AVFrame 存放解碼後的數據

//10.解碼循環
while (av_read_frame(m_AVFormatContext, m_Packet) >= 0) { //讀取幀
    if (m_Packet->stream_index == m_StreamIndex) {
        if (avcodec_send_packet(m_AVCodecContext, m_Packet) != 0) { //視頻解碼
            return -1;
        }
        while (avcodec_receive_frame(m_AVCodecContext, m_Frame) == 0) {
			//獲取到 m_Frame 解碼數據,在這裏進行格式轉換,然後進行渲染,下一節介紹 ANativeWindow 渲染過程
        }
    }
    av_packet_unref(m_Packet); //釋放 m_Packet 引用,防止內存泄漏
}

//11.釋放資源,解碼完成
if(m_Frame != nullptr) {
    av_frame_free(&m_Frame);
    m_Frame = nullptr;
}

if(m_Packet != nullptr) {
    av_packet_free(&m_Packet);
    m_Packet = nullptr;
}

if(m_AVCodecContext != nullptr) {
    avcodec_close(m_AVCodecContext);
    avcodec_free_context(&m_AVCodecContext);
    m_AVCodecContext = nullptr;
    m_AVCodec = nullptr;
}

if(m_AVFormatContext != nullptr) {
    avformat_close_input(&m_AVFormatContext);
    avformat_free_context(m_AVFormatContext);
    m_AVFormatContext = nullptr;
}

ANativeWindow 渲染解碼幀

每一種操作系統都定義了自己的窗口系統,而 ANativeWindow 就是 Android 的本地窗口,在 Android Java 層,Surface 又繼承於 ANativeWindow ,實際上 Surface 是 ANativeWindow 的具體實現,所以一個 ANativeWindow 表示的就是一塊屏幕緩衝區。

我們要渲染一幀圖像,只需要將圖像數據刷進 ANativeWindow 所表示的屏幕緩衝區即可。

enum {
    // NOTE: these values must match the values from graphics/common/x.x/types.hal

    /** Red: 8 bits, Green: 8 bits, Blue: 8 bits, Alpha: 8 bits. **/
    WINDOW_FORMAT_RGBA_8888          = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
    /** Red: 8 bits, Green: 8 bits, Blue: 8 bits, Unused: 8 bits. **/
    WINDOW_FORMAT_RGBX_8888          = AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM,
    /** Red: 5 bits, Green: 6 bits, Blue: 5 bits. **/
    WINDOW_FORMAT_RGB_565            = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM,
};

需要注意的是 ANativeWindow 僅支持 RGB 類型的圖像數據,所以我們還需要利用 libswscale 庫將解碼後的 YUV 數據轉成 RGB 。

利用 libswscale 庫將對圖像進行格式轉換,有如下幾個步驟:

//1. 分配存儲 RGB 圖像的 buffer
m_VideoWidth = m_AVCodecContext->width;
m_VideoHeight = m_AVCodecContext->height;

m_RGBAFrame = av_frame_alloc();
//計算 Buffer 的大小 
int bufferSize = av_image_get_buffer_size(AV_PIX_FMT_RGBA, m_VideoWidth, m_VideoHeight, 1);
//爲 m_RGBAFrame 分配空間
m_FrameBuffer = (uint8_t *) av_malloc(bufferSize * sizeof(uint8_t));
av_image_fill_arrays(m_RGBAFrame->data, m_RGBAFrame->linesize, m_FrameBuffer, AV_PIX_FMT_RGBA,
                     m_VideoWidth, m_VideoHeight, 1);
//2. 獲取轉換的上下文
m_SwsContext = sws_getContext(m_VideoWidth, m_VideoHeight, m_AVCodecContext->pix_fmt,
                           m_RenderWidth, m_RenderHeight, AV_PIX_FMT_RGBA,
                           SWS_FAST_BILINEAR, NULL, NULL, NULL);

//3. 格式轉換
sws_scale(m_SwsContext, frame->data, frame->linesize, 0, m_VideoHeight, m_RGBAFrame->data, m_RGBAFrame->linesize);

//4. 釋放資源
if(m_RGBAFrame != nullptr) {
    av_frame_free(&m_RGBAFrame);
    m_RGBAFrame = nullptr;
}

if(m_FrameBuffer != nullptr) {
    free(m_FrameBuffer);
    m_FrameBuffer = nullptr;
}

if(m_SwsContext != nullptr) {
    sws_freeContext(m_SwsContext);
    m_SwsContext = nullptr;
    }

我們拿到了 RGBA 格式的圖像,可以利用 ANativeWindow 進行渲染了。

//1. 利用 Java 層 SurfaceView 傳下來的 Surface 對象,獲取 ANativeWindow
m_NativeWindow = ANativeWindow_fromSurface(env, surface);

//2. 設置渲染區域和輸入格式
ANativeWindow_setBuffersGeometry(m_NativeWindow, m_VideoWidth,
                                     m_VideoHeight, WINDOW_FORMAT_RGBA_8888);

//3. 渲染
ANativeWindow_Buffer m_NativeWindowBuffer;
//鎖定當前 Window ,獲取屏幕緩衝區 Buffer 的指針
ANativeWindow_lock(m_NativeWindow, &m_NativeWindowBuffer, nullptr);
uint8_t *dstBuffer = static_cast<uint8_t *>(m_NativeWindowBuffer.bits);

int srcLineSize = m_RGBAFrame->linesize[0];//輸入圖的步長(一行像素有多少字節)
int dstLineSize = m_NativeWindowBuffer.stride * 4;//RGBA 緩衝區步長

for (int i = 0; i < m_VideoHeight; ++i) {
    //一行一行地拷貝圖像數據
    memcpy(dstBuffer + i * dstLineSize, m_FrameBuffer + i * srcLineSize, srcLineSize);
}
//解鎖當前 Window ,渲染緩衝區數據
ANativeWindow_unlockAndPost(m_NativeWindow);

//4. 釋放 ANativeWindow 
if(m_NativeWindow)
    ANativeWindow_release(m_NativeWindow);

以上就是 FFmpeg + ANativeWindow 實現視頻解碼播放的整個過程。

實現代碼路徑:
Android Learn FFmpeg

參考

https://blog.csdn.net/leixiaohua1020

聯繫與交流

聯繫我

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