Modern Apps git

← Modern-Apps.git

camera: panorama improvements

Commit
bd71bc80d8df67af658ccf1391d3b94eaad12fb9
Author
Vayun Mathur <[email protected]>
When
2026-07-20 02:38 UTC (4 months ago)
Parents
d0a9d24

Diff

camera/rust/src/blend.rs
diff --git a/camera/rust/src/blend.rs b/camera/rust/src/blend.rsindex 22ad227ff7..cb47922c6b 100644--- a/camera/rust/src/blend.rs+++ b/camera/rust/src/blend.rs@@ -1,57 +1,62 @@-//! Compositing blender. Uses a FeatherBlender (distance-weighted average of the-//! actual warped pixels). Because the result is a convex combination of input-//! pixel values, it can never overshoot the valid range — unlike a Laplacian-//! multi-band pyramid, which rings and clips to white at seams in smooth regions.-//! After blending, the panorama is cropped to the maximal all-opaque rectangle so-//! there are no black borders.+//! 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.  use crate::imgbuf::Rgba; use crate::sphere::WarpedTile; -/// Manhattan distance (in pixels) from each covered pixel to the nearest-/// uncovered pixel — used as the feather weight (large in the interior, small at-/// the coverage edge, so seams blend smoothly). Two-pass chamfer transform.-fn coverage_distance(img: &Rgba) -> Vec<f32> {-    let (w, h) = (img.w, img.h);-    let big = (w + h) as i32;-    let mut d = vec![0i32; w * h];-    for i in 0..w * h {-        d[i] = if img.px[i * 4 + 3] != 0 { big } else { 0 };+/// Separable box blur of a float plane (running-sum, radius r).+fn box_blur(src: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {+    if r == 0 {+        return src.to_vec();     }-    // forward+    let mut tmp = vec![0f32; w * h];+    let norm = 1.0 / (2 * r + 1) as f32;+    // horizontal     for y in 0..h {+        let row = y * w;+        let mut sum = 0.0;+        for x in 0..=r.min(w - 1) {+            sum += src[row + x];+        }         for x in 0..w {-            let i = y * w + x;-            if d[i] == 0 {-                continue;-            }-            if x > 0 {-                d[i] = d[i].min(d[i - 1] + 1);+            tmp[row + x] = sum * norm;+            let add = x + r + 1;+            let sub = x as isize - r as isize;+            if add < w {+                sum += src[row + add];             }-            if y > 0 {-                d[i] = d[i].min(d[i - w] + 1);+            if sub >= 0 {+                sum -= src[row + sub as usize];             }         }     }-    // backward-    for y in (0..h).rev() {-        for x in (0..w).rev() {-            let i = y * w + x;-            if d[i] == 0 {-                continue;-            }-            if x + 1 < w {-                d[i] = d[i].min(d[i + 1] + 1);+    let mut out = vec![0f32; w * h];+    // vertical+    for x in 0..w {+        let mut sum = 0.0;+        for y in 0..=r.min(h - 1) {+            sum += tmp[y * w + x];+        }+        for y in 0..h {+            out[y * w + x] = sum * norm;+            let add = y + r + 1;+            let sub = y as isize - r as isize;+            if add < h {+                sum += tmp[add * w + x];             }-            if y + 1 < h {-                d[i] = d[i].min(d[i + w] + 1);+            if sub >= 0 {+                sum -= tmp[sub as usize * w + x];             }         }     }-    d.iter().map(|&v| v as f32).collect()+    out } -pub fn multiband_blend(tiles: &[WarpedTile], _masks: &[Vec<u8>], gain_maps: &[Vec<f32>]) -> Option<Rgba> {+pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>]) -> Option<Rgba> {     let num = tiles.len();     if num == 0 {         return None;@@ -78,18 +83,24 @@ pub fn multiband_blend(tiles: &[WarpedTile], _masks: &[Vec<u8>], gain_maps: &[Ve     for ti in 0..num {         let t = &tiles[ti];         let gmap = &gain_maps[ti];-        let dist = coverage_distance(&t.img);-        for ly in 0..t.img.h {-            for lx in 0..t.img.w {-                let li = ly * t.img.w + lx;+        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);+        for ly in 0..th {+            for lx in 0..tw {+                let li = ly * tw + lx;                 let c = t.img.get(lx, ly);                 if c[3] == 0 {+                    continue; // frame doesn't cover here+                }+                let weight = feather[li];+                if weight <= 0.0 {                     continue;                 }-                // feather weight: distance from the coverage edge (+1 so edge-                // pixels still contribute), squared for a sharper interior bias.-                let dw = dist[li] + 1.0;-                let weight = dw * dw;                 let gain = gmap[li];                 let gxp = (t.corner_x - gx0) as usize + lx;                 let gyp = (t.corner_y - gy0) as usize + ly;@@ -102,6 +113,31 @@ pub fn multiband_blend(tiles: &[WarpedTile], _masks: &[Vec<u8>], gain_maps: &[Ve         }     } +    // 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];+        for ly in 0..t.img.h {+            for lx in 0..t.img.w {+                let c = t.img.get(lx, ly);+                if c[3] == 0 {+                    continue;+                }+                let gxp = (t.corner_x - gx0) as usize + lx;+                let gyp = (t.corner_y - gy0) as usize + ly;+                let idx = gyp * cw + gxp;+                if accw[idx] <= 0.0 {+                    let gain = gmap[ly * t.img.w + lx];+                    acc[idx * 3] = (c[0] as f32 * gain).min(255.0);+                    acc[idx * 3 + 1] = (c[1] as f32 * gain).min(255.0);+                    acc[idx * 3 + 2] = (c[2] as f32 * gain).min(255.0);+                    accw[idx] = 1.0;+                }+            }+        }+    }+     let mut out = Rgba::new(cw, ch);     for i in 0..cw * ch {         let w = accw[i];
camera/rust/src/imgbuf.rs
diff --git a/camera/rust/src/imgbuf.rs b/camera/rust/src/imgbuf.rsindex c854679c58..20bed0c003 100644--- a/camera/rust/src/imgbuf.rs+++ b/camera/rust/src/imgbuf.rs@@ -20,6 +20,13 @@ impl Rgba {         Rgba { w, h, px }     } +    /// Decode JPEG/PNG bytes into an RGBA buffer.+    pub fn from_jpeg(bytes: &[u8]) -> Option<Rgba> {+        let img = image::load_from_memory(bytes).ok()?.to_rgba8();+        let (w, h) = img.dimensions();+        Some(Rgba::from_bytes(w as usize, h as usize, img.into_raw()))+    }+     #[inline]     pub fn get(&self, x: usize, y: usize) -> [u8; 4] {         let i = (y * self.w + x) * 4;
camera/rust/src/lib.rs
diff --git a/camera/rust/src/lib.rs b/camera/rust/src/lib.rsindex 8c5e4b5996..f750fa46df 100644--- a/camera/rust/src/lib.rs+++ b/camera/rust/src/lib.rs@@ -23,7 +23,7 @@ use std::sync::{Mutex, OnceLock};  struct Session {     sphere: bool,-    frames: Vec<Rgba>,+    frames: Vec<Vec<u8>>, // JPEG-compressed frames (decoded on demand at stitch time)     yaw: Vec<f32>,     pitch: Vec<f32>, }@@ -71,23 +71,52 @@ fn do_stitch(s: &mut Session) -> Option<Vec<u8>> {  fn do_merge(s: &mut Session) -> Option<Vec<u8>> {     let frames = std::mem::take(&mut s.frames);-    let result = night::align_and_merge(&frames)?;+    // Decode the JPEG burst to RGBA for alignment + merge.+    let decoded: Vec<Rgba> = frames.iter().filter_map(|j| Rgba::from_jpeg(j)).collect();+    let result = night::align_and_merge(&decoded)?;     encode_jpeg(&result, 95) } +/// Serialize an [`stitch::Estimate`] to a compact little-endian blob for the+/// Kotlin GPU compositor. Layout:+///   header: canvas_w u32, canvas_h u32, u0 f64, v0 f64, scale f64, count u32+///   per cam: original_index u32, focal f64, ppx f64, ppy f64, R[9] f64+///            (row-major), gain f32+fn serialize_estimate(est: &stitch::Estimate) -> Vec<u8> {+    let mut out = Vec::with_capacity(32 + est.cams.len() * (4 + 8 * 12 + 4));+    out.extend_from_slice(&est.canvas_w.to_le_bytes());+    out.extend_from_slice(&est.canvas_h.to_le_bytes());+    out.extend_from_slice(&est.u0.to_le_bytes());+    out.extend_from_slice(&est.v0.to_le_bytes());+    out.extend_from_slice(&est.scale.to_le_bytes());+    out.extend_from_slice(&(est.cams.len() as u32).to_le_bytes());+    for c in &est.cams {+        out.extend_from_slice(&(c.original_index as u32).to_le_bytes());+        out.extend_from_slice(&c.focal.to_le_bytes());+        out.extend_from_slice(&c.ppx.to_le_bytes());+        out.extend_from_slice(&c.ppy.to_le_bytes());+        for v in &c.r {+            out.extend_from_slice(&v.to_le_bytes());+        }+        out.extend_from_slice(&c.gain.to_le_bytes());+    }+    out+}++// Registration-only path for the GPU compositor. Borrows the session (does not+// consume its frames) so a CPU-stitch fallback can still run if the GPU fails.+fn do_estimate(s: &Session) -> Option<Vec<u8>> {+    let est = stitch::estimate_pano(&s.frames, &s.yaw, &s.pitch)?;+    Some(serialize_estimate(&est))+}+ #[cfg(test)] mod tests {     use super::*;     use crate::imgbuf::Rgba; -    fn load(path: &str) -> Rgba {-        let img = image::ImageReader::open(path)-            .expect("open image")-            .decode()-            .expect("decode image")-            .to_rgba8();-        let (w, h) = img.dimensions();-        Rgba::from_bytes(w as usize, h as usize, img.into_raw())+    fn load(path: &str) -> Vec<u8> {+        std::fs::read(path).expect("read image bytes")     }      /// Stitches the two sample photos from linrl3/Image-Stitching-OpenCV and@@ -97,7 +126,10 @@ mod tests {     fn stitch_two_samples() {         let a = load("testdata/q11.jpg");         let b = load("testdata/q22.jpg");-        let (aw, ah) = (a.w, a.h);+        let (aw, ah) = {+            let img = crate::imgbuf::Rgba::from_jpeg(&a).unwrap();+            (img.w, img.h)+        };         let t0 = std::time::Instant::now();         let out = crate::stitch::stitch_panorama(&[a, b], &[0.0, 0.0], &[0.0, 0.0])             .expect("stitch returned None");@@ -171,13 +203,55 @@ mod tests {         assert_eq!(border_black, 0, "black pixels on the border");         assert!(black_pct < 0.05, "too many black pixels: {:.3}%", black_pct);     }++    /// Registration-only path used by the GPU compositor: decode the estimate+    /// blob and assert it yields 2 cameras with finite intrinsics/rotation and a+    /// plausible canvas size. (GLES compositing itself needs an Android EGL+    /// context, so it can't run under host `cargo test`.)+    #[test]+    fn estimate_two_samples() {+        let a = load("testdata/q11.jpg");+        let b = load("testdata/q22.jpg");+        let est = crate::stitch::estimate_pano(&[a, b], &[0.0, 0.0], &[0.0, 0.0])+            .expect("estimate returned None");+        let blob = serialize_estimate(&est);++        // Header: canvas_w u32, canvas_h u32, u0 f64, v0 f64, scale f64, count u32.+        let u32_at = |o: usize| u32::from_le_bytes(blob[o..o + 4].try_into().unwrap());+        let f64_at = |o: usize| f64::from_le_bytes(blob[o..o + 8].try_into().unwrap());+        let canvas_w = u32_at(0);+        let canvas_h = u32_at(4);+        let scale = f64_at(24);+        let count = u32_at(32);+        assert_eq!(count, 2, "expected 2 cameras, got {count}");+        assert!(scale.is_finite() && scale > 1.0, "bad scale {scale}");+        assert!(+            canvas_w > 800 && canvas_h > 400 && (canvas_w as u64 * canvas_h as u64) < 12_000_000,+            "implausible canvas {canvas_w}x{canvas_h}"+        );++        // Per-cam records begin at offset 36; each is 4 + 8*12 + 4 = 104 bytes.+        let rec = 4 + 8 * 12 + 4;+        assert_eq!(blob.len(), 36 + count as usize * rec, "blob size mismatch");+        for i in 0..count as usize {+            let base = 36 + i * rec;+            let focal = f64_at(base + 4);+            assert!(focal.is_finite() && focal > 1.0, "bad focal {focal}");+            for j in 0..9 {+                let v = f64_at(base + 4 + 8 * (3 + j));+                assert!(v.is_finite(), "non-finite rotation entry");+            }+            let gain = f32::from_le_bytes(blob[base + 100..base + 104].try_into().unwrap());+            assert!(gain.is_finite() && gain >= 0.5 && gain <= 2.0, "bad gain {gain}");+        }+    } }  #[cfg(not(test))] mod jni_bindings {     use super::*;     use jni::objects::{JByteArray, JClass};-    use jni::sys::{jboolean, jbyteArray, jfloat, jint, jlong};+    use jni::sys::{jboolean, jbyteArray, jfloat, jlong};     use jni::JNIEnv;      #[no_mangle]@@ -199,23 +273,20 @@ mod jni_bindings {         env: JNIEnv<'l>,         _class: JClass<'l>,         handle: jlong,-        rgba: JByteArray<'l>,-        width: jint,-        height: jint,+        jpeg: JByteArray<'l>,         yaw: jfloat,         pitch: jfloat,         _roll: jfloat,     ) {-        let bytes = match env.convert_byte_array(&rgba) {+        let bytes = match env.convert_byte_array(&jpeg) {             Ok(b) => b,             Err(_) => return,         };-        let (w, h) = (width as usize, height as usize);-        if bytes.len() != w * h * 4 {+        if bytes.is_empty() {             return;         }         if let Some(s) = registry().lock().unwrap().get_mut(&(handle as i64)) {-            s.frames.push(Rgba::from_bytes(w, h, bytes));+            s.frames.push(bytes);             s.yaw.push(yaw);             s.pitch.push(pitch);         }@@ -239,6 +310,41 @@ mod jni_bindings {         run_and_return(env, handle, false)     } +    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_estimate<'l>(+        env: JNIEnv<'l>,+        _class: JClass<'l>,+        handle: jlong,+    ) -> jbyteArray {+        let null = std::ptr::null_mut();+        // Move the session data out so the (long) registration doesn't hold the+        // registry lock, then restore it afterwards so a CPU-stitch fallback can+        // still consume the same frames if the GPU path fails.+        let session = match registry().lock().unwrap().get_mut(&(handle as i64)) {+            Some(s) => Session {+                sphere: s.sphere,+                frames: std::mem::take(&mut s.frames),+                yaw: std::mem::take(&mut s.yaw),+                pitch: std::mem::take(&mut s.pitch),+            },+            None => return null,+        };+        let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| do_estimate(&session)))+            .unwrap_or(None);+        if let Some(s) = registry().lock().unwrap().get_mut(&(handle as i64)) {+            s.frames = session.frames;+            s.yaw = session.yaw;+            s.pitch = session.pitch;+        }+        match bytes {+            Some(b) => match env.byte_array_from_slice(&b) {+                Ok(arr) => arr.into_raw(),+                Err(_) => null,+            },+            None => null,+        }+    }+     #[no_mangle]     pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_free<'l>(         _env: JNIEnv<'l>,@@ -278,3 +384,4 @@ mod jni_bindings {         }     } }+
camera/rust/src/matching.rs
diff --git a/camera/rust/src/matching.rs b/camera/rust/src/matching.rsindex 0814d2b184..427a27176a 100644--- a/camera/rust/src/matching.rs+++ b/camera/rust/src/matching.rs@@ -51,16 +51,32 @@ fn match_pair(src: usize, dst: usize, fs: &Features, fd: &Features) -> Option<Ma     Some(MatchInfo { src, dst, h, inliers, confidence }) } -/// Match pairs (i<j). `window` limits pairs to |i-j| <= window (0 = all pairs);-/// for an ordered continuous sweep a small window is far cheaper and loses-/// nothing since only nearby frames overlap. Runs in parallel across pairs.-pub fn match_all(feats: &[Features], window: usize) -> Vec<MatchInfo> {+/// Angular separation (deg) between two frames' gyro orientations.+fn angular_dist(yaw: &[f32], pitch: &[f32], i: usize, j: usize) -> f32 {+    let mut dy = (yaw[i] - yaw[j]) % 360.0;+    if dy > 180.0 {+        dy -= 360.0;+    }+    if dy < -180.0 {+        dy += 360.0;+    }+    let dp = pitch[i] - pitch[j];+    (dy * dy + dp * dp).sqrt()+}++/// Match pairs (i<j). When per-frame gyro orientations are available, only pairs+/// within `max_angle` degrees are matched (they physically overlap) — this both+/// connects a 2D photo-sphere grid (horizontal AND vertical neighbours) and keeps+/// the pair count low. Falls back to all pairs otherwise. Runs in parallel.+pub fn match_all(feats: &[Features], yaw: &[f32], pitch: &[f32], max_angle: f32) -> Vec<MatchInfo> {     let n = feats.len();+    let use_angles = yaw.len() == n && pitch.len() == n && max_angle > 0.0;     let mut pairs: Vec<(usize, usize)> = Vec::new();     for i in 0..n {-        let jmax = if window == 0 { n } else { (i + window + 1).min(n) };-        for j in (i + 1)..jmax {-            pairs.push((i, j));+        for j in (i + 1)..n {+            if !use_angles || angular_dist(yaw, pitch, i, j) <= max_angle {+                pairs.push((i, j));+            }         }     }     pairs
camera/rust/src/seam.rs
diff --git a/camera/rust/src/seam.rs b/camera/rust/src/seam.rsindex aab30c05e3..8679e8f0ac 100644--- a/camera/rust/src/seam.rs+++ b/camera/rust/src/seam.rs@@ -7,7 +7,7 @@ use crate::imgbuf::Rgba; use crate::sphere::WarpedTile;  const INF: i64 = 1 << 40;-const MAX_CUT_NODES: usize = 900_000;+const MAX_CUT_NODES: usize = 150_000;  pub fn seam_masks(tiles: &[WarpedTile]) -> Vec<Vec<u8>> {     graph_cut_masks(tiles).unwrap_or_else(|| voronoi_masks(tiles))
camera/rust/src/stitch.rs
diff --git a/camera/rust/src/stitch.rs b/camera/rust/src/stitch.rsindex 2cd50ae1c9..4455309ee8 100644--- a/camera/rust/src/stitch.rs+++ b/camera/rust/src/stitch.rs@@ -14,16 +14,17 @@ use crate::imgbuf::{to_gray, Rgba}; use crate::matching::{biggest_component, match_all, MatchInfo}; use crate::seam::seam_masks; use crate::sphere::{warp_one, warped_bounds, WarpedTile};+use crate::warp::mean_luma; use crate::wave::wave_correct_horizontal; use rayon::prelude::*;  const MAX_FEATURES: usize = 3000; const FAST_THRESHOLD: i32 = 12; const CONF_THRESH: f64 = 1.0;-const MATCH_WINDOW: usize = 5; // match each frame only to ~5 neighbours (ordered sweep)+const MATCH_MAX_ANGLE: f32 = 55.0; // match frames within this gyro separation (deg) const REG_MEGAPIXELS: f64 = 0.6; // registration resolution (like OpenCV's registr_resol_)-const COMPOSE_MAX_PIXELS: f64 = 3_000_000.0; // cap output canvas area (bounds warp+blend cost/memory)-const SEAM_MAX_PIXELS: f64 = 400_000.0; // seam/exposure canvas area (OpenCV seam_est_resol_)+const COMPOSE_MAX_PIXELS: f64 = 8_000_000.0; // cap output canvas area (bounds warp+blend cost/memory)+const SEAM_MAX_PIXELS: f64 = 100_000.0; // seam/exposure canvas area (OpenCV seam_est_resol_ = 0.1 MP)  fn remap_matches(matches: Vec<MatchInfo>, kept: &[usize]) -> Vec<MatchInfo> {     let max = kept.iter().max().map(|m| m + 1).unwrap_or(0);@@ -62,36 +63,211 @@ fn median_focal(cams: &[CameraParams]) -> f64 {     } } -pub fn stitch_panorama(frames: &[Rgba], _yaw: &[f32], _pitch: &[f32]) -> Option<Rgba> {-    let n = frames.len();+/// One kept frame's camera solution for GPU compositing. `r` is the 3×3 rotation+/// serialized **row-major** (r[0..3] = row 0, etc.). Intrinsics are at full+/// capture resolution (aspect = 1, so K = [[focal,0,ppx],[0,focal,ppy],[0,0,1]]).+pub struct FrameCam {+    pub original_index: usize,+    pub focal: f64,+    pub ppx: f64,+    pub ppy: f64,+    pub r: [f64; 9],+    pub gain: f32,+}++/// Registration result for the GPU compositor: the global sphere canvas geometry+/// (in warp pixels) plus the per-kept-frame camera solutions. The compositor+/// warps each kept frame with `outputPx = (u - u0, v - v0)` onto a+/// `canvas_w × canvas_h` canvas using `scale`.+pub struct Estimate {+    pub canvas_w: u32,+    pub canvas_h: u32,+    pub u0: f64,+    pub v0: f64,+    pub scale: f64,+    pub cams: Vec<FrameCam>,+}++fn median_f32(vals: &[f32]) -> f32 {+    let mut v: Vec<f32> = vals.iter().copied().filter(|x| x.is_finite() && *x > 0.0).collect();+    if v.is_empty() {+        return 0.0;+    }+    v.sort_by(|a, b| a.total_cmp(b));+    let m = v.len() / 2;+    if v.len() % 2 == 1 {+        v[m]+    } else {+        (v[m - 1] + v[m]) / 2.0+    }+}++/// Registration-only path for the GPU compositor: runs the same low-res+/// features → matching → estimate → bundle-adjust → wave-correct stages as+/// [`stitch_panorama`], computes the compose canvas geometry, and returns+/// per-frame camera solutions + a cheap exposure gain — **without** running the+/// expensive per-pixel warp/seam/blend (those move to the GPU).+pub fn estimate_pano(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> Option<Estimate> {+    let n = frames_jpeg.len();+    if n < 2 {+        return None;+    }++    // Full-resolution frame dimensions (from the first frame).+    let (full_w, full_h) = {+        let f0 = Rgba::from_jpeg(&frames_jpeg[0])?;+        (f0.w, f0.h)+    };++    // Registration at ~0.6 MP; also capture each frame's mean luma (for the+    // cheap per-frame exposure gain) from the already-decoded low-res image.+    let reg_scale = (REG_MEGAPIXELS * 1e6 / (full_w as f64 * full_h as f64)).sqrt().min(1.0);+    let reg_w = ((full_w as f64 * reg_scale).round() as usize).max(1);+    let reg_h = ((full_h as f64 * reg_scale).round() as usize).max(1);+    let reg: Vec<(Features, f32)> = frames_jpeg+        .par_iter()+        .map(|j| {+            let full = Rgba::from_jpeg(j).unwrap_or_else(|| Rgba::new(1, 1));+            let small = if reg_scale < 0.999 { full.resized(reg_w, reg_h) } else { full };+            let luma = mean_luma(&small);+            (detect_and_describe(&to_gray(&small), MAX_FEATURES, FAST_THRESHOLD), luma)+        })+        .collect();+    let (feats, lumas): (Vec<Features>, Vec<f32>) = reg.into_iter().unzip();++    let matches = match_all(&feats, yaw, pitch, MATCH_MAX_ANGLE);+    if matches.is_empty() {+        return None;+    }+    let kept = biggest_component(n, &matches, CONF_THRESH);+    if kept.len() < 2 {+        return None;+    }+    let matches = remap_matches(matches, &kept);+    if matches.is_empty() {+        return None;+    }+    let m = kept.len();++    let mut cams = estimate_cameras(m, reg_w, reg_h, &matches);+    bundle_adjust(&mut cams, &matches);+    wave_correct_horizontal(&mut cams);++    // Rescale intrinsics from registration to full resolution.+    for c in cams.iter_mut() {+        c.focal /= reg_scale;+        c.ppx = full_w as f64 / 2.0;+        c.ppy = full_h as f64 / 2.0;+    }++    // Choose the compose scale (bounded so the canvas stays within memory), the+    // same way stitch_panorama does, so GPU and CPU paths size the canvas alike.+    let mut scale = median_focal(&cams);+    if !scale.is_finite() || scale <= 1.0 {+        return None;+    }+    let compose_area = {+        let mut gx0 = f64::MAX;+        let mut gy0 = f64::MAX;+        let mut gx1 = f64::MIN;+        let mut gy1 = f64::MIN;+        for c in cams.iter() {+            if let Some((u0, v0, u1, v1)) = warped_bounds(full_w, full_h, &c.k(), &c.r, scale) {+                gx0 = gx0.min(u0);+                gy0 = gy0.min(v0);+                gx1 = gx1.max(u1);+                gy1 = gy1.max(v1);+            }+        }+        (gx1 - gx0).max(1.0) * (gy1 - gy0).max(1.0)+    };+    if compose_area.is_finite() && compose_area > COMPOSE_MAX_PIXELS {+        scale *= (COMPOSE_MAX_PIXELS / compose_area).sqrt();+    }++    // Final global bounds at the committed scale -> canvas geometry.+    let (mut gx0, mut gy0, mut gx1, mut gy1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+    for c in cams.iter() {+        if let Some((u0, v0, u1, v1)) = warped_bounds(full_w, full_h, &c.k(), &c.r, scale) {+            gx0 = gx0.min(u0);+            gy0 = gy0.min(v0);+            gx1 = gx1.max(u1);+            gy1 = gy1.max(v1);+        }+    }+    if !gx0.is_finite() || !gy0.is_finite() || !gx1.is_finite() || !gy1.is_finite() {+        return None;+    }+    let canvas_w = ((gx1 - gx0).ceil() as i64 + 1).max(1);+    let canvas_h = ((gy1 - gy0).ceil() as i64 + 1).max(1);++    // Cheap per-frame exposure gain: pull each kept frame toward the median luma.+    let kept_lumas: Vec<f32> = kept.iter().map(|&i| lumas[i]).collect();+    let ref_luma = median_f32(&kept_lumas);+    let cams_out: Vec<FrameCam> = kept+        .iter()+        .zip(cams.iter())+        .map(|(&i, c)| {+            let luma = lumas[i];+            let gain = if ref_luma > 1.0 && luma > 1.0 { (ref_luma / luma).clamp(0.5, 2.0) } else { 1.0 };+            let r = c.r;+            FrameCam {+                original_index: i,+                focal: c.focal,+                ppx: c.ppx,+                ppy: c.ppy,+                r: [+                    r[(0, 0)], r[(0, 1)], r[(0, 2)],+                    r[(1, 0)], r[(1, 1)], r[(1, 2)],+                    r[(2, 0)], r[(2, 1)], r[(2, 2)],+                ],+                gain,+            }+        })+        .collect();++    Some(Estimate {+        canvas_w: canvas_w as u32,+        canvas_h: canvas_h as u32,+        u0: gx0,+        v0: gy0,+        scale,+        cams: cams_out,+    })+}++pub fn stitch_panorama(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> Option<Rgba> {+    let n = frames_jpeg.len();     if n == 0 {         return None;     }     if n == 1 {-        return Some(frames[0].clone());+        return Rgba::from_jpeg(&frames_jpeg[0]);     } -    let full_w = frames[0].w;-    let full_h = frames[0].h;+    // Full-resolution frame dimensions (from the first frame).+    let (full_w, full_h) = {+        let f0 = Rgba::from_jpeg(&frames_jpeg[0])?;+        (f0.w, f0.h)+    }; -    // --- registration resolution (downscale for the slow stages) ---+    // --- registration: decode each frame, downscale to ~0.6 MP, detect features.+    // Frames are decoded on demand and dropped, so max-res frames never all sit in+    // RAM as RGBA at once. ---     let reg_scale = (REG_MEGAPIXELS * 1e6 / (full_w as f64 * full_h as f64)).sqrt().min(1.0);     let reg_w = ((full_w as f64 * reg_scale).round() as usize).max(1);     let reg_h = ((full_h as f64 * reg_scale).round() as usize).max(1);-    let reg_frames: Vec<Rgba> = if reg_scale < 0.999 {-        frames.par_iter().map(|f| f.resized(reg_w, reg_h)).collect()-    } else {-        frames.to_vec()-    };--    // 1) features (parallel)-    let feats: Vec<Features> = reg_frames+    let feats: Vec<Features> = frames_jpeg         .par_iter()-        .map(|f| detect_and_describe(&to_gray(f), MAX_FEATURES, FAST_THRESHOLD))+        .map(|j| {+            let full = Rgba::from_jpeg(j).unwrap_or_else(|| Rgba::new(1, 1));+            let small = if reg_scale < 0.999 { full.resized(reg_w, reg_h) } else { full };+            detect_and_describe(&to_gray(&small), MAX_FEATURES, FAST_THRESHOLD)+        })         .collect(); -    // 2) all-pairs matching-    let matches = match_all(&feats, MATCH_WINDOW);+    // 2) matching (by gyro angular proximity so both pano rings and sphere grids connect)+    let matches = match_all(&feats, yaw, pitch, MATCH_MAX_ANGLE);     if matches.is_empty() {         return None;     }@@ -128,14 +304,13 @@ pub fn stitch_panorama(frames: &[Rgba], _yaw: &[f32], _pitch: &[f32]) -> Option<     if !scale.is_finite() || scale <= 1.0 {         return None;     }-    let kept_full: Vec<&Rgba> = kept.iter().map(|&i| &frames[i]).collect();     let mut compose_area = {         let mut gx0 = f64::MAX;         let mut gy0 = f64::MAX;         let mut gx1 = f64::MIN;         let mut gy1 = f64::MIN;-        for (f, c) in kept_full.iter().zip(cams.iter()) {-            if let Some((u0, v0, u1, v1)) = warped_bounds(f.w, f.h, &c.k(), &c.r, scale) {+        for c in cams.iter() {+            if let Some((u0, v0, u1, v1)) = warped_bounds(full_w, full_h, &c.k(), &c.r, scale) {                 gx0 = gx0.min(u0);                 gy0 = gy0.min(v0);                 gx1 = gx1.max(u1);@@ -150,32 +325,30 @@ pub fn stitch_panorama(frames: &[Rgba], _yaw: &[f32], _pitch: &[f32]) -> Option<     }     let seam_scale = (scale * (SEAM_MAX_PIXELS / compose_area).sqrt()).min(scale).max(1.0); -    // Low-res warps -> exposure + seam (cheap).-    let seam_tiles = kept_full+    // Decode each kept frame once (on demand), warp both the low-res seam tile and+    // the full-res compose tile from it, then drop the decoded frame — so at most a+    // few full-res frames are in RAM at a time even at maximum capture resolution.+    let warped: Vec<(WarpedTile, WarpedTile)> = kept         .par_iter()         .zip(cams.par_iter())-        .map(|(f, c)| warp_one(f, &c.k(), &c.r, seam_scale))+        .map(|(&i, c)| {+            let full = Rgba::from_jpeg(&frames_jpeg[i])?;+            let seam = warp_one(&full, &c.k(), &c.r, seam_scale)?;+            let comp = warp_one(&full, &c.k(), &c.r, scale)?;+            Some((seam, comp))+        })         .collect::<Option<Vec<_>>>()?;+    let (seam_tiles, tiles): (Vec<WarpedTile>, Vec<WarpedTile>) = warped.into_iter().unzip();+     let seam_gains = compensate(&seam_tiles);     let low_masks = seam_masks(&seam_tiles); -    // Full-res warps -> blend.-    let tiles = kept_full-        .par_iter()-        .zip(cams.par_iter())-        .map(|(f, c)| warp_one(f, &c.k(), &c.r, scale))-        .collect::<Option<Vec<_>>>()?;--    // Build compose-resolution seam masks as a true partition of the actual-    // coverage: every covered pixel is owned by exactly one covering tile,-    // guided by the low-res seam. This avoids unassigned (black) gaps at seams-    // that break the blend and the crop.+    // Compose-resolution seam masks as a true partition of the coverage.     let masks = build_compose_masks(&tiles, &seam_tiles, &low_masks);     let gain_maps: Vec<Vec<f32>> = (0..tiles.len())         .map(|i| resize_gain(&seam_gains[i], seam_tiles[i].img.w, seam_tiles[i].img.h, tiles[i].img.w, tiles[i].img.h))         .collect(); -    // 10) multi-band blend + crop     multiband_blend(&tiles, &masks, &gain_maps) } 
camera/rust/testdata/output.jpg
diff --git a/camera/rust/testdata/output.jpg b/camera/rust/testdata/output.jpgindex fd3d4fa534..24ddb24e14 100644Binary files a/camera/rust/testdata/output.jpg and b/camera/rust/testdata/output.jpg differ
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 4b83637876..e130ceeba5 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -136,6 +136,8 @@ import com.vayunmathur.camera.util.AspectRatioOption import com.vayunmathur.camera.util.BokehAnalyzer import com.vayunmathur.camera.util.CameraMode import com.vayunmathur.camera.util.CameraViewModel+import com.vayunmathur.camera.util.GuideDot+import com.vayunmathur.camera.util.GuideDotState import com.vayunmathur.camera.util.FlashMode import com.vayunmathur.camera.util.buildColorAdjustmentMatrix import com.vayunmathur.camera.util.formatZoomLabel@@ -279,8 +281,10 @@ fun CameraScreen(      val panoSweeping by viewModel.panoramaEngine.isSweeping.collectAsState()     val panoStitching by viewModel.panoramaEngine.isStitching.collectAsState()-    val panoFrameCount by viewModel.panoramaEngine.frameCount.collectAsState()-    val panoAngle by viewModel.panoramaEngine.sweepAngle.collectAsState()+    val panoDots by viewModel.panoramaEngine.guideDots.collectAsState()+    val panoCurrentAngle by viewModel.panoramaEngine.currentAngle.collectAsState()+    val panoDirection by viewModel.panoramaEngine.sweepDirection.collectAsState()+    val panoPitch by viewModel.panoramaEngine.currentPitch.collectAsState()      // Orientation tracking     var deviceRotation by remember { mutableIntStateOf(0) }@@ -705,8 +709,10 @@ fun CameraScreen(                         PanoramaOverlay(                             isSweeping = panoSweeping,                             isStitching = panoStitching,-                            frameCount = panoFrameCount,-                            sweepAngle = panoAngle,+                            guideDots = panoDots,+                            currentAngle = panoCurrentAngle,+                            sweepDirection = panoDirection,+                            currentPitch = panoPitch,                             modifier = previewSize                         )                     }@@ -1630,8 +1636,10 @@ private fun IsoBar( private fun PanoramaOverlay(     isSweeping: Boolean,     isStitching: Boolean,-    frameCount: Int,-    sweepAngle: Float,+    guideDots: List<GuideDot>,+    currentAngle: Float,+    sweepDirection: Int,+    currentPitch: Float,     modifier: Modifier = Modifier ) {     if (isStitching) {@@ -1647,12 +1655,15 @@ private fun PanoramaOverlay(      if (!isSweeping) return -    // Flash briefly each time a new frame is captured.+    val capturedCount = guideDots.count { it.state == GuideDotState.CAPTURED }+    val totalDots = guideDots.size+    val halfFOV = 30f+     val flashAlpha = remember { Animatable(0f) }-    LaunchedEffect(frameCount) {-        if (frameCount > 1) {-            flashAlpha.snapTo(0.25f)-            flashAlpha.animateTo(0f, tween(200))+    LaunchedEffect(capturedCount) {+        if (capturedCount > 1) {+            flashAlpha.snapTo(0.3f)+            flashAlpha.animateTo(0f, tween(250))         }     } @@ -1664,6 +1675,38 @@ private fun PanoramaOverlay(         Canvas(Modifier.fillMaxSize()) {             val centerX = size.width / 2             val centerY = size.height / 2+            val halfVertFOV = 40f++            guideDots.forEach { dot ->+                val angleOffset = dot.targetAngle - currentAngle+                val pitchOffset = dot.targetPitch - currentPitch+                if (Math.abs(angleOffset) <= halfFOV * 1.2f && Math.abs(pitchOffset) <= halfVertFOV * 1.2f) {+                    val dotX = centerX + (angleOffset / halfFOV) * (size.width / 2)+                    val dotY = centerY - (pitchOffset / halfVertFOV) * (size.height / 2)+                    val baseRadius = 14.dp.toPx()++                    when (dot.state) {+                        GuideDotState.PENDING -> {+                            drawCircle(Color.White.copy(alpha = 0.7f), baseRadius, Offset(dotX, dotY), style = Stroke(2.dp.toPx()))+                            drawCircle(Color.White.copy(alpha = 0.3f), 3.dp.toPx(), Offset(dotX, dotY))+                        }+                        GuideDotState.ALIGNING, GuideDotState.CAPTURING -> {+                            drawCircle(Color(0xFF4FC3F7), baseRadius * 1.2f, Offset(dotX, dotY))+                            drawCircle(Color.White, baseRadius * 1.2f, Offset(dotX, dotY), style = Stroke(2.dp.toPx()))+                        }+                        GuideDotState.CAPTURED -> {+                            drawCircle(Color(0xFF4CAF50), baseRadius, Offset(dotX, dotY))+                            val checkPath = Path().apply {+                                moveTo(dotX - baseRadius * 0.35f, dotY)+                                lineTo(dotX - baseRadius * 0.05f, dotY + baseRadius * 0.3f)+                                lineTo(dotX + baseRadius * 0.4f, dotY - baseRadius * 0.3f)+                            }+                            drawPath(checkPath, Color.White, style = Stroke(2.5.dp.toPx(), cap = StrokeCap.Round))+                        }+                    }+                }+            }+             val crossSize = 20.dp.toPx()             val crossGap = 6.dp.toPx()             val crossStroke = 2.dp.toPx()@@ -1675,23 +1718,14 @@ private fun PanoramaOverlay(             drawCircle(crossColor, 2.dp.toPx(), Offset(centerX, centerY))         } -        Column(+        Text(+            "$capturedCount / $totalDots",+            color = Color.White,+            fontSize = 16.sp,+            fontWeight = FontWeight.Medium,             modifier = Modifier.align(Alignment.TopCenter).padding(top = 60.dp)                 .background(Color.Black.copy(alpha = 0.4f), RoundedCornerShape(16.dp))-                .padding(horizontal = 16.dp, vertical = 6.dp),-            horizontalAlignment = Alignment.CenterHorizontally-        ) {-            Text(-                "Pan slowly \u2014 tap shutter to finish",-                color = Color.White,-                fontSize = 14.sp,-                fontWeight = FontWeight.Medium-            )-            Text(-                "$frameCount frames \u00b7 ${sweepAngle.toInt()}\u00b0",-                color = Color.White.copy(alpha = 0.85f),-                fontSize = 12.sp-            )-        }+                .padding(horizontal = 16.dp, vertical = 6.dp)+        )     } }
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 2377efb9f2..6faaf0f53d 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -927,26 +927,36 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             owner.start()             sessionLifecycleOwner = owner -            // Target ~1080p for the analysis stream: a large jump over the default-            // ~VGA analysis size, while bounding per-frame memory (the sphere sweep-            // holds ~40 frames until stitch).-            val analysisSelector = ResolutionSelector.Builder()-                .setResolutionStrategy(-                    ResolutionStrategy(-                        android.util.Size(1920, 1080),-                        ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER+            // Max-resolution analysis stream (same as the photo route): frames are+            // now stored JPEG-compressed and decoded one at a time at stitch, so a+            // high-res sweep no longer blows up memory. Fall back to a default-res+            // bind if the high-res analysis combo is rejected by the device.+            fun bind(maxRes: Boolean): Camera {+                val analysisBuilder = ImageAnalysis.Builder()+                    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+                if (maxRes) {+                    analysisBuilder.setResolutionSelector(+                        ResolutionSelector.Builder()+                            .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)+                            .setAllowedResolutionMode(+                                ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE+                            )+                            .build()                     )-                )-                .build()-            val analysis = ImageAnalysis.Builder()-                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)-                .setResolutionSelector(analysisSelector)-                .build()-            imageAnalysis = analysis-            // No ImageCapture in this session.-            imageCapture = null+                }+                val analysis = analysisBuilder.build()+                imageAnalysis = analysis+                imageCapture = null // No ImageCapture in this session.+                return provider.bindToLifecycle(owner, selector, preview, analysis)+            } -            boundCamera = provider.bindToLifecycle(owner, selector, preview, analysis)+            boundCamera = try {+                bind(maxRes = true)+            } catch (e: Exception) {+                Log.w("PhotoSession", "Max-res panorama bind failed; retrying at default resolution", e)+                provider.unbindAll()+                bind(maxRes = false)+            }              boundCamera?.cameraInfo?.zoomState?.value?.let {                 updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)
camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.kt b/camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.ktnew file mode 100644index 0000000000..226b053457--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/util/GpuStitcher.kt@@ -0,0 +1,571 @@+package com.vayunmathur.camera.util++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.opengl.EGL14+import android.opengl.EGLConfig+import android.opengl.EGLContext+import android.opengl.EGLDisplay+import android.opengl.EGLSurface+import android.opengl.GLES20+import android.opengl.GLES30+import android.opengl.GLUtils+import android.util.Log+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.FloatBuffer+import java.nio.ShortBuffer+import kotlin.math.atan2+import kotlin.math.acos+import kotlin.math.sqrt++/**+ * GPU panorama compositor (OpenGL ES 3.x, headless EGL pbuffer + FBO). Replaces+ * the CPU per-pixel warp + feather blend with a textured-mesh remap + additive+ * blend on an RGBA16F accumulation buffer, then a normalization pass.+ *+ * Registration (features/match/estimate/BA/wave) stays in Rust; this consumes+ * its [Estimate] blob (see [parseEstimate]) plus the captured JPEG frames and+ * produces a cropped [Bitmap]. Everything here returns null on any failure so+ * the caller can fall back to the Rust CPU stitcher.+ */+object GpuStitcher {++    private const val TAG = "GpuStitcher"++    // Warp mesh resolution (grid cells per axis over each source image).+    private const val GRID = 48++    // Feather width in source-UV units (distance from edge over which weight ramps).+    private const val FEATHER = 0.15f++    // Coverage threshold: accumulated weight above this counts as "has data".+    private const val COVERAGE_EPS = 1e-2f++    private const val EGL_OPENGL_ES3_BIT = 0x0040++    /** One kept frame's camera solution. [r] is the 3×3 rotation, row-major. */+    data class FrameCam(+        val originalIndex: Int,+        val focal: Double,+        val ppx: Double,+        val ppy: Double,+        val r: DoubleArray,+        val gain: Float,+    )++    /** Compose canvas geometry + per-frame cameras from Rust registration. */+    data class Estimate(+        val canvasW: Int,+        val canvasH: Int,+        val u0: Double,+        val v0: Double,+        val scale: Double,+        val cams: List<FrameCam>,+    )++    /** The composited panorama, cropped to content, plus the full-canvas geometry. */+    data class CompositeResult(+        val bitmap: Bitmap,+        val fullWidth: Int,+        val fullHeight: Int,+        val croppedLeft: Int,+        val croppedTop: Int,+    )++    /**+     * Decode the little-endian blob produced by the Rust `estimate` JNI call.+     * Layout: canvas_w u32, canvas_h u32, u0 f64, v0 f64, scale f64, count u32,+     * then per cam: original_index u32, focal f64, ppx f64, ppy f64, R[9] f64+     * (row-major), gain f32.+     */+    fun parseEstimate(blob: ByteArray): Estimate? {+        return try {+            val buf = ByteBuffer.wrap(blob).order(ByteOrder.LITTLE_ENDIAN)+            val canvasW = buf.int+            val canvasH = buf.int+            val u0 = buf.double+            val v0 = buf.double+            val scale = buf.double+            val count = buf.int+            if (count <= 0 || canvasW <= 0 || canvasH <= 0) return null+            val cams = ArrayList<FrameCam>(count)+            repeat(count) {+                val idx = buf.int+                val focal = buf.double+                val ppx = buf.double+                val ppy = buf.double+                val r = DoubleArray(9) { buf.double }+                val gain = buf.float+                cams.add(FrameCam(idx, focal, ppx, ppy, r, gain))+            }+            Estimate(canvasW, canvasH, u0, v0, scale, cams)+        } catch (t: Throwable) {+            Log.e(TAG, "parseEstimate failed", t)+            null+        }+    }++    /**+     * Composite the kept frames on the GPU. [frames] is indexed by the frame's+     * original capture index (matching [FrameCam.originalIndex]). Returns null+     * on any GL/EGL failure or unsupported capability so the caller falls back+     * to the CPU stitcher.+     */+    fun composite(estimate: Estimate, frames: List<ByteArray>): CompositeResult? {+        var gl: GlEnv? = null+        return try {+            gl = GlEnv.create() ?: return null+            gl.render(estimate, frames)+        } catch (t: Throwable) {+            Log.e(TAG, "composite failed", t)+            null+        } finally {+            gl?.release()+        }+    }++    /** Forward spherical map for one source pixel (mirrors Rust `Proj::forward`). */+    private fun forward(cam: FrameCam, scale: Double, x: Double, y: Double): DoubleArray {+        // K^-1 * [x,y,1] with K = [[f,0,ppx],[0,f,ppy],[0,0,1]], aspect = 1.+        val a = (x - cam.ppx) / cam.focal+        val b = (y - cam.ppy) / cam.focal+        val c = 1.0+        val r = cam.r+        val px = r[0] * a + r[1] * b + r[2] * c+        val py = r[3] * a + r[4] * b + r[5] * c+        val pz = r[6] * a + r[7] * b + r[8] * c+        val u = scale * atan2(px, pz)+        val denom = sqrt(px * px + py * py + pz * pz)+        val ww = if (denom > 1e-12) (py / denom).coerceIn(-1.0, 1.0) else 0.0+        val v = scale * (Math.PI - acos(ww))+        return doubleArrayOf(u, v)+    }++    /** Encapsulates the EGL context + GL resources for one composite pass. */+    private class GlEnv private constructor(+        private val display: EGLDisplay,+        private val context: EGLContext,+        private val surface: EGLSurface,+    ) {+        private var warpProgram = 0+        private var normProgram = 0+        private var accumTex = 0+        private var accumFbo = 0+        private var outTex = 0+        private var outFbo = 0++        fun render(est: Estimate, frames: List<ByteArray>): CompositeResult? {+            val maxTex = IntArray(1)+            GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, maxTex, 0)+            val cap = maxTex[0].coerceAtLeast(2048)+            if (est.canvasW > cap || est.canvasH > cap) {+                Log.w(TAG, "canvas ${est.canvasW}x${est.canvasH} exceeds GL_MAX_TEXTURE_SIZE $cap")+                return null+            }++            // RGBA16F accumulation FBO — needs GL_EXT_color_buffer_float.+            accumTex = genTexture(GLES30.GL_NEAREST)+            GLES30.glTexImage2D(+                GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F,+                est.canvasW, est.canvasH, 0, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null+            )+            accumFbo = genFbo(accumTex)+            if (GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) != GLES30.GL_FRAMEBUFFER_COMPLETE) {+                Log.w(TAG, "RGBA16F FBO incomplete (no color-buffer-float support)")+                return null+            }++            warpProgram = buildProgram(WARP_VS, WARP_FS) ?: return null+            normProgram = buildProgram(NORM_VS, NORM_FS) ?: return null++            // --- accumulate all frames additively ---+            GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, accumFbo)+            GLES30.glViewport(0, 0, est.canvasW, est.canvasH)+            GLES30.glClearColor(0f, 0f, 0f, 0f)+            GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)+            GLES20.glEnable(GLES20.GL_BLEND)+            GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE)+            GLES20.glBlendEquation(GLES20.GL_FUNC_ADD)++            val indices = buildIndexBuffer()+            val indexCount = GRID * GRID * 6+            GLES30.glUseProgram(warpProgram)+            val uGain = GLES30.glGetUniformLocation(warpProgram, "uGain")+            val uFeather = GLES30.glGetUniformLocation(warpProgram, "uFeather")+            val uTex = GLES30.glGetUniformLocation(warpProgram, "uTex")++            var drawn = 0+            for (cam in est.cams) {+                val jpeg = frames.getOrNull(cam.originalIndex) ?: continue+                val tex = uploadFrame(jpeg, cap) ?: continue+                try {+                    val verts = buildFrameMesh(est, cam)+                    GLES30.glActiveTexture(GLES30.GL_TEXTURE0)+                    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, tex)+                    GLES30.glUniform1i(uTex, 0)+                    GLES30.glUniform1f(uGain, cam.gain)+                    GLES30.glUniform1f(uFeather, FEATHER)++                    verts.position(0)+                    GLES30.glEnableVertexAttribArray(0)+                    GLES30.glVertexAttribPointer(0, 2, GLES30.GL_FLOAT, false, 4 * 4, verts)+                    verts.position(2)+                    GLES30.glEnableVertexAttribArray(1)+                    GLES30.glVertexAttribPointer(1, 2, GLES30.GL_FLOAT, false, 4 * 4, verts)++                    indices.position(0)+                    GLES30.glDrawElements(GLES30.GL_TRIANGLES, indexCount, GLES30.GL_UNSIGNED_SHORT, indices)+                    GLES30.glDisableVertexAttribArray(0)+                    GLES30.glDisableVertexAttribArray(1)+                    drawn+++                } finally {+                    val t = intArrayOf(tex)+                    GLES30.glDeleteTextures(1, t, 0)+                }+            }+            GLES20.glDisable(GLES20.GL_BLEND)+            if (drawn == 0) return null++            // --- normalization pass into an RGBA8 output FBO ---+            outTex = genTexture(GLES30.GL_NEAREST)+            GLES30.glTexImage2D(+                GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA8,+                est.canvasW, est.canvasH, 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null+            )+            outFbo = genFbo(outTex)+            if (GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) != GLES30.GL_FRAMEBUFFER_COMPLETE) {+                Log.w(TAG, "output FBO incomplete")+                return null+            }+            GLES30.glViewport(0, 0, est.canvasW, est.canvasH)+            GLES30.glClearColor(0f, 0f, 0f, 0f)+            GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)+            GLES30.glUseProgram(normProgram)+            GLES30.glActiveTexture(GLES30.GL_TEXTURE0)+            GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, accumTex)+            GLES30.glUniform1i(GLES30.glGetUniformLocation(normProgram, "uAccum"), 0)+            GLES30.glUniform1f(GLES30.glGetUniformLocation(normProgram, "uEps"), COVERAGE_EPS)+            GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)++            // --- read back + crop to content ---+            val pixels = ByteBuffer.allocateDirect(est.canvasW * est.canvasH * 4).order(ByteOrder.nativeOrder())+            GLES30.glReadPixels(0, 0, est.canvasW, est.canvasH, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, pixels)++            val full = Bitmap.createBitmap(est.canvasW, est.canvasH, Bitmap.Config.ARGB_8888)+            pixels.rewind()+            full.copyPixelsFromBuffer(pixels)++            pixels.rewind()+            val rect = contentRect(pixels, est.canvasW, est.canvasH)+            if (rect == null) {+                return CompositeResult(full, est.canvasW, est.canvasH, 0, 0)+            }+            val (rx, ry, rw, rh) = rect+            val cropped = Bitmap.createBitmap(full, rx, ry, rw, rh)+            if (cropped != full) full.recycle()+            return CompositeResult(cropped, est.canvasW, est.canvasH, rx, ry)+        }++        private fun uploadFrame(jpeg: ByteArray, cap: Int): Int? {+            val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+            BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size, bounds)+            if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null+            var sample = 1+            while (bounds.outWidth / sample > cap || bounds.outHeight / sample > cap) sample *= 2+            val opts = BitmapFactory.Options().apply { inSampleSize = sample }+            val bmp = BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size, opts) ?: return null+            // UVs are normalized, so a downsampled texture samples the same content;+            // the mesh's source-pixel coords use full-res intrinsics (ppx=fullW/2).+            val tex = genTexture(GLES30.GL_LINEAR)+            GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bmp, 0)+            bmp.recycle()+            return tex+        }++        /** Build a GRID×GRID warp mesh: interleaved [ndcX, ndcY, u, v] per vertex. */+        private fun buildFrameMesh(est: Estimate, cam: FrameCam): FloatBuffer {+            val cols = GRID + 1+            val data = FloatArray(cols * cols * 4)+            var p = 0+            for (j in 0..GRID) {+                val b = j.toFloat() / GRID+                for (i in 0..GRID) {+                    val a = i.toFloat() / GRID+                    // Source pixel coords (ppx/ppy assume full-res width; UVs are+                    // normalized so a downsampled texture samples the same content).+                    val sx = a.toDouble() * (cam.ppx * 2.0)+                    val sy = b.toDouble() * (cam.ppy * 2.0)+                    val uv = forward(cam, est.scale, sx, sy)+                    val outX = uv[0] - est.u0+                    val outY = uv[1] - est.v0+                    val ndcX = (outX / est.canvasW * 2.0 - 1.0).toFloat()+                    val ndcY = (outY / est.canvasH * 2.0 - 1.0).toFloat()+                    data[p++] = ndcX+                    data[p++] = ndcY+                    data[p++] = a+                    data[p++] = b+                }+            }+            return ByteBuffer.allocateDirect(data.size * 4).order(ByteOrder.nativeOrder())+                .asFloatBuffer().apply { put(data); position(0) }+        }++        private fun buildIndexBuffer(): ShortBuffer {+            val cols = GRID + 1+            val idx = ShortArray(GRID * GRID * 6)+            var p = 0+            for (j in 0 until GRID) {+                for (i in 0 until GRID) {+                    val a = (j * cols + i).toShort()+                    val bb = (j * cols + i + 1).toShort()+                    val c = ((j + 1) * cols + i).toShort()+                    val d = ((j + 1) * cols + i + 1).toShort()+                    idx[p++] = a; idx[p++] = c; idx[p++] = bb+                    idx[p++] = bb; idx[p++] = c; idx[p++] = d+                }+            }+            return ByteBuffer.allocateDirect(idx.size * 2).order(ByteOrder.nativeOrder())+                .asShortBuffer().apply { put(idx); position(0) }+        }++        private fun genTexture(filter: Int): Int {+            val ids = IntArray(1)+            GLES30.glGenTextures(1, ids, 0)+            GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ids[0])+            GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, filter)+            GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, filter)+            GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)+            GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)+            return ids[0]+        }++        private fun genFbo(tex: Int): Int {+            val ids = IntArray(1)+            GLES30.glGenFramebuffers(1, ids, 0)+            GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, ids[0])+            GLES30.glFramebufferTexture2D(+                GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, tex, 0+            )+            return ids[0]+        }++        private fun buildProgram(vs: String, fs: String): Int? {+            val v = compileShader(GLES30.GL_VERTEX_SHADER, vs) ?: return null+            val f = compileShader(GLES30.GL_FRAGMENT_SHADER, fs) ?: return null+            val p = GLES30.glCreateProgram()+            GLES30.glAttachShader(p, v)+            GLES30.glAttachShader(p, f)+            GLES30.glLinkProgram(p)+            val status = IntArray(1)+            GLES30.glGetProgramiv(p, GLES30.GL_LINK_STATUS, status, 0)+            GLES30.glDeleteShader(v)+            GLES30.glDeleteShader(f)+            if (status[0] == 0) {+                Log.e(TAG, "program link failed: ${GLES30.glGetProgramInfoLog(p)}")+                GLES30.glDeleteProgram(p)+                return null+            }+            return p+        }++        private fun compileShader(type: Int, src: String): Int? {+            val s = GLES30.glCreateShader(type)+            GLES30.glShaderSource(s, src)+            GLES30.glCompileShader(s)+            val status = IntArray(1)+            GLES30.glGetShaderiv(s, GLES30.GL_COMPILE_STATUS, status, 0)+            if (status[0] == 0) {+                Log.e(TAG, "shader compile failed: ${GLES30.glGetShaderInfoLog(s)}")+                GLES30.glDeleteShader(s)+                return null+            }+            return s+        }++        fun release() {+            if (accumFbo != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(accumFbo), 0)+            if (outFbo != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(outFbo), 0)+            if (accumTex != 0) GLES30.glDeleteTextures(1, intArrayOf(accumTex), 0)+            if (outTex != 0) GLES30.glDeleteTextures(1, intArrayOf(outTex), 0)+            if (warpProgram != 0) GLES30.glDeleteProgram(warpProgram)+            if (normProgram != 0) GLES30.glDeleteProgram(normProgram)+            EGL14.eglMakeCurrent(display, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT)+            EGL14.eglDestroySurface(display, surface)+            EGL14.eglDestroyContext(display, context)+            EGL14.eglTerminate(display)+        }++        companion object {+            /** Bring up a headless ES3 context on a 1×1 pbuffer, or null on failure. */+            fun create(): GlEnv? {+                val display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)+                if (display == EGL14.EGL_NO_DISPLAY) return null+                val ver = IntArray(2)+                if (!EGL14.eglInitialize(display, ver, 0, ver, 1)) return null++                val cfgAttr = intArrayOf(+                    EGL14.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,+                    EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT,+                    EGL14.EGL_RED_SIZE, 8,+                    EGL14.EGL_GREEN_SIZE, 8,+                    EGL14.EGL_BLUE_SIZE, 8,+                    EGL14.EGL_ALPHA_SIZE, 8,+                    EGL14.EGL_NONE+                )+                val configs = arrayOfNulls<EGLConfig>(1)+                val numConfig = IntArray(1)+                if (!EGL14.eglChooseConfig(display, cfgAttr, 0, configs, 0, 1, numConfig, 0) ||+                    numConfig[0] == 0 || configs[0] == null+                ) {+                    EGL14.eglTerminate(display)+                    return null+                }+                val config = configs[0]!!++                val ctxAttr = intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE)+                val context = EGL14.eglCreateContext(display, config, EGL14.EGL_NO_CONTEXT, ctxAttr, 0)+                if (context == EGL14.EGL_NO_CONTEXT) {+                    EGL14.eglTerminate(display)+                    return null+                }+                val surfAttr = intArrayOf(EGL14.EGL_WIDTH, 1, EGL14.EGL_HEIGHT, 1, EGL14.EGL_NONE)+                val surface = EGL14.eglCreatePbufferSurface(display, config, surfAttr, 0)+                if (surface == EGL14.EGL_NO_SURFACE) {+                    EGL14.eglDestroyContext(display, context)+                    EGL14.eglTerminate(display)+                    return null+                }+                if (!EGL14.eglMakeCurrent(display, surface, surface, context)) {+                    EGL14.eglDestroySurface(display, surface)+                    EGL14.eglDestroyContext(display, context)+                    EGL14.eglTerminate(display)+                    return null+                }+                // Require float color-buffer support up front (FBO completeness+                // is re-checked at render time as a backstop).+                if (!hasColorBufferFloat()) {+                    Log.w(TAG, "no GL_EXT_color_buffer_float; falling back to CPU")+                    val env = GlEnv(display, context, surface)+                    env.release()+                    return null+                }+                return GlEnv(display, context, surface)+            }++            /** ES3-safe extension query (the monolithic GL_EXTENSIONS string may be empty). */+            private fun hasColorBufferFloat(): Boolean {+                val legacy = GLES30.glGetString(GLES30.GL_EXTENSIONS)+                if (legacy != null && (legacy.contains("GL_EXT_color_buffer_float") ||+                        legacy.contains("GL_EXT_color_buffer_half_float"))+                ) {+                    return true+                }+                val count = IntArray(1)+                GLES30.glGetIntegerv(GLES30.GL_NUM_EXTENSIONS, count, 0)+                for (i in 0 until count[0]) {+                    val e = GLES30.glGetStringi(GLES30.GL_EXTENSIONS, i) ?: continue+                    if (e == "GL_EXT_color_buffer_float" || e == "GL_EXT_color_buffer_half_float") {+                        return true+                    }+                }+                return false+            }+        }+    }++    /**+     * Maximal all-opaque (alpha == 255) rectangle in the RGBA byte buffer — a+     * Kotlin port of the Rust `content_rect` histogram/stack max-rectangle. The+     * buffer is top-down (matching the readback), so the rect is in bitmap+     * coordinates directly. Returns (x, y, w, h) or null if nothing is covered.+     */+    private data class Rect(val x: Int, val y: Int, val w: Int, val h: Int)++    private fun contentRect(pixels: ByteBuffer, w: Int, h: Int): Rect? {+        val heights = IntArray(w)+        var best: Rect? = null+        var bestArea = 0+        val stack = IntArray(w + 1)+        for (y in 0 until h) {+            val rowBase = y * w * 4+            for (x in 0 until w) {+                val alpha = pixels.get(rowBase + x * 4 + 3).toInt() and 0xFF+                heights[x] = if (alpha == 255) heights[x] + 1 else 0+            }+            var sp = 0+            var x = 0+            while (x <= w) {+                val cur = if (x == w) 0 else heights[x]+                if (sp == 0 || cur >= heights[stack[sp - 1]]) {+                    stack[sp++] = x+                    x+++                } else {+                    val top = stack[--sp]+                    val height = heights[top]+                    val left = if (sp == 0) 0 else stack[sp - 1] + 1+                    val width = x - left+                    val area = height * width+                    if (area > bestArea) {+                        bestArea = area+                        best = Rect(left, y + 1 - height, width, height)+                    }+                }+            }+        }+        return if (best != null && best.w > 0 && best.h > 0) best else null+    }++    // --- shaders (ES 3.10) ---++    private const val WARP_VS = """#version 310 es+        layout(location = 0) in vec2 aPos;+        layout(location = 1) in vec2 aUv;+        out vec2 vUv;+        void main() {+            vUv = aUv;+            gl_Position = vec4(aPos, 0.0, 1.0);+        }+    """++    private const val WARP_FS = """#version 310 es+        precision highp float;+        uniform sampler2D uTex;+        uniform float uGain;+        uniform float uFeather;+        in vec2 vUv;+        out vec4 frag;+        void main() {+            vec4 c = texture(uTex, vUv);+            float dx = min(vUv.x, 1.0 - vUv.x);+            float dy = min(vUv.y, 1.0 - vUv.y);+            float d = min(dx, dy);+            float w = smoothstep(0.0, uFeather, d);+            frag = vec4(c.rgb * w * uGain, w);+        }+    """++    private const val NORM_VS = """#version 310 es+        out vec2 vUv;+        void main() {+            vec2 p = vec2(float((gl_VertexID & 1) << 2) - 1.0,+                          float((gl_VertexID & 2) << 1) - 1.0);+            vUv = (p + 1.0) * 0.5;+            gl_Position = vec4(p, 0.0, 1.0);+        }+    """++    private const val NORM_FS = """#version 310 es+        precision highp float;+        uniform sampler2D uAccum;+        uniform float uEps;+        in vec2 vUv;+        out vec4 frag;+        void main() {+            vec4 a = texture(uAccum, vUv);+            float cov = a.a > uEps ? 1.0 : 0.0;+            float wsum = max(a.a, 1e-4);+            frag = vec4(a.rgb / wsum, cov);+        }+    """+}
camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt b/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.ktindex bbbf1aa1b3..fad5b817b5 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt@@ -4,7 +4,6 @@ import android.graphics.Bitmap import android.graphics.BitmapFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext-import java.nio.ByteBuffer import kotlin.math.roundToInt  /**@@ -60,11 +59,9 @@ object NightCaptureEngine {         val handle = StitchNative.newSession(false)         try {             for (f in burst) {-                val bmp = if (f.config == Bitmap.Config.ARGB_8888) f else f.copy(Bitmap.Config.ARGB_8888, false)-                val buf = ByteBuffer.allocate(bmp.width * bmp.height * 4)-                bmp.copyPixelsToBuffer(buf)-                StitchNative.addFrame(handle, buf.array(), bmp.width, bmp.height, 0f, 0f, 0f)-                if (bmp !== f) bmp.recycle()+                val baos = java.io.ByteArrayOutputStream()+                f.compress(Bitmap.CompressFormat.JPEG, 95, baos)+                StitchNative.addFrame(handle, baos.toByteArray(), 0f, 0f, 0f)             }             val jpeg = StitchNative.merge(handle) ?: return null             return BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size)
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 adce68873f..58b321741f 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt@@ -10,9 +10,24 @@ import android.hardware.SensorEventListener import android.hardware.SensorManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.withContext-import java.nio.ByteBuffer+import java.io.ByteArrayOutputStream++enum class GuideDotState {+    PENDING,+    ALIGNING,+    CAPTURING,+    CAPTURED+}++data class GuideDot(+    val index: Int,+    val targetAngle: Float,+    val targetPitch: Float = 0f,+    val state: GuideDotState+)  /**  * Geometry of a stitched panorama, written out as GPano XMP so compliant viewers@@ -30,10 +45,11 @@ data class PanoInfo( )  /**- * Drives the panorama/photo-sphere sweep. Instead of a guide-dot system, it- * captures frames *continuously* as the user pans — one frame per fixed increment- * of device rotation — giving dense overlap for smooth stitching. Frames are fed- * to the native [StitchNative] Rust stitcher (OpenCV-free).+ * Drives the panorama/photo-sphere sweep with a guide-dot system: the user aligns+ * the reticle to each target dot and a frame is captured when steady on it. Frames+ * are captured at full resolution, stored JPEG-compressed, and fed to the native+ * [StitchNative] Rust stitcher (OpenCV-free). Panorama and photo-sphere share the+ * exact same capture + stitch path; only the dot layout and GPano tag differ.  */ class PanoramaEngine(private val context: Context) : SensorEventListener { @@ -52,19 +68,24 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {     private val _sweepAngle = MutableStateFlow(0f)     val sweepAngle = _sweepAngle.asStateFlow() +    private val _guideDots = MutableStateFlow<List<GuideDot>>(emptyList())+    val guideDots: StateFlow<List<GuideDot>> = _guideDots.asStateFlow()+     private val _currentAngle = MutableStateFlow(0f)-    val currentAngle = _currentAngle.asStateFlow()+    val currentAngle: StateFlow<Float> = _currentAngle.asStateFlow()      private val _currentPitch = MutableStateFlow(0f)-    val currentPitch = _currentPitch.asStateFlow()+    val currentPitch: StateFlow<Float> = _currentPitch.asStateFlow()++    private val _sweepDirection = MutableStateFlow(0)+    val sweepDirection: StateFlow<Int> = _sweepDirection.asStateFlow()      private var nativeHandle: Long = 0L+    private val capturedFrames = mutableListOf<ByteArray>()     private var accumulatedAngle = 0f     private var accumulatedPitch = 0f     private var accumulatedRoll = 0f     private var lastTimestamp = 0L-    private var lastCaptureYaw = 0f-    private var lastCapturePitch = 0f     private var angularVelocity = 0f     private var pitchVelocity = 0f @@ -74,24 +95,21 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {     var latestFrame: Bitmap? = null      /**-     * Invoked once when a sweep auto-completes (frame budget reached, or the-     * panorama passes a near-full rotation). The owner runs stitch + save.+     * Invoked once when a sweep auto-completes (all guide dots captured, or a flat+     * panorama reaches its angular limit). The owner runs stitch + save.      */     var onSweepComplete: (() -> Unit)? = null      companion object {-        // Continuous capture: one frame per this much rotation (deg). With a-        // ~67° FOV, an 18° step still gives ~73% overlap (plenty) while keeping-        // the frame count — and thus stitch time on low-end phones — bounded.-        private const val CAPTURE_STEP_DEG = 18f-        // Don't capture while whipping the phone (limits motion blur).-        private const val CAPTURE_MAX_VEL_DPS = 120f-        // Bound total frames so the stitch stays fast on low-end hardware.-        private const val MAX_FRAMES = 16-        // Frames are downscaled before stitching to bound memory over a long sweep.-        private const val FRAME_SCALE = 0.6f-        // Auto-finish a flat panorama once it has swept nearly all the way around.-        private const val PANO_MAX_ANGLE = 350f+        // Frames are captured at full analysis resolution and stored+        // JPEG-compressed (decoded one at a time by the native stitcher).+        private const val JPEG_QUALITY = 92+        // A frame is captured when the reticle is within this of a dot and steady.+        private const val ALIGNMENT_THRESHOLD_DEGREES = 3f+        private const val PITCH_THRESHOLD_DEGREES = 5f+        private const val MAX_VELOCITY_DPS = 30f+        // Safety auto-finish for a flat panorama that has swept far enough.+        private const val PANO_MAX_ANGLE = 200f     }      fun startSweep(fullSphere: Boolean = false) {@@ -99,20 +117,47 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {         accumulatedAngle = 0f         accumulatedPitch = 0f         accumulatedRoll = 0f-        lastCaptureYaw = 0f-        lastCapturePitch = 0f         lastTimestamp = 0L         angularVelocity = 0f         pitchVelocity = 0f         _frameCount.value = 0         _sweepAngle.value = 0f+        _sweepDirection.value = 0         _currentAngle.value = 0f         _currentPitch.value = 0f +        // Guide-dot layout: a full-sphere grid (pitch rows) or a flat horizontal ring.+        val dots = if (fullSphere) {+            var idx = 0+            val result = mutableListOf<GuideDot>()+            val rows = listOf(+                0f to 30f,+                -30f to 40f,+                30f to 40f,+                -60f to 72f,+                60f to 72f+            )+            for ((pitch, yawStep) in rows) {+                val count = (360f / yawStep).toInt()+                for (i in 0 until count) {+                    result.add(GuideDot(idx, i * yawStep, pitch, if (idx == 0) GuideDotState.CAPTURING else GuideDotState.PENDING))+                    idx+++                }+            }+            result+        } else {+            (0 until 7).map { i ->+                GuideDot(i, i * 30f, 0f, if (i == 0) GuideDotState.CAPTURING else GuideDotState.PENDING)+            }+        }+        _guideDots.value = dots+         if (nativeHandle != 0L && StitchNative.isAvailable) StitchNative.free(nativeHandle)         nativeHandle = if (StitchNative.isAvailable) StitchNative.newSession(fullSphere) else 0L+        capturedFrames.clear()          captureFrame() // seed with the starting frame+        updateDotState(0, GuideDotState.CAPTURED)          _isSweeping.value = true         gyroscope?.let {@@ -125,30 +170,24 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {         sensorManager.unregisterListener(this)     } -    private fun bitmapToRgba(bmp: Bitmap): ByteArray {-        val src = if (bmp.config == Bitmap.Config.ARGB_8888) bmp else bmp.copy(Bitmap.Config.ARGB_8888, false)-        val buf = ByteBuffer.allocate(src.width * src.height * 4)-        src.copyPixelsToBuffer(buf)-        if (src !== bmp) src.recycle()-        return buf.array()-    }-     private fun captureFrame() {         val frame = latestFrame ?: return         val handle = nativeHandle         if (handle == 0L) return-        val w = (frame.width * FRAME_SCALE).toInt().coerceAtLeast(1)-        val h = (frame.height * FRAME_SCALE).toInt().coerceAtLeast(1)-        val scaled = Bitmap.createScaledBitmap(frame, w, h, true)+        // Rotate to upright and JPEG-compress. Storing frames compressed keeps+        // memory bounded across a long, high-resolution sweep (they're decoded on+        // demand by the native stitcher, one at a time).         val rotMatrix = Matrix().apply { postRotate(90f) }-        val rotated = Bitmap.createBitmap(scaled, 0, 0, scaled.width, scaled.height, rotMatrix, true)-        scaled.recycle()-        val rgba = bitmapToRgba(rotated)-        StitchNative.addFrame(handle, rgba, rotated.width, rotated.height, accumulatedAngle, accumulatedPitch, accumulatedRoll)+        val rotated = Bitmap.createBitmap(frame, 0, 0, frame.width, frame.height, rotMatrix, true)+        val baos = ByteArrayOutputStream()+        rotated.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, baos)         rotated.recycle()+        val jpeg = baos.toByteArray()+        // Keep the same JPEG bytes the native registrar receives, so the GPU+        // compositor can decode kept frames into textures by capture index.+        capturedFrames.add(jpeg)+        StitchNative.addFrame(handle, jpeg, accumulatedAngle, accumulatedPitch, accumulatedRoll)         _frameCount.value = _frameCount.value + 1-        lastCaptureYaw = accumulatedAngle-        lastCapturePitch = accumulatedPitch     }      override fun onSensorChanged(event: SensorEvent) {@@ -170,23 +209,21 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {             _currentAngle.value = accumulatedAngle             _sweepAngle.value = Math.abs(accumulatedAngle) -            // Continuous capture: whenever the device has rotated far enough since-            // the last frame and isn't moving too fast.-            val movedYaw = Math.abs(accumulatedAngle - lastCaptureYaw)-            val movedPitch = Math.abs(accumulatedPitch - lastCapturePitch)-            val notTooFast = Math.abs(angularVelocity) < CAPTURE_MAX_VEL_DPS &&-                Math.abs(pitchVelocity) < CAPTURE_MAX_VEL_DPS-            if (notTooFast && _frameCount.value < MAX_FRAMES &&-                (movedYaw >= CAPTURE_STEP_DEG || movedPitch >= CAPTURE_STEP_DEG)-            ) {-                captureFrame()+            // Mirror the dot ring to match the sweep direction (flat pano only).+            if (_sweepDirection.value == 0 && Math.abs(accumulatedAngle) > 10f) {+                val dir = if (accumulatedAngle > 0) 1 else -1+                _sweepDirection.value = dir+                if (dir == -1 && !sphereMode) {+                    _guideDots.value = _guideDots.value.map { it.copy(targetAngle = -it.targetAngle) }+                }             }++            checkDotAlignment()         }         lastTimestamp = timestamp -        val reachedBudget = _frameCount.value >= MAX_FRAMES-        val fullLoop = !sphereMode && Math.abs(accumulatedAngle) > PANO_MAX_ANGLE-        if (reachedBudget || fullLoop) {+        val allCaptured = _guideDots.value.all { it.state == GuideDotState.CAPTURED }+        if (allCaptured || (!sphereMode && Math.abs(accumulatedAngle) > PANO_MAX_ANGLE)) {             stopSweep()             onSweepComplete?.invoke()         }@@ -194,9 +231,54 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {      override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} +    /** Capture the frame for the nearest aligned, steady dot; update dot states. */+    private fun checkDotAlignment() {+        val dots = _guideDots.value+        val currentAng = accumulatedAngle+        var captured = false++        _guideDots.value = dots.map { dot ->+            if (dot.state == GuideDotState.CAPTURED) return@map dot++            val angleDiff = Math.abs(wrapDegrees(currentAng - dot.targetAngle))+            val pitchDiff = Math.abs(accumulatedPitch - dot.targetPitch)+            val withinCapture = angleDiff < ALIGNMENT_THRESHOLD_DEGREES && pitchDiff < PITCH_THRESHOLD_DEGREES+            val withinAligning = angleDiff < ALIGNMENT_THRESHOLD_DEGREES * 2 && pitchDiff < PITCH_THRESHOLD_DEGREES * 2+            val steadyEnough = Math.abs(angularVelocity) < MAX_VELOCITY_DPS && Math.abs(pitchVelocity) < MAX_VELOCITY_DPS++            when {+                withinCapture && steadyEnough && !captured -> {+                    captureFrame()+                    captured = true+                    dot.copy(state = GuideDotState.CAPTURED)+                }+                withinCapture -> dot.copy(state = GuideDotState.CAPTURING)+                withinAligning -> dot.copy(state = GuideDotState.ALIGNING)+                dot.state != GuideDotState.PENDING -> dot.copy(state = GuideDotState.PENDING)+                else -> dot+            }+        }+    }++    private fun updateDotState(index: Int, state: GuideDotState) {+        _guideDots.value = _guideDots.value.map {+            if (it.index == index) it.copy(state = state) else it+        }+    }++    /** Smallest signed difference of an angle in degrees, normalized to (-180, 180]. */+    private fun wrapDegrees(deg: Float): Float {+        var d = deg % 360f+        if (d > 180f) d -= 360f+        if (d < -180f) d += 360f+        return d+    }+     /**-     * Runs the native stitcher over the captured frames. Returns the stitched-     * JPEG bytes plus its GPano geometry, or null on failure.+     * Produces the stitched panorama. Tries the GPU compositor first (Rust+     * registration → [GpuStitcher] warp+blend), falling back to the full Rust+     * CPU stitcher if registration, EGL/GLES, or GPU compositing fails. Returns+     * the JPEG bytes plus GPano geometry, or null.      */     suspend fun stitch(): Pair<ByteArray, PanoInfo>? {         val handle = nativeHandle@@ -204,31 +286,73 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {         _isStitching.value = true         return withContext(Dispatchers.IO) {             try {-                val jpeg = StitchNative.stitch(handle) ?: return@withContext null-                val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }-                BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size, opts)-                val w = opts.outWidth-                val h = opts.outHeight-                if (w <= 0 || h <= 0) return@withContext null-                val info = PanoInfo(-                    projectionType = if (sphereMode) "equirectangular" else "cylindrical",-                    fullWidth = w,-                    fullHeight = h,-                    croppedWidth = w,-                    croppedHeight = h,-                    croppedLeft = 0,-                    croppedTop = 0,-                )-                Pair(jpeg, info)+                gpuStitch(handle) ?: cpuStitch(handle)             } catch (e: Exception) {                 e.printStackTrace()-                null+                try {+                    cpuStitch(handle)+                } catch (e2: Exception) {+                    e2.printStackTrace()+                    null+                }             } finally {                 _isStitching.value = false             }         }     } +    /** GPU path: Rust registration blob → [GpuStitcher] → JPEG. Null on any failure. */+    private fun gpuStitch(handle: Long): Pair<ByteArray, PanoInfo>? {+        val t0 = System.currentTimeMillis()+        val blob = StitchNative.estimate(handle) ?: return null+        val estimate = GpuStitcher.parseEstimate(blob) ?: return null+        val tReg = System.currentTimeMillis()+        val result = GpuStitcher.composite(estimate, capturedFrames) ?: return null+        val tComp = System.currentTimeMillis()++        val baos = ByteArrayOutputStream()+        val ok = result.bitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, baos)+        val cw = result.bitmap.width+        val ch = result.bitmap.height+        result.bitmap.recycle()+        if (!ok || cw <= 0 || ch <= 0) return null++        val info = PanoInfo(+            projectionType = if (sphereMode) "equirectangular" else "cylindrical",+            fullWidth = result.fullWidth,+            fullHeight = result.fullHeight,+            croppedWidth = cw,+            croppedHeight = ch,+            croppedLeft = result.croppedLeft,+            croppedTop = result.croppedTop,+        )+        android.util.Log.i(+            "PanoramaEngine",+            "GPU stitch: estimate=${tReg - t0}ms composite=${tComp - tReg}ms -> ${cw}x$ch"+        )+        return Pair(baos.toByteArray(), info)+    }++    /** CPU fallback: the full Rust stitcher. */+    private fun cpuStitch(handle: Long): Pair<ByteArray, PanoInfo>? {+        val jpeg = StitchNative.stitch(handle) ?: return null+        val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }+        BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size, opts)+        val w = opts.outWidth+        val h = opts.outHeight+        if (w <= 0 || h <= 0) return null+        val info = PanoInfo(+            projectionType = if (sphereMode) "equirectangular" else "cylindrical",+            fullWidth = w,+            fullHeight = h,+            croppedWidth = w,+            croppedHeight = h,+            croppedLeft = 0,+            croppedTop = 0,+        )+        return Pair(jpeg, info)+    }+     fun saveToMediaStore(jpeg: ByteArray, info: PanoInfo) {         val prefix = if (sphereMode) "SPHERE" else "PANO"         val contentValues = MediaStoreSaver.imageValues("${prefix}_${MediaStoreSaver.timestamp()}.jpg")@@ -239,12 +363,15 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {     fun reset() {         if (nativeHandle != 0L && StitchNative.isAvailable) StitchNative.free(nativeHandle)         nativeHandle = 0L+        capturedFrames.clear()         _frameCount.value = 0         _sweepAngle.value = 0f         _isSweeping.value = false         _isStitching.value = false         _currentAngle.value = 0f         _currentPitch.value = 0f+        _sweepDirection.value = 0+        _guideDots.value = emptyList()         accumulatedPitch = 0f         accumulatedRoll = 0f         pitchVelocity = 0f
camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt b/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.ktindex c39d7cef4f..5093c833ff 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt@@ -21,12 +21,20 @@ object StitchNative {     /** Opens a stitch session. [sphere] selects full-sphere vs flat panorama. */     external fun newSession(sphere: Boolean): Long -    /** Adds one RGBA frame (row-major, length = width*height*4) with its gyro orientation (degrees). */-    external fun addFrame(handle: Long, rgba: ByteArray, width: Int, height: Int, yaw: Float, pitch: Float, roll: Float)+    /** Adds one JPEG-compressed frame with its gyro orientation (degrees). Decoded on demand at stitch time. */+    external fun addFrame(handle: Long, jpeg: ByteArray, yaw: Float, pitch: Float, roll: Float)      /** Stitches the added frames into a panorama; returns JPEG bytes or null. Consumes the frames. */     external fun stitch(handle: Long): ByteArray? +    /**+     * Runs registration only (features/match/estimate/BA/wave) and returns a+     * compact binary blob describing the compose canvas + per-frame camera+     * solutions for the GPU compositor. Does NOT consume the frames, so a CPU+     * [stitch] fallback can still run. Returns null on failure.+     */+    external fun estimate(handle: Long): ByteArray?+     /** Aligns + merges the added frames (night mode); returns JPEG bytes or null. Consumes the frames. */     external fun merge(handle: Long): ByteArray?