Skip to content

Recording pipeline

This page follows a recording from the camera to the playback screen: the ffmpeg process that writes it, the indexer that turns files into database rows, the uploader and mirror passes that move copies around, the janitor that deletes them, and the API that stitches them back into a playable HLS stream. Every constant here is quoted from the source, so you can check each statement in the named file.

go2rtc holds the only connection to each camera (see How it works). The recorder never talks to a camera directly. It reads go2rtc’s local RTSP restream, one ffmpeg per camera, and everything after that works on files and rows.

camera ──RTSP──▶ go2rtc (stream cam_<id>, restream on rtsp://127.0.0.1:8554)
│
▼
ffmpeg, one per camera, stream copy internal/record/recorder.go
│ writes <dir>/<epoch>.ts every 10 s
▼
┌───────────────┴────────────────┐
│ local destination │ network destination (SMB / SFTP)
│ indexer: ffprobe → segments │ spool → uploader: Put → segments row
└───────────────┬────────────────┘
▼
mirror pass: copy indexed segments → segment_copies mirror.go
▼
janitor: age, quota, caps, free space → file, then row internal/retention/janitor.go
▼
API: /hls playlist built from rows → /seg/{seg}.ts internal/api/recordings_handlers.go

Four loops drive it:

Loop Function Interval
Start and stop recorders Recorder.Reconcile 60 s (reconcileEvery), plus on demand
Index, upload, mirror indexOnce, uploadOnce, mirrorOnce 8 s (indexInterval)
Retention Janitor.enforce 5 min (interval), plus EnforceNow after an allocation change
Recording health Watchdog.tick (internal/watchdog) 15 s

Recorder.ShouldRecord decides. A camera records when it is enabled, has a main RTSP URL, and its record mode (cameras.record_mode) allows it:

Mode What the recorder does
continuous Records all the time.
motion Also records all the time. The janitor later deletes the footage that no event overlaps (see Retention).
scheduled Records inside the camera’s recording windows only (the schedules table: weekday, start minute, end minute).
never Does not record.

Schedule windows are evaluated in the site profile’s timezone (site.Load), not the host’s, so a host in UTC and a daylight-saving change do not shift them. Reconcile re-checks every 60 seconds, so a window opens or closes within a minute of its boundary.

The global Recording quality setting (record_quality in the settings table, PUT /api/v1/system/settings with recordQuality: "low") makes each camera record its sub stream (cam_<id>_sub) instead of the main one, but only for cameras that have a sub URL. Changing it calls RestartAll, so every recorder reconnects within seconds. See Recording for the user-facing side.

superviseFFmpeg builds the argument list on each start. For a camera that records what it receives (no lower recording quality set), on the default destination, it is:

ffmpeg -hide_banner -loglevel warning -nostdin
-rtsp_transport tcp -use_wallclock_as_timestamps 1 -fflags +genpts
-i rtsp://127.0.0.1:8554/cam_<id>
-map 0:v:0 -map 0:a?
-c:v copy
-c:a aac -b:a 32k
-f segment -segment_time 10 -segment_format mpegts
-strftime 1 /var/lib/aperture/recordings/<id>/%s.ts

Do not run this yourself next to a running recorder: two processes writing the same directory can open the same second’s file.

Argument Why it is there
-hide_banner -loglevel warning -nostdin Quiet output, and ffmpeg never waits for keyboard input on stdin.
-rtsp_transport tcp RTP travels inside the RTSP TCP connection to go2rtc, so no packets are lost to UDP and no extra ports are opened.
-use_wallclock_as_timestamps 1 Timestamps come from the clock when packets arrive, not from the camera’s RTP clock. go2rtc can reconnect a camera underneath a running ffmpeg (a stream restart, a dropped link), and the camera’s RTP clock then comes back far from where it was. The segment muxer cuts on timestamps, so with camera timestamps it would split at every keyframe or never, and audio and video would end up far apart in the file. inputArgs in recorder.go carries this comment.
-fflags +genpts Generates presentation timestamps for packets that arrive without one.
-i rtsp://127.0.0.1:8554/cam_<id> go2rtc’s restream (stream.Manager.RTSPURL, or RTSPURLSub for cam_<id>_sub). The base comes from APERTURE_GO2RTC_RTSP.
-map 0:v:0 Records exactly one video track, the first. Some sources expose several video tracks in one feed (a dual-lens camera, or main and sub in one stream). Copying all of them yields an MPEG-TS the segment muxer cannot rotate: one file that grows forever.
-map 0:a? The audio track if there is one. The ? makes it optional, so cameras without audio still record.
-c:v copy Stream copy: the video is never decoded, costs almost no CPU, and is bit-for-bit what the camera sent.
-c:a aac -b:a 32k Audio is re-encoded, not copied. Stream-copying AAC from RTSP into MPEG-TS with ffmpeg 7.x declares the audio track and then writes no packets to it; ffprobe still reports aac, but players see an empty track. Re-encoding at 32 kbit/s costs very little CPU.
-f segment -segment_time 10 The segment muxer starts a new file every 10 seconds (segmentSeconds). With stream copy a file can only start on a keyframe, so its real length follows the camera’s keyframe interval.
-segment_format mpegts MPEG-TS files are self-contained, readable while they are being written, and served to the browser’s HLS player as they are.
-strftime 1 and %s.ts Each file is named after the Unix epoch second it starts at, for example 1773475200.ts. The indexer reads the start time from the name.
no -reset_timestamps Deliberately absent. Timestamps stay continuous across the files of one ffmpeg run, so the generated playlist plays across file boundaries without a jump. Real gaps (restarts) are marked in the playlist instead.

ffmpeg and ffprobe are found through PATH. The aperture systemd unit puts /usr/lib/aperture/bin first, so a build installed there by deploy/install.sh --pin-ffmpeg wins over the distribution’s; the default is the distribution’s ffmpeg. The installer (deploy/vendor.sh, unless you pass --skip-vendor) smoke-tests whichever one it uses by writing an MPEG-TS file and reading its duration back.

Recorder.resolveTarget picks the directory from the camera’s primary destination (cameras.location_id):

Primary destination ffmpeg writes to Path stored in segments.path
Default (location id "") <recordings dir>/<camera id>/ Absolute
Local folder <folder>/<camera id>/ Absolute
SMB or SFTP <data dir>/spool/<camera id>/ <camera id>/<epoch>.ts, relative to the share
Unknown, disabled or misconfigured Falls back to the default Absolute, on the default

The recordings dir is the recordings_path setting when an admin has set one (PUT /api/v1/system/storage), otherwise APERTURE_RECORDINGS_DIR (/var/lib/aperture/recordings when installed). The fallback row is on purpose: a broken destination never stops recording. See Storage for setting destinations up.

A camera with any of record_height, record_fps or record_kbps set (migration 0034_record_quality.sql; API fields recordHeight 144 to 4320, recordFps 1 to 120, recordKbps 100 to 100000) records a re-encoded copy instead. Live view is unaffected. wantsReencode and videoArgs in internal/record/quality.go replace -c:v copy with:

-threads 4 (before -i: caps decoder threads)
-vf "select='isnan(prev_selected_t)+gte(t-prev_selected_t,0.0850)',scale=-2:'min(1080,ih)'"
-fps_mode vfr
-c:v libx264 -preset veryfast -threads 4
-pix_fmt yuv420p
-force_key_frames expr:gte(t,n_forced*2)
-crf 26 (or -b:v 2000k -maxrate 2000k -bufsize 4000k)

That example is a camera set to 1080 lines and 10 fps.

  • Height and framerate are ceilings. scale=-2:'min(H,ih)' never upscales a smaller camera, and the framerate cap is a select filter that only drops frames (fps= would duplicate frames to reach its target). The gap it asks for is shortened by framerateSlack (0.85) so timing jitter does not drop an extra frame.
  • -pix_fmt yuv420p turns 10-bit HEVC into 8-bit H.264, which browsers play.
  • A forced keyframe every 2 seconds keeps the recording seekable whatever the framerate.
  • With recordKbps set the bitrate is fixed (-b:v, -maxrate, -bufsize twice the rate); without it the encoder targets constant quality (-crf 26).
  • Decoder and encoder each get 4 threads (reencodeThreads). Left to ffmpeg, both size their pools to the core count, and every decoder thread holds whole frames, which costs a lot of memory on very large cameras.

With an NVIDIA card whose driver and ffmpeg support NVENC, a re-encode runs on the card instead (internal/record/hwenc.go), in the best of three modes that works for the camera:

Mode Decode Framerate cap and scale Encode
gpu GPU (-hwaccel cuda) GPU (scale_cuda, which also turns 10-bit into 8-bit) h264_nvenc
hybrid CPU CPU (the filters above) h264_nvenc
cpu CPU CPU libx264, as above

The encoder runs -preset p4 -tune hq -profile:v high -rc vbr, with -cq 28 -b:v 0 for constant quality (about the size and quality of libx264 at CRF 26) or the same fixed-bitrate arguments when recordKbps is set. Keyframes and segments are the same as on the CPU: 2-second keyframes, 10-second H.264 segments. Measured on a 3840x1080 H.264 camera recorded at 360p, the gpu mode used 7% of the CPU time libx264 did, hybrid 74%.

  • A test encode at startup decides whether NVENC works; a failed test is believed for 10 minutes.
  • A run whose ffmpeg fails on a hardware step steps down (GPU decoding failed: hybrid; the encoder failed: cpu), logs it once, and tries the better mode again after 15 minutes, doubling up to 4 hours. A run that lasts 30 minutes resets the wait.
  • GeForce cards allow 8 NVENC sessions for the whole machine. Aperture counts its own; cameras past the limit record on the CPU and move over when a session frees up.
  • CUDA_CACHE_PATH points at gpu-cache in the data directory. Without a writable cache, each start compiles the scale_cuda kernels again, about 4 seconds of CPU.
  • The setting record_hw_encoding (Settings › General › Hardware encoding; hardwareEncoding in GET and PUT /api/v1/system/settings) is auto (the default) or off (always the CPU). Changing it restarts only the cameras that re-encode.
  • GET /api/v1/system/status reports, per camera, recordEncoder (copy, cpu or nvenc), recordDecoder and recordEncoderNote (why a camera is not fully on the GPU: hardwareOff, noHardware, sessionLimit, hardwareFailed, gpuDecodeFailed, unsupported, reencodeFailed), and a hardwareEncoder block for the machine.

VAAPI (Intel, AMD) and Quick Sync are not supported yet.

Without a GPU, re-encoding costs roughly a CPU core per camera. Because it can fail in ways stream copy cannot, keepReencoding counts exits: an ffmpeg that dies within 30 seconds (reencodeQuickUnder) three times in a row (reencodeMaxQuick) makes the supervisor fall back to stream copy and log re-encoding keeps failing, recording the original stream instead. The fallback lasts until that supervisor is restarted (a camera change, a settings change, an nvrd restart). A quality preference never costs the footage itself.

Changing a camera’s recording quality calls RestartCamera, because ffmpeg’s arguments are fixed at start.

Each recording camera has one supervisor goroutine (camProc) running superviseFFmpeg:

  1. ffmpeg runs until it exits or the supervisor’s context is cancelled.
  2. On an unexpected exit it logs recorder ffmpeg exited; restarting with how long it ran.
  3. Backoff: if ffmpeg ran longer than 30 seconds the wait resets to 1 second; otherwise it doubles, up to 30 seconds.
  4. The source URL and the re-encode decision are re-read on each loop; the target directory is resolved once per supervisor.

Two rules keep processes from overlapping:

  • recordCmd sets cmd.Cancel to send SIGTERM rather than SIGKILL, and cmd.WaitDelay to 10 seconds (ffmpegStopGrace). On SIGTERM ffmpeg stops reading, flushes its muxer and closes the segment it is writing, so the footage up to the stop is complete on disk. An ffmpeg still running 10 seconds later is killed.
  • A stopped supervisor moves to exiting until its ffmpeg is gone. startLocked makes a new supervisor for the same camera wait for it, because two ffmpegs writing one directory could both open the same second’s file.

These trigger a restart of one camera (RestartCamera) or all of them (RestartAll): a change of primary destination or destinations, a change of recording quality, a change of the recordings path, a change of the global Recording quality preference, the watchdog, and the oversized-segment net below.

indexOnce runs every 8 seconds and turns finished files on local destinations into segments rows. Network destinations are handled by the uploader instead.

For each camera it lists the directory and considers only regular files named <integer>.ts, so the events/ thumbnail folder and the reservation file are ignored. A per-camera cursor (lastIdx) remembers the last indexed epoch; on first sight it is seeded from the database (Store.MaxSegmentStart).

A file is complete when a newer file exists in the directory, or when it has not been modified for 30 seconds (recording paused or stopped). For each complete file past the cursor it runs:

Terminal window
ffprobe -v error -show_entries format=duration -of csv=p=0 /var/lib/aperture/recordings/<id>/1773475200.ts

The probed duration is then checked by writtenDuration: if it exceeds the time the file was actually being written (modification time minus start second) by more than 5 seconds (durationSlack), the written time wins. A timestamp jump inside a file can otherwise probe as hours of video, and an end time in the future breaks playback and hides the camera from the watchdog.

The row (Store.InsertSegment) holds:

Column Value
id Random 32-character hex id
camera_id, location_id The camera and the destination the file is on
path Absolute path, or backend-relative for network destinations
start_ts Epoch second from the file name, times 1000 (unix ms)
end_ts, duration_ms start_ts plus the checked duration
size_bytes File size
has_motion, locked 0

A file ffprobe cannot read is skipped and retried; once it has been untouched for 2 minutes the indexer logs recorder: unreadable segment, skipping and moves its cursor past it. The file stays on disk.

There is a second guard on read. clampSegmentDuration in internal/store/segments.go runs inside scanSegment, which every segment query goes through. A row whose duration is zero, negative or longer than 60 seconds (maxSaneSegmentMS) gets its wall-clock span instead, or 10 seconds if that is not believable either, and an implausible end_ts is recomputed. Stored rows are not modified; the timeline and the playlist see the same corrected values.

POST /api/v1/system/reindex (an admin session only, not an API token) calls Recorder.Reindex. It indexes every .ts file on a local destination whose start time has no row. To avoid probing tens of thousands of files it estimates each duration from the gap to the next file (accepted between 1 and 20 seconds, otherwise 10), and inserts each camera’s rows in one transaction (InsertSegmentsBatch). Network destinations are not rescanned.

internal/watchdog/watchdog.go catches a recorder that is wedged without exiting, which the supervisor’s backoff never sees. Every 15 seconds, for each enabled camera that is not in never mode:

  1. Stale: the newest segment’s end_ts is more than 90 seconds old (store.RecordingGraceMs), the camera has recorded at least once, and recording is due (RecordingDue: for a scheduled camera, its window has been open for at least 3 minutes, scheduleStartGrace). The health endpoint’s recordingOk uses the same 90 seconds.
  2. Stalled: stale, and NeedsRecovery agrees: the camera should be recording and no .ts file in its directory was modified in the last 30 seconds. A camera whose footage is only waiting on an upload is still writing, so it is left alone.
  3. Recover, at most once a minute per camera (recoverBackoff): stream.Manager.Restart re-registers the main stream in go2rtc, and RestartCamera starts a fresh ffmpeg. The fresh ffmpeg matters: an ffmpeg that stays connected through a stream restart carries on with the new source’s timestamps, and the segmenter then cuts at every keyframe or never.

Recoveries are counted per camera per UTC day for the health view. The same loop also works out whether each camera is online; that is described in Live streaming.

-map 0:v:0 and wall-clock timestamps prevent most streams that cannot be cut. As a last net, both indexOnce and uploadOnce check the newest file of each camera with notRotating: if it is larger than 256 MiB (maxSegmentBytes) and was modified in the last 30 seconds, the stream is not rotating. A normal 10-second segment is a few MB. The recorder logs recorder: active segment not rotating; restarting camera to cap file growth and calls RestartCamera. The restart closes the file, so it gets indexed and becomes subject to retention. Without this, such a file would grow until the disk is full, and because it is never indexed, retention would never see it.

A camera whose primary destination is an SMB share or SFTP server never writes across the network from ffmpeg. It writes to <data dir>/spool/<camera id>/ (Config.SpoolDir), and uploadOnce drains the spool every 8 seconds and once when the recorder starts, to pick up anything left from a previous run. A network outage therefore never interrupts ffmpeg.

For each spooled camera, oldest file first:

  1. A file is complete under the same rule as the indexer (a newer file exists, or 30 seconds without a write). Its duration is probed and checked the same way. An unreadable file is deleted from the spool once it is 2 minutes old.
  2. If the destination’s backend cannot be built (storage.Registry.For), everything stays spooled and the camera is skipped this round.
  3. Backend.Put uploads to <camera id>/<epoch>.ts. The SMB and SFTP backends write <name>.part and rename it, so a half-written file never has the final name. Connections time out after 20 seconds.
  4. The first failed upload stops this camera for the round (backpressure); everything left is retried 8 seconds later.
  5. Only after a successful upload is the row inserted, with the backend-relative path and the uploaded byte count. Only after the row is inserted is the spool file removed. If the insert fails, the spool file stays and the next upload overwrites the same remote name, so a retry is safe.

enforceSpoolCap bounds each camera’s spool at 4 GiB (spoolMaxBytesPerCam, about two hours at 4 Mbit/s). Past that it deletes the oldest un-uploaded files and logs recorder: spool over cap, dropped oldest un-uploaded segments. ffmpeg keeps recording the newest footage either way.

Share credentials are stored encrypted with AES-256-GCM (internal/secret) under the enc_key in <data dir>/secrets.json. The registry decrypts them when it builds a backend and caches the backend per location. Serving, deleting and capacity checks for a network segment all go through the same backend, keyed by the row’s location_id.

A camera can record to several destinations. The model, from migration 0030_mirrors.sql:

  • cameras.location_id is the primary destination, the only one ffmpeg writes to.
  • camera_destinations (camera_id, location_id, retention_days) lists every destination of the camera, primary included. retention_days = 0 inherits the camera’s own retention.
  • segment_copies (segment_id, location_id, path, size_bytes, created_at) holds the extra physical copies. The segments row stays the canonical copy.

mirrorOnce runs after each index and upload pass. For each mirror destination (every destination except the primary, MirrorDestinationsForCamera) it asks SegmentsNeedingCopy for up to 12 segments (mirrorBatchPerDest) that are not yet on that destination, newest first, so a mirror stays current and older footage backfills behind it. Only footage inside that destination’s retention is copied; copying what it would delete straight away wastes the transfer.

copySegment copies a local file to <folder>/<camera id>/<epoch>.ts.part and renames it, or calls Backend.Put for a network mirror (staging a network-primary file into a temporary local file first). The segment_copies row is written only after the copy succeeded, so a missing copy is retried on the next pass. The first failure on a destination stops copies to it for that pass. A slow or dead mirror can only fall behind; it can never stall recording, because ffmpeg is not involved.

handleSegmentFile serves the canonical copy, and when that is unreachable (file gone, share down) it tries each copy in turn, so a mirrored recording stays playable through either destination.

When retention has to remove the canonical copy from its location while a mirror must keep it, the janitor promotes the mirror (promoteAndRemove):

  1. It picks a copy, preferring a local one (cheaper to serve).
  2. It deletes the old canonical file first. If that fails, nothing changes and the next pass retries.
  3. Store.PromoteCopy, in one transaction, points the segments row at the copy’s location_id and path and deletes the copy row.

The order matters: once the row points elsewhere, nothing records the old file, so a file left behind would be orphaned.

Janitor.enforce in internal/retention/janitor.go runs at start, every 5 minutes, and immediately after an allocation change (EnforceNow). A mutex keeps two passes from overlapping. One pass, in order:

  1. Snapshot the queued and running exports (see protection), delete expired leases, and note whether any lease is active.
  2. For each camera:
    • Motion mode: delete segments that ended more than 2 minutes ago (motionGraceMs) and overlap no event (Store.NonEventSegments). Events already include their pre-roll and post-roll (5 seconds each by default), so the kept footage covers them.
    • Age: delete segments whose end_ts is older than the longest retention among the camera’s destinations. If any destination has unlimited retention, nothing ages out here.
    • Per-destination retention: on each destination with a retention, delete expired mirror copies, and promote expired canonical copies to a surviving mirror. A canonical copy with no mirror yet is left for the mirror pass to copy first.
    • Per-camera quota (cameras.storage_quota_bytes): delete the oldest segments until the camera is under it.
  3. Default location cap: the storage_cap_bytes setting is Aperture’s whole footprint on that disk, so footage is capped at the allocation minus app data (everything under the data dir plus each camera’s events/ thumbnails). With no cap set, the free-space floor applies instead.
  4. Each enabled destination: a local folder with an allocation gets a hard cap, without one the free-space floor. A network share with an allocation gets a delete-oldest cap, and always a free-space floor, because the share’s disk holds other things too.
  5. Reservation: resize each local destination’s reservation file (below).

Caps and floors evict oldest first in batches of 50 (deleteBatch). Mirror copies parked on a location go before canonical footage, since freeing one loses nothing. A canonical segment with a surviving mirror is promoted instead of deleted. A full delete (Janitor.delete) removes every mirror copy, then the canonical file, then the row. Rows with locked = 1 are skipped by every retention query.

The janitor removes the file first and the row second, and keeps the row whenever the file may still be there (removeFile). The row is the only record of a file; a row dropped after a failed delete would leave footage that retention can never see again, filling the disk behind its back. A file that is already gone counts as removed. The next pass retries everything that failed. The Remove footage… action in Playback (DELETE /api/v1/cameras/{id}/recordings, handleDeleteRecordings) follows the same rule and reports failedSegments.

A destination that is down could make every delete wait for a full connection timeout, with every other camera queued behind it. So each pass has a failed-delete budget per location: once 30 seconds (deleteFailureBudget) have been lost to failed deletes on one location, the remaining deletes there are not attempted this pass. An oldest-first loop also gives up after reading past 500 undeletable items (maxStuck). Failures are logged once per location per pass, retention: could not delete footage, keeping it to retry next pass, with counts of failed and not-tried deletes.

Two mechanisms stop retention from deleting footage that something is reading:

  • Segment leases (segment_leases, migration 0025): a time window on one camera, protected until it expires. Exports take one per camera (export:<job id>), and API clients can take one with POST /api/v1/cameras/{id}/lease ({"fromTs", "toTs", "ttlSec"}, at most 7200 seconds) and release it with DELETE /api/v1/cameras/{id}/lease/{leaseId}. Janitor.delete refuses a segment that overlaps an unexpired lease.
  • Running exports: segments overlapping a queued or running export’s window are skipped as well, but only for exports younger than 2 hours (exportMaxProtectAge), so a stuck render cannot hold footage on a nearly full disk.

See Export for the user side.

freeFloor is how much the free-space net keeps free on a local filesystem: 7 % of it (minFreeFraction), and at least 5 GiB (minFreeBytesFloor), where that 5 GiB minimum is itself capped at a quarter of the filesystem so a small disk is not wiped trying to reach it. On a network share (shareFreeFloor) there is no percentage, only the 5 GiB minimum with the same quarter cap: 7 % of a large NAS pool would delete footage to defend space nobody reserved for it.

With an allocation set, reserve.Reconcile (internal/reserve/reserve.go) keeps a file named .aperture-reservation in the destination’s root. Its size is the allocation minus the footage (and app data, for the default), and its blocks are really allocated with fallocate, so no other program can use that space, even while Aperture is stopped. As footage grows the file shrinks; at the ceiling the janitor trims the oldest footage. The file never grows into the last 3 GiB of the filesystem (SafetyMargin). With no allocation the file is removed. Storage covers the wizard that sets this up, and Capacity the sizing.

The data and recordings directories must not nest

Section titled “The data and recordings directories must not nest”

The janitor counts everything under the data dir as app data and subtracts it from the default location’s cap. If the recordings directory sat inside the data dir, all footage would count as app data, the cap target would drop to zero, and the first pass would delete every recording on the default location.

So deploy/libexec/aperture-harden, which the aperture unit runs as ExecStartPre, refuses to start when APERTURE_RECORDINGS_DIR is inside APERTURE_DATA_DIR:

aperture-harden: FATAL: APERTURE_RECORDINGS_DIR is inside APERTURE_DATA_DIR.

Keep them as sibling directories, as the installer does (/var/lib/aperture/data and /var/lib/aperture/recordings). The object-recognition models live in /var/lib/aperture/ai, beside the data dir rather than in it, for the same reason. The API also refuses to add a local destination whose path is the data dir or the current recordings dir (handleCreateLocation, handleTestLocation); that check compares paths exactly, it is not a nesting check.

There is no special disk-full mode; the layers above are designed to keep it from happening:

  • With an allocation, the reservation file holds the space and the cap trims footage before the allocation is exceeded.
  • Without one, the free-space floor deletes the oldest footage on each pass.
  • A camera’s spool for a network destination is capped at 4 GiB.
  • A segment that does not rotate is cut at 256 MiB.

If a disk fills anyway (another program writes to it between passes), a recording ffmpeg that exits is restarted by its supervisor with the usual backoff, and one that stays up without writing is restarted by the watchdog once its footage is 90 seconds stale. Recording resumes once a janitor pass, at most 5 minutes later, has freed space on a disk Aperture is allowed to delete from. Footage that ffmpeg could not write in the meantime is lost. On a disk you share with other data, set an allocation; see Storage and Troubleshooting.

The aperture unit uses KillMode=mixed and KillSignal=SIGTERM: systemd sends SIGTERM to nvrd alone, so its ordered shutdown runs undisturbed, and SIGKILLs the whole control group only after TimeoutStopSec=45. On SIGTERM, main in cmd/nvrd/main.go shuts down in this order, each step bounded (cmd/nvrd/shutdown.go):

  1. Extensions, while the API they call is still up: SIGTERM, SIGKILL after their 5-second grace, plus 2 seconds of slack (extStopSlack).
  2. Background services, up to 20 seconds (bgStopWait). Cancelling their context makes Recorder.Run call drain: every supervisor’s ffmpeg gets SIGTERM, finishes the segment it is writing, and Run returns only once every ffmpeg has exited or been killed after 10 seconds. A janitor pass in flight finishes; the detectors reap their own ffmpeg.
  3. HTTP, up to 10 seconds (httpStopWait), so live view and the web app keep working until the end.
  4. Storage: the backend registry and then the database are closed.

The worst case is about 37 seconds, inside the 45-second unit timeout; normally it takes a second or two. The log line shutdown complete reports the time of each phase and the slowest service. After a restart, the indexer picks up the last segment because a newer file exists or because it has gone quiet for 30 seconds, and the uploader drains whatever the previous run left in the spool.

There are no playlist files on disk. handleHLS builds a VOD playlist from the database on each request:

GET /api/v1/cameras/{id}/hls?from=<unix ms>&to=<unix ms>

It needs the media:read scope and access to the camera (see Scopes). Without from and to it covers the last 24 hours. It lists the camera’s segments overlapping the range (Store.ListSegments, ordered by start_ts) and writes:

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-PLAYLIST-TYPE:VOD
#EXT-X-TARGETDURATION:11
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-PROGRAM-DATE-TIME:2026-03-14T08:00:00.000Z
#EXTINF:10.010,
seg/<segment id>.ts
#EXTINF:9.990,
seg/<segment id>.ts
#EXT-X-DISCONTINUITY
#EXT-X-PROGRAM-DATE-TIME:2026-03-14T08:00:32.000Z
#EXTINF:10.000,
seg/<segment id>.ts
#EXT-X-ENDLIST
  • EXT-X-TARGETDURATION is the longest segment’s duration, rounded up (at least 1).
  • EXTINF is each row’s duration_ms in seconds, three decimals.
  • EXT-X-DISCONTINUITY marks a hole of more than 2.5 seconds (discontinuityGapMS) between one segment’s end and the next one’s start. The threshold is not 1 second because start times come from epoch-second file names and carry up to 999 ms of truncation, while end times carry a probed duration in milliseconds. A false marker is not harmless: at a discontinuity hls.js places the next fragment by playlist time instead of its real timestamps, which creates the buffer hole the marker claims to describe. Within one ffmpeg run timestamps are continuous, so real gaps come from restarts and are never sub-second.
  • EXT-X-PROGRAM-DATE-TIME anchors wall-clock time at the first segment’s exact start_ts and again after every discontinuity, because hls.js resets its date accumulation there. Within a run only the EXTINF durations can drift, and each anchor bounds that drift.
  • The response has Content-Type: application/vnd.apple.mpegurl and Cache-Control: no-cache.

The segment URIs are relative, so they resolve to GET /api/v1/cameras/{id}/seg/{seg} (handleSegmentFile, also media:read). It checks that the segment belongs to that camera and answers with video/mp2t. Local files go out through http.ServeFile, network files stream through the backend with http.ServeContent; both support HTTP range requests. Then it falls back to mirror copies, then 404.

One repair happens at serve time: a segment whose MPEG-TS program table declares an audio track that carries no AAC frames gets a silent track substituted as it is served (internal/api/segment_fixup.go). Browsers’ Media Source Extensions cannot add or drop an audio track mid-stream, so the whole archive keeps one track layout. The check scans the first 1 MiB of the file without spawning a process, so healthy segments keep the direct file path; repairs run at most two at a time, with a 6-second limit, for files up to 64 MiB. Stored files are never modified.

web/src/screens/Playback.tsx loads one playlist per day (from and to are the day’s start and end) into hls.js. Playlist time is the sum of segment durations, not wall-clock time: gaps take no playlist time. web/src/lib/playlist.ts converts between the two with wallToOffset and offsetToWall, using the day’s segment list, and hands the start offset to hls.js as startPosition. The player allows buffer holes of up to 0.5 seconds (maxBufferHole) and nudges past larger ones, because recorder restarts leave real holes.

The timeline rail draws from GET /api/v1/cameras/{id}/coverage (coverage:read), which merges segments server-side into covered ranges; tolerance_ms (default 2000) sets how large a gap is joined over. The rail asks for the day and its neighbours with a tolerance of 15000.

A runtime switch, PUT /api/v1/system/playback with {"pdtSeek": true}, stores playback.pdt_seek and shows it in GET /api/v1/capabilities. It is off by default; the current web player does not read it and seeks by offset as described above. Other HLS players can use the date-time tags directly.

Hover previews on the timeline come from GET /api/v1/cameras/{id}/frame?t=<unix ms> (handleFrame): the time is rounded down to the second, ffmpeg extracts one 320-pixel-wide JPEG at the offset inside the segment, and the result is cached under <data dir>/frame-cache/<camera id>/. At most two extractions run at once, each limited to 6 seconds, so a burst of hovering cannot take CPU from recording. A segment on a network destination is first downloaded into <data dir>/rcache.

Related: Recording, Storage, Playback, Data model.