【FFmpeg】(二)視頻解碼、像素格式轉(zhuǎn)換與Native原生繪制

視頻解碼、像素格式轉(zhuǎn)換與Native原生繪制

一、視頻解碼

1、FFmpeg 庫(kù)簡(jiǎn)介

FFmpeg 一共包含8個(gè)庫(kù)

  • avcodec:編解碼(最重要的庫(kù))
  • avformat:封裝格式處理
  • avfilter:濾鏡特效處理
  • avdevice:各自設(shè)備的輸入輸出
  • avutil:工具庫(kù)(大部分庫(kù)都需要這個(gè)庫(kù)的支持)
  • postproc:后加工
  • swresample:音頻采樣數(shù)據(jù)格式轉(zhuǎn)換
  • swscale:視頻像素?cái)?shù)據(jù)格式轉(zhuǎn)換

2、FFmpeg 解碼的流程圖

FFmpeg 解碼的流程圖

3、FFmpeg 數(shù)據(jù)格式簡(jiǎn)介

  • AVFormatContext:封裝格式上下文結(jié)構(gòu)體,也是統(tǒng)領(lǐng)全局的結(jié)構(gòu)體,保存了視頻文件封裝格式相關(guān)信息
  • AVInputFormat:每種封裝格式(例如FLV、MKV、MP4、AVI)對(duì)應(yīng)一個(gè)該結(jié)構(gòu)體。
  • AVStream:視頻文件中每個(gè)視頻(音頻)流對(duì)應(yīng)一個(gè)該結(jié)構(gòu)體
  • AVCodeContext:編解碼器上下文結(jié)構(gòu)體,保存了視頻(音頻)編解碼相關(guān)信息。
  • AVCodec:每種視頻(音頻)編解碼器(例如H.264解碼器)對(duì)應(yīng)一個(gè)該結(jié)構(gòu)體
  • AVPacket:存儲(chǔ)一幀壓縮編碼數(shù)據(jù)
  • AVFrame:存儲(chǔ)一幀解碼后的像素(采樣)數(shù)據(jù)

二、像素格式轉(zhuǎn)換

像素格式轉(zhuǎn)換就是將yuv420p 的轉(zhuǎn)成ARGB,可以使用 C/C++ 庫(kù) libyuv 來(lái)進(jìn)行轉(zhuǎn)換

I420ToARGB

參數(shù)按順序如下:

參數(shù) 類型 說(shuō)明
src_y uint8_t* 來(lái)源的frame的 y 幀數(shù)據(jù) yuv_frame->data
src_stride_y int 來(lái)源的frame的y大小數(shù)據(jù) yuv_frame->linesize
src_u uint8_t* 來(lái)源的frame的 u 幀數(shù)據(jù)yuv_frame->data
src_stride_u int 來(lái)源的frame的u大小數(shù)據(jù) yuv_frame->linesize
src_v uint8_t* 來(lái)源的frame的 v 幀數(shù)據(jù)yuv_frame->data
src_stride_v int 來(lái)源的frame的v大小數(shù)據(jù) yuv_frame->linesize
dst_argb uint8_t* 轉(zhuǎn)換后的 rgb 的frame數(shù)據(jù)
dst_stride_argb int 轉(zhuǎn)換后的 rgb 的frame的大小數(shù)據(jù)
width int 像素?cái)?shù)據(jù)寬度
height int 像素?cái)?shù)據(jù)高度

三、Native 原生繪制

Native 原生繪制是使用ANativeWindow 將surface 和 緩沖區(qū)buffer綁定,進(jìn)而去更新緩沖區(qū)的數(shù)據(jù),并刷新到 surface 就可以實(shí)現(xiàn)原生繪制

1、獲取ANativeWindow指針,定義緩沖區(qū)

    //Native 繪制
    ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, surface);
    //緩沖區(qū)buffer
    ANativeWindow_Buffer windowBuffer;

2、設(shè)置緩沖區(qū)參數(shù)

//設(shè)置緩沖區(qū)參數(shù)
ANativeWindow_setBuffersGeometry(nativeWindow, avCodecContext->width,
                                             avCodecContext->height, WINDOW_FORMAT_RGBA_8888);

3、刷新數(shù)據(jù)到緩沖區(qū)

  • 對(duì)緩沖區(qū)進(jìn)行加鎖
  • 刷新轉(zhuǎn)換后的數(shù)據(jù)到緩沖區(qū)
  • 對(duì)緩沖區(qū)數(shù)據(jù)進(jìn)行解鎖
//LOCK
ANativeWindow_lock(nativeWindo&windowBuffer, NULL
avpicture_fill((AVPicture rgba_frame, windowBuffer.bitPIX_FMT_RGBA,
            avCodecContext->width,
            avCodecContext->height
//fix buffer
I420ToARGB(
        yuv_frame->data[0yuv_frame->linesize[0],
        yuv_frame->data[2yuv_frame->linesize[2],
        yuv_frame->data[1yuv_frame->linesize[1],
        rgba_frame->data[0rgba_frame->linesize[0],
        avCodecContext->widtavCodecContext->height
//UNLOCK
ANativeWindow_unlockAndPost(natiindow);

4、釋放nativeWindow

ANativeWindow_release(nativeWindow);

四、使用FFmpeg實(shí)現(xiàn)native原生繪制,顯示視頻圖像

之前說(shuō)明了Android Studio 使用 CMake 來(lái)配置FFmpeg 的方法,這里就省略項(xiàng)目配置與Java代碼部分,主要來(lái)實(shí)現(xiàn)C/C++代碼部分,將像素?cái)?shù)據(jù)會(huì)知道 Surface 上

#include "cn_onestravel_ndk_ffmpeg_render_VideoPlayer.h"
#include <android/log.h>
#include <unistd.h>
//編碼
#include "include/libavcodec/avcodec.h"
//封裝格式處理
#include "include/libavformat/avformat.h"
//像素處理
#include "include/libswscale/swscale.h"
#include "include/libavutil/avutil.h"
#include "include/libavutil/frame.h"
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <libyuv.h>
#include <pthread.h>


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


/*
 * Class:     cn_onestravel_ndk_ffmpeg_render_VideoPlayer
 * Method:    render
 * Signature: (Ljava/lang/String;Landroid/view/Surface;)V
 */
JNIEXPORT void JNICALL Java_cn_onestravel_ndk_ffmpeg_render_VideoPlayer_render
        (JNIEnv *env, jclass jcls, jstring jstr_input, jobject surface) {
    const char *cstr_input = (*env)->GetStringUTFChars(env, jstr_input, NULL);
    //注冊(cè)ffmpeg 所有組件
    av_register_all();
    //封裝格式上下文
    AVFormatContext *formatContext = avformat_alloc_context();
    //打開(kāi)輸入視頻文件
    if (avformat_open_input(&formatContext, cstr_input, NULL, NULL) != 0) {
        LOGE("無(wú)法打開(kāi)視頻文件");
        return;
    }
    //獲取視頻文件信息
    if (avformat_find_stream_info(formatContext, NULL) < 0) {
        LOGE("獲取視頻文件信息失敗");
        return;
    }
    //獲取視頻流的索引位置
    //遍歷所有類型的流(音頻流,視頻流、字幕流)
    int i = 0;
    int v_stream_index = -1;
    for (; i < formatContext->nb_streams; i++) {
        if (formatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
            v_stream_index = i;
            break;
        }
    }
    if (v_stream_index < 0) {
        LOGE("%s", "找不到視頻流\n");
        return;
    }
    //獲取視頻流中的編解碼的上下文
    AVCodecContext *avCodecContext = formatContext->streams[v_stream_index]->codec;
    //根據(jù)視頻編解碼上下文的id得到對(duì)應(yīng)的編解碼器

    AVCodec *avCodec = avcodec_find_decoder(avCodecContext->codec_id);
    if (avCodec == NULL) {
        LOGE("未找到解碼器");
        return;
    }
    //打開(kāi)解碼器
    if (avcodec_open2(avCodecContext, avCodec, NULL) < 0) {
        LOGE("打開(kāi)解碼器失敗");
        return;
    }
    //輸出視頻信息
    LOGI("視頻文件格式:%s", formatContext->iformat->name);
    //formatContext->duration單位為微妙
    LOGI("視頻時(shí)長(zhǎng):%lld", (formatContext->duration) / 1000000);
    LOGI("視頻的寬度和高度 W:%d ,H:%d", avCodecContext->width, avCodecContext->height);
    LOGI("視頻解碼器名稱:%s", avCodec->name);
    //準(zhǔn)備讀取
    //AVPacket用于存儲(chǔ)一幀一幀的壓縮數(shù)據(jù)(H264)
    //緩沖區(qū),開(kāi)辟空間
    AVPacket *packet = (AVPacket *) av_malloc(sizeof(AVPacket));
    AVFrame *yuv_frame = av_frame_alloc();
    AVFrame *yuv_scale_frame = av_frame_alloc();
    AVFrame *rgba_frame = av_frame_alloc();
    //Native 繪制
    ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, surface);
    //緩沖區(qū)buffer
    ANativeWindow_Buffer windowBuffer;

    int len, got_frame, frame_count = 0;
    while (av_read_frame(formatContext, packet) >= 0) {
        len = avcodec_decode_video2(avCodecContext, yuv_frame, &got_frame, packet);
        //不為0,正在解碼
        if (got_frame) {
            int i = frame_count++;
            LOGI("解碼%d幀", i);
            ANativeWindow_setBuffersGeometry(nativeWindow, avCodecContext->width,
                                             avCodecContext->height, WINDOW_FORMAT_RGBA_8888);
            //LOCK
            ANativeWindow_lock(nativeWindow, &windowBuffer, NULL);

            avpicture_fill((AVPicture *) rgba_frame, windowBuffer.bits, PIX_FMT_RGBA,
                           avCodecContext->width,
                           avCodecContext->height);

            //fix buffer
            I420ToARGB(
                    yuv_frame->data[0], yuv_frame->linesize[0],
                    yuv_frame->data[2], yuv_frame->linesize[2],
                    yuv_frame->data[1], yuv_frame->linesize[1],
                    rgba_frame->data[0], rgba_frame->linesize[0],
                    avCodecContext->width, avCodecContext->height);

            //UNLOCK
            ANativeWindow_unlockAndPost(nativeWindow);
//            ANativeWindow_release(nativeWindow);
            usleep(16 * 1000);
        }
        av_free_packet(packet);
    }
    ANativeWindow_release(nativeWindow);
    av_frame_free(yuv_frame);
    av_frame_free(rgba_frame);
    avcodec_close(avCodec);
    avcodec_free_context(avCodecContext);
    avformat_free_context(formatContext);
    (*env)->ReleaseStringUTFChars(env, jstr_input, cstr_input);

}

自定義 VideoView 繼承自 SurfaceView

public class VideoView extends SurfaceView {
    public VideoView(Context context) {
        super(context);
        init();
    }

    public VideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public VideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init(){
        //初始化SurfaceView的像素格式
        SurfaceHolder holder = getHolder();
        holder.setFormat(PixelFormat.RGBA_8888);
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容