AGENTS.md — camera/ (':camera')
Scoped supplement. Global rules in root AGENTS.md apply. Stay inside camera/ + allowed shared modules. Do not root-scan.
Install: ./install camera (dev by default).
- Gradle: :camera / dir: camera/
- Package roots present: ui, domain, platform, data, sync
- Entry files: MainActivity.kt (sole launcher; routes watches to WearMainActivity), Route.kt (
Route.Camera/Route.Settings), ui/WearMainActivity.kt - Deps: :library:ml, :library:wearlink, :library:log, Wear Compose material
- Metadata: metadata_data/camera.md (present)
- Rust: yes / screenshotTest: yes (phone + large-tablet preview-rendered over a screenshot-only fake viewfinder scene)
Overview
Purpose: The most featureful open-source camera app — usable as the system camera and from the lockscreen. 100% offline. Key features:
- Photo + video capture on a direct Camera2 implementation (
platform/camera2/driver, sessions, extension and high-speed sessions) with per-mode sessions: single, portrait, night, slo-mo, video - Panorama stitching + night-burst alignment in the native Rust
camera_stitchengine - Photo-sphere capture: guide waypoints spaced from the active lens's measured FOV at 40% overlap (rows reach the poles), heading/pitch from the fused rotation-vector sensor (gyro dead reckoning, then accelerometer+magnetometer, as fallbacks), stitch seeded with the HAL focal length, and output rendered onto a full 360×180 equirect canvas whose GPano XMP describes that sphere (Google Photos renders it as a sphere)
- Portrait mode with on-device segmentation (MediaPipe selfie + MODNet matting on a Vulkan compute runtime,
.mamlassets) - QR/barcode scanning (zxing) and optional GPS geotagging written into EXIF
Architecture / data-flow: Single-screen ui/CameraScreen + platform/CameraViewModel over per-mode platform/ session objects on the platform/camera2/ driver; domain/ holds pure lens-selection logic, platform/ capability queries; heavy work (stitch, night align, bokeh) goes through Rust JNI (platform/StitchNative) and lands in MediaStore via data/MediaStoreSaver. onCreateBeforeContent only honors the ACTION_IMAGE_CAPTURE capture-for-result intent; Content() sits behind a camera+mic permission gate. Lens selection: platform/LensSelector.enumerateLenses feeds domain/LensDiscovery with every top-level camera id plus each logical camera's getPhysicalCameraIds() sub-cameras (validated against their stream-configuration maps); the Camera2 preview always opens the facing's logical camera, so lens stops (sub-1x / tele included) are reached through the single continuous ui/ZoomBar row and pinch zoom, which apply the ratio to that session rather than opening a sub-camera id; live scrub/pinch moves go through setZoomRatioLive (no persistence, no lens sync), and only the committed final ratio (chip tap, scrub/pinch release, lens/Wear selection, via setZoomRatio) landing on a lens's nominal ratio syncs selectedLens to that lens (startup persistence + night-detection reset, via syncSelectedLensToZoomStop), while a ratio between stops leaves the selection alone. Entry points + reading order: MainActivity.kt → Route.kt (Route.Camera/Settings) → ui/CameraScreen.kt → platform/CameraViewModel.kt → platform/CameraSessions.kt → platform/PanoramaEngine.kt / NightCaptureEngine.kt.
One APK, two form factors (phone + watch)
This module is the single Camera APK for phones and watches: same applicationId = "com.vayunmathur.camera" and signing on both. The manifest deliberately declares no android.hardware.type.watch feature (required=true would block phones; required=false is disallowed for this feature), declares the camera feature not-required (a watch has no camera; the watch experience is a remote viewfinder streamed from the phone), and carries com.google.android.wearable.standalone=false; distribution is sideload/F-Droid, not Play's watch channel, so the APK installs on phones and watches alike. platform/FormFactor.kt reads PackageManager.FEATURE_WATCH at runtime: MainActivity (the sole launcher entry) forwards watches to ui/WearMainActivity before any phone state (CameraViewModel, phone wear sync, permission gate) is touched; phones get the camera UI. MainActivity's forward is the form-factor gate for activities: the phone-side platform/WearCameraSync starts only on the phone path, and the watch-side sync/WearLinkBridge is created only by ui/WearMainActivity (exported=false, no launcher filter). Two manifest broadcast receivers (both exported only under the Watch conduit's signature permission) serve the phone path: sync/ConduitSyncTriggerReceiver starts the sync so queued conduit ops replay, and sync/OpenOnPhoneReceiver launches MainActivity for a direct open-on-phone broadcast.
Wear sync (Watch conduit client)
Protocol: shared wire types live in :library:wearlink at com.vayunmathur.library.wearlink.camera.WearCameraProtocol; the golden-JSON tests in this module pin the shared code's wire format.
- Mirrored state + thumbnail: conduit data items (
/camera/state,/camera/thumbnail, phone -> watch); the state carriesphoneOpen(MainActivity exists on the phone) and the phone's current mode - Control ops + live viewfinder: conduit messages (
/camera/opwatch -> phone,/camera/preview-framephone -> watch);OPEN_ON_PHONEon/camera/opis the open-on-phone handoff (phone launchesMainActivityunless already open), capture ops are executed by the phone in its current mode - Transport: Watch conduit client — phone side
platform/WearCameraSync.ktand watch sidesync/WearLinkBridge.ktboth useWearLinkClientNode(Messenger to the Watch app'swatch_conduitservice, appIdcamera); this app owns no RFCOMM link and holds no Bluetooth permission for this channel, so neither entry activity prompts for Bluetooth. With the Watch app absent the node reportsNotInstalled/Unavailableand the sync stays idle; state + thumbnail republish on conduitConnected.
Watch experience (in this module)
ui/WearMainActivity(aWearShellActivity) routesui/WearRouteover exactly two screens, driven by the mirroredphoneOpenstate plus frame liveness via the puredomain/WearWatchPresentation:OpenOnPhone(one centred filled "Open in phone" button with the phone icon while the phone Camera app is not open) andViewfinder(only the streamed viewfinder plus one small capture button, themed by the phone's mode viawearCaptureButtonSpec/wearCaptureOp; recording shows the stop theme). The viewfinder requires frames to actually arrive:data/WearCameraStorestamps the wait for the first frame and each frame's arrival, the preview request is retried while no frame is held, andwearWatchScreenfalls back toOpenOnPhonewhen no live frame has arrived withinWEAR_VIEWFINDER_FRAME_TIMEOUT_MS— there is no resting waiting state. The watch camera remote never opens a local camera and offers no other controls. Mirrored truth is in-memory only indata/WearCameraStore(no offline copy: nothing is usable without the phone).- Wire protocol (
WearCameraProtocol, WCF1 preview frames) lives in:library:wearlinkatcom.vayunmathur.library.wearlink.camera; this module'sWearCameraProtocolTestpins the golden JSON/frame bytes (including the watch store's stale-frame rules). Live viewfinder frames travel as/camera/preview-framemessages (never the bounded STREAM primitive); phone drops frames latest-only, watch drops stale sequences (a lower sequence with a newer frame timestamp is a restarted phone stream and is accepted) and clears the live frame when the link drops or streaming stops — a frozen frame is never shown as live. - Watch listing screenshots are the
group = "wear"previews insrc/screenshotTest/.../ui/WearMetadataPreviews.kt, collected by:camera:metadataintometadata_data/photos/camera/wear/; phone/tablet shots keep their buckets.
Gotchas:
- Capture code lives in
platform/(the Camera2 driver inplatform/camera2/); there is noutil/root in this module - Camera2 session reopen after a surface destroy (background/resume, size change) is serialized in
platform/camera2/: a session parks a reopen until the previous device's realonClosed(deviceclose()only initiates HAL teardown), andPreviewSurfaceBridgeforgets its pinned stream size on destroy so a newSurfaceTextureis re-pinned before configure. A device/configure failure tears the session down to CLOSED (capture session, every output and the device are closed, never leaked) so the next surface/lifecycle open on the same session can succeed; bind-failure latches for every preview engine are cleared on manual retry and on each lifecycle STARTED entry (clearBindFailuresOnResume), otherwise a latched failure would keep its own preview branch uncomposed and could never re-arm - Listing screenshots are preview-rendered (
:camera:metadata): Layoutlib can't open a camera, sosrc/screenshotTestdraws the deterministicFakeCameraPreviewscene behind the real top bar/grid/shutter/mode controls.Route.Settingsis captured from the statelessCameraSettingsContentslice inui/SettingsPage.ktwith literal fixtures. ThescreenshotFakePreviewparameter onCameraScreen/CameraPreviewSurfaceis the same seam inmain— production-default null, never passed byMainActivity, so no fake frame can appear on device - Volume keys act as the shutter, gated on the camera route being foreground; Esc/space covers desktop keyboards
.mamlmodel assets ship uncompressed (noCompress) — never compress them- Capture rotation is one decision in
domain/CaptureRotation.kt(sensor orientation from characteristics + physical display rotation + facing), consumed by stills (StillCapturePlanner), analysis frames, and video/slo-mo/Motion-Photo muxer hints. The activity is portrait-locked, so the window display rotation is always 0 and must never orient captures: the physical quadrant comes from theOrientationEventListener(fed to sessions viaCameraViewModel.setCaptureDisplayRotationDegrees); preview sizing/metering keep the window rotation. The live preview adds no rotation in its view layer: its stream texture transform (domain/PreviewTransform.computeTextureAffine) is the single preview rotation, soui/CameraPreviewSurfacenever rotates the surface with the physical quadrant. Only the ZoomBar numbers and the config-row icons rotate with that quadrant — glyph rotation only, never a second capture or preview rotation. Metadata convention: JPEG/JPEG_R keep sensor pixels + EXIF orientation (flip-carrying for mirrored raw front pixels), AVIF bakes rotation/mirror into pixels with EXIF Normal and noirot, MP4 carries only the muxer orientation hint, night/pano RGB outputs bake pixels upright. No DNG writer is wired (DngMetadataonly assembles requirements)
Key files
Root — entry + navigation
- com/vayunmathur/camera/MainActivity.kt
- com/vayunmathur/camera/Route.kt
domain/ — pure lens-selection logic
- com/vayunmathur/camera/domain/LensModel.kt
- com/vayunmathur/camera/domain/LensDiscovery.kt — offered-lens computation over pure
LensCandidates: every session-configurable camera the HAL exposes (top-level ids plus logical cameras' physical sub-cameras) is offered; a physical ultra-wide is never dropped for overlapping the logical zoom range; on logical-only devices the logical camera's zoom-ratio range synthesizes the ultra-wide (sub-1x) and telephoto (2x) stops no camera id exposes, anchored to the logical id (PhysicalLens.synthesizedFromZoomRange) - com/vayunmathur/camera/domain/LensSelectionLogic.kt
- com/vayunmathur/camera/domain/ArgbToI420Converter.kt — bulk ARGB→YUV 4:2:0 for the Motion Photo clip
- com/vayunmathur/camera/domain/MotionClipTiming.kt — per-frame clip PTS from actual ring-buffer capture timestamps (duration = captured span plus one interval; no uniform-rate clamp), consumed by
MotionPhotoEncoder - com/vayunmathur/camera/domain/MotionSaveQueue.kt — bound on Motion Photos still saving after the shutter
- com/vayunmathur/camera/domain/StillCaptureModePolicy.kt — ZSL vs MINIMIZE_LATENCY choice
- com/vayunmathur/camera/domain/CaptureRotation.kt — the one capture-rotation decision (sensor + physical display + facing) and EXIF convention
- com/vayunmathur/camera/domain/AnalysisRotation.kt — analysis-frame rotation (same formula as CaptureRotation)
- com/vayunmathur/camera/domain/PanoXmp.kt
- com/vayunmathur/camera/domain/SphereWaypoints.kt — FOV-derived photo-sphere waypoint layout + fused-orientation yaw/pitch math
- com/vayunmathur/camera/domain/MotionPhotoWriter.kt — GCamera XMP + assembly for both containers: JPEG (XMP injected, MP4 trailer) and AVIF (XMP item + MP4 trailer via the Rust mux); an AVIF still carries both a
tmapgain map and a motion clip (gain-map encode first, motion mux appends the MP4 as the EOF trailer; JPEG_R Motion Photo bytes on any gain-map failure) - com/vayunmathur/camera/domain/GainMapMath.kt — ISO 21496-1 gain-map params + encode/decode math for AVIF Ultra HDR;
StillFormatRouting.stillSaveRoutesends Ultra HDR sources under AVIF to thetmapencoder (JPEG_R bytes on any gain-map failure) - com/vayunmathur/camera/domain/StillDimensions.kt — true still dimensions parsed from the image buffer (JPEG SOF, AVIF primary
ispe, TIFF tags); every save path derives dimensions from the actual buffer so file metadata and MediaStore never record 0x0
platform/ — capability queries
- com/vayunmathur/camera/platform/CameraCapabilities.kt
- com/vayunmathur/camera/platform/WearCameraSync.kt — phone conduit client node; mirrored state/thumbnail publish, op handling, preview streaming; wire protocol
com.vayunmathur.library.wearlink.camera.WearCameraProtocol(WCF1 frames) in:library:wearlink; this module'sWearCameraProtocolTestpins the golden JSON/frame bytes - com/vayunmathur/camera/platform/LensSelector.kt
ui/ — single screen + settings + panes
- com/vayunmathur/camera/ui/CameraScreen.kt
- com/vayunmathur/camera/ui/CameraScreenState.kt
- com/vayunmathur/camera/ui/CameraScreenKit.kt
- com/vayunmathur/camera/ui/CameraScreenEffects.kt
- com/vayunmathur/camera/ui/CameraPreviewBox.kt
- com/vayunmathur/camera/ui/CameraPreviewOverlays.kt
- com/vayunmathur/camera/ui/CaptureFlashOverlay.kt
- com/vayunmathur/camera/ui/CameraOverlays.kt
- com/vayunmathur/camera/ui/CameraPanoramaOverlay.kt
- com/vayunmathur/camera/ui/CameraTopBar.kt
- com/vayunmathur/camera/ui/CameraBottomControls.kt
- com/vayunmathur/camera/ui/CameraShutterPane.kt
- com/vayunmathur/camera/ui/CameraShutterRow.kt
- com/vayunmathur/camera/ui/CameraModeBars.kt
- com/vayunmathur/camera/ui/CameraModesPane.kt
- com/vayunmathur/camera/ui/CameraSettingsBars.kt
- com/vayunmathur/camera/ui/CameraSettingsColumn.kt
- com/vayunmathur/camera/ui/CameraStatusIndicators.kt
- com/vayunmathur/camera/ui/CameraWideLayout.kt
- com/vayunmathur/camera/ui/ZoomBar.kt — the single zoom row (shown by default in
CameraSettingsColumnwhen no setting pane is selected, hidden in zoom-locked panorama/photosphere; there is no zoom entry in the config row below it): continuous relative scrub (live viasetZoomRatioLive, committed on release) + lens-stop chips, numbers rotating with device orientation. Scrub mapping is the puredomain/ZoomScrub.kt(log-scale, slop-compensated, monotonic across lens stops, chip set frozen mid-scrub) - com/vayunmathur/camera/ui/SettingsPage.kt
- com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt
platform/ — ViewModel, sessions, engines
- com/vayunmathur/camera/platform/CameraViewModel.kt
- com/vayunmathur/camera/platform/CameraViewModelActions.kt
- com/vayunmathur/camera/platform/CameraViewModelTypes.kt
- com/vayunmathur/camera/platform/CameraStartup.kt
- com/vayunmathur/camera/platform/CameraSessions.kt
- com/vayunmathur/camera/platform/CaptureOrientation.kt — pushes the physical display rotation to live sessions
- com/vayunmathur/camera/platform/CameraSingleCapture.kt
- com/vayunmathur/camera/platform/CameraPhotoCapture.kt
- com/vayunmathur/camera/platform/CameraCaptureProcessing.kt
- com/vayunmathur/camera/platform/CameraVideoRecording.kt
- com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt
- com/vayunmathur/camera/platform/Camera2SloMoGlue.kt
- com/vayunmathur/camera/platform/CameraManualControls.kt
- com/vayunmathur/camera/platform/CameraControls.kt
- com/vayunmathur/camera/platform/CameraNightMode.kt
- com/vayunmathur/camera/platform/CameraNightCapture.kt
- com/vayunmathur/camera/platform/NightCaptureEngine.kt
- com/vayunmathur/camera/platform/PanoramaEngine.kt
- com/vayunmathur/camera/platform/GpuStitcher.kt
- com/vayunmathur/camera/platform/StitchNative.kt — JNI bridge into
camera_stitch - com/vayunmathur/camera/platform/PortraitBokeh.kt
- com/vayunmathur/camera/platform/BokehAnalyzer.kt
- com/vayunmathur/camera/platform/PhotoAnalyzer.kt
- com/vayunmathur/camera/platform/MotionPhotoEncoder.kt
- com/vayunmathur/camera/platform/VideoProcessor.kt
- com/vayunmathur/camera/platform/CodecSupport.kt
- com/vayunmathur/camera/platform/GainMapExtractor.kt — extracts the HAL JPEGR gain map (
Bitmap.gainmap, API 34+) as a grayscaleGainMapFramefor the AVIFtmapmux in Rust (`src/main/rust/src/avifgainmap.rs+avifgainmapparse.rs, viaStitchNative.encodeAvifUltraHdr`)
platform/camera2/ — Camera2 driver
- com/vayunmathur/camera/platform/camera2/Camera2Driver.kt
- com/vayunmathur/camera/platform/camera2/Camera2Session.kt
- com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt
- com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt
- com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt
- com/vayunmathur/camera/platform/camera2/StillCapture.kt
- com/vayunmathur/camera/platform/camera2/StreamSelection.kt
Watch experience (ui/ + data/ + sync/)
- com/vayunmathur/camera/ui/WearMainActivity.kt — watch entry (WearShellActivity)
- com/vayunmathur/camera/ui/WearRoute.kt, WearOpenOnPhoneScreen.kt, WearViewfinderScreen.kt
- com/vayunmathur/camera/domain/WearWatchPresentation.kt — pure two-screen state machine + capture-button theme/op mapping
- com/vayunmathur/camera/sync/OpenOnPhoneReceiver.kt, ConduitSyncTriggerReceiver.kt — phone broadcast entries (open launch / sync wake)
- com/vayunmathur/camera/platform/FormFactor.kt — watch detection (
FEATURE_WATCH) - com/vayunmathur/camera/data/WearCameraStore.kt — mirrored phone state + newest preview frame/thumbnail (in-memory only)
- com/vayunmathur/camera/sync/WearLinkBridge.kt — watch conduit client node; mirrored state/thumbnail receive, preview frames, op sends
data/ — settings + saving
- com/vayunmathur/camera/data/MediaStoreSaver.kt
- com/vayunmathur/camera/data/CameraSettings.kt
- com/vayunmathur/camera/data/CameraSaveLocation.kt
- com/vayunmathur/camera/data/CameraSaveRouting.kt
Verify (this module only)
./gradlew :camera:compileDevKotlin
./gradlew :camera:lint
./gradlew :camera:checkMetadata