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

Android 端 FFmpeg 解碼實戰:從 NDK 交叉編譯到 JNI 畫面輸出

編輯:關於 Android 程式設計

要在 Android 上做多媒體,FFmpeg 幾乎是繞不開的一塊基石。本文把 H.264 軟解碼在 Android 上落地的完整過程梳理一遍,分成編譯移植、JNI 封裝、上層調用三個階段,把踩過的坑也一併記下,供大家參考。

一、把 FFmpeg 交叉編譯成 Android 可用的庫

網上關於 FFmpeg 移植的文章不少,但照著某些步驟折騰半天,最後生成的 libffmpeg.so 只有幾 KB,顯然某個環節出了問題。後來換了另一種思路:不追求直接產出 so,而是先編出各個模組的 .a 靜態庫,最後只由我們自己寫的 JNI 模組組裝成一個共享庫。實測這種方式反而更乾淨可控,最終也只需要維護一個庫。

筆者調整過的 ffmpeg 目錄:https://download.csdn.net/detail/hclydao/6865961

下載解壓後進入 ffmpeg-1.2.4-android,目錄裡有個 mkconfig.sh,需要改動的地方集中在三處:NDK 工具鏈路徑、目標平台路徑、臨時目錄,以及安裝前綴。

#!/bin/sh
export PREBUILT=/dao/work/tools/android-ndk-r5b/toolchains/arm-linux-androideabi-4.4.3
export PLATFORM=/dao/work/tools/android-ndk-r5b/platforms/android-9/arch-arm
export TMPDIR=/dao/tmp

./configure \
  --target-os=linux \
  --arch=arm \
  --disable-ffmpeg --disable-ffplay --disable-ffprobe --disable-ffserver \
  --disable-avdevice --disable-avfilter --disable-postproc \
  --disable-swresample --disable-avresample \
  --disable-symver --disable-debug --disable-stripping \
  --disable-yasm --disable-asm \
  --enable-gpl --enable-version3 --enable-nonfree \
  --disable-doc \
  --enable-static --disable-shared \
  --enable-cross-compile \
  --prefix=/dao/_install \
  --cc=$PREBUILT/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc \
  --cross-prefix=$PREBUILT/prebuilt/linux-x86/bin/arm-linux-androideabi- \
  --nm=$PREBUILT/prebuilt/linux-x86/bin/arm-linux-androideabi-nm \
  --extra-cflags="-fPIC -DANDROID -I$PLATFORM/usr/include" \
  --extra-ldflags="-L$PLATFORM/usr/lib -nostdlib"

sed -i 's/HAVE_LRINT 0/HAVE_LRINT 1/g'   config.h
sed -i 's/HAVE_LRINTF 0/HAVE_LRINTF 1/g' config.h
sed -i 's/HAVE_ROUND 0/HAVE_ROUND 1/g'   config.h
sed -i 's/HAVE_ROUNDF 0/HAVE_ROUNDF 1/g' config.h
sed -i 's/HAVE_TRUNC 0/HAVE_TRUNC 1/g'   config.h
sed -i 's/HAVE_TRUNCF 0/HAVE_TRUNCF 1/g' config.h
sed -i 's/HAVE_CBRT 0/HAVE_CBRT 1/g'     config.h
sed -i 's/HAVE_CBRTF 0/HAVE_CBRTF 1/g'   config.h
sed -i 's/HAVE_ISINF 0/HAVE_ISINF 1/g'   config.h
sed -i 's/HAVE_ISNAN 0/HAVE_ISNAN 1/g'   config.h
sed -i 's/HAVE_SINF 0/HAVE_SINF 1/g'     config.h
sed -i 's/HAVE_RINT 0/HAVE_RINT 1/g'     config.h
sed -i 's/#define av_restrict restrict/#define av_restrict/g' config.h

開頭三段環境變量要換成你機器上的實際路徑:PREBUILT 指向 NDK 的 toolchain,PLATFORM 指向目標 API 等級的 arch-arm 目錄,TMPDIR 則是編譯期的臨時目錄。接著把下面這行改成你自己的安裝位置:

--prefix=/dao/_install \

一連串 sed 的作用是把 configure 誤判為不存在的 libc 數學函數(lrint、round、trunc、isnan 等)在 config.h 裡重新打開,同時把 av_restrict 展開成空,避開與 Android 頭文件的衝突。這一步不做,編譯階段就會大面積報錯。

改完執行 ./mkconfig.sh,中途出現一個警告可以無視;接著 make,幾分鐘後再 make install。安裝目錄下會生成 include 和 lib 兩個目錄,前者是頭文件,後者是我們要的 .a 靜態庫。移植到此完成,先把產物留著,下一步要用。

二、JNI 層的編寫

在工程目錄下新建 jni 文件夾(筆者當初直接在工程裡建,結果一次 ndk-build 把工程文件刪掉了,建議另開目錄操作),把剛才 include 整個目錄拷進去,再把 lib 下的所有 .a 一併拷進 jni。然後新建 Android.mk:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := avformat
LOCAL_SRC_FILES := libavformat.a
LOCAL_EXPORT_C_INCLUDES := libavformat
LOCAL_EXPORT_LDLIBS := -llog
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := avcodec
LOCAL_SRC_FILES := libavcodec.a
LOCAL_EXPORT_C_INCLUDES := libavcodec
LOCAL_EXPORT_LDLIBS := -llog
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := avutil
LOCAL_SRC_FILES := libavutil.a
LOCAL_EXPORT_C_INCLUDES := libavutil
LOCAL_EXPORT_LDLIBS := -llog
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := swscale
LOCAL_SRC_FILES := libswscale.a
LOCAL_C_INCLUDES := libavutil libswscale
LOCAL_EXPORT_C_INCLUDES := libswscale
LOCAL_EXPORT_LDLIBS := -llog -lavutil
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE := ffmpegutils
LOCAL_SRC_FILES := native.c
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_LDLIBS := -L$(LOCAL_PATH) -lm -lz
LOCAL_STATIC_LIBRARIES := avformat avcodec avutil swscale
include $(BUILD_SHARED_LIBRARY)

前四段用 PREBUILT_STATIC_LIBRARY 把 FFmpeg 的靜態庫「預編譯化」,最後一段才真正編出 libffmpegutils.so,並透過 LOCAL_STATIC_LIBRARIES 把它們串起來。

接著是我們真正要對外暴露的 native.c,裡面做了三件事:註冊解碼器並打開 H.264 上下文、把 byte 陣列丟進 avcodec_decode_video2 解碼、再用 sws_scale 把 YUV 轉成 RGB565 寫回 Java 陣列。

#include <jni.h>
#include <string.h>
#include <stdio.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>

#define LOG_TAG "FFMPEGSample"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)

static AVCodecContext *pCodecCtx = NULL;
static AVFrame *pFrame = NULL;
static AVPacket avpkt;
static struct SwsContext *swsctx = NULL;
static AVFrame *picture = NULL;

JNIEXPORT jint JNICALL
Java_com_dao_iclient_FfmpegIF_getffmpegv(JNIEnv *env, jclass obj) {
    LOGI("getffmpegv");
    return avformat_version();
}

JNIEXPORT jint JNICALL
Java_com_dao_iclient_FfmpegIF_DecodeInit(JNIEnv *env, jclass obj, jint width, jint height) {
    AVCodec *pCodec = NULL;
    avcodec_register_all();
    av_init_packet(&avpkt);
    pCodec = avcodec_find_decoder(CODEC_ID_H264);
    if (pCodec == NULL) return 0;

    pCodecCtx = avcodec_alloc_context3(pCodec);
    if (avcodec_open2(pCodecCtx, pCodec, NULL) >= 0) {
        pCodecCtx->height = height;
        pCodecCtx->width  = width;
        pFrame = avcodec_alloc_frame();
        return 1;
    }
    return 0;
}

JNIEXPORT jint JNICALL
Java_com_dao_iclient_FfmpegIF_Decoding(JNIEnv *env, jclass obj,
                                       jbyteArray pSrcData, jint DataLen,
                                       jbyteArray pDeData) {
    int frameFinished = 0;
    int consumed_bytes;

    jbyte *Buf   = (*env)->GetByteArrayElements(env, pSrcData, 0);
    jbyte *Pixel = (*env)->GetByteArrayElements(env, pDeData, 0);

    avpkt.data = (uint8_t *)Buf;
    avpkt.size = DataLen;
    consumed_bytes = avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &avpkt);

    if (frameFinished) {
        picture = avcodec_alloc_frame();
        avpicture_fill((AVPicture *)picture, (uint8_t *)Pixel,
                       PIX_FMT_RGB565, pCodecCtx->width, pCodecCtx->height);
        swsctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
                                pCodecCtx->width, pCodecCtx->height, PIX_FMT_RGB565,
                                SWS_BICUBIC, NULL, NULL, NULL);
        sws_scale(swsctx, (const uint8_t * const *)pFrame->data, pFrame->linesize,
                  0, pCodecCtx->height, picture->data, picture->linesize);
    }

    (*env)->ReleaseByteArrayElements(env, pSrcData, Buf, 0);
    (*env)->ReleaseByteArrayElements(env, pDeData, Pixel, 0);
    return consumed_bytes;
}

JNIEXPORT jint JNICALL
Java_com_dao_iclient_FfmpegIF_DecodeRelease(JNIEnv *env, jclass obj) {
    if (swsctx) sws_freeContext(swsctx);
    av_free_packet(&avpkt);
    av_free(pFrame);
    av_free(picture);
    avcodec_close(pCodecCtx);
    av_free(pCodecCtx);
    return 1;
}

這份代碼的骨架來自 Churn Labs 的版本(Apache 2.0),並參考 dranger 的 FFmpeg 官方教程做了 Android 化改造。

函數命名必須嚴格遵守 Java_包名_類名_函數名 的規則,包名中的點要換成下劃線。本例中 com.dao.iclient 是包名、FfmpegIF 是類名,因此 C 函數寫成 Java_com_dao_iclient_FfmpegIF_DecodeInit。名字對不上,編譯能過但運行時會拋 UnsatisfiedLinkError。確認 NDK 環境變量已配好後,在 jni 的上一級目錄執行 ndk-build(注意別站錯目錄),產物會出現在 libs/armeabi/ 下。

三、在應用中調用

先在 Java 側聲明對應的 native 方法:

package com.dao.iclient;

public class FfmpegIF {
    public static short TYPE_MODE_DATA = 0;
    public static short TYPE_MODE_COM  = 1;

    public static int VIDEO_COM_START = 0x00;
    public static int VIDEO_COM_POSE  = 0x01;
    public static int VIDEO_COM_RUN   = 0x02;
    public static int VIDEO_COM_ACK   = 0x03;
    public static int VIDEO_COM_STOP  = 0x04;

    static public native int getffmpegv();
    static public native int DecodeInit(int width, int height);
    static public native int Decoding(byte[] in, int datalen, byte[] out);
    static public native int DecodeRelease();

    static {
        System.loadLibrary("ffmpegutils");
    }
}

布局裡放一個 ImageView 作為顯示載體。本例的場景是接收網路傳過來的 H.264 碼流並即時解碼顯示,關鍵點在於:解碼在子線程進行,UI 刷新交給 Handler。

public class IcoolClient extends Activity {
    private static final int REFRESH = 0;

    private Socket socket;
    private ByteBuffer buffer;
    private ByteBuffer Imagbuf;
    private OutputStream outputStream;
    private InputStream inputStream;

    private int packagesize;
    private int width = 640;
    private int height = 480;
    private Bitmap VideoBit;
    private ImageView mImag;
    private byte[] mout;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icool_client);
        mImag = (ImageView) findViewById(R.id.mimg);

        packagesize = 7 * 4 + 2 * 2;
        buffer = ByteBuffer.allocate(packagesize);

        mout = new byte[width * height * 2];
        Imagbuf = ByteBuffer.wrap(mout);
        VideoBit = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

        FfmpegIF.DecodeInit(width, height);
        mHandler = new Handler();
        new StartThread().start();
    }

    final Runnable mUpdateUI = new Runnable() {
        @Override
        public void run() {
            VideoBit.copyPixelsFromBuffer(Imagbuf);
            mImag.setImageBitmap(VideoBit);
        }
    };

    class StartThread extends Thread {
        @Override
        public void run() {
            try {
                socket = new Socket("192.168.1.15", 9876);
                SendCom(FfmpegIF.VIDEO_COM_STOP);
                SendCom(FfmpegIF.VIDEO_COM_START);

                inputStream = socket.getInputStream();
                byte[] Rbuffer = new byte[packagesize];

                while (true) {
                    inputStream.read(Rbuffer);
                    SystemClock.sleep(3);
                    int datasize = getDataL(Rbuffer);
                    if (datasize > 0) {
                        byte[] Data = new byte[datasize];
                        int size = inputStream.read(Data);
                        FfmpegIF.Decoding(Data, size, mout);
                        mHandler.post(mUpdateUI);
                        SendCom(FfmpegIF.VIDEO_COM_ACK);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void SendCom(int comtype) throws IOException {
        outputStream = socket.getOutputStream();
        buffer.clear();
        buffer.put(ShorttoByteArray(FfmpegIF.TYPE_MODE_COM));
        buffer.put(InttoByteArray(packagesize));
        buffer.put(InttoByteArray(0));        // sendDeviceID
        buffer.put(InttoByteArray(0));        // receiveDeviceID
        buffer.put(ShorttoByteArray((short) 0)); // sendDeviceType
        buffer.put(InttoByteArray(0));        // dataIndex
        buffer.put(InttoByteArray(0));        // dataLen
        buffer.put(InttoByteArray(0));        // frameNum
        buffer.put(InttoByteArray(comtype));
        outputStream.write(buffer.array());
    }

    private static byte[] ShorttoByteArray(short n) {
        return new byte[]{ (byte)(n & 0xff), (byte)((n >> 8) & 0xff) };
    }

    private static byte[] InttoByteArray(int n) {
        return new byte[]{ (byte)(n & 0xff), (byte)((n >> 8) & 0xff),
                           (byte)((n >> 16) & 0xff), (byte)((n >> 24) & 0xff) };
    }

    public int getDataL(byte[] getbuffer) {
        return ((getbuffer[20] & 0xff))
             | ((getbuffer[21] & 0xff) << 8)
             | ((getbuffer[22] & 0xff) << 16)
             | ((getbuffer[23] & 0xff) << 24);
    }

    private void byte2hex(byte[] buffer) {
        StringBuilder h = new StringBuilder();
        for (byte b : buffer) h.append(String.format(" %02X", b & 0xFF));
        Log.d("hex", h.toString());
    }
}

幾個容易卡住的細節

  • 主線程不能刷新的問題:解碼必須放在子線程,但 ImageView 的更新只能回主線程,所以透過 Handler.post() 把 mUpdateUI 拋回去。
  • 協議包的位元組對齊:伺服器端是 C 寫的,指令包直接按結構體記憶體佈局填充,這裡最容易出事的是型別寬度不一致——C 的 long 是 4 個位元組,Java 的 long 是 8 個位元組。筆者曾在這裡耗掉幾個小時,建議兩端統一用固定寬度型別(int32_t / int)。
  • 位元組序:ShorttoByteArray / InttoByteArray 採小端序,低有效位元組在前、高有效位元組在後,與 x86 及 ARM 預設一致。
  • 調試手段:留一個 byte2hex 把收發的位元組轉成十六進位字串打印,比盯著二進位流猜問題快得多。

原文作者:hclydao(轉載請保留出處聲明)。

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