OptrisOptrisDocumentation

Documentation/OTC SDK/Overviewv12.0

Recording Attachments

Put your own files inside the recording, add one after it has finished, and read them back. A recording is a container, so a batch number, a work order or a calibration certificate can travel with the frames rather than beside them.

The recording chapter is seven pages, each answering one question:

Page Question
Recording How do I write a camera to a file?
A Running Recording What is it telling me while it runs?
Recording File Format What is the file, and what may a third party rely on?
Preview Pictures Why does the file open on a picture, and which frame is it?
Snapshots and Interval Capture How do I save one frame, or one every N seconds?
Recording Attachments How do I put my own files inside the recording?
Playback How do I read one back?

Applications can put their own files inside the images and recordings the SDK writes: a process context dump, a config file, a reading taken from another system. The same rec::Attachment type serves both: in a snapshot it becomes an otCa chunk, in a recording an MKV attachment stream.

Attachments are collected by asking, not by telling:

imager->Recorder().AddAttachmentProvider(
    [&](const optris::sdk::rec::AttachmentRequest& request) {
  optris::sdk::rec::Attachment context;
  context.name = "process.json";
  context.mime = "application/json";
  context.data = SerializeProcessState();  // yours, returning bytes
  return std::vector{context};
});

The provider is called once per file, as that file's header is written: for a snapshot, inside the call that saves it; for a recording and for every recording segment, before any frame is written to it.

AttachmentRequest::format says which container is being written (PNG, TIFF, CSV or JPEG for a still, MKV for a recording) and can_carry_attachments says whether it can hold one. A CSV and a JPEG cannot, so that flag is false for them and anything returned for such a file is dropped with a log line rather than refused: the file is written either way. Gate on the flag, which is the SDK's answer to its own rule, and use the format to decide what to attach. Files set on a SnapshotInfo by hand are still refused for those two formats, because there the SDK never asked.

Why a callback and not a setter

A recording an alarm starts is one the application never gets a call for: Recorder().Start() is never invoked, so there is nothing to hang an Attach(...) off. And a manual start gives no usable window either: the provider is asked when the header is written, which is after Start() has returned, and once the header is down MKV attachments can no longer be added. Being asked, rather than waiting to be told, is what makes the manual and the triggered case the same case.

When, exactly

Starting a recording opens the file and stops there. The header waits for the cover's look-ahead, which resolves on the first frame that makes a usable cover, at six frames, or at 400 ms of capture time, whichever comes first. The provider is asked as that header goes down. A recording that ended while that look-ahead was still unresolved is asked inside the call that stops it, which writes the frames still held; a recording that received no frame at all is asked nothing, because its file is discarded rather than finished. The guarantee worth relying on is that nothing reaches the file ahead of your attachments, not that the pull happens inside any particular call. One consequence: state your code sets up just after Start() returns may or may not reach the file, so have what the provider reads ready beforehand.

Which thread, and what it holds

For a recording the provider never runs on the thread that started it. It runs on:

  • the thread that writes the recording, for every recording and every segment of one (the recording controller's mutex is not held while it does);
  • the thread that stops a recording which ended while that look-ahead was still unresolved: the application's own thread, or the SDK's timer thread for a bounded auto-stop.

For a snapshot it is the thread of the SaveSnapshot() call, or the SDK's action thread for an alarm-fired one, or the SDK's timer thread for an interval capture.

The provider list is a camera's, and the set asked for one file is the set registered when that file started. A provider you register while a file is being written is not asked for that file, and one you remove may still be asked once for a file already under way; RemoveAttachmentProvider() takes the provider out of the list, it does not wait for one that is running. If you need a provider to stop answering immediately, make the provider itself return nothing.

It is not the camera's frame thread, and the recording controller's mutex is not held while it runs. The provider runs where the writing happens, which is a thread of the SDK's own, so it cannot stall frame delivery for the camera, and a Recorder().Stop() reached from inside it cannot deadlock against a lock of your own. A provider that blocks delays the recording it is writing the header for, and nothing else. Return promptly and prepare the bytes in advance where you can, but it is no longer a camera's frame rate you are spending.

AttachmentRequest::on_action_thread is not a reliable answer to "are my locks held". It reads false for the first file of a manually started recording even though that runs on an SDK thread, and false for an interval-capture snapshot, which runs on the SDK's timer thread. Today it reliably separates only a manual SaveSnapshot() (false, and genuinely your thread) from an alarm-fired file or a segment rollover (true). For anything other than a snapshot, assume you are on an SDK thread whatever it says.

Throwing is treated as attaching nothing: an attachment is never a reason to lose a recording. Do not call back into the imager's recording or snapshot methods from inside the provider: the provider is asked from inside the write it is supplying a header for, so a Stop() from there would re-enter the recorder it is standing in.

From a binding

The same pull shape, flattened: optris_sdk_imager_set_attachment_provider() registers one callback, and the callback adds files to the sink it is handed with optris_sdk_attachment_sink_add().

static void OTC_SDK_C_CALL Provide(
    const optris_sdk_attachment_request *request,
    optris_sdk_attachment_sink *sink, void *user_data) {
  (void)user_data;
  if (request->scope != OPTRIS_SDK_ATTACHMENT_SCOPE_SNAPSHOT) {
    return;  /* nothing to add is normal and adds nothing */
  }
  const char *json = "{\"layout\":\"line 4\"}";
  optris_sdk_attachment_sink_add(sink, "process.json", "application/json",
                                 json, strlen(json), 1);
}

optris_sdk_imager_set_attachment_provider(imager, Provide, NULL);

One provider per camera, where C++ takes a list of them. Across a flat ABI a single callback that adds as many files as it likes is the same expressiveness with none of the registration-id bookkeeping. Registering replaces any previous provider; passing NULL stops it being pulled. The sink is borrowed for the duration of the call and nothing else: storing the pointer and using it later is reported as an invalid handle rather than acted on.

Segmented recordings

When a segment limit rolls a recording over, rec::RecordingOptions::max_segment_duration or ::max_segment_bytes from the public API, or rec::GlobalConfig::max_segment_duration_sec and ::max_segment_bytes underneath it (every file is numbered, the first one included: name_part000.mkv, name_part001.mkv, name_part002.mkv, ..., and nothing at the bare name.mkv, see Splitting a long recording), every segment carries the full metadata and every attachment, and the provider is asked again for each one with scope == kRecordingSegment and an incrementing segment_index. A segment is a file someone can be handed on its own, and one that cannot say which camera produced it is not much use. Asking again (rather than caching the first answer) also lets an application update its context as a long recording runs.

You are asked before any frame is written to the file. The provider fires as the header goes down, because that is the last moment an attachment stream can be declared at all. So anything that only exists once the recording has ended (a summary of the run, a statistic gathered over it, a widget history) cannot go in through the provider. Use the provider for what you know at the start: the layout, the manifest, the device configuration. For the rest, see adding a file afterwards, which is the other half of the same seam and does not replace it.

Attachment::compress does nothing on a recording

It deflates the payload inside a PNG's otCa chunk or a TIFF's tag 65200. An MKV attachment stream is stored verbatim, so the flag is ignored there and reads back as false. Harmless, just inert.

An empty attachment is dropped, not carried. Matroska stores no entry for one (measured on ffmpeg 7.1.5, the muxer writes nothing at all for an attachment stream with an empty payload), so a zero-byte file returned by a provider is dropped before the recording's otc-meta.json index is built, and the post-hoc calls below refuse it outright. Neither the container nor the index will claim a file that is not there.

camera.SetAttachmentProvider(request =>
[
    new Attachment("operator.json",
                   JsonSerializer.SerializeToUtf8Bytes(shift))
    {
        Mime = "application/json",
    },
]);

Adding a file after the recording has finished

The provider covers what is known up front. This covers what the session produces: a log, a report, the per-widget histories that only exist once the last frame is in.

#include <optrissdk.h>

// Yours, and it did not exist until the recording ended.
std::vector<std::byte> CollectHistory();

void AttachTheHistory() {
  optris::sdk::rec::Attachment history;
  history.name = "widget-7-history.csv";
  history.mime = "text/csv";
  history.data = CollectHistory();

  try {
    optris::sdk::rec::Recorder::AttachToFile("/data/run.mkv", {history});
  } catch (const optris::sdk::SdkException& e) {
    std::println(stderr, "{}", e.what());
  }
}

A reader cannot tell when an attachment arrived, and is not meant to be able to. What you add here comes back through every read in the next section, in the same enumeration, at the same position in it (after the application's own files and before cover.jpg, exactly where a provider's would have been) and with the same SHA-256 recorded in the recording's own otc-meta.json, which is updated rather than left stale.

This rewrites the file

Matroska keeps its attachments in the Segment header, ahead of the first Cluster, so there is no offset at the end where another could go: adding one means writing the whole container out again, which is the operation ffmpeg -i in.mkv -attach … -c copy out.mkv performs. On a 5 GB recording that is 5 GB read, 5 GB written, and 5 GB of free space while it runs: measured at 484 MB/s on a workstation SSD, about ten seconds. Pass every file in one call. Calling once per file rewrites the container once per file.

A failure cannot cost you the recording

The source is opened for reading only. The result goes to <path>.otc-attach-<pid>.tmp beside it, is flushed, reopened and checked (every attachment present at its recorded size, every track still there, the duration unchanged) and only then renamed over the original, which is a single atomic operation on both Linux and Windows. A crash, a power cut, a full disk or a muxer failure at any point before that rename costs the temporary and nothing else; the original is still the file it was, byte for byte. This is deliberately not mkvpropedit --add-attachment's in-place edit, which is cheaper and can leave a recording that is neither the old file nor the new one.

Three things to plan for rather than discover:

  • Free space is checked before a byte is written, and the call fails naming what it needed and what was there.
  • A recording open elsewhere. On Windows the final rename fails and the call reports an I/O error with the original intact. On Linux it succeeds, and a reader that already has the file open keeps reading the bytes it opened until it reopens the path.
  • AttachToFile replaces the file; AttachToCopy does not. Use the second when the original must be kept as it is, or when you are building a copy to hand on.

A session file is ordinary Matroska, so all of this works on one. A session handle has 44 optris_sdk_session_* entry points of its own, so a session can be recorded and played back from C and .NET; hanging attachments off one is still to be done.

Reading them back

What went in comes out three ways, depending on what you have in your hand.

A recording on disk, with no camera and no playback. The cheapest read: it parses the container header and stops, so it costs the same on an hour-long take as on a one-second one. This is what a folder listing wants.

auto carried = optris::sdk::Player::ReadAttachments("/data/run.mkv");
for (const auto& file : carried) {
  if (file.name == "layout.oclayout") {
    RestoreLayout(file.data);  // yours: the SDK only carried the bytes
  }
}

A recording already being replayed. optris::sdk::Player::GetAttachments(), optris_sdk_imager_get_attachment_count() and its two companions, or ThermalCamera.Attachments: the same three questions off a handle from optris_sdk_imager_create_from_file(). On a live camera the C calls report OPTRIS_SDK_ERROR_NOT_SUPPORTED and the .NET property throws FeatureNotSupportedException: a camera carries no file, and answering with an empty list would read as "this recording carries nothing".

A snapshot. rec::Snapshot::ReadAttachments(), optris_sdk_snapshot_open() or Snapshot.Open(), as described above. RecordingAttachments.Read(path) in .NET covers both containers behind one call when the file came from a listing and its kind is not known in advance.

The SDK's own files are in the same list. otc-meta.json, device.json, config.json, and otc-session.json for a multi-camera session file, come back beside yours, so telling them apart is a comparison on the name, and a session file can be recognized without decoding a frame.

A recording's digests are recorded, not re-verified. optris_sdk_attachment_info::sha256 and AttachmentInfo.Sha256 carry what the file's own otc-meta.json index recorded for each payload. Unlike a snapshot's, they are not checked on read: an MKV attachment is stored verbatim rather than deflated, so there is no decode step that could go wrong unnoticed, and hashing a payload the caller may never ask for is work nobody asked for. A file this SDK did not write carries no index and reports an empty string, which means "the file does not say", never "it matched".