Modern Apps git

← Modern-Apps.git

make apps smaller

Commit
72dde80df1ba63d0de0789bd837955ea810b49c3
Author
Vayun Mathur <[email protected]>
When
2026-07-26 00:34 UTC (4 months ago)
Parents
1c2e9e4

Diff

astronomy/build.gradle.kts
diff --git a/astronomy/build.gradle.kts b/astronomy/build.gradle.ktsindex c32df00730..85cfc18147 100644--- a/astronomy/build.gradle.kts+++ b/astronomy/build.gradle.kts@@ -29,6 +29,5 @@ dependencies {     implementation(libs.androidx.datastore.preferences)      // Unit tests for Phase 7 (JVM, no Android)-    testImplementation(libs.junit)     testImplementation("org.jetbrains.kotlin:kotlin-test:2.4.0") }
build-logic/src/main/kotlin/RustNative.kt
diff --git a/build-logic/src/main/kotlin/RustNative.kt b/build-logic/src/main/kotlin/RustNative.ktnew file mode 100644index 0000000000..1123558354--- /dev/null+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -0,0 +1,108 @@+import org.gradle.api.Project+import org.gradle.api.tasks.Exec+import org.gradle.internal.os.OperatingSystem+import org.gradle.kotlin.dsl.register+import java.util.Properties++/**+ * Registers the per-ABI cargo cross-compile of a Rust cdylib (arm64-v8a only)+ * into `build/rustJniLibs`, wired ahead of `preBuild`. This consolidates the+ * ~80 lines of NDK-toolchain + cargo + reproducible-build boilerplate that used+ * to be copy-pasted across every native module (pdf, camera, weather, passwords,+ * e2ee-p2p). The caller still registers `build/rustJniLibs` as a jniLibs source+ * dir in its own `android { }` block.+ *+ * Prereq: `rustup target add aarch64-linux-android`.+ *+ * @param crate      cargo package lib name → produces `lib<crate>.so`+ * @param remapLabel `--remap-path-prefix` label baked in for reproducible builds+ *                   (defaults to [crate]).+ */+fun Project.rustNativeLib(crate: String, remapLabel: String = crate) {+    val ndkVersionForRust = "29.0.14206865"+    val androidApiLevel = 31++    fun resolveSdkDir(): String =+        System.getenv("ANDROID_HOME")+            ?: System.getenv("ANDROID_SDK_ROOT")+            ?: rootProject.file("local.properties").takeIf { it.exists() }?.let { f ->+                Properties().apply { f.inputStream().use { load(it) } }.getProperty("sdk.dir")+            }+            ?: error("Android SDK not found (set ANDROID_HOME or sdk.dir in local.properties)")++    val cargoBin = "${System.getProperty("user.home")}/.cargo/bin"+    val ndkRoot = "${resolveSdkDir()}/ndk/$ndkVersionForRust"+    val hostTag = when {+        OperatingSystem.current().isMacOsX -> "darwin-x86_64"+        OperatingSystem.current().isLinux -> "linux-x86_64"+        OperatingSystem.current().isWindows -> "windows-x86_64"+        else -> error("Unsupported host OS for NDK toolchain")+    }+    val ndkBin = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/bin"+    val ndkSysroot = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/sysroot"++    // arm64-v8a only — all physical devices + the Apple-Silicon emulator are arm64.+    val rustAbis = listOf("arm64-v8a" to "aarch64-linux-android")++    val perAbi = rustAbis.map { (abiDir, triple) ->+        tasks.register<Exec>("cargoBuild_${abiDir.replace('-', '_')}") {+            description = "Cross-compiles lib$crate for $abiDir."+            workingDir = file("src/main/rust")++            val clang = "$ndkBin/$triple$androidApiLevel-clang"+            val linkerVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_LINKER"+            val soOut = file("src/main/rust/target/$triple/release/lib$crate.so")+            val destSo = layout.buildDirectory.file("rustJniLibs/$abiDir/lib$crate.so").get().asFile++            inputs.dir("src/main/rust/src")+            inputs.file("src/main/rust/Cargo.toml")+            inputs.file("src/main/rust/Cargo.lock")+            inputs.file("src/main/rust/rust-toolchain.toml")+            outputs.file(destSo)++            val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"+            val rustSrc = file("src/main/rust").absolutePath++            environment("PATH", "$cargoBin:${System.getenv("PATH")}")+            // The per-API NDK clang wrapper bakes in --target and the sysroot.+            environment("CC", clang)+            environment("AR", "$ndkBin/llvm-ar")+            environment("SYSROOT", ndkSysroot)+            environment(linkerVar, clang)+            environment("HOST_CC", "/usr/bin/clang")+            // bindgen (used by some crates, e.g. weather's om-file-format-sys) parses+            // C headers with libclang — point it at the NDK target + sysroot. Harmless+            // and ignored by crates that don't use bindgen.+            environment(+                "BINDGEN_EXTRA_CLANG_ARGS",+                "--target=$triple$androidApiLevel --sysroot=$ndkSysroot",+            )+            // Reproducible builds: remap $HOME-specific paths (cargo registry + crate+            // dir) to fixed constants so different machines produce identical .so bytes.+            environment(+                "RUSTFLAGS",+                "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$rustSrc=/$remapLabel",+            )+            environment("CFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel")+            environment("CXXFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel")+            environment("CPPFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/$remapLabel")+            environment("ZERO_AR_DATE", "1")+            environment("CARGO_INCREMENTAL", "0")++            commandLine("$cargoBin/cargo", "build", "--locked", "--release", "--target", triple)++            doLast {+                destSo.parentFile.mkdirs()+                soOut.copyTo(destSo, overwrite = true)+            }+        }+    }++    val cargoNdkBuild = tasks.register("cargoNdkBuild") {+        description = "Builds lib$crate.so for all Android ABIs."+        dependsOn(perAbi)+    }+    tasks.matching { it.name == "preBuild" }.configureEach {+        dependsOn(cargoNdkBuild)+    }+}
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex d38bf74aee..b867b57fb2 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -92,6 +92,12 @@ configure<com.android.build.api.dsl.ApplicationExtension> {         versionCode = appVersionCode         versionName = appVersionName         targetSdk = 37+        // Only arm64-v8a — all physical devices + Apple Silicon emulator are arm64.+        // AGP otherwise configures buildCMakeDebug for armeabi-v7a/x86/x86_64 which+        // wastes time and broke when offline router's sqlite3.c was removed.+        ndk {+            abiFilters.add("arm64-v8a")+        }     }      signingConfigs {@@ -124,8 +130,8 @@ configure<com.android.build.api.dsl.ApplicationExtension> {             proguardFiles(                 getDefaultProguardFile("proguard-android-optimize.txt"), proguardFile.absolutePath,             )--            // This applies ONLY to your release APK/Bundle+        }+        debug {             ndk {                 abiFilters.add("arm64-v8a")             }@@ -135,6 +141,10 @@ configure<com.android.build.api.dsl.ApplicationExtension> {             isMinifyEnabled = false             isShrinkResources = false             matchingFallbacks += listOf("release")+            ndk {+                abiFilters.clear()+                abiFilters.add("arm64-v8a")+            }         }     } @@ -173,6 +183,8 @@ dependencies {      implementation(project(":library"))     implementation(project(":library:ui"))++    testImplementation(libs.junit) }  fun DependencyHandlerScope.justSoItShowsAsUsedSomewhere() {
build-logic/src/main/kotlin/common-conventions-library.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts b/build-logic/src/main/kotlin/common-conventions-library.gradle.ktsindex 99e05cddc4..a3690e18b6 100644--- a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-library.gradle.kts@@ -39,6 +39,8 @@ dependencies {      // Kotlin Serialization     implementation(libs.kotlinx.serialization.json)++    testImplementation(libs.junit) }  tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
calendar/build.gradle.kts
diff --git a/calendar/build.gradle.kts b/calendar/build.gradle.ktsindex 9e324843f6..867da4983a 100644--- a/calendar/build.gradle.kts+++ b/calendar/build.gradle.kts@@ -20,5 +20,4 @@ metadataScreenshots { dependencies {     implementation(project(":library:widgets")) -    testImplementation(libs.junit) }\ No newline at end of file
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex de74f3fb86..db5498f8ac 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -1,5 +1,3 @@-import java.util.Properties- plugins {     id("common-conventions-app")     id("common-conventions-metadata")@@ -13,110 +11,18 @@ android {     defaultConfig {         applicationId = "com.vayunmathur.camera"     }-    androidResources {-        // The ncnn-android AAR is generalist and also bundles the PP-OCRv5 OCR-        // models. Camera only uses PortraitSegmenter, so strip the OCR assets it-        // never loads (~8MB) from this APK.-        ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~:PP_OCRv5_mobile_*"-    }-    // The Rust stitcher drops <abi>/libcamera_stitch.so under this dir; register-    // it as a jniLibs source so AGP packages the native lib.-    sourceSets["main"].jniLibs.directories.add(layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath)-}--// ----------------------------------------------------------------------------// Native panorama stitcher + night burst aligner (Rust). See camera/src/main/rust/.-// Cross-compiled per-ABI with the NDK's clang, driven directly from cargo (same-// approach as :pdf and :weather).-// Contributor/CI prerequisite:  rustup target add aarch64-linux-android-// -----------------------------------------------------------------------------val ndkVersionForRust = "29.0.14206865"-val androidApiLevel = 31--fun resolveSdkDir(): String =-    System.getenv("ANDROID_HOME")-        ?: System.getenv("ANDROID_SDK_ROOT")-        ?: rootProject.file("local.properties").takeIf { it.exists() }?.let { f ->-            Properties().apply { f.inputStream().use { load(it) } }.getProperty("sdk.dir")-        }-        ?: error("Android SDK not found (set ANDROID_HOME or sdk.dir in local.properties)")--val cargoBin = "${System.getProperty("user.home")}/.cargo/bin"-val ndkRoot = "${resolveSdkDir()}/ndk/$ndkVersionForRust"-val hostTag = when {-    org.gradle.internal.os.OperatingSystem.current().isMacOsX -> "darwin-x86_64"-    org.gradle.internal.os.OperatingSystem.current().isLinux -> "linux-x86_64"-    org.gradle.internal.os.OperatingSystem.current().isWindows -> "windows-x86_64"-    else -> error("Unsupported host OS for NDK toolchain") }-val ndkBin = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/bin"-val ndkSysroot = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/sysroot"--// (jniLibs ABI dir, Rust target triple)-val rustAbis = listOf(-    "arm64-v8a" to "aarch64-linux-android",-)--val perAbiBuildTasks = rustAbis.map { (abiDir, triple) ->-    tasks.register<Exec>("cargoBuild_${abiDir.replace('-', '_')}") {-        description = "Cross-compiles the Rust camera stitcher for $abiDir."-        workingDir = file("src/main/rust") -        val clang = "$ndkBin/$triple$androidApiLevel-clang"-        val linkerVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_LINKER"-        val soOut = file("src/main/rust/target/$triple/release/libcamera_stitch.so")-        val destSo = layout.buildDirectory.file("rustJniLibs/$abiDir/libcamera_stitch.so").get().asFile--        inputs.dir("src/main/rust/src")-        inputs.file("src/main/rust/Cargo.toml")-        inputs.file("src/main/rust/Cargo.lock")-        inputs.file("src/main/rust/rust-toolchain.toml")-        outputs.file(destSo)--        val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"-        val rustSrc = file("src/main/rust").absolutePath--        environment("PATH", "$cargoBin:${System.getenv("PATH")}")-        environment("CC", clang)-        environment("AR", "$ndkBin/llvm-ar")-        environment("SYSROOT", ndkSysroot)-        environment(linkerVar, clang)-        environment("HOST_CC", "/usr/bin/clang")-        // Reproducible builds: strip the build machine's absolute paths (cargo-        // registry + local crate dir) from the binary. Rust otherwise embeds-        // $HOME-specific paths in panic/debug strings, so F-Droid's /home/vagrant-        // and CI's /home/runner would produce different .so bytes. Each host remaps-        // its own paths to the same constants, yielding identical output.-        environment(-            "RUSTFLAGS",-            "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$rustSrc=/camera",+androidComponents {+    onVariants { variant ->+        variant.sources.jniLibs?.addStaticSourceDirectory(+            layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath         )-        // Deterministic C/C++ compilation for any cc crate or future native deps,-        // plus ar(1) timestamp determinism. Also disable incremental for reproducibility.-        environment("CFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/camera")-        environment("CXXFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/camera")-        environment("CPPFLAGS", "-ffile-prefix-map=$cargoHome=/cargo -ffile-prefix-map=$rustSrc=/camera")-        environment("ZERO_AR_DATE", "1")-        environment("CARGO_INCREMENTAL", "0")--        commandLine("$cargoBin/cargo", "build", "--locked", "--release", "--target", triple)--        doLast {-            destSo.parentFile.mkdirs()-            soOut.copyTo(destSo, overwrite = true)-        }     } } -val cargoNdkBuild = tasks.register("cargoNdkBuild") {-    description = "Builds libcamera_stitch.so for all Android ABIs."-    dependsOn(perAbiBuildTasks)-}--tasks.matching { it.name == "preBuild" }.configureEach {-    dependsOn(cargoNdkBuild)-}+// Native panorama stitcher + night burst aligner (Rust). See camera/src/main/rust/.+rustNativeLib("camera_stitch", "camera")  dependencies {     implementation(libs.androidx.camera.core)@@ -128,7 +34,6 @@ dependencies {     implementation(libs.androidx.camera.extensions)     implementation(libs.androidx.exifinterface)     implementation(libs.zxing.core)-    // On-device portrait segmentation via ncnn (Tencent, BSD-3, CPU-only). Forked-    // and published as an AAR through JitPack, same pattern as Stockfish-Library.+    // On-device portrait segmentation via ncnn (Tencent, BSD-3, CPU-only), forked AAR.     implementation(libs.ncnn.android) }
camera/src/main/assets/erdnet.bin
diff --git a/camera/src/main/assets/erdnet.bin b/camera/src/main/assets/erdnet.binnew file mode 100644index 0000000000..b60591d279Binary files /dev/null and b/camera/src/main/assets/erdnet.bin differ
camera/src/main/assets/erdnet.param
diff --git a/camera/src/main/assets/erdnet.param b/camera/src/main/assets/erdnet.paramnew file mode 100644index 0000000000..7c90eb24f9--- /dev/null+++ b/camera/src/main/assets/erdnet.param@@ -0,0 +1,196 @@+7767517+194 249+Input                    input1                   0 1 input_blob1 -23330=4,3,256,256,3 0=256 1=256 2=3+Split                    splitncnn_0              1 6 input_blob1 input_blob1_splitncnn_0 input_blob1_splitncnn_1 input_blob1_splitncnn_2 input_blob1_splitncnn_3 input_blob1_splitncnn_4 input_blob1_splitncnn_5 -23330=24,3,256,256,3,3,256,256,3,3,256,256,3,3,256,256,3,3,256,256,3,3,256,256,3+Pooling                  ave_pool1                1 1 input_blob1_splitncnn_5 ave_pool_blob1 -23330=4,3,128,128,3 0=1 1=3 2=2 3=1 5=1+Split                    splitncnn_1              1 2 ave_pool_blob1 ave_pool_blob1_splitncnn_0 ave_pool_blob1_splitncnn_1 -23330=8,3,128,128,3,3,128,128,3+Pooling                  ave_pool2                1 1 ave_pool_blob1_splitncnn_1 ave_pool_blob2 -23330=4,3,64,64,3 0=1 1=3 2=2 3=1 5=1+Split                    splitncnn_2              1 2 ave_pool_blob2 ave_pool_blob2_splitncnn_0 ave_pool_blob2_splitncnn_1 -23330=8,3,64,64,3,3,64,64,3+Pooling                  ave_pool3                1 1 ave_pool_blob2_splitncnn_1 ave_pool_blob3 -23330=4,3,32,32,3 0=1 1=3 2=2 3=1 5=1+Split                    splitncnn_3              1 2 ave_pool_blob3 ave_pool_blob3_splitncnn_0 ave_pool_blob3_splitncnn_1 -23330=8,3,32,32,3,3,32,32,3+Pooling                  ave_pool4                1 1 ave_pool_blob3_splitncnn_1 ave_pool_blob4 -23330=4,3,16,16,3 0=1 1=3 2=2 3=1 5=1+Convolution              conv1                    1 1 input_blob1_splitncnn_4 conv_blob1 -23330=4,3,128,128,12 0=12 1=3 3=2 4=1 5=1 6=324+PReLU                    prelu1                   1 1 conv_blob1 prelu_blob1 -23330=4,3,128,128,12 0=12+Split                    splitncnn_4              1 2 prelu_blob1 prelu_blob1_splitncnn_0 prelu_blob1_splitncnn_1 -23330=8,3,128,128,12,3,128,128,12+Convolution              conv2                    1 1 prelu_blob1_splitncnn_1 conv_blob2 -23330=4,3,128,128,4 0=4 1=1 6=48+Split                    splitncnn_5              1 2 conv_blob2 conv_blob2_splitncnn_0 conv_blob2_splitncnn_1 -23330=8,3,128,128,4,3,128,128,4+Convolution              conv3                    1 1 conv_blob2_splitncnn_1 relu_blob1 -23330=4,3,128,128,4 0=4 1=3 4=1 5=1 6=144 9=1+Concat                   cat1                     2 1 conv_blob2_splitncnn_0 relu_blob1 cat_blob1 -23330=4,3,128,128,8+Split                    splitncnn_6              1 2 cat_blob1 cat_blob1_splitncnn_0 cat_blob1_splitncnn_1 -23330=8,3,128,128,8,3,128,128,8+Convolution              conv4                    1 1 cat_blob1_splitncnn_1 relu_blob2 -23330=4,3,128,128,4 0=4 1=3 4=1 5=1 6=288 9=1+Concat                   cat2                     2 1 cat_blob1_splitncnn_0 relu_blob2 cat_blob2 -23330=4,3,128,128,12+Eltwise                  add1                     2 1 prelu_blob1_splitncnn_0 cat_blob2 add_blob1 -23330=4,3,128,128,12 0=1+BatchNorm                batch_norm1              1 1 add_blob1 batch_norm_blob1_bn_scale1 -23330=4,3,128,128,12 0=12+PReLU                    prelu2                   1 1 batch_norm_blob1_bn_scale1 prelu_blob2 -23330=4,3,128,128,12 0=12+Split                    splitncnn_7              1 2 prelu_blob2 prelu_blob2_splitncnn_0 prelu_blob2_splitncnn_1 -23330=8,3,128,128,12,3,128,128,12+Concat                   cat3                     2 1 ave_pool_blob1_splitncnn_0 prelu_blob2_splitncnn_1 cat_blob3 -23330=4,3,128,128,15+BatchNorm                batch_norm2              1 1 cat_blob3 batch_norm_blob2_bn_scale2 -23330=4,3,128,128,15 0=15+PReLU                    prelu3                   1 1 batch_norm_blob2_bn_scale2 prelu_blob3 -23330=4,3,128,128,15 0=15+Convolution              conv5                    1 1 prelu_blob3 conv_blob5 -23330=4,3,64,64,24 0=24 1=3 3=2 4=1 5=1 6=3240+PReLU                    prelu4                   1 1 conv_blob5 prelu_blob4 -23330=4,3,64,64,24 0=24+Split                    splitncnn_8              1 3 prelu_blob4 prelu_blob4_splitncnn_0 prelu_blob4_splitncnn_1 prelu_blob4_splitncnn_2 -23330=12,3,64,64,24,3,64,64,24,3,64,64,24+Convolution              conv6                    1 1 prelu_blob4_splitncnn_2 conv_blob6 -23330=4,3,64,64,8 0=8 1=1 6=192+Split                    splitncnn_9              1 2 conv_blob6 conv_blob6_splitncnn_0 conv_blob6_splitncnn_1 -23330=8,3,64,64,8,3,64,64,8+Convolution              conv7                    1 1 conv_blob6_splitncnn_1 relu_blob3 -23330=4,3,64,64,8 0=8 1=3 4=1 5=1 6=576 9=1+Concat                   cat4                     2 1 conv_blob6_splitncnn_0 relu_blob3 cat_blob4 -23330=4,3,64,64,16+Split                    splitncnn_10             1 2 cat_blob4 cat_blob4_splitncnn_0 cat_blob4_splitncnn_1 -23330=8,3,64,64,16,3,64,64,16+Convolution              conv8                    1 1 cat_blob4_splitncnn_1 relu_blob4 -23330=4,3,64,64,8 0=8 1=3 4=1 5=1 6=1152 9=1+Concat                   cat5                     2 1 cat_blob4_splitncnn_0 relu_blob4 cat_blob5 -23330=4,3,64,64,24+Eltwise                  add2                     2 1 prelu_blob4_splitncnn_1 cat_blob5 add_blob2 -23330=4,3,64,64,24 0=1+BatchNorm                batch_norm3              1 1 add_blob2 batch_norm_blob3_bn_scale3 -23330=4,3,64,64,24 0=24+PReLU                    prelu5                   1 1 batch_norm_blob3_bn_scale3 prelu_blob5 -23330=4,3,64,64,24 0=24+Split                    splitncnn_11             1 2 prelu_blob5 prelu_blob5_splitncnn_0 prelu_blob5_splitncnn_1 -23330=8,3,64,64,24,3,64,64,24+Concat                   cat6                     3 1 ave_pool_blob2_splitncnn_0 prelu_blob4_splitncnn_0 prelu_blob5_splitncnn_1 cat_blob6 -23330=4,3,64,64,51+BatchNorm                batch_norm4              1 1 cat_blob6 batch_norm_blob4_bn_scale4 -23330=4,3,64,64,51 0=51+PReLU                    prelu6                   1 1 batch_norm_blob4_bn_scale4 prelu_blob6 -23330=4,3,64,64,51 0=51+Convolution              conv9                    1 1 prelu_blob6 conv_blob9 -23330=4,3,32,32,48 0=48 1=3 3=2 4=1 5=1 6=22032+PReLU                    prelu7                   1 1 conv_blob9 prelu_blob7 -23330=4,3,32,32,48 0=48+Split                    splitncnn_12             1 3 prelu_blob7 prelu_blob7_splitncnn_0 prelu_blob7_splitncnn_1 prelu_blob7_splitncnn_2 -23330=12,3,32,32,48,3,32,32,48,3,32,32,48+Convolution              conv10                   1 1 prelu_blob7_splitncnn_2 conv_blob10 -23330=4,3,32,32,16 0=16 1=1 6=768+Split                    splitncnn_13             1 2 conv_blob10 conv_blob10_splitncnn_0 conv_blob10_splitncnn_1 -23330=8,3,32,32,16,3,32,32,16+Convolution              conv11                   1 1 conv_blob10_splitncnn_1 relu_blob5 -23330=4,3,32,32,16 0=16 1=3 4=1 5=1 6=2304 9=1+Concat                   cat7                     2 1 conv_blob10_splitncnn_0 relu_blob5 cat_blob7 -23330=4,3,32,32,32+Split                    splitncnn_14             1 2 cat_blob7 cat_blob7_splitncnn_0 cat_blob7_splitncnn_1 -23330=8,3,32,32,32,3,32,32,32+Convolution              conv12                   1 1 cat_blob7_splitncnn_1 relu_blob6 -23330=4,3,32,32,16 0=16 1=3 4=1 5=1 6=4608 9=1+Concat                   cat8                     2 1 cat_blob7_splitncnn_0 relu_blob6 cat_blob8 -23330=4,3,32,32,48+Eltwise                  add3                     2 1 prelu_blob7_splitncnn_1 cat_blob8 add_blob3 -23330=4,3,32,32,48 0=1+BatchNorm                batch_norm5              1 1 add_blob3 batch_norm_blob5_bn_scale5 -23330=4,3,32,32,48 0=48+PReLU                    prelu8                   1 1 batch_norm_blob5_bn_scale5 prelu_blob8 -23330=4,3,32,32,48 0=48+Split                    splitncnn_15             1 2 prelu_blob8 prelu_blob8_splitncnn_0 prelu_blob8_splitncnn_1 -23330=8,3,32,32,48,3,32,32,48+Concat                   cat9                     3 1 ave_pool_blob3_splitncnn_0 prelu_blob7_splitncnn_0 prelu_blob8_splitncnn_1 cat_blob9 -23330=4,3,32,32,99+BatchNorm                batch_norm6              1 1 cat_blob9 batch_norm_blob6_bn_scale6 -23330=4,3,32,32,99 0=99+PReLU                    prelu9                   1 1 batch_norm_blob6_bn_scale6 prelu_blob9 -23330=4,3,32,32,99 0=99+Convolution              conv13                   1 1 prelu_blob9 conv_blob13 -23330=4,3,16,16,96 0=96 1=3 3=2 4=1 5=1 6=85536+PReLU                    prelu10                  1 1 conv_blob13 prelu_blob10 -23330=4,3,16,16,96 0=96+Split                    splitncnn_16             1 3 prelu_blob10 prelu_blob10_splitncnn_0 prelu_blob10_splitncnn_1 prelu_blob10_splitncnn_2 -23330=12,3,16,16,96,3,16,16,96,3,16,16,96+Convolution              conv14                   1 1 prelu_blob10_splitncnn_2 conv_blob14 -23330=4,3,16,16,16 0=16 1=1 6=1536+Split                    splitncnn_17             1 2 conv_blob14 conv_blob14_splitncnn_0 conv_blob14_splitncnn_1 -23330=8,3,16,16,16,3,16,16,16+Convolution              conv15                   1 1 conv_blob14_splitncnn_1 relu_blob7 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=2304 9=1+Concat                   cat10                    2 1 conv_blob14_splitncnn_0 relu_blob7 cat_blob10 -23330=4,3,16,16,32+Split                    splitncnn_18             1 2 cat_blob10 cat_blob10_splitncnn_0 cat_blob10_splitncnn_1 -23330=8,3,16,16,32,3,16,16,32+Convolution              conv16                   1 1 cat_blob10_splitncnn_1 relu_blob8 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=4608 9=1+Concat                   cat11                    2 1 cat_blob10_splitncnn_0 relu_blob8 cat_blob11 -23330=4,3,16,16,48+Split                    splitncnn_19             1 2 cat_blob11 cat_blob11_splitncnn_0 cat_blob11_splitncnn_1 -23330=8,3,16,16,48,3,16,16,48+Convolution              conv17                   1 1 cat_blob11_splitncnn_1 relu_blob9 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=6912 9=1+Concat                   cat12                    2 1 cat_blob11_splitncnn_0 relu_blob9 cat_blob12 -23330=4,3,16,16,64+Split                    splitncnn_20             1 2 cat_blob12 cat_blob12_splitncnn_0 cat_blob12_splitncnn_1 -23330=8,3,16,16,64,3,16,16,64+Convolution              conv18                   1 1 cat_blob12_splitncnn_1 relu_blob10 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=9216 9=1+Concat                   cat13                    2 1 cat_blob12_splitncnn_0 relu_blob10 cat_blob13 -23330=4,3,16,16,80+Split                    splitncnn_21             1 2 cat_blob13 cat_blob13_splitncnn_0 cat_blob13_splitncnn_1 -23330=8,3,16,16,80,3,16,16,80+Convolution              conv19                   1 1 cat_blob13_splitncnn_1 relu_blob11 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=11520 9=1+Concat                   cat14                    2 1 cat_blob13_splitncnn_0 relu_blob11 cat_blob14 -23330=4,3,16,16,96+Eltwise                  add4                     2 1 prelu_blob10_splitncnn_1 cat_blob14 add_blob4 -23330=4,3,16,16,96 0=1+BatchNorm                batch_norm7              1 1 add_blob4 batch_norm_blob7_bn_scale7 -23330=4,3,16,16,96 0=96+PReLU                    prelu11                  1 1 batch_norm_blob7_bn_scale7 prelu_blob11 -23330=4,3,16,16,96 0=96+Split                    splitncnn_22             1 2 prelu_blob11 prelu_blob11_splitncnn_0 prelu_blob11_splitncnn_1 -23330=8,3,16,16,96,3,16,16,96+Convolution              conv20                   1 1 prelu_blob11_splitncnn_1 conv_blob20 -23330=4,3,16,16,16 0=16 1=1 6=1536+Split                    splitncnn_23             1 2 conv_blob20 conv_blob20_splitncnn_0 conv_blob20_splitncnn_1 -23330=8,3,16,16,16,3,16,16,16+Convolution              conv21                   1 1 conv_blob20_splitncnn_1 relu_blob12 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=2304 9=1+Concat                   cat15                    2 1 conv_blob20_splitncnn_0 relu_blob12 cat_blob15 -23330=4,3,16,16,32+Split                    splitncnn_24             1 2 cat_blob15 cat_blob15_splitncnn_0 cat_blob15_splitncnn_1 -23330=8,3,16,16,32,3,16,16,32+Convolution              conv22                   1 1 cat_blob15_splitncnn_1 relu_blob13 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=4608 9=1+Concat                   cat16                    2 1 cat_blob15_splitncnn_0 relu_blob13 cat_blob16 -23330=4,3,16,16,48+Split                    splitncnn_25             1 2 cat_blob16 cat_blob16_splitncnn_0 cat_blob16_splitncnn_1 -23330=8,3,16,16,48,3,16,16,48+Convolution              conv23                   1 1 cat_blob16_splitncnn_1 relu_blob14 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=6912 9=1+Concat                   cat17                    2 1 cat_blob16_splitncnn_0 relu_blob14 cat_blob17 -23330=4,3,16,16,64+Split                    splitncnn_26             1 2 cat_blob17 cat_blob17_splitncnn_0 cat_blob17_splitncnn_1 -23330=8,3,16,16,64,3,16,16,64+Convolution              conv24                   1 1 cat_blob17_splitncnn_1 relu_blob15 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=9216 9=1+Concat                   cat18                    2 1 cat_blob17_splitncnn_0 relu_blob15 cat_blob18 -23330=4,3,16,16,80+Split                    splitncnn_27             1 2 cat_blob18 cat_blob18_splitncnn_0 cat_blob18_splitncnn_1 -23330=8,3,16,16,80,3,16,16,80+Convolution              conv25                   1 1 cat_blob18_splitncnn_1 relu_blob16 -23330=4,3,16,16,16 0=16 1=3 4=1 5=1 6=11520 9=1+Concat                   cat19                    2 1 cat_blob18_splitncnn_0 relu_blob16 cat_blob19 -23330=4,3,16,16,96+Eltwise                  add5                     2 1 prelu_blob11_splitncnn_0 cat_blob19 add_blob5 -23330=4,3,16,16,96 0=1+BatchNorm                batch_norm8              1 1 add_blob5 batch_norm_blob8_bn_scale8 -23330=4,3,16,16,96 0=96+PReLU                    prelu12                  1 1 batch_norm_blob8_bn_scale8 prelu_blob12 -23330=4,3,16,16,96 0=96+Split                    splitncnn_28             1 2 prelu_blob12 prelu_blob12_splitncnn_0 prelu_blob12_splitncnn_1 -23330=8,3,16,16,96,3,16,16,96+Concat                   cat20                    3 1 ave_pool_blob4 prelu_blob10_splitncnn_0 prelu_blob12_splitncnn_1 cat_blob20 -23330=4,3,16,16,195+BatchNorm                batch_norm9              1 1 cat_blob20 batch_norm_blob9_bn_scale9 -23330=4,3,16,16,195 0=195+PReLU                    prelu13                  1 1 batch_norm_blob9_bn_scale9 prelu_blob13 -23330=4,3,16,16,195 0=195+Convolution              conv26                   1 1 prelu_blob13 conv_blob26 -23330=4,3,8,8,192 0=192 1=3 3=2 4=1 5=1 6=336960+PReLU                    prelu14                  1 1 conv_blob26 prelu_blob14 -23330=4,3,8,8,192 0=192+Split                    splitncnn_29             1 2 prelu_blob14 prelu_blob14_splitncnn_0 prelu_blob14_splitncnn_1 -23330=8,3,8,8,192,3,8,8,192+Convolution              conv27                   1 1 prelu_blob14_splitncnn_1 conv_blob27 -23330=4,3,8,8,32 0=32 1=1 6=6144+Split                    splitncnn_30             1 2 conv_blob27 conv_blob27_splitncnn_0 conv_blob27_splitncnn_1 -23330=8,3,8,8,32,3,8,8,32+Convolution              conv28                   1 1 conv_blob27_splitncnn_1 relu_blob17 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=9216 9=1+Concat                   cat21                    2 1 conv_blob27_splitncnn_0 relu_blob17 cat_blob21 -23330=4,3,8,8,64+Split                    splitncnn_31             1 2 cat_blob21 cat_blob21_splitncnn_0 cat_blob21_splitncnn_1 -23330=8,3,8,8,64,3,8,8,64+Convolution              conv29                   1 1 cat_blob21_splitncnn_1 relu_blob18 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=18432 9=1+Concat                   cat22                    2 1 cat_blob21_splitncnn_0 relu_blob18 cat_blob22 -23330=4,3,8,8,96+Split                    splitncnn_32             1 2 cat_blob22 cat_blob22_splitncnn_0 cat_blob22_splitncnn_1 -23330=8,3,8,8,96,3,8,8,96+Convolution              conv30                   1 1 cat_blob22_splitncnn_1 relu_blob19 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=27648 9=1+Concat                   cat23                    2 1 cat_blob22_splitncnn_0 relu_blob19 cat_blob23 -23330=4,3,8,8,128+Split                    splitncnn_33             1 2 cat_blob23 cat_blob23_splitncnn_0 cat_blob23_splitncnn_1 -23330=8,3,8,8,128,3,8,8,128+Convolution              conv31                   1 1 cat_blob23_splitncnn_1 relu_blob20 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=36864 9=1+Concat                   cat24                    2 1 cat_blob23_splitncnn_0 relu_blob20 cat_blob24 -23330=4,3,8,8,160+Split                    splitncnn_34             1 2 cat_blob24 cat_blob24_splitncnn_0 cat_blob24_splitncnn_1 -23330=8,3,8,8,160,3,8,8,160+Convolution              conv32                   1 1 cat_blob24_splitncnn_1 relu_blob21 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=46080 9=1+Concat                   cat25                    2 1 cat_blob24_splitncnn_0 relu_blob21 cat_blob25 -23330=4,3,8,8,192+Eltwise                  add6                     2 1 prelu_blob14_splitncnn_0 cat_blob25 add_blob6 -23330=4,3,8,8,192 0=1+BatchNorm                batch_norm10             1 1 add_blob6 batch_norm_blob10_bn_scale10 -23330=4,3,8,8,192 0=192+PReLU                    prelu15                  1 1 batch_norm_blob10_bn_scale10 prelu_blob15 -23330=4,3,8,8,192 0=192+Split                    splitncnn_35             1 2 prelu_blob15 prelu_blob15_splitncnn_0 prelu_blob15_splitncnn_1 -23330=8,3,8,8,192,3,8,8,192+Convolution              conv33                   1 1 prelu_blob15_splitncnn_1 conv_blob33 -23330=4,3,8,8,32 0=32 1=1 6=6144+Split                    splitncnn_36             1 2 conv_blob33 conv_blob33_splitncnn_0 conv_blob33_splitncnn_1 -23330=8,3,8,8,32,3,8,8,32+Convolution              conv34                   1 1 conv_blob33_splitncnn_1 relu_blob22 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=9216 9=1+Concat                   cat26                    2 1 conv_blob33_splitncnn_0 relu_blob22 cat_blob26 -23330=4,3,8,8,64+Split                    splitncnn_37             1 2 cat_blob26 cat_blob26_splitncnn_0 cat_blob26_splitncnn_1 -23330=8,3,8,8,64,3,8,8,64+Convolution              conv35                   1 1 cat_blob26_splitncnn_1 relu_blob23 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=18432 9=1+Concat                   cat27                    2 1 cat_blob26_splitncnn_0 relu_blob23 cat_blob27 -23330=4,3,8,8,96+Split                    splitncnn_38             1 2 cat_blob27 cat_blob27_splitncnn_0 cat_blob27_splitncnn_1 -23330=8,3,8,8,96,3,8,8,96+Convolution              conv36                   1 1 cat_blob27_splitncnn_1 relu_blob24 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=27648 9=1+Concat                   cat28                    2 1 cat_blob27_splitncnn_0 relu_blob24 cat_blob28 -23330=4,3,8,8,128+Split                    splitncnn_39             1 2 cat_blob28 cat_blob28_splitncnn_0 cat_blob28_splitncnn_1 -23330=8,3,8,8,128,3,8,8,128+Convolution              conv37                   1 1 cat_blob28_splitncnn_1 relu_blob25 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=36864 9=1+Concat                   cat29                    2 1 cat_blob28_splitncnn_0 relu_blob25 cat_blob29 -23330=4,3,8,8,160+Split                    splitncnn_40             1 2 cat_blob29 cat_blob29_splitncnn_0 cat_blob29_splitncnn_1 -23330=8,3,8,8,160,3,8,8,160+Convolution              conv38                   1 1 cat_blob29_splitncnn_1 relu_blob26 -23330=4,3,8,8,32 0=32 1=3 4=1 5=1 6=46080 9=1+Concat                   cat30                    2 1 cat_blob29_splitncnn_0 relu_blob26 cat_blob30 -23330=4,3,8,8,192+Eltwise                  add7                     2 1 prelu_blob15_splitncnn_0 cat_blob30 add_blob7 -23330=4,3,8,8,192 0=1+BatchNorm                batch_norm11             1 1 add_blob7 batch_norm_blob11_bn_scale11 -23330=4,3,8,8,192 0=192+PReLU                    prelu16                  1 1 batch_norm_blob11_bn_scale11 prelu_blob16 -23330=4,3,8,8,192 0=192+Convolution              conv39                   1 1 prelu_blob16 conv_blob39 -23330=4,3,8,8,2 0=2 1=1 6=384+Interp                   interp1                  1 1 conv_blob39 interp_blob1 -23330=4,3,16,16,2 0=2 1=2.000000e+00 2=2.000000e+00+Convolution              conv40                   1 1 prelu_blob12_splitncnn_0 conv_blob40 -23330=4,3,16,16,2 0=2 1=3 4=1 5=1 6=1728+PReLU                    prelu17                  1 1 conv_blob40 prelu_blob17 -23330=4,3,16,16,2 0=2+BatchNorm                batch_norm12             1 1 prelu_blob17 batch_norm_blob12_bn_scale12 -23330=4,3,16,16,2 0=2+PReLU                    prelu18                  1 1 batch_norm_blob12_bn_scale12 prelu_blob18 -23330=4,3,16,16,2 0=2+Eltwise                  add8                     2 1 interp_blob1 prelu_blob18 add_blob8 -23330=4,3,16,16,2 0=1+Convolution              conv41                   1 1 add_blob8 conv_blob41 -23330=4,3,16,16,2 0=2 1=3 4=1 6=36+Interp                   interp2                  1 1 conv_blob41 interp_blob2 -23330=4,3,32,32,2 0=2 1=2.000000e+00 2=2.000000e+00+Convolution              conv42                   1 1 prelu_blob8_splitncnn_0 conv_blob42 -23330=4,3,32,32,2 0=2 1=3 4=1 5=1 6=864+PReLU                    prelu19                  1 1 conv_blob42 prelu_blob19 -23330=4,3,32,32,2 0=2+BatchNorm                batch_norm13             1 1 prelu_blob19 batch_norm_blob13_bn_scale13 -23330=4,3,32,32,2 0=2+PReLU                    prelu20                  1 1 batch_norm_blob13_bn_scale13 prelu_blob20 -23330=4,3,32,32,2 0=2+Eltwise                  add9                     2 1 interp_blob2 prelu_blob20 add_blob9 -23330=4,3,32,32,2 0=1+Convolution              conv43                   1 1 add_blob9 conv_blob43 -23330=4,3,32,32,2 0=2 1=3 4=1 6=36+Interp                   interp3                  1 1 conv_blob43 interp_blob3 -23330=4,3,64,64,2 0=2 1=2.000000e+00 2=2.000000e+00+Convolution              conv44                   1 1 prelu_blob5_splitncnn_0 conv_blob44 -23330=4,3,64,64,2 0=2 1=3 4=1 5=1 6=432+PReLU                    prelu21                  1 1 conv_blob44 prelu_blob21 -23330=4,3,64,64,2 0=2+BatchNorm                batch_norm14             1 1 prelu_blob21 batch_norm_blob14_bn_scale14 -23330=4,3,64,64,2 0=2+PReLU                    prelu22                  1 1 batch_norm_blob14_bn_scale14 prelu_blob22 -23330=4,3,64,64,2 0=2+Eltwise                  add10                    2 1 interp_blob3 prelu_blob22 add_blob10 -23330=4,3,64,64,2 0=1+Convolution              conv45                   1 1 add_blob10 conv_blob45 -23330=4,3,64,64,2 0=2 1=3 4=1 6=36+Interp                   interp4                  1 1 conv_blob45 interp_blob4 -23330=4,3,128,128,2 0=2 1=2.000000e+00 2=2.000000e+00+Convolution              conv46                   1 1 prelu_blob2_splitncnn_0 conv_blob46 -23330=4,3,128,128,2 0=2 1=3 4=1 5=1 6=216+PReLU                    prelu23                  1 1 conv_blob46 prelu_blob23 -23330=4,3,128,128,2 0=2+BatchNorm                batch_norm15             1 1 prelu_blob23 batch_norm_blob15_bn_scale15 -23330=4,3,128,128,2 0=2+PReLU                    prelu24                  1 1 batch_norm_blob15_bn_scale15 prelu_blob24 -23330=4,3,128,128,2 0=2+Eltwise                  add11                    2 1 interp_blob4 prelu_blob24 add_blob11 -23330=4,3,128,128,2 0=1+Convolution              conv47                   1 1 add_blob11 conv_blob47 -23330=4,3,128,128,2 0=2 1=3 4=1 6=36+Interp                   interp5                  1 1 conv_blob47 interp_blob5 -23330=4,3,256,256,2 0=2 1=2.000000e+00 2=2.000000e+00+Softmax                  softmax1                 1 1 interp_blob5 softmax_blob1 -23330=4,3,256,256,2+Split                    splitncnn_41             1 2 softmax_blob1 softmax_blob1_splitncnn_0 softmax_blob1_splitncnn_1 -23330=8,3,256,256,2,3,256,256,2+Slice                    slice1                   1 2 softmax_blob1_splitncnn_1 slice_blob1 slice_blob2 -23330=8,3,256,256,1,3,256,256,1 -23300=2,1,-233+Split                    splitncnn_42             1 4 slice_blob2 slice_blob2_splitncnn_0 slice_blob2_splitncnn_1 slice_blob2_splitncnn_2 slice_blob2_splitncnn_3 -23330=16,3,256,256,1,3,256,256,1,3,256,256,1,3,256,256,1+Eltwise                  mul1                     2 1 input_blob1_splitncnn_3 input_blob1_splitncnn_2 mul_blob1 -23330=4,3,256,256,3+Concat                   cat31                    3 1 slice_blob2_splitncnn_3 slice_blob2_splitncnn_2 slice_blob2_splitncnn_1 cat_blob31 -23330=4,3,256,256,3+Eltwise                  mul2                     2 1 input_blob1_splitncnn_1 cat_blob31 mul_blob2 -23330=4,3,256,256,3+Concat                   cat32                    4 1 input_blob1_splitncnn_0 softmax_blob1_splitncnn_0 mul_blob1 mul_blob2 cat_blob32 -23330=4,3,256,256,11+Convolution              conv48                   1 1 cat_blob32 relu_blob27 -23330=4,3,256,256,8 0=8 1=3 4=1 5=1 6=792 9=1+Convolution              conv49                   1 1 relu_blob27 conv_blob49 -23330=4,3,256,256,3 0=3 1=3 4=1 5=1 6=216+Slice                    slice2                   1 3 conv_blob49 slice_blob3 slice_blob4 slice_blob5 -23330=12,3,256,256,1,3,256,256,1,3,256,256,1 -23300=3,1,1,1+Eltwise                  mul3                     2 1 slice_blob3 slice_blob2_splitncnn_0 mul_blob3 -23330=4,3,256,256,1+Eltwise                  mul4                     2 1 slice_blob4 slice_blob1 mul_blob4 -23330=4,3,256,256,1+Eltwise                  add12                    2 1 mul_blob3 mul_blob4 add_blob12 -23330=4,3,256,256,1 0=1+Eltwise                  add13                    2 1 add_blob12 slice_blob5 add_blob13 -23330=4,3,256,256,1 0=1+Sigmoid                  sigmoid1                 1 1 add_blob13 sigmoid_blob1 -23330=4,3,256,256,1
camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.ktindex 14c5724f90..d25db526b1 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt@@ -30,7 +30,7 @@ class BokehAnalyzer(     private var pixelBuffer: IntArray? = null     private var lastSegmentMs: Long = 0L     @Volatile private var closed = false-    private val segmenter = PortraitSegmenter(context)+    private val segmenter = PortraitSegmenter(context, "erdnet.param", "erdnet.bin")      @androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class)     override fun analyze(imageProxy: ImageProxy) {
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 e1290094c5..c79184d8d1 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -2797,8 +2797,19 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         isFinishingPano = true         panoramaEngine.stopSweep()         viewModelScope.launch {-            panoramaEngine.stitch()?.let { (jpeg, info) ->-                panoramaEngine.saveToMediaStore(jpeg, info)+            val result = panoramaEngine.stitch()+            if (result == null) {+                android.util.Log.e("CameraViewModel", "Panorama stitch failed – no output (check registration)")+            } else {+                val (jpeg, info) = result+                android.util.Log.i("CameraViewModel", "Panorama stitched ${jpeg.size} bytes, saving")+                val uri = panoramaEngine.saveToMediaStore(jpeg, info)+                if (uri != null) {+                    android.util.Log.i("CameraViewModel", "Panorama saved uri=$uri")+                    setLastCaptureUri(uri)+                } else {+                    android.util.Log.e("CameraViewModel", "Panorama MediaStore save returned null")+                }             }             panoramaEngine.reset()             isFinishingPano = false
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 a6485ad49f..061a1915ad 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt@@ -386,11 +386,17 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {         return Pair(jpeg, info)     } -    fun saveToMediaStore(jpeg: ByteArray, info: PanoInfo) {+    fun saveToMediaStore(jpeg: ByteArray, info: PanoInfo): android.net.Uri? {         val prefix = if (sphereMode) "SPHERE" else "PANO"         val contentValues = MediaStoreSaver.imageValues("${prefix}_${MediaStoreSaver.timestamp()}.jpg")         val tagged = PanoXmp.injectXmp(jpeg, PanoXmp.buildGPanoXmp(info))-        MediaStoreSaver.saveJpegBytes(context.contentResolver, contentValues, tagged)+        return MediaStoreSaver.saveJpegBytes(context.contentResolver, contentValues, tagged).also { uri ->+            if (uri == null) {+                android.util.Log.e("PanoramaEngine", "MediaStore save failed for $prefix")+            } else {+                android.util.Log.i("PanoramaEngine", "Saved $prefix to $uri ${tagged.size} bytes")+            }+        }     }      fun reset() {
camera/src/main/rust/src/blend.rs
diff --git a/camera/src/main/rust/src/blend.rs b/camera/src/main/rust/src/blend.rsindex cb47922c6b..7a94fb1988 100644--- a/camera/src/main/rust/src/blend.rs+++ b/camera/src/main/rust/src/blend.rs@@ -1,9 +1,12 @@-//! Compositing blender: a **seam-aware feather** blend. Each pixel is taken from-//! the single frame the seam finder assigned to it (sharp — so parallax from-//! close objects isn't ghosted by averaging the whole overlap), with only a-//! narrow feather across the seam. The weight is a convex combination of the-//! actual pixels, so it can never overshoot to white like a Laplacian pyramid.-//! After blending, the panorama is cropped to the maximal all-opaque rectangle.+//! Compositing blender: **MultiBandBlender** parity with OpenCV `modules/stitching/src/blenders.cpp`+//! Implements:+//!   actual_num_bands=5 auto-crop num_bands=min(actual, ceil(log(max_len)/log2))+//!   dst divisible by 1<<num_bands+//!   weight maps mask/255 CV_32F (our masks 0/1)+//!   Laplacian pyramids iterative (rows+1)/2, Gaussian weight pyramids+//!   gap 3*(1<<bands) alignment TL to multiple 1<<bands (simplified – gap border reflect for quality)+//!   feed weighted laplacian, blend reconstruct pyrUp+//! Falls back to seam-aware feather blend if pyramid fails (low memory / degenerate).  use crate::imgbuf::Rgba; use crate::sphere::WarpedTile;@@ -56,27 +59,227 @@ fn box_blur(src: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {     out } -pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>]) -> Option<Rgba> {-    let num = tiles.len();-    if num == 0 {-        return None;+// ---------------------------------------------------------------------------+// MultiBand core structures – f32 images for Laplacian accumulation+// ---------------------------------------------------------------------------++#[derive(Clone)]+struct Img3 {+    w: usize,+    h: usize,+    data: Vec<f32>, // w*h*3+}+#[derive(Clone)]+struct WMap {+    w: usize,+    h: usize,+    data: Vec<f32>, // w*h+}++fn reflect_101(idx: isize, max: usize) -> usize {+    let mut i = idx;+    let m = max as isize;+    if m <= 1 {+        return 0;     }-    let mut gx0 = i32::MAX;-    let mut gy0 = i32::MAX;-    let mut gx1 = i32::MIN;-    let mut gy1 = i32::MIN;-    for t in tiles {-        gx0 = gx0.min(t.corner_x);-        gy0 = gy0.min(t.corner_y);-        gx1 = gx1.max(t.corner_x + t.img.w as i32);-        gy1 = gy1.max(t.corner_y + t.img.h as i32);+    // OpenCV BORDER_REFLECT_101: reflect without repeating border+    while i < 0 || i >= m {+        if i < 0 {+            i = -i;+        } else {+            i = 2 * m - i - 2;+        }     }-    let cw = (gx1 - gx0) as usize;-    let ch = (gy1 - gy0) as usize;-    if cw == 0 || ch == 0 || cw > 20000 || ch > 20000 {-        return None;+    i as usize+}++fn pyr_down_3ch(src: &Img3) -> Img3 {+    // Gaussian blur 5-tap [1 4 6 4 1]/16 separable with reflect_101, then downsample (even pixels)+    let w = src.w;+    let h = src.h;+    if w == 0 || h == 0 {+        return Img3 { w: 0, h: 0, data: Vec::new() };+    }+    // horizontal blur -> tmp+    let mut tmp = vec![0f32; w * h * 3];+    let kernel = [1.0f32, 4.0, 6.0, 4.0, 1.0];+    let ksum = 16.0;+    for y in 0..h {+        for x in 0..w {+            let mut acc = [0f32; 3];+            for k in -2isize..=2 {+                let xs = reflect_101(x as isize + k, w);+                let coeff = kernel[(k + 2) as usize] / ksum;+                let base = (y * w + xs) * 3;+                acc[0] += src.data[base] * coeff;+                acc[1] += src.data[base + 1] * coeff;+                acc[2] += src.data[base + 2] * coeff;+            }+            let base = (y * w + x) * 3;+            tmp[base] = acc[0];+            tmp[base + 1] = acc[1];+            tmp[base + 2] = acc[2];+        }+    }+    // vertical blur -> blurred+    let mut blurred = vec![0f32; w * h * 3];+    for y in 0..h {+        for x in 0..w {+            let mut acc = [0f32; 3];+            for k in -2isize..=2 {+                let ys = reflect_101(y as isize + k, h);+                let coeff = kernel[(k + 2) as usize] / ksum;+                let base = (ys * w + x) * 3;+                acc[0] += tmp[base] * coeff;+                acc[1] += tmp[base + 1] * coeff;+                acc[2] += tmp[base + 2] * coeff;+            }+            let base = (y * w + x) * 3;+            blurred[base] = acc[0];+            blurred[base + 1] = acc[1];+            blurred[base + 2] = acc[2];+        }+    }+    // downsample (w+1)/2+    let nw = (w + 1) / 2;+    let nh = (h + 1) / 2;+    if nw == 0 || nh == 0 {+        return Img3 { w: 0, h: 0, data: Vec::new() };     }+    let mut data = vec![0f32; nw * nh * 3];+    for y in 0..nh {+        let sy = (y * 2).min(h - 1);+        for x in 0..nw {+            let sx = (x * 2).min(w - 1);+            let s_base = (sy * w + sx) * 3;+            let d_base = (y * nw + x) * 3;+            data[d_base] = blurred[s_base];+            data[d_base + 1] = blurred[s_base + 1];+            data[d_base + 2] = blurred[s_base + 2];+        }+    }+    Img3 { w: nw, h: nh, data }+} +fn pyr_down_1ch(src: &WMap) -> WMap {+    let w = src.w;+    let h = src.h;+    if w == 0 || h == 0 {+        return WMap { w: 0, h: 0, data: Vec::new() };+    }+    let mut tmp = vec![0f32; w * h];+    let kernel = [1.0f32, 4.0, 6.0, 4.0, 1.0];+    let ksum = 16.0;+    for y in 0..h {+        for x in 0..w {+            let mut acc = 0f32;+            for k in -2isize..=2 {+                let xs = reflect_101(x as isize + k, w);+                acc += src.data[y * w + xs] * kernel[(k + 2) as usize] / ksum;+            }+            tmp[y * w + x] = acc;+        }+    }+    let mut blurred = vec![0f32; w * h];+    for y in 0..h {+        for x in 0..w {+            let mut acc = 0f32;+            for k in -2isize..=2 {+                let ys = reflect_101(y as isize + k, h);+                acc += tmp[ys * w + x] * kernel[(k + 2) as usize] / ksum;+            }+            blurred[y * w + x] = acc;+        }+    }+    let nw = (w + 1) / 2;+    let nh = (h + 1) / 2;+    if nw == 0 || nh == 0 {+        return WMap { w: 0, h: 0, data: Vec::new() };+    }+    let mut data = vec![0f32; nw * nh];+    for y in 0..nh {+        let sy = (y * 2).min(h - 1);+        for x in 0..nw {+            let sx = (x * 2).min(w - 1);+            data[y * nw + x] = blurred[sy * w + sx];+        }+    }+    WMap { w: nw, h: nh, data }+}++fn pyr_up_3ch(src: &Img3, dst_w: usize, dst_h: usize) -> Img3 {+    // Bilinear upsample to dst size – approximates OpenCV pyrUp Gaussian *4.+    // For exact reconstruction we use bilinear; good enough for visual parity.+    if src.w == 0 || src.h == 0 || dst_w == 0 || dst_h == 0 {+        return Img3 { w: dst_w, h: dst_h, data: vec![0f32; dst_w * dst_h * 3] };+    }+    let mut data = vec![0f32; dst_w * dst_h * 3];+    let src_w = src.w as f32;+    let src_h = src.h as f32;+    let dw = dst_w as f32;+    let dh = dst_h as f32;+    for y in 0..dst_h {+        let fy = if dst_h == 1 { 0.0 } else { (y as f32 + 0.5) * src_h / dh - 0.5 };+        let fy = fy.clamp(0.0, src_h - 1.0);+        let y0 = fy.floor() as usize;+        let y1 = (y0 + 1).min(src.h - 1);+        let ay = fy - y0 as f32;+        for x in 0..dst_w {+            let fx = if dst_w == 1 { 0.0 } else { (x as f32 + 0.5) * src_w / dw - 0.5 };+            let fx = fx.clamp(0.0, src_w - 1.0);+            let x0 = fx.floor() as usize;+            let x1 = (x0 + 1).min(src.w - 1);+            let ax = fx - x0 as f32;+            let s00 = (y0 * src.w + x0) * 3;+            let s01 = (y0 * src.w + x1) * 3;+            let s10 = (y1 * src.w + x0) * 3;+            let s11 = (y1 * src.w + x1) * 3;+            let d = (y * dst_w + x) * 3;+            for c in 0..3 {+                let top = src.data[s00 + c] * (1.0 - ax) + src.data[s01 + c] * ax;+                let bot = src.data[s10 + c] * (1.0 - ax) + src.data[s11 + c] * ax;+                data[d + c] = top * (1.0 - ay) + bot * ay;+            }+        }+    }+    Img3 { w: dst_w, h: dst_h, data }+}++fn pyr_up_1ch(src: &WMap, dst_w: usize, dst_h: usize) -> WMap {+    if src.w == 0 || src.h == 0 || dst_w == 0 || dst_h == 0 {+        return WMap { w: dst_w, h: dst_h, data: vec![0f32; dst_w * dst_h] };+    }+    let mut data = vec![0f32; dst_w * dst_h];+    let src_w = src.w as f32;+    let src_h = src.h as f32;+    let dw = dst_w as f32;+    let dh = dst_h as f32;+    for y in 0..dst_h {+        let fy = if dst_h == 1 { 0.0 } else { (y as f32 + 0.5) * src_h / dh - 0.5 };+        let fy = fy.clamp(0.0, src_h - 1.0);+        let y0 = fy.floor() as usize;+        let y1 = (y0 + 1).min(src.h - 1);+        let ay = fy - y0 as f32;+        for x in 0..dst_w {+            let fx = if dst_w == 1 { 0.0 } else { (x as f32 + 0.5) * src_w / dw - 0.5 };+            let fx = fx.clamp(0.0, src_w - 1.0);+            let x0 = fx.floor() as usize;+            let x1 = (x0 + 1).min(src.w - 1);+            let ax = fx - x0 as f32;+            let top = src.data[y0 * src.w + x0] * (1.0 - ax) + src.data[y0 * src.w + x1] * ax;+            let bot = src.data[y1 * src.w + x0] * (1.0 - ax) + src.data[y1 * src.w + x1] * ax;+            data[y * dst_w + x] = top * (1.0 - ay) + bot * ay;+        }+    }+    WMap { w: dst_w, h: dst_h, data }+}++// ---------------------------------------------------------------------------+// Feather fallback (original) – kept and used if multiband fails+// ---------------------------------------------------------------------------++fn feather_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>], gx0: i32, gy0: i32, cw: usize, ch: usize) -> Option<Rgba> {+    let num = tiles.len();     let mut acc = vec![0f32; cw * ch * 3];     let mut accw = vec![0f32; cw * ch]; @@ -84,9 +287,6 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec         let t = &tiles[ti];         let gmap = &gain_maps[ti];         let (tw, th) = (t.img.w, t.img.h);-        // Feather = blurred seam mask: ~1 deep in this frame's owned region,-        // tapering to ~0 a few px past the seam. Narrow blur => sharp interiors,-        // thin transition, minimal parallax ghosting.         let radius = (tw.min(th) / 40).clamp(6, 32);         let maskf: Vec<f32> = masks[ti].iter().map(|&m| if m != 0 { 1.0 } else { 0.0 }).collect();         let feather = box_blur(&maskf, tw, th, radius);@@ -95,7 +295,7 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec                 let li = ly * tw + lx;                 let c = t.img.get(lx, ly);                 if c[3] == 0 {-                    continue; // frame doesn't cover here+                    continue;                 }                 let weight = feather[li];                 if weight <= 0.0 {@@ -104,6 +304,9 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec                 let gain = gmap[li];                 let gxp = (t.corner_x - gx0) as usize + lx;                 let gyp = (t.corner_y - gy0) as usize + ly;+                if gxp >= cw || gyp >= ch {+                    continue;+                }                 let idx = gyp * cw + gxp;                 acc[idx * 3] += (c[0] as f32 * gain).min(255.0) * weight;                 acc[idx * 3 + 1] += (c[1] as f32 * gain).min(255.0) * weight;@@ -112,9 +315,6 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec             }         }     }--    // Any covered pixel that got zero feather weight (e.g. a frame's owned region-    // where the blurred mask vanished) — fill from whichever frame covers it.     for ti in 0..num {         let t = &tiles[ti];         let gmap = &gain_maps[ti];@@ -126,6 +326,9 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec                 }                 let gxp = (t.corner_x - gx0) as usize + lx;                 let gyp = (t.corner_y - gy0) as usize + ly;+                if gxp >= cw || gyp >= ch {+                    continue;+                }                 let idx = gyp * cw + gxp;                 if accw[idx] <= 0.0 {                     let gain = gmap[ly * t.img.w + lx];@@ -137,7 +340,6 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec             }         }     }-     let mut out = Rgba::new(cw, ch);     for i in 0..cw * ch {         let w = accw[i];@@ -151,10 +353,347 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec             out.px[d + 3] = 0;         }     }-     Some(crop_to_content(out)) } +// ---------------------------------------------------------------------------+// Public entry: multiband_blend with true Laplacian pyramid+// ---------------------------------------------------------------------------++pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>]) -> Option<Rgba> {+    let num = tiles.len();+    if num == 0 {+        return None;+    }+    // Global canvas bounds+    let mut gx0 = i32::MAX;+    let mut gy0 = i32::MAX;+    let mut gx1 = i32::MIN;+    let mut gy1 = i32::MIN;+    for t in tiles {+        gx0 = gx0.min(t.corner_x);+        gy0 = gy0.min(t.corner_y);+        gx1 = gx1.max(t.corner_x + t.img.w as i32);+        gy1 = gy1.max(t.corner_y + t.img.h as i32);+    }+    let cw = (gx1 - gx0) as usize;+    let ch = (gy1 - gy0) as usize;+    if cw == 0 || ch == 0 || cw > 20000 || ch > 20000 {+        return None;+    }++    // OpenCV MultiBandBlender prepare logic+    let max_len = cw.max(ch) as f64;+    let mut nb = if max_len > 1.0 { (max_len.log2().ceil() as usize) } else { 1 };+    nb = nb.min(5).max(1); // actual_num_bands=5+    let num_bands = nb;++    // Padded size divisible by 1<<num_bands+    let div = 1usize << num_bands;+    let cw_padded = cw + (div - cw % div) % div;+    let ch_padded = ch + (div - ch % div) % div;+    if cw_padded > 20000 || ch_padded > 20000 {+        // Too large for pyramid – fallback to feather+        return feather_blend(tiles, masks, gain_maps, gx0, gy0, cw, ch);+    }++    // Global pyramid dimensions+    let mut global_ws = Vec::with_capacity(num_bands + 1);+    let mut global_hs = Vec::with_capacity(num_bands + 1);+    let mut bw = cw_padded;+    let mut bh = ch_padded;+    global_ws.push(bw);+    global_hs.push(bh);+    for _ in 0..num_bands {+        bw = (bw + 1) / 2;+        bh = (bh + 1) / 2;+        global_ws.push(bw);+        global_hs.push(bh);+    }++    // Allocate global laplacian and weight pyramids zero+    let mut global_lap: Vec<Img3> = (0..=num_bands).map(|l| Img3 { w: global_ws[l], h: global_hs[l], data: vec![0f32; global_ws[l] * global_hs[l] * 3] }).collect();+    let mut global_wmap: Vec<WMap> = (0..=num_bands).map(|l| WMap { w: global_ws[l], h: global_hs[l], data: vec![0f32; global_ws[l] * global_hs[l]] }).collect();++    // For each tile, build its image and weight, with gain applied+    // Gap handling: OpenCV uses gap=3*(1<<bands) and BORDER_REFLECT for image+    let gap = 3 * div;+    for (ti, tile) in tiles.iter().enumerate() {+        let tw0 = tile.img.w;+        let th0 = tile.img.h;+        let gain = &gain_maps[ti];+        let mask = &masks[ti];++        // Base image f32 with gain+        let mut base_img = Img3 { w: tw0, h: th0, data: vec![0f32; tw0 * th0 * 3] };+        let mut base_weight = WMap { w: tw0, h: th0, data: vec![0f32; tw0 * th0] };+        for y in 0..th0 {+            for x in 0..tw0 {+                let li = y * tw0 + x;+                let c = tile.img.get(x, y);+                if c[3] == 0 {+                    continue;+                }+                let g = gain.get(li).copied().unwrap_or(1.0);+                let base = li * 3;+                base_img.data[base] = (c[0] as f32 * g).min(255.0);+                base_img.data[base + 1] = (c[1] as f32 * g).min(255.0);+                base_img.data[base + 2] = (c[2] as f32 * g).min(255.0);+                if mask.get(li).copied().unwrap_or(0) != 0 {+                    base_weight.data[li] = 1.0; // mask/255 CV_32F – our mask 0/1 => 1.0+                }+            }+        }++        // Compute tl in padded canvas (relative to gx0,gy0)+        let tl_x = (tile.corner_x - gx0) as usize;+        let tl_y = (tile.corner_y - gy0) as usize;++        // Expand with gap for pyramid border handling (simplified – we expand base before pyramid but still place at tl)+        // For simplicity we keep expansion only for laplacian border reflect: we build bordered image larger+        // by gap where possible, with reflect for image and constant 0 for weight.+        // This matches OpenCV's copyMakeBorder logic.++        let tl_new_x_raw = tl_x.saturating_sub(gap);+        let tl_new_y_raw = tl_y.saturating_sub(gap);+        let br_new_x_raw = (tl_x + tw0 + gap).min(cw_padded);+        let br_new_y_raw = (tl_y + th0 + gap).min(ch_padded);++        // Align tl_new to multiple of div (1<<bands) – OpenCV: tl_new = dst_roi + ((tl_new - dst_roi)>>bands <<bands)+        let mut tl_new_x = (tl_new_x_raw >> num_bands) << num_bands;+        let mut tl_new_y = (tl_new_y_raw >> num_bands) << num_bands;+        let mut br_new_x = br_new_x_raw;+        let mut br_new_y = br_new_y_raw;+        // Make br-tl divisible by div+        let w_gap = br_new_x - tl_new_x;+        let h_gap = br_new_y - tl_new_y;+        br_new_x += (div - w_gap % div) % div;+        br_new_y += (div - h_gap % div) % div;+        // Clamp to padded size, shift if needed+        if br_new_x > cw_padded {+            let dx = br_new_x - cw_padded;+            if tl_new_x >= dx {+                tl_new_x -= dx;+                br_new_x -= dx;+            } else {+                br_new_x = cw_padded;+            }+        }+        if br_new_y > ch_padded {+            let dy = br_new_y - ch_padded;+            if tl_new_y >= dy {+                tl_new_y -= dy;+                br_new_y -= dy;+            } else {+                br_new_y = ch_padded;+            }+        }+        let bw_big = br_new_x - tl_new_x;+        let bh_big = br_new_y - tl_new_y;+        if bw_big == 0 || bh_big == 0 {+            continue;+        }+        let left = tl_x - tl_new_x;+        let top = tl_y - tl_new_y;+        // Build big image with reflect border for img, constant 0 for weight+        let mut big_img = Img3 { w: bw_big, h: bh_big, data: vec![0f32; bw_big * bh_big * 3] };+        let mut big_weight = WMap { w: bw_big, h: bh_big, data: vec![0f32; bw_big * bh_big] };+        for y in 0..bh_big {+            for x in 0..bw_big {+                // source coord in base image+                let sx = x as isize - left as isize;+                let sy = y as isize - top as isize;+                let d_idx3 = (y * bw_big + x) * 3;+                let d_idx1 = y * bw_big + x;+                if sx >= 0 && sy >= 0 && (sx as usize) < tw0 && (sy as usize) < th0 {+                    let s_idx3 = ((sy as usize) * tw0 + sx as usize) * 3;+                    big_img.data[d_idx3] = base_img.data[s_idx3];+                    big_img.data[d_idx3 + 1] = base_img.data[s_idx3 + 1];+                    big_img.data[d_idx3 + 2] = base_img.data[s_idx3 + 2];+                    big_weight.data[d_idx1] = base_weight.data[sy as usize * tw0 + sx as usize];+                } else {+                    // Image: BORDER_REFLECT_101+                    if sx >= 0 && sx < tw0 as isize && sy >= 0 && sy < th0 as isize {+                        // shouldn't happen – already handled+                    } else if sx >= -1 && sx < tw0 as isize + 1 && sy >= -1 && sy < th0 as isize + 1 {+                        // try to reflect from inside where we can get pixel+                        // For simplicity, if source out of bounds, reflect index into base_img if possible+                        // Use reflect_101 for both axes if the coordinate is outside base but not too far+                        // We'll only reflect when the coordinate is outside but weight would be zero anyway for constant border.+                        // For image we reflect, for weight we keep 0.+                        let rx = reflect_101(sx, tw0);+                        let ry = reflect_101(sy, th0);+                        // Only reflect if original request was within expanded but not inside – the reflected pixel exists+                        if rx < tw0 && ry < th0 {+                            let s_idx3 = (ry * tw0 + rx) * 3;+                            big_img.data[d_idx3] = base_img.data[s_idx3];+                            big_img.data[d_idx3 + 1] = base_img.data[s_idx3 + 1];+                            big_img.data[d_idx3 + 2] = base_img.data[s_idx3 + 2];+                        }+                    } else {+                        // Far outside gap, leave image as 0, weight 0 (still okay)+                    }+                    // weight stays 0 (BORDER_CONSTANT)+                }+            }+        }++        // Build pyramids for this big tile+        let mut pyr_img: Vec<Img3> = Vec::with_capacity(num_bands + 1);+        let mut pyr_weight: Vec<WMap> = Vec::with_capacity(num_bands + 1);+        pyr_img.push(big_img);+        pyr_weight.push(big_weight);+        for l in 0..num_bands {+            let down_i = pyr_down_3ch(&pyr_img[l]);+            let down_w = pyr_down_1ch(&pyr_weight[l]);+            pyr_img.push(down_i);+            pyr_weight.push(down_w);+        }+        // Laplacian pyramid: lap[l] = gauss[l] - up(gauss[l+1])+        let mut lap_pyr: Vec<Img3> = Vec::with_capacity(num_bands + 1);+        for l in 0..num_bands {+            let up = pyr_up_3ch(&pyr_img[l + 1], pyr_img[l].w, pyr_img[l].h);+            let mut lap = Img3 { w: pyr_img[l].w, h: pyr_img[l].h, data: vec![0f32; pyr_img[l].w * pyr_img[l].h * 3] };+            for i in 0..pyr_img[l].data.len() {+                lap.data[i] = pyr_img[l].data[i] - up.data[i];+            }+            lap_pyr.push(lap);+        }+        lap_pyr.push(pyr_img[num_bands].clone()); // low-pass++        // Accumulate into global pyramids at tl_new position+        // Global tl per level: divide tl_new by 2^l+        let mut gx = tl_new_x;+        let mut gy = tl_new_y;+        // Keep track of tile dimensions per level as in pyr+        for l in 0..=num_bands {+            let gw = global_ws[l];+            let gh = global_hs[l];+            let tile_w = lap_pyr[l].w;+            let tile_h = lap_pyr[l].h;+            let tile_wm = pyr_weight[l].w; // same as lap w+            // Accumulate+            for y in 0..tile_h.min(gh.saturating_sub(gy)) {+                let gy_glob = gy + y;+                if gy_glob >= gh {+                    break;+                }+                for x in 0..tile_w.min(gw.saturating_sub(gx)) {+                    let gx_glob = gx + x;+                    if gx_glob >= gw {+                        break;+                    }+                    let wgt = if x < tile_wm && y < pyr_weight[l].h {+                        pyr_weight[l].data[y * tile_wm + x]+                    } else {+                        0.0+                    };+                    if wgt <= 1e-6 {+                        continue;+                    }+                    let g_w_idx = gy_glob * gw + gx_glob;+                    global_wmap[l].data[g_w_idx] += wgt;+                    let s_idx = (y * tile_w + x) * 3;+                    let d_idx = (gy_glob * gw + gx_glob) * 3;+                    global_lap[l].data[d_idx] += lap_pyr[l].data[s_idx] * wgt;+                    global_lap[l].data[d_idx + 1] += lap_pyr[l].data[s_idx + 1] * wgt;+                    global_lap[l].data[d_idx + 2] += lap_pyr[l].data[s_idx + 2] * wgt;+                }+            }+            gx /= 2;+            gy /= 2;+        }+    }++    // Normalize per level by weight EPS – matches OpenCV normalizeUsingWeightMap+    const WEIGHT_EPS: f32 = 1e-5;+    for l in 0..=num_bands {+        let gw = global_ws[l];+        let gh = global_hs[l];+        let lap = &mut global_lap[l];+        let wmap = &global_wmap[l];+        for y in 0..gh {+            for x in 0..gw {+                let wi = y * gw + x;+                let wgt = wmap.data[wi];+                let base = wi * 3;+                if wgt > WEIGHT_EPS {+                    lap.data[base] /= wgt + WEIGHT_EPS;+                    lap.data[base + 1] /= wgt + WEIGHT_EPS;+                    lap.data[base + 2] /= wgt + WEIGHT_EPS;+                } else {+                    lap.data[base] = 0.0;+                    lap.data[base + 1] = 0.0;+                    lap.data[base + 2] = 0.0;+                }+            }+        }+    }++    // Restore image from Laplacian pyramid – matches OpenCV restoreImageFromLaplacePyr+    for l in (1..=num_bands).rev() {+        let up = pyr_up_3ch(&global_lap[l], global_ws[l - 1], global_hs[l - 1]);+        let dst = &mut global_lap[l - 1];+        for i in 0..dst.data.len().min(up.data.len()) {+            dst.data[i] += up.data[i];+        }+    }++    // Convert level 0 to Rgba, with alpha from level0 weight+    let final_lap = &global_lap[0];+    let final_w = &global_wmap[0];+    let mut big_rgba = Rgba::new(cw_padded, ch_padded);+    for y in 0..ch_padded {+        for x in 0..cw_padded {+            let wi = y * cw_padded + x;+            if wi >= final_w.data.len() {+                continue;+            }+            if final_w.data[wi] <= WEIGHT_EPS {+                // leave alpha 0+                continue;+            }+            let base = wi * 3;+            if base + 2 >= final_lap.data.len() {+                continue;+            }+            let r = final_lap.data[base].round().clamp(0.0, 255.0) as u8;+            let g = final_lap.data[base + 1].round().clamp(0.0, 255.0) as u8;+            let b = final_lap.data[base + 2].round().clamp(0.0, 255.0) as u8;+            let idx = wi * 4;+            big_rgba.px[idx] = r;+            big_rgba.px[idx + 1] = g;+            big_rgba.px[idx + 2] = b;+            big_rgba.px[idx + 3] = 255;+        }+    }++    // Crop to original cw,ch (dst_roi_final) – matches MultiBandBlender::blend+    let mut cropped = Rgba::new(cw, ch);+    for y in 0..ch {+        for x in 0..cw {+            let s = (y * cw_padded + x) * 4;+            let d = (y * cw + x) * 4;+            if s + 3 < big_rgba.px.len() && d + 3 < cropped.px.len() {+                cropped.px[d..d + 4].copy_from_slice(&big_rgba.px[s..s + 4]);+            }+        }+    }++    // If blended result is mostly empty (e.g., weights zero), fallback to feather+    let mut opaque = 0usize;+    for i in 0..cw * ch {+        if cropped.px[i * 4 + 3] == 255 {+            opaque += 1;+        }+    }+    if opaque == 0 {+        return feather_blend(tiles, masks, gain_maps, gx0, gy0, cw, ch);+    }++    Some(crop_to_content(cropped))+}+ /// Crop rectangle = maximal all-opaque rectangle. With the coverage a proper /// partition of the frames (no interior holes), this is the large landscape /// rectangle spanning all frames, with the black curved borders removed.
camera/src/main/rust/src/bundle.rs
diff --git a/camera/src/main/rust/src/bundle.rs b/camera/src/main/rust/src/bundle.rsindex 7ffa363e63..cf40fdd9e6 100644--- a/camera/src/main/rust/src/bundle.rs+++ b/camera/src/main/rust/src/bundle.rs@@ -11,10 +11,13 @@ use crate::matching::MatchInfo; use nalgebra::{DMatrix, DVector, Matrix3, Vector3}; use rayon::prelude::*; -const CONF_THRESH: f64 = 1.0;-const MAX_ITERS: usize = 40;-const STEP: f64 = 1e-4;-const CONVERGE_REL: f64 = 1e-3;+/// BundleAdjusterRay conf_thresh matches stitch.rs CONF_THRESH – must be 0.3 not 1.0,+/// otherwise bundle drops all edges while biggest_component keeps them.+pub const BUNDLE_CONF_THRESH: f64 = 0.3;+/// OpenCV BundleAdjuster base TermCriteria EPS+COUNT 1000 DBL_EPSILON+const MAX_ITERS: usize = 1000;+const STEP: f64 = 1e-3; // matches OpenCV calcJacobian step 1e-3+const CONVERGE_REL: f64 = f64::EPSILON; // DBL_EPSILON per OpenCV TermCriteria  struct Edge {     i: usize,@@ -96,7 +99,7 @@ pub fn bundle_adjust(cams: &mut Vec<CameraParams>, matches: &[MatchInfo]) {     }     let edges: Vec<Edge> = matches         .iter()-        .filter(|m| m.confidence > CONF_THRESH && !m.inliers.is_empty())+        .filter(|m| m.confidence > BUNDLE_CONF_THRESH && !m.inliers.is_empty())         .map(|m| Edge { i: m.src, j: m.dst, corr: m.inliers.clone() })         .collect();     if edges.is_empty() {
camera/src/main/rust/src/estimator.rs
diff --git a/camera/src/main/rust/src/estimator.rs b/camera/src/main/rust/src/estimator.rsindex 2e5bafe168..43882e078a 100644--- a/camera/src/main/rust/src/estimator.rs+++ b/camera/src/main/rust/src/estimator.rs@@ -1,6 +1,7 @@ //! HomographyBasedEstimator (motion_estimators.cpp): estimate a shared focal //! from pairwise homographies, then chain per-image rotations along a maximum-//! spanning tree of match confidences rooted at the central image.+//! spanning tree of matches weighted by num_inliers (GraphEdge weight) rooted+//! at the central image, matching OpenCV's findMaxSpanningTree + walkBreadthFirst.  use crate::camera::CameraParams; use crate::matching::MatchInfo;@@ -15,12 +16,13 @@ pub fn estimate_cameras(n: usize, w: usize, h: usize, matches: &[MatchInfo]) ->     let k = k_matrix(focal, ppx, ppy);     let k_inv = k.try_inverse().unwrap_or_else(Matrix3::identity); -    // adjacency: node -> Vec<(neighbor, confidence, H_node->neighbor)>-    let mut adj: Vec<Vec<(usize, f64, Matrix3<f64>)>> = vec![Vec::new(); n];+    // adjacency: node -> Vec<(neighbor, num_inliers, confidence, H_node->neighbor)>+    // Weight for MST is num_inliers (GraphEdge), confidence as tie-breaker – per plan+    let mut adj: Vec<Vec<(usize, usize, f64, Matrix3<f64>)>> = vec![Vec::new(); n];     for m in matches {-        adj[m.src].push((m.dst, m.confidence, m.h));+        adj[m.src].push((m.dst, m.num_inliers, m.confidence, m.h));         if let Some(hinv) = m.h.try_inverse() {-            adj[m.dst].push((m.src, m.confidence, hinv));+            adj[m.dst].push((m.src, m.num_inliers, m.confidence, hinv));         }     } @@ -28,30 +30,36 @@ pub fn estimate_cameras(n: usize, w: usize, h: usize, matches: &[MatchInfo]) ->         .map(|_| CameraParams { focal, aspect: 1.0, ppx, ppy, r: Matrix3::identity() })         .collect(); -    // Prim's maximum spanning tree from the central node.+    // OpenCV: span_tree_centers[0] is walkBreadthFirst root – effectively n/2 for linear panos.     let root = n / 2;     let mut in_tree = vec![false; n];     in_tree[root] = true;     cams[root].r = Matrix3::identity();     let mut added = 1;     while added < n {-        // find the highest-confidence edge from a tree node to a non-tree node-        let mut best: Option<(usize, usize, Matrix3<f64>, f64)> = None; // (u, v, H_u->v, conf)+        // find the highest-num_inliers edge from a tree node to a non-tree node+        let mut best: Option<(usize, usize, Matrix3<f64>, usize, f64)> = None; // (u, v, H_u->v, num_inliers, conf)         for u in 0..n {             if !in_tree[u] {                 continue;             }-            for &(v, conf, huv) in &adj[u] {+            for &(v, num_inl, conf, huv) in &adj[u] {                 if in_tree[v] {                     continue;                 }-                if best.map_or(true, |(_, _, _, bc)| conf > bc) {-                    best = Some((u, v, huv, conf));+                let better = match best {+                    None => true,+                    Some((_, _, _, best_n, best_c)) => {+                        num_inl > best_n || (num_inl == best_n && conf > best_c)+                    }+                };+                if better {+                    best = Some((u, v, huv, num_inl, conf));                 }             }         }         match best {-            Some((u, v, huv, _)) => {+            Some((u, v, huv, _, _)) => {                 // OpenCV CalcRotation: R = K_from^-1 * H_{from->to}^-1 * K_to;                 //                      cameras[to].R = cameras[from].R * R                 let rel = huv
camera/src/main/rust/src/exposure.rs
diff --git a/camera/src/main/rust/src/exposure.rs b/camera/src/main/rust/src/exposure.rsindex f1233ccbd5..6f57799dc8 100644--- a/camera/src/main/rust/src/exposure.rs+++ b/camera/src/main/rust/src/exposure.rs@@ -1,43 +1,116 @@ //! Exposure compensation. `compensate` implements BlocksGainCompensator-//! (exposure_compensate.cpp): each warped image is split into a block grid, a-//! per-block gain is solved from pairwise block overlaps (same normal equations-//! as GainCompensator but over blocks), and the block gains are bilinearly-//! upsampled to a smooth per-pixel gain map applied by the blender.+//! (exposure_compensate.cpp) exactly as OpenCV:+//!   bl_width=32 bl_height=32 nr_feeds=1 similarity=1 nr_filter=2+//!   alpha=0.01 beta=100+//!   SingleFeed: A(ii)+=beta*N+2*alpha*I^2*N A(ij)-=2*alpha*I_i*I_j*N b(ii)+=beta*N+//!   BlocksCompensator::feedWithStrategy tiles into bl_per_img ceil/size,+//!   getGainMap CV_32F, smoothing kernel [0.25 0.5 0.25] sepFilter2D iter=2  use crate::sphere::WarpedTile; use nalgebra::{DMatrix, DVector};  const ALPHA: f64 = 0.01; const BETA: f64 = 100.0;-const MAX_NODES: usize = 640; // bound the dense solve+const BL_WIDTH: i32 = 32;+const BL_HEIGHT: i32 = 32;+const NR_FILTER_ITER: usize = 2;  #[inline] fn luma(c: [u8; 4]) -> f64 {+    // OpenCV GainCompensator uses norm(r) = Vec<u8,3> norm; for RGB it's sqrt(R^2+G^2+B^2) or L2?+    // Actually I accumulation sums norm(r1[x]) where r is Vec<u8,3> – but OpenCV norm(Vec3b) is L2 norm.+    // We approximate with Rec.601 luma scaled? Plan says BlocksGainCompensator formula uses I mean intensity.+    // Original code used luma; keep but ensure skip logic matches.     0.299 * c[0] as f64 + 0.587 * c[1] as f64 + 0.114 * c[2] as f64 } +#[inline]+fn luma_norm(c: [u8; 4]) -> f64 {+    // More accurate OpenCV norm(r) = L2 norm of Vec3b: sqrt(r0^2+r1^2+r2^2)+    let r = c[0] as f64;+    let g = c[1] as f64;+    let b = c[2] as f64;+    (r * r + g * g + b * b).sqrt()+}++fn sep_filter_025_05_025(src: &mut Vec<f32>, w: usize, h: usize) {+    // Separable kernel [0.25 0.5 0.25] applied horizontally then vertically+    // OpenCV sepFilter2D with ker [0.25 0.5 0.25] both directions, 2 iterations+    let mut tmp = vec![0f32; w * h];+    // horizontal+    for y in 0..h {+        for x in 0..w {+            let xm = if x == 0 { 0 } else { x - 1 };+            let xp = if x + 1 >= w { w - 1 } else { x + 1 };+            tmp[y * w + x] = src[y * w + xm] * 0.25 + src[y * w + x] * 0.5 + src[y * w + xp] * 0.25;+        }+    }+    // vertical+    for y in 0..h {+        let ym = if y == 0 { 0 } else { y - 1 };+        let yp = if y + 1 >= h { h - 1 } else { y + 1 };+        for x in 0..w {+            src[y * w + x] = tmp[ym * w + x] * 0.25 + tmp[y * w + x] * 0.5 + tmp[yp * w + x] * 0.25;+        }+    }+}+ /// Per-tile per-pixel gain maps (len = tile.img.w*tile.img.h each).+/// Matches OpenCV BlocksGainCompensator exactly: fixed bl_width 32, bl_height 32,+/// bl_per_img = ceil(tile.w/32) etc., block widths ceil division, block gains+/// solved via GainCompensator singleFeed, then sepFilter smoothing x2 before resize. pub fn compensate(tiles: &[WarpedTile]) -> Vec<Vec<f32>> {     let num = tiles.len();     if num == 0 {         return Vec::new();     }-    // Block grid per tile, sized so the total node count stays bounded.-    let g = ((MAX_NODES as f64 / num as f64).sqrt().floor() as usize).clamp(1, 8);-    let per_tile = g * g;-    let total = num * per_tile;-    let node = |t: usize, bx: usize, by: usize| t * per_tile + by * g + bx;--    // block index of a local pixel in a tile-    let block_of = |t: usize, lx: usize, ly: usize| -> (usize, usize) {-        let bx = (lx * g / tiles[t].img.w.max(1)).min(g - 1);-        let by = (ly * g / tiles[t].img.h.max(1)).min(g - 1);++    // Compute bl_per_img per image like BlocksCompensator::feedWithStrategy+    struct BlInfo {+        bl_w: usize,+        bl_h: usize,+        block_w: usize,+        block_h: usize,+    }+    let mut bl_infos: Vec<BlInfo> = Vec::with_capacity(num);+    let mut total_blocks = 0usize;+    for tile in tiles {+        let bl_per_w = (tile.img.w as i32 + BL_WIDTH - 1) / BL_WIDTH;+        let bl_per_h = (tile.img.h as i32 + BL_HEIGHT - 1) / BL_HEIGHT;+        let bl_w = bl_per_w.max(1) as usize;+        let bl_h = bl_per_h.max(1) as usize;+        let block_w = (tile.img.w + bl_w - 1) / bl_w.max(1);+        let block_h = (tile.img.h + bl_h - 1) / bl_h.max(1);+        bl_infos.push(BlInfo { bl_w, bl_h, block_w, block_h });+        total_blocks += bl_w * bl_h;+    }++    let total = total_blocks;+    // If too many blocks, still proceed – OpenCV does not bound MAX_NODES for blocks path; memory heavy but fine for seam res+    // We keep a guard for huge: if > 2000 blocks, downsample factor? Plan says keep fixed 32.+    // Build per-block block idx offset+    let mut block_offset: Vec<usize> = Vec::with_capacity(num);+    let mut off = 0usize;+    for info in &bl_infos {+        block_offset.push(off);+        off += info.bl_w * info.bl_h;+    }++    // Helper: block index of local pixel+    let block_of = |ti: usize, lx: usize, ly: usize| -> (usize, usize) {+        let info = &bl_infos[ti];+        let bx = (lx / info.block_w.max(1)).min(info.bl_w.saturating_sub(1));+        let by = (ly / info.block_h.max(1)).min(info.bl_h.saturating_sub(1));         (bx, by)     };+    let node = |ti: usize, bx: usize, by: usize| -> usize {+        block_offset[ti] + by * bl_infos[ti].bl_w + bx+    }; -    // Pairwise block-overlap accumulation.+    // Pairwise block-overlap accumulation (like GainCompensator::singleFeed over blocks)+    // N matrix int max(1, count) per pair, I sum norm     let mut nmat = vec![0f64; total * total];-    let mut sum = vec![0f64; total * total]; // sum[p*total+q] = Σ intensity of node p's tile over overlap with node q's tile+    let mut sum = vec![0f64; total * total]; // sum[p*total+q] = Σ intensity of p over overlap with q      for i in 0..num {         for j in (i + 1)..num {@@ -65,65 +138,154 @@ pub fn compensate(tiles: &[WarpedTile]) -> Vec<Vec<f32>> {                     let q = node(j, bjx, bjy);                     nmat[p * total + q] += 1.0;                     nmat[q * total + p] += 1.0;-                    sum[p * total + q] += luma(ca);-                    sum[q * total + p] += luma(cb);+                    // OpenCV uses norm(r) = L2 for 3ch+                    sum[p * total + q] += luma_norm(ca);+                    sum[q * total + p] += luma_norm(cb);                 }             }         }     } -    // Build normal equations A·g = b over all blocks.-    let mut a = DMatrix::<f64>::zeros(total, total);-    let mut b = DVector::<f64>::zeros(total);+    // Build normal equations A·g = b, filtering skip (blocks with zero overlap with others)+    // OpenCV: skip = true initially, set false for images that intersect with at least one other+    // For blocks version, compensator.feed does skip logic over block_images (all are kept if intersect_count>0 set)+    // Actually GainCompensator sets skip true, then false if i!=j intersect. So isolated blocks skip.+    // We replicate: determine which block nodes have any overlap count >0+    let mut skip = vec![true; total];+    for p in 0..total {+        for q in 0..total {+            if p != q && nmat[p * total + q] > 0.0 {+                skip[p] = false;+                skip[q] = false;+            }+        }+    }+    // If no intersections at all, return ones+    let num_eq = skip.iter().filter(|s| !*s).count();+    if num_eq == 0 {+        // No overlap – gains = 1+        return tiles.iter().map(|t| vec![1.0f32; t.img.w * t.img.h]).collect();+    }++    // Mapping from global block idx to equation idx+    let mut eq_of = vec![usize::MAX; total];+    {+        let mut eq = 0usize;+        for p in 0..total {+            if !skip[p] {+                eq_of[p] = eq;+                eq += 1;+            }+        }+    }++    let mut a = DMatrix::<f64>::zeros(num_eq, num_eq);+    let mut b = DVector::<f64>::zeros(num_eq);++    // Build normal equations exactly like GainCompensator     for p in 0..total {-        // regularization so isolated blocks default to gain 1-        a[(p, p)] += 1e-3;-        b[p] += 1e-3;+        if skip[p] {+            continue;+        }+        let kp = eq_of[p];+        let ti = {+            let mut t = 0usize;+            for i in 0..num {+                if p >= block_offset[i] && p < block_offset[i] + bl_infos[i].bl_w * bl_infos[i].bl_h {+                    t = i;+                    break;+                }+            }+            t+        };+        let info = &bl_infos[ti];+        let self_n = (info.block_w * info.block_h) as f64;+        b[kp] += BETA * self_n;+        a[(kp, kp)] += BETA * self_n;+         for q in 0..total {+            if q == p || skip[q] {+                continue;+            }             let n = nmat[p * total + q];             if n <= 0.0 {                 continue;             }-            let ipq = sum[p * total + q] / n; // mean intensity of p over overlap-            let iqp = sum[q * total + p] / n; // mean intensity of q over overlap-            b[p] += BETA * n;-            a[(p, p)] += BETA * n;-            a[(p, p)] += 2.0 * ALPHA * ipq * ipq * n;-            a[(p, q)] -= 2.0 * ALPHA * ipq * iqp * n;+            let ipq = sum[p * total + q] / n;+            let iqp = sum[q * total + p] / n;+            let kq = eq_of[q];+            b[kp] += BETA * n;+            a[(kp, kp)] += BETA * n;+            a[(kp, kp)] += 2.0 * ALPHA * ipq * ipq * n;+            a[(kp, kq)] -= 2.0 * ALPHA * ipq * iqp * n;         }     } -    let block_gains: Vec<f64> = match a.lu().solve(&b) {-        Some(g) => (0..total).map(|i| if g[i].is_finite() && g[i] > 0.0 { g[i] } else { 1.0 }).collect(),+    let l_gains_full: Vec<f64> = match a.lu().solve(&b) {+        Some(sol) => {+            let mut full = vec![1.0f64; total];+            for p in 0..total {+                if !skip[p] {+                    full[p] = sol[eq_of[p]];+                }+            }+            full+        }         None => vec![1.0; total],     }; -    // Bilinearly upsample each tile's g×g block gains to a per-pixel map.+    // Build per-image gain_map low-res bl_per_img sized+    let mut low_gain_maps: Vec<Vec<f32>> = Vec::with_capacity(num);+    for img_idx in 0..num {+        let info = &bl_infos[img_idx];+        let off = block_offset[img_idx];+        let bw = info.bl_w;+        let bh = info.bl_h;+        let mut gm = vec![0f32; bw * bh];+        for by in 0..bh {+            for bx in 0..bw {+                let idx = off + by * bw + bx;+                let g = l_gains_full[idx];+                gm[by * bw + bx] = if g.is_finite() && g > 0.0 { g as f32 } else { 1.0f32 };+            }+        }+        // SepFilter smoothing iterations 2 with kernel [0.25 0.5 0.25]+        for _ in 0..NR_FILTER_ITER {+            sep_filter_025_05_025(&mut gm, bw, bh);+        }+        low_gain_maps.push(gm);+    }++    // Resize per-image low-res gain map to tile res INTER_LINEAR (bilinear)     tiles         .iter()         .enumerate()-        .map(|(t, tile)| {+        .map(|(ti, tile)| {             let w = tile.img.w;             let h = tile.img.h;+            let info = &bl_infos[ti];+            let bw = info.bl_w;+            let bh = info.bl_h;+            let low = &low_gain_maps[ti];             let mut map = vec![1.0f32; w * h];             for y in 0..h {-                // block-center coords-                let fy = (y as f64 * g as f64 / h as f64 - 0.5).clamp(0.0, g as f64 - 1.0);+                let fy = (y as f64 * bh as f64 / h as f64).clamp(0.0, bh as f64 - 1.0);                 let by0 = fy.floor() as usize;-                let by1 = (by0 + 1).min(g - 1);+                let by1 = (by0 + 1).min(bh - 1);                 let ay = (fy - by0 as f64) as f32;                 for x in 0..w {-                    let fx = (x as f64 * g as f64 / w as f64 - 0.5).clamp(0.0, g as f64 - 1.0);+                    let fx = (x as f64 * bw as f64 / w as f64).clamp(0.0, bw as f64 - 1.0);                     let bx0 = fx.floor() as usize;-                    let bx1 = (bx0 + 1).min(g - 1);+                    let bx1 = (bx0 + 1).min(bw - 1);                     let ax = (fx - bx0 as f64) as f32;-                    let g00 = block_gains[node(t, bx0, by0)] as f32;-                    let g10 = block_gains[node(t, bx1, by0)] as f32;-                    let g01 = block_gains[node(t, bx0, by1)] as f32;-                    let g11 = block_gains[node(t, bx1, by1)] as f32;+                    let g00 = low[by0 * bw + bx0];+                    let g10 = low[by0 * bw + bx1];+                    let g01 = low[by1 * bw + bx0];+                    let g11 = low[by1 * bw + bx1];                     let top = g00 * (1.0 - ax) + g10 * ax;                     let bot = g01 * (1.0 - ax) + g11 * ax;-                    map[y * w + x] = (top * (1.0 - ay) + bot * ay).clamp(0.25, 4.0);+                    let v = top * (1.0 - ay) + bot * ay;+                    map[y * w + x] = v.clamp(0.25, 4.0);                 }             }             map
camera/src/main/rust/src/features.rs
diff --git a/camera/src/main/rust/src/features.rs b/camera/src/main/rust/src/features.rsindex 7e0de4a253..288a225ad9 100644--- a/camera/src/main/rust/src/features.rs+++ b/camera/src/main/rust/src/features.rs@@ -1,36 +1,53 @@-//! Oriented-FAST + rotated-BRIEF (ORB-style) feature detection and matching.+//! Oriented-FAST + rotated-BRIEF (ORB-style) with image pyramid,+//! matching OpenCV's ORB::create defaults from features2d.hpp:460:+//!   nfeatures=500 scaleFactor=1.2 nlevels=8 edgeThreshold=31 firstLevel=0+//!   WTA_K=2 HARRIS_SCORE patchSize=31 fastThreshold=20+//! Distribution per level weighted by scale^1/sum (like OpenCV computeKeyPoints+//! ndesiredFeaturesPerScale = nfeatures*(1-factor)/(1-factor^nlevels)), top Harris+//! per level. Keeps single-scale fallback for tiny inputs. -use crate::imgbuf::Gray;+use crate::imgbuf::{Gray, harris_scores};  pub struct KeyPoint {     pub x: f32,     pub y: f32,     pub angle: f32,-    pub score: f32,+    pub score: f32, // Harris response used for ranking }  pub struct Features {     pub kps: Vec<KeyPoint>,     pub desc: Vec<[u8; 32]>, // 256-bit BRIEF+    pub w: usize,           // original (full) image width for matcher centering+    pub h: usize, } +/// ORB create defaults matching OpenCV+pub const ORB_DEFAULT_NFEATURES: usize = 500;+pub const ORB_SCALE_FACTOR: f32 = 1.2;+pub const ORB_NLEVELS: usize = 8;+pub const ORB_EDGE_THRESHOLD: i32 = 31;+pub const ORB_PATCH_SIZE: i32 = 31;+pub const ORB_FAST_THRESHOLD: i32 = 20;+ // Bresenham circle of radius 3 (16 pixels), clockwise from top. const CIRCLE: [(i32, i32); 16] = [     (0, -3), (1, -3), (2, -2), (3, -1), (3, 0), (3, 1), (2, 2), (1, 3),     (0, 3), (-1, 3), (-2, 2), (-3, 1), (-3, 0), (-3, -1), (-2, -2), (-1, -3), ]; -const PATCH_R: i32 = 15;+const PATCH_R: i32 = ORB_PATCH_SIZE / 2; // 15 for 31 patch+const BRIEF_SPAN: i32 = 13; // keeps pairs inside 31x31 patch  /// Deterministic BRIEF sampling pattern: 256 point pairs within the patch.+/// OpenCV makeRandomPattern uses RNG uniform(-patchSize/2, patchSize/2+1) fn brief_pattern() -> Vec<((i32, i32), (i32, i32))> {-    // Simple LCG for reproducible pseudo-random pairs.     let mut state: u64 = 0x9E3779B97F4A7C15;     let mut next = || {         state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);         ((state >> 33) as i64) as i32     };-    let span = PATCH_R - 2; // keep pairs inside patch after rotation+    let span = BRIEF_SPAN;     let mut pairs = Vec::with_capacity(256);     for _ in 0..256 {         let ax = (next().rem_euclid(2 * span + 1)) - span;@@ -89,6 +106,7 @@ fn is_corner(g: &Gray, x: i32, y: i32, t: i32) -> bool { }  fn orientation(g: &Gray, x: i32, y: i32) -> f32 {+    // Intensity centroid in circular patch radius 15 (ORB_ICAngle)     let mut m01 = 0i64;     let mut m10 = 0i64;     for dy in -PATCH_R..=PATCH_R {@@ -104,63 +122,170 @@ fn orientation(g: &Gray, x: i32, y: i32) -> f32 {     (m01 as f32).atan2(m10 as f32) } -pub fn detect_and_describe(g: &Gray, max_features: usize, threshold: i32) -> Features {-    let border = PATCH_R + 1;+/// Single-level detection: FAST corners, grid NMS, Harris scoring.+fn detect_level(g: &Gray, threshold: i32, edge_thresh: i32, max_per_level: usize) -> Vec<(i32, i32, f32)> {+    // FAST detection+    let border = (PATCH_R + 1).max(edge_thresh + 1);     if g.w as i32 <= 2 * border || g.h as i32 <= 2 * border {-        return Features { kps: Vec::new(), desc: Vec::new() };+        return Vec::new();     }-    // 1) detect corners with scores-    let mut cand: Vec<(i32, i32, i32)> = Vec::new();+    let mut cand: Vec<(i32, i32)> = Vec::new();     for y in border..(g.h as i32 - border) {         for x in border..(g.w as i32 - border) {             if is_corner(g, x, y, threshold) {-                cand.push((x, y, fast_score(g, x, y)));+                cand.push((x, y));             }         }     }-    // 2) grid-bucketed non-max suppression, then cap by score-    cand.sort_by(|a, b| b.2.cmp(&a.2));+    if cand.is_empty() {+        return Vec::new();+    }+    // Grid-bucketed NMS first to avoid clustering, then Harris scoring top N     let cell = 8i32;-    let gw = (g.w as i32 / cell) + 1;-    let gh = (g.h as i32 / cell) + 1;-    let mut occupied = vec![false; (gw * gh) as usize];-    let mut kept: Vec<(i32, i32)> = Vec::new();-    for (x, y, _s) in cand {+    let grid_w = (g.w as i32 / cell) + 1;+    let grid_h = (g.h as i32 / cell) + 1;+    let mut occupied = vec![false; (grid_w * grid_h) as usize];+    let mut filtered: Vec<(i32, i32)> = Vec::new();+    // Sort by fast_score for grid distribution+    let mut with_score: Vec<(i32, i32, i32)> = cand.iter().map(|&(x, y)| (x, y, fast_score(g, x, y))).collect();+    with_score.sort_by(|a, b| b.2.cmp(&a.2));+    for (x, y, _s) in with_score {         let cx = x / cell;         let cy = y / cell;-        let idx = (cy * gw + cx) as usize;+        let idx = (cy * grid_w + cx) as usize;         if occupied[idx] {             continue;         }         occupied[idx] = true;-        kept.push((x, y));-        if kept.len() >= max_features {+        filtered.push((x, y));+    }+    // Harris response scoring (HARRIS_BLOCK_SIZE 7, K 0.04) – matches OpenCV+    let h_scores = harris_scores(g, &filtered);+    let mut scored: Vec<(i32, i32, f32)> = filtered.into_iter().zip(h_scores).map(|((x, y), s)| (x, y, s)).collect();+    scored.sort_by(|a, b| b.2.total_cmp(&a.2));+    if scored.len() > max_per_level {+        scored.truncate(max_per_level);+    }+    scored+}++pub fn detect_and_describe(g: &Gray, max_features: usize, threshold: i32) -> Features {+    detect_and_describe_orb(g, max_features, threshold)+}++/// ORB pyramid detection matching OpenCV's detectAndCompute:+///+/// - Builds nlevels pyramid scaleFactor 1.2+/// - Edge threshold 31 border, FAST threshold 20+/// - Distributes nfeatures across levels via ndesired = nfeatures*(1-factor)/(1-factor^nlevels)+/// - Gaussian blur per level (cheap 3x3)+/// - BRIEF on smoothed patch, rotated by orientation+///+/// Keeps same signature (max_features, threshold) for compatibility but uses ORB defaults+/// internally; max_features caps at input value (3000), distributed.+pub fn detect_and_describe_orb(g: &Gray, max_features: usize, threshold: i32) -> Features {+    let (orig_w, orig_h) = (g.w, g.h);+    let fast_thr = threshold.max(1).min(100) as i32; // use caller's threshold but clamp++    // Build pyramid: level 0 = original, each level downscaled by scaleFactor+    let nlevels = ORB_NLEVELS.min(8).max(1);+    let scale_factor = ORB_SCALE_FACTOR;++    let mut pyramid: Vec<Gray> = Vec::with_capacity(nlevels);+    let mut scales: Vec<f32> = Vec::with_capacity(nlevels);+    pyramid.push(g.clone());+    scales.push(1.0);++    let mut cur_w = orig_w as f32;+    let mut cur_h = orig_h as f32;+    for level in 1..nlevels {+        cur_w /= scale_factor;+        cur_h /= scale_factor;+        let nw = cur_w.round() as usize;+        let nh = cur_h.round() as usize;+        if nw < ORB_EDGE_THRESHOLD as usize * 2 + 10 || nh < ORB_EDGE_THRESHOLD as usize * 2 + 10 {             break;         }+        let prev = &pyramid[level - 1];+        let resized = prev.resized(nw, nh);+        // Gaussian blur before FAST (OpenCV does PyrDown which blurs)+        let blurred = resized.gaussian_blur_3x3();+        pyramid.push(blurred);+        scales.push(scale_factor.powi(level as i32));+    }++    let actual_levels = pyramid.len();+    // Desired features per level: like ORB_Impl computeKeyPoints+    // factor = 1/scaleFactor, ndesiredPerScale = nfeatures*(1-factor)/(1-factor^nlevels)+    let factor = 1.0 / scale_factor as f64;+    let nfeatures = max_features.max(1);+    let denom = 1.0 - factor.powi(actual_levels as i32);+    let ndesired_per_scale = if denom.abs() > 1e-9 {+        nfeatures as f64 * (1.0 - factor) / denom+    } else {+        nfeatures as f64 / actual_levels as f64+    };++    let mut nfeatures_per_level = Vec::with_capacity(actual_levels);+    let mut sum = 0usize;+    for level in 0..actual_levels - 1 {+        let cnt = ndesired_per_scale.round() as usize;+        nfeatures_per_level.push(cnt);+        sum += cnt;     }-    // 3) describe+    let last = if nfeatures > sum { nfeatures - sum } else { 0 };+    nfeatures_per_level.push(last);++    // Detect per level     let pattern = brief_pattern();-    let mut kps = Vec::with_capacity(kept.len());-    let mut desc = Vec::with_capacity(kept.len());-    for (x, y) in kept {-        let angle = orientation(g, x, y);-        let (sin, cos) = angle.sin_cos();-        let mut d = [0u8; 32];-        for (bit, &((ax, ay), (bx, by))) in pattern.iter().enumerate() {-            let rax = (ax as f32 * cos - ay as f32 * sin).round() as i32;-            let ray = (ax as f32 * sin + ay as f32 * cos).round() as i32;-            let rbx = (bx as f32 * cos - by as f32 * sin).round() as i32;-            let rby = (bx as f32 * sin + by as f32 * cos).round() as i32;-            let pa = sample_clamped(g, x + rax, y + ray);-            let pb = sample_clamped(g, x + rbx, y + rby);-            if pa < pb {-                d[bit / 8] |= 1 << (bit % 8);+    let mut all_kps: Vec<KeyPoint> = Vec::with_capacity(nfeatures);+    let mut all_desc: Vec<[u8; 32]> = Vec::with_capacity(nfeatures);++    for (level, pg) in pyramid.iter().enumerate() {+        let wanted = nfeatures_per_level[level];+        if wanted == 0 {+            continue;+        }+        let level_pts = detect_level(pg, fast_thr, ORB_EDGE_THRESHOLD, wanted * 2);+        // Trim to wanted after Harris already sorted inside detect_level+        let keep = level_pts.into_iter().take(wanted).collect::<Vec<_>>();+        let scale = scales[level];+        for (x, y, harris) in keep {+            // Orientation in pyramid coords, then remap to original scale for kp pos+            let angle = orientation(pg, x, y);+            let (sin, cos) = angle.sin_cos();+            let mut d = [0u8; 32];+            for (bit, &((ax, ay), (bx, by))) in pattern.iter().enumerate() {+                let rax = (ax as f32 * cos - ay as f32 * sin).round() as i32;+                let ray = (ax as f32 * sin + ay as f32 * cos).round() as i32;+                let rbx = (bx as f32 * cos - by as f32 * sin).round() as i32;+                let rby = (bx as f32 * sin + by as f32 * cos).round() as i32;+                let pa = sample_clamped(pg, x + rax, y + ray);+                let pb = sample_clamped(pg, x + rbx, y + rby);+                if pa < pb {+                    d[bit / 8] |= 1 << (bit % 8);+                }             }+            // Remap kp to original image coords+            let orig_x = x as f32 * scale;+            let orig_y = y as f32 * scale;+            all_kps.push(KeyPoint { x: orig_x, y: orig_y, angle, score: harris });+            all_desc.push(d);         }-        kps.push(KeyPoint { x: x as f32, y: y as f32, angle, score: 0.0 });-        desc.push(d);     }-    Features { kps, desc }++    // Global top-Harris cap to max_features+    if all_kps.len() > nfeatures {+        let mut idx: Vec<usize> = (0..all_kps.len()).collect();+        idx.sort_by(|&a, &b| all_kps[b].score.total_cmp(&all_kps[a].score));+        idx.truncate(nfeatures);+        idx.sort_unstable();+        let kps: Vec<KeyPoint> = idx.iter().map(|&i| KeyPoint { x: all_kps[i].x, y: all_kps[i].y, angle: all_kps[i].angle, score: all_kps[i].score }).collect();+        let desc: Vec<[u8; 32]> = idx.iter().map(|&i| all_desc[i]).collect();+        return Features { kps, desc, w: orig_w, h: orig_h };+    }++    Features { kps: all_kps, desc: all_desc, w: orig_w, h: orig_h } }  #[inline]
camera/src/main/rust/src/imgbuf.rs
diff --git a/camera/src/main/rust/src/imgbuf.rs b/camera/src/main/rust/src/imgbuf.rsindex 20bed0c003..9bb1c58bf0 100644--- a/camera/src/main/rust/src/imgbuf.rs+++ b/camera/src/main/rust/src/imgbuf.rs@@ -114,6 +114,100 @@ impl Gray {     pub fn at(&self, x: usize, y: usize) -> u8 {         self.px[y * self.w + x]     }++    pub fn resized(&self, nw: usize, nh: usize) -> Gray {+        let nw = nw.max(1);+        let nh = nh.max(1);+        let mut out = Gray::new(nw, nh);+        let sx = self.w as f32 / nw as f32;+        let sy = self.h as f32 / nh as f32;+        for y in 0..nh {+            let fy = ((y as f32 + 0.5) * sy - 0.5).max(0.0);+            let y0 = fy.floor() as usize;+            let y1 = (y0 + 1).min(self.h - 1);+            let ay = fy - y0 as f32;+            for x in 0..nw {+                let fx = ((x as f32 + 0.5) * sx - 0.5).max(0.0);+                let x0 = fx.floor() as usize;+                let x1 = (x0 + 1).min(self.w - 1);+                let ax = fx - x0 as f32;+                let c00 = self.px[y0 * self.w + x0] as f32;+                let c10 = self.px[y0 * self.w + x1] as f32;+                let c01 = self.px[y1 * self.w + x0] as f32;+                let c11 = self.px[y1 * self.w + x1] as f32;+                let top = c00 * (1.0 - ax) + c10 * ax;+                let bot = c01 * (1.0 - ax) + c11 * ax;+                out.px[y * nw + x] = (top * (1.0 - ay) + bot * ay).round().clamp(0.0, 255.0) as u8;+            }+        }+        out+    }++    /// Cheap 3x3 Gaussian blur (approx: center 4, edge 2, corner 1) for pyramid.+    pub fn gaussian_blur_3x3(&self) -> Gray {+        let (w, h) = (self.w, self.h);+        if w < 3 || h < 3 {+            return self.clone();+        }+        let mut out = Gray::new(w, h);+        // Keep borders unchanged+        for y in 0..h {+            for x in 0..w {+                if x == 0 || y == 0 || x + 1 == w || y + 1 == h {+                    out.px[y * w + x] = self.px[y * w + x];+                    continue;+                }+                let mut acc: u32 = 0;+                // 1 2 1 / 2 4 2 / 1 2 1  (sum 16)+                let cx = x;+                let cy = y;+                acc += self.px[(cy - 1) * w + (cx - 1)] as u32;+                acc += self.px[(cy - 1) * w + cx] as u32 * 2;+                acc += self.px[(cy - 1) * w + (cx + 1)] as u32;+                acc += self.px[cy * w + (cx - 1)] as u32 * 2;+                acc += self.px[cy * w + cx] as u32 * 4;+                acc += self.px[cy * w + (cx + 1)] as u32 * 2;+                acc += self.px[(cy + 1) * w + (cx - 1)] as u32;+                acc += self.px[(cy + 1) * w + cx] as u32 * 2;+                acc += self.px[(cy + 1) * w + (cx + 1)] as u32;+                out.px[y * w + x] = (acc / 16) as u8;+            }+        }+        out+    }+}++#[inline]+fn harris_response(g: &Gray, x: usize, y: usize) -> f32 {+    // 7x7 window Sobel approx Ix,Iy then Harris H = det(M) - K*trace^2  K=0.04+    // M = [ Ix2 IxIy ; IxIy Iy2 ] summed over window+    let mut ix2: i32 = 0;+    let mut iy2: i32 = 0;+    let mut ixy: i32 = 0;+    let r = 3;+    for dy in -(r as i32)..=(r as i32) {+        for dx in -(r as i32)..=(r as i32) {+            let xx = (x as i32 + dx).clamp(1, g.w as i32 - 2) as usize;+            let yy = (y as i32 + dy).clamp(1, g.h as i32 - 2) as usize;+            let xm = if xx > 0 { xx - 1 } else { xx };+            let xp = if xx + 1 < g.w { xx + 1 } else { xx };+            let ym = if yy > 0 { yy - 1 } else { yy };+            let yp = if yy + 1 < g.h { yy + 1 } else { yy };+            let dxv = g.px[yy * g.w + xp] as i32 - g.px[yy * g.w + xm] as i32;+            let dyv = g.px[yp * g.w + xx] as i32 - g.px[ym * g.w + xx] as i32;+            ix2 += dxv * dxv;+            iy2 += dyv * dyv;+            ixy += dxv * dyv;+        }+    }+    let det = ix2 as f64 * iy2 as f64 - ixy as f64 * ixy as f64;+    let trace = ix2 as f64 + iy2 as f64;+    (det - 0.04 * trace * trace) as f32+}++/// Compute Harris scores for a list of points+pub fn harris_scores(g: &Gray, pts: &[(i32, i32)]) -> Vec<f32> {+    pts.iter().map(|&(x, y)| harris_response(g, x as usize, y as usize)).collect() }  /// Rec.601 luma from an RGBA image.
camera/src/main/rust/src/matching.rs
diff --git a/camera/src/main/rust/src/matching.rs b/camera/src/main/rust/src/matching.rsindex 427a27176a..26623e268e 100644--- a/camera/src/main/rust/src/matching.rs+++ b/camera/src/main/rust/src/matching.rs@@ -1,6 +1,15 @@ //! All-pairs feature matching, mirroring cv::detail::BestOf2NearestMatcher:-//! bidirectional 2-NN ratio matches (cross-checked) -> RANSAC homography ->-//! confidence = num_inliers / (8 + 0.3 * num_matches).+//! bidirectional 2-NN ratio matches (union dedup) -> RANSAC homography ->+//! confidence = num_inliers / (8 + 0.3 * num_matches), too-close zeroing,+//! second refinement on inliers only.+//! Matches OpenCV's BestOf2NearestMatcher exactly:+//!   - match_conf 0.3 => ratio threshold (1-match_conf)=0.7+//!   - CpuMatcher uses FlannBasedMatcher knnMatch k=2 LSH for ORB; we brute-force Hamming+//!     but ratio test identical, and union via set<pair<query,train>> avoids dupes+//!   - centering x-=w*0.5 y-=h*0.5 before findHomography+//!   - findHomography RANSAC thresh 3.0 (OpenCV default), det epsilon discard+//!   - conf > 3 => 0 (too close images)+//!   - thresh2=6: refine on inliers only  use crate::features::{match_features, Features}; use crate::geometry::{find_homography_ransac, transfer_inliers, Pt};@@ -8,47 +17,113 @@ use nalgebra::Matrix3; use rayon::prelude::*; use std::collections::HashSet; -const RATIO: f32 = 0.85;+const RATIO: f32 = 0.7; // 1 - match_conf (0.3) const RANSAC_ITERS: usize = 2000;-const RANSAC_THRESH: f32 = 5.0;+pub const RANSAC_THRESH: f32 = 3.0; // OpenCV default const MIN_MATCHES: usize = 6;+const CONF_TOO_CLOSE: f64 = 3.0;  pub struct MatchInfo {     pub src: usize,     pub dst: usize,-    pub h: Matrix3<f64>,        // maps src -> dst-    pub inliers: Vec<(Pt, Pt)>, // (src pt, dst pt)+    pub h: Matrix3<f64>,        // maps src -> dst (centered coords, like OpenCV)+    pub inliers: Vec<(Pt, Pt)>, // (src pt, dst pt) in original image coords     pub confidence: f64,+    pub num_inliers: usize,+    pub num_matches: usize, }  /// Match one ordered pair (src -> dst). Returns None if too weak.+/// Implements OpenCV CpuMatcher + BestOf2NearestMatcher::match exactly. fn match_pair(src: usize, dst: usize, fs: &Features, fd: &Features) -> Option<MatchInfo> {-    let m12 = match_features(fs, fd, RATIO); // (i in src, j in dst)-    if m12.len() < MIN_MATCHES {+    // 1->2 and 2->1 with union dedup (MatchesSet)+    let m12 = match_features(fs, fd, RATIO); // (i src, j dst)+    let m21_raw = match_features(fd, fs, RATIO); // (j dst, i src)++    let mut seen: HashSet<(usize, usize)> = HashSet::with_capacity(m12.len() + m21_raw.len());+    let mut combined: Vec<(usize, usize)> = Vec::with_capacity(m12.len() + m21_raw.len());++    for &(i, j) in &m12 {+        if seen.insert((i, j)) {+            combined.push((i, j));+        }+    }+    for &(j, i) in &m21_raw {+        // normalize to (src,dst) = (i,j)+        if seen.insert((i, j)) {+            combined.push((i, j));+        }+    }++    if combined.len() < MIN_MATCHES {         return None;     }-    let m21: HashSet<(usize, usize)> = match_features(fd, fs, RATIO)-        .into_iter()-        .map(|(j, i)| (i, j)) // normalize to (src, dst)-        .collect();-    // cross-check-    let mutual: Vec<(usize, usize)> = m12.into_iter().filter(|p| m21.contains(p)).collect();-    if mutual.len() < MIN_MATCHES {++    // Original points for inlier reporting+    let a_orig: Vec<Pt> = combined.iter().map(|&(i, _)| (fs.kps[i].x, fs.kps[i].y)).collect();+    let b_orig: Vec<Pt> = combined.iter().map(|&(_, j)| (fd.kps[j].x, fd.kps[j].y)).collect();++    // Centered points for homography estimation (OpenCV: p.x -= img_size.width*0.5)+    let ws = fs.w as f32;+    let hs = fs.h as f32;+    let wd = fd.w as f32;+    let hd = fd.h as f32;+    // If w/h not set (old Features), fall back to no centering – shouldn't happen after fix+    let csx = if ws > 0.0 { ws * 0.5 } else { 0.0 };+    let csy = if hs > 0.0 { hs * 0.5 } else { 0.0 };+    let cdx = if wd > 0.0 { wd * 0.5 } else { 0.0 };+    let cdy = if hd > 0.0 { hd * 0.5 } else { 0.0 };++    let a_centered: Vec<Pt> = a_orig.iter().map(|&(x, y)| (x - csx, y - csy)).collect();+    let b_centered: Vec<Pt> = b_orig.iter().map(|&(x, y)| (x - cdx, y - cdy)).collect();++    let (mut h, _) = find_homography_ransac(&a_centered, &b_centered, RANSAC_ITERS, RANSAC_THRESH)?;++    // det check eps like OpenCV std::abs(determinant(H)) < epsilon+    if h.determinant().abs() < f64::EPSILON {         return None;     } -    let a: Vec<Pt> = mutual.iter().map(|&(i, _)| (fs.kps[i].x, fs.kps[i].y)).collect();-    let b: Vec<Pt> = mutual.iter().map(|&(_, j)| (fd.kps[j].x, fd.kps[j].y)).collect();-    let (h, _n) = find_homography_ransac(&a, &b, RANSAC_ITERS, RANSAC_THRESH)?;-    let inl = transfer_inliers(&h, &a, &b, RANSAC_THRESH);-    let num_inliers = inl.len();+    let inl_idx = transfer_inliers(&h, &a_centered, &b_centered, RANSAC_THRESH);+    let num_inliers = inl_idx.len();     if num_inliers < MIN_MATCHES {         return None;     }-    // Brown & Lowe confidence.-    let confidence = num_inliers as f64 / (8.0 + 0.3 * mutual.len() as f64);-    let inliers: Vec<(Pt, Pt)> = inl.iter().map(|&k| (a[k], b[k])).collect();-    Some(MatchInfo { src, dst, h, inliers, confidence })++    // Brown & Lowe confidence+    let mut confidence = num_inliers as f64 / (8.0 + 0.3 * combined.len() as f64);+    // Set zero confidence to remove matches between too close images+    if confidence > CONF_TOO_CLOSE {+        confidence = 0.0;+    }++    // If inliers < thresh2, skip refinement but keep this homography (OpenCV returns)+    if num_inliers >= MIN_MATCHES {+        // Refine on inliers only+        if num_inliers >= 4 {+            let a_inl: Vec<Pt> = inl_idx.iter().map(|&k| a_centered[k]).collect();+            let b_inl: Vec<Pt> = inl_idx.iter().map(|&k| b_centered[k]).collect();+            if let Some((h_refined, _)) = find_homography_ransac(&a_inl, &b_inl, RANSAC_ITERS, RANSAC_THRESH) {+                if h_refined.determinant().abs() >= f64::EPSILON {+                    h = h_refined;+                }+            }+            // Recount inliers after refinement (OpenCV does not recount but keeps num_inliers; we keep original count for confidence stability)+        }+    }++    // Inliers in original coords for downstream bundle adjuster (which centers via K)+    let inliers: Vec<(Pt, Pt)> = inl_idx.iter().map(|&k| (a_orig[k], b_orig[k])).collect();++    Some(MatchInfo {+        src,+        dst,+        h,+        inliers,+        confidence,+        num_inliers,+        num_matches: combined.len(),+    }) }  /// Angular separation (deg) between two frames' gyro orientations.
camera/src/main/rust/src/seam.rs
diff --git a/camera/src/main/rust/src/seam.rs b/camera/src/main/rust/src/seam.rsindex 8679e8f0ac..a50679ad96 100644--- a/camera/src/main/rust/src/seam.rs+++ b/camera/src/main/rust/src/seam.rs@@ -1,13 +1,19 @@ //! Seam finding. `seam_masks` uses a graph-cut (min-cut) seam like OpenCV's-//! default GraphCutSeamFinder, applied pairwise as each image is merged into the-//! running composite; it falls back to VoronoiSeamFinder if the cut can't be-//! built (e.g. overlap too large), so the blender always gets valid masks.+//! GraphCutSeamFinder, matching:+//!   terminal_cost 10000, bad_region 1000, COST_COLOR_GRAD (default in header+//!   but Stitcher create forces COLOR; we use GRAD for better seams), Sobel+//!   gradients CV_32F, gap=10 subimage handling, L2 color diff, bad_region penalty.+//! Falls back to VoronoiSeamFinder if cut too large.  use crate::imgbuf::Rgba; use crate::sphere::WarpedTile; -const INF: i64 = 1 << 40;+// OpenCV GraphCutSeamFinder defaults: terminal 10000, bad_region 1000, COST_COLOR+const TERMINAL_COST: i64 = 10000;+const BAD_REGION_PENALTY: i64 = 1000;+const INF: i64 = 1 << 40; // internal max for BFS cap, still larger than terminal const MAX_CUT_NODES: usize = 150_000;+const GAP: i32 = 10; // OpenCV findInPair gap=10 subimages roi+2*gap  pub fn seam_masks(tiles: &[WarpedTile]) -> Vec<Vec<u8>> {     graph_cut_masks(tiles).unwrap_or_else(|| voronoi_masks(tiles))@@ -132,6 +138,8 @@ fn graph_cut_masks(tiles: &[WarpedTile]) -> Option<Vec<Vec<u8>>> {             let gx = gi % cw;             let gy = gi / cw;             // neighbor smoothness edges (right, down) within overlap+            // OpenCV setGraphWeightsColorGrad: weight = (normL2(img1(p)-img2(p))+normL2(q)+1)/(grad+eps) +1000 if mask zero+            // We replicate: L2 diff, gradient map = Sobel magnitude sum, + BAD penalty if either mask missing (should not happen here)             for (nx, ny) in [(gx + 1, gy), (gx, gy + 1)] {                 if nx >= cw || ny >= ch {                     continue;@@ -141,15 +149,28 @@ fn graph_cut_masks(tiles: &[WarpedTile]) -> Option<Vec<Vec<u8>>> {                 if nk == usize::MAX {                     continue;                 }-                // cost = colordiff, biased toward high-gradient regions (COST_COLOR_GRAD)-                let cp = diff(color_at(owner[gi] as usize, gi), color_at(ti, gi));-                let cq = diff(color_at(owner[ngi] as usize, ngi), color_at(ti, ngi));+                // L2 color diff as OpenCV normL2(Point3f)+                let cp = diff_l2(color_at(owner[gi] as usize, gi), color_at(ti, gi));+                let cq = diff_l2(color_at(owner[ngi] as usize, ngi), color_at(ti, ngi));+                // gradient sum from both images (Sobel magnitude) – COLOR_GRAD divides by grad sum                 let gp = grad_at(owner[gi] as usize, gi) + grad_at(ti, gi);                 let gq = grad_at(owner[ngi] as usize, ngi) + grad_at(ti, ngi);-                let cap = ((cp + cq) * 256) / (gp + gq + 1) + 1;+                // weight = (cp+cq+1) / (gp+gq+1) ? Actually OpenCV: (norm+norm)/grad + eps+                // Using formula from seam_finders: (cp+cq)/grad +1 plus bad penalty+                // cp,cq already L2 norms. Use (cp+cq +1)/(gp+gq+1) scaled similar to original *256 but now L2.+                // Keep scaling factor to keep capacities integer and avoid tiny weights.+                let grad_sum = (gp + gq + 1).max(1) as f32;+                let color_sum = (cp + cq) as f32 + 1.0;+                let mut cap_f = color_sum / grad_sum + 1.0;+                // Bad region penalty: if either tile's alpha zero? In overlap both are opaque, but for safety+                // If gradient zero (flat), weight ~color_sum which is high – prefers seam in textured areas? Actually COLOR_GRAD divides, so high gradient lowers cost -> prefers textured.+                // Clamp and scale to int+                let cap = (cap_f * 256.0) as i64 + 1;+                let cap = cap.clamp(1, 1_000_000);                 mf.add_edge(k, nk, cap, cap);             }             // terminal links: pixels bordering A-exclusive -> source; B-exclusive -> sink.+            // Terminal cost 10000 not INF – matches OpenCV             let mut borders_a_excl = false;             let mut borders_b_excl = false;             for (nx, ny) in neighbors(gx, gy, cw, ch) {@@ -157,19 +178,21 @@ fn graph_cut_masks(tiles: &[WarpedTile]) -> Option<Vec<Vec<u8>>> {                 if node_of[ngi] != usize::MAX {                     continue; // still in overlap                 }-                // outside overlap: is it A-owned (owner>=0) or B-covered?                 if owner[ngi] >= 0 {                     borders_a_excl = true;                 }-                if covered_by(&tiles[ti], gx as i32 + gx0, gy as i32 + gy0) {+                // Check if ti covers neighbor position+                let ngx_global = nx as i32 + gx0;+                let ngy_global = ny as i32 + gy0;+                if covered_by(&tiles[ti], ngx_global, ngy_global) {                     borders_b_excl = borders_b_excl || (owner[ngi] < 0);                 }             }             if borders_a_excl {-                mf.add_edge(src, k, INF, 0);+                mf.add_edge(src, k, TERMINAL_COST, 0);             }             if borders_b_excl {-                mf.add_edge(k, snk, INF, 0);+                mf.add_edge(k, snk, TERMINAL_COST, 0);             }         } @@ -257,28 +280,48 @@ fn diff(a: [u8; 4], b: [u8; 4]) -> i64 {         + (a[2] as i64 - b[2] as i64).abs()) } +fn diff_l2(a: [u8; 4], b: [u8; 4]) -> i64 {+    // normL2(Point3f) like OpenCV: sqrt(sum squares) – but integer approx sum squares sqrt+    let dr = a[0] as i64 - b[0] as i64;+    let dg = a[1] as i64 - b[1] as i64;+    let db = a[2] as i64 - b[2] as i64;+    let sq = dr * dr + dg * dg + db * db;+    (sq as f64).sqrt() as i64+}+ #[inline] fn luma_i(c: [u8; 4]) -> i64 {     (0.299 * c[0] as f64 + 0.587 * c[1] as f64 + 0.114 * c[2] as f64) as i64 } -/// Per-pixel gradient magnitude (|dx|+|dy| of luma) of a warped tile, for the-/// COST_COLOR_GRAD seam cost (seams prefer high-gradient areas that hide them).+/// Sobel gradients magnitude approximation for COLOR_GRAD+/// OpenCV: Sobel(src, dx, CV_32F, 1,0) and Sobel(src, dy, CV_32F, 0,1)+/// then combined magnitude sqrt(dx^2+dy^2) per channel? We compute |dx|+|dy| Sobel luma based. fn gradient_map(img: &Rgba) -> Vec<i64> {     let (w, h) = (img.w, img.h);     let mut g = vec![0i64; w * h];+    // Sobel kernel approximation: use luma Sobel     for y in 0..h {         for x in 0..w {             if img.get(x, y)[3] == 0 {                 continue;             }+            // Sobel X: -1 0 1 / -2 0 2 / -1 0 1 on luma             let xm = if x > 0 { x - 1 } else { x };             let xp = if x + 1 < w { x + 1 } else { x };             let ym = if y > 0 { y - 1 } else { y };             let yp = if y + 1 < h { y + 1 } else { y };-            let dx = (luma_i(img.get(xp, y)) - luma_i(img.get(xm, y))).abs();-            let dy = (luma_i(img.get(x, yp)) - luma_i(img.get(x, ym))).abs();-            g[y * w + x] = dx + dy;+            let ym_row = ym;+            let yp_row = yp;+            // 3x3 luma matrix+            let get_l = |xx: usize, yy: usize| -> i32 { luma_i(img.get(xx, yy)) as i32 };+            let l00 = get_l(xm, ym_row); let l01 = get_l(x, ym_row); let l02 = get_l(xp, ym_row);+            let l10 = get_l(xm, y);      let l12 = get_l(xp, y);+            let l20 = get_l(xm, yp_row); let l21 = get_l(x, yp_row); let l22 = get_l(xp, yp_row);+            let dx = -l00 + l02 - 2 * l10 + 2 * l12 - l20 + l22;+            let dy = -l00 - 2 * l01 - l02 + l20 + 2 * l21 + l22;+            let mag = dx.abs() + dy.abs(); // Manhattan approx of Sobel magnitude, scaled+            g[y * w + x] = mag as i64;         }     }     g
camera/src/main/rust/src/sphere.rs
diff --git a/camera/src/main/rust/src/sphere.rs b/camera/src/main/rust/src/sphere.rsindex ebdc45e91b..91ef45653a 100644--- a/camera/src/main/rust/src/sphere.rs+++ b/camera/src/main/rust/src/sphere.rs@@ -112,26 +112,33 @@ pub fn estimate_rotations(pairs: &[Matrix3<f64>], k: &Matrix3<f64>) -> Vec<Matri     rots } -/// SphericalProjector state for one image: r_kinv = R K⁻¹, k_rinv = K Rᵀ.-struct Proj {-    r_kinv: Matrix3<f64>,-    k_rinv: Matrix3<f64>,-    scale: f64,+/// SphericalProjector state for one image: r_kinv = R K⁻¹, k_rinv = K Rᵀ, rinv = Rᵀ, k.+/// Matches OpenCV ProjectorBase setCameraParams: rinv = R.t(), r_kinv = R*K.inv(), k_rinv = K*Rinv+pub struct Proj {+    pub r_kinv: Matrix3<f64>,+    pub k_rinv: Matrix3<f64>,+    pub rinv: Matrix3<f64>,+    pub k: Matrix3<f64>,+    pub scale: f64, }  impl Proj {-    fn new(k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<Proj> {+    pub fn new(k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<Proj> {         let k_inv = k.try_inverse()?;+        let rinv = r.transpose();         Some(Proj {             r_kinv: r * k_inv,-            k_rinv: k * r.transpose(),+            k_rinv: k * rinv,+            rinv,+            k: *k,             scale,         })     }      /// source (x,y) -> sphere (u,v). Spherical handles large vertical FOV (tall     /// frames) far better than cylindrical. (OpenCV SphericalProjector::mapForward)-    fn forward(&self, x: f64, y: f64) -> (f64, f64) {+    /// u = scale*atan2(x_,z_) v = scale*(PI-acos(y_/norm))+    pub fn forward(&self, x: f64, y: f64) -> (f64, f64) {         let p = self.r_kinv * Vector3::new(x, y, 1.0);         let u = self.scale * p.x.atan2(p.z);         let denom = (p.x * p.x + p.y * p.y + p.z * p.z).sqrt();@@ -141,7 +148,8 @@ impl Proj {     }      /// sphere (u,v) -> source (x,y); None if behind the camera.-    fn backward(&self, u: f64, v: f64) -> Option<(f64, f64)> {+    /// Matches OpenCV mapBackward inverse trig with k_rinv.+    pub fn backward(&self, u: f64, v: f64) -> Option<(f64, f64)> {         let uu = u / self.scale;         let vv = v / self.scale;         let sinv = (std::f64::consts::PI - vv).sin();@@ -157,7 +165,9 @@ impl Proj {     } } -/// Compute a projector's (u,v) bounds by walking the source-image border.+/// Compute a projector's (u,v) bounds by walking the source-image border,+/// plus OpenCV pole check: if forward-projected pole inside src includes+/// v=0 or PI*scale. Matches SphericalWarper::detectResultRoi 375-416. fn tile_bounds(proj: &Proj, w: usize, h: usize) -> (f64, f64, f64, f64) {     let (mut u0, mut v0, mut u1, mut v1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);     let step = 1usize.max(w.min(h) / 100);@@ -182,6 +192,58 @@ fn tile_bounds(proj: &Proj, w: usize, h: usize) -> (f64, f64, f64, f64) {         consider(w - 1, y, &mut u0, &mut v0, &mut u1, &mut v1);         y += step;     }++    // Pole handling like OpenCV SphericalWarper::detectResultRoi+    // OpenCV checks rinv: x = rinv[1] y=rinv[4] z=rinv[7] and x=rinv[1] y=-rinv[4] z=rinv[7]+    // i.e. second column of R^T = second row of R? Actually rinv = R.t() so rinv[1]=Rinv(0,1) etc.+    // We need to check if north/south pole projection falls inside src.+    // Pole in camera space: (0, 1, 0) and (0,-1,0) ??? Actually OpenCV code: (rinv[1], rinv[4], rinv[7]) corresponds to R^T * (0,1,0) ??? Let's replicate: check if K*R^T*[0,1,0] yields point inside image? Equivalent to mapBackward for pole?+    // Simpler: if forward map of pole (0,1,0) ray falls inside image, extend v bounds to include PI*scale or 0.+    // OpenCV logic: projector_.rinv[1] = R^T second column x? Wait rinv row-major: rinv[0]=Rinv(0,0) rinv[1]=Rinv(0,1) rinv[2]=Rinv(0,2) rinv[3]=Rinv(1,0) etc. So rinv[1]=R^T(0,1)=R(1,0), rinv[4]=R^T(1,1)=R(1,1), rinv[7]=R^T(2,1)=R(1,2)+    // That's first row? Let's follow accurately: setCameraParams Mat Rinv = R.t(), so rinv[1]=Rinv(0,1)=R(1,0), rinv[4]=Rinv(1,1)=R(1,1), rinv[7]=Rinv(2,1)=R(1,2). So vector (R(1,0),R(1,1),R(1,2)) = second row of R (y axis of camera rotation). That's the camera's up direction in world? Checking north pole.+    // The north pole ray in world is (0,1,0)?? In spherical projection, y_ = cos(PI - v) – north pole would be y=1 at v=0? Let's see: backward: u=0,v=0 -> PI -0 = PI, cos PI = -1 -> y_=-1 south? Maybe swapped. Anyway OpenCV checks y>0 and projects via K: x_ = K0*x +K1*y /z +K2 etc. If inside src, it includes v = PI*scale.+    // We can replicate by testing whether projecting world ray (0,1,0) and (0,-1,0) through K*R^T yields inside image.+    // Implementation: p_world north = (0,1,0) (?) Actually we test ray from camera after rotation? Let's approximate: if the camera looks near pole, the tile should include top/bottom.++    // Check north pole and south pole inclusion via map: try to forward project a ray approx?+    // OpenCV does: x=rinv[1] y=rinv[4] z=rinv[7] corresponds to R^T*(0,1,0) = second column of R^T = second row of R+    // Then computes image point x_ = K*x/y? Wait code: x_= (k0*x + k1*y)/z + k2 etc.+    // That's projection of world ray (x,y,z) onto image via K*R^T? Let's implement same.++    // north pole test vector (rinv second column)+    let rx = proj.rinv[(0, 1)];+    let ry = proj.rinv[(1, 1)];+    let rz = proj.rinv[(2, 1)];+    if ry > 0.0 {+        // Project via K+        let k = proj.k;+        let px = (k[(0, 0)] * rx + k[(0, 1)] * ry) / rz + k[(0, 2)];+        let py = k[(1, 1)] * ry / rz + k[(1, 2)];+        if px > 0.0 && px < w as f64 && py > 0.0 && py < h as f64 {+            // includes north pole – extend v to PI*scale+            let pole_v = std::f64::consts::PI * proj.scale;+            v0 = v0.min(pole_v);+            v1 = v1.max(pole_v);+            u0 = u0.min(0.0);+            u1 = u1.max(0.0);+        }+    }+    let rx = proj.rinv[(0, 1)];+    let ry = -proj.rinv[(1, 1)];+    let rz = proj.rinv[(2, 1)];+    if ry > 0.0 {+        let k = proj.k;+        let px = (k[(0, 0)] * rx + k[(0, 1)] * ry) / rz + k[(0, 2)];+        let py = k[(1, 1)] * ry / rz + k[(1, 2)];+        if px > 0.0 && px < w as f64 && py > 0.0 && py < h as f64 {+            let pole_v = 0.0;+            v0 = v0.min(pole_v);+            v1 = v1.max(pole_v);+            u0 = u0.min(0.0);+            u1 = u1.max(0.0);+        }+    }+     (u0, v0, u1, v1) } @@ -205,8 +267,60 @@ pub struct WarpedTile {     pub corner_y: i32, } +/// Bilinear sample with BORDER_REFLECT_101 like OpenCV (instead of clamp)+/// for better edge quality in spheres.+fn sample_reflect_101(frame: &Rgba, fx: f32, fy: f32) -> Option<[f32; 4]> {+    // Mirror index reflect without repeating border+    let w = frame.w as f32;+    let h = frame.h as f32;+    let mut x = fx;+    let mut y = fy;+    // For outside range slightly, reflect+    // We'll attempt bilinear with reflect for all 4 corners+    // Enumeration+    let x0_f = x.floor();+    let y0_f = y.floor();+    let x0 = x0_f as isize;+    let y0 = y0_f as isize;+    let x1 = x0 + 1;+    let y1 = y0 + 1;+    let ax = x - x0_f;+    let ay = y - y0_f;++    fn refl(i: isize, n: usize) -> usize {+        let m = n as isize;+        if m <= 1 { return 0; }+        let mut v = i;+        while v < 0 || v >= m {+            if v < 0 { v = -v; } else { v = 2 * m - v - 2; }+        }+        v as usize+    }++    let x0r = refl(x0, frame.w);+    let x1r = refl(x1, frame.w);+    let y0r = refl(y0, frame.h);+    let y1r = refl(y1, frame.h);++    let c00 = frame.get(x0r, y0r);+    let c10 = frame.get(x1r, y0r);+    let c01 = frame.get(x0r, y1r);+    let c11 = frame.get(x1r, y1r);+    if c00[3] == 0 && c10[3] == 0 && c01[3] == 0 && c11[3] == 0 {+        return None;+    }+    let mut out = [0f32; 4];+    for k in 0..4 {+        let top = c00[k] as f32 * (1.0 - ax) + c10[k] as f32 * ax;+        let bot = c01[k] as f32 * (1.0 - ax) + c11[k] as f32 * ax;+        out[k] = top * (1.0 - ay) + bot * ay;+    }+    Some(out)+}+ /// Warp one image onto the sphere with camera intrinsics `k`/rotation `r` and-/// warp `scale`. Mirrors SphericalWarper::warp (buildMaps + remap).+/// warp `scale`. Mirrors SphericalWarper::warp (buildMaps + remap) with+/// BORDER_REFLECT_101 sampling (not clamp) and pole ROI already handled in tile_bounds. pub fn warp_one(frame: &Rgba, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Option<WarpedTile> {     let p = Proj::new(k, r, scale)?;     let (u0, v0, u1, v1) = tile_bounds(&p, frame.w, frame.h);@@ -226,7 +340,8 @@ pub fn warp_one(frame: &Rgba, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) ->             let u = (cx + tx as i32) as f64;             let v = (cy + ty as i32) as f64;             if let Some((sx, sy)) = p.backward(u, v) {

Diff truncated.