Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
loom_cam.c
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 * @file loom_cam.c
20 * @brief Fresh-first saved-image requests to the standalone loomcam process.
21 * @details The AI camera remains owned by its existing driver. This adapter owns
22 * only paths, one pending request, one joinable worker and one completion mailbox.
23 * It never sends UART or mutates flight waypoints. Return vectors are validated,
24 * but archived reference photographs are not yet compared against live images.
25 */
26#include "loom_cam.h"
27#include <dirent.h>
28#include "inference_settings.h"
30#include <math.h>
31#include "path_utils.h"
32
33#include <errno.h>
34#include <fcntl.h>
35#include <inttypes.h>
36#include <limits.h>
37#include <poll.h>
38#include <pthread.h>
39#include <signal.h>
40#include <spawn.h>
41#include <stdatomic.h>
42#include <stdio.h>
43#include <string.h>
44#include <sys/wait.h>
45#include <sys/eventfd.h>
46#include <time.h>
47#include <unistd.h>
48
49#ifndef USHER_LOOMCAM_COMMAND
50 /** @brief Saved-photo child executable; not another camera-acquisition process. */
51 #define USHER_LOOMCAM_COMMAND "./bin/loomcam"
52#endif
53/** @name Bounded child-process policy
54 * One monotonic deadline bounds reply handling independently of fragmentation
55 * and interrupted polls. A short exit grace permits a flushed reply before exit.
56 * @{ */
57#define LOOM_RESULT_LINE_BYTES 384U /**< Fixed result storage bounds a child's reply. */
58#define LOOM_SEQUENCE_TEXT_BYTES 16U /**< Decimal uint32 ID plus terminator, without truncation. */
59#define LOOM_WORKER_POLL_MS 50 /**< Watchdog poll interval; shutdown is checked between polls. */
60#define LOOM_WORKER_TIMEOUT_MS 5000U /**< Whole reply operation budget in monotonic milliseconds. */
61#define LOOM_EXIT_GRACE_MS 200U /**< Allow a flushed reply to precede normal child exit. */
62#define LOOM_KILL_GRACE_MS 1000U /**< Maximum wait for a killed owned child. */
63#define LOOM_NS_PER_MS 1000000L /**< Convert the poll interval for nanosleep. */
64#define LOOM_REFERENCE_PHOTO_LIMIT 256U /**< Bound hard links retained for one sortie. */
65#define LOOM_REFERENCE_SESSION_LIMIT 64U /**< Bound retained sortie directories without pruning evidence. */
66/** @} */
67
68/** @name Saved-photo and wire-unit conventions
69 * Geographic limits are degrees multiplied by 1e7; quality is in thousandths.
70 * The reference filename uses ten digits to cover every uint32_t photo number.
71 * @{ */
72#define LOOM_LATITUDE_LIMIT_E7 INT32_C(900000000) /**< Latitude range in degrees times 1e7. */
73#define LOOM_LONGITUDE_LIMIT_E7 INT32_C(1800000000) /**< Longitude range in the same wire units. */
74#define LOOM_QUALITY_MAX INT32_C(1000) /**< Quality uses thousandths, not an arbitrary float score. */
75#define LOOM_REFERENCE_SEQUENCE_DIGITS 10 /**< Fits every uint32 photo number in the archive basename. */
76#define LOOM_JPEG_EXTENSION ".jpg" /**< Final suffix replaced when associating saved sidecars. */
77#define LOOM_JPEG_EXTENSION_BYTES (sizeof(LOOM_JPEG_EXTENSION) - 1U) /**< Exclude the string terminator. */
78#define LOOM_DECIMAL_RADIX 10 /**< Reply grammar accepts explicit decimal integers only. */
79/** @} */
80
81/** @brief Ordered fields of the strict LOOM_POINT_V1 text contract. */
93
94/** @brief The validity field accepts only these two numeric wire values. */
96/** @brief POSIX pipe endpoints; names distinguish child output from parent input. */
98
99extern char **environ; /**< Borrowed POSIX environment passed to the explicit-argv child. */
100/* The mutex protects paths, phase, admission and the completion mailbox.
101 * Atomic lifecycle flags additionally let the child watchdog and enabled()
102 * observe shutdown without holding that mutex through blocking process I/O. */
103static pthread_mutex_t loom_mutex = PTHREAD_MUTEX_INITIALIZER; /**< Protects admission, phase and mailbox state. */
104static pthread_cond_t loom_available = PTHREAD_COND_INITIALIZER; /**< Wakes the worker for pending work or shutdown. */
105static pthread_t loom_thread; /**< Joinable saved-photo worker; no sensor ownership. */
106static atomic_bool loom_stopping; /**< Watchdog-visible shutdown flag outside slow I/O. */
107static atomic_bool loom_running; /**< Lifecycle availability queried without taking the mutex. */
108/** @var loom_pending
109 * @brief The latest copied path awaits worker consumption; older pending work is replaceable. */
110static bool loom_pending, loom_ready; /**< One completion mailbox is available for consumption. */
111static uint32_t loom_latest_sequence; /**< Highest admitted FC photo number; rejects duplicates/reversed work. */
112/** @var loom_session
113 * @brief START token used to admit the corresponding STOP, not a photo number. */
114static uint32_t loom_session, loom_phase; /**< Generation that invalidates results crossing a phase change. */
115static bool loom_recording; /**< Outbound reference collection rather than return matching. */
116/** @var loom_filename
117 * @brief Latest admitted immutable saved-photo path, copied into bounded storage. */
118/** @var loom_references
119 * @brief Reference-directory configuration, fixed until the worker has been joined. */
121static char loom_model[PATH_MAX]; /**< Owned model/configuration paths. */
122static char loom_settings[PATH_MAX]; /**< Selected assignment, immutable during worker lifetime. */
125static struct camera_point_result loom_result; /**< Single correlated matched/no-match completion. */
126static pid_t loom_matcher_pid = -1;
127static int loom_notification = -1;
128
129/** @brief Clear the completion event counter.
130 * @details The mailbox owns the result; the event counter only indicates
131 * that the event loop should inspect it under the stream's synchronization. */
132static void drain_notification(void)
133{
134 if (loom_notification < 0) return;
135 eventfd_t count;
136 int received;
137 do { received = eventfd_read(loom_notification, &count); } while (received < 0 && errno == EINTR);
138}
139
140/** @brief Wake the event loop when completion state may have changed.
141 * @details The nonblocking event descriptor is not a result queue. A
142 * saturated counter already has the desired readable state. */
143static void notify_completion(void)
144{
145 if (loom_notification < 0) return;
146 const uint64_t count = 1;
147 ssize_t written;
148 do { written = write(loom_notification, &count, sizeof(count)); } while (written < 0 && errno == EINTR);
149}
150
151/**
152 * @brief Copy a complete NUL-terminated path into owned, fixed-size storage.
153 * @param destination Writable buffer of @p capacity bytes.
154 * @param capacity Buffer size, including space for the terminator.
155 * @param source Borrowed path; NULL selects an empty optional configuration.
156 * @return True on complete copy; false rather than silently truncating a path.
157 */
158static bool copy_path(char *destination, size_t capacity, const char *source)
159{
160 if (!source) source = "";
161 const size_t length = strnlen(source, capacity);
162 if (length >= capacity) return false;
163 for (size_t index = 0; index <= length; ++index) destination[index] = source[index];
164 return true;
165}
166
167/**
168 * @brief Consume one exact field prefix followed by a signed decimal integer.
169 * @param[in,out] cursor Current parse position; advanced only after conversion.
170 * @param key Exact prefix, including the separator between fields.
171 * @param[out] value Parsed wide integer, before wire-range validation.
172 * @return False for missing digits, prefix mismatch or integer overflow.
173 * @details Reject leading whitespace and a plus sign instead of allowing
174 * strtoimax() to quietly accept a different producer grammar.
175 */
176static bool read_result_field(const char **cursor, const char *key, intmax_t *value)
177{
178 const size_t length = strlen(key);
179 if (strncmp(*cursor, key, length) != 0) return false;
180 const char *number = *cursor + length;
181 const char *digit = number[0] == '-' ? number + 1 : number;
182 if (*digit < '0' || *digit > '9') return false;
183 char *end;
184 errno = 0;
185 *value = strtoimax(number, &end, LOOM_DECIMAL_RADIX);
186 if (errno == ERANGE || end == number) return false;
187 *cursor = end;
188 return true;
189}
190
191/**
192 * @brief Validate and correlate one complete reply before publishing any fields.
193 * @param line NUL-terminated reply; only one optional final newline is allowed.
194 * @param sequence Photo number that the child must echo exactly.
195 * @param[out] result Destination, changed only after the whole reply is accepted.
196 * @return True for a well-formed matched or no-match reply.
197 * @details A valid point must fit geographic and quality limits. An invalid
198 * reply may retain int32 diagnostics, but cannot authorize navigation. FC-side
199 * freshness, request eligibility and waypoint guards remain independent gates.
200 */
201static bool parse_result(const char *line, uint32_t sequence, struct camera_point_result *result)
202{
203 if (!line || !result || !sequence) return false;
204 static const char *const keys[LOOM_RESULT_FIELD_COUNT] = {
205 "LOOM_POINT_V1 sequence=", " valid=", " lat=", " lon=", " alt_mm=", " agl_mm=", " quality=", " metric="
206 };
207 intmax_t values[LOOM_RESULT_FIELD_COUNT];
208 const char *cursor = line;
209 for (size_t index = 0; index < LOOM_RESULT_FIELD_COUNT; ++index) {
210 if (!read_result_field(&cursor, keys[index], &values[index])) return false;
211 if (index >= LOOM_FIELD_LATITUDE && (values[index] < INT32_MIN || values[index] > INT32_MAX)) return false;
212 }
213 if (values[LOOM_FIELD_SEQUENCE] != sequence
215 || (*cursor != '\0' && !(*cursor == '\n' && cursor[1] == '\0'))) return false;
216 struct camera_point_result point = {
217 .session_id = sequence, .valid = values[LOOM_FIELD_VALID] == LOOM_WIRE_VALID,
218 .lat = (int32_t)values[LOOM_FIELD_LATITUDE], .lon = (int32_t)values[LOOM_FIELD_LONGITUDE],
219 .alt_mm = (int32_t)values[LOOM_FIELD_ALTITUDE_MM], .agl_mm = (int32_t)values[LOOM_FIELD_AGL_MM],
220 .quality = (int32_t)values[LOOM_FIELD_QUALITY], .metric = (int32_t)values[LOOM_FIELD_METRIC]
221 };
224 || (!point.lat && !point.lon) || point.agl_mm < 0 || point.quality < 0
225 || point.quality > LOOM_QUALITY_MAX)) return false;
226 *result = point;
227 return true;
228}
229
230/**
231 * @brief Read the watchdog clock in milliseconds.
232 * @return Monotonic milliseconds, or zero if the clock cannot be read.
233 * @details Wall-clock corrections must not extend or shorten a matcher deadline.
234 */
235static uint64_t loom_monotonic_ms(void)
236{
237 struct timespec now;
238 if (clock_gettime(CLOCK_MONOTONIC, &now) != 0 || now.tv_sec < 0) return 0;
239 return (uint64_t)now.tv_sec * 1000U + (uint64_t)now.tv_nsec / LOOM_NS_PER_MS;
240}
241
242/**
243 * @brief Wait up to a bounded time for the owned matcher to exit.
244 * @param timeout_ms Polling budget in milliseconds.
245 * @param[out] status Optional wait status, set when ownership is cleared.
246 * @return True if no matcher remains owned; false on timeout or a wait error.
247 * @details Use nonblocking waits to preserve the deadline. On failure retain
248 * the PID so a later cleanup attempt does not lose ownership.
249 */
250static bool reap_matcher(unsigned timeout_ms, int *status)
251{
252 if (loom_matcher_pid <= 0) return true;
253 const uint64_t started = loom_monotonic_ms();
254 for (;;) {
255 int observed = -1;
256 const pid_t result = waitpid(loom_matcher_pid, &observed, WNOHANG);
257 if (result == loom_matcher_pid || (result < 0 && errno == ECHILD)) {
258 loom_matcher_pid = -1;
259 if (status) *status = observed;
260 return true;
261 }
262 if (result < 0 && errno != EINTR) return false;
263 const uint64_t now = loom_monotonic_ms();
264 if (!started || !now || now < started || now - started >= timeout_ms) return false;
265 if (poll(NULL, 0, 10) < 0 && errno != EINTR) return false;
266 }
267}
268
269/**
270 * @brief Check whether an in-flight match still belongs to the active phase.
271 * @param phase Generation saved when the photo was admitted.
272 * @return True if that generation can still produce a result.
273 * @details Consult shared phase state under the mutex; photo numbers alone
274 * cannot distinguish work across phase changes.
275 */
276static bool matcher_phase_current(uint32_t phase)
277{
278 pthread_mutex_lock(&loom_mutex);
279 const bool current = !loom_stopping && phase == loom_phase;
280 pthread_mutex_unlock(&loom_mutex);
281 return current;
282}
283
284/**
285 * @brief Run the saved-photo matcher with bounded output and a watchdog.
286 * @param filename Immutable saved JPEG to process, not another capture request.
287 * @param references Reference archive for this phase.
288 * @param sequence Photo number that the matcher must echo.
289 * @param phase Generation used to cancel superseded work.
290 * @param[out] result Accepted reply; unchanged on execution or parsing failure.
291 * @return True only for a well-formed current reply and a successful child exit.
292 * @details Pass arguments directly and collect the reply on a private stdout
293 * pipe. Monitor the deadline and phase while reading so slow or superseded
294 * work cannot indefinitely hold the worker.
295 */
296static bool run_matcher(const char *filename, const char *references, uint32_t sequence,
297 struct camera_point_result *result, uint32_t phase)
298{
299 if (!filename || !result || !sequence || !reap_matcher(0, NULL)) return false;
300 const uint64_t started = loom_monotonic_ms();
301 if (!started) return false;
303 if (pipe(output) != 0) return false;
304 if (fcntl(output[LOOM_PIPE_READ], F_SETFD, FD_CLOEXEC) != 0
305 || fcntl(output[LOOM_PIPE_WRITE], F_SETFD, FD_CLOEXEC) != 0) {
307 }
308 posix_spawn_file_actions_t actions;
309 if (posix_spawn_file_actions_init(&actions) != 0) {
311 }
312 int setup = posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
313 if (!setup) setup = posix_spawn_file_actions_adddup2(&actions, output[LOOM_PIPE_WRITE], STDOUT_FILENO);
314 DIR *descriptors = opendir("/proc/self/fd");
315 if (!descriptors) setup = errno ? errno : EIO;
316 struct dirent *entry;
317 while (descriptors && !setup && (entry = readdir(descriptors)) != NULL) {
318 char *end = NULL;
319 const long descriptor = strtol(entry->d_name, &end, 10);
320 if (!entry->d_name[0] || !end || *end || descriptor <= STDERR_FILENO || descriptor > INT_MAX ||
321 descriptor == dirfd(descriptors)) continue;
322 setup = posix_spawn_file_actions_addclose(&actions, (int)descriptor);
323 }
324 if (descriptors) closedir(descriptors);
325 char sequence_text[LOOM_SEQUENCE_TEXT_BYTES];
326 snprintf(sequence_text, sizeof(sequence_text), "%" PRIu32, sequence);
327 char *arguments[] = {(char *)USHER_LOOMCAM_COMMAND, "--image", (char *)filename,
328 "--sequence", sequence_text, "--reference-dir", (char *)references,
329 loom_settings[0] ? "--settings" : "--model", loom_settings[0] ? loom_settings : loom_model, NULL
330 };
331 posix_spawnattr_t attributes;
332 bool attributes_ready = false;
333 if (!setup) { setup = posix_spawnattr_init(&attributes); attributes_ready = setup == 0; }
334 sigset_t mask, defaults;
335 sigemptyset(&mask);
336 sigemptyset(&defaults);
337 sigaddset(&defaults, SIGINT);
338 sigaddset(&defaults, SIGTERM);
339 if (!setup) setup = posix_spawnattr_setsigmask(&attributes, &mask);
340 if (!setup) setup = posix_spawnattr_setsigdefault(&attributes, &defaults);
341 if (!setup) setup = posix_spawnattr_setpgroup(&attributes, 0);
342 if (!setup) setup = posix_spawnattr_setflags(&attributes,
343 POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETPGROUP);
344 const int spawned = setup ? setup : posix_spawn(&loom_matcher_pid, USHER_LOOMCAM_COMMAND,
345 &actions, &attributes, arguments, environ);
346 if (attributes_ready) posix_spawnattr_destroy(&attributes);
347 posix_spawn_file_actions_destroy(&actions);
349 if (spawned) { close(output[LOOM_PIPE_READ]); return false; }
350 char line[LOOM_RESULT_LINE_BYTES];
351 size_t length = 0;
352 bool complete = false;
353 while (matcher_phase_current(phase)) {
354 const uint64_t now = loom_monotonic_ms();
355 if (!now || now < started || now - started >= LOOM_WORKER_TIMEOUT_MS) break;
356 const uint64_t remaining = LOOM_WORKER_TIMEOUT_MS - (now - started);
357 const int wait_ms = remaining < LOOM_WORKER_POLL_MS ? (int)remaining : LOOM_WORKER_POLL_MS;
358 struct pollfd descriptor = {.fd = output[LOOM_PIPE_READ], .events = POLLIN};
359 const int ready = poll(&descriptor, 1, wait_ms);
360 if (ready < 0) { if (errno == EINTR) continue; break; }
361 if (!ready) continue;
362 const ssize_t count = read(output[LOOM_PIPE_READ], line + length, sizeof(line) - length - 1);
363 if (count <= 0) break;
364 length += (size_t)count;
365 line[length] = '\0';
366 if (memchr(line, '\0', length) || memchr(line, '\r', length)) break;
367 const char *newline = strchr(line, '\n');
368 if (newline) { complete = newline == line + length - 1; break; }
369 if (length + 1 == sizeof(line)) break;
370 }
372 int status = -1;
373 if (!reap_matcher(complete && !loom_stopping ? LOOM_EXIT_GRACE_MS : 0, &status)) {
374 kill(-loom_matcher_pid, SIGKILL);
375 kill(loom_matcher_pid, SIGKILL);
376 if (!reap_matcher(LOOM_KILL_GRACE_MS, &status))
377 fprintf(stderr, "LOOM_cam: killed matcher has not exited; retaining child ownership\n");
378 return false;
379 }
380 return complete && matcher_phase_current(phase) && WIFEXITED(status) && WEXITSTATUS(status) == 0
381 && parse_result(line, sequence, result);
382}
383
384/**
385 * @brief Check whether a session reference directory has room for another entry.
386 * @param directory Path of the existing session directory.
387 * @return True if the directory could be read and is below its entry limit.
388 * @details Count existing directory entries instead of relying on in-memory
389 * counters so pre-existing files still count against the archive bound.
390 */
391static bool reference_directory_available(const char *directory)
392{
393 DIR *stream = opendir(directory);
394 if (!stream) return false;
395 unsigned entries = 0;
396 errno = 0;
397 struct dirent *entry;
398 while ((entry = readdir(stream)) != NULL) {
399 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;
400 if (++entries > LOOM_REFERENCE_PHOTO_LIMIT) { errno = ENOSPC; break; }
401 }
402 const bool available = errno == 0 && entries < LOOM_REFERENCE_PHOTO_LIMIT;
403 if (closedir(stream) != 0) return false;
404 if (!available && !errno) errno = ENOSPC;
405 return available;
406}
407
408static bool reference_root_available(const char *directory);
409
410/**
411 * @brief Create an exclusive archive directory for a new session.
412 * @param base Archive root path.
413 * @param session_id Identifier formatted into the directory name.
414 * @param[out] destination Buffer for the formatted directory path.
415 * @param capacity Size of @p destination, including its terminator.
416 * @return True only if a new directory was created.
417 * @details Apply the root entry limit first and use exclusive directory
418 * creation so a reused session ID cannot silently inherit old references.
419 */
420static bool create_session_reference_directory(const char *base, uint32_t session_id,
421 char *destination, size_t capacity)
422{
423 if (!base || !base[0] || usher_ensure_directory(base) != 0 || !reference_root_available(base)) return false;
424 const int length = snprintf(destination, capacity, "%s/session-%010" PRIu32, base, session_id);
425 if (length < 0 || (size_t)length >= capacity) { errno = ENAMETOOLONG; return false; }
426 return mkdir(destination, 0700) == 0;
427}
428
429/**
430 * @brief Archive a published outbound JPEG without copying its pixels.
431 * @param filename Original saved JPEG.
432 * @param directory Existing session archive.
433 * @param sequence Photo number used in the reference basename.
434 * @return True if the new reference was linked.
435 * @details A hard link neither copies the image nor replaces an existing
436 * reference. The original must remain immutable and on the same filesystem.
437 */
438static bool record_reference(const char *filename, const char *directory, uint32_t sequence)
439{
440 char destination[PATH_MAX];
441 const int length = snprintf(destination, sizeof(destination), "%s/%c%0*" PRIu32 LOOM_JPEG_EXTENSION,
443 if (!directory || !directory[0] || length < 0 || (size_t)length >= sizeof(destination)
444 || !reference_directory_available(directory) || link(filename, destination) != 0) return false;
445 return true;
446}
447
448/**
449 * @brief Check whether the archive root can admit another session.
450 * @param directory Path of the archive root.
451 * @return True if the directory could be read and is below its entry limit.
452 * @details Stop scanning at the bound; old sessions remain on disk and
453 * consume capacity rather than being silently evicted.
454 */
455static bool reference_root_available(const char *directory)
456{
457 DIR *stream = opendir(directory);
458 if (!stream) return false;
459 unsigned entries = 0;
460 errno = 0;
461 struct dirent *entry;
462 while ((entry = readdir(stream)) != NULL) {
463 if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) continue;
464 if (++entries >= LOOM_REFERENCE_SESSION_LIMIT) { errno = ENOSPC; break; }
465 }
466 const bool available = errno == 0 && entries < LOOM_REFERENCE_SESSION_LIMIT;
467 if (closedir(stream) != 0) return false;
468 if (!available && !errno) errno = ENOSPC;
469 return available;
470}
471
472/**
473 * @brief Validate a return candidate in the persistent owner.
474 * @param[in,out] result Candidate, updated if the configured filter accepts it.
475 * @return True for an accepted candidate or an explicit no-point result.
476 * @details Keep ordering state across matcher subprocesses. Apply confidence
477 * and reference checks before passing an eligible candidate to the estimator.
478 */
480{
481 if (!result) return false;
482 if (!result->valid) return true;
483 if (result->quality < 0 || result->quality > LOOM_QUALITY_MAX ||
484 (double)result->quality / LOOM_QUALITY_MAX < loom_return_options.limits.minimum_confidence) return false;
487 const unsigned home_fields = (1U << 5) | (1U << 6);
488 const bool home_configured = (loom_return_options.seen & home_fields) == home_fields;
489 if (!home_configured || result->metric == LOOM_METRIC_BARO_MAGNETO) {
490 if (!result->session_id || result->session_id <= loom_return_state.sequence ||
493 (!result->lat && !result->lon)) return false;
494 loom_return_state.sequence = result->session_id;
495 return true;
496 }
497 const double radians = 0.017453292519943295, earth = 6378137;
498 const double scale = cos(loom_return_options.home_latitude * radians);
499 struct loom_return_point candidate = {
500 earth * scale * remainder(result->lon / 1e7 - loom_return_options.home_longitude, 360) * radians,
501 earth * (result->lat / 1e7 - loom_return_options.home_latitude) * radians
502 };
503 struct loom_return_state proposed = loom_return_state;
504 if (!loom_return_update(&proposed, &loom_return_options.limits, result->session_id,
505 candidate, &candidate)) return false;
506 const double latitude = loom_return_options.home_latitude + candidate.north / earth / radians;
507 const double longitude = remainder(loom_return_options.home_longitude + candidate.east / (earth * scale) / radians, 360);
508 if (!isfinite(latitude) || !isfinite(longitude) || fabs(latitude) > 90 || fabs(longitude) > 180 ||
509 (!llround(latitude * 1e7) && !llround(longitude * 1e7))) return false;
510 result->lat = (int32_t)llround(latitude * 1e7);
511 result->lon = (int32_t)llround(longitude * 1e7);
512 loom_return_state = proposed;
513 return true;
514}
515
516/**
517 * @brief Process the newest pending photo and suppress superseded completions.
518 * @param unused Required pthread argument; no per-thread heap state is used.
519 * @return NULL after shutdown.
520 * @details Snapshot the pending work under the mutex and release it before
521 * filesystem or child I/O. The phase generation prevents work from a previous
522 * phase from publishing into the new one, even if a photo number is reused.
523 */
524static void *loom_worker(void *unused)
525{
526 (void)unused;
527 for (;;) {
528 char filename[PATH_MAX];
529 pthread_mutex_lock(&loom_mutex);
530 while (!loom_pending && !loom_stopping) pthread_cond_wait(&loom_available, &loom_mutex);
531 if (loom_stopping) { pthread_mutex_unlock(&loom_mutex); return NULL; }
532 const uint32_t sequence = loom_latest_sequence;
533 const uint32_t phase = loom_phase;
534 const bool recording = loom_recording;
535 char references[PATH_MAX];
536 const bool paths_valid = copy_path(filename, sizeof(filename), loom_filename)
537 && copy_path(references, sizeof(references), loom_session_references);
538 loom_pending = false;
539 pthread_mutex_unlock(&loom_mutex);
540 /* Both collection and failed matching publish correlated INVALID results.
541 * Originals remain the evidence archive; dropped work is never a waypoint. */
542 struct camera_point_result result = {.session_id = sequence};
543 if (!paths_valid) fprintf(stderr, "LOOM_cam: photo path snapshot unavailable; no waypoint\n");
544 else if (recording && !record_reference(filename, references, sequence))
545 fprintf(stderr, "LOOM_cam: photo %" PRIu32 " reference unavailable (%s); original retained\n",
546 sequence, strerror(errno));
547 else if (!recording && !run_matcher(filename, references, sequence, &result, phase))
548 fprintf(stderr, "LOOM_cam: photo %" PRIu32 " matcher unavailable/invalid; no waypoint\n", sequence);
549 pthread_mutex_lock(&loom_mutex);
550 if (!loom_stopping && sequence == loom_latest_sequence && phase == loom_phase) {
552 result = (struct camera_point_result){.session_id = sequence};
553 loom_result = result; loom_ready = true;
555 }
556 pthread_mutex_unlock(&loom_mutex);
557 }
558}
559
560int loom_cam_set_settings(const char *settings)
561{
562 pthread_mutex_lock(&loom_mutex);
563 const int result = loom_running || !copy_path(loom_settings, sizeof(loom_settings), settings) ? -1 : 0;
564 pthread_mutex_unlock(&loom_mutex);
565 return result;
566}
567
568int loom_cam_init(const char *references, const char *model)
569{
570 pthread_mutex_lock(&loom_mutex);
571 if (loom_running) { pthread_mutex_unlock(&loom_mutex); return -1; }
572 if (!copy_path(loom_references, sizeof(loom_references), references)
574 || !copy_path(loom_model, sizeof(loom_model), model)) { pthread_mutex_unlock(&loom_mutex); return -1; }
577 char settings_path[INFERENCE_PATH_CAPACITY], settings_error[1024];
578 const char *selected_settings = loom_settings[0] ? loom_settings : NULL;
579 if (!selected_settings && inference_settings_find("loomcam", "loom_cam", settings_path, sizeof(settings_path)))
580 selected_settings = settings_path;
581 if (selected_settings) {
582 struct inference_settings inference;
585 settings_error, sizeof(settings_error)) ||
587 pthread_mutex_unlock(&loom_mutex);
588 return -1;
589 }
590 }
591 loom_pending = loom_ready = false;
594 /* Return mode permits bench matching against an existing reference directory
595 * before START. START explicitly changes to outbound reference collection. */
596 loom_recording = false;
597 loom_stopping = false;
598 if (!reap_matcher(0, NULL)) { pthread_mutex_unlock(&loom_mutex); return -1; }
599 loom_notification = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
600 if (loom_notification < 0) { pthread_mutex_unlock(&loom_mutex); return -1; }
601 const int error = pthread_create(&loom_thread, NULL, loom_worker, NULL);
602 loom_running = error == 0;
604 pthread_mutex_unlock(&loom_mutex);
605 return error ? -1 : 0;
606}
607
609{
610 return atomic_load(&loom_running) && !atomic_load(&loom_stopping);
611}
612
614{
615 pthread_mutex_lock(&loom_mutex);
616 const int descriptor = loom_notification;
617 pthread_mutex_unlock(&loom_mutex);
618 return descriptor;
619}
620
621bool loom_cam_start(uint32_t session_id)
622{
623 char session_references[PATH_MAX];
624 pthread_mutex_lock(&loom_mutex);
625 const bool eligible = loom_running && !loom_stopping && session_id != 0 && session_id != loom_session;
626 pthread_mutex_unlock(&loom_mutex);
627 if (!eligible) return false;
629 session_references, sizeof(session_references))) {
630 fprintf(stderr, "LOOM_cam: cannot create references for session %" PRIu32 " (%s)\n",
631 session_id, strerror(errno));
632 return false;
633 }
634 pthread_mutex_lock(&loom_mutex);
635 const bool accepted = loom_running && !loom_stopping && session_id != loom_session
636 && copy_path(loom_session_references, sizeof(loom_session_references), session_references);
637 if (accepted) {
638 /* The photo number alone cannot distinguish results from an earlier mode.
639 * Advance the phase so an in-flight old child cannot fill the new mailbox. */
640 loom_session = session_id;
641 ++loom_phase;
642 loom_recording = true;
644 loom_pending = loom_ready = false;
646 }
647 pthread_mutex_unlock(&loom_mutex);
648 if (!accepted) rmdir(session_references);
649 return accepted;
650}
651
652bool loom_cam_stop(uint32_t session_id)
653{
654 pthread_mutex_lock(&loom_mutex);
655 const bool accepted = loom_running && !loom_stopping && session_id && session_id == loom_session;
656 if (accepted) {
657 /* STOP changes processing policy, not camera ownership or flight waypoints.
658 * Matching still needs its own validated result after this transition. */
659 ++loom_phase;
660 loom_recording = false;
662 loom_pending = loom_ready = false;
664 }
665 pthread_mutex_unlock(&loom_mutex);
666 return accepted;
667}
668
669void loom_cam_image_saved(const char *filename, const union dc_shot_union *shot)
670{
671 /* Never stall capture completion on matcher contention. Replace older work
672 * rather than building a queue that would steer from obsolete photographs. */
673 if (!filename || !shot || shot->data.nr <= 0 || pthread_mutex_trylock(&loom_mutex) != 0) return;
674 if (loom_running && !loom_stopping && (uint32_t)shot->data.nr > loom_latest_sequence
675 && copy_path(loom_filename, sizeof(loom_filename), filename)) {
676 loom_latest_sequence = (uint32_t)shot->data.nr;
677 loom_pending = true;
678 loom_ready = false;
680 pthread_cond_signal(&loom_available);
681 }
682 pthread_mutex_unlock(&loom_mutex);
683}
684
686{
687 if (!result || pthread_mutex_trylock(&loom_mutex) != 0) return false;
688 const bool ready = loom_ready;
689 if (ready) { *result = loom_result; loom_ready = false; }
691 pthread_mutex_unlock(&loom_mutex);
692 return ready;
693}
694
696{
697 pthread_mutex_lock(&loom_mutex);
698 const bool running = loom_running;
699 loom_stopping = true;
700 pthread_cond_signal(&loom_available);
701 pthread_mutex_unlock(&loom_mutex);
702 /* Joining outside the mutex lets the worker observe shutdown and reap its
703 * child before configuration storage can be reused by the next init. */
704 if (running) pthread_join(loom_thread, NULL);
705 if (!reap_matcher(0, NULL)) {
706 kill(-loom_matcher_pid, SIGKILL);
707 kill(loom_matcher_pid, SIGKILL);
709 fprintf(stderr, "LOOM_cam: matcher exit remains unconfirmed\n");
710 }
711 pthread_mutex_lock(&loom_mutex);
715 pthread_mutex_unlock(&loom_mutex);
716}
static void wait_ms(int milliseconds)
Wait until a short polling interval elapses.
char ** environ
static unsigned capacity[COVERAGE_CAMERAS]
static double latitude
static double longitude
int descriptor
Definition chdk_pipe.c:142
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
static bool started
static bool ready
bool inference_settings_find(const char *application, const char *module, char *filename, size_t capacity)
Discover application_settings.ini in adjacent, development-module, then installed-share order.
bool inference_settings_read(struct inference_settings *settings, const char *filename, ini_field_handler extra, void *context, char *error, size_t capacity)
Parse one flat INI, delegate application keys and resolve paths against the selected file.
void inference_settings_init(struct inference_settings *settings, enum inference_backend backend)
Reset storage and select conservative thread/timeout defaults.
Shared application_settings.ini discovery with module-owned extra keys.
#define INFERENCE_PATH_CAPACITY
@ INFERENCE_AUTO
bool loom_cam_poll_result(struct camera_point_result *result)
Consume a result on the serial owner; session_id carries the photo number for this stream.
Definition loom_cam.c:685
#define LOOM_JPEG_EXTENSION
Definition loom_cam.c:76
static char loom_model[PATH_MAX]
Definition loom_cam.c:121
#define USHER_LOOMCAM_COMMAND
Saved-photo child executable; not another camera-acquisition process.
Definition loom_cam.c:51
static struct camera_point_result loom_result
Definition loom_cam.c:125
bool loom_cam_start(uint32_t session_id)
Select outbound reference collection and discard old-phase mailbox work.
Definition loom_cam.c:621
static bool loom_pending
The latest copied path awaits worker consumption; older pending work is replaceable.
Definition loom_cam.c:110
bool loom_cam_stop(uint32_t session_id)
Select return matching and discard old-phase mailbox work.
Definition loom_cam.c:652
static bool copy_path(char *destination, size_t capacity, const char *source)
Copy a complete NUL-terminated path into owned, fixed-size storage.
Definition loom_cam.c:158
static uint64_t loom_monotonic_ms(void)
Read the watchdog clock in milliseconds.
Definition loom_cam.c:235
void loom_cam_deinit(void)
Cancel pending work and join the worker before reusing adapter state.
Definition loom_cam.c:695
int loom_cam_set_settings(const char *settings)
Select executable settings before starting the saved-photo worker.
Definition loom_cam.c:560
static bool loom_ready
Definition loom_cam.c:110
static char loom_references[PATH_MAX]
Reference-directory configuration, fixed until the worker has been joined.
Definition loom_cam.c:120
#define LOOM_SEQUENCE_TEXT_BYTES
Definition loom_cam.c:58
static pthread_t loom_thread
Definition loom_cam.c:105
static bool filter_return_point(struct camera_point_result *result)
Validate a return candidate in the persistent owner.
Definition loom_cam.c:479
#define LOOM_REFERENCE_SESSION_LIMIT
Definition loom_cam.c:65
static void notify_completion(void)
Wake the event loop when completion state may have changed.
Definition loom_cam.c:143
#define LOOM_REFERENCE_PHOTO_LIMIT
Definition loom_cam.c:64
static uint32_t loom_session
START token used to admit the corresponding STOP, not a photo number.
Definition loom_cam.c:114
static atomic_bool loom_stopping
Definition loom_cam.c:106
static bool run_matcher(const char *filename, const char *references, uint32_t sequence, struct camera_point_result *result, uint32_t phase)
Run the saved-photo matcher with bounded output and a watchdog.
Definition loom_cam.c:296
static char loom_settings[PATH_MAX]
Definition loom_cam.c:122
static bool matcher_phase_current(uint32_t phase)
Check whether an in-flight match still belongs to the active phase.
Definition loom_cam.c:276
static bool reap_matcher(unsigned timeout_ms, int *status)
Wait up to a bounded time for the owned matcher to exit.
Definition loom_cam.c:250
loom_wire_validity
The validity field accepts only these two numeric wire values.
Definition loom_cam.c:95
@ LOOM_WIRE_INVALID
Definition loom_cam.c:95
@ LOOM_WIRE_VALID
Definition loom_cam.c:95
static pid_t loom_matcher_pid
Definition loom_cam.c:126
static char loom_filename[PATH_MAX]
Latest admitted immutable saved-photo path, copied into bounded storage.
Definition loom_cam.c:120
static atomic_bool loom_running
Definition loom_cam.c:107
loom_pipe_endpoint
POSIX pipe endpoints; names distinguish child output from parent input.
Definition loom_cam.c:97
@ LOOM_PIPE_READ
Definition loom_cam.c:97
@ LOOM_PIPE_WRITE
Definition loom_cam.c:97
@ LOOM_PIPE_ENDPOINT_COUNT
Definition loom_cam.c:97
static int loom_notification
Definition loom_cam.c:127
static bool read_result_field(const char **cursor, const char *key, intmax_t *value)
Consume one exact field prefix followed by a signed decimal integer.
Definition loom_cam.c:176
static void drain_notification(void)
Clear the completion event counter.
Definition loom_cam.c:132
static bool reference_directory_available(const char *directory)
Check whether a session reference directory has room for another entry.
Definition loom_cam.c:391
static void * loom_worker(void *unused)
Process the newest pending photo and suppress superseded completions.
Definition loom_cam.c:524
bool loom_cam_enabled(void)
Report whether this optional stream is running and not stopping.
Definition loom_cam.c:608
static bool loom_recording
Definition loom_cam.c:115
#define LOOM_LONGITUDE_LIMIT_E7
Definition loom_cam.c:73
#define LOOM_EXIT_GRACE_MS
Definition loom_cam.c:61
static uint32_t loom_phase
Definition loom_cam.c:114
static pthread_cond_t loom_available
Definition loom_cam.c:104
#define LOOM_REFERENCE_SEQUENCE_DIGITS
Definition loom_cam.c:75
#define LOOM_QUALITY_MAX
Definition loom_cam.c:74
#define LOOM_WORKER_TIMEOUT_MS
Definition loom_cam.c:60
#define LOOM_WORKER_POLL_MS
Definition loom_cam.c:59
#define LOOM_RESULT_LINE_BYTES
Definition loom_cam.c:57
#define LOOM_LATITUDE_LIMIT_E7
Definition loom_cam.c:72
static bool record_reference(const char *filename, const char *directory, uint32_t sequence)
Archive a published outbound JPEG without copying its pixels.
Definition loom_cam.c:438
static bool reference_root_available(const char *directory)
Check whether the archive root can admit another session.
Definition loom_cam.c:455
static pthread_mutex_t loom_mutex
Definition loom_cam.c:103
static bool create_session_reference_directory(const char *base, uint32_t session_id, char *destination, size_t capacity)
Create an exclusive archive directory for a new session.
Definition loom_cam.c:420
void loom_cam_image_saved(const char *filename, const union dc_shot_union *shot)
Copy the newest completed AIcam photo request into bounded worker storage.
Definition loom_cam.c:669
int loom_cam_completion_fd(void)
Borrow the nonblocking completion descriptor; minus one when not initialized.
Definition loom_cam.c:613
static char loom_session_references[PATH_MAX]
Definition loom_cam.c:120
static bool parse_result(const char *line, uint32_t sequence, struct camera_point_result *result)
Validate and correlate one complete reply before publishing any fields.
Definition loom_cam.c:201
int loom_cam_init(const char *references, const char *model)
Start one saved-photo worker; does not acquire another camera.
Definition loom_cam.c:568
loom_result_field
Ordered fields of the strict LOOM_POINT_V1 text contract.
Definition loom_cam.c:82
@ LOOM_RESULT_FIELD_COUNT
Definition loom_cam.c:91
@ LOOM_FIELD_ALTITUDE_MM
Definition loom_cam.c:87
@ LOOM_FIELD_SEQUENCE
Definition loom_cam.c:83
@ LOOM_FIELD_VALID
Definition loom_cam.c:84
@ LOOM_FIELD_METRIC
Definition loom_cam.c:90
@ LOOM_FIELD_AGL_MM
Definition loom_cam.c:88
@ LOOM_FIELD_LATITUDE
Definition loom_cam.c:85
@ LOOM_FIELD_QUALITY
Definition loom_cam.c:89
@ LOOM_FIELD_LONGITUDE
Definition loom_cam.c:86
static uint32_t loom_latest_sequence
Definition loom_cam.c:111
#define LOOM_KILL_GRACE_MS
Definition loom_cam.c:62
#define LOOM_NS_PER_MS
Definition loom_cam.c:63
Bounded asynchronous saved-photo adapter for LOOM_cam.
#define LOOM_IMAGE_PREFIX
LOOM photographs and outbound references use 'o', not AIcam's 'a'.
Definition loom_cam.h:38
void loom_return_options_init(struct loom_return_options *options)
Initialize return limits with feature-only semantics by default.
Definition loom_return.c:40
bool loom_return_options_valid(const struct loom_return_options *options)
Check that optional destination coordinates are either both present or both omitted.
Definition loom_return.c:47
bool loom_return_update(struct loom_return_state *state, const struct loom_return_config *config, uint32_t sequence, struct loom_return_point candidate, struct loom_return_point *target)
Admit a fresh bounded target and limit its movement.
bool loom_return_setting(void *context, const char *key, const char *value)
Parse one LOOM-owned settings field, rejecting duplicates and unknown keys.
Definition loom_return.c:55
Bounded direction-to-target policy, independent of inference and FC transport.
@ LOOM_METRIC_BARO_MAGNETO
Definition loom_return.h:38
@ LOOM_RETURN_NONE
Definition loom_return.h:58
#define LOOM_DECIMAL_RADIX
The CLI accepts decimal photo numbers, never signed or truncated IDs.
Definition loomcam.c:46
static const volatile sig_atomic_t * running
struct jpeg_error_mgr error
Definition lwir_image.c:60
static const char * selected_settings
Small path and writable-directory helpers shared by USHER backends.
#define PATH_MAX
Definition path_utils.h:39
static int usher_ensure_directory(const char *path)
Create missing directory components and verify the final directory is writable.
Definition path_utils.h:97
static pthread_cond_t available
Definition pose_log.c:73
static size_t count
Definition pose_log.c:79
static uint64_t accepted
Definition pose_log.c:81
static FILE * output
Definition pose_log.c:77
Per-application configuration; all resolved paths belong to this caller-owned value.
double minimum_confidence
Definition loom_return.h:46
Module-owned inference settings, separate from universal runtime settings.
Definition loom_return.h:65
struct loom_return_config limits
Definition loom_return.h:66
enum loom_return_frame frame
Definition loom_return.h:67
Local ground point in metres east/north of the reference origin.
Definition loom_return.h:31
Caller-owned sequence and smoothing state; first observation seeds target.
Definition loom_return.h:51
One timestamped geographic position for a replay annotation.
struct usher_control_result result
Definition usher.c:377
union dc_shot_union shot
Definition usher.c:534