Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/android-validation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,58 @@ 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))));
```

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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -241,20 +242,30 @@ public void aStreamDeliversEncodedFrames() throws Exception {
public void theControlsAnswer() throws Exception {
AtomicInteger maxZoom = new AtomicInteger();
AtomicReference<CameraView.Flash> flash = new AtomicReference<>();
AtomicReference<CameraView.Flash> 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. */
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ public void closingAndReopeningWorksOnALiveCamera() throws Exception {
public void theOptionalControlsAreOfferedToTheCamera() throws Exception {
AtomicReference<String> reported = new AtomicReference<>();

DeviceState.assumeTheLampMayBeLit();

withOpenCamera(camera -> {
camera.setTorchEnabled(true);
sleep(300);
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -22,6 +25,27 @@
final class DeviceState {
private DeviceState() {}

/**
* Turns the flash off for a test that does not care about it.
*
* <p>Separate from the tests so there is one place to look when a run starts flashing.</p>
*/
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.
*
* <p>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.</p>
*/
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}
Expand Down
22 changes: 22 additions & 0 deletions camera-view/src/main/java/com/xlythe/view/camera/CameraView.java
Original file line number Diff line number Diff line change
Expand Up @@ -1271,6 +1271,28 @@ public void startFrameAnalysis(
mFrameStream.start();
}

/**
* The horizontal angle of view, in degrees, that the camera can currently see.
*
* <p>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.</p>
*
* <p>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.</p>
*
* @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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>Zero when the camera does not publish enough to work it out. Includes the effect of
* zoom, because a zoomed camera sees less.</p>
*/
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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>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.</p>
*
* @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.
*
* <p>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.</p>
*
* @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;
Expand Down
Loading
Loading