Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Studio 2.2 以上搭配 CMake 串接 FFmpeg:動手做一個簡易播放器

編輯:關於 Android 程式設計

背景

上一次初次用 CMake 編譯 JNI 之後,這回再把 CMake 腳本升級一階:直接拿網路上的 FFmpeg 解碼範例,用 CMake 重新編出一個能播放的簡易播放器(這裡只做到視訊解碼與渲染,不含音訊)。以下把整個過程記錄下來分享。

一、Gradle 配置

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "jonesx.videoplayer"
        minSdkVersion 9
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"

        ndk {
            abiFilters 'armeabi'
        }

        externalNativeBuild {
            cmake {
                arguments '-DANDROID_TOOLCHAIN=clang', '-DANDROID_STL=gnustl_static'
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.android.support:design:22.2.1'
}

二、CMake 配置

整個工程的目錄層級大致如下(cpp 目錄內含 CMakeLists.txt、VideoPlayer.cpp 與 include 標頭檔,jniLibs 則放 FFmpeg 的 .so)。

CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.1)

set(lib_src_DIR ${CMAKE_SOURCE_DIR}/../jniLibs/${ANDROID_ABI})
include_directories( ${CMAKE_SOURCE_DIR}/include )

add_library(avcodec-57_lib SHARED IMPORTED)
set_target_properties(avcodec-57_lib PROPERTIES IMPORTED_LOCATION ${lib_src_DIR}/libavcodec-57.so)

add_library(avformat-57_lib SHARED IMPORTED)
set_target_properties(avformat-57_lib PROPERTIES IMPORTED_LOCATION ${lib_src_DIR}/libavformat-57.so)

add_library(avutil-55_lib SHARED IMPORTED)
set_target_properties(avutil-55_lib PROPERTIES IMPORTED_LOCATION ${lib_src_DIR}/libavutil-55.so)

add_library(swresample-2_lib SHARED IMPORTED)
set_target_properties(swresample-2_lib PROPERTIES IMPORTED_LOCATION ${lib_src_DIR}/libswresample-2.so)

add_library(swscale-4_lib SHARED IMPORTED)
set_target_properties(swscale-4_lib PROPERTIES IMPORTED_LOCATION ${lib_src_DIR}/libswscale-4.so)

# 建置應用自身的 shared library
add_library(VideoPlayer SHARED VideoPlayer.cpp)

# 連結 VideoPlayer 所需的函式庫
target_link_libraries(VideoPlayer
                      log
                      android
                      avcodec-57_lib
                      avformat-57_lib
                      avutil-55_lib
                      swresample-2_lib
                      swscale-4_lib)

這裡的重點是把相依的 .so 標成 IMPORTED 目標,路徑一定要對上,我在這部分卡了很久,最後靠同事幫忙才找到問題。以 swscale 為例:

add_library(swscale-4_lib SHARED IMPORTED)
set_target_properties(swscale-4_lib PROPERTIES IMPORTED_LOCATION
    ${lib_src_DIR}/libswscale-4.so)

最後別忘了在 target_link_libraries 中把對應的庫加進去,否則連結階段會找不到符號。

三、VideoPlayer.cpp

#include <jni.h>
#include "VideoPlayer.h"
#include <android/log.h>
#include <android/native_window.h>

extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavutil/imgutils.h"
};

#define LOG_TAG "videoplayer"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

JNIEXPORT jint JNIEXPORT Java_jonesx_videoplayer_VideoPlayer_play
        (JNIEnv *env, jclass clazz, jobject surface) {

    LOGD("play");

    // SD 卡中的視訊檔路徑,可自行修改或改由 JNI 傳入
    char *file_name = "/sdcard/test.mp4";

    av_register_all();
    AVFormatContext *pFormatCtx = avformat_alloc_context();

    // 開啟視訊檔
    if (avformat_open_input(&pFormatCtx, file_name, NULL, NULL) != 0) {
        LOGD("Couldn't open file:%s\n", file_name);
        return -1;
    }

    // 取得串流資訊
    if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
        LOGD("Couldn't find stream information.");
        return -1;
    }

    // 找出第一支視訊串流
    int videoStream = -1, i;
    for (i = 0; i < pFormatCtx->nb_streams; i++) {
        if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO
                && videoStream < 0) {
            videoStream = i;
        }
    }
    if (videoStream == -1) {
        LOGD("Didn't find a video stream.");
        return -1;
    }

    // 取得該串流的 codec context,並找到解碼器
    AVCodecContext *pCodecCtx = pFormatCtx->streams[videoStream]->codec;
    AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
    if (pCodec == NULL) {
        LOGD("Codec not found.");
        return -1;
    }
    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
        LOGD("Could not open codec.");
        return -1;
    }

    // 取得 native window
    ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, surface);

    int videoWidth = pCodecCtx->width;
    int videoHeight = pCodecCtx->height;

    // 設定 native window 的 buffer 大小,後續可自動縮放
    ANativeWindow_setBuffersGeometry(nativeWindow, videoWidth, videoHeight,
                                     WINDOW_FORMAT_RGBA_8888);
    ANativeWindow_Buffer windowBuffer;

    // 配置解碼用與渲染用的 AVFrame
    AVFrame *pFrame = av_frame_alloc();
    AVFrame *pFrameRGBA = av_frame_alloc();
    if (pFrameRGBA == NULL || pFrame == NULL) {
        LOGD("Could not allocate video frame.");
        return -1;
    }

    // 計算並配置 buffer,此 buffer 即為渲染來源,格式為 RGBA
    int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGBA,
                                            pCodecCtx->width,
                                            pCodecCtx->height, 1);
    uint8_t *buffer = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t));
    av_image_fill_arrays(pFrameRGBA->data, pFrameRGBA->linesize, buffer,
                         AV_PIX_FMT_RGBA, pCodecCtx->width,
                         pCodecCtx->height, 1);

    // 解碼後的幀格式並非 RGBA,渲染前必須先做格式轉換
    struct SwsContext *sws_ctx = sws_getContext(
            pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
            pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_RGBA,
            SWS_BILINEAR, NULL, NULL, NULL);

    int frameFinished;
    AVPacket packet;
    while (av_read_frame(pFormatCtx, &packet) >= 0) {
        if (packet.stream_index == videoStream) {
            // 解碼視訊幀;並非每次 decode 都會產出一幀
            avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);

            if (frameFinished) {
                // 鎖定 native window buffer
                ANativeWindow_lock(nativeWindow, &windowBuffer, 0);

                // 格式轉換
                sws_scale(sws_ctx,
                          (uint8_t const *const *) pFrame->data, pFrame->linesize,
                          0, pCodecCtx->height,
                          pFrameRGBA->data, pFrameRGBA->linesize);

                // window 的 stride 與幀的 stride 不同,必須逐行複製
                uint8_t *dst = (uint8_t *) windowBuffer.bits;
                int dstStride = windowBuffer.stride * 4;
                uint8_t *src = (pFrameRGBA->data[0]);
                int srcStride = pFrameRGBA->linesize[0];

                int h;
                for (h = 0; h < videoHeight; h++) {
                    memcpy(dst + h * dstStride, src + h * srcStride, srcStride);
                }

                ANativeWindow_unlockAndPost(nativeWindow);
            }
        }
        av_packet_unref(&packet);
    }

    av_free(buffer);
    av_free(pFrameRGBA);
    av_free(pFrame);
    avcodec_close(pCodecCtx);
    avformat_close_input(&pFormatCtx);
    return 0;
}

以上是標準的 FFmpeg 解碼流程。

這裡有個容易踩的坑:我使用 C++ 編譯器 clang,而 FFmpeg 的 .so 都是 C 語言編寫的,因此標頭檔必須包在 extern "C" 裡:

extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavutil/imgutils.h"
};

少了這段、不對 C 標頭做 linkage 規範,就會出現一堆 undefined reference。

四、VideoPlayer.java

package jonesx.videoplayer;

/**
 * Created by Jonesx on 2016/3/12.
 */
public class VideoPlayer {
    static {
        System.loadLibrary("VideoPlayer");
    }

    public static native int play(Object surface);
}

五、MainActivity.java

這裡用 SurfaceView 負責畫面輸出。

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    SurfaceHolder surfaceHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surface_view);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                VideoPlayer.play(surfaceHolder.getSurface());
            }
        }).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }
}

把解碼迴圈丟到子執行緒是必要的,否則會卡住 UI 執行緒。整個流程走通後,就能在 SurfaceView 上看到 FFmpeg 解出來的畫面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved