camera: photo sphere now produces a real 360x180 sphere (#923)
- Commit
55b4bc34b2d634194d52747f7e5bf47905241e45- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 19:06 UTC (5 days ago)
- Parents
087677c
Sphere results were heavily overlapping garbage, including in Google Photos, because the pieces disagreed about what a sphere is: waypoints were laid out at a fixed angular step unrelated to the active lens's field of view, heading came from gyro dead reckoning that drifts over a multi-minute sweep, the stitcher pasted frames onto a partial flat canvas, and the GPano XMP then described that patch as a full 360x180 sphere. Waypoints are now derived per lens in domain/SphereWaypoints: spacing from the measured FOV at 40% overlap, rows reaching the poles. Heading/pitch comes from the fused rotation-vector sensor (domain/SphereOrientation, absolute and drift-free); gyro dead reckoning and accelerometer+magnetometer remain as fallbacks. The HAL focal length flows through StitchNative into the Rust focal estimate as a clamped prior [0.5x, 2x], angular matching uses the true great-circle angle, and estimate_pano renders onto a full exactly-2:1 equirect canvas (u0=-180, v0=pole) with meridian wrap, so the JPEG finally is the sphere the (always-correct) GPano writer describes. The flat panorama ring is unchanged. New SphereWaypointsTest (spacing/overlap/pole coverage at three FOVs), orientation math tests, a partial-sphere GPano case, and Rust tests for the equirect canvas, focal prior and great-circle matching. Verified: :camera:testDevUnitTest passes (634 tests), cargo camera_stitch 144 lib + 27 integration tests pass. Owed on-device: one POCO sweep to confirm rotation-vector sign and Google Photos sphere rendering end to end.
Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex 854f78d368..51eaf3e583 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -15,6 +15,7 @@ _Install: ./install camera (dev by default)._ **Key features:** - Photo + video capture on a direct Camera2 implementation (`platform/camera2/` driver, sessions, extension and high-speed sessions) with per-mode sessions: single, portrait, night, slo-mo, video - Panorama stitching + night-burst alignment in the native Rust `camera_stitch` engine+- Photo-sphere capture: guide waypoints spaced from the active lens's measured FOV at 40% overlap (rows reach the poles), heading/pitch from the fused rotation-vector sensor (gyro dead reckoning, then accelerometer+magnetometer, as fallbacks), stitch seeded with the HAL focal length, and output rendered onto a full 360×180 equirect canvas whose GPano XMP describes that sphere (Google Photos renders it as a sphere) - Portrait mode with on-device segmentation (MediaPipe selfie + MODNet matting on a Vulkan compute runtime, `.maml` assets) - QR/barcode scanning (zxing) and optional GPS geotagging written into EXIF **Architecture / data-flow:** Single-screen `ui/CameraScreen` + `platform/CameraViewModel` over per-mode `platform/` session objects on the `platform/camera2/` driver; `domain/` holds pure lens-selection logic, `platform/` capability queries; heavy work (stitch, night align, bokeh) goes through Rust JNI (`platform/StitchNative`) and lands in MediaStore via `data/MediaStoreSaver`. `onCreateBeforeContent` only honors the `ACTION_IMAGE_CAPTURE` capture-for-result intent; `Content()` sits behind a camera+mic permission gate.@@ -40,6 +41,7 @@ _Install: ./install camera (dev by default)._ - com/vayunmathur/camera/domain/CaptureRotation.kt — the one capture-rotation decision (sensor + physical display + facing) and EXIF convention - com/vayunmathur/camera/domain/AnalysisRotation.kt — analysis-frame rotation (same formula as CaptureRotation) - com/vayunmathur/camera/domain/PanoXmp.kt+- com/vayunmathur/camera/domain/SphereWaypoints.kt — FOV-derived photo-sphere waypoint layout + fused-orientation yaw/pitch math - com/vayunmathur/camera/domain/MotionPhotoWriter.kt ### platform/ — capability queries - com/vayunmathur/camera/platform/CameraCapabilities.kt
camera/src/main/java/com/vayunmathur/camera/domain/SphereWaypoints.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/SphereWaypoints.kt b/camera/src/main/java/com/vayunmathur/camera/domain/SphereWaypoints.ktnew file mode 100644index 0000000000..d1fdf45326--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/SphereWaypoints.kt@@ -0,0 +1,151 @@+package com.vayunmathur.camera.domain++import kotlin.math.atan+import kotlin.math.atan2+import kotlin.math.ceil+import kotlin.math.cos+import kotlin.math.tan++/** One photo-sphere capture target: yaw (0..360) and pitch (-90..90), degrees. */+data class SphereWaypoint(val yawDeg: Float, val pitchDeg: Float)++/**+ * Photo-sphere waypoint layout derived from the capturing lens's field of view.+ *+ * The old layout used fixed angular steps (30°/40°/72°) chosen for one nominal+ * lens: on a narrower lens the steps exceed the frame, leaving unmatchable+ * gaps; on a wider lens they waste frames; and the ±60° ring plus missing+ * poles left the sphere's caps uncovered. Here every step is+ * `FOV * (1 - overlap)` — the standard 30–50% stitch overlap band — with the+ * per-row yaw step widened by `1 / cos(pitch)` (rings shrink toward the+ * poles) and rows added until the frame edge reaches the pole.+ */+object SphereWaypoints {++ /** Fraction of each frame that must overlap its neighbour (stitch band 0.3–0.5). */+ const val OVERLAP_FRACTION = 0.4f++ /** Fallback frame FOV (portrait-held 1x wide lens) when the HAL reports none. */+ const val DEFAULT_H_FOV_DEG = 50f+ const val DEFAULT_V_FOV_DEG = 66f++ private const val FULL_CIRCLE_DEG = 360f+ private const val HALF_CIRCLE_DEG = 180f+ private const val POLE_DEG = 90f+ private const val MIN_STEP_DEG = 10f+ private const val MAX_YAW_STEP_DEG = 120f+ private const val MIN_ROW_DOTS = 3+ /** Frame edge must reach within this of the pole, else a cap row is added. */+ private const val POLE_COVERAGE_TOLERANCE_DEG = 1f+ /** Full-frame (35mm) sensor dimensions: width x height in mm. */+ private const val FULL_FRAME_WIDTH_MM = 36f+ private const val FULL_FRAME_HEIGHT_MM = 24f+ private const val RAD_TO_DEG = 57.29577951308232f++ /**+ * Sphere waypoints for a frame with horizontal/vertical FOV [hFovDeg] /+ * [vFovDeg] (the upright capture frame's own axes). Row order is equator,+ * then alternating negative/positive pitch rows — the order the user is+ * guided through. Alternate rows are staggered by half a yaw step so each+ * frame has diagonal neighbours, not just ring neighbours.+ */+ fun generate(+ hFovDeg: Float,+ vFovDeg: Float,+ overlap: Float = OVERLAP_FRACTION,+ ): List<SphereWaypoint> {+ val h = hFovDeg.coerceIn(MIN_STEP_DEG, FULL_CIRCLE_DEG)+ val v = vFovDeg.coerceIn(MIN_STEP_DEG, HALF_CIRCLE_DEG)+ val ov = overlap.coerceIn(0f, 0.9f)+ val stepPitch = (v * (1f - ov)).coerceAtLeast(MIN_STEP_DEG)+ val equatorYawStep = (h * (1f - ov)).coerceAtLeast(MIN_STEP_DEG)++ // Pitch rows: multiples of stepPitch whose frame edge can still be+ // guided, plus a cap row at (pole - half vertical FOV) when the last+ // regular row leaves the pole uncovered.+ val pitches = mutableListOf(0f)+ var k = 1+ while (true) {+ val p = k * stepPitch+ if (p > POLE_DEG - v / 2f + POLE_COVERAGE_TOLERANCE_DEG) break+ pitches.add(p)+ pitches.add(-p)+ k+++ }+ val maxRow = pitches.maxOf { kotlin.math.abs(it) }+ if (maxRow + v / 2f < POLE_DEG - POLE_COVERAGE_TOLERANCE_DEG) {+ val cap = POLE_DEG - v / 2f+ pitches.add(cap)+ pitches.add(-cap)+ }+ // Equator first, then rows by increasing |pitch|, negative before positive.+ val orderedPitches = pitches.sortedWith(compareBy({ kotlin.math.abs(it) }, { it }))++ val out = ArrayList<SphereWaypoint>()+ for ((rowIndex, pitch) in orderedPitches.withIndex()) {+ val cosPitch = cos(Math.toRadians(pitch.toDouble())).toFloat().coerceAtLeast(0.05f)+ val yawStep = (equatorYawStep / cosPitch).coerceAtMost(MAX_YAW_STEP_DEG)+ val count = ceil(FULL_CIRCLE_DEG / yawStep).toInt().coerceAtLeast(MIN_ROW_DOTS)+ val step = FULL_CIRCLE_DEG / count+ val offset = if (rowIndex % 2 == 1) step / 2f else 0f+ for (i in 0 until count) {+ out.add(SphereWaypoint((offset + i * step) % FULL_CIRCLE_DEG, pitch))+ }+ }+ return out+ }++ /**+ * Portrait-held frame FOV (horizontal, vertical) in degrees for a lens of+ * 35mm-equivalent focal length [eq35Mm]. A portrait frame's width spans+ * the sensor's 24mm dimension and its height the 36mm dimension.+ */+ fun fovFromEq35(eq35Mm: Float): Pair<Float, Float> {+ val eq = eq35Mm.coerceAtLeast(1f)+ val h = 2f * atan(FULL_FRAME_HEIGHT_MM / 2f / eq) * RAD_TO_DEG+ val v = 2f * atan(FULL_FRAME_WIDTH_MM / 2f / eq) * RAD_TO_DEG+ return h to v+ }++ /** Focal length in pixels per unit frame width: `f_px / width` for [hFovDeg]. */+ fun focalOverWidth(hFovDeg: Float): Float {+ val halfRad = Math.toRadians(hFovDeg.coerceIn(1f, 179f).toDouble()) / 2.0+ return (0.5 / tan(halfRad)).toFloat()+ }+}++/**+ * Pure orientation math for fused-sensor (rotation-vector / accel+magnetometer)+ * sphere tracking: the relative rotation from the sweep-start orientation to+ * the current one, decomposed into guide yaw/pitch.+ */+object SphereOrientation {++ private const val RAD_TO_DEG = 57.29577951308232f++ /**+ * Relative rotation `refᵀ · cur` of two row-major 3×3 rotation matrices —+ * the current orientation expressed in the sweep-start device frame.+ */+ fun relativeRotation(ref: FloatArray, cur: FloatArray): FloatArray {+ val out = FloatArray(9)+ for (i in 0..2) {+ for (j in 0..2) {+ out[i * 3 + j] = ref[i] * cur[j] + ref[3 + i] * cur[3 + j] + ref[6 + i] * cur[6 + j]+ }+ }+ return out+ }++ /**+ * (yaw, pitch) in degrees of a relative rotation [rel] (row-major 3×3),+ * decomposed as `Ry(yaw) · Rx(pitch)`: yaw about the start-frame up axis,+ * pitch about its right axis. Exact for pure yaw or pure pitch; the guide+ * rows stay below ±90° pitch so the decomposition never hits gimbal lock.+ */+ fun yawPitchDegrees(rel: FloatArray): Pair<Float, Float> {+ val yaw = atan2(rel[2], rel[8]) * RAD_TO_DEG+ val pitch = atan2(-rel[5], rel[4]) * RAD_TO_DEG+ return yaw to pitch+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.ktindex 0b3086f721..6f8727153b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoRecording.kt@@ -480,6 +480,22 @@ fun CameraViewModel.captureVideoSnapshot() { ) } +/**+ * (horizontal FOV, vertical FOV, focal-over-width) of the upright capture+ * frame for the selected lens, from its 35mm-equivalent focal length; the+ * sphere-typical defaults when the HAL reported no equivalent focal length.+ */+internal fun CameraViewModel.panoLensIntrinsics(): Triple<Float, Float, Float> {+ val eq = selectedLensMutable.value?.focalLengthMm35Eq+ val (hFov, vFov) = if (eq != null && eq > 0f) {+ com.vayunmathur.camera.domain.SphereWaypoints.fovFromEq35(eq)+ } else {+ com.vayunmathur.camera.domain.SphereWaypoints.DEFAULT_H_FOV_DEG to+ com.vayunmathur.camera.domain.SphereWaypoints.DEFAULT_V_FOV_DEG+ }+ return Triple(hFov, vFov, com.vayunmathur.camera.domain.SphereWaypoints.focalOverWidth(hFov))+}+ fun CameraViewModel.startPanorama() { if (panoramaEngine.isSweeping.value || panoramaEngine.isStitching.value || isCapturingMutable.value) return // Stitch input must be 1x: re-assert the lock on the session whose@@ -488,7 +504,8 @@ fun CameraViewModel.startPanorama() { // mode entry. (Mode entry already applied 1x; this is the capture- // time backstop.) activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)- panoramaEngine.startSweep()+ val (hFov, vFov, focalOverWidth) = panoLensIntrinsics()+ panoramaEngine.startSweep(hFovDeg = hFov, vFovDeg = vFov, focalOverWidth = focalOverWidth) } fun CameraViewModel.stopPanorama() = finishPanoramaSweep()@@ -497,7 +514,8 @@ fun CameraViewModel.startPhotosphere() { if (panoramaEngine.isSweeping.value || panoramaEngine.isStitching.value || isCapturingMutable.value) return // Same 1x stitch-input lock as startPanorama (see there). activeCamera2Session?.setZoomRatio(ZOOM_LOCK_RATIO)- panoramaEngine.startSweep(fullSphere = true)+ val (hFov, vFov, focalOverWidth) = panoLensIntrinsics()+ panoramaEngine.startSweep(fullSphere = true, hFovDeg = hFov, vFovDeg = vFov, focalOverWidth = focalOverWidth) } fun CameraViewModel.stopPhotosphere() = finishPanoramaSweep()
camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.ktindex 7204c8b023..3de70b379c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt@@ -164,7 +164,7 @@ object NightCaptureEngine { tryLosslessRgba(burst)?.let { return it } // Fallback: old JPEG-compressed path (backwards compat) return try {- val handle = StitchNative.newSession(false)+ val handle = StitchNative.newSession(false, 0f) try { for (f in burst) { val baos = java.io.ByteArrayOutputStream()
camera/src/main/java/com/vayunmathur/camera/platform/PanoramaEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/PanoramaEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/PanoramaEngine.ktindex 5d27e51db6..69dc6ef72b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/PanoramaEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/PanoramaEngine.kt@@ -19,6 +19,8 @@ import kotlinx.coroutines.withContext import java.io.ByteArrayOutputStream import com.vayunmathur.camera.data.MediaStoreSaver import com.vayunmathur.camera.domain.PanoXmp+import com.vayunmathur.camera.domain.SphereOrientation+import com.vayunmathur.camera.domain.SphereWaypoints import com.vayunmathur.camera.data.SafDocuments import com.vayunmathur.camera.data.SaveTarget @@ -50,6 +52,28 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager private val gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)+ // Fused absolute orientation is preferred over gyro dead reckoning: pure+ // gyro integration drifts without bound over a multi-minute sphere sweep+ // (an uncalibrated Xiaomi gyro bias of ~0.5°/s is ~30° by the last row),+ // which misplaces every guide dot after the first ring and feeds the+ // stitcher gyro angles that no longer match the frames.+ private val rotationVector = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)+ ?: sensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR)+ private val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)+ private val magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)++ /** Which sensor family currently drives heading/pitch. */+ private enum class TrackingSource { FUSED, GYRO, ACCEL_MAG, NONE }++ private var trackingSource = TrackingSource.NONE+ /** Sweep-start orientation (row-major 3x3) for fused tracking; null until seeded. */+ private var fusedReference: FloatArray? = null+ private var fusedMatrix = FloatArray(9)+ private var lastAccel: FloatArray? = null+ private var lastMag: FloatArray? = null+ private var prevFusedYaw = 0f+ private var prevFusedPitch = 0f+ private var prevFusedTimestamp = 0L private val _isSweeping = MutableStateFlow(false) val isSweeping = _isSweeping.asStateFlow()@@ -153,7 +177,19 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { private const val PANO_MAX_ANGLE = 380f } - fun startSweep(fullSphere: Boolean = false) {+ /**+ * Starts a sweep. [hFovDeg]/[vFovDeg] are the upright capture frame's+ * field of view (from the active lens; defaults assume a typical 1x wide+ * lens) — sphere waypoints are spaced from them at+ * [SphereWaypoints.OVERLAP_FRACTION] overlap, and [focalOverWidth] seeds+ * the stitcher's focal estimate with the real lens intrinsics.+ */+ fun startSweep(+ fullSphere: Boolean = false,+ hFovDeg: Float = SphereWaypoints.DEFAULT_H_FOV_DEG,+ vFovDeg: Float = SphereWaypoints.DEFAULT_V_FOV_DEG,+ focalOverWidth: Float = SphereWaypoints.focalOverWidth(hFovDeg),+ ) { sphereMode = fullSphere accumulatedAngle = 0f accumulatedPitch = 0f@@ -161,38 +197,29 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { lastTimestamp = 0L angularVelocity = 0f pitchVelocity = 0f+ fusedReference = null+ lastAccel = null+ lastMag = null+ prevFusedTimestamp = 0L+ prevFusedYaw = 0f+ prevFusedPitch = 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 full horizontal ring.+ // Guide-dot layout: an FOV-derived full-sphere grid (pitch rows whose+ // frame edges reach the poles) or a full 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++- }+ SphereWaypoints.generate(hFovDeg, vFovDeg).mapIndexed { idx, wp ->+ GuideDot(+ idx,+ wp.yawDeg,+ wp.pitchDeg,+ if (idx == 0) GuideDotState.CAPTURING else GuideDotState.PENDING+ ) }- result } else { // Full horizontal ring: 12 dots every 30° around the whole circle. (0 until 12).map { i ->@@ -202,7 +229,11 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { _guideDots.value = dots if (nativeHandle != 0L && StitchNative.isAvailable) StitchNative.free(nativeHandle)- nativeHandle = if (StitchNative.isAvailable) StitchNative.newSession(fullSphere) else 0L+ nativeHandle = if (StitchNative.isAvailable) {+ StitchNative.newSession(fullSphere, focalOverWidth)+ } else {+ 0L+ } capturedFrames.clear() // Seed with the starting frame, but only mark dot 0 captured if a frame was actually@@ -214,8 +245,28 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { } _isSweeping.value = true- gyroscope?.let {- sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_GAME)+ // Sensor selection, best first: fused rotation vector (absolute,+ // drift-free) -> gyro dead reckoning -> accelerometer+magnetometer+ // fusion. The old code registered the gyroscope only, so a device+ // without one silently never advanced the sweep.+ trackingSource = when {+ rotationVector != null -> {+ sensorManager.registerListener(this, rotationVector, SensorManager.SENSOR_DELAY_GAME)+ TrackingSource.FUSED+ }+ gyroscope != null -> {+ sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_GAME)+ TrackingSource.GYRO+ }+ accelerometer != null && magnetometer != null -> {+ sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME)+ sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_GAME)+ TrackingSource.ACCEL_MAG+ }+ else -> {+ Log.error("PanoramaEngine", "no orientation sensor available; sweep cannot track")+ TrackingSource.NONE+ } } } @@ -283,8 +334,26 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { override fun onSensorChanged(event: SensorEvent) { if (!_isSweeping.value) return- if (event.sensor.type != Sensor.TYPE_GYROSCOPE) return+ when (event.sensor.type) {+ Sensor.TYPE_ROTATION_VECTOR, Sensor.TYPE_GAME_ROTATION_VECTOR -> {+ SensorManager.getRotationMatrixFromVector(fusedMatrix, event.values)+ onFusedOrientation(event.timestamp)+ }+ Sensor.TYPE_ACCELEROMETER -> {+ lastAccel = event.values.copyOf()+ tryAccelMagOrientation(event.timestamp)+ }+ Sensor.TYPE_MAGNETIC_FIELD -> {+ lastMag = event.values.copyOf()+ tryAccelMagOrientation(event.timestamp)+ }+ Sensor.TYPE_GYROSCOPE -> onGyroEvent(event)+ else -> Unit+ }+ } + /** Gyro dead reckoning (fallback when no fused orientation sensor exists). */+ private fun onGyroEvent(event: SensorEvent) { val timestamp = event.timestamp if (lastTimestamp != 0L) { val dt = (timestamp - lastTimestamp) / 1_000_000_000f@@ -299,20 +368,68 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { _currentPitch.value = accumulatedPitch _currentAngle.value = accumulatedAngle _sweepAngle.value = Math.abs(accumulatedAngle)+ onOrientationUpdated()+ }+ lastTimestamp = timestamp+ } - // Mirror the dot ring to match the sweep direction (flat pano only).- if (_sweepDirection.value == 0 && Math.abs(accumulatedAngle) > SWEEP_DIRECTION_MIN_ANGLE) {- 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) }- }- }+ /** Accelerometer+magnetometer fusion fallback (no rotation vector, no gyro). */+ private fun tryAccelMagOrientation(timestamp: Long) {+ val accel = lastAccel ?: return+ val mag = lastMag ?: return+ // Fails near free fall or magnetic poles; the next event retries.+ if (!SensorManager.getRotationMatrix(fusedMatrix, null, accel, mag)) return+ onFusedOrientation(timestamp)+ } - checkDotAlignment()+ /**+ * Absolute heading/pitch from the fused orientation in [fusedMatrix],+ * relative to the sweep-start orientation. Unlike gyro integration this+ * cannot drift: every event re-derives the angle from the fused matrix.+ * Fused yaw wraps at ±180°; dot matching wraps differences, so the ring+ * still completes across the seam.+ */+ private fun onFusedOrientation(timestamp: Long) {+ val ref = fusedReference+ if (ref == null) {+ fusedReference = fusedMatrix.copyOf()+ prevFusedTimestamp = timestamp+ return }- lastTimestamp = timestamp+ val rel = SphereOrientation.relativeRotation(ref, fusedMatrix)+ val (yawDeg, pitchDeg) = SphereOrientation.yawPitchDegrees(rel)+ // Same sign convention as the gyro path (angle grows with -omega_y),+ // so dots progress identically whichever sensor source is running.+ val newYaw = -yawDeg+ if (prevFusedTimestamp != 0L) {+ val dt = (timestamp - prevFusedTimestamp) / 1_000_000_000f+ if (dt > 0f) {+ angularVelocity = wrapDegrees(newYaw - prevFusedYaw) / dt+ pitchVelocity = (pitchDeg - prevFusedPitch) / dt+ }+ }+ prevFusedYaw = newYaw+ prevFusedPitch = pitchDeg+ prevFusedTimestamp = timestamp+ accumulatedAngle = newYaw+ accumulatedPitch = pitchDeg+ _currentPitch.value = accumulatedPitch+ _currentAngle.value = accumulatedAngle+ _sweepAngle.value = Math.abs(accumulatedAngle)+ onOrientationUpdated()+ } + /** Dot-ring direction mirroring, alignment capture, and sweep completion. */+ private fun onOrientationUpdated() {+ // Mirror the dot ring to match the sweep direction (flat pano only).+ if (_sweepDirection.value == 0 && Math.abs(accumulatedAngle) > SWEEP_DIRECTION_MIN_ANGLE) {+ 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() val allCaptured = _guideDots.value.all { it.state == GuideDotState.CAPTURED } if (allCaptured || (!sphereMode && Math.abs(accumulatedAngle) > PANO_MAX_ANGLE)) { stopSweep()
camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.ktindex d77df57078..60767f901f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt@@ -16,8 +16,13 @@ import java.nio.ByteBuffer object StitchNative { val isAvailable: Boolean = NativeLoader.load("camera_stitch", "StitchNative") - /** Opens a stitch session. [sphere] selects full-sphere vs flat panorama. */- external fun newSession(sphere: Boolean): Long+ /**+ * Opens a stitch session. [sphere] selects full-sphere vs flat panorama.+ * [focalOverWidth] is the lens focal length in pixels per unit frame width+ * (`f_px / width`, from the HAL via the lens FOV; 0 = unknown) and seeds+ * the stitcher's focal estimation with the real device intrinsics.+ */+ external fun newSession(sphere: Boolean, focalOverWidth: Float): Long /** 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)
camera/src/main/rust/src/blend_part1.rs
diff --git a/camera/src/main/rust/src/blend_part1.rs b/camera/src/main/rust/src/blend_part1.rsindex 9606540770..adfead1b8d 100644--- a/camera/src/main/rust/src/blend_part1.rs+++ b/camera/src/main/rust/src/blend_part1.rs@@ -1,4 +1,12 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>]) -> Option<Rgba> {+ multiband_blend_with_rect(tiles, masks, gain_maps).map(|(img, _, _)| img)+}++/// Like [`multiband_blend`], but also returns the content crop's top-left+/// corner (x, y) within the tiles' bounding-box canvas. The sphere stitcher+/// needs that origin to place the cropped blend onto the full equirect+/// canvas at the right longitude/latitude.+pub fn multiband_blend_with_rect(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec<f32>]) -> Option<(Rgba, usize, usize)> { let num = tiles.len(); if num == 0 { return None;@@ -31,8 +39,8 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec let cw_padded = cw + (div - cw % div) % div; let ch_padded = ch + (div - ch % div) % div; if cw_padded > 20000 || ch_padded > 20000 {- // Too large for pyramid – fallback to feather- return feather_blend(tiles, masks, gain_maps, gx0, gy0, cw, ch);+ // Too large for pyramid – fallback to feather (full bbox, no crop)+ return feather_blend(tiles, masks, gain_maps, gx0, gy0, cw, ch).map(|img| (img, 0, 0)); } // Global pyramid dimensions@@ -320,10 +328,11 @@ pub fn multiband_blend(tiles: &[WarpedTile], masks: &[Vec<u8>], gain_maps: &[Vec } } if opaque == 0 {- return feather_blend(tiles, masks, gain_maps, gx0, gy0, cw, ch);+ return feather_blend(tiles, masks, gain_maps, gx0, gy0, cw, ch).map(|img| (img, 0, 0)); } - Some(crop_to_content(cropped))+ let (img, rx, ry) = crop_to_content_with_rect(cropped);+ Some((img, rx, ry)) } /// Crop rectangle = maximal all-opaque rectangle. With the coverage a proper@@ -361,10 +370,16 @@ fn content_rect(valid: &[bool], w: usize, h: usize) -> (usize, usize, usize, usi } fn crop_to_content(img: Rgba) -> Rgba {+ crop_to_content_with_rect(img).0+}++/// Crops to the maximal all-opaque rectangle, also returning its top-left+/// corner (x, y) in the input image.+fn crop_to_content_with_rect(img: Rgba) -> (Rgba, usize, usize) { 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;+ return (img, 0, 0); } let mut out = Rgba::new(rw, rh); for y in 0..rh {@@ -374,5 +389,91 @@ fn crop_to_content(img: Rgba) -> Rgba { out.px[d..d + 4].copy_from_slice(&img.px[s..s + 4]); } }+ (out, rx, ry)+}++/// 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.+pub 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 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;+ }+ }+ }+ masks+}++/// Bilinear upscale of a per-pixel gain map.+pub fn resize_gain(src: &[f32], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<f32> {+ if sw == 0 || sh == 0 {+ return vec![1.0f32; dw * dh];+ }+ let mut out = vec![1.0f32; dw * dh];+ for y in 0..dh {+ let fy = ((y as f64 + 0.5) * sh as f64 / dh as f64 - 0.5).clamp(0.0, sh as f64 - 1.0);+ let y0 = fy.floor() as usize;+ let y1 = (y0 + 1).min(sh - 1);+ let ay = (fy - y0 as f64) as f32;+ for x in 0..dw {+ let fx = ((x as f64 + 0.5) * sw as f64 / dw as f64 - 0.5).clamp(0.0, sw as f64 - 1.0);+ let x0 = fx.floor() as usize;+ let x1 = (x0 + 1).min(sw - 1);+ let ax = (fx - x0 as f64) as f32;+ let g00 = src[y0 * sw + x0];+ let g10 = src[y0 * sw + x1];+ let g01 = src[y1 * sw + x0];+ let g11 = src[y1 * sw + x1];+ let top = g00 * (1.0 - ax) + g10 * ax;+ let bot = g01 * (1.0 - ax) + g11 * ax;+ out[y * dw + x] = top * (1.0 - ay) + bot * ay;+ }+ } out }
camera/src/main/rust/src/estimator.rs
diff --git a/camera/src/main/rust/src/estimator.rs b/camera/src/main/rust/src/estimator.rsindex ba9da2f03e..d7fc70d689 100644--- a/camera/src/main/rust/src/estimator.rs+++ b/camera/src/main/rust/src/estimator.rs@@ -5,15 +5,24 @@ use crate::camera::CameraParams; use crate::matching::MatchInfo;-use crate::sphere::{estimate_focal, k_matrix, orthonormalize};+use crate::sphere::{estimate_focal_with_prior, k_matrix, orthonormalize}; use crate::linalg::Matrix3; /// `node -> [(neighbour, num_inliers, confidence, H_node->neighbour)]`. type Adjacency = Vec<Vec<(usize, usize, f64, Matrix3<f64>)>>; -pub fn estimate_cameras(n: usize, w: usize, h: usize, matches: &[MatchInfo]) -> Vec<CameraParams> {+/// Estimates per-image rotations around a shared focal. `focal_prior` is the+/// device-measured focal in pixels at this (registration) resolution, when+/// the HAL provided one; see `estimate_focal_with_prior`.+pub fn estimate_cameras(+ n: usize,+ w: usize,+ h: usize,+ matches: &[MatchInfo],+ focal_prior: Option<f64>,+) -> Vec<CameraParams> { let hs: Vec<Matrix3<f64>> = matches.iter().map(|m| m.h).collect();- let focal = estimate_focal(&hs, w, h);+ let focal = estimate_focal_with_prior(&hs, w, h, focal_prior); let ppx = w as f64 / 2.0; let ppy = h as f64 / 2.0; let k = k_matrix(focal, ppx, ppy);
camera/src/main/rust/src/estimator_tests.rs
diff --git a/camera/src/main/rust/src/estimator_tests.rs b/camera/src/main/rust/src/estimator_tests.rsindex ed7fe7d9f3..949d4f39d5 100644--- a/camera/src/main/rust/src/estimator_tests.rs+++ b/camera/src/main/rust/src/estimator_tests.rs@@ -31,7 +31,7 @@ fn mi(src: usize, dst: usize, h: Matrix3<f64>, inl: usize, conf: f64) -> MatchIn #[test] fn estimate_cameras_single_image_gets_identity() {- let cams = estimate_cameras(1, 640, 480, &[]);+ let cams = estimate_cameras(1, 640, 480, &[], None); assert_eq!(cams.len(), 1); assert!(approx(mdiff(&(cams[0].r), &(Matrix3::identity())), 0.0, 1e-12)); assert!(approx(cams[0].focal, 1120.0, 1e-9), "fallback focal w+h");@@ -40,7 +40,7 @@ fn estimate_cameras_single_image_gets_identity() { #[test] fn estimate_cameras_disconnected_images_all_identity() {- let cams = estimate_cameras(3, 640, 480, &[]);+ let cams = estimate_cameras(3, 640, 480, &[], None); assert_eq!(cams.len(), 3); for c in &cams { assert!(approx(mdiff(&(c.r), &(Matrix3::identity())), 0.0, 1e-9));@@ -54,7 +54,7 @@ fn estimate_cameras_identity_homography_chain_keeps_identity() { // Identity homographies carry no focal, so the fallback focal applies // and CalcRotation yields identity relative rotations. let matches = vec![mi(0, 1, Matrix3::identity(), 50, 0.9), mi(1, 2, Matrix3::identity(), 40, 0.9)];- let cams = estimate_cameras(3, 640, 480, &matches);+ let cams = estimate_cameras(3, 640, 480, &matches, None); assert_eq!(cams.len(), 3); for c in &cams { assert!(approx(mdiff(&(c.r), &(Matrix3::identity())), 0.0, 1e-6), "identity chain must stay identity");@@ -66,7 +66,7 @@ fn estimate_cameras_identity_homography_chain_keeps_identity() { fn estimate_cameras_root_is_middle_image_with_identity() { // Root is n/2; with no matches every camera (root included) is identity, // and the root index for 4 cameras is 2.- let cams = estimate_cameras(4, 800, 600, &[]);+ let cams = estimate_cameras(4, 800, 600, &[], None); assert_eq!(cams.len(), 4); assert!(approx(mdiff(&(cams[2].r), &(Matrix3::identity())), 0.0, 1e-12)); assert!(approx(cams[0].focal, 1400.0, 1e-9), "w+h fallback");@@ -77,10 +77,19 @@ fn estimate_cameras_root_is_middle_image_with_identity() { fn estimate_cameras_singular_homography_does_not_panic() { let zero = Matrix3::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); let matches = vec![mi(0, 1, zero, 10, 0.5)];- let cams = estimate_cameras(2, 320, 240, &matches);+ let cams = estimate_cameras(2, 320, 240, &matches, None); assert_eq!(cams.len(), 2); for c in &cams { assert!(c.focal.is_finite() && c.focal > 1.0); assert_rotation(&c.r); } }++#[test]+fn estimate_cameras_uses_focal_prior_when_no_matches() {+ // No homographies to estimate from: cameras get the HAL focal, not the+ // (w + h) fallback that implies a ~32-degree lens.+ let cams = estimate_cameras(2, 640, 480, &[], Some(500.0));+ assert!((cams[0].focal - 500.0).abs() < 1e-9, "focal {}", cams[0].focal);+ assert!((cams[1].focal - 500.0).abs() < 1e-9, "focal {}", cams[1].focal);+}
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex ebd807f4cc..67b0709616 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -32,6 +32,8 @@ use std::sync::{Mutex, OnceLock}; struct Session { sphere: bool,+ /// HAL focal in pixels per unit frame width (0 = unknown); seeds focal estimation.+ focal_over_width: f32, frames: Vec<Vec<u8>>, // JPEG-compressed frames (decoded on demand at stitch time) yaw: Vec<f32>, pitch: Vec<f32>,@@ -89,8 +91,7 @@ fn do_stitch(s: &mut Session) -> Option<Vec<u8>> { let frames = std::mem::take(&mut s.frames); let yaw = std::mem::take(&mut s.yaw); let pitch = std::mem::take(&mut s.pitch);- let _ = s.sphere;- let result = stitch::stitch_panorama(&frames, &yaw, &pitch)?;+ let result = stitch::stitch_panorama(&frames, &yaw, &pitch, s.sphere, s.focal_over_width)?; encode_jpeg(&result, 92) } @@ -139,7 +140,7 @@ fn serialize_estimate(est: &stitch::Estimate) -> Vec<u8> { // 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 path fails. fn do_estimate(s: &Session) -> Option<Vec<u8>> {- let est = stitch::estimate_pano(&s.frames, &s.yaw, &s.pitch)?;+ let est = stitch::estimate_pano(&s.frames, &s.yaw, &s.pitch, s.sphere, s.focal_over_width)?; Some(serialize_estimate(&est)) } @@ -160,7 +161,7 @@ mod tests { (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])+ let out = crate::stitch::stitch_panorama(&[a, b], &[0.0, 0.0], &[0.0, 0.0], false, 0.0) .expect("stitch returned None"); let dt = t0.elapsed(); let jpeg = encode_jpeg(&out, 92).expect("encode");@@ -219,7 +220,7 @@ mod tests { 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])+ let est = crate::stitch::estimate_pano(&[a, b], &[0.0, 0.0], &[0.0, 0.0], false, 0.0) .expect("estimate returned None"); let blob = serialize_estimate(&est); let u32_at = |o: usize| u32::from_le_bytes(blob[o..o + 4].try_into().unwrap());@@ -248,6 +249,7 @@ mod tests { assert!(gain.is_finite() && (0.5..=2.0).contains(&gain), "bad gain {gain}"); } }+ } mod jni_bindings {@@ -261,11 +263,18 @@ mod jni_bindings { _env: EnvUnowned<'l>, _class: JClass<'l>, sphere: jboolean,+ focal_over_width: jfloat, ) -> jlong { let h = next_handle(); registry().lock().unwrap().insert( h,- Session { sphere, frames: Vec::new(), yaw: Vec::new(), pitch: Vec::new() },+ Session {+ sphere,+ focal_over_width,+ frames: Vec::new(),+ yaw: Vec::new(),+ pitch: Vec::new(),+ }, ); h }@@ -333,6 +342,7 @@ mod jni_bindings { let session = match registry().lock().unwrap().get_mut(&handle) { Some(s) => Session { sphere: s.sphere,+ focal_over_width: s.focal_over_width, frames: std::mem::take(&mut s.frames), yaw: std::mem::take(&mut s.yaw), pitch: std::mem::take(&mut s.pitch),@@ -449,6 +459,7 @@ mod jni_bindings { let mut session = match registry().lock().unwrap().get_mut(&handle) { Some(s) => Session { sphere: s.sphere,+ focal_over_width: s.focal_over_width, frames: std::mem::take(&mut s.frames), yaw: std::mem::take(&mut s.yaw), pitch: std::mem::take(&mut s.pitch),
camera/src/main/rust/src/matching.rs
diff --git a/camera/src/main/rust/src/matching.rs b/camera/src/main/rust/src/matching.rsindex c69f41aa47..95fb71ab4c 100644--- a/camera/src/main/rust/src/matching.rs+++ b/camera/src/main/rust/src/matching.rs@@ -123,7 +123,13 @@ fn match_pair(src: usize, dst: usize, fs: &Features, fd: &Features) -> Option<Ma }) } -/// Angular separation (deg) between two frames' gyro orientations.+/// Angular separation (deg) between two frames' gyro orientations: the true+/// great-circle angle between their viewing directions. The old Euclidean+/// `sqrt(dyaw^2 + dpitch^2)` overestimates separation toward the poles — at+/// pitch 60° a 72° yaw step is really ~34° on the sphere — so the polar+/// rings of a sphere grid fell outside the matching window and were only+/// ever connected diagonally, weakening exactly the rows with the least+/// overlap to spare. 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 {@@ -132,8 +138,11 @@ fn angular_dist(yaw: &[f32], pitch: &[f32], i: usize, j: usize) -> f32 { if dy < -180.0 { dy += 360.0; }- let dp = pitch[i] - pitch[j];- (dy * dy + dp * dp).sqrt()+ let dy = dy.to_radians();+ let p1 = pitch[i].to_radians();+ let p2 = pitch[j].to_radians();+ let cos_ang = (p1.sin() * p2.sin() + p1.cos() * p2.cos() * dy.cos()).clamp(-1.0, 1.0);+ cos_ang.acos().to_degrees() } /// Match pairs (i<j). When per-frame gyro orientations are available, only pairs
camera/src/main/rust/src/matching_tests.rs
diff --git a/camera/src/main/rust/src/matching_tests.rs b/camera/src/main/rust/src/matching_tests.rsindex bdca6737f0..110f8f31d7 100644--- a/camera/src/main/rust/src/matching_tests.rs+++ b/camera/src/main/rust/src/matching_tests.rs@@ -14,19 +14,23 @@ fn angular_dist_zero_for_same_orientation() { #[test] fn angular_dist_wraps_yaw_across_zero() {- // 359° and 1° are 2° apart, not 358°.+ // 359° and 1° are 2° apart, not 358°. (Tolerance is loose: f32 acos+ // loses precision near 0 degrees.) let yaw = [359.0f32, 1.0]; let pitch = [0.0f32, 0.0];- assert!((angular_dist(&yaw, &pitch, 0, 1) - 2.0).abs() < 1e-5);+ assert!((angular_dist(&yaw, &pitch, 0, 1) - 2.0).abs() < 0.01); let yaw2 = [1.0f32, 359.0];- assert!((angular_dist(&yaw2, &pitch, 0, 1) - 2.0).abs() < 1e-5);+ assert!((angular_dist(&yaw2, &pitch, 0, 1) - 2.0).abs() < 0.01); } #[test]-fn angular_dist_combines_yaw_and_pitch_as_euclidean() {+fn angular_dist_combines_yaw_and_pitch_on_the_sphere() {+ // Small angles: great-circle distance matches the Euclidean 3-4-5 to+ // within f32 acos precision; large ones follow the sphere (covered by+ // angular_dist_uses_great_circle_not_euclidean_yaw_pitch). let yaw = [0.0f32, 3.0]; let pitch = [0.0f32, 4.0];- assert!((angular_dist(&yaw, &pitch, 0, 1) - 5.0).abs() < 1e-5, "3-4-5");+ assert!((angular_dist(&yaw, &pitch, 0, 1) - 5.0).abs() < 0.01, "3-4-5"); } #[test]@@ -121,3 +125,23 @@ fn match_all_gyro_gate_excludes_distant_pairs() { // Mismatched yaw length disables the gate (falls back to all pairs). let _ = match_all(&feats, &[0.0], &[0.0, 0.0], 55.0); }++#[test]+fn angular_dist_uses_great_circle_not_euclidean_yaw_pitch() {+ // At pitch 60 a 72-degree yaw step is only ~34 degrees on the sphere;+ // the old Euclidean metric reported 72 and excluded polar-ring+ // neighbours from the matching window entirely.+ let yaw = [0.0f32, 72.0];+ let pitch = [60.0f32, 60.0];+ let d = angular_dist(&yaw, &pitch, 0, 1);+ assert!(d > 30.0 && d < 40.0, "great-circle distance {d}");+ // Equator: yaw difference is the angle, unchanged.+ let d_eq = angular_dist(&[0.0, 30.0], &[0.0, 0.0], 0, 1);+ assert!((d_eq - 30.0).abs() < 0.01, "equatorial distance {d_eq}");+ // Pure pitch difference is the angle, unchanged.+ let d_p = angular_dist(&[10.0, 10.0], &[0.0, 30.0], 0, 1);+ assert!((d_p - 30.0).abs() < 0.01, "pitch distance {d_p}");+ // Yaw wrap: -170 vs 170 is 20 degrees, not 340.+ let d_w = angular_dist(&[-170.0, 170.0], &[0.0, 0.0], 0, 1);+ assert!((d_w - 20.0).abs() < 0.01, "wrapped distance {d_w}");+}
camera/src/main/rust/src/sphere.rs
diff --git a/camera/src/main/rust/src/sphere.rs b/camera/src/main/rust/src/sphere.rsindex fa67d95432..9c6ead5cbe 100644--- a/camera/src/main/rust/src/sphere.rs+++ b/camera/src/main/rust/src/sphere.rs@@ -63,7 +63,28 @@ fn sanitize(f: Option<f64>) -> Option<f64> { /// OpenCV `estimateFocal`: median of sqrt(f0*f1) over pairwise homographies that /// yield both focals; falls back to (w + h) when nothing is estimable.+/// (Production uses [`estimate_focal_with_prior`]; this parity entry point is+/// exercised by the focal-estimation tests.)+#[allow(dead_code)] pub fn estimate_focal(pairs: &[Matrix3<f64>], w: usize, h: usize) -> f64 {+ estimate_focal_with_prior(pairs, w, h, None)+}++/// [`estimate_focal`] with a device-intrinsics prior (focal length in pixels+/// at this resolution, from the camera HAL). When no homography yields a+/// focal, the old fallback `(w + h)` implies a ~32° FOV at 640x480 — wildly+/// wrong for a real wide lens, and the warp then crushes every frame into a+/// narrow wedge that blends into a ghosted stack. With a prior, the fallback+/// is the measured lens focal, and any homography estimate is clamped to+/// [0.5, 2.0]x the prior (HAL focals are accurate to a few percent; a+/// homography estimate outside that band is estimation noise, not truth).+pub fn estimate_focal_with_prior(+ pairs: &[Matrix3<f64>],+ w: usize,+ h: usize,+ prior: Option<f64>,+) -> f64 {+ let prior = prior.filter(|v| v.is_finite() && *v > 1.0); let mut all = Vec::new(); for hmat in pairs { let (f0, f1) = focals_from_homography(hmat);@@ -72,14 +93,18 @@ pub fn estimate_focal(pairs: &[Matrix3<f64>], w: usize, h: usize) -> f64 { } } if all.is_empty() {- return (w + h) as f64;+ return prior.unwrap_or((w + h) as f64); } all.sort_by(|a, b| a.total_cmp(b)); let m = all.len() / 2;- if all.len() % 2 == 1 {+ let median = if all.len() % 2 == 1 { all[m] } else { (all[m - 1] + all[m]) / 2.0+ };+ match prior {+ Some(p) => median.clamp(0.5 * p, 2.0 * p),+ None => median, } } @@ -334,6 +359,29 @@ pub fn warp_one(frame: &Rgba, k: &Matrix3<f64>, r: &Matrix3<f64>, scale: f64) -> Some(WarpedTile { img, corner_x: cx, corner_y: cy }) } +/// Full-sphere equirect canvas for warp `scale`: width spans 360°, height+/// 180°, so `canvas_w == 2 * canvas_h` exactly and the GPano geometry written+/// for the result describes a real 360x180 sphere. Returns+/// (canvas_w, canvas_h, u0, v0) with u0 = -canvas_w/2, v0 = 0.+pub fn sphere_canvas(scale: f64) -> (u32, u32, f64, f64) {+ let mut w = (2.0 * std::f64::consts::PI * scale).round() as u32;+ if w % 2 == 1 {+ w += 1;+ }+ let w = w.max(2);+ (w, w / 2, -(w as f64) / 2.0, 0.0)+}++/// Device focal prior in registration-resolution pixels, from the HAL focal+/// expressed as focal-over-frame-width at full resolution (0 = unknown).+pub fn focal_prior_reg(focal_over_width: f32, full_w: usize, reg_scale: f64) -> Option<f64> {+ if focal_over_width > 0.0 && focal_over_width.is_finite() {+ Some(focal_over_width as f64 * full_w as f64 * reg_scale)+ } else {+ None+ }+}+ #[cfg(test)] mod sphere_host_tests { use super::*;
camera/src/main/rust/src/sphere_tests.rs
diff --git a/camera/src/main/rust/src/sphere_tests.rs b/camera/src/main/rust/src/sphere_tests.rsindex 191ea26ff2..71a0ad86bd 100644--- a/camera/src/main/rust/src/sphere_tests.rs+++ b/camera/src/main/rust/src/sphere_tests.rs@@ -182,3 +182,32 @@ fn sample_reflect_101_mirrors_at_borders() { let clear = Rgba::new(4, 4); assert!(sample_reflect_101(&clear, 1.0, 1.0).is_none()); }++#[test]+fn estimate_focal_with_prior_falls_back_to_lens_not_w_plus_h() {+ // No valid homography pair: with a HAL prior the fallback is the real+ // lens focal, not (w + h) (~32 deg FOV at 640x480).+ assert_eq!(estimate_focal_with_prior(&[], 640, 480, Some(500.0)), 500.0);+ assert_eq!(estimate_focal_with_prior(&[Matrix3::identity()], 640, 480, Some(500.0)), 500.0);+ // Without a prior the historical fallback is unchanged.+ assert_eq!(estimate_focal_with_prior(&[], 640, 480, None), 1120.0);+ // A non-finite / degenerate prior is ignored.+ assert_eq!(estimate_focal_with_prior(&[], 640, 480, Some(f64::NAN)), 1120.0);+ assert_eq!(estimate_focal_with_prior(&[], 640, 480, Some(0.5)), 1120.0);+}++#[test]+fn estimate_focal_with_prior_clamps_noisy_homography_estimates() {+ // True focal 500 homography, but the device prior says 100: a homography+ // estimate 5x the measured lens focal is noise, clamped to 2x prior.+ let k = k_matrix(500.0, 320.0, 240.0);+ let kinv = k.try_inverse().unwrap();+ let r = rodrigues_to_mat(Vector3::new(0.0, 0.3, 0.0));+ let h = k * r * kinv;+ let clamped = estimate_focal_with_prior(&[h], 640, 480, Some(100.0));+ assert!(approx(clamped, 200.0, 1e-9), "clamped focal {clamped}");+ // A plausible prior (within band) leaves the estimate untouched.+ let raw = estimate_focal(&[h], 640, 480);+ let kept = estimate_focal_with_prior(&[h], 640, 480, Some(raw));+ assert!(approx(kept, raw, 1e-9), "in-band estimate {kept} vs {raw}");+}
camera/src/main/rust/src/stitch.rs
diff --git a/camera/src/main/rust/src/stitch.rs b/camera/src/main/rust/src/stitch.rsindex 333867bbb3..1f0ef90a3c 100644--- a/camera/src/main/rust/src/stitch.rs+++ b/camera/src/main/rust/src/stitch.rs@@ -4,7 +4,8 @@ //! captured resolution. Matching is windowed to nearby frames and the slow //! stages are parallelised with rayon. -use crate::blend::multiband_blend;+use crate::blend::{build_compose_masks, multiband_blend, multiband_blend_with_rect, resize_gain};+use crate::sphere::{focal_prior_reg, sphere_canvas}; use crate::bundle::bundle_adjust; use crate::camera::CameraParams; use crate::estimator::estimate_cameras;@@ -104,12 +105,22 @@ fn median_f32(vals: &[f32]) -> f32 { } } + /// 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> {+/// expensive per-pixel warp/seam/blend (those move to the GPU). In sphere+/// mode the canvas is the full 360x180 equirect (see [`sphere_canvas`]), not+/// the warped tiles' bounding box: labelling a bounding box as a full sphere+/// is what made viewers wrap/stretch sphere results beyond recognition.+pub fn estimate_pano(+ frames_jpeg: &[Vec<u8>],+ yaw: &[f32],+ pitch: &[f32],+ sphere: bool,+ focal_over_width: f32,+) -> Option<Estimate> { let n = frames_jpeg.len(); if n < 2 { return None;@@ -151,7 +162,13 @@ pub fn estimate_pano(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> Opt } let m = kept.len(); - let mut cams = estimate_cameras(m, reg_w, reg_h, &matches);+ let mut cams = estimate_cameras(+ m,+ reg_w,+ reg_h,+ &matches,+ focal_prior_reg(focal_over_width, full_w, reg_scale),+ ); bundle_adjust(&mut cams, &matches); wave_correct_horizontal(&mut cams); @@ -164,11 +181,15 @@ pub fn estimate_pano(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> Opt // 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.+ // A sphere canvas is the whole 360x180 equirect (2*pi^2*scale^2 px), a flat+ // panorama the warped tiles' bounding box. let mut scale = median_focal(&cams); if !scale.is_finite() || scale <= 1.0 { return None; }- let compose_area = {+ let compose_area = if sphere {+ 2.0 * std::f64::consts::PI * std::f64::consts::PI * scale * scale+ } else { let mut gx0 = f64::MAX; let mut gy0 = f64::MAX; let mut gx1 = f64::MIN;@@ -187,21 +208,31 @@ pub fn estimate_pano(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> Opt 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);+ // Final canvas geometry: the full equirect for a sphere, else the warped+ // tiles' global bounds.+ let (canvas_w, canvas_h, gx0, gy0) = if sphere {+ let (w, h, u0, v0) = sphere_canvas(scale);+ (w as i64, h as i64, u0, v0)+ } else {+ 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);+ if !gx0.is_finite() || !gy0.is_finite() || !gx1.is_finite() || !gy1.is_finite() {+ return None;+ }+ (+ ((gx1 - gx0).ceil() as i64 + 1).max(1),+ ((gy1 - gy0).ceil() as i64 + 1).max(1),+ gx0,+ gy0,+ )+ }; // 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();@@ -238,7 +269,13 @@ pub fn estimate_pano(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> Opt }) } -pub fn stitch_panorama(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> Option<Rgba> {+pub fn stitch_panorama(+ frames_jpeg: &[Vec<u8>],+ yaw: &[f32],+ pitch: &[f32],+ sphere: bool,+ focal_over_width: f32,+) -> Option<Rgba> { let n = frames_jpeg.len(); if n == 0 { return None;@@ -286,7 +323,13 @@ pub fn stitch_panorama(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> O let m = kept.len(); // 4) estimate cameras -> 5) bundle adjust -> 6) wave correct (all at reg res)- let mut cams = estimate_cameras(m, reg_w, reg_h, &matches);+ let mut cams = estimate_cameras(+ m,+ reg_w,+ reg_h,+ &matches,+ focal_prior_reg(focal_over_width, full_w, reg_scale),+ ); bundle_adjust(&mut cams, &matches); wave_correct_horizontal(&mut cams); @@ -306,7 +349,10 @@ pub fn stitch_panorama(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> O if !scale.is_finite() || scale <= 1.0 { return None; }- let mut compose_area = {+ let mut compose_area = if sphere {+ // The sphere output is the full 360x180 equirect, not the tile bbox.+ 2.0 * std::f64::consts::PI * std::f64::consts::PI * scale * scale+ } else { let mut gx0 = f64::MAX; let mut gy0 = f64::MAX; let mut gx1 = f64::MIN;@@ -351,94 +397,44 @@ pub fn stitch_panorama(frames_jpeg: &[Vec<u8>], yaw: &[f32], pitch: &[f32]) -> O .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(); - multiband_blend(&tiles, &masks, &gain_maps)-}--/// 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;+ if !sphere {+ return multiband_blend(&tiles, &masks, &gain_maps); }+ // Sphere: paste the cropped blend onto the full 360x180 equirect canvas+ // at its true longitude/latitude (wrapping at the +-180 meridian), so the+ // JPEG itself is the full sphere the GPano tags describe. Uncovered+ // pixels stay transparent-black; with pole-reaching waypoints there+ // should be none.+ let (blended, crop_x, crop_y) = multiband_blend_with_rect(&tiles, &masks, &gain_maps)?;+ let (canvas_w, canvas_h, u0, v0) = sphere_canvas(scale);+ let (canvas_w, canvas_h) = (canvas_w as usize, canvas_h as usize); let mut gx0 = i32::MAX; let mut gy0 = i32::MAX;- let mut gx1 = i32::MIN;- let mut gy1 = i32::MIN;- for t in tiles {+ 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;+ // Blended image top-left in sphere (u, v), then in canvas pixels.+ let origin_x = gx0 + crop_x as i32 - u0.round() as i32;+ let origin_y = gy0 + crop_y as i32 - v0.round() as i32;+ let mut canvas = Rgba::new(canvas_w, canvas_h);+ for y in 0..blended.h {+ let cy = origin_y + y as i32;+ if cy < 0 || cy >= canvas_h as i32 {+ continue;+ }+ for x in 0..blended.w {+ let px = blended.get(x, y);+ if px[3] == 0 {+ continue; }+ let cx = (origin_x + x as i32).rem_euclid(canvas_w as i32);+ canvas.set(cx as usize, cy as usize, px); } }- masks+ Some(canvas) } -/// Bilinear upscale of a per-pixel gain map.-fn resize_gain(src: &[f32], sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<f32> {- if sw == 0 || sh == 0 {- return vec![1.0f32; dw * dh];- }- let mut out = vec![1.0f32; dw * dh];- for y in 0..dh {- let fy = ((y as f64 + 0.5) * sh as f64 / dh as f64 - 0.5).clamp(0.0, sh as f64 - 1.0);- let y0 = fy.floor() as usize;- let y1 = (y0 + 1).min(sh - 1);- let ay = (fy - y0 as f64) as f32;- for x in 0..dw {- let fx = ((x as f64 + 0.5) * sw as f64 / dw as f64 - 0.5).clamp(0.0, sw as f64 - 1.0);- let x0 = fx.floor() as usize;- let x1 = (x0 + 1).min(sw - 1);- let ax = (fx - x0 as f64) as f32;- let g00 = src[y0 * sw + x0];- let g10 = src[y0 * sw + x1];- let g01 = src[y1 * sw + x0];- let g11 = src[y1 * sw + x1];- let top = g00 * (1.0 - ax) + g10 * ax;- let bot = g01 * (1.0 - ax) + g11 * ax;- out[y * dw + x] = top * (1.0 - ay) + bot * ay;- }- }- out-} #[cfg(test)] #[path = "stitch_tests.rs"]
camera/src/main/rust/src/stitch_tests.rs
diff --git a/camera/src/main/rust/src/stitch_tests.rs b/camera/src/main/rust/src/stitch_tests.rsindex b90a9b492f..62f0ebe05b 100644--- a/camera/src/main/rust/src/stitch_tests.rs+++ b/camera/src/main/rust/src/stitch_tests.rs@@ -122,8 +122,46 @@ fn build_compose_masks_empty_input_gives_empty_masks() { #[test] fn stitch_panorama_degenerate_inputs_return_none_or_single_frame() {- assert!(stitch_panorama(&[], &[], &[]).is_none());- assert!(stitch_panorama(&[vec![1, 2, 3]], &[0.0], &[0.0]).is_none(), "bad JPEG");- assert!(estimate_pano(&[vec![1, 2, 3]], &[0.0], &[0.0]).is_none(), "needs >= 2 frames");- assert!(estimate_pano(&[], &[], &[]).is_none());+ assert!(stitch_panorama(&[], &[], &[], false, 0.0).is_none());+ assert!(stitch_panorama(&[vec![1, 2, 3]], &[0.0], &[0.0], false, 0.0).is_none(), "bad JPEG");+ assert!(estimate_pano(&[vec![1, 2, 3]], &[0.0], &[0.0], false, 0.0).is_none(), "needs >= 2 frames");+ assert!(estimate_pano(&[], &[], &[], false, 0.0).is_none());+}++#[test]+fn sphere_canvas_is_exactly_two_to_one() {+ // GPano equirect geometry: full width must be exactly twice full height,+ // with u0 at -180 degrees and v0 at the north pole.+ let (w, h, u0, v0) = sphere_canvas(1000.0);+ assert_eq!(w, 2 * h);+ assert_eq!(u0, -(w as f64) / 2.0);+ assert_eq!(v0, 0.0);+ // Odd circumferences round up to an even width so 2:1 stays exact.+ let (w2, h2, _, _) = sphere_canvas(1000.3);+ assert_eq!(w2, 2 * h2);+}++#[test]+fn focal_prior_reg_scales_and_rejects_unknown() {+ // focal_over_width 0.8 at 1000px wide, half-scale registration -> 400px.+ let prior = focal_prior_reg(0.8, 1000, 0.5).expect("prior");+ assert!((prior - 400.0).abs() < 0.01, "prior {prior}");+ assert_eq!(focal_prior_reg(0.0, 1000, 0.5), None);+ assert_eq!(focal_prior_reg(-1.0, 1000, 0.5), None);+ assert_eq!(focal_prior_reg(f32::NAN, 1000, 0.5), None);+}++#[test]+fn estimate_sphere_uses_full_equirect_canvas() {+ let a = std::fs::read("testdata/q11.jpg").expect("read sample a");+ let b = std::fs::read("testdata/q22.jpg").expect("read sample b");+ let est = estimate_pano(&[a, b], &[0.0, 0.0], &[0.0, 0.0], true, 0.0)+ .expect("sphere estimate returned None");+ // A sphere result must be a true 360x180 equirect: exactly 2:1, u0 at+ // -180 degrees, v0 at the north pole — otherwise GPano viewers+ // (Google Photos) wrap a bounding box as if it were the whole sphere.+ assert_eq!(est.canvas_w, 2 * est.canvas_h, "equirect must be 2:1");+ assert_eq!(est.u0, -(est.canvas_w as f64) / 2.0, "u0 must be -180deg in px");+ assert_eq!(est.v0, 0.0, "v0 must be the north pole");+ assert!(est.scale.is_finite() && est.scale > 1.0, "bad scale {}", est.scale); }
camera/src/test/java/com/vayunmathur/camera/domain/PanoXmpTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/PanoXmpTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/PanoXmpTest.ktindex 0f33d711da..dc7c69d54c 100644--- a/camera/src/test/java/com/vayunmathur/camera/domain/PanoXmpTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/domain/PanoXmpTest.kt@@ -41,6 +41,30 @@ class PanoXmpTest { assertTrue(xmp.contains("GPano:FullPanoWidthPixels=\"8000\""), xmp) } + @Test fun spherePacketDescribesFullEquirectWithCropWindow() {+ // Partial-coverage sphere: the JPEG is a crop window inside the full+ // 360x180 equirect (2:1). Google Photos renders the sphere from the+ // full dimensions + crop offsets, so all six must agree with reality.+ val partial = PanoInfo(+ projectionType = "equirectangular",+ fullWidth = 6000,+ fullHeight = 3000,+ croppedWidth = 5000,+ croppedHeight = 2400,+ croppedLeft = 500,+ croppedTop = 300,+ )+ assertEquals(partial.fullWidth, 2 * partial.fullHeight, "equirect full pano must be 2:1")+ val xmp = PanoXmp.buildGPanoXmp(partial)+ assertTrue(xmp.contains("GPano:ProjectionType=\"equirectangular\""), xmp)+ assertTrue(xmp.contains("GPano:FullPanoWidthPixels=\"6000\""), xmp)+ assertTrue(xmp.contains("GPano:FullPanoHeightPixels=\"3000\""), xmp)+ assertTrue(xmp.contains("GPano:CroppedAreaImageWidthPixels=\"5000\""), xmp)+ assertTrue(xmp.contains("GPano:CroppedAreaImageHeightPixels=\"2400\""), xmp)+ assertTrue(xmp.contains("GPano:CroppedAreaLeftPixels=\"500\""), xmp)+ assertTrue(xmp.contains("GPano:CroppedAreaTopPixels=\"300\""), xmp)+ }+ @Test fun injectAfterSoi() { val jpeg = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0x11, 0x22, 0x33) val out = PanoXmp.injectXmp(jpeg, "<x/>")
camera/src/test/java/com/vayunmathur/camera/domain/SphereWaypointsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/SphereWaypointsTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/SphereWaypointsTest.ktnew file mode 100644index 0000000000..1e5fd9a5fa--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/SphereWaypointsTest.kt@@ -0,0 +1,137 @@+package com.vayunmathur.camera.domain++import kotlin.math.cos+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Pure-JVM tests for [SphereWaypoints] spacing/overlap math and [SphereOrientation]. */+class SphereWaypointsTest {++ /** Every row's true on-sphere yaw spacing must keep at least the target overlap. */+ private fun assertOverlapHeld(hFov: Float, vFov: Float) {+ val wps = SphereWaypoints.generate(hFov, vFov)+ val byPitch = wps.groupBy { Math.round(it.pitchDeg) }+ for ((pitch, row) in byPitch) {+ val step = 360f / row.size+ val onSphereStep = step * cos(Math.toRadians(pitch.toDouble())).toFloat()+ val overlap = 1f - onSphereStep / hFov+ assertTrue(+ overlap >= SphereWaypoints.OVERLAP_FRACTION - 0.01f,+ "pitch $pitch step $onSphereStep overlap $overlap < target (hFov $hFov)",+ )+ assertTrue(row.all { it.yawDeg >= 0f && it.yawDeg < 360f }, "yaw range at pitch $pitch")+ }+ // Pitch rows are spaced by at most vFov * (1 - overlap), so vertical+ // neighbours overlap by at least the target too.+ val pitches = byPitch.keys.map { it.toFloat() }.sorted()+ val maxGap = pitches.zipWithNext { a, b -> b - a }.maxOrNull() ?: 0f+ assertTrue(+ maxGap <= vFov * (1f - SphereWaypoints.OVERLAP_FRACTION) + 1f,+ "pitch gap $maxGap too wide for vFov $vFov",+ )+ // The top row's frame edge must reach the pole (no black cap).+ val maxPitch = pitches.maxOf { kotlin.math.abs(it) }+ assertTrue(maxPitch + vFov / 2f >= 89f, "pole uncovered: maxPitch $maxPitch vFov $vFov")+ // And no waypoint may sit beyond the pole.+ assertTrue(wps.all { kotlin.math.abs(it.pitchDeg) <= 90f }, "waypoint past pole")+ }++ @Test fun spacingHoldsForRepresentativeFovs() {+ // Portrait-held frames: (horizontal, vertical) FOV in degrees.+ assertOverlapHeld(50f, 66f) // typical 1x wide (~27mm eq)+ assertOverlapHeld(85f, 95f) // ultrawide (~14mm eq)+ assertOverlapHeld(26f, 36f) // telephoto (~70mm eq)+ assertOverlapHeld(47.9f, 67.4f) // exactly 27mm eq via fovFromEq35+ }++ @Test fun defaultFovLayoutShape() {+ val wps = SphereWaypoints.generate(+ SphereWaypoints.DEFAULT_H_FOV_DEG,+ SphereWaypoints.DEFAULT_V_FOV_DEG,+ )+ // Equator 12 (30 deg steps) + two rows of 10 at ~40 deg + two cap+ // rows of 7 at 57 deg whose edges reach the poles.+ assertEquals(46, wps.size)+ assertEquals(12, wps.count { it.pitchDeg == 0f })+ assertEquals(+ listOf(-57, -40, 0, 40, 57),+ wps.map { Math.round(it.pitchDeg) }.distinct().sorted(),+ )+ // First waypoint is the equator start; the guide order starts there.+ assertEquals(SphereWaypoint(0f, 0f), wps.first())+ }++ @Test fun narrowerLensGetsMoreWaypoints() {+ val wide = SphereWaypoints.generate(85f, 95f).size+ val main = SphereWaypoints.generate(50f, 66f).size+ val tele = SphereWaypoints.generate(26f, 36f).size+ assertTrue(wide < main && main < tele, "counts wide=$wide main=$main tele=$tele")+ }++ @Test fun fovFromEq35MatchesFullFrameGeometry() {+ val (h, v) = SphereWaypoints.fovFromEq35(27f)+ // Portrait frame: width spans 24mm, height spans 36mm of the sensor.+ assertEquals(47.9f, h, 0.6f)+ assertEquals(67.4f, v, 0.6f)+ }++ @Test fun focalOverWidthMatchesFov() {+ // 60 deg horizontal FOV -> f/w = 0.5 / tan(30 deg).+ assertEquals(0.866f, SphereWaypoints.focalOverWidth(60f), 0.01f)+ // Narrower FOV -> longer focal per width.+ assertTrue(SphereWaypoints.focalOverWidth(30f) > SphereWaypoints.focalOverWidth(60f))+ }+}++/** Pure-JVM tests for [SphereOrientation] relative-rotation decomposition. */+class SphereOrientationTest {++ private fun ry(deg: Float): FloatArray {+ val r = Math.toRadians(deg.toDouble())+ val c = cos(r).toFloat()+ val s = kotlin.math.sin(r).toFloat()+ return floatArrayOf(c, 0f, s, 0f, 1f, 0f, -s, 0f, c)+ }++ private fun rx(deg: Float): FloatArray {+ val r = Math.toRadians(deg.toDouble())+ val c = cos(r).toFloat()+ val s = kotlin.math.sin(r).toFloat()+ return floatArrayOf(1f, 0f, 0f, 0f, c, -s, 0f, s, c)+ }++ private val identity = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f)++ @Test fun pureYawAndPitchExtractExactly() {+ val (yaw, pitch) = SphereOrientation.yawPitchDegrees(ry(30f))+ assertEquals(30f, yaw, 0.01f)+ assertEquals(0f, pitch, 0.01f)+ val (yaw2, pitch2) = SphereOrientation.yawPitchDegrees(rx(20f))+ assertEquals(0f, yaw2, 0.01f)+ assertEquals(20f, pitch2, 0.01f)+ val (yaw3, pitch3) = SphereOrientation.yawPitchDegrees(rx(-45f))+ assertEquals(-45f, pitch3, 0.01f)+ assertEquals(0f, yaw3, 0.01f)+ }++ @Test fun relativeRotationRemovesTheReference() {+ // Sweep started already yawed 10 deg; current 40 deg -> relative 30.+ val rel = SphereOrientation.relativeRotation(ry(10f), ry(40f))+ val (yaw, _) = SphereOrientation.yawPitchDegrees(rel)+ assertEquals(30f, yaw, 0.01f)+ // Identity reference passes the current orientation through.+ val rel2 = SphereOrientation.relativeRotation(identity, rx(15f))+ val (_, pitch2) = SphereOrientation.yawPitchDegrees(rel2)+ assertEquals(15f, pitch2, 0.01f)+ }++ @Test fun relativeRotationIsIdentityForSameOrientation() {+ val rel = SphereOrientation.relativeRotation(ry(25f), ry(25f))+ for (i in 0..2) {+ for (j in 0..2) {+ assertEquals(if (i == j) 1f else 0f, rel[i * 3 + j], 0.001f)+ }+ }+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/PanoramaEngineExtraTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/PanoramaEngineExtraTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/PanoramaEngineExtraTest.ktindex 31c836b6ef..46a811907d 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/PanoramaEngineExtraTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/PanoramaEngineExtraTest.kt@@ -64,12 +64,19 @@ class PanoramaEngineExtraTest { assertTrue(!e.isSweeping.value) } - @Test fun sphereSweepLaysOutFortyDotsAcrossPitchRows() {+ @Test fun sphereSweepLaysOutFovDerivedDotsAcrossPitchRows() { val e = engine() e.startSweep(fullSphere = true) val dots = e.guideDots.value- assertEquals(40, dots.size)- assertEquals(listOf(0f, -30f, 30f, -60f, 60f), dots.map { it.targetPitch }.distinct())+ // Default-FOV layout (SphereWaypointsTest pins the math): equator+ // ring plus alternating pitch rows whose frame edges reach the poles.+ assertEquals(46, dots.size)+ assertEquals(+ listOf(-57, -40, 0, 40, 57),+ dots.map { Math.round(it.targetPitch) }.distinct().sorted(),+ )+ assertEquals(GuideDotState.CAPTURING, dots[0].state)+ assertTrue(dots.drop(1).all { it.state == GuideDotState.PENDING }) e.stopSweep() }