From be58c1239f4480918874d4b74ace02e4bc769d67 Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 01:18:47 -0500 Subject: [PATCH 01/10] Bring the build current, and make the old-API build real Gradle 9.9.2 with the daemon pinned to JDK 21, dependencies moved to their current releases, and API 37 validation that reproduces rather than drifting with whatever is installed. Two things are more than housekeeping. The coverage report was dropping every Kotlin class, because AGP moved where it writes them and the configured path silently matched nothing - which is how the Compose sources went unmeasured. Every layout this project has shipped against is accepted now, and a path that matches nothing fails the build rather than producing a quietly smaller report. The report also reads a device run's execution data when there is any, because the paths that only exist on a real camera cannot be reached off one, and a figure built from unit tests alone understates a camera library. The gates are two. The strict one keeps 90% of lines and branches over the deterministic logic - the coordinate maths, the metadata, the stream framing - which has no camera, codec or surface in it and so has no excuse; every class in it has hosted a real bug. The second holds a floor under the library as a whole, set a little under where the suite stands, so the rest cannot quietly rot. The old gate covered four classes and passed because of what it left out. And -Pcameraview.core=true builds the library without the CameraX backend, the Compose wrapper or their dependencies. That is not hypothetical: camera-camera2 pulls in camera-camera2-pipe, which declares a minSdk of 24, and a dependency's floor becomes the app's floor whatever this library declares. Both configurations are assembled, so the claim is one the build proves. Co-Authored-By: Claude Opus 5 --- .github/workflows/android-validation.yml | 94 +++++++++ .gitignore | 7 +- build.gradle | 26 ++- camera-view/build.gradle | 121 ++++++++--- gradle.properties | 13 +- gradle/coverage.gradle | 185 +++++++++++++++++ gradle/gradle-daemon-jvm.properties | 13 ++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 48966 bytes gradle/wrapper/gradle-wrapper.properties | 8 + gradlew | 248 +++++++++++++++++++++++ gradlew.bat | 93 +++++++++ settings.gradle | 4 +- 12 files changed, 765 insertions(+), 47 deletions(-) create mode 100644 .github/workflows/android-validation.yml create mode 100644 gradle/coverage.gradle create mode 100644 gradle/gradle-daemon-jvm.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat diff --git a/.github/workflows/android-validation.yml b/.github/workflows/android-validation.yml new file mode 100644 index 0000000..946c887 --- /dev/null +++ b/.github/workflows/android-validation.yml @@ -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/** diff --git a/.gitignore b/.gitignore index 637d11e..b8a3847 100644 --- a/.gitignore +++ b/.gitignore @@ -6,8 +6,5 @@ /build /.idea *.iml -/gradle -gradlew -gradlew.bat -*.apk -.vscode/settings.json +*.apk +.vscode/settings.json diff --git a/build.gradle b/build.gradle index 883c064..c9fbd27 100644 --- a/build.gradle +++ b/build.gradle @@ -6,9 +6,7 @@ buildscript { google() } dependencies { - classpath 'com.android.tools.build:gradle:9.2.1' - classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' - classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.2.10' + classpath 'com.android.tools.build:gradle:9.3.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files @@ -20,4 +18,26 @@ allprojects { mavenCentral() google() } + + configurations.configureEach { + resolutionStrategy { + failOnDynamicVersions() + failOnChangingVersions() + } + } + + tasks.withType(Test).configureEach { + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(21) + } + jvmArgs( + '--add-opens=java.base/java.lang=ALL-UNNAMED', + '--add-opens=java.base/java.util=ALL-UNNAMED', + '--add-exports=java.base/jdk.internal.access=ALL-UNNAMED' + ) + testLogging { + events 'failed', 'skipped' + exceptionFormat = 'full' + } + } } diff --git a/camera-view/build.gradle b/camera-view/build.gradle index eab72c9..7c56df4 100644 --- a/camera-view/build.gradle +++ b/camera-view/build.gradle @@ -2,7 +2,7 @@ plugins { id 'com.android.library' id 'maven-publish' id 'signing' - id 'org.jetbrains.kotlin.android' + id 'jacoco' id 'org.jetbrains.kotlin.plugin.compose' version '2.3.21' id 'com.gradleup.nmcp' version '1.5.0' } @@ -11,51 +11,109 @@ Properties projectProperties = new Properties() projectProperties.load(rootProject.file('gradle.properties').newDataInputStream()) Properties localProperties = new Properties() -localProperties.load(project.rootProject.file('local.properties').newDataInputStream()) +File localPropertiesFile = project.rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localProperties.load(localPropertiesFile.newDataInputStream()) +} + +// Builds without the optional backends, for an app whose minSdk is older than the newest +// androidx.camera and Compose releases support. CameraView's own floor is API 21, which the +// camera2 and legacy backends cover on their own; what forces a higher one is the dependencies +// CameraX and the Compose wrapper bring with them. Set -Pcameraview.core=true to leave both out: +// the source directories and their dependencies go together, so what is left is a library that +// compiles and links against nothing newer than API 21. +boolean coreOnly = project.hasProperty('cameraview.core') + && project.property('cameraview.core').toString().toBoolean() android { compileSdkVersion 37 defaultConfig { minSdkVersion 21 + targetSdkVersion 37 + testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' } compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } - kotlinOptions { - jvmTarget = '17' + buildFeatures { + compose = !coreOnly } - buildFeatures { - compose = true + if (coreOnly) { + sourceSets.main.java.filter.exclude '**/com/xlythe/view/camera/x/**' + sourceSets.main.kotlin.filter.exclude '**/com/xlythe/compose/**' + sourceSets.main.java.filter.exclude '**/com/xlythe/view/camera/CameraXBarcodeAnalyzer.java' + sourceSets.test.java.filter.exclude '**/com/xlythe/view/camera/x/**' } lint { - abortOnError false + abortOnError = true + checkReleaseBuilds = true targetSdk 37 } + buildTypes { + debug { + enableAndroidTestCoverage = true + } + } publishing { singleVariant("release") { withSourcesJar() withJavadocJar() } } - namespace 'com.xlythe.view.camera' + namespace = 'com.xlythe.view.camera' testOptions { targetSdk 37 + animationsDisabled = true + unitTests.includeAndroidResources = true unitTests.all { maxHeapSize = "2g" + jacoco { + includeNoLocationClasses = true + excludes = ['jdk.internal.*'] + } + } + managedDevices { + localDevices { + pixel2Api30 { + device = 'Pixel 2' + apiLevel = 30 + systemImageSource = 'aosp' + } + pixel6Api37 { + device = 'Pixel 6' + apiLevel = 37 + systemImageSource = 'aosp' + pageAlignment = com.android.build.api.dsl.ManagedVirtualDevice.PageAlignment.FORCE_16KB_PAGES + } + } + groups { + cameraMatrix { + targetDevices.addAll(localDevices.pixel2Api30, localDevices.pixel6Api37) + } + } } } } +jacoco { + toolVersion = '0.8.16' +} + afterEvaluate { + def releaseComponent = components.findByName('release') + if (releaseComponent == null) { + logger.warn('Release software component is not available; publication tasks will remain disabled.') + return + } publishing { publications { release(MavenPublication) { - from components.release + from releaseComponent groupId = group = projectProperties.getProperty("bintray.groupId") artifactId = projectProperties.getProperty("bintray.artifact") version = projectProperties.getProperty("bintray.libraryVersion") @@ -111,25 +169,38 @@ signing { dependencies { api fileTree(include: ['*.jar'], dir: 'libs') - api 'androidx.legacy:legacy-support-v4:[1.0.0,)' - api 'androidx.exifinterface:exifinterface:[1.4.1,)' - api 'androidx.camera:camera-core:[1.4.2,)' - api 'androidx.camera:camera-camera2:[1.4.2,)' - api 'androidx.camera:camera-lifecycle:[1.4.2,)' - api 'androidx.camera:camera-video:[1.4.2,)' - api 'com.google.guava:guava:[31.1-android,)' - api 'com.google.mlkit:barcode-scanning:[17.3.0,)' - api 'androidx.activity:activity-compose:[1.10.1,)' - api 'androidx.lifecycle:lifecycle-runtime-ktx:[2.8.7,)' - testImplementation 'org.robolectric:robolectric:+' - testImplementation 'org.mockito:mockito-core:+' - testImplementation 'junit:junit:+' + api 'androidx.legacy:legacy-support-v4:1.0.0' + api 'androidx.exifinterface:exifinterface:1.4.2' + api 'androidx.concurrent:concurrent-futures:1.3.0' + api 'com.google.guava:guava:33.8.0-android' + api 'com.google.mlkit:barcode-scanning:17.3.0' + if (!coreOnly) { + api 'androidx.camera:camera-core:1.7.0' + api 'androidx.camera:camera-camera2:1.7.0' + api 'androidx.camera:camera-lifecycle:1.7.0' + api 'androidx.camera:camera-extensions:1.7.0' + api 'androidx.camera:camera-video:1.7.0' + api 'androidx.activity:activity-compose:1.13.0' + api 'androidx.lifecycle:lifecycle-runtime-ktx:2.11.1' + } + testImplementation 'org.robolectric:robolectric:4.18.1' + testImplementation 'androidx.compose.ui:ui-test-junit4-android:1.9.2' + debugImplementation 'androidx.compose.ui:ui-test-manifest:1.9.2' + testImplementation 'org.mockito:mockito-core:5.24.0' + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test:core:1.7.0' + androidTestImplementation 'androidx.test.ext:junit:1.3.0' + androidTestImplementation 'androidx.test:rules:1.7.0' + androidTestImplementation 'androidx.test:runner:1.7.0' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.7.0' constraints { - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:2.2.20") { + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:2.3.21") { because("kotlin-stdlib-jdk7 is now a part of kotlin-stdlib") } - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:2.2.20") { + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:2.3.21") { because("kotlin-stdlib-jdk8 is now a part of kotlin-stdlib") } } -} \ No newline at end of file +} + +apply from: rootProject.file('gradle/coverage.gradle') diff --git a/gradle.properties b/gradle.properties index 6f3b770..d7c5e3d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,17 +18,6 @@ bintray.licenseUrl=http://www.apache.org/licenses/LICENSE-2.0.txt bintray.allLicenses=Apache-2.0 android.useAndroidX=true -android.enableJetifier=true -android.nonTransitiveRClass=false -android.nonFinalResIds=false org.gradle.jvmargs=-Xmx8g -Dfile.encoding=UTF-8 -android.defaults.buildfeatures.resvalues=true -android.sdk.defaultTargetSdkToCompileSdkIfUnset=false -android.enableAppCompileTimeRClass=false -android.usesSdkInManifest.disallowed=false -android.uniquePackageNames=false android.dependency.useConstraints=true -android.r8.strictFullModeForKeepRules=false -android.r8.optimizedResourceShrinking=false -android.builtInKotlin=false -android.newDsl=false +android.generateSyncIssueWhenLibraryConstraintsAreEnabled=false diff --git a/gradle/coverage.gradle b/gradle/coverage.gradle new file mode 100644 index 0000000..e6b5ec8 --- /dev/null +++ b/gradle/coverage.gradle @@ -0,0 +1,185 @@ +import org.gradle.testing.jacoco.tasks.JacocoCoverageVerification +import org.gradle.testing.jacoco.tasks.JacocoReport + +def coverageExclusions = [ + '**/R.class', + '**/R$*.class', + '**/BuildConfig.*', + '**/Manifest*.*' +] + +// JaCoCo needs the compiled classes, and AGP keeps moving where it writes them: Kotlin output +// lived in build/tmp/kotlin-classes/debug before AGP 9 and lives under built_in_kotlinc now. +// Accept every layout we have shipped against, then assert below that each language actually +// matched one. A path that quietly stops existing drops a whole source set from the report +// instead of failing, which is how the Compose sources went unmeasured. +def javaClassDirectories = [ + 'intermediates/javac/debug/compileDebugJavaWithJavac/classes' +] +def kotlinClassDirectories = [ + 'intermediates/built_in_kotlinc/debug/compileDebugKotlin/classes', + 'tmp/kotlin-classes/debug' +] + +def classTrees = { List relativePaths, Closure filter -> + files(relativePaths.collect { relativePath -> + fileTree(layout.buildDirectory.dir(relativePath)) { filter.delegate = delegate; filter() } + }) +} + +def allProductionClasses = classTrees(javaClassDirectories + kotlinClassDirectories) { + exclude coverageExclusions +} + +// These classes are deterministic production logic and must remain thoroughly unit tested: the +// coordinate maths, the metadata, the stream framing and the small value types. They have no +// camera, codec or surface in them, so there is no reason for any of them to be less than fully +// covered, and each has been the home of a real bug - a preview rotated twice, an orientation +// table with one wrong cell, a GPS speed truncated by the rational it was written as. +// +// Everything that drives a camera, a codec or a view lifecycle stays out of this gate and in the +// full report. Robolectric can reach a surprising amount of it with the right shadows, but not +// all, and a gate that demands what cannot be reached off a device only teaches people to +// exclude things. +def coreCoverageIncludes = [ + 'com/xlythe/view/camera/Exif.class', + 'com/xlythe/view/camera/Exif$*.class', + 'com/xlythe/view/camera/PermissionChecker.class', + 'com/xlythe/view/camera/TransformMath.class', + 'com/xlythe/view/camera/x/CameraXMath.class', + 'com/xlythe/view/camera/stream/AudioBuffer.class', + 'com/xlythe/view/camera/stream/AudioStreamHeader.class', + 'com/xlythe/view/camera/stream/AudioStreamHeader$*.class', + 'com/xlythe/view/camera/stream/LossyPipedOutputStream.class', + 'com/xlythe/view/camera/stream/VideoFrame*.class' +] + +// And a floor under the library as a whole, so the parts that are not in the gate above cannot +// quietly rot. Set just under where the suite actually stands rather than at an aspiration: a +// gate nobody can meet is a gate somebody turns off. +def wholeLibraryLineMinimum = 0.63 + +def wholeLibraryBranchMinimum = 0.45 + +def coreProductionClasses = classTrees(javaClassDirectories + kotlinClassDirectories) { + include coreCoverageIncludes +} + +def unitCoverageData = layout.buildDirectory.file('jacoco/testDebugUnitTest.exec') + +// Instrumented coverage, when a device run has produced any. The paths that only exist on a real +// camera - a capture that makes a JPEG, two outputs configured at once, a detector running in the +// image signal processor - cannot be reached off one, so a report built from unit tests alone +// understates the library and a gate built on it asks for the impossible. AGP writes one file per +// device under code_coverage, and a connected run writes outputs/code-coverage; both are picked +// up when present and neither is required, so the report still builds without a device. +def instrumentedCoverageData = files( + fileTree(layout.buildDirectory.dir('outputs/code_coverage')) { + include '**/*.ec' + }, + fileTree(layout.buildDirectory.dir('outputs/code-coverage')) { + include '**/*.ec' + }) + +def allCoverageData = files(unitCoverageData, instrumentedCoverageData) + +/** + * Fails when a configured class directory produced nothing, so a moved AGP intermediate path + * surfaces as a build failure rather than as a silently smaller report. + */ +def assertClassesFound = { String language, List relativePaths -> + boolean found = relativePaths.any { relativePath -> + File directory = layout.buildDirectory.dir(relativePath).get().asFile + directory.isDirectory() && fileTree(directory).matching { include '**/*.class' }.any() + } + if (!found) { + throw new GradleException("No compiled ${language} classes found for coverage. " + + "Looked in ${relativePaths}. An AGP upgrade has probably moved the output; " + + "update gradle/coverage.gradle rather than leaving the report incomplete.") + } +} + +tasks.register('jacocoTestReport', JacocoReport) { + group = 'verification' + description = 'Generates the whole-library unit-test coverage report.' + dependsOn tasks.named('testDebugUnitTest') + + classDirectories.setFrom(allProductionClasses) + sourceDirectories.setFrom(files('src/main/java')) + executionData.setFrom(allCoverageData) + + doFirst { + assertClassesFound('Java', javaClassDirectories) + assertClassesFound('Kotlin', kotlinClassDirectories) + } + + reports { + xml.required = true + html.required = true + csv.required = false + } +} + +tasks.register('jacocoCoreCoverageVerification', JacocoCoverageVerification) { + group = 'verification' + description = 'Enforces 90% line and branch coverage for deterministic core logic.' + dependsOn tasks.named('jacocoTestReport') + + classDirectories.setFrom(coreProductionClasses) + sourceDirectories.setFrom(files('src/main/java')) + executionData.setFrom(allCoverageData) + + doFirst { + assertClassesFound('Java', javaClassDirectories) + assertClassesFound('Kotlin', kotlinClassDirectories) + } + + violationRules { + rule { + limit { + counter = 'LINE' + value = 'COVEREDRATIO' + minimum = 0.90 + } + limit { + counter = 'BRANCH' + value = 'COVEREDRATIO' + minimum = 0.90 + } + } + } +} + +tasks.register('jacocoLibraryCoverageVerification', JacocoCoverageVerification) { + group = 'verification' + description = 'Holds a floor under the library as a whole, so untested code cannot grow.' + dependsOn tasks.named('jacocoTestReport') + + classDirectories.setFrom(allProductionClasses) + sourceDirectories.setFrom(files('src/main/java')) + executionData.setFrom(allCoverageData) + + violationRules { + rule { + limit { + counter = 'LINE' + value = 'COVEREDRATIO' + minimum = wholeLibraryLineMinimum + } + limit { + counter = 'BRANCH' + value = 'COVEREDRATIO' + minimum = wholeLibraryBranchMinimum + } + } + } +} + +tasks.named('check') { + dependsOn tasks.named('jacocoCoreCoverageVerification') + dependsOn tasks.named('jacocoLibraryCoverageVerification') +} + +tasks.matching { it.name == 'testDebugUnitTest' }.configureEach { + finalizedBy tasks.named('jacocoTestReport') +} diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties new file mode 100644 index 0000000..64a7e38 --- /dev/null +++ b/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,13 @@ +#This file is generated by updateDaemonJvm +toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/bc7c5a81f3d680de7b32b5671550e6fa/redirect +toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/06a33bd735fe2a3eaad523052759de91/redirect +toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/bc7c5a81f3d680de7b32b5671550e6fa/redirect +toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/06a33bd735fe2a3eaad523052759de91/redirect +toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/f257be9f04bfdf169051808541767806/redirect +toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/1dcbacacca32618bd21ec5465779ade1/redirect +toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/bc7c5a81f3d680de7b32b5671550e6fa/redirect +toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/06a33bd735fe2a3eaad523052759de91/redirect +toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/476d3c08f4989328dee56d22e202d98d/redirect +toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/5a88b04b5e582b332d2e6bc12b45f1b9/redirect +toolchainVendor=ADOPTIUM +toolchainVersion=21 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..d997cfc60f4cff0e7451d19d49a82fa986695d07 GIT binary patch literal 48966 zcma&NW0WmQwk%w>ZQHhO+qUi6W!pA(xoVef+k2O7+pkXd9rt^$@9p#T8Y9=Q^(R-x zjL3*NQ$ZRS1O)&B0s;U4fbe_$e;)(@NB~(;6+v1_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ii6PALi)3nOXL)o&Uj%-OnQ52M&L%(%ZaWiu^(R{b!Bu2WJl< h$Zw`p^gE5e2}ml*LW4$nU|{5+pXG<~Ugg7I{||-5t(pJ; literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..544adfc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=971fcd7150ca4ba04852c0b2ca0d2d0ab9468e14b03473eab19528809914c76b +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..739907d --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle index 5380024..dbb6a22 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,4 +1,4 @@ plugins { - id 'org.gradle.toolchains.foojay-resolver-convention' version '0.10.0' + id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' } -include ':app', ':app-compose', ':camera-view' +include ':app', ':app-compose', ':app-wear', ':camera-view' From 2d2f462551bd445e4b0b8d5e5d2e64b689843332 Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 01:18:45 -0500 Subject: [PATCH 02/10] Give CameraView frames, faces and a choice of backend Three things an app could not do, and one it could not do on purpose. Which backend CameraView drove was decided by a package-private constant that was always false, so the CameraX implementation - its lifecycle handling, its device-quirk database, its vendor Extensions - could not be reached from an app at all. CameraView.Backend names the three, per view with app:backend or process-wide with setDefaultBackend, and Camera2 stays the default. CameraX is built reflectively, so asking for it on a build that excluded androidx.camera falls back with a warning instead of throwing out of a constructor - which also makes the dependency genuinely optional. startFrameAnalysis hands every frame to an analyzer of the caller's own, which is what barcode scanning was already doing privately. Each frame says how to turn itself upright, whether it came from a user-facing lens, and where its pixels land on the view, so an overlay lines up without the caller redoing the transform; only the newest frame is kept, so a slow analyzer drops frames instead of falling behind. The barcode scanner is an analyzer on top of it now, which is one frame pump in the library instead of two. setFaceDetectionListener reports the faces the camera is already tracking - the free hardware detector a manufacturer's own app draws its boxes from - with a matrix onto the view, because the three backends do not agree on what coordinates faces are in. A camera that cannot report faces refuses the listener rather than accepting one that never fires. Also here: a known JPEG quality instead of whatever each device picks, a wide-gamut colour space where the platform and camera support one, isSnapshotWhileRecordingSupported for the video-snapshot button, isImageConfirmationPending so a click handler can ask before acting where confirmPicture() would throw, the microphone permission moved to the methods that actually record audio, and the center-crop maths pulled out of the CameraX backend into TransformMath so the preview and the frame analyzers cannot drift apart. Co-Authored-By: Claude Opus 5 --- camera-view/src/main/AndroidManifest.xml | 52 +- .../java/com/xlythe/view/camera/Barcode.java | 8 + .../xlythe/view/camera/BarcodeScanner.java | 172 +- .../com/xlythe/view/camera/CameraView.java | 3031 ++++++++++------- .../view/camera/CameraXBarcodeAnalyzer.java | 82 + .../java/com/xlythe/view/camera/Face.java | 105 + .../com/xlythe/view/camera/FrameStream.java | 334 ++ .../com/xlythe/view/camera/ICameraModule.java | 263 +- .../com/xlythe/view/camera/TransformMath.java | 115 + camera-view/src/main/res/values/attrs.xml | 24 + 10 files changed, 2783 insertions(+), 1403 deletions(-) create mode 100644 camera-view/src/main/java/com/xlythe/view/camera/CameraXBarcodeAnalyzer.java create mode 100644 camera-view/src/main/java/com/xlythe/view/camera/Face.java create mode 100644 camera-view/src/main/java/com/xlythe/view/camera/FrameStream.java create mode 100644 camera-view/src/main/java/com/xlythe/view/camera/TransformMath.java diff --git a/camera-view/src/main/AndroidManifest.xml b/camera-view/src/main/AndroidManifest.xml index 400dd68..ea639ff 100644 --- a/camera-view/src/main/AndroidManifest.xml +++ b/camera-view/src/main/AndroidManifest.xml @@ -1,54 +1,4 @@ - - - - + - diff --git a/camera-view/src/main/java/com/xlythe/view/camera/Barcode.java b/camera-view/src/main/java/com/xlythe/view/camera/Barcode.java index 7bb1d6d..a4925a0 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/Barcode.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/Barcode.java @@ -4,6 +4,8 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; @@ -25,6 +27,7 @@ public class Barcode { Format.PDF417, Format.AZTEC }) + @Retention(RetentionPolicy.SOURCE) public @interface Format { int UNKNOWN = com.google.mlkit.vision.barcode.common.Barcode.FORMAT_UNKNOWN; int ALL_FORMATS = com.google.mlkit.vision.barcode.common.Barcode.FORMAT_ALL_FORMATS; @@ -58,6 +61,7 @@ public class Barcode { Type.CALENDAR_EVENT, Type.DRIVER_LICENSE }) + @Retention(RetentionPolicy.SOURCE) public @interface Type { int UNKNOWN = com.google.mlkit.vision.barcode.common.Barcode.TYPE_UNKNOWN; int CONTACT_INFO = com.google.mlkit.vision.barcode.common.Barcode.TYPE_CONTACT_INFO; @@ -80,6 +84,7 @@ public static class WiFi { EncryptionType.WPA, EncryptionType.WEP }) + @Retention(RetentionPolicy.SOURCE) public @interface EncryptionType { int OPEN = com.google.mlkit.vision.barcode.common.Barcode.WiFi.TYPE_OPEN; int WPA = com.google.mlkit.vision.barcode.common.Barcode.WiFi.TYPE_WPA; @@ -221,6 +226,7 @@ public static class Email { Type.WORK, Type.HOME }) + @Retention(RetentionPolicy.SOURCE) public @interface Type { int UNKNOWN = com.google.mlkit.vision.barcode.common.Barcode.Email.TYPE_UNKNOWN; int WORK = com.google.mlkit.vision.barcode.common.Barcode.Email.TYPE_WORK; @@ -262,6 +268,7 @@ public static class Phone { Type.FAX, Type.MOBILE }) + @Retention(RetentionPolicy.SOURCE) public @interface Type { int UNKNOWN = com.google.mlkit.vision.barcode.common.Barcode.Phone.TYPE_UNKNOWN; int WORK = com.google.mlkit.vision.barcode.common.Barcode.Phone.TYPE_WORK; @@ -498,6 +505,7 @@ public static class Address { Type.WORK, Type.HOME }) + @Retention(RetentionPolicy.SOURCE) public @interface Type { int UNKNOWN = com.google.mlkit.vision.barcode.common.Barcode.Phone.TYPE_UNKNOWN; int WORK = com.google.mlkit.vision.barcode.common.Barcode.Phone.TYPE_WORK; diff --git a/camera-view/src/main/java/com/xlythe/view/camera/BarcodeScanner.java b/camera-view/src/main/java/com/xlythe/view/camera/BarcodeScanner.java index 21ab6f5..6de022c 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/BarcodeScanner.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/BarcodeScanner.java @@ -1,18 +1,13 @@ package com.xlythe.view.camera; import android.Manifest; -import android.graphics.ImageFormat; -import android.media.Image; -import android.media.ImageReader; -import android.os.Build; import android.util.Log; -import android.view.Surface; +import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.RequiresPermission; import com.google.android.gms.tasks.Tasks; -import com.google.common.util.concurrent.SettableFuture; import com.google.mlkit.vision.barcode.BarcodeScannerOptions; import com.google.mlkit.vision.barcode.BarcodeScanning; import com.google.mlkit.vision.common.InputImage; @@ -21,24 +16,28 @@ import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.concurrent.ExecutionException; - -import static android.os.Process.THREAD_PRIORITY_DISPLAY; -import static android.os.Process.THREAD_PRIORITY_VIDEO; -import static android.os.Process.setThreadPriority; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; /** * When created, you must pass a {@link BarcodeDetectorListener}. Once {@link #start()} is called, * the listener will be called whenever a {@link Barcode} is discovered until {@link #stop()} is * called. + * + *

This is an ML Kit analyzer on top of {@link FrameStream}, which owns the camera frames; the + * same stream is public, so any other detector can be run the same way.

*/ @RequiresApi(18) class BarcodeScanner { private static final String TAG = CameraView.class.getSimpleName(); - /** Draws on our surface. */ - private final VideoRecorder.Canvas mCanvas; + /** Maximum time allowed for a single ML Kit scan. */ + private static final long OPERATION_TIMEOUT_SECONDS = 10; + + /** The camera's frames. */ + private final FrameStream mFrames; /** Processes frames. */ private final com.google.mlkit.vision.barcode.BarcodeScanner mScanner; @@ -46,161 +45,60 @@ class BarcodeScanner { /** Allows us to report events back to the caller. */ private final BarcodeDetectorListener mListener; - /** The rotation of the image. */ - private int mCameraOrientation; - - /** - * If true, the background thread will continue to loop and process frames. Once false, the thread - * will shut down. - */ - private volatile boolean mIsAlive; - - /** The background thread processing frames for us. */ - private Thread mThread; + /** Ensures the ML Kit scanner is closed exactly once. */ + private final AtomicBoolean mStopped = new AtomicBoolean(); /** A simple barcode scanner. */ - public BarcodeScanner(VideoRecorder.Canvas canvas, BarcodeDetectorListener listener, @Barcode.Format int format, @Barcode.Format int... formats) { - this.mCanvas = canvas; + BarcodeScanner(VideoRecorder.Canvas canvas, @Nullable CameraView cameraView, + BarcodeDetectorListener listener, @Barcode.Format int format, + @Barcode.Format int... formats) { this.mScanner = BarcodeScanning.getClient(new BarcodeScannerOptions.Builder() .setBarcodeFormats(format, formats) .build()); this.mListener = listener; + this.mFrames = new FrameStream( + canvas, cameraView, new FrameStream.Params(), this::processFrame); } /** @return True if actively scanning. False otherwise. */ public boolean isScanning() { - return mIsAlive; + return mFrames.isAnalyzing(); } /** Starts scanning. */ @RequiresPermission(Manifest.permission.CAMERA) public void start() { - if (isScanning()) { - Log.w(TAG, "BarcodeScanner is already running"); + if (mStopped.get()) { + Log.w(TAG, "BarcodeScanner cannot be restarted"); return; } - - mIsAlive = true; - mThread = - new Thread() { - @RequiresPermission(Manifest.permission.CAMERA) - @Override - public void run() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - setThreadPriority(THREAD_PRIORITY_VIDEO); - } else { - setThreadPriority(THREAD_PRIORITY_DISPLAY); - } - - SettableFuture requestedSizeFuture = SettableFuture.create(); - SettableFuture providedSurface = SettableFuture.create(); - VideoRecorder.SurfaceProvider surfaceProvider = (width, height, orientation, flipped) -> { - mCameraOrientation = orientation; - requestedSizeFuture.set(new CameraMetadata(width, height, orientation, flipped)); - try { - return providedSurface.get(); - } catch (ExecutionException | InterruptedException e) { - throw new RuntimeException(e); - } - }; - mCanvas.attachSurface(surfaceProvider); - - ImageReader imageReader = null; - try { - CameraMetadata metadata = Objects.requireNonNull(requestedSizeFuture.get()); - imageReader = ImageReader.newInstance(metadata.getWidth(), metadata.getHeight(), ImageFormat.YUV_420_888, 2); - providedSurface.set(imageReader.getSurface()); - - while (isAlive()) { - Image image = imageReader.acquireLatestImage(); - if (image != null) { - try { - processFrame(image); - } finally { - image.close(); - } - } else { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - break; - } - } - } - - } catch (ExecutionException | InterruptedException e) { - Log.e(TAG, "Exception with barcode scanner stream", e); - } finally { - stopInternal(); - if (imageReader != null) { - mCanvas.detachSurface(surfaceProvider); - imageReader.close(); - } - } - } - }; - mThread.start(); - } - - private void stopInternal() { - mIsAlive = false; + mFrames.start(); } /** Stops scanning. */ public void stop() { - stopInternal(); - if (mThread != null) { - try { - mThread.join(300); - } catch (InterruptedException e) { - Log.e(TAG, "Interrupted while joining BarcodeScanner thread", e); - Thread.currentThread().interrupt(); - } + mFrames.close(); + if (mStopped.compareAndSet(false, true)) { + mScanner.close(); } } - private void processFrame(Image mediaImage) { - InputImage image = InputImage.fromMediaImage(mediaImage, mCameraOrientation); + private void processFrame(FrameStream.Frame frame) { + if (mStopped.get()) { + return; + } + InputImage image = InputImage.fromMediaImage( + frame.getImage(), frame.getRotationDegrees()); try { - List barcodes = Tasks.await(mScanner.process(image)); + List barcodes = + Tasks.await(mScanner.process(image), OPERATION_TIMEOUT_SECONDS, TimeUnit.SECONDS); List list = new ArrayList<>(barcodes.size()); for (com.google.mlkit.vision.barcode.common.Barcode barcode : barcodes) { list.add(new Barcode(barcode)); } mListener.onBarcodeFound(list); - } catch (ExecutionException | InterruptedException e) { + } catch (ExecutionException | InterruptedException | TimeoutException e) { Log.w(TAG, "Barcode processing failed", e); } } - - private static class CameraMetadata { - final int width; - final int height; - final int orientation; - final boolean flipped; - - CameraMetadata(int width, int height, int orientation, boolean flipped) { - this.width = width; - this.height = height; - this.orientation = orientation; - this.flipped = flipped; - } - - int getWidth() { - return width; - } - - int getHeight() { - return height; - } - - int getOrientation() { - return orientation; - } - - boolean isFlipped() { - return flipped; - } - } } 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 9e17b06..65ad903 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 @@ -1,1208 +1,1823 @@ -package com.xlythe.view.camera; - -import android.Manifest; -import android.annotation.TargetApi; -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Matrix; -import android.graphics.Rect; -import android.graphics.SurfaceTexture; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Parcelable; -import android.util.AttributeSet; -import android.util.Log; -import android.view.Display; -import android.view.MotionEvent; -import android.view.ScaleGestureDetector; -import android.view.Surface; -import android.view.TextureView; -import android.view.View; -import android.view.ViewConfiguration; -import android.view.ViewGroup; -import android.view.WindowManager; -import android.widget.FrameLayout; -import android.widget.ImageView; - -import androidx.annotation.Nullable; -import androidx.annotation.RequiresApi; -import androidx.annotation.RequiresPermission; -import androidx.annotation.UiThread; - -import com.xlythe.view.camera.legacy.LegacyCameraModule; -import com.xlythe.view.camera.v2.Camera2Module; -import com.xlythe.view.camera.x.CameraXModule; - -import java.io.File; -import java.util.List; - -/** - * A {@link View} that displays a preview of the camera with methods {@link #takePicture(File)}, - * {@link #startRecording(File)} and {@link #stopRecording()}. - * - * Because the Camera is a limited resource and consumes a high amount of power, CameraView must be - * opened/closed. It's recommended to call {@link #open()} in - * {@link android.app.Activity#onStart()} and {@link #close()} in - * {@link android.app.Activity#onStop()}. - */ -public class CameraView extends FrameLayout { - static final String TAG = CameraView.class.getSimpleName(); - static final boolean DEBUG = false; - - // When enabled, CameraX will be used. It's currently unstable. - // Notable bugs: - // * Pictures taken with CameraX may be rotated. CameraX does apply exif rotation itself, but - // incorrectly (eg. Samsung Fold 3 front facing camera). Attempts to overwrite the exif - // metadata manually to fix this failed (and I'm not sure why...). - // * Rotating the device breaks the ability to take pictures/images unless a new CameraView is - // used. - // * The video preview doesn't match the same dimensions of the video that is being recorded. - // * Streaming videos isn't working. - static final boolean USE_CAMERA_X = false; - - // When enabled, CameraV2 will be used. It's currently stable. - static final boolean USE_CAMERA_V2 = true; - - public static final int INDEFINITE_VIDEO_DURATION = -1; - public static final int INDEFINITE_VIDEO_SIZE = -1; - - public static final String ACTION_CAMERA_STATE_CHANGED = "com.xlythe.view.camera.CAMERA_STATE_CHANGED"; - - private static final String EXTRA_SUPER = "super"; - private static final String EXTRA_MODULE = "module"; - private static final String EXTRA_QUALITY = "quality"; - private static final String EXTRA_ZOOM_LEVEL = "zoom_level"; - private static final String EXTRA_PINCH_TO_ZOOM_ENABLED = "pinch_to_zoom_enabled"; - private static final String EXTRA_PINCH_TO_ZOOM_SCALE_FACTOR = "pinch_to_zoom_scale_factor"; - private static final String EXTRA_FLASH = "flash"; - private static final String EXTRA_LENS_FACING = "lens_facing"; - private static final String EXTRA_MAX_VIDEO_DURATION = "max_video_duration"; - private static final String EXTRA_MAX_VIDEO_SIZE = "max_video_size"; - private static final String EXTRA_CONFIRM_IMAGE = "confirm_image"; - private static final String EXTRA_CONFIRM_VIDEO = "confirm_video"; - private static final String EXTRA_PENDING_IMAGE_FILE_PATH = "pending_image_file_path"; - private static final String EXTRA_PENDING_VIDEO_FILE_PATH = "pending_video_file_path"; - private static final String EXTRA_MATCH_PREVIEW_ASPECT_RATIO = "match_preview_aspect_ratio"; - - private enum Status { - OPEN, CLOSED, AWAITING_TEXTURE - } - - /** - * Determines the resolution of CameraView's outputs. All resolutions are best attempts, and - * will fall to lower qualities if the Android device cannot support them. Resolutions also may - * change in the future (if, say, Android adds 8k resolution). - * - * (*) {@link Quality#MAX} will output at 4k. - * (*) {@link Quality#HIGH} will output at 1080p. - * (*) {@link Quality#MEDIUM} will output at 720. - * (*) {@link Quality#LOW} will output at 480. - */ - public enum Quality { - MAX(0), HIGH(1), MEDIUM(2), LOW(3); - - private final int id; - - Quality(int id) { - this.id = id; - } - - static Quality fromId(int id) { - for (Quality q : values()) { - if (q.id == id) return q; - } - throw new IllegalArgumentException(); - } - } - - /** - * Determines the use of the camera's flash when taking pictures. - */ - public enum Flash { - AUTO(0), ON(1), OFF(2); - - private final int id; - - Flash(int id) { - this.id = id; - } - - static Flash fromId(int id) { - for (Flash f : values()) { - if (f.id == id) return f; - } - throw new IllegalArgumentException(); - } - } - - /** - * Adjusts which camera to use. - */ - public enum LensFacing { - BACK(0), FRONT(1); - - private final int id; - - LensFacing(int id) { - this.id = id; - } - - static LensFacing fromId(int id) { - for (LensFacing lf : values()) { - if (lf.id == id) return lf; - } - throw new IllegalArgumentException(); - } - } - - /** - * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a - * {@link TextureView}. - */ - private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() { - @Override - public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) { - if (DEBUG) Log.v(TAG, "Surface Texture now available."); - synchronized (CameraView.this) { - if (getStatus() == Status.AWAITING_TEXTURE) { - setStatus(Status.OPEN); - } - } - } - - @Override - public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {} - - @Override - public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) { - synchronized (CameraView.this) { - if (getStatus() == Status.OPEN) { - Log.w(TAG, "Surface destroyed but was not closed."); - close(); - } - } - return true; - } - - @Override - public void onSurfaceTextureUpdated(SurfaceTexture texture) {} - }; - - private Status mStatus = Status.CLOSED; - private OnImageCapturedListener mOnImageCapturedListener; - private OnVideoCapturedListener mOnVideoCapturedListener; - - // For overriding onTouch - private final int mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); - private final int mLongPressTimeout = ViewConfiguration.getLongPressTimeout(); - private final Handler mHandler = new Handler(); - private float mInitialMotionEventX; - private float mInitialMotionEventY; - private boolean mIsLongPressMotionEvent; - - // For tap-to-focus - private final Rect mFocusingRect = new Rect(); - private final Rect mMeteringRect = new Rect(); - - // For pinch-to-zoom - private PinchToZoomGestureDetector mScaleDetector; - private boolean mIsPinchToZoomEnabled = true; - - private ICameraModule mCameraModule; - - @Nullable - private OnCameraStateChangedListener mOnCameraStateChangedListener; - - private TextureView mCameraView; - private ImageView mImagePreview; - private VideoView mVideoPreview; - - private File mImagePendingConfirmation; - private File mVideoPendingConfirmation; - - private boolean mIsImageConfirmationEnabled; - private boolean mIsVideoConfirmationEnabled; - - @Nullable - private BarcodeScanner mBarcodeScanner; - - // When true, avoid adding/removing views. While usually harmless (although it can cause state - // loss), it's especially important since calling removeView(TextureView) after - // onSaveInstanceState() will trigger a NPE on Android N. - private boolean mHasSavedState = false; - - public CameraView(Context context) { - this(context, null); - } - - public CameraView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public CameraView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(context, attrs); - } - - @TargetApi(21) - public CameraView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - init(context, attrs); - } - - private void init(Context context, @Nullable AttributeSet attrs) { - if (USE_CAMERA_X && Build.VERSION.SDK_INT >= 21) { - mCameraModule = new CameraXModule(this); - } else if (USE_CAMERA_V2 && Build.VERSION.SDK_INT >= 21) { - mCameraModule = new Camera2Module(this); - } else { - mCameraModule = new LegacyCameraModule(this); - } - - if (attrs != null) { - TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CameraView); - setQuality(Quality.fromId(a.getInteger(R.styleable.CameraView_quality, getQuality().id))); - setFlash(Flash.fromId(a.getInteger(R.styleable.CameraView_flash, getFlash().id))); - setLensFacing(LensFacing.fromId(a.getInteger(R.styleable.CameraView_lensFacing, getLensFacing().id))); - setPinchToZoomEnabled(a.getBoolean(R.styleable.CameraView_pinchToZoomEnabled, isPinchToZoomEnabled())); - if (a.hasValue(R.styleable.CameraView_maxVideoDuration)) { - setMaxVideoDuration(a.getInteger(R.styleable.CameraView_maxVideoDuration, INDEFINITE_VIDEO_DURATION)); - } - if (a.hasValue(R.styleable.CameraView_maxVideoSize)) { - setMaxVideoSize(a.getInteger(R.styleable.CameraView_maxVideoSize, INDEFINITE_VIDEO_SIZE)); - } - setImageConfirmationEnabled(a.getBoolean(R.styleable.CameraView_confirmImages, isImageConfirmationEnabled())); - setVideoConfirmationEnabled(a.getBoolean(R.styleable.CameraView_confirmVideos, isVideoConfirmationEnabled())); - setMatchPreviewAspectRatio(a.getBoolean(R.styleable.CameraView_matchPreviewAspectRatio, isMatchPreviewAspectRatioEnabled())); - a.recycle(); - } - - if (getBackground() == null) { - setBackgroundColor(0xFF111111); - } - - mScaleDetector = new PinchToZoomGestureDetector(context); - } - - @Override - public void onFinishInflate() { - super.onFinishInflate(); - addView(mCameraView = new TextureView(getContext())); - addView(mImagePreview = new ImageView(getContext())); - addView(mVideoPreview = new VideoView(getContext())); - mImagePreview.setScaleType(ImageView.ScaleType.CENTER_CROP); - mImagePreview.setVisibility(View.GONE); - mVideoPreview.setVisibility(View.GONE); - - mCameraView.setSurfaceTextureListener(mSurfaceTextureListener); - } - - @Override - protected LayoutParams generateDefaultLayoutParams() { - return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); - } - - @Override - protected Parcelable onSaveInstanceState() { - Bundle state = new Bundle(); - state.putParcelable(EXTRA_SUPER, super.onSaveInstanceState()); - state.putParcelable(EXTRA_MODULE, mCameraModule.onSaveInstanceState()); - state.putInt(EXTRA_QUALITY, getQuality().id); - state.putInt(EXTRA_ZOOM_LEVEL, getZoomLevel()); - state.putBoolean(EXTRA_PINCH_TO_ZOOM_ENABLED, isPinchToZoomEnabled()); - state.putFloat(EXTRA_PINCH_TO_ZOOM_SCALE_FACTOR, mScaleDetector.getCumulativeScaleFactor()); - state.putInt(EXTRA_FLASH, getFlash().id); - state.putInt(EXTRA_LENS_FACING, getLensFacing().id); - state.putLong(EXTRA_MAX_VIDEO_DURATION, getMaxVideoDuration()); - state.putLong(EXTRA_MAX_VIDEO_SIZE, getMaxVideoSize()); - state.putBoolean(EXTRA_CONFIRM_IMAGE, isImageConfirmationEnabled()); - state.putBoolean(EXTRA_CONFIRM_VIDEO, isVideoConfirmationEnabled()); - state.putBoolean(EXTRA_MATCH_PREVIEW_ASPECT_RATIO, isMatchPreviewAspectRatioEnabled()); - if (mImagePendingConfirmation != null) { - state.putString(EXTRA_PENDING_IMAGE_FILE_PATH, mImagePendingConfirmation.getAbsolutePath()); - } - if (mVideoPendingConfirmation != null) { - state.putString(EXTRA_PENDING_VIDEO_FILE_PATH, mVideoPendingConfirmation.getAbsolutePath()); - } - mHasSavedState = true; - return state; - } - - @Override - protected void onRestoreInstanceState(Parcelable savedState) { - if (savedState instanceof Bundle) { - Bundle state = (Bundle) savedState; - super.onRestoreInstanceState(state.getParcelable(EXTRA_SUPER)); - mCameraModule.onRestoreInstanceState(state.getParcelable(EXTRA_MODULE)); - setQuality(Quality.fromId(state.getInt(EXTRA_QUALITY))); - setZoomLevel(state.getInt(EXTRA_ZOOM_LEVEL)); - setPinchToZoomEnabled(state.getBoolean(EXTRA_PINCH_TO_ZOOM_ENABLED)); - mScaleDetector.setCumulativeScaleFactor(state.getFloat(EXTRA_PINCH_TO_ZOOM_SCALE_FACTOR, mScaleDetector.getCumulativeScaleFactor())); - setFlash(Flash.fromId(state.getInt(EXTRA_FLASH))); - setLensFacing(LensFacing.fromId(state.getInt(EXTRA_LENS_FACING))); - setMaxVideoDuration(state.getLong(EXTRA_MAX_VIDEO_DURATION)); - setMaxVideoSize(state.getLong(EXTRA_MAX_VIDEO_SIZE)); - setImageConfirmationEnabled(state.getBoolean(EXTRA_CONFIRM_IMAGE)); - setVideoConfirmationEnabled(state.getBoolean(EXTRA_CONFIRM_VIDEO)); - setMatchPreviewAspectRatio(state.getBoolean(EXTRA_MATCH_PREVIEW_ASPECT_RATIO)); - - if (state.containsKey(EXTRA_PENDING_IMAGE_FILE_PATH)) { - File file = new File(state.getString(EXTRA_PENDING_IMAGE_FILE_PATH)); - if (file.exists()) { - showImageConfirmation(file); - } - } - if (state.containsKey(EXTRA_PENDING_VIDEO_FILE_PATH)) { - File file = new File(state.getString(EXTRA_PENDING_VIDEO_FILE_PATH)); - if (file.exists()) { - showVideoConfirmation(file); - } - } - } else { - super.onRestoreInstanceState(savedState); - } - mHasSavedState = false; - } - - protected synchronized Status getStatus() { - return mStatus; - } - - private synchronized void setStatus(Status status) { - if (mStatus == status) { - return; - } - - if (DEBUG) { - Log.v(TAG, "Camera state set to " + status.name()); - } - mStatus = status; - - switch (mStatus) { - case OPEN: - onOpen(); - break; - case CLOSED: - onClose(); - break; - } - } - - /* - * Opens the camera and starts displaying a preview. You are in charge of checking if the - * phone has PackageManager.FEATURE_CAMERA_ANY and, if you are targeting Android M+, that - * the phone has the following permissions: - * Manifest.permission.CAMERA - * Manifest.permission.RECORD_AUDIO - * Manifest.permission.WRITE_EXTERNAL_STORAGE - */ - @RequiresPermission(allOf = { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO, - Manifest.permission.WRITE_EXTERNAL_STORAGE - }) - public synchronized void open() { - if (mCameraView.isAvailable()) { - setStatus(Status.OPEN); - } else { - setStatus(Status.AWAITING_TEXTURE); - } - } - - /* - * Closes the camera. - */ - public synchronized void close() { - setStatus(Status.CLOSED); - } - - /** - * @return True if camera is currently open - */ - public synchronized boolean isOpen() { - return getStatus() == Status.OPEN; - } - - /** - * @return One of 0, 90, 180, 270. - */ - protected int getDisplayRotation() { - Display display; - if (Build.VERSION.SDK_INT >= 17) { - display = getDisplay(); - } else { - display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - } - - // Null when the View is detached. If we were in the middle of a background operation, - // better to not NPE. When the background operation finishes, it'll realize that the camera - // was closed. - if (display == null) { - return 0; - } - - int displayRotation = display.getRotation(); - switch (displayRotation) { - case Surface.ROTATION_0: - displayRotation = 0; - break; - case Surface.ROTATION_90: - displayRotation = 90; - break; - case Surface.ROTATION_180: - displayRotation = 180; - break; - case Surface.ROTATION_270: - displayRotation = 270; - break; - } - return displayRotation; - } - - public TextureView asTextureView() { - return mCameraView; - } - - @UiThread - public SurfaceTexture getSurfaceTexture() { - return mCameraView.getSurfaceTexture(); - } - - @UiThread - protected Matrix getTransform(Matrix matrix) { - return mCameraView.getTransform(matrix); - } - - @UiThread - protected void setTransform(final Matrix matrix) { - mCameraView.setTransform(matrix); - } - - /** - * When enabled, requires images to be confirmed before - * {@link OnImageCapturedListener#onImageCaptured(File)} is triggered. A preview of the image - * will be displayed in CameraView's preview. - */ - public void setImageConfirmationEnabled(boolean enabled) { - mIsImageConfirmationEnabled = enabled; - } - - /** - * When true, {@link #takePicture(File)} will trigger the - * {@link OnImageCapturedListener#onImageConfirmation()} callback. To continue, call - * {@link #confirmPicture()}. - */ - public boolean isImageConfirmationEnabled() { - return mIsImageConfirmationEnabled; - } - - /** - * When enabled, requires videos to be confirmed before - * {@link OnVideoCapturedListener#onVideoCaptured(File)} is triggered. A preview of the video - * will be displayed in CameraView's preview. - */ - public void setVideoConfirmationEnabled(boolean enabled) { - mIsVideoConfirmationEnabled = enabled; - } - - /** - * When true, {@link #startRecording(File)} will trigger the - * {@link OnVideoCapturedListener#onVideoConfirmation()} callback. To continue, call - * {@link #confirmVideo()}. - */ - public boolean isVideoConfirmationEnabled() { - return mIsVideoConfirmationEnabled; - } - - void showImageConfirmation(File file) { - Log.d(TAG, "Saved the picture to " + file); - if (isImageConfirmationEnabled()) { - mCameraModule.pause(); - mImagePreview.setVisibility(View.VISIBLE); - Image.with(getContext()).load(file).into(mImagePreview); - mImagePendingConfirmation = file; - - if (getOnImageCapturedListener() != null) { - getOnImageCapturedListener().onImageConfirmation(); - } - } else { - if (getOnImageCapturedListener() != null) { - getOnImageCapturedListener().onImageCaptured(file); - } - } - } - - void onImageFailed() { - Log.d(TAG, "Failed to take a picture"); - if (isImageConfirmationEnabled()) { - mCameraModule.resume(); - } - - if (getOnImageCapturedListener() != null) { - getOnImageCapturedListener().onFailure(); - } - } - - void showVideoConfirmation(File file) { - Log.d(TAG, "Saved the video to " + file); - if (isVideoConfirmationEnabled()) { - mCameraModule.pause(); - - mVideoPreview.setVisibility(View.VISIBLE); - mVideoPreview.setShouldMirror(isUsingFrontFacingCamera()); - mVideoPreview.setShouldLoop(true); - mVideoPreview.setVolume(0.3f); - mVideoPreview.setFile(file); - if (!mVideoPreview.play()) { - Log.w(TAG, "Failed to play video preview"); - } - - mVideoPendingConfirmation = file; - - if (getOnVideoCapturedListener() != null) { - getOnVideoCapturedListener().onVideoConfirmation(); - } - } else { - if (getOnVideoCapturedListener() != null) { - getOnVideoCapturedListener().onVideoCaptured(file); - } - } - } - - void onVideoFailed() { - Log.d(TAG, "Failed to record a video"); - if (isVideoConfirmationEnabled()) { - mCameraModule.resume(); - } - - if (getOnVideoCapturedListener() != null) { - getOnVideoCapturedListener().onFailure(); - } - } - - /** - * Attempts to match image and video outputs to the preview aspect ratio. - */ - @TargetApi(21) - public void setMatchPreviewAspectRatio(boolean enabled) { - mCameraModule.setMatchPreviewAspectRatio(enabled); - } - - /** - * When enabled, image and video outputs will attempt to match the same aspect ratio used in - * the preview. It's advised that this is enabled when using - * {@link #setImageConfirmationEnabled(boolean)} and - * {@link #setVideoConfirmationEnabled(boolean)} as it provides the least amount of jank when - * showing the preview. Having this enabled also ensures that what the user sees is what the - * picture/video output. - */ - public boolean isMatchPreviewAspectRatioEnabled() { - return mCameraModule.isMatchPreviewAspectRatioEnabled(); - } - - /** - * Sets the quality for image and video outputs. - */ - public void setQuality(Quality quality) { - mCameraModule.setQuality(quality); - } - - /** - * Gets the current quality for image and video outputs. - */ - public Quality getQuality() { - return mCameraModule.getQuality(); - } - - /** - * Sets the maximum video duration before {@link OnVideoCapturedListener#onVideoCaptured(File)} - * is called automatically. Use {@link #INDEFINITE_VIDEO_DURATION} to disable the timeout. - */ - public void setMaxVideoDuration(long duration) { - mCameraModule.setMaxVideoDuration(duration); - } - - /** - * Returns the maximum duration of videos, or {@link #INDEFINITE_VIDEO_DURATION} if there is - * no timeout. - */ - public long getMaxVideoDuration() { - return mCameraModule.getMaxVideoDuration(); - } - - /** - * Sets the maximum video size in bytes before - * {@link OnVideoCapturedListener#onVideoCaptured(File)} is called automatically. Use - * {@link #INDEFINITE_VIDEO_SIZE} to disable the size restriction. - */ - public void setMaxVideoSize(long size) { - mCameraModule.setMaxVideoSize(size); - } - - /** - * Returns the maximum size of videos in bytes, or {@link #INDEFINITE_VIDEO_SIZE} if there is - * no timeout. - */ - public long getMaxVideoSize() { - return mCameraModule.getMaxVideoSize(); - } - - protected void onOpen() { - mCameraModule.open(); - - if (mOnCameraStateChangedListener != null) { - mOnCameraStateChangedListener.onCameraOpened(); - } - } - - protected void onClose() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - exitBarcodeScanner(); - } - mCameraModule.close(); - - if (!mHasSavedState) { - // Destroy the TextureView we used for the previous round of camera activity. This is - // because the TextureView will continue to show a bitmap of the old view until the camera - // is able to draw to it again. We'd rather clear the TextureView, but since there's no such - // way, we destroy it instead. - removeView(mCameraView); - addView(mCameraView = new TextureView(getContext()), 0 /* view position */); - mCameraView.setSurfaceTextureListener(mSurfaceTextureListener); - } - - if (mOnCameraStateChangedListener != null) { - mOnCameraStateChangedListener.onCameraClosed(); - } - } - - /** - * Takes a picture and calls {@link OnImageCapturedListener#onImageCaptured(File)} when done. - * @param file The destination. - */ - public void takePicture(File file) { - Log.v(TAG, "Taking a picture"); - if (isImageConfirmationEnabled()) { - mCameraModule.pause(); - } - - mCameraModule.takePicture(file); - } - - /** - * Confirms a picture that is currently being displayed on the preview. - */ - public void confirmPicture() { - if (isImageConfirmationEnabled()) { - mCameraModule.resume(); - } - - if (mImagePendingConfirmation == null) { - throw new IllegalStateException("confirmPicture() called, but no picture was awaiting confirmation"); - } - Image.clear(mImagePreview); - mImagePreview.setVisibility(View.GONE); - getOnImageCapturedListener().onImageCaptured(mImagePendingConfirmation); - mImagePendingConfirmation = null; - } - - /** - * Rejects a picture that is currently being displayed on the preview. - */ - public void rejectPicture() { - if (isImageConfirmationEnabled()) { - mCameraModule.resume(); - } - - if (mImagePendingConfirmation == null) { - throw new IllegalStateException("rejectPicture() called, but no picture was awaiting confirmation"); - } - Image.clear(mImagePreview); - mImagePreview.setVisibility(View.GONE); - if (!mImagePendingConfirmation.delete()) { - Log.w(TAG, "Attempted to clean up pending image file, but failed"); - } - mImagePendingConfirmation = null; - } - - /** - * Takes a video and calls {@link OnVideoCapturedListener#onVideoCaptured(File)} when done. - * @param file The destination. - */ - public void startRecording(File file) { - Log.v(TAG, "Recording a video"); - mCameraModule.startRecording(file); - } - - /** - * Stops an in progress video. - */ - public void stopRecording() { - Log.v(TAG, "Stopped recording a video"); - if (isVideoConfirmationEnabled()) { - mCameraModule.pause(); - } - - mCameraModule.stopRecording(); - } - - /** - * @return True if currently recording. - */ - public boolean isRecording() { - return mCameraModule.isRecording(); - } - - /** - * Confirms a video that is currently being displayed on the preview. - */ - public void confirmVideo() { - if (isVideoConfirmationEnabled()) { - mCameraModule.resume(); - } - - if (mVideoPendingConfirmation == null) { - throw new IllegalStateException("confirmVideo() called, but no video was awaiting confirmation"); - } - mVideoPreview.pause(); - mVideoPreview.setVisibility(View.GONE); - getOnVideoCapturedListener().onVideoCaptured(mVideoPendingConfirmation); - mVideoPendingConfirmation = null; - } - - /** - * Rejects a video that is currently being displayed on the preview. - */ - public void rejectVideo() { - if (isVideoConfirmationEnabled()) { - mCameraModule.resume(); - } - - if (mVideoPendingConfirmation == null) { - throw new IllegalStateException("rejectVideo() called, but no video was awaiting confirmation"); - } - mVideoPreview.pause(); - mVideoPreview.setVisibility(View.GONE); - if (!mVideoPendingConfirmation.delete()) { - Log.w(TAG, "Attempted to clean up pending video file, but failed"); - } - mVideoPendingConfirmation = null; - } - - /** - * Starts a video stream. The stream will continue until {@link VideoStream#close} is called. - * - * @return A stream that can be shared to a remote device. - */ - @RequiresPermission(allOf = { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO - }) - @RequiresApi(18) - public VideoStream stream() { - return stream(new VideoStream.Params.Builder().build()); - } - - /** - * Starts a video stream. The stream will continue until {@link VideoStream#close} is called. - * - * @return A stream that can be shared to a remote device. - */ - @RequiresPermission(allOf = { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO - }) - @RequiresApi(18) - public VideoStream stream(VideoStream.Params params) { - if (params.isVideoEnabled() && !isOpen()) { - throw new IllegalStateException("Camera must be open before starting a video stream"); - } - - return new VideoStream.Builder().attach(mCameraModule).setParams(params).build(); - } - - public interface BarcodeDetectorListener { - void onBarcodeFound(List barcodes); - } - - @RequiresApi(19) - @RequiresPermission(Manifest.permission.CAMERA) - public void enterBarcodeScanner(BarcodeDetectorListener listener, @Barcode.Format int format, @Barcode.Format int... formats) { - if (!isOpen()) { - throw new IllegalStateException("Camera must be open before scanning for barcodes"); - } - - if (mBarcodeScanner != null) { - throw new IllegalStateException("Barcode scanner cannot be started twice"); - } - - mBarcodeScanner = new BarcodeScanner(mCameraModule.getCanvas(), listener, format, formats); - mBarcodeScanner.start(); - } - - @RequiresApi(19) - public void exitBarcodeScanner() { - if (mBarcodeScanner != null) { - mBarcodeScanner.stop(); - mBarcodeScanner = null; - } - } - - /** - * @return True if the device supports a front facing camera. - */ - public boolean hasFrontFacingCamera() { - return mCameraModule.hasFrontFacingCamera(); - } - - /** - * @return True if CameraView is currently using a front facing camera. - */ - public boolean isUsingFrontFacingCamera() { - return mCameraModule.isUsingFrontFacingCamera(); - } - - /** - * Toggles the active camera to the next available camera. Typically, this toggles between - * the front and back facing cameras. - */ - public void toggleCamera() { - mCameraModule.toggleCamera(); - } - - /** - * Sets which camera (front or back) to use. - */ - public void setLensFacing(LensFacing lensFacing) { - if (getLensFacing().equals(lensFacing)) { - return; - } - - mCameraModule.setLensFacing(lensFacing); - } - - /** - * Returns which camera (front or back) is being used. - */ - public LensFacing getLensFacing() { - return mCameraModule.isUsingFrontFacingCamera() ? LensFacing.FRONT : LensFacing.BACK; - } - - /** - * Focuses the camera on the given area. Limited from -1000 to 1000. - */ - public void focus(Rect focus, Rect metering) { - mCameraModule.focus(focus, metering); - } - - /** - * Sets the active flash strategy. - */ - public void setFlash(Flash flashMode) { - mCameraModule.setFlash(flashMode); - } - - /** - * Gets the active flash strategy. - */ - public Flash getFlash() { - return mCameraModule.getFlash(); - } - - /** - * @return True if the camera supports flash. - */ - public boolean hasFlash() { - return mCameraModule.hasFlash(); - } - - protected int getRelativeCameraOrientation() { - return mCameraModule.getRelativeCameraOrientation(); - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - super.onLayout(changed, left, top, right, bottom); - if (changed) { - mCameraModule.onLayoutChanged(); - } - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - // Disable pinch-to-zoom while a preview is visible. - if (mImagePendingConfirmation != null - || mVideoPendingConfirmation != null - || mCameraModule.isPaused()) { - return super.onTouchEvent(event); - } - - mScaleDetector.onTouchEvent(event); - if (event.getPointerCount() == 2 && isPinchToZoomEnabled() && isZoomSupported()) { - return true; - } - - // Camera focus - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - mInitialMotionEventX = event.getX(); - mInitialMotionEventY = event.getY(); - mIsLongPressMotionEvent = false; - mHandler.postDelayed(() -> { - if (Build.VERSION.SDK_INT >= 24) { - performLongClick(mInitialMotionEventX, mInitialMotionEventY); - } else { - performLongClick(); - } - mIsLongPressMotionEvent = true; - }, mLongPressTimeout); - break; - case MotionEvent.ACTION_CANCEL: - mHandler.removeCallbacksAndMessages(null); - break; - case MotionEvent.ACTION_UP: - float distanceX = event.getX() - mInitialMotionEventX; - float distanceY = event.getY() - mInitialMotionEventY; - float distanceMoved = (float) Math.sqrt(distanceX * distanceX + distanceY * distanceY); - if (distanceMoved > mTouchSlop && !mIsLongPressMotionEvent) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 - && hasOnClickListeners()) { - performClick(); - } else { - calculateTapArea(mFocusingRect, event.getX(), event.getY(), 1f); - calculateTapArea(mMeteringRect, event.getX(), event.getY(), 1.5f); - if (area(mFocusingRect) != 0 && area(mMeteringRect) != 0) { - focus(mFocusingRect, mMeteringRect); - } - } - mHandler.removeCallbacksAndMessages(null); - } - break; - } - return true; - } - - /** - * Returns the width * height of the given rect - */ - private int area(Rect rect) { - return rect.width() * rect.height(); - } - - /** - * The area must be between -1000,-1000 and 1000,1000 - */ - private void calculateTapArea(Rect rect, float x, float y, float coefficient) { - int max = 1000; - int min = -1000; - - // Default to 300 (1/6th the total area) and scale by the coefficient - int areaSize = Float.valueOf(300 * coefficient).intValue(); - - // Rotate the coordinates if the camera orientation is different - int width = getWidth(); - int height = getHeight(); - - int relativeCameraOrientation = getRelativeCameraOrientation(); - int temp = -1; - float tempf = -1f; - switch (relativeCameraOrientation) { - case 90: - // Fall-through - case 270: - // We're horizontal. Swap width/height. Swap x/y. - temp = width; - width = height; - height = temp; - - tempf = x; - x = y; - y = tempf; - break; - } - switch (relativeCameraOrientation) { - case 180: - // Fall-through - case 270: - // We're upside down. Fix x/y. - x = width - x; - y = height - y; - break; - } - - // Grab the x, y position from within the View and normalize it to -1000 to 1000 - x = min + distance(max, min) * (x / width); - y = min + distance(max, min) * (y / height); - - - // Modify the rect to the bounding area - rect.top = (int) y - areaSize / 2; - rect.left = (int) x - areaSize / 2; - rect.bottom = rect.top + areaSize; - rect.right = rect.left + areaSize; - - // Cap at -1000 to 1000 - rect.top = rangeLimit(rect.top, max, min); - rect.left = rangeLimit(rect.left, max, min); - rect.bottom = rangeLimit(rect.bottom, max, min); - rect.right = rangeLimit(rect.right, max, min); - } - - private int rangeLimit(int val, int max, int min) { - return Math.min(Math.max(val, min), max); - } - - private int distance(int a, int b) { - return Math.abs(a - b); - } - - /** - * When enabled, the user can pinch the camera to zoom in/out. - */ - public void setPinchToZoomEnabled(boolean enabled) { - mIsPinchToZoomEnabled = enabled; - } - - /** - * @return True if pinch to zoom is enabled. - */ - public boolean isPinchToZoomEnabled() { - return mIsPinchToZoomEnabled; - } - - /** - * Sets the current zoom level, from 0 to {@link #getMaxZoomLevel()}. - */ - public void setZoomLevel(int zoomLevel) { - mCameraModule.setZoomLevel(zoomLevel); - } - - /** - * @return The current zoom level. - */ - public int getZoomLevel() { - return mCameraModule.getZoomLevel(); - } - - /** - * @return The maximum zoom level. - */ - public int getMaxZoomLevel() { - return mCameraModule.getMaxZoomLevel(); - } - - /** - * @return True if the camera supports zooming. - */ - public boolean isZoomSupported() { - return mCameraModule.isZoomSupported(); - } - - /** - * Enables listening for image-related callbacks. - */ - public void setOnImageCapturedListener(OnImageCapturedListener l) { - mOnImageCapturedListener = l; - mCameraModule.setOnImageCapturedListener(l); - } - - protected OnImageCapturedListener getOnImageCapturedListener() { - return mOnImageCapturedListener; - } - - /** - * Enables listening for video-related callbacks. - */ - public void setOnVideoCapturedListener(OnVideoCapturedListener l) { - mOnVideoCapturedListener = l; - mCameraModule.setOnVideoCapturedListener(l); - } - - protected OnVideoCapturedListener getOnVideoCapturedListener() { - return mOnVideoCapturedListener; - } - - /** - * Enables listening for callbacks about the camera being opened or closed. - */ - public void setOnCameraStateChangedListener(OnCameraStateChangedListener l) { - mOnCameraStateChangedListener = l; - } - - protected OnCameraStateChangedListener getOnCameraStateChangedListener() { - return mOnCameraStateChangedListener; - } - - public interface OnImageCapturedListener { - void onImageConfirmation(); - void onImageCaptured(File file); - void onFailure(); - } - - public interface OnVideoCapturedListener { - void onVideoConfirmation(); - void onVideoCaptured(File file); - void onFailure(); - } - - public interface OnCameraStateChangedListener { - void onCameraOpened(); - void onCameraClosed(); - } - - private class PinchToZoomGestureDetector extends ScaleGestureDetector implements ScaleGestureDetector.OnScaleGestureListener { - final float MAX_SCALE = 5f; - float mScaleFactor = 1f; - - PinchToZoomGestureDetector(Context context) { - this(context, new S()); - } - - PinchToZoomGestureDetector(Context context, S s) { - super(context, s); - s.setRealGestureDetector(this); - } - - float getCumulativeScaleFactor() { - return mScaleFactor; - } - - void setCumulativeScaleFactor(float scaleFactor) { - mScaleFactor = scaleFactor; - } - - @Override - public boolean onScale(ScaleGestureDetector detector) { - mScaleFactor *= detector.getScaleFactor(); - - // Don't let the object get too small or too large. - mScaleFactor = Math.max(1f, Math.min(mScaleFactor, MAX_SCALE)); - - // y = (x-1) * (maxZoom/maxScale) - setZoomLevel(rangeLimit((int) ((mScaleFactor-1) * getMaxZoomLevel() / MAX_SCALE), getMaxZoomLevel(), 0)); - return true; - } - - @Override - public boolean onScaleBegin(ScaleGestureDetector detector) { - return false; - } - - @Override - public void onScaleEnd(ScaleGestureDetector detector) {} - } - - private static class S extends ScaleGestureDetector.SimpleOnScaleGestureListener { - private ScaleGestureDetector.OnScaleGestureListener listener; - - void setRealGestureDetector(ScaleGestureDetector.OnScaleGestureListener l) { - listener = l; - } - - @Override - public boolean onScale(ScaleGestureDetector detector) { - return listener.onScale(detector); - } - } -} +package com.xlythe.view.camera; + +import android.Manifest; +import android.annotation.TargetApi; +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Matrix; +import android.graphics.Rect; +import android.graphics.SurfaceTexture; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Parcelable; +import android.util.AttributeSet; +import android.util.Log; +import android.view.Display; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.Surface; +import android.view.TextureView; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.FrameLayout; +import android.widget.ImageView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; +import androidx.annotation.RequiresPermission; +import androidx.annotation.UiThread; + +import com.xlythe.view.camera.legacy.LegacyCameraModule; +import com.xlythe.view.camera.v2.Camera2Module; + +import java.io.File; +import java.util.List; + +/** + * A {@link View} that displays a preview of the camera with methods {@link #takePicture(File)}, + * {@link #startRecording(File)} and {@link #stopRecording()}. + * + * Because the Camera is a limited resource and consumes a high amount of power, CameraView must be + * opened/closed. It's recommended to call {@link #open()} in + * {@link android.app.Activity#onStart()} and {@link #close()} in + * {@link android.app.Activity#onStop()}. + */ +public class CameraView extends FrameLayout { + static final String TAG = CameraView.class.getSimpleName(); + static final boolean DEBUG = false; + + /** + * Which implementation of the camera a {@link CameraView} drives. + * + *

Camera2 is the default because it is what this library has been shipping and validating + * on devices. CameraX owns more behaviour - it carries a database of per-device quirks, and it + * is the only backend that can reach a manufacturer's own Extensions - but it is opt-in until + * it has had the same validation here.

+ * + * @see #setDefaultBackend + */ + public enum Backend { + /** The newest implementation the device supports. */ + AUTO(0), + /** {@code android.hardware.camera2}, the default. */ + CAMERA2(1), + /** + * {@code androidx.camera}. + * + *

Needs the androidx.camera dependencies on the classpath. An app that excluded them + * falls back to {@link #CAMERA2}.

+ */ + CAMERA_X(2), + /** {@code android.hardware.Camera}, for devices that predate camera2. */ + LEGACY(3); + + final int id; + + Backend(int id) { + this.id = id; + } + + static Backend fromId(int id) { + for (Backend backend : values()) { + if (backend.id == id) { + return backend; + } + } + return AUTO; + } + } + + /** The backend a CameraView uses when its layout does not name one. */ + private static volatile Backend sDefaultBackend = Backend.AUTO; + + /** + * Chooses the backend for every CameraView created from now on. + * + *

Set this before the view is inflated - in {@code Application.onCreate}, say - because a + * view picks its backend once, when it is created. A single view can be told directly with + * {@code app:backend} in its layout.

+ */ + public static void setDefaultBackend(@NonNull Backend backend) { + sDefaultBackend = backend; + } + + @NonNull + public static Backend getDefaultBackend() { + return sDefaultBackend; + } + + // When enabled, CameraV2 will be used. It's currently stable. + static final boolean USE_CAMERA_V2 = true; + + public static final int INDEFINITE_VIDEO_DURATION = -1; + public static final int INDEFINITE_VIDEO_SIZE = -1; + + public static final String ACTION_CAMERA_STATE_CHANGED = "com.xlythe.view.camera.CAMERA_STATE_CHANGED"; + + private static final String EXTRA_SUPER = "super"; + private static final String EXTRA_MODULE = "module"; + private static final String EXTRA_QUALITY = "quality"; + private static final String EXTRA_ZOOM_LEVEL = "zoom_level"; + private static final String EXTRA_PINCH_TO_ZOOM_ENABLED = "pinch_to_zoom_enabled"; + private static final String EXTRA_PINCH_TO_ZOOM_SCALE_FACTOR = "pinch_to_zoom_scale_factor"; + private static final String EXTRA_FLASH = "flash"; + private static final String EXTRA_LENS_FACING = "lens_facing"; + private static final String EXTRA_MAX_VIDEO_DURATION = "max_video_duration"; + private static final String EXTRA_MAX_VIDEO_SIZE = "max_video_size"; + private static final String EXTRA_CONFIRM_IMAGE = "confirm_image"; + private static final String EXTRA_CONFIRM_VIDEO = "confirm_video"; + private static final String EXTRA_PENDING_IMAGE_FILE_PATH = "pending_image_file_path"; + private static final String EXTRA_PENDING_VIDEO_FILE_PATH = "pending_video_file_path"; + private static final String EXTRA_MATCH_PREVIEW_ASPECT_RATIO = "match_preview_aspect_ratio"; + /** Saved-state key for dynamic range. */ + private static final String EXTRA_DYNAMIC_RANGE = "dynamic_range"; + /** Saved-state key for the CameraX photo extension. */ + private static final String EXTRA_EXTENSION = "extension"; + /** Saved-state key for front-video mirroring. */ + private static final String EXTRA_FRONT_VIDEO_MIRRORING = "front_video_mirroring"; + /** Saved-state key for preview stabilization. */ + private static final String EXTRA_PREVIEW_STABILIZATION = "preview_stabilization"; + /** Saved-state key for video stabilization. */ + private static final String EXTRA_VIDEO_STABILIZATION = "video_stabilization"; + /** Saved-state key for exposure compensation. */ + private static final String EXTRA_EXPOSURE_COMPENSATION = "exposure_compensation"; + /** Saved-state key for torch state. */ + private static final String EXTRA_TORCH = "torch"; + /** Saved-state key for low-light boost state. */ + private static final String EXTRA_LOW_LIGHT_BOOST = "low_light_boost"; + + /** + * The lifecycle state of the camera and its preview surface. + * + *

Status changes are serialized on the main thread.

+ */ + private enum Status { + CLOSED, + WAITING_FOR_SURFACE, + OPENING, + OPEN, + CLOSING, + ERROR + } + + /** + * Determines the resolution of CameraView's outputs. All resolutions are best attempts, and + * will fall to lower qualities if the Android device cannot support them. Resolutions also may + * change in the future (if, say, Android adds 8k resolution). + * + * (*) {@link Quality#MAX} will output at 4k. + * (*) {@link Quality#HIGH} will output at 1080p. + * (*) {@link Quality#MEDIUM} will output at 720. + * (*) {@link Quality#LOW} will output at 480. + */ + public enum Quality { + MAX(0), HIGH(1), MEDIUM(2), LOW(3); + + private final int id; + + Quality(int id) { + this.id = id; + } + + static Quality fromId(int id) { + for (Quality q : values()) { + if (q.id == id) return q; + } + throw new IllegalArgumentException(); + } + } + + /** + * Determines the use of the camera's flash when taking pictures. + */ + public enum Flash { + AUTO(0), ON(1), OFF(2); + + private final int id; + + Flash(int id) { + this.id = id; + } + + static Flash fromId(int id) { + for (Flash f : values()) { + if (f.id == id) return f; + } + throw new IllegalArgumentException(); + } + } + + /** + * Adjusts which camera to use. + */ + public enum LensFacing { + BACK(0), FRONT(1); + + private final int id; + + LensFacing(int id) { + this.id = id; + } + + static LensFacing fromId(int id) { + for (LensFacing lf : values()) { + if (lf.id == id) return lf; + } + throw new IllegalArgumentException(); + } + } + + /** Selects an optional CameraX vendor photo-processing extension. */ + public enum Extension { + NONE(0), BOKEH(1), HDR(2), NIGHT(3), FACE_RETOUCH(4), AUTO(5); + + /** Stable XML and saved-state identifier. */ + private final int id; + + Extension(int id) { + this.id = id; + } + + static Extension fromId(int id) { + for (Extension extension : values()) { + if (extension.id == id) return extension; + } + throw new IllegalArgumentException(); + } + } + /** Selects standard or high dynamic range video when supported by the active backend. */ + public enum DynamicRange { + SDR(0), HDR(1); + + /** Stable XML and saved-state identifier. */ + private final int id; + + DynamicRange(int id) { + this.id = id; + } + + static DynamicRange fromId(int id) { + for (DynamicRange dynamicRange : values()) { + if (dynamicRange.id == id) return dynamicRange; + } + throw new IllegalArgumentException(); + } + } + + /** + * The range of colours a picture is recorded in. + * + *

sRGB is what every camera has always produced and what every viewer understands. A + * modern sensor can see more than sRGB can describe, and a modern screen can show more, which + * is why a manufacturer's own camera app saves wide-gamut stills - the difference is visible + * in saturated reds and greens, where sRGB clips.

+ * + *

Wide gamut is not free: a viewer that ignores the colour profile shows the picture + * oversaturated, so it is opt-in rather than the default.

+ */ + public enum ColorSpace { + /** What every camera has always produced. */ + SRGB(0), + /** Wider than sRGB, and what Android and Apple both use for wide-gamut images. */ + DISPLAY_P3(1); + + /** Stable XML and saved-state identifier. */ + private final int id; + + ColorSpace(int id) { + this.id = id; + } + + static ColorSpace fromId(int id) { + for (ColorSpace colorSpace : values()) { + if (colorSpace.id == id) return colorSpace; + } + throw new IllegalArgumentException(); + } + } + + /** + * {@link TextureView.SurfaceTextureListener} handles several lifecycle events on a + * {@link TextureView}. + */ + private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() { + @Override + public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) { + if (DEBUG) Log.v(TAG, "Surface Texture now available."); + if (getStatus() == Status.WAITING_FOR_SURFACE) { + openOnMainThread(); + } + } + + @Override + public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {} + + @Override + public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) { + Status state = getStatus(); + if (state == Status.OPEN || state == Status.OPENING + || state == Status.WAITING_FOR_SURFACE) { + Log.w(TAG, "Surface destroyed while camera was active."); + close(); + } + return true; + } + + @Override + public void onSurfaceTextureUpdated(SurfaceTexture texture) {} + }; + + /** The current internal camera lifecycle status. Guarded by this CameraView monitor. */ + private Status mStatus = Status.CLOSED; + private OnImageCapturedListener mOnImageCapturedListener; + private OnVideoCapturedListener mOnVideoCapturedListener; + + // For overriding onTouch + private final int mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); + private final int mLongPressTimeout = ViewConfiguration.getLongPressTimeout(); + private final Handler mHandler = new Handler(Looper.getMainLooper()); + private float mInitialMotionEventX; + private float mInitialMotionEventY; + private boolean mIsLongPressMotionEvent; + /** Dispatches the pending long-press gesture without clearing unrelated handler work. */ + private final Runnable mLongPressRunnable = () -> { + if (Build.VERSION.SDK_INT >= 24) { + performLongClick(mInitialMotionEventX, mInitialMotionEventY); + } else { + performLongClick(); + } + mIsLongPressMotionEvent = true; + }; + + // For tap-to-focus + private final Rect mFocusingRect = new Rect(); + private final Rect mMeteringRect = new Rect(); + + // For pinch-to-zoom + private PinchToZoomGestureDetector mScaleDetector; + private boolean mIsPinchToZoomEnabled = true; + + private ICameraModule mCameraModule; + + @Nullable + private OnCameraStateChangedListener mOnCameraStateChangedListener; + + private TextureView mCameraView; + private ImageView mImagePreview; + private VideoView mVideoPreview; + + private File mImagePendingConfirmation; + private File mVideoPendingConfirmation; + + private boolean mIsImageConfirmationEnabled; + private boolean mIsVideoConfirmationEnabled; + + @Nullable + private BarcodeScanner mBarcodeScanner; + /** Whether the active backend owns a native barcode analysis use case. */ + private boolean mUsingModuleBarcodeScanner; + + /** The caller's own frame analyzer, if one is running. */ + @Nullable + private FrameStream mFrameStream; + + /** The caller's face listener, if the camera agreed to report faces. */ + @Nullable + private FaceDetectionListener mFaceDetectionListener; + + // When true, avoid adding/removing views. While usually harmless (although it can cause state + // loss), it's especially important since calling removeView(TextureView) after + // onSaveInstanceState() will trigger a NPE on Android N. + private boolean mHasSavedState = false; + + public CameraView(Context context) { + this(context, null); + } + + public CameraView(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public CameraView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(context, attrs); + } + + @TargetApi(21) + public CameraView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + init(context, attrs); + } + + /** + * Builds the backend, falling back when the one asked for cannot run here. + * + *

CameraX is created reflectively so that androidx.camera is a dependency an app can + * exclude: a build that never selects CameraX never loads the class, and one that excluded + * the dependency and asks for it anyway gets Camera2 and a warning rather than a + * NoClassDefFoundError out of a constructor.

+ */ + @NonNull + private ICameraModule createModule(@NonNull Backend backend) { + if (Build.VERSION.SDK_INT < 21) { + return new LegacyCameraModule(this); + } + switch (backend) { + case LEGACY: + return new LegacyCameraModule(this); + case CAMERA_X: + ICameraModule cameraX = createCameraXModule(); + if (cameraX != null) { + return cameraX; + } + Log.w(TAG, "androidx.camera is not on the classpath; using Camera2 instead"); + return new Camera2Module(this); + case AUTO: + case CAMERA2: + default: + return USE_CAMERA_V2 ? new Camera2Module(this) : new LegacyCameraModule(this); + } + } + + @Nullable + private ICameraModule createCameraXModule() { + try { + return (ICameraModule) Class.forName("com.xlythe.view.camera.x.CameraXModule") + .getConstructor(CameraView.class) + .newInstance(this); + } catch (ReflectiveOperationException | LinkageError | RuntimeException error) { + if (DEBUG) Log.d(TAG, "CameraX is unavailable", error); + return null; + } + } + + /** Which implementation this view ended up driving. */ + @NonNull + public Backend getBackend() { + if (mCameraModule instanceof LegacyCameraModule) { + return Backend.LEGACY; + } + if (mCameraModule instanceof Camera2Module) { + return Backend.CAMERA2; + } + return Backend.CAMERA_X; + } + + private void init(Context context, @Nullable AttributeSet attrs) { + Backend backend = sDefaultBackend; + if (attrs != null) { + TypedArray chosen = context.obtainStyledAttributes(attrs, R.styleable.CameraView); + backend = Backend.fromId( + chosen.getInteger(R.styleable.CameraView_backend, backend.id)); + chosen.recycle(); + } + mCameraModule = createModule(backend); + + if (attrs != null) { + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CameraView); + setQuality(Quality.fromId(a.getInteger(R.styleable.CameraView_quality, getQuality().id))); + setFlash(Flash.fromId(a.getInteger(R.styleable.CameraView_flash, getFlash().id))); + setLensFacing(LensFacing.fromId(a.getInteger(R.styleable.CameraView_lensFacing, getLensFacing().id))); + setPinchToZoomEnabled(a.getBoolean(R.styleable.CameraView_pinchToZoomEnabled, isPinchToZoomEnabled())); + if (a.hasValue(R.styleable.CameraView_maxVideoDuration)) { + setMaxVideoDuration(a.getInteger(R.styleable.CameraView_maxVideoDuration, INDEFINITE_VIDEO_DURATION)); + } + if (a.hasValue(R.styleable.CameraView_maxVideoSize)) { + setMaxVideoSize(a.getInteger(R.styleable.CameraView_maxVideoSize, INDEFINITE_VIDEO_SIZE)); + } + setImageConfirmationEnabled(a.getBoolean(R.styleable.CameraView_confirmImages, isImageConfirmationEnabled())); + setVideoConfirmationEnabled(a.getBoolean(R.styleable.CameraView_confirmVideos, isVideoConfirmationEnabled())); + setMatchPreviewAspectRatio(a.getBoolean(R.styleable.CameraView_matchPreviewAspectRatio, isMatchPreviewAspectRatioEnabled())); + setDynamicRange(DynamicRange.fromId(a.getInteger(R.styleable.CameraView_dynamicRange, getDynamicRange().id))); + setExtension(Extension.fromId(a.getInteger(R.styleable.CameraView_extension, getExtension().id))); + setFrontVideoMirroringEnabled(a.getBoolean(R.styleable.CameraView_frontVideoMirroringEnabled, isFrontVideoMirroringEnabled())); + setPreviewStabilizationEnabled(a.getBoolean(R.styleable.CameraView_previewStabilizationEnabled, isPreviewStabilizationEnabled())); + setVideoStabilizationEnabled(a.getBoolean(R.styleable.CameraView_videoStabilizationEnabled, isVideoStabilizationEnabled())); + setExposureCompensation(a.getInteger(R.styleable.CameraView_exposureCompensation, getExposureCompensation())); + setTorchEnabled(a.getBoolean(R.styleable.CameraView_torchEnabled, isTorchEnabled())); + setLowLightBoostEnabled(a.getBoolean(R.styleable.CameraView_lowLightBoostEnabled, isLowLightBoostEnabled())); + a.recycle(); + } + + if (getBackground() == null) { + setBackgroundColor(0xFF111111); + } + + mScaleDetector = new PinchToZoomGestureDetector(context); + ensurePreviewViews(); + } + + @Override + public void onFinishInflate() { + super.onFinishInflate(); + ensurePreviewViews(); + } + + private void ensurePreviewViews() { + if (mCameraView != null) { + return; + } + addView(mCameraView = new TextureView(getContext())); + addView(mImagePreview = new ImageView(getContext())); + addView(mVideoPreview = new VideoView(getContext())); + mImagePreview.setScaleType(ImageView.ScaleType.CENTER_CROP); + mImagePreview.setVisibility(View.GONE); + mVideoPreview.setVisibility(View.GONE); + mCameraView.setSurfaceTextureListener(mSurfaceTextureListener); + } + + @Override + protected LayoutParams generateDefaultLayoutParams() { + return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + } + + @Override + protected Parcelable onSaveInstanceState() { + Bundle state = new Bundle(); + state.putParcelable(EXTRA_SUPER, super.onSaveInstanceState()); + state.putParcelable(EXTRA_MODULE, mCameraModule.onSaveInstanceState()); + state.putInt(EXTRA_QUALITY, getQuality().id); + state.putInt(EXTRA_ZOOM_LEVEL, getZoomLevel()); + state.putBoolean(EXTRA_PINCH_TO_ZOOM_ENABLED, isPinchToZoomEnabled()); + state.putFloat(EXTRA_PINCH_TO_ZOOM_SCALE_FACTOR, mScaleDetector.getCumulativeScaleFactor()); + state.putInt(EXTRA_FLASH, getFlash().id); + state.putInt(EXTRA_LENS_FACING, getLensFacing().id); + state.putLong(EXTRA_MAX_VIDEO_DURATION, getMaxVideoDuration()); + state.putLong(EXTRA_MAX_VIDEO_SIZE, getMaxVideoSize()); + state.putBoolean(EXTRA_CONFIRM_IMAGE, isImageConfirmationEnabled()); + state.putBoolean(EXTRA_CONFIRM_VIDEO, isVideoConfirmationEnabled()); + state.putBoolean(EXTRA_MATCH_PREVIEW_ASPECT_RATIO, isMatchPreviewAspectRatioEnabled()); + state.putInt(EXTRA_DYNAMIC_RANGE, getDynamicRange().id); + state.putInt(EXTRA_EXTENSION, getExtension().id); + state.putBoolean(EXTRA_FRONT_VIDEO_MIRRORING, isFrontVideoMirroringEnabled()); + state.putBoolean(EXTRA_PREVIEW_STABILIZATION, isPreviewStabilizationEnabled()); + state.putBoolean(EXTRA_VIDEO_STABILIZATION, isVideoStabilizationEnabled()); + state.putInt(EXTRA_EXPOSURE_COMPENSATION, getExposureCompensation()); + state.putBoolean(EXTRA_TORCH, isTorchEnabled()); + state.putBoolean(EXTRA_LOW_LIGHT_BOOST, isLowLightBoostEnabled()); + if (mImagePendingConfirmation != null) { + state.putString(EXTRA_PENDING_IMAGE_FILE_PATH, mImagePendingConfirmation.getAbsolutePath()); + } + if (mVideoPendingConfirmation != null) { + state.putString(EXTRA_PENDING_VIDEO_FILE_PATH, mVideoPendingConfirmation.getAbsolutePath()); + } + mHasSavedState = true; + return state; + } + + @Override + protected void onRestoreInstanceState(Parcelable savedState) { + if (savedState instanceof Bundle) { + Bundle state = (Bundle) savedState; + super.onRestoreInstanceState(state.getParcelable(EXTRA_SUPER)); + mCameraModule.onRestoreInstanceState(state.getParcelable(EXTRA_MODULE)); + setQuality(Quality.fromId(state.getInt(EXTRA_QUALITY))); + setZoomLevel(state.getInt(EXTRA_ZOOM_LEVEL)); + setPinchToZoomEnabled(state.getBoolean(EXTRA_PINCH_TO_ZOOM_ENABLED)); + mScaleDetector.setCumulativeScaleFactor(state.getFloat(EXTRA_PINCH_TO_ZOOM_SCALE_FACTOR, mScaleDetector.getCumulativeScaleFactor())); + setFlash(Flash.fromId(state.getInt(EXTRA_FLASH))); + setLensFacing(LensFacing.fromId(state.getInt(EXTRA_LENS_FACING))); + setMaxVideoDuration(state.getLong(EXTRA_MAX_VIDEO_DURATION)); + setMaxVideoSize(state.getLong(EXTRA_MAX_VIDEO_SIZE)); + setImageConfirmationEnabled(state.getBoolean(EXTRA_CONFIRM_IMAGE)); + setVideoConfirmationEnabled(state.getBoolean(EXTRA_CONFIRM_VIDEO)); + setMatchPreviewAspectRatio(state.getBoolean(EXTRA_MATCH_PREVIEW_ASPECT_RATIO)); + setDynamicRange(DynamicRange.fromId(state.getInt(EXTRA_DYNAMIC_RANGE, DynamicRange.SDR.id))); + setExtension(Extension.fromId(state.getInt(EXTRA_EXTENSION, Extension.NONE.id))); + setFrontVideoMirroringEnabled(state.getBoolean(EXTRA_FRONT_VIDEO_MIRRORING, true)); + setPreviewStabilizationEnabled(state.getBoolean(EXTRA_PREVIEW_STABILIZATION)); + setVideoStabilizationEnabled(state.getBoolean(EXTRA_VIDEO_STABILIZATION)); + setExposureCompensation(state.getInt(EXTRA_EXPOSURE_COMPENSATION)); + setTorchEnabled(state.getBoolean(EXTRA_TORCH)); + setLowLightBoostEnabled(state.getBoolean(EXTRA_LOW_LIGHT_BOOST)); + + if (state.containsKey(EXTRA_PENDING_IMAGE_FILE_PATH)) { + File file = new File(state.getString(EXTRA_PENDING_IMAGE_FILE_PATH)); + if (file.exists()) { + showImageConfirmation(file); + } + } + if (state.containsKey(EXTRA_PENDING_VIDEO_FILE_PATH)) { + File file = new File(state.getString(EXTRA_PENDING_VIDEO_FILE_PATH)); + if (file.exists()) { + showVideoConfirmation(file); + } + } + } else { + super.onRestoreInstanceState(savedState); + } + mHasSavedState = false; + } + + protected synchronized Status getStatus() { + return mStatus; + } + + @UiThread + private synchronized void setStatus(Status status) { + if (mStatus == status) { + return; + } + if (DEBUG) { + Log.v(TAG, "Camera status set to " + status.name()); + } + mStatus = status; + } + private void runOnMainThread(Runnable runnable) { + if (Looper.myLooper() == Looper.getMainLooper()) { + runnable.run(); + } else { + mHandler.post(runnable); + } + } + + /* + * Opens the camera and starts displaying a preview. You are in charge of checking if the + * phone has PackageManager.FEATURE_CAMERA_ANY and, if you are targeting Android M+, that the + * phone has granted Manifest.permission.CAMERA. + * + * Showing a preview and taking pictures need nothing else. The microphone is only required + * by the methods that record or stream audio, which ask for it themselves, and outputs are + * written to the File you pass in, so no storage permission is involved. + */ + @RequiresPermission(Manifest.permission.CAMERA) + public synchronized void open() { + runOnMainThread(this::openOnMainThread); + } + + @UiThread + private void openOnMainThread() { + Status state = getStatus(); + if (state == Status.OPEN || state == Status.OPENING) { + return; + } + if (mCameraView == null || !mCameraView.isAvailable()) { + setStatus(Status.WAITING_FOR_SURFACE); + return; + } + + setStatus(Status.OPENING); + try { + onOpen(); + if (getStatus() == Status.OPENING) { + setStatus(Status.OPEN); + if (mOnCameraStateChangedListener != null) { + mOnCameraStateChangedListener.onCameraOpened(); + } + } + } catch (RuntimeException e) { + onCameraError(e); + } + } + + /* + * Closes the camera. + */ + public synchronized void close() { + runOnMainThread(this::closeOnMainThread); + } + + @UiThread + private void closeOnMainThread() { + Status state = getStatus(); + if (state == Status.CLOSED || state == Status.CLOSING) { + return; + } + + setStatus(Status.CLOSING); + try { + onClose(); + } finally { + setStatus(Status.CLOSED); + } + } + + /** + * @return True if camera is currently open + */ + public synchronized boolean isOpen() { + return getStatus() == Status.OPEN; + } + + void onCameraError(Throwable error) { + runOnMainThread(() -> { + Log.e(TAG, "Camera operation failed", error); + setStatus(Status.ERROR); + + }); + } + + /** + * @return One of 0, 90, 180, 270. + */ + protected int getDisplayRotation() { + Display display; + if (Build.VERSION.SDK_INT >= 17) { + display = getDisplay(); + } else { + display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); + } + + // Null when the View is detached. If we were in the middle of a background operation, + // better to not NPE. When the background operation finishes, it'll realize that the camera + // was closed. + if (display == null) { + return 0; + } + + int displayRotation = display.getRotation(); + switch (displayRotation) { + case Surface.ROTATION_0: + displayRotation = 0; + break; + case Surface.ROTATION_90: + displayRotation = 90; + break; + case Surface.ROTATION_180: + displayRotation = 180; + break; + case Surface.ROTATION_270: + displayRotation = 270; + break; + } + return displayRotation; + } + + public TextureView asTextureView() { + return mCameraView; + } + + @UiThread + public SurfaceTexture getSurfaceTexture() { + return mCameraView.getSurfaceTexture(); + } + + @UiThread + protected Matrix getTransform(Matrix matrix) { + return mCameraView.getTransform(matrix); + } + + @UiThread + protected void setTransform(final Matrix matrix) { + mCameraView.setTransform(matrix); + } + + /** + * When enabled, requires images to be confirmed before + * {@link OnImageCapturedListener#onImageCaptured(File)} is triggered. A preview of the image + * will be displayed in CameraView's preview. + */ + public void setImageConfirmationEnabled(boolean enabled) { + mIsImageConfirmationEnabled = enabled; + } + + /** + * When true, {@link #takePicture(File)} will trigger the + * {@link OnImageCapturedListener#onImageConfirmation()} callback. To continue, call + * {@link #confirmPicture()}. + */ + public boolean isImageConfirmationEnabled() { + return mIsImageConfirmationEnabled; + } + + /** + * When enabled, requires videos to be confirmed before + * {@link OnVideoCapturedListener#onVideoCaptured(File)} is triggered. A preview of the video + * will be displayed in CameraView's preview. + */ + public void setVideoConfirmationEnabled(boolean enabled) { + mIsVideoConfirmationEnabled = enabled; + } + + /** + * When true, {@link #startRecording(File)} will trigger the + * {@link OnVideoCapturedListener#onVideoConfirmation()} callback. To continue, call + * {@link #confirmVideo()}. + */ + public boolean isVideoConfirmationEnabled() { + return mIsVideoConfirmationEnabled; + } + + void showImageConfirmation(File file) { + Log.d(TAG, "Saved the picture to " + file); + if (isImageConfirmationEnabled()) { + mCameraModule.pause(); + mImagePreview.setVisibility(View.VISIBLE); + Image.with(getContext()).load(file).into(mImagePreview); + mImagePendingConfirmation = file; + + if (getOnImageCapturedListener() != null) { + getOnImageCapturedListener().onImageConfirmation(); + } + } else { + if (getOnImageCapturedListener() != null) { + getOnImageCapturedListener().onImageCaptured(file); + } + } + } + + void onImageFailed() { + Log.d(TAG, "Failed to take a picture"); + if (isImageConfirmationEnabled()) { + mCameraModule.resume(); + } + + if (getOnImageCapturedListener() != null) { + getOnImageCapturedListener().onFailure(); + } + } + + void showVideoConfirmation(File file) { + Log.d(TAG, "Saved the video to " + file); + if (isVideoConfirmationEnabled()) { + mCameraModule.pause(); + + mVideoPreview.setVisibility(View.VISIBLE); + mVideoPreview.setShouldMirror(isUsingFrontFacingCamera()); + mVideoPreview.setShouldLoop(true); + mVideoPreview.setVolume(0.3f); + mVideoPreview.setFile(file); + if (!mVideoPreview.play()) { + Log.w(TAG, "Failed to play video preview"); + } + + mVideoPendingConfirmation = file; + + if (getOnVideoCapturedListener() != null) { + getOnVideoCapturedListener().onVideoConfirmation(); + } + } else { + if (getOnVideoCapturedListener() != null) { + getOnVideoCapturedListener().onVideoCaptured(file); + } + } + } + + void onVideoFailed() { + Log.d(TAG, "Failed to record a video"); + if (isVideoConfirmationEnabled()) { + mCameraModule.resume(); + } + + if (getOnVideoCapturedListener() != null) { + getOnVideoCapturedListener().onFailure(); + } + } + + /** + * Attempts to match image and video outputs to the preview aspect ratio. + */ + @TargetApi(21) + public void setMatchPreviewAspectRatio(boolean enabled) { + mCameraModule.setMatchPreviewAspectRatio(enabled); + } + + /** + * When enabled, image and video outputs will attempt to match the same aspect ratio used in + * the preview. It's advised that this is enabled when using + * {@link #setImageConfirmationEnabled(boolean)} and + * {@link #setVideoConfirmationEnabled(boolean)} as it provides the least amount of jank when + * showing the preview. Having this enabled also ensures that what the user sees is what the + * picture/video output. + */ + public boolean isMatchPreviewAspectRatioEnabled() { + return mCameraModule.isMatchPreviewAspectRatioEnabled(); + } + + /** + * Sets the quality for image and video outputs. + */ + public void setQuality(Quality quality) { + mCameraModule.setQuality(quality); + } + + /** + * Gets the current quality for image and video outputs. + */ + /** + * How hard a still capture is compressed, from 1 to 100, 95 by default. + * + *

Without this every device picks its own number, which is not the same on any two phones. + *

+ */ + public void setPictureQuality(int percent) { + mCameraModule.setPictureQuality(percent); + } + + public int getPictureQuality() { + return mCameraModule.getPictureQuality(); + } + + public Quality getQuality() { + return mCameraModule.getQuality(); + } + + /** + * Sets the maximum video duration before {@link OnVideoCapturedListener#onVideoCaptured(File)} + * is called automatically. Use {@link #INDEFINITE_VIDEO_DURATION} to disable the timeout. + */ + public void setMaxVideoDuration(long duration) { + mCameraModule.setMaxVideoDuration(duration); + } + + /** + * Returns the maximum duration of videos, or {@link #INDEFINITE_VIDEO_DURATION} if there is + * no timeout. + */ + public long getMaxVideoDuration() { + return mCameraModule.getMaxVideoDuration(); + } + + /** + * Sets the maximum video size in bytes before + * {@link OnVideoCapturedListener#onVideoCaptured(File)} is called automatically. Use + * {@link #INDEFINITE_VIDEO_SIZE} to disable the size restriction. + */ + public void setMaxVideoSize(long size) { + mCameraModule.setMaxVideoSize(size); + } + + /** + * Returns the maximum size of videos in bytes, or {@link #INDEFINITE_VIDEO_SIZE} if there is + * no timeout. + */ + public long getMaxVideoSize() { + return mCameraModule.getMaxVideoSize(); + } + + protected void onOpen() { + mCameraModule.open(); + } + + protected void onClose() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + exitBarcodeScanner(); + stopFrameAnalysis(); + } + mCameraModule.close(); + + if (!mHasSavedState) { + // Destroy the TextureView we used for the previous round of camera activity. This is + // because the TextureView will continue to show a bitmap of the old view until the camera + // is able to draw to it again. We'd rather clear the TextureView, but since there's no such + // way, we destroy it instead. + removeView(mCameraView); + addView(mCameraView = new TextureView(getContext()), 0 /* view position */); + mCameraView.setSurfaceTextureListener(mSurfaceTextureListener); + } + + if (mOnCameraStateChangedListener != null) { + mOnCameraStateChangedListener.onCameraClosed(); + } + } + + /** + * Takes a picture and calls {@link OnImageCapturedListener#onImageCaptured(File)} when done. + * @param file The destination. + */ + public void takePicture(File file) { + Log.v(TAG, "Taking a picture"); + // Freezing the preview to show the picture is right for a still, and wrong in the middle + // of a recording: the recording would freeze with it. + if (isImageConfirmationEnabled() && !isRecording()) { + mCameraModule.pause(); + } + + mCameraModule.takePicture(file); + } + + /** + * Whether a picture is waiting to be confirmed or rejected. + * + *

Worth asking before either: a confirmation can be cleared from under the UI showing it - + * by the camera closing, or by state being restored - and {@link #confirmPicture()} and + * {@link #rejectPicture()} both throw when there is nothing pending, which from a button's + * click handler is a crash.

+ */ + public boolean isImageConfirmationPending() { + return mImagePendingConfirmation != null; + } + + /** Whether a video is waiting to be confirmed or rejected. */ + public boolean isVideoConfirmationPending() { + return mVideoPendingConfirmation != null; + } + + /** + * Confirms a picture that is currently being displayed on the preview. + */ + public void confirmPicture() { + if (mImagePendingConfirmation == null) { + throw new IllegalStateException("confirmPicture() called, but no picture was awaiting confirmation"); + } + if (isImageConfirmationEnabled()) { + mCameraModule.resume(); + } + + Image.clear(mImagePreview); + mImagePreview.setVisibility(View.GONE); + if (getOnImageCapturedListener() != null) { + getOnImageCapturedListener().onImageCaptured(mImagePendingConfirmation); + } + mImagePendingConfirmation = null; + } + + /** + * Rejects a picture that is currently being displayed on the preview. + */ + public void rejectPicture() { + if (mImagePendingConfirmation == null) { + throw new IllegalStateException("rejectPicture() called, but no picture was awaiting confirmation"); + } + if (isImageConfirmationEnabled()) { + mCameraModule.resume(); + } + + Image.clear(mImagePreview); + mImagePreview.setVisibility(View.GONE); + if (!mImagePendingConfirmation.delete()) { + Log.w(TAG, "Attempted to clean up pending image file, but failed"); + } + mImagePendingConfirmation = null; + } + + /** + * Takes a video and calls {@link OnVideoCapturedListener#onVideoCaptured(File)} when done. + * + *

Records audio alongside the video, so this is where the microphone is needed rather + * than at {@link #open()}.

+ * + * @param file The destination. + */ + @RequiresPermission(Manifest.permission.RECORD_AUDIO) + public void startRecording(File file) { + Log.v(TAG, "Recording a video"); + mCameraModule.startRecording(file); + } + + /** + * Stops an in progress video. + */ + public void stopRecording() { + Log.v(TAG, "Stopped recording a video"); + if (isVideoConfirmationEnabled()) { + mCameraModule.pause(); + } + + mCameraModule.stopRecording(); + } + + /** + * @return True if currently recording. + */ + public boolean isRecording() { + return mCameraModule.isRecording(); + } + + /** + * Confirms a video that is currently being displayed on the preview. + */ + public void confirmVideo() { + if (mVideoPendingConfirmation == null) { + throw new IllegalStateException("confirmVideo() called, but no video was awaiting confirmation"); + } + if (isVideoConfirmationEnabled()) { + mCameraModule.resume(); + } + + mVideoPreview.pause(); + mVideoPreview.setVisibility(View.GONE); + if (getOnVideoCapturedListener() != null) { + getOnVideoCapturedListener().onVideoCaptured(mVideoPendingConfirmation); + } + mVideoPendingConfirmation = null; + } + + /** + * Rejects a video that is currently being displayed on the preview. + */ + public void rejectVideo() { + if (mVideoPendingConfirmation == null) { + throw new IllegalStateException("rejectVideo() called, but no video was awaiting confirmation"); + } + if (isVideoConfirmationEnabled()) { + mCameraModule.resume(); + } + + mVideoPreview.pause(); + mVideoPreview.setVisibility(View.GONE); + if (!mVideoPendingConfirmation.delete()) { + Log.w(TAG, "Attempted to clean up pending video file, but failed"); + } + mVideoPendingConfirmation = null; + } + + /** + * Starts a video stream. The stream will continue until {@link VideoStream#close} is called. + * + * @return A stream that can be shared to a remote device. + */ + @RequiresPermission(allOf = { + Manifest.permission.CAMERA, + Manifest.permission.RECORD_AUDIO + }) + @RequiresApi(18) + public VideoStream stream() { + return stream(new VideoStream.Params.Builder().build()); + } + + /** + * Starts a video stream. The stream will continue until {@link VideoStream#close} is called. + * + * @return A stream that can be shared to a remote device. + */ + @RequiresPermission(allOf = { + Manifest.permission.CAMERA, + Manifest.permission.RECORD_AUDIO + }) + @RequiresApi(18) + public VideoStream stream(VideoStream.Params params) { + if (params.isVideoEnabled() && !isOpen()) { + throw new IllegalStateException("Camera must be open before starting a video stream"); + } + + return new VideoStream.Builder().attach(mCameraModule).setParams(params).build(); + } + + public interface BarcodeDetectorListener { + void onBarcodeFound(List barcodes); + } + + @RequiresApi(19) + @RequiresPermission(Manifest.permission.CAMERA) + public void enterBarcodeScanner(BarcodeDetectorListener listener, @Barcode.Format int format, @Barcode.Format int... formats) { + if (!isOpen()) { + throw new IllegalStateException("Camera must be open before scanning for barcodes"); + } + + if (mBarcodeScanner != null || mUsingModuleBarcodeScanner) { + throw new IllegalStateException("Barcode scanner cannot be started twice"); + } + + mUsingModuleBarcodeScanner = mCameraModule.startBarcodeScanner(listener, format, formats); + if (!mUsingModuleBarcodeScanner) { + mBarcodeScanner = new BarcodeScanner( + mCameraModule.getCanvas(), this, listener, format, formats); + mBarcodeScanner.start(); + } + } + + @RequiresApi(19) + public void exitBarcodeScanner() { + if (mBarcodeScanner != null) { + mBarcodeScanner.stop(); + mBarcodeScanner = null; + } + if (mUsingModuleBarcodeScanner) { + mCameraModule.stopBarcodeScanner(); + mUsingModuleBarcodeScanner = false; + } + } + + /** + * Hands every camera frame to an analyzer, for detection the library does not do itself. + * + *

The analyzer is called on a background thread with the most recent frame, so one that + * takes longer than a frame interval drops frames instead of falling behind. Each frame says + * how to turn it upright and where its pixels land on this view, which is what an overlay + * drawn over the preview needs.

+ * + *

This runs alongside the preview and recording, and stays attached across a lens switch. + * Call {@link #stopFrameAnalysis()} to let the camera give the buffers back.

+ * + * @throws IllegalStateException if the camera is not open, or analysis is already running + */ + @RequiresApi(19) + @RequiresPermission(Manifest.permission.CAMERA) + public void startFrameAnalysis(@NonNull FrameStream.Analyzer analyzer) { + startFrameAnalysis(analyzer, new FrameStream.Params()); + } + + /** + * {@link #startFrameAnalysis(FrameStream.Analyzer)} with a say over the frames themselves. + * + * @see FrameStream.Params#setMaxSize + */ + @RequiresApi(19) + @RequiresPermission(Manifest.permission.CAMERA) + public void startFrameAnalysis( + @NonNull FrameStream.Analyzer analyzer, @NonNull FrameStream.Params params) { + if (!isOpen()) { + throw new IllegalStateException("Camera must be open before analyzing frames"); + } + if (mFrameStream != null) { + throw new IllegalStateException("Frame analysis cannot be started twice"); + } + mFrameStream = new FrameStream(mCameraModule.getCanvas(), this, params, analyzer); + mFrameStream.start(); + } + + /** Stops the analyzer started by {@link #startFrameAnalysis}. */ + @RequiresApi(19) + public void stopFrameAnalysis() { + if (mFrameStream != null) { + mFrameStream.close(); + mFrameStream = null; + } + } + + /** Whether an analyzer is receiving frames. */ + @RequiresApi(19) + public boolean isAnalyzingFrames() { + return mFrameStream != null && mFrameStream.isAnalyzing(); + } + + /** Receives the faces the camera itself is tracking. */ + public interface FaceDetectionListener { + /** + * Called on the main thread whenever the camera reports its faces, which is roughly once + * per preview frame. An empty list means it has stopped seeing any. + * + * @param faces the faces, in the camera's own coordinates + * @param faceToView maps a face's bounds onto this view, for drawing over the preview + */ + void onFacesDetected(@NonNull List faces, @NonNull Matrix faceToView); + } + + /** + * Whether this camera can record in a given colour range. + * + *

Worth asking before offering the choice: wide gamut needs API 34 and a camera that + * reports the profile, and a picture saved in a colour space the viewer ignores looks + * oversaturated rather than better.

+ */ + public boolean isColorSpaceSupported(ColorSpace colorSpace) { + return mCameraModule.isColorSpaceSupported(colorSpace); + } + + /** + * The colour range pictures are recorded in, sRGB by default. + * + *

Takes effect the next time the camera configures its session, so set it before opening + * or expect a brief reconfiguration.

+ */ + public void setColorSpace(ColorSpace colorSpace) { + mCameraModule.setColorSpace(colorSpace); + } + + public ColorSpace getColorSpace() { + return mCameraModule.getColorSpace(); + } + + /** + * Whether a picture can be taken while a recording is running. + * + *

The video-snapshot button every camera app has. Not every camera can hold a preview, a + * recording and a still at once, so this is worth asking before showing the control: where it + * is false, {@link #takePicture} during a recording reports a failure and the recording + * continues.

+ */ + public boolean isSnapshotWhileRecordingSupported() { + return mCameraModule.isSnapshotWhileRecordingSupported(); + } + + /** + * Whether this camera can report the faces it is tracking. + * + *

Almost every camera can: it needs faces to decide what to focus and expose for, so the + * work is already being done in hardware. A camera that cannot is usually an external or + * virtual one.

+ */ + public boolean isFaceDetectionSupported() { + return mCameraModule.isFaceDetectionSupported(); + } + + /** + * Reports the faces the camera is tracking, or stops when given null. + * + *

This is the camera's own detector, the one the manufacturer's app draws boxes from. It is + * free, it arrives with the preview, and it finds faces rather than describing them - for + * anything beyond where a face is, run a detector over + * {@link #startFrameAnalysis(FrameStream.Analyzer)} instead.

+ * + * @return whether the camera took it on. False means this camera cannot report faces, and the + * listener will never be called. + */ + public boolean setFaceDetectionListener(@Nullable FaceDetectionListener listener) { + mFaceDetectionListener = listener; + boolean enabled = mCameraModule.setFaceDetectionEnabled(listener != null); + if (!enabled) { + mFaceDetectionListener = null; + } + return enabled; + } + + /** Called by the active backend, on the main thread. */ + void onFacesDetected(@NonNull List faces, @NonNull Matrix faceToView) { + FaceDetectionListener listener = mFaceDetectionListener; + if (listener != null) { + listener.onFacesDetected(faces, faceToView); + } + } + + /** + * @return True if the device supports a front facing camera. + */ + public boolean hasFrontFacingCamera() { + return mCameraModule.hasFrontFacingCamera(); + } + + /** + * @return True if CameraView is currently using a front facing camera. + */ + public boolean isUsingFrontFacingCamera() { + return mCameraModule.isUsingFrontFacingCamera(); + } + + /** + * Toggles the active camera to the next available camera. Typically, this toggles between + * the front and back facing cameras. + */ + public void toggleCamera() { + mCameraModule.toggleCamera(); + } + + /** + * Sets which camera (front or back) to use. + */ + public void setLensFacing(LensFacing lensFacing) { + if (getLensFacing().equals(lensFacing)) { + return; + } + + mCameraModule.setLensFacing(lensFacing); + } + + /** + * Returns which camera (front or back) is being used. + */ + public LensFacing getLensFacing() { + return mCameraModule.isUsingFrontFacingCamera() ? LensFacing.FRONT : LensFacing.BACK; + } + + /** + * Focuses the camera on the given area. Limited from -1000 to 1000. + */ + public void focus(Rect focus, Rect metering) { + mCameraModule.focus(focus, metering); + } + + /** + * Sets the active flash strategy. + */ + public void setFlash(Flash flashMode) { + mCameraModule.setFlash(flashMode); + } + + /** + * Gets the active flash strategy. + */ + public Flash getFlash() { + return mCameraModule.getFlash(); + } + + /** + * @return True if the camera supports flash. + */ + public boolean hasFlash() { + return mCameraModule.hasFlash(); + } + + /** Sets the requested video dynamic range. */ + public void setDynamicRange(DynamicRange dynamicRange) { + mCameraModule.setDynamicRange(dynamicRange); + } + + /** Returns the requested video dynamic range. */ + public DynamicRange getDynamicRange() { + return mCameraModule.getDynamicRange(); + } + + /** Returns whether the active backend and lens support the requested dynamic range. */ + public boolean isDynamicRangeSupported(DynamicRange dynamicRange) { + return mCameraModule.isDynamicRangeSupported(dynamicRange); + } + + /** Sets the optional CameraX photo-processing extension. */ + public void setExtension(Extension extension) { + mCameraModule.setExtension(extension); + } + + /** Returns the requested CameraX photo-processing extension. */ + public Extension getExtension() { + return mCameraModule.getExtension(); + } + + /** Returns whether the active backend and lens support the extension. */ + public boolean isExtensionSupported(Extension extension) { + return mCameraModule.isExtensionSupported(extension); + } + /** Controls whether front-camera video files are mirrored. */ + public void setFrontVideoMirroringEnabled(boolean enabled) { + mCameraModule.setFrontVideoMirroringEnabled(enabled); + } + + /** Returns whether front-camera video files are mirrored. */ + public boolean isFrontVideoMirroringEnabled() { + return mCameraModule.isFrontVideoMirroringEnabled(); + } + + /** Enables stabilized preview output when the active camera supports it. */ + public void setPreviewStabilizationEnabled(boolean enabled) { + mCameraModule.setPreviewStabilizationEnabled(enabled); + } + + /** Returns whether preview stabilization is requested. */ + public boolean isPreviewStabilizationEnabled() { + return mCameraModule.isPreviewStabilizationEnabled(); + } + + /** Returns whether preview stabilization is supported by the active camera. */ + public boolean isPreviewStabilizationSupported() { + return mCameraModule.isPreviewStabilizationSupported(); + } + + /** Enables stabilized recorded video when the active camera supports it. */ + public void setVideoStabilizationEnabled(boolean enabled) { + mCameraModule.setVideoStabilizationEnabled(enabled); + } + + /** Returns whether video stabilization is requested. */ + public boolean isVideoStabilizationEnabled() { + return mCameraModule.isVideoStabilizationEnabled(); + } + + /** Returns whether video stabilization is supported by the active camera. */ + public boolean isVideoStabilizationSupported() { + return mCameraModule.isVideoStabilizationSupported(); + } + + /** Sets the exposure compensation index, clamped to the active camera's range. */ + public void setExposureCompensation(int exposureCompensation) { + mCameraModule.setExposureCompensation(exposureCompensation); + } + + /** Returns the last accepted exposure compensation index. */ + public int getExposureCompensation() { + return mCameraModule.getExposureCompensation(); + } + + /** Returns the active camera's minimum exposure compensation index. */ + public int getMinExposureCompensation() { + return mCameraModule.getMinExposureCompensation(); + } + + /** Returns the active camera's maximum exposure compensation index. */ + public int getMaxExposureCompensation() { + return mCameraModule.getMaxExposureCompensation(); + } + + /** Returns whether the active camera supports exposure compensation. */ + public boolean isExposureCompensationSupported() { + return mCameraModule.isExposureCompensationSupported(); + } + + /** Enables continuous torch illumination when supported. */ + public void setTorchEnabled(boolean enabled) { + mCameraModule.setTorchEnabled(enabled); + } + + /** Returns whether torch illumination is requested. */ + public boolean isTorchEnabled() { + return mCameraModule.isTorchEnabled(); + } + + /** Enables CameraX low-light boost when supported. */ + public void setLowLightBoostEnabled(boolean enabled) { + mCameraModule.setLowLightBoostEnabled(enabled); + } + + /** Returns whether low-light boost is requested. */ + public boolean isLowLightBoostEnabled() { + return mCameraModule.isLowLightBoostEnabled(); + } + + /** Returns whether the active camera supports low-light boost. */ + public boolean isLowLightBoostSupported() { + return mCameraModule.isLowLightBoostSupported(); + } + protected int getRelativeCameraOrientation() { + return mCameraModule.getRelativeCameraOrientation(); + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + if (changed) { + mCameraModule.onLayoutChanged(); + } + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + // Disable pinch-to-zoom while a preview is visible. + if (mImagePendingConfirmation != null + || mVideoPendingConfirmation != null + || mCameraModule.isPaused()) { + return super.onTouchEvent(event); + } + + mScaleDetector.onTouchEvent(event); + if (event.getPointerCount() == 2 && isPinchToZoomEnabled() && isZoomSupported()) { + return true; + } + + // Camera focus + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + mInitialMotionEventX = event.getX(); + mInitialMotionEventY = event.getY(); + mIsLongPressMotionEvent = false; + mHandler.removeCallbacks(mLongPressRunnable); + mHandler.postDelayed(mLongPressRunnable, mLongPressTimeout); + break; + case MotionEvent.ACTION_MOVE: + if (movedBeyondTouchSlop(event)) { + mHandler.removeCallbacks(mLongPressRunnable); + } + break; + case MotionEvent.ACTION_CANCEL: + mHandler.removeCallbacks(mLongPressRunnable); + break; + case MotionEvent.ACTION_UP: + mHandler.removeCallbacks(mLongPressRunnable); + if (!movedBeyondTouchSlop(event) && !mIsLongPressMotionEvent) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 + && hasOnClickListeners()) { + performClick(); + } else { + calculateTapArea(mFocusingRect, event.getX(), event.getY(), 1f); + calculateTapArea(mMeteringRect, event.getX(), event.getY(), 1.5f); + if (area(mFocusingRect) != 0 && area(mMeteringRect) != 0) { + focus(mFocusingRect, mMeteringRect); + } + } + } + break; + } + return true; + } + + private boolean movedBeyondTouchSlop(MotionEvent event) { + float distanceX = event.getX() - mInitialMotionEventX; + float distanceY = event.getY() - mInitialMotionEventY; + return Math.hypot(distanceX, distanceY) > mTouchSlop; + } + + /** + * Returns the width * height of the given rect + */ + private int area(Rect rect) { + return rect.width() * rect.height(); + } + + /** + * The area must be between -1000,-1000 and 1000,1000 + */ + private void calculateTapArea(Rect rect, float x, float y, float coefficient) { + int max = 1000; + int min = -1000; + + // Default to 300 (1/6th the total area) and scale by the coefficient + int areaSize = Float.valueOf(300 * coefficient).intValue(); + + // Rotate the coordinates if the camera orientation is different + int width = getWidth(); + int height = getHeight(); + + int relativeCameraOrientation = getRelativeCameraOrientation(); + int temp = -1; + float tempf = -1f; + switch (relativeCameraOrientation) { + case 90: + // Fall-through + case 270: + // We're horizontal. Swap width/height. Swap x/y. + temp = width; + width = height; + height = temp; + + tempf = x; + x = y; + y = tempf; + break; + } + switch (relativeCameraOrientation) { + case 180: + // Fall-through + case 270: + // We're upside down. Fix x/y. + x = width - x; + y = height - y; + break; + } + + // Grab the x, y position from within the View and normalize it to -1000 to 1000 + x = min + distance(max, min) * (x / width); + y = min + distance(max, min) * (y / height); + + + // Modify the rect to the bounding area + rect.top = (int) y - areaSize / 2; + rect.left = (int) x - areaSize / 2; + rect.bottom = rect.top + areaSize; + rect.right = rect.left + areaSize; + + // Cap at -1000 to 1000 + rect.top = rangeLimit(rect.top, max, min); + rect.left = rangeLimit(rect.left, max, min); + rect.bottom = rangeLimit(rect.bottom, max, min); + rect.right = rangeLimit(rect.right, max, min); + } + + private int rangeLimit(int val, int max, int min) { + return Math.min(Math.max(val, min), max); + } + + /** + * Maps a cumulative pinch scale onto a zoom level. + * + *

The scale starts at 1 rather than 0, so the usable range of a pinch is maxScale - 1. A + * fully spread pinch has to land on the camera's maximum zoom; dividing by maxScale instead + * stopped at four fifths of it and left the last of the range unreachable.

+ * + * @param scaleFactor the cumulative scale, between 1 and maxScale + * @param maxScale the scale a fully spread pinch reaches + * @param maxZoomLevel the zoom level that scale maps to + */ + static int zoomLevelForScale(float scaleFactor, float maxScale, int maxZoomLevel) { + if (maxScale <= 1f || maxZoomLevel <= 0) { + return 0; + } + float clamped = Math.max(1f, Math.min(scaleFactor, maxScale)); + int zoomLevel = (int) ((clamped - 1f) * maxZoomLevel / (maxScale - 1f)); + return Math.min(Math.max(zoomLevel, 0), maxZoomLevel); + } + + private int distance(int a, int b) { + return Math.abs(a - b); + } + + /** + * When enabled, the user can pinch the camera to zoom in/out. + */ + public void setPinchToZoomEnabled(boolean enabled) { + mIsPinchToZoomEnabled = enabled; + } + + /** + * @return True if pinch to zoom is enabled. + */ + public boolean isPinchToZoomEnabled() { + return mIsPinchToZoomEnabled; + } + + /** + * Sets the current zoom level, from 0 to {@link #getMaxZoomLevel()}. + */ + public void setZoomLevel(int zoomLevel) { + mCameraModule.setZoomLevel(zoomLevel); + } + + /** + * @return The current zoom level. + */ + public int getZoomLevel() { + return mCameraModule.getZoomLevel(); + } + + /** + * @return The maximum zoom level. + */ + public int getMaxZoomLevel() { + return mCameraModule.getMaxZoomLevel(); + } + + /** + * @return True if the camera supports zooming. + */ + public boolean isZoomSupported() { + return mCameraModule.isZoomSupported(); + } + + /** + * Enables listening for image-related callbacks. + */ + public void setOnImageCapturedListener(OnImageCapturedListener l) { + mOnImageCapturedListener = l; + mCameraModule.setOnImageCapturedListener(l); + } + + protected OnImageCapturedListener getOnImageCapturedListener() { + return mOnImageCapturedListener; + } + + /** + * Enables listening for video-related callbacks. + */ + public void setOnVideoCapturedListener(OnVideoCapturedListener l) { + mOnVideoCapturedListener = l; + mCameraModule.setOnVideoCapturedListener(l); + } + + protected OnVideoCapturedListener getOnVideoCapturedListener() { + return mOnVideoCapturedListener; + } + + /** + * Enables listening for callbacks about the camera being opened or closed. + */ + public void setOnCameraStateChangedListener(OnCameraStateChangedListener l) { + mOnCameraStateChangedListener = l; + } + + protected OnCameraStateChangedListener getOnCameraStateChangedListener() { + return mOnCameraStateChangedListener; + } + + public interface OnImageCapturedListener { + void onImageConfirmation(); + void onImageCaptured(File file); + void onFailure(); + } + + public interface OnVideoCapturedListener { + void onVideoConfirmation(); + void onVideoCaptured(File file); + void onFailure(); + } + + public interface OnCameraStateChangedListener { + void onCameraOpened(); + void onCameraClosed(); + } + + private class PinchToZoomGestureDetector extends ScaleGestureDetector implements ScaleGestureDetector.OnScaleGestureListener { + final float MAX_SCALE = 5f; + float mScaleFactor = 1f; + + PinchToZoomGestureDetector(Context context) { + this(context, new S()); + } + + PinchToZoomGestureDetector(Context context, S s) { + super(context, s); + s.setRealGestureDetector(this); + } + + float getCumulativeScaleFactor() { + return mScaleFactor; + } + + void setCumulativeScaleFactor(float scaleFactor) { + mScaleFactor = scaleFactor; + } + + @Override + public boolean onScale(ScaleGestureDetector detector) { + mScaleFactor *= detector.getScaleFactor(); + + // Don't let the object get too small or too large. + mScaleFactor = Math.max(1f, Math.min(mScaleFactor, MAX_SCALE)); + + setZoomLevel(zoomLevelForScale(mScaleFactor, MAX_SCALE, getMaxZoomLevel())); + return true; + } + + @Override + public boolean onScaleBegin(ScaleGestureDetector detector) { + return false; + } + + @Override + public void onScaleEnd(ScaleGestureDetector detector) {} + } + + private static class S extends ScaleGestureDetector.SimpleOnScaleGestureListener { + private ScaleGestureDetector.OnScaleGestureListener listener; + + void setRealGestureDetector(ScaleGestureDetector.OnScaleGestureListener l) { + listener = l; + } + + @Override + public boolean onScale(ScaleGestureDetector detector) { + return listener.onScale(detector); + } + } +} diff --git a/camera-view/src/main/java/com/xlythe/view/camera/CameraXBarcodeAnalyzer.java b/camera-view/src/main/java/com/xlythe/view/camera/CameraXBarcodeAnalyzer.java new file mode 100644 index 0000000..7ea8a22 --- /dev/null +++ b/camera-view/src/main/java/com/xlythe/view/camera/CameraXBarcodeAnalyzer.java @@ -0,0 +1,82 @@ +package com.xlythe.view.camera; + +import android.media.Image; +import android.util.Log; + +import androidx.annotation.NonNull; +import androidx.annotation.RestrictTo; +import androidx.camera.core.ExperimentalGetImage; +import androidx.camera.core.ImageAnalysis; +import androidx.camera.core.ImageProxy; + +import com.google.mlkit.vision.barcode.BarcodeScannerOptions; +import com.google.mlkit.vision.barcode.BarcodeScanning; +import com.google.mlkit.vision.common.InputImage; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; + +/** CameraX ImageAnalysis adapter for CameraView's ML Kit barcode callback. */ +@RestrictTo(RestrictTo.Scope.LIBRARY) +public final class CameraXBarcodeAnalyzer implements ImageAnalysis.Analyzer, AutoCloseable { + /** Log tag shared with CameraView. */ + private static final String TAG = CameraView.class.getSimpleName(); + /** ML Kit scanner processing CameraX image proxies. */ + private final com.google.mlkit.vision.barcode.BarcodeScanner mScanner; + /** CameraView callback receiving mapped barcode values. */ + private final CameraView.BarcodeDetectorListener mListener; + /** Executor serializing listener and image completion callbacks. */ + private final Executor mCallbackExecutor; + /** Ensures no callbacks are delivered after the analyzer closes. */ + private final AtomicBoolean mClosed = new AtomicBoolean(); + + public CameraXBarcodeAnalyzer( + @NonNull CameraView.BarcodeDetectorListener listener, + @NonNull Executor callbackExecutor, + @Barcode.Format int format, + @Barcode.Format int... formats) { + mListener = listener; + mCallbackExecutor = callbackExecutor; + mScanner = BarcodeScanning.getClient(new BarcodeScannerOptions.Builder() + .setBarcodeFormats(format, formats) + .build()); + } + + @ExperimentalGetImage + @Override public void analyze(@NonNull ImageProxy imageProxy) { + if (mClosed.get()) { + imageProxy.close(); + return; + } + Image mediaImage = imageProxy.getImage(); + if (mediaImage == null) { + imageProxy.close(); + return; + } + InputImage image = InputImage.fromMediaImage( + mediaImage, imageProxy.getImageInfo().getRotationDegrees()); + try { + mScanner.process(image) + .addOnSuccessListener(mCallbackExecutor, barcodes -> { + if (mClosed.get()) return; + List mapped = new ArrayList<>(barcodes.size()); + for (com.google.mlkit.vision.barcode.common.Barcode barcode : barcodes) { + mapped.add(new Barcode(barcode)); + } + mListener.onBarcodeFound(mapped); + }) + .addOnFailureListener(mCallbackExecutor, + error -> Log.w(TAG, "CameraX barcode analysis failed", error)) + .addOnCompleteListener(mCallbackExecutor, ignored -> imageProxy.close()); + } catch (RuntimeException error) { + imageProxy.close(); + Log.w(TAG, "CameraX barcode analysis could not start", error); + } + } + + @Override public void close() { + if (mClosed.compareAndSet(false, true)) mScanner.close(); + } +} \ No newline at end of file diff --git a/camera-view/src/main/java/com/xlythe/view/camera/Face.java b/camera-view/src/main/java/com/xlythe/view/camera/Face.java new file mode 100644 index 0000000..0000365 --- /dev/null +++ b/camera-view/src/main/java/com/xlythe/view/camera/Face.java @@ -0,0 +1,105 @@ +package com.xlythe.view.camera; + +import android.graphics.Point; +import android.graphics.Rect; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +/** + * A face the camera itself is tracking. + * + *

Every camera on Android runs face detection in its image signal processor, because it needs + * faces to decide what to focus and expose for; this is that result, which costs nothing to ask + * for and arrives with the preview rather than a frame behind it. It is the same detector the + * manufacturer's own camera app shows boxes from.

+ * + *

What it is not is a face analyzer. There are no landmarks beyond the eyes and mouth, no + * expression, no identity across sessions, and a camera reporting in its simple mode gives only + * the bounds. For anything more, run a detector of your own over + * {@link CameraView#startFrameAnalysis}.

+ * + *

The bounds are in the camera's own coordinates, which are not the view's: the listener is + * given a matrix that maps them.

+ * + * @see CameraView#setFaceDetectionListener + */ +public final class Face { + /** What {@link #getId()} reports when the camera does not track faces between frames. */ + public static final int ID_UNKNOWN = -1; + + private final Rect mBounds; + private final int mScore; + private final int mId; + @Nullable private final Point mLeftEye; + @Nullable private final Point mRightEye; + @Nullable private final Point mMouth; + + /** Builds a face from what a backend's own detector reported. */ + @androidx.annotation.RestrictTo(androidx.annotation.RestrictTo.Scope.LIBRARY) + @NonNull + public static Face create(@NonNull Rect bounds, int score, int id, + @Nullable Point leftEye, @Nullable Point rightEye, @Nullable Point mouth) { + return new Face(bounds, score, id, leftEye, rightEye, mouth); + } + + private Face(@NonNull Rect bounds, int score, int id, + @Nullable Point leftEye, @Nullable Point rightEye, @Nullable Point mouth) { + mBounds = bounds; + mScore = score; + mId = id; + mLeftEye = leftEye; + mRightEye = rightEye; + mMouth = mouth; + } + + /** The face's rectangle, in the coordinates the listener's matrix maps from. */ + @NonNull + public Rect getBounds() { + return mBounds; + } + + /** How sure the camera is, from 1 to 100. */ + public int getScore() { + return mScore; + } + + /** + * An identifier that stays with this face while the camera keeps tracking it, or + * {@link #ID_UNKNOWN}. + * + *

Useful for smoothing: a box drawn for a face that keeps its id can be interpolated + * towards its new position instead of jumping.

+ */ + public int getId() { + return mId; + } + + /** Where the camera thinks the left eye is, if it reports landmarks at all. */ + @Nullable + public Point getLeftEyePosition() { + return mLeftEye; + } + + @Nullable + public Point getRightEyePosition() { + return mRightEye; + } + + @Nullable + public Point getMouthPosition() { + return mMouth; + } + + /** Whether this face came with eye and mouth positions. */ + public boolean hasLandmarks() { + return mLeftEye != null || mRightEye != null || mMouth != null; + } + + @NonNull + @Override + public String toString() { + return "Face{bounds=" + mBounds + ", score=" + mScore + ", id=" + mId + + ", landmarks=" + hasLandmarks() + "}"; + } +} diff --git a/camera-view/src/main/java/com/xlythe/view/camera/FrameStream.java b/camera-view/src/main/java/com/xlythe/view/camera/FrameStream.java new file mode 100644 index 0000000..51ea299 --- /dev/null +++ b/camera-view/src/main/java/com/xlythe/view/camera/FrameStream.java @@ -0,0 +1,334 @@ +package com.xlythe.view.camera; + +import android.Manifest; +import android.graphics.ImageFormat; +import android.graphics.Matrix; +import android.graphics.RectF; +import android.media.Image; +import android.media.ImageReader; +import android.os.Build; +import android.util.Log; +import android.util.Size; +import android.view.Surface; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; +import androidx.annotation.RequiresPermission; + +import com.google.common.util.concurrent.SettableFuture; +import com.xlythe.view.camera.stream.VideoRecorder; + +import java.io.Closeable; +import java.util.Objects; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import static android.os.Process.THREAD_PRIORITY_DISPLAY; +import static android.os.Process.THREAD_PRIORITY_VIDEO; +import static android.os.Process.setThreadPriority; + +/** + * The camera's frames, one at a time, for code that wants to look at them. + * + *

This is the general form of what the barcode scanner does: attach a surface to whichever + * backend is running, pull frames off it as fast as they are produced, and hand each one to an + * analyzer. It exists so that detection - faces, text, objects, a model of your own - does not + * have to be built into the library to be possible, and so that every analyzer gets the same + * answer about where a frame's pixels land on screen.

+ * + *

Frames arrive on a background thread and only the most recent one is kept, so an analyzer + * that takes longer than a frame interval drops frames rather than falling behind. The {@link + * Image} inside a {@link Frame} belongs to the camera and is recycled as soon as + * {@link Analyzer#onFrame} returns: anything that outlives the call has to be copied out.

+ * + *

Start one with {@link CameraView#startFrameAnalysis}.

+ */ +@RequiresApi(19) +public final class FrameStream implements Closeable { + private static final String TAG = CameraView.class.getSimpleName(); + + /** Maximum time allowed for the backend to hand over a surface. */ + private static final long SURFACE_TIMEOUT_SECONDS = 10; + + /** How long to wait before asking the camera for another frame. */ + private static final long IDLE_POLL_MILLIS = 10; + + /** Two buffers let the camera fill one while the analyzer reads the other. */ + private static final int BUFFER_COUNT = 2; + + /** What an analyzer is given for each frame the camera produces. */ + public interface Analyzer { + /** + * Called on a background thread for each frame. + * + *

The frame's image is recycled when this returns.

+ */ + void onFrame(@NonNull Frame frame); + } + + /** What the analyzer wants from the camera. */ + public static final class Params { + @Nullable private Size mMaxSize; + private int mImageFormat = ImageFormat.YUV_420_888; + + /** + * Caps the frame size, which is otherwise whatever the preview is using. + * + *

Detection costs scale with pixels, and most detectors are no better at full preview + * resolution than at a fraction of it. The backend picks the closest size it supports + * within this bound, so the frames are usually smaller than asked for and never larger. + *

+ */ + @NonNull + public Params setMaxSize(@Nullable Size maxSize) { + mMaxSize = maxSize; + return this; + } + + @Nullable + public Size getMaxSize() { + return mMaxSize; + } + + /** + * The pixel format of the frames, {@link ImageFormat#YUV_420_888} by default. + * + *

YUV is the format every camera can produce without conversion, and the one ML Kit and + * most native detectors take. {@link ImageFormat#PRIVATE} is worth asking for when the + * frames only ever go to the GPU.

+ */ + @NonNull + public Params setImageFormat(int imageFormat) { + mImageFormat = imageFormat; + return this; + } + + public int getImageFormat() { + return mImageFormat; + } + } + + /** One frame, valid for the duration of the {@link Analyzer#onFrame} call that received it. */ + public final class Frame { + private final Image mImage; + private final int mRotationDegrees; + private final boolean mMirrored; + + Frame(@NonNull Image image, int rotationDegrees, boolean mirrored) { + mImage = image; + mRotationDegrees = rotationDegrees; + mMirrored = mirrored; + } + + /** The camera's own image. Do not close it, and do not keep it. */ + @NonNull + public Image getImage() { + return mImage; + } + + public int getWidth() { + return mImage.getWidth(); + } + + public int getHeight() { + return mImage.getHeight(); + } + + /** + * The clockwise rotation, in degrees, that makes this frame upright. + * + *

Frames come off the sensor in the sensor's own orientation, which on almost every + * phone is a quarter turn from the way the device is held. This is the value ML Kit's + * {@code InputImage} and most other detectors take.

+ */ + public int getRotationDegrees() { + return mRotationDegrees; + } + + /** Whether the frame came from a user-facing lens, whose image is a mirror of the scene. */ + public boolean isMirrored() { + return mMirrored; + } + + /** The frame's size once {@link #getRotationDegrees} has been applied. */ + @NonNull + public Size getUprightSize() { + return TransformMath.rotateSize( + new Size(getWidth(), getHeight()), mRotationDegrees); + } + + /** + * Maps this frame's pixels onto the CameraView showing it. + * + *

Use this to draw over the preview: run the detection in frame coordinates, then map + * the result through this matrix to get view coordinates. It turns the frame upright for + * the device's current orientation and scales it to cover the view, which is what the + * preview itself does with the same frames, so a point on a face lands on that face.

+ * + *

Mirroring is left to the caller. {@link #isMirrored} says whether the frame came from + * a user-facing lens; whether the preview shows it mirrored is up to the backend.

+ * + * @return the mapping, or an identity matrix if the view is not laid out or this stream is + * not attached to one + */ + @NonNull + public Matrix getFrameToViewTransform() { + CameraView view = mCameraView; + if (view == null) { + return new Matrix(); + } + return TransformMath.centerCrop( + new RectF(0f, 0f, getWidth(), getHeight()), + TransformMath.within360(mRotationDegrees - view.getDisplayRotation()), + false /* the caller decides about mirroring */, + view.getWidth(), view.getHeight()); + } + } + + /** The backend's surfaces. */ + private final VideoRecorder.Canvas mCanvas; + + /** The view the frames are being previewed on, for {@link Frame#getFrameToViewTransform}. */ + @Nullable + private final CameraView mCameraView; + + private final Params mParams; + private final Analyzer mAnalyzer; + + /** Whether the background thread should keep pulling frames. */ + private final AtomicBoolean mIsAlive = new AtomicBoolean(); + + /** The thread pulling frames, once started. */ + private final AtomicReference mThread = new AtomicReference<>(); + + FrameStream(@NonNull VideoRecorder.Canvas canvas, @Nullable CameraView cameraView, + @NonNull Params params, @NonNull Analyzer analyzer) { + mCanvas = canvas; + mCameraView = cameraView; + mParams = params; + mAnalyzer = analyzer; + } + + /** Whether frames are being delivered. */ + public boolean isAnalyzing() { + return mIsAlive.get(); + } + + /** Starts delivering frames. Does nothing if already started. */ + @RequiresPermission(Manifest.permission.CAMERA) + public void start() { + if (!mIsAlive.compareAndSet(false, true)) { + Log.w(TAG, "FrameStream is already running"); + return; + } + Thread thread = new Thread(this::pump, "CameraView-FrameAnalysis"); + thread.setDaemon(true); + mThread.set(thread); + thread.start(); + } + + /** Stops delivering frames and waits briefly for the thread to notice. */ + @Override + public void close() { + mIsAlive.set(false); + Thread thread = mThread.getAndSet(null); + if (thread == null || thread == Thread.currentThread()) { + return; + } + thread.interrupt(); + try { + thread.join(300); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } + } + + private void pump() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + setThreadPriority(THREAD_PRIORITY_VIDEO); + } else { + setThreadPriority(THREAD_PRIORITY_DISPLAY); + } + + // The backend decides the frame size, and only tells us when it hands over the surface it + // wants filled - which it cannot do until we have one to give. The two futures pass the + // size out and the surface back in across that handshake. + SettableFuture configuration = SettableFuture.create(); + SettableFuture surface = SettableFuture.create(); + VideoRecorder.SurfaceProvider provider = new VideoRecorder.SurfaceProvider() { + @Override + public Surface getSurface(int width, int height, int orientation, boolean flipped) { + configuration.set(new Configuration(width, height, orientation, flipped)); + try { + return surface.get(SURFACE_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (ExecutionException | InterruptedException | TimeoutException error) { + throw new RuntimeException(error); + } + } + + @Nullable + @Override + public Size getMaxSize() { + return mParams.getMaxSize(); + } + }; + mCanvas.attachSurface(provider); + + ImageReader reader = null; + try { + Configuration frames = Objects.requireNonNull( + configuration.get(SURFACE_TIMEOUT_SECONDS, TimeUnit.SECONDS)); + reader = ImageReader.newInstance(frames.width, frames.height, + mParams.getImageFormat(), BUFFER_COUNT); + surface.set(reader.getSurface()); + + while (mIsAlive.get()) { + Image image = reader.acquireLatestImage(); + if (image == null) { + try { + Thread.sleep(IDLE_POLL_MILLIS); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + break; + } + continue; + } + try { + mAnalyzer.onFrame(new Frame(image, frames.orientation, frames.flipped)); + } catch (RuntimeException error) { + Log.w(TAG, "Frame analysis failed", error); + } finally { + image.close(); + } + } + } catch (ExecutionException | InterruptedException | TimeoutException + | RuntimeException error) { + Log.e(TAG, "Exception with the frame analysis stream", error); + } finally { + mIsAlive.set(false); + mCanvas.detachSurface(provider); + if (reader != null) { + reader.close(); + } + } + } + + /** What the backend reported about the frames it is going to produce. */ + private static final class Configuration { + final int width; + final int height; + final int orientation; + final boolean flipped; + + Configuration(int width, int height, int orientation, boolean flipped) { + this.width = width; + this.height = height; + this.orientation = orientation; + this.flipped = flipped; + } + } +} 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 72075ae..11d90cc 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 @@ -10,24 +10,56 @@ import android.util.Log; import androidx.annotation.RequiresApi; +import androidx.annotation.NonNull; import com.xlythe.view.camera.stream.VideoRecorder; import java.io.File; +import java.util.concurrent.CountDownLatch; +import java.util.List; +import java.util.concurrent.TimeUnit; public abstract class ICameraModule { public static final String TAG = CameraView.TAG; public static final boolean DEBUG = CameraView.DEBUG; + /** Maximum wait for a backend to detach a custom encoder surface on the main thread. */ + private static final long SURFACE_DETACH_TIMEOUT_SECONDS = 2; + /** Owning CameraView used for view state and callbacks. */ private final CameraView mView; + /** Requested image and video quality. */ private CameraView.Quality mQuality = CameraView.Quality.HIGH; + + /** JPEG compression for still captures. See {@link #setPictureQuality}. */ + private int mPictureQuality = DEFAULT_PICTURE_QUALITY; + /** Requested maximum video duration in milliseconds. */ private long mMaxVideoDuration = CameraView.INDEFINITE_VIDEO_DURATION; + /** Requested maximum video size in bytes. */ private long mMaxVideoSize = CameraView.INDEFINITE_VIDEO_SIZE; + /** Requested still-image flash behavior. */ private CameraView.Flash mFlash = CameraView.Flash.AUTO; + /** Requested capture dynamic range. */ + private CameraView.DynamicRange mDynamicRange = CameraView.DynamicRange.SDR; + /** Requested CameraX photo extension. */ + private CameraView.Extension mExtension = CameraView.Extension.NONE; + /** Whether front-camera video output should be mirrored. */ + private boolean mFrontVideoMirroringEnabled = true; + /** Whether preview stabilization is requested. */ + private boolean mPreviewStabilizationEnabled; + /** Whether video stabilization is requested. */ + private boolean mVideoStabilizationEnabled; + /** Requested exposure compensation index. */ + private int mExposureCompensation; + /** Whether continuous torch illumination is requested. */ + private boolean mTorchEnabled; + /** Whether CameraX low-light boost is requested. */ + private boolean mLowLightBoostEnabled; + /** Listener receiving still-image terminal callbacks. */ private CameraView.OnImageCapturedListener mOnImageCapturedListener; + /** Listener receiving video terminal callbacks. */ private CameraView.OnVideoCapturedListener mOnVideoCapturedListener; - // When true, pictures and videos will try to match the aspect ratio of the preview + /** Whether pictures and videos should match the preview aspect ratio. */ private boolean mMatchPreviewAspectRatio = true; public ICameraModule(CameraView view) { @@ -58,6 +90,14 @@ protected void detachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { } + protected boolean startBarcodeScanner( + CameraView.BarcodeDetectorListener listener, + @Barcode.Format int format, + @Barcode.Format int... formats) { + return false; + } + + protected void stopBarcodeScanner() {} @RequiresApi(18) public VideoRecorder.Canvas getCanvas() { return new VideoRecorder.Canvas() { @@ -68,7 +108,26 @@ public void attachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { @Override public void detachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { - new Handler(Looper.getMainLooper()).post(() -> ICameraModule.this.detachSurface(surfaceProvider)); + if (Looper.myLooper() == Looper.getMainLooper()) { + ICameraModule.this.detachSurface(surfaceProvider); + return; + } + CountDownLatch detached = new CountDownLatch(1); + new Handler(Looper.getMainLooper()).post(() -> { + try { + ICameraModule.this.detachSurface(surfaceProvider); + } finally { + detached.countDown(); + } + }); + try { + if (!detached.await(SURFACE_DETACH_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + Log.w(TAG, "Timed out detaching custom camera surface"); + } + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + Log.w(TAG, "Interrupted while detaching custom camera surface", error); + } } }; } @@ -95,11 +154,9 @@ protected void setTransform(Matrix matrix) { /* * Opens the camera and starts displaying a preview. You are in charge of checking if the - * phone has PackageManager.FEATURE_CAMERA_ANY and, if you are targeting Android M+, that - * the phone has the following permissions: - * Manifest.permission.CAMERA - * Manifest.permission.RECORD_AUDIO - * Manifest.permission.WRITE_EXTERNAL_STORAGE + * phone has PackageManager.FEATURE_CAMERA_ANY and, if you are targeting Android M+, that the + * phone has granted Manifest.permission.CAMERA. The microphone belongs to + * startRecording(File), not here. */ public abstract void open(); @@ -153,6 +210,10 @@ public void onVideoFailed() { mView.onVideoFailed(); } + protected void onCameraError(Throwable error) { + mView.onCameraError(error); + } + public abstract void setLensFacing(CameraView.LensFacing lensFacing); public abstract void toggleCamera(); @@ -177,6 +238,25 @@ public void setQuality(CameraView.Quality quality) { mQuality = quality; } + /** The JPEG quality every backend is asked for unless the app says otherwise. */ + public static final int DEFAULT_PICTURE_QUALITY = 95; + + /** + * How hard a still capture is compressed, from 1 to 100. + * + *

Left alone, every backend takes whatever the device chose, which is not the same number + * on any two phones and on some is low enough to show. 95 is where a JPEG stops being + * visibly different from the uncompressed frame while still being a fraction of the size of + * one encoded at 100, and it is what the manufacturers' own apps settle around.

+ */ + public void setPictureQuality(int percent) { + mPictureQuality = Math.max(1, Math.min(percent, 100)); + } + + public int getPictureQuality() { + return mPictureQuality; + } + public CameraView.Quality getQuality() { return mQuality; } @@ -205,6 +285,175 @@ public CameraView.Flash getFlash() { return mFlash; } + public synchronized void setDynamicRange(CameraView.DynamicRange dynamicRange) { + if (dynamicRange == null) throw new NullPointerException("dynamicRange cannot be null"); + mDynamicRange = dynamicRange; + } + + public synchronized CameraView.DynamicRange getDynamicRange() { + return mDynamicRange; + } + + public synchronized boolean isDynamicRangeSupported(CameraView.DynamicRange dynamicRange) { + return dynamicRange == CameraView.DynamicRange.SDR; + } + + public synchronized void setExtension(CameraView.Extension extension) { + if (extension == null) throw new NullPointerException("extension cannot be null"); + mExtension = extension; + } + + public synchronized CameraView.Extension getExtension() { + return mExtension; + } + + public synchronized boolean isExtensionSupported(CameraView.Extension extension) { + return extension == CameraView.Extension.NONE; + } + public synchronized void setFrontVideoMirroringEnabled(boolean enabled) { + mFrontVideoMirroringEnabled = enabled; + } + + public synchronized boolean isFrontVideoMirroringEnabled() { + return mFrontVideoMirroringEnabled; + } + + public synchronized void setPreviewStabilizationEnabled(boolean enabled) { + mPreviewStabilizationEnabled = enabled; + } + + public synchronized boolean isPreviewStabilizationEnabled() { + return mPreviewStabilizationEnabled; + } + + public synchronized boolean isPreviewStabilizationSupported() { + return false; + } + + public synchronized void setVideoStabilizationEnabled(boolean enabled) { + mVideoStabilizationEnabled = enabled; + } + + public synchronized boolean isVideoStabilizationEnabled() { + return mVideoStabilizationEnabled; + } + + public synchronized boolean isVideoStabilizationSupported() { + return false; + } + + public synchronized void setExposureCompensation(int exposureCompensation) { + mExposureCompensation = exposureCompensation; + } + + public synchronized int getExposureCompensation() { + return mExposureCompensation; + } + + public synchronized int getMinExposureCompensation() { + return 0; + } + + public synchronized int getMaxExposureCompensation() { + return 0; + } + + public synchronized boolean isExposureCompensationSupported() { + return false; + } + + public synchronized void setTorchEnabled(boolean enabled) { + mTorchEnabled = enabled; + } + + public synchronized boolean isTorchEnabled() { + return mTorchEnabled; + } + + public synchronized void setLowLightBoostEnabled(boolean enabled) { + mLowLightBoostEnabled = enabled; + } + + public synchronized boolean isLowLightBoostEnabled() { + return mLowLightBoostEnabled; + } + + public synchronized boolean isLowLightBoostSupported() { + return false; + } + + /** The colour range pictures are recorded in. See {@link CameraView.ColorSpace}. */ + private CameraView.ColorSpace mColorSpace = CameraView.ColorSpace.SRGB; + + /** + * Whether this camera can record in a given colour range. + * + *

sRGB is always supported, because it is what a camera that has never heard of colour + * spaces produces.

+ */ + public boolean isColorSpaceSupported(CameraView.ColorSpace colorSpace) { + return colorSpace == CameraView.ColorSpace.SRGB; + } + + public void setColorSpace(CameraView.ColorSpace colorSpace) { + if (!isColorSpaceSupported(colorSpace)) { + Log.w(TAG, "This camera cannot record in " + colorSpace); + return; + } + mColorSpace = colorSpace; + } + + public CameraView.ColorSpace getColorSpace() { + return mColorSpace; + } + + /** + * Whether a picture can be taken while a recording is running. + * + *

Not every camera can hold a preview, a recording and a still at once; a LEGACY camera2 + * device guarantees nothing of the sort. Where it cannot, recording keeps working and the + * picture is refused rather than the whole session being lost.

+ */ + public boolean isSnapshotWhileRecordingSupported() { + return false; + } + + /** Whether this camera can report the faces it is already tracking. */ + public boolean isFaceDetectionSupported() { + return false; + } + + /** + * Asks the backend to start or stop reporting faces. + * + * @return whether the backend is now in the requested state. A backend with no face detection + * refuses to start, which CameraView reports to the caller rather than leaving a listener + * that never fires; stopping always succeeds. + */ + protected boolean setFaceDetectionEnabled(boolean enabled) { + return !enabled; + } + + /** + * Reports the faces the camera is tracking. + * + * @param faceToView maps a face's bounds onto the view, since the camera's coordinates are + * neither the view's nor the same across backends + */ + protected final void onFacesDetected( + @NonNull List faces, @NonNull Matrix faceToView) { + // Backends read faces on whichever thread the camera delivers results on, and the + // listener is documented as arriving on the main one. Posting through a Handler rather + // than View.post matters: a detached View queues its runnables until it is attached + // again, which for a camera that is closing means never. + if (Looper.myLooper() == Looper.getMainLooper()) { + getView().onFacesDetected(faces, faceToView); + return; + } + new Handler(Looper.getMainLooper()).post( + () -> getView().onFacesDetected(faces, faceToView)); + } + public boolean hasFlash() { return false; } 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 new file mode 100644 index 0000000..72d230a --- /dev/null +++ b/camera-view/src/main/java/com/xlythe/view/camera/TransformMath.java @@ -0,0 +1,115 @@ +package com.xlythe.view.camera; + +import android.graphics.Matrix; +import android.graphics.RectF; +import android.util.Size; + +import androidx.annotation.NonNull; +import androidx.annotation.RestrictTo; + +/** + * The center-crop mapping every consumer of a camera buffer in this library shares. + * + *

A camera hands out buffers in sensor orientation at whatever aspect ratio it was asked for, + * which is rarely the shape of the view showing them. Everything that draws or measures against + * those buffers - the preview, a video stream being played back, and anything analysing frames - + * needs the same answer: where does a pixel of the buffer land in the view, once the buffer has + * been turned upright, mirrored if the lens faces the user, and scaled up until it covers the view + * without being distorted.

+ * + *

Keeping that in one place matters because the mapping is easy to get subtly wrong and hard to + * notice: a preview that is rotated twice, or stretched by the difference between two aspect + * ratios, still looks like a camera.

+ */ +@RestrictTo(RestrictTo.Scope.LIBRARY) +public final class TransformMath { + private TransformMath() {} + + /** Normalizes any rotation, including negative ones, into [0, 360). */ + public static int within360(int rotationDegrees) { + return ((rotationDegrees % 360) + 360) % 360; + } + + /** Swaps a size's dimensions for the quarter turns that transpose them. */ + @NonNull + public static Size rotateSize(@NonNull Size size, int rotationDegrees) { + int rotation = within360(rotationDegrees); + return rotation == 90 || rotation == 270 + ? new Size(size.getHeight(), size.getWidth()) + : size; + } + + /** + * Maps a region of a camera buffer onto a view, upright and filling it. + * + *

The region is rotated by {@code rotationDegrees}, flipped horizontally when + * {@code mirrored}, then scaled by the larger of the two axis ratios so the view is covered + * and the overflow is split evenly on both sides. Pixels outside the view are the crop.

+ * + * @param crop the region of the buffer to show, in buffer pixels + * @return the mapping, or an identity matrix when the crop or the view is empty + */ + @NonNull + public static Matrix centerCrop( + @NonNull RectF crop, int rotationDegrees, boolean mirrored, + int viewWidth, int viewHeight) { + Matrix bufferToView = new Matrix(); + if (crop.isEmpty() || viewWidth <= 0 || viewHeight <= 0) { + return bufferToView; + } + + bufferToView.postTranslate(-crop.centerX(), -crop.centerY()); + bufferToView.postRotate(rotationDegrees); + if (mirrored) { + bufferToView.postScale(-1f, 1f); + } + + // The crop is now centered on the origin, so this rectangle is the crop's size after + // rotation: the shape that has to be made to cover the view. + RectF oriented = new RectF(crop); + bufferToView.mapRect(oriented); + bufferToView.postTranslate(-oriented.left, -oriented.top); + + float scale = Math.max(viewWidth / oriented.width(), viewHeight / oriented.height()); + bufferToView.postScale(scale, scale); + bufferToView.postTranslate( + (viewWidth - oriented.width() * scale) / 2f, + (viewHeight - oriented.height() * scale) / 2f); + return bufferToView; + } + + /** + * Re-expresses a buffer-to-view mapping as a TextureView transform. + * + *

A TextureView has already stretched the whole buffer over its own bounds by the time its + * transform is applied, so a transform is relative to that stretch rather than to the buffer. + * Undoing the stretch first turns a mapping stated in buffer pixels into one TextureView can + * use.

+ * + * @return the transform, or an identity matrix when the buffer or the view is empty + */ + @NonNull + public static Matrix asTextureTransform( + @NonNull Matrix bufferToView, @NonNull Size bufferSize, + int viewWidth, int viewHeight) { + Matrix identity = new Matrix(); + if (bufferSize.getWidth() <= 0 || bufferSize.getHeight() <= 0 + || viewWidth <= 0 || viewHeight <= 0) { + return identity; + } + + Matrix defaultBufferToView = new Matrix(); + defaultBufferToView.setRectToRect( + new RectF(0f, 0f, bufferSize.getWidth(), bufferSize.getHeight()), + new RectF(0f, 0f, viewWidth, viewHeight), + Matrix.ScaleToFit.FILL); + Matrix viewToBuffer = new Matrix(); + if (!defaultBufferToView.invert(viewToBuffer)) { + return identity; + } + + Matrix textureTransform = new Matrix(); + textureTransform.setConcat(bufferToView, viewToBuffer); + return textureTransform; + } +} diff --git a/camera-view/src/main/res/values/attrs.xml b/camera-view/src/main/res/values/attrs.xml index 9293d85..119074d 100644 --- a/camera-view/src/main/res/values/attrs.xml +++ b/camera-view/src/main/res/values/attrs.xml @@ -1,6 +1,12 @@ + + + + + + @@ -22,6 +28,24 @@ + + + + + + + + + + + + + + + + + + From 2bde4b6c881282f161d315261928be66fae4f525 Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 01:18:45 -0500 Subject: [PATCH 03/10] Make all three camera backends work * fix: harden the Camera2 backend and widen what it can do The production backend, and where most of this library's behaviour comes from. Lifecycle and failures: a session that cannot be configured no longer leaves the camera half-open, a lens switch reopens the device directly rather than racing its own release, and a recording that hits its duration or size limit is delivered rather than dropped. A capture that never reached disk is reported as a failure instead of silently succeeding. The flash is driven through CONTROL_AE_MODE, which is the only thing Camera2 reads, and the repeating request is reissued so auto-exposure can converge under it before the next still. What it can do now: zoom runs across every physical lens the camera has, through CONTROL_ZOOM_RATIO where the device offers it, so a high ratio reaches a telephoto rather than digitally cropping; the preview size is probed from the camera instead of a hardcoded ceiling; a built-in sensor is preferred over an external or virtual one; STATISTICS_FACE_DETECT_MODE carries face detection on the repeating request; a wide colour space is named through the session where the platform has one; and a recording session carries a still output sized to the recording, which is the combination Camera2 guarantees from LIMITED hardware up - LEGACY records without one rather than risking a session it cannot configure. The recorded bit rate is also scaled to the frame actually being recorded. setProfile fixes it to the profile's own resolution while the size is chosen separately, so a smaller frame was being written at a wastefully high rate and a larger one starved. * fix: make the CameraX backend work, starting with the preview It double-rotated the preview. CameraX publishes whether the stream it hands over already carries the camera's own rotation and mirror - hasCameraTransform - and the transform ignored it, so on the path where the camera writes straight into the SurfaceTexture the rotation was applied twice. That is the same split androidx.camera.view performs internally, and it is performed here now. The rest is the pipeline around it: the media operations are serialized so a capture and a recording cannot interleave, a recording is timed from the Start event rather than from the request, the surface handshake with a custom stream is bounded instead of waiting forever, the lifecycle is retired when its host is destroyed, and every capability query is guarded individually - one of them threw out of a callback and took the whole bind down with it, which is why the backend never appeared to work at all. What it can do now: the optional controls it supports are exposed rather than silently ignored, a still output is bound alongside a recording so a picture can be taken while recording, face detection goes through camera2 interop to the request the pipeline was going to issue anyway, and a barcode client that cannot be built is reported through the return value instead of throwing out of a posted task. * fix: stop the legacy backend crashing, and clamp its zoom The backend kept for devices below the Camera2 floor, and the least guarded of the three. takePicture and startRecording before the camera opened both threw a NullPointerException straight at the caller. Nothing holds an app to the camera's lifecycle - a shutter button is pressed when it is pressed - so both are states an app reaches rather than programming errors, and both report through the failure callback the caller is already listening to now, as Camera2 has always done. Closing while recording released the camera from under the recorder, leaving an encoder writing to a file nothing would finish and isRecording() answering yes for a camera that no longer existed. Zoom was not clamped at all, and the level, maximum and support queries all threw before open(). It is scaled onto the same 0-100 range the other backends use, so a caller does not have to know which backend it is talking to. A recording that hits its limit is delivered rather than dropped, and face detection is reported through the platform's own listener. Co-Authored-By: Claude Opus 5 --- .../camera/legacy/LegacyCameraModule.java | 1127 +++---- .../xlythe/view/camera/v2/Camera2Module.java | 2494 ++++++++++------ .../xlythe/view/camera/v2/PictureSession.java | 114 +- .../xlythe/view/camera/v2/PreviewSession.java | 17 +- .../xlythe/view/camera/v2/SessionImpl.java | 121 + .../xlythe/view/camera/v2/StreamSession.java | 64 +- .../xlythe/view/camera/v2/VideoSession.java | 160 +- .../com/xlythe/view/camera/x/CameraXMath.java | 162 + .../xlythe/view/camera/x/CameraXModule.java | 2594 ++++++++++++----- 9 files changed, 4590 insertions(+), 2263 deletions(-) create mode 100644 camera-view/src/main/java/com/xlythe/view/camera/x/CameraXMath.java 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 004b2de..a0c6fe1 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 @@ -1,492 +1,635 @@ -package com.xlythe.view.camera.legacy; - -import android.Manifest; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.ImageFormat; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Rect; -import android.graphics.YuvImage; -import android.hardware.Camera; -import android.location.Location; -import android.media.CamcorderProfile; -import android.media.MediaRecorder; -import android.os.Build; -import android.util.Log; - -import com.xlythe.view.camera.CameraView; -import com.xlythe.view.camera.ICameraModule; -import com.xlythe.view.camera.LocationProvider; -import com.xlythe.view.camera.PermissionChecker; -import com.xlythe.view.camera.stream.VideoRecorder; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Map; - -import androidx.annotation.Nullable; -import androidx.annotation.RequiresApi; -import androidx.annotation.RestrictTo; -import androidx.collection.ArrayMap; - -@RestrictTo(RestrictTo.Scope.LIBRARY) -public class LegacyCameraModule extends ICameraModule { - private static final int INVALID_CAMERA_ID = -1; - - private static final long STALE_LOCATION_MILLIS = 2 * 60 * 60 * 1000; - private static final long GPS_TIMEOUT_MILLIS = 10; - - private int mActiveCamera = INVALID_CAMERA_ID; - private Camera mCamera; - @Nullable private Camera.Size mPreviewSize; - - private MediaRecorder mVideoRecorder; - private File mVideoFile; - - private final Map mSurfaceProviders = new ArrayMap<>(); - - public LegacyCameraModule(CameraView view) { - super(view); - } - - @Override - public void open() { - Log.d(TAG, "onOpen() activeCamera="+getActiveCamera()); - try { - mCamera = Camera.open(getActiveCamera()); - } catch (RuntimeException e) { - Log.e(TAG, "Failed to open camera", e); - return; - } - - try { - mCamera.setPreviewTexture(getSurfaceTexture()); - - Camera.Parameters parameters = mCamera.getParameters(); - int cameraOrientation = getRelativeCameraOrientation(); - mCamera.setDisplayOrientation(cameraOrientation); - mPreviewSize = chooseOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), getWidth(), getHeight()); - parameters.setPreviewSize(getPreviewWidth(), getPreviewHeight()); - parameters.setPictureFormat(ImageFormat.JPEG); - mCamera.setParameters(parameters); - transformPreview(getWidth(), getHeight(), getPreviewWidth(), getPreviewHeight(), cameraOrientation); - - mCamera.startPreview(); - } catch (IOException e) { - Log.e(TAG, "Failed to properly initialize camera", e); - } - } - - @Override - public void close() { - Log.d(TAG, "onClose() activeCamera="+getActiveCamera()); - if (mCamera != null) { - mCamera.stopPreview(); - mCamera.release(); - mCamera = null; - mPreviewSize = null; - } - } - - @Override - public void onLayoutChanged() { - if (mPreviewSize == null) { - return; - } - - int cameraOrientation = getRelativeCameraOrientation(); - transformPreview(getWidth(), getHeight(), getPreviewWidth(), getPreviewHeight(), cameraOrientation); - } - - private void transformPreview(int viewWidth, int viewHeight, int previewWidth, int previewHeight, int cameraOrientation) { - if (DEBUG) { - Log.d(TAG, String.format("Configuring SurfaceView matrix: " - + "viewWidth=%s, viewHeight=%s, previewWidth=%s, previewHeight=%s, cameraOrientation=%s", - viewWidth, viewHeight, previewWidth, previewHeight, cameraOrientation)); - } - - Matrix matrix = new Matrix(); - - // Because the camera already rotates the preview for us (@see Camera.setDisplayOrientation(int)}, - // we need to flip the width/height to the dimensions we'll actually be given. - if (cameraOrientation == 90 || cameraOrientation == 270) { - int temp = previewWidth; - previewWidth = previewHeight; - previewHeight = temp; - } - - // We want to maintain aspect ratio, but we also want both sides to be >= the view's width and height. - // Otherwise, there will be blank space around our preview. - double aspectRatio = (double) previewHeight / (double) previewWidth; - int newWidth, newHeight; - if (getHeight() > viewWidth * aspectRatio) { - newWidth = (int) (viewHeight / aspectRatio); - newHeight = viewHeight; - } else { - newWidth = viewWidth; - newHeight = (int) (viewWidth * aspectRatio); - } - - // We scale the image up so that it definitely fits (or overflows) our bounds - matrix.setScale((float) newWidth / (float) viewWidth, (float) newHeight / (float) viewHeight); - - // And then we reposition it so that it's centered - matrix.postTranslate((viewWidth - newWidth) / 2f, (viewHeight - newHeight) / 2f); - - // And once we're done, we apply our changes. - setTransform(matrix); - } - - @Override - public void takePicture(File file) { - mCamera.takePicture(null, null, new LegacyPictureListener( - file, getRelativeCameraOrientation(false /* isPreview */), isUsingFrontFacingCamera(), this)); - } - - @Override - public void startRecording(File file) { - mVideoFile = file; - mVideoRecorder = new MediaRecorder(); - - mCamera.unlock(); - mVideoRecorder.setCamera(mCamera); - - mVideoRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); - mVideoRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); - switch (getQuality()) { - case MAX: - if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_HIGH)) { - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); - break; - } - // Fall-through - case HIGH: - if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_1080P)) { - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P)); - break; - } - // Fall-through - case MEDIUM: - if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_720P)) { - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P)); - break; - } - // Fall-through - case LOW: - if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_480P)) { - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P)); - break; - } - // Fall-through - default: - mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW)); - break; - } - mVideoRecorder.setOutputFile(file.getAbsolutePath()); - mVideoRecorder.setMaxDuration((int) getMaxVideoDuration()); - mVideoRecorder.setMaxFileSize(getMaxVideoSize()); - mVideoRecorder.setMaxDuration((int) getMaxVideoDuration()); - mVideoRecorder.setMaxFileSize(getMaxVideoSize()); - mVideoRecorder.setOrientationHint(getRelativeCameraOrientation(false /* isPreview */)); - mVideoRecorder.setOnInfoListener((mr, what, extra) -> { - switch (what) { - case MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED: - Log.w(TAG, "Max duration for recording reached"); - break; - case MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED: - Log.w(TAG, "Max filesize for recording reached"); - break; - } - }); - - Location location = getLocation(getContext()); - if (location != null) { - mVideoRecorder.setLocation((float) location.getLatitude(), (float) location.getLongitude()); - } - - try { - mVideoRecorder.prepare(); - mVideoRecorder.start(); - } catch (IOException | RuntimeException e) { - e.printStackTrace(); - mVideoRecorder = null; - onVideoFailed(); - } - } - - @Override - public void stopRecording() { - if (mVideoRecorder != null) { - try { - mVideoRecorder.stop(); - showVideoConfirmation(mVideoFile); - } catch (RuntimeException e) { - Log.e(TAG, "Failed to stop video recorder. This can happen if a video is stopped too quickly. :(", e); - onVideoFailed(); - } - mVideoRecorder = null; - } else { - onVideoFailed(); - } - } - - @Override - public boolean isRecording() { - return mVideoRecorder != null; - } - - @Override - public void focus(Rect focus, Rect metering) { - if (DEBUG) { - Log.d(TAG, String.format("Focus: focus=%s, metering=%s", focus, metering)); - } - if (mCamera != null) { - mCamera.cancelAutoFocus(); - - Camera.Parameters parameters = mCamera.getParameters(); - if (!parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO)) { - Log.w(TAG, "Focus not available on this camera"); - return; - } - - parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); - - if (parameters.getMaxNumFocusAreas() > 0) { - parameters.setFocusAreas(Collections.singletonList(new Camera.Area(focus, 1000))); - } - - if (parameters.getMaxNumMeteringAreas() > 0) { - parameters.setMeteringAreas(Collections.singletonList(new Camera.Area(metering, 1000))); - } - - mCamera.setParameters(parameters); - mCamera.autoFocus((success, camera) -> { - if (DEBUG) { - Log.d(TAG, "AutoFocus: " + success); - } - }); - } else { - Log.w(TAG, "Attempted to set focus but no camera found"); - } - } - - @Override - public void setZoomLevel(int zoomLevel) { - if (mCamera != null) { - Camera.Parameters parameters = mCamera.getParameters(); - parameters.setZoom(zoomLevel); - mCamera.setParameters(parameters); - } else { - Log.w(TAG, "Attempted to set zoom level to " + zoomLevel + " but no camera found"); - } - } - - @Override - public int getZoomLevel() { - return mCamera.getParameters().getZoom(); - } - - @Override - public int getMaxZoomLevel() { - return mCamera.getParameters().getMaxZoom(); - } - - @Override - public boolean isZoomSupported() { - return mCamera.getParameters().isZoomSupported(); - } - - @Override - public void toggleCamera() { - boolean shouldOpen = getView().isOpen(); - close(); - mActiveCamera = (mActiveCamera + 1) % Camera.getNumberOfCameras(); - if (shouldOpen) { - open(); - } - } - - @Override - public void setLensFacing(CameraView.LensFacing lensFacing) { - boolean shouldOpen = getView().isOpen(); - close(); - - // Search for the properly facing camera - int numberOfCameras = Camera.getNumberOfCameras(); - for (int i = 0; i < numberOfCameras; i++) { - Camera.CameraInfo info = new Camera.CameraInfo(); - Camera.getCameraInfo(i, info); - if ((info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT && lensFacing.equals(CameraView.LensFacing.FRONT)) - || (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK && lensFacing.equals(CameraView.LensFacing.BACK))) { - mActiveCamera = i; - break; - } - } - - if (shouldOpen) { - open(); - } - } - - @Override - public boolean hasFrontFacingCamera() { - // Search for the front facing camera - int numberOfCameras = Camera.getNumberOfCameras(); - for (int i = 0; i < numberOfCameras; i++) { - Camera.CameraInfo info = new Camera.CameraInfo(); - Camera.getCameraInfo(i, info); - if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { - return true; - } - } - return false; - } - - @Override - public boolean isUsingFrontFacingCamera() { - Camera.CameraInfo info = new Camera.CameraInfo(); - Camera.getCameraInfo(getActiveCamera(), info); - return info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT; - } - - @Override - protected int getRelativeCameraOrientation() { - return getRelativeCameraOrientation(true /* isPreview */); - } - - @RequiresApi(18) - @Override - protected void attachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { - if (mCamera != null && mPreviewSize != null) { - LegacySurfaceHolder surfaceHolder = new LegacySurfaceHolder(getContext(), surfaceProvider, mPreviewSize.width, mPreviewSize.height, getSensorOrientation(), isUsingFrontFacingCamera()); - mSurfaceProviders.put(surfaceProvider, surfaceHolder); - mCamera.setPreviewCallback((data, camera) -> { - Canvas canvas = surfaceHolder.lockCanvas(); - canvas.drawBitmap(toBitmap(data, camera), new Matrix(), new Paint()); - surfaceHolder.unlockCanvasAndPost(canvas); - }); - } - } - - @RequiresApi(18) - @Override - protected void detachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { - LegacySurfaceHolder surfaceHolder = mSurfaceProviders.remove(surfaceProvider); - if (surfaceHolder != null) { - surfaceHolder.close(); - mCamera.setPreviewCallback(null); - } - } - - private Bitmap toBitmap(byte[] data, Camera camera) { - Camera.Parameters parameters = camera.getParameters(); - int width = parameters.getPreviewSize().width; - int height = parameters.getPreviewSize().height; - - YuvImage yuv = new YuvImage(data, parameters.getPreviewFormat(), width, height, null); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - yuv.compressToJpeg(new Rect(0, 0, width, height), 50, out); - - byte[] bytes = out.toByteArray(); - return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); - } - - private int getRelativeCameraOrientation(boolean isPreview) { - return getRelativeImageOrientation(getDisplayRotation(), getSensorOrientation(), isUsingFrontFacingCamera(), isPreview); - } - - private int getSensorOrientation() { - Camera.CameraInfo info = new Camera.CameraInfo(); - Camera.getCameraInfo(getActiveCamera(), info); - return info.orientation; - } - - private int getActiveCamera() { - if (mActiveCamera != INVALID_CAMERA_ID) { - return mActiveCamera; - } - - int numberOfCameras = Camera.getNumberOfCameras(); - if (numberOfCameras == 0) { - return INVALID_CAMERA_ID; - } - - for (int i = 0; i < numberOfCameras; i++) { - Camera.CameraInfo info = new Camera.CameraInfo(); - Camera.getCameraInfo(i, info); - if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { - mActiveCamera = i; - return mActiveCamera; - } - } - - mActiveCamera = 0; - return mActiveCamera; - } - - private int getPreviewWidth() { - if (mPreviewSize == null) { - return 0; - } - - return mPreviewSize.width; - } - - private int getPreviewHeight() { - if (mPreviewSize == null) { - return 0; - } - - return mPreviewSize.height; - } - - private static Camera.Size chooseOptimalPreviewSize(List choices, int width, int height) { - if (DEBUG) { - Log.d(TAG, String.format("Initializing PreviewSurface with width=%s and height=%s", width, height)); - } - // Collect the supported resolutions that are at least as big as the preview Surface - List bigEnough = new ArrayList<>(); - for (Camera.Size option : choices) { - if (option.width >= width && option.height >= height) { - bigEnough.add(option); - } - } - - // Pick the smallest of those, assuming we found any - if (bigEnough.size() > 0) { - return Collections.min(bigEnough, new CompareSizesByArea()); - } else { - Log.e(TAG, "Couldn't find any suitable preview size"); - return choices.get(0); - } - } - - private static class CompareSizesByArea implements Comparator { - @Override - public int compare(Camera.Size lhs, Camera.Size rhs) { - // We cast here to ensure the multiplications won't overflow - return Long.signum((long) lhs.width * lhs.height - - (long) rhs.width * rhs.height); - } - } - - @SuppressWarnings({"MissingPermission"}) - @Nullable - static Location getLocation(Context context) { - if (PermissionChecker.hasPermissions(context, Manifest.permission.ACCESS_FINE_LOCATION)) { - // Our GPS timeout is purposefully low. We're not intending to wait until GPS is acquired - // but we want a last known location for the next time a picture is taken. - return LocationProvider.getGPSLocation(context, STALE_LOCATION_MILLIS, GPS_TIMEOUT_MILLIS); - } - return null; - } -} +package com.xlythe.view.camera.legacy; + +import android.Manifest; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Canvas; +import android.graphics.ImageFormat; +import android.graphics.Matrix; +import android.graphics.Paint; +import android.graphics.Rect; +import android.graphics.RectF; +import android.graphics.YuvImage; +import android.hardware.Camera; +import android.location.Location; +import android.media.CamcorderProfile; +import android.media.MediaRecorder; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import com.xlythe.view.camera.CameraView; +import com.xlythe.view.camera.Face; +import com.xlythe.view.camera.ICameraModule; +import com.xlythe.view.camera.LocationProvider; +import com.xlythe.view.camera.PermissionChecker; +import com.xlythe.view.camera.TransformMath; +import com.xlythe.view.camera.stream.VideoRecorder; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; +import androidx.annotation.RestrictTo; +import androidx.collection.ArrayMap; + +@RestrictTo(RestrictTo.Scope.LIBRARY) +public class LegacyCameraModule extends ICameraModule { + private static final int INVALID_CAMERA_ID = -1; + + /** The zoom scale CameraView publishes, matching the Camera2 and CameraX backends. */ + private static final int MAX_ZOOM_LEVEL = 100; + + private static final long STALE_LOCATION_MILLIS = 2 * 60 * 60 * 1000; + private static final long GPS_TIMEOUT_MILLIS = 10; + + private int mActiveCamera = INVALID_CAMERA_ID; + private Camera mCamera; + @Nullable private Camera.Size mPreviewSize; + + private MediaRecorder mVideoRecorder; + private File mVideoFile; + + private final Map mSurfaceProviders = new ArrayMap<>(); + + public LegacyCameraModule(CameraView view) { + super(view); + } + + @Override + public void open() { + Log.d(TAG, "onOpen() activeCamera="+getActiveCamera()); + try { + mCamera = Camera.open(getActiveCamera()); + } catch (RuntimeException e) { + Log.e(TAG, "Failed to open camera", e); + return; + } + + try { + mCamera.setPreviewTexture(getSurfaceTexture()); + + Camera.Parameters parameters = mCamera.getParameters(); + int cameraOrientation = getRelativeCameraOrientation(); + mCamera.setDisplayOrientation(cameraOrientation); + mPreviewSize = chooseOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), getWidth(), getHeight()); + parameters.setPreviewSize(getPreviewWidth(), getPreviewHeight()); + parameters.setPictureFormat(ImageFormat.JPEG); + parameters.setJpegQuality(getPictureQuality()); + mCamera.setParameters(parameters); + transformPreview(getWidth(), getHeight(), getPreviewWidth(), getPreviewHeight(), cameraOrientation); + + mCamera.startPreview(); + } catch (IOException e) { + Log.e(TAG, "Failed to properly initialize camera", e); + } + } + + @Override + public void close() { + Log.d(TAG, "onClose() activeCamera="+getActiveCamera()); + if (isRecording()) { + // The recorder holds the camera, so releasing the camera under a running recording + // leaves an encoder writing to a file nothing will ever finish, and isRecording() + // answering yes for a camera that no longer exists. + stopRecording(); + } + if (mCamera != null) { + mCamera.stopPreview(); + mCamera.release(); + mCamera = null; + mPreviewSize = null; + } + } + + @Override + public void onLayoutChanged() { + if (mPreviewSize == null) { + return; + } + + int cameraOrientation = getRelativeCameraOrientation(); + transformPreview(getWidth(), getHeight(), getPreviewWidth(), getPreviewHeight(), cameraOrientation); + } + + private void transformPreview(int viewWidth, int viewHeight, int previewWidth, int previewHeight, int cameraOrientation) { + if (DEBUG) { + Log.d(TAG, String.format("Configuring SurfaceView matrix: " + + "viewWidth=%s, viewHeight=%s, previewWidth=%s, previewHeight=%s, cameraOrientation=%s", + viewWidth, viewHeight, previewWidth, previewHeight, cameraOrientation)); + } + + Matrix matrix = new Matrix(); + + // Because the camera already rotates the preview for us (@see Camera.setDisplayOrientation(int)}, + // we need to flip the width/height to the dimensions we'll actually be given. + if (cameraOrientation == 90 || cameraOrientation == 270) { + int temp = previewWidth; + previewWidth = previewHeight; + previewHeight = temp; + } + + // We want to maintain aspect ratio, but we also want both sides to be >= the view's width and height. + // Otherwise, there will be blank space around our preview. + double aspectRatio = (double) previewHeight / (double) previewWidth; + int newWidth, newHeight; + if (getHeight() > viewWidth * aspectRatio) { + newWidth = (int) (viewHeight / aspectRatio); + newHeight = viewHeight; + } else { + newWidth = viewWidth; + newHeight = (int) (viewWidth * aspectRatio); + } + + // We scale the image up so that it definitely fits (or overflows) our bounds + matrix.setScale((float) newWidth / (float) viewWidth, (float) newHeight / (float) viewHeight); + + // And then we reposition it so that it's centered + matrix.postTranslate((viewWidth - newWidth) / 2f, (viewHeight - newHeight) / 2f); + + // And once we're done, we apply our changes. + setTransform(matrix); + } + + @Override + public void takePicture(File file) { + if (mCamera == null) { + // Nothing is holding a caller to the camera's lifecycle - a button is pressed when it + // is pressed - so this is a state an app reaches rather than a programming error, and + // the answer is the failure callback it is already listening to. + Log.w(TAG, "Cannot take a picture before the camera is open"); + onImageFailed(); + return; + } + mCamera.takePicture(null, null, new LegacyPictureListener( + file, getRelativeCameraOrientation(false /* isPreview */), isUsingFrontFacingCamera(), this)); + } + + @Override + public void startRecording(File file) { + if (mCamera == null) { + Log.w(TAG, "Cannot record before the camera is open"); + onVideoFailed(); + return; + } + mVideoFile = file; + mVideoRecorder = new MediaRecorder(); + + mCamera.unlock(); + mVideoRecorder.setCamera(mCamera); + + mVideoRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); + mVideoRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); + switch (getQuality()) { + case MAX: + if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_HIGH)) { + mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); + break; + } + // Fall-through + case HIGH: + if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_1080P)) { + mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P)); + break; + } + // Fall-through + case MEDIUM: + if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_720P)) { + mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P)); + break; + } + // Fall-through + case LOW: + if (CamcorderProfile.hasProfile(mActiveCamera, CamcorderProfile.QUALITY_480P)) { + mVideoRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P)); + break; + } + // Fall-through + default: + mVideoRecorder.setProfile(CamcorderProfile.get(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) -> { + switch (what) { + case MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED: + Log.w(TAG, "Max duration for recording reached"); + finishLimitedRecording(); + break; + case MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED: + Log.w(TAG, "Max filesize for recording reached"); + finishLimitedRecording(); + break; + } + }); + + Location location = getLocation(getContext()); + if (location != null) { + mVideoRecorder.setLocation((float) location.getLatitude(), (float) location.getLongitude()); + } + + try { + mVideoRecorder.prepare(); + mVideoRecorder.start(); + } catch (IOException | RuntimeException e) { + e.printStackTrace(); + mVideoRecorder = null; + onVideoFailed(); + } + } + + /** + * Delivers a recording MediaRecorder ended on its own at a duration or size limit. + * + *

Capturing has already stopped by this point, but the file is only finalized by stop(), + * so finish it the way an explicit stopRecording() would. Posted because the callback arrives + * on MediaRecorder's own thread.

+ */ + private void finishLimitedRecording() { + new Handler(Looper.getMainLooper()).post(() -> { + if (isRecording()) { + stopRecording(); + } + }); + } + + @Override + public void stopRecording() { + if (mVideoRecorder != null) { + try { + mVideoRecorder.stop(); + showVideoConfirmation(mVideoFile); + } catch (RuntimeException e) { + Log.e(TAG, "Failed to stop video recorder. This can happen if a video is stopped too quickly. :(", e); + onVideoFailed(); + } + mVideoRecorder = null; + } else { + onVideoFailed(); + } + } + + @Override + public boolean isRecording() { + return mVideoRecorder != null; + } + + @Override + public void focus(Rect focus, Rect metering) { + if (DEBUG) { + Log.d(TAG, String.format("Focus: focus=%s, metering=%s", focus, metering)); + } + if (mCamera != null) { + mCamera.cancelAutoFocus(); + + Camera.Parameters parameters = mCamera.getParameters(); + if (!parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO)) { + Log.w(TAG, "Focus not available on this camera"); + return; + } + + parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); + + if (parameters.getMaxNumFocusAreas() > 0) { + parameters.setFocusAreas(Collections.singletonList(new Camera.Area(focus, 1000))); + } + + if (parameters.getMaxNumMeteringAreas() > 0) { + parameters.setMeteringAreas(Collections.singletonList(new Camera.Area(metering, 1000))); + } + + mCamera.setParameters(parameters); + mCamera.autoFocus((success, camera) -> { + if (DEBUG) { + Log.d(TAG, "AutoFocus: " + success); + } + }); + } else { + Log.w(TAG, "Attempted to set focus but no camera found"); + } + } + + @Override + public void setZoomLevel(int zoomLevel) { + if (mCamera == null) { + Log.w(TAG, "Attempted to set zoom level to " + zoomLevel + " but no camera found"); + return; + } + Camera.Parameters parameters = mCamera.getParameters(); + if (!parameters.isZoomSupported()) { + Log.w(TAG, "Zoom not supported"); + return; + } + // The level is a position in the camera's range, as it is on the other backends, while + // this API takes an index into the camera's own zoom table. Passing the level straight + // through meant the scale differed per device and an out-of-range value reached the + // camera unchecked. + parameters.setZoom(toZoomIndex(zoomLevel, parameters.getMaxZoom())); + mCamera.setParameters(parameters); + } + + /** Maps a 0..MAX_ZOOM_LEVEL position onto an index into the camera's zoom table. */ + static int toZoomIndex(int zoomLevel, int maxZoomIndex) { + int clamped = Math.max(0, Math.min(zoomLevel, MAX_ZOOM_LEVEL)); + if (maxZoomIndex <= 0) { + return 0; + } + return Math.round((float) clamped * maxZoomIndex / MAX_ZOOM_LEVEL); + } + + /** Maps an index into the camera's zoom table back onto a 0..MAX_ZOOM_LEVEL position. */ + static int toZoomLevel(int zoomIndex, int maxZoomIndex) { + if (maxZoomIndex <= 0) { + return 0; + } + int clamped = Math.max(0, Math.min(zoomIndex, maxZoomIndex)); + return Math.round((float) clamped * MAX_ZOOM_LEVEL / maxZoomIndex); + } + + @Override + public int getZoomLevel() { + if (mCamera == null) { + return 0; + } + Camera.Parameters parameters = mCamera.getParameters(); + return toZoomLevel(parameters.getZoom(), parameters.getMaxZoom()); + } + + @Override + public int getMaxZoomLevel() { + // Fixed, so one zoom control works across every backend. + return MAX_ZOOM_LEVEL; + } + + @Override + public boolean isZoomSupported() { + return mCamera != null && mCamera.getParameters().isZoomSupported(); + } + + @Override + public boolean isFaceDetectionSupported() { + return mCamera != null + && mCamera.getParameters().getMaxNumDetectedFaces() > 0; + } + + @Override + protected boolean setFaceDetectionEnabled(boolean enabled) { + if (mCamera == null) { + return !enabled; + } + if (!enabled) { + try { + mCamera.setFaceDetectionListener(null); + mCamera.stopFaceDetection(); + } catch (RuntimeException error) { + // Throws if detection was never started, which is not a failure to stop. + if (DEBUG) Log.d(TAG, "Face detection was not running", error); + } + return true; + } + if (!isFaceDetectionSupported()) { + return false; + } + mCamera.setFaceDetectionListener((faces, camera) -> onFacesDetected( + translate(faces), faceToViewTransform())); + try { + mCamera.startFaceDetection(); + } catch (RuntimeException error) { + Log.w(TAG, "Camera refused to start face detection", error); + mCamera.setFaceDetectionListener(null); + return false; + } + return true; + } + + @NonNull + private static List translate(@Nullable Camera.Face[] faces) { + if (faces == null) { + return Collections.emptyList(); + } + List translated = new ArrayList<>(faces.length); + for (Camera.Face face : faces) { + if (face == null || face.rect == null) { + continue; + } + translated.add(Face.create(face.rect, face.score, face.id, + face.leftEye, face.rightEye, face.mouth)); + } + return translated; + } + + /** + * Maps face bounds onto the view. + * + *

The old API reports faces in a fixed square from -1000 to 1000 that covers the field of + * view as it is currently displayed, so the rotation the preview needed has already been + * applied and only the scale into the view is left.

+ */ + @NonNull + private Matrix faceToViewTransform() { + return TransformMath.centerCrop(new RectF(-1000f, -1000f, 1000f, 1000f), + 0 /* already in display orientation */, + false /* and already mirrored if the lens is */, + getView().getWidth(), getView().getHeight()); + } + + @Override + public void toggleCamera() { + boolean shouldOpen = getView().isOpen(); + close(); + mActiveCamera = (mActiveCamera + 1) % Camera.getNumberOfCameras(); + if (shouldOpen) { + open(); + } + } + + @Override + public void setLensFacing(CameraView.LensFacing lensFacing) { + boolean shouldOpen = getView().isOpen(); + close(); + + // Search for the properly facing camera + int numberOfCameras = Camera.getNumberOfCameras(); + for (int i = 0; i < numberOfCameras; i++) { + Camera.CameraInfo info = new Camera.CameraInfo(); + Camera.getCameraInfo(i, info); + if ((info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT && lensFacing.equals(CameraView.LensFacing.FRONT)) + || (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK && lensFacing.equals(CameraView.LensFacing.BACK))) { + mActiveCamera = i; + break; + } + } + + if (shouldOpen) { + open(); + } + } + + @Override + public boolean hasFrontFacingCamera() { + // Search for the front facing camera + int numberOfCameras = Camera.getNumberOfCameras(); + for (int i = 0; i < numberOfCameras; i++) { + Camera.CameraInfo info = new Camera.CameraInfo(); + Camera.getCameraInfo(i, info); + if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { + return true; + } + } + return false; + } + + @Override + public boolean isUsingFrontFacingCamera() { + Camera.CameraInfo info = new Camera.CameraInfo(); + Camera.getCameraInfo(getActiveCamera(), info); + return info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT; + } + + @Override + protected int getRelativeCameraOrientation() { + return getRelativeCameraOrientation(true /* isPreview */); + } + + @RequiresApi(18) + @Override + protected void attachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { + if (mCamera != null && mPreviewSize != null) { + LegacySurfaceHolder surfaceHolder = new LegacySurfaceHolder(getContext(), surfaceProvider, mPreviewSize.width, mPreviewSize.height, getSensorOrientation(), isUsingFrontFacingCamera()); + mSurfaceProviders.put(surfaceProvider, surfaceHolder); + mCamera.setPreviewCallback((data, camera) -> { + Canvas canvas = surfaceHolder.lockCanvas(); + canvas.drawBitmap(toBitmap(data, camera), new Matrix(), new Paint()); + surfaceHolder.unlockCanvasAndPost(canvas); + }); + } + } + + @RequiresApi(18) + @Override + protected void detachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { + LegacySurfaceHolder surfaceHolder = mSurfaceProviders.remove(surfaceProvider); + if (surfaceHolder != null) { + surfaceHolder.close(); + mCamera.setPreviewCallback(null); + } + } + + private Bitmap toBitmap(byte[] data, Camera camera) { + Camera.Parameters parameters = camera.getParameters(); + int width = parameters.getPreviewSize().width; + int height = parameters.getPreviewSize().height; + + YuvImage yuv = new YuvImage(data, parameters.getPreviewFormat(), width, height, null); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + yuv.compressToJpeg(new Rect(0, 0, width, height), 50, out); + + byte[] bytes = out.toByteArray(); + return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); + } + + private int getRelativeCameraOrientation(boolean isPreview) { + return getRelativeImageOrientation(getDisplayRotation(), getSensorOrientation(), isUsingFrontFacingCamera(), isPreview); + } + + private int getSensorOrientation() { + Camera.CameraInfo info = new Camera.CameraInfo(); + Camera.getCameraInfo(getActiveCamera(), info); + return info.orientation; + } + + private int getActiveCamera() { + if (mActiveCamera != INVALID_CAMERA_ID) { + return mActiveCamera; + } + + int numberOfCameras = Camera.getNumberOfCameras(); + if (numberOfCameras == 0) { + return INVALID_CAMERA_ID; + } + + for (int i = 0; i < numberOfCameras; i++) { + Camera.CameraInfo info = new Camera.CameraInfo(); + Camera.getCameraInfo(i, info); + if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { + mActiveCamera = i; + return mActiveCamera; + } + } + + mActiveCamera = 0; + return mActiveCamera; + } + + private int getPreviewWidth() { + if (mPreviewSize == null) { + return 0; + } + + return mPreviewSize.width; + } + + private int getPreviewHeight() { + if (mPreviewSize == null) { + return 0; + } + + return mPreviewSize.height; + } + + private static Camera.Size chooseOptimalPreviewSize(List choices, int width, int height) { + if (DEBUG) { + Log.d(TAG, String.format("Initializing PreviewSurface with width=%s and height=%s", width, height)); + } + // Collect the supported resolutions that are at least as big as the preview Surface + List bigEnough = new ArrayList<>(); + for (Camera.Size option : choices) { + if (option.width >= width && option.height >= height) { + bigEnough.add(option); + } + } + + // Pick the smallest of those, assuming we found any + if (bigEnough.size() > 0) { + return Collections.min(bigEnough, new CompareSizesByArea()); + } else { + Log.e(TAG, "Couldn't find any suitable preview size"); + return choices.get(0); + } + } + + private static class CompareSizesByArea implements Comparator { + @Override + public int compare(Camera.Size lhs, Camera.Size rhs) { + // We cast here to ensure the multiplications won't overflow + return Long.signum((long) lhs.width * lhs.height - + (long) rhs.width * rhs.height); + } + } + + @SuppressWarnings({"MissingPermission"}) + @Nullable + static Location getLocation(Context context) { + if (PermissionChecker.hasPermissions(context, Manifest.permission.ACCESS_FINE_LOCATION)) { + // Our GPS timeout is purposefully low. We're not intending to wait until GPS is acquired + // but we want a last known location for the next time a picture is taken. + return LocationProvider.getGPSLocation(context, STALE_LOCATION_MILLIS, GPS_TIMEOUT_MILLIS); + } + return null; + } +} 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 80db740..e0b857d 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 @@ -1,889 +1,1605 @@ -package com.xlythe.view.camera.v2; - -import android.Manifest; -import android.annotation.TargetApi; -import android.content.Context; -import android.graphics.Matrix; -import android.graphics.Rect; -import android.hardware.camera2.CameraAccessException; -import android.hardware.camera2.CameraCaptureSession; -import android.hardware.camera2.CameraCharacteristics; -import android.hardware.camera2.CameraDevice; -import android.hardware.camera2.CameraManager; -import android.hardware.camera2.params.MeteringRectangle; -import android.hardware.camera2.params.StreamConfigurationMap; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.os.Parcelable; -import android.util.Log; -import android.util.Size; -import android.view.Surface; - -import com.xlythe.view.camera.CameraView; -import com.xlythe.view.camera.ICameraModule; -import com.xlythe.view.camera.stream.VideoRecorder; - -import java.io.File; -import java.util.List; -import java.util.Locale; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.RequiresPermission; -import androidx.annotation.RestrictTo; - -import static java.lang.String.format; - -/** - * A wrapper around the Camera2 APIs. Camera2 has some peculiarities, such as crashing if you attach - * too many surfaces (or too large a surface) to a capture session. To get around that, we define - * {@link Session}s that list out compatible surfaces and creates capture requests for them. - */ -@TargetApi(21) -@RestrictTo(RestrictTo.Scope.LIBRARY) -public class Camera2Module extends ICameraModule { - private static final int ZOOM_NOT_SUPPORTED = 1; - - private static final String EXTRA_DEVICE_ID = "device_id"; - - // It seems like, when Lollipop was released, 1080p was settled on as the 'default' resolution. - // Camera2 has a long table of different combinations of preview, picture, and video with the - // repeated requirement "Up to either 1080p, or the largest size supported by the device. - // Whichever is smaller." To go past 1080p requires limiting another column on the table. As a - // general rule, we don't go past 1080p unless we test on a wide range of devices. - static final Size MAX_SUPPORTED_SIZE = new Size(1920, 1080); - - /** - * This is how we'll talk to the camera. - */ - @NonNull - private final CameraManager mCameraManager; - - /** - * This is the id of the camera (eg. front or back facing) that we're currently using. - */ - @Nullable - private String mActiveCamera; - - /** - * The current capture session. There is one capture session per {@link Session}. - */ - @Nullable - private CameraCaptureSession mCaptureSession; - - /** - * The currently active camera. This may be a front facing camera or a back facing one. - */ - @Nullable - private CameraDevice mCameraDevice; - - /** - * A handler to receive callbacks from the camera on. - */ - @NonNull - private final Handler mHandler; - - /** - * A session that's attempting, but has not yet become, the active session. - */ - @Nullable - private Session mRegisteringSession; - - /** - * The currently active session. See {@link PictureSession} and {@link VideoSession}. - */ - @Nullable - private Session mActiveSession; - - /** - * The current zoom level, from 0 to {@link #getMaxZoomLevel()}. - */ - private int mZoomLevel; - - /** - * If true, the camera is currently open. - */ - private boolean mIsOpen = false; - - /** - * If true, the preview should be paused. - */ - private boolean mIsPaused = false; - - /** - * If true, we are currently recording. - */ - private boolean mIsRecording = false; - - /** - * - */ - private boolean mIsAttemptingToReopen = false; - - /** - * Callbacks for when the camera is available / unavailable - */ - private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() { - @Override - public void onOpened(@NonNull CameraDevice cameraDevice) { - if (!mIsOpen) { - Log.w(TAG, "Camera was opened after CameraView was closed. Disconnecting from the camera."); - close(); - return; - } - - // The camera has opened. Start the preview now. - mCameraDevice = cameraDevice; - setSession(new PictureSession(Camera2Module.this)); - - // Once we've successfully opened, we clean up any flags. - mIsAttemptingToReopen = false; - } - - @Override - public void onDisconnected(@NonNull CameraDevice cameraDevice) { - Log.w(TAG, "Camera disconnected"); - - // The camera has disconnected or errored out and we need to close ourselves to reset state. - // We'll try one time to reconnect before accepting defeat. - - // Cache if the CameraView wants us to be open. We could have disconnected because - // we were closed. - boolean isCameraViewOpen = mIsOpen; - - // Close to clean up our state. - close(); - - // If we should be open, and if we haven't attempted to reopen before, try opening again now. - if (isCameraViewOpen && !mIsAttemptingToReopen) { - mIsAttemptingToReopen = true; - open(); - } - } - - @Override - public void onError(@NonNull CameraDevice cameraDevice, int error) { - Log.e(TAG, "Camera crashed: " + Camera2Module.toString(error)); - onDisconnected(cameraDevice); - } - }; - - private static String toString(int error) { - switch (error) { - case CameraDevice.StateCallback.ERROR_CAMERA_DEVICE: - return "ERROR_CAMERA_DEVICE"; - case CameraDevice.StateCallback.ERROR_CAMERA_DISABLED: - return "ERROR_CAMERA_DISABLED"; - case CameraDevice.StateCallback.ERROR_CAMERA_IN_USE: - return "ERROR_CAMERA_IN_USE"; - case CameraDevice.StateCallback.ERROR_CAMERA_SERVICE: - return "ERROR_CAMERA_SERVICE"; - case CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE: - return "ERROR_MAX_CAMERAS_IN_USE"; - } - return format(Locale.US, "UNKNOWN_ERROR(%d)", error); - } - - public Camera2Module(CameraView cameraView) { - super(cameraView); - mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE); - mHandler = new Handler(Looper.getMainLooper()); - } - - private void setSession(final Session session) { - if (mCameraDevice == null) { - if (DEBUG) Log.w(TAG, "Cannot start a session without a CameraDevice"); - return; - } - - try { - // Clean up any previous sessions - boolean hasPreviousState = false; - if (mCaptureSession != null) { - mCaptureSession.stopRepeating(); - try { - mCaptureSession.abortCaptures(); - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to abort captures", e); - } - mCaptureSession.close(); - mCaptureSession = null; - hasPreviousState = true; - } - if (mRegisteringSession != null) { - Log.d(TAG, format("%s is replacing %s", session.getClass().getSimpleName(), mRegisteringSession.getClass().getSimpleName())); - - // Restore state from the previous session - session.setMeteringRectangle(mRegisteringSession.getMeteringRectangle()); - session.setCropRegion(mRegisteringSession.getCropRegion()); - - mRegisteringSession.close(); - mRegisteringSession = null; - hasPreviousState = true; - } - if (mActiveSession != null) { - // Restore state from the previous session - session.setMeteringRectangle(mActiveSession.getMeteringRectangle()); - session.setCropRegion(mActiveSession.getCropRegion()); - - mActiveSession.close(); - mActiveSession = null; - hasPreviousState = true; - } - if (hasPreviousState) { - mHandler.post(() -> setSession(session)); - return; - } - - // Assume this is a brand new session that's never been set up. Initialize it so that - // it can decide what size to set its surfaces to. - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); - StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); - session.initialize(map); - - // Now, with all of our surfaces, we'll ask for a new session - mRegisteringSession = session; - mCameraDevice.createCaptureSession(session.getSurfaces(), new CameraCaptureSession.StateCallback() { - @Override - public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { - if (mCameraDevice == null) { - return; - } - - try { - mCaptureSession = cameraCaptureSession; - mActiveSession = session; - if (mRegisteringSession == session) { - mRegisteringSession = null; - } - if (!mIsPaused) { - session.onAvailable(mCameraDevice, mCaptureSession); - } - if (mZoomLevel != 0) { - setZoomLevel(mZoomLevel); - } - } catch (CameraAccessException | IllegalStateException | IllegalArgumentException e) { - Log.e(TAG, "Failed to start session " + session.getClass().getSimpleName(), e); - } - } - - @Override - public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) { - Log.e(TAG, "Configure failed"); - } - }, mHandler); - } catch (CameraAccessException | IllegalStateException | IllegalArgumentException e) { - // Crashes if the Camera is interacted with while still loading - Log.e(TAG, "Failed to create capture session", e); - } - } - - @RequiresPermission(Manifest.permission.CAMERA) - @Override - public void open() { - mIsOpen = true; - try { - mActiveCamera = getActiveCamera(); - if (DEBUG) Log.d(TAG, "Opening camera " + mActiveCamera); - mCameraManager.openCamera(mActiveCamera, mStateCallback, mHandler); - } catch (CameraAccessException | IllegalArgumentException e) { - Log.e(TAG, "Failed to open camera", e); - } - } - - @Override - public void close() { - if (mCaptureSession != null) { - try { - mCaptureSession.close(); - } catch (Exception e) { - // Instance of CameraAccessException (although not declared). - // Nothing we can do but swallow it. - Log.e(TAG, "Failed to close camera", e); - } - mCaptureSession = null; - } - if (mActiveSession != null) { - mActiveSession.close(); - mActiveSession = null; - } - if (mCameraDevice != null) { - mCameraDevice.close(); - mCameraDevice = null; - } - mIsPaused = false; - mIsOpen = false; - mIsRecording = false; - } - - @Override - public boolean hasFrontFacingCamera() { - try { - for (String cameraId : mCameraManager.getCameraIdList()) { - if (isFrontFacing(cameraId)) return true; - } - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to query camera", e); - } - return false; - } - - @Override - public boolean isUsingFrontFacingCamera() { - try { - return isFrontFacing(getActiveCamera()); - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to query camera", e); - } - return false; - } - - @RequiresPermission(Manifest.permission.CAMERA) - @Override - public void toggleCamera() { - int position = 0; - - try { - for (String cameraId : mCameraManager.getCameraIdList()) { - if (cameraId.equals(getActiveCamera())) { - break; - } - position++; - } - - // Close the old camera and open with the new camera id, but only if it was already - // open before toggle was requested. - boolean shouldOpen = mIsOpen; - close(); - mActiveCamera = mCameraManager.getCameraIdList()[(position + 1) % mCameraManager.getCameraIdList().length]; - if (shouldOpen) { - open(); - } - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to query camera", e); - } - } - - @Override - public void setLensFacing(CameraView.LensFacing lensFacing) { - int position = 0; - - try { - for (String cameraId : mCameraManager.getCameraIdList()) { - boolean isFrontFacing = isFrontFacing(cameraId); - if ((isFrontFacing && lensFacing.equals(CameraView.LensFacing.FRONT)) - || (!isFrontFacing && lensFacing.equals(CameraView.LensFacing.BACK))) { - break; - } - position++; - } - - // Close the old camera and open with the new camera id, but only if it was already - // open before toggle was requested. - boolean shouldOpen = mIsOpen; - close(); - mActiveCamera = mCameraManager.getCameraIdList()[position % mCameraManager.getCameraIdList().length]; - if (shouldOpen) { - open(); - } - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to query camera", e); - } - } - - @Override - public void focus(Rect focus, Rect metering) { - if (mCaptureSession == null) { - if (DEBUG) Log.w(TAG, "Cannot focus. No capture session."); - return; - } - - if (mActiveSession == null) { - if (DEBUG) Log.w(TAG, "Cannot focus. No active session."); - return; - } - - if (mCameraDevice == null) { - if (DEBUG) Log.w(TAG, "Cannot focus. No camera device."); - return; - } - - try { - if (!supportsFocus(getActiveCamera())) { - Log.w(TAG, "Focus not available on this camera"); - return; - } - - if (mActiveSession == null) { - Log.w(TAG, "No active session available"); - return; - } - - // Our metering Rect ranges from -1000 to 1000. We need to remap it to fit the camera dimensions (0 to width). - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); - Rect arraySize = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); - if (arraySize == null) { - Log.w(TAG, "Unable to load the active array size"); - return; - } - resize(metering, arraySize.width(), arraySize.height()); - - // Now we can update our request - mActiveSession.setMeteringRectangle(new MeteringRectangle(metering, MeteringRectangle.METERING_WEIGHT_MAX)); - if (!mIsPaused) { - mActiveSession.onInvalidate(mCameraDevice, mCaptureSession); - } - } catch (CameraAccessException | IllegalStateException | IllegalArgumentException e) { - // Crashes if the Camera is interacted with while still loading - Log.e(TAG, "Failed to focus", e); - } - } - - /** - * Resizes a Rect from its original dimensions of -1000 to 1000 to 0 to width/height. - */ - private static void resize(Rect metering, int maxWidth, int maxHeight) { - // We can calculate the new width by scaling it to its new dimensions - int newWidth = metering.width() * maxWidth / 2000; - int newHeight = metering.height() * maxHeight / 2000; - - // Then we calculate how far from the top/left corner it should be - int leftOffset = (metering.left + 1000) * maxWidth / 2000; - int topOffset = (metering.top + 1000) * maxHeight / 2000; - - // And now we can resize the Rect to its new dimensions - metering.left = leftOffset; - metering.top = topOffset; - metering.right = metering.left + newWidth; - metering.bottom = metering.top + newHeight; - } - - @Override - public void setZoomLevel(int zoomLevel) { - mZoomLevel = zoomLevel; - - if (mCameraDevice == null || mCaptureSession == null || mActiveSession == null) { - Log.w(TAG, "No active session available"); - return; - } - - try { - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); - Rect m = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); - if (m == null) { - Log.w(TAG, "Zoom not supported"); - return; - } - - int maxZoom = getMaxZoomLevel(); - - int minW = m.width() / maxZoom; - int minH = m.height() / maxZoom; - int difW = m.width() - minW; - int difH = m.height() - minH; - int cropW = difW * zoomLevel / maxZoom; - int cropH = difH * zoomLevel / maxZoom; - Rect cropRegion = new Rect(cropW, cropH, m.width() - cropW, m.height() - cropH); - - if (cropRegion.left > cropRegion.right || cropRegion.top > cropRegion.bottom) { - Log.w(TAG, "Crop Region has inverted, ignoring further zoom levels"); - return; - } - mActiveSession.setCropRegion(cropRegion); - if (!mIsPaused) { - mActiveSession.onInvalidate(mCameraDevice, mCaptureSession); - } - } catch (CameraAccessException | IllegalStateException | IllegalArgumentException e) { - // Crashes if the Camera is interacted with while still loading - Log.e(TAG, "Failed to zoom", e); - } - } - - @Override - public int getZoomLevel() { - return mZoomLevel; - } - - @Override - public int getMaxZoomLevel() { - try { - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); - Float maxZoom = (characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM)); - if (maxZoom == null) { - return ZOOM_NOT_SUPPORTED; - } - - // We scale the max zoom (which is a float) by 10 so that we can use ints. However, - // there's no need to do that if we can't even zoom. - if (maxZoom == ZOOM_NOT_SUPPORTED) { - return ZOOM_NOT_SUPPORTED; - } - - return (int) (maxZoom * 10); - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to query camera", e); - } - - return ZOOM_NOT_SUPPORTED; - } - - @Override - public boolean hasFlash() { - try { - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); - Boolean hasFlash = (characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)); - if (hasFlash == null) { - return false; - } - return hasFlash; - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to query camera", e); - } - - return false; - } - - @Override - public boolean isZoomSupported() { - return getMaxZoomLevel() != ZOOM_NOT_SUPPORTED; - } - - @Override - public void pause() { - if (mCaptureSession == null) { - if (DEBUG) Log.w(TAG, "Cannot pause. No capture session."); - return; - } - - if (!mIsPaused) { - try { - mCaptureSession.stopRepeating(); - } catch (CameraAccessException | IllegalStateException | IllegalArgumentException e) { - Log.e(TAG, "Failed to pause the camera", e); - } - mIsPaused = true; - } else { - if (DEBUG) Log.w(TAG, "Cannot pause. Was never unpaused."); - } - } - - @Override - public void resume() { - try { - if (mCaptureSession == null) { - if (DEBUG) Log.w(TAG, "Cannot pause. No capture session."); - return; - } - - if (mActiveSession == null) { - if (DEBUG) Log.w(TAG, "Cannot pause. No active session."); - return; - } - - if (mCameraDevice == null) { - if (DEBUG) Log.w(TAG, "Cannot pause. No camera device."); - return; - } - - if (mIsPaused) { - try { - mActiveSession.onAvailable(mCameraDevice, mCaptureSession); - } catch (CameraAccessException | IllegalStateException | IllegalArgumentException e) { - Log.e(TAG, "Failed to resume the camera", e); - } - } else { - if (DEBUG) { - Log.w(TAG, "Cannot resume. Was never paused."); - } - } - } finally { - mIsPaused = false; - } - } - - @Override - public boolean isPaused() { - return mIsPaused; - } - - @Override - public void setQuality(CameraView.Quality quality) { - super.setQuality(quality); - - // When quality changes, we need to update our session with the new dimensions - if (mActiveSession != null) { - if (mActiveSession instanceof PictureSession) { - setSession(new PictureSession(this)); - } else if (mActiveSession instanceof VideoSession) { - setSession(new VideoSession(this, ((VideoSession) mActiveSession).getFile())); - } else if (mActiveSession instanceof StreamSession) { - // Ignored. Streams cannot be restarted so we'll update quality once the stream ends. - } - } - } - - @Override - public void takePicture(File file) { - if (mCaptureSession == null) { - if (DEBUG) Log.w(TAG, "Cannot take picture. No capture session."); - return; - } - - if (mActiveSession == null) { - if (DEBUG) Log.w(TAG, "Cannot take picture. No active session."); - return; - } - - if (mCameraDevice == null) { - if (DEBUG) Log.w(TAG, "Cannot take picture. No camera device."); - return; - } - - if (mActiveSession instanceof PictureSession) { - PictureSession pictureSession = (PictureSession) mActiveSession; - pictureSession.takePicture(file, mCameraDevice, mCaptureSession); - } else { - onImageFailed(); - } - } - - @RequiresPermission(Manifest.permission.RECORD_AUDIO) - @Override - public void startRecording(File file) { - // Quick fail if the CameraDevice was never created. - if (mCameraDevice == null) { - onVideoFailed(); - return; - } - - mIsRecording = true; - setSession(new VideoSession(this, file)); - } - - @Override - public void stopRecording() { - mIsRecording = false; - setSession(new PictureSession(this)); - } - - @Override - public boolean isRecording() { - return mIsRecording; - } - - @Override - public void showVideoConfirmation(File file) { - super.showVideoConfirmation(file); - mIsRecording = false; - } - - @Override - public void onVideoFailed() { - super.onVideoFailed(); - mIsRecording = false; - } - - @Override - protected void attachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { - setSession(new StreamSession(this, surfaceProvider)); - } - - @Override - protected void detachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { - setSession(new PictureSession(this)); - } - - void transformPreview(int previewWidth, int previewHeight) throws CameraAccessException { - int viewWidth = getWidth(); - int viewHeight = getHeight(); - int displayOrientation = getDisplayRotation(); - int cameraOrientation = getSensorOrientation(getActiveCamera()); - - // Camera2 rotates the preview to always face in portrait mode, even if the phone is - // currently in landscape. This is great for portrait mode, because there's less work to be done. - // It's less great for landscape, because we have to undo it. Without any matrix modifications, - // the preview will be smushed into the aspect ratio of the view. - Matrix matrix = new Matrix(); - - // Camera2 reverses the preview width/height. - if (cameraOrientation != 0 && cameraOrientation != 180) { - int temp = previewWidth; - previewWidth = previewHeight; - previewHeight = temp; - } - - // We want to find the aspect ratio of the preview. Our goal is to stretch the image in - // our SurfaceView to match this ratio, so that the image doesn't looked smushed. - // This means the edges of the preview will be cut off. - float aspectRatio = (float) previewHeight / (float) previewWidth; - int newWidth, newHeight; - if (viewHeight > viewWidth * aspectRatio) { - newWidth = (int) Math.ceil(viewHeight / aspectRatio); - newHeight = viewHeight; - } else { - newWidth = viewWidth; - newHeight = (int) Math.ceil(viewWidth * aspectRatio); - } - - // For portrait, we've already been mostly stretched. For landscape, our image is rotated 90 degrees. - // Think of it as a sideways squished photo. We want to first streeeetch the height of the photo - // until it matches the aspect ratio we originally expected. Now we're no longer stretched - // (although we're wildly off screen, with only the far left sliver of the photo still - // visible on the screen, and our picture is still sideways). - float scaleX = (float) newWidth / (float) viewWidth; - float scaleY = (float) newHeight / (float) viewHeight; - - // However, we've actually stretched too much. The height of the picture is currently the - // width of our screen. When we rotate the picture, it'll be too large and we'll end up - // cropping a lot of the picture. That's what this step is for. We scale down the image so - // that the height of the photo (currently the width of the phone) becomes the height we - // want (the height of the phone, or slightly bigger, depending on aspect ratio). - float scale = 1f; - if (displayOrientation == 90 || displayOrientation == 270) { - boolean cropHeight = viewWidth > newHeight * viewHeight / newWidth; - if (cropHeight) { - // If we're cropping the top/bottom, then we want the widths to be exact - scale = (float) viewWidth / newHeight; - } else { - // If we're cropping the left/right, then we want the heights to be exact - scale = (float) viewHeight / newWidth; - } - newWidth = (int) Math.ceil(newWidth * scale); - newHeight = (int) Math.ceil(newHeight * scale); - scaleX *= scale; - scaleY *= scale; - } - - // Because we scaled the preview beyond the bounds of the view, we need to crop some of it. - // By translating the photo over, we'll move it into the center. - int translateX = (int) Math.ceil((viewWidth - newWidth) / 2d); - int translateY = (int) Math.ceil((viewHeight - newHeight) / 2d); - - // Due to the direction of rotation (90 vs 270), a 1 pixel offset can either put us - // exactly where we want to be, or it can put us 1px lower than we wanted. This is error - // correction for that. - if (displayOrientation == 270) { - translateX = (int) Math.floor((viewWidth - newWidth) / 2d); - translateY = (int) Math.floor((viewHeight - newHeight) / 2d); - } - - // Finally, with our photo scaled and centered, we apply a rotation. - int rotation = -displayOrientation; - - matrix.setScale(scaleX, scaleY); - matrix.postTranslate(translateX, translateY); - matrix.postRotate(rotation, (int) Math.ceil(viewWidth / 2d), (int) Math.ceil(viewHeight / 2d)); - - if (DEBUG) { - Log.d(TAG, format("transformPreview: displayOrientation=%s, cameraOrientation=%s, " - + "viewWidth=%s, viewHeight=%s, viewAspectRatio=%s, previewWidth=%s, previewHeight=%s, previewAspectRatio=%s, " - + "newWidth=%s, newHeight=%s, scaleX=%s, scaleY=%s, scale=%s, " - + "translateX=%s, translateY=%s, rotation=%s", - displayOrientation, cameraOrientation, viewWidth, viewHeight, - ((float) viewHeight / (float) viewWidth), previewWidth, previewHeight, aspectRatio, - newWidth, newHeight, scaleX, scaleY, scale, translateX, translateY, rotation)); - } - - setTransform(matrix); - } - - @Override - protected int getRelativeCameraOrientation() { - try { - return getRelativeImageOrientation(getDisplayRotation(), getSensorOrientation(getActiveCamera()), isUsingFrontFacingCamera(), false); - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to query camera", e); - return 0; - } - } - - @NonNull - String getActiveCamera() throws CameraAccessException { - return mActiveCamera == null ? getDefaultCamera() : mActiveCamera; - } - - private String getDefaultCamera() throws CameraAccessException { - for (String cameraId : mCameraManager.getCameraIdList()) { - if (isBackFacing(cameraId)) { - return cameraId; - } - } - return mCameraManager.getCameraIdList()[0]; - } - - private boolean supportsFocus(String cameraId) throws CameraAccessException { - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); - Integer maxRegions = characteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF); - return maxRegions != null && maxRegions >= 1; - } - - private boolean isFrontFacing(String cameraId) throws CameraAccessException { - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); - Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); - return facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT; - } - - private boolean isBackFacing(String cameraId) throws CameraAccessException { - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); - Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); - return facing != null && facing == CameraCharacteristics.LENS_FACING_BACK; - } - - private int getSensorOrientation(String cameraId) throws CameraAccessException { - CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); - Integer orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); - return orientation == null ? 0 : orientation; - } - - protected int getSensorOrientation() { - try { - return getSensorOrientation(getActiveCamera()); - } catch (CameraAccessException e) { - return 0; - } - } - - Handler getHandler() { - return mHandler; - } - - @Override - public Parcelable onSaveInstanceState() { - Bundle state = new Bundle(); - state.putString(EXTRA_DEVICE_ID, mActiveCamera); - return state; - } - - @Override - public void onRestoreInstanceState(Parcelable state) { - mActiveCamera = ((Bundle) state).getString(EXTRA_DEVICE_ID); - } - - @Override - public void onLayoutChanged() { - if (mActiveSession != null) { - try { - mActiveSession.onLayoutChanged(); - } catch (CameraAccessException e) { - Log.e(TAG, "Failed to adjust the camera after a layout change", e); - } - } - } - - /** - * A session has multiple surfaces for the camera to draw to. - */ - interface Session { - void initialize(@NonNull StreamConfigurationMap map) throws CameraAccessException; - void onLayoutChanged() throws CameraAccessException; - @NonNull List getSurfaces(); - void setMeteringRectangle(@Nullable MeteringRectangle meteringRectangle); - @Nullable MeteringRectangle getMeteringRectangle(); - void setCropRegion(@Nullable Rect region); - @Nullable Rect getCropRegion(); - void onAvailable(@NonNull CameraDevice cameraDevice, @NonNull CameraCaptureSession session) throws CameraAccessException; - void onInvalidate(@NonNull CameraDevice cameraDevice, @NonNull CameraCaptureSession session) throws CameraAccessException; - void close(); - } -} +package com.xlythe.view.camera.v2; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.ImageFormat; +import android.graphics.Matrix; +import android.graphics.Rect; +import android.graphics.RectF; +import android.graphics.SurfaceTexture; +import android.hardware.camera2.CameraAccessException; +import android.hardware.camera2.CameraCaptureSession; +import android.hardware.camera2.CameraCharacteristics; +import android.hardware.camera2.CameraDevice; +import android.hardware.camera2.CameraManager; +import android.hardware.camera2.CameraMetadata; +import android.hardware.camera2.CaptureResult; +import android.hardware.camera2.params.MeteringRectangle; +import android.hardware.camera2.params.OutputConfiguration; +import android.hardware.camera2.params.SessionConfiguration; +import android.hardware.camera2.params.StreamConfigurationMap; +import android.media.ImageReader; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Parcelable; +import android.util.DisplayMetrics; +import android.util.Log; +import android.util.Range; +import android.util.Size; +import android.view.Surface; + +import com.xlythe.view.camera.CameraView; +import com.xlythe.view.camera.Face; +import com.xlythe.view.camera.ICameraModule; +import com.xlythe.view.camera.TransformMath; +import com.xlythe.view.camera.stream.VideoRecorder; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.annotation.Nullable; +import androidx.annotation.RequiresPermission; +import androidx.annotation.RestrictTo; + +import static java.lang.String.format; + +/** + * A wrapper around the Camera2 APIs. Camera2 has some peculiarities, such as crashing if you attach + * too many surfaces (or too large a surface) to a capture session. To get around that, we define + * {@link Session}s that list out compatible surfaces and creates capture requests for them. + */ +@TargetApi(21) +@RestrictTo(RestrictTo.Scope.LIBRARY) +public class Camera2Module extends ICameraModule { + /** The zoom scale CameraView publishes, matching the CameraX backend so the two agree. */ + private static final int MAX_ZOOM_LEVEL = 100; + /** Maximum automatic reopen attempts before reporting a terminal Camera2 failure. */ + private static final int MAX_REOPEN_ATTEMPTS = 1; + + private static final String EXTRA_DEVICE_ID = "device_id"; + + // It seems like, when Lollipop was released, 1080p was settled on as the 'default' resolution. + // Camera2 has a long table of different combinations of preview, picture, and video with the + // repeated requirement "Up to either 1080p, or the largest size supported by the device. + // Whichever is smaller." To go past 1080p requires limiting another column on the table. As a + // general rule, we don't go past 1080p unless we test on a wide range of devices. + static final Size MAX_SUPPORTED_SIZE = new Size(1920, 1080); + + /** + * The largest preview the camera is guaranteed to manage alongside a full-size still capture. + * + *

Camera2's guaranteed stream combinations define PREVIEW as the largest output at most + * 1920x1080 and at most the display size, and every level of that table is written in terms + * of it, so exceeding either half leaves guaranteed territory. We only ever applied the 1080p + * half, which over-asks on a device whose panel is smaller.

+ * + *

When the device can be asked directly, through isSessionConfigurationSupported from API + * 29, a larger preview is used if it says yes. Anything else, including an older API, a + * refusal or a failure to answer, keeps the guaranteed size: the worst case is exactly the + * behavior that shipped.

+ */ + @NonNull + Size getPreviewSizeCap(@NonNull List candidates) { + Size guaranteed = guaranteedPreviewCap(displaySize()); + if (largestWithin(candidates, guaranteed) == null) { + // Every output this camera offers is larger than the panel, which happens on a small + // screen paired with a normal sensor. Admit the smallest one rather than nothing. + Size smallest = smallestOf(candidates); + return smallest == null ? guaranteed : smallest; + } + + Size largest = largestWithin(candidates, null); + if (largest == null || !exceeds(largest, guaranteed)) { + return guaranteed; + } + if (isPreviewSizeSupported(largest)) { + if (DEBUG) Log.d(TAG, "Camera confirmed a preview larger than the guaranteed size"); + return largest; + } + return guaranteed; + } + + /** The smallest candidate by area, or null when there are none. */ + @Nullable + static Size smallestOf(@NonNull List candidates) { + Size best = null; + for (Size size : candidates) { + if (best == null + || (long) size.getWidth() * size.getHeight() + < (long) best.getWidth() * best.getHeight()) { + best = size; + } + } + return best; + } + + /** Intersects the two halves of the table's PREVIEW definition. */ + @NonNull + static Size guaranteedPreviewCap(@Nullable Size displaySize) { + if (displaySize == null) { + return MAX_SUPPORTED_SIZE; + } + // The display is reported in its current orientation, and camera sizes are always + // landscape, so compare against its long and short edges rather than width and height. + int longEdge = Math.max(displaySize.getWidth(), displaySize.getHeight()); + int shortEdge = Math.min(displaySize.getWidth(), displaySize.getHeight()); + return new Size( + Math.min(MAX_SUPPORTED_SIZE.getWidth(), longEdge), + Math.min(MAX_SUPPORTED_SIZE.getHeight(), shortEdge)); + } + + /** True when either dimension of a size is past the cap. */ + static boolean exceeds(@NonNull Size size, @NonNull Size cap) { + return size.getWidth() > cap.getWidth() || size.getHeight() > cap.getHeight(); + } + + /** The largest candidate within an optional cap, by area. */ + @Nullable + static Size largestWithin(@NonNull List candidates, @Nullable Size cap) { + Size best = null; + for (Size size : candidates) { + if (cap != null && exceeds(size, cap)) { + continue; + } + if (best == null + || (long) size.getWidth() * size.getHeight() + > (long) best.getWidth() * best.getHeight()) { + best = size; + } + } + return best; + } + + @Nullable + private Size displaySize() { + try { + DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); + if (metrics.widthPixels <= 0 || metrics.heightPixels <= 0) { + return null; + } + return new Size(metrics.widthPixels, metrics.heightPixels); + } catch (RuntimeException error) { + Log.w(TAG, "Unable to read the display size", error); + return null; + } + } + + /** + * Asks the camera whether it would configure a preview of this size next to a full-size + * still capture. Returns false whenever the answer is anything but a clear yes. + */ + private boolean isPreviewSizeSupported(@NonNull Size previewSize) { + CameraDevice device = mCameraDevice; + if (device == null || Build.VERSION.SDK_INT < 29) { + return false; + } + + ImageReader probeReader = null; + try { + CameraCharacteristics characteristics = + mCameraManager.getCameraCharacteristics(getActiveCamera()); + StreamConfigurationMap map = + characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); + Size stillSize = map == null ? null + : largestWithin(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), null); + if (stillSize == null) { + return false; + } + + // A throwaway reader stands in for the still-capture stream, so the combination can + // be checked without building, and then tearing down, the real session. + probeReader = ImageReader.newInstance(stillSize.getWidth(), stillSize.getHeight(), + ImageFormat.JPEG, 1); + List outputs = Arrays.asList( + new OutputConfiguration(previewSize, SurfaceTexture.class), + new OutputConfiguration(probeReader.getSurface())); + SessionConfiguration configuration = new SessionConfiguration( + SessionConfiguration.SESSION_REGULAR, outputs, mHandler::post, + new CameraCaptureSession.StateCallback() { + @Override public void onConfigured(@NonNull CameraCaptureSession session) {} + @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) {} + }); + return device.isSessionConfigurationSupported(configuration); + } catch (CameraAccessException | RuntimeException error) { + // Anything but a clear yes keeps the guaranteed size, including a device that cannot + // answer the question at all. + if (DEBUG) Log.d(TAG, "Camera could not confirm the preview size", error); + return false; + } finally { + if (probeReader != null) { + probeReader.close(); + } + } + } + + /** + * This is how we'll talk to the camera. + */ + @NonNull + private final CameraManager mCameraManager; + + /** + * This is the id of the camera (eg. front or back facing) that we're currently using. + */ + @Nullable + private String mActiveCamera; + + /** + * The current capture session. There is one capture session per {@link Session}. + */ + @Nullable + private CameraCaptureSession mCaptureSession; + + /** + * The currently active camera. This may be a front facing camera or a back facing one. + */ + @Nullable + private CameraDevice mCameraDevice; + + /** + * A handler to receive callbacks from the camera on. + */ + @NonNull + private final Handler mHandler; + + /** + * A session that's attempting, but has not yet become, the active session. + */ + @Nullable + private Session mRegisteringSession; + + /** + * The currently active session. See {@link PictureSession} and {@link VideoSession}. + */ + @Nullable + private Session mActiveSession; + + /** The face detection mode the repeating request carries, or null when faces are not wanted. */ + @Nullable + private Integer mFaceDetectMode; + + /** How many faces the last report had, so an empty camera is not reported every frame. */ + private int mLastFaceCount; + + /** + * The current zoom level, from 0 to {@link #getMaxZoomLevel()}. + */ + private int mZoomLevel; + + /** + * If true, the camera is currently open. + */ + private boolean mIsOpen = false; + + /** + * If true, the preview should be paused. + */ + private boolean mIsPaused = false; + + /** + * If true, we are currently recording. + */ + private boolean mIsRecording = false; + + /** + * Incremented for every open/close cycle so callbacks from an obsolete camera request can be + * rejected without disturbing the current device. + */ + private int mGeneration; + + /** Number of consecutive reopen attempts since the last usable capture session. */ + private int mReopenAttempts; + + /** + * Generation to open after the previous Camera2 device reports that it has fully closed, or + * zero when no lens switch is waiting for device release. + */ + private int mPendingOpenGeneration; + + /** Camera2 device whose onClosed callback is allowed to complete a pending lens switch. */ + @Nullable + private CameraDevice mPendingCloseDevice; + + private CameraDevice.StateCallback createStateCallback(final int generation) { + return new CameraDevice.StateCallback() { + @Override + public void onOpened(@NonNull CameraDevice cameraDevice) { + if (!mIsOpen || generation != mGeneration) { + Log.w(TAG, "Ignoring a stale Camera2 open callback"); + cameraDevice.close(); + return; + } + + mCameraDevice = cameraDevice; + setSession(new PictureSession(Camera2Module.this)); + } + + @Override + public void onDisconnected(@NonNull CameraDevice cameraDevice) { + handleCameraFailure(cameraDevice, generation, "Camera disconnected"); + } + + @Override + public void onError(@NonNull CameraDevice cameraDevice, int error) { + handleCameraFailure(cameraDevice, generation, + "Camera device error: " + Camera2Module.toString(error)); + } + + @Override + public void onClosed(@NonNull CameraDevice cameraDevice) { + int pendingGeneration = mPendingOpenGeneration; + if (pendingGeneration == 0 || cameraDevice != mPendingCloseDevice) { + return; + } + mPendingOpenGeneration = 0; + mPendingCloseDevice = null; + if (mIsOpen && pendingGeneration == mGeneration) { + openCamera(pendingGeneration); + } + } + }; + } + + @SuppressLint("MissingPermission") + private void openCamera(int generation) { + try { + mActiveCamera = getActiveCamera(); + if (DEBUG) Log.d(TAG, "Opening camera " + mActiveCamera); + mCameraManager.openCamera(mActiveCamera, createStateCallback(generation), mHandler); + } catch (CameraAccessException | RuntimeException e) { + mIsOpen = false; + closeCameraResources(); + onCameraError(new IllegalStateException("Failed to open Camera2 device", e)); + } + } + + private void handleCameraFailure(@NonNull CameraDevice cameraDevice, int generation, + String message) { + Log.e(TAG, message); + cameraDevice.close(); + if (generation != mGeneration) { + Log.w(TAG, "Ignoring a stale Camera2 failure callback"); + return; + } + + boolean shouldReopen = mIsOpen && mReopenAttempts < MAX_REOPEN_ATTEMPTS; + closeCameraResources(); + if (shouldReopen) { + mReopenAttempts++; + int retryGeneration = ++mGeneration; + mHandler.post(() -> { + if (mIsOpen && retryGeneration == mGeneration) { + openCamera(retryGeneration); + } + }); + } else if (mIsOpen) { + mIsOpen = false; + onCameraError(new IllegalStateException(message)); + } + } + + static String toString(int error) { + switch (error) { + case CameraDevice.StateCallback.ERROR_CAMERA_DEVICE: + return "ERROR_CAMERA_DEVICE"; + case CameraDevice.StateCallback.ERROR_CAMERA_DISABLED: + return "ERROR_CAMERA_DISABLED"; + case CameraDevice.StateCallback.ERROR_CAMERA_IN_USE: + return "ERROR_CAMERA_IN_USE"; + case CameraDevice.StateCallback.ERROR_CAMERA_SERVICE: + return "ERROR_CAMERA_SERVICE"; + case CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE: + return "ERROR_MAX_CAMERAS_IN_USE"; + } + return format(Locale.US, "UNKNOWN_ERROR(%d)", error); + } + + public Camera2Module(CameraView cameraView) { + super(cameraView); + mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE); + mHandler = new Handler(Looper.getMainLooper()); + } + + private void setSession(final Session session) { + if (!mIsOpen || mCameraDevice == null) { + if (DEBUG) Log.w(TAG, "Cannot start a session without an open CameraDevice"); + closeSession(session); + return; + } + + try { + // Clean up any previous sessions + boolean hasPreviousState = false; + if (mCaptureSession != null) { + mCaptureSession.stopRepeating(); + try { + mCaptureSession.abortCaptures(); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to abort captures", e); + } + mCaptureSession.close(); + mCaptureSession = null; + hasPreviousState = true; + } + if (mRegisteringSession != null) { + Log.d(TAG, format("%s is replacing %s", session.getClass().getSimpleName(), mRegisteringSession.getClass().getSimpleName())); + + // Restore state from the previous session + session.setMeteringRectangle(mRegisteringSession.getMeteringRectangle()); + session.setCropRegion(mRegisteringSession.getCropRegion()); + + mRegisteringSession.close(); + mRegisteringSession = null; + hasPreviousState = true; + } + if (mActiveSession != null) { + // Restore state from the previous session + session.setMeteringRectangle(mActiveSession.getMeteringRectangle()); + session.setCropRegion(mActiveSession.getCropRegion()); + + mActiveSession.close(); + mActiveSession = null; + hasPreviousState = true; + } + if (hasPreviousState) { + mHandler.post(() -> setSession(session)); + return; + } + + // Assume this is a brand new session that's never been set up. Claim ownership before + // initialization so any failure can clean up this exact session. + mRegisteringSession = session; + CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); + StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); + if (map == null) { + throw new IllegalStateException("Camera has no stream configuration map"); + } + session.initialize(map); + + // Now, with all of our surfaces, we'll ask for a new session + createCaptureSession(session.getSurfaces(), new CameraCaptureSession.StateCallback() { + @Override + public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { + if (!mIsOpen || mCameraDevice == null || mRegisteringSession != session) { + cameraCaptureSession.close(); + return; + } + + try { + mCaptureSession = cameraCaptureSession; + mActiveSession = session; + if (mRegisteringSession == session) { + mRegisteringSession = null; + } + mReopenAttempts = 0; + if (!mIsPaused) { + session.onAvailable(mCameraDevice, mCaptureSession); + } + if (mZoomLevel != 0) { + setZoomLevel(mZoomLevel); + } + } catch (CameraAccessException | RuntimeException e) { + failSession(session, cameraCaptureSession, + "Failed to start " + session.getClass().getSimpleName(), e); + } + } + + @Override + public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) { + if (!mIsOpen || mRegisteringSession != session) { + cameraCaptureSession.close(); + return; + } + failSession(session, cameraCaptureSession, + "Failed to configure " + session.getClass().getSimpleName(), null); + } + }); + } catch (CameraAccessException | RuntimeException e) { + failSession(session, null, "Failed to create capture session", e); + } + } + + /** + * Asks the device for a session, naming a colour space when one was asked for. + * + *

A colour space belongs to the session configuration, which means the newer + * SessionConfiguration form of createCaptureSession and API 34. The older call is kept for + * everything else rather than replaced: it is the path every device this library has ever run + * on uses, and it has nothing to gain from being rewritten for a feature that is not in + * play.

+ */ + private void createCaptureSession(@NonNull List surfaces, + @NonNull CameraCaptureSession.StateCallback callback) throws CameraAccessException { + CameraDevice device = mCameraDevice; + if (device == null) { + throw new IllegalStateException("Camera has no device to configure"); + } + if (Build.VERSION.SDK_INT < 34 || getColorSpace() == CameraView.ColorSpace.SRGB) { + device.createCaptureSession(surfaces, callback, mHandler); + return; + } + android.graphics.ColorSpace.Named named = namedColorSpace(getColorSpace()); + if (named == null) { + device.createCaptureSession(surfaces, callback, mHandler); + return; + } + + List outputs = new ArrayList<>(surfaces.size()); + for (Surface surface : surfaces) { + outputs.add(new OutputConfiguration(surface)); + } + SessionConfiguration configuration = new SessionConfiguration( + SessionConfiguration.SESSION_REGULAR, outputs, mHandler::post, callback); + configuration.setColorSpace(named); + device.createCaptureSession(configuration); + } + + private void failSession(Session session, @Nullable CameraCaptureSession captureSession, + String message, @Nullable Throwable cause) { + Log.e(TAG, message, cause); + boolean ownsSession = mRegisteringSession == session || mActiveSession == session + || (captureSession != null && mCaptureSession == captureSession); + if (captureSession != null) { + captureSession.close(); + } + if (!ownsSession) { + closeSession(session); + return; + } + if (mCaptureSession == captureSession) { + mCaptureSession = null; + } + if (mRegisteringSession == session) { + mRegisteringSession = null; + } + if (mActiveSession == session) { + mActiveSession = null; + } + closeSession(session); + if (mIsOpen) { + mIsOpen = false; + mGeneration++; + closeCameraResources(); + onCameraError(new IllegalStateException(message, cause)); + } + } + + private void closeSession(@Nullable Session session) { + if (session == null) { + return; + } + try { + session.close(); + } catch (RuntimeException e) { + Log.e(TAG, "Failed to close Camera2 session resources", e); + } + } + + private void closeCameraResources() { + CameraCaptureSession captureSession = mCaptureSession; + Session registeringSession = mRegisteringSession; + Session activeSession = mActiveSession; + CameraDevice cameraDevice = mCameraDevice; + mCaptureSession = null; + mRegisteringSession = null; + mActiveSession = null; + mCameraDevice = null; + + if (captureSession != null) { + try { + captureSession.close(); + } catch (RuntimeException e) { + Log.e(TAG, "Failed to close Camera2 capture session", e); + } + } + closeSession(registeringSession); + if (activeSession != registeringSession) { + closeSession(activeSession); + } + if (cameraDevice != null) { + try { + cameraDevice.close(); + } catch (RuntimeException e) { + Log.e(TAG, "Failed to close Camera2 device", e); + } + } + mIsPaused = false; + mIsRecording = false; + } + + @RequiresPermission(Manifest.permission.CAMERA) + @Override + public void open() { + if (mIsOpen) { + return; + } + closeCameraResources(); + mIsOpen = true; + mReopenAttempts = 0; + mPendingOpenGeneration = 0; + mPendingCloseDevice = null; + openCamera(++mGeneration); + } + + @Override + public void close() { + mIsOpen = false; + mReopenAttempts = 0; + mPendingOpenGeneration = 0; + mPendingCloseDevice = null; + mGeneration++; + closeCameraResources(); + } + + @Override + public boolean hasFrontFacingCamera() { + try { + for (String cameraId : mCameraManager.getCameraIdList()) { + if (isFrontFacing(cameraId)) return true; + } + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to query camera", e); + } + return false; + } + + @Override + public boolean isUsingFrontFacingCamera() { + try { + return isFrontFacing(getActiveCamera()); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to query camera", e); + } + return false; + } + + @RequiresPermission(Manifest.permission.CAMERA) + @Override + public void toggleCamera() { + try { + String[] cameraIds = getAvailableCameraIds(); + if (cameraIds.length < 2) { + Log.w(TAG, "Cannot toggle camera: only one camera is available"); + return; + } + + String activeCamera = getActiveCamera(); + int position = 0; + while (position < cameraIds.length && !cameraIds[position].equals(activeCamera)) { + position++; + } + + switchCamera(cameraIds[(position + 1) % cameraIds.length]); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to toggle camera", e); + } + } + + @Override + @SuppressLint("MissingPermission") + public void setLensFacing(CameraView.LensFacing lensFacing) { + try { + String matchingCamera = preferredCamera(getAvailableCameraIds(), + lensFacing == CameraView.LensFacing.FRONT + ? CameraCharacteristics.LENS_FACING_FRONT + : CameraCharacteristics.LENS_FACING_BACK); + if (matchingCamera == null) { + Log.w(TAG, "No camera found for lens facing " + lensFacing); + return; + } + if (matchingCamera.equals(getActiveCamera())) { + return; + } + + switchCamera(matchingCamera); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to change lens facing", e); + } + } + + private void switchCamera(String cameraId) { + boolean shouldReopen = mIsOpen; + CameraDevice deviceToClose = mCameraDevice; + boolean mustAwaitDeviceClose = deviceToClose != null; + mIsOpen = false; + mReopenAttempts = 0; + mPendingOpenGeneration = 0; + mPendingCloseDevice = null; + mGeneration++; + closeCameraResources(); + mActiveCamera = cameraId; + if (shouldReopen) { + mIsOpen = true; + int nextGeneration = ++mGeneration; + if (mustAwaitDeviceClose) { + mPendingOpenGeneration = nextGeneration; + mPendingCloseDevice = deviceToClose; + } else { + openCamera(nextGeneration); + } + } + } + + @Override + public void focus(Rect focus, Rect metering) { + if (mCaptureSession == null) { + if (DEBUG) Log.w(TAG, "Cannot focus. No capture session."); + return; + } + + if (mActiveSession == null) { + if (DEBUG) Log.w(TAG, "Cannot focus. No active session."); + return; + } + + if (mCameraDevice == null) { + if (DEBUG) Log.w(TAG, "Cannot focus. No camera device."); + return; + } + + try { + if (!supportsFocus(getActiveCamera())) { + Log.w(TAG, "Focus not available on this camera"); + return; + } + + if (mActiveSession == null) { + Log.w(TAG, "No active session available"); + return; + } + + // Our metering Rect ranges from -1000 to 1000. We need to remap it to fit the camera dimensions (0 to width). + CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); + Rect arraySize = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); + if (arraySize == null) { + Log.w(TAG, "Unable to load the active array size"); + return; + } + resize(metering, arraySize.width(), arraySize.height()); + + // Now we can update our request + mActiveSession.setMeteringRectangle(new MeteringRectangle(metering, MeteringRectangle.METERING_WEIGHT_MAX)); + if (!mIsPaused) { + mActiveSession.onInvalidate(mCameraDevice, mCaptureSession); + } + } catch (CameraAccessException | RuntimeException e) { + // Crashes if the Camera is interacted with while still loading + Log.e(TAG, "Failed to focus", e); + } + } + + /** + * Resizes a Rect from its original dimensions of -1000 to 1000 to 0 to width/height. + */ + private static void resize(Rect metering, int maxWidth, int maxHeight) { + // We can calculate the new width by scaling it to its new dimensions + int newWidth = metering.width() * maxWidth / 2000; + int newHeight = metering.height() * maxHeight / 2000; + + // Then we calculate how far from the top/left corner it should be + int leftOffset = (metering.left + 1000) * maxWidth / 2000; + int topOffset = (metering.top + 1000) * maxHeight / 2000; + + // And now we can resize the Rect to its new dimensions + metering.left = leftOffset; + metering.top = topOffset; + metering.right = metering.left + newWidth; + metering.bottom = metering.top + newHeight; + } + + @Override + public void setZoomLevel(int zoomLevel) { + mZoomLevel = rangeLimit(zoomLevel); + + if (mCameraDevice == null || mCaptureSession == null || mActiveSession == null) { + if (DEBUG) Log.w(TAG, "No active session available"); + return; + } + + try { + CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); + Range ratioRange = zoomRatioRange(characteristics); + if (ratioRange != null) { + // The whole optical range, so the low end can reach an ultra-wide lens and the + // high end a telephoto, with the camera switching between them as it crosses the + // thresholds. A crop region could only ever zoom within one lens. + mActiveSession.setZoomRatio( + zoomRatioFor(ratioRange.getLower(), ratioRange.getUpper(), mZoomLevel)); + mActiveSession.setCropRegion(null); + } else { + Rect activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); + Float maxDigitalZoom = characteristics.get( + CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM); + if (activeArray == null || maxDigitalZoom == null || maxDigitalZoom <= 1f) { + mZoomLevel = 0; + Log.w(TAG, "Zoom not supported"); + return; + } + mActiveSession.setZoomRatio(null); + mActiveSession.setCropRegion( + calculateCropRegion(activeArray, maxDigitalZoom, mZoomLevel)); + } + if (!mIsPaused) { + mActiveSession.onInvalidate(mCameraDevice, mCaptureSession); + } + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to zoom", e); + } + } + + /** + * The camera's usable zoom ratio range, or null when the control is unavailable. + * + *

CONTROL_ZOOM_RATIO_RANGE arrives in API 30. A lower bound below one means the logical + * camera has a wider physical lens to switch to.

+ */ + @Nullable + private static Range zoomRatioRange(@NonNull CameraCharacteristics characteristics) { + if (Build.VERSION.SDK_INT < 30) { + return null; + } + Range range = characteristics.get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE); + if (range == null || range.getUpper() <= range.getLower()) { + return null; + } + return range; + } + + /** Maps a zoom level onto a ratio range, linearly from the widest lens to the longest. */ + static float zoomRatioFor(float minRatio, float maxRatio, int zoomLevel) { + float fraction = (float) rangeLimit(zoomLevel) / MAX_ZOOM_LEVEL; + return minRatio + (maxRatio - minRatio) * fraction; + } + + static Rect calculateCropRegion(Rect activeArray, float maxDigitalZoom, int zoomLevel) { + float fraction = (float) rangeLimit(zoomLevel) / MAX_ZOOM_LEVEL; + float zoom = 1f + (Math.max(1f, maxDigitalZoom) - 1f) * fraction; + int cropWidth = Math.max(1, (int) (activeArray.width() / zoom)); + int cropHeight = Math.max(1, (int) (activeArray.height() / zoom)); + int cropLeft = (activeArray.width() - cropWidth) / 2; + int cropTop = (activeArray.height() - cropHeight) / 2; + return new Rect( + activeArray.left + cropLeft, + activeArray.top + cropTop, + activeArray.left + cropLeft + cropWidth, + activeArray.top + cropTop + cropHeight); + } + + /** Clamps a caller's zoom level into the range this backend publishes. */ + private static int rangeLimit(int zoomLevel) { + return Math.max(0, Math.min(zoomLevel, MAX_ZOOM_LEVEL)); + } + + @Override + public int getZoomLevel() { + return mZoomLevel; + } + + /** + * The zoom scale, which is fixed rather than derived from the camera. + * + *

A device-dependent maximum made the scale mean something different on every phone, and + * something different again from the CameraX backend, so a caller could not drive one zoom + * control across both. The level is a position in the camera's range instead: 0 is the widest + * lens it has and {@link #MAX_ZOOM_LEVEL} the longest.

+ */ + @Override + public int getMaxZoomLevel() { + return MAX_ZOOM_LEVEL; + } + + @Override + public boolean hasFlash() { + try { + CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(getActiveCamera()); + Boolean hasFlash = (characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)); + if (hasFlash == null) { + return false; + } + return hasFlash; + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to query camera", e); + } + + return false; + } + + @Override + public boolean isZoomSupported() { + try { + CameraCharacteristics characteristics = + mCameraManager.getCameraCharacteristics(getActiveCamera()); + if (zoomRatioRange(characteristics) != null) { + return true; + } + Float maxDigitalZoom = + characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM); + return maxDigitalZoom != null && maxDigitalZoom > 1f; + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to query camera", e); + } + return false; + } + + @Override + public void pause() { + if (mCaptureSession == null) { + if (DEBUG) Log.w(TAG, "Cannot pause. No capture session."); + return; + } + + if (!mIsPaused) { + try { + mCaptureSession.stopRepeating(); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to pause the camera", e); + } + mIsPaused = true; + } else { + if (DEBUG) Log.w(TAG, "Cannot pause. Was never unpaused."); + } + } + + @Override + public void resume() { + try { + if (mCaptureSession == null) { + if (DEBUG) Log.w(TAG, "Cannot pause. No capture session."); + return; + } + + if (mActiveSession == null) { + if (DEBUG) Log.w(TAG, "Cannot pause. No active session."); + return; + } + + if (mCameraDevice == null) { + if (DEBUG) Log.w(TAG, "Cannot pause. No camera device."); + return; + } + + if (mIsPaused) { + try { + mActiveSession.onAvailable(mCameraDevice, mCaptureSession); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to resume the camera", e); + } + } else { + if (DEBUG) { + Log.w(TAG, "Cannot resume. Was never paused."); + } + } + } finally { + mIsPaused = false; + } + } + + @Override + public boolean isPaused() { + return mIsPaused; + } + + @Override + public void setQuality(CameraView.Quality quality) { + super.setQuality(quality); + + // When quality changes, we need to update our session with the new dimensions + if (mActiveSession != null) { + if (mActiveSession instanceof PictureSession) { + setSession(new PictureSession(this)); + } else if (mActiveSession instanceof VideoSession) { + setSession(new VideoSession(this, ((VideoSession) mActiveSession).getFile())); + } else if (mActiveSession instanceof StreamSession) { + // Ignored. Streams cannot be restarted so we'll update quality once the stream ends. + } + } + } + + @Override + public void setFlash(CameraView.Flash flash) { + super.setFlash(flash); + + // The strategy is carried by the repeating request, so the preview has to be reissued for + // auto-exposure to converge under the new mode before the next capture. + reissueRepeatingRequest("the flash strategy"); + } + + /** Rebuilds the repeating request, for a setting the request itself carries. */ + private void reissueRepeatingRequest(String what) { + mHandler.post(() -> { + if (mCameraDevice == null || mCaptureSession == null || mActiveSession == null + || mIsPaused) { + return; + } + try { + mActiveSession.onInvalidate(mCameraDevice, mCaptureSession); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to apply " + what, e); + } + }); + } + + /** + * Whether a picture can be taken while recording. + * + *

Camera2's mandatory stream combinations guarantee a preview, a recording and a still + * together from LIMITED hardware upwards - that combination is what a camera app's + * video-snapshot button uses - with the still no larger than the recording. LEGACY hardware + * guarantees nothing of the sort, and a session it cannot configure costs the recording as + * well as the picture, so there it records without one.

+ */ + @Override + public boolean isColorSpaceSupported(CameraView.ColorSpace colorSpace) { + if (colorSpace == CameraView.ColorSpace.SRGB) { + return true; + } + if (Build.VERSION.SDK_INT < 34) { + // The session could not be told about a colour space before API 34, so asking for one + // would silently produce sRGB anyway. + return false; + } + android.graphics.ColorSpace.Named named = namedColorSpace(colorSpace); + if (named == null) { + return false; + } + try { + android.hardware.camera2.params.ColorSpaceProfiles profiles = + mCameraManager.getCameraCharacteristics(getActiveCamera()) + .get(CameraCharacteristics.REQUEST_AVAILABLE_COLOR_SPACE_PROFILES); + return profiles != null + && profiles.getSupportedColorSpaces(ImageFormat.JPEG).contains(named); + } catch (CameraAccessException | RuntimeException error) { + if (DEBUG) Log.d(TAG, "Camera cannot report its colour space profiles", error); + return false; + } + } + + @Override + public void setColorSpace(CameraView.ColorSpace colorSpace) { + CameraView.ColorSpace before = getColorSpace(); + super.setColorSpace(colorSpace); + if (getColorSpace() != before) { + // The colour space belongs to the session, not to a request, so it only takes hold + // when the session is built again. + restartActiveSession(); + } + } + + /** + * The platform's name for a colour space, or null for one it does not have. + * + *

Only callable once the platform is known to be new enough: the return type itself only + * exists from API 26, so a caller that has not checked risks failing to load rather than + * getting a null.

+ */ + @RequiresApi(34) + @Nullable + private static android.graphics.ColorSpace.Named namedColorSpace( + CameraView.ColorSpace colorSpace) { + switch (colorSpace) { + case DISPLAY_P3: + return android.graphics.ColorSpace.Named.DISPLAY_P3; + case SRGB: + return android.graphics.ColorSpace.Named.SRGB; + default: + return null; + } + } + + /** Rebuilds the session, for a setting the session itself carries. */ + private void restartActiveSession() { + mHandler.post(() -> { + Session session = mActiveSession; + if (mCameraDevice == null || session == null || mIsPaused) { + return; + } + setSession(session instanceof PictureSession && !(session instanceof VideoSession) + ? new PictureSession(this) : session); + }); + } + + @Override + public boolean isSnapshotWhileRecordingSupported() { + return isRecordingSnapshotSupported(); + } + + boolean isRecordingSnapshotSupported() { + try { + Integer level = mCameraManager.getCameraCharacteristics(getActiveCamera()) + .get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); + return level != null + && level != CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY; + } catch (CameraAccessException | RuntimeException error) { + if (DEBUG) Log.d(TAG, "Camera cannot report its hardware level", error); + return false; + } + } + + @Override + public boolean isFaceDetectionSupported() { + return faceDetectMode() != null; + } + + @Override + protected boolean setFaceDetectionEnabled(boolean enabled) { + if (!enabled) { + boolean wasEnabled = mFaceDetectMode != null; + mFaceDetectMode = null; + if (wasEnabled) { + reissueRepeatingRequest("the end of face detection"); + } + return true; + } + Integer mode = faceDetectMode(); + if (mode == null) { + return false; + } + mFaceDetectMode = mode; + reissueRepeatingRequest("face detection"); + return true; + } + + /** + * The face detection mode the repeating request should ask for, or null for none. + * + *

FULL adds eye and mouth positions and an identity that persists while a face is tracked; + * SIMPLE gives only the bounds and a score. Both are computed by hardware that is already + * finding faces to focus and expose for, so the richer mode is preferred where it exists.

+ */ + @Nullable + private Integer faceDetectMode() { + try { + CameraCharacteristics characteristics = + mCameraManager.getCameraCharacteristics(getActiveCamera()); + int[] modes = characteristics.get( + CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES); + Integer maxFaces = + characteristics.get(CameraCharacteristics.STATISTICS_INFO_MAX_FACE_COUNT); + if (modes == null || maxFaces == null || maxFaces <= 0) { + return null; + } + boolean simple = false; + for (int mode : modes) { + if (mode == CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_FULL) { + return CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_FULL; + } + if (mode == CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE) { + simple = true; + } + } + return simple ? CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE : null; + } catch (CameraAccessException | RuntimeException error) { + if (DEBUG) Log.d(TAG, "Camera cannot report its face detection modes", error); + return null; + } + } + + /** The mode the repeating request is carrying, read by the sessions that build it. */ + @Nullable + Integer getFaceDetectMode() { + return mFaceDetectMode; + } + + /** + * Translates a capture result's faces and hands them to the view, on the main thread. + * + *

Called for every completed preview frame while face detection is on, so a camera that + * sees nothing is not reported over and over: an empty result is passed on once, to clear + * whatever was drawn, and then skipped until a face comes back.

+ */ + void onFacesCaptured(@NonNull CaptureResult result) { + android.hardware.camera2.params.Face[] detected = + result.get(CaptureResult.STATISTICS_FACES); + if (detected == null) { + detected = new android.hardware.camera2.params.Face[0]; + } + if (detected.length == 0 && mLastFaceCount == 0) { + return; + } + mLastFaceCount = detected.length; + + List faces = new ArrayList<>(detected.length); + for (android.hardware.camera2.params.Face face : detected) { + Rect bounds = face.getBounds(); + if (bounds == null) { + continue; + } + faces.add(Face.create(bounds, face.getScore(), face.getId(), + face.getLeftEyePosition(), face.getRightEyePosition(), + face.getMouthPosition())); + } + onFacesDetected(faces, faceToViewTransform()); + } + + /** + * Maps face bounds onto the view. + * + *

Faces are reported in active-array coordinates, so the region the preview is actually + * showing is the crop region when zoom is being done by cropping, and the whole array when the + * camera is handling zoom itself through CONTROL_ZOOM_RATIO. Rotation is the sensor's own + * orientation less the display's, which is what the preview transform applies.

+ */ + @NonNull + private Matrix faceToViewTransform() { + Rect region = mActiveSession == null ? null : mActiveSession.getCropRegion(); + if (region == null) { + region = activeArraySize(); + } + if (region == null) { + return new Matrix(); + } + return TransformMath.centerCrop(new RectF(region), + TransformMath.within360(getSensorOrientation() - getDisplayRotation()), + false /* the Camera2 preview is not mirrored */, + getView().getWidth(), getView().getHeight()); + } + + @Nullable + private Rect activeArraySize() { + try { + return mCameraManager.getCameraCharacteristics(getActiveCamera()) + .get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); + } catch (CameraAccessException | RuntimeException error) { + if (DEBUG) Log.d(TAG, "Camera cannot report its active array", error); + return null; + } + } + + @Override + public void takePicture(File file) { + if (file == null) { + throw new IllegalArgumentException("Picture destination cannot be null"); + } + if (mCaptureSession == null || mActiveSession == null || mCameraDevice == null) { + Log.w(TAG, "Cannot take picture before Camera2 preview is ready"); + onImageFailed(); + return; + } + + if (mActiveSession instanceof PictureSession) { + PictureSession pictureSession = (PictureSession) mActiveSession; + pictureSession.takePicture(file, mCameraDevice, mCaptureSession); + } else { + onImageFailed(); + } + } + + @RequiresPermission(Manifest.permission.RECORD_AUDIO) + @Override + public void startRecording(File file) { + if (file == null) { + throw new IllegalArgumentException("Video destination cannot be null"); + } + if (mCameraDevice == null || !mIsOpen) { + onVideoFailed(); + return; + } + if (mIsRecording) { + Log.w(TAG, "Ignoring duplicate Camera2 recording request"); + return; + } + + mIsRecording = true; + setSession(new VideoSession(this, file)); + } + + @Override + public void stopRecording() { + mIsRecording = false; + setSession(new PictureSession(this)); + } + + @Override + public boolean isRecording() { + return mIsRecording; + } + + @Override + public void showVideoConfirmation(File file) { + super.showVideoConfirmation(file); + mIsRecording = false; + } + + @Override + public void onVideoFailed() { + super.onVideoFailed(); + mIsRecording = false; + } + + @Override + protected void attachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { + setSession(new StreamSession(this, surfaceProvider)); + } + + @Override + protected void detachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { + setSession(new PictureSession(this)); + } + + void transformPreview(int previewWidth, int previewHeight) throws CameraAccessException { + int viewWidth = getWidth(); + int viewHeight = getHeight(); + if (previewWidth <= 0 || previewHeight <= 0 || viewWidth <= 0 || viewHeight <= 0) { + if (DEBUG) Log.w(TAG, "Skipping preview transform for zero-sized surface"); + return; + } + int displayOrientation = getDisplayRotation(); + int cameraOrientation = getSensorOrientation(getActiveCamera()); + + // Camera2 rotates the preview to always face in portrait mode, even if the phone is + // currently in landscape. This is great for portrait mode, because there's less work to be done. + // It's less great for landscape, because we have to undo it. Without any matrix modifications, + // the preview will be smushed into the aspect ratio of the view. + Matrix matrix = new Matrix(); + + // Camera2 reverses the preview width/height. + if (cameraOrientation != 0 && cameraOrientation != 180) { + int temp = previewWidth; + previewWidth = previewHeight; + previewHeight = temp; + } + + // We want to find the aspect ratio of the preview. Our goal is to stretch the image in + // our SurfaceView to match this ratio, so that the image doesn't looked smushed. + // This means the edges of the preview will be cut off. + float aspectRatio = (float) previewHeight / (float) previewWidth; + int newWidth, newHeight; + if (viewHeight > viewWidth * aspectRatio) { + newWidth = (int) Math.ceil(viewHeight / aspectRatio); + newHeight = viewHeight; + } else { + newWidth = viewWidth; + newHeight = (int) Math.ceil(viewWidth * aspectRatio); + } + + // For portrait, we've already been mostly stretched. For landscape, our image is rotated 90 degrees. + // Think of it as a sideways squished photo. We want to first streeeetch the height of the photo + // until it matches the aspect ratio we originally expected. Now we're no longer stretched + // (although we're wildly off screen, with only the far left sliver of the photo still + // visible on the screen, and our picture is still sideways). + float scaleX = (float) newWidth / (float) viewWidth; + float scaleY = (float) newHeight / (float) viewHeight; + + // However, we've actually stretched too much. The height of the picture is currently the + // width of our screen. When we rotate the picture, it'll be too large and we'll end up + // cropping a lot of the picture. That's what this step is for. We scale down the image so + // that the height of the photo (currently the width of the phone) becomes the height we + // want (the height of the phone, or slightly bigger, depending on aspect ratio). + float scale = 1f; + if (displayOrientation == 90 || displayOrientation == 270) { + boolean cropHeight = viewWidth > newHeight * viewHeight / newWidth; + if (cropHeight) { + // If we're cropping the top/bottom, then we want the widths to be exact + scale = (float) viewWidth / newHeight; + } else { + // If we're cropping the left/right, then we want the heights to be exact + scale = (float) viewHeight / newWidth; + } + newWidth = (int) Math.ceil(newWidth * scale); + newHeight = (int) Math.ceil(newHeight * scale); + scaleX *= scale; + scaleY *= scale; + } + + // Because we scaled the preview beyond the bounds of the view, we need to crop some of it. + // By translating the photo over, we'll move it into the center. + int translateX = (int) Math.ceil((viewWidth - newWidth) / 2d); + int translateY = (int) Math.ceil((viewHeight - newHeight) / 2d); + + // Due to the direction of rotation (90 vs 270), a 1 pixel offset can either put us + // exactly where we want to be, or it can put us 1px lower than we wanted. This is error + // correction for that. + if (displayOrientation == 270) { + translateX = (int) Math.floor((viewWidth - newWidth) / 2d); + translateY = (int) Math.floor((viewHeight - newHeight) / 2d); + } + + // Finally, with our photo scaled and centered, we apply a rotation. + int rotation = -displayOrientation; + + matrix.setScale(scaleX, scaleY); + matrix.postTranslate(translateX, translateY); + matrix.postRotate(rotation, (int) Math.ceil(viewWidth / 2d), (int) Math.ceil(viewHeight / 2d)); + + if (DEBUG) { + Log.d(TAG, format("transformPreview: displayOrientation=%s, cameraOrientation=%s, " + + "viewWidth=%s, viewHeight=%s, viewAspectRatio=%s, previewWidth=%s, previewHeight=%s, previewAspectRatio=%s, " + + "newWidth=%s, newHeight=%s, scaleX=%s, scaleY=%s, scale=%s, " + + "translateX=%s, translateY=%s, rotation=%s", + displayOrientation, cameraOrientation, viewWidth, viewHeight, + ((float) viewHeight / (float) viewWidth), previewWidth, previewHeight, aspectRatio, + newWidth, newHeight, scaleX, scaleY, scale, translateX, translateY, rotation)); + } + + setTransform(matrix); + } + + @Override + protected int getRelativeCameraOrientation() { + try { + return getRelativeImageOrientation(getDisplayRotation(), getSensorOrientation(getActiveCamera()), isUsingFrontFacingCamera(), false); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to query camera", e); + return 0; + } + } + + @NonNull + String getActiveCamera() throws CameraAccessException { + String[] cameraIds = getAvailableCameraIds(); + if (mActiveCamera != null) { + for (String cameraId : cameraIds) { + if (cameraId.equals(mActiveCamera)) { + return cameraId; + } + } + Log.w(TAG, "Previously selected camera is no longer available: " + mActiveCamera); + mActiveCamera = null; + } + String backFacing = preferredCamera(cameraIds, CameraCharacteristics.LENS_FACING_BACK); + if (backFacing != null) { + return backFacing; + } + String anyCamera = preferredCamera(cameraIds, null); + return anyCamera == null ? cameraIds[0] : anyCamera; + } + + /** + * The camera we would rather open, among those matching a lens facing. + * + *

Ranked by {@link #devicePreference}, so a built-in sensor wins over a USB webcam or a + * virtual camera that happens to be listed first or to report the same lens facing.

+ * + * @param lensFacing the facing to match, or null for any + */ + @Nullable + private String preferredCamera(@NonNull String[] cameraIds, @Nullable Integer lensFacing) { + String best = null; + int bestPreference = Integer.MAX_VALUE; + for (String cameraId : cameraIds) { + try { + if (lensFacing != null) { + Integer facing = mCameraManager.getCameraCharacteristics(cameraId) + .get(CameraCharacteristics.LENS_FACING); + if (facing == null || !facing.equals(lensFacing)) { + continue; + } + } + int preference = devicePreference(cameraId); + if (preference < bestPreference) { + best = cameraId; + bestPreference = preference; + } + } catch (CameraAccessException | RuntimeException error) { + Log.w(TAG, "Unable to inspect camera " + cameraId, error); + } + } + return best; + } + + /** + * How much we prefer a camera when nothing has been chosen yet, lowest first. + * + *

INFO_DEVICE_TYPE arrives in API 37 and is the first way to tell a built-in sensor from a + * USB webcam or a virtual camera. Before it, every entry in the list looked alike, so a + * plugged-in webcam reporting itself as back-facing could become the default camera. External + * and virtual cameras stay in the list for {@link #toggleCamera()} to reach; they just stop + * being picked by default.

+ */ + private int devicePreference(@NonNull String cameraId) throws CameraAccessException { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.CINNAMON_BUN) { + return 0; + } + Integer deviceType = mCameraManager.getCameraCharacteristics(cameraId) + .get(CameraCharacteristics.INFO_DEVICE_TYPE); + if (deviceType == null) { + return 1; + } + switch (deviceType) { + case CameraMetadata.INFO_DEVICE_TYPE_BUILT_IN: + return 0; + case CameraMetadata.INFO_DEVICE_TYPE_UNKNOWN: + return 1; + case CameraMetadata.INFO_DEVICE_TYPE_EXTERNAL: + case CameraMetadata.INFO_DEVICE_TYPE_VIRTUAL: + default: + return 2; + } + } + + private String[] getAvailableCameraIds() throws CameraAccessException { + String[] cameraIds = mCameraManager.getCameraIdList(); + if (cameraIds.length == 0) { + throw new IllegalStateException("No cameras are available on this device"); + } + return cameraIds; + } + + private boolean supportsFocus(String cameraId) throws CameraAccessException { + CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); + Integer maxRegions = characteristics.get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF); + return maxRegions != null && maxRegions >= 1; + } + + private boolean isFrontFacing(String cameraId) throws CameraAccessException { + CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); + Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); + return facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT; + } + + private boolean isBackFacing(String cameraId) throws CameraAccessException { + CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); + Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); + return facing != null && facing == CameraCharacteristics.LENS_FACING_BACK; + } + + private int getSensorOrientation(String cameraId) throws CameraAccessException { + CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); + Integer orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); + return orientation == null ? 0 : orientation; + } + + protected int getSensorOrientation() { + try { + return getSensorOrientation(getActiveCamera()); + } catch (CameraAccessException | RuntimeException e) { + return 0; + } + } + + Handler getHandler() { + return mHandler; + } + + @Override + public Parcelable onSaveInstanceState() { + Bundle state = new Bundle(); + state.putString(EXTRA_DEVICE_ID, mActiveCamera); + return state; + } + + @Override + public void onRestoreInstanceState(Parcelable state) { + if (state instanceof Bundle) { + mActiveCamera = ((Bundle) state).getString(EXTRA_DEVICE_ID); + } + } + + @Override + public void onLayoutChanged() { + if (mActiveSession != null) { + try { + mActiveSession.onLayoutChanged(); + } catch (CameraAccessException | RuntimeException e) { + Log.e(TAG, "Failed to adjust the camera after a layout change", e); + } + } + } + + /** + * A session has multiple surfaces for the camera to draw to. + */ + interface Session { + void initialize(@NonNull StreamConfigurationMap map) throws CameraAccessException; + void onLayoutChanged() throws CameraAccessException; + @NonNull List getSurfaces(); + void setMeteringRectangle(@Nullable MeteringRectangle meteringRectangle); + @Nullable MeteringRectangle getMeteringRectangle(); + void setCropRegion(@Nullable Rect region); + @Nullable Rect getCropRegion(); + void setZoomRatio(@Nullable Float zoomRatio); + @Nullable Float getZoomRatio(); + void onAvailable(@NonNull CameraDevice cameraDevice, @NonNull CameraCaptureSession session) throws CameraAccessException; + void onInvalidate(@NonNull CameraDevice cameraDevice, @NonNull CameraCaptureSession session) throws CameraAccessException; + void close(); + } +} diff --git a/camera-view/src/main/java/com/xlythe/view/camera/v2/PictureSession.java b/camera-view/src/main/java/com/xlythe/view/camera/v2/PictureSession.java index 0f61564..f220d1f 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/v2/PictureSession.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/v2/PictureSession.java @@ -32,6 +32,7 @@ import java.util.List; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import androidx.annotation.UiThread; import androidx.annotation.WorkerThread; @@ -68,14 +69,46 @@ class PictureSession extends PreviewSession { @Override public void initialize(@NonNull StreamConfigurationMap map) throws CameraAccessException { super.initialize(map); - mPictureSurface.initialize(map); + // Both the still size and anything a subclass adds are chosen from the preview's, so the + // hook goes between the two: a recording session sizes its video here and the still is + // then capped to it. + onPreviewInitialized(map); + if (hasStillCapture()) { + mPictureSurface.initialize(map, maxPictureSize()); + } + } + + /** Lets a subclass add its own outputs once the preview has a size and before the still does. */ + protected void onPreviewInitialized(@NonNull StreamConfigurationMap map) + throws CameraAccessException {} + + /** + * Whether this session carries a still-capture output at all. + * + *

A session that cannot take a picture does not pay for the reader or the stream slot.

+ */ + protected boolean hasStillCapture() { + return true; + } + + /** + * The largest still this session may ask for, or null for the largest the camera offers. + * + *

Only a recording session needs this: the combination of a preview, a recording and a + * still is guaranteed by Camera2 at the recording size, not at the sensor's maximum.

+ */ + @Nullable + protected Size maxPictureSize() { + return null; } @NonNull @Override public List getSurfaces() { List surfaces = super.getSurfaces(); - surfaces.add(mPictureSurface.getSurface()); + if (hasStillCapture()) { + surfaces.add(mPictureSurface.getSurface()); + } return surfaces; } @@ -86,32 +119,23 @@ public void close() { } void takePicture(@NonNull File file, @NonNull CameraDevice device, @NonNull CameraCaptureSession session) { + if (!hasStillCapture()) { + Log.w(TAG, "This camera cannot take a picture in its current configuration"); + onImageFailed(); + return; + } mPictureSurface.initializePicture(file); try { CaptureRequest.Builder builder = device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); - if (hasFlash()) { - switch (getFlash()) { - case AUTO: - // TODO: This doesn't work :( - builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); - break; - case ON: - builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_SINGLE); - break; - case OFF: - builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); - break; - } - } + applyFlash(builder); builder.addTarget(mPictureSurface.getSurface()); if (mMeteringRectangle != null) { builder.set(CaptureRequest.CONTROL_AE_REGIONS, new MeteringRectangle[]{mMeteringRectangle}); builder.set(CaptureRequest.CONTROL_AF_REGIONS, new MeteringRectangle[]{mMeteringRectangle}); } - if (mCropRegion != null) { - builder.set(CaptureRequest.SCALER_CROP_REGION, mCropRegion); - } + applyZoom(builder); + builder.set(CaptureRequest.JPEG_QUALITY, (byte) getPictureQuality()); session.capture(builder.build(), null /* callback */, getHandler()); } catch (CameraAccessException | IllegalStateException | IllegalArgumentException e) { // Crashes if the Camera is interacted with while still loading @@ -120,7 +144,7 @@ void takePicture(@NonNull File file, @NonNull CameraDevice device, @NonNull Came } } - private static class ImageSaver extends AsyncTask { + private static class ImageSaver extends AsyncTask { private final Context mContext; // The image that was captured @@ -144,26 +168,32 @@ private static class ImageSaver extends AsyncTask { mFile = file; } + /** @return true only when the picture reached disk, so a failure is never reported as one. */ @WorkerThread @Override - protected Void doInBackground(Void... params) { + protected Boolean doInBackground(Void... params) { // Finally, we save the file to disk - byte[] bytes = getBytes(); + byte[] bytes; + try { + bytes = getBytes(); + } finally { + mImage.close(); + } if (bytes == null) { Log.e(TAG, "Failed to get bytes from image"); - mImage.close(); - return null; + return false; } try (FileOutputStream output = new FileOutputStream(mFile)) { output.write(bytes); - } catch (IOException e) { + } catch (IOException | RuntimeException e) { Log.e(TAG, "Failed to write the file", e); - mImage.close(); - return null; + // Leave no truncated file behind for a caller that is told the capture failed. + if (mFile.exists() && !mFile.delete()) { + Log.w(TAG, "Failed to clean up a partially written picture"); + } + return false; } - mImage.close(); - try { Exif exif = new Exif(mFile); exif.attachTimestamp(); @@ -180,7 +210,7 @@ protected Void doInBackground(Void... params) { Log.e(TAG, "Failed to update EXIF", e); } - return null; + return true; } private byte[] getBytes() { @@ -311,8 +341,12 @@ public void onImageAvailable(final ImageReader reader) { mFile) { @UiThread @Override - protected void onPostExecute(Void aVoid) { - showImageConfirmation(file); + protected void onPostExecute(Boolean saved) { + if (Boolean.TRUE.equals(saved)) { + showImageConfirmation(file); + } else { + onImageFailed(); + } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); mFile = null; @@ -330,7 +364,6 @@ protected void onPostExecute(Void aVoid) { private final CameraSurface mPreviewSurface; private ImageReader mImageReader; private File mFile; - private boolean mIsTakingPhoto = false; PictureSurface(Camera2Module camera2Module, CameraSurface previewSurface) { super(camera2Module); @@ -339,8 +372,12 @@ protected void onPostExecute(Void aVoid) { @Override void initialize(StreamConfigurationMap map) { + initialize(map, null /* maxSize */); + } + + void initialize(StreamConfigurationMap map, @Nullable Size maxSize) { if (DEBUG) Log.d(TAG, "Initializing PictureSession"); - super.initialize(chooseSize(getSizes(map), mPreviewSurface.mSize)); + super.initialize(chooseSize(within(getSizes(map), maxSize), mPreviewSurface.mSize)); mImageReader = ImageReader.newInstance(getWidth(), getHeight(), getImageFormat(getQuality()), 1 /* maxImages */); mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mCameraView.getHandler()); } @@ -387,13 +424,4 @@ private static int getImageFormat(CameraView.Quality quality) { return IMAGE_FORMAT_DEFAULT; } } - - private static boolean isRaw(int imageFormat) { - switch (imageFormat) { - case ImageFormat.YUV_420_888: - return true; - default: - return false; - } - } } diff --git a/camera-view/src/main/java/com/xlythe/view/camera/v2/PreviewSession.java b/camera-view/src/main/java/com/xlythe/view/camera/v2/PreviewSession.java index 260df79..0722db9 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/v2/PreviewSession.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/v2/PreviewSession.java @@ -13,6 +13,7 @@ import android.view.Surface; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -54,25 +55,25 @@ public void onLayoutChanged() throws CameraAccessException { private CaptureRequest createCaptureRequest(@NonNull CameraDevice device) throws CameraAccessException { CaptureRequest.Builder builder = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); + applyFlash(builder); if (mMeteringRectangle != null) { builder.set(CaptureRequest.CONTROL_AE_REGIONS, new MeteringRectangle[]{mMeteringRectangle}); builder.set(CaptureRequest.CONTROL_AF_REGIONS, new MeteringRectangle[]{mMeteringRectangle}); } - if (mCropRegion != null) { - builder.set(CaptureRequest.SCALER_CROP_REGION, mCropRegion); - } + applyZoom(builder); + applyFaceDetection(builder); builder.addTarget(mPreviewSurface.getSurface()); return builder.build(); } @Override public void onAvailable(@NonNull CameraDevice device, @NonNull CameraCaptureSession session) throws CameraAccessException { - session.setRepeatingRequest(createCaptureRequest(device), null /* callback */, getHandler()); + session.setRepeatingRequest(createCaptureRequest(device), repeatingCallback(), getHandler()); } @Override public void onInvalidate(@NonNull CameraDevice device, @NonNull CameraCaptureSession session) throws CameraAccessException { - session.setRepeatingRequest(createCaptureRequest(device), null /* callback */, getHandler()); + session.setRepeatingRequest(createCaptureRequest(device), repeatingCallback(), getHandler()); } @NonNull @@ -95,6 +96,9 @@ private Size chooseOptimalSize(List choices, int viewWidth, int viewHeight if (DEBUG) { Log.d(TAG, "Choosing from sizes " + choices); } + if (choices.isEmpty()) { + throw new IllegalStateException("Camera reports no preview sizes"); + } // These sizes are all larger than our view port, so we won't have to scale the image up. List availableSizes = new ArrayList<>(choices.size()); @@ -117,7 +121,8 @@ private Size chooseOptimalSize(List choices, int viewWidth, int viewHeight } private List getSizes(StreamConfigurationMap map) { - return filter(map.getOutputSizes(SurfaceTexture.class)); + Size[] supported = map.getOutputSizes(SurfaceTexture.class); + return filter(supported, mCameraView.getPreviewSizeCap(Arrays.asList(supported))); } private Surface mSurface; diff --git a/camera-view/src/main/java/com/xlythe/view/camera/v2/SessionImpl.java b/camera-view/src/main/java/com/xlythe/view/camera/v2/SessionImpl.java index 9f24169..bed7ab8 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/v2/SessionImpl.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/v2/SessionImpl.java @@ -5,9 +5,13 @@ import android.content.Context; import android.graphics.Rect; import android.hardware.camera2.CameraAccessException; +import android.hardware.camera2.CameraCaptureSession; +import android.hardware.camera2.CaptureRequest; +import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.MeteringRectangle; import android.hardware.camera2.params.StreamConfigurationMap; import android.location.Location; +import android.os.Build; import android.os.Handler; import android.util.Log; import android.util.Size; @@ -48,6 +52,10 @@ abstract class SessionImpl implements Camera2Module.Session { @Nullable Rect mCropRegion; + /** Zoom as a ratio across the camera's whole range, which can switch physical lenses. */ + @Nullable + Float mZoomRatio; + SessionImpl(Camera2Module camera2Module) { mCamera2Module = camera2Module; } @@ -69,6 +77,92 @@ CameraView.Flash getFlash() { return mCamera2Module.getFlash(); } + /** + * Applies the requested flash strategy to a capture request. + * + *

Camera2 drives the flash through CONTROL_AE_MODE; FLASH_MODE is ignored unless the + * auto-exposure routine has been told not to manage the flash itself. The mode also has to be + * on the repeating preview request, because that is the only stream auto-exposure can converge + * over before a still capture. AOSP's Camera2Basic applies it to both builders for the same + * reason.

+ */ + /** + * Asks the camera for the faces it is tracking, when something wants them. + * + *

Face detection is a mode on the request rather than a one-off query, so it has to be on + * the repeating preview request; the results then arrive with each completed frame.

+ */ + /** + * The sizes that fit inside a bound, or all of them when none do. + * + *

Falling back to all of them rather than to nothing matters: a bound no size fits is a + * reason to pick badly, not a reason to have no output at all.

+ */ + @NonNull + static List within(@NonNull List sizes, @Nullable Size maxSize) { + if (maxSize == null) { + return sizes; + } + List fitting = new ArrayList<>(sizes.size()); + for (Size size : sizes) { + if (size.getWidth() <= maxSize.getWidth() && size.getHeight() <= maxSize.getHeight()) { + fitting.add(size); + } + } + return fitting.isEmpty() ? sizes : fitting; + } + + void applyFaceDetection(@NonNull CaptureRequest.Builder builder) { + Integer mode = mCamera2Module.getFaceDetectMode(); + if (mode != null) { + builder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, mode); + } + } + + /** + * The callback the repeating request needs, or null when nothing is listening. + * + *

A null callback is what the session passes by default: the camera then does not have to + * deliver results at all, which is one fewer thing happening per frame.

+ */ + @Nullable + CameraCaptureSession.CaptureCallback repeatingCallback() { + if (mCamera2Module.getFaceDetectMode() == null) { + return null; + } + return new CameraCaptureSession.CaptureCallback() { + @Override + public void onCaptureCompleted(@NonNull CameraCaptureSession session, + @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { + mCamera2Module.onFacesCaptured(result); + } + }; + } + + int getPictureQuality() { + return mCamera2Module.getPictureQuality(); + } + + void applyFlash(@NonNull CaptureRequest.Builder builder) { + if (!hasFlash()) { + return; + } + switch (getFlash()) { + case AUTO: + builder.set(CaptureRequest.CONTROL_AE_MODE, + CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); + break; + case ON: + builder.set(CaptureRequest.CONTROL_AE_MODE, + CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH); + break; + case OFF: + builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); + builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); + break; + } + } + int getRelativeCameraOrientation() { return mCamera2Module.getRelativeCameraOrientation(); } @@ -92,6 +186,33 @@ public MeteringRectangle getMeteringRectangle() { return mMeteringRectangle; } + /** + * Applies zoom to a capture request. + * + *

Prefers CONTROL_ZOOM_RATIO, which is the only control that lets the camera switch + * between the physical lenses behind a logical camera, so a ratio below one reaches an + * ultra-wide and a high ratio reaches a telephoto. SCALER_CROP_REGION only ever crops the + * sensor of the lens already in use, so it is the fallback for older devices.

+ */ + void applyZoom(@NonNull CaptureRequest.Builder builder) { + if (Build.VERSION.SDK_INT >= 30 && mZoomRatio != null) { + builder.set(CaptureRequest.CONTROL_ZOOM_RATIO, mZoomRatio); + } else if (mCropRegion != null) { + builder.set(CaptureRequest.SCALER_CROP_REGION, mCropRegion); + } + } + + @Override + public void setZoomRatio(@Nullable Float zoomRatio) { + mZoomRatio = zoomRatio; + } + + @Nullable + @Override + public Float getZoomRatio() { + return mZoomRatio; + } + @Override public void setCropRegion(@Nullable Rect region) { mCropRegion = region; diff --git a/camera-view/src/main/java/com/xlythe/view/camera/v2/StreamSession.java b/camera-view/src/main/java/com/xlythe/view/camera/v2/StreamSession.java index 635a950..0c64d74 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/v2/StreamSession.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/v2/StreamSession.java @@ -1,45 +1,24 @@ package com.xlythe.view.camera.v2; import android.annotation.TargetApi; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.ImageFormat; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Rect; -import android.graphics.YuvImage; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; -import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.MeteringRectangle; import android.hardware.camera2.params.StreamConfigurationMap; -import android.location.Location; -import android.media.Image; -import android.media.ImageReader; -import android.os.AsyncTask; -import android.os.Build; +import android.media.MediaCodec; import android.util.Log; import android.util.Size; import android.view.Surface; import androidx.annotation.NonNull; -import androidx.annotation.UiThread; -import androidx.annotation.WorkerThread; -import com.xlythe.view.camera.CameraView; -import com.xlythe.view.camera.Exif; import com.xlythe.view.camera.stream.VideoRecorder; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; import java.util.Arrays; +import java.util.Collections; import java.util.List; import static com.xlythe.view.camera.ICameraModule.DEBUG; @@ -72,9 +51,8 @@ private CaptureRequest createCaptureRequest(@NonNull CameraDevice device) throws builder.set(CaptureRequest.CONTROL_AE_REGIONS, new MeteringRectangle[]{mMeteringRectangle}); builder.set(CaptureRequest.CONTROL_AF_REGIONS, new MeteringRectangle[]{mMeteringRectangle}); } - if (mCropRegion != null) { - builder.set(CaptureRequest.SCALER_CROP_REGION, mCropRegion); - } + applyZoom(builder); + applyFaceDetection(builder); builder.addTarget(getPreviewSurface().getSurface()); builder.addTarget(mStreamSurface.getSurface()); return builder.build(); @@ -82,12 +60,12 @@ private CaptureRequest createCaptureRequest(@NonNull CameraDevice device) throws @Override public void onAvailable(@NonNull CameraDevice device, @NonNull CameraCaptureSession session) throws CameraAccessException { - session.setRepeatingRequest(createCaptureRequest(device), null /* callback */, getHandler()); + session.setRepeatingRequest(createCaptureRequest(device), repeatingCallback(), getHandler()); } @Override public void onInvalidate(@NonNull CameraDevice device, @NonNull CameraCaptureSession session) throws CameraAccessException { - session.setRepeatingRequest(createCaptureRequest(device), null /* callback */, getHandler()); + session.setRepeatingRequest(createCaptureRequest(device), repeatingCallback(), getHandler()); } @NonNull @@ -117,6 +95,32 @@ private static final class StreamSurface extends CameraSurface { @Override void initialize(StreamConfigurationMap map) { if (DEBUG) Log.d(TAG, "Initializing StreamSession"); + + Size maxSize = mSurfaceProvider.getMaxSize(); + if (maxSize == null) { + super.initialize(mPreviewSurface.mSize); + return; + } + + // The caller is sending this somewhere the preview resolution will not fit. Take the + // largest size the camera can feed MediaCodec within the bound, since an arbitrary + // size is not guaranteed to configure. + Size[] supported = map.getOutputSizes(MediaCodec.class); + List candidates = filter(supported, maxSize); + if (!candidates.isEmpty()) { + super.initialize(Collections.max(candidates, new CompareSizesByArea())); + return; + } + + // Nothing fits. The cap is there because of a bandwidth ceiling, so overshoot it by as + // little as possible rather than falling back to the preview, which is larger still. + if (supported.length > 0) { + Size smallest = Collections.min(Arrays.asList(supported), new CompareSizesByArea()); + Log.w(TAG, "No stream size within " + maxSize + ", using " + smallest); + super.initialize(smallest); + return; + } + Log.w(TAG, "Camera reports no MediaCodec sizes, falling back to the preview"); super.initialize(mPreviewSurface.mSize); } @@ -127,7 +131,9 @@ Surface getSurface() { @Override void close() { - mPreviewSurface.close(); + // The Surface belongs to the VideoRecorder that handed it over, and the preview + // Surface belongs to PreviewSession, which closes it from super.close(). Closing + // the preview from here only closed it a second time and never released this one. } } } diff --git a/camera-view/src/main/java/com/xlythe/view/camera/v2/VideoSession.java b/camera-view/src/main/java/com/xlythe/view/camera/v2/VideoSession.java index 706f217..c0e18f3 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/v2/VideoSession.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/v2/VideoSession.java @@ -1,5 +1,6 @@ package com.xlythe.view.camera.v2; +import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; @@ -16,18 +17,21 @@ import android.util.Size; import android.view.Surface; +import com.xlythe.view.camera.CameraView; + import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import static com.xlythe.view.camera.ICameraModule.DEBUG; import static com.xlythe.view.camera.ICameraModule.TAG; @TargetApi(21) -class VideoSession extends PreviewSession { +class VideoSession extends PictureSession { /** * The VideoSurface must always check CamcorderProfile to see if the outputs supported by the * camera are also supported by MediaRecorder. Bizarre as it sounds, @@ -35,16 +39,48 @@ class VideoSession extends PreviewSession { * sizes it gives back. Because MediaRecorder is always (at most) limited to 4k recording, that * is our max video size. */ + /** Floor for a rescaled bit rate, below which even a small frame looks broken. */ + private static final int MIN_VIDEO_BIT_RATE = 64_000; + /** Ceiling for a rescaled bit rate, so a 4K profile cannot run away on an odd device. */ + private static final int MAX_VIDEO_BIT_RATE = 100_000_000; + private final VideoSurface mVideoSurface; + /** Whether this session carries a still output alongside the recording. */ + private final boolean mSnapshotSupported; + VideoSession(Camera2Module camera2Module, File file) { super(camera2Module); mVideoSurface = new VideoSurface(camera2Module, file, getPreviewSurface()); + mSnapshotSupported = camera2Module.isRecordingSnapshotSupported(); + } + + /** + * Whether a picture can be taken while this session is recording. + * + *

Camera2 guarantees a preview, a recording and a still together from LIMITED hardware + * upwards - it is the combination every camera app's video-snapshot button uses - but only + * with the still no larger than the recording, which is what {@link #maxPictureSize} says. + * A LEGACY camera has no such guarantee, so it records without one rather than risking a + * session it cannot configure.

+ */ + @Override + protected boolean hasStillCapture() { + return mSnapshotSupported; } + @Nullable @Override - public void initialize(@NonNull StreamConfigurationMap map) throws CameraAccessException { - super.initialize(map); + protected Size maxPictureSize() { + return mVideoSurface.mIsInitialized + ? new Size(mVideoSurface.getWidth(), mVideoSurface.getHeight()) + : null; + } + + @Override + @SuppressLint({"WrongThread", "ThreadConstraint"}) + protected void onPreviewInitialized(@NonNull StreamConfigurationMap map) + throws CameraAccessException { mVideoSurface.initialize(map); if (!mVideoSurface.mIsInitialized) { onVideoFailed(); @@ -59,9 +95,8 @@ private CaptureRequest createCaptureRequest(@NonNull CameraDevice device) throws builder.set(CaptureRequest.CONTROL_AE_REGIONS, new MeteringRectangle[]{mMeteringRectangle}); builder.set(CaptureRequest.CONTROL_AF_REGIONS, new MeteringRectangle[]{mMeteringRectangle}); } - if (mCropRegion != null) { - builder.set(CaptureRequest.SCALER_CROP_REGION, mCropRegion); - } + applyZoom(builder); + applyFaceDetection(builder); builder.addTarget(getPreviewSurface().getSurface()); builder.addTarget(mVideoSurface.getSurface()); return builder.build(); @@ -82,6 +117,11 @@ public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull C mVideoSurface.mAwaitingRecording = false; mVideoSurface.startRecording(); } + // Recording does not stop whoever is watching for faces. + CameraCaptureSession.CaptureCallback faces = repeatingCallback(); + if (faces != null) { + faces.onCaptureCompleted(session, request, result); + } } }, getHandler()); } @@ -98,7 +138,7 @@ public void onInvalidate(@NonNull CameraDevice device, @NonNull CameraCaptureSes return; } - session.setRepeatingRequest(createCaptureRequest(device), null /* callback */, getHandler()); + session.setRepeatingRequest(createCaptureRequest(device), repeatingCallback(), getHandler()); } @Override @@ -124,7 +164,57 @@ boolean isRecording() { return mVideoSurface.isRecording(); } - private static final class VideoSurface extends CameraSurface { + static final class VideoSurface extends CameraSurface { + /** + * The best profile the camera actually has for a requested quality, stepping down until + * one exists. QUALITY_LOW is guaranteed on every camera, so it is the floor. + */ + private static CamcorderProfile chooseProfile(int cameraId, CameraView.Quality quality) { + int[] preferences; + switch (quality) { + case MAX: + preferences = new int[] {CamcorderProfile.QUALITY_2160P, + CamcorderProfile.QUALITY_1080P, CamcorderProfile.QUALITY_720P, + CamcorderProfile.QUALITY_480P}; + break; + case HIGH: + preferences = new int[] {CamcorderProfile.QUALITY_1080P, + CamcorderProfile.QUALITY_720P, CamcorderProfile.QUALITY_480P}; + break; + case MEDIUM: + preferences = new int[] {CamcorderProfile.QUALITY_720P, + CamcorderProfile.QUALITY_480P}; + break; + case LOW: + default: + preferences = new int[] {CamcorderProfile.QUALITY_480P}; + break; + } + for (int preference : preferences) { + if (CamcorderProfile.hasProfile(cameraId, preference)) { + return CamcorderProfile.get(cameraId, preference); + } + } + return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_LOW); + } + + /** + * Rescales a profile's bit rate for the frame size actually being recorded. + * + *

Bit rate requirements track pixel count closely enough for this, and the result is + * clamped so an odd profile cannot produce an unusable rate.

+ */ + static int scaleBitRate(int profileBitRate, int profileWidth, int profileHeight, + int width, int height) { + long profilePixels = (long) profileWidth * profileHeight; + long pixels = (long) width * height; + if (profileBitRate <= 0 || profilePixels <= 0 || pixels <= 0) { + return Math.max(MIN_VIDEO_BIT_RATE, profileBitRate); + } + long scaled = (long) profileBitRate * pixels / profilePixels; + return (int) Math.max(MIN_VIDEO_BIT_RATE, Math.min(scaled, MAX_VIDEO_BIT_RATE)); + } + private int getIntCameraId() { try { return Integer.parseInt(getCameraId()); @@ -195,35 +285,8 @@ void initialize(StreamConfigurationMap map) { mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); int intCameraId = getIntCameraId(); - switch (getQuality()) { - case MAX: - if (CamcorderProfile.hasProfile(intCameraId, CamcorderProfile.QUALITY_2160P)) { - mMediaRecorder.setProfile(CamcorderProfile.get(intCameraId, CamcorderProfile.QUALITY_2160P)); - break; - } - // Fall-through - case HIGH: - if (CamcorderProfile.hasProfile(intCameraId, CamcorderProfile.QUALITY_1080P)) { - mMediaRecorder.setProfile(CamcorderProfile.get(intCameraId, CamcorderProfile.QUALITY_1080P)); - break; - } - // Fall-through - case MEDIUM: - if (CamcorderProfile.hasProfile(intCameraId, CamcorderProfile.QUALITY_720P)) { - mMediaRecorder.setProfile(CamcorderProfile.get(intCameraId, CamcorderProfile.QUALITY_720P)); - break; - } - // Fall-through - case LOW: - if (CamcorderProfile.hasProfile(intCameraId, CamcorderProfile.QUALITY_480P)) { - mMediaRecorder.setProfile(CamcorderProfile.get(intCameraId, CamcorderProfile.QUALITY_480P)); - break; - } - // Fall-through - default: - mMediaRecorder.setProfile(CamcorderProfile.get(intCameraId, CamcorderProfile.QUALITY_LOW)); - break; - } + CamcorderProfile profile = chooseProfile(intCameraId, getQuality()); + mMediaRecorder.setProfile(profile); mMediaRecorder.setOutputFile(mFile.getAbsolutePath()); mMediaRecorder.setMaxDuration((int) mCameraView.getMaxVideoDuration()); mMediaRecorder.setMaxFileSize(mCameraView.getMaxVideoSize()); @@ -231,13 +294,22 @@ void initialize(StreamConfigurationMap map) { switch (what) { case MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED: Log.w(TAG, "Max duration for recording reached"); + finishLimitedRecording(); break; case MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED: Log.w(TAG, "Max filesize for recording reached"); + finishLimitedRecording(); break; } }); mMediaRecorder.setVideoSize(getWidth(), getHeight()); + // setProfile fixed the bit rate to the profile's own resolution, but the size + // above is chosen separately, from what the camera supports at this quality and + // at the preview's aspect ratio, so the two routinely disagree. Left alone, a + // smaller frame is written at a wastefully high rate and a larger one is starved. + mMediaRecorder.setVideoEncodingBitRate(scaleBitRate( + profile.videoBitRate, profile.videoFrameWidth, profile.videoFrameHeight, + getWidth(), getHeight())); mMediaRecorder.setOrientationHint(mCameraView.getRelativeCameraOrientation()); Location location = getLocation(getContext()); @@ -280,6 +352,20 @@ void startRecording() { } } + /** + * Delivers a recording that MediaRecorder ended on its own because the duration or file + * size limit was reached. MediaRecorder has stopped capturing by this point but the file + * is only finalized by stop(), so hand the session back to the module as an explicit + * stopRecording() would and let it tear the VideoSession down. + */ + private void finishLimitedRecording() { + mCameraView.getHandler().post(() -> { + if (mIsRecordingVideo && mCameraView.isRecording()) { + mCameraView.stopRecording(); + } + }); + } + void stopRecording() { if (mAwaitingRecording) { mAwaitingRecording = false; diff --git a/camera-view/src/main/java/com/xlythe/view/camera/x/CameraXMath.java b/camera-view/src/main/java/com/xlythe/view/camera/x/CameraXMath.java new file mode 100644 index 0000000..5541c8c --- /dev/null +++ b/camera-view/src/main/java/com/xlythe/view/camera/x/CameraXMath.java @@ -0,0 +1,162 @@ +package com.xlythe.view.camera.x; + +import android.graphics.Matrix; +import android.graphics.Rect; +import android.graphics.RectF; +import android.util.Size; + +import androidx.annotation.NonNull; + +import com.xlythe.view.camera.TransformMath; + +/** Pure coordinate and transform helpers shared by the CameraX backend and its tests. */ +final class CameraXMath { + /** The minimum valid CameraX metering-point size. */ + private static final float MIN_METERING_SIZE = 0.01f; + + /** The square space androidx.camera rotates rectangles in before mapping them to a buffer. */ + private static final RectF NORMALIZED_RECT = new RectF(-1f, -1f, 1f, 1f); + + private CameraXMath() {} + + /** Converts CameraView's [-1000, 1000] coordinate into a surface pixel coordinate. */ + static float toSurfaceCoordinate(int coordinate, int length) { + if (length <= 0) { + return 0f; + } + float normalized = (clamp(coordinate, -1000, 1000) + 1000f) / 2000f; + return normalized * length; + } + + /** Converts a CameraView metering rectangle into CameraX's fractional point size. */ + static float toMeteringSize(@NonNull Rect rectangle) { + float size = Math.max(Math.abs(rectangle.width()), Math.abs(rectangle.height())) / 2000f; + return clamp(size, MIN_METERING_SIZE, 1f); + } + + /** Normalizes any rotation, including negative ones, into [0, 360). */ + static int within360(int rotationDegrees) { + return TransformMath.within360(rotationDegrees); + } + + /** + * Returns the rotation CameraView still has to apply after the camera's own buffer transform. + * + *

When the camera feeds the SurfaceTexture directly it has already rotated the buffer into + * the device's natural orientation and horizontally flipped it if mirroring was requested, so + * only the difference between that and the target rotation is left. This is the same split + * androidx.camera.view.PreviewTransformation#getRemainingRotationDegrees performs, and it + * reduces to minus the display rotation for a back camera or a mirrored front camera.

+ * + * @param rotationDegrees TransformationInfo#getRotationDegrees, sensor to target rotation + * @param sensorOrientationDegrees the rotation the camera itself applied to the buffer + * @param mirrored TransformationInfo#isMirroring + */ + static int remainingRotationDegrees( + int rotationDegrees, int sensorOrientationDegrees, boolean mirrored) { + // A horizontal flip reverses the direction of any rotation applied before it, so the + // leftover rotation is negated whenever the camera mirrored the buffer. + return mirrored + ? within360(sensorOrientationDegrees - rotationDegrees) + : within360(rotationDegrees - sensorOrientationDegrees); + } + + /** Swaps a size's dimensions for the quarter turns that transpose them. */ + @NonNull + static Size rotateSize(@NonNull Size size, int rotationDegrees) { + return TransformMath.rotateSize(size, rotationDegrees); + } + + /** + * Builds the TextureView transform which maps the CameraX crop rectangle into the view using + * center-crop scaling, CameraX's rotation, and CameraX's explicit mirror flag. + * + * @param hasCameraTransform TransformationInfo#hasCameraTransform. When true the SurfaceTexture + * already carries the camera's rotation and mirror, so applying the full rotation here + * would turn the preview twice. + * @param sensorOrientationDegrees the active lens' sensor orientation, which is the rotation + * the camera writes into the SurfaceTexture + */ + @NonNull + static Matrix createTextureTransform( + @NonNull Size bufferSize, + @NonNull Rect cropRectangle, + int rotationDegrees, + boolean mirrored, + boolean hasCameraTransform, + int sensorOrientationDegrees, + int viewWidth, + int viewHeight) { + if (!hasCameraTransform) { + // CameraX copied the stream through its own pipeline, so the SurfaceTexture carries no + // camera transform and this matrix owns the whole rotation and the mirror. + return createCenterCropTransform(bufferSize, new RectF(cropRectangle), rotationDegrees, + mirrored, viewWidth, viewHeight); + } + int applied = within360(sensorOrientationDegrees); + Size orientedBuffer = rotateSize(bufferSize, applied); + RectF orientedCrop = mapThroughCameraTransform( + cropRectangle, bufferSize, orientedBuffer, applied, mirrored); + return createCenterCropTransform(orientedBuffer, orientedCrop, + remainingRotationDegrees(rotationDegrees, applied, mirrored), + false /* the camera already mirrored the buffer */, viewWidth, viewHeight); + } + + /** + * Maps a crop rectangle from raw buffer coordinates into the coordinates TextureView actually + * draws, which are the buffer rotated by the camera and flipped when the stream is mirrored. + */ + @NonNull + private static RectF mapThroughCameraTransform( + @NonNull Rect cropRectangle, + @NonNull Size bufferSize, + @NonNull Size orientedBufferSize, + int rotationDegrees, + boolean mirrored) { + Matrix cameraTransform = new Matrix(); + cameraTransform.setRectToRect( + new RectF(0f, 0f, bufferSize.getWidth(), bufferSize.getHeight()), + NORMALIZED_RECT, Matrix.ScaleToFit.FILL); + cameraTransform.postRotate(rotationDegrees); + if (mirrored) { + cameraTransform.postScale(-1f, 1f); + } + Matrix normalizedToOriented = new Matrix(); + normalizedToOriented.setRectToRect(NORMALIZED_RECT, + new RectF(0f, 0f, orientedBufferSize.getWidth(), orientedBufferSize.getHeight()), + Matrix.ScaleToFit.FILL); + cameraTransform.postConcat(normalizedToOriented); + + RectF orientedCrop = new RectF(cropRectangle); + cameraTransform.mapRect(orientedCrop); + return orientedCrop; + } + + /** + * Rotates the crop rectangle, scales it to fill the view without distorting it, and expresses + * the result relative to the stretch TextureView applies to a buffer by default. + */ + @NonNull + private static Matrix createCenterCropTransform( + @NonNull Size bufferSize, + @NonNull RectF crop, + int rotationDegrees, + boolean mirrored, + int viewWidth, + int viewHeight) { + if (crop.isEmpty()) { + return new Matrix(); + } + return TransformMath.asTextureTransform( + TransformMath.centerCrop(crop, rotationDegrees, mirrored, viewWidth, viewHeight), + bufferSize, viewWidth, viewHeight); + } + + private static int clamp(int value, int minimum, int maximum) { + return Math.max(minimum, Math.min(value, maximum)); + } + + private static float clamp(float value, float minimum, float maximum) { + return Math.max(minimum, Math.min(value, maximum)); + } +} 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 0ad4d7c..dd9c6a8 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 @@ -2,1057 +2,2117 @@ import android.Manifest; import android.annotation.SuppressLint; -import android.annotation.TargetApi; +import android.app.Activity; +import android.app.Application; +import android.content.Context; +import android.content.ContextWrapper; import android.content.Intent; -import android.graphics.ImageFormat; +import android.hardware.camera2.CameraCaptureSession; +import android.hardware.camera2.CameraCharacteristics; +import android.hardware.camera2.CaptureRequest; +import android.hardware.camera2.CaptureResult; +import android.hardware.camera2.TotalCaptureResult; import android.graphics.Matrix; import android.graphics.Rect; +import android.graphics.RectF; import android.graphics.SurfaceTexture; -import android.hardware.camera2.CameraCharacteristics; import android.location.Location; -import android.os.Build; +import android.os.Bundle; import android.os.Handler; +import android.os.Looper; import android.util.Log; +import android.util.Range; +import android.util.Rational; import android.util.Size; import android.view.Surface; +import android.view.View; import androidx.annotation.NonNull; +import androidx.annotation.OptIn; import androidx.annotation.Nullable; import androidx.annotation.RequiresPermission; import androidx.annotation.RestrictTo; -import androidx.camera.camera2.interop.Camera2CameraInfo; -import androidx.camera.core.AspectRatio; import androidx.camera.core.Camera; +import androidx.camera.camera2.interop.Camera2CameraInfo; +import androidx.camera.camera2.interop.Camera2Interop; +import androidx.camera.camera2.interop.ExperimentalCamera2Interop; +import androidx.camera.core.CameraInfo; +import androidx.camera.core.DynamicRange; +import androidx.camera.core.ExposureState; import androidx.camera.core.CameraInfoUnavailableException; import androidx.camera.core.CameraSelector; +import androidx.camera.core.CameraState; import androidx.camera.core.FocusMeteringAction; import androidx.camera.core.FocusMeteringResult; import androidx.camera.core.ImageCapture; import androidx.camera.core.ImageCaptureException; -import androidx.camera.core.ImageProxy; +import androidx.camera.core.ImageAnalysis; +import androidx.camera.core.MeteringPoint; +import androidx.camera.core.MirrorMode; import androidx.camera.core.Preview; import androidx.camera.core.SurfaceOrientedMeteringPointFactory; +import androidx.camera.core.SurfaceRequest; +import androidx.camera.core.SessionConfig; import androidx.camera.core.UseCase; import androidx.camera.core.UseCaseGroup; import androidx.camera.core.ViewPort; -import android.util.Rational; import androidx.camera.core.ZoomState; +import androidx.camera.core.resolutionselector.AspectRatioStrategy; +import androidx.camera.core.resolutionselector.ResolutionSelector; +import androidx.camera.core.resolutionselector.ResolutionStrategy; import androidx.camera.lifecycle.ProcessCameraProvider; -import androidx.lifecycle.ViewTreeLifecycleOwner; +import androidx.camera.video.FallbackStrategy; import androidx.camera.video.FileOutputOptions; import androidx.camera.video.PendingRecording; import androidx.camera.video.Quality; import androidx.camera.video.QualitySelector; import androidx.camera.video.Recorder; import androidx.camera.video.Recording; +import androidx.camera.video.VideoCapabilities; import androidx.camera.video.VideoCapture; import androidx.camera.video.VideoRecordEvent; -import androidx.collection.ArrayMap; +import androidx.camera.extensions.ExtensionsManager; import androidx.core.content.ContextCompat; import androidx.lifecycle.Lifecycle; +import androidx.lifecycle.LifecycleEventObserver; import androidx.lifecycle.LifecycleOwner; +import androidx.lifecycle.LifecycleRegistry; +import androidx.lifecycle.LiveData; +import androidx.lifecycle.Observer; +import androidx.lifecycle.ViewTreeLifecycleOwner; import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.MoreExecutors; import com.xlythe.view.camera.CameraView; -import com.xlythe.view.camera.Exif; +import com.xlythe.view.camera.Face; +import com.xlythe.view.camera.CameraXBarcodeAnalyzer; +import com.xlythe.view.camera.Barcode; import com.xlythe.view.camera.ICameraModule; import com.xlythe.view.camera.LocationProvider; import com.xlythe.view.camera.PermissionChecker; +import com.xlythe.view.camera.TransformMath; import com.xlythe.view.camera.stream.VideoRecorder; import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Executor; -/** - * A wrapper around the CameraX APIs. - */ -@TargetApi(21) +/** A CameraView backend implemented with CameraX. */ @RestrictTo(RestrictTo.Scope.LIBRARY) public class CameraXModule extends ICameraModule implements LifecycleOwner { - /** - * The library can crash and fail to return events (even #onError). - * To work around that, we'll assume an error after this timeout. - */ - private static final long LIB_TIMEOUT_MILLIS = 5000; - - /** When this flag is off, we attempt to write the file ourselves instead of using CameraX's convenience method. */ - private static final boolean SUPPORTS_WRITE_TO_FILE = true; - - /** CameraX breaks if you unbind the preview while taking a picture. When this flag is off, we won't unbind. */ - private static final boolean SUPPORTS_PICTURE_WITHOUT_PREVIEW = false; - - /** CameraX can get into a bad state when taking pictures. When this is true, we attempt to forcefully get back into a good state. */ - private static final boolean SUPPORTS_FORCE_RESTORE = false; - - /** The time (in milliseconds) that we consider a GPS signal to be relevant. */ + /** The time for which a cached GPS location remains useful. */ private static final long STALE_LOCATION_MILLIS = 2 * 60 * 60 * 1000; - - /** The time (in milliseconds) to wait for a GPS signal. This runs on the UI thread and so must be short. */ + /** A short timeout used only to refresh and read the last known GPS location. */ private static final long GPS_TIMEOUT_MILLIS = 10; + /** The public CameraView zoom range is represented as one hundred linear steps. */ + private static final int MAX_ZOOM_LEVEL = 100; + /** Maximum time CameraX may take to report a still-image terminal callback. */ + private static final long IMAGE_CAPTURE_TIMEOUT_MILLIS = 15_000; + /** Maximum time CameraX may take to emit the recording Start event. */ + private static final long RECORDING_START_TIMEOUT_MILLIS = 15_000; + /** Maximum time CameraX may take to emit Finalize after a stop request. */ + private static final long RECORDING_FINALIZE_TIMEOUT_MILLIS = 10_000; + /** Delay allowing a removed stream surface to settle before restoring stabilization. */ + private static final long STREAM_RECONFIGURE_DELAY_MILLIS = 500; + + /** Internal CameraX lifecycle states, serialized on the main thread. */ + private enum State { CLOSED, SUSPENDED, WAITING_FOR_PROVIDER, BINDING, OPEN, RECORDING, STOPPING, ERROR } + + /** Main-thread handler used for all mutable backend state and recording timeouts. */ + private final Handler mMainHandler = new Handler(Looper.getMainLooper()); + /** Monitor guarding snapshots read from arbitrary caller threads. */ + private final Object mSnapshotLock = new Object(); + /** Main-thread executor required by CameraX binding and callback APIs. */ + private final Executor mMainExecutor; + /** Stable lifecycle owner used even when CameraView is hosted by a plain Activity. */ + private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); + /** Receives attachment changes so an open request cannot retain a detached camera. */ + private final View.OnAttachStateChangeListener mAttachStateListener = + new View.OnAttachStateChangeListener() { + @Override public void onViewAttachedToWindow(View view) { + onHostAttachmentChanged(true); + } - /** A future handle to the CameraX library. Until this is loaded, we cannot use CameraX. */ - private final ListenableFuture mCameraProviderFuture; - - /** - * A handle to the CameraX library. You must wait until {@link #mCameraProviderFuture} has - * loaded before this becomes non-null. - */ - @Nullable - private ProcessCameraProvider mCameraProvider; - - /** - * True if the module has been opened. This is checked when async operations haven't finished - * yet, as a way to release resources if we were closed before they loaded. - */ - private boolean mIsOpen; + @Override public void onViewDetachedFromWindow(View view) { + onHostAttachmentChanged(false); + } + }; + /** Receives host lifecycle transitions when a view-tree lifecycle owner is available. */ + private final LifecycleEventObserver mHostLifecycleObserver = + (source, event) -> onHostLifecycleChanged(source); + /** Tracks start, stop, and destruction for a plain Activity without a LifecycleOwner. */ + private final Application.ActivityLifecycleCallbacks mActivityLifecycleCallbacks = + new Application.ActivityLifecycleCallbacks() { + @Override public void onActivityCreated( + @NonNull Activity activity, @Nullable Bundle state) {} + @Override public void onActivityStarted(@NonNull Activity activity) { + onHostActivityStartedChanged(activity, true); + } + @Override public void onActivityResumed(@NonNull Activity activity) {} + @Override public void onActivityPaused(@NonNull Activity activity) {} + @Override public void onActivityStopped(@NonNull Activity activity) { + onHostActivityStartedChanged(activity, false); + } + @Override public void onActivitySaveInstanceState( + @NonNull Activity activity, @NonNull Bundle state) {} + @Override public void onActivityDestroyed(@NonNull Activity activity) { + if (activity != mHostActivity) return; + onHostActivityStartedChanged(activity, false); + activity.getApplication().unregisterActivityLifecycleCallbacks(this); + mHostActivity = null; + closeOnMainThread(); + destroyOnMainThread(); + } + }; - /** The currently active Camera. Null if the camera isn't open. */ + /** The single provider future and single listener used for this backend instance. */ + private final ListenableFuture mCameraProviderFuture; + /** Ordered custom stream providers requested by VideoStream instances. */ + private final Set mSurfaceProviders = new LinkedHashSet<>(); + /** Custom Preview use cases in the currently bound atomic use-case group. */ + private final Map mBoundStreamPreviews = new LinkedHashMap<>(); + /** Every use case currently bound by this module, and therefore safe for it to unbind. */ + private final List mBoundUseCases = new ArrayList<>(); + /** Plain Activity containing CameraView when it does not expose a LifecycleOwner. */ + @Nullable private Activity mHostActivity; + /** Last started/stopped state reported by the plain Activity host. */ + private boolean mHostActivityStarted = true; + /** Current view-tree lifecycle owner, or null for plain Activity/application hosts. */ + @Nullable private LifecycleOwner mHostLifecycleOwner; + /** CameraState source currently observed for runtime failures. */ + @Nullable private LiveData mObservedCameraState; + /** Generation-scoped observer installed on the active CameraState source. */ + @Nullable private Observer mCameraStateObserver; + /** CameraX provider after its asynchronous initialization completes. */ + @Nullable private ProcessCameraProvider mCameraProvider; + /** Asynchronous CameraX extension-manager initialization. */ + @Nullable private ListenableFuture mExtensionsManagerFuture; + /** CameraX vendor extension manager after initialization. */ + @Nullable private ExtensionsManager mExtensionsManager; + /** Camera returned by the latest successful atomic bind. */ @Nullable private Camera mActiveCamera; - - /** The size of the preview. Cached in case we need to adjust our view size. */ - @Nullable private Size mPreviewSize; - - /** The preview that draws to the texture surface. Non-null while open. */ + /** Display Preview in the latest successful bind. */ @Nullable private Preview mPreview; - - /** Allows us to take pictures. Non-null while open, but is temporarily unbound while recording a video. */ + /** Still-image use case in the latest successful bind. */ @Nullable private ImageCapture mImageCapture; - - /** A video capture that captures what's visible on the screen. Non-null while taking a video. */ + /** Native barcode-analysis use case in the latest successful bind. */ + @Nullable private ImageAnalysis mImageAnalysis; + /** Native CameraX barcode analyzer while scanning is requested. */ + @Nullable private CameraXBarcodeAnalyzer mBarcodeAnalyzer; + /** Single-thread executor owned by the active native barcode analyzer. */ + @Nullable private ExecutorService mAnalysisExecutor; + /** Video use case while a recording is being prepared, recorded, or finalized. */ @Nullable private VideoCapture mVideoCapture; - - /** A helper class for mVideoCapture that allows us to stop the recording. */ + /** Active CameraX recording; cleared only by its Finalize event. */ @Nullable private Recording mVideoRecording; - - private int mLastWidth = 0; - private int mLastHeight = 0; - - /** Custom use cases, beyond the typical Preview/Image/Video ones. */ - private final Map mCustomUseCases = new ArrayMap<>(); - - /** True if using the front facing camera. False otherwise. */ - private boolean mIsFrontFacing = false; - - /** The current zoom level, from 0 to {@link #getMaxZoomLevel()}. */ + /** Output file associated with the active recording. */ + @Nullable private File mVideoFile; + /** Latest CameraX preview transformation metadata. */ + @Nullable private SurfaceRequest.TransformationInfo mTransformationInfo; + + /** Whether the bound configuration can take a still while it records. */ + private boolean mSnapshotWhileRecording; + + /** Whether the caller asked for faces, which the bound request has to carry. + * + *

CameraX has no face detection of its own, so this is a camera2 request option and + * session callback added through interop, both of which are fixed at bind time.

*/ + private boolean mFaceDetectionRequested; + + /** How many faces the last report had, so an empty camera is not reported every frame. */ + private int mLastFaceCount; + /** Resolution of the SurfaceTexture buffer for the latest display Preview request. */ + @Nullable private Size mPreviewResolution; + /** Main-thread state of this CameraX backend. */ + private State mState = State.CLOSED; + /** Whether the CameraView is attached to a window. */ + private boolean mViewAttached; + /** Whether the optional view-tree lifecycle owner is at least STARTED. */ + private boolean mHostStarted; + /** Last critical CameraState error already reported, preventing duplicate callbacks. */ + @Nullable private Integer mLastCriticalCameraError; + /** Whether a critical runtime camera failure requires an explicit reopen. */ + private boolean mCriticalCameraFailure; + /** Lens requested while recording, applied after CameraX emits Finalize. */ + @Nullable private Boolean mPendingFrontFacing; + /** Whether the host is gone, after which the lifecycle registry cannot be driven again. */ + private boolean mDestroyed; + /** Whether CameraView currently wants this backend open. */ + private boolean mOpenRequested; + /** Whether confirmation UI has intentionally paused CameraX use cases. */ + private boolean mPaused; + /** Requested lens; false is back-facing and true is front-facing. */ + private boolean mFrontFacing; + /** Sensor orientation for the requested lens, available before CameraX finishes binding. */ + private int mSensorOrientation; + /** Last accepted public zoom level in the range 0..100. */ private int mZoomLevel; - - /** True if the preview is currently paused. */ - private boolean mIsPaused = false; + /** Last non-zero CameraView layout width used to choose resolutions and ViewPort. */ + private int mLastWidth; + /** Last non-zero CameraView layout height used to choose resolutions and ViewPort. */ + private int mLastHeight; + /** Monotonic token invalidating stale provider, surface, and binding callbacks. */ + private long mGeneration; + /** Monotonic token ensuring an image request reports at most one terminal result. */ + private long mImageOperationId; + /** Monotonic token ensuring a video request reports at most one terminal result. */ + private long mVideoOperationId; + /** Usable media duration reported by CameraX for the active recording. */ + private long mRecordedVideoDurationMillis; + /** Pending image destination while a terminal callback is outstanding. */ + @Nullable private File mPendingImageFile; + /** Pending maximum-duration stop task for the active recording. */ + @Nullable private Runnable mDurationStopTask; + /** Pending still-image timeout task. */ + @Nullable private Runnable mImageTimeoutTask; + /** Pending recording-start timeout task. */ + @Nullable private Runnable mRecordingStartTimeoutTask; + /** Pending recording-finalize timeout task. */ + @Nullable private Runnable mRecordingFinalizeTimeoutTask; + /** Snapshot of requested lens facing guarded by mSnapshotLock. */ + private boolean mSnapshotFrontFacing; + /** Snapshot of pause state guarded by mSnapshotLock. */ + private boolean mSnapshotPaused; + /** Snapshot of recording state guarded by mSnapshotLock. */ + private boolean mSnapshotRecording; + /** Snapshot of accepted zoom level guarded by mSnapshotLock. */ + private int mSnapshotZoomLevel; + /** Snapshot of front-camera availability guarded by mSnapshotLock. */ + private boolean mSnapshotHasFrontCamera; + /** Snapshot of flash availability guarded by mSnapshotLock. */ + private boolean mSnapshotHasFlash; + /** Snapshot of zoom availability guarded by mSnapshotLock. */ + private boolean mSnapshotZoomSupported; + /** Snapshot of HDR capture availability guarded by mSnapshotLock. */ + private boolean mSnapshotHdrSupported; + /** Snapshot of preview stabilization availability guarded by mSnapshotLock. */ + private boolean mSnapshotPreviewStabilizationSupported; + /** Snapshot of video stabilization availability guarded by mSnapshotLock. */ + private boolean mSnapshotVideoStabilizationSupported; + /** Snapshot of exposure-control availability guarded by mSnapshotLock. */ + private boolean mSnapshotExposureSupported; + /** Snapshot of minimum exposure compensation guarded by mSnapshotLock. */ + private int mSnapshotMinExposure; + /** Snapshot of maximum exposure compensation guarded by mSnapshotLock. */ + private int mSnapshotMaxExposure; + /** Snapshot of low-light boost availability guarded by mSnapshotLock. */ + private boolean mSnapshotLowLightBoostSupported; + /** Snapshot of supported vendor extensions guarded by mSnapshotLock. */ + private Set mSnapshotExtensions = Collections.singleton(CameraView.Extension.NONE); public CameraXModule(CameraView cameraView) { super(cameraView); + mMainExecutor = ContextCompat.getMainExecutor(getContext()); + mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED); + mViewAttached = getView().isAttachedToWindow(); + getView().addOnAttachStateChangeListener(mAttachStateListener); + mHostActivity = findActivity(getContext()); + if (mHostActivity != null) { + mHostActivity.getApplication() + .registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks); + } + updateHostLifecycleOwner(); mCameraProviderFuture = ProcessCameraProvider.getInstance(getContext()); - mCameraProviderFuture.addListener(() -> { - try { - mCameraProvider = mCameraProviderFuture.get(); - getContext().sendBroadcast(new Intent(CameraView.ACTION_CAMERA_STATE_CHANGED).setPackage(getContext().getPackageName())); - } catch (ExecutionException | InterruptedException e) { - Log.e(TAG, "Unable to load camera", e); - } - }, ContextCompat.getMainExecutor(getContext())); + mCameraProviderFuture.addListener(this::onProviderReady, mMainExecutor); + } - getView().addOnAttachStateChangeListener(new android.view.View.OnAttachStateChangeListener() { - @Override - public void onViewAttachedToWindow(android.view.View v) { - Log.d(TAG, "View attached to window, rebinding use cases."); - rebindUseCases(); - } + @NonNull @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; } - @Override - public void onViewDetachedFromWindow(android.view.View v) { - Log.d(TAG, "View detached from window."); + private void publishSnapshot() { + boolean hasFrontCamera = false; + Set supportedExtensions = EnumSet.of(CameraView.Extension.NONE); + ProcessCameraProvider provider = mCameraProvider; + if (provider != null) { + try { + hasFrontCamera = provider.hasCamera(selectorFor(CameraSelector.LENS_FACING_FRONT)); + ExtensionsManager extensionsManager = mExtensionsManager; + if (extensionsManager != null) { + CameraSelector selector = selectorFor(mFrontFacing + ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK); + for (CameraView.Extension extension : CameraView.Extension.values()) { + if (extension != CameraView.Extension.NONE + && extensionsManager.isExtensionAvailable(selector, toExtensionMode(extension))) { + supportedExtensions.add(extension); + } + } + } + } catch (CameraInfoUnavailableException | RuntimeException error) { + Log.w(TAG, "Unable to refresh CameraX capabilities", error); } - }); - } - - @NonNull - @Override - public Lifecycle getLifecycle() { - LifecycleOwner owner = ViewTreeLifecycleOwner.get(getView()); - if (owner != null) { - return owner.getLifecycle(); } - return ((LifecycleOwner) getContext()).getLifecycle(); + Camera camera = mActiveCamera; + CameraInfo cameraInfo = camera == null ? null : camera.getCameraInfo(); + boolean hasFlash = cameraInfo != null && cameraInfo.hasFlashUnit(); + boolean zoomSupported = false; + boolean hdrSupported = false; + boolean previewStabilizationSupported = false; + boolean videoStabilizationSupported = false; + boolean exposureSupported = false; + int minExposure = 0; + int maxExposure = 0; + boolean lowLightBoostSupported = false; + if (cameraInfo != null) { + // Each of these asks the camera a separate question, and a camera that cannot answer + // one throws rather than declining: Recorder.getVideoCapabilities, for instance, + // fails outright on a camera with no encoder profiles. This runs from lifecycle + // callbacks and from CameraX's own listeners, so an escaping exception takes the host + // down. Ask each question on its own and treat a failure as unsupported, which is + // what an unanswerable capability means anyway. + zoomSupported = query(cameraInfo, "zoom", info -> { + ZoomState zoom = info.getZoomState().getValue(); + return zoom != null && zoom.getMaxZoomRatio() > zoom.getMinZoomRatio(); + }, false); + hdrSupported = query(cameraInfo, "HDR", CameraXModule::supportsHdr, false); + previewStabilizationSupported = query(cameraInfo, "preview stabilization", + info -> Preview.getPreviewCapabilities(info).isStabilizationSupported(), false); + videoStabilizationSupported = query(cameraInfo, "video stabilization", + info -> Recorder.getVideoCapabilities(info).isStabilizationSupported(), false); + exposureSupported = query(cameraInfo, "exposure", + info -> info.getExposureState().isExposureCompensationSupported(), false); + minExposure = query(cameraInfo, "minimum exposure", + info -> info.getExposureState().getExposureCompensationRange().getLower(), 0); + maxExposure = query(cameraInfo, "maximum exposure", + info -> info.getExposureState().getExposureCompensationRange().getUpper(), 0); + lowLightBoostSupported = query(cameraInfo, "low-light boost", + CameraInfo::isLowLightBoostSupported, false); + } + synchronized (mSnapshotLock) { + mSnapshotFrontFacing = mFrontFacing; + mSnapshotPaused = mPaused; + mSnapshotRecording = mVideoRecording != null; + mSnapshotZoomLevel = mZoomLevel; + mSnapshotHasFrontCamera = hasFrontCamera; + mSnapshotHasFlash = hasFlash; + mSnapshotZoomSupported = zoomSupported; + mSnapshotHdrSupported = hdrSupported; + mSnapshotPreviewStabilizationSupported = previewStabilizationSupported; + mSnapshotVideoStabilizationSupported = videoStabilizationSupported; + mSnapshotExposureSupported = exposureSupported; + mSnapshotMinExposure = minExposure; + mSnapshotMaxExposure = maxExposure; + mSnapshotLowLightBoostSupported = lowLightBoostSupported; + mSnapshotExtensions = Collections.unmodifiableSet(EnumSet.copyOf(supportedExtensions)); + } } - @RequiresPermission(Manifest.permission.CAMERA) - @Override - public void open() { - mIsOpen = true; - loadPreview(); + /** One capability question, with its own failure handled. */ + private interface CapabilityQuery { + T ask(@NonNull CameraInfo cameraInfo); + } - if (DEBUG) { - Log.d(TAG, "CameraXModule opened"); + /** + * Asks the camera one question, answering with {@code fallback} when it cannot say. + * + *

A capability query that throws is reported as unsupported rather than propagated, + * because this is called from lifecycle and CameraX callbacks where nothing can handle it.

+ */ + private static T query(@NonNull CameraInfo cameraInfo, @NonNull String name, + @NonNull CapabilityQuery capabilityQuery, T fallback) { + try { + return capabilityQuery.ask(cameraInfo); + } catch (RuntimeException error) { + if (DEBUG) Log.d(TAG, "Camera cannot report " + name, error); + return fallback; } } - private void loadPreview() { - if (!mIsOpen) { - Log.v(TAG, "Ignoring call to load preview. The camera is no longer open."); + private void onHostAttachmentChanged(boolean attached) { + mViewAttached = attached; + updateHostLifecycleOwner(); + updateBackendLifecycle(); + } + + private void updateHostLifecycleOwner() { + LifecycleOwner owner = ViewTreeLifecycleOwner.get(getView()); + if (owner == mHostLifecycleOwner) { + mHostStarted = (mHostActivity == null || mHostActivityStarted) + && (owner == null || owner.getLifecycle().getCurrentState() + .isAtLeast(Lifecycle.State.STARTED)); return; } + if (mHostLifecycleOwner != null) { + mHostLifecycleOwner.getLifecycle().removeObserver(mHostLifecycleObserver); + } + mHostLifecycleOwner = owner; + if (owner == null) { + mHostStarted = mHostActivity == null || mHostActivityStarted; + } else { + owner.getLifecycle().addObserver(mHostLifecycleObserver); + mHostStarted = (mHostActivity == null || mHostActivityStarted) + && owner.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED); + } + } - // We haven't loaded our CameraProvider yet. We'll delay until we are loaded, and try again. - if (mCameraProvider == null) { - mCameraProviderFuture.addListener(this::loadPreview, ContextCompat.getMainExecutor(getContext())); + private void onHostLifecycleChanged(@NonNull LifecycleOwner owner) { + if (owner != mHostLifecycleOwner) return; + if (owner.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) { + closeOnMainThread(); + destroyOnMainThread(); return; } + mHostStarted = (mHostActivity == null || mHostActivityStarted) + && owner.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED); + updateBackendLifecycle(); + } - mPreview = new Preview.Builder() - .setTargetResolution(getTargetResolution()) - //.setTargetAspectRatio(getTargetAspectRatio()) - .setTargetRotation(getTargetRotation()) - .build(); - mPreview.setSurfaceProvider(request -> { - SurfaceTexture surfaceTexture = getSurfaceTexture(); - if (surfaceTexture == null) { - // Can happen if there's a race condition, and the texture is closed before we're - // asked to provide it. - request.willNotProvideSurface(); - return; - } - - int cameraWidth = request.getResolution().getWidth(); - int cameraHeight = request.getResolution().getHeight(); - // Required or the preview will start drawing in odd aspect ratios. - surfaceTexture.setDefaultBufferSize(cameraWidth, cameraHeight); - - Surface surface = new Surface(surfaceTexture); - request.provideSurface(surface, ContextCompat.getMainExecutor(getContext()), result -> { - if (DEBUG) { - Log.d(TAG, "Surface no longer needed. Result Code: " + result.getResultCode()); - } - surface.release(); - }); + /** + * Retires this backend once its host is gone. + * + *

ProcessCameraProvider observes the lifecycle this module owns, and the module observes + * the host's, so leaving the registry short of DESTROYED kept both sides registered after the + * host went away. The registry is one-way, so everything that would drive it afterwards has + * to stop as well.

+ */ + private void destroyOnMainThread() { + if (mDestroyed) return; + mDestroyed = true; - mPreviewSize = new Size(cameraWidth, cameraHeight); - transformPreview(cameraWidth, cameraHeight); - }); + if (mHostLifecycleOwner != null) { + mHostLifecycleOwner.getLifecycle().removeObserver(mHostLifecycleObserver); + mHostLifecycleOwner = null; + } + getView().removeOnAttachStateChangeListener(mAttachStateListener); + mLifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED); + mState = State.CLOSED; + } - // We previously attempted to register the ImageCapture just in time, while taking a picture. - // However, CameraX doesn't handle that well and #takePicture would silently fail. Instead, - // we'll keep it registered whenever the preview is registered. - mImageCapture = new ImageCapture.Builder() - .setTargetResolution(getTargetResolution()) - //.setTargetAspectRatio(getTargetAspectRatio()) - .setTargetRotation(getTargetRotation()) - .setFlashMode(getFlashMode()) - .setCaptureMode(getCaptureMode()) - .build(); + private void onHostActivityStartedChanged(@NonNull Activity activity, boolean started) { - if (!rebindUseCases()) { - Log.e(TAG, "Failed to load camera preview"); - } + if (activity != mHostActivity) return; + mHostActivityStarted = started; + mHostStarted = started && (mHostLifecycleOwner == null + || mHostLifecycleOwner.getLifecycle().getCurrentState() + .isAtLeast(Lifecycle.State.STARTED)); + updateBackendLifecycle(); + } - if (DEBUG) { - Log.d(TAG, "Preview loaded"); - if (mActiveCamera != null) { - mActiveCamera.getCameraInfo().getCameraState().observe(this, cameraState -> Log.d(TAG, "CameraState changed: type=" + cameraState.getType() + ", error=" + cameraState.getError())); - } + @Nullable private static Activity findActivity(@NonNull Context initialContext) { + Context context = initialContext; + while (context instanceof ContextWrapper) { + if (context instanceof Activity) return (Activity) context; + Context baseContext = ((ContextWrapper) context).getBaseContext(); + if (baseContext == context) break; + context = baseContext; } + return context instanceof Activity ? (Activity) context : null; } - @Override - public void close() { - mIsOpen = false; + private boolean isHostActive() { + boolean hasLifecycleHost = mHostLifecycleOwner != null || mHostActivity != null; + return mViewAttached && (!hasLifecycleHost || mHostStarted); + } - if (mCameraProvider == null) { + @SuppressLint("MissingPermission") + private void updateBackendLifecycle() { + if (mDestroyed) return; + if (!mOpenRequested) { + mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED); return; } - - if (mPreview == null) { + if (isHostActive()) { + mLifecycleRegistry.setCurrentState(Lifecycle.State.STARTED); + if (mCameraProvider != null && mVideoRecording == null + && mBoundUseCases.isEmpty() && !mPaused) { + reconcileUseCases(true); + } return; } - - if (mImageCapture == null) { + if (mVideoRecording != null) { + stopRecordingOnMainThread(); return; } + unbindCurrentUseCases(); + mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED); + mState = State.SUSPENDED; + } - if (isRecording()) { - stopRecording(); - } - - List toUnbind = new ArrayList<>(); - if (mPreview != null) toUnbind.add(mPreview); - if (mImageCapture != null) toUnbind.add(mImageCapture); - if (mVideoCapture != null) toUnbind.add(mVideoCapture); - toUnbind.addAll(mCustomUseCases.values()); - - unbind(toUnbind.toArray(new UseCase[0])); - - mPreviewSize = null; - mPreview = null; - mImageCapture = null; - mActiveCamera = null; + @RequiresPermission(Manifest.permission.CAMERA) + @Override public void open() { runOnMainThread(this::openOnMainThread); } - if (DEBUG) { - Log.d(TAG, "CameraXModule closed"); - } + @SuppressLint("MissingPermission") + private void openOnMainThread() { + if (mDestroyed) return; + if (mOpenRequested && mState != State.ERROR) return; + mOpenRequested = true; + mPaused = false; + mLastCriticalCameraError = null; + mCriticalCameraFailure = false; + mPendingFrontFacing = null; + mGeneration++; + updateBackendLifecycle(); + publishSnapshot(); } - @Override - public boolean hasFrontFacingCamera() { - if (mCameraProvider == null) { - Log.w(TAG, "Failed to query for front facing camera. CameraProvider is not available yet."); - return false; + @Override public void close() { runOnMainThread(this::closeOnMainThread); } + + private void closeOnMainThread() { + if (mDestroyed) return; + if (!mOpenRequested && mState == State.CLOSED) return; + mOpenRequested = false; + mPaused = false; + mPendingFrontFacing = null; + mGeneration++; + failPendingImage("Camera closed before image capture completed"); + cancelRecordingTimeouts(); + cancelDurationStop(); + publishSnapshot(); + if (mVideoRecording != null) { + stopRecordingOnMainThread(); + return; } + releaseAllUseCases(); + mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED); + mState = State.CLOSED; + publishSnapshot(); + } + private void onProviderReady() { try { - return mCameraProvider.hasCamera(new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_FRONT).build()); - } catch (CameraInfoUnavailableException e) { - Log.e(TAG, "Failed to query for front facing camera", e); - return false; + mCameraProvider = mCameraProviderFuture.get(); + initializeExtensions(); + publishSnapshot(); + getContext().sendBroadcast(new Intent(CameraView.ACTION_CAMERA_STATE_CHANGED) + .setPackage(getContext().getPackageName())); + if (mOpenRequested) updateBackendLifecycle(); + } catch (ExecutionException e) { + failProvider(e.getCause() == null ? e : e.getCause()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + failProvider(e); + } catch (RuntimeException e) { + failProvider(e); } } - @Override - public boolean isUsingFrontFacingCamera() { - return mIsFrontFacing; + private void initializeExtensions() { + if (mExtensionsManagerFuture != null || mCameraProvider == null) return; + mExtensionsManagerFuture = ExtensionsManager.getInstanceAsync(getContext(), mCameraProvider); + mExtensionsManagerFuture.addListener(() -> { + try { + mExtensionsManager = mExtensionsManagerFuture.get(); + if (!isExtensionAvailableInternal(getExtension())) { + super.setExtension(CameraView.Extension.NONE); + } + publishSnapshot(); + if (mOpenRequested && mVideoRecording == null && !mPaused && isHostActive()) { + reconcileUseCases(true); + } + } catch (ExecutionException error) { + Log.w(TAG, "CameraX extensions are unavailable", error.getCause()); + super.setExtension(CameraView.Extension.NONE); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + Log.w(TAG, "CameraX extension initialization was interrupted", error); + super.setExtension(CameraView.Extension.NONE); + } + }, mMainExecutor); + } + private void failProvider(@NonNull Throwable error) { + mState = State.ERROR; + Log.e(TAG, "Unable to initialize CameraX", error); + if (mOpenRequested) onCameraError(error); } - @SuppressLint("MissingPermission") - @Override - public void toggleCamera() { - mIsFrontFacing = !mIsFrontFacing; + private void observeCameraState(@NonNull Camera camera) { + if (mObservedCameraState != null && mCameraStateObserver != null) { + mObservedCameraState.removeObserver(mCameraStateObserver); + } + long generation = mGeneration; + LiveData source = camera.getCameraInfo().getCameraState(); + Observer observer = cameraState -> { + if (generation != mGeneration || camera != mActiveCamera + || source != mObservedCameraState) { + return; + } + onCameraStateChanged(cameraState); + }; + mObservedCameraState = source; + mCameraStateObserver = observer; + source.observe(this, observer); + } - boolean shouldOpen = mIsOpen; - close(); - if (shouldOpen) { - open(); + private void onCameraStateChanged(@NonNull CameraState cameraState) { + CameraState.StateError error = cameraState.getError(); + if (error == null) { + mLastCriticalCameraError = null; + return; + } + if (error.getType() == CameraState.ErrorType.RECOVERABLE) { + Log.w(TAG, "CameraX is recovering from camera error " + error.getCode(), + error.getCause()); + return; } + if (mLastCriticalCameraError != null && mLastCriticalCameraError.equals(error.getCode())) return; + mLastCriticalCameraError = error.getCode(); + mCriticalCameraFailure = true; + mState = State.ERROR; + onCameraError(new IllegalStateException( + "CameraX critical camera error " + error.getCode(), error.getCause())); } - @SuppressLint("MissingPermission") - @Override - public void setLensFacing(CameraView.LensFacing lensFacing) { - mIsFrontFacing = lensFacing.equals(CameraView.LensFacing.FRONT); + @Override public boolean hasFrontFacingCamera() { + synchronized (mSnapshotLock) { + return mSnapshotHasFrontCamera; + } + } - boolean shouldOpen = mIsOpen; - close(); - if (shouldOpen) { - open(); + @Override public boolean isUsingFrontFacingCamera() { + synchronized (mSnapshotLock) { + return mSnapshotFrontFacing; } } @SuppressLint("MissingPermission") - private void attemptToRecover() { - Log.w(TAG, "Camera is likely in a failed state. Attempting to recover."); + @Override public void toggleCamera() { + runOnMainThread(() -> { + boolean requested = mPendingFrontFacing == null ? mFrontFacing : mPendingFrontFacing; + setLensFacingOnMainThread(!requested); + }); + } - getView().close(); - getView().open(); + @SuppressLint("MissingPermission") + @Override public void setLensFacing(CameraView.LensFacing lensFacing) { + if (lensFacing == null) throw new NullPointerException("lensFacing cannot be null"); + runOnMainThread(() -> setLensFacingOnMainThread(lensFacing == CameraView.LensFacing.FRONT)); } - @Override - public void focus(Rect focus, Rect metering) { - if (mActiveCamera == null) { + @SuppressLint("MissingPermission") + private void setLensFacingOnMainThread(boolean frontFacing) { + if (!isLensAvailable(frontFacing)) return; + if (mVideoRecording != null) { + mPendingFrontFacing = frontFacing; + Log.i(TAG, "Deferring CameraX lens switch until recording finalizes"); return; } - - SurfaceOrientedMeteringPointFactory factory = new SurfaceOrientedMeteringPointFactory(getWidth(), getHeight()); - ListenableFuture result = mActiveCamera.getCameraControl() - .startFocusAndMetering(new FocusMeteringAction.Builder(factory.createPoint(focus.centerX(), focus.centerY())).build()); - result.addListener(() -> { - boolean isSuccessful = false; - try { - isSuccessful = result.get().isFocusSuccessful(); - } catch (ExecutionException | InterruptedException e) { - e.printStackTrace(); - } - Log.d(TAG, isSuccessful ? "Successfully focused" : "Failed to focus"); - }, MoreExecutors.directExecutor()); + if (frontFacing == mFrontFacing) return; + mFrontFacing = frontFacing; + mGeneration++; + publishSnapshot(); + if (mOpenRequested && mVideoRecording == null) reconcileUseCases(true); } - @Override - public void setZoomLevel(int zoomLevel) { - if (mActiveCamera == null) { - return; + private boolean isLensAvailable(boolean frontFacing) { + ProcessCameraProvider provider = mCameraProvider; + if (provider == null) return true; + try { + int facing = frontFacing ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK; + if (provider.hasCamera(selectorFor(facing))) return true; + Log.w(TAG, "Ignoring lens switch because the requested camera is unavailable"); + } catch (CameraInfoUnavailableException | RuntimeException error) { + Log.w(TAG, "Unable to validate requested camera", error); } + return false; + } + + private void applyPendingLensFacing() { + Boolean frontFacing = mPendingFrontFacing; + mPendingFrontFacing = null; + if (frontFacing == null || frontFacing == mFrontFacing || !isLensAvailable(frontFacing)) return; + mFrontFacing = frontFacing; + mGeneration++; + } + @Override public void focus(Rect focus, Rect metering) { + if (focus == null || metering == null) return; + runOnMainThread(() -> focusOnMainThread(focus, metering)); + } - ZoomState zoomState = mActiveCamera.getCameraInfo().getZoomState().getValue(); - if (zoomState == null) { + private void focusOnMainThread(@NonNull Rect focus, @NonNull Rect metering) { + Camera camera = mActiveCamera; + Preview preview = mPreview; + int width = getWidth(); + int height = getHeight(); + if (camera == null || preview == null || width <= 0 || height <= 0) return; + SurfaceOrientedMeteringPointFactory factory = new SurfaceOrientedMeteringPointFactory(width, height, preview); + MeteringPoint focusPoint = factory.createPoint( + CameraXMath.toSurfaceCoordinate(focus.centerX(), width), + CameraXMath.toSurfaceCoordinate(focus.centerY(), height), + CameraXMath.toMeteringSize(focus)); + MeteringPoint meteringPoint = factory.createPoint( + CameraXMath.toSurfaceCoordinate(metering.centerX(), width), + CameraXMath.toSurfaceCoordinate(metering.centerY(), height), + CameraXMath.toMeteringSize(metering)); + FocusMeteringAction action = new FocusMeteringAction.Builder(focusPoint, FocusMeteringAction.FLAG_AF) + .addPoint(meteringPoint, FocusMeteringAction.FLAG_AE | FocusMeteringAction.FLAG_AWB) + .build(); + if (!camera.getCameraInfo().isFocusMeteringSupported(action)) { + Log.d(TAG, "Focus/metering action is not supported by this camera"); return; } - - float minRatio = zoomState.getMinZoomRatio(); - float maxRatio = zoomState.getMaxZoomRatio(); - float steps = (maxRatio - minRatio) / getMaxZoomLevel(); - - // Note: Because we're dealing with floats, we'll use Math.min to ensure we don't - // accidentally exceed the max with our multiplication. - float zoom = Math.min(minRatio + steps * zoomLevel, maxRatio); - ListenableFuture result = mActiveCamera.getCameraControl().setZoomRatio(zoom); + ListenableFuture result = camera.getCameraControl().startFocusAndMetering(action); result.addListener(() -> { - boolean isSuccessful = false; try { - result.get(); - isSuccessful = true; - } catch (ExecutionException | InterruptedException e) { - e.printStackTrace(); + Log.d(TAG, result.get().isFocusSuccessful() ? "Successfully focused" : "Focus completed without a lock"); + } catch (ExecutionException e) { + Log.w(TAG, "Focus/metering failed", e.getCause()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + Log.w(TAG, "Focus/metering interrupted", e); } - Log.d(TAG, isSuccessful ? "Successfully zoomed" : "Failed to zoom"); - }, MoreExecutors.directExecutor()); - mZoomLevel = zoomLevel; + }, mMainExecutor); } - @Override - public int getZoomLevel() { - return mZoomLevel; + @Override public void setZoomLevel(int zoomLevel) { + runOnMainThread(() -> setZoomOnMainThread(zoomLevel)); } - @Override - public int getMaxZoomLevel() { - return 100; - } - - @Override - public boolean isZoomSupported() { - return true; - } - - @Override - public boolean hasFlash() { - if (mActiveCamera == null) { - return false; + private void setZoomOnMainThread(int zoomLevel) { + int clamped = Math.max(0, Math.min(zoomLevel, MAX_ZOOM_LEVEL)); + Camera camera = mActiveCamera; + if (camera == null) { + mZoomLevel = clamped; + publishSnapshot(); + return; } - - return mActiveCamera.getCameraInfo().hasFlashUnit(); + ListenableFuture result = camera.getCameraControl().setLinearZoom(clamped / (float) MAX_ZOOM_LEVEL); + result.addListener(() -> { + try { + result.get(); + mZoomLevel = clamped; + publishSnapshot(); + } catch (ExecutionException e) { + Log.w(TAG, "Zoom request failed", e.getCause()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + Log.w(TAG, "Zoom request interrupted", e); + } + }, mMainExecutor); } - private int getSensorOrientation() { - if (mActiveCamera == null) { - return 0; + @Override public int getZoomLevel() { + synchronized (mSnapshotLock) { + return mSnapshotZoomLevel; } - - return mActiveCamera.getCameraInfo().getSensorRotationDegrees(); } - - @Override - public void pause() { - if (SUPPORTS_PICTURE_WITHOUT_PREVIEW) { - unbind(mPreview); + @Override public int getMaxZoomLevel() { return MAX_ZOOM_LEVEL; } + @Override public boolean isZoomSupported() { + synchronized (mSnapshotLock) { + return mSnapshotZoomSupported; } - mIsPaused = true; } - - @RequiresPermission(Manifest.permission.CAMERA) - @Override - public void resume() { - if (SUPPORTS_PICTURE_WITHOUT_PREVIEW) { - bind(mPreview); + @Override public boolean hasFlash() { + synchronized (mSnapshotLock) { + return mSnapshotHasFlash; } - mIsPaused = false; } - - @Override - public boolean isPaused() { - return mIsPaused; + @Override public void setFlash(CameraView.Flash flash) { + super.setFlash(flash); + runOnMainThread(() -> { if (mImageCapture != null) mImageCapture.setFlashMode(getFlashMode()); }); } - @Override - public void takePicture(File file) { - if (mCameraProvider == null) { - Log.w(TAG, "Failed to take a picture. CameraProvider is not available yet."); - onImageFailed(); + @Override public void setDynamicRange(CameraView.DynamicRange dynamicRange) { + if (dynamicRange == null) throw new NullPointerException("dynamicRange cannot be null"); + if (dynamicRange == CameraView.DynamicRange.HDR && mActiveCamera != null + && !supportsHdr(mActiveCamera.getCameraInfo())) { + Log.w(TAG, "Ignoring HDR request because the active camera does not support it"); return; } - - if (mImageCapture == null) { - Log.w(TAG, "Failed to take a picture. ImageCapture is not available yet."); - onImageFailed(); - return; + super.setDynamicRange(dynamicRange); + if (dynamicRange == CameraView.DynamicRange.HDR && isLowLightBoostEnabled()) { + setLowLightBoostEnabled(false); } + rebindConfiguration(); + } - if (isRecording()) { - Log.w(TAG, "Failed to take a picture. Pictures cannot be taken while recording."); - onImageFailed(); - return; + @Override public boolean isDynamicRangeSupported(CameraView.DynamicRange dynamicRange) { + if (dynamicRange == null) return false; + if (dynamicRange == CameraView.DynamicRange.SDR) return true; + synchronized (mSnapshotLock) { + return mSnapshotHdrSupported; } + } - AtomicBoolean reportedFailure = new AtomicBoolean(false); - - Handler cancellationHandler = new Handler(); - cancellationHandler.postDelayed(() -> { - Log.w(TAG, "Failed to take a picture. Timed out while waiting for picture callback."); - if (!reportedFailure.get()) { - onImageFailed(); - reportedFailure.set(true); + @Override public void setExtension(CameraView.Extension extension) { + if (extension == null) throw new NullPointerException("extension cannot be null"); + runOnMainThread(() -> { + if (extension != CameraView.Extension.NONE && mExtensionsManager != null + && !isExtensionAvailableInternal(extension)) { + Log.w(TAG, "Ignoring unsupported CameraX extension " + extension); + return; } - - // Note: We cannot attempt to recover immediately, as unbinding the ImageCapture starts - // a chain of events internally. A small delay is enough, though. - if (SUPPORTS_FORCE_RESTORE) { - unbind(mImageCapture); - new Handler().postDelayed(this::attemptToRecover, 150); + super.setExtension(extension); + if (mOpenRequested && mVideoRecording == null && !mPaused && isHostActive()) { + reconcileUseCases(true); } - }, LIB_TIMEOUT_MILLIS); - - if (SUPPORTS_WRITE_TO_FILE) { - ImageCapture.Metadata metadata = new ImageCapture.Metadata(); - metadata.setLocation(getLocation()); - metadata.setReversedHorizontal(isUsingFrontFacingCamera()); - ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(file).setMetadata(metadata).build(); - mImageCapture.takePicture(options, ContextCompat.getMainExecutor(getContext()), new ImageCapture.OnImageSavedCallback() { - @Override - public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) { - showImageConfirmation(file); - cancellationHandler.removeCallbacksAndMessages(null); - } - - @Override - public void onError(@NonNull ImageCaptureException e) { - Log.w(TAG, "Failed to take a picture. ImageCapture failed.", e); - if (!reportedFailure.get()) { - onImageFailed(); - reportedFailure.set(true); - } - cancellationHandler.removeCallbacksAndMessages(null); - } - }); - } else { - mImageCapture.takePicture(ContextCompat.getMainExecutor(getContext()), new ImageCapture.OnImageCapturedCallback() { - public void onCaptureSuccess(@NonNull ImageProxy image) { - if (save(file, image)) { - showImageConfirmation(file); - } else { - if (!reportedFailure.get()) { - onImageFailed(); - reportedFailure.set(true); - } - } - - cancellationHandler.removeCallbacksAndMessages(null); - } + }); + } - public void onError(@NonNull final ImageCaptureException e) { - Log.w(TAG, "Failed to take a picture. ImageCapture failed.", e); - if (!reportedFailure.get()) { - onImageFailed(); - reportedFailure.set(true); - } - cancellationHandler.removeCallbacksAndMessages(null); - } - }); + @Override public boolean isExtensionSupported(CameraView.Extension extension) { + if (extension == null) return false; + synchronized (mSnapshotLock) { + return mSnapshotExtensions.contains(extension); } } - private boolean save(File file, ImageProxy image) { - if (image.getFormat() != ImageFormat.JPEG) { - throw new IllegalArgumentException("Received ImageProxy with unexpected format " + image.getFormat()); + private boolean isExtensionAvailableInternal(@NonNull CameraView.Extension extension) { + if (extension == CameraView.Extension.NONE) return true; + ExtensionsManager manager = mExtensionsManager; + if (manager == null || mCameraProvider == null) return false; + CameraSelector selector = selectorFor(mFrontFacing + ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK); + try { + return manager.isExtensionAvailable(selector, toExtensionMode(extension)); + } catch (IllegalArgumentException | IllegalStateException error) { + Log.w(TAG, "Unable to query CameraX extension " + extension, error); + return false; } + } - ImageProxy.PlaneProxy planeProxy = image.getPlanes()[0]; - ByteBuffer buffer = planeProxy.getBuffer(); - byte[] bytes = new byte[buffer.remaining()]; - buffer.get(bytes); + private static int toExtensionMode(@NonNull CameraView.Extension extension) { + switch (extension) { + case BOKEH: return androidx.camera.extensions.ExtensionMode.BOKEH; + case HDR: return androidx.camera.extensions.ExtensionMode.HDR; + case NIGHT: return androidx.camera.extensions.ExtensionMode.NIGHT; + case FACE_RETOUCH: return androidx.camera.extensions.ExtensionMode.FACE_RETOUCH; + case AUTO: return androidx.camera.extensions.ExtensionMode.AUTO; + case NONE: + default: return androidx.camera.extensions.ExtensionMode.NONE; + } + } + @Override public void setFrontVideoMirroringEnabled(boolean enabled) { + super.setFrontVideoMirroringEnabled(enabled); + } - FileOutputStream output = null; - try { - output = new FileOutputStream(file); - output.write(bytes); - writeExif(file); - return true; - } catch (IOException e) { - Log.e(TAG, "Failed to write the file", e); - } finally { - image.close(); - if (output != null) { - try { - output.close(); - } catch (IOException e) { - Log.e(TAG, "Failed to close the output stream", e); - } - } + @Override public void setPreviewStabilizationEnabled(boolean enabled) { + if (enabled && mActiveCamera != null && !isPreviewStabilizationSupported()) { + Log.w(TAG, "Ignoring preview stabilization because the active camera does not support it"); + return; } - return false; + super.setPreviewStabilizationEnabled(enabled); + rebindConfiguration(); } - private void writeExif(File file) throws IOException { - Exif exif = new Exif(file); - exif.attachTimestamp(); - exif.rotate(getSensorOrientation()); - if (isUsingFrontFacingCamera()) { - exif.flipHorizontally(); + @Override public boolean isPreviewStabilizationSupported() { + synchronized (mSnapshotLock) { + return mSnapshotPreviewStabilizationSupported; } - Location location = getLocation(); - if (location != null) { - exif.attachLocation(location); + } + + @Override public void setVideoStabilizationEnabled(boolean enabled) { + if (enabled && mActiveCamera != null && !isVideoStabilizationSupported()) { + Log.w(TAG, "Ignoring video stabilization because the active camera does not support it"); + return; } - exif.save(); + super.setVideoStabilizationEnabled(enabled); } - @SuppressLint("MissingPermission") - @Nullable - private Location getLocation() { - if (PermissionChecker.hasPermissions(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)) { - // Our GPS timeout is purposefully low. We're not intending to wait until GPS is acquired - // but we want a last known location for the next time a picture is taken. - return LocationProvider.getGPSLocation(getContext(), STALE_LOCATION_MILLIS, GPS_TIMEOUT_MILLIS); + @Override public boolean isVideoStabilizationSupported() { + synchronized (mSnapshotLock) { + return mSnapshotVideoStabilizationSupported; } + } - return null; + @Override public void setExposureCompensation(int exposureCompensation) { + runOnMainThread(() -> setExposureCompensationOnMainThread(exposureCompensation)); } - @RequiresPermission(Manifest.permission.RECORD_AUDIO) - @Override - public void startRecording(File file) { - if (mCameraProvider == null) { - Log.w(TAG, "Failed to take a video. CameraProvider is not available yet."); - onVideoFailed(); + private void setExposureCompensationOnMainThread(int exposureCompensation) { + Camera camera = mActiveCamera; + if (camera == null) { + super.setExposureCompensation(exposureCompensation); return; } - - VideoCapture videoCapture = VideoCapture.withOutput(new Recorder.Builder() - .setQualitySelector(QualitySelector.fromOrderedList(getVideoQualityPriority())) - .build()); - - mVideoCapture = videoCapture; - if (!rebindUseCases()) { - Log.w(TAG, "Failed to take a video. VideoCapture failed."); - onVideoFailed(); - mVideoCapture = null; - rebindUseCases(); + ExposureState exposure = camera.getCameraInfo().getExposureState(); + if (!exposure.isExposureCompensationSupported()) { + Log.w(TAG, "Ignoring exposure request because the active camera does not support it"); return; } - - Recorder recorder = videoCapture.getOutput(); - FileOutputOptions.Builder options = new FileOutputOptions.Builder(file); - if (getMaxVideoSize() != CameraView.INDEFINITE_VIDEO_SIZE) { - options.setFileSizeLimit(getMaxVideoSize()); - } - PendingRecording pendingRecording = recorder.prepareRecording(getContext(), options.build()); - Recording recording = pendingRecording.withAudioEnabled().start(ContextCompat.getMainExecutor(getContext()), videoRecordEvent -> { - if (videoRecordEvent instanceof VideoRecordEvent.Start) { - Log.d(TAG, "Started video recording"); - } else if (videoRecordEvent instanceof VideoRecordEvent.Pause) { - Log.d(TAG, "Paused video recording"); - } else if (videoRecordEvent instanceof VideoRecordEvent.Resume) { - Log.d(TAG, "Resumed video recording"); - } else if (videoRecordEvent instanceof VideoRecordEvent.Status) { - Log.d(TAG, "Received video recording status update"); - } else if (videoRecordEvent instanceof VideoRecordEvent.Finalize) { - VideoRecordEvent.Finalize finalizeEvent = (VideoRecordEvent.Finalize) videoRecordEvent; - switch (finalizeEvent.getError()) { - case VideoRecordEvent.Finalize.ERROR_NONE: - case VideoRecordEvent.Finalize.ERROR_FILE_SIZE_LIMIT_REACHED: - case VideoRecordEvent.Finalize.ERROR_DURATION_LIMIT_REACHED: - // The good cases. - showVideoConfirmation(file); - stopRecording(); - break; - case VideoRecordEvent.Finalize.ERROR_INSUFFICIENT_STORAGE: - // The possibly good cases. - if (file.exists()) { - showVideoConfirmation(file); - stopRecording(); - break; - } - - // Fall through on failure - case VideoRecordEvent.Finalize.ERROR_ENCODING_FAILED: - case VideoRecordEvent.Finalize.ERROR_INVALID_OUTPUT_OPTIONS: - case VideoRecordEvent.Finalize.ERROR_NO_VALID_DATA: - case VideoRecordEvent.Finalize.ERROR_RECORDER_ERROR: - case VideoRecordEvent.Finalize.ERROR_SOURCE_INACTIVE: - case VideoRecordEvent.Finalize.ERROR_RECORDING_GARBAGE_COLLECTED: - case VideoRecordEvent.Finalize.ERROR_UNKNOWN: - default: - // The bad cases - Log.e(TAG, "Failed to start video recording: " + toString(finalizeEvent)); - onVideoFailed(); - stopRecording(); - break; - } - } else { - Log.w(TAG, "Received unknown video recording event " + videoRecordEvent); + Range range = exposure.getExposureCompensationRange(); + int clamped = Math.max(range.getLower(), Math.min(exposureCompensation, range.getUpper())); + ListenableFuture result = camera.getCameraControl().setExposureCompensationIndex(clamped); + result.addListener(() -> { + try { + super.setExposureCompensation(result.get()); + } catch (ExecutionException error) { + Log.w(TAG, "Exposure request failed", error.getCause()); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + Log.w(TAG, "Exposure request interrupted", error); } - }); - - mVideoCapture = videoCapture; - mVideoRecording = recording; + }, mMainExecutor); } - private List getVideoQualityPriority() { - List qualities = new ArrayList<>(); - switch (getQuality()) { - case MAX: - qualities.add(Quality.UHD); - // fall through - case HIGH: - qualities.add(Quality.FHD); - // fall through - case MEDIUM: - qualities.add(Quality.HD); - // fall through - case LOW: - qualities.add(Quality.SD); + @Override public int getMinExposureCompensation() { + synchronized (mSnapshotLock) { + return mSnapshotMinExposure; } - return qualities; } - private String toString(VideoRecordEvent.Finalize event) { - switch (event.getError()) { - case VideoRecordEvent.Finalize.ERROR_NONE: - return "ERROR_NONE"; - case VideoRecordEvent.Finalize.ERROR_FILE_SIZE_LIMIT_REACHED: - return "ERROR_FILE_SIZE_LIMIT_REACHED"; - case VideoRecordEvent.Finalize.ERROR_INSUFFICIENT_STORAGE: - return "ERROR_INSUFFICIENT_STORAGE"; - case VideoRecordEvent.Finalize.ERROR_ENCODING_FAILED: - return "ERROR_ENCODING_FAILED"; - case VideoRecordEvent.Finalize.ERROR_INVALID_OUTPUT_OPTIONS: - return "ERROR_INVALID_OUTPUT_OPTIONS"; - case VideoRecordEvent.Finalize.ERROR_NO_VALID_DATA: - return "ERROR_NO_VALID_DATA"; - case VideoRecordEvent.Finalize.ERROR_RECORDER_ERROR: - return "ERROR_RECORDER_ERROR"; - case VideoRecordEvent.Finalize.ERROR_SOURCE_INACTIVE: - return "ERROR_SOURCE_INACTIVE"; - case VideoRecordEvent.Finalize.ERROR_UNKNOWN: - default: - return String.format(Locale.US, "[%d]ERROR_UNKNOWN", event.getError()); + @Override public int getMaxExposureCompensation() { + synchronized (mSnapshotLock) { + return mSnapshotMaxExposure; } } - @Override - public void stopRecording() { - if (mVideoCapture == null || mVideoRecording == null) { - return; + @Override public boolean isExposureCompensationSupported() { + synchronized (mSnapshotLock) { + return mSnapshotExposureSupported; } + } - mVideoRecording.stop(); - unbind(mVideoCapture); - mVideoCapture = null; - mVideoRecording = null; - rebindUseCases(); + @Override public void setTorchEnabled(boolean enabled) { + runOnMainThread(() -> setTorchEnabledOnMainThread(enabled)); } - @Override - public boolean isRecording() { - return mVideoCapture != null; + private void setTorchEnabledOnMainThread(boolean enabled) { + Camera camera = mActiveCamera; + if (enabled && camera != null && !camera.getCameraInfo().hasFlashUnit()) { + Log.w(TAG, "Ignoring torch request because the active camera has no flash unit"); + return; + } + if (enabled && isLowLightBoostEnabled()) { + super.setLowLightBoostEnabled(false); + if (camera != null && camera.getCameraInfo().isLowLightBoostSupported()) { + camera.getCameraControl().enableLowLightBoostAsync(false); + } + } + super.setTorchEnabled(enabled); + if (camera == null) return; + ListenableFuture result = camera.getCameraControl().enableTorch(enabled); + reportControlFailure("Torch", result); } - private boolean areUseCasesMutuallyExclusive() { - return !isAtLeastLimited(); + @Override public void setLowLightBoostEnabled(boolean enabled) { + runOnMainThread(() -> setLowLightBoostEnabledOnMainThread(enabled)); } - private boolean isAtLeastLimited() { - switch (getHardwareLevel()) { - case CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3: - case CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL: - case CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL: - case CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED: - return true; - case CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY: - default: - return false; + private void setLowLightBoostEnabledOnMainThread(boolean enabled) { + Camera camera = mActiveCamera; + if (enabled && getDynamicRange() == CameraView.DynamicRange.HDR) { + Log.w(TAG, "Ignoring low-light boost because HDR is enabled"); + return; + } + if (enabled && camera != null && !camera.getCameraInfo().isLowLightBoostSupported()) { + Log.w(TAG, "Ignoring low-light boost because the active camera does not support it"); + return; } + if (enabled && isTorchEnabled()) { + super.setTorchEnabled(false); + if (camera != null) camera.getCameraControl().enableTorch(false); + } + super.setLowLightBoostEnabled(enabled); + if (camera == null || !camera.getCameraInfo().isLowLightBoostSupported()) return; + ListenableFuture result = camera.getCameraControl().enableLowLightBoostAsync(enabled); + reportControlFailure("Low-light boost", result); } - @SuppressLint("UnsafeOptInUsageError") - private int getHardwareLevel() { - if (mCameraProvider == null) { - return -1; + @Override public boolean isLowLightBoostSupported() { + synchronized (mSnapshotLock) { + return mSnapshotLowLightBoostSupported; } + } - if (mActiveCamera == null) { - return -1; + private void reportControlFailure(@NonNull String name, @NonNull ListenableFuture result) { + result.addListener(() -> { + try { + result.get(); + } catch (ExecutionException error) { + Log.w(TAG, name + " request failed", error.getCause()); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + Log.w(TAG, name + " request interrupted", error); + } + }, mMainExecutor); + } + + private void rebindConfiguration() { + runOnMainThread(() -> { + if (mOpenRequested && mVideoRecording == null && !mPaused && isHostActive()) { + reconcileUseCases(true); + } + }); + } + @Override public void setMaxVideoDuration(long duration) { + super.setMaxVideoDuration(duration); + runOnMainThread(() -> { + if (mVideoRecording != null) scheduleDurationStop(mVideoOperationId); + }); + } + + @Override public void setQuality(CameraView.Quality quality) { + super.setQuality(quality); + runOnMainThread(() -> { + if (mOpenRequested && mVideoRecording == null && !mPaused) reconcileUseCases(true); + }); + } + + @Override public void setMatchPreviewAspectRatio(boolean enabled) { + super.setMatchPreviewAspectRatio(enabled); + runOnMainThread(() -> { + if (mOpenRequested && mVideoRecording == null && !mPaused) reconcileUseCases(true); + }); + } + + /** + * Marks the backend paused without stopping the camera, which is as far as CameraX goes. + * + *

Camera2 stops its repeating request here, so the preview freezes while the still-capture + * surface stays configured. CameraX has no public equivalent: the only lever is unbinding the + * use cases, and that cannot be used here. CameraView calls pause() immediately before + * takePicture() when confirmation is enabled, so unbinding would drop the ImageCapture the + * capture is about to use, and it calls pause() before stopRecording(), where unbinding would + * destroy a recording that has not finalized.

+ * + *

Nothing visible depends on it, because the confirmation preview is drawn over the + * TextureView either way. The cost is power: the camera keeps streaming while the user looks + * at a captured frame, where Camera2's would have stopped. Closing that gap needs CameraX to + * expose something narrower than unbind.

+ */ + @Override public void pause() { + runOnMainThread(() -> { + mPaused = true; + publishSnapshot(); + }); + } + + @RequiresPermission(Manifest.permission.CAMERA) + @Override public void resume() { + runOnMainThread(() -> { + if (!mPaused) return; + mPaused = false; + updateBackendLifecycle(); + publishSnapshot(); + }); + } + + @Override public boolean isPaused() { + synchronized (mSnapshotLock) { + return mSnapshotPaused; + } + } + + @Override protected boolean startBarcodeScanner( + CameraView.BarcodeDetectorListener listener, + @Barcode.Format int format, + @Barcode.Format int... formats) { + if (listener == null) throw new NullPointerException("listener cannot be null"); + CameraXBarcodeAnalyzer analyzer; + try { + analyzer = new CameraXBarcodeAnalyzer(listener, mMainExecutor, format, formats); + } catch (RuntimeException | LinkageError error) { + // ML Kit is initialized by a manifest provider and its detector is delivered by Play + // services, so building the client can fail on a device that has neither. Reporting it + // here lets CameraView fall back to the shared scanner; the client used to be built + // inside the posted task below, where the same failure took the whole app down. + Log.w(TAG, "CameraX cannot scan barcodes on this device", error); + return false; + } + runOnMainThread(() -> startBarcodeScannerOnMainThread(analyzer)); + return true; + } + + private void startBarcodeScannerOnMainThread(@NonNull CameraXBarcodeAnalyzer analyzer) { + if (mBarcodeAnalyzer != null) { + Log.w(TAG, "CameraX barcode analysis is already active"); + analyzer.close(); + return; } + mAnalysisExecutor = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(runnable, "CameraView-BarcodeAnalysis"); + thread.setDaemon(true); + return thread; + }); + mBarcodeAnalyzer = analyzer; + if (mOpenRequested && mVideoRecording == null && !mPaused && isHostActive()) { + reconcileUseCases(true); + } + } - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { - return CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY; + @Override protected void stopBarcodeScanner() { + runOnMainThread(this::stopBarcodeScannerOnMainThread); + } + + private void stopBarcodeScannerOnMainThread() { + releaseBarcodeAnalysisResources(); + if (mOpenRequested && mVideoRecording == null && !mPaused && isHostActive()) { + reconcileUseCases(false); } + } + + private void releaseBarcodeAnalysisResources() { + CameraXBarcodeAnalyzer analyzer = mBarcodeAnalyzer; + mBarcodeAnalyzer = null; + if (analyzer != null) analyzer.close(); + ExecutorService executor = mAnalysisExecutor; + mAnalysisExecutor = null; + if (executor != null) executor.shutdownNow(); + } + @Override public void takePicture(File file) { + if (file == null) throw new NullPointerException("file cannot be null"); + runOnMainThread(() -> takePictureOnMainThread(file)); + } - Integer hardwareLevel = Camera2CameraInfo.from(mActiveCamera.getCameraInfo()).getCameraCharacteristic(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); - if (hardwareLevel == null) { - return CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY; + private void takePictureOnMainThread(@NonNull File file) { + ImageCapture imageCapture = mImageCapture; + if (!mOpenRequested || imageCapture == null || isRecording() || mPendingImageFile != null) { + Log.w(TAG, "Cannot take a picture in the current CameraX state: " + mState); + onImageFailed(); + return; } + long operationId = ++mImageOperationId; + mPendingImageFile = file; + scheduleImageTimeout(operationId); + ImageCapture.Metadata metadata = new ImageCapture.Metadata(); + metadata.setLocation(getLocation()); + metadata.setReversedHorizontal(mFrontFacing); + ImageCapture.OutputFileOptions options = new ImageCapture.OutputFileOptions.Builder(file) + .setMetadata(metadata).build(); + imageCapture.takePicture(options, mMainExecutor, new ImageCapture.OnImageSavedCallback() { + @Override public void onImageSaved(@NonNull ImageCapture.OutputFileResults results) { + if (!completePendingImage(operationId)) return; + showImageConfirmation(file); + } + @Override public void onError(@NonNull ImageCaptureException error) { + if (!completePendingImage(operationId)) return; + Log.w(TAG, "Image capture failed", error); + onImageFailed(); + } + }); + } + + private void scheduleImageTimeout(long operationId) { + cancelImageTimeout(); + mImageTimeoutTask = () -> { + if (operationId != mImageOperationId || mPendingImageFile == null) return; + failPendingImage("CameraX image capture timed out"); + }; + mMainHandler.postDelayed(mImageTimeoutTask, IMAGE_CAPTURE_TIMEOUT_MILLIS); + } - return hardwareLevel; + private boolean completePendingImage(long operationId) { + if (operationId != mImageOperationId || mPendingImageFile == null) return false; + mImageOperationId++; + mPendingImageFile = null; + cancelImageTimeout(); + return true; + } + + private void failPendingImage(@NonNull String reason) { + if (mPendingImageFile == null) return; + Log.e(TAG, reason); + mImageOperationId++; + mPendingImageFile = null; + cancelImageTimeout(); + onImageFailed(); } - @Override - protected int getRelativeCameraOrientation() { - return getRelativeImageOrientation(getDisplayRotation(), getSensorOrientation(), isUsingFrontFacingCamera(), false); + private void cancelImageTimeout() { + if (mImageTimeoutTask == null) return; + mMainHandler.removeCallbacks(mImageTimeoutTask); + mImageTimeoutTask = null; + } + @SuppressLint("MissingPermission") + @Nullable private Location getLocation() { + if (!PermissionChecker.hasPermissions(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)) return null; + return LocationProvider.getGPSLocation(getContext(), STALE_LOCATION_MILLIS, GPS_TIMEOUT_MILLIS); } - private Size getTargetResolution() { - return new Size(getWidth(), getHeight()); + @RequiresPermission(Manifest.permission.RECORD_AUDIO) + @Override public void startRecording(File file) { + if (file == null) throw new NullPointerException("file cannot be null"); + runOnMainThread(() -> startRecordingOnMainThread(file)); } - @AspectRatio.Ratio - private int getTargetAspectRatio() { - Size resolution = getTargetResolution(); + @SuppressLint("MissingPermission") + private void startRecordingOnMainThread(@NonNull File file) { + if (!mOpenRequested || mPaused || mState != State.OPEN || mVideoRecording != null) { + Log.w(TAG, "Cannot start recording in the current CameraX state: " + mState); + onVideoFailed(); + return; + } + long operationId = ++mVideoOperationId; + mRecordedVideoDurationMillis = 0; + Recorder recorder = new Recorder.Builder().setQualitySelector(createQualitySelector()).build(); + CameraInfo cameraInfo = mActiveCamera == null ? null : mActiveCamera.getCameraInfo(); + VideoCapture.Builder videoBuilder = new VideoCapture.Builder<>(recorder) + .setMirrorMode(isFrontVideoMirroringEnabled() + ? MirrorMode.MIRROR_MODE_ON_FRONT_ONLY : MirrorMode.MIRROR_MODE_OFF) + .setTargetRotation(getTargetRotation()); + if (cameraInfo != null) { + videoBuilder.setDynamicRange(selectedDynamicRange(cameraInfo)); + if (isVideoStabilizationEnabled() + && Recorder.getVideoCapabilities(cameraInfo).isStabilizationSupported()) { + videoBuilder.setVideoStabilizationEnabled(true); + } + } + mVideoCapture = videoBuilder.build(); + if (!reconcileUseCases(false)) { + mVideoCapture = null; + reconcileUseCases(false); + Log.w(TAG, "CameraX could not bind Preview and VideoCapture together"); + onVideoFailed(); + return; + } + try { + FileOutputOptions.Builder output = new FileOutputOptions.Builder(file); + if (getMaxVideoSize() != CameraView.INDEFINITE_VIDEO_SIZE) output.setFileSizeLimit(getMaxVideoSize()); + PendingRecording pending = recorder.prepareRecording(getContext(), output.build()); + if (PermissionChecker.hasPermissions(getContext(), Manifest.permission.RECORD_AUDIO)) pending = pending.withAudioEnabled(); + mVideoFile = file; + mState = State.RECORDING; + mVideoRecording = pending.start(mMainExecutor, event -> handleVideoEvent(operationId, file, event)); + scheduleRecordingStartTimeout(operationId); + publishSnapshot(); + } catch (RuntimeException error) { + Log.e(TAG, "Unable to start CameraX recording", error); + mVideoCapture = null; + mVideoFile = null; + mVideoRecording = null; + cancelRecordingTimeouts(); + mState = State.OPEN; + reconcileUseCases(false); + publishSnapshot(); + onVideoFailed(); + } + } - int width = Math.max(resolution.getWidth(), resolution.getHeight()); - int height = Math.min(resolution.getWidth(), resolution.getHeight()); - float aspectRatio = (float) width / (float) height; - // 1.55 is halfway between 1.33 (4:3) and 1.77 (16:9). As those are the only - // supported aspect ratios, we will use the closer one. - if (aspectRatio > 1.55) { - return AspectRatio.RATIO_16_9; + private void handleVideoEvent(long operationId, @NonNull File file, @NonNull VideoRecordEvent event) { + if (operationId != mVideoOperationId) return; + mRecordedVideoDurationMillis = Math.max(mRecordedVideoDurationMillis, + event.getRecordingStats().getRecordedDurationNanos() / 1_000_000L); + if (event instanceof VideoRecordEvent.Start) { + cancelRecordingStartTimeout(); + mState = State.RECORDING; + publishSnapshot(); + return; + } + if (event instanceof VideoRecordEvent.Status) { + scheduleDurationStop(operationId); + return; + } + if (!(event instanceof VideoRecordEvent.Finalize)) return; + VideoRecordEvent.Finalize finalized = (VideoRecordEvent.Finalize) event; + cancelDurationStop(); + cancelRecordingTimeouts(); + mVideoOperationId++; + mVideoRecording = null; + mVideoCapture = null; + mVideoFile = null; + applyPendingLensFacing(); + boolean success = isSuccessfulFinalize(finalized) && file.exists(); + if (mCriticalCameraFailure) { + releaseAllUseCases(); + mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED); + mState = State.ERROR; + } else if (mOpenRequested && isHostActive()) { + mState = State.OPEN; + if (!mPaused) reconcileUseCases(false); } else { - return AspectRatio.RATIO_4_3; + releaseAllUseCases(); + mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED); + mState = mOpenRequested ? State.SUSPENDED : State.CLOSED; + } + publishSnapshot(); + if (success) { + showVideoConfirmation(file); + } else { + Log.e(TAG, "CameraX recording failed: " + describeFinalize(finalized), finalized.getCause()); + onVideoFailed(); } } - private int getTargetRotation() { - switch (getDisplayRotation()) { - case 0: - return Surface.ROTATION_0; - case 90: - return Surface.ROTATION_90; - case 180: - return Surface.ROTATION_180; - case 270: - return Surface.ROTATION_270; + private static boolean isSuccessfulFinalize(@NonNull VideoRecordEvent.Finalize event) { + switch (event.getError()) { + case VideoRecordEvent.Finalize.ERROR_NONE: + case VideoRecordEvent.Finalize.ERROR_FILE_SIZE_LIMIT_REACHED: + case VideoRecordEvent.Finalize.ERROR_DURATION_LIMIT_REACHED: + return true; + default: + return false; } - return Surface.ROTATION_0; } - private CameraSelector getCameraSelector() { - return new CameraSelector.Builder().requireLensFacing(getLensFacing()).build(); + @NonNull private static String describeFinalize(@NonNull VideoRecordEvent.Finalize event) { + return String.format(Locale.US, "error=%d, stats=%s", event.getError(), event.getRecordingStats()); } - private int getLensFacing() { - return mIsFrontFacing ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK; + @Override public void stopRecording() { runOnMainThread(this::stopRecordingOnMainThread); } + + private void stopRecordingOnMainThread() { + Recording recording = mVideoRecording; + if (recording == null || mState == State.STOPPING) return; + cancelDurationStop(); + mState = State.STOPPING; + try { + recording.stop(); + scheduleRecordingFinalizeTimeout(mVideoOperationId); + } catch (RuntimeException error) { + Log.e(TAG, "Unable to stop CameraX recording", error); + File file = mVideoFile; + mVideoOperationId++; + mVideoRecording = null; + mVideoCapture = null; + mVideoFile = null; + cancelRecordingTimeouts(); + applyPendingLensFacing(); + if (mOpenRequested && isHostActive() && !mCriticalCameraFailure) { + mState = State.OPEN; + if (!mPaused) reconcileUseCases(false); + } else { + releaseAllUseCases(); + mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED); + mState = mCriticalCameraFailure ? State.ERROR + : (mOpenRequested ? State.SUSPENDED : State.CLOSED); + } + publishSnapshot(); + if (file != null) onVideoFailed(); + } } - private int getFlashMode() { - switch (getFlash()) { - case ON: - return ImageCapture.FLASH_MODE_ON; - case OFF: - return ImageCapture.FLASH_MODE_OFF; - case AUTO: - return ImageCapture.FLASH_MODE_AUTO; + @Override public boolean isRecording() { + synchronized (mSnapshotLock) { + return mSnapshotRecording; } - return ImageCapture.FLASH_MODE_AUTO; } - @SuppressLint("UnsafeOptInUsageError") - private int getCaptureMode() { - switch (getQuality()) { + private void scheduleRecordingStartTimeout(long operationId) { + cancelRecordingStartTimeout(); + mRecordingStartTimeoutTask = () -> { + if (operationId != mVideoOperationId || mVideoRecording == null) return; + Log.e(TAG, "CameraX recording did not start before the timeout"); + stopRecordingOnMainThread(); + }; + mMainHandler.postDelayed(mRecordingStartTimeoutTask, RECORDING_START_TIMEOUT_MILLIS); + } + + private void scheduleRecordingFinalizeTimeout(long operationId) { + cancelRecordingFinalizeTimeout(); + mRecordingFinalizeTimeoutTask = () -> { + if (operationId != mVideoOperationId || mVideoRecording == null) return; + Log.e(TAG, "CameraX recording did not finalize before the timeout"); + Recording recording = mVideoRecording; + mVideoOperationId++; + mVideoRecording = null; + mVideoCapture = null; + mVideoFile = null; + cancelDurationStop(); + cancelRecordingTimeouts(); + try { + recording.close(); + } catch (RuntimeException error) { + Log.w(TAG, "Unable to close timed-out CameraX recording", error); + } + applyPendingLensFacing(); + if (mOpenRequested && isHostActive() && !mCriticalCameraFailure) { + mState = State.OPEN; + if (!mPaused) reconcileUseCases(false); + } else { + releaseAllUseCases(); + mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED); + mState = mCriticalCameraFailure ? State.ERROR + : (mOpenRequested ? State.SUSPENDED : State.CLOSED); + } + publishSnapshot(); + onVideoFailed(); + }; + mMainHandler.postDelayed(mRecordingFinalizeTimeoutTask, RECORDING_FINALIZE_TIMEOUT_MILLIS); + } + + private void cancelRecordingStartTimeout() { + if (mRecordingStartTimeoutTask == null) return; + mMainHandler.removeCallbacks(mRecordingStartTimeoutTask); + mRecordingStartTimeoutTask = null; + } + + private void cancelRecordingFinalizeTimeout() { + if (mRecordingFinalizeTimeoutTask == null) return; + mMainHandler.removeCallbacks(mRecordingFinalizeTimeoutTask); + mRecordingFinalizeTimeoutTask = null; + } + + private void cancelRecordingTimeouts() { + cancelRecordingStartTimeout(); + cancelRecordingFinalizeTimeout(); + } + private void scheduleDurationStop(long operationId) { + cancelDurationStop(); + long remaining = remainingDurationMillis( + getMaxVideoDuration(), mRecordedVideoDurationMillis); + if (remaining < 0) return; + mDurationStopTask = () -> { + if (operationId == mVideoOperationId && mVideoRecording != null) { + stopRecordingOnMainThread(); + } + }; + if (remaining == 0) { + mDurationStopTask.run(); + } else { + mMainHandler.postDelayed(mDurationStopTask, remaining); + } + } + + static long remainingDurationMillis(long maximum, long recorded) { + if (maximum == CameraView.INDEFINITE_VIDEO_DURATION + || maximum <= 0 || recorded <= 0) { + return -1; + } + return Math.max(0, maximum - recorded); + } + + private void cancelDurationStop() { + if (mDurationStopTask != null) { + mMainHandler.removeCallbacks(mDurationStopTask); + mDurationStopTask = null; + } + } + + private static boolean supportsHdr(@NonNull CameraInfo cameraInfo) { + Set cameraRanges = cameraInfo.querySupportedDynamicRanges( + Collections.singleton(DynamicRange.HDR_UNSPECIFIED_10_BIT)); + Set videoRanges = Recorder.getVideoCapabilities(cameraInfo) + .getSupportedDynamicRanges(); + for (DynamicRange range : videoRanges) { + if (range.getEncoding() != DynamicRange.ENCODING_SDR && cameraRanges.contains(range)) { + return true; + } + } + return false; + } + + @NonNull private DynamicRange selectedDynamicRange(@NonNull CameraInfo cameraInfo) { + if (getDynamicRange() == CameraView.DynamicRange.SDR) return DynamicRange.SDR; + Set cameraRanges = cameraInfo.querySupportedDynamicRanges( + Collections.singleton(DynamicRange.HDR_UNSPECIFIED_10_BIT)); + VideoCapabilities capabilities = Recorder.getVideoCapabilities(cameraInfo); + for (DynamicRange range : capabilities.getSupportedDynamicRanges()) { + if (range.getEncoding() != DynamicRange.ENCODING_SDR && cameraRanges.contains(range)) { + return range; + } + } + Log.w(TAG, "Falling back to SDR because HDR is unavailable for this lens"); + return DynamicRange.SDR; + } + @NonNull private QualitySelector createQualitySelector() { + List priorities = videoQualityPriority(getQuality()); + Quality lowestPreference = priorities.get(priorities.size() - 1); + return QualitySelector.fromOrderedList(priorities, FallbackStrategy.lowerQualityOrHigherThan(lowestPreference)); + } + + @NonNull static List videoQualityPriority(@NonNull CameraView.Quality quality) { + List qualities = new ArrayList<>(); + switch (quality) { case MAX: - return ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY; + qualities.add(Quality.UHD); + qualities.add(Quality.FHD); + qualities.add(Quality.HD); + qualities.add(Quality.SD); + break; case HIGH: - return ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY; - default: - return ImageCapture.CAPTURE_MODE_ZERO_SHUTTER_LAG; + qualities.add(Quality.FHD); + qualities.add(Quality.HD); + qualities.add(Quality.SD); + break; + case MEDIUM: + qualities.add(Quality.HD); + qualities.add(Quality.SD); + break; + case LOW: + qualities.add(Quality.SD); + break; } + return qualities; } - - private boolean bind(UseCase... useCases) { - if (mCameraProvider == null) { + @SuppressLint("MissingPermission") + private boolean reconcileUseCases(boolean reportFailure) { + if (mDestroyed) return false; + if (!mOpenRequested || mPaused) return false; + if (!isHostActive()) { + mState = State.SUSPENDED; return false; } - + ProcessCameraProvider provider = mCameraProvider; + if (provider == null) { + mState = State.WAITING_FOR_PROVIDER; + return false; + } + if (mVideoRecording != null) return true; + long generation = ++mGeneration; + mState = State.BINDING; + CameraSelector selector = getCameraSelector(); try { - int width = getWidth(); - int height = getHeight(); - if (width > 0 && height > 0) { - Rational aspect = new Rational(width, height); - ViewPort viewPort = new ViewPort.Builder(aspect, getTargetRotation()).build(); - UseCaseGroup.Builder builder = new UseCaseGroup.Builder() - .setViewPort(viewPort); - for (UseCase useCase : useCases) { - builder.addUseCase(useCase); + if (!provider.hasCamera(selector)) throw new IllegalStateException("No camera matches the requested lens facing"); + CameraInfo cameraInfo = provider.getCameraInfo(selector); + mSensorOrientation = cameraInfo.getSensorRotationDegrees(); + Preview displayPreview = createDisplayPreview(generation, cameraInfo); + // A still output is wanted alongside a recording, not instead of it: that is the + // combination a camera app's video-snapshot button uses. Barcode analysis is the one + // thing that genuinely takes the slot, because it needs the frames itself. + ImageCapture imageCapture = mBarcodeAnalyzer == null + ? createImageCapture(cameraInfo) : null; + ImageAnalysis imageAnalysis = mVideoCapture == null && mBarcodeAnalyzer != null + ? createImageAnalysis() : null; + Map streamPreviews = createStreamPreviews(generation); + List requested = new ArrayList<>(); + requested.add(displayPreview); + if (mVideoCapture != null) requested.add(mVideoCapture); + if (imageCapture != null) requested.add(imageCapture); + else if (imageAnalysis != null) requested.add(imageAnalysis); + requested.addAll(streamPreviews.values()); + + // Not every camera can hold a preview, a recording and a still at once. Asked for one + // that cannot, the bind fails and the recording is lost with it, so the still is the + // part that gives way. + if (mVideoCapture != null && imageCapture != null + && !cameraInfo.isSessionConfigSupported(createSessionConfig(requested))) { + Log.d(TAG, "This camera cannot take a picture while recording"); + requested.remove(imageCapture); + imageCapture = null; + } + mSnapshotWhileRecording = mVideoCapture != null && imageCapture != null; + if (!streamPreviews.isEmpty() + && !provider.getCameraInfo(selector).isSessionConfigSupported(createSessionConfig(requested))) { + if (isPreviewStabilizationEnabled()) { + displayPreview = createDisplayPreview(generation, cameraInfo, false); + requested.set(0, displayPreview); + Log.w(TAG, "Preview stabilization is unavailable while a custom stream is attached"); } - mActiveCamera = mCameraProvider.bindToLifecycle(this, getCameraSelector(), builder.build()); - } else { - mActiveCamera = mCameraProvider.bindToLifecycle(this, getCameraSelector(), useCases); + if (!provider.getCameraInfo(selector) + .isSessionConfigSupported(createSessionConfig(requested))) { + // Some CameraX backends report false for a second Preview even though the real + // bind succeeds. Keep this as diagnostics and let the atomic bind decide. + Log.w(TAG, "CameraX could not preflight the requested streaming combination"); + } + } + unbindCurrentUseCases(); + Camera camera = bindAtomically(selector, requested); + if (generation != mGeneration || !mOpenRequested || mPaused) { + provider.unbind(requested.toArray(new UseCase[0])); + return false; + } + mPreview = displayPreview; + mImageCapture = imageCapture; + mImageAnalysis = imageAnalysis; + mBoundStreamPreviews.clear(); + mBoundStreamPreviews.putAll(streamPreviews); + mBoundUseCases.clear(); + mBoundUseCases.addAll(requested); + mActiveCamera = camera; + observeCameraState(camera); + mState = mVideoCapture == null ? State.OPEN : State.BINDING; + publishSnapshot(); + if (mZoomLevel > 0) setZoomOnMainThread(mZoomLevel); + if (getExposureCompensation() != 0) { + setExposureCompensationOnMainThread(getExposureCompensation()); } + if (isTorchEnabled()) setTorchEnabledOnMainThread(true); + if (isLowLightBoostEnabled()) setLowLightBoostEnabledOnMainThread(true); return true; - } catch (IllegalArgumentException e) { - Log.w(TAG, "Failed to bind UseCase.", e); + } catch (CameraInfoUnavailableException | IllegalArgumentException | IllegalStateException error) { + unbindCurrentUseCases(); + mState = State.ERROR; + Log.e(TAG, "Unable to bind CameraX use cases", error); + if (reportFailure) onCameraError(error); return false; } } - private void unbind(UseCase... useCases) { - if (mCameraProvider == null) { - return; + @NonNull private Camera bindAtomically(@NonNull CameraSelector selector, @NonNull List useCases) { + int width = getWidth(); + int height = getHeight(); + if (isMatchPreviewAspectRatioEnabled() && width > 0 && height > 0) { + UseCaseGroup.Builder group = new UseCaseGroup.Builder().setViewPort(createViewPort(width, height)); + for (UseCase useCase : useCases) group.addUseCase(useCase); + return mCameraProvider.bindToLifecycle(this, selector, group.build()); + } + return mCameraProvider.bindToLifecycle(this, selector, useCases.toArray(new UseCase[0])); + } + + @NonNull private SessionConfig createSessionConfig(@NonNull List useCases) { + SessionConfig.Builder builder = new SessionConfig.Builder(useCases); + int width = getWidth(); + int height = getHeight(); + if (isMatchPreviewAspectRatioEnabled() && width > 0 && height > 0) { + builder.setViewPort(createViewPort(width, height)); } + return builder.build(); + } + + @NonNull private ViewPort createViewPort(int width, int height) { + return new ViewPort.Builder(new Rational(width, height), getTargetRotation()) + .setScaleType(ViewPort.FILL_CENTER).build(); + } + + @NonNull private Preview createDisplayPreview(long generation, @NonNull CameraInfo cameraInfo) { + return createDisplayPreview(generation, cameraInfo, true); + } + + @NonNull private Preview createDisplayPreview( + long generation, @NonNull CameraInfo cameraInfo, boolean allowStabilization) { + Preview.Builder builder = new Preview.Builder() + .setResolutionSelector(createResolutionSelector()) + .setTargetRotation(getTargetRotation()); + if (allowStabilization && isPreviewStabilizationEnabled() + && Preview.getPreviewCapabilities(cameraInfo).isStabilizationSupported()) { + builder.setPreviewStabilizationEnabled(true); + } + applyFaceDetection(builder, cameraInfo); + Preview preview = builder.build(); + preview.setSurfaceProvider(mMainExecutor, request -> provideDisplaySurface(generation, request)); + return preview; + } + + @Override public boolean isSnapshotWhileRecordingSupported() { + return mSnapshotWhileRecording; + } - mCameraProvider.unbind(useCases); + @Override public boolean isFaceDetectionSupported() { + Camera camera = mActiveCamera; + return camera != null && faceDetectMode(camera.getCameraInfo()) != null; } - private boolean rebindUseCases() { - if (!mIsOpen || mCameraProvider == null) { + @Override protected boolean setFaceDetectionEnabled(boolean enabled) { + if (!enabled) { + boolean wasEnabled = mFaceDetectionRequested; + mFaceDetectionRequested = false; + if (wasEnabled) { + runOnMainThread(() -> reconcileUseCases(false)); + } + return true; + } + if (!isFaceDetectionSupported()) { return false; } + mFaceDetectionRequested = true; + runOnMainThread(() -> reconcileUseCases(false)); + return true; + } - List toUnbind = new ArrayList<>(); - if (mPreview != null) toUnbind.add(mPreview); - if (mImageCapture != null) toUnbind.add(mImageCapture); - if (mVideoCapture != null) toUnbind.add(mVideoCapture); - toUnbind.addAll(mCustomUseCases.values()); - - mCameraProvider.unbind(toUnbind.toArray(new UseCase[0])); + /** + * Asks the camera for the faces it is tracking, through Camera2. + * + *

CameraX has no face detection of its own, so this goes straight to the camera2 request + * the pipeline is going to issue anyway. That is a request option and a session callback, both + * fixed when a use case is bound, which is why turning detection on rebinds.

+ */ + @OptIn(markerClass = ExperimentalCamera2Interop.class) + private void applyFaceDetection( + @NonNull Preview.Builder builder, @Nullable CameraInfo cameraInfo) { + if (!mFaceDetectionRequested) { + return; + } + Integer mode = faceDetectMode(cameraInfo); + if (mode == null) { + return; + } + new Camera2Interop.Extender<>(builder) + .setCaptureRequestOption(CaptureRequest.STATISTICS_FACE_DETECT_MODE, mode) + .setSessionCaptureCallback(new CameraCaptureSession.CaptureCallback() { + @Override public void onCaptureCompleted( + @NonNull CameraCaptureSession session, + @NonNull CaptureRequest request, + @NonNull TotalCaptureResult result) { + onFacesCaptured(result); + } + }); + } - List useCases = new ArrayList<>(); - if (mPreview != null) { - useCases.add(mPreview); + /** The richest face detection mode the bound camera supports, or null if it has none. */ + @OptIn(markerClass = ExperimentalCamera2Interop.class) + @Nullable + private Integer faceDetectMode(@Nullable CameraInfo cameraInfo) { + if (cameraInfo == null) { + return null; } - if (mVideoCapture != null) { - useCases.add(mVideoCapture); - if (!areUseCasesMutuallyExclusive() && mImageCapture != null) { - useCases.add(mImageCapture); + try { + Camera2CameraInfo camera2 = Camera2CameraInfo.from(cameraInfo); + int[] modes = camera2.getCameraCharacteristic( + CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES); + Integer maxFaces = camera2.getCameraCharacteristic( + CameraCharacteristics.STATISTICS_INFO_MAX_FACE_COUNT); + if (modes == null || maxFaces == null || maxFaces <= 0) { + return null; } - } else if (mImageCapture != null) { - useCases.add(mImageCapture); + boolean simple = false; + for (int mode : modes) { + if (mode == CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_FULL) { + return CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_FULL; + } + if (mode == CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE) { + simple = true; + } + } + return simple ? CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE : null; + } catch (RuntimeException | LinkageError error) { + // A camera CameraX is not driving through camera2 cannot answer this at all. + if (DEBUG) Log.d(TAG, "Camera cannot report its face detection modes", error); + return null; } - useCases.addAll(mCustomUseCases.values()); + } - if (!useCases.isEmpty()) { - return bind(useCases.toArray(new UseCase[0])); + /** Translates a capture result's faces and hands them to the view, on the main thread. */ + private void onFacesCaptured(@NonNull TotalCaptureResult result) { + android.hardware.camera2.params.Face[] detected = + result.get(CaptureResult.STATISTICS_FACES); + if (detected == null) { + detected = new android.hardware.camera2.params.Face[0]; } - return false; - } + if (detected.length == 0 && mLastFaceCount == 0) { + return; + } + mLastFaceCount = detected.length; - @Override - protected void attachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { - Preview useCase = new Preview.Builder() - .setTargetResolution(getTargetResolution()) - //.setTargetAspectRatio(getTargetAspectRatio()) - .setTargetRotation(getTargetRotation()) - .build(); - useCase.setSurfaceProvider(request -> - request.provideSurface(surfaceProvider.getSurface(request.getResolution().getWidth(), request.getResolution().getHeight(), getSensorOrientation(), isUsingFrontFacingCamera()), ContextCompat.getMainExecutor(getContext()), result -> { - if (DEBUG) { - Log.d(TAG, "Surface no longer needed. Result Code: " + result.getResultCode()); + List faces = new ArrayList<>(detected.length); + for (android.hardware.camera2.params.Face face : detected) { + Rect bounds = face.getBounds(); + if (bounds == null) { + continue; } - })); - if (bind(useCase)) { - mCustomUseCases.put(surfaceProvider, useCase); - Log.d(TAG, "Successfully bound custom surface"); + faces.add(Face.create(bounds, face.getScore(), face.getId(), + face.getLeftEyePosition(), face.getRightEyePosition(), + face.getMouthPosition())); } + onFacesDetected(faces, faceToViewTransform(result)); } - @Override - protected void detachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { - UseCase useCase = mCustomUseCases.remove(surfaceProvider); - if (useCase != null) { - unbind(useCase); + /** + * Maps face bounds onto the view. + * + *

Faces are reported in active-array coordinates, so the region being previewed is the crop + * region the request ended up with. The rotation is the one CameraX publishes for the stream: + * its transformation info already states the turn from the sensor to the target rotation, + * which is exactly what sensor coordinates need to become view coordinates.

+ */ + @NonNull + private Matrix faceToViewTransform(@NonNull TotalCaptureResult result) { + Rect region = result.get(CaptureResult.SCALER_CROP_REGION); + if (region == null) { + region = activeArraySize(); } + SurfaceRequest.TransformationInfo information = mTransformationInfo; + if (region == null || information == null) { + return new Matrix(); + } + return TransformMath.centerCrop(new RectF(region), + CameraXMath.within360(information.getRotationDegrees()), + false /* mirroring is the caller's decision */, + getView().getWidth(), getView().getHeight()); } - @Override - public void onLayoutChanged() { - if (mPreviewSize == null) { + @OptIn(markerClass = ExperimentalCamera2Interop.class) + @Nullable + private Rect activeArraySize() { + Camera camera = mActiveCamera; + if (camera == null) { + return null; + } + CameraInfo cameraInfo = camera.getCameraInfo(); + try { + return Camera2CameraInfo.from(cameraInfo).getCameraCharacteristic( + CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); + } catch (RuntimeException | LinkageError error) { + if (DEBUG) Log.d(TAG, "Camera cannot report its active array", error); + return null; + } + } + + private void provideDisplaySurface(long generation, @NonNull SurfaceRequest request) { + SurfaceTexture texture = getSurfaceTexture(); + if (texture == null || generation != mGeneration || !mOpenRequested) { + request.willNotProvideSurface(); return; } + Size resolution = request.getResolution(); + texture.setDefaultBufferSize(resolution.getWidth(), resolution.getHeight()); + request.setTransformationInfoListener(mMainExecutor, information -> { + if (generation != mGeneration) return; + mPreviewResolution = resolution; + mTransformationInfo = information; + applyPreviewTransform(); + }); + Surface surface = new Surface(texture); + request.provideSurface(surface, mMainExecutor, result -> { + request.clearTransformationInfoListener(); + surface.release(); + if (DEBUG) Log.d(TAG, "Display surface released with result " + result.getResultCode()); + }); + } + + @NonNull private ImageCapture createImageCapture(@NonNull CameraInfo cameraInfo) { + return new ImageCapture.Builder() + .setResolutionSelector(createImageResolutionSelector()) + .setTargetRotation(getTargetRotation()) + .setFlashMode(getFlashMode()) + .setCaptureMode(getCaptureMode()) + .setJpegQuality(getPictureQuality()) + .build(); + } + + @NonNull private ImageAnalysis createImageAnalysis() { + ExecutorService executor = mAnalysisExecutor; + CameraXBarcodeAnalyzer analyzer = mBarcodeAnalyzer; + if (executor == null || analyzer == null) { + throw new IllegalStateException("Barcode analysis requested without an analyzer executor"); + } + ImageAnalysis analysis = new ImageAnalysis.Builder() + .setResolutionSelector(createResolutionSelector()) + .setTargetRotation(getTargetRotation()) + .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) + .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888) + .build(); + analysis.setAnalyzer(executor, analyzer); + return analysis; + } + @NonNull private Map createStreamPreviews(long generation) { + Map previews = new LinkedHashMap<>(); + for (VideoRecorder.SurfaceProvider surfaceProvider : mSurfaceProviders) { + Size maxSize = surfaceProvider.getMaxSize(); + Preview preview = new Preview.Builder() + .setResolutionSelector(maxSize == null + ? createResolutionSelector() + : createStreamResolutionSelector(maxSize)) + .setTargetRotation(getTargetRotation()) + .build(); + preview.setSurfaceProvider(mMainExecutor, request -> { + if (generation != mGeneration || !mOpenRequested) { + request.willNotProvideSurface(); + return; + } + try { + Size resolution = request.getResolution(); + Surface surface = surfaceProvider.getSurface( + resolution.getWidth(), resolution.getHeight(), getSensorOrientation(), mFrontFacing); + request.provideSurface(surface, mMainExecutor, result -> { + if (DEBUG) Log.d(TAG, "Stream surface released with result " + result.getResultCode()); + }); + } catch (RuntimeException error) { + Log.e(TAG, "Unable to provide CameraX stream surface", error); + request.willNotProvideSurface(); + } + }); + previews.put(surfaceProvider, preview); + } + return previews; + } + + private void unbindCurrentUseCases() { + if (mCameraProvider != null && !mBoundUseCases.isEmpty()) { + try { + mCameraProvider.unbind(mBoundUseCases.toArray(new UseCase[0])); + } catch (RuntimeException error) { + Log.w(TAG, "Unable to unbind CameraX use cases", error); + } + } + mBoundUseCases.clear(); + mBoundStreamPreviews.clear(); + if (mObservedCameraState != null && mCameraStateObserver != null) { + mObservedCameraState.removeObserver(mCameraStateObserver); + } + mObservedCameraState = null; + mCameraStateObserver = null; + mActiveCamera = null; + mPreview = null; + mImageCapture = null; + mImageAnalysis = null; + mPreviewResolution = null; + mTransformationInfo = null; + publishSnapshot(); + } - transformPreview(mPreviewSize.getWidth(), mPreviewSize.getHeight()); + private void releaseAllUseCases() { + unbindCurrentUseCases(); + mVideoCapture = null; + mVideoRecording = null; + mVideoFile = null; + releaseBarcodeAnalysisResources(); + setTransform(new Matrix()); + } + @NonNull private ResolutionSelector createResolutionSelector() { + ResolutionSelector.Builder builder = new ResolutionSelector.Builder().setAspectRatioStrategy(getAspectRatioStrategy()); int width = getWidth(); int height = getHeight(); - if (width != mLastWidth || height != mLastHeight) { - mLastWidth = width; - mLastHeight = height; - getView().post(() -> rebindUseCases()); + if (width > 0 && height > 0) { + builder.setResolutionStrategy(new ResolutionStrategy( + new Size(width, height), ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER)); } + return builder.build(); } - private void transformPreview(int previewWidth, int previewHeight) { - int viewWidth = getWidth(); - int viewHeight = getHeight(); - int displayOrientation = getDisplayRotation(); - int cameraOrientation = getSensorOrientation(); + /** + * Resolution for a custom stream whose caller has capped it, because it is leaving the device + * over a link the preview resolution would not fit through. Prefers the largest supported + * size at or below the cap, and only exceeds it when the camera offers nothing smaller. + */ + @NonNull private ResolutionSelector createStreamResolutionSelector(@NonNull Size maxSize) { + return new ResolutionSelector.Builder() + .setAspectRatioStrategy(getAspectRatioStrategy()) + .setResolutionStrategy(new ResolutionStrategy( + maxSize, ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER)) + .build(); + } - // Camera2 rotates the preview to always face in portrait mode, even if the phone is - // currently in landscape. This is great for portrait mode, because there's less work to be done. - // It's less great for landscape, because we have to undo it. Without any matrix modifications, - // the preview will be smushed into the aspect ratio of the view. - Matrix matrix = new Matrix(); + @NonNull private ResolutionSelector createImageResolutionSelector() { + return new ResolutionSelector.Builder() + .setAspectRatioStrategy(getAspectRatioStrategy()) + .setResolutionStrategy(new ResolutionStrategy(imageTargetSize(getQuality()), + ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER)) + .build(); + } - // Camera2 reverses the preview width/height. - if (cameraOrientation != 0 && cameraOrientation != 180) { - int temp = previewWidth; - previewWidth = previewHeight; - previewHeight = temp; + @NonNull static Size imageTargetSize(@NonNull CameraView.Quality quality) { + switch (quality) { + case MAX: return new Size(3840, 2160); + case HIGH: return new Size(1920, 1080); + case MEDIUM: return new Size(1280, 720); + case LOW: + default: return new Size(720, 480); } + } + @NonNull private AspectRatioStrategy getAspectRatioStrategy() { + int width = Math.max(getWidth(), getHeight()); + int height = Math.min(getWidth(), getHeight()); + if (width > 0 && height > 0 && (float) width / height > 1.55f) { + return AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY; + } + return AspectRatioStrategy.RATIO_4_3_FALLBACK_AUTO_STRATEGY; + } - // We want to find the aspect ratio of the preview. Our goal is to stretch the image in - // our SurfaceView to match this ratio, so that the image doesn't looked smushed. - // This means the edges of the preview will be cut off. - float aspectRatio = (float) previewHeight / (float) previewWidth; - int newWidth, newHeight; - if (viewHeight > viewWidth * aspectRatio) { - newWidth = (int) Math.ceil(viewHeight / aspectRatio); - newHeight = viewHeight; - } else { - newWidth = viewWidth; - newHeight = (int) Math.ceil(viewWidth * aspectRatio); - } - - // For portrait, we've already been mostly stretched. For landscape, our image is rotated 90 degrees. - // Think of it as a sideways squished photo. We want to first streeeetch the height of the photo - // until it matches the aspect ratio we originally expected. Now we're no longer stretched - // (although we're wildly off screen, with only the far left sliver of the photo still - // visible on the screen, and our picture is still sideways). - float scaleX = (float) newWidth / (float) viewWidth; - float scaleY = (float) newHeight / (float) viewHeight; - - // However, we've actually stretched too much. The height of the picture is currently the - // width of our screen. When we rotate the picture, it'll be too large and we'll end up - // cropping a lot of the picture. That's what this step is for. We scale down the image so - // that the height of the photo (currently the width of the phone) becomes the height we - // want (the height of the phone, or slightly bigger, depending on aspect ratio). - float scale = 1f; - if (displayOrientation == 90 || displayOrientation == 270) { - boolean cropHeight = viewWidth > newHeight * viewHeight / newWidth; - if (cropHeight) { - // If we're cropping the top/bottom, then we want the widths to be exact - scale = (float) viewWidth / newHeight; - } else { - // If we're cropping the left/right, then we want the heights to be exact - scale = (float) viewHeight / newWidth; + @NonNull private CameraSelector getCameraSelector() { + CameraSelector selector = selectorFor(mFrontFacing + ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK); + CameraView.Extension extension = getExtension(); + ExtensionsManager manager = mExtensionsManager; + if (mVideoCapture == null && extension != CameraView.Extension.NONE && manager != null) { + try { + int extensionMode = toExtensionMode(extension); + boolean analysisCompatible = mBarcodeAnalyzer == null + || manager.isImageAnalysisSupported(selector, extensionMode); + if (analysisCompatible && manager.isExtensionAvailable(selector, extensionMode)) { + return manager.getExtensionEnabledCameraSelector(selector, extensionMode); + } + } catch (IllegalArgumentException | IllegalStateException error) { + Log.w(TAG, "Unable to enable CameraX extension " + extension, error); } - newWidth = (int) Math.ceil(newWidth * scale); - newHeight = (int) Math.ceil(newHeight * scale); - scaleX *= scale; - scaleY *= scale; } + return selector; + } - // Because we scaled the preview beyond the bounds of the view, we need to crop some of it. - // By translating the photo over, we'll move it into the center. - int translateX = (int) Math.ceil((viewWidth - newWidth) / 2d); - int translateY = (int) Math.ceil((viewHeight - newHeight) / 2d); + @NonNull private static CameraSelector selectorFor(int lensFacing) { + return new CameraSelector.Builder().requireLensFacing(lensFacing).build(); + } - // Due to the direction of rotation (90 vs 270), a 1 pixel offset can either put us - // exactly where we want to be, or it can put us 1px lower than we wanted. This is error - // correction for that. - if (displayOrientation == 270) { - translateX = (int) Math.floor((viewWidth - newWidth) / 2d); - translateY = (int) Math.floor((viewHeight - newHeight) / 2d); + private int getFlashMode() { + switch (getFlash()) { + case ON: return ImageCapture.FLASH_MODE_ON; + case OFF: return ImageCapture.FLASH_MODE_OFF; + case AUTO: + default: return ImageCapture.FLASH_MODE_AUTO; } + } - // Finally, with our photo scaled and centered, we apply a rotation. - int rotation = -displayOrientation; - - matrix.setScale(scaleX, scaleY); - matrix.postTranslate(translateX, translateY); - matrix.postRotate(rotation, (int) Math.ceil(viewWidth / 2d), (int) Math.ceil(viewHeight / 2d)); + private int getCaptureMode() { + switch (getQuality()) { + case MAX: return ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY; + case HIGH: + case MEDIUM: + case LOW: + default: return ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY; + } + } - if (DEBUG) { - Log.d(TAG, String.format("transformPreview: displayOrientation=%s, cameraOrientation=%s, " - + "viewWidth=%s, viewHeight=%s, viewAspectRatio=%s, previewWidth=%s, previewHeight=%s, previewAspectRatio=%s, " - + "newWidth=%s, newHeight=%s, scaleX=%s, scaleY=%s, scale=%s, " - + "translateX=%s, translateY=%s, rotation=%s", - displayOrientation, cameraOrientation, viewWidth, viewHeight, - ((float) viewHeight / (float) viewWidth), previewWidth, previewHeight, aspectRatio, - newWidth, newHeight, scaleX, scaleY, scale, translateX, translateY, rotation)); + private int getTargetRotation() { + switch (getDisplayRotation()) { + case 90: return Surface.ROTATION_90; + case 180: return Surface.ROTATION_180; + case 270: return Surface.ROTATION_270; + case 0: + default: return Surface.ROTATION_0; } + } + + private int getSensorOrientation() { + Camera camera = mActiveCamera; + return camera == null ? mSensorOrientation : camera.getCameraInfo().getSensorRotationDegrees(); + } + + @Override protected int getRelativeCameraOrientation() { + return getRelativeImageOrientation(getDisplayRotation(), getSensorOrientation(), mFrontFacing, false); + } + @Override protected void attachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { + if (surfaceProvider == null) return; + runOnMainThread(() -> { + if (!mSurfaceProviders.add(surfaceProvider)) return; + if (mOpenRequested && !mPaused && mVideoRecording == null + && mCameraProvider != null && !reconcileUseCases(false)) { + mSurfaceProviders.remove(surfaceProvider); + reconcileUseCases(false); + Log.e(TAG, "Device rejected the additional CameraX streaming Preview"); + } + }); + } + + @Override protected void detachSurface(VideoRecorder.SurfaceProvider surfaceProvider) { + if (surfaceProvider == null) return; + runOnMainThread(() -> { + if (!mSurfaceProviders.remove(surfaceProvider)) return; + Preview streamPreview = mBoundStreamPreviews.remove(surfaceProvider); + if (streamPreview != null && mCameraProvider != null) { + try { + mCameraProvider.unbind(streamPreview); + mBoundUseCases.remove(streamPreview); + mState = State.OPEN; + publishSnapshot(); + } catch (RuntimeException error) { + Log.w(TAG, "Unable to unbind the CameraX stream Preview", error); + reconcileUseCases(false); + return; + } + } + if (mSurfaceProviders.isEmpty() && isPreviewStabilizationEnabled() + && mOpenRequested && !mPaused && mVideoRecording == null) { + long generation = mGeneration; + mMainHandler.postDelayed(() -> { + if (generation == mGeneration && mSurfaceProviders.isEmpty() + && mOpenRequested && !mPaused && mVideoRecording == null) { + reconcileUseCases(false); + } + }, STREAM_RECONFIGURE_DELAY_MILLIS); + } + }); + } + + @Override public void onLayoutChanged() { + runOnMainThread(() -> { + applyPreviewTransform(); + if (mPreview != null) mPreview.setTargetRotation(getTargetRotation()); + if (mImageCapture != null) mImageCapture.setTargetRotation(getTargetRotation()); + if (mImageAnalysis != null) mImageAnalysis.setTargetRotation(getTargetRotation()); + if (mVideoCapture != null) mVideoCapture.setTargetRotation(getTargetRotation()); + int width = getWidth(); + int height = getHeight(); + if (width <= 0 || height <= 0 || (width == mLastWidth && height == mLastHeight)) return; + mLastWidth = width; + mLastHeight = height; + if (mOpenRequested && !mPaused && mVideoRecording == null) reconcileUseCases(true); + }); + } + + private void applyPreviewTransform() { + Size resolution = mPreviewResolution; + SurfaceRequest.TransformationInfo information = mTransformationInfo; + if (resolution == null || information == null) return; + setTransform(CameraXMath.createTextureTransform( + resolution, information.getCropRect(), information.getRotationDegrees(), + information.isMirroring(), information.hasCameraTransform(), + getSensorOrientation(), getWidth(), getHeight())); + } + + /** Returns whether an atomic CameraX bind is active; used only by device validation. */ + boolean isCameraBoundForTesting() { + return mActiveCamera != null && !mBoundUseCases.isEmpty(); + } - setTransform(matrix); + private void runOnMainThread(@NonNull Runnable action) { + if (Looper.myLooper() == Looper.getMainLooper()) action.run(); + else mMainHandler.post(action); } -} +} \ No newline at end of file From d18c258d752939f892b2eb4abce87d9a200e50cc Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 01:18:46 -0500 Subject: [PATCH 04/10] Correct Exif, and keep VideoView off the main thread * fix: make Exif thread-safe, spec-correct, and able to turn left Three things wrong with the metadata every picture carries. The date formatters were shared mutable SimpleDateFormats, which is a data race in any app that writes two pictures at once. Sub-second timestamps were neither zero-padded on the way out nor scaled by digit count on the way in, so a value this library wrote and anything else read back was wrong by up to a factor of a hundred. One entry in the anticlockwise orientation table was wrong: a left turn from 270 degrees gave 90 instead of 180. So a left turn did not undo a right turn and four left turns did not come back to where they started - only for an image already at 270, which is one lens on a device held one particular way, and which is how a camera ships saving upside-down pictures on one phone. GPS speed and altitude were written as a decimal over a denominator of one. Both halves of an EXIF rational are integers, so a reader has to truncate that numerator: 48.28 km/h came back as 48, in a field whose only purpose is to be read back. * perf: keep VideoView off the main thread, and stop it when it is gone Preparing a video read the container and configured the decoder on the thread drawing the UI, and both block for as long as the file takes to parse. The metadata is read on a worker now and the player prepares asynchronously, with a generation counter so a video that was replaced while it was being read is discarded rather than drawn over the one that replaced it. Detaching only shut that worker down. What stopped playback and released the decoder was the SurfaceTexture being destroyed, which on a device happens on the way out - but that is a callback from the platform about a texture, not a statement about this view, and a detach that does not destroy the texture leaves a decoder running and audio playing from a view nobody can see. The streaming parameters are sized rather than guessed, and a stream can cap its resolution below the preview: a link that cannot carry the preview has to ask for less before the frames exist, because re-encoding afterwards costs more than the link saves. Co-Authored-By: Claude Opus 5 --- .../java/com/xlythe/view/camera/Exif.java | 134 +++++-- .../com/xlythe/view/camera/VideoStream.java | 165 +++++--- .../com/xlythe/view/camera/VideoView.java | 371 ++++++++++++++---- 3 files changed, 495 insertions(+), 175 deletions(-) diff --git a/camera-view/src/main/java/com/xlythe/view/camera/Exif.java b/camera-view/src/main/java/com/xlythe/view/camera/Exif.java index 04d93db..51096a0 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/Exif.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/Exif.java @@ -21,9 +21,27 @@ public class Exif { private static final String TAG = Exif.class.getSimpleName(); - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy:MM:dd", Locale.ENGLISH); - private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH); - private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.ENGLISH); + // SimpleDateFormat keeps mutable parsing state, so a shared instance cannot be used from more + // than one thread. Pictures are saved on AsyncTask's thread pool, so two captures finishing + // together were formatting and parsing through the same objects: the usual result is a + // corrupted timestamp, and the unlucky one is an exception thrown from inside the formatter. + private static final ThreadLocal DATE_FORMAT = formatter("yyyy:MM:dd"); + private static final ThreadLocal TIME_FORMAT = formatter("HH:mm:ss"); + private static final ThreadLocal DATETIME_FORMAT = + formatter("yyyy:MM:dd HH:mm:ss"); + + /** One formatter per thread, built lazily. */ + private static ThreadLocal formatter(String pattern) { + return new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + return new SimpleDateFormat(pattern, Locale.ENGLISH); + } + }; + } + + /** Thousandths, which is finer than any GPS reports and well inside a rational's range. */ + private static final long RATIONAL_SCALE = 1000; private static final String KILOMETERS_PER_HOUR = "K"; private static final String MILES_PER_HOUR = "M"; @@ -352,10 +370,10 @@ private void attachLastModifiedTimestamp() { mExifInterface.setAttribute(ExifInterface.TAG_DATETIME, datetime); try { - String subsec = Long.toString(now - convertFromExifDateTime(datetime).getTime()); - mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME, subsec); + long millis = now - convertFromExifDateTime(datetime).getTime(); + mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME, formatSubSecond(millis)); } catch (ParseException e) { - e.printStackTrace(); + Log.w(TAG, "Unable to record the sub-second timestamp", e); } } @@ -368,20 +386,49 @@ public long getLastModifiedTimestamp() { return -1; } - String subSecs = mExifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME); - if (subSecs != null) { - try { - long sub = Long.parseLong(subSecs); - while (sub > 1000) { - sub /= 10; - } - timestamp += sub; - } catch (NumberFormatException e) { - e.printStackTrace(); + return timestamp + + parseSubSecond(mExifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME)); + } + + /** + * Writes a sub-second count as EXIF expects it. + * + *

SubSecTime is the digits after the decimal point, so 50 milliseconds is "050" and not + * "50", which any other reader would take for half a second.

+ */ + static String formatSubSecond(long millis) { + long clamped = Math.max(0, Math.min(millis, 999)); + return String.format(Locale.ENGLISH, "%03d", clamped); + } + + /** + * Reads an EXIF sub-second string as milliseconds. + * + *

The digit count sets the scale, because the value is a fraction of a second rather than + * a count of anything: "5" is half a second, "05" is fifty milliseconds, and "005" is five. + * Treating the digits as milliseconds, as this used to, under-read every value with fewer + * than three digits by a factor of ten or a hundred.

+ */ + static long parseSubSecond(@Nullable String subSeconds) { + if (subSeconds == null) { + return 0; + } + StringBuilder digits = new StringBuilder(); + for (int i = 0; i < subSeconds.length() && digits.length() < 3; i++) { + char character = subSeconds.charAt(i); + if (character < '0' || character > '9') { + break; } + digits.append(character); } - - return timestamp; + if (digits.length() == 0) { + return 0; + } + long value = Long.parseLong(digits.toString()); + for (int i = digits.length(); i < 3; i++) { + value *= 10; + } + return value; } /** @@ -393,20 +440,8 @@ public long getTimestamp() { return -1; } - String subSecs = mExifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL); - if (subSecs != null) { - try { - long sub = Long.parseLong(subSecs); - while (sub > 1000) { - sub /= 10; - } - timestamp += sub; - } catch (NumberFormatException e) { - // Ignored - } - } - - return timestamp; + return timestamp + parseSubSecond( + mExifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL)); } /** @@ -495,7 +530,7 @@ public void rotate(int degrees) { orientation = ExifInterface.ORIENTATION_FLIP_HORIZONTAL; break; case ExifInterface.ORIENTATION_ROTATE_270: - orientation = ExifInterface.ORIENTATION_ROTATE_90; + orientation = ExifInterface.ORIENTATION_ROTATE_180; break; case ExifInterface.ORIENTATION_NORMAL: // Fall-through @@ -630,11 +665,11 @@ public void attachTimestamp() { mExifInterface.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, datetime); try { - String subsec = Long.toString(now - convertFromExifDateTime(datetime).getTime()); + String subsec = formatSubSecond(now - convertFromExifDateTime(datetime).getTime()); mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, subsec); mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, subsec); } catch (ParseException e) { - e.printStackTrace(); + Log.w(TAG, "Unable to record the sub-second timestamp", e); } mRemoveTimestamp = false; @@ -661,11 +696,13 @@ public void attachLocation(Location location) { mExifInterface.setLatLong(location.getLatitude(), location.getLongitude()); if (location.hasAltitude()) { mExifInterface.setAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF, Integer.toString(0)); - mExifInterface.setAttribute(ExifInterface.TAG_GPS_ALTITUDE, Double.toString(location.getAltitude()) + "/1"); + mExifInterface.setAttribute(ExifInterface.TAG_GPS_ALTITUDE, + rational(location.getAltitude())); } if (location.hasSpeed()) { mExifInterface.setAttribute(ExifInterface.TAG_GPS_SPEED_REF, KILOMETERS_PER_HOUR); - mExifInterface.setAttribute(ExifInterface.TAG_GPS_SPEED, Double.toString(Speed.fromMetersPerSecond(location.getSpeed()).toKilometersPerHour()) + "/1"); + mExifInterface.setAttribute(ExifInterface.TAG_GPS_SPEED, rational( + Speed.fromMetersPerSecond(location.getSpeed()).toKilometersPerHour())); } mExifInterface.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, convertToExifDate(location.getTime())); mExifInterface.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, convertToExifTime(location.getTime())); @@ -726,28 +763,39 @@ private long parseTimestamp(@Nullable String datetime) { } } + /** + * A decimal as the rational EXIF stores. + * + *

Both halves of an EXIF rational are integers, so writing the decimal itself over a + * denominator of one - which is what this used to do - leaves a numerator the reader has to + * truncate. A speed of 48.28 km/h came back as 48, and an altitude of 5.7m as 5.

+ */ + private static String rational(double value) { + return Math.round(value * RATIONAL_SCALE) + "/" + RATIONAL_SCALE; + } + private static String convertToExifDateTime(long timestamp) { - return DATETIME_FORMAT.format(new Date(timestamp)); + return DATETIME_FORMAT.get().format(new Date(timestamp)); } private static Date convertFromExifDateTime(String dateTime) throws ParseException { - return DATETIME_FORMAT.parse(dateTime); + return DATETIME_FORMAT.get().parse(dateTime); } private static String convertToExifDate(long timestamp) { - return DATE_FORMAT.format(new Date(timestamp)); + return DATE_FORMAT.get().format(new Date(timestamp)); } private static Date convertFromExifDate(String date) throws ParseException { - return DATE_FORMAT.parse(date); + return DATE_FORMAT.get().parse(date); } private static String convertToExifTime(long timestamp) { - return TIME_FORMAT.format(new Date(timestamp)); + return TIME_FORMAT.get().format(new Date(timestamp)); } private static Date convertFromExifTime(String time) throws ParseException { - return TIME_FORMAT.parse(time); + return TIME_FORMAT.get().parse(time); } private static class Speed { diff --git a/camera-view/src/main/java/com/xlythe/view/camera/VideoStream.java b/camera-view/src/main/java/com/xlythe/view/camera/VideoStream.java index 5d70c1a..3d59b4f 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/VideoStream.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/VideoStream.java @@ -3,6 +3,7 @@ import android.Manifest; import android.annotation.SuppressLint; import android.util.Log; +import android.util.Size; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -18,11 +19,29 @@ import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; @RequiresApi(18) public class VideoStream implements Closeable { private static final String TAG = VideoStream.class.getSimpleName(); + // A PipedInputStream defaults to a 1024 byte buffer, which is smaller than a single encoded + // key frame. The writer then blocks mid-frame waiting on the reader for every frame, which + // stalls the encoder drain loop instead of letting the lossy path shed frames. Size the pipes + // to hold several frames, and let the lossy stream start dropping well before they fill. + /** Buffer for the encoded video pipe. */ + private static final int VIDEO_PIPE_BYTES = 1024 * 1024; + /** Backlog tolerated on the video pipe before droppable frames are discarded. */ + private static final int VIDEO_MAX_BUFFERED_BYTES = 256 * 1024; + /** Buffer for the PCM audio pipe, whose chunks are far smaller than a video frame. */ + private static final int AUDIO_PIPE_BYTES = 64 * 1024; + /** Backlog tolerated on the audio pipe before chunks are discarded. */ + private static final int AUDIO_MAX_BUFFERED_BYTES = 16 * 1024; + + /** Ensures recorder and input resources are closed exactly once. */ + private final AtomicBoolean mClosed = new AtomicBoolean(); + /** Determines if this is encoding or decoding a video stream. */ private final InputType mInputType; @@ -45,33 +64,26 @@ public class VideoStream implements Closeable { private VideoStream(ICameraModule cameraModule, Params params) { mInputType = InputType.CAMERA_MODULE; - if (params.isAudioEnabled()) { - AudioRecorder audioRecorder; - PipedInputStream audioInputStream; - try { - audioInputStream = new PipedInputStream(); - audioRecorder = new AudioRecorder(params.isLossy() ? new LossyPipedOutputStream(audioInputStream) : new PipedOutputStream(audioInputStream)); + AudioRecorder audioRecorder = null; + PipedInputStream audioInputStream = null; + VideoRecorder videoRecorder = null; + PipedInputStream videoInputStream = null; + try { + if (params.isAudioEnabled()) { + audioInputStream = new PipedInputStream(AUDIO_PIPE_BYTES); + audioRecorder = new AudioRecorder(params.isLossy() + ? new LossyPipedOutputStream(audioInputStream, AUDIO_MAX_BUFFERED_BYTES) + : new PipedOutputStream(audioInputStream)); audioRecorder.start(); - } catch (IOException e) { - audioRecorder = null; - audioInputStream = null; } - mAudioRecorder = audioRecorder; - mAudioInputStream = audioInputStream; - } else { - mAudioRecorder = null; - mAudioInputStream = null; - } - - if (params.isVideoEnabled()) { - VideoRecorder videoRecorder; - PipedInputStream videoInputStream; - try { - videoInputStream = new PipedInputStream(); + if (params.isVideoEnabled()) { + videoInputStream = new PipedInputStream(VIDEO_PIPE_BYTES); videoRecorder = new VideoRecorder( cameraModule.getCanvas(), - params.isLossy() ? new LossyPipedOutputStream(videoInputStream) : new PipedOutputStream(videoInputStream)); + params.isLossy() + ? new LossyPipedOutputStream(videoInputStream, VIDEO_MAX_BUFFERED_BYTES) + : new PipedOutputStream(videoInputStream)); if (params.getBitRate() != 0) { videoRecorder.setBitRate(params.getBitRate()); } @@ -81,20 +93,26 @@ private VideoStream(ICameraModule cameraModule, Params params) { if (params.getIFrameInterval() != 0) { videoRecorder.setIFrameInterval(params.getIFrameInterval()); } + videoRecorder.setMaxSize(params.getMaxSize()); videoRecorder.start(); - } catch (IOException e) { - videoRecorder = null; - videoInputStream = null; } - - mVideoRecorder = videoRecorder; - mVideoInputStream = videoInputStream; - } else { - mVideoRecorder = null; - mVideoInputStream = null; + } catch (IOException | RuntimeException e) { + if (audioRecorder != null) { + audioRecorder.stop(); + } + if (videoRecorder != null) { + videoRecorder.stop(); + } + closeQuietly(audioInputStream); + closeQuietly(videoInputStream); + throw new IllegalStateException("Failed to create camera stream", e); } - } + mAudioRecorder = audioRecorder; + mAudioInputStream = audioInputStream; + mVideoRecorder = videoRecorder; + mVideoInputStream = videoInputStream; + } private VideoStream(@Nullable InputStream audioStream, @Nullable InputStream videoStream) { mInputType = InputType.INPUT_STREAM; @@ -108,32 +126,37 @@ private VideoStream(@Nullable InputStream audioStream, @Override public void close() { - if (mAudioRecorder != null) { - mAudioRecorder.stop(); + if (!mClosed.compareAndSet(false, true)) { + return; } - if (mVideoRecorder != null) { - mVideoRecorder.stop(); - } - if (mAudioInputStream != null) { - try { - mAudioInputStream.close(); - } catch (IOException e) { - // ignored + try { + if (mAudioRecorder != null) { + mAudioRecorder.stop(); } + } catch (RuntimeException e) { + Log.e(TAG, "Failed to stop audio stream", e); } - if (mVideoInputStream != null) { - try { - mVideoInputStream.close(); - } catch (IOException e) { - // ignored + try { + if (mVideoRecorder != null) { + mVideoRecorder.stop(); } + } catch (RuntimeException e) { + Log.e(TAG, "Failed to stop video stream", e); } + closeQuietly(mAudioInputStream); + closeQuietly(mVideoInputStream); Log.d(TAG, "VideoStream closed"); } - @Override - protected void finalize() { - close(); + private static void closeQuietly(@Nullable InputStream inputStream) { + if (inputStream == null) { + return; + } + try { + inputStream.close(); + } catch (IOException e) { + Log.w(TAG, "Failed to close stream input", e); + } } public boolean hasAudio() { @@ -180,26 +203,26 @@ public static class Builder { @Nullable private InputStream mVideoStream; Builder setParams(Params params) { - mParams = params; + mParams = Objects.requireNonNull(params, "Stream params cannot be null"); return this; } @RequiresPermission(Manifest.permission.RECORD_AUDIO) Builder attach(ICameraModule cameraModule) { setInputType(InputType.CAMERA_MODULE); - mCameraModule = cameraModule; + mCameraModule = Objects.requireNonNull(cameraModule, "Camera module cannot be null"); return this; } public Builder withAudioStream(InputStream audioStream) { setInputType(InputType.INPUT_STREAM); - mAudioStream = audioStream; + mAudioStream = Objects.requireNonNull(audioStream, "Audio stream cannot be null"); return this; } public Builder withVideoStream(InputStream videoStream) { setInputType(InputType.INPUT_STREAM); - mVideoStream = videoStream; + mVideoStream = Objects.requireNonNull(videoStream, "Video stream cannot be null"); return this; } @@ -236,19 +259,22 @@ public static class Params { private final int mFrameRate; private final int mIFrameInterval; private final boolean mIsLossy; + @Nullable private final Size mMaxSize; private Params(boolean audioEnabled, boolean videoEnabled, int bitRate, int frameRate, int iframeInterval, - boolean isLossy) { + boolean isLossy, + @Nullable Size maxSize) { this.mAudioEnabled = audioEnabled; this.mVideoEnabled = videoEnabled; this.mBitRate = bitRate; this.mFrameRate = frameRate; this.mIFrameInterval = iframeInterval; this.mIsLossy = isLossy; + this.mMaxSize = maxSize; } public boolean isAudioEnabled() { @@ -275,6 +301,12 @@ public boolean isLossy() { return mIsLossy; } + /** The resolution cap for the video stream, or null to follow the preview. */ + @Nullable + public Size getMaxSize() { + return mMaxSize; + } + public static class Builder { private boolean mAudioEnabled = true; private boolean mVideoEnabled = true; @@ -282,6 +314,7 @@ public static class Builder { private int mFrameRate; private int mIFrameInterval; private boolean mIsLossy = true; + @Nullable private Size mMaxSize; public Builder setAudioEnabled(boolean audioEnabled) { this.mAudioEnabled = audioEnabled; @@ -313,12 +346,32 @@ public Builder setIsLossy(boolean isLossy) { return this; } + /** + * Caps the resolution of the video stream, independent of the preview on screen. + * + *

Set this when the stream leaves the device over a link that cannot carry the + * preview's resolution, such as a watch reached over Bluetooth. The active camera picks + * the closest size it supports within the bound, so the stream is usually smaller than + * asked for and never larger. Leave it unset to follow the preview.

+ */ + public Builder setMaxSize(@Nullable Size maxSize) { + mMaxSize = maxSize; + return this; + } + public Params build() { if (!mAudioEnabled && !mVideoEnabled) { throw new IllegalStateException("Cannot create a stream with both audio and video disabled"); } + if (mBitRate < 0 || mFrameRate < 0 || mIFrameInterval < 0) { + throw new IllegalArgumentException("Stream encoding values cannot be negative"); + } + if (mMaxSize != null && (mMaxSize.getWidth() <= 0 || mMaxSize.getHeight() <= 0)) { + throw new IllegalArgumentException("Stream dimensions must be positive: " + mMaxSize); + } - return new Params(mAudioEnabled, mVideoEnabled, mBitRate, mFrameRate, mIFrameInterval, mIsLossy); + return new Params(mAudioEnabled, mVideoEnabled, mBitRate, mFrameRate, mIFrameInterval, + mIsLossy, mMaxSize); } } } diff --git a/camera-view/src/main/java/com/xlythe/view/camera/VideoView.java b/camera-view/src/main/java/com/xlythe/view/camera/VideoView.java index 25cd393..344a8c2 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/VideoView.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/VideoView.java @@ -6,8 +6,8 @@ import android.content.res.TypedArray; import android.graphics.Matrix; import android.graphics.SurfaceTexture; -import android.media.AudioManager; import android.media.MediaMetadataRetriever; +import android.media.AudioAttributes; import android.media.MediaPlayer; import android.os.Build; import android.os.Handler; @@ -22,12 +22,14 @@ import android.widget.FrameLayout; import java.io.File; -import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import androidx.annotation.Nullable; +import androidx.annotation.UiThread; import androidx.annotation.RequiresApi; import com.xlythe.view.camera.stream.AudioPlayer; @@ -39,12 +41,17 @@ public class VideoView extends FrameLayout implements TextureView.SurfaceTexture // ---------- General ---------- + /** Delivers player callbacks and view mutations on the UI thread. */ + private final Handler mMainHandler = new Handler(Looper.getMainLooper()); + // The view we draw the video on to private TextureView mTextureView; // Whether to play a file or a stream private InputType mInputType = InputType.UNKNOWN; // If true, the texture view is ready to be drawn on private boolean mIsAvailable; + /** True while an already-cleaned texture is being replaced with a fresh preview surface. */ + private boolean mIsReplacingTextureView; // If true, we should be playing private boolean mIsPlaying; // An optional listener for when videos are paused/played @@ -70,6 +77,20 @@ public class VideoView extends FrameLayout implements TextureView.SurfaceTexture @Nullable private MediaPlayer.OnCompletionListener mOnCompletionListener; // If true, the video should loop private boolean mIsLooping = false; + /** + * Reads container metadata off the main thread. + * + *

Parsing a container blocks for as long as it takes to read its headers, which is long + * enough to drop frames and, on a large or damaged file, long enough to be an ANR.

+ */ + @Nullable private ExecutorService mPrepareExecutor; + /** + * Invalidates work from an earlier prepare, so metadata for a file that has since been + * replaced cannot configure the player. + */ + private int mPrepareGeneration; + /** Held open until the player is prepared, because MediaPlayer reads from it until then. */ + @Nullable private FileInputStream mPreparingInputStream; // ---------- Stream ---------- @@ -81,6 +102,10 @@ public class VideoView extends FrameLayout implements TextureView.SurfaceTexture @Nullable private AudioPlayer mAudioPlayer; // Plays the video half of the VideoStream @Nullable private VideoPlayer mVideoPlayer; + /** True after the prepared stream audio channel reaches end-of-stream. */ + private boolean mAudioStreamEnded; + /** True after the prepared stream video channel reaches end-of-stream. */ + private boolean mVideoStreamEnded; public VideoView(Context context) { this(context, null); @@ -145,22 +170,19 @@ public File getFile() { } public void setFile(@Nullable File file) { - if (Objects.equals(file, mFile) && mInputType.equals(InputType.FILE)) { + if (Objects.equals(file, mFile) && mInputType == InputType.FILE) { return; } if (DEBUG) Log.d(TAG, "File set to " + file); - this.mFile = file; - if (mVideoStream != null) { - if (Build.VERSION.SDK_INT <= 18) { - throw new RuntimeException("API not available"); - } - if (DEBUG) Log.d(TAG, "Stream replaced with file"); - mVideoStream.close(); - mVideoStream = null; - mPreparedVideoStream = null; + if (mInputType == InputType.STREAM) { + releaseStreamPlayback(true); + } else { + releaseMediaPlayer(); } - this.mInputType = InputType.FILE; + mFile = file; + mVideoStream = null; + mInputType = InputType.FILE; createTextureView(); if (file != null && mIsAvailable) { prepare(); @@ -180,21 +202,22 @@ public VideoStream getStream() { @RequiresApi(18) public void setStream(VideoStream videoStream) { - if (videoStream == null) { - throw new NullPointerException("VideoStream cannot be null"); - } - if (Objects.equals(videoStream, mVideoStream) && mInputType.equals(InputType.STREAM)) { + Objects.requireNonNull(videoStream, "VideoStream cannot be null"); + if (videoStream == mVideoStream && mInputType == InputType.STREAM) { return; } if (DEBUG) Log.d(TAG, "Stream set"); - this.mVideoStream = videoStream; - this.mFile = null; - this.mInputType = InputType.STREAM; - if (DEBUG) Log.d(TAG, "Preparing TextureView"); + if (mInputType == InputType.STREAM) { + releaseStreamPlayback(true); + } else { + releaseMediaPlayer(); + } + mVideoStream = videoStream; + mFile = null; + mInputType = InputType.STREAM; createTextureView(); - if (videoStream != null && mIsAvailable) { - if (DEBUG) Log.d(TAG, "Preparing stream"); + if (mIsAvailable) { prepare(); } if (DEBUG) Log.d(TAG, "Stream ready"); @@ -222,26 +245,19 @@ public void onSurfaceTextureUpdated(SurfaceTexture texture) {} public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) { if (DEBUG) Log.d(TAG, "Texture destroyed"); mIsAvailable = false; + if (mIsReplacingTextureView) { + return true; + } setPlayingState(false); switch (mInputType) { case FILE: - ensureMediaPlayer(); - if (mMediaPlayer != null) { - mMediaPlayer.release(); - mMediaPlayer = null; - } + releaseMediaPlayer(); break; case STREAM: - if (mVideoStream != null && mPreparedVideoStream == mVideoStream) { - if (Build.VERSION.SDK_INT < 18) { - throw new RuntimeException("API not available"); - } - if (DEBUG) Log.d(TAG, "Stream destroyed"); - mVideoStream.close(); - mVideoStream = null; - mPreparedVideoStream = null; - } + releaseStreamPlayback(true); + break; + case UNKNOWN: break; } @@ -291,49 +307,146 @@ protected void prepare() { protected void prepareFile() { if (DEBUG) Log.d(TAG, "Preparing video"); - ensureMediaPlayer(); + File file = mFile; + SurfaceTexture surfaceTexture = mTextureView == null ? null : mTextureView.getSurfaceTexture(); + if (file == null || surfaceTexture == null) { + Log.w(TAG, "Cannot prepare video without a file and surface"); + return; + } - try { - FileDescriptor fileDescriptor = new FileInputStream(mFile).getFD(); + // Reading the container and preparing the decoder both block for as long as the file + // takes to parse, so neither belongs on the thread drawing the UI. Read the metadata on a + // worker, then configure the player and let it prepare asynchronously. + int generation = ++mPrepareGeneration; + prepareExecutor().execute(() -> { + VideoMetadata metadata = readMetadata(file); + mMainHandler.post(() -> { + if (generation != mPrepareGeneration) { + if (DEBUG) Log.d(TAG, "Discarding metadata for a replaced video"); + return; + } + if (metadata == null) { + setPlayingState(false); + return; + } + startPreparing(file, surfaceTexture, metadata, generation); + }); + }); + } + + /** Container dimensions, already corrected for the rotation recorded in the file. */ + private static final class VideoMetadata { + final int width; + final int height; - MediaMetadataRetriever retriever = new MediaMetadataRetriever(); - retriever.setDataSource(fileDescriptor); + VideoMetadata(int width, int height) { + this.width = width; + this.height = height; + } + } + + @Nullable + private VideoMetadata readMetadata(File file) { + MediaMetadataRetriever retriever = new MediaMetadataRetriever(); + try (FileInputStream inputStream = new FileInputStream(file)) { + retriever.setDataSource(inputStream.getFD()); int width = extractAsInt(retriever, MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); int height = extractAsInt(retriever, MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); - int rotation = Build.VERSION.SDK_INT < 17 ? 0 : extractAsInt(retriever, MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); - retriever.release(); - if (DEBUG) Log.d(TAG, String.format("Video metadata: width=%d, height=%d, rotation=%d", width, height, rotation)); - - if (rotation == 90 || rotation == 270) { - int temp = width; - width = height; - height = temp; + int rotation = extractAsInt(retriever, MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); + if (DEBUG) Log.d(TAG, String.format( + "Video metadata: width=%d, height=%d, rotation=%d", width, height, rotation)); + return rotation == 90 || rotation == 270 + ? new VideoMetadata(height, width) + : new VideoMetadata(width, height); + } catch (IOException | RuntimeException e) { + Log.e(TAG, "Failed to read video metadata from " + file, e); + return null; + } finally { + try { + retriever.release(); + } catch (IOException e) { + Log.w(TAG, "Failed to release video metadata retriever", e); } - transformPreview(width, height); + } + } - Surface surface = new Surface(mTextureView.getSurfaceTexture()); + @UiThread + private void startPreparing(File file, SurfaceTexture surfaceTexture, + VideoMetadata metadata, int generation) { + ensureMediaPlayer(); + transformPreview(metadata.width, metadata.height); + closePreparingInputStream(); + Surface surface = new Surface(surfaceTexture); + try { try { Objects.requireNonNull(mMediaPlayer).stop(); - } catch (IllegalStateException e) { - if (DEBUG) e.printStackTrace(); + } catch (IllegalStateException ignored) { + // The newly created player has not entered the started state yet. } + mMediaPlayer.reset(); - try { - mMediaPlayer.reset(); - } catch (IllegalStateException e) { - if (DEBUG) e.printStackTrace(); - } + // MediaPlayer reads from the descriptor until it finishes preparing, so unlike the + // synchronous path this stream cannot be closed when the call returns. + FileInputStream inputStream = new FileInputStream(file); + mPreparingInputStream = inputStream; - mMediaPlayer.setDataSource(fileDescriptor); + mMediaPlayer.setDataSource(inputStream.getFD()); mMediaPlayer.setSurface(surface); - mMediaPlayer.prepare(); - mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); + mMediaPlayer.setAudioAttributes(new AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_MOVIE) + .setUsage(AudioAttributes.USAGE_MEDIA) + .build()); + mMediaPlayer.setOnPreparedListener(mediaPlayer -> { + mediaPlayer.setOnPreparedListener(null); + closePreparingInputStream(); + if (generation != mPrepareGeneration) { + return; + } + seekToFirstFrame(); + if (mIsPlaying) { + playFile(); + } + }); + mMediaPlayer.setOnErrorListener((mediaPlayer, what, extra) -> { + Log.e(TAG, "Failed to prepare video file " + file + + " (what=" + what + ", extra=" + extra + ")"); + closePreparingInputStream(); + setPlayingState(false); + return true; + }); + mMediaPlayer.prepareAsync(); } catch (IllegalStateException | IOException e) { - e.printStackTrace(); + Log.e(TAG, "Failed to prepare video file " + file, e); + closePreparingInputStream(); + setPlayingState(false); + } finally { + surface.release(); + } + } + + private void closePreparingInputStream() { + FileInputStream inputStream = mPreparingInputStream; + mPreparingInputStream = null; + if (inputStream == null) { + return; } + try { + inputStream.close(); + } catch (IOException e) { + Log.w(TAG, "Failed to close the video input stream", e); + } + } - seekToFirstFrame(); + private ExecutorService prepareExecutor() { + if (mPrepareExecutor == null) { + mPrepareExecutor = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(runnable, "VideoView-Prepare"); + thread.setDaemon(true); + return thread; + }); + } + return mPrepareExecutor; } protected void prepareStream() { @@ -346,22 +459,25 @@ protected void prepareStream() { throw new RuntimeException("API not available"); } + mAudioStreamEnded = !videoStream.hasAudio(); + mVideoStreamEnded = !videoStream.hasVideo(); if (videoStream.hasAudio()) { mAudioPlayer = new AudioPlayer(videoStream.getAudioInputStream()); - mAudioPlayer.setStreamEndListener(() -> new Handler(Looper.getMainLooper()).post(() -> { - setPlayingState(false); - videoStream.close(); - })); + mAudioPlayer.setStreamEndListener(() -> mMainHandler.post(() -> + onStreamEnded(videoStream, true))); } if (videoStream.hasVideo()) { @SuppressLint("Recycle") Surface surface = new Surface(mTextureView.getSurfaceTexture()); mVideoPlayer = new VideoPlayer(surface, videoStream.getVideoInputStream()); - mVideoPlayer.setStreamEndListener(() -> new Handler(Looper.getMainLooper()).post(() -> { - setPlayingState(false); - videoStream.close(); - })); - mVideoPlayer.setOnMetadataAvailableListener((width, height, orientation, flipped) -> new Handler(Looper.getMainLooper()).post(() -> transformPreview(width, height, orientation, flipped))); + mVideoPlayer.setStreamEndListener(() -> mMainHandler.post(() -> + onStreamEnded(videoStream, false))); + mVideoPlayer.setOnMetadataAvailableListener((width, height, orientation, flipped) -> + mMainHandler.post(() -> { + if (mPreparedVideoStream == videoStream) { + transformPreview(width, height, orientation, flipped); + } + })); } mPreparedVideoStream = videoStream; @@ -370,12 +486,101 @@ protected void prepareStream() { } } + private void onStreamEnded(VideoStream videoStream, boolean audio) { + if (mPreparedVideoStream != videoStream) { + videoStream.close(); + return; + } + if (audio) { + mAudioStreamEnded = true; + } else { + mVideoStreamEnded = true; + } + if (mAudioStreamEnded && mVideoStreamEnded) { + setPlayingState(false); + releaseStreamPlayback(true); + } + } + + private void releaseMediaPlayer() { + // Invalidate any prepare still in flight, so its metadata cannot configure a player that + // has gone away, and drop the descriptor it was holding open. + mPrepareGeneration++; + closePreparingInputStream(); + + MediaPlayer mediaPlayer = mMediaPlayer; + mMediaPlayer = null; + if (mediaPlayer != null) { + mediaPlayer.release(); + } + } + + @Override + protected void onDetachedFromWindow() { + ExecutorService executor = mPrepareExecutor; + mPrepareExecutor = null; + if (executor != null) { + executor.shutdownNow(); + } + + // A view that is gone must not still be decoding. On a device the SurfaceTexture is + // destroyed on the way out and that callback releases everything, but it is a callback + // from the platform about a texture, not a statement about this view: a detach that does + // not destroy the texture would leave a decoder running and audio playing from a view + // nobody can see. Releasing here says it directly. The file is kept, so reattaching + // prepares again. + setPlayingState(false); + switch (mInputType) { + case FILE: + releaseMediaPlayer(); + break; + case STREAM: + releaseStreamPlayback(true); + break; + case UNKNOWN: + break; + } + super.onDetachedFromWindow(); + } + + @RequiresApi(18) + private void releaseStreamPlayback(boolean closeStream) { + AudioPlayer audioPlayer = mAudioPlayer; + VideoPlayer videoPlayer = mVideoPlayer; + VideoStream preparedStream = mPreparedVideoStream; + VideoStream currentStream = mVideoStream; + mAudioPlayer = null; + mVideoPlayer = null; + mPreparedVideoStream = null; + if (audioPlayer != null) { + audioPlayer.stop(); + } + if (videoPlayer != null) { + videoPlayer.stop(); + } + if (closeStream) { + if (preparedStream != null) { + preparedStream.close(); + } + if (currentStream != null && currentStream != preparedStream) { + currentStream.close(); + } + mVideoStream = null; + } + setPlayingState(false); + } + private int extractAsInt(MediaMetadataRetriever retriever, int key) { String metadata = retriever.extractMetadata(key); if (metadata == null) { return 0; } - return Integer.parseInt(metadata); + try { + return Integer.parseInt(metadata); + } catch (NumberFormatException e) { + Log.w(TAG, "Invalid numeric video metadata: " + metadata, e); + return 0; + } } public void seekToFirstFrame() { @@ -518,7 +723,8 @@ public boolean isLooping() { public void setVolume(float volume) { ensureMediaPlayer(); - Objects.requireNonNull(mMediaPlayer).setVolume(volume, volume); + float clampedVolume = Math.max(0f, Math.min(volume, 1f)); + Objects.requireNonNull(mMediaPlayer).setVolume(clampedVolume, clampedVolume); } void transformPreview(int videoWidth, int videoHeight) { @@ -529,6 +735,10 @@ void transformPreview(int videoWidth, int videoHeight) { int viewWidth = getWidth(); int viewHeight = getHeight(); + if (videoWidth <= 0 || videoHeight <= 0 || viewWidth <= 0 || viewHeight <= 0 + || mTextureView == null) { + return; + } Matrix matrix = new Matrix(); @@ -574,7 +784,12 @@ private void createTextureView() { // is able to draw to it again. We'd rather clear the TextureView, but since there's no such // way, we destroy it instead. if (mTextureView != null) { - removeView(mTextureView); + mIsReplacingTextureView = true; + try { + removeView(mTextureView); + } finally { + mIsReplacingTextureView = false; + } } mIsAvailable = false; addView(mTextureView = new TextureView(getContext()), 0); @@ -621,6 +836,10 @@ private void transformPreview(int previewWidth, int previewHeight, int cameraOri int viewWidth = getWidth(); int viewHeight = getHeight(); + if (previewWidth <= 0 || previewHeight <= 0 || viewWidth <= 0 || viewHeight <= 0 + || mTextureView == null) { + return; + } int displayOrientation = getDisplayRotation(); if (isMirrored()) { flipped = !flipped; From 5981e48295a61f97d30b57e075bdc0daba71707d Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 01:18:46 -0500 Subject: [PATCH 05/10] Fix the lossy stream and the UI layer * fix: make the lossy stream drop the right frames, and say what it sends A stream that falls behind has to shed something, and it was shedding whatever arrived next. Video is a key frame followed by frames described relative to it, so dropping a key frame takes the rest of its group with it and the picture breaks until the next one - and dropping the codec configuration means the decoder never starts at all. Only delta frames are droppable now, a frame is dropped whole rather than truncated mid-write, and when the reader is hopelessly behind a sync frame is requested so the stream can be rejoined rather than hoarding what it already has. The budget is stated in time, not bytes. How far behind a caller is willing to be is a question about latency, so the backlog is a quarter of a second of whatever the stream is producing, with a floor so a trickle still buffers enough to be worth decoding. Audio was worse: the recorder took the lowest sample rate AudioRecord would give it and the player the lowest AudioTrack would, which are different questions asked of what are often two different devices. When the answers differed the audio played at the wrong speed and pitch, with nothing to indicate why. The recorder writes a short header naming the rate, channels and encoding, and the player configures its track from it; a stream without one is still read as PCM at the player's own guess, so an older recorder keeps working. * fix: stop the UI layer calling stale callbacks and dead views The two wrappers an app actually touches, and the same class of bug in both. Both composables build their view inside a remember and install listeners on it there, so the listeners held whichever lambdas the first composition happened to pass. A caller whose callbacks close over state - which is most callers - kept being called with the stale ones. rememberUpdatedState in both, so the listeners read the latest at the moment they fire, and the camera's state listener is cleared on dispose rather than left pointing at a composition that is gone. The Compose camera can also reject a capture now, which it could confirm but not decline. CameraFragment reached a view it had already released: its state receiver is registered from onAttach and unregistered in onDetach, so it can fire before onViewCreated has resolved the Views and after onDestroyView has let them go, and both windows dereferenced a null CameraView. It also dispatched onCameraClosed itself on top of the one CameraView already sends, so a subclass saw it twice; the lens toggle re-synced itself and read as a tap; the elapsed-time label counted something other than elapsed time; and the confirm and cancel buttons called through to methods that throw when nothing is pending - which they outlive, because a camera that closes clears the pending capture while the buttons are still on screen. Co-Authored-By: Claude Opus 5 --- .../java/com/xlythe/compose/camera/Camera.kt | 91 +- .../java/com/xlythe/compose/camera/Video.kt | 16 +- .../fragment/camera/CameraFragment.java | 1381 +++++++++-------- .../view/camera/stream/AudioPlayer.java | 62 +- .../view/camera/stream/AudioRecorder.java | 38 +- .../view/camera/stream/AudioStreamHeader.java | 136 ++ .../camera/stream/LossyPipedOutputStream.java | 142 +- .../xlythe/view/camera/stream/VideoFrame.java | 11 +- .../view/camera/stream/VideoPlayer.java | 45 +- .../view/camera/stream/VideoRecorder.java | 282 +++- 10 files changed, 1431 insertions(+), 773 deletions(-) create mode 100644 camera-view/src/main/java/com/xlythe/view/camera/stream/AudioStreamHeader.java diff --git a/camera-view/src/main/java/com/xlythe/compose/camera/Camera.kt b/camera-view/src/main/java/com/xlythe/compose/camera/Camera.kt index 8961ad5..8400664 100644 --- a/camera-view/src/main/java/com/xlythe/compose/camera/Camera.kt +++ b/camera-view/src/main/java/com/xlythe/compose/camera/Camera.kt @@ -3,9 +3,11 @@ package com.xlythe.compose.camera import android.Manifest import android.annotation.SuppressLint import android.content.Context +import android.graphics.Point import android.hardware.display.DisplayManager import android.hardware.display.DisplayManager.DisplayListener import android.os.Handler +import android.os.Looper import android.os.Parcelable import android.util.Log import android.util.SparseArray @@ -13,7 +15,9 @@ import androidx.annotation.RequiresPermission import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner @@ -47,13 +51,22 @@ enum class LensFacing { interface CameraController { fun takePicture(file: File) + + /** Records audio alongside the video, so the microphone is needed here and not at Camera. */ + @RequiresPermission(Manifest.permission.RECORD_AUDIO) fun startRecording(file: File) fun stopRecording() fun stream(): VideoStream? fun toggleCamera() fun confirmPicture() fun confirmVideo() - fun enterBarcodeScanner(listener: (List) -> Unit, vararg formats: Int) + + /** Discards a picture awaiting confirmation, deleting its file. */ + fun rejectPicture() + + /** Discards a video awaiting confirmation, deleting its file. */ + fun rejectVideo() + fun enterBarcodeScanner(listener: (List) -> Unit, @Barcode.Format vararg formats: Int) fun exitBarcodeScanner() } @@ -69,6 +82,7 @@ private class CameraControllerImpl( ?: Log.e(TAG, "View not available for takePicture") } + @RequiresPermission(Manifest.permission.RECORD_AUDIO) override fun startRecording(file: File) { getView()?.startRecording(file) ?: Log.e(TAG, "View not available for startRecording") @@ -99,8 +113,18 @@ private class CameraControllerImpl( ?: Log.e(TAG, "View not available for confirmVideo") } - @SuppressLint("MissingPermission") - override fun enterBarcodeScanner(listener: (List) -> Unit, vararg formats: Int) { + override fun rejectPicture() { + getView()?.rejectPicture() + ?: Log.e(TAG, "View not available for rejectPicture") + } + + override fun rejectVideo() { + getView()?.rejectVideo() + ?: Log.e(TAG, "View not available for rejectVideo") + } + + @SuppressLint("MissingPermission", "WrongConstant") + override fun enterBarcodeScanner(listener: (List) -> Unit, @Barcode.Format vararg formats: Int) { if (formats.isNotEmpty()) { val first = formats[0] val rest = if (formats.size > 1) formats.sliceArray(1 until formats.size) else IntArray(0) @@ -121,11 +145,13 @@ private class CameraControllerImpl( /** * A Composable that displays a preview of the camera. * - * **Important:** This composable requires the [Manifest.permission.CAMERA], - * [Manifest.permission.RECORD_AUDIO] , and [Manifest.permission.WRITE_EXTERNAL_STORAGE] permissions - * to be granted *before* it is included in the composition. The underlying view - * will not be opened or functional otherwise. Use conditional rendering based on - * permission status at the call site. + * **Important:** This composable requires [Manifest.permission.CAMERA] to be granted *before* it + * is included in the composition. The underlying view will not be opened or functional otherwise. + * Use conditional rendering based on permission status at the call site. + * + * Showing a preview and taking pictures need nothing else. The microphone is only required by + * [CameraController.startRecording] and [CameraController.stream], which ask for it themselves, + * and outputs are written to the [File] you pass in, so no storage permission is involved. * * @param modifier Modifier for layout. * @param quality The quality for image and video outputs. @@ -140,9 +166,7 @@ private class CameraControllerImpl( * @param controller Exposes the methods {@link CameraController#takePicture(File)}, * * {@link CameraController#startRecording(File)} and {@link CameraController#stopRecording()}. */ -@RequiresPermission( - allOf = [Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE] -) +@RequiresPermission(Manifest.permission.CAMERA) @Composable fun Camera( modifier: Modifier = Modifier, @@ -169,6 +193,19 @@ fun Camera( val context = LocalContext.current val lifecycleOwner = LocalLifecycleOwner.current + // The CameraView below is remembered for the life of the composition, so the listeners + // installed on it capture whichever lambdas the first composition happened to pass. A caller + // whose callbacks close over state would then keep being called with the stale ones. Track + // the latest instead, so the listeners read them at the moment they fire. + val currentOnImageConfirmation by rememberUpdatedState(onImageConfirmation) + val currentOnImageCaptured by rememberUpdatedState(onImageCaptured) + val currentOnImageCaptureFailed by rememberUpdatedState(onImageCaptureFailed) + val currentOnVideoConfirmation by rememberUpdatedState(onVideoConfirmation) + val currentOnVideoCaptured by rememberUpdatedState(onVideoCaptured) + val currentOnVideoCaptureFailed by rememberUpdatedState(onVideoCaptureFailed) + val currentOnCameraOpened by rememberUpdatedState(onCameraOpened) + val currentOnCameraClosed by rememberUpdatedState(onCameraClosed) + // Initialize and then cache our CameraView. val cameraView = remember { object : CameraView(context) { @@ -181,39 +218,39 @@ fun Camera( this.setOnImageCapturedListener(object : CameraView.OnImageCapturedListener { override fun onImageConfirmation() { - onImageConfirmation() + currentOnImageConfirmation() } override fun onImageCaptured(file: File) { - onImageCaptured(file) + currentOnImageCaptured(file) } override fun onFailure() { - onImageCaptureFailed() + currentOnImageCaptureFailed() } }) this.setOnVideoCapturedListener(object : CameraView.OnVideoCapturedListener { override fun onVideoConfirmation() { - onVideoConfirmation() + currentOnVideoConfirmation() } override fun onVideoCaptured(file: File) { - onVideoCaptured(file) + currentOnVideoCaptured(file) } override fun onFailure() { - onVideoCaptureFailed() + currentOnVideoCaptureFailed() } }) this.setOnCameraStateChangedListener(object : CameraView.OnCameraStateChangedListener { override fun onCameraOpened() { - onCameraOpened() + currentOnCameraOpened() } override fun onCameraClosed() { - onCameraClosed() + currentOnCameraClosed() } }) } @@ -264,13 +301,18 @@ fun Camera( return } - val display = displayManager.getDisplay(displayId) - if (lastKnownWidth == display.width && lastKnownHeight == display.height && lastKnownRotation == display.rotation) { + val display = cameraView.display ?: return + val displaySize = Point() + @Suppress("DEPRECATION") + display.getRealSize(displaySize) + val width = displaySize.x + val height = displaySize.y + if (lastKnownWidth == width && lastKnownHeight == height && lastKnownRotation == display.rotation) { return } - lastKnownWidth = display.width - lastKnownHeight = display.height + lastKnownWidth = width + lastKnownHeight = height lastKnownRotation = display.rotation if (cameraView.isOpen) { @@ -279,7 +321,7 @@ fun Camera( } } } - displayManager.registerDisplayListener(displayListener, Handler()) + displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) @@ -293,6 +335,7 @@ fun Camera( } cameraView.setOnImageCapturedListener(null) cameraView.setOnVideoCapturedListener(null) + cameraView.setOnCameraStateChangedListener(null) } } diff --git a/camera-view/src/main/java/com/xlythe/compose/camera/Video.kt b/camera-view/src/main/java/com/xlythe/compose/camera/Video.kt index c9e8a3e..b406017 100644 --- a/camera-view/src/main/java/com/xlythe/compose/camera/Video.kt +++ b/camera-view/src/main/java/com/xlythe/compose/camera/Video.kt @@ -5,7 +5,9 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner @@ -74,18 +76,26 @@ fun Video( val context = LocalContext.current val lifecycleOwner = LocalLifecycleOwner.current + // The VideoView below is remembered for the life of the composition, so the listeners + // installed on it capture whichever lambdas the first composition happened to pass. A caller + // whose callbacks close over state would then keep being called with the stale ones. Track + // the latest instead, so the listeners read them at the moment they fire. + val currentOnCompletion by rememberUpdatedState(onCompletion) + val currentOnPlay by rememberUpdatedState(onPlay) + val currentOnPause by rememberUpdatedState(onPause) + // Initialize and then cache our VideoView. val videoView = remember { VideoView(context).apply { - this.setOnCompletionListener { onCompletion() } + this.setOnCompletionListener { currentOnCompletion() } this.setEventListener(object : VideoView.EventListener { override fun onPlay() { - onPlay() + currentOnPlay() } override fun onPause() { - onPause() + currentOnPause() } }) } diff --git a/camera-view/src/main/java/com/xlythe/fragment/camera/CameraFragment.java b/camera-view/src/main/java/com/xlythe/fragment/camera/CameraFragment.java index 6c4e9e6..a5352f9 100644 --- a/camera-view/src/main/java/com/xlythe/fragment/camera/CameraFragment.java +++ b/camera-view/src/main/java/com/xlythe/fragment/camera/CameraFragment.java @@ -1,657 +1,724 @@ -package com.xlythe.fragment.camera; - -import android.Manifest; -import android.animation.ValueAnimator; -import android.annotation.SuppressLint; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.graphics.Rect; -import android.hardware.display.DisplayManager; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Vibrator; -import android.text.format.DateFormat; -import android.view.Display; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewConfiguration; -import android.view.animation.LinearInterpolator; -import android.widget.CompoundButton; -import android.widget.ProgressBar; -import android.widget.TextView; - -import com.xlythe.view.camera.CameraView; -import com.xlythe.view.camera.PermissionChecker; -import com.xlythe.view.camera.R; - -import java.io.File; -import java.util.Arrays; -import java.util.Date; -import java.util.Formatter; -import java.util.Locale; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.RequiresPermission; -import androidx.core.content.ContextCompat; -import androidx.fragment.app.Fragment; - -public abstract class CameraFragment extends Fragment implements CameraView.OnImageCapturedListener, CameraView.OnVideoCapturedListener, CameraView.OnCameraStateChangedListener { - private static final String[] REQUIRED_PERMISSIONS; - private static final String[] OPTIONAL_PERMISSIONS; - - static { - if (Build.VERSION.SDK_INT >= 34) { - // In U+, READ_MEDIA_IMAGES and READ_MEDIA_VIDEO no longer give access to the file system and the user must manually select files from a system window. - // As this experience is terrible, support for reading previews of images taken is removed. An image that was taken immediately can still be previewed. - REQUIRED_PERMISSIONS = new String[] { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO - }; - OPTIONAL_PERMISSIONS = new String[] { - Manifest.permission.ACCESS_FINE_LOCATION, - Manifest.permission.VIBRATE, - }; - } else if (Build.VERSION.SDK_INT >= 33) { - // In T+, READ_EXTERNAL_STORAGE is removed and replaced with READ_MEDIA_IMAGES and READ_MEDIA_VIDEO - REQUIRED_PERMISSIONS = new String[] { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO - }; - OPTIONAL_PERMISSIONS = new String[] { - Manifest.permission.ACCESS_FINE_LOCATION, - Manifest.permission.VIBRATE, - Manifest.permission.READ_MEDIA_IMAGES, - Manifest.permission.READ_MEDIA_VIDEO - }; - } else if (Build.VERSION.SDK_INT >= 19) { - // In KitKat+, WRITE_EXTERNAL_STORAGE is optional - REQUIRED_PERMISSIONS = new String[] { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO - }; - OPTIONAL_PERMISSIONS = new String[] { - Manifest.permission.WRITE_EXTERNAL_STORAGE, - Manifest.permission.ACCESS_FINE_LOCATION, - Manifest.permission.VIBRATE - }; - } else { - REQUIRED_PERMISSIONS = new String[] { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO, - Manifest.permission.WRITE_EXTERNAL_STORAGE - }; - OPTIONAL_PERMISSIONS = new String[] { - Manifest.permission.ACCESS_FINE_LOCATION, - Manifest.permission.VIBRATE - }; - } - } - - private static final int REQUEST_CODE_PERMISSIONS = 10; - private static final String DESTINATION = "yyyy-MM-dd HH:mm:ss"; - private static final String PHOTO_EXT = ".jpg"; - private static final String VIDEO_EXT = ".mp4"; - - private View mCameraHolder; - - private View mPermissionPrompt; - - private CameraView mCamera; - - private View mPermissionRequest; - - @Nullable - private View mCapture; - - @Nullable - private View mConfirm; - - @Nullable - private TextView mDuration; - - @Nullable - private ProgressBar mProgress; - - @Nullable - private CompoundButton mToggle; - - @Nullable - private View mCancel; - - private final ProgressBarAnimator mAnimator = new ProgressBarAnimator(); - - private DisplayManager.DisplayListener mDisplayListener; - - private final BroadcastReceiver mStateChangedReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - invalidate(); - } - }; - - @SuppressWarnings({"MissingPermission"}) - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - if (requestCode == REQUEST_CODE_PERMISSIONS) { - if (PermissionChecker.hasPermissions(getContext(), REQUIRED_PERMISSIONS)) { - showCamera(); - } else { - showPermissionPrompt(); - } - } - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - - if (Build.VERSION.SDK_INT >= 17) { - DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); - mDisplayListener = new DisplayManager.DisplayListener() { - int lastKnownWidth = -1; - int lastKnownHeight = -1; - int lastKnownRotation = -1; - - @Override - public void onDisplayAdded(int displayId) {} - - @Override - public void onDisplayRemoved(int displayId) {} - - @SuppressLint("WrongConstant") - @SuppressWarnings({"MissingPermission"}) - @Override - public void onDisplayChanged(int displayId) { - if (getDisplayId() != displayId) { - return; - } - - Display display = displayManager.getDisplay(displayId); - if (lastKnownWidth == display.getWidth() - && lastKnownHeight == display.getHeight() - && lastKnownRotation == display.getRotation()) { - return; - } - - lastKnownWidth = display.getWidth(); - lastKnownHeight = display.getHeight(); - lastKnownRotation = display.getRotation(); - - if (PermissionChecker.hasPermissions(getContext(), REQUIRED_PERMISSIONS)) { - if (mCamera.isOpen()) { - mCamera.close(); - mCamera.open(); - } - } - } - }; - displayManager.registerDisplayListener(mDisplayListener, new Handler()); - } - - ContextCompat.registerReceiver(context, mStateChangedReceiver, new IntentFilter(CameraView.ACTION_CAMERA_STATE_CHANGED), ContextCompat.RECEIVER_NOT_EXPORTED); - } - - private int getDisplayId() { - if (Build.VERSION.SDK_INT < 17) { - return -1; - } - - View view = getView(); - if (view == null) { - return -1; - } - - return view.getDisplay().getDisplayId(); - } - - @Override - public void onDetach() { - requireContext().unregisterReceiver(mStateChangedReceiver); - if (Build.VERSION.SDK_INT > 17) { - DisplayManager displayManager = (DisplayManager) requireContext().getSystemService(Context.DISPLAY_SERVICE); - displayManager.unregisterDisplayListener(mDisplayListener); - } - super.onDetach(); - } - - @SuppressWarnings({"MissingPermission"}) - @Override - public void onStart() { - super.onStart(); - if (PermissionChecker.hasPermissions(getContext(), REQUIRED_PERMISSIONS)) { - showCamera(); - } else { - showPermissionPrompt(); - } - } - - @Override - public void onStop() { - mCamera.close(); - onCameraClosed(); - super.onStop(); - } - - @Override - public void onImageCaptured(File file) { - - } - - @Override - public void onVideoCaptured(File file) { - - } - - public void setEnabled(boolean enabled) { - if (mCapture != null) { - mCapture.setEnabled(enabled); - } else { - mCamera.setEnabled(enabled); - } - } - - public boolean isEnabled() { - if (mCapture != null) { - return mCapture.isEnabled(); - } else { - return mCamera.isEnabled(); - } - } - - public void setQuality(CameraView.Quality quality) { - mCamera.setQuality(quality); - } - - public CameraView.Quality getQuality() { - return mCamera.getQuality(); - } - - public void setMaxVideoDuration(long duration) { - mCamera.setMaxVideoDuration(duration); - } - - public long getMaxVideoDuration() { - return mCamera.getMaxVideoDuration(); - } - - public void setMaxVideoSize(long size) { - mCamera.setMaxVideoSize(size); - } - - public long getMaxVideoSize() { - return mCamera.getMaxVideoSize(); - } - - protected void onTakePicture() {} - - protected void onRecordStart() {} - - protected void onRecordStop() {} - - @Override - public void onCameraOpened() {} - - @Override - public void onCameraClosed() {} - - @RequiresPermission(allOf = { - Manifest.permission.CAMERA, - Manifest.permission.RECORD_AUDIO, - Manifest.permission.WRITE_EXTERNAL_STORAGE - }) - private void showCamera() { - mCameraHolder.setVisibility(View.VISIBLE); - mPermissionPrompt.setVisibility(View.GONE); - mCamera.open(); - } - - private void showPermissionPrompt() { - mCameraHolder.setVisibility(View.GONE); - mPermissionPrompt.setVisibility(View.VISIBLE); - } - - private static String stringForTime(int timeMs) { - int totalSeconds = timeMs / 1000; - - int seconds = totalSeconds % 60; - int minutes = (totalSeconds / 60) % 60; - int hours = totalSeconds / 3600; - - Formatter formatter = new Formatter(Locale.getDefault()); - - if (hours > 0) { - return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); - } else { - return formatter.format("%02d:%02d", minutes, seconds).toString(); - } - } - - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - mCameraHolder = view.findViewById(R.id.layout_camera); - mPermissionPrompt = view.findViewById(R.id.layout_permissions); - mPermissionRequest = view.findViewById(R.id.request_permissions); - mCamera = view.findViewById(R.id.camera); - mToggle = view.findViewById(R.id.toggle); - mCapture = mCameraHolder.findViewById(R.id.capture); - mProgress = view.findViewById(R.id.progress); - mDuration = view.findViewById(R.id.duration); - mCancel = view.findViewById(R.id.cancel); - mConfirm = view.findViewById(R.id.confirm); - - if (mCameraHolder == null) { - throw new IllegalStateException("No View found with id R.id.layout_camera"); - } - - if (mCamera == null) { - throw new IllegalStateException("No CameraView found with id R.id.camera"); - } - - if (mPermissionPrompt == null) { - throw new IllegalStateException("No View found with id R.id.layout_permissions"); - } - - if (mPermissionRequest == null) { - throw new IllegalStateException("No View found with id R.id.request_permissions"); - } - - invalidate(); - } - - private void invalidate() { - mCamera.setOnImageCapturedListener(this); - mCamera.setOnVideoCapturedListener(this); - mCamera.setOnCameraStateChangedListener(this); - - if (mCapture != null) { - mCapture.setOnTouchListener(new OnTouchListener(getContext())); - } - - if (mConfirm != null) { - mConfirm.setOnClickListener(v -> mCamera.confirmPicture()); - mCamera.setImageConfirmationEnabled(true); - mCamera.setVideoConfirmationEnabled(true); - } else { - mCamera.setImageConfirmationEnabled(false); - mCamera.setVideoConfirmationEnabled(false); - } - - mPermissionRequest.setOnClickListener(v -> requestPermissions(concat(REQUIRED_PERMISSIONS, OPTIONAL_PERMISSIONS), REQUEST_CODE_PERMISSIONS)); - - if (mToggle != null) { - mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE); - mToggle.setChecked(mCamera.isUsingFrontFacingCamera()); - } - - if (mProgress != null) { - mProgress.setMax(10000); - } - - if (mDuration != null) { - mDuration.setVisibility(View.GONE); - } - - if (mCancel != null) { - mCancel.setVisibility(View.GONE); - } - - if (mConfirm != null) { - mConfirm.setVisibility(View.GONE); - } - } - - @Override - public void onViewStateRestored(@Nullable Bundle savedInstanceState) { - super.onViewStateRestored(savedInstanceState); - - // Set listeners here, or else restoring state will trigger them. - if (mToggle != null) { - mToggle.setOnCheckedChangeListener((b, checked) -> { - mCamera.toggleCamera(); - onToggle(); - }); - } - } - - protected void onToggle() { - - } - - @Override - public void onFailure() {} - - @Override - public void onImageConfirmation() { - View.OnClickListener listener = view -> { - if (view == mCancel) { - mCamera.rejectPicture(); - } else { - mCamera.confirmPicture(); - } - - // After confirming/rejecting, show our buttons again - if (mConfirm != null) { - mConfirm.setVisibility(View.GONE); - } - if (mCapture != null) { - mCapture.setVisibility(View.VISIBLE); - } - if (mCancel != null) { - mCancel.setVisibility(View.GONE); - } - if (mToggle != null) { - mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE); - } - }; - if (mCancel != null) { - mCancel.setVisibility(View.VISIBLE); - mCancel.setOnClickListener(listener); - } - if (mToggle != null) { - mToggle.setVisibility(View.GONE); - } - if (mCapture != null) { - mCapture.setVisibility(View.GONE); - } - if (mConfirm != null) { - mConfirm.setVisibility(View.VISIBLE); - mConfirm.setOnClickListener(listener); - } - } - - @Override - public void onVideoConfirmation() { - View.OnClickListener listener = v -> { - if (v == mCancel) { - mCamera.rejectVideo(); - } else { - mCamera.confirmVideo(); - } - - // After confirming/rejecting, show our buttons again - if (mConfirm != null) { - mConfirm.setVisibility(View.GONE); - } - if (mCapture != null) { - mCapture.setVisibility(View.VISIBLE); - } - if (mCancel != null) { - mCancel.setVisibility(View.GONE); - } - if (mToggle != null) { - mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE); - } - }; - if (mCancel != null) { - mCancel.setVisibility(View.VISIBLE); - mCancel.setOnClickListener(listener); - } - if (mToggle != null) { - mToggle.setVisibility(View.GONE); - } - if (mCapture != null) { - mCapture.setVisibility(View.GONE); - } - if (mConfirm != null) { - mConfirm.setVisibility(View.VISIBLE); - mConfirm.setOnClickListener(listener); - } - } - - private class ProgressBarAnimator extends ValueAnimator { - private ProgressBarAnimator() { - setInterpolator(new LinearInterpolator()); - setFloatValues(0f, 1f); - addUpdateListener(animation -> { - float percent = (float) animation.getAnimatedValue(); - onUpdate(percent); - }); - } - - void onUpdate(float percent) { - if (mProgress != null) { - mProgress.setProgress((int) (percent * 10000)); - } - if (mDuration != null) { - mDuration.setText(stringForTime((int) (percent * 10000))); - } - } - } - - private class OnTouchListener implements View.OnTouchListener { - private final int TAP = 1; - private final int HOLD = 2; - private final int RELEASE = 3; - - private final long LONG_PRESS = ViewConfiguration.getLongPressTimeout(); - - private final Context mContext; - - private long mDownEventTimestamp; - private Rect mViewBoundsRect; - @SuppressLint("HandlerLeak") - private final Handler mHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case TAP: - onTap(); - break; - case HOLD: - onHold(); - if (mCamera.getMaxVideoDuration() > 0) { - sendEmptyMessageDelayed(RELEASE, mCamera.getMaxVideoDuration()); - } - break; - case RELEASE: - onRelease(); - break; - } - } - }; - - OnTouchListener(Context context) { - mContext = context; - } - - Context getContext() { - return mContext; - } - - void onTap() { - mCamera.takePicture(new File(getContext().getCacheDir(), DateFormat.format(DESTINATION, new Date()) + PHOTO_EXT)); - onTakePicture(); - } - - void onHold() { - vibrate(); - mCamera.startRecording(new File(getContext().getCacheDir(), DateFormat.format(DESTINATION, new Date()) + VIDEO_EXT)); - if (mCamera.isRecording()) { - if (mDuration != null) { - mDuration.setVisibility(View.VISIBLE); - } - if (mCamera.getMaxVideoDuration() > 0) { - mAnimator.setDuration(mCamera.getMaxVideoDuration()).start(); - } - onRecordStart(); - } - } - - void onRelease() { - mCamera.stopRecording(); - mAnimator.cancel(); - if (mProgress != null) { - mProgress.setProgress(0); - } - if (mDuration != null) { - mDuration.setVisibility(View.GONE); - } - onRecordStop(); - } - - @SuppressLint("ClickableViewAccessibility") - @Override - public boolean onTouch(View v, MotionEvent event) { - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - mDownEventTimestamp = System.currentTimeMillis(); - mViewBoundsRect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); - mHandler.sendEmptyMessageDelayed(HOLD, LONG_PRESS); - v.setPressed(true); - break; - case MotionEvent.ACTION_MOVE: - // If the user moves their finger off the button, trigger RELEASE - if (mViewBoundsRect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) { - break; - } - // Fall-through - case MotionEvent.ACTION_CANCEL: - clearHandler(); - if (delta() > LONG_PRESS && (mCamera.getMaxVideoDuration() <= 0 || delta() < mCamera.getMaxVideoDuration())) { - mHandler.sendEmptyMessage(RELEASE); - } - v.setPressed(false); - break; - case MotionEvent.ACTION_UP: - clearHandler(); - if (delta() < LONG_PRESS) { - mHandler.sendEmptyMessage(TAP); - } else if ((mCamera.getMaxVideoDuration() <= 0 || delta() < mCamera.getMaxVideoDuration())) { - mHandler.sendEmptyMessage(RELEASE); - } - v.setPressed(false); - break; - } - return true; - } - - private long delta() { - return System.currentTimeMillis() - mDownEventTimestamp; - } - - @SuppressWarnings({"MissingPermission"}) - private void vibrate() { - Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE); - if (PermissionChecker.hasPermissions(getContext(), Manifest.permission.VIBRATE) && vibrator.hasVibrator()) { - vibrator.vibrate(25); - } - } - - private void clearHandler() { - mHandler.removeMessages(TAP); - mHandler.removeMessages(HOLD); - mHandler.removeMessages(RELEASE); - } - } - - private static T[] concat(T[] first, T[] second) { - T[] result = Arrays.copyOf(first, first.length + second.length); - System.arraycopy(second, 0, result, first.length, second.length); - return result; - } -} +package com.xlythe.fragment.camera; + +import android.Manifest; +import android.animation.ValueAnimator; +import android.annotation.SuppressLint; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.graphics.Rect; +import android.hardware.display.DisplayManager; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.os.Vibrator; +import android.text.format.DateFormat; +import android.view.Display; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.animation.LinearInterpolator; +import android.widget.CompoundButton; +import android.widget.ProgressBar; +import android.widget.TextView; + +import com.xlythe.view.camera.CameraView; +import com.xlythe.view.camera.PermissionChecker; +import com.xlythe.view.camera.R; + +import java.io.File; +import java.util.Arrays; +import java.util.Date; +import java.util.Formatter; +import java.util.Locale; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RequiresPermission; +import androidx.core.content.ContextCompat; +import androidx.fragment.app.Fragment; + +public abstract class CameraFragment extends Fragment implements CameraView.OnImageCapturedListener, CameraView.OnVideoCapturedListener, CameraView.OnCameraStateChangedListener { + private static final String[] REQUIRED_PERMISSIONS; + private static final String[] OPTIONAL_PERMISSIONS; + + static { + if (Build.VERSION.SDK_INT >= 34) { + // In U+, READ_MEDIA_IMAGES and READ_MEDIA_VIDEO no longer give access to the file system and the user must manually select files from a system window. + // As this experience is terrible, support for reading previews of images taken is removed. An image that was taken immediately can still be previewed. + REQUIRED_PERMISSIONS = new String[] { + Manifest.permission.CAMERA, + Manifest.permission.RECORD_AUDIO + }; + OPTIONAL_PERMISSIONS = new String[] { + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.VIBRATE, + }; + } else if (Build.VERSION.SDK_INT >= 33) { + // In T+, READ_EXTERNAL_STORAGE is removed and replaced with READ_MEDIA_IMAGES and READ_MEDIA_VIDEO + REQUIRED_PERMISSIONS = new String[] { + Manifest.permission.CAMERA, + Manifest.permission.RECORD_AUDIO + }; + OPTIONAL_PERMISSIONS = new String[] { + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.VIBRATE, + Manifest.permission.READ_MEDIA_IMAGES, + Manifest.permission.READ_MEDIA_VIDEO + }; + } else if (Build.VERSION.SDK_INT >= 19) { + // In KitKat+, WRITE_EXTERNAL_STORAGE is optional + REQUIRED_PERMISSIONS = new String[] { + Manifest.permission.CAMERA, + Manifest.permission.RECORD_AUDIO + }; + OPTIONAL_PERMISSIONS = new String[] { + Manifest.permission.WRITE_EXTERNAL_STORAGE, + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.VIBRATE + }; + } else { + REQUIRED_PERMISSIONS = new String[] { + Manifest.permission.CAMERA, + Manifest.permission.RECORD_AUDIO, + Manifest.permission.WRITE_EXTERNAL_STORAGE + }; + OPTIONAL_PERMISSIONS = new String[] { + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.VIBRATE + }; + } + } + + /** Package-private so a test can deliver a result under the same code the prompt asks with. */ + static final int REQUEST_CODE_PERMISSIONS = 10; + // Colons are not legal in a file name on every filesystem Android mounts, and MediaStore + // rejects them in a display name, so the default avoids them. + private static final String DESTINATION = "yyyy-MM-dd-HH-mm-ss"; + private static final String PHOTO_EXT = ".jpg"; + private static final String VIDEO_EXT = ".mp4"; + + private View mCameraHolder; + + private View mPermissionPrompt; + + private CameraView mCamera; + + private View mPermissionRequest; + + @Nullable + private View mCapture; + + @Nullable + private View mConfirm; + + @Nullable + private TextView mDuration; + + @Nullable + private ProgressBar mProgress; + + @Nullable + private CompoundButton mToggle; + + @Nullable + private View mCancel; + + private final ProgressBarAnimator mAnimator = new ProgressBarAnimator(); + + /** Held so invalidate() can set the toggle's state without the listener reading it as a tap. */ + private final CompoundButton.OnCheckedChangeListener mToggleListener = (button, checked) -> { + mCamera.toggleCamera(); + onToggle(); + }; + + private DisplayManager.DisplayListener mDisplayListener; + + private final BroadcastReceiver mStateChangedReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + invalidate(); + } + }; + + @SuppressWarnings({"MissingPermission"}) + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + if (requestCode == REQUEST_CODE_PERMISSIONS) { + if (PermissionChecker.hasPermissions(getContext(), REQUIRED_PERMISSIONS)) { + showCamera(); + } else { + showPermissionPrompt(); + } + } + } + + @Override + public void onAttach(Context context) { + super.onAttach(context); + + if (Build.VERSION.SDK_INT >= 17) { + DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); + mDisplayListener = new DisplayManager.DisplayListener() { + int lastKnownWidth = -1; + int lastKnownHeight = -1; + int lastKnownRotation = -1; + + @Override + public void onDisplayAdded(int displayId) {} + + @Override + public void onDisplayRemoved(int displayId) {} + + @SuppressLint("WrongConstant") + @SuppressWarnings({"MissingPermission"}) + @Override + public void onDisplayChanged(int displayId) { + if (getDisplayId() != displayId) { + return; + } + + Display display = displayManager.getDisplay(displayId); + if (lastKnownWidth == display.getWidth() + && lastKnownHeight == display.getHeight() + && lastKnownRotation == display.getRotation()) { + return; + } + + lastKnownWidth = display.getWidth(); + lastKnownHeight = display.getHeight(); + lastKnownRotation = display.getRotation(); + + if (PermissionChecker.hasPermissions(getContext(), REQUIRED_PERMISSIONS)) { + if (mCamera.isOpen()) { + mCamera.close(); + mCamera.open(); + } + } + } + }; + displayManager.registerDisplayListener(mDisplayListener, new Handler()); + } + + ContextCompat.registerReceiver(context, mStateChangedReceiver, new IntentFilter(CameraView.ACTION_CAMERA_STATE_CHANGED), ContextCompat.RECEIVER_NOT_EXPORTED); + } + + private int getDisplayId() { + if (Build.VERSION.SDK_INT < 17) { + return -1; + } + + View view = getView(); + if (view == null) { + return -1; + } + + return view.getDisplay().getDisplayId(); + } + + @Override + public void onDetach() { + requireContext().unregisterReceiver(mStateChangedReceiver); + // Must match the version gate onAttach registers under, or the listener outlives us. + if (Build.VERSION.SDK_INT >= 17) { + DisplayManager displayManager = (DisplayManager) requireContext().getSystemService(Context.DISPLAY_SERVICE); + displayManager.unregisterDisplayListener(mDisplayListener); + } + super.onDetach(); + } + + @SuppressWarnings({"MissingPermission"}) + @Override + public void onStart() { + super.onStart(); + if (PermissionChecker.hasPermissions(getContext(), REQUIRED_PERMISSIONS)) { + showCamera(); + } else { + showPermissionPrompt(); + } + } + + @Override + public void onStop() { + // CameraView dispatches onCameraClosed() itself, and only when it really was open. + if (mCamera != null) { + mCamera.close(); + } + super.onStop(); + } + + @Override + public void onImageCaptured(File file) { + + } + + @Override + public void onVideoCaptured(File file) { + + } + + public void setEnabled(boolean enabled) { + if (mCapture != null) { + mCapture.setEnabled(enabled); + } else { + mCamera.setEnabled(enabled); + } + } + + public boolean isEnabled() { + if (mCapture != null) { + return mCapture.isEnabled(); + } else { + return mCamera.isEnabled(); + } + } + + public void setQuality(CameraView.Quality quality) { + mCamera.setQuality(quality); + } + + public CameraView.Quality getQuality() { + return mCamera.getQuality(); + } + + public void setMaxVideoDuration(long duration) { + mCamera.setMaxVideoDuration(duration); + } + + public long getMaxVideoDuration() { + return mCamera.getMaxVideoDuration(); + } + + public void setMaxVideoSize(long size) { + mCamera.setMaxVideoSize(size); + } + + public long getMaxVideoSize() { + return mCamera.getMaxVideoSize(); + } + + protected void onTakePicture() {} + + protected void onRecordStart() {} + + protected void onRecordStop() {} + + @Override + public void onCameraOpened() {} + + @Override + public void onCameraClosed() {} + + @RequiresPermission(Manifest.permission.CAMERA) + private void showCamera() { + // A permission result can land after onDestroyView, once the Views are gone. + if (mCamera == null) { + return; + } + mCameraHolder.setVisibility(View.VISIBLE); + mPermissionPrompt.setVisibility(View.GONE); + mCamera.open(); + } + + private void showPermissionPrompt() { + if (mCameraHolder == null) { + return; + } + mCameraHolder.setVisibility(View.GONE); + mPermissionPrompt.setVisibility(View.VISIBLE); + } + + private static String stringForTime(long timeMs) { + long totalSeconds = Math.max(0, timeMs) / 1000; + + long seconds = totalSeconds % 60; + long minutes = (totalSeconds / 60) % 60; + long hours = totalSeconds / 3600; + + try (Formatter formatter = new Formatter(Locale.getDefault())) { + if (hours > 0) { + return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); + } else { + return formatter.format("%02d:%02d", minutes, seconds).toString(); + } + } + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + mCameraHolder = view.findViewById(R.id.layout_camera); + mPermissionPrompt = view.findViewById(R.id.layout_permissions); + mPermissionRequest = view.findViewById(R.id.request_permissions); + mCamera = view.findViewById(R.id.camera); + + // Check the required Views before anything reads through them, so a layout that is + // missing one reports which id it needs instead of throwing from findViewById. + if (mCameraHolder == null) { + throw new IllegalStateException("No View found with id R.id.layout_camera"); + } + + if (mCamera == null) { + throw new IllegalStateException("No CameraView found with id R.id.camera"); + } + + if (mPermissionPrompt == null) { + throw new IllegalStateException("No View found with id R.id.layout_permissions"); + } + + if (mPermissionRequest == null) { + throw new IllegalStateException("No View found with id R.id.request_permissions"); + } + + mToggle = view.findViewById(R.id.toggle); + mCapture = mCameraHolder.findViewById(R.id.capture); + mProgress = view.findViewById(R.id.progress); + mDuration = view.findViewById(R.id.duration); + mCancel = view.findViewById(R.id.cancel); + mConfirm = view.findViewById(R.id.confirm); + + invalidate(); + } + + private void invalidate() { + // The state receiver is registered from onAttach and unregistered in onDetach, so it can + // fire before onViewCreated has resolved the Views and after onDestroyView has released + // them. Both windows used to dereference a null CameraView. + if (mCamera == null) { + return; + } + + mCamera.setOnImageCapturedListener(this); + mCamera.setOnVideoCapturedListener(this); + mCamera.setOnCameraStateChangedListener(this); + + if (mCapture != null) { + mCapture.setOnTouchListener(new OnTouchListener(getContext())); + } + + if (mConfirm != null) { + mConfirm.setOnClickListener(v -> mCamera.confirmPicture()); + mCamera.setImageConfirmationEnabled(true); + mCamera.setVideoConfirmationEnabled(true); + } else { + mCamera.setImageConfirmationEnabled(false); + mCamera.setVideoConfirmationEnabled(false); + } + + mPermissionRequest.setOnClickListener(v -> requestPermissions(concat(REQUIRED_PERMISSIONS, OPTIONAL_PERMISSIONS), REQUEST_CODE_PERMISSIONS)); + + if (mToggle != null) { + mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE); + // Detach the listener first: invalidate() also runs after the camera reports itself + // ready, by which point the listener is attached and setChecked would read as a tap + // and toggle the lens the user never asked to change. + mToggle.setOnCheckedChangeListener(null); + mToggle.setChecked(mCamera.isUsingFrontFacingCamera()); + mToggle.setOnCheckedChangeListener(mToggleListener); + } + + if (mProgress != null) { + mProgress.setMax(10000); + } + + if (mDuration != null) { + mDuration.setVisibility(View.GONE); + } + + if (mCancel != null) { + mCancel.setVisibility(View.GONE); + } + + if (mConfirm != null) { + mConfirm.setVisibility(View.GONE); + } + } + + @Override + public void onDestroyView() { + // Drop the Views with the hierarchy that owned them, so anything still arriving, such as + // the camera state broadcast, does not reach a destroyed CameraView. + mCameraHolder = null; + mPermissionPrompt = null; + mPermissionRequest = null; + mCamera = null; + mToggle = null; + mCapture = null; + mProgress = null; + mDuration = null; + mCancel = null; + mConfirm = null; + super.onDestroyView(); + } + + @Override + public void onViewStateRestored(@Nullable Bundle savedInstanceState) { + super.onViewStateRestored(savedInstanceState); + + // Set listeners here, or else restoring state will trigger them. + if (mToggle != null) { + mToggle.setOnCheckedChangeListener(mToggleListener); + } + } + + protected void onToggle() { + + } + + @Override + public void onFailure() {} + + /** + * Puts the capture button back and takes the confirmation buttons away. + * + *

The same thing happens after confirming a picture and after confirming a video, and it + * has to happen whether or not the thing being confirmed was still there - so it is one + * method rather than two copies and a third for the case that goes wrong.

+ */ + private void restoreCaptureButtons() { + if (mConfirm != null) { + mConfirm.setVisibility(View.GONE); + } + if (mCapture != null) { + mCapture.setVisibility(View.VISIBLE); + } + if (mCancel != null) { + mCancel.setVisibility(View.GONE); + } + if (mToggle != null) { + mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE); + } + } + + @Override + public void onImageConfirmation() { + View.OnClickListener listener = view -> { + // The buttons outlive what they are confirming: a camera that closes, or state being + // restored, clears the pending picture while they are still on screen, and both of + // these throw when there is nothing pending. From a click handler that is a crash, + // so the buttons are put back either way and the picture is only acted on if it is + // still there. + if (mCamera.isImageConfirmationPending()) { + if (view == mCancel) { + mCamera.rejectPicture(); + } else { + mCamera.confirmPicture(); + } + } + + restoreCaptureButtons(); + }; + if (mCancel != null) { + mCancel.setVisibility(View.VISIBLE); + mCancel.setOnClickListener(listener); + } + if (mToggle != null) { + mToggle.setVisibility(View.GONE); + } + if (mCapture != null) { + mCapture.setVisibility(View.GONE); + } + if (mConfirm != null) { + mConfirm.setVisibility(View.VISIBLE); + mConfirm.setOnClickListener(listener); + } + } + + @Override + public void onVideoConfirmation() { + View.OnClickListener listener = v -> { + if (!mCamera.isVideoConfirmationPending()) { + // As above: the buttons outlive what they are confirming. + restoreCaptureButtons(); + return; + } + if (v == mCancel) { + mCamera.rejectVideo(); + } else { + mCamera.confirmVideo(); + } + + restoreCaptureButtons(); + }; + if (mCancel != null) { + mCancel.setVisibility(View.VISIBLE); + mCancel.setOnClickListener(listener); + } + if (mToggle != null) { + mToggle.setVisibility(View.GONE); + } + if (mCapture != null) { + mCapture.setVisibility(View.GONE); + } + if (mConfirm != null) { + mConfirm.setVisibility(View.VISIBLE); + mConfirm.setOnClickListener(listener); + } + } + + private class ProgressBarAnimator extends ValueAnimator { + private ProgressBarAnimator() { + setInterpolator(new LinearInterpolator()); + setFloatValues(0f, 1f); + addUpdateListener(animation -> { + float percent = (float) animation.getAnimatedValue(); + onUpdate(percent); + }); + } + + void onUpdate(float percent) { + if (mProgress != null) { + mProgress.setProgress((int) (percent * 10000)); + } + if (mDuration != null) { + // The animator runs for the whole maximum duration, so the fraction elapsed is + // what turns into a wall-clock time. Scaling by the progress bar's own range + // instead counted a fixed ten seconds for every recording. + mDuration.setText(stringForTime((long) (percent * mCamera.getMaxVideoDuration()))); + } + } + } + + private class OnTouchListener implements View.OnTouchListener { + private final int TAP = 1; + private final int HOLD = 2; + private final int RELEASE = 3; + + private final long LONG_PRESS = ViewConfiguration.getLongPressTimeout(); + + private final Context mContext; + + private long mDownEventTimestamp; + private Rect mViewBoundsRect; + @SuppressLint("HandlerLeak") + private final Handler mHandler = new Handler() { + // Reached only from the capture button, which showCamera gates on the fragment's + // REQUIRED_PERMISSIONS, so the microphone has been granted by the time a hold starts. + @SuppressWarnings("MissingPermission") + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case TAP: + onTap(); + break; + case HOLD: + onHold(); + if (mCamera.getMaxVideoDuration() > 0) { + sendEmptyMessageDelayed(RELEASE, mCamera.getMaxVideoDuration()); + } + break; + case RELEASE: + onRelease(); + break; + } + } + }; + + OnTouchListener(Context context) { + mContext = context; + } + + Context getContext() { + return mContext; + } + + void onTap() { + mCamera.takePicture(new File(getContext().getCacheDir(), DateFormat.format(DESTINATION, new Date()) + PHOTO_EXT)); + onTakePicture(); + } + + // CameraFragment records on long press, so the microphone really is required here, and + // it stays in REQUIRED_PERMISSIONS for that reason. + @RequiresPermission(Manifest.permission.RECORD_AUDIO) + void onHold() { + vibrate(); + mCamera.startRecording(new File(getContext().getCacheDir(), DateFormat.format(DESTINATION, new Date()) + VIDEO_EXT)); + if (mCamera.isRecording()) { + boolean hasDurationLimit = mCamera.getMaxVideoDuration() > 0; + if (mDuration != null) { + // Without a limit there is no animator to drive the label, so showing it + // would only leave the previous recording's time on screen. + mDuration.setVisibility(hasDurationLimit ? View.VISIBLE : View.GONE); + mDuration.setText(stringForTime(0)); + } + if (hasDurationLimit) { + mAnimator.setDuration(mCamera.getMaxVideoDuration()).start(); + } + onRecordStart(); + } + } + + void onRelease() { + mCamera.stopRecording(); + mAnimator.cancel(); + if (mProgress != null) { + mProgress.setProgress(0); + } + if (mDuration != null) { + mDuration.setVisibility(View.GONE); + } + onRecordStop(); + } + + @SuppressLint("ClickableViewAccessibility") + @Override + public boolean onTouch(View v, MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + mDownEventTimestamp = System.currentTimeMillis(); + mViewBoundsRect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); + mHandler.sendEmptyMessageDelayed(HOLD, LONG_PRESS); + v.setPressed(true); + break; + case MotionEvent.ACTION_MOVE: + // If the user moves their finger off the button, trigger RELEASE + if (mViewBoundsRect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) { + break; + } + // Fall-through + case MotionEvent.ACTION_CANCEL: + clearHandler(); + if (delta() > LONG_PRESS && (mCamera.getMaxVideoDuration() <= 0 || delta() < mCamera.getMaxVideoDuration())) { + mHandler.sendEmptyMessage(RELEASE); + } + v.setPressed(false); + break; + case MotionEvent.ACTION_UP: + clearHandler(); + if (delta() < LONG_PRESS) { + mHandler.sendEmptyMessage(TAP); + } else if ((mCamera.getMaxVideoDuration() <= 0 || delta() < mCamera.getMaxVideoDuration())) { + mHandler.sendEmptyMessage(RELEASE); + } + v.setPressed(false); + break; + } + return true; + } + + private long delta() { + return System.currentTimeMillis() - mDownEventTimestamp; + } + + @SuppressWarnings({"MissingPermission"}) + private void vibrate() { + Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE); + if (PermissionChecker.hasPermissions(getContext(), Manifest.permission.VIBRATE) && vibrator.hasVibrator()) { + vibrator.vibrate(25); + } + } + + private void clearHandler() { + mHandler.removeMessages(TAP); + mHandler.removeMessages(HOLD); + mHandler.removeMessages(RELEASE); + } + } + + private static T[] concat(T[] first, T[] second) { + T[] result = Arrays.copyOf(first, first.length + second.length); + System.arraycopy(second, 0, result, first.length, second.length); + return result; + } +} diff --git a/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioPlayer.java b/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioPlayer.java index dee7101..ea8914c 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioPlayer.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioPlayer.java @@ -11,6 +11,7 @@ import java.io.IOException; import java.io.InputStream; +import java.util.concurrent.atomic.AtomicBoolean; import static android.os.Process.THREAD_PRIORITY_AUDIO; import static android.os.Process.setThreadPriority; @@ -34,9 +35,11 @@ public class AudioPlayer { * will shut down. */ private volatile boolean mIsAlive; + /** Ensures the input stream is closed exactly once. */ + private final AtomicBoolean mStopped = new AtomicBoolean(); /** The background thread playing audio for us. */ - private Thread mThread; + private volatile Thread mThread; /** * A simple audio player. @@ -57,8 +60,8 @@ public boolean isPlaying() { } /** Starts playing the stream. */ - public void start() { - if (mThread != null) { + public synchronized void start() { + if (mThread != null || mStopped.get()) { Log.w(TAG, "AudioPlayer cannot be started more than once"); return; } @@ -71,20 +74,42 @@ public void run() { setThreadPriority(THREAD_PRIORITY_AUDIO); Buffer buffer = new Buffer(); + InputStream audio = mInputStream; + int sampleRate = buffer.getSampleRate(); + int channels = AudioFormat.CHANNEL_OUT_MONO; + try { + AudioStreamHeader.Read read = AudioStreamHeader.read(mInputStream); + audio = read.stream; + if (read.header != null) { + // The recorder said what it is sending, which beats guessing from this + // device's hardware: the two are not the same device. + sampleRate = read.header.getSampleRate(); + channels = read.header.getChannelCount() > 1 + ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO; + } + } catch (IOException error) { + Log.e(TAG, "Failed to read the audio stream's description", error); + } + + int size = AudioTrack.getMinBufferSize( + sampleRate, channels, AudioFormat.ENCODING_PCM_16BIT); + if (size <= 0) { + size = buffer.getSize(); + } AudioTrack audioTrack = new AudioTrack( AudioManager.STREAM_VOICE_CALL, - buffer.getSampleRate(), - AudioFormat.CHANNEL_OUT_MONO, + sampleRate, + channels, AudioFormat.ENCODING_PCM_16BIT, - buffer.getSize(), + size, AudioTrack.MODE_STREAM); audioTrack.play(); - Log.d(TAG, "Started playing audio"); + Log.d(TAG, "Started playing audio at " + sampleRate + "Hz"); int len; try { - while (isPlaying() && (len = mInputStream.read(buffer.data())) > 0) { + while (isPlaying() && (len = audio.read(buffer.data())) > 0) { audioTrack.write(buffer.data(), 0, len); } } catch (IOException e) { @@ -105,24 +130,25 @@ public void run() { private void stopInternal() { mIsAlive = false; - try { - mInputStream.close(); - } catch (IOException e) { - Log.e(TAG, "Failed to close audio input stream", e); + if (mStopped.compareAndSet(false, true)) { + try { + mInputStream.close(); + } catch (IOException e) { + Log.e(TAG, "Failed to close audio input stream", e); + } + Log.d(TAG, "Stopped playing audio"); } - Log.d(TAG, "Stopped playing audio"); } /** Stops playing the stream. */ public void stop() { - if (mThread == null) { - Log.w(TAG, "AudioPlayer not started"); + stopInternal(); + Thread thread = mThread; + if (thread == null || thread == Thread.currentThread()) { return; } - - stopInternal(); try { - mThread.join(300); + thread.join(300); } catch (InterruptedException e) { Log.e(TAG, "Interrupted while joining AudioPlayer thread", e); Thread.currentThread().interrupt(); diff --git a/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioRecorder.java b/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioRecorder.java index f7440c7..6325ca6 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioRecorder.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioRecorder.java @@ -13,6 +13,7 @@ import java.io.IOException; import java.io.OutputStream; +import java.util.concurrent.atomic.AtomicBoolean; import static android.os.Process.THREAD_PRIORITY_AUDIO; import static android.os.Process.setThreadPriority; @@ -32,9 +33,11 @@ public class AudioRecorder { * will shut down. */ private volatile boolean mIsAlive; + /** Ensures the output stream is closed exactly once. */ + private final AtomicBoolean mStopped = new AtomicBoolean(); /** The background thread recording audio for us. */ - private Thread mThread; + private volatile Thread mThread; /** * A simple audio recorder. @@ -61,8 +64,8 @@ public boolean isRecording() { /** Starts recording audio. */ @RequiresPermission(Manifest.permission.RECORD_AUDIO) - public void start() { - if (isRecording()) { + public synchronized void start() { + if (mThread != null || mStopped.get()) { Log.w(TAG, "AudioRecorder is already running"); return; } @@ -93,6 +96,19 @@ public void run() { record.startRecording(); Log.d(TAG, "Started recording audio"); + // Tell the other end what it is about to receive, so it does not have to guess + // the sample rate from its own hardware and play the audio at the wrong pitch. + try { + new AudioStreamHeader(buffer.getSampleRate(), 1 /* mono */, + AudioFormat.ENCODING_PCM_16BIT).writeTo(mOutputStream); + } catch (java.io.IOException error) { + Log.e(TAG, "Failed to describe the audio stream", error); + mIsAlive = false; + record.stop(); + record.release(); + return; + } + // While we're running, we'll read the bytes from the AudioRecord and write them // to our output stream. try { @@ -123,18 +139,24 @@ public void run() { private void stopInternal() { mIsAlive = false; - try { - mOutputStream.close(); - } catch (IOException e) { - Log.e(TAG, "Failed to close audio output stream", e); + if (mStopped.compareAndSet(false, true)) { + try { + mOutputStream.close(); + } catch (IOException e) { + Log.e(TAG, "Failed to close audio output stream", e); + } } } /** Stops recording audio. */ public void stop() { stopInternal(); + Thread thread = mThread; + if (thread == null || thread == Thread.currentThread()) { + return; + } try { - mThread.join(300); + thread.join(300); } catch (InterruptedException e) { Log.e(TAG, "Interrupted while joining AudioRecorder thread", e); Thread.currentThread().interrupt(); diff --git a/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioStreamHeader.java b/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioStreamHeader.java new file mode 100644 index 0000000..554d474 --- /dev/null +++ b/camera-view/src/main/java/com/xlythe/view/camera/stream/AudioStreamHeader.java @@ -0,0 +1,136 @@ +package com.xlythe.view.camera.stream; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.RestrictTo; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.SequenceInputStream; + +/** + * What the recorder tells the player about the audio that follows. + * + *

Without it both ends have to guess, and they guess separately: the recorder takes the lowest + * rate {@code AudioRecord} will give it and the player the lowest {@code AudioTrack} will, which + * are different questions asked of what may be two different devices. When the answers differ the + * audio plays at the wrong speed and pitch - a phone streaming to a watch is exactly the case + * where they are most likely to.

+ * + *

A stream with no header is read as raw PCM at the player's own guess, which is what a + * recorder from before this existed produces.

+ */ +@RestrictTo(RestrictTo.Scope.LIBRARY) +public final class AudioStreamHeader { + /** 'X', 'A', 'U', 'D'. Chosen to be something PCM audio is very unlikely to start with. */ + private static final int MAGIC = 0x58415544; + + private static final int VERSION = 1; + + /** Magic, version, sample rate, channel count, encoding. */ + static final int LENGTH = 4 + 1 + 4 + 1 + 1; + + private final int mSampleRate; + private final int mChannelCount; + private final int mEncoding; + + AudioStreamHeader(int sampleRate, int channelCount, int encoding) { + mSampleRate = sampleRate; + mChannelCount = channelCount; + mEncoding = encoding; + } + + public int getSampleRate() { + return mSampleRate; + } + + public int getChannelCount() { + return mChannelCount; + } + + /** One of the {@code AudioFormat.ENCODING_*} constants. */ + public int getEncoding() { + return mEncoding; + } + + void writeTo(@NonNull OutputStream outputStream) throws IOException { + DataOutputStream out = new DataOutputStream(outputStream); + out.writeInt(MAGIC); + out.writeByte(VERSION); + out.writeInt(mSampleRate); + out.writeByte(mChannelCount); + out.writeByte(mEncoding); + out.flush(); + } + + /** + * Reads the header, if the stream has one. + * + *

The bytes are consumed either way, so the caller is given back a stream to keep reading: + * when there was no header those bytes are audio and are put back in front of it.

+ */ + @NonNull + static Read read(@NonNull InputStream inputStream) throws IOException { + byte[] start = new byte[LENGTH]; + int read = 0; + while (read < start.length) { + int count = inputStream.read(start, read, start.length - read); + if (count < 0) { + break; + } + read += count; + } + if (read < start.length) { + // Too short to be a header, so it is the whole of a very short stream. + return new Read(null, prepend(start, read, inputStream)); + } + + DataInputStream header = new DataInputStream( + new java.io.ByteArrayInputStream(start)); + try { + if (header.readInt() != MAGIC || header.readByte() != VERSION) { + return new Read(null, prepend(start, read, inputStream)); + } + int sampleRate = header.readInt(); + int channelCount = header.readByte(); + int encoding = header.readByte(); + if (sampleRate <= 0 || channelCount <= 0) { + return new Read(null, prepend(start, read, inputStream)); + } + return new Read( + new AudioStreamHeader(sampleRate, channelCount, encoding), inputStream); + } catch (EOFException error) { + return new Read(null, prepend(start, read, inputStream)); + } + } + + private static InputStream prepend(byte[] start, int length, InputStream rest) { + ByteArrayOutputStream head = new ByteArrayOutputStream(length); + head.write(start, 0, length); + return new SequenceInputStream( + new java.io.ByteArrayInputStream(head.toByteArray()), rest); + } + + @NonNull + @Override + public String toString() { + return "AudioStreamHeader{sampleRate=" + mSampleRate + + ", channels=" + mChannelCount + ", encoding=" + mEncoding + "}"; + } + + /** A header, when the stream had one, and the stream to keep reading audio from. */ + static final class Read { + @Nullable final AudioStreamHeader header; + @NonNull final InputStream stream; + + Read(@Nullable AudioStreamHeader header, @NonNull InputStream stream) { + this.header = header; + this.stream = stream; + } + } +} diff --git a/camera-view/src/main/java/com/xlythe/view/camera/stream/LossyPipedOutputStream.java b/camera-view/src/main/java/com/xlythe/view/camera/stream/LossyPipedOutputStream.java index 952df8c..29fa5ba 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/stream/LossyPipedOutputStream.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/stream/LossyPipedOutputStream.java @@ -4,19 +4,64 @@ import java.io.PipedInputStream; import java.io.PipedOutputStream; +/** + * A {@link PipedOutputStream} that discards data instead of blocking when the reader falls + * behind, trading completeness for latency on a live link. + * + *

There are two ways to write to it, and they have different guarantees.

+ * + *

{@link #writeFrame(byte[], boolean)} is the one to use for anything whose records depend on + * each other, such as encoded video. It discards a record as a unit and never discards one that + * later records are decoded against.

+ * + *

The inherited {@link #write} methods drop at the granularity of a single call, and the + * caller is responsible for the consequences: a record split across several calls can be dropped + * halfway, and because the format on the wire carries no sentinel to resynchronize on, that + * desynchronizes the reader permanently. They are safe only for a producer that writes one whole + * independent record per call and then flushes, which is what {@link AudioRecorder} does with PCM + * chunks.

+ */ public class LossyPipedOutputStream extends PipedOutputStream { - private static final int MAX_BUFFER_SIZE = 0; + /** + * How far behind the reader may fall, in bytes, before droppable frames start being discarded. + * Large enough to absorb a key frame and the frames around it, small enough that the reader is + * never more than a moment behind. + */ + public static final int DEFAULT_MAX_BUFFERED_BYTES = 128 * 1024; + + /** + * How much further behind the reader may fall before even frames that others depend on are + * discarded. Past this point the backlog is too stale to be worth showing, and holding on to + * reference frames only grows it, since those are the largest frames. + */ + private static final int HARD_CEILING_MULTIPLIER = 4; + + private volatile int maxBufferedBytes; + private volatile int hardCeilingBytes; private PipedInputStream snk; private boolean canDropNextPacket = false; + private boolean resyncRequested = false; public LossyPipedOutputStream() { + this(DEFAULT_MAX_BUFFERED_BYTES); + } + + public LossyPipedOutputStream(int maxBufferedBytes) { super(); + this.maxBufferedBytes = maxBufferedBytes; + this.hardCeilingBytes = maxBufferedBytes * HARD_CEILING_MULTIPLIER; } public LossyPipedOutputStream(PipedInputStream snk) throws IOException { + this(snk, DEFAULT_MAX_BUFFERED_BYTES); + } + + public LossyPipedOutputStream(PipedInputStream snk, int maxBufferedBytes) throws IOException { super(snk); this.snk = snk; + this.maxBufferedBytes = maxBufferedBytes; + this.hardCeilingBytes = maxBufferedBytes * HARD_CEILING_MULTIPLIER; } @Override @@ -25,6 +70,82 @@ public synchronized void connect(PipedInputStream snk) throws IOException { this.snk = snk; } + /** + * Writes one whole frame, or discards the whole frame. + * + *

A frame is only ever written in full, so the reader never sees a partial record.

+ * + * @param frame the complete frame, including whatever length prefix the format uses + * @param droppable whether later frames can still be decoded without this one. Pass false for a + * key frame, for a codec-configuration frame, and for a stream header: those are written + * even when the reader is behind, because discarding one corrupts every frame that follows + * until the next key frame rather than costing a single frame. + * @return true when the frame was written, false when it was dropped + */ + public synchronized boolean writeFrame(byte[] frame, boolean droppable) throws IOException { + PipedInputStream sink = requireSink(); + int buffered = sink.available(); + if (droppable) { + if (buffered > maxBufferedBytes) { + return false; + } + } else if (buffered > hardCeilingBytes) { + // Reference frames are piling up too. Only the newest one is ever needed to resume, and + // the queued ones describe a moment that has already passed, so stop feeding the backlog + // and let the reader drain. Ask for a fresh one via consumeResyncRequest once it has. + resyncRequested = true; + return false; + } + super.write(frame, 0, frame.length); + super.flush(); + // The frame API owns its own decision, so leave the byte-level path's state alone. + canDropNextPacket = false; + return true; + } + + /** + * Whether the producer should now make a new frame that nothing else depends on, because the + * ones it had were discarded. + * + *

Returns true once, and only after the reader has caught back up, so the producer spends a + * key frame when it will actually get through rather than onto a backlog that is still too + * deep. Until then the reader has nothing it can decode, which is the cost of having been that + * far behind.

+ */ + public synchronized boolean consumeResyncRequest() throws IOException { + if (!resyncRequested || requireSink().available() > maxBufferedBytes) { + return false; + } + resyncRequested = false; + return true; + } + + /** Returns how far behind the reader currently is, in bytes. */ + public synchronized int bufferedBytes() throws IOException { + return requireSink().available(); + } + + /** + * Adjusts how far behind the reader may fall before frames are dropped. + * + *

A byte count only means something next to a bit rate: the same backlog that is a fraction + * of a second of video on a fast link is several seconds of it on a slow one, and on a live + * stream that latency is the failure the dropping exists to prevent. A producer that knows its + * bit rate should set this from it rather than leave the default.

+ */ + public synchronized void setMaxBufferedBytes(int maxBufferedBytes) { + if (maxBufferedBytes <= 0) { + throw new IllegalArgumentException("Buffer limit must be positive: " + maxBufferedBytes); + } + this.maxBufferedBytes = maxBufferedBytes; + this.hardCeilingBytes = maxBufferedBytes * HARD_CEILING_MULTIPLIER; + } + + /** The backlog, in bytes, at which droppable frames start being discarded. */ + public int getMaxBufferedBytes() { + return maxBufferedBytes; + } + @Override public void write(int b) throws IOException { if (shouldDropPacket()) { @@ -56,17 +177,24 @@ public synchronized void flush() throws IOException { } private boolean shouldDropPacket() throws IOException { - PipedInputStream pipedInputStream = snk; - if (snk == null) { - throw new IOException("Missing sink"); - } + PipedInputStream pipedInputStream = requireSink(); int bytesWritten = pipedInputStream.available(); - if (canDropNextPacket && bytesWritten > MAX_BUFFER_SIZE) { + if (canDropNextPacket && bytesWritten > maxBufferedBytes) { + // Deliberately leaves the flag set, so a producer that splits one record over several + // calls drops all of them together rather than writing the tail of a dropped record. return true; } canDropNextPacket = false; return false; } -} \ No newline at end of file + + private PipedInputStream requireSink() throws IOException { + PipedInputStream sink = snk; + if (sink == null) { + throw new IOException("Missing sink"); + } + return sink; + } +} diff --git a/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoFrame.java b/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoFrame.java index 68f7b49..934ab38 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoFrame.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoFrame.java @@ -91,8 +91,17 @@ public static VideoFrame fromBytes(byte[] bytes) { ByteBuffer buffer = ByteBuffer.wrap(bytes); while (buffer.hasRemaining()) { + if (buffer.remaining() < Integer.BYTES) { + break; + } + int len = buffer.getInt(); - if (len < 1) continue; + if (len < 1) { + continue; + } + if (len > buffer.remaining()) { + break; + } byte frameType = buffer.get(); byte[] data = new byte[len - 1]; diff --git a/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoPlayer.java b/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoPlayer.java index 6b54553..16b18c2 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoPlayer.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoPlayer.java @@ -16,6 +16,7 @@ import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicBoolean; import static android.media.MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED; import static android.media.MediaCodec.INFO_OUTPUT_FORMAT_CHANGED; @@ -59,9 +60,13 @@ public class VideoPlayer { * will shut down. */ private volatile boolean mIsAlive; + /** Ensures the input stream is closed exactly once. */ + private final AtomicBoolean mStopped = new AtomicBoolean(); + /** Ensures the decoder output surface is released only once. */ + private final AtomicBoolean mSurfaceReleased = new AtomicBoolean(); /** The background thread playing video for us. */ - private Thread mThread; + private volatile Thread mThread; /** * A simple audio player. @@ -87,8 +92,8 @@ public boolean isPlaying() { } /** Starts playing the stream. */ - public void start() { - if (mThread != null) { + public synchronized void start() { + if (mThread != null || mStopped.get()) { Log.w(TAG, "VideoPlayer cannot be started more than once"); return; } @@ -179,15 +184,20 @@ public void run() { mThread.start(); } - private void closeDecoder() { + private synchronized void closeDecoder() { MediaCodec decoder = mDecoder; + mDecoder = null; if (decoder != null) { try { decoder.stop(); } catch (IllegalStateException e) { Log.e(TAG, "Exception with playing video stream", e); } - decoder.release(); + try { + decoder.release(); + } catch (IllegalStateException e) { + Log.e(TAG, "Failed to release video decoder", e); + } } } @@ -269,26 +279,29 @@ private void readFully(byte[] buffer) throws IOException { private void stopInternal() { mIsAlive = false; - try { - mInputStream.close(); - } catch (IOException e) { - Log.e(TAG, "Failed to close video input stream", e); + if (mStopped.compareAndSet(false, true)) { + try { + mInputStream.close(); + } catch (IOException e) { + Log.e(TAG, "Failed to close video input stream", e); + } + Log.d(TAG, "Stopped playing video"); + } + if (mSurfaceReleased.compareAndSet(false, true)) { + mSurface.release(); } - mSurface.release(); closeDecoder(); - Log.d(TAG, "Stopped playing video"); } /** Stops playing the stream. */ public void stop() { - if (mThread == null) { - Log.w(TAG, "VideoPlayer not started"); + stopInternal(); + Thread thread = mThread; + if (thread == null || thread == Thread.currentThread()) { return; } - - stopInternal(); try { - mThread.join(300); + thread.join(300); } catch (InterruptedException e) { Log.e(TAG, "Interrupted while joining VideoPlayer thread", e); Thread.currentThread().interrupt(); diff --git a/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoRecorder.java b/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoRecorder.java index 17151be..361298a 100644 --- a/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoRecorder.java +++ b/camera-view/src/main/java/com/xlythe/view/camera/stream/VideoRecorder.java @@ -6,8 +6,10 @@ import android.media.MediaCodecList; import android.media.MediaFormat; import android.os.Build; +import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.util.Log; +import android.util.Size; import android.view.Surface; import androidx.annotation.IntRange; @@ -20,11 +22,18 @@ import com.google.common.util.concurrent.SettableFuture; import com.xlythe.view.camera.CameraView; +import static com.xlythe.view.camera.ICameraModule.DEBUG; + import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import java.util.Objects; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import static android.media.MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED; import static android.media.MediaCodec.INFO_OUTPUT_FORMAT_CHANGED; @@ -46,14 +55,23 @@ public class VideoRecorder { private static final int DEFAULT_FRAME_RATE = 15; // 15fps private static final int DEFAULT_IFRAME_INTERVAL = 10; // 10 seconds between I-frames + /** How far behind the reader may fall, as a duration of video, before frames are dropped. */ + private static final long TARGET_BACKLOG_MILLIS = 250; + /** Floor for the backlog budget, so a very low bit rate still leaves room for a frame. */ + private static final int MIN_BACKLOG_BYTES = 8 * 1024; + /** Ceiling for the backlog budget, so a very high bit rate does not buffer without limit. */ + private static final int MAX_BACKLOG_BYTES = 512 * 1024; + private static final int INFO_SUCCESS = 0; private static final int NO_TIMEOUT = -1; + /** Maximum time allowed for the camera/encoder surface handshake. */ + private static final long SURFACE_TIMEOUT_SECONDS = 10; /** The stream to write to. */ private final OutputStream mOutputStream; /** The encoder that writes bytes into the OutputStream. */ - @Nullable private volatile MediaCodec mEncoder; + private final AtomicReference mEncoder = new AtomicReference<>(); /** Draws on our surface. */ private final Canvas mCanvas; @@ -67,14 +85,20 @@ public class VideoRecorder { /** The iframe interval, in bits per second. */ private int mIFrameInterval = DEFAULT_IFRAME_INTERVAL; - /** - * If true, the background thread will continue to loop and record video. Once false, the thread - * will shut down. - */ - private volatile boolean mIsAlive; + /** The largest frame to encode, or null to follow whatever the preview is using. */ + @Nullable private volatile Size mMaxSize; + /** Whether the background thread should continue recording video. */ + private final AtomicBoolean mIsAlive = new AtomicBoolean(); + /** Ensures the output stream is closed exactly once. */ + private final AtomicBoolean mStopped = new AtomicBoolean(); /** The background thread recording video for us. */ - private Thread mThread; + private final AtomicReference mThread = new AtomicReference<>(); + + /** Frames discarded because the reader fell behind. */ + private final AtomicLong mDroppedFrames = new AtomicLong(); + /** Surface provider currently attached to the camera backend. */ + private final AtomicReference mSurfaceProvider = new AtomicReference<>(); /** * A simple video recorder. @@ -126,21 +150,42 @@ public int getIFrameInterval() { return mIFrameInterval; } + /** + * Caps the resolution this stream encodes, independent of what the preview shows. + * + *

Set this when the stream leaves the device over a link that cannot carry the preview's + * resolution. The backend picks the closest size its camera supports within the bound, so the + * stream is usually smaller than asked and never larger. Null follows the preview.

+ */ + public void setMaxSize(@Nullable Size maxSize) { + if (maxSize != null && (maxSize.getWidth() <= 0 || maxSize.getHeight() <= 0)) { + throw new IllegalArgumentException("Stream dimensions must be positive: " + maxSize); + } + mMaxSize = maxSize; + } + + /** The resolution cap for this stream, or null when it follows the preview. */ + @Nullable + public Size getMaxSize() { + return mMaxSize; + } + /** @return True if actively recording. False otherwise. */ public boolean isRecording() { - return mIsAlive; + return mIsAlive.get(); } /** Starts recording video. */ @RequiresPermission(Manifest.permission.CAMERA) - public void start() { - if (isRecording()) { + public synchronized void start() { + if (mThread.get() != null || mStopped.get()) { Log.w(TAG, "VideoRecorder is already running"); return; } - mIsAlive = true; - mThread = + mIsAlive.set(true); + applyBacklogBudget(); + Thread thread = new Thread() { @RequiresPermission(Manifest.permission.CAMERA) @Override @@ -154,24 +199,41 @@ public void run() { MediaCodecInfo codecInfo = selectCodec(MIME_TYPE); if (codecInfo == null) { Log.e(TAG, "Unable to find an appropriate codec for " + MIME_TYPE); + stopInternal(); return; } SettableFuture requestedSizeFuture = SettableFuture.create(); SettableFuture providedSurface = SettableFuture.create(); - SurfaceProvider surfaceProvider = (width, height, orientation, flipped) -> { - requestedSizeFuture.set(new CameraMetadata(width, height, orientation, flipped)); - try { - return providedSurface.get(); - } catch (ExecutionException | InterruptedException e) { - throw new RuntimeException(e); + SurfaceProvider surfaceProvider = new SurfaceProvider() { + @Override + public Surface getSurface(int width, int height, int orientation, boolean flipped) { + requestedSizeFuture.set(new CameraMetadata(width, height, orientation, flipped)); + try { + return providedSurface.get(SURFACE_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (ExecutionException | InterruptedException | TimeoutException e) { + throw new RuntimeException(e); + } + } + + @Nullable + @Override + public Size getMaxSize() { + return VideoRecorder.this.getMaxSize(); } }; - mCanvas.attachSurface(surfaceProvider); + synchronized (VideoRecorder.this) { + if (!isRecording()) { + stopInternal(); + return; + } + mSurfaceProvider.set(surfaceProvider); + mCanvas.attachSurface(surfaceProvider); + } Surface surface = null; try { - CameraMetadata metadata = Objects.requireNonNull(requestedSizeFuture.get()); + CameraMetadata metadata = Objects.requireNonNull(requestedSizeFuture.get(SURFACE_TIMEOUT_SECONDS, TimeUnit.SECONDS)); MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, metadata.getWidth(), metadata.getHeight()); // Failing to specify some of these can cause the MediaCodec configure() call to @@ -194,7 +256,7 @@ public void run() { getIFrameInterval()); MediaCodec encoder = MediaCodec.createByCodecName(codecInfo.getName()); - mEncoder = encoder; + mEncoder.set(encoder); encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); surface = encoder.createInputSurface(); providedSurface.set(surface); @@ -222,6 +284,7 @@ public void run() { encodedData.position(info.offset); write(data, info.presentationTimeUs, info.flags); encoder.releaseOutputBuffer(index, false); + requestSyncFrameIfNeeded(encoder); break; case INFO_TRY_AGAIN_LATER: Log.d(TAG, "Video not ready yet. Trying again later."); @@ -237,29 +300,44 @@ public void run() { } encoder.signalEndOfInputStream(); - } catch (IOException | IllegalArgumentException | IllegalStateException | InterruptedException | ExecutionException e) { + } catch (IOException | IllegalArgumentException | IllegalStateException | InterruptedException | ExecutionException | TimeoutException e) { Log.e(TAG, "Exception with recording video stream", e); } finally { + detachSurfaceProvider(); stopInternal(); if (surface != null) { - mCanvas.detachSurface(surfaceProvider); surface.release(); } } } }; - mThread.start(); + mThread.set(thread); + thread.start(); } - private void closeEncoder() { - MediaCodec encoder = mEncoder; + private void detachSurfaceProvider() { + SurfaceProvider surfaceProvider = mSurfaceProvider.getAndSet(null); + if (surfaceProvider == null) return; + try { + mCanvas.detachSurface(surfaceProvider); + } catch (RuntimeException error) { + Log.w(TAG, "Unable to detach video stream surface", error); + } + } + + private synchronized void closeEncoder() { + MediaCodec encoder = mEncoder.getAndSet(null); if (encoder != null) { try { encoder.stop(); } catch (IllegalStateException e) { Log.e(TAG, "Exception with recording video stream", e); } - encoder.release(); + try { + encoder.release(); + } catch (IllegalStateException e) { + Log.e(TAG, "Failed to release video encoder", e); + } } } @@ -289,9 +367,8 @@ private void write(int width, .build() .asBytes(); - mOutputStream.write(Ints.toByteArray(frame.length)); - mOutputStream.write(frame); - mOutputStream.flush(); + // The header describes every frame that follows, so it is never droppable. + writeFrame(frame, false); } private void write(byte[] data, long presentationTimeUs, int flags) throws IOException { @@ -302,26 +379,140 @@ private void write(byte[] data, long presentationTimeUs, int flags) throws IOExc .build() .asBytes(); - mOutputStream.write(Ints.toByteArray(frame.length)); - mOutputStream.write(frame); + writeFrame(frame, isDroppable(flags)); + } + + /** + * Hands one frame to the output stream. + * + *

On a lossy stream the length prefix and the payload have to be discarded together, so they + * go out as a single frame rather than as two writes: dropping only one of them would leave the + * reader looking for a length in the middle of a payload, and the format carries no sentinel it + * could resynchronize on.

+ */ + private void writeFrame(byte[] frame, boolean droppable) throws IOException { + byte[] prefixed = new byte[Integer.BYTES + frame.length]; + byte[] length = Ints.toByteArray(frame.length); + System.arraycopy(length, 0, prefixed, 0, length.length); + System.arraycopy(frame, 0, prefixed, length.length, frame.length); + + if (mOutputStream instanceof LossyPipedOutputStream) { + LossyPipedOutputStream lossyOutputStream = (LossyPipedOutputStream) mOutputStream; + if (!lossyOutputStream.writeFrame(prefixed, droppable)) { + long dropped = mDroppedFrames.incrementAndGet(); + if (DEBUG) { + Log.d(TAG, "Dropped a video frame to keep up with the reader. Total: " + dropped); + } + } + return; + } + + mOutputStream.write(prefixed); mOutputStream.flush(); } - private void stopInternal() { - mIsAlive = false; + /** + * Whether a frame can be discarded without harming the frames after it. + * + *

H.264 sends a key frame and then deltas against it, so every frame until the next key + * frame is decoded relative to that one. Dropping a key frame therefore breaks the picture for + * up to a whole I-frame interval rather than for a single frame, and dropping the + * codec-configuration frame that carries the SPS/PPS leaves the decoder unable to start at + * all. Only the deltas are safe to lose.

+ */ + static boolean isDroppable(int flags) { + return (flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) == 0 + && (flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0 + && (flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) == 0; + } + + /** Number of frames dropped so far because the reader could not keep up. */ + public long getDroppedFrameCount() { + return mDroppedFrames.get(); + } + + /** + * Converts a latency budget into a backlog of bytes at the given bit rate. + * + *

A fixed byte count is the wrong unit for a live stream, because the latency it represents + * depends entirely on the bit rate: 128 KiB is under a fifth of a second at 6 Mbps but four + * seconds at 256 kbps, and four seconds behind is exactly what dropping frames is meant to + * avoid. Clamped at both ends so a very low bit rate still leaves room for a frame and a very + * high one does not buffer without limit.

+ */ + static int backlogBytesFor(int bitRate, long latencyMillis) { + long bytes = (long) bitRate / 8 * latencyMillis / 1000; + return (int) Math.max(MIN_BACKLOG_BYTES, Math.min(bytes, MAX_BACKLOG_BYTES)); + } + + /** Applies the latency budget to a lossy sink, which cannot know the bit rate itself. */ + private void applyBacklogBudget() { + if (!(mOutputStream instanceof LossyPipedOutputStream)) { + return; + } + int bytes = backlogBytesFor(getBitRate(), TARGET_BACKLOG_MILLIS); + ((LossyPipedOutputStream) mOutputStream).setMaxBufferedBytes(bytes); + if (DEBUG) { + Log.d(TAG, "Dropping frames past " + bytes + " bytes of backlog at " + getBitRate() + "bps"); + } + } + + /** + * Mints a new key frame once the lossy stream has had to discard the ones it had. + * + *

Only the newest key frame matters to a reader resuming playback, so the stream throws + * reference frames away rather than queueing them when it is hopelessly behind. That would + * otherwise leave the reader with nothing decodable until the next scheduled one, up to a whole + * I-frame interval away and ten seconds by default. Asking the encoder for one closes that gap, + * and means a long I-frame interval stays affordable for the bandwidth it saves.

+ */ + private void requestSyncFrameIfNeeded(MediaCodec encoder) { + if (!(mOutputStream instanceof LossyPipedOutputStream)) { + return; + } + try { + if (!((LossyPipedOutputStream) mOutputStream).consumeResyncRequest()) { + return; + } + } catch (IOException error) { + return; + } + + Bundle parameters = new Bundle(); + parameters.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0); try { - mOutputStream.close(); - } catch (IOException e) { - Log.e(TAG, "Failed to close video output stream", e); + encoder.setParameters(parameters); + if (DEBUG) { + Log.d(TAG, "Requested a key frame to resume a stream that fell too far behind"); + } + } catch (IllegalStateException error) { + Log.w(TAG, "Unable to request a key frame", error); + } + } + + private void stopInternal() { + mIsAlive.set(false); + if (mStopped.compareAndSet(false, true)) { + try { + mOutputStream.close(); + } catch (IOException e) { + Log.e(TAG, "Failed to close video output stream", e); + } } closeEncoder(); } /** Stops recording video. */ - public void stop() { + public synchronized void stop() { + detachSurfaceProvider(); stopInternal(); + Thread thread = mThread.get(); + if (thread == null || thread == Thread.currentThread()) { + return; + } try { - mThread.join(300); + thread.interrupt(); + thread.join(300); } catch (InterruptedException e) { Log.e(TAG, "Interrupted while joining VideoRecorder thread", e); Thread.currentThread().interrupt(); @@ -358,6 +549,19 @@ public interface Canvas { public interface SurfaceProvider { Surface getSurface(int width, int height, int orientation, boolean flipped); + + /** + * The largest frame this stream wants, or null to follow the preview. + * + *

A backend asks before it picks the resolution it will render into, so a caller sending + * the stream over a link that cannot carry the preview can ask for less. The backend chooses + * the closest size its camera supports within this bound, so the result is usually smaller + * than the value given and never larger.

+ */ + @Nullable + default Size getMaxSize() { + return null; + } } private static class CameraMetadata { From 8271658c7c9d9fdc67edd56c17071493f4fc6bd6 Mon Sep 17 00:00:00 2001 From: Xlythe Date: Wed, 25 Nov 2026 01:18:47 -0500 Subject: [PATCH 06/10] Add a Wear companion to the sample, and save where Android expects The phone streams its camera to the watch and the watch's button asks the phone for a picture, which comes back as a file. None of it is in the library, and that is the finding: the watch reads the stream with the same VideoView.setStream the phone sample already uses on a local pipe, and the phone sends it with stream parameters that were already public. What is left over is transport, and transport is a sample's job. What does need saying is the numbers. A Data Layer channel prefers Bluetooth and only falls back to Wi-Fi when there is no Bluetooth at all, so the preview is asked for at 480p and a megabit rather than at whatever the camera would like to send, with a key frame every second because a stream can only be joined at a key frame and the watch should not wait seconds for a picture. The sample also saved its captures into its own cache directory, where nothing else on the device can see them. They go through MediaStore on API 29 and up and into the public directories below it, with the broadcast older Android needs and a media scan for the versions in between - and the sample builds at 23 under the core flag, so that older path is compiled rather than claimed. Co-Authored-By: Claude Opus 5 --- app-compose/build.gradle | 34 +-- .../com/xlythe/sample/camera/MainActivity.kt | 3 + .../src/main/res/values-v31/themes.xml | 7 + app-compose/src/main/res/values/themes.xml | 2 - .../xlythe/sample/camera/MainActivityTest.kt | 2 +- app-wear/.gitignore | 1 + app-wear/build.gradle | 32 ++ app-wear/src/main/AndroidManifest.xml | 29 ++ .../sample/camera/wear/MainActivity.java | 220 ++++++++++++++ .../sample/camera/wear/WearProtocol.java | 52 ++++ .../src/main/res/layout/activity_main.xml | 44 +++ app-wear/src/main/res/values/strings.xml | 14 + app/build.gradle | 40 ++- app/src/main/AndroidManifest.xml | 5 +- .../xlythe/sample/camera/CaptureSaver.java | 205 +++++++++++++ .../xlythe/sample/camera/MainFragment.java | 99 +----- .../sample/camera/ResizingFragment.java | 96 +----- .../xlythe/sample/camera/StreamFragment.java | 97 +----- .../xlythe/sample/camera/WearFragment.java | 285 ++++++++++++++++++ .../xlythe/sample/camera/WearProtocol.java | 52 ++++ app/src/main/res/layout/fragment_wear.xml | 69 +++++ app/src/main/res/menu/nav.xml | 4 + app/src/main/res/navigation/graph.xml | 6 + app/src/main/res/values-v31/styles.xml | 12 + app/src/main/res/values/strings.xml | 6 + app/src/main/res/values/styles.xml | 2 - app/src/main/res/values/wear.xml | 11 + .../sample/camera/MainActivityTest.java | 2 +- 28 files changed, 1134 insertions(+), 297 deletions(-) create mode 100644 app-compose/src/main/res/values-v31/themes.xml create mode 100644 app-wear/.gitignore create mode 100644 app-wear/build.gradle create mode 100644 app-wear/src/main/AndroidManifest.xml create mode 100644 app-wear/src/main/java/com/xlythe/sample/camera/wear/MainActivity.java create mode 100644 app-wear/src/main/java/com/xlythe/sample/camera/wear/WearProtocol.java create mode 100644 app-wear/src/main/res/layout/activity_main.xml create mode 100644 app-wear/src/main/res/values/strings.xml create mode 100644 app/src/main/java/com/xlythe/sample/camera/CaptureSaver.java create mode 100644 app/src/main/java/com/xlythe/sample/camera/WearFragment.java create mode 100644 app/src/main/java/com/xlythe/sample/camera/WearProtocol.java create mode 100644 app/src/main/res/layout/fragment_wear.xml create mode 100644 app/src/main/res/values-v31/styles.xml create mode 100644 app/src/main/res/values/wear.xml diff --git a/app-compose/build.gradle b/app-compose/build.gradle index 809c2a2..aa80c1c 100644 --- a/app-compose/build.gradle +++ b/app-compose/build.gradle @@ -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 { @@ -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 @@ -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' diff --git a/app-compose/src/main/java/com/xlythe/sample/camera/MainActivity.kt b/app-compose/src/main/java/com/xlythe/sample/camera/MainActivity.kt index 0969f2e..0cc6518 100644 --- a/app-compose/src/main/java/com/xlythe/sample/camera/MainActivity.kt +++ b/app-compose/src/main/java/com/xlythe/sample/camera/MainActivity.kt @@ -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 @@ -363,6 +364,7 @@ fun StreamDemoScreen() { } } +@SuppressLint("MissingPermission") @Composable fun ResizingDemoScreen() { val cameraController = remember { mutableStateOf(null) } @@ -417,6 +419,7 @@ fun ResizingDemoScreen() { } } +@SuppressLint("MissingPermission") @Composable fun QrCodeDemoScreen() { val context = LocalContext.current diff --git a/app-compose/src/main/res/values-v31/themes.xml b/app-compose/src/main/res/values-v31/themes.xml new file mode 100644 index 0000000..9eefc1a --- /dev/null +++ b/app-compose/src/main/res/values-v31/themes.xml @@ -0,0 +1,7 @@ + + + \ No newline at end of file diff --git a/app-compose/src/main/res/values/themes.xml b/app-compose/src/main/res/values/themes.xml index 0464542..667ec8c 100644 --- a/app-compose/src/main/res/values/themes.xml +++ b/app-compose/src/main/res/values/themes.xml @@ -3,7 +3,5 @@
\ No newline at end of file diff --git a/app-compose/src/test/java/com/xlythe/sample/camera/MainActivityTest.kt b/app-compose/src/test/java/com/xlythe/sample/camera/MainActivityTest.kt index 0dd57f9..d8a1917 100644 --- a/app-compose/src/test/java/com/xlythe/sample/camera/MainActivityTest.kt +++ b/app-compose/src/test/java/com/xlythe/sample/camera/MainActivityTest.kt @@ -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 diff --git a/app-wear/.gitignore b/app-wear/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app-wear/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app-wear/build.gradle b/app-wear/build.gradle new file mode 100644 index 0000000..dfcb542 --- /dev/null +++ b/app-wear/build.gradle @@ -0,0 +1,32 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 37 + enableKotlin = false + + defaultConfig { + // The Data Layer pairs a watch app with a phone app by application id and signature, so + // this has to be the id of the phone sample rather than one of its own. + applicationId "com.xlythe.sample.camera" + minSdkVersion 30 + targetSdkVersion 37 + versionCode 1 + versionName "1.0.0" + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + lint { + abortOnError = true + checkReleaseBuilds = true + } + namespace = 'com.xlythe.sample.camera.wear' +} + +dependencies { + // Only the pieces that read a stream and show a picture; the watch never opens a camera. + implementation project(':camera-view') + implementation 'com.google.android.gms:play-services-wearable:19.0.0' + implementation 'androidx.appcompat:appcompat:1.7.1' +} diff --git a/app-wear/src/main/AndroidManifest.xml b/app-wear/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2fbd396 --- /dev/null +++ b/app-wear/src/main/AndroidManifest.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/app-wear/src/main/java/com/xlythe/sample/camera/wear/MainActivity.java b/app-wear/src/main/java/com/xlythe/sample/camera/wear/MainActivity.java new file mode 100644 index 0000000..1e51d0c --- /dev/null +++ b/app-wear/src/main/java/com/xlythe/sample/camera/wear/MainActivity.java @@ -0,0 +1,220 @@ +package com.xlythe.sample.camera.wear; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; + +import com.google.android.gms.wearable.CapabilityClient; +import com.google.android.gms.wearable.ChannelClient; +import com.google.android.gms.wearable.Node; +import com.google.android.gms.wearable.Wearable; +import com.xlythe.view.camera.VideoStream; +import com.xlythe.view.camera.VideoView; + +import java.io.File; +import java.util.Set; +import java.util.concurrent.Executors; + +/** + * The watch end of the companion sample: the phone's camera on your wrist, and a shutter button. + * + *

Nothing here opens a camera. The phone does that, and CameraView's own streaming encodes the + * preview; all the watch does is hand the bytes coming off a Data Layer channel to a + * {@link VideoView}, which is the same thing the phone sample does with a local pipe. That is why + * none of this lives in the library: the only part that is specific to a watch is the transport. + *

+ */ +public class MainActivity extends AppCompatActivity { + private static final String TAG = "CameraViewWear"; + + /** Declared by the phone app in wear.xml, and how the watch finds it. */ + private static final String CAPABILITY_PHONE_CAMERA = "camera_view_sample"; + + private VideoView mPreview; + private ImageView mPicture; + private Button mShutter; + private TextView mStatus; + + @Nullable private Node mPhone; + @Nullable private VideoStream mStream; + + private final ChannelClient.ChannelCallback mChannelCallback = + new ChannelClient.ChannelCallback() { + @Override + public void onChannelOpened(@NonNull ChannelClient.Channel channel) { + if (WearProtocol.PATH_PREVIEW.equals(channel.getPath())) { + showPreview(channel); + } else if (WearProtocol.PATH_PICTURE.equals(channel.getPath())) { + showPicture(channel); + } + } + + @Override + public void onChannelClosed(@NonNull ChannelClient.Channel channel, + int closeReason, int appSpecificErrorCode) { + if (WearProtocol.PATH_PREVIEW.equals(channel.getPath())) { + runOnUiThread(() -> setStatus(R.string.status_preview_ended)); + } + } + }; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + mPreview = findViewById(R.id.preview); + mPicture = findViewById(R.id.picture); + mShutter = findViewById(R.id.shutter); + mStatus = findViewById(R.id.status); + + mShutter.setOnClickListener(view -> takePicture()); + mPicture.setOnClickListener(view -> mPicture.setVisibility(View.GONE)); + } + + @Override + protected void onStart() { + super.onStart(); + Wearable.getChannelClient(this).registerChannelCallback(mChannelCallback); + findPhone(); + } + + @Override + protected void onStop() { + Wearable.getChannelClient(this).unregisterChannelCallback(mChannelCallback); + tell(WearProtocol.PATH_STOP_PREVIEW); + closeStream(); + super.onStop(); + } + + /** + * Finds the phone by the capability it advertises rather than by picking a connected node. + * + *

A watch can be connected to more than one thing, and only the node running the phone + * half of this sample can answer.

+ */ + private void findPhone() { + setStatus(R.string.status_looking_for_phone); + Wearable.getCapabilityClient(this) + .getCapability(CAPABILITY_PHONE_CAMERA, CapabilityClient.FILTER_REACHABLE) + .addOnSuccessListener(this, info -> { + Set nodes = info.getNodes(); + mPhone = nodes.isEmpty() ? null : nodes.iterator().next(); + if (mPhone == null) { + setStatus(R.string.status_no_phone); + mShutter.setEnabled(false); + return; + } + mShutter.setEnabled(true); + setStatus(R.string.status_asking_for_preview); + tell(WearProtocol.PATH_START_PREVIEW); + }) + .addOnFailureListener(this, error -> { + Log.w(TAG, "Could not look for the phone", error); + setStatus(R.string.status_no_phone); + }); + } + + private void takePicture() { + if (mPhone == null) { + findPhone(); + return; + } + setStatus(R.string.status_capturing); + tell(WearProtocol.PATH_TAKE_PICTURE); + } + + /** Sends a one-shot message, which is all the watch ever needs to send. */ + private void tell(String path) { + Node phone = mPhone; + if (phone == null) { + return; + } + Wearable.getMessageClient(this) + .sendMessage(phone.getId(), path, new byte[0]) + .addOnFailureListener(error -> Log.w(TAG, "Could not send " + path, error)); + } + + /** + * Plays the phone's preview. + * + *

The channel's input stream is H.264 exactly as CameraView's encoder produced it, which is + * what VideoView.setStream expects, so there is nothing to decode here.

+ */ + private void showPreview(ChannelClient.Channel channel) { + ChannelClient channels = Wearable.getChannelClient(this); + channels.getInputStream(channel).addOnSuccessListener(this, inputStream -> { + closeStream(); + mStream = new VideoStream.Builder().withVideoStream(inputStream).build(); + mPreview.setStream(mStream); + mPreview.play(); + setStatus(R.string.status_streaming); + }).addOnFailureListener(this, error -> { + Log.w(TAG, "Could not read the preview", error); + setStatus(R.string.status_preview_failed); + }); + } + + /** + * Shows a picture the phone just took. + * + *

Received to a file rather than read from the stream, because a full-size JPEG over a + * watch link takes long enough that holding it in memory while it arrives is the wrong + * trade.

+ */ + private void showPicture(ChannelClient.Channel channel) { + File file = new File(getCacheDir(), "from-phone.jpg"); + Wearable.getChannelClient(this) + .receiveFile(channel, android.net.Uri.fromFile(file), false /* append */) + .addOnSuccessListener(this, ignored -> decode(file)) + .addOnFailureListener(this, error -> { + Log.w(TAG, "Could not receive the picture", error); + setStatus(R.string.status_capture_failed); + }); + } + + private void decode(File file) { + Executors.newSingleThreadExecutor().execute(() -> { + // Decoded small: a watch screen is a few hundred pixels across and the phone's + // picture is thousands. + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = 4; + Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); + runOnUiThread(() -> { + if (bitmap == null) { + setStatus(R.string.status_capture_failed); + return; + } + mPicture.setImageBitmap(bitmap); + mPicture.setVisibility(View.VISIBLE); + setStatus(R.string.status_streaming); + }); + }); + } + + private void closeStream() { + VideoStream stream = mStream; + mStream = null; + if (stream == null) { + return; + } + try { + stream.close(); + } catch (RuntimeException error) { + Log.w(TAG, "Could not close the preview stream", error); + } + } + + private void setStatus(int message) { + mStatus.setText(message); + } +} diff --git a/app-wear/src/main/java/com/xlythe/sample/camera/wear/WearProtocol.java b/app-wear/src/main/java/com/xlythe/sample/camera/wear/WearProtocol.java new file mode 100644 index 0000000..65cdacd --- /dev/null +++ b/app-wear/src/main/java/com/xlythe/sample/camera/wear/WearProtocol.java @@ -0,0 +1,52 @@ +package com.xlythe.sample.camera.wear; + +import android.util.Size; + +/** + * What the phone and the watch say to each other. + * + *

Mirrored in the phone module on purpose: they are separate applications that happen to live + * in one repository, and a shared Gradle module for a handful of constants would be more + * machinery than it saves. A change has to be made in both copies.

+ * + *

The split between messages and channels is the Data Layer's own: a message is a small + * one-shot notification, and a channel is a socket, which is what a preview or a photo needs. + * What a channel is not is fast. The Data Layer prefers Bluetooth and only uses Wi-Fi when there + * is no Bluetooth at all, so a realistic budget is a couple of megabits - which is why the + * preview is asked for at a size and bit rate a watch link can carry rather than whatever the + * phone's camera would like to send.

+ */ +final class WearProtocol { + /** The watch asking the phone to start sending a preview. */ + static final String PATH_START_PREVIEW = "/camera-view/start-preview"; + + /** The watch asking the phone to stop. */ + static final String PATH_STOP_PREVIEW = "/camera-view/stop-preview"; + + /** The watch asking the phone to take a picture and send it back. */ + static final String PATH_TAKE_PICTURE = "/camera-view/take-picture"; + + /** The channel the phone streams the preview over. */ + static final String PATH_PREVIEW = "/camera-view/preview"; + + /** The channel the phone sends a captured picture over. */ + static final String PATH_PICTURE = "/camera-view/picture"; + + /** + * The preview the watch asks for. + * + *

480p at a megabit is about what a Bluetooth link will carry without the stream falling + * behind, and a watch screen cannot show more than that anyway. The key frame interval is the + * part that is easy to get wrong: a stream can only be joined at a key frame, so a long + * interval means the watch stares at black for that long after it connects.

+ */ + static final Size PREVIEW_SIZE = new Size(640, 480); + + static final int PREVIEW_BIT_RATE = 1_000_000; + + static final int PREVIEW_FRAME_RATE = 20; + + static final int PREVIEW_KEY_FRAME_INTERVAL_SECONDS = 1; + + private WearProtocol() {} +} diff --git a/app-wear/src/main/res/layout/activity_main.xml b/app-wear/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..00113ef --- /dev/null +++ b/app-wear/src/main/res/layout/activity_main.xml @@ -0,0 +1,44 @@ + + + + + + + +