Modern Apps git

← Modern-Apps.git

camera use GPU stitcher

Commit
ce92f338d307cc30959cb0072d06b3bfc9fa57c5
Author
Vayun Mathur <[email protected]>
When
2026-07-20 15:20 UTC (4 months ago)
Parents
bd71bc8

Diff

camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex 6faaf0f53d..016faf760c 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -903,11 +903,12 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     }      /**-     * Binds a lean Preview + high-resolution ImageAnalysis session for the+     * Binds a lean Preview + capped-resolution ImageAnalysis session for the      * panorama and photo-sphere modes. These sweep off the analysis stream and-     * never use ImageCapture, so dropping the capture use case frees the device's-     * stream-config budget to grant a much sharper (~1080p) analysis stream than-     * the 3-stream photo session can — the dominant lever on panorama quality.+     * never use ImageCapture. The analysis stream is capped at ~3 MP: the pano+     * analyzer decodes every delivered frame to a Bitmap, so an uncapped max-res+     * stream janks the preview, while the 8 MP compose canvas means higher+     * per-frame resolution barely affects the stitched output.      */     suspend fun setupPanoramaSession(): Boolean {         return try {@@ -927,19 +928,24 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             owner.start()             sessionLifecycleOwner = owner -            // Max-resolution analysis stream (same as the photo route): frames are-            // now stored JPEG-compressed and decoded one at a time at stitch, so a-            // high-res sweep no longer blows up memory. Fall back to a default-res-            // bind if the high-res analysis combo is rejected by the device.-            fun bind(maxRes: Boolean): Camera {+            // Cap the analysis stream at ~3 MP. The compose canvas is bounded to+            // 8 MP, so per-frame resolution beyond a few MP adds little to the+            // stitched output — but the analyzer converts every delivered frame to+            // a Bitmap, so a max-res stream makes that conversion (and its GC+            // churn) heavy enough to jank the preview during the sweep. ~3 MP keeps+            // it smooth. Falls back to the device-default analysis resolution if+            // this bound can't bind.+            fun bind(capped: Boolean): Camera {                 val analysisBuilder = ImageAnalysis.Builder()                     .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)-                if (maxRes) {+                if (capped) {                     analysisBuilder.setResolutionSelector(                         ResolutionSelector.Builder()-                            .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)-                            .setAllowedResolutionMode(-                                ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE+                            .setResolutionStrategy(+                                ResolutionStrategy(+                                    Size(2016, 1512), // ~3 MP+                                    ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER+                                )                             )                             .build()                     )@@ -951,11 +957,11 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             }              boundCamera = try {-                bind(maxRes = true)+                bind(capped = true)             } catch (e: Exception) {-                Log.w("PhotoSession", "Max-res panorama bind failed; retrying at default resolution", e)+                Log.w("PhotoSession", "Capped panorama bind failed; retrying at default resolution", e)                 provider.unbindAll()-                bind(maxRes = false)+                bind(capped = false)             }              boundCamera?.cameraInfo?.zoomState?.value?.let {
camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.kt b/camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.ktindex 226b053457..8c9286bdbb 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.kt@@ -115,7 +115,11 @@ object GpuStitcher {     fun composite(estimate: Estimate, frames: List<ByteArray>): CompositeResult? {         var gl: GlEnv? = null         return try {-            gl = GlEnv.create() ?: return null+            gl = GlEnv.create()+            if (gl == null) {+                Log.w(TAG, "EGL/GLES init failed or float FBO unsupported; cannot composite")+                return null+            }             gl.render(estimate, frames)         } catch (t: Throwable) {             Log.e(TAG, "composite failed", t)@@ -400,9 +404,15 @@ object GpuStitcher {             /** Bring up a headless ES3 context on a 1×1 pbuffer, or null on failure. */             fun create(): GlEnv? {                 val display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)-                if (display == EGL14.EGL_NO_DISPLAY) return null+                if (display == EGL14.EGL_NO_DISPLAY) {+                    Log.w(TAG, "eglGetDisplay: no display")+                    return null+                }                 val ver = IntArray(2)-                if (!EGL14.eglInitialize(display, ver, 0, ver, 1)) return null+                if (!EGL14.eglInitialize(display, ver, 0, ver, 1)) {+                    Log.w(TAG, "eglInitialize failed")+                    return null+                }                  val cfgAttr = intArrayOf(                     EGL14.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,@@ -418,6 +428,7 @@ object GpuStitcher {                 if (!EGL14.eglChooseConfig(display, cfgAttr, 0, configs, 0, 1, numConfig, 0) ||                     numConfig[0] == 0 || configs[0] == null                 ) {+                    Log.w(TAG, "eglChooseConfig failed (no ES3 pbuffer config)")                     EGL14.eglTerminate(display)                     return null                 }@@ -426,17 +437,20 @@ object GpuStitcher {                 val ctxAttr = intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE)                 val context = EGL14.eglCreateContext(display, config, EGL14.EGL_NO_CONTEXT, ctxAttr, 0)                 if (context == EGL14.EGL_NO_CONTEXT) {+                    Log.w(TAG, "eglCreateContext failed")                     EGL14.eglTerminate(display)                     return null                 }                 val surfAttr = intArrayOf(EGL14.EGL_WIDTH, 1, EGL14.EGL_HEIGHT, 1, EGL14.EGL_NONE)                 val surface = EGL14.eglCreatePbufferSurface(display, config, surfAttr, 0)                 if (surface == EGL14.EGL_NO_SURFACE) {+                    Log.w(TAG, "eglCreatePbufferSurface failed")                     EGL14.eglDestroyContext(display, context)                     EGL14.eglTerminate(display)                     return null                 }                 if (!EGL14.eglMakeCurrent(display, surface, surface, context)) {+                    Log.w(TAG, "eglMakeCurrent failed")                     EGL14.eglDestroySurface(display, surface)                     EGL14.eglDestroyContext(display, context)                     EGL14.eglTerminate(display)
camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.ktindex 58b321741f..772306c32f 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt@@ -282,17 +282,27 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {      */     suspend fun stitch(): Pair<ByteArray, PanoInfo>? {         val handle = nativeHandle-        if (handle == 0L || _frameCount.value < 2) return null+        if (handle == 0L || _frameCount.value < 2) {+            android.util.Log.w("PanoramaEngine", "stitch skipped: handle=$handle frames=${_frameCount.value}")+            return null+        }         _isStitching.value = true         return withContext(Dispatchers.IO) {             try {-                gpuStitch(handle) ?: cpuStitch(handle)+                android.util.Log.i("PanoramaEngine", "stitch start: frames=${_frameCount.value} sphere=$sphereMode")+                val gpu = gpuStitch(handle)+                if (gpu != null) {+                    gpu+                } else {+                    android.util.Log.w("PanoramaEngine", "GPU path failed; falling back to CPU stitch")+                    cpuStitch(handle)+                }             } catch (e: Exception) {-                e.printStackTrace()+                android.util.Log.e("PanoramaEngine", "GPU stitch threw; falling back to CPU", e)                 try {                     cpuStitch(handle)                 } catch (e2: Exception) {-                    e2.printStackTrace()+                    android.util.Log.e("PanoramaEngine", "CPU stitch also failed", e2)                     null                 }             } finally {@@ -304,10 +314,26 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {     /** GPU path: Rust registration blob → [GpuStitcher] → JPEG. Null on any failure. */     private fun gpuStitch(handle: Long): Pair<ByteArray, PanoInfo>? {         val t0 = System.currentTimeMillis()-        val blob = StitchNative.estimate(handle) ?: return null-        val estimate = GpuStitcher.parseEstimate(blob) ?: return null+        val blob = StitchNative.estimate(handle)+        if (blob == null) {+            android.util.Log.w("PanoramaEngine", "estimate returned null (registration failed)")+            return null+        }+        val estimate = GpuStitcher.parseEstimate(blob)+        if (estimate == null) {+            android.util.Log.w("PanoramaEngine", "parseEstimate returned null (bad blob, ${blob.size} bytes)")+            return null+        }         val tReg = System.currentTimeMillis()-        val result = GpuStitcher.composite(estimate, capturedFrames) ?: return null+        android.util.Log.i(+            "PanoramaEngine",+            "estimate ok in ${tReg - t0}ms: canvas=${estimate.canvasW}x${estimate.canvasH} cams=${estimate.cams.size} frames=${capturedFrames.size}"+        )+        val result = GpuStitcher.composite(estimate, capturedFrames)+        if (result == null) {+            android.util.Log.w("PanoramaEngine", "GpuStitcher.composite returned null")+            return null+        }         val tComp = System.currentTimeMillis()          val baos = ByteArrayOutputStream()@@ -335,12 +361,18 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {      /** CPU fallback: the full Rust stitcher. */     private fun cpuStitch(handle: Long): Pair<ByteArray, PanoInfo>? {-        val jpeg = StitchNative.stitch(handle) ?: return null+        val t0 = System.currentTimeMillis()+        val jpeg = StitchNative.stitch(handle)+        if (jpeg == null) {+            android.util.Log.e("PanoramaEngine", "CPU stitch returned null (registration/stitch failed)")+            return null+        }         val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }         BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size, opts)         val w = opts.outWidth         val h = opts.outHeight         if (w <= 0 || h <= 0) return null+        android.util.Log.i("PanoramaEngine", "CPU stitch ok in ${System.currentTimeMillis() - t0}ms -> ${w}x$h")         val info = PanoInfo(             projectionType = if (sphereMode) "equirectangular" else "cylindrical",             fullWidth = w,