Repository navigation
Conversation
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
* 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 <noreply@anthropic.com>
* 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 <noreply@anthropic.com>
* 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
* test: write the Robolectric shadows the camera APIs need Almost none of this library could be tested off a device, and the reason was not the library. Robolectric ships shadows for the camera APIs that stop short of the places a camera actually does something, so the code waiting on those places waited forever - and a test that cannot reach the code is indistinguishable from code that works. Six shadows and three fakes, each filling a specific gap. A CameraManager that reports the cameras that already exist when an availability callback is registered, which is how a real one works and what camera2-pipe suspends on - without it CameraX never finished discovery and never bound, with no error to show for it. A CameraDevice and a CameraCaptureSession that can be configured and can invoke their callbacks, so a session reaches onConfigured and a recording reaches onCaptureCompleted. An ImageReader a test can hand a frame to, which is what makes the still-capture path - decode, orient, write, report - reachable at all. CamcorderProfile.getAll, the API 31 replacement that CameraX prefers and that returned null, taking the whole encoder-profile lookup down with it. And a TextureView that produces a SurfaceTexture, without which every preview in the library parks at "waiting for a surface" forever: that one shadow is what made the Compose wrapper, VideoView and the whole open-and-use lifecycle testable. They are written to be upstreamable - real contracts, not whatever made one test pass - because every one of them is a gap any Android camera library would hit. * test: cover the library, from 25% of lines to 70% Branch coverage went from 14% to 50%. More to the point, the suite now runs the code rather than its edges, and most of the fixes in this series were found by writing it. Both backends are driven against the shadowed camera service: opening, configuring a session, capturing, recording, probing preview sizes, switching lenses, and the capability queries that a camera answers differently on every device. The CameraX backend is reachable from a unit test for the first time. The streaming layer is covered on both sides of the wire - the framing, the drop policy, the backlog arithmetic, and the three ways a stream arriving off a network can be malformed. Exif's orientation algebra is stated as properties over all eight orientations rather than as a second copy of the table, which is why one wrong cell had nowhere to hide. Two kinds of test are here because a camera app fails at them rather than at any single call. Resources: every public entry point driven ten times with exact before-and-after counts of readers, threads and sessions, because anything allocated per use and not given back grows for as long as the app is open and crashes a long way from the cause. And latency as a bound rather than a measurement - with an analyzer held inside one frame while ten more arrive, the next frame it sees has to be the newest and all ten have to go back to the camera, because a queue that grows is latency that never recovers. What is not covered is stated where it would be looked for: CameraX sharing one stream between outputs needs an OpenGL context no emulator off a device provides, ML Kit needs Play services, and a prepared decoder needs a real container. Those are instrumented instead. * test: drive the paths that only exist on a real camera What is left after the unit suite is exactly what matters most: a capture that produces an actual JPEG, a recording that produces an actual file, three outputs configured at once, a detector running in the image signal processor, a stream encoding real frames. None of those can be reached off a device, so they are instrumented, against the API 30 and API 37 images the module's device matrix already names. Each test skips rather than fails where the hardware cannot do it - a device with one camera, a camera that cannot report faces, a camera that cannot hold a recording and a still together - so the suite says what it did not get to instead of going red on a thin emulator. Run with ./gradlew :camera-view:cameraMatrixGroupDebugAndroidTest. This has not been run here: the matrix's system images are not installed on this machine, and downloading them is several gigabytes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The README is how to use the library, so the new APIs are in it the way the rest are: frame analysis, face detection, the video snapshot, wide gamut, choosing a backend, the core-only build for an older minSdk, and the Wear companion. Each is a few lines and the call that does it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
onCameraOpened fired as soon as open() returned. Opening a camera is two asynchronous steps - the device opens, then a session is configured - so the callback an app enables its shutter button on arrived before there was anything to capture with, and the first tap was lost: V CameraView: Taking a picture W CameraView: Cannot take picture before Camera2 preview is ready D CameraView: Failed to take a picture Found by running the instrumented tests on a real camera, where a capture and a recording issued straight after onCameraOpened both failed. No unit test could have found it: off a device the session configures within the same looper pass, so the gap does not exist. Each backend now reports when it is genuinely usable - camera2 when its session is configured and targeted, CameraX when a use case is bound - and a backend that opens synchronously still says so immediately through isCameraReady. isOpen() means usable now, which is also what makes it a sound thing to guard a capture on. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test: run every backend against a real camera The library's whole proposition is that three implementations behave the same, and there is only one way to find out: the same scenarios against each of them on hardware. Off a device they cannot even be compared - CameraX copies a shared stream through an OpenGL processor, and the old API needs a camera that answers. 29 tests across camera2, CameraX and the legacy backend: a capture that produces a file, a recording that produces a file, frames reaching an analyzer, a stream encoding real frames, the controls answering, a lens switch, a picture taken while recording, and the camera's own face detector. All pass on an API 37 image. Three corrections came out of writing them. Two were mine: a capture awaited after the camera had been closed is a capture whose reader was abandoned, and two seconds is not long enough for an encoder behind a software-rendered surface to produce anything - a recording is seconds long, so the test is too. The third is in the library and has its own commit. A camera that cannot do something is skipped rather than failed, and the reasons are specific: an image with one camera, an emulated camera that advertises face detection without ever populating the results. A suite that went red on those would say nothing useful. With the device run merged in, coverage is 76% of lines and 58% of branches - CameraX alone goes from 52% to 73%, because that is where the code whose behaviour is the hardware lives. * test: cover the rest of the public surface on a real camera The parts an app touches most and the unit suite can only reach the edges of, because each needs something only a device has: a confirmation that holds a real preview frame, an ML Kit detector that needs Play services, an audio stream that needs a microphone, a decoder that needs a container the camera actually produced. Covers confirming and rejecting a picture, barcode scanning starting and stopping over real frames, an audio-and-video stream played back through the view that would show it, a recorded file decoded, closing and reopening a live camera, every optional control offered to hardware that accepts or declines each, and the camera surviving its activity being recreated - through the framework, so the whole save-and-restore path runs rather than the two hooks. Three of these were written wrong first, and each wrong version was instructive: confirming a picture is a View operation and belongs on the main thread, a second ActivityScenario destroys the first on the way out, and a prewarmed Recorder cannot serve a second recording - that last one was a bug in the library and is fixed with it. * test: point the device matrix at the versions that matter, and stop it lying Three corrections to the device suite, all from running it. The matrix ran API 30 and 37. Chosen from the code instead: the library branches on the platform version at ten thresholds, and an API 28 device takes the older side of the most of them - the pre-29 storage path, the pre-30 and pre-31 codec keys, the pre-33 permissions, the pre-34 colour space. An API 30 device takes none of the first two, so a matrix of 30 and 37 left that code never executed by anything. Whether a recording produced bytes is now an assumption rather than an assertion. Reporting is what the library owes and is still asserted either way, but the encoding itself is the encoder's business, and behind a software-rendered surface it is marginal: CameraX finalizes with ERROR_NO_VALID_DATA and nothing recorded, from a window that is ample on real hardware. Asserting it made the suite red for a reason that was never the library's, and - worse - made it green by luck when the machine happened to be idle. The resource tests compare against a baseline rather than against zero. Robolectric reuses a sandbox across test classes with the same configuration, so the registry of open readers is not empty on the way in, and what a leak looks like is growth across the work under test. Asserting zero passed alone and failed in the suite, which is the least useful way for a test to be wrong. Also closes an ImageReader that a re-initialized still surface would otherwise replace without handing back - found while chasing the above, and defensive rather than a demonstrated leak. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
First of four stacked PRs. Merge in order; each one's head compiles on its own, verified by building
assembleDebugand the unit-test sources at every head before any of this was pushed.This is the historical bulk — ten commits that could not be split further without breaking compilation, because the unit tests added alongside the backend work reference Robolectric shadows introduced later in the series, while those shadows' own tests exercise the backend code. The two are mutually dependent, so they travel together.
-Pcameraview.core=true), which has to come first: nothing earlier in the series has a working build configuration.Nothing here is pushed to a release. The commit messages carry the reasoning for each change.