Android Studio NDK開發(fā)(十三):FFmpeg視頻解碼

1. 前言

前面已經(jīng)介紹了播放一個(gè)視頻文件的流程圖

1.png

而視頻解碼是播放視頻文件的一個(gè)步驟,本篇博客將介紹FFmpeg視頻解碼。

首先我們簡單的了解一下FFmpeg八大庫:

2. FFmpeg庫簡介

庫的名稱 庫的作用
avcodec 該庫是音視頻編解碼的核心庫,用于各種類型聲音、圖像編解碼
avformat 各種音視頻封裝格式的處理,為avcodec庫提供獨(dú)立的音頻或視頻碼流源
avfilter 音視頻濾波器的開發(fā),濾鏡特效的處理
avdevice 硬件采集、加速、顯示,各種設(shè)備的輸入輸出
avutil 工具庫,大部分庫都需要這個(gè)庫的支持
postproc 音視頻應(yīng)用后期效果處理,如圖像的去塊效應(yīng)
swresample 音頻采樣數(shù)據(jù)格式轉(zhuǎn)換
swscale 視頻像素?cái)?shù)據(jù)格式轉(zhuǎn)換

而視頻轉(zhuǎn)碼將用到其中的三個(gè)庫,分別是avcodec、avformat、swscale

3. FFmpeg解碼的函數(shù)

3.1 FFmpeg解碼流程圖

2.png

3.2 FFmpeg解碼函數(shù)簡介

av_register_all():注冊所有組件
avformat_open_input():打開輸入視頻文件
avformat_find_stream_info():獲取視頻文件信息
avcodec_find_decoder():查找解碼器
avcodec_open2():打開解碼器
av_read_frame():從輸入文件讀取一幀壓縮數(shù)據(jù)
avcodec_decode_video2():解碼一幀壓縮數(shù)據(jù)
avcodec_close():關(guān)閉解碼器
avformat_close_input():關(guān)閉輸入視頻文件

開始接觸這些函數(shù)時(shí),必然很陌生,我們需要熟記這些函數(shù),因?yàn)榧磳⑦M(jìn)行的視頻解碼,這些函數(shù)都會(huì)用到。

4. FFmpeg數(shù)據(jù)結(jié)構(gòu)簡介

  • AVFormatContext

封裝格式上下文結(jié)構(gòu)體,也是統(tǒng)領(lǐng)全局的結(jié)構(gòu)體,保存了視頻文件封裝格式相關(guān)信息。

  1. iformat:輸入視頻的AVInputFormat
  2. nb_streams :輸入視頻的AVStream 個(gè)數(shù)
  3. streams :輸入視頻的AVStream []數(shù)組
  4. duration :輸入視頻的時(shí)長(以微秒為單位)
  5. bit_rate :輸入視頻的碼率
  • AVInputFormat

每種封裝格式(例如FLV、MKV、MP4、AVI)對應(yīng)一個(gè)該結(jié)構(gòu)體。

  1. name:封裝格式名稱
  2. long_name:封裝格式的長名稱
  3. extensions:封裝格式的擴(kuò)展名
  4. id:封裝格式ID
  5. 一些封裝格式處理的接口函數(shù)
  • AVStream

視頻文件中每個(gè)視頻(音頻)流對應(yīng)一個(gè)該結(jié)構(gòu)體。

  1. id:序號(hào)
  2. codec:該流對應(yīng)的AVCodecContext
  3. time_base:該流的時(shí)基
  4. r_frame_rate: 該流的幀率
  • AVCodeContext

編碼器上下文結(jié)構(gòu)體,保存了視頻(音頻)編解碼相關(guān)信息。

  1. codec:編解碼器的AVCodec
  2. width, height:圖像的寬高(只針對視頻)
  3. pix_fmt:像素格式(只針對視頻)
  4. sample_rate:采樣率(只針對音頻)
  5. channels:聲道數(shù)(只針對音頻)
  6. sample_fmt:采樣格式(只針對音頻)
  • AVCodec

每種視頻(音頻)編解碼器(例如H.264解碼器)對應(yīng)一個(gè)該結(jié)構(gòu)體。

  1. name:編解碼器名稱
  2. long_name:編解碼器長名稱
  3. type:編解碼器類型
  4. id:編解碼器ID
  5. 一些編解碼的接口函數(shù)
  • AVPacket

存儲(chǔ)一幀壓縮編碼數(shù)據(jù)。

  1. pts:顯示時(shí)間戳
  2. dts :解碼時(shí)間戳
  3. data :壓縮編碼數(shù)據(jù)
  4. size :壓縮編碼數(shù)據(jù)大小
  5. stream_index :所屬的AVStream
  • AVFrame

存儲(chǔ)一幀解碼后像素(采樣)數(shù)據(jù)。

  1. data:解碼后的圖像像素?cái)?shù)據(jù)(音頻采樣數(shù)據(jù))
  2. linesize:對視頻來說是圖像中一行像素的大??;對音頻來說是整個(gè)音頻幀的大小
  3. width, height:圖像的寬高(只針對視頻)
  4. key_frame:是否為關(guān)鍵幀(只針對視頻)
  5. pict_type:幀類型(只針對視頻) ,例如I, P, B

有人要說了,這么多數(shù)據(jù)結(jié)構(gòu)我怎么記啊,其實(shí)并不需要大家去記,我們只要心里有個(gè)印象,在用的時(shí)候能用起來就行,通過用也能幫助我們記憶。

4. 原理簡述

本次我們要做的是把一個(gè)mp4視頻文件轉(zhuǎn)換成yuv視頻文件,所以我們拿到mp4視頻文件獲取到視頻流的位置,從而獲取編解碼上下文,然后循環(huán)讀取數(shù)據(jù)包獲取AVFrame像素?cái)?shù)據(jù),而最后想要轉(zhuǎn)換成yuv視頻文件,所以需要將此時(shí)的像素?cái)?shù)據(jù)轉(zhuǎn)換成YUV420P像素?cái)?shù)據(jù),最后寫入輸出文件中。

5. FFmpeg解碼過程

5.1 注冊所有組件

av_register_all();

5.2 打開輸入視頻文件

//封裝格式上下文
AVFormatContext* pFormatCtx = avformat_alloc_context();
//2. 打開輸入視頻文件,成功返回0,第三個(gè)參數(shù)為NULL,表示自動(dòng)檢測文件格式
if (avformat_open_input(&pFormatCtx, input_cstr, NULL, NULL) != 0) {
        LOGE("%s", "打開輸入視頻文件失敗");
        return;
    }

當(dāng)我們不知道某個(gè)函數(shù)怎么使用的時(shí)候,我們可以點(diǎn)進(jìn)去,查看它函數(shù)的注釋,通過這些去了解函數(shù)使用和需要傳入什么樣的值,比如avformat_open_input函數(shù):

/**
 * Open an input stream and read the header. The codecs are not opened.
 * The stream must be closed with avformat_close_input().
 *
 * @param ps Pointer to user-supplied AVFormatContext (allocated by avformat_alloc_context).
 *           May be a pointer to NULL, in which case an AVFormatContext is allocated by this
 *           function and written into ps.
 *           Note that a user-supplied AVFormatContext will be freed on failure.
 * @param url URL of the stream to open.
 * @param fmt If non-NULL, this parameter forces a specific input format.
 *            Otherwise the format is autodetected.
 * @param options  A dictionary filled with AVFormatContext and demuxer-private options.
 *                 On return this parameter will be destroyed and replaced with a dict containing
 *                 options that were not found. May be NULL.
 *
 * @return 0 on success, a negative AVERROR on failure.
 *
 * @note If you want to use custom IO, preallocate the format context and set its pb field.
 */

從函數(shù)注釋中我們得知第三個(gè)參數(shù)為NULL的時(shí)候,就表示自動(dòng)檢測文件格式,還有需要關(guān)流,通過調(diào)用avformat_close_input()函數(shù)去實(shí)現(xiàn),......,很多信息都可以從這里得到,我們需要學(xué)會(huì)這種方式去了解函數(shù)使用。

5.3 獲取視頻文件信息

if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
        LOGE("%s", "獲取視頻文件信息失敗");
        return;
    }
//查找視頻流所在的位置
//遍歷所有類型的流(視頻流、音頻流可能還有字幕流),找到視頻流的位置
int video_stream_index = -1;
    int i = 0;
    for(; i < pFormatCtx -> nb_streams; i++) {
        if (pFormatCtx->streams[i]->codec-> codec_type == AVMEDIA_TYPE_VIDEO) {
            video_stream_index = i;
            break;
        }
    }

5.4 查找解碼器

//編解碼上下文
AVCodecContext* pCodecCtx = pFormatCtx->streams[video_stream_index]->codec;
//4. 查找解碼器 不能通過pCodecCtx->codec獲得解碼器
AVCodec* pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
        LOGE("%s", "查找解碼器失敗");
        return;
    }

5.5 打開解碼器

if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
        LOGE("%s", "打開解碼器失敗");
        return;
    }

5.6 讀取壓縮的視頻數(shù)據(jù)AVPacket

av_read_frame(pFormatCtx, pPacket)

5.7 解碼一幀壓縮數(shù)據(jù)AVPacket ---> AVFrame

avcodec_decode_video2(pCodecCtx, pFrame, &got_frame, pPacket);

6. 完整JNI代碼zp_decode.c

//
// Created by zp on 2017/12/5.
//
#include <jni.h>
#include <android/log.h>

//解碼
#include "libavcodec/avcodec.h"
//封裝格式
#include "libavformat/avformat.h"
//縮放
#include "libswscale/swscale.h"

#define LOGI(FORMAT, ...) __android_log_print(ANDROID_LOG_INFO, "zp", FORMAT, ##__VA_ARGS__);
#define LOGE(FORMAT, ...) __android_log_print(ANDROID_LOG_ERROR, "zp", FORMAT, ##__VA_ARGS__);

JNIEXPORT void JNICALL
Java_com_zhangpan_zpplayer_util_VideoUtils_decode(JNIEnv *env, jclass type, jstring input_jstr,
jstring output_jstr) {
    const char* input_cstr = (*env) -> GetStringUTFChars(env, input_jstr, NULL);
    const char* output_cstr = (*env) -> GetStringUTFChars(env, output_jstr, NULL);

    //1. 注冊所有組件
    av_register_all();

    //封裝格式上下文
    AVFormatContext* pFormatCtx = avformat_alloc_context();
    //2. 打開輸入視頻文件,成功返回0,第三個(gè)參數(shù)為NULL,表示自動(dòng)檢測文件格式
    if (avformat_open_input(&pFormatCtx, input_cstr, NULL, NULL) != 0) {
        LOGE("%s", "打開輸入視頻文件失敗");
        return;
    }

    //3. 獲取視頻文件信息
    if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
        LOGE("%s", "獲取視頻文件信息失敗");
        return;
    }

    //查找視頻流所在的位置
    //遍歷所有類型的流(視頻流、音頻流可能還有字幕流),找到視頻流的位置
    int video_stream_index = -1;
    int i = 0;
    for(; i < pFormatCtx -> nb_streams; i++) {
        if (pFormatCtx->streams[i]->codec-> codec_type == AVMEDIA_TYPE_VIDEO) {
            video_stream_index = i;
            break;
        }
    }

    //編解碼上下文
    AVCodecContext* pCodecCtx = pFormatCtx->streams[video_stream_index]->codec;
    //4. 查找解碼器 不能通過pCodecCtx->codec獲得解碼器
    AVCodec* pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
    if (pCodec == NULL) {
        LOGE("%s", "查找解碼器失敗");
        return;
    }

    //5. 打開解碼器
    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
        LOGE("%s", "打開解碼器失敗");
        return;
    }

    //編碼數(shù)據(jù)
    AVPacket* pPacket = (AVPacket*)av_malloc(sizeof(AVPacket));

    //像素?cái)?shù)據(jù)(解碼數(shù)據(jù))
    AVFrame* pFrame = av_frame_alloc();
    AVFrame* pYuvFrame = av_frame_alloc();

    FILE* fp_yuv = fopen(output_cstr, "wb");

    //只有指定了AVFrame的像素格式、畫面大小才能真正分配內(nèi)存
    //緩沖區(qū)分配內(nèi)存
    uint8_t* out_buffer = (uint8_t*)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
    //初始化緩沖區(qū)
    avpicture_fill((AVPicture*)pYuvFrame, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);

    //srcW:源圖像的寬
    //srcH:源圖像的高
    //srcFormat:源圖像的像素格式
    //dstW:目標(biāo)圖像的寬
    //dstH:目標(biāo)圖像的高
    //dstFormat:目標(biāo)圖像的像素格式
    //flags:設(shè)定圖像拉伸使用的算法
    struct SwsContext* pSwsCtx = sws_getContext(
            pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
            pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P,
            SWS_BILINEAR, NULL, NULL, NULL);

    int got_frame, len, frameCount = 0;
    //6. 從輸入文件一幀一幀讀取壓縮的視頻數(shù)據(jù)AVPacket
    while(av_read_frame(pFormatCtx, pPacket) >= 0) {
        if (pPacket->stream_index == video_stream_index) {
            //7. 解碼一幀壓縮數(shù)據(jù)AVPacket ---> AVFrame,第3個(gè)參數(shù)為0時(shí)表示解碼完成
            len = avcodec_decode_video2(pCodecCtx, pFrame, &got_frame, pPacket);

            if (len < 0) {
                LOGE("%s", "解碼失敗");
                return;
            }
            //AVFrame ---> YUV420P
            //srcSlice[]、dst[]        輸入、輸出數(shù)據(jù)
            //srcStride[]、dstStride[] 輸入、輸出畫面一行的數(shù)據(jù)的大小 AVFrame 轉(zhuǎn)換是一行一行轉(zhuǎn)換的
            //srcSliceY                輸入數(shù)據(jù)第一列要轉(zhuǎn)碼的位置 從0開始
            //srcSliceH                輸入畫面的高度
            sws_scale(pSwsCtx,
                      pFrame->data, pFrame->linesize, 0, pFrame->height,
                      pYuvFrame->data, pYuvFrame->linesize);

            //非0表示正在解碼
            if (got_frame) {
                //圖像寬高的乘積就是視頻的總像素,而一個(gè)像素包含一個(gè)y,u對應(yīng)1/4個(gè)y,v對應(yīng)1/4個(gè)y
                int yuv_size = pCodecCtx->width * pCodecCtx->height;
                //寫入y的數(shù)據(jù)
                fwrite(pYuvFrame->data[0], 1, yuv_size, fp_yuv);
                //寫入u的數(shù)據(jù)
                fwrite(pYuvFrame->data[1], 1, yuv_size/4, fp_yuv);
                //寫入v的數(shù)據(jù)
                fwrite(pYuvFrame->data[2], 1, yuv_size/4, fp_yuv);

                LOGI("解碼第%d幀", frameCount++);
            }
            av_free_packet(pPacket);
        }
    }

    fclose(fp_yuv);
    av_frame_free(&pFrame);
    av_frame_free(&pYuvFrame);
    avcodec_free_context(&pCodecCtx);
    avformat_free_context(pFormatCtx);

    (*env) -> ReleaseStringUTFChars(env, input_jstr, input_cstr);
    (*env) -> ReleaseStringUTFChars(env, output_jstr, output_cstr);
}

解碼主要是在C中做的,Java中只是簡單的調(diào)用了,具體的配置,請看我的上一篇博客:Android Studio NDK開發(fā)(十二):FFmpeg編譯與配置,直接看測試FFmpeg模塊。

編譯運(yùn)行完之后,將輸出文件復(fù)制到電腦中,用YUV專屬播放器播放,能完整且流暢播放,表示解碼成功。

3.png

項(xiàng)目源碼:

展望

喜歡本篇博客的簡友們,就請來一波點(diǎn)贊,您的每一次關(guān)注,將成為我前進(jìn)的動(dòng)力,謝謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容