From 374347d39d85010e2415884c86c1898c5648a4b8 Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 02:59:01 -0500 Subject: [PATCH 1/4] Report the camera's field of view The angle a camera can see is what maps a direction in the world onto a position on the preview, so anything drawn over the camera to point at something needs it - a marker on a landmark, an arrow towards a place, a pillar over where something was left. The library published nothing about its optics, so none of that could be placed: without the angle of view there is no way to turn "30 degrees to my right" into a screen coordinate. Worked out from the sensor's physical size and the focal length in front of it, with the maths in TransformMath beside the rest of the camera geometry, where it is unit tested against arithmetic that can be checked by hand and covered by the strict gate. Two things here are easy to get wrong and both are now pinned by tests. Zoom narrows the view by the tangent of the half-angle rather than by the ratio, so a 60-degree view at 2x is 32.2 degrees and not 30 - dividing would misplace a marker, and more badly the further from centre it is. And the first published focal length is the right one to measure, not the shortest: a zoom ratio of one means the lens the camera uses by default, which the array leads with, while the shortest belongs to the ultra-wide that the ratio reaches by going below one, so taking it and then applying the ratio counts it twice. All three backends answer. Camera2 reads the characteristics and goes through the same effective zoom ratio that setZoomLevel applies - both mechanisms, the ratio control and the active-array crop - so the reported angle cannot disagree with the request that produced the picture. The crop-zoom formula now has one definition instead of two. The legacy API reports the angle itself and only needs its zoom taken off. CameraX has no opinion on optics, so it reads the same two characteristics through Camera2CameraInfo and takes the ratio from its own zoom state. A camera that publishes neither returns 0 rather than having a plausible angle invented for it, and FakeCamera2 now publishes a sensor and lens so the backend path is asserted against known numbers. Co-Authored-By: Claude Opus 5 --- .github/workflows/android-validation.yml | 2 +- README.md | 17 +++++ .../com/xlythe/view/camera/CameraView.java | 22 ++++++ .../com/xlythe/view/camera/ICameraModule.java | 15 ++++ .../com/xlythe/view/camera/TransformMath.java | 37 ++++++++++ .../camera/legacy/LegacyCameraModule.java | 42 +++++++++++ .../xlythe/view/camera/v2/Camera2Module.java | 74 ++++++++++++++++++- .../xlythe/view/camera/x/CameraXModule.java | 50 +++++++++++++ .../xlythe/view/camera/TransformMathTest.java | 65 ++++++++++++++++ .../view/camera/v2/Camera2SessionTest.java | 28 +++++++ .../xlythe/view/camera/v2/FakeCamera2.java | 7 ++ 11 files changed, 356 insertions(+), 3 deletions(-) diff --git a/.github/workflows/android-validation.yml b/.github/workflows/android-validation.yml index 805681b..6450d98 100644 --- a/.github/workflows/android-validation.yml +++ b/.github/workflows/android-validation.yml @@ -78,7 +78,7 @@ jobs: if [ -e /dev/kvm ]; then sudo chmod 666 /dev/kvm fi - - name: Run API 30 and API 37 managed-device tests + - name: Run API 28 and API 37 managed-device tests run: >- ./gradlew --no-daemon --stacktrace :camera-view:cameraMatrixGroupDebugAndroidTest diff --git a/README.md b/README.md index 8ac540c..33c1672 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,23 @@ mCameraView.setFaceDetectionListener((faces, faceToView) -> { mCameraView.setFaceDetectionListener(null); ``` +Field of view +----------------- +getHorizontalFieldOfView and getVerticalFieldOfView report the angle, in degrees, that the camera +can currently see. That is what turns a direction in the world into a position on the preview, so +anything drawn over the camera to point at something needs it: a bearing half the angle of view +away from where the camera points sits at the edge of the preview, a quarter sits halfway out. + +Both narrow as the camera zooms in, so read them again after changing the zoom, and both return 0 +when the camera is closed or does not publish its optics. Pair them with +getRelativeCameraOrientation to know which way round the frame is. +```java +float fov = mCameraView.getHorizontalFieldOfView(); +// bearing is degrees clockwise from where the camera points, negative to the left +float x = getWidth() * (0.5f + (float) Math.tan(Math.toRadians(bearing)) + / (2f * (float) Math.tan(Math.toRadians(fov / 2)))); +``` + Frames ----------------- startFrameAnalysis hands every frame to your own analyzer, on a background thread, for detection diff --git a/camera-view/src/main/java/com/xlythe/view/camera/CameraView.java b/camera-view/src/main/java/com/xlythe/view/camera/CameraView.java index fc6bb16..6e68999 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/CameraView.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/CameraView.java @@ -1271,6 +1271,28 @@ public void startFrameAnalysis( mFrameStream.start(); } + /** + * The horizontal angle of view, in degrees, that the camera can currently see. + * + *

This is what turns a direction in the world into a position on screen, so anything drawn + * over the preview to point at something - a marker on a landmark, an arrow towards a place - + * needs it. A bearing that is half the angle of view away from where the camera is pointed sits + * at the edge of the preview; one at a quarter sits halfway out.

+ * + *

It narrows as the camera zooms in, so read it again after changing the zoom. Use it with + * {@link #getRelativeCameraOrientation} to know which way the frame is turned.

+ * + * @return the angle in degrees, or 0 if the camera is closed or does not publish its optics + */ + public float getHorizontalFieldOfView() { + return mCameraModule.getHorizontalFieldOfView(); + } + + /** The vertical angle of view, on the same terms as {@link #getHorizontalFieldOfView}. */ + public float getVerticalFieldOfView() { + return mCameraModule.getVerticalFieldOfView(); + } + /** * Whether {@link #startFrameAnalysis} will work on the backend in use. * diff --git a/camera-view/src/main/java/com/xlythe/view/camera/ICameraModule.java b/camera-view/src/main/java/com/xlythe/view/camera/ICameraModule.java index d396a47..fcb6b98 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/ICameraModule.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/ICameraModule.java @@ -435,6 +435,21 @@ protected final void onCameraReady() { getView().onCameraReady(); } + /** + * The horizontal angle of view, in degrees, of the camera as it is currently configured. + * + *

Zero when the camera does not publish enough to work it out. Includes the effect of + * zoom, because a zoomed camera sees less.

+ */ + public float getHorizontalFieldOfView() { + return 0f; + } + + /** The vertical angle of view, on the same terms as {@link #getHorizontalFieldOfView}. */ + public float getVerticalFieldOfView() { + return 0f; + } + /** * Whether this backend can deliver frames to an analyzer. * diff --git a/camera-view/src/main/java/com/xlythe/view/camera/TransformMath.java b/camera-view/src/main/java/com/xlythe/view/camera/TransformMath.java index 72d230a..1aeec09 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/TransformMath.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/TransformMath.java @@ -25,6 +25,43 @@ public final class TransformMath { private TransformMath() {} + /** + * The angle of view a lens of this focal length sees across a sensor of this size. + * + *

Both arguments are in the same unit - millimetres, as a camera reports them - and which + * dimension of the sensor is passed in decides whether the answer is the horizontal or the + * vertical angle.

+ * + * @return the angle in degrees, or 0 when either measurement is missing + */ + public static float fieldOfViewDegrees(float sensorSizeMm, float focalLengthMm) { + if (sensorSizeMm <= 0f || focalLengthMm <= 0f) { + return 0f; + } + return (float) Math.toDegrees(2 * Math.atan(sensorSizeMm / (2 * focalLengthMm))); + } + + /** + * The angle of view that is left after zooming in. + * + *

Zoom is a crop, so it narrows what the camera sees. It does not narrow it in proportion + * to the zoom ratio, though - halving the visible width halves the tangent of the half-angle, + * not the angle - which is why anything drawn over the preview by bearing has to go through + * this rather than dividing.

+ * + * @return the angle in degrees, or 0 when either argument is missing + */ + public static float zoomedFieldOfViewDegrees(float fieldOfViewDegrees, float zoomRatio) { + if (fieldOfViewDegrees <= 0f || zoomRatio <= 0f) { + return 0f; + } + if (zoomRatio == 1f) { + return fieldOfViewDegrees; + } + double halfAngle = Math.toRadians(fieldOfViewDegrees) / 2; + return (float) Math.toDegrees(2 * Math.atan(Math.tan(halfAngle) / zoomRatio)); + } + /** Normalizes any rotation, including negative ones, into [0, 360). */ public static int within360(int rotationDegrees) { return ((rotationDegrees % 360) + 360) % 360; diff --git a/camera-view/src/main/java/com/xlythe/view/camera/legacy/LegacyCameraModule.java b/camera-view/src/main/java/com/xlythe/view/camera/legacy/LegacyCameraModule.java index 883aa51..f7abe88 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/legacy/LegacyCameraModule.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/legacy/LegacyCameraModule.java @@ -505,6 +505,48 @@ protected int getRelativeCameraOrientation() { return getRelativeCameraOrientation(true /* isPreview */); } + /** + * The angle of view, which this API reports itself. + * + *

Camera.Parameters gives the angle for the lens wide open, with no account of zoom, so + * the zoom this module has applied is taken off here to match what the preview is showing. + *

+ */ + @Override + public float getHorizontalFieldOfView() { + return fieldOfView(true /* horizontal */); + } + + @Override + public float getVerticalFieldOfView() { + return fieldOfView(false /* horizontal */); + } + + private float fieldOfView(boolean horizontal) { + Camera camera = mCamera; + if (camera == null) { + return 0f; + } + try { + Camera.Parameters parameters = camera.getParameters(); + float full = horizontal + ? parameters.getHorizontalViewAngle() : parameters.getVerticalViewAngle(); + if (!parameters.isZoomSupported()) { + return full; + } + List ratios = parameters.getZoomRatios(); + int index = parameters.getZoom(); + if (ratios == null || index < 0 || index >= ratios.size()) { + return full; + } + // getZoomRatios is in hundredths, so 100 is no zoom at all. + return TransformMath.zoomedFieldOfViewDegrees(full, ratios.get(index) / 100f); + } catch (RuntimeException error) { + if (DEBUG) Log.d(TAG, "Could not work out the field of view", error); + return 0f; + } + } + /** * No: this backend draws frames rather than producing them. * diff --git a/camera-view/src/main/java/com/xlythe/view/camera/v2/Camera2Module.java b/camera-view/src/main/java/com/xlythe/view/camera/v2/Camera2Module.java index fc7b829..6efb115 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/v2/Camera2Module.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/v2/Camera2Module.java @@ -30,6 +30,7 @@ import android.util.Log; import android.util.Range; import android.util.Size; +import android.util.SizeF; import android.view.Surface; import com.xlythe.view.camera.CameraView; @@ -863,9 +864,14 @@ static float zoomRatioFor(float minRatio, float maxRatio, int zoomLevel) { return minRatio + (maxRatio - minRatio) * fraction; } - static Rect calculateCropRegion(Rect activeArray, float maxDigitalZoom, int zoomLevel) { + /** The zoom a level maps onto when the camera zooms by cropping rather than by ratio. */ + static float cropZoomFor(float maxDigitalZoom, int zoomLevel) { float fraction = (float) rangeLimit(zoomLevel) / MAX_ZOOM_LEVEL; - float zoom = 1f + (Math.max(1f, maxDigitalZoom) - 1f) * fraction; + return 1f + (Math.max(1f, maxDigitalZoom) - 1f) * fraction; + } + + static Rect calculateCropRegion(Rect activeArray, float maxDigitalZoom, int zoomLevel) { + float zoom = cropZoomFor(maxDigitalZoom, zoomLevel); int cropWidth = Math.max(1, (int) (activeArray.width() / zoom)); int cropHeight = Math.max(1, (int) (activeArray.height() / zoom)); int cropLeft = (activeArray.width() - cropWidth) / 2; @@ -1016,6 +1022,70 @@ public void setFlash(CameraView.Flash flash) { reissueRepeatingRequest("the flash strategy"); } + @Override + public float getHorizontalFieldOfView() { + return fieldOfView(true /* horizontal */); + } + + @Override + public float getVerticalFieldOfView() { + return fieldOfView(false /* horizontal */); + } + + /** + * The angle of view, worked out from the sensor's size and the lens in front of it. + * + *

The shortest focal length is the one used: a camera that publishes several is either a + * zoom lens, where the shortest is the widest view it can give, or a logical camera standing + * for several physical ones, where the shortest belongs to the widest of them. Zoom is then + * applied on top, since the request this session is issuing is what decides how much of that + * view is actually being shown.

+ */ + private float fieldOfView(boolean horizontal) { + try { + CameraCharacteristics characteristics = + mCameraManager.getCameraCharacteristics(getActiveCamera()); + SizeF sensor = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE); + float[] focalLengths = + characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS); + if (sensor == null || focalLengths == null || focalLengths.length == 0) { + return 0f; + } + // The first focal length, not the shortest: a zoom ratio of one means the lens the + // camera uses by default, and that is the one this array leads with. On a logical + // camera the shortest belongs to the ultra-wide, which the ratio reaches by going + // below one - so taking it here and then applying the ratio would count it twice. + float full = TransformMath.fieldOfViewDegrees( + horizontal ? sensor.getWidth() : sensor.getHeight(), focalLengths[0]); + return TransformMath.zoomedFieldOfViewDegrees( + full, effectiveZoomRatio(characteristics)); + } catch (CameraAccessException | IllegalArgumentException | IllegalStateException error) { + if (DEBUG) Log.d(TAG, "Could not work out the field of view", error); + return 0f; + } + } + + /** + * How much this session is actually zoomed, whichever way it is doing it. + * + *

Two mechanisms, as in setZoomLevel: the zoom ratio control where it exists, which can + * cross between physical lenses, and a crop of the sensor's active array where it does not. + * Read here rather than worked out again, so that the angle of view cannot disagree with the + * request that produced the picture.

+ */ + private float effectiveZoomRatio(@NonNull CameraCharacteristics characteristics) { + Range ratioRange = zoomRatioRange(characteristics); + if (ratioRange != null) { + return zoomRatioFor(ratioRange.getLower(), ratioRange.getUpper(), mZoomLevel); + } + Float maxDigitalZoom = + characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM); + if (maxDigitalZoom == null || maxDigitalZoom <= 1f) { + return 1f; + } + return cropZoomFor(maxDigitalZoom, mZoomLevel); + } + /** Rebuilds the repeating request, for a setting the request itself carries. */ private void reissueRepeatingRequest(String what) { mHandler.post(() -> { diff --git a/camera-view/src/main/java/com/xlythe/view/camera/x/CameraXModule.java b/camera-view/src/main/java/com/xlythe/view/camera/x/CameraXModule.java index a5f72ae..55507c5 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/x/CameraXModule.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/x/CameraXModule.java @@ -24,6 +24,7 @@ import android.util.Range; import android.util.Rational; import android.util.Size; +import android.util.SizeF; import android.view.Surface; import android.view.View; @@ -1690,6 +1691,55 @@ private boolean reconcileUseCases(boolean reportFailure) { return mSnapshotWhileRecording; } + @Override + public float getHorizontalFieldOfView() { + return fieldOfView(true /* horizontal */); + } + + @Override + public float getVerticalFieldOfView() { + return fieldOfView(false /* horizontal */); + } + + /** + * The angle of view, read from the camera2 characteristics underneath CameraX. + * + *

CameraX does not publish the optics itself, so this goes through Camera2CameraInfo to + * the same two values the camera2 backend reads. The zoom comes from CameraX's own zoom + * state rather than from a request, since CameraX owns the requests here.

+ */ + @OptIn(markerClass = ExperimentalCamera2Interop.class) + private float fieldOfView(boolean horizontal) { + Camera camera = mActiveCamera; + if (camera == null) { + return 0f; + } + try { + Camera2CameraInfo info = Camera2CameraInfo.from(camera.getCameraInfo()); + SizeF sensor = info.getCameraCharacteristic( + CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE); + float[] focalLengths = info.getCameraCharacteristic( + CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS); + if (sensor == null || focalLengths == null || focalLengths.length == 0) { + return 0f; + } + // The first focal length, for the reason the camera2 backend records: a zoom ratio + // of one is the lens the camera uses by default, which is the one this array leads + // with, and the shortest is the ultra-wide the ratio reaches by going below one. + float full = TransformMath.fieldOfViewDegrees( + horizontal ? sensor.getWidth() : sensor.getHeight(), focalLengths[0]); + + ZoomState zoom = camera.getCameraInfo().getZoomState().getValue(); + if (zoom == null) { + return full; + } + return TransformMath.zoomedFieldOfViewDegrees(full, zoom.getZoomRatio()); + } catch (IllegalArgumentException | IllegalStateException | LinkageError error) { + Log.w(TAG, "Could not work out the field of view", error); + return 0f; + } + } + @Override public boolean isFaceDetectionSupported() { Camera camera = mActiveCamera; return camera != null && faceDetectMode(camera.getCameraInfo()) != null; diff --git a/camera-view/src/test/java/com/xlythe/view/camera/TransformMathTest.java b/camera-view/src/test/java/com/xlythe/view/camera/TransformMathTest.java index 7b00ec8..a598ad5 100644 --- a/camera-view/src/test/java/com/xlythe/view/camera/TransformMathTest.java +++ b/camera-view/src/test/java/com/xlythe/view/camera/TransformMathTest.java @@ -25,6 +25,71 @@ public class TransformMathTest { private static final float TOLERANCE = 0.01f; + /** + * The angle a lens sees across a sensor, which is what turns a bearing into a screen position. + * + *

Checked against arithmetic that can be done by hand: a 36mm-wide frame behind a 50mm + * lens is the classic case, and 2*atan(36/100) is 39.6 degrees.

+ */ + @Test + public void aFieldOfViewComesFromTheSensorAndTheLens() { + assertEquals(39.60f, + TransformMath.fieldOfViewDegrees(36f /* mm */, 50f /* mm */), 0.05f); + assertEquals("the same frame is narrower the short way across", + 26.99f, TransformMath.fieldOfViewDegrees(24f, 50f), 0.05f); + + // A phone: a small sensor behind a very short lens, which is why it sees so much. + assertEquals(67.63f, TransformMath.fieldOfViewDegrees(5.76f, 4.3f), 0.05f); + + // A longer lens on the same sensor sees less. + assertTrue("a longer lens must see less", + TransformMath.fieldOfViewDegrees(5.76f, 6f) + < TransformMath.fieldOfViewDegrees(5.76f, 4.3f)); + } + + /** A camera that will not say how big its sensor is gets no answer invented for it. */ + @Test + public void anUnknownSensorOrLensHasNoFieldOfView() { + assertEquals(0f, TransformMath.fieldOfViewDegrees(0f, 50f), 0f); + assertEquals(0f, TransformMath.fieldOfViewDegrees(36f, 0f), 0f); + assertEquals(0f, TransformMath.fieldOfViewDegrees(-36f, 50f), 0f); + assertEquals(0f, TransformMath.fieldOfViewDegrees(36f, -50f), 0f); + } + + /** + * Zooming narrows the view, but not in proportion to the zoom. + * + *

This is the whole reason the method exists. Doubling the zoom halves the width of what + * is visible, which halves the tangent of the half-angle rather than the angle - so a 60 + * degree view at 2x is 32.2 degrees, not 30. Anything drawing by bearing and dividing + * instead would put its marker in the wrong place, and more wrongly the further from centre + * it is.

+ */ + @Test + public void zoomNarrowsTheViewByTangentAndNotByRatio() { + assertEquals(32.20f, TransformMath.zoomedFieldOfViewDegrees(60f, 2f), 0.05f); + assertTrue("dividing the angle would have given 30", + TransformMath.zoomedFieldOfViewDegrees(60f, 2f) > 30f); + + assertEquals("no zoom is no change", + 60f, TransformMath.zoomedFieldOfViewDegrees(60f, 1f), 0.001f); + assertTrue("more zoom is always less view", + TransformMath.zoomedFieldOfViewDegrees(60f, 4f) + < TransformMath.zoomedFieldOfViewDegrees(60f, 2f)); + + // A logical camera can report a ratio below one, which is a wider view than its own 1x. + assertTrue("a ratio below one widens the view", + TransformMath.zoomedFieldOfViewDegrees(60f, 0.5f) > 60f); + } + + /** And nothing to narrow, or no ratio to narrow it by, answers nothing. */ + @Test + public void anUnknownZoomOrViewHasNoAngle() { + assertEquals(0f, TransformMath.zoomedFieldOfViewDegrees(0f, 2f), 0f); + assertEquals(0f, TransformMath.zoomedFieldOfViewDegrees(60f, 0f), 0f); + assertEquals(0f, TransformMath.zoomedFieldOfViewDegrees(60f, -2f), 0f); + } + @Test public void rotationsNormalizeIntoACircle() { assertEquals(0, TransformMath.within360(0)); diff --git a/camera-view/src/test/java/com/xlythe/view/camera/v2/Camera2SessionTest.java b/camera-view/src/test/java/com/xlythe/view/camera/v2/Camera2SessionTest.java index 0d7ac9f..f3d560b 100644 --- a/camera-view/src/test/java/com/xlythe/view/camera/v2/Camera2SessionTest.java +++ b/camera-view/src/test/java/com/xlythe/view/camera/v2/Camera2SessionTest.java @@ -45,6 +45,34 @@ public void tearDown() { cameraView.release(); } + /** + * The angle of view the camera can see, and what zoom does to it. + * + *

This is what maps a direction in the world onto a position on the preview, so anything + * drawn over the camera to point at something depends on it. The fake camera publishes a + * 5.76mm by 4.29mm sensor behind a 4.3mm lens, and the arithmetic can be done by hand: + * 2*atan(5.76/8.6) is 67.63 degrees across.

+ */ + @Test + public void reportsTheAngleOfViewAndNarrowsItWithZoom() throws Exception { + float wide = module.getHorizontalFieldOfView(); + assertEquals("a 5.76mm sensor behind a 4.3mm lens", 67.63f, wide, 0.1f); + + float tall = module.getVerticalFieldOfView(); + assertEquals("and 53.02 degrees the short way", 53.02f, tall, 0.1f); + assertTrue("the sensor is wider than it is tall, so the angle is too", wide > tall); + + module.setZoomLevel(module.getMaxZoomLevel()); + float zoomed = module.getHorizontalFieldOfView(); + assertTrue("zooming in has to narrow the view: " + wide + " -> " + zoomed, + zoomed < wide); + assertTrue("and never to nothing", zoomed > 0f); + + module.setZoomLevel(0); + assertEquals("coming back out restores it", + wide, module.getHorizontalFieldOfView(), 0.1f); + } + @Test public void readsCapabilitiesFromTheActiveCamera() throws Exception { assertEquals(FakeCamera2.BACK_ID, module.getActiveCamera()); diff --git a/camera-view/src/test/java/com/xlythe/view/camera/v2/FakeCamera2.java b/camera-view/src/test/java/com/xlythe/view/camera/v2/FakeCamera2.java index e297059..7132ab0 100644 --- a/camera-view/src/test/java/com/xlythe/view/camera/v2/FakeCamera2.java +++ b/camera-view/src/test/java/com/xlythe/view/camera/v2/FakeCamera2.java @@ -3,6 +3,7 @@ import android.content.Context; import android.graphics.ImageFormat; import android.graphics.Rect; +import android.util.SizeF; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraManager; @@ -183,6 +184,12 @@ static void addCamera(Context context, String id, int lensFacing, int sensorOrie shadow.set(CameraCharacteristics.CONTROL_MAX_REGIONS_AE, 1); shadow.set(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM, 4f); shadow.set(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE, new Rect(0, 0, 4000, 3000)); + // A plausible phone sensor and lens: 5.76mm x 4.29mm behind a 4.3mm lens, which is about + // 67 degrees across. Published so that anything working out an angle of view has + // something to work from - a camera that publishes neither can only decline. + shadow.set(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE, new SizeF(5.76f, 4.29f)); + shadow.set(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS, + new float[] {4.3f, 6.0f}); if (faceDetection) { shadow.set(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES, new int[] {CameraMetadata.STATISTICS_FACE_DETECT_MODE_OFF, From 23f0c6274ccbe40ec8a67b81c3cd897f73440853 Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 03:03:28 -0500 Subject: [PATCH 2/4] Stop the device suite flashing in the room it runs in The library's default flash mode is AUTO, so in a dim room every capture in the suite fires the flash - a dozen times over a full run across the classes and the three backends, which is unpleasant for whoever is holding the phone and makes the captures depend on the light in the room. Nothing here asserts on exposure. The shared open path turns the flash off, in one place so there is one place to look when a run starts flashing. That made the two flash-control tests tautological: both set OFF and asserted OFF, which a setter that did nothing would also pass. They now move the mode away from the harness's OFF and assert it took, then put it back. Choosing a mode lights nothing on its own - only a capture does, and neither test takes a picture. The torch test is the one that means to light the lamp, so it asks first: pass -Pandroid.testInstrumentationRunnerArguments.lamp=off and nothing in the suite lights up. The default is still to run it, because a torch nobody turns on is a torch nobody is testing. Co-Authored-By: Claude Opus 5 --- .../camera/test/BackendMatrixDeviceTest.java | 21 ++++++++++++++-- .../camera/test/CameraDeviceCaptureTest.java | 16 +++++++++++-- .../camera/test/CameraSurfaceDeviceTest.java | 8 +++++++ .../xlythe/view/camera/test/DeviceState.java | 24 +++++++++++++++++++ .../camera/test/VideoQualityDeviceTest.java | 6 +++++ 5 files changed, 71 insertions(+), 4 deletions(-) diff --git a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/BackendMatrixDeviceTest.java b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/BackendMatrixDeviceTest.java index 218c5ef..ad2ea66 100644 --- a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/BackendMatrixDeviceTest.java +++ b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/BackendMatrixDeviceTest.java @@ -1,5 +1,6 @@ package com.xlythe.view.camera.test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -241,20 +242,30 @@ public void aStreamDeliversEncodedFrames() throws Exception { public void theControlsAnswer() throws Exception { AtomicInteger maxZoom = new AtomicInteger(); AtomicReference flash = new AtomicReference<>(); + AtomicReference flashAfterOff = new AtomicReference<>(); AtomicBoolean faces = new AtomicBoolean(); withOpenCamera(camera -> { maxZoom.set(camera.getMaxZoomLevel()); camera.setZoomLevel(maxZoom.get() / 2); sleep(500); - camera.setFlash(CameraView.Flash.OFF); + // Away from the OFF the harness set, so a setter that did nothing would be + // visible. Choosing a mode does not light anything; only a capture does, and this + // test takes no picture. + camera.setFlash(CameraView.Flash.ON); sleep(200); flash.set(camera.getFlash()); + camera.setFlash(CameraView.Flash.OFF); + sleep(200); + flashAfterOff.set(camera.getFlash()); faces.set(camera.isFaceDetectionSupported()); }); assertTrue("every backend scales zoom the same way on " + backend, maxZoom.get() > 0); - assertTrue(flash.get() == CameraView.Flash.OFF); + assertEquals("the flash mode has to be the one that was asked for on " + backend, + CameraView.Flash.ON, flash.get()); + assertEquals("and it has to change back on " + backend, + CameraView.Flash.OFF, flashAfterOff.get()); } /** What a test does with an open camera. */ @@ -300,6 +311,12 @@ private void withOpenCamera(CameraAction action) throws Exception { opened.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); CameraView camera = held.get(); assertNotNull(camera); + // The library's default is AUTO, so in a dim room every capture in this suite fires + // the flash - a dozen times over a full run, which is unpleasant for whoever is + // holding the phone and makes the captures depend on the light in the room. Nothing + // here asserts on exposure; the tests that mean to exercise the flash set the mode + // they want themselves. + DeviceState.turnTheFlashOff(camera); try { action.run(camera); } finally { diff --git a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/CameraDeviceCaptureTest.java b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/CameraDeviceCaptureTest.java index 311f401..2afa3b5 100644 --- a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/CameraDeviceCaptureTest.java +++ b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/CameraDeviceCaptureTest.java @@ -1,5 +1,6 @@ package com.xlythe.view.camera.test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -278,16 +279,21 @@ public void theControlsTakeEffect() throws Exception { sleep(500); zoom.set(camera.getZoomLevel()); - camera.setFlash(CameraView.Flash.OFF); + // Away from the OFF the harness set, so a setter that did nothing would show. + // Choosing a mode lights nothing on its own; only a capture does, and this test + // takes no picture. + camera.setFlash(CameraView.Flash.ON); sleep(200); flash.set(camera.getFlash()); + camera.setFlash(CameraView.Flash.OFF); camera.focus(new Rect(-100, -100, 100, 100), new Rect(-200, -200, 200, 200)); sleep(500); }); assertTrue("zoom stayed inside its range", zoom.get() >= 0); - assertTrue(flash.get() == CameraView.Flash.OFF); + assertEquals("the flash mode has to be the one that was asked for", + CameraView.Flash.ON, flash.get()); } /** Switching lenses on a real camera reconfigures a session rather than just a flag. */ @@ -349,6 +355,12 @@ private void withOpenCamera(CameraAction action) throws Exception { opened.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); CameraView camera = held.get(); assertNotNull(camera); + // The library's default is AUTO, so in a dim room every capture in this suite fires + // the flash - a dozen times over a full run, which is unpleasant for whoever is + // holding the phone and makes the captures depend on the light in the room. Nothing + // here asserts on exposure; the tests that mean to exercise the flash set the mode + // they want themselves. + DeviceState.turnTheFlashOff(camera); try { action.run(camera); } finally { diff --git a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/CameraSurfaceDeviceTest.java b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/CameraSurfaceDeviceTest.java index edc8386..ae21e1c 100644 --- a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/CameraSurfaceDeviceTest.java +++ b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/CameraSurfaceDeviceTest.java @@ -290,6 +290,8 @@ public void closingAndReopeningWorksOnALiveCamera() throws Exception { public void theOptionalControlsAreOfferedToTheCamera() throws Exception { AtomicReference reported = new AtomicReference<>(); + DeviceState.assumeTheLampMayBeLit(); + withOpenCamera(camera -> { camera.setTorchEnabled(true); sleep(300); @@ -404,6 +406,12 @@ private void withOpenCamera(CameraAction action) throws Exception { opened.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); CameraView camera = held.get(); assertNotNull(camera); + // The library's default is AUTO, so in a dim room every capture in this suite fires + // the flash - a dozen times over a full run, which is unpleasant for whoever is + // holding the phone and makes the captures depend on the light in the room. Nothing + // here asserts on exposure; the tests that mean to exercise the flash set the mode + // they want themselves. + DeviceState.turnTheFlashOff(camera); try { action.run(camera); } finally { diff --git a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/DeviceState.java b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/DeviceState.java index db31c13..e69deb5 100644 --- a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/DeviceState.java +++ b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/DeviceState.java @@ -7,8 +7,11 @@ import android.os.PowerManager; import androidx.test.core.app.ApplicationProvider; +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.annotation.NonNull; import org.junit.Assume; +import com.xlythe.view.camera.CameraView; /** * What the device has to be for a camera test to mean anything. @@ -22,6 +25,27 @@ final class DeviceState { private DeviceState() {} + /** + * Turns the flash off for a test that does not care about it. + * + *

Separate from the tests so there is one place to look when a run starts flashing.

+ */ + static void turnTheFlashOff(@NonNull CameraView camera) { + camera.setFlash(CameraView.Flash.OFF); + } + + /** + * Skips a test whose whole point is to light the lamp, when someone has asked for a dark run. + * + *

Pass {@code -Pandroid.testInstrumentationRunnerArguments.lamp=off} and nothing in the + * suite lights up. The default is to run it, because a torch that never turns on is a torch + * nobody is testing - but a person sitting next to the phone gets to say otherwise.

+ */ + static void assumeTheLampMayBeLit() { + String lamp = InstrumentationRegistry.getArguments().getString("lamp"); + Assume.assumeFalse("a dark run was asked for with -Plamp=off", "off".equals(lamp)); + } + /** Skips unless there is a camera to test and a screen to show it on. */ static void assumeATestableCamera() { Context context = ApplicationProvider.getApplicationContext(); diff --git a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/VideoQualityDeviceTest.java b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/VideoQualityDeviceTest.java index 874f2e9..58aebdd 100644 --- a/camera-view/src/androidTest/java/com/xlythe/view/camera/test/VideoQualityDeviceTest.java +++ b/camera-view/src/androidTest/java/com/xlythe/view/camera/test/VideoQualityDeviceTest.java @@ -306,6 +306,12 @@ private File record() throws Exception { CameraView camera = held.get(); assertNotNull(camera); + // The library's default is AUTO, so in a dim room every capture in this suite fires + // the flash - a dozen times over a full run, which is unpleasant for whoever is + // holding the phone and makes the captures depend on the light in the room. Nothing + // here asserts on exposure; the tests that mean to exercise the flash set the mode + // they want themselves. + DeviceState.turnTheFlashOff(camera); try { camera.setOnVideoCapturedListener(new CameraView.OnVideoCapturedListener() { @Override public void onVideoConfirmation() {} From 16936726018e62f3e2fabf85590dbd71c8a19d0b Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 03:19:57 -0500 Subject: [PATCH 3/4] Put a place in the world onto the viewfinder Groundwork for markers drawn over the preview: a pillar of light standing where something was left, an arrow towards a place, a label on a landmark. Two ways in, because there are two ways of knowing where something is. A direction is all a compass and a location can give, and it needs nothing but the camera's angle of view - which is why this lands now that the library reports one. Position goes as the tangent of the angle rather than in proportion to it, so half the angle of view away is the edge of the view and a quarter is not halfway out; doing that arithmetic at the call site is the mistake this exists to prevent. Up in the world is down a view's y axis, and the flip is here so a caller cannot forget it. A point in metres is what a tracked session gives, and it goes through that session's own matrices the way its renderer would. A point behind the camera is refused rather than projected: dividing by a negative w mirrors it through the centre, so something you have already walked past lands plausibly on the wall ahead. Occlusion is what makes a marker look like it is in the room rather than painted on the glass. The depth comparison carries a tolerance because a reading is noisy and taken a moment apart from the pose, and an exact comparison makes a marker flicker along every edge it is near; no reading at all shows the marker, since guessing either way is worse. visiblePillar walks a tall marker from the ground up and returns the stretch that is in front, so a pillar whose base is behind the sofa still shows its top - which is the whole point of it being tall. Nothing here draws anything. In the strict coverage gate with the rest of the geometry, because every mistake available here is silent: a marker at a wrong position still looks like a marker, it just points at the wrong thing. Co-Authored-By: Claude Opus 5 --- README.md | 35 +++ .../com/xlythe/view/camera/WorldOverlay.java | 242 +++++++++++++++ .../xlythe/view/camera/WorldOverlayTest.java | 276 ++++++++++++++++++ gradle/coverage.gradle | 2 + 4 files changed, 555 insertions(+) create mode 100644 camera-view/src/main/java/com/xlythe/view/camera/WorldOverlay.java create mode 100644 camera-view/src/test/java/com/xlythe/view/camera/WorldOverlayTest.java diff --git a/README.md b/README.md index 33c1672..a138f95 100644 --- a/README.md +++ b/README.md @@ -290,6 +290,41 @@ float x = getWidth() * (0.5f + (float) Math.tan(Math.toRadians(bearing)) / (2f * (float) Math.tan(Math.toRadians(fov / 2)))); ``` +Pointing at something +----------------- +WorldOverlay turns a place in the world into a position in the view, so an app can draw a marker +over the preview. It draws nothing itself - what the marker looks like is yours. + +If all you know is a direction, which is all a compass and a location give, use the bearing with +the angle of view. Position goes as the tangent of the angle, not in proportion to it, so half the +angle of view away is the edge of the view and a quarter is not halfway out. +```java +float x = WorldOverlay.screenXForBearing(bearing, mCameraView.getHorizontalFieldOfView(), getWidth()); +float y = WorldOverlay.screenYForElevation(elevation, mCameraView.getVerticalFieldOfView(), getHeight()); +// NaN when there is no angle of view to work from, or the bearing is at a right angle +``` + +If you have a session that tracks the device through the world and can say where things are in +metres, project a point through its matrices instead. A point behind the camera has no position in +the view and is refused rather than drawn in front of you. +```java +PointF at = new PointF(); +if (WorldOverlay.project(viewProjectionMatrix, x, y, z, getWidth(), getHeight(), at)) { + // draw at `at` +} +``` + +For a marker that should sit in the room rather than on the glass, compare how far away it is +against how far away the scene is at that point, and hide it when something is in front. A tall +marker is handled by visiblePillar, which returns the stretch that is not hidden - so a pillar +whose base is behind the sofa still shows its top, which is the point of it being tall. +```java +float away = WorldOverlay.distanceFromCamera(viewMatrix, x, y, z); +if (!WorldOverlay.isOccluded(away, depthMetersAt(at.x, at.y), 0.1f)) { + // draw at `at` +} +``` + Frames ----------------- startFrameAnalysis hands every frame to your own analyzer, on a background thread, for detection diff --git a/camera-view/src/main/java/com/xlythe/view/camera/WorldOverlay.java b/camera-view/src/main/java/com/xlythe/view/camera/WorldOverlay.java new file mode 100644 index 0000000..ab974f3 --- /dev/null +++ b/camera-view/src/main/java/com/xlythe/view/camera/WorldOverlay.java @@ -0,0 +1,242 @@ +package com.xlythe.view.camera; + +import android.graphics.PointF; +import android.opengl.Matrix; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +/** + * Puts things in the world onto the viewfinder showing it. + * + *

Two ways of saying where something is, because there are two ways of knowing. A direction - + * "the keys are 30 degrees to my right and a little below" - is all a compass and a location can + * give, and it needs nothing but the camera's angle of view. A point in metres is what a tracked + * session gives, and it needs that session's own view and projection matrices.

+ * + *

Both come out as a position in the view, ready to draw at. Neither draws anything: what the + * marker looks like is the app's business, and a library that decided would be in the way.

+ * + * @see CameraView#getHorizontalFieldOfView() + */ +public final class WorldOverlay { + private WorldOverlay() {} + + /** + * Where a compass bearing lands across the viewfinder. + * + *

The bearing is relative to where the camera is pointed, positive to the right. Half the + * angle of view away is the edge of the view, a quarter is halfway out - but not linearly, + * which is the part worth getting from here rather than from arithmetic at the call site: the + * view is a projection, so the position goes as the tangent of the angle.

+ * + * @param bearingDegrees degrees clockwise from where the camera points, negative to the left + * @param fieldOfViewDegrees the camera's horizontal angle of view, from + * {@link CameraView#getHorizontalFieldOfView()} + * @param viewWidth the width of the view, in pixels + * @return the x coordinate, which is outside [0, viewWidth] when the bearing is out of frame, + * or {@link Float#NaN} when there is no angle of view to work from or the bearing is at or + * past a right angle, where a projection has no answer + */ + public static float screenXForBearing( + float bearingDegrees, float fieldOfViewDegrees, int viewWidth) { + return project(bearingDegrees, fieldOfViewDegrees, viewWidth, false /* invert */); + } + + /** + * Where an elevation lands down the viewfinder. + * + *

Positive is above where the camera points, which is up the world and so down the + * y axis of a view. The flip is here so that a caller cannot forget it.

+ * + * @param elevationDegrees degrees above where the camera points, negative below + * @param fieldOfViewDegrees the camera's vertical angle of view, from + * {@link CameraView#getVerticalFieldOfView()} + * @param viewHeight the height of the view, in pixels + * @return the y coordinate, or {@link Float#NaN} on the same terms as + * {@link #screenXForBearing} + */ + public static float screenYForElevation( + float elevationDegrees, float fieldOfViewDegrees, int viewHeight) { + return project(elevationDegrees, fieldOfViewDegrees, viewHeight, true /* invert */); + } + + private static float project( + float angleDegrees, float fieldOfViewDegrees, int extent, boolean invert) { + if (fieldOfViewDegrees <= 0f || fieldOfViewDegrees >= 180f || extent <= 0) { + return Float.NaN; + } + if (Math.abs(angleDegrees) >= 90f) { + // At a right angle the projection plane is parallel to the direction, so there is no + // position to report rather than an enormous one. + return Float.NaN; + } + double halfExtent = Math.tan(Math.toRadians(fieldOfViewDegrees / 2)); + if (halfExtent <= 0) { + return Float.NaN; + } + double offset = Math.tan(Math.toRadians(angleDegrees)) / halfExtent; + if (invert) { + offset = -offset; + } + return (float) (extent * (0.5 + offset / 2)); + } + + /** + * Where a point in the world lands in the view. + * + *

For a session that tracks the device through the world and can say where things are in + * metres. The matrices are the ones such a session publishes, column-major as OpenGL wants + * them, and this applies them the way the renderer does - so a marker drawn at the result sits + * where the renderer would have drawn it.

+ * + * @param viewProjectionMatrix the projection matrix multiplied by the view matrix, 16 floats + * @param out set to the position in the view, in pixels + * @return whether the point is in front of the camera at all. A point behind it has no + * position in the view, and {@code out} is left alone - drawing a marker for something + * behind you is the mistake this return value exists to prevent + */ + public static boolean project( + @NonNull float[] viewProjectionMatrix, + float worldX, float worldY, float worldZ, + int viewWidth, int viewHeight, + @NonNull PointF out) { + if (viewProjectionMatrix.length < 16 || viewWidth <= 0 || viewHeight <= 0) { + return false; + } + float[] clip = new float[4]; + Matrix.multiplyMV(clip, 0, viewProjectionMatrix, 0, + new float[] {worldX, worldY, worldZ, 1f}, 0); + if (clip[3] <= 0f) { + // w is the distance along the view direction, so this is at or behind the camera. + return false; + } + // Clip space to normalized device coordinates, which run -1 to 1 with y upwards, and then + // to the view, whose y runs downwards from the top. + float ndcX = clip[0] / clip[3]; + float ndcY = clip[1] / clip[3]; + out.set(viewWidth * (ndcX + 1f) / 2f, viewHeight * (1f - ndcY) / 2f); + return true; + } + + /** + * How far a point in the world is from the camera, in metres. + * + *

This is the number to compare against a depth reading to decide whether something in the + * scene is in front of it.

+ * + * @param viewMatrix the session's view matrix, 16 floats, column-major + * @return the distance in metres, or {@link Float#NaN} if the matrix is not a matrix + */ + public static float distanceFromCamera( + @NonNull float[] viewMatrix, float worldX, float worldY, float worldZ) { + if (viewMatrix.length < 16) { + return Float.NaN; + } + float[] inCamera = new float[4]; + Matrix.multiplyMV(inCamera, 0, viewMatrix, 0, + new float[] {worldX, worldY, worldZ, 1f}, 0); + // The camera looks down its own negative z, so what is in front has negative z. + return -inCamera[2]; + } + + /** + * Whether something in the scene stands in front of the point being marked. + * + *

This is what makes a marker look like it is in the room rather than painted on the glass: + * a pillar placed across the hall should disappear behind the sofa in front of it.

+ * + *

The tolerance matters. A depth reading is noisy and is measured at a slightly different + * moment from the pose, so comparing them exactly makes a marker flicker along every edge it + * is near. Treating anything within the tolerance as "not occluded" keeps the marker steady + * and errs towards showing it, which is the kinder way to be wrong.

+ * + * @param markerMeters how far away the thing being marked is + * @param sceneMeters how far away the scene is at that point on screen, 0 or negative where + * the session has no reading + * @param toleranceMeters how much closer the scene has to be before it counts as in the way + * @return whether to hide the marker + */ + public static boolean isOccluded( + float markerMeters, float sceneMeters, float toleranceMeters) { + if (sceneMeters <= 0f || Float.isNaN(sceneMeters) || Float.isNaN(markerMeters)) { + // No reading is not the same as nothing in the way, and guessing either way is worse + // than showing the marker. + return false; + } + return sceneMeters < markerMeters - Math.max(0f, toleranceMeters); + } + + /** + * The visible part of an upright pillar standing at a point in the world. + * + *

A pillar of light is the one marker that cannot be a dot: it is tall, which is what makes + * it findable from across a room and over furniture. The bottom may be behind the sofa while + * the top is not, so this walks it from the ground up and returns the stretch that is in + * front - the top being visible is the whole point, and a marker that vanished because its + * base was hidden would be useless.

+ * + * @param samples how many points up the pillar to test; more is smoother and slower + * @param scene asked how far away the scene is at a position in the view + * @return the lowest and highest visible points in the view, or null when no part of it is + */ + @Nullable + public static VisibleRun visiblePillar( + @NonNull float[] viewMatrix, @NonNull float[] viewProjectionMatrix, + float worldX, float groundY, float worldZ, float heightMeters, + int viewWidth, int viewHeight, int samples, float toleranceMeters, + @NonNull SceneDepth scene) { + if (samples < 2 || heightMeters <= 0f) { + return null; + } + PointF at = new PointF(); + PointF lowest = null; + PointF highest = null; + for (int i = 0; i < samples; i++) { + float y = groundY + heightMeters * i / (samples - 1); + if (!project(viewProjectionMatrix, worldX, y, worldZ, viewWidth, viewHeight, at)) { + continue; + } + float distance = distanceFromCamera(viewMatrix, worldX, y, worldZ); + if (isOccluded(distance, scene.metersAt(at.x, at.y), toleranceMeters)) { + continue; + } + if (lowest == null) { + lowest = new PointF(at.x, at.y); + } + highest = new PointF(at.x, at.y); + } + return lowest == null ? null : new VisibleRun(lowest, highest); + } + + /** How far away the scene is at a point in the view. */ + public interface SceneDepth { + /** + * @return metres, or 0 or less where there is no reading + */ + float metersAt(float viewX, float viewY); + } + + /** The stretch of a pillar that is not hidden, from its lowest visible point to its highest. */ + public static final class VisibleRun { + private final PointF mFrom; + private final PointF mTo; + + VisibleRun(@NonNull PointF from, @NonNull PointF to) { + mFrom = from; + mTo = to; + } + + /** The lowest visible point, which is nearest the ground. */ + @NonNull + public PointF getFrom() { + return mFrom; + } + + /** The highest visible point. */ + @NonNull + public PointF getTo() { + return mTo; + } + } +} diff --git a/camera-view/src/test/java/com/xlythe/view/camera/WorldOverlayTest.java b/camera-view/src/test/java/com/xlythe/view/camera/WorldOverlayTest.java new file mode 100644 index 0000000..33ffd65 --- /dev/null +++ b/camera-view/src/test/java/com/xlythe/view/camera/WorldOverlayTest.java @@ -0,0 +1,276 @@ +package com.xlythe.view.camera; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import android.graphics.PointF; +import android.opengl.Matrix; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +/** + * Putting a place in the world onto the view showing it. + * + *

Every mistake available here is silent. A marker an app draws at a wrong position still looks + * like a marker - it just points at the wrong thing, or drifts as the camera turns, or sits on the + * wrong side of the sofa. So the values are checked against arithmetic that can be done by hand, + * and the three classic sign errors - the y axis of a view running the opposite way to the world, + * a point behind the camera projecting as though it were in front, and a depth test that hides + * what it should show - each have a test of their own.

+ */ +@RunWith(RobolectricTestRunner.class) +@Config(sdk = {29, 37}) +public class WorldOverlayTest { + private static final int WIDTH = 1080; + private static final int HEIGHT = 1920; + + /** Straight ahead is the middle, whatever the angle of view. */ + @Test + public void aBearingOfZeroIsTheMiddleOfTheView() { + assertEquals(WIDTH / 2f, + WorldOverlay.screenXForBearing(0f, 67f, WIDTH), 0.01f); + assertEquals(WIDTH / 2f, + WorldOverlay.screenXForBearing(0f, 20f, WIDTH), 0.01f); + } + + /** Half the angle of view away is the edge, which is what makes the angle worth knowing. */ + @Test + public void halfTheAngleOfViewIsTheEdge() { + assertEquals("the right edge", + WIDTH, WorldOverlay.screenXForBearing(30f, 60f, WIDTH), 0.5f); + assertEquals("and the left", + 0f, WorldOverlay.screenXForBearing(-30f, 60f, WIDTH), 0.5f); + } + + /** + * And a quarter of the way is not half way across. + * + *

This is the whole reason to go through this rather than scaling the angle: the view is a + * projection, so position goes as the tangent. At 15 degrees into a 60 degree view the + * tangent is 0.2679 against a half-extent of 0.5774, which is 0.4641 of the way out - 0.732 + * of the half-width, not 0.5 of it.

+ */ + @Test + public void aBearingProjectsByTangentRatherThanInProportion() { + float x = WorldOverlay.screenXForBearing(15f, 60f, WIDTH); + float halfway = WIDTH / 2f + WIDTH / 4f; + + assertEquals(WIDTH / 2f + WIDTH / 2f * 0.4641f, x, 1f); + assertTrue("scaling the angle would have put it at " + halfway + ", not " + x, + x < halfway); + } + + /** Up in the world is down the view, and the flip belongs here rather than at the call site. */ + @Test + public void elevationIsFlippedForTheView() { + assertEquals("the middle", HEIGHT / 2f, + WorldOverlay.screenYForElevation(0f, 50f, HEIGHT), 0.01f); + assertEquals("looking up puts it at the top of the view", + 0f, WorldOverlay.screenYForElevation(25f, 50f, HEIGHT), 0.5f); + assertEquals("and down at the bottom", + HEIGHT, WorldOverlay.screenYForElevation(-25f, 50f, HEIGHT), 0.5f); + } + + /** Out of frame is reported as a position outside the view, not clamped to its edge. */ + @Test + public void aBearingOutOfFrameIsOutsideTheView() { + assertTrue("past the right edge", + WorldOverlay.screenXForBearing(45f, 60f, WIDTH) > WIDTH); + assertTrue("past the left", + WorldOverlay.screenXForBearing(-45f, 60f, WIDTH) < 0f); + } + + /** With no angle of view, or at a right angle, there is no answer to give. */ + @Test + public void anImpossibleBearingHasNoPosition() { + assertTrue(Float.isNaN(WorldOverlay.screenXForBearing(10f, 0f, WIDTH))); + assertTrue(Float.isNaN(WorldOverlay.screenXForBearing(10f, 180f, WIDTH))); + assertTrue(Float.isNaN(WorldOverlay.screenXForBearing(10f, 60f, 0))); + assertTrue("a right angle is parallel to the view plane", + Float.isNaN(WorldOverlay.screenXForBearing(90f, 60f, WIDTH))); + assertTrue(Float.isNaN(WorldOverlay.screenYForElevation(-90f, 50f, HEIGHT))); + } + + /** A point dead ahead projects to the middle of the view. */ + @Test + public void aPointAheadProjectsToTheMiddle() { + PointF at = new PointF(); + + assertTrue(WorldOverlay.project(viewProjection(), 0f, 0f, -5f, WIDTH, HEIGHT, at)); + + assertEquals(WIDTH / 2f, at.x, 1f); + assertEquals(HEIGHT / 2f, at.y, 1f); + } + + /** Right of the camera is right of the view, and above it is above. */ + @Test + public void aPointProjectsToTheRightSideUp() { + PointF right = new PointF(); + PointF up = new PointF(); + float[] viewProjection = viewProjection(); + + assertTrue(WorldOverlay.project(viewProjection, 1f, 0f, -5f, WIDTH, HEIGHT, right)); + assertTrue(WorldOverlay.project(viewProjection, 0f, 1f, -5f, WIDTH, HEIGHT, up)); + + assertTrue("a point to the right belongs right of centre", right.x > WIDTH / 2f); + assertEquals("and at the same height", HEIGHT / 2f, right.y, 1f); + assertTrue("a point above belongs above centre, which is a smaller y", up.y < HEIGHT / 2f); + assertEquals("and at the same place across", WIDTH / 2f, up.x, 1f); + } + + /** + * A point behind the camera is refused rather than projected. + * + *

Dividing by a negative w mirrors the point through the centre, so something behind you + * lands plausibly in front - a marker for the keys you have already walked past, drawn on the + * wall ahead. The sign of w is the only thing that catches it.

+ */ + @Test + public void aPointBehindTheCameraIsRefused() { + PointF at = new PointF(-1f, -1f); + + assertFalse("behind the camera", WorldOverlay.project( + viewProjection(), 0f, 0f, 5f, WIDTH, HEIGHT, at)); + assertEquals("and the caller's point is left alone", -1f, at.x, 0f); + assertEquals(-1f, at.y, 0f); + + assertFalse("and exactly at it is just as unanswerable", WorldOverlay.project( + viewProjection(), 0f, 0f, 0f, WIDTH, HEIGHT, at)); + } + + /** A matrix that is not a matrix, or a view with no size, is refused too. */ + @Test + public void anImpossibleProjectionIsRefused() { + PointF at = new PointF(); + assertFalse(WorldOverlay.project(new float[4], 0f, 0f, -5f, WIDTH, HEIGHT, at)); + assertFalse(WorldOverlay.project(viewProjection(), 0f, 0f, -5f, 0, HEIGHT, at)); + assertFalse(WorldOverlay.project(viewProjection(), 0f, 0f, -5f, WIDTH, 0, at)); + } + + /** How far away something is, which is what a depth reading gets compared against. */ + @Test + public void reportsHowFarAwayAPointIs() { + assertEquals("five metres down the view direction", + 5f, WorldOverlay.distanceFromCamera(view(), 0f, 0f, -5f), 0.001f); + assertEquals("sideways does not count as distance along the view", + 0f, WorldOverlay.distanceFromCamera(view(), 3f, 0f, 0f), 0.001f); + assertTrue("behind the camera is a negative distance", + WorldOverlay.distanceFromCamera(view(), 0f, 0f, 2f) < 0f); + assertTrue(Float.isNaN(WorldOverlay.distanceFromCamera(new float[4], 0f, 0f, -5f))); + } + + /** Something nearer than the marker hides it; something further away does not. */ + @Test + public void nearerSceneHidesTheMarker() { + assertTrue("a sofa two metres away hides a pillar five metres away", + WorldOverlay.isOccluded(5f, 2f, 0.1f)); + assertFalse("a wall ten metres away does not", + WorldOverlay.isOccluded(5f, 10f, 0.1f)); + } + + /** + * A reading within the tolerance leaves the marker alone. + * + *

Depth is noisy and is measured a moment apart from the pose, so an exact comparison makes + * a marker flicker along every edge it is near.

+ */ + @Test + public void aCloseReadingDoesNotFlickerTheMarker() { + assertFalse("within the tolerance is not in the way", + WorldOverlay.isOccluded(5f, 4.95f, 0.1f)); + assertTrue("beyond it is", WorldOverlay.isOccluded(5f, 4.5f, 0.1f)); + } + + /** No depth reading means show the marker, because guessing either way is worse. */ + @Test + public void noDepthReadingShowsTheMarker() { + assertFalse(WorldOverlay.isOccluded(5f, 0f, 0.1f)); + assertFalse(WorldOverlay.isOccluded(5f, -1f, 0.1f)); + assertFalse(WorldOverlay.isOccluded(5f, Float.NaN, 0.1f)); + assertFalse(WorldOverlay.isOccluded(Float.NaN, 2f, 0.1f)); + } + + /** + * A pillar whose base is hidden still shows its top. + * + *

The point of a pillar of light is to be findable over the furniture, so losing the whole + * marker because the floor beside it is behind a sofa would defeat it.

+ */ + @Test + public void aPillarBehindSomethingLowStillShowsItsTop() { + // The scene is close low down the view and far away higher up, which is what a sofa in + // front of an open room looks like to a depth reading. + WorldOverlay.SceneDepth sofa = (x, y) -> y > HEIGHT / 2f ? 1f : 100f; + + WorldOverlay.VisibleRun visible = WorldOverlay.visiblePillar( + view(), viewProjection(), 0f, -1.5f /* ground */, -5f, 3f /* metres tall */, + WIDTH, HEIGHT, 32 /* samples */, 0.1f, sofa); + + assertNotNull("the top of the pillar is not hidden", visible); + assertTrue("and what shows is the upper part of it", + visible.getTo().y <= HEIGHT / 2f); + assertTrue("the visible stretch runs upwards", + visible.getTo().y <= visible.getFrom().y); + } + + /** A pillar entirely behind a wall shows nothing at all. */ + @Test + public void aPillarBehindAWallShowsNothing() { + WorldOverlay.SceneDepth wall = (x, y) -> 1f; + + assertNull(WorldOverlay.visiblePillar( + view(), viewProjection(), 0f, -1.5f, -5f, 3f, + WIDTH, HEIGHT, 16, 0.1f, wall)); + } + + /** A pillar in the open shows all of itself. */ + @Test + public void aPillarInTheOpenShowsAllOfItself() { + WorldOverlay.SceneDepth openRoom = (x, y) -> 100f; + + WorldOverlay.VisibleRun visible = WorldOverlay.visiblePillar( + view(), viewProjection(), 0f, -1.5f, -5f, 3f, + WIDTH, HEIGHT, 16, 0.1f, openRoom); + + assertNotNull(visible); + assertTrue("the bottom is below the top on screen", + visible.getFrom().y > visible.getTo().y); + } + + /** Nonsense asked of a pillar gets nothing back rather than a guess. */ + @Test + public void anImpossiblePillarIsRefused() { + WorldOverlay.SceneDepth open = (x, y) -> 100f; + assertNull("one sample is not a pillar", WorldOverlay.visiblePillar( + view(), viewProjection(), 0f, 0f, -5f, 3f, WIDTH, HEIGHT, 1, 0.1f, open)); + assertNull("nor is one with no height", WorldOverlay.visiblePillar( + view(), viewProjection(), 0f, 0f, -5f, 0f, WIDTH, HEIGHT, 16, 0.1f, open)); + } + + /** A camera at the origin looking down its own negative z, as a tracked session reports it. */ + private static float[] view() { + float[] matrix = new float[16]; + Matrix.setLookAtM(matrix, 0, + 0f, 0f, 0f /* eye */, + 0f, 0f, -1f /* centre */, + 0f, 1f, 0f /* up */); + return matrix; + } + + /** That camera's view matrix with a plain perspective projection in front of it. */ + private static float[] viewProjection() { + float[] projection = new float[16]; + // A 90 degree vertical field of view, so the half-extent is exactly 1 and the arithmetic + // above can be checked by hand. + Matrix.perspectiveM(projection, 0, 90f, (float) WIDTH / HEIGHT, 0.1f, 100f); + float[] viewProjection = new float[16]; + Matrix.multiplyMM(viewProjection, 0, projection, 0, view(), 0); + return viewProjection; + } +} diff --git a/gradle/coverage.gradle b/gradle/coverage.gradle index 9ffdf11..d5425f6 100644 --- a/gradle/coverage.gradle +++ b/gradle/coverage.gradle @@ -46,6 +46,8 @@ def coreCoverageIncludes = [ 'com/xlythe/view/camera/Exif$*.class', 'com/xlythe/view/camera/PermissionChecker.class', 'com/xlythe/view/camera/TransformMath.class', + 'com/xlythe/view/camera/WorldOverlay.class', + 'com/xlythe/view/camera/WorldOverlay$*.class', 'com/xlythe/view/camera/x/CameraXMath.class', 'com/xlythe/view/camera/stream/AudioBuffer.class', 'com/xlythe/view/camera/stream/AudioStreamHeader.class', From ba404f836618851b7a4fc40eaa0b8b3af7c4e062 Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 03:31:37 -0500 Subject: [PATCH 4/4] Record legacy video with the profile of the camera in use The only open issue on the repository is a 2017 report of recordings full of green lines, which is what MediaRecorder produces when it is handed a size or encoder configuration its camera cannot deliver. One way to do that is here: every quality checked hasProfile against the active camera and then fetched the profile with the single-argument overload, which returns the first back-facing camera's profile whatever camera is open. On the front camera that handed MediaRecorder another sensor's configuration. The issue was filed against Jelly Bean, which this library no longer supports, so this is not a fix for that report - but it is the same mistake, still present, on every front-camera recording where the two cameras publish different profiles. The camera2 path already guards the equivalent by filtering sizes through CamcorderProfile before offering them. setMaxDuration was also being called twice. Co-Authored-By: Claude Opus 5 --- .../view/camera/legacy/LegacyCameraModule.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/camera-view/src/main/java/com/xlythe/view/camera/legacy/LegacyCameraModule.java b/camera-view/src/main/java/com/xlythe/view/camera/legacy/LegacyCameraModule.java index f7abe88..f26e4de 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/legacy/LegacyCameraModule.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/legacy/LegacyCameraModule.java @@ -190,38 +190,41 @@ public void startRecording(File file) { mVideoRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); mVideoRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); + // Every profile below is fetched for the camera actually in use. The single-argument + // overload returns the first back-facing camera's profile whatever camera is open, so on + // the front camera it handed MediaRecorder a size and encoder configuration belonging to + // a different sensor - which is one way to get a recording full of green lines. switch (getQuality()) { case MAX: if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_HIGH)) { - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); + mVideoRecorder.setProfile(CamcorderProfile.get(mActiveCamera, CamcorderProfile.QUALITY_HIGH)); break; } // Fall-through case HIGH: if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_1080P)) { - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P)); + mVideoRecorder.setProfile(CamcorderProfile.get(mActiveCamera, CamcorderProfile.QUALITY_1080P)); break; } // Fall-through case MEDIUM: if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_720P)) { - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P)); + mVideoRecorder.setProfile(CamcorderProfile.get(mActiveCamera, CamcorderProfile.QUALITY_720P)); break; } // Fall-through case LOW: if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_480P)) { - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P)); + mVideoRecorder.setProfile(CamcorderProfile.get(mActiveCamera, CamcorderProfile.QUALITY_480P)); break; } // Fall-through default: - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW)); + mVideoRecorder.setProfile(CamcorderProfile.get(mActiveCamera, CamcorderProfile.QUALITY_LOW)); break; } mVideoRecorder.setOutputFile(file.getAbsolutePath()); mVideoRecorder.setMaxDuration((int) getMaxVideoDuration()); - mVideoRecorder.setMaxDuration((int) getMaxVideoDuration()); mVideoRecorder.setMaxFileSize(getMaxVideoSize()); mVideoRecorder.setOrientationHint(getRelativeCameraOrientation(false /* isPreview */)); mVideoRecorder.setOnInfoListener((mr, what, extra) -> {