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
94 changes: 94 additions & 0 deletions .github/workflows/android-validation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
name: Android validation

on:
push:
pull_request:
workflow_dispatch:
schedule:
- cron: '30 8 * * 1'

permissions:
contents: read

concurrency:
group: android-validation-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
verify:
runs-on: ubuntu-latest
timeout-minutes: 35
steps:
- name: Check out source
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Make Gradle wrapper executable
run: chmod +x gradlew
- name: Set up JDK 21
uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
with:
distribution: temurin
java-version: '21'
check-latest: false
- name: Configure Gradle
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
- name: Verify build, lint, tests, and coverage
run: >-
./gradlew --no-daemon --stacktrace
:camera-view:lintDebug
:app:lintDebug
:app-compose:lintDebug
:camera-view:testDebugUnitTest
:app:testDebugUnitTest
:app-compose:testDebugUnitTest
:camera-view:jacocoCoreCoverageVerification
:camera-view:assembleRelease
:app:assembleDebug
:app-compose:assembleDebug
- name: Upload verification reports
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: verification-reports
if-no-files-found: ignore
path: |
**/build/reports/lint-results-*.html
**/build/reports/tests/**
camera-view/build/reports/jacoco/**

managed-device:
needs: verify
runs-on: ubuntu-latest
timeout-minutes: 90
steps:
- name: Check out source
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Make Gradle wrapper executable
run: chmod +x gradlew
- name: Set up JDK 21
uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0
with:
distribution: temurin
java-version: '21'
check-latest: false
- name: Configure Gradle
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
- name: Enable KVM
run: |
if [ -e /dev/kvm ]; then
sudo chmod 666 /dev/kvm
fi
- name: Run API 30 and API 37 managed-device tests
run: >-
./gradlew --no-daemon --stacktrace
:camera-view:cameraMatrixGroupDebugAndroidTest
-Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect
- name: Upload device-test results
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: managed-device-results
if-no-files-found: ignore
path: |
camera-view/build/reports/androidTests/**
camera-view/build/outputs/androidTest-results/**
camera-view/build/outputs/code_coverage/**
7 changes: 2 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,5 @@
/build
/.idea
*.iml
/gradle
gradlew
gradlew.bat
*.apk
.vscode/settings.json
*.apk
.vscode/settings.json
130 changes: 126 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Camera View
====================

CameraView provides a simple wrapper around the Android camera APIs, with backwards compatibility
to API 14. Rather than directly manipulating the camera, here you have an Android View that can be
to API 21. Rather than directly manipulating the camera, here you have an Android View that can be
placed within your app. This View displays a preview and has the methods takePicture(File),
startRecording(File) and stopRecording(). For simple use cases, CameraFragment exists as well.
If you inflate a CameraFragment with Views that have the correct ids (eg. @id/capture),
Expand Down Expand Up @@ -38,7 +38,7 @@ Camera
Camera is a Composable that simplifies the Android Camera APIs.

Camera includes the optional attributes quality [max, high, medium, low],
maxVideoDuration [milliseconds], and maxVideoSize [bytes].
lensFacing [back, front], maxVideoDuration [milliseconds], and maxVideoSize [bytes].
```kotlin
val cameraController = remember { mutableStateOf<CameraController?>(null) }
Camera(
Expand All @@ -47,7 +47,6 @@ Camera(
lensFacing = Camera.LensFacing.BACK,
maxVideoDuration = 10000,
maxVideoSize = 10000000,
controller = cameraController,
controller = cameraController
)
```
Expand Down Expand Up @@ -168,7 +167,9 @@ CameraFragment, then this will happen for free.


CameraView includes the optional attributes quality [max, high, medium, low],
maxVideoDuration [milliseconds], and maxVideoSize [bytes].
flash [auto, on, off], lensFacing [back, front], maxVideoDuration [milliseconds],
maxVideoSize [bytes], confirmImages [boolean], confirmVideos [boolean],
pinchToZoomEnabled [boolean] and matchPreviewAspectRatio [boolean].
```xml
<com.xlythe.view.camera.CameraView
xmlns:camera="http://schemas.android.com/apk/res-auto"
Expand All @@ -181,6 +182,16 @@ maxVideoDuration [milliseconds], and maxVideoSize [bytes].
camera:maxVideoSize="10000000" />
```

The following attributes are also accepted, but the Camera2 backend that ships enabled today
ignores all of them. They are read by the CameraX backend, which is still opt-in:
dynamicRange [sdr, hdr], extension [none, bokeh, hdr, night, faceRetouch, auto],
frontVideoMirroringEnabled [boolean], previewStabilizationEnabled [boolean],
videoStabilizationEnabled [boolean], exposureCompensation [integer], torchEnabled [boolean]
and lowLightBoostEnabled [boolean]. Each has a matching setter, and a companion that reports
whether the active camera supports it, for example isDynamicRangeSupported(DynamicRange) or
isLowLightBoostSupported(). Query support before relying on one; an unsupported request is
logged and dropped rather than applied.

CameraView's methods are rather straight forward. Again, if you're using CameraFragment, it will
handle binding the Views to the appropriate methods on CameraView.

Expand All @@ -204,6 +215,117 @@ Toggles between the various cameras on the device (typically the front and back
```java
mCameraView.toggleCamera();
```
Reports when the camera opens and closes. CameraFragment already implements this.
```java
mCameraView.setOnCameraStateChangedListener(listener);
```
With confirmation enabled, a capture is shown in CameraView's own preview and onImageConfirmation()
or onVideoConfirmation() fires instead of onImageCaptured(File) or onVideoCaptured(File). Accept or
discard it to continue; rejecting also deletes the file. Enable matchPreviewAspectRatio alongside
this so the capture and the preview are framed the same.
```java
mCameraView.setImageConfirmationEnabled(true);
mCameraView.confirmPicture(); // or rejectPicture()
mCameraView.confirmVideo(); // or rejectVideo()
```
Scans the preview for barcodes while the camera is open, reporting each batch of results to the
listener. Formats come from Barcode.Format, and the camera must already be open.
```java
mCameraView.enterBarcodeScanner(listener, Barcode.Format.QR_CODE);
mCameraView.exitBarcodeScanner();
```

Wide gamut
-----------------
Pictures are sRGB unless you ask otherwise. A modern sensor sees more than sRGB can describe,
which is why manufacturers' camera apps save wide-gamut stills, but a viewer that ignores the
colour profile shows them oversaturated - so it is opt-in, and refused on a camera or a platform
that cannot honour it rather than quietly producing sRGB.
```java
if (mCameraView.isColorSpaceSupported(CameraView.ColorSpace.DISPLAY_P3)) {
mCameraView.setColorSpace(CameraView.ColorSpace.DISPLAY_P3);
}
```

Video snapshot
-----------------
takePicture works during a recording, where the camera can hold a preview, a recording and a still
at once - which is most of them, but not a LEGACY camera2 device. Ask before showing the button;
where it is false the picture is refused and the recording carries on.
```java
if (mCameraView.isSnapshotWhileRecordingSupported()) {
mCameraView.takePicture(file);
}
```

Faces
-----------------
The camera finds faces on its own, to decide what to focus and expose for. setFaceDetectionListener
reports them, with a matrix that maps a face's bounds onto the view so you can draw over the
preview. It returns false on a camera that cannot report faces.
```java
mCameraView.setFaceDetectionListener((faces, faceToView) -> {
for (Face face : faces) {
RectF onScreen = new RectF(face.getBounds());
faceToView.mapRect(onScreen);
}
});
mCameraView.setFaceDetectionListener(null);
```

Frames
-----------------
startFrameAnalysis hands every frame to your own analyzer, on a background thread, for detection
CameraView does not do itself. Only the newest frame is kept, so a slow analyzer drops frames
rather than falling behind, and the image is recycled when onFrame returns. Params.setMaxSize asks
for smaller frames than the preview, which most detectors are no worse at.
```java
mCameraView.startFrameAnalysis(frame -> {
InputImage image = InputImage.fromMediaImage(frame.getImage(), frame.getRotationDegrees());
// ... and frame.getFrameToViewTransform() maps a result onto the view
}, new FrameStream.Params().setMaxSize(new Size(640, 480)));
mCameraView.stopFrameAnalysis();
```

Wear companion
-----------------
The sample has a watch half, in `app-wear`: the phone streams its camera to the watch and the
watch's button asks the phone for a picture. Both halves share one application id, which is how
the Data Layer pairs them, so they have to be built and signed together.

Nothing in the library is Wear-specific. The watch reads the phone's stream with the same
VideoView.setStream the phone sample uses locally; what the sample adds is the transport, and the
numbers that make it work over a watch link - 480p, a megabit, and a key frame every second,
since a stream can only be joined at a key frame.
```java
mCameraView.stream(new VideoStream.Params.Builder()
.setAudioEnabled(false)
.setMaxSize(new Size(640, 480))
.setBitRate(1_000_000)
.setIFrameInterval(1)
.setIsLossy(true)
.build());
```

Backends
-----------------
CameraView drives camera2 by default. CameraX is opt-in: it carries a database of per-device
quirks and is the only backend that can reach a manufacturer's Extensions, but it has had less
validation here. The legacy android.hardware.Camera backend is there for devices that predate
camera2.
```java
CameraView.setDefaultBackend(CameraView.Backend.CAMERA_X);
```
```xml
<com.xlythe.view.camera.CameraView
app:backend="cameraX" />
```
If your minSdk is older than androidx.camera supports, build with `-Pcameraview.core=true` to
leave the CameraX backend, the Compose wrapper and their dependencies out. What is left covers
API 21 and up. This is not hypothetical: `camera-camera2` pulls in `camera-camera2-pipe`, which
declares a minSdk of 24, and a dependency's floor becomes your app's floor whatever this library
declares. The sample reads the same flag, so `-Pcameraview.core=true :app:assembleDebug` builds
it at 23.

Exif
-----------------
Expand Down
34 changes: 17 additions & 17 deletions app-compose/build.gradle
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'org.jetbrains.kotlin.plugin.compose' version '2.3.21'
}

android {
namespace 'com.xlythe.sample.camera'
namespace = 'com.xlythe.sample.camera'
compileSdk 37

defaultConfig {
Expand All @@ -25,14 +24,15 @@ android {
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = '11'
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
buildFeatures {
compose true
compose = true
}
lint {
abortOnError = true
checkReleaseBuilds = true
}
testOptions {
unitTests.includeAndroidResources = true
Expand All @@ -44,20 +44,20 @@ android {

dependencies {
implementation project(':camera-view')
implementation 'androidx.core:core-ktx:+'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:+'
implementation 'androidx.activity:activity-compose:+'
implementation platform('androidx.compose:compose-bom:+')
implementation 'androidx.core:core-ktx:1.19.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.11.1'
implementation 'androidx.activity:activity-compose:1.13.0'
implementation platform('androidx.compose:compose-bom:2026.06.01')
implementation 'androidx.compose.ui:ui'
implementation 'androidx.compose.ui:ui-graphics'
implementation 'androidx.compose.ui:ui-tooling-preview'
implementation 'androidx.compose.material3:material3'
implementation 'androidx.compose.material:material-icons-extended'
testImplementation 'junit:junit:+'
testImplementation 'org.robolectric:robolectric:+'
androidTestImplementation 'androidx.test.ext:junit:+'
androidTestImplementation 'androidx.test.espresso:espresso-core:+'
androidTestImplementation platform('androidx.compose:compose-bom:+')
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.robolectric:robolectric:4.18.1'
androidTestImplementation 'androidx.test.ext:junit:1.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.7.0'
androidTestImplementation platform('androidx.compose:compose-bom:2026.06.01')
androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
debugImplementation 'androidx.compose.ui:ui-tooling'
debugImplementation 'androidx.compose.ui:ui-test-manifest'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ private fun createImageFile(context: Context): File {
return File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir)
}

@SuppressLint("MissingPermission")
@Composable
fun SimpleDemoScreen() {
val context = LocalContext.current
Expand Down Expand Up @@ -363,6 +364,7 @@ fun StreamDemoScreen() {
}
}

@SuppressLint("MissingPermission")
@Composable
fun ResizingDemoScreen() {
val cameraController = remember { mutableStateOf<CameraController?>(null) }
Expand Down Expand Up @@ -417,6 +419,7 @@ fun ResizingDemoScreen() {
}
}

@SuppressLint("MissingPermission")
@Composable
fun QrCodeDemoScreen() {
val context = LocalContext.current
Expand Down
7 changes: 7 additions & 0 deletions app-compose/src/main/res/values-v31/themes.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<resources>
<style name="Theme.CameraView" parent="android:Theme.Material.NoActionBar">
<item name="android:windowBackground">#121212</item>
<item name="android:windowSplashScreenBackground">#000000</item>
<item name="android:windowSplashScreenAnimatedIcon">@android:color/transparent</item>
</style>
</resources>
2 changes: 0 additions & 2 deletions app-compose/src/main/res/values/themes.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@

<style name="Theme.CameraView" parent="android:Theme.Material.NoActionBar">
<item name="android:windowBackground">#121212</item>
<item name="android:windowSplashScreenBackground">#000000</item>
<item name="android:windowSplashScreenAnimatedIcon">@android:color/transparent</item>
</style>
</resources>
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config

@RunWith(RobolectricTestRunner::class)
@Config(minSdk = 24)
@Config(sdk = [37])
class MainActivityTest {

@Test
Expand Down
1 change: 1 addition & 0 deletions app-wear/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
Loading
Loading