Aner Video
Capture local cameras, remote media and recordings through bounded native frame slots, explicit read outcomes and standard video recording.
ImplementedAner 0.1.0 or neweraner.video connects cameras, recorded files and remote streams to bounded native frame storage. Use it independently for acquisition and recording, or compose it with Aner Vision, Tensor and neural models.
The module exposes synthetic sources and bounded acquisition and recording APIs. Camera access and encoded media require the matching optional backend and hardware.
Start with a reproducible source
import aner.video
let source = video.synthetic(width: 160, height: 120, frames: 12)
let frame = video.frame_slot()
while source.read_into(frame) == "ready" {
print(frame.sequence())
print(frame.width())
}
print(source.state())
source.close()The synthetic source needs no camera, network, codec library or external file. It produces deterministic RGB8 frames. Non realtime synthetic input and recorded files preserve order through bounded backpressure; live sources prefer newer pending frames when their queues fill. See the complete basic program.
Sources and optional backend
| Entry point | Input | Scheduling |
|---|---|---|
video.synthetic(...) | Deterministic generated RGB frames | Ordered by default; realtime: true paces a live source |
video.file(path, ...) | A local encoded video or image file | Ordered, bounded read ahead |
video.camera(device, ...) | An OS capture device locator | Live, bounded latest frame queue |
video.stream(url, ...) | Supported RTSP or HTTP(S) media | Live, bounded latest frame queue |
video.snapshot_url(url, ...) | One HTTP(S) image response | Finite, bounded request without redirects |
File, camera, remote decoding and recording require a build with the installed FFmpeg libraries. video.available() reports whether that backend was compiled in. It does not establish that a particular codec, protocol, camera or accelerator is available. video.camera_backend() reports the selected OS capture backend. No subprocess or shell command is launched by capture or recording.
The initial interchange format is packed CPU RGB8, with explicit row stride. Decode, color conversion, resize and recording use CPU paths. Existing Metal/MPS and CUDA tensor computation remain separate capabilities. Hardware decoding, shared GPU capture surfaces and zero copy frame to tensor conversion are future work.
Local cameras
import aner.video
print(video.devices())
let camera = video.camera(device: "default", width: 640, height: 480, fps: 30.0)
let frame = video.frame_slot()
var accepted = 0
var waits = 0
var active = true
while accepted < 30 && waits < 10 && active {
let status = camera.read_into(frame, timeout_ms: 1000)
if status == "ready" {
print(frame.width())
print(frame.height())
accepted += 1
} else if status == "timeout" {
waits += 1
} else {
print(camera.error())
active = false
}
}
camera.close()Device locators are backend specific: AVFoundation on macOS, Video4Linux2 on Linux, and DirectShow on Windows. The OS may require camera permission or exclusive access. Discovery returns a bounded JSON report and explicitly reports when enumeration is unavailable. On Windows use an explicit DirectShow locator; the initial adapter does not select a default device there. A numeric locator can change after unplugging or rebooting; applications must retain their own logical camera identity and verify the device binding.
Requested width, height and FPS are capture preferences supported by the device/backend. Inspect delivered frame dimensions; do not infer the actual mode from the request. Exposure, autofocus, PTZ, hardware triggering and a portable strict mode negotiation API are not exposed in this first increment.
Remote input
import aner.video
let source = video.stream("https://camera.example.invalid/video.mjpeg",
timeout_ms: 3000, queue_frames: 2)
let frame = video.frame_slot()
let status = source.read_into(frame, timeout_ms: 1000)
print(status)
source.close()Replace the fictional URL privately. This example is checked without opening a connection; running it makes the request. RTSP and HTTP(S) media support depends on the installed backend. An HTTP URL returning a single image is a finite source; automatic snapshot polling, proprietary cloud session negotiation, ONVIF discovery/control, WebRTC negotiation and HLS specific low latency guarantees are outside this increment.
For a single authenticated image, use video.snapshot_url(url, authorization: secrets.stored("camera-authorization")) after importing aner.secrets. The secret contains the raw bearer token; the adapter constructs the Authorization header internally. Authorization requires HTTPS and redirects are refused. For a private camera CA, pass ca_file: "camera-ca.pem"; an empty path uses system trust and hostname verification remains enabled. Ambient proxy settings are not used by this snapshot adapter. Continuous video.stream has no credential overload in this increment. Do not put passwords or tokens in URLs. Userinfo and fragments are rejected; ordinary bounded query selectors such as channel, subtype and dimensions are accepted, while recognized credential like query names are rejected. The name filter cannot determine whether an arbitrary value is secret. Backend diagnostics are sanitized. An explicitly configured unencrypted stream transport remains unencrypted.
Read outcomes and lifetime
source.read_into(frame, timeout_ms: 1000) returns a scalar String, avoiding a new managed Result or Optional wrapper per frame.
| Status | Meaning | Caller action |
|---|---|---|
ready | A new frame was delivered | Process this frame |
timeout | No new frame arrived within the caller's wait | Retry, cancel or report a stall |
end | The finite input completed | Finish the loop |
cancelled | A native cancellation request interrupted the read | Stop processing |
closed | The source was explicitly closed | Stop processing |
failed | The worker encountered a terminal input/backend error | Inspect source.error() and close/reopen deliberately |
A timeout is not end of file. Process pixels only after ready; a previously held image must not be described as a new observation. Source close is idempotent, stops native work and releases its capture resources. Aliases share source and slot state. Automatic reconnection and camera identity rebinding are future work; reopening creates a new session identity.
One reader consumes a source's delivery queue. Multiple independent cameras each own a source and worker. Concurrent reads on one shared mutable slot are unsupported. Use one slot per consumer and coordinate access explicitly.
Frame identity and timing
Frame accessors expose geometry, sequence, source/session identity, source presentation timestamp and monotonic host receipt time. Timestamp provenance matters: a media presentation timestamp is not necessarily sensor exposure time. A missing source timestamp must remain distinguishable from zero. Host monotonic times are useful for local elapsed measurements and are not UTC dates.
Never estimate real capture time solely as sequence / requested_fps. Streams can have variable frame rate, gaps, reordering and different clock domains. Multiple cameras operating together are independent; this implementation does not establish synchronized exposure, PTP clock alignment, stereo calibration or cross camera tracking.
Memory and queue budgets
queue_frames and memory_mb bound source read ahead; a frame slot has its own byte budget. Snapshot retention is separately budgeted. Bounds apply to the owned pixel queues and slots, not to the whole process: decoder state, model weights, tensors and codec allocations have their own costs. An oversized frame fails before its RGB output is allocated. Queued and cached source RGB capacities share memory_mb; one additional in flight frame may use up to the per frame limit of min(64 MiB, memory_mb). The caller slot and retained snapshot pool have separate budgets.
Use a reusable slot inside long loops. source.snapshot(frame) creates an independent immutable VideoFrame for deliberate retention. Snapshots retain their pixels after source closure and consume the source's snapshot budget until the last alias is released. An explicit snapshot is a copy, not a borrowed view into a buffer that the next read overwrites.
Avoid appending every frame, input tensor or detection object to a List. Aner's managed collection heap is collected between session cells; a continuous cell must recycle its native resources during execution. The same rule applies to model result containers. Reusing a slot prevents video storage from depending on cell completion.
Several cameras
import aner.video
let left = video.synthetic(width: 160, height: 120, frames: 4)
let right = video.synthetic(width: 160, height: 120, frames: 4)
let a = video.frame_slot()
let b = video.frame_slot()
while left.read_into(a) == "ready" {
if right.read_into(b) == "ready" {
print(a.source_id())
print(b.source_id())
}
}
left.close()
right.close()Replace the two sources with distinct camera locators to capture physical devices. This loop pairs delivered observations; it does not synchronize exposures. A production application should service sources fairly, handle each outcome independently and avoid an indefinite sequential wait on a stalled source. See the complete multi source example.
Recording and replay
video.record(path, width, height, fps: 30.0) opens a new Matroska recording with lossless FFV1 encoding. Use a new .mkv path. The writer accepts matching RGB8 frame geometry, refuses an existing destination and finalizes the container on close().
import aner.video
let source = video.synthetic(width: 160, height: 120, frames: 12)
let frame = video.frame_slot()
let recording = video.record("capture.mkv", width: 160, height: 120, fps: 30.0)
while source.read_into(frame) == "ready" {
recording.write(frame)
}
recording.close()
source.close()
let replay = video.file("capture.mkv")
while replay.read_into(frame) == "ready" {
print(frame.sequence())
}
replay.close()The writer records only the frames supplied by the caller. It preserves relative presentation time gaps when source timestamps are available, uses the declared rate when they are absent, and rejects mixed source sessions or nonmonotonic timestamps. It does not promise that every camera frame reaches it. A slow combined inference/recording loop can lose pending live frames; inspect source counters. Recording is synchronous in the calling flow. Independent subscriptions, asynchronous recording branches, packet remuxing, automatic segmentation, disk quotas and timestamp sidecars are future work.
Diagnostics and optimization
Inspect state(), backend(), error(), captured(), delivered(), dropped(), queued_frames() and queued_bytes(). Captured, delivered and inferred counts describe different pipeline stages. Source queue drops do not count every possible device or network loss.
Choose the lowest source resolution and rate adequate for the task. Uncompressed 1920×1080 YUY2 at 30 FPS carries about 124 MB/s per camera before transport overhead. Controllers and hubs may share bandwidth and power. Compression reduces transport bandwidth while adding decode work. RGB output adds its own memory traffic; a 1920×1080 RGB8 frame contains 6,220,800 bytes.
Keep model weights and preprocessing plans resident, reuse input/output slots and report any tensor transfer explicitly. Measure frame age, latency percentiles, queue occupancy, delivered/inferred FPS, CPU/GPU use and process memory over a sustained run. A camera's advertised FPS does not establish application throughput.
API reference
Constructors support concise named arguments; receiver methods also have module forms. The complete callable index is generated from native declarations. The video/vision parameter reference lists defaults, output types and constraints.
Native video failures produce source located R4301 errors. Expected delivery outcomes use the read status String; inspect source.error() after failed. Wrong source argument types or names fail during checking. Checking a program never opens a camera, network connection or recording. These APIs execute through the native runtime interpreter; the standalone typed CPU source compiler does not lower video/vision programs.
Examples and validation
- Synthetic acquisition: deterministic finite input without external dependencies.
- Camera capture: device discovery and bounded waits.
- Multiple sources: independent identities and slots.
- Remote input: explicit endpoint and credentials.
- Record and replay: standard video file round trip.
- Vision preprocessing: RGB frames to NCHW tensors.
Native and language tests exercise synthetic ordering, bounds, lifecycle, preprocessing geometry and postprocessing. FFmpeg enabled tests add recording/replay. Physical cameras, remote camera interoperability and accelerator performance require qualification on their actual hardware; synthetic success does not establish those results.