OptrisOptrisDocumentation

Documentation/OTC SDK/OTC SDK — C++ API referencev12.0

optris::sdk::rec::RecordingController

Fed thermal frames by the Imager's frame dispatch. When pre-roll is enabled, frames are continuously buffered; when recording starts, the buffer is flushed to disk and recording continues until StopRecording().

While recording, each frame also carries the region record (the leaf matrices of any measuring area that moved, plus every area's readings and alarm state), so a recording captures what its regions did, not just the frames.

Public types

FrameStateProvider

std::function< FrameCameraState()> FrameStateProvider

Gathers FrameCameraState. Supplied by the owner, called on the camera's frame thread, once per frame that is being recorded or kept -- so it must be quick. It is read there rather than by the writer deliberately: these are properties of the moment the frame arrived, and a backlog can be seconds deep.

WriteInterposer

std::function< void(size_t bytes)> WriteInterposer

What a test puts between the muxer and the operating system.

Spelled out here rather than taken from rec::Recorder, so this header does not have to include the Recorder's. It is the same type, and that method is where its contract is written down.

SnapshotWriter

std::function< void(const std::string &path, optris::sdk::SnapshotFormat format)> SnapshotWriter

Writes one still image. Supplied by the owner.

Interval capture needs the most recent frame and the snapshot metadata, and both belong to the Imager rather than to this class. Taking the writer as a callback keeps that dependency pointing one way, and lets the tests drive interval capture with no camera at all. It throws on failure, like the rest of this surface, and interval capture logs the refusal and keeps running: one image that could not be written is not a reason to stop capturing.

RecordingEventCallback

std::function< void(const std::string &path)> RecordingEventCallback

RecordingPhaseCallback

std::function< void(const RecordingEvent &)> RecordingPhaseCallback

One handler for every phase a recording can reach.

RecordingDetailCallback

std::function< void(const RecordingEventDetail &)> RecordingDetailCallback

One handler for every phase, given the recording each event belongs to and, on the events that end it, its final statistics. Added in 12.0.15.

Public functions

RecordingController

RecordingController(optris::sdk::Imager &imager)

~RecordingController

~RecordingController()

Quiesce

void Quiesce()

Stop everything that runs on a thread of this controller's own, and return only once nothing is inside it.

Joins the timer thread, finalises a recording that is still open (waiting for a failed recording's finalize too), and closes the rolling history's open segment. Idempotent: the destructor calls it, and calling it first leaves the destructor nothing to do.

Exists so that the owner can perform this shutdown while it can still answer for itself. Imager::~Imager() hands its Impl to Imager::TearDown() by value, so Imager::impl_ is null for the whole of the teardown that destroys this controller -- and both the recording stop and the interval capture's snapshot writer read the camera through that handle.

RecordingController

RecordingController(const RecordingController &)=delete

operator=

RecordingController & operator=(const RecordingController &)=delete

FeedThermalFrame

void FeedThermalFrame(const optris::sdk::ThermalFrame &frame)

Feed one thermal frame to the recorder/pre-roll buffer. Called by the Imager's frame dispatch so recording runs alongside the app's own thermal callback instead of replacing it.

SetFrameStateProvider

void SetFrameStateProvider(FrameStateProvider provider)

Install the provider the frame path reads the camera through. Set by the Imager when it creates the controller.

Without one, a recording still writes its frames but carries no region records, no render block and no flag-policy block, and says so in the log once per recording rather than silently. That is the state the record-layer tests drive this class in, which have no camera at all.

EnablePreRoll

void EnablePreRoll(std::chrono::milliseconds duration)

Enable the pre-roll ring buffer.

Pre-roll and continuous recording, and why only one at a time: Pre-roll and continuous recording, and why only one at a time These answer the same question -- what happened just before? -- at two scales. This one keeps deep-copied frames in RAM, so its depth is seconds and its cost is memory; StartContinuous() keeps FFV1 segments on disk, so its depth is hours and its cost is disk (7.4 GB/h measured on a 640x480 sensor at 32 Hz).

Both work and neither is going away. Pre-roll is still the right answer when there is no disk to spend, when a few seconds is enough, and for a bounded alarm recording, which is what it was built for. Continuous recording is the answer when the history has to outlive the event, or outlive the process.

What is refused is both at once on one camera, because that would encode and store every frame twice over for one answer. This call returns kInvalidState while a continuous recording is running, and StartContinuous() returns kInvalidState while pre-roll is enabled; each message names the other. Stop one to use the other.

Frames are captured into a ring buffer of the given duration. The buffer depth is computed from the Imager's frame rate and then capped by the memory budget; GetPreRoll() reports what is actually in force.

The duration is what the buffer holds, whatever rate frames: The duration is what the buffer holds, whatever rate frames arrive at The depth is a frame count derived from the sensor's rate, and that is not always the rate frames are delivered at -- with ProcessingConfig::subsampled_framerate set, a 30 s request on a 27 Hz camera subsampled to 1 Hz used to keep 810 frames, which is 13.5 minutes. The buffer also evicts by frame timestamp, so what is held is this duration and the depth is the memory bound.

What a buffered frame carries: What a buffered frame carries The region record, the render block and the flag-policy block that were in force as the frame arrived -- so a replay of the pre-roll shows the measuring areas and the colour range it was recorded with. Building them is what pre-roll costs while nothing is being recorded: about 260 B of telemetry a frame with one rectangle, and one call to the frame-state provider per frame.

Milliseconds, not seconds. Whole seconds meant that a request for 900 ms became a zero-capacity ring that accepted every frame and kept none, reported itself as enabled, and produced a recording with no pre-roll in it.

Parameters

Name Description
duration Pre-roll buffer duration. Must be positive. A duration shorter than one frame period is raised to one frame period, on the same reasoning as interval capture: a buffer cannot hold less than one frame, and the raise is observable through GetPreRoll() and logged.

Exceptions

Name Description
InvalidArgumentException when duration is not positive.
InvalidStateException when a continuous recording is running; it already keeps this history, on disk.

DisablePreRoll

void DisablePreRoll()

Disable pre-roll buffering and discard the buffer.

The buffered frames' memory is released, not merely forgotten. This used to reset the ring's counters and leave every stored frame's pixels allocated, so an application that turned pre-roll off to free memory freed none of it until the camera was closed or pre-roll was armed again: measured on a 640x480 at 32 Hz with 10 s armed, +200 MB over the baseline before and +200 MB after.

IsPreRollEnabled

auto IsPreRollEnabled() const -> bool

Whether pre-roll buffering is active.

GetPreRoll

auto GetPreRoll() const -> PreRollState

Read the pre-roll settings back.

SetPreRollMemoryBudget

void SetPreRollMemoryBudget(uint64_t bytes)

Cap how much memory the pre-roll ring may use.

Every buffered frame is a deep copy, so an uncapped ring is a memory leak with a duration on it -- sixty seconds of a 640x480 sensor at 32 Hz is about 1.2 GB. The depth is cut to fit rather than the request being refused, because a shorter pre-roll is what the caller wanted an approximation of, and GetPreRoll() says what it got.

Takes effect on the next EnablePreRoll().

Parameters

Name Description
bytes The budget. Zero means no cap, which is what the SDK did before this existed.

GetPreRollMemoryBudget

auto GetPreRollMemoryBudget() const -> uint64_t

The pre-roll memory budget in force.

StartContinuous

void StartContinuous(const ContinuousConfig &config)

Start writing everything this camera sees to disk, for as long as it runs.

The rolling history is not a recording in the sense the rest of this class means: nothing is "started" at the interesting moment, IsRecording() stays false, and the files are segments pruned against a retention window rather than a take somebody keeps. What a person keeps comes out of SaveClip().

A manual or alarm-driven StartRecording() still works while this runs, and writes its own file. The two cost the same frames twice, which is a reasonable thing to want -- an operator's recording alongside the history -- and is a deliberate choice rather than the accidental double-store that pre-roll plus continuous would be.

The camera's metadata, the application's attachment providers and the stream dimensions are supplied exactly as they are for an ordinary recording, so a segment and a clip describe their camera the same way a take does.

Parameters

Name Description
config Directory, segmentation, retention and the disk-full decision. See ContinuousConfig.

Exceptions

Name Description
InvalidStateException when a continuous recording is already running, or pre-roll is enabled (see EnablePreRoll()).
Whatever ContinuousRecorder::Create() raises.

StopContinuous

void StopContinuous()

Stop writing to the rolling history.

The segments stay on disk and stay cuttable, and the next StartContinuous() on the same directory adopts them. A no-op when nothing is running.

IsContinuous

auto IsContinuous() const -> bool

Whether a rolling history is being written.

Independent of IsRecording(), which is about a take.

GetContinuousTimeline

auto GetContinuousTimeline() const -> std::vector< TimelineSpan >

What history is on disk. See ContinuousRecorder:: GetTimeline(). Empty when nothing is running.

GetContinuousStats

auto GetContinuousStats() const -> ContinuousStats

What the rolling history has done -- segments written, pruned, bytes reclaimed, free space, whether the retention window had to be shortened. See ContinuousStats.

SaveClip

auto SaveClip(uint64_t from_us, uint64_t to_us, const std::string &output_path) -> ClipResult

Cut a keepable file out of the history.

This is the replacement for "start recording and hope the interesting part has not happened yet": the window is chosen after the fact, from frames already on disk, and the cut is a container copy with no re-encode. See ContinuousRecorder::ExtractClip().

Parameters

Name Description
from_us In point, on the camera clock -- the domain TimelineSpan and Telemetry::timestamp_us use.
to_us Out point.
output_path Where the clip goes.

Returns: What was produced.

Exceptions

Name Description
InvalidStateException when no continuous recording is running.
Whatever ContinuousRecorder::ExtractClip() raises.

AddAttachmentProvider

auto AddAttachmentProvider(AttachmentProvider provider) -> uint32_t

Register a provider pulled once per recording file, as that file's header is written.

Providers are invoked before any frame is written to the file -- the only window in which an MKV attachment can still be added -- and that is the guarantee to rely on. It is not during StartRecording(): registering happens there, but the pull waits for the header, which waits for the cover's look-ahead and so lands after the call has returned. A pre-roll makes no difference to that: the pre-roll is handed to the same write queue as the live frames rather than flushed on the timer thread, so the pull happens on this controller's writer thread either way.

The same code path serves a manual StartRecording() and an alarm-driven one, which is the point: an application writes one provider and it works for both, including the trigger-started case where it never calls StartRecording() at all.

See also: AttachmentProvider for which thread the provider runs on, and whether any lock is held while it does. For a recording it is never the thread that called StartRecording().

Returns: An id for RemoveAttachmentProvider().

RemoveAttachmentProvider

void RemoveAttachmentProvider(uint32_t provider_id)

StartRecording

void StartRecording(const std::string &output_path, const std::optional< optris::sdk::AlarmEvent > &cause=std::nullopt)

Start recording explicitly.

If pre-roll is enabled, the buffer is flushed first -- on the controller's own thread, so this call returns without waiting for the encode and frame delivery is never stalled by it.

Starting while already recording is an error: Starting while already recording is an error It returns kInvalidState and changes nothing. It used to return success and do nothing at all, so a caller that asked for a second file was told it had one, IsRecording() agreed, and no such file ever existed. Stop the running recording first if you mean to start another.

Parameters

Name Description
output_path Output MKV file path.
cause The alarm that asked for this recording, if any. Passed on to the attachment providers.

Exceptions

Name Description
InvalidStateException when a recording is already running.
PathExistsException when a regular file is already at output_path. The SDK refuses rather than truncating it: the file is opened with O_TRUNC, so overwriting would lose a measurement with no error and no log line. Pass a free path, or remove the file deliberately first.
IoException or InsufficientSpaceException when the file cannot be opened or the destination is below the caller's own free-space floor.

StartRecording

void StartRecording(const std::string &output_path, const RecordingOptions &options, const std::optional< optris::sdk::AlarmEvent > &cause=std::nullopt)

Start recording with duration and segmentation settings.

Parameters

Name Description
output_path Output MKV file path, and the stem every later segment is named from.
options Duration and segment limits. See RecordingOptions.
cause The alarm that asked for this recording, if any.

Exceptions

Name Description
InvalidArgumentException when a limit is negative.
As the overload above otherwise.

StopRecording

void StopRecording()

Stop the current recording and finalize the file.

Safe to call at any time, from any thread, however many times. A recording that has already stopped -- including one that stopped itself at the end of its duration -- is left alone rather than finalized a second time.

Reports RecordingStopReason::kApplication, because that is what calling this is.

RecordingPhase::kStopped is raised, and this returns, only once every RecordingPhase::kSegmentCompleted of the parts the recording finished has been delivered and its handler has returned, for at most 5 seconds of a handler that does not return. See Recorder::Stop().

StopRecording

void StopRecording(RecordingStopReason reason, const std::string &message={})

Stop the current recording, saying who ended it.

reason reaches the application as RecordingEvent::stop_reason on RecordingPhase::kStopped, and message as RecordingEvent::message beside it.

A Stopped with no message used to read identically whoever had ended the recording: the application calling StopRecording(), a bounded recording reaching its duration, an alarm rule's stop, or the SDK's own reconnect stopping it before a re-open. An application could see that its file had ended and not why, which is what makes an application guess ("a bounded recording reached its duration, a write failed, or an alarm rule stopped it").

The field is the contract and the message is not. A caller that has to match text cannot be told apart from one that is guessing, and the text is free to be reworded or translated without anybody thinking they have changed an interface. The message is for a log a person reads.

Parameters

Name Description
reason Who ended it. RecordingStopReason::kUnknown is accepted and means "this caller is not saying", which is what a Stopped carried before the field existed.
message Human-readable detail, or empty.

OnCameraOutage

void OnCameraOutage(const std::string &message={})

Tell the recording layer that the camera has stopped delivering and is about to be re-opened.

Called by the SDK's own reconnect, once per outage, immediately before the teardown. An application driving a controller by hand may call it for an outage of its own.

Two things happen, and the second happens either way:

  1. A running recording is stopped -- finalized, with RecordingStopReason::kReconnect -- unless it was started with RecordingOptions::hold_open_across_reconnect true, in which case it is held open across the outage.
  2. The next frame to arrive is marked as being on the far side of a hole, whether it goes into a held-open recording or into an armed pre-roll ring. See rec::RecordingGap, and rec::Telemetry::gap, which is where a reader finds it.

The second is why this is one call rather than a conditional stop: an armed pre-roll keeps its pre-outage frames on purpose -- they are the history somebody asked for -- so a recording started after the camera comes back begins with frames from both sides of the outage, and the marker is what stops a reader having to infer the join from a jump in the timestamps.

Safe on a controller that is neither recording nor buffering: it leaves a marker that the next frame will carry if either starts before one arrives, and costs nothing otherwise.

Parameters

Name Description
message What the SDK knows about the outage. Reaches the stopped recording as RecordingEvent::message and the marked frame as rec::RecordingGap::message.

IsRecording

auto IsRecording() const -> bool

Whether a recording is currently active.

GetRecordingToken

auto GetRecordingToken() const -> uint64_t

Which recording is open: a number that identifies this take, or 0 when nothing is recording.

Every start gets a new number and no number is reused, so two reads that return the same non-zero value are looking at the same recording and two that differ are not. Nothing is promised about the value itself -- it is an identity, not a count, and it is not part of the file or the public record.

IsRecording() answers "is something recording"; this answers "is it still the one I was looking at". The difference matters to anything that started a recording and may later want to end it: an alarm rule stopping on its own clear used to stop whatever was open, including an operator's manual recording its rule had never started, because a boolean cannot tell the two apart.

Lock-free, like IsRecording(): a caller polling it must not be the thing that waits for a disk.

GetLastError

auto GetLastError() const -> std::optional< optris::sdk::Error< RecordError > >

Why the last recording stopped, if it stopped by failing.

A write that fails happens on the writer thread, where there is no caller to hand an error to. The recording is stopped -- so IsRecording() tells the truth -- and the reason is left here. Empty when nothing has failed since the last successful StartRecording(), which clears it.

A full disk, a permission change and a drive removed mid-recording all arrive this way. The path that could not be written at all is refused by StartRecording() instead.

StartRecording

void StartRecording(const std::string &output_path, std::chrono::milliseconds duration, const std::optional< optris::sdk::AlarmEvent > &cause=std::nullopt)

Record for duration, then stop without being asked.

The clock starts when the recording goes live, which is after any pre-roll buffer has been flushed. The duration therefore bounds what happens from here on, and a bounded recording with pre-roll enabled produces a file about pre-roll + duration long. That is the useful reading: the caller is asking for the next thirty seconds, and the pre-roll is history it separately asked to keep.

The recording is closed on a dedicated thread, never on the one delivering frames, so finalizing the file cannot stall the camera.

Stopping early with StopRecording() is fine and cancels the deadline. The auto-stop only ever closes the recording it was armed for, never a later one that happens to be running by then.

Parameters

Name Description
output_path Output MKV file path.
duration How long to record. Must be positive.
cause The alarm that asked for this recording, if any. Passed on to the attachment providers.

Exceptions

Name Description
InvalidArgumentException when duration is not positive.
InvalidStateException when a recording is already running -- including an unbounded one, which this used to accept without arming any deadline at all.
As the overload above otherwise.

GetRemainingDuration

auto GetRemainingDuration() const -> std::optional< std::chrono::milliseconds >

How much of a bounded recording is left to run.

Returns: The remaining time, or nullopt when nothing is recording or the running recording has no duration limit.

GetStatistics

auto GetStatistics() const -> RecordingStats

What the current -- or last -- recording did with its frames.

Reset when a recording starts, and kept after it stops, so the totals are readable once the file is closed.

Every frame the recording was offered is in exactly one of the counters or still in the write queue -- frames_written + lost + RecordingStats::queue_depth` -- which is what makes "1,204 written, 3 lost" a statement about the file rather than a guess, including while the recording runs.

Never behind a disk. This reads a snapshot the writer thread banks after every frame; it does not reach into the Recorder, and no getter on this class does. A thread that asks how a recording is doing used to wait for the slow write it was asking about.

SetWriteInterposer

void SetWriteInterposer(WriteInterposer interposer)

Interpose on every write the next recording makes to the operating system. A test hook.

Handed to each Recorder this controller opens from now on, including the rolling history's. See rec::Recorder::SetWriteInterposer() for what chaining a context does and does not change about the file. It exists because a slow drive is what the off-thread write has to survive, and no test tree has one.

Parameters

Name Description
interposer Called on the writing thread before each block of container bytes goes out, with the size of that block. An empty function removes the hook.

Has no effect on a recording that is already open.

StartIntervalCapture

void StartIntervalCapture(const IntervalCaptureConfig &config)

Begin capturing a still image every so often.

Captures run on the same dedicated thread as the bounded recording deadline and never on the frame-delivery thread, because writing an image is file I/O and a camera is waiting on that thread.

An interval shorter than the frame period: An interval shorter than the frame period Nothing can produce more images than there are frames, so an interval below the camera's frame period is raised to the frame period rather than refused -- an application asking for "as often as possible" gets exactly that. The value actually in force is reported by GetIntervalCaptureInterval(), so the adjustment is observable rather than silent, and it is logged once when it happens.

Interval capture is independent of recording: it runs whether or not a recording is active, and StopRecording() does not stop it.

Parameters

Name Description
config Interval, destination and format.

Exceptions

Name Description
InvalidArgumentException when the interval is not positive or the name pattern is empty.
InvalidStateException when no snapshot writer has been installed, which on a camera the SDK built never happens, because the Imager installs one.
IoException when the folder cannot be created or written to; the message names it. Nothing starts then.

StopIntervalCapture

void StopIntervalCapture()

Stop capturing at intervals. A no-op if not capturing.

An image being written when it is called is finished before it returns, so the directory then holds whole files only and GetIntervalCaptureCount() no longer changes.

IsIntervalCapturing

auto IsIntervalCapturing() const -> bool

Whether interval capture is currently running.

GetIntervalCaptureInterval

auto GetIntervalCaptureInterval() const -> std::chrono::milliseconds

The interval actually in force, after any raise to the frame period. Zero when interval capture is not running.

GetIntervalCaptureCount

auto GetIntervalCaptureCount() const -> uint64_t

How many images the running interval capture has written.

Reset each time interval capture starts. Counts only images that reached disk, so a run whose writes are failing reports fewer than the elapsed time would suggest.

SetSnapshotWriter

void SetSnapshotWriter(SnapshotWriter writer)

Install the writer that interval capture uses. Set by the Imager when it creates the controller.

SetDeviceMetadata

void SetDeviceMetadata(const DeviceMetadata &metadata)

SetOutputDirectory

void SetOutputDirectory(const std::string &dir)

Set the output directory for alarm-driven recordings.

A recording started by an alarm action is written here with a name expanded from the action's pattern. Defaults to the current working directory.

Parameters

Name Description
dir Output directory path.

OnRecordingStarted

void OnRecordingStarted(RecordingEventCallback callback)

Called when a recording starts, however it was started.

OnRecordingStopped

void OnRecordingStopped(RecordingEventCallback callback)

Called when a recording stops and file is finalized.

SetRecordingCallback

void SetRecordingCallback(RecordingPhaseCallback callback)

Be told that a recording started, stopped, rolled over or failed.

The two callbacks above cannot report a failure, and a failure is the case an application most needs: a recording that dies on a full disk leaves IsRecording() false and a truncated file, which from outside is indistinguishable from one that was stopped on purpose.

Threading: Threading Fired on whichever SDK thread reached the phase -- the caller's thread for a start it asked for, the controller's timer thread for an auto-stop, and the controller's writer thread for a failure or a finished segment. Never the camera's frame thread, which is where the last two used to come from.

Never with the controller's lock held and never from inside a write, so the handler may call back in -- StopRecording() included, which a stop asked for on the writer thread recognises and does not wait for itself over. It runs on a thread the SDK needs, so it should still return promptly: a handler that blocks blocks the recording.

SetRecordingDetailCallback

void SetRecordingDetailCallback(RecordingDetailCallback callback)

Be told what SetRecordingCallback() tells, together with which recording each event is about and the final statistics of the recording a Stopped ends. Added in 12.0.15.

Independent of SetRecordingCallback(): either, both or neither may be installed, and each event reaches the RecordingEvent handler first and this one straight after, on the same thread and under the same rules (see there). Pass nullptr to stop delivery.

The handler to use when events are acted on later, on a thread of the application's: GetStatistics() then describes whatever recording is current by the time it is read, which need not be the one the event is about. See RecordingEventDetail.

SetSegmentLimitAction

void SetSegmentLimitAction(SegmentLimitAction action)

What a recording does when it reaches its segment limit. Added in 12.0.10.

Applies to every recording started after the call, whether the application or an alarm rule starts it, and only to one that asks for a segment limit. The default, SegmentLimitAction::kContinueSeries, is what a segmented recording has always done. See SegmentLimitAction for the files and the events each choice gives; SegmentLimitAction::kStopRecording (12.0.28) ends the recording at the limit with RecordingStopReason::kSegmentLimit.

GetSegmentLimitAction

auto GetSegmentLimitAction() const -> SegmentLimitAction

What SetSegmentLimitAction() last set.