SPB Git

Repository Public License

camera-engine.md 9.0 KB 129 lines markdown

1<!--2ORIX Camera3File: docs/architecture/camera-engine.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->78# Camera Engine910## CameraBackend1112`App/Sources/Core/CameraSession/CameraBackend.swift` defines everything the interface may ask of a camera:1314- authorisation: `cameraAccess`, `requestCameraAccess`, `microphoneAccess`, `requestMicrophoneAccess`;15- `lenses()` and `configure(lensID:purpose:)`, which returns the `CameraCapabilities` of that configuration;16- exposure (`setExposureAuto`, `setExposureLocked`, `setExposureManual(iso:duration:)`, `setExposureBias`);17- focus (`setFocusAuto`, `setFocusLocked`, `setFocusManual(lensPosition:)`, `focusAndExpose(at:expose:)`);18- white balance (`setWhiteBalanceAuto`, `setWhiteBalanceLocked`, `setWhiteBalance(temperature:tint:)`);19- `setZoom`, `setTorch`;20- `capturePhoto(_:)` and `captureBracket(biases:)`;21- `attachPreviewLayer(_:)`, an `events` stream, and a `receiver` for frames and audio.2223`CapturePurpose` is `.photo` or `.video(format, audio:, stabilization:)`. Changing mode reconfigures the session only when the purpose changes.2425Two implementations exist, selected at compile time:2627| | Compiled for | Frames from |28|---|---|---|29| `DeviceCameraBackend` | iOS devices (`#if !targetEnvironment(simulator)`) | `AVCaptureVideoDataOutput` |30| `VirtualCameraBackend` | the Simulator only | `SyntheticScene`, on a timer |3132## DeviceCameraBackend3334**One serial queue owns the session.** Every session and device configuration runs on `sessionQueue`, so two configuration changes can never interleave. Frames arrive on a separate video queue, audio on an audio queue.3536Configuration sequence (`configureOnQueue`):37381. Discover physical cameras; choose the requested lens or the back wide camera.392. Replace the input if the lens changed; observe its `systemPressureState`.403. Add the photo output and the video data output (BGRA, late frames discarded) once.414. Photo purpose: session preset `.photo`. Video purpose: find the 8-bit full-range format matching resolution and frame rate (the one with the widest field of view if several match), set it as `activeFormat` and fix min and max frame duration.425. Add or remove the microphone input and audio data output.436. Data-output connection: rotation angle 0, mirroring off, stabilisation `.standard` or `.off`.447. Photo output: largest non-deferred `maxPhotoDimensions`, quality prioritisation allowed, ProRAW enabled where supported.458. Start the session and the 10 Hz state timer; return the resolved capabilities.4647**Controls.** Each control method dispatches to the session queue, locks the device for configuration, checks the relevant `is…Supported` property, clamps the value to the device range and applies it. Errors from `lockForConfiguration` are published as runtime-error events.4849**Live state.** A timer on the session queue reads ISO, exposure duration, bias, target offset, modes, lens position, adjusting flags, white-balance temperature and tint (converted from the current gains), zoom, torch, active dimensions, frame rate and active stabilisation, and publishes a `LiveCameraState`. The interface displays these readings, not the requested values.5051**Events.** `CameraEvent` carries state, interruptions with a human-readable reason, the end of an interruption, runtime errors, pressure level and rotation angles. After a media-services reset the session is restarted.5253**Photo capture.** `makeSettings` builds `AVCapturePhotoSettings` for the requested format and applies the AVFoundation rules (see the capability matrix, section 7). A `PhotoProcessor` delegate collects the processed and RAW photos of one request and reports once, in `didFinishCaptureFor`. Requests in flight are retained by unique id.5455## Rotation and display geometry5657Frames are never rotated in the capture pipeline. Three consumers rotate, each with the angle the system provides:5859| Consumer | Angle | Mechanism |60|---|---|---|61| Monitor | `videoRotationAngleForHorizonLevelPreview` | uv matrix in the vertex shader |62| Photos | `videoRotationAngleForHorizonLevelCapture` | set on the photo connection before each capture (EXIF orientation) |63| Movies | capture angle | `CaptureGeometry.movieTransform` on the writer's video track |64| Multi-frame stills | capture angle | `CaptureGeometry.exifOrientation`, then baked into pixels before encoding |6566The rotation coordinator is created with the Metal view's layer, because without a layer it reports a preview angle of 0. Until the layer is attached the capture angle is used.6768### Display geometry6970The monitor draws one quad. For a screen point with centred coordinates (u, v), v pointing down, the shader samples the source at7172```73sx = cos θ · m · u + sin θ · v74sy = −sin θ · m · u + cos θ · v75```7677then adds 0.5 to both. θ is the clockwise display rotation (a multiple of 90°) and m is −1 when the display is mirrored (front camera), else 1. For θ = 90°: `sx = v`, `sy = −u`: the top-right of the screen shows the top-left of the sensor frame, which is what rotating the picture clockwise means.7879The quad is scaled for aspect fit or fill from the rotated image size (`MonitorRenderer.quadScale`); `imageRect` returns the same rectangle in points so SwiftUI overlays (grid, masks, reticle) are laid out on the picture, not on the view.8081Focus magnification replaces the centred coordinate c by `centre · (1 − 1/z) + c / z` before the rotation.8283`CaptureGeometry.sensorPoint(displayed:rotationDegrees:mirrored:)` is the inverse mapping used for tap-to-focus. A test marks the sensor's top-left corner, renders rotated and mirrored, and checks that the mark lands where `displayedPoint` says.8485## MonitorRenderer8687One Metal render pass (`Packages/ORIXCameraKit/Sources/ORIXImaging/Monitoring/MonitorRenderer.swift`):88891. The pixel buffer becomes a texture through `CVMetalTextureCache` (no copy).902. The fragment shader samples the frame, then applies, in order: display LUT (3D texture, mixed by intensity), monochrome, false colour, clipping warning, highlight zebra, shadow zebra, focus peaking.913. Luma is Rec. 709 on encoded values throughout.9293Zebra stripes are generated in screen pixels (12-pixel period, animated); peaking samples the eight neighbours one source texel away. The shader source is a string compiled at run time with `makeLibrary(source:)`, which keeps the package free of build-phase requirements. `renderOffscreen` renders into a texture and reads the bytes back: the tests and the benchmark use it.9495`MonitorView` hosts an `MTKView` that draws at display rate (30 Hz under serious thermal pressure) whatever the camera's frame rate, always from the pipeline's latest frame, or from an override frame while a multi-frame capture shows its running result.9697## FramePipeline9899`receive(_:)` runs on the capture queue for every frame:1001011. store the frame as `latest`; record its timestamp;1022. if recording, append it to the `VideoRecorder` (time-lapse: only when the interval has elapsed);1033. if accumulating, add it to the `FrameAccumulator`; signal when the frame limit is reached;1044. if a night stack is collecting, register and merge it;1055. if the analysis queue is free and 1/12 s has passed, hand the frame to it.106107The analysis queue computes the histogram, zebra coverage, the focus metrics on a 480-pixel luma plane, the mean absolute luma change against the previous analysed frame, and frame timing (mean interval → delivered fps, standard deviation → jitter) over the last 90 timestamps. It publishes an `AnalysisSnapshot`. A busy flag makes it skip frames instead of queueing them.108109Audio buffers go to the recorder and, every 60 ms, to `levels(of:)`, which computes RMS and peak in dBFS with vDSP.110111## CameraModel112113`CameraModel` (main actor, `@Observable`) owns the backend, the pipeline, the monitor state and the settings. It:114115- starts and suspends the session with the scene phase and when the library covers the camera;116- maps the mode to a `CapturePurpose` and reconfigures only when it changes;117- drops stored choices the current camera cannot honour (`sanitizeSettings`);118- clamps every manual request to the capability ranges before calling the backend;119- turns analysis snapshots into the smoothed histogram curves and Auto mode's hints;120- runs the capture flows and stores the results.121122`CameraSettings` is a `Codable` struct saved as JSON in UserDefaults. Its decoder tolerates missing keys, so settings written by an older build keep working.123124## VirtualCameraBackend125126The Simulator has no camera. This backend renders `SyntheticScene` on a timer and reacts to the controls so that the interface and the pipeline have something real to process: exposure gain follows ISO × duration (nominal at ISO 100, 1/60 s) or the bias in auto; white balance shifts red and blue gains around 5500 K; manual focus away from lens position 0.72 blurs the scene; zoom crops it. Photos are rendered at the requested size and encoded as HEIC with EXIF that names the virtual camera. RAW requests throw with the explanation shown in the interface.127128It is a test double. It is compiled out of device builds, its captures are flagged synthetic, and the monitor carries a "SIMULATOR · TEST SCENE" badge.129
Files main
Menu

Theme