Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / camera / AGENTS.md

AGENTS.md18.8 KiBRenderedCodeRaw
1# AGENTS.md — camera/ (':camera')
2
3> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `camera/` + allowed shared modules. Do not root-scan.
4
5_Install: ./install camera (dev by default)._
6- Gradle: :camera / dir: camera/
7- Package roots present: ui, domain, platform, data, sync
8- Entry files: MainActivity.kt (sole launcher; routes watches to WearMainActivity), Route.kt (`Route.Camera` / `Route.Settings`), ui/WearMainActivity.kt
9- Deps: :library:ml, :library:wearlink, :library:log, Wear Compose material
10- Metadata: metadata_data/camera.md (present)
11- Rust: yes / screenshotTest: yes (phone + large-tablet preview-rendered over a screenshot-only fake viewfinder scene)
12
13## Overview
14**Purpose:** The most featureful open-source camera app — usable as the system camera and from the lockscreen. 100% offline.
15**Key features:**
16- 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
17- Panorama stitching + night-burst alignment in the native Rust `camera_stitch` engine
18- 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)
19- Portrait mode with on-device segmentation (MediaPipe selfie + MODNet matting on a Vulkan compute runtime, `.maml` assets)
20- QR/barcode scanning (zxing) and optional GPS geotagging written into EXIF
21**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.
22**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.
23**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`.
24
25## One APK, two form factors (phone + watch)
26This module is the single Camera APK for phones and watches: same
27`applicationId = "com.vayunmathur.camera"` and signing on both. The manifest deliberately declares no
28`android.hardware.type.watch` feature (required=true would block
29phones; required=false is disallowed for this feature), declares the
30camera feature not-required (a watch has no camera; the watch
31experience is a remote viewfinder streamed from the phone), and
32carries `com.google.android.wearable.standalone=false`; distribution
33is sideload/F-Droid, not Play's watch channel, so the APK installs on
34phones and watches alike. `platform/FormFactor.kt` reads
35`PackageManager.FEATURE_WATCH` at runtime: `MainActivity` (the sole
36launcher entry) forwards watches to `ui/WearMainActivity` before any
37phone state (CameraViewModel, phone wear sync, permission gate) is
38touched; phones get the camera UI. `MainActivity`'s forward is the
39form-factor gate for activities: the phone-side
40`platform/WearCameraSync` starts only on the phone path, and the
41watch-side `sync/WearLinkBridge` is created only by
42`ui/WearMainActivity` (`exported=false`, no launcher filter). Two
43manifest broadcast receivers (both exported only under the Watch
44conduit's signature permission) serve the phone path:
45`sync/ConduitSyncTriggerReceiver` starts the sync so queued conduit
46ops replay, and `sync/OpenOnPhoneReceiver` launches `MainActivity`
47for a direct open-on-phone broadcast.
48
49## Wear sync (Watch conduit client)
50**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.
51- Mirrored state + thumbnail: conduit data items (`/camera/state`, `/camera/thumbnail`, phone -> watch); the state carries `phoneOpen` (MainActivity exists on the phone) and the phone's current mode
52- Control ops + live viewfinder: conduit messages (`/camera/op` watch -> phone, `/camera/preview-frame` phone -> watch); `OPEN_ON_PHONE` on `/camera/op` is the open-on-phone handoff (phone launches `MainActivity` unless already open), capture ops are executed by the phone in its current mode
53- **Transport: Watch conduit client** — phone side `platform/WearCameraSync.kt` and watch side `sync/WearLinkBridge.kt` both use `WearLinkClientNode` (Messenger to the Watch app's `watch_conduit` service, appId `camera`); 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 reports `NotInstalled`/`Unavailable` and the sync stays idle; state + thumbnail republish on conduit `Connected`.
54
55## Watch experience (in this module)
56- `ui/WearMainActivity` (a `WearShellActivity`) routes `ui/WearRoute` over exactly two screens, driven by the mirrored `phoneOpen` state plus frame liveness via the pure `domain/WearWatchPresentation`: `OpenOnPhone` (one centred filled "Open in phone" button with the phone icon while the phone Camera app is not open) and `Viewfinder` (only the streamed viewfinder plus one small capture button, themed by the phone's mode via `wearCaptureButtonSpec`/`wearCaptureOp`; recording shows the stop theme). The viewfinder requires frames to actually arrive: `data/WearCameraStore` stamps the wait for the first frame and each frame's arrival, the preview request is retried while no frame is held, and `wearWatchScreen` falls back to `OpenOnPhone` when no live frame has arrived within `WEAR_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 in `data/WearCameraStore` (no offline copy: nothing is usable without the phone).
57- Wire protocol (`WearCameraProtocol`, WCF1 preview frames) lives in `:library:wearlink` at `com.vayunmathur.library.wearlink.camera`; this module's `WearCameraProtocolTest` pins the golden JSON/frame bytes (including the watch store's stale-frame rules). Live viewfinder frames travel as `/camera/preview-frame` messages (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.
58- Watch listing screenshots are the `group = "wear"` previews in `src/screenshotTest/.../ui/WearMetadataPreviews.kt`, collected by `:camera:metadata` into `metadata_data/photos/camera/wear/`; phone/tablet shots keep their buckets.
59**Gotchas:**
60- Capture code lives in `platform/` (the Camera2 driver in `platform/camera2/`); there is no `util/` root in this module
61- 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 real `onClosed` (device `close()` only initiates HAL teardown), and `PreviewSurfaceBridge` forgets its pinned stream size on destroy so a new `SurfaceTexture` is 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
62- Listing screenshots are preview-rendered (`:camera:metadata`): Layoutlib can't open a camera, so `src/screenshotTest` draws the deterministic `FakeCameraPreview` scene behind the real top bar/grid/shutter/mode controls. `Route.Settings` is captured from the stateless `CameraSettingsContent` slice in `ui/SettingsPage.kt` with literal fixtures. The `screenshotFakePreview` parameter on `CameraScreen`/`CameraPreviewSurface` is the same seam in `main` — production-default null, never passed by `MainActivity`, so no fake frame can appear on device
63- Volume keys act as the shutter, gated on the camera route being foreground; Esc/space covers desktop keyboards
64- `.maml` model assets ship uncompressed (`noCompress`) — never compress them
65- 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 the `OrientationEventListener` (fed to sessions via `CameraViewModel.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, so `ui/CameraPreviewSurface` never 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 no `irot`, MP4 carries only the muxer orientation hint, night/pano RGB outputs bake pixels upright. No DNG writer is wired (`DngMetadata` only assembles requirements)
66
67## Key files
68### Root — entry + navigation
69- com/vayunmathur/camera/MainActivity.kt
70- com/vayunmathur/camera/Route.kt
71### domain/ — pure lens-selection logic
72- com/vayunmathur/camera/domain/LensModel.kt
73- com/vayunmathur/camera/domain/LensDiscovery.kt — offered-lens computation over pure `LensCandidate`s: 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`)
74- com/vayunmathur/camera/domain/LensSelectionLogic.kt
75- com/vayunmathur/camera/domain/ArgbToI420Converter.kt — bulk ARGB→YUV 4:2:0 for the Motion Photo clip
76- 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`
77- com/vayunmathur/camera/domain/MotionSaveQueue.kt — bound on Motion Photos still saving after the shutter
78- com/vayunmathur/camera/domain/StillCaptureModePolicy.kt — ZSL vs MINIMIZE_LATENCY choice
79- com/vayunmathur/camera/domain/CaptureRotation.kt — the one capture-rotation decision (sensor + physical display + facing) and EXIF convention
80- com/vayunmathur/camera/domain/AnalysisRotation.kt — analysis-frame rotation (same formula as CaptureRotation)
81- com/vayunmathur/camera/domain/PanoXmp.kt
82- com/vayunmathur/camera/domain/SphereWaypoints.kt — FOV-derived photo-sphere waypoint layout + fused-orientation yaw/pitch math
83- 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 `tmap` gain 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)
84- com/vayunmathur/camera/domain/GainMapMath.kt — ISO 21496-1 gain-map params + encode/decode math for AVIF Ultra HDR; `StillFormatRouting.stillSaveRoute` sends Ultra HDR sources under AVIF to the `tmap` encoder (JPEG_R bytes on any gain-map failure)
85- 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
86### platform/ — capability queries
87- com/vayunmathur/camera/platform/CameraCapabilities.kt
88- 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's `WearCameraProtocolTest` pins the golden JSON/frame bytes
89- com/vayunmathur/camera/platform/LensSelector.kt
90### ui/ — single screen + settings + panes
91- com/vayunmathur/camera/ui/CameraScreen.kt
92- com/vayunmathur/camera/ui/CameraScreenState.kt
93- com/vayunmathur/camera/ui/CameraScreenKit.kt
94- com/vayunmathur/camera/ui/CameraScreenEffects.kt
95- com/vayunmathur/camera/ui/CameraPreviewBox.kt
96- com/vayunmathur/camera/ui/CameraPreviewOverlays.kt
97- com/vayunmathur/camera/ui/CaptureFlashOverlay.kt
98- com/vayunmathur/camera/ui/CameraOverlays.kt
99- com/vayunmathur/camera/ui/CameraPanoramaOverlay.kt
100- com/vayunmathur/camera/ui/CameraTopBar.kt
101- com/vayunmathur/camera/ui/CameraBottomControls.kt
102- com/vayunmathur/camera/ui/CameraShutterPane.kt
103- com/vayunmathur/camera/ui/CameraShutterRow.kt
104- com/vayunmathur/camera/ui/CameraModeBars.kt
105- com/vayunmathur/camera/ui/CameraModesPane.kt
106- com/vayunmathur/camera/ui/CameraSettingsBars.kt
107- com/vayunmathur/camera/ui/CameraSettingsColumn.kt
108- com/vayunmathur/camera/ui/CameraStatusIndicators.kt
109- com/vayunmathur/camera/ui/CameraWideLayout.kt
110- com/vayunmathur/camera/ui/ZoomBar.kt — the single zoom row (shown by default in `CameraSettingsColumn` when 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 via `setZoomRatioLive`, committed on release) + lens-stop chips, numbers rotating with device orientation. Scrub mapping is the pure `domain/ZoomScrub.kt` (log-scale, slop-compensated, monotonic across lens stops, chip set frozen mid-scrub)
111- com/vayunmathur/camera/ui/SettingsPage.kt
112- com/vayunmathur/camera/ui/CameraPostProcessingSettings.kt
113### platform/ — ViewModel, sessions, engines
114- com/vayunmathur/camera/platform/CameraViewModel.kt
115- com/vayunmathur/camera/platform/CameraViewModelActions.kt
116- com/vayunmathur/camera/platform/CameraViewModelTypes.kt
117- com/vayunmathur/camera/platform/CameraStartup.kt
118- com/vayunmathur/camera/platform/CameraSessions.kt
119- com/vayunmathur/camera/platform/CaptureOrientation.kt — pushes the physical display rotation to live sessions
120- com/vayunmathur/camera/platform/CameraSingleCapture.kt
121- com/vayunmathur/camera/platform/CameraPhotoCapture.kt
122- com/vayunmathur/camera/platform/CameraCaptureProcessing.kt
123- com/vayunmathur/camera/platform/CameraVideoRecording.kt
124- com/vayunmathur/camera/platform/Camera2VideoRecordingEngine.kt
125- com/vayunmathur/camera/platform/Camera2SloMoGlue.kt
126- com/vayunmathur/camera/platform/CameraManualControls.kt
127- com/vayunmathur/camera/platform/CameraControls.kt
128- com/vayunmathur/camera/platform/CameraNightMode.kt
129- com/vayunmathur/camera/platform/CameraNightCapture.kt
130- com/vayunmathur/camera/platform/NightCaptureEngine.kt
131- com/vayunmathur/camera/platform/PanoramaEngine.kt
132- com/vayunmathur/camera/platform/GpuStitcher.kt
133- com/vayunmathur/camera/platform/StitchNative.kt — JNI bridge into `camera_stitch`
134- com/vayunmathur/camera/platform/PortraitBokeh.kt
135- com/vayunmathur/camera/platform/BokehAnalyzer.kt
136- com/vayunmathur/camera/platform/PhotoAnalyzer.kt
137- com/vayunmathur/camera/platform/MotionPhotoEncoder.kt
138- com/vayunmathur/camera/platform/VideoProcessor.kt
139- com/vayunmathur/camera/platform/CodecSupport.kt
140- com/vayunmathur/camera/platform/GainMapExtractor.kt — extracts the HAL JPEG_R gain map (`Bitmap.gainmap`, API 34+) as a grayscale `GainMapFrame` for the AVIF `tmap` mux in Rust (`src/main/rust/src/avif_gainmap.rs` + `avif_gainmap_parse.rs`, via `StitchNative.encodeAvifUltraHdr`)
141### platform/camera2/ — Camera2 driver
142- com/vayunmathur/camera/platform/camera2/Camera2Driver.kt
143- com/vayunmathur/camera/platform/camera2/Camera2Session.kt
144- com/vayunmathur/camera/platform/camera2/Camera2SessionRingCapture.kt
145- com/vayunmathur/camera/platform/camera2/Camera2ExtensionSession.kt
146- com/vayunmathur/camera/platform/camera2/Camera2HighSpeedSession.kt
147- com/vayunmathur/camera/platform/camera2/StillCapture.kt
148- com/vayunmathur/camera/platform/camera2/StreamSelection.kt
149### Watch experience (ui/ + data/ + sync/)
150- com/vayunmathur/camera/ui/WearMainActivity.kt — watch entry (WearShellActivity)
151- com/vayunmathur/camera/ui/WearRoute.kt, WearOpenOnPhoneScreen.kt, WearViewfinderScreen.kt
152- com/vayunmathur/camera/domain/WearWatchPresentation.kt — pure two-screen state machine + capture-button theme/op mapping
153- com/vayunmathur/camera/sync/OpenOnPhoneReceiver.kt, ConduitSyncTriggerReceiver.kt — phone broadcast entries (open launch / sync wake)
154- com/vayunmathur/camera/platform/FormFactor.kt — watch detection (`FEATURE_WATCH`)
155- com/vayunmathur/camera/data/WearCameraStore.kt — mirrored phone state + newest preview frame/thumbnail (in-memory only)
156- com/vayunmathur/camera/sync/WearLinkBridge.kt — watch conduit client node; mirrored state/thumbnail receive, preview frames, op sends
157### data/ — settings + saving
158- com/vayunmathur/camera/data/MediaStoreSaver.kt
159- com/vayunmathur/camera/data/CameraSettings.kt
160- com/vayunmathur/camera/data/CameraSaveLocation.kt
161- com/vayunmathur/camera/data/CameraSaveRouting.kt
162
163## Verify (this module only)
164```
165./gradlew :camera:compileDevKotlin
166./gradlew :camera:lint
167./gradlew :camera:checkMetadata
168```