2

我正在编写一个 Android 应用程序,其中本机线程以大约 60 fps 的速度不断生成图像帧(作为原始像素数据),然后应该以SurfaceView. 目前,线程将像素数据写入native线程和JVM之间的直接ByteBuffer共享,然后通过JNI调用回调,通知JVM端一帧准备好;然后将缓冲区读入 aBitmap并在SurfaceView. 我的代码大致如下(完整的源代码太大而无法共享):

// this is a call into native code that retrieves
// the width and height of the frame in pixels
// returns something on the order of 320×200
private external fun getFrameDimensions(): (Int, Int)

// a direct ByteBuffer shared between the JVM and the native thread
private val frameBuffer: ByteBuffer

private fun getFrame(): Bitmap {
    val (width, height) = getFrameDimensions()

    return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply {
        setHasAlpha(false)
        copyPixelsFromBuffer(frameBuffer.apply {
            order(ByteOrder.nativeOrder())
            rewind()
        })
    }
}

// the SurfaceView widget which should display the image
private lateinit var surfaceView: SurfaceView

private val SCALE = 8

// callback invoked by the native thread
public fun onFrameReady() {
    val canvas: Canvas = surfaceView.holder.lockCanvas() ?: return
    val bitmap = getFrame()
    
    try {
        canvas.drawBitmap(bitmap.scale(
            bitmap.width * SCALE,
            bitmap.height * SCALE),
            0.0f, 0.0f, null
        )
    } finally {
        holder.unlockCanvasAndPost(canvas)
    }
}

好消息是上述方法有效:屏幕以大致预期的帧速率更新。然而,性能真的很差,以至于应用程序锁定:它停止响应,例如按下◁</kbd> button and eventually an ANR message pops up. Clearly I am doing something wrong, but I am not quite able to tell what exactly.

有没有办法使上述运行更快?最好我想避免编写不必要的本机代码。我特别想避免将任何特定于 Android 的东西放在事物的本机方面。

4

1 回答 1

2

那么有几个问题。Kotlin 代码的主要特点是您每秒大约创建 60 次位图,并且不使用该方法来处理它bitmap.recycle(),这会在您不再需要该位图后释放该位图的本机内存。虽然帧速率为 60 fps,但很难找到正确的时间来释放它,但我认为它应该在执行帧绘制之后的某个地方。

但是您的整个代码中的主要问题是在本机代码中使用表面视图的正确方法是您没有使用它。要正确执行此操作,您必须将 Surface 从 Android 代码直接传递到本机代码。之后,您应该ANativeWindow通过ANativeWindow_fromSurface(). 用于ANativeWindow_setBuffersGeometry()设置大小和颜色格式。锁定缓冲区,复制像素并解锁缓冲区以发布它。全部在本机代码中,无需任何进一步的 Android 交互。它看起来像

ANativeWindow* window = ANativeWindow_fromSurface(env, javaSurface);
ANativeWindow_setBuffersGeometry(window, width, height, WINDOW_FORMAT_RGBA_8888);

ANativeWindow_Buffer buffer;
if (ANativeWindow_lock(window, &buffer, NULL) == 0) {
  memcpy(buffer.bits, pixels,  width * height * 2);
  ANativeWindow_unlockAndPost(window);
}

ANativeWindow_release(window);

请注意,这样您就不会创建大量位图,而这是导致性能问题的主要原因 - 您将直接将像素写入 Surface 而无需任何中间容器在线上有大量关于此的信息,甚至还有NDK 示例中的google示例显示了类似的方法(它通过编解码器呈现视频,但仍然如此)。如果有不清楚的地方,请联系我,我会尽力为您提供更多详细信息。

您可以使用的另一种方法是使用 Android 提供的 OpenGL ES API 以高效的方式在 SurfaceView 上绘制图像 - 还有大量在线信息。与原生绘图相比,它的生产力会降低。

于 2021-01-29T05:05:51.920 回答