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

Android OpenGLES 2.0(十三):用壓縮紋理流暢播放逐幀動畫

編輯:關於 Android 程式設計

直播應用裡的送禮特效非常常見,有些用粒子實現,但更大一部分其實是逐幀動畫。本篇要解決的問題是:如何用 OpenGLES 在 Android 上把大尺寸逐幀動畫播得流暢。

一、為什麼常規方案會卡

有人會說,Android 的 Animation 框架本身就支持逐幀動畫,幾分鐘就能寫出來。確實如此,但圖片尺寸一大就卡。原因不在渲染,而在解碼:PNG 不能被直接繪製,必須先解碼成 Bitmap,而這個過程相當耗時,還受機型、CPU 狀態、圖片內容影響。小圖還能接受,一張 720×720 的圖,解碼常常要 100ms 以上,甚至超過 200ms,這個數字放在動畫裡是災難性的。

那改用 OpenGL 渲染呢?它能改善一些,但瓶頸既然是解碼而不是渲染,換 GPU 自然收效有限——這一點是反覆驗證過才確認的。

於是思路轉向:直接用 BMP 存儲,解碼開銷幾乎可以忽略。但 BMP 不壓縮,一張 720×720 的圖換算下來是 720×720×4/1024 ≈ 2025KB,一秒 25 幀就是二三十兆,顯然不能接受。所以真正的答案落在壓縮紋理上。

二、方案對比

待選方案

方案1:直接逐幀加載 PNG 2D 紋理
方案2:使用 ETC1 壓縮紋理替代 PNG
方案3:使用 ETC2 壓縮紋理替代 PNG
方案4:使用 PVRTC 壓縮紋理替代 PNG
方案5:使用 S3TC 壓縮紋理替代 PNG

文件大小

PNG 的大小與內容相關,透明區域越多越小。ETC1 每個像素佔 0.5 字節,720×720 轉 ETC 後約 720×720×2×0.5 + 16 ≈ 507KB(alpha 通道會讓文件高度翻倍,16 字節是文件頭)。ETC2 的體積與是否保留 A 通道直接相關:不含 A 通道時與 ETC1 不含 A 相同,含 A 通道時與 ETC1 保留 A 相同。S3TC 方面,相對 24 位原圖 DXT1 壓縮比為 6:1,DXT2~DXT5 為 4:1。PVRTC4 為 6:1,PVRTC2 為 12:1(要求寬高為 2 的冪)。

設備支持

PNG   通用
ETC1  OpenGL ES 2.0 標準,Android 2.2 及以上基本全支持
ETC2  OpenGL ES 3.0 標準,Android 4.3 及以上基本全支持
S3TC 起源於 Windows/DirectX,Android 支持率極低,僅 NVIDIA Tegra2 一類芯片
PVRTC 僅 PowerVR GPU 支持,在蘋果生態中廣泛使用

選型結論

方案 4、5 因支持率問題直接排除。方案 1 可用,但 Android 2.2 以下設備基本絕跡,2.2~4.3 之間仍有約 15% 的佔比,權衡之後在方案 2 與方案 3 中選 ETC1,於是保留方案 1 與方案 2 做對比。

實測數據

以 60 張 720×720 的煙花逐幀圖為樣本(測試機 360F4):

PNG 總大小 4.88M,ETC 總大小 29.6M
PNG 的 IO + 解碼耗時 15~40ms,與單張圖大小相關
ETC 不在 CPU 中解碼,只有 IO 開銷,約 4~10ms
兩者的渲染耗時基本一致

可以看到 ETC 在解碼環節的優勢非常明顯,代價是包體變大。

針對體積的補充方案

把 ETC 紋理打包成 zip,加載時直接從 zip 中讀取,總大小降到 7.05M,IO + 解碼約 4~16ms,渲染耗時與未壓縮的 ETC 相同。(不同機型、不同環境數據會有差異,這裡僅用於兩種加載方式的橫向對比。)

三、播放 ZIP 包中的 ETC1 紋理

這種方式特別適合透明區域較多的圖片:這類圖的 ETC 紋理往往比 PNG 大不少,用 zip 一壓剛好回到同一個量級。先說實現過程中踩到的坑。

踩坑記錄

坑一,Mali 官網給的三種方案中,方法一(RGB 與 Alpha 拼成一張圖)最簡單,但部分圖片在邊界處會出現奇怪的線條。原因是紋理採樣時 RGB 與 Alpha 壓在同一張圖裡,邊界處採樣會越界取到隔壁像素,顏色自然不對。方法三不會有這個問題,但單獨的 Alpha 通道會額外佔用空間與內存帶寬。所以最終選方法二:RGB 與 Alpha 分開兩張紋理。

坑二,打包時命名必須保證字典序等於播放順序,數字要補零。比如 100 張圖會生成 200 個 pkm 文件,最後一張是 p100alpha.pkm、倒數第二張是 p100.pkm,那第一張就必須寫成 p001.pkm 而不是 p1.pkm。這裡踩坑的根源是按文件夾、zip 包的順序遍歷。

坑三,Android 提供的 ETC1Util.createTexture(InputStream) 有問題,後面貼代碼時說明。

四、實現

OpenGLES 提供了 GLES10.glCompressedTexImage2D(...) 加載壓縮紋理,但在 Android 上用 ETC1Util.loadTexture(int target, int level, int border, int fallbackFormat, int fallbackType, ETC1Texture texture) 更省事。這樣我們只需要拿到一個 ETC1Texture 對象,而 ETC1Util 恰好提供了創建方法——問題就在這個方法裡。

看它的源碼:

public static ETC1Texture createTexture(InputStream input) throws IOException {
    int width = 0;
    int height = 0;
    byte[] ioBuffer = new byte[4096];
    {
        if (input.read(ioBuffer, 0, ETC1.ETC_PKM_HEADER_SIZE) != ETC1.ETC_PKM_HEADER_SIZE) {
            throw new IOException("Unable to read PKM file header.");
        }
        ByteBuffer headerBuffer = ByteBuffer.allocateDirect(ETC1.ETC_PKM_HEADER_SIZE)
                .order(ByteOrder.nativeOrder());
        headerBuffer.put(ioBuffer, 0, ETC1.ETC_PKM_HEADER_SIZE).position(0);
        if (!ETC1.isValid(headerBuffer)) {
            throw new IOException("Not a PKM file.");
        }
        width = ETC1.getWidth(headerBuffer);
        height = ETC1.getHeight(headerBuffer);
    }
    int encodedSize = ETC1.getEncodedDataSize(width, height);
    ByteBuffer dataBuffer = ByteBuffer.allocateDirect(encodedSize).order(ByteOrder.nativeOrder());
    for (int i = 0; i < encodedSize; ) {
        int chunkSize = Math.min(ioBuffer.length, encodedSize - i);
        if (input.read(ioBuffer, 0, chunkSize) != chunkSize) {
            throw new IOException("Unable to read PKM file data.");
        }
        dataBuffer.put(ioBuffer, 0, chunkSize);
        i += chunkSize;
    }
    dataBuffer.position(0);
    return new ETC1Texture(width, height, dataBuffer);
}

問題在於它對 read 的返回值要求極其嚴格,一次讀不滿就拋異常,而從 zip 流中讀數據時這種情況屢屢發生。改寫之後:

ETC1Util.ETC1Texture createTexture(InputStream input) throws IOException {
    int width = 0;
    int height = 0;
    byte[] ioBuffer = new byte[4096];
    {
        if (input.read(ioBuffer, 0, ETC1.ETC_PKM_HEADER_SIZE) != ETC1.ETC_PKM_HEADER_SIZE) {
            throw new IOException("Unable to read PKM file header.");
        }
        if (headerBuffer == null) {
            headerBuffer = ByteBuffer.allocateDirect(ETC1.ETC_PKM_HEADER_SIZE)
                    .order(ByteOrder.nativeOrder());
        }
        headerBuffer.put(ioBuffer, 0, ETC1.ETC_PKM_HEADER_SIZE).position(0);
        if (!ETC1.isValid(headerBuffer)) {
            throw new IOException("Not a PKM file.");
        }
        width = ETC1.getWidth(headerBuffer);
        height = ETC1.getHeight(headerBuffer);
    }
    int encodedSize = ETC1.getEncodedDataSize(width, height);
    ByteBuffer dataBuffer = ByteBuffer.allocateDirect(encodedSize).order(ByteOrder.nativeOrder());
    int len;
    while ((len = input.read(ioBuffer)) != -1) {
        dataBuffer.put(ioBuffer, 0, len);
    }
    dataBuffer.position(0);
    return new ETC1Util.ETC1Texture(width, height, dataBuffer);
}

關鍵改動是:headerBuffer 複用,不再每幀重新分配;讀數據改成循環讀到流末尾,兼容 zip 流的讀取特性。這樣「從 InputStream 拿到 ETC1Texture」這一步就通了,剩下的事情只是遍歷 zip 條目。

public class ZipPkmReader {

    private String path;
    private ZipInputStream mZipStream;
    private AssetManager mManager;
    private ZipEntry mZipEntry;
    private ByteBuffer headerBuffer;

    public ZipPkmReader(Context context) {
        this(context.getAssets());
    }

    public ZipPkmReader(AssetManager manager) {
        this.mManager = manager;
    }

    public void setZipPath(String path) {
        this.path = path;
    }

    public boolean open() {
        if (path == null) return false;
        try {
            if (path.startsWith("assets/")) {
                InputStream s = mManager.open(path.substring(7));
                mZipStream = new ZipInputStream(s);
            } else {
                mZipStream = new ZipInputStream(new FileInputStream(path));
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void close() {
        if (mZipStream != null) {
            try {
                mZipStream.closeEntry();
                mZipStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (headerBuffer != null) {
                headerBuffer.clear();
                headerBuffer = null;
            }
        }
    }

    private boolean hasElements() {
        try {
            if (mZipStream != null) {
                mZipEntry = mZipStream.getNextEntry();
                if (mZipEntry != null) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public InputStream getNextStream() {
        return hasElements() ? mZipStream : null;
    }

    public ETC1Util.ETC1Texture getNextTexture() {
        if (hasElements()) {
            try {
                return createTexture(mZipStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private ETC1Util.ETC1Texture createTexture(InputStream input) throws IOException {
        int width = 0;
        int height = 0;
        byte[] ioBuffer = new byte[4096];
        {
            if (input.read(ioBuffer, 0, ETC1.ETC_PKM_HEADER_SIZE) != ETC1.ETC_PKM_HEADER_SIZE) {
                throw new IOException("Unable to read PKM file header.");
            }
            if (headerBuffer == null) {
                headerBuffer = ByteBuffer.allocateDirect(ETC1.ETC_PKM_HEADER_SIZE)
                        .order(ByteOrder.nativeOrder());
            }
            headerBuffer.put(ioBuffer, 0, ETC1.ETC_PKM_HEADER_SIZE).position(0);
            if (!ETC1.isValid(headerBuffer)) {
                throw new IOException("Not a PKM file.");
            }
            width = ETC1.getWidth(headerBuffer);
            height = ETC1.getHeight(headerBuffer);
        }
        int encodedSize = ETC1.getEncodedDataSize(width, height);
        ByteBuffer dataBuffer = ByteBuffer.allocateDirect(encodedSize).order(ByteOrder.nativeOrder());
        int len;
        while ((len = input.read(ioBuffer)) != -1) {
            dataBuffer.put(ioBuffer, 0, len);
        }
        dataBuffer.position(0);
        return new ETC1Util.ETC1Texture(width, height, dataBuffer);
    }
}

Shader 直接採用 Mali 官網方法二的版本。然後起一個定時器週期性 requestRender,每次加載下一幀壓縮紋理,動畫就跑起來了(Demo 為簡便直接在 GL 線程裡 sleep 後 requestRender)。

頂點著色器

attribute vec4 vPosition;
attribute vec2 vCoord;
varying vec2 aCoord;
uniform mat4 vMatrix;

void main() {
    aCoord = vCoord;
    gl_Position = vMatrix * vPosition;
}

片元著色器

precision mediump float;
varying vec2 aCoord;
uniform sampler2D vTexture;       // RGB
uniform sampler2D vTextureAlpha;  // Alpha

void main() {
    vec4 color = texture2D(vTexture, aCoord);
    color.a = texture2D(vTextureAlpha, aCoord).r;
    gl_FragColor = color;
}

片元著色器裡有兩個採樣器:一個提供原圖的 RGB 信息,一個提供 Alpha。要注意壓縮紋理在色彩上是有損的,與原 PNG 不會完全一致。

紋理傳入的代碼:

GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0]);
ETC1Util.loadTexture(GLES20.GL_TEXTURE_2D, 0, 0,
        GLES20.GL_RGB, GLES20.GL_UNSIGNED_SHORT_5_6_5, t);
GLES20.glUniform1i(mHTexture, 0);

GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[1]);
ETC1Util.loadTexture(GLES20.GL_TEXTURE_2D, 0, 0,
        GLES20.GL_RGB, GLES20.GL_UNSIGNED_SHORT_5_6_5, tAlpha);
GLES20.glUniform1i(mGlHAlpha, 1);

其餘部分與常規的圖片渲染沒有差別。完整的 Demo 代碼已整理進 Android OpenGLES 2.0 系列示例項目,托管在 GitHub 上,有興趣的可以拉下來對照運行。

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