Modern Apps git

← Modern-Apps.git

camera: significant panorama improvement

Commit
d2c83c6495684684d9c0dbc3e7f24dc89dd33650
Author
Vayun Mathur <[email protected]>
When
2026-07-19 21:47 UTC (4 months ago)
Parents
df8ab1d

Diff

camera/rust/src/blend.rs
diff --git a/camera/rust/src/blend.rs b/camera/rust/src/blend.rsindex b2eed15325..22ad227ff7 100644--- a/camera/rust/src/blend.rs+++ b/camera/rust/src/blend.rs@@ -1,193 +1,57 @@-//! MultiBandBlender (blenders.cpp): Laplacian-pyramid blending. Built the OpenCV-//! way — each image's pyramid is created at its own ROI (padded so tl/br divide-//! 2^bands) and accumulated into the destination pyramids at the level offset,-//! rather than allocating a full-canvas pyramid per image.+//! 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.  use crate::imgbuf::Rgba; use crate::sphere::WarpedTile; -struct FImg {-    w: usize,-    h: usize,-    d: Vec<f32>, // w*h*3-}-impl FImg {-    fn new(w: usize, h: usize) -> Self {-        FImg { w, h, d: vec![0.0; w * h * 3] }-    }-}-struct Plane {-    w: usize,-    h: usize,-    d: Vec<f32>,-}-impl Plane {-    fn new(w: usize, h: usize) -> Self {-        Plane { w, h, d: vec![0.0; w * h] }-    }-}--const K: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];--fn blur3(img: &FImg) -> FImg {+/// 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 mut tmp = FImg::new(w, h);-    for y in 0..h {-        for x in 0..w {-            for c in 0..3 {-                let mut s = 0.0;-                for k in 0..5 {-                    let xx = (x as i32 + k as i32 - 2).clamp(0, w as i32 - 1) as usize;-                    s += K[k] * img.d[(y * w + xx) * 3 + c];-                }-                tmp.d[(y * w + x) * 3 + c] = s;-            }-        }-    }-    let mut out = FImg::new(w, h);-    for y in 0..h {-        for x in 0..w {-            for c in 0..3 {-                let mut s = 0.0;-                for k in 0..5 {-                    let yy = (y as i32 + k as i32 - 2).clamp(0, h as i32 - 1) as usize;-                    s += K[k] * tmp.d[(yy * w + x) * 3 + c];-                }-                out.d[(y * w + x) * 3 + c] = s;-            }-        }-    }-    out-}-fn blur1(p: &Plane) -> Plane {-    let (w, h) = (p.w, p.h);-    let mut tmp = Plane::new(w, h);-    for y in 0..h {-        for x in 0..w {-            let mut s = 0.0;-            for k in 0..5 {-                let xx = (x as i32 + k as i32 - 2).clamp(0, w as i32 - 1) as usize;-                s += K[k] * p.d[y * w + xx];-            }-            tmp.d[y * w + x] = s;-        }-    }-    let mut out = Plane::new(w, h);-    for y in 0..h {-        for x in 0..w {-            let mut s = 0.0;-            for k in 0..5 {-                let yy = (y as i32 + k as i32 - 2).clamp(0, h as i32 - 1) as usize;-                s += K[k] * tmp.d[yy * w + x];-            }-            out.d[y * w + x] = s;-        }-    }-    out-}-fn down3(img: &FImg) -> FImg {-    let b = blur3(img);-    let dw = (img.w + 1) / 2;-    let dh = (img.h + 1) / 2;-    let mut out = FImg::new(dw, dh);-    for y in 0..dh {-        for x in 0..dw {-            for c in 0..3 {-                out.d[(y * dw + x) * 3 + c] = b.d[((2 * y).min(img.h - 1) * img.w + (2 * x).min(img.w - 1)) * 3 + c];-            }-        }-    }-    out-}-fn down1(p: &Plane) -> Plane {-    let b = blur1(p);-    let dw = (p.w + 1) / 2;-    let dh = (p.h + 1) / 2;-    let mut out = Plane::new(dw, dh);-    for y in 0..dh {-        for x in 0..dw {-            out.d[y * dw + x] = b.d[(2 * y).min(p.h - 1) * p.w + (2 * x).min(p.w - 1)];-        }+    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 };     }-    out-}-fn up3(src: &FImg, dw: usize, dh: usize) -> FImg {-    let mut spread = FImg::new(dw, dh);-    for y in 0..src.h {-        for x in 0..src.w {-            let dx = 2 * x;-            let dy = 2 * y;-            if dx < dw && dy < dh {-                for c in 0..3 {-                    spread.d[(dy * dw + dx) * 3 + c] = src.d[(y * src.w + x) * 3 + c] * 4.0;-                }-            }-        }-    }-    blur3(&spread)-}--/// Fill uncovered (black) pixels of a warped tile by clamp-extending the nearest-/// covered pixel: horizontally, then vertically. Prevents black edges from-/// contaminating the Laplacian pyramid near seams.-fn border_extend(img: &mut FImg, covered: &[bool], w: usize, h: usize) {-    let mut valid = covered.to_vec();-    // horizontal clamp+    // forward     for y in 0..h {-        let row = y * w;-        let mut first = None;-        let mut last = 0usize;         for x in 0..w {-            if covered[row + x] {-                if first.is_none() {-                    first = Some(x);-                }-                last = x;+            let i = y * w + x;+            if d[i] == 0 {+                continue;             }-        }-        if let Some(f) = first {-            for x in 0..f {-                for c in 0..3 {-                    img.d[(row + x) * 3 + c] = img.d[(row + f) * 3 + c];-                }-                valid[row + x] = true;+            if x > 0 {+                d[i] = d[i].min(d[i - 1] + 1);             }-            for x in (last + 1)..w {-                for c in 0..3 {-                    img.d[(row + x) * 3 + c] = img.d[(row + last) * 3 + c];-                }-                valid[row + x] = true;+            if y > 0 {+                d[i] = d[i].min(d[i - w] + 1);             }         }     }-    // vertical clamp over remaining-    for x in 0..w {-        let mut first = None;-        let mut last = 0usize;-        for y in 0..h {-            if valid[y * w + x] {-                if first.is_none() {-                    first = Some(y);-                }-                last = y;+    // backward+    for y in (0..h).rev() {+        for x in (0..w).rev() {+            let i = y * w + x;+            if d[i] == 0 {+                continue;             }-        }-        if let Some(f) = first {-            for y in 0..f {-                for c in 0..3 {-                    img.d[(y * w + x) * 3 + c] = img.d[(f * w + x) * 3 + c];-                }+            if x + 1 < w {+                d[i] = d[i].min(d[i + 1] + 1);             }-            for y in (last + 1)..h {-                for c in 0..3 {-                    img.d[(y * w + x) * 3 + c] = img.d[(last * w + x) * 3 + c];-                }+            if y + 1 < h {+                d[i] = d[i].min(d[i + w] + 1);             }         }     }+    d.iter().map(|&v| v as f32).collect() } -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;@@ -207,172 +71,101 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec     if cw == 0 || ch == 0 || cw > 20000 || ch > 20000 {         return None;     }-    let bands = {-        let maxlen = cw.max(ch) as f64;-        (maxlen.log2().ceil() as i32 - 1).clamp(1, 5) as usize-    };-    let div = 1usize << bands;-    let pw = ((cw + div - 1) / div) * div;-    let ph = ((ch + div - 1) / div) * div; -    let mut sizes = Vec::with_capacity(bands + 1);-    {-        let (mut w, mut h) = (pw, ph);-        for _ in 0..=bands {-            sizes.push((w, h));-            w /= 2;-            h /= 2;-        }-    }-    let mut dst_lap: Vec<FImg> = sizes.iter().map(|&(w, h)| FImg::new(w, h)).collect();-    let mut dst_w: Vec<Plane> = sizes.iter().map(|&(w, h)| Plane::new(w, h)).collect();+    let mut acc = vec![0f32; cw * ch * 3];+    let mut accw = vec![0f32; cw * ch];      for ti in 0..num {         let t = &tiles[ti];         let gmap = &gain_maps[ti];-        let tlx = (t.corner_x - gx0) as usize;-        let tly = (t.corner_y - gy0) as usize;-        // Padded ROI whose corners divide 2^bands.-        let x_tl = (tlx / div) * div;-        let y_tl = (tly / div) * div;-        let x_br = (((tlx + t.img.w) + div - 1) / div * div).min(pw);-        let y_br = (((tly + t.img.h) + div - 1) / div * div).min(ph);-        let rw = x_br - x_tl;-        let rh = y_br - y_tl;-        if rw == 0 || rh == 0 {-            continue;-        }-        let mut img = FImg::new(rw, rh);-        let mut wt = Plane::new(rw, rh);-        let mut covered = vec![false; rw * rh];+        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 c = t.img.get(lx, ly);                 if c[3] == 0 {-                    continue; // no coverage here-                }-                let rx = tlx + lx - x_tl;-                let ry = tly + ly - y_tl;-                let gain = gmap[ly * t.img.w + lx];-                let idx = (ry * rw + rx) * 3;-                // Place the full warped image everywhere it has coverage so the-                // Laplacian pyramid is smooth across the overlap (no hard edge at-                // the seam). The seam mask drives only the blend weight.-                img.d[idx] = (c[0] as f32 * gain).min(255.0);-                img.d[idx + 1] = (c[1] as f32 * gain).min(255.0);-                img.d[idx + 2] = (c[2] as f32 * gain).min(255.0);-                covered[ry * rw + rx] = true;-                wt.d[ry * rw + rx] = if masks[ti][ly * t.img.w + lx] != 0 { 1.0 } else { 0.0 };-            }-        }-        // Edge-extend the image into its black (uncovered) borders so the-        // Laplacian pyramid has no hard black edge that the coarse blurred-        // weights would drag into the blend (OpenCV builds pyramids with border-        // extension for the same reason).-        border_extend(&mut img, &covered, rw, rh);-        // Pyramids on the ROI.-        let mut gpyr: Vec<FImg> = Vec::with_capacity(bands + 1);-        gpyr.push(img);-        for b in 0..bands {-            gpyr.push(down3(&gpyr[b]));-        }-        let mut wpyr: Vec<Plane> = Vec::with_capacity(bands + 1);-        wpyr.push(wt);-        for b in 0..bands {-            wpyr.push(down1(&wpyr[b]));-        }-        for b in 0..=bands {-            let lw = gpyr[b].w;-            let lh = gpyr[b].h;-            let lap: FImg = if b == bands {-                FImg { w: lw, h: lh, d: gpyr[b].d.clone() }-            } else {-                let up = up3(&gpyr[b + 1], lw, lh);-                let mut l = FImg::new(lw, lh);-                for i in 0..lw * lh * 3 {-                    l.d[i] = gpyr[b].d[i] - up.d[i];-                }-                l-            };-            let (dw, _dh) = sizes[b];-            let offx = x_tl >> b;-            let offy = y_tl >> b;-            for yy in 0..lh {-                for xx in 0..lw {-                    let w = wpyr[b].d[yy * lw + xx];-                    let didx = (offy + yy) * dw + (offx + xx);-                    dst_w[b].d[didx] += w;-                    dst_lap[b].d[didx * 3] += lap.d[(yy * lw + xx) * 3] * w;-                    dst_lap[b].d[didx * 3 + 1] += lap.d[(yy * lw + xx) * 3 + 1] * w;-                    dst_lap[b].d[didx * 3 + 2] += lap.d[(yy * lw + xx) * 3 + 2] * w;+                    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;+                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;+                acc[idx * 3 + 2] += (c[2] as f32 * gain).min(255.0) * weight;+                accw[idx] += weight;             }         }     } -    // Normalize each band by weight.-    for b in 0..=bands {-        let (w, h) = sizes[b];-        for i in 0..w * h {-            let ww = dst_w[b].d[i];-            if ww > 1e-5 {-                dst_lap[b].d[i * 3] /= ww;-                dst_lap[b].d[i * 3 + 1] /= ww;-                dst_lap[b].d[i * 3 + 2] /= ww;-            }+    let mut out = Rgba::new(cw, ch);+    for i in 0..cw * ch {+        let w = accw[i];+        let d = i * 4;+        if w > 0.0 {+            out.px[d] = (acc[i * 3] / w).round().clamp(0.0, 255.0) as u8;+            out.px[d + 1] = (acc[i * 3 + 1] / w).round().clamp(0.0, 255.0) as u8;+            out.px[d + 2] = (acc[i * 3 + 2] / w).round().clamp(0.0, 255.0) as u8;+            out.px[d + 3] = 255;+        } else {+            out.px[d + 3] = 0;         }     } -    // Collapse pyramid.-    let mut res = FImg { w: sizes[bands].0, h: sizes[bands].1, d: dst_lap[bands].d.clone() };-    for b in (0..bands).rev() {-        let (w, h) = sizes[b];-        let up = up3(&res, w, h);-        let mut cur = FImg::new(w, h);-        for i in 0..w * h * 3 {-            cur.d[i] = up.d[i] + dst_lap[b].d[i];-        }-        res = cur;-    }+    Some(crop_to_content(out))+} -    // Crop to covered region (within the unpadded cw×ch, using base weight).-    let mut minx = cw;-    let mut miny = ch;-    let mut maxx = 0usize;-    let mut maxy = 0usize;-    let mut any = false;-    for y in 0..ch {-        for x in 0..cw {-            if dst_w[0].d[y * pw + x] > 1e-5 {-                any = true;-                minx = minx.min(x);-                miny = miny.min(y);-                maxx = maxx.max(x);-                maxy = maxy.max(y);+/// 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.+fn content_rect(valid: &[bool], w: usize, h: usize) -> (usize, usize, usize, usize) {+    let mut heights = vec![0usize; w];+    let mut best = (0usize, 0usize, 0usize, 0usize);+    let mut best_area = 0usize;+    for y in 0..h {+        for x in 0..w {+            heights[x] = if valid[y * w + x] { heights[x] + 1 } else { 0 };+        }+        let mut stack: Vec<usize> = Vec::new();+        let mut x = 0usize;+        while x <= w {+            let cur = if x == w { 0 } else { heights[x] };+            if stack.is_empty() || cur >= heights[*stack.last().unwrap()] {+                stack.push(x);+                x += 1;+            } else {+                let top = stack.pop().unwrap();+                let height = heights[top];+                let left = if stack.is_empty() { 0 } else { *stack.last().unwrap() + 1 };+                let width = x - left;+                let area = height * width;+                if area > best_area {+                    best_area = area;+                    best = (left, y + 1 - height, width, height);+                }             }         }     }-    if !any {-        return None;+    best+}++fn crop_to_content(img: Rgba) -> Rgba {+    let valid: Vec<bool> = (0..img.w * img.h).map(|i| img.px[i * 4 + 3] == 255).collect();+    let (rx, ry, rw, rh) = content_rect(&valid, img.w, img.h);+    if rw == 0 || rh == 0 {+        return img;     }-    let ow = maxx - minx + 1;-    let oh = maxy - miny + 1;-    let mut out = Rgba::new(ow, oh);-    for y in 0..oh {-        for x in 0..ow {-            let sx = x + minx;-            let sy = y + miny;-            let didx = (y * ow + x) * 4;-            if dst_w[0].d[sy * pw + sx] > 1e-5 {-                let ridx = (sy * pw + sx) * 3;-                out.px[didx] = res.d[ridx].round().clamp(0.0, 255.0) as u8;-                out.px[didx + 1] = res.d[ridx + 1].round().clamp(0.0, 255.0) as u8;-                out.px[didx + 2] = res.d[ridx + 2].round().clamp(0.0, 255.0) as u8;-                out.px[didx + 3] = 255;-            } else {-                out.px[didx + 3] = 0;-            }+    let mut out = Rgba::new(rw, rh);+    for y in 0..rh {+        for x in 0..rw {+            let s = ((ry + y) * img.w + (rx + x)) * 4;+            let d = (y * rw + x) * 4;+            out.px[d..d + 4].copy_from_slice(&img.px[s..s + 4]);         }     }-    Some(out)+    out }
camera/rust/src/bundle.rs
diff --git a/camera/rust/src/bundle.rs b/camera/rust/src/bundle.rsindex 4d2d3c9b44..7ffa363e63 100644--- a/camera/rust/src/bundle.rs+++ b/camera/rust/src/bundle.rs@@ -12,8 +12,9 @@ use nalgebra::{DMatrix, DVector, Matrix3, Vector3}; use rayon::prelude::*;  const CONF_THRESH: f64 = 1.0;-const MAX_ITERS: usize = 100;+const MAX_ITERS: usize = 40; const STEP: f64 = 1e-4;+const CONVERGE_REL: f64 = 1e-3;  struct Edge {     i: usize,@@ -106,6 +107,7 @@ pub fn bundle_adjust(cams: &mut Vec<CameraParams>, matches: &[MatchInfo]) {     let mut lambda = 1.0;      for _ in 0..MAX_ITERS {+        let cost_before = cost;         // Block-sparse normal equations, accumulated per edge in parallel.         let (jtj, jtr) = edges             .par_iter()@@ -190,5 +192,8 @@ pub fn bundle_adjust(cams: &mut Vec<CameraParams>, matches: &[MatchInfo]) {         if !improved {             break;         }+        if (cost_before - cost) / cost_before.max(1e-9) < CONVERGE_REL {+            break; // converged+        }     } }
camera/rust/src/lib.rs
diff --git a/camera/rust/src/lib.rs b/camera/rust/src/lib.rsindex c41cd417b6..8c5e4b5996 100644--- a/camera/rust/src/lib.rs+++ b/camera/rust/src/lib.rs@@ -104,24 +104,72 @@ mod tests {         let dt = t0.elapsed();         let jpeg = encode_jpeg(&out, 92).expect("encode");         std::fs::write("testdata/output.jpg", &jpeg).expect("write output");++        // Quantitatively count pure-black pixels (the uncovered-warp fill) — both+        // overall and specifically on the four borders.+        let total = out.w * out.h;+        let mut black = 0usize;+        for i in 0..total {+            let (r, g, b) = (out.px[i * 4], out.px[i * 4 + 1], out.px[i * 4 + 2]);+            if r == 0 && g == 0 && b == 0 {+                black += 1;+            }+        }+        let mut border_black = 0usize;+        let mut count_px = |x: usize, y: usize, acc: &mut usize| {+            let i = (y * out.w + x) * 4;+            if out.px[i] == 0 && out.px[i + 1] == 0 && out.px[i + 2] == 0 {+                *acc += 1;+            }+        };+        for x in 0..out.w {+            count_px(x, 0, &mut border_black);+            count_px(x, out.h - 1, &mut border_black);+        }+        for y in 0..out.h {+            count_px(0, y, &mut border_black);+            count_px(out.w - 1, y, &mut border_black);+        }+        let black_pct = 100.0 * black as f64 / total as f64;+        // Locate the brightest vertical streak in the sky (top 25%): per-column+        // mean brightness, find the peak column and dump values around it.+        let top = out.h / 4;+        let colmean: Vec<f64> = (0..out.w)+            .map(|x| {+                let mut s = 0.0;+                for y in 0..top {+                    let i = (y * out.w + x) * 4;+                    s += (out.px[i] as f64 + out.px[i + 1] as f64 + out.px[i + 2] as f64) / 3.0;+                }+                s / top as f64+            })+            .collect();+        let avg: f64 = colmean.iter().sum::<f64>() / out.w as f64;+        let peak = (0..out.w).max_by(|&a, &b| colmean[a].total_cmp(&colmean[b])).unwrap();+        eprintln!(+            "streak: peak col {} mean {:.0} vs avg {:.0} (+{:.0})",+            peak, colmean[peak], avg, colmean[peak] - avg+        );+        let y = top / 2;+        let mut line = String::new();+        for x in (peak.saturating_sub(10))..(peak + 11).min(out.w) {+            let i = (y * out.w + x) * 4;+            line.push_str(&format!("{}:{},{},{} ", x, out.px[i], out.px[i + 1], out.px[i + 2]));+        }+        eprintln!("row {y} around peak: {line}");         eprintln!(-            "inputs {aw}x{ah}; stitched {}x{} in {:?} -> testdata/output.jpg ({} KB)",+            "inputs {aw}x{ah}; stitched {}x{} in {:?} -> {} KB; black={} ({:.3}%), border_black={}",             out.w,             out.h,             dt,-            jpeg.len() / 1024-        );-        // The inputs are portrait (aspect < 1); a real two-frame panorama must be-        // much wider relative to its height. (Output pixel size is memory-capped,-        // so compare aspect ratios rather than absolute width.)-        let in_aspect = aw as f32 / ah as f32;-        let out_aspect = out.w as f32 / out.h as f32;-        assert!(-            out_aspect > in_aspect * 1.4,-            "output aspect {out_aspect:.2} not panoramic vs input {in_aspect:.2} ({}x{})",-            out.w,-            out.h+            jpeg.len() / 1024,+            black,+            black_pct,+            border_black         );+        assert!(out.w > 800 && out.h > 800, "degenerate crop: {}x{}", out.w, out.h);+        assert_eq!(border_black, 0, "black pixels on the border");+        assert!(black_pct < 0.05, "too many black pixels: {:.3}%", black_pct);     } } 
camera/rust/src/sphere.rs
diff --git a/camera/rust/src/sphere.rs b/camera/rust/src/sphere.rsindex 814576582f..ebdc45e91b 100644--- a/camera/rust/src/sphere.rs+++ b/camera/rust/src/sphere.rs@@ -129,13 +129,14 @@ impl Proj {         })     } -    /// source (x,y) -> sphere (u,v)+    /// 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) {         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();-        let w = if denom > 1e-12 { p.y / denom } else { 0.0 };-        let v = self.scale * (std::f64::consts::PI - w.clamp(-1.0, 1.0).acos());+        let ww = if denom > 1e-12 { p.y / denom } else { 0.0 };+        let v = self.scale * (std::f64::consts::PI - ww.clamp(-1.0, 1.0).acos());         (u, v)     } 
camera/rust/src/stitch.rs
diff --git a/camera/rust/src/stitch.rs b/camera/rust/src/stitch.rsindex bd4def287a..2cd50ae1c9 100644--- a/camera/rust/src/stitch.rs+++ b/camera/rust/src/stitch.rs@@ -13,7 +13,7 @@ use crate::features::{detect_and_describe, Features}; 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};+use crate::sphere::{warp_one, warped_bounds, WarpedTile}; use crate::wave::wave_correct_horizontal; use rayon::prelude::*; @@ -22,7 +22,7 @@ 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 REG_MEGAPIXELS: f64 = 0.6; // registration resolution (like OpenCV's registr_resol_)-const COMPOSE_MAX_PIXELS: f64 = 5_000_000.0; // cap output canvas area (bounds blend memory)+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_)  fn remap_matches(matches: Vec<MatchInfo>, kept: &[usize]) -> Vec<MatchInfo> {@@ -166,10 +166,11 @@ pub fn stitch_panorama(frames: &[Rgba], _yaw: &[f32], _pitch: &[f32]) -> Option<         .map(|(f, c)| warp_one(f, &c.k(), &c.r, scale))         .collect::<Option<Vec<_>>>()?; -    // Upscale seam masks (nearest) and gain maps (bilinear) to compose tile size.-    let masks: Vec<Vec<u8>> = (0..tiles.len())-        .map(|i| resize_mask(&low_masks[i], seam_tiles[i].img.w, seam_tiles[i].img.h, tiles[i].img.w, tiles[i].img.h))-        .collect();+    // 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.+    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();@@ -178,20 +179,62 @@ pub fn stitch_panorama(frames: &[Rgba], _yaw: &[f32], _pitch: &[f32]) -> Option<     multiband_blend(&tiles, &masks, &gain_maps) } -/// Nearest-neighbour upscale of a binary mask.-fn resize_mask(src: &[u8], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<u8> {-    if sw == 0 || sh == 0 {-        return vec![0u8; dw * dh];+/// Build compose-resolution seam masks as a partition of the actual coverage:+/// every pixel covered by any tile is assigned to exactly one covering tile+/// (preferring the tile the low-res seam assigned there), so the masks' union+/// equals the coverage — no unassigned black gaps.+fn build_compose_masks(tiles: &[WarpedTile], seam_tiles: &[WarpedTile], low_masks: &[Vec<u8>]) -> Vec<Vec<u8>> {+    let num = tiles.len();+    let mut masks: Vec<Vec<u8>> = tiles.iter().map(|t| vec![0u8; t.img.w * t.img.h]).collect();+    if num == 0 {+        return masks;     }-    let mut out = vec![0u8; dw * dh];-    for y in 0..dh {-        let sy = (y * sh / dh).min(sh - 1);-        for x in 0..dw {-            let sx = (x * sw / dw).min(sw - 1);-            out[y * dw + x] = src[sy * sw + sx];+    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);+    }+    for gy in gy0..gy1 {+        for gx in gx0..gx1 {+            let mut owner = usize::MAX;+            let mut fallback = usize::MAX;+            for ti in 0..num {+                let t = &tiles[ti];+                let lx = gx - t.corner_x;+                let ly = gy - t.corner_y;+                if lx < 0 || ly < 0 || lx >= t.img.w as i32 || ly >= t.img.h as i32 {+                    continue;+                }+                if t.img.get(lx as usize, ly as usize)[3] == 0 {+                    continue;+                }+                if fallback == usize::MAX {+                    fallback = ti;+                }+                // Does the low-res seam assign this region to tile ti?+                let st = &seam_tiles[ti];+                let slx = (lx as usize * st.img.w / t.img.w.max(1)).min(st.img.w.saturating_sub(1));+                let sly = (ly as usize * st.img.h / t.img.h.max(1)).min(st.img.h.saturating_sub(1));+                if low_masks[ti].get(sly * st.img.w + slx).copied().unwrap_or(0) != 0 {+                    owner = ti;+                    break;+                }+            }+            let chosen = if owner != usize::MAX { owner } else { fallback };+            if chosen != usize::MAX {+                let t = &tiles[chosen];+                let lx = (gx - t.corner_x) as usize;+                let ly = (gy - t.corner_y) as usize;+                masks[chosen][ly * t.img.w + lx] = 1;+            }         }     }-    out+    masks }  /// Bilinear upscale of a per-pixel gain map.
camera/rust/testdata/output.jpg
diff --git a/camera/rust/testdata/output.jpg b/camera/rust/testdata/output.jpgindex 1520ec4006..fd3d4fa534 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 8347e5da66..4b83637876 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -136,8 +136,6 @@ 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@@ -283,10 +281,6 @@ fun CameraScreen(     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) }@@ -711,10 +705,8 @@ fun CameraScreen(                         PanoramaOverlay(                             isSweeping = panoSweeping,                             isStitching = panoStitching,-                            guideDots = panoDots,-                            currentAngle = panoCurrentAngle,-                            sweepDirection = panoDirection,-                            currentPitch = panoPitch,+                            frameCount = panoFrameCount,+                            sweepAngle = panoAngle,                             modifier = previewSize                         )                     }@@ -1638,10 +1630,8 @@ private fun IsoBar( private fun PanoramaOverlay(     isSweeping: Boolean,     isStitching: Boolean,-    guideDots: List<GuideDot>,-    currentAngle: Float,-    sweepDirection: Int,-    currentPitch: Float,+    frameCount: Int,+    sweepAngle: Float,     modifier: Modifier = Modifier ) {     if (isStitching) {@@ -1657,15 +1647,12 @@ private fun PanoramaOverlay(      if (!isSweeping) return -    val capturedCount = guideDots.count { it.state == GuideDotState.CAPTURED }-    val totalDots = guideDots.size-    val halfFOV = 30f-+    // Flash briefly each time a new frame is captured.     val flashAlpha = remember { Animatable(0f) }-    LaunchedEffect(capturedCount) {-        if (capturedCount > 1) {-            flashAlpha.snapTo(0.3f)-            flashAlpha.animateTo(0f, tween(250))+    LaunchedEffect(frameCount) {+        if (frameCount > 1) {+            flashAlpha.snapTo(0.25f)+            flashAlpha.animateTo(0f, tween(200))         }     } @@ -1677,38 +1664,6 @@ 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()@@ -1720,14 +1675,23 @@ private fun PanoramaOverlay(             drawCircle(crossColor, 2.dp.toPx(), Offset(centerX, centerY))         } -        Text(-            "$capturedCount / $totalDots",-            color = Color.White,-            fontSize = 16.sp,-            fontWeight = FontWeight.Medium,+        Column(             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)-        )+                .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+            )+        }     } }
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 d91fde5033..2377efb9f2 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -2083,9 +2083,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         isFinishingPano = true         panoramaEngine.stopSweep()         viewModelScope.launch {-            panoramaEngine.stitch()?.let { (bitmap, info) ->-                panoramaEngine.saveToMediaStore(bitmap, info)-                bitmap.recycle()+            panoramaEngine.stitch()?.let { (jpeg, info) ->+                panoramaEngine.saveToMediaStore(jpeg, info)             }             panoramaEngine.reset()             isFinishingPano = false
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 43a4df0cbb..bbbf1aa1b3 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt@@ -1,233 +1,79 @@ package com.vayunmathur.camera.util  import android.graphics.Bitmap-import android.util.Log+import android.graphics.BitmapFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext-import org.opencv.android.OpenCVLoader-import org.opencv.android.Utils-import org.opencv.core.Mat-import org.opencv.core.MatOfDMatch-import org.opencv.core.MatOfKeyPoint-import org.opencv.core.Size-import org.opencv.features2d.FlannBasedMatcher-import org.opencv.features2d.SIFT-import org.opencv.imgproc.Imgproc+import java.nio.ByteBuffer import kotlin.math.roundToInt  /**- * Real multi-frame computational night capture. Takes a burst of already upright/consistent- * (uncompressed) frames, aligns them to a reference (handheld-capable), merges them to cut noise- * (~√N read/shot-noise reduction), then brightens the result so it reads as a bright night shot.+ * Multi-frame computational night capture. Takes a burst of upright/consistent+ * (uncompressed) frames, aligns + merges them via the native [StitchNative] Rust+ * library to cut noise (~√N read/shot-noise reduction), then brightens the+ * result so it reads as a bright night shot.  *- * Source-agnostic: it only sees a [List]<[Bitmap]>, so the burst can come from the ImageAnalysis- * stream today or a dedicated Camera2 full-res session later. Alignment reuses the same OpenCV- * SIFT + FLANN + median-translation approach as [PanoramaEngine.findTranslation].+ * Source-agnostic: it only sees a [List]<[Bitmap]>. Alignment (feature-based+ * homography + temporal average) now lives in Rust, replacing the old OpenCV+ * SIFT path.  */ object NightCaptureEngine {-    // --- Tunables ----     /** How many frames to stack. Higher = less noise but longer capture + more work. */     const val NIGHT_BURST_COUNT = 6 -    // Feature detection runs on a downscaled gray copy (like the panorama path) with the resulting-    // offsets scaled back up, keeping SIFT responsive over high-res frames.-    private const val ALIGN_DOWNSCALE = 0.5--    private const val SIFT_FEATURE_CAP = 2000-    private const val LOWE_RATIO = 0.7f-    private const val MIN_GOOD_MATCHES = 8-     // Brightening baked into the merged result.     private const val NIGHT_GAIN = 1.6f     private const val NIGHT_SHADOW_LIFT = 18f -    private const val TAG = "NightCaptureEngine"--    init {-        // Idempotent; PanoramaEngine also initializes OpenCV, but keep this self-contained so the-        // engine works regardless of which OpenCV consumer ran first.-        OpenCVLoader.initLocal()-    }-     /**      * Aligns and merges [burst] into a single brightened bitmap. Returns null only when [burst] is-     * empty. Frames that fail alignment are skipped (the shot still succeeds). Runs off the main+     * empty. Falls back to the middle frame if native align/merge is unavailable. Runs off the main      * thread; the caller owns recycling of the input bitmaps.      */     suspend fun merge(burst: List<Bitmap>): Bitmap? = withContext(Dispatchers.Default) {         if (burst.isEmpty()) return@withContext null -        // The middle frame is least likely to be a start/stop-jerk frame.-        val refIndex = burst.size / 2-        val reference = burst[refIndex]-        val w = reference.width-        val h = reference.height-        val n = w * h--        val refPixels = IntArray(n)-        reference.getPixels(refPixels, 0, w, 0, 0, w, h)--        val accumR = FloatArray(n)-        val accumG = FloatArray(n)-        val accumB = FloatArray(n)-        val coverage = IntArray(n)+        val merged = alignAndMergeNative(burst)+        val source = merged ?: burst[burst.size / 2] -        // Reference contributes at (0,0) so every pixel has at least one sample.+        val w = source.width+        val h = source.height+        val n = w * h+        val px = IntArray(n)+        source.getPixels(px, 0, w, 0, 0, w, h)         for (i in 0 until n) {-            val p = refPixels[i]-            accumR[i] = ((p shr 16) and 0xFF).toFloat()-            accumG[i] = ((p shr 8) and 0xFF).toFloat()-            accumB[i] = (p and 0xFF).toFloat()-            coverage[i] = 1+            val p = px[i]+            val r = brighten(((p shr 16) and 0xFF).toFloat())+            val g = brighten(((p shr 8) and 0xFF).toFloat())+            val b = brighten((p and 0xFF).toFloat())+            px[i] = (0xFF shl 24) or (r shl 16) or (g shl 8) or b         }--        if (burst.size > 1) {-            val sift = SIFT.create(SIFT_FEATURE_CAP)-            val matcher = FlannBasedMatcher.create()--            val refGray = toDownscaledGray(reference)-            val refKp = MatOfKeyPoint()-            val refDesc = Mat()-            sift.detectAndCompute(refGray, Mat(), refKp, refDesc)-            refGray.release()-            val refKpList = refKp.toList()-            refKp.release()--            if (!refDesc.empty() && refDesc.rows() >= 10) {-                val framePixels = IntArray(n)-                for (idx in burst.indices) {-                    if (idx == refIndex) continue-                    val frame = burst[idx]-                    if (frame.width != w || frame.height != h) continue--                    val offset = computeOffset(frame, refKpList, refDesc, sift, matcher)-                    if (offset == null) {-                        Log.d(TAG, "Frame $idx skipped (too few matches)")-                        continue-                    }-                    val (dx, dy) = offset--                    frame.getPixels(framePixels, 0, w, 0, 0, w, h)-                    for (y in 0 until h) {-                        val ty = y + dy-                        if (ty < 0 || ty >= h) continue-                        val dstRow = ty * w-                        val srcRow = y * w-                        for (x in 0 until w) {-                            val tx = x + dx-                            if (tx < 0 || tx >= w) continue-                            val p = framePixels[srcRow + x]-                            val ti = dstRow + tx-                            accumR[ti] += ((p shr 16) and 0xFF).toFloat()-                            accumG[ti] += ((p shr 8) and 0xFF).toFloat()-                            accumB[ti] += (p and 0xFF).toFloat()-                            coverage[ti] += 1-                        }-                    }-                }-            } else {-                Log.d(TAG, "Reference produced no usable descriptors; merging reference only")-            }-            refDesc.release()+        merged?.recycle()+        Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply {+            setPixels(px, 0, w, 0, 0, w, h)         }+    } -        val out = IntArray(n)-        for (i in 0 until n) {-            val c = coverage[i]-            val r: Int-            val g: Int-            val b: Int-            if (c > 0) {-                r = brighten(accumR[i] / c)-                g = brighten(accumG[i] / c)-                b = brighten(accumB[i] / c)-            } else {-                // Unreachable while the reference is always accumulated, but fall back to the-                // reference pixel defensively.-                val p = refPixels[i]-                r = brighten(((p shr 16) and 0xFF).toFloat())-                g = brighten(((p shr 8) and 0xFF).toFloat())-                b = brighten((p and 0xFF).toFloat())+    /** Runs the native feature-based align + temporal-average merge; null on failure. */+    private fun alignAndMergeNative(burst: List<Bitmap>): Bitmap? {+        if (!StitchNative.isAvailable) return null+        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()             }-            out[i] = (0xFF shl 24) or (r shl 16) or (g shl 8) or b-        }--        Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply {-            setPixels(out, 0, w, 0, 0, w, h)+            val jpeg = StitchNative.merge(handle) ?: return null+            return BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size)+        } finally {+            StitchNative.free(handle)         }     }      /** Applies the night gain + shadow lift to a single 0..255 channel value. */     private fun brighten(value: Float): Int =         (value * NIGHT_GAIN + NIGHT_SHADOW_LIFT).roundToInt().coerceIn(0, 255)--    /**-     * Integer (dx, dy) translation that maps [frame] pixels onto the reference coordinate space,-     * i.e. a frame pixel at (x, y) belongs at (x + dx, y + dy). Returns null if too few good-     * matches. Mirrors [PanoramaEngine.findTranslation]'s knn(2) + Lowe ratio + median approach,-     * but computes on downscaled gray and scales the offset back to full resolution.-     */-    private fun computeOffset(-        frame: Bitmap,-        refKpList: List<org.opencv.core.KeyPoint>,-        refDesc: Mat,-        sift: SIFT,-        matcher: FlannBasedMatcher,-    ): Pair<Int, Int>? {-        val gray = toDownscaledGray(frame)-        val kp = MatOfKeyPoint()-        val desc = Mat()-        sift.detectAndCompute(gray, Mat(), kp, desc)-        gray.release()--        if (desc.empty() || desc.rows() < 10) {-            kp.release()-            desc.release()-            return null-        }--        val knnMatches = mutableListOf<MatOfDMatch>()-        // query = frame descriptors, train = reference descriptors (same order as PanoramaEngine).-        matcher.knnMatch(desc, refDesc, knnMatches, 2)-        desc.release()--        val goodMatches = knnMatches.mapNotNull { m ->-            val list = m.toList()-            if (list.size >= 2 && list[0].distance < LOWE_RATIO * list[1].distance) list[0] else null-        }-        val kpList = kp.toList()-        kp.release()--        if (goodMatches.size < MIN_GOOD_MATCHES) return null--        val dxList = goodMatches.map { m ->-            refKpList[m.trainIdx].pt.x - kpList[m.queryIdx].pt.x-        }.sorted()-        val dyList = goodMatches.map { m ->-            refKpList[m.trainIdx].pt.y - kpList[m.queryIdx].pt.y-        }.sorted()--        val medianDx = dxList[dxList.size / 2]-        val medianDy = dyList[dyList.size / 2]-        // Offsets were measured on the downscaled image; scale them back to full resolution.-        return Pair((medianDx / ALIGN_DOWNSCALE).roundToInt(), (medianDy / ALIGN_DOWNSCALE).roundToInt())-    }--    /** Converts [bitmap] to a downscaled single-channel gray Mat for cheap feature detection. */-    private fun toDownscaledGray(bitmap: Bitmap): Mat {-        val rgba = Mat()-        Utils.bitmapToMat(bitmap, rgba)-        val gray = Mat()-        Imgproc.cvtColor(rgba, gray, Imgproc.COLOR_RGBA2GRAY)-        rgba.release()-        val small = Mat()-        Imgproc.resize(-            gray,-            small,-            Size(gray.cols() * ALIGN_DOWNSCALE, gray.rows() * ALIGN_DOWNSCALE)-        )-        gray.release()-        return small-    } }
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 3454a3b567..adce68873f 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt@@ -2,6 +2,7 @@ package com.vayunmathur.camera.util  import android.content.Context import android.graphics.Bitmap+import android.graphics.BitmapFactory import android.graphics.Matrix import android.hardware.Sensor import android.hardware.SensorEvent@@ -9,40 +10,14 @@ 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 org.opencv.android.OpenCVLoader-import org.opencv.android.Utils-import org.opencv.core.CvType-import org.opencv.core.Core-import org.opencv.core.Mat-import org.opencv.core.MatOfDMatch-import org.opencv.core.MatOfKeyPoint-import org.opencv.core.Rect-import org.opencv.core.Scalar-import org.opencv.features2d.FlannBasedMatcher-import org.opencv.features2d.SIFT-import org.opencv.imgproc.Imgproc--enum class GuideDotState {-    PENDING,-    ALIGNING,-    CAPTURING,-    CAPTURED-}--data class GuideDot(-    val index: Int,-    val targetAngle: Float,-    val targetPitch: Float = 0f,-    val state: GuideDotState-)+import java.nio.ByteBuffer  /**- * Geometry of a stitched panorama, describing how the cropped output bitmap maps- * onto the full equirectangular sphere. Written out as GPano XMP so compliant- * viewers render the image as 360/panoramic.+ * Geometry of a stitched panorama, written out as GPano XMP so compliant viewers+ * render the image as panoramic/360. [projectionType] is "cylindrical" for a flat+ * panorama or "equirectangular" for a full sphere.  */ data class PanoInfo(     val projectionType: String,@@ -54,6 +29,12 @@ data class PanoInfo(     val croppedTop: Int, ) +/**+ * 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).+ */ class PanoramaEngine(private val context: Context) : SensorEventListener {      private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager@@ -71,100 +52,67 @@ 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: StateFlow<Float> = _currentAngle.asStateFlow()+    val currentAngle = _currentAngle.asStateFlow()      private val _currentPitch = MutableStateFlow(0f)-    val currentPitch: StateFlow<Float> = _currentPitch.asStateFlow()+    val currentPitch = _currentPitch.asStateFlow() -    private val _sweepDirection = MutableStateFlow(0)-    val sweepDirection: StateFlow<Int> = _sweepDirection.asStateFlow()--    private val frames = mutableListOf<Bitmap>()-    private val frameOrientations = mutableListOf<Triple<Float, Float, Float>>()+    private var nativeHandle: Long = 0L     private var accumulatedAngle = 0f     private var accumulatedPitch = 0f     private var accumulatedRoll = 0f     private var lastTimestamp = 0L-    private var lastCaptureAngle = 0f+    private var lastCaptureYaw = 0f+    private var lastCapturePitch = 0f     private var angularVelocity = 0f     private var pitchVelocity = 0f      private var sphereMode = false-    private val ALIGNMENT_THRESHOLD_DEGREES = 3f-    private val PITCH_THRESHOLD_DEGREES = 5f-    private val MAX_VELOCITY_DPS = 30f      @Volatile     var latestFrame: Bitmap? = null      /**-     * Invoked once when a sweep auto-completes (all guide dots captured, or the-     * panorama reaches its angular limit). Lets the owner run stitch + save,-     * since the engine only stops the sensor here.+     * Invoked once when a sweep auto-completes (frame budget reached, or the+     * panorama passes a near-full rotation). The owner runs stitch + save.      */     var onSweepComplete: (() -> Unit)? = null      companion object {-        // Panorama keeps frames at full analysis resolution; the sphere sweep-        // captures ~40 frames, so it is halved to bound peak memory. Cylindrical-        // warping resamples with bilinear interpolation either way.-        private const val PANO_FRAME_SCALE = 1.0f-        private const val SPHERE_FRAME_SCALE = 0.5f--        init {-            OpenCVLoader.initLocal()-        }+        // 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     }      fun startSweep(fullSphere: Boolean = false) {         sphereMode = fullSphere-        frames.clear()         accumulatedAngle = 0f         accumulatedPitch = 0f         accumulatedRoll = 0f-        lastCaptureAngle = 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 -        frameOrientations.clear()--        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 -        captureFrame()-        updateDotState(0, GuideDotState.CAPTURED)+        captureFrame() // seed with the starting frame          _isSweeping.value = true         gyroscope?.let {@@ -177,19 +125,30 @@ 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 scale = if (sphereMode) SPHERE_FRAME_SCALE else PANO_FRAME_SCALE-        val w = (frame.width * scale).toInt()-        val h = (frame.height * scale).toInt()+        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)         val rotMatrix = Matrix().apply { postRotate(90f) }         val rotated = Bitmap.createBitmap(scaled, 0, 0, scaled.width, scaled.height, rotMatrix, true)         scaled.recycle()-        frames.add(rotated)-        frameOrientations.add(Triple(accumulatedAngle, accumulatedPitch, accumulatedRoll))-        _frameCount.value = frames.size-        lastCaptureAngle = accumulatedAngle+        val rgba = bitmapToRgba(rotated)+        StitchNative.addFrame(handle, rgba, rotated.width, rotated.height, accumulatedAngle, accumulatedPitch, accumulatedRoll)+        rotated.recycle()+        _frameCount.value = _frameCount.value + 1+        lastCaptureYaw = accumulatedAngle+        lastCapturePitch = accumulatedPitch     }      override fun onSensorChanged(event: SensorEvent) {@@ -211,20 +170,23 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {             _currentAngle.value = accumulatedAngle             _sweepAngle.value = Math.abs(accumulatedAngle) -            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) }-                }+            // 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()             }--            checkDotAlignment()         }         lastTimestamp = timestamp -        val allCaptured = _guideDots.value.all { it.state == GuideDotState.CAPTURED }-        if (allCaptured || (!sphereMode && Math.abs(accumulatedAngle) > 200f)) {+        val reachedBudget = _frameCount.value >= MAX_FRAMES+        val fullLoop = !sphereMode && Math.abs(accumulatedAngle) > PANO_MAX_ANGLE+        if (reachedBudget || fullLoop) {             stopSweep()             onSweepComplete?.invoke()         }@@ -232,54 +194,32 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {      override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} -    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-    }--    suspend fun stitch(): Pair<Bitmap, PanoInfo>? {-        if (frames.size < 2) return null+    /**+     * Runs the native stitcher over the captured frames. Returns the stitched+     * JPEG bytes plus its GPano geometry, or null on failure.+     */+    suspend fun stitch(): Pair<ByteArray, PanoInfo>? {+        val handle = nativeHandle+        if (handle == 0L || _frameCount.value < 2) return null         _isStitching.value = true         return withContext(Dispatchers.IO) {             try {-                if (sphereMode) stitchSphere() else stitchManual()+                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)             } catch (e: Exception) {                 e.printStackTrace()                 null@@ -289,422 +229,25 @@ class PanoramaEngine(private val context: Context) : SensorEventListener {         }     } -    private fun estimateFocalLength(width: Int, hfovDegrees: Double = 67.0): Double {-        return (width / 2.0) / Math.tan(Math.toRadians(hfovDegrees / 2.0))-    }--    /**-     * Estimates focal length in pixels from the recorded gyro yaw between-     * consecutive frames and the feature translation measured on the raw frames:-     * a camera rotation of dθ shifts image content by ≈ f·tan(dθ). Uses the-     * median across frame pairs; returns null when there isn't enough motion or-     * feature signal so the caller can fall back to a nominal-FOV estimate.-     */-    private fun estimateFocalFromMotion(mats: List<Mat>, sift: SIFT, matcher: FlannBasedMatcher): Double? {-        if (frameOrientations.size != mats.size) return null-        val focals = mutableListOf<Double>()-        for (i in 1 until mats.size) {-            val dThetaDeg = wrapDegrees(frameOrientations[i].first - frameOrientations[i - 1].first)-            val dTheta = Math.toRadians(Math.abs(dThetaDeg).toDouble())-            if (dTheta < Math.toRadians(3.0)) continue-            val trans = findTranslation(mats[i - 1], mats[i], sift, matcher) ?: continue-            val dx = Math.abs(trans.first).toDouble()-            if (dx < 2.0) continue-            focals.add(dx / Math.tan(dTheta))-        }-        if (focals.size < 2) return null-        focals.sort()-        return focals[focals.size / 2]-    }--    private fun projectCylindrical(src: Mat, f: Double): Mat {-        val h = src.rows()-        val w = src.cols()-        val cx = w / 2.0-        val cy = h / 2.0-        // Build float remap tables and let OpenCV resample with bilinear-        // interpolation — sharp, artifact-free, and far faster than the previous-        // per-pixel nearest-neighbour copy.-        val mapX = Mat(h, w, CvType.CV_32FC1)-        val mapY = Mat(h, w, CvType.CV_32FC1)-        val rowX = FloatArray(w)-        val rowY = FloatArray(w)-        for (y in 0 until h) {-            val hNorm = (y - cy) / f-            for (x in 0 until w) {-                val theta = (x - cx) / f-                rowX[x] = (f * Math.tan(theta) + cx).toFloat()-                rowY[x] = (hNorm * (1.0 / Math.cos(theta)) * f + cy).toFloat()-            }-            mapX.put(y, 0, rowX)-            mapY.put(y, 0, rowY)-        }-        val dst = Mat.zeros(h, w, src.type())-        Imgproc.remap(src, dst, mapX, mapY, Imgproc.INTER_LINEAR, Core.BORDER_CONSTANT, Scalar(0.0, 0.0, 0.0, 0.0))-        mapX.release()-        mapY.release()-        return dst-    }--    private fun findTranslation(base: Mat, next: Mat, sift: SIFT, matcher: FlannBasedMatcher): Pair<Int, Int>? {-        val gray1 = Mat()-        val gray2 = Mat()-        Imgproc.cvtColor(base, gray1, Imgproc.COLOR_RGBA2GRAY)-        Imgproc.cvtColor(next, gray2, Imgproc.COLOR_RGBA2GRAY)--        val kp1 = MatOfKeyPoint()-        val desc1 = Mat()-        val kp2 = MatOfKeyPoint()-        val desc2 = Mat()-        sift.detectAndCompute(gray1, Mat(), kp1, desc1)-        sift.detectAndCompute(gray2, Mat(), kp2, desc2)-        gray1.release()-        gray2.release()--        if (desc1.empty() || desc2.empty() || desc1.rows() < 10 || desc2.rows() < 10) return null--        val knnMatches = mutableListOf<MatOfDMatch>()-        matcher.knnMatch(desc2, desc1, knnMatches, 2)-        desc1.release()-        desc2.release()--        val goodMatches = knnMatches.mapNotNull { m ->-            val list = m.toList()-            if (list.size >= 2 && list[0].distance < 0.7f * list[1].distance) list[0] else null-        }-        if (goodMatches.size < 6) return null--        val kpList1 = kp1.toList()-        val kpList2 = kp2.toList()-        kp1.release()-        kp2.release()--        val dxList = goodMatches.map { m ->-            kpList1[m.trainIdx].pt.x - kpList2[m.queryIdx].pt.x-        }.sorted()-        val dyList = goodMatches.map { m ->-            kpList1[m.trainIdx].pt.y - kpList2[m.queryIdx].pt.y-        }.sorted()--        val medianDx = dxList[dxList.size / 2].toInt()-        val medianDy = dyList[dyList.size / 2].toInt()-        return Pair(medianDx, medianDy)-    }--    private fun stitchManual(): Pair<Bitmap, PanoInfo>? {-        return try {-            val mats = frames.map { bmp ->-                val mat = Mat()-                Utils.bitmapToMat(bmp, mat)-                mat-            }--            val sift = SIFT.create(3000)-            val matcher = FlannBasedMatcher.create()--            // Self-calibrate the focal length from the gyro yaw + measured feature-            // shift instead of assuming a fixed FOV; falls back to a nominal FOV-            // when there isn't enough motion signal.-            val f = estimateFocalFromMotion(mats, sift, matcher) ?: estimateFocalLength(mats[0].cols())-            val cylFrames = mats.map { projectCylindrical(it, f) }-            mats.forEach { it.release() }--            // Compute pairwise translations-            val offsets = mutableListOf(Pair(0, 0))-            for (i in 1 until cylFrames.size) {-                val trans = findTranslation(cylFrames[i - 1], cylFrames[i], sift, matcher)-                if (trans == null) {-                    cylFrames.forEach { it.release() }-                    return null-                }-                val prev = offsets.last()-                offsets.add(Pair(prev.first + trans.first, prev.second + trans.second))-            }--            val h = cylFrames[0].rows()-            val w = cylFrames[0].cols()-            val minX = offsets.minOf { it.first }-            val maxX = offsets.maxOf { it.first } + w-            val minY = offsets.minOf { it.second }-            val maxY = offsets.maxOf { it.second } + h-            val canvasW = maxX - minX-            val canvasH = maxY - minY-            if (canvasW <= 0 || canvasH <= 0 || canvasW > 20000 || canvasH > 20000) {-                cylFrames.forEach { it.release() }-                return null-            }--            val canvas = Mat.zeros(canvasH, canvasW, cylFrames[0].type())-            val weightCanvas = Mat.zeros(canvasH, canvasW, CvType.CV_32FC1)--            for (i in cylFrames.indices) {-                val ox = offsets[i].first - minX-                val oy = offsets[i].second - minY-                val frame = cylFrames[i]--                // Build a weight map: higher in center, falls off at edges-                val fw = Mat.zeros(h, w, CvType.CV_32FC1)-                for (y in 0 until h) {-                    val wy = (Math.min(y, h - 1 - y).toFloat() / (h / 2f)).coerceIn(0f, 1f)-                    for (x in 0 until w) {-                        val px = frame.get(y, x) ?: continue-                        if (px[0] == 0.0 && px[1] == 0.0 && px[2] == 0.0) continue-                        val wx = (Math.min(x, w - 1 - x).toFloat() / (w / 2f)).coerceIn(0f, 1f)-                        fw.put(y, x, (wx * wy).toDouble())-                    }-                }--                for (y in 0 until h) {-                    val cy = oy + y-                    if (cy < 0 || cy >= canvasH) continue-                    for (x in 0 until w) {-                        val cx = ox + x-                        if (cx < 0 || cx >= canvasW) continue-                        val pixel = frame.get(y, x) ?: continue-                        if (pixel[0] == 0.0 && pixel[1] == 0.0 && pixel[2] == 0.0) continue-                        val fwVal = fw.get(y, x)[0].toFloat()-                        val existingWeight = weightCanvas.get(cy, cx)[0].toFloat()-                        val totalWeight = existingWeight + fwVal-                        if (totalWeight > 0f) {-                            val existing = canvas.get(cy, cx)-                            val blendR = (existing[0] * existingWeight + pixel[0] * fwVal) / totalWeight-                            val blendG = (existing[1] * existingWeight + pixel[1] * fwVal) / totalWeight-                            val blendB = (existing[2] * existingWeight + pixel[2] * fwVal) / totalWeight-                            val blendA = (existing[3] * existingWeight + pixel[3] * fwVal) / totalWeight-                            canvas.put(cy, cx, blendR, blendG, blendB, blendA)-                            weightCanvas.put(cy, cx, totalWeight.toDouble())-                        }-                    }-                }-                fw.release()-            }--            cylFrames.forEach { it.release() }-            weightCanvas.release()--            // Crop out black borders-            val grayCanvas = Mat()-            Imgproc.cvtColor(canvas, grayCanvas, Imgproc.COLOR_RGBA2GRAY)-            val thresh = Mat()-            Imgproc.threshold(grayCanvas, thresh, 1.0, 255.0, Imgproc.THRESH_BINARY)-            grayCanvas.release()--            // Find the largest interior rectangle by scanning rows/cols-            var top = 0; var bottom = canvasH - 1; var left = 0; var right = canvasW - 1-            outer@ for (y in 0 until canvasH) {-                for (x in 0 until canvasW) {-                    if (thresh.get(y, x)[0] == 0.0) { top = y + 1; continue@outer }-                }-                break-            }-            outer@ for (y in canvasH - 1 downTo top) {-                for (x in 0 until canvasW) {-                    if (thresh.get(y, x)[0] == 0.0) { bottom = y - 1; continue@outer }-                }-                break-            }-            outer@ for (x in 0 until canvasW) {-                for (y in top..bottom) {-                    if (thresh.get(y, x)[0] == 0.0) { left = x + 1; continue@outer }-                }-                break-            }-            outer@ for (x in canvasW - 1 downTo left) {-                for (y in top..bottom) {-                    if (thresh.get(y, x)[0] == 0.0) { right = x - 1; continue@outer }-                }-                break-            }-            thresh.release()--            val cropW = right - left + 1-            val cropH = bottom - top + 1-            val cropped = if (cropW > 10 && cropH > 10) {-                Mat(canvas, Rect(left, top, cropW, cropH)).clone()-            } else {-                canvas.clone()-            }-            canvas.release()--            val bitmap = Bitmap.createBitmap(cropped.cols(), cropped.rows(), Bitmap.Config.ARGB_8888)-            Utils.matToBitmap(cropped, bitmap)-            cropped.release()--            // A regular (non-sphere) panorama is a flat, wide image — not a slice-            // of a 360 sphere. Tag it as a complete cylindrical panorama (full ==-            // cropped, no offsets) so viewers show it as a scrollable panorama-            // rather than opening the immersive 360/VR sphere viewer.-            val info = PanoInfo(-                projectionType = "cylindrical",-                fullWidth = bitmap.width,-                fullHeight = bitmap.height,-                croppedWidth = bitmap.width,-                croppedHeight = bitmap.height,-                croppedLeft = 0,-                croppedTop = 0,-            )-            Pair(bitmap, info)-        } catch (_: Exception) {-            null-        }-    }--    private fun stitchSphere(): Pair<Bitmap, PanoInfo>? {-        if (frames.isEmpty() || frameOrientations.size != frames.size) return null--        val frameW = frames[0].width-        val frameH = frames[0].height-        val f = estimateFocalLength(frameH)-        val cx = frameW / 2.0-        val cy = frameH / 2.0--        val eqW = (frameH * 360.0 / 67.0).toInt().coerceIn(800, 4096)-        val eqH = eqW / 2--        val accumR = FloatArray(eqW * eqH)-        val accumG = FloatArray(eqW * eqH)-        val accumB = FloatArray(eqW * eqH)-        val accumW = FloatArray(eqW * eqH)--        for (i in frames.indices) {-            val frame = frames[i]-            val (yawDeg, pitchDeg, rollDeg) = frameOrientations[i]-            val yawRad = Math.toRadians(yawDeg.toDouble())-            val pitchRad = Math.toRadians(-pitchDeg.toDouble())-            val rollRad = Math.toRadians(-rollDeg.toDouble())-            val cosYaw = Math.cos(yawRad)-            val sinYaw = Math.sin(yawRad)-            val cosPitch = Math.cos(pitchRad)-            val sinPitch = Math.sin(pitchRad)-            val cosRoll = Math.cos(rollRad)-            val sinRoll = Math.sin(rollRad)--            val pixels = IntArray(frameW * frameH)-            frame.getPixels(pixels, 0, frameW, 0, 0, frameW, frameH)--            for (py in 0 until frameH) {-                val dy = -(py - cy) / f-                for (px in 0 until frameW) {-                    val dx = (px - cx) / f-                    val dz = 1.0-                    val len = Math.sqrt(dx * dx + dy * dy + dz * dz)-                    val ndx = dx / len; val ndy = dy / len; val ndz = dz / len--                    // Roll around Z axis-                    val zx = ndx * cosRoll - ndy * sinRoll-                    val zy = ndx * sinRoll + ndy * cosRoll-                    val zz = ndz--                    // Pitch around X axis-                    val rx = zx-                    val ry = zy * cosPitch - zz * sinPitch-                    val rz = zy * sinPitch + zz * cosPitch--                    // Yaw around Y axis-                    val wx = rx * cosYaw + rz * sinYaw-                    val wy = ry-                    val wz = -rx * sinYaw + rz * cosYaw--                    val worldYaw = Math.atan2(wx, wz)-                    val worldPitch = Math.asin(wy.coerceIn(-1.0, 1.0))--                    val eqX = ((worldYaw + Math.PI) / (2.0 * Math.PI) * eqW).toInt()-                    val eqY = ((Math.PI / 2.0 - worldPitch) / Math.PI * eqH).toInt()--                    if (eqX in 0 until eqW && eqY in 0 until eqH) {-                        val pixel = pixels[py * frameW + px]-                        val r = (pixel shr 16) and 0xFF-                        val g = (pixel shr 8) and 0xFF-                        val b = pixel and 0xFF--                        val edgeX = Math.min(px, frameW - 1 - px).toFloat() / (frameW / 2f)-                        val edgeY = Math.min(py, frameH - 1 - py).toFloat() / (frameH / 2f)-                        val w = (edgeX * edgeY).coerceIn(0f, 1f)--                        val idx = eqY * eqW + eqX-                        accumR[idx] += r * w-                        accumG[idx] += g * w-                        accumB[idx] += b * w-                        accumW[idx] += w-                    }-                }-            }-        }--        val outPixels = IntArray(eqW * eqH)-        for (i in outPixels.indices) {-            if (accumW[i] > 0f) {-                val r = (accumR[i] / accumW[i]).toInt().coerceIn(0, 255)-                val g = (accumG[i] / accumW[i]).toInt().coerceIn(0, 255)-                val b = (accumB[i] / accumW[i]).toInt().coerceIn(0, 255)-                outPixels[i] = (0xFF shl 24) or (r shl 16) or (g shl 8) or b-            }-        }--        val full = Bitmap.createBitmap(eqW, eqH, Bitmap.Config.ARGB_8888)-        full.setPixels(outPixels, 0, eqW, 0, 0, eqW, eqH)--        // Crop to covered region-        var top = eqH; var bottom = 0; var left = eqW; var right = 0-        for (ey in 0 until eqH) {-            for (ex in 0 until eqW) {-                if (accumW[ey * eqW + ex] > 0f) {-                    if (ey < top) top = ey-                    if (ey > bottom) bottom = ey-                    if (ex < left) left = ex-                    if (ex > right) right = ex-                }-            }-        }-        if (right > left && bottom > top) {-            val cropped = Bitmap.createBitmap(full, left, top, right - left + 1, bottom - top + 1)-            full.recycle()-            val info = PanoInfo(-                projectionType = "equirectangular",-                fullWidth = eqW,-                fullHeight = eqH,-                croppedWidth = right - left + 1,-                croppedHeight = bottom - top + 1,-                croppedLeft = left,-                croppedTop = top,-            )-            return Pair(cropped, info)-        }-        val info = PanoInfo(-            projectionType = "equirectangular",-            fullWidth = eqW,-            fullHeight = eqH,-            croppedWidth = eqW,-            croppedHeight = eqH,-            croppedLeft = 0,-            croppedTop = 0,-        )-        return Pair(full, info)-    }--    fun saveToMediaStore(bitmap: Bitmap, info: PanoInfo) {+    fun saveToMediaStore(jpeg: ByteArray, info: PanoInfo) {         val prefix = if (sphereMode) "SPHERE" else "PANO"         val contentValues = MediaStoreSaver.imageValues("${prefix}_${MediaStoreSaver.timestamp()}.jpg")-        val baos = java.io.ByteArrayOutputStream()-        bitmap.compress(Bitmap.CompressFormat.JPEG, 95, baos)-        val tagged = PanoXmp.injectXmp(baos.toByteArray(), PanoXmp.buildGPanoXmp(info))+        val tagged = PanoXmp.injectXmp(jpeg, PanoXmp.buildGPanoXmp(info))         MediaStoreSaver.saveJpegBytes(context.contentResolver, contentValues, tagged)     }      fun reset() {-        frames.forEach { it.recycle() }-        frames.clear()-        frameOrientations.clear()+        if (nativeHandle != 0L && StitchNative.isAvailable) StitchNative.free(nativeHandle)+        nativeHandle = 0L         _frameCount.value = 0         _sweepAngle.value = 0f         _isSweeping.value = false         _isStitching.value = false-        _guideDots.value = emptyList()         _currentAngle.value = 0f         _currentPitch.value = 0f-        _sweepDirection.value = 0         accumulatedPitch = 0f         accumulatedRoll = 0f         pitchVelocity = 0f+        latestFrame = null     } }
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.ktnew file mode 100644index 0000000000..c39d7cef4f--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt@@ -0,0 +1,35 @@+package com.vayunmathur.camera.util++import android.util.Log++/**+ * JNI bridge to the native `camera_stitch` Rust library (feature-based panorama+ * stitcher + night burst aligner). Replaces the previous OpenCV dependency.+ *+ * Usage: newSession() -> addFrame()* -> stitch()/merge() -> free().+ */+object StitchNative {+    val isAvailable: Boolean = try {+        System.loadLibrary("camera_stitch")+        Log.i("StitchNative", "libcamera_stitch loaded")+        true+    } catch (t: Throwable) {+        Log.e("StitchNative", "System.loadLibrary(camera_stitch) failed", t)+        false+    }++    /** 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)++    /** Stitches the added frames into a panorama; returns JPEG bytes or null. Consumes the frames. */+    external fun stitch(handle: Long): ByteArray?++    /** Aligns + merges the added frames (night mode); returns JPEG bytes or null. Consumes the frames. */+    external fun merge(handle: Long): ByteArray?++    /** Releases the session. */+    external fun free(handle: Long)+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 0cd0bf5aaa..5a3f3ed205 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -30,6 +30,8 @@ include(":library:network") include(":library:biometric") include(":library:downloadservice") include(":library:ui")+include(":library:room")+include(":library:ink") include(":library:e2ee-p2p") include(":library:widgets") include(":library:work")