OptrisOptrisDocumentation

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

optris::sdk::Recorder

Writes what a camera is seeing to disk: recordings, still images, and the files your application wants to travel with them.

A handle, not an owner. Reached through Imager::Recorder().

Unlike the other sub-interfaces this one belongs to a camera specifically -- a Player is already a recording, and has nothing to record.

Public functions

Recorder

Recorder()=default

Recorder

Recorder(Imager *imager)

EnablePreRoll

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

Capture continuously into a fixed-duration ring buffer. When a recording starts -- by your call, or by an alarm rule carrying a RecordingAction -- the buffer is flushed to disk first, so the recording includes what happened before you asked for it.

Parameters

Name Description
duration How much history to keep. Must be positive. Anything shorter than one frame period becomes one frame, and a depth that would cost more than the memory budget is cut to fit -- GetPreRoll() reports what is actually in force, which is not always what you asked for.

Exceptions

Name Description
InvalidArgumentException if duration is not positive. A type of its own since the recording refusals were made exhaustive: it was a plain SdkException, which reaches C as OPTRIS_SDK_ERROR_UNKNOWN.

DisablePreRoll

void DisablePreRoll()

GetPreRoll

auto GetPreRoll() const -> rec::PreRollState

What the pre-roll buffer is actually doing: whether it is on, the duration in force, how deep the ring really is, and how much history it is holding.

Worth reading rather than assuming. An application that wants to show the user "3 s of pre-roll" should show this, not the value it passed in.

To decide whether the buffer is full, read rec::PreRollState::holds_duration. Comparing buffered with frames is never true on a camera that delivers fewer frames than its sensor's rate, however long the buffer is armed.

SetPreRollMemoryBudget

void SetPreRollMemoryBudget(uint64_t bytes)

Cap the memory the pre-roll ring may use. 512 MiB by default.

Every buffered frame is a full copy of the pixels, so a long pre-roll on a large sensor is measured in gigabytes. The depth is cut to the budget rather than the request refused; see GetPreRoll() for what survived.

GetPreRollMemoryBudget

auto GetPreRollMemoryBudget() const -> uint64_t

StartContinuous

void StartContinuous(const rec::ContinuousConfig &config)

Record everything this camera sees to disk for as long as it runs, and cut keepable files out of it afterwards.

The way a security recorder works: nothing is started at the interesting moment, because by then it is already recorded. See rec::ContinuousConfig for the retention window and the disk-full decision, and rec::ContinuousRecorder for the model.

IsRecording() stays false while this runs -- a take and a history are different things -- and Start() still works alongside it, writing its own file.

Pre-roll and this are mutually exclusive: Pre-roll and this are mutually exclusive They answer the same question at two scales, and running both would store every frame twice. This throws InvalidStateException while pre-roll is enabled, and EnablePreRoll() throws while this is running; each message names the other.

Exceptions

Name Description
InvalidStateException when a history is already running or pre-roll is enabled.
IoException when the directory cannot be used or the volume is already below min_free_bytes plus room for one segment. OPTRIS_SDK_ERROR_IO, which optris_sdk_imager_start_continuous() has always documented and did not deliver.
InvalidArgumentException when the retention policy has no bound at all, or the configuration is otherwise unacceptable -- no directory, no segment limit. OPTRIS_SDK_ERROR_INVALID_ARGUMENT, likewise documented and likewise not delivered: both of these were a plain SdkException and so OPTRIS_SDK_ERROR_UNKNOWN, which is the same answer the ABI gives a C++ exception it has never heard of. The two are separate types because the remedies are different -- one is another destination, the other a field the caller must set.

StopContinuous

void StopContinuous()

Stop writing the rolling history. The segments stay on disk and stay cuttable. A no-op when nothing is running.

IsContinuous

auto IsContinuous() const -> bool

Whether a rolling history is being written. Independent of IsRecording().

GetContinuousTimeline

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

What history is on disk, oldest first. Empty when nothing is running. See rec::TimelineSpan.

GetContinuousStats

auto GetContinuousStats() const -> rec::ContinuousStats

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

SaveClip

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

Cut a keepable file out of the history.

A container copy: no frame is decoded and none is re-encoded, so the clip's temperatures are the history's temperatures exactly.

Parameters

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

Returns: What was produced, including whether the window was fully covered. See rec::ClipResult.

Exceptions

Name Description
InvalidStateException when no history is running, which is a different question from the window being wrong: this one is fixed by starting a history.
InvalidArgumentException when the window cannot exist -- an out point at or before the in point -- or output_path is empty. OPTRIS_SDK_ERROR_INVALID_ARGUMENT.
IoException when the clip was written but could not be put at output_path. OPTRIS_SDK_ERROR_IO.

Start

void Start(const std::string &output_path)

Start recording to an MKV file. If pre-roll is on, the buffer is flushed first -- on the SDK's own thread, so this call does not wait for it and frame delivery is not stalled by it.

A path that already holds a file is refused, not overwritten: A path that already holds a file is refused, not overwritten Only a regular file: a directory, a device node or a FIFO holds no measurement to lose and still gets the real reason it could not be opened. A symlink is followed, because the file it points at is the one that would be destroyed.

Read this if you deliberately overwrite a fixed name, a latest.mkv or a nightly that reuses one path: one std::filesystem::remove() before the call is the whole migration. Without it the file is not overwritten but deleted -- the open truncates, and a recording that captured nothing has its file removed -- with nothing failing and nothing logged.

The SDK had already decided this wherever it names the file itself; see rec::UniqueFilePath(), which interval capture and alarm-fired recordings keep using. Those generate the name, so moving to the next free one is right there. This call takes the caller's own string, so recording somewhere else would trade one silent surprise for another.

Exceptions

Name Description
InvalidStateException if a recording is already running. Starting a second one used to succeed silently and keep writing the first file, so a caller was told it had a file it did not have. Call Stop() first.
PathExistsException if a regular file is already at output_path, per the note above. The message names the path. A type of its own, so that recognising this case needs no match on the message text.

Start

void Start(const std::string &output_path, const rec::RecordingOptions &options)

Start recording with duration and segmentation settings.

Segmentation is what makes a long recording survive a destination that caps a single file: a lossless recording of a 640x480 sensor passes 4 GiB in well under an hour. Set max_segment_bytes to whatever that cap is and the recording rolls over into name_part000.mkv, name_part001.mkv and so on instead of dying at the boundary. Each finished file is reported through OnRecording().

Every part carries a suffix, the first one included, and that changed in API version 24. name.mkv with a segment limit writes name_part000.mkv and nothing at name.mkv, so an application that passed a path and then reopened it must read the path out of the OnRecording() notification, call rec::OpenSeries(), or open _part000 itself. Without a segment limit the path is kept exactly as given.

Parameters

Name Description
output_path Output MKV path, and the stem every segment is named from.
options Duration and segment limits.

Exceptions

Name Description
InvalidStateException if a recording is already running.
InvalidArgumentException if a limit is negative. OPTRIS_SDK_ERROR_INVALID_ARGUMENT rather than OPTRIS_SDK_ERROR_UNKNOWN, which is what a bare SdkException reached C as.
PathExistsException if a regular file is already at the first part's path -- @p output_path itself with no segment limit, and _part000 with one, which is the file the recorder is about to open. Only that first file is checked: the later rollover names are the SDK's own, and a rollover onto a name a previous run used is not refused. See Start(const std::string &).

Start

void Start(const std::string &output_path, std::chrono::milliseconds duration)

Record for a fixed length of time and stop without being asked.

Useful on its own, and the thing an alarm-triggered recording needs: without it, a recording a trigger started runs until something else stops it.

The clock starts once recording is live, after any pre-roll has been flushed -- so with pre-roll on, the file covers roughly pre-roll + duration. Stopping early with Stop() is fine.

Parameters

Name Description
output_path Output MKV file path.
duration How long to record. Must be positive.

Exceptions

Name Description
InvalidStateException if a recording is already running.
InvalidArgumentException if the duration is not positive.
PathExistsException if a regular file is already at output_path. A separate type from the duration refusal on purpose: one is fixed by choosing another name, the other by correcting the call. See Start(const std::string &).

Stop

void Stop()

Stop recording and finalize the file.

When this returns, the recording is complete on disk: the encoder has been drained, the trailer written and the file closed. It is safe to open, copy or play it immediately. A no-op if nothing is recording, so calling it twice is harmless.

A recording in parts has also reported every part it finished: rec::RecordingPhase::kStopped is raised, and this returns, only after each rec::RecordingPhase::kSegmentCompleted of those parts has been delivered and its handler has returned. The parts named by kSegmentCompleted and the one kStopped ends are then every file of the recording. So a handler of OnRecording() that is still running on the thread that writes the recording holds this up until it returns, for at most 5 seconds; after that the stop goes on and says so in the log. Such a handler must therefore never wait for the thread that calls Stop() (a UI dispatcher's synchronous invoke, for example). Calling Stop() from inside the handler is fine: it does not wait for itself.

IsRecording

auto IsRecording() const -> bool

Whether a recording is currently running.

Turning false carries the same guarantee as Stop() returning: the file is finished and can be opened, copied or played. That holds for a recording the application stopped and for one that reached the duration it was started with, so polling this is a valid way to wait for a time-limited recording to finish.

GetLastError

auto GetLastError() const -> std::string

Why the last recording stopped, if it stopped because it could not be written. Empty otherwise.

Start() reports a path it cannot write at all by throwing: the file is opened while the caller is still there, so a directory that does not exist or a permission that forbids the write is an exception rather than a recording that never happens.

What Start() cannot see is a disk that fills, or a stick pulled out, half an hour later. That failure lands on the thread writing the recording, where there is nobody to throw at. The recording is stopped and this is the reason. It is cleared by the next Start() that succeeds.

Which signal means the file is finished: Which signal means the file is finished IsRecording() is not that signal. It goes false as soon as the recording is torn down, which is before the file has been finalized: the trailer and the close are more disk I/O on a disk that has just refused a write, and they are done on a thread of their own so that neither the writer nor the SDK's timer thread waits for them.

The signal is rec::RecordingPhase::kStopped, delivered to OnRecording(), and it means for a failed recording exactly what it means for one that was asked to stop: the file is complete on disk. Anything that acts on the finished file -- reading its size, deleting a recording that holds no frame, rewriting it with RecordingFile::AttachFiles -- belongs there and not on IsRecording() going false.

Stop() also waits for it, so a caller that would rather block than subscribe can call Stop() after a failure and know the file is finished when it returns. Disposing the camera waits as well, which is what stops a process exiting from leaving a file without its trailer.

if (!imager->Recorder().IsRecording()) {
  const auto why = imager->Recorder().GetLastError();
  if (!why.empty())
    std::println(stderr, "the recording stopped itself: {}", why);
}

GetRemainingRecordingTime

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

How much of a time-limited recording is left to run. Zero when nothing is recording, or the recording has no limit.

IsRecordingBounded

auto IsRecordingBounded() const -> bool

Whether the running recording has a deadline at all.

GetRemainingRecordingTime() reports zero both for a recording that will run forever and for one whose deadline has just passed, which is two different things.

GetStatistics

auto GetStatistics() const -> rec::RecordingStats

What this recording -- or, once it has stopped, the last one -- did with its frames.

Frames written, frames lost and why, how deep the write queue is, bytes written, and the last error. Without it, a recording that silently stopped growing looks exactly like a healthy one: IsRecording() stays true while every frame is refused.

All three loss counters, not two. The sum below used to leave out frames_dropped_backlog, which is the one a slow target shows up in -- so an example that leaves it out prints "0 lost" for exactly the case that matters.

auto stats = imager->Recorder().GetStatistics();
std::println("{} frames written, {} lost, {} queued",
             stats.frames_written,
             stats.frames_dimension_mismatch +
                 stats.frames_write_error +
                 stats.frames_dropped_backlog,
             stats.queue_depth);

Never behind a disk: the recording is written on a thread of the SDK's own and this reads what that thread has banked. See rec::RecordingController::GetStatistics().

OnRecording

void OnRecording(std::function< void(const rec::RecordingEvent &)> handler)

Be told that a recording started, stopped, rolled over into the next segment, or failed.

The event an application otherwise cannot get: polling IsRecording() can see that a recording ended but never whether it reached its duration, was stopped by an alarm rule, or died on a write error. Pass nullptr to stop delivery.

Threading: Threading Fired on an SDK thread -- the caller's for a start it asked for, the SDK's timer thread for an auto-stop, and the thread that writes the recording for a failure or a finished segment. A failed recording's kStopped arrives on the thread that finalized its file, which is none of those.

Never the camera's frame thread. A failure and a segment rollover used to be reported from there, which is why calling back into the camera from a handler was a deadlock rather than merely a bad idea. Calling back in is now permitted, including StopRecording() -- but a handler that blocks still blocks the recording, so setting a flag and acting on your own thread is still the better shape.

Registering it before starting a recording is no longer required for segment events: the live handler is read when the notice is delivered rather than when the recording opened.

OnRecordingDetail

void OnRecordingDetail(std::function< void(const rec::RecordingEventDetail &)> handler)

Be told what OnRecording() tells, together with which recording each event is about and, on the events that end a recording, that recording's final statistics. Added in 12.0.15.

Use this one when your handler hands events to a thread of your own, which is what the threading note above recommends. Reading GetStatistics() when such a thread gets to a Stopped reads whichever recording is current by then: if an alarm rule or your application has already started the next one, its start has reset the figures and a complete file reads as 0 frames written. rec::RecordingEventDetail::statistics was taken when the recording ended and stays that recording's.

std::mutex mutex;
std::vector<rec::RecordingEventDetail> held;
imager->Recorder().OnRecordingDetail(
    [&](const rec::RecordingEventDetail &detail) {
      std::lock_guard lock(mutex);
      held.push_back(detail);  // Acted on later, on your own thread.
    });

Later, on that thread, a Stopped whose statistics say frames_written == 0 really is a recording that kept nothing.

Independent of OnRecording(): register either or both. Each event reaches the OnRecording() handler first and this one straight after, on the same thread and under the same rules. Pass nullptr to stop delivery.

SetSegmentLimitAction

void SetSegmentLimitAction(rec::SegmentLimitAction action)

What a recording does when it reaches its segment limit, RecordingOptions::max_segment_bytes or RecordingOptions::max_segment_duration. Added in 12.0.10.

rec::SegmentLimitAction::kContinueSeries, the default, carries on in the next part of the same recording, which Player::OpenSeries() replays as one. rec::SegmentLimitAction::kStartNewRecording ends the recording and starts a new one, named with its own start time. rec::SegmentLimitAction::kStopRecording (12.0.28) ends the recording at the limit: one file, finished and playable, and a rec::RecordingPhase::kStopped with rec::RecordingStopReason::kSegmentLimit.

Applies to every recording started after the call, by the application or by an alarm rule, and has no effect on one with no segment limit.

imager->Recorder().SetSegmentLimitAction(
    rec::SegmentLimitAction::kStartNewRecording);
rec::RecordingOptions options;
options.max_segment_bytes = 2'000'000'000;
imager->Recorder().Start("run.mkv", options);

GetSegmentLimitAction

auto GetSegmentLimitAction() const -> rec::SegmentLimitAction

What SetSegmentLimitAction() last set.

StartIntervalCapture

void StartIntervalCapture(std::chrono::milliseconds interval, const std::string &directory={}, SnapshotFormat format=SnapshotFormat::kPng, const std::string &name_pattern="snapshot_{sequence}")

Write a still image every interval, for a time-lapse or a long unattended run. Independent of recording: Stop() does not end it.

An interval shorter than the camera's frame period is raised to the frame period, because no more images than frames can exist. GetIntervalCaptureInterval() reports what is actually in force.

Parameters

Name Description
interval Time between images. Must be positive.
directory Where to write. Empty uses the output directory, and failing that the current directory. A folder that is not there yet is created, with the folders above it.
format Image format, which also picks the extension.
name_pattern Filename stem, without extension. See File name patterns -- {sequence}, {timestamp}, {serial}, {model}. A run that reuses a directory and a pattern no longer overwrites the previous run's images; the SDK appends -1, -2, ... instead.

Exceptions

Name Description
SdkException if the arguments are rejected.
IoException if the folder cannot be created or written to, naming it. Nothing starts then.

StartIntervalCapture

void StartIntervalCapture(std::chrono::milliseconds interval, const std::string &directory, SnapshotFormat format, const std::string &name_pattern, const rec::CsvOptions &csv)

StartIntervalCapture() with the unit and spelling of each CSV image: csv is to every image of a SnapshotFormat::kCsv time-lapse what it is to SaveCsvSnapshot(), so a run can be written in degrees Fahrenheit, or for a spreadsheet in a German locale, or both. Ignored by the other formats.

The overload without csv writes the default CSV, so a capture started with it after one started with this does not inherit the earlier options.

rec::CsvOptions csv;
csv.temperature_unit = TemperatureUnit::kFahrenheit;
imager->Recorder().StartIntervalCapture(
    std::chrono::minutes(1), "timelapse", SnapshotFormat::kCsv,
    "night_{sequence}", csv);

Exceptions

Name Description
InvalidArgumentException for a refused interval or name pattern, as the overload above, and for options rec::CsvOptions documents as refused, whatever the format. Nothing starts then.
IoException for a folder that cannot be created or written to, as the overload above.

StopIntervalCapture

void StopIntervalCapture()

Stop writing images 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 a time-lapse is running.

GetIntervalCaptureInterval

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

The interval actually in force, after any raise to the frame period. Zero when no time-lapse is running.

GetIntervalCaptureCount

auto GetIntervalCaptureCount() const -> uint64_t

How many images the running time-lapse has written so far.

SetOutputDirectory

void SetOutputDirectory(const std::string &directory)

Where alarm-driven snapshots and recordings are written when the action does not name a directory.

GetOutputDirectory

auto GetOutputDirectory() const -> std::string

SaveSnapshot

void SaveSnapshot(const std::string &path, SnapshotFormat format=SnapshotFormat::kPng, const rec::SnapshotInfo &info={}, const rec::SnapshotOptions &opts={})

Write the most recent frame to a still image, pulling any registered attachment providers as the file is opened.

The camera's identity, radiometry and measurement range are filled in from the Imager. Anything set on info explicitly wins over what the Imager would have supplied.

Parameters

Name Description
path Output file path.
format Container to write.
info Extra metadata and attachments.
opts Scale and compression settings.

Exceptions

Name Description
IoException on failure, including when no frame has been captured yet, and when no frame marked as a measurement (FrameMetadata::thermal_data_reliable) has been captured since a change of the temperature range, the operation mode or the clipped window. The frame held until then was taken with the settings just left, or during the recalibration that follows the change, and the file would label it with the range now in force. See Imager::SetOperationMode(). Outside that case a frame that is not a measurement is written, and the file records it, so StillSource::Open() and rec::Snapshot::LoadThermal() report it with the flag false.

SaveSnapshot

void SaveSnapshot(const ThermalFrame &frame, const std::string &path, SnapshotFormat format=SnapshotFormat::kPng, const rec::SnapshotInfo &info={}, const rec::SnapshotOptions &opts={})

Write a frame the application already has to a still image.

The overload to reach for from inside a thermal callback, where the frame is to hand and the SDK's retained copy may already have moved on. Metadata, attachments and options behave exactly as for the frameless overload.

Exceptions

Name Description
IoException on failure.

SaveCsvSnapshot

void SaveCsvSnapshot(const std::string &path, const rec::CsvOptions &csv, const rec::SnapshotInfo &info={})

Write the most recent frame as a CSV snapshot, spelled the way csv asks.

SaveSnapshot() with SnapshotFormat::kCsv, plus the choice of delimiter, decimal separator, how an unmeasured pixel is written and whether the # header lines appear, so a spreadsheet set to a German or French locale opens the file as numbers. Metadata is filled in exactly as SaveSnapshot() fills it. A default-constructed rec::CsvOptions writes the same file SaveSnapshot() writes.

Exceptions

Name Description
std::invalid_argument for a spelling rec::CsvOptions documents as refused (the same type SaveSnapshot() raises for a refused argument). Nothing is written then.
IoException on the same terms as SaveSnapshot().

SaveCsvSnapshot

void SaveCsvSnapshot(const ThermalFrame &frame, const std::string &path, const rec::CsvOptions &csv, const rec::SnapshotInfo &info={})

Write a frame the application already has as a CSV snapshot, spelled the way csv asks. The overload for a thermal callback; otherwise exactly the frameless one.

AddAttachmentProvider

auto AddAttachmentProvider(rec::AttachmentProvider provider) -> uint32_t

Register a provider the SDK pulls as it opens a snapshot or a recording, so your application can attach its own files.

This shape exists because the obvious one cannot work: for a trigger-started recording the application never calls Start(), so there is no moment at which to push an attachment. See rec::AttachmentProvider for the full contract.

RemoveAttachmentProvider

void RemoveAttachmentProvider(uint32_t provider_id)