Camera Engine
CameraBackend
App/Sources/Core/CameraSession/CameraBackend.swift defines everything the interface may ask of a camera:
- authorisation:
cameraAccess,requestCameraAccess,microphoneAccess,requestMicrophoneAccess; lenses()andconfigure(lensID:purpose:), which returns theCameraCapabilitiesof that configuration;- exposure (
setExposureAuto,setExposureLocked,setExposureManual(iso:duration:),setExposureBias); - focus (
setFocusAuto,setFocusLocked,setFocusManual(lensPosition:),focusAndExpose(at:expose:)); - white balance (
setWhiteBalanceAuto,setWhiteBalanceLocked,setWhiteBalance(temperature:tint:)); setZoom,setTorch;capturePhoto(_:)andcaptureBracket(biases:);attachPreviewLayer(_:), aneventsstream, and areceiverfor frames and audio.
CapturePurpose is .photo or .video(format, audio:, stabilization:). Changing mode reconfigures the session only when the purpose changes.
Two implementations exist, selected at compile time:
| Compiled for | Frames from | |
|---|---|---|
DeviceCameraBackend |
iOS devices (#if !targetEnvironment(simulator)) |
AVCaptureVideoDataOutput |
VirtualCameraBackend |
the Simulator only | SyntheticScene, on a timer |
DeviceCameraBackend
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.
Configuration sequence (configureOnQueue):
- Discover physical cameras; choose the requested lens or the back wide camera.
- Replace the input if the lens changed; observe its
systemPressureState. - Add the photo output and the video data output (BGRA, late frames discarded) once.
- 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 asactiveFormatand fix min and max frame duration. - Add or remove the microphone input and audio data output.
- Data-output connection: rotation angle 0, mirroring off, stabilisation
.standardor.off. - Photo output: largest non-deferred
maxPhotoDimensions, quality prioritisation allowed, ProRAW enabled where supported. - Start the session and the 10 Hz state timer; return the resolved capabilities.
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.
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.
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.
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.
Rotation and display geometry
Frames are never rotated in the capture pipeline. Three consumers rotate, each with the angle the system provides:
| Consumer | Angle | Mechanism |
|---|---|---|
| Monitor | videoRotationAngleForHorizonLevelPreview |
uv matrix in the vertex shader |
| Photos | videoRotationAngleForHorizonLevelCapture |
set on the photo connection before each capture (EXIF orientation) |
| Movies | capture angle | CaptureGeometry.movieTransform on the writer's video track |
| Multi-frame stills | capture angle | CaptureGeometry.exifOrientation, then baked into pixels before encoding |
The 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.
Display geometry
The monitor draws one quad. For a screen point with centred coordinates (u, v), v pointing down, the shader samples the source at
sx = cos θ · m · u + sin θ · v
sy = −sin θ · m · u + cos θ · vthen 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.
The 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.
Focus magnification replaces the centred coordinate c by centre · (1 − 1/z) + c / z before the rotation.
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.
MonitorRenderer
One Metal render pass (Packages/ORIXCameraKit/Sources/ORIXImaging/Monitoring/MonitorRenderer.swift):
- The pixel buffer becomes a texture through
CVMetalTextureCache(no copy). - 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.
- Luma is Rec. 709 on encoded values throughout.
Zebra 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.
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.
FramePipeline
receive(_:) runs on the capture queue for every frame:
- store the frame as
latest; record its timestamp; - if recording, append it to the
VideoRecorder(time-lapse: only when the interval has elapsed); - if accumulating, add it to the
FrameAccumulator; signal when the frame limit is reached; - if a night stack is collecting, register and merge it;
- if the analysis queue is free and 1/12 s has passed, hand the frame to it.
The 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.
Audio buffers go to the recorder and, every 60 ms, to levels(of:), which computes RMS and peak in dBFS with vDSP.
CameraModel
CameraModel (main actor, @Observable) owns the backend, the pipeline, the monitor state and the settings. It:
- starts and suspends the session with the scene phase and when the library covers the camera;
- maps the mode to a
CapturePurposeand reconfigures only when it changes; - drops stored choices the current camera cannot honour (
sanitizeSettings); - clamps every manual request to the capability ranges before calling the backend;
- turns analysis snapshots into the smoothed histogram curves and Auto mode's hints;
- runs the capture flows and stores the results.
CameraSettings is a Codable struct saved as JSON in UserDefaults. Its decoder tolerates missing keys, so settings written by an older build keep working.
VirtualCameraBackend
The 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.
It 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.