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
lwir_cam_pipe.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#include "lwir_cam_pipe.h"
19#include "camera_capture.h"
21#include "path_utils.h"
22
23/**
24 * @file lwir_cam_pipe.c
25 * @brief USHER-side supervisor for the persistent LWIR capture-server process.
26 * @details The server holds the Tiny1-C stream open, avoiding per-shot sensor warmup.
27 * This parent owns its pipes and child lifecycle, validates line-protocol replies and
28 * capture timing. All failure paths clear state before returning so USHER's supervisor
29 * can schedule a later retry without reusing a stale descriptor.
30 */
31
32#include <errno.h>
33#include <fcntl.h>
34#include <limits.h>
35#include <math.h>
36#include <poll.h>
37#include <signal.h>
38#include <spawn.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <sys/wait.h>
45#include <time.h>
46#include <unistd.h>
47
48#include "camera_backend.h"
49
50#ifndef USHER_LWIR_CAM_PHOTO_DIR
51 #define USHER_LWIR_CAM_PHOTO_DIR "~/Pictures/sensoraia"
52#endif
53
54#ifndef USHER_LWIR_CAM_COMMAND
55 #define USHER_LWIR_CAM_COMMAND "./bin/lwircam"
56#endif
57
58#ifndef CHILD_STOP_GRACE_MS
59 #define CHILD_STOP_GRACE_MS 500
60#endif
61#define CHILD_WAIT_INTERVAL_MS 10
62#define IMAGE_PROCESS_TIMEOUT_MS 30000
63#ifndef LWIR_SERVER_START_TIMEOUT_MS
64 #define LWIR_SERVER_START_TIMEOUT_MS 30000
65#endif
66#define LWIR_WARMUP_TIMEOUT_MS 30000
67#ifndef LWIR_REQUEST_TIMEOUT_MS
68 #define LWIR_REQUEST_TIMEOUT_MS 8000
69#endif
70
71extern char **environ;
72
73static pid_t capture_server_pid = -1;
74static int capture_server_input = -1;
75static int capture_server_output = -1;
76/** Buffered reassembly for read_server_status(): avoids one poll()+read() syscall
77 * pair per byte, which otherwise adds up to hundreds of syscalls per response line
78 * set on every single shot. */
79static char status_buffer[512];
81static double capture_delay_s = -1;
84static const char *calibration_path;
87static const char *lwir_config;
88static const volatile sig_atomic_t *running;
89
91{
92 running = host ? host->running : NULL;
93}
94
95int lwir_cam_pipe_set_config(const char *path)
96{
97 if (!path || !*path || capture_server_pid >= 0) return -1;
98 lwir_config = path;
99 return 0;
100}
101
102/** @brief Read the capture-server watchdog clock.
103 * @return Monotonic milliseconds, or zero on failure.
104 * @details Keep supervision independent of system time corrections. */
105static uint64_t monotonic_ms(void)
106{
107 struct timespec now;
108 return clock_gettime(CLOCK_MONOTONIC, &now) == 0
109 ? (uint64_t)now.tv_sec * 1000U + (uint64_t)now.tv_nsec / 1000000U : 0;
110}
111
112/** @brief Wait up to a bounded time for the capture child to exit.
113 * @param pid Owned positive child PID.
114 * @param[out] status Wait status, set if this call reaps the child.
115 * @param timeout_ms Nonnegative budget; zero checks without sleeping.
116 * @return One if reaped or no longer a child, zero on timeout, or -1 on error.
117 * @details Use nonblocking waits so a child stuck in a device call does not
118 * indefinitely block its supervisor. */
119static int wait_child(pid_t pid, int *status, int timeout_ms)
120{
121 const uint64_t started_ms = monotonic_ms();
122 if (started_ms == 0) return -1;
123 for (;;) {
124 pid_t result = waitpid(pid, status, WNOHANG);
125 if (result == pid || (result < 0 && errno == ECHILD)) return 1;
126 if (result < 0 && errno != EINTR) return -1;
127 uint64_t now_ms = monotonic_ms();
128 if (now_ms == 0 || now_ms - started_ms >= (uint64_t)timeout_ms) return 0;
129 struct timespec pause = {.tv_sec = 0, .tv_nsec = CHILD_WAIT_INTERVAL_MS * 1000000L};
130 while (nanosleep(&pause, &pause) != 0 && errno == EINTR) {}
131 }
132}
133
134/** @brief Stop an owned capture child, escalating only after its grace period.
135 * @param pid Owned positive child PID.
136 * @param[out] status Wait status, set if the child is reaped here.
137 * @return One if ownership ended, zero if still waiting after escalation, or -1 on error.
138 * @details Reap an already exited child first. Give normal teardown a chance
139 * to release the camera before sending SIGKILL. */
140static int terminate_child(pid_t pid, int *status)
141{
142 int result = wait_child(pid, status, 0);
143 if (result != 0) return result;
144 if (kill(pid, SIGTERM) != 0 && errno != ESRCH) return -1;
145 result = wait_child(pid, status, CHILD_STOP_GRACE_MS);
146 if (result != 0) return result;
147 if (kill(pid, SIGKILL) != 0 && errno != ESRCH) return -1;
148 return wait_child(pid, status, CHILD_STOP_GRACE_MS);
149}
150
151/** @brief Open a close-on-exec pipe for child protocol setup.
152 * @param[out] descriptors Read and write descriptors; valid only on success.
153 * @return Zero on success, or -1 with errno on failure.
154 * @details Keep both descriptors above stderr so child's descriptor
155 * redirection cannot alias an endpoint when a standard descriptor was closed. */
156static int create_cloexec_pipe(int descriptors[2])
157{
158 if (pipe(descriptors) != 0) return -1;
159 for (size_t index = 0; index < 2; ++index) {
160 if (descriptors[index] <= STDERR_FILENO) {
161 const int replacement = fcntl(descriptors[index], F_DUPFD_CLOEXEC, STDERR_FILENO + 1);
162 if (replacement < 0) {
163 const int saved_errno = errno;
164 close(descriptors[0]);
165 close(descriptors[1]);
166 errno = saved_errno;
167 return -1;
168 }
169 close(descriptors[index]);
170 descriptors[index] = replacement;
171 }
172 int flags = fcntl(descriptors[index], F_GETFD);
173 if (flags < 0 || fcntl(descriptors[index], F_SETFD, flags | FD_CLOEXEC) != 0) {
174 int saved_errno = errno;
175 close(descriptors[0]);
176 close(descriptors[1]);
177 errno = saved_errno;
178 return -1;
179 }
180 }
181 return 0;
182}
183
184void lwir_cam_pipe_set_photo_directory(const char *directory)
185{
186 photo_directory = directory == NULL ? USHER_LWIR_CAM_PHOTO_DIR : directory;
187}
188
193
194int lwir_cam_pipe_set_calibration(const char *path)
195{
196 if (!LWIR_ENABLE_ANALYSIS) { errno = ENOTSUP; return -1; }
197 if (path == NULL || path[0] == '\0') return -1;
198 calibration_path = path;
199 return 0;
200}
201
206
207/** @brief Parse one server timing payload after its protocol prefix.
208 * @param text Space-separated unsigned timing fields.
209 * @param timing Receives validated timing evidence.
210 * @param callback True for callback sequence/drop fields, false for polling timing.
211 * @return 1 for valid evidence, 0 for malformed or implausible evidence.
212 * @details Parsing is intentionally strict: timing metadata enriches EXIF but must
213 * never be accepted merely because a server process printed a vaguely similar line. */
214static int parse_capture_timing(const char *text, struct capture_timing *timing, bool callback)
215{
216 if (!text || !timing) return 0;
217 uint64_t values[4] = {0};
218 const size_t count = callback ? 4 : 2;
219 for (size_t index = 0; index < count; ++index) {
220 char *end;
221 if (*text < '0' || *text > '9') return 0;
222 errno = 0;
223 unsigned long long value = strtoull(text, &end, 10);
224 if (errno != 0 || value > UINT64_MAX) return 0;
225 values[index] = value;
226 if (index + 1 == count) {
227 if (*end != '\0') return 0;
228 } else {
229 if (*end != ' ') return 0;
230 text = end + 1;
231 }
232 }
233 struct capture_timing parsed = {
234 .request_monotonic_us = values[0], .arrival_monotonic_us = values[1],
235 .callback_sequence = values[2], .callback_drops = values[3], .callback_arrival = callback
236 };
237 if (!capture_timing_valid(&parsed)) return 0;
238 *timing = parsed;
239 return 1;
240}
241
243{
244 return capture_delay_s;
245}
246
247/** @brief Read server diagnostic lines until an expected terminal reply arrives.
248 * @param expected Success line required to complete the operation.
249 * @param timeout_ms Whole-operation deadline.
250 * @param keep_running Optional cancellation flag; checked between bounded polls
251 * so stopping USHER need not wait for a thermal camera's full startup deadline.
252 * @return 0 on the expected reply, -1 for cancellation, timeout, EOF, or server error.
253 * @details Informational timing lines are parsed before the terminal reply. The buffer
254 * avoids a syscall per character while retaining line framing. One absolute deadline
255 * prevents a noisy or malicious child from extending an operation indefinitely. */
256static int read_server_status(const char *expected, int timeout_ms,
257 const volatile sig_atomic_t *keep_running)
258{
259 char line[256] = {0};
260 size_t line_size = 0;
261 const uint64_t started_ms = monotonic_ms();
262 if (started_ms == 0) return -1;
263
264 for (;;) {
265 if (!capture_running(keep_running)) return -1;
267 if (capture_server_output < 0) return -1;
268 uint64_t now_ms = monotonic_ms();
269 if (now_ms == 0 || now_ms - started_ms >= (uint64_t)timeout_ms) return -1;
270 int remaining_ms = timeout_ms - (int)(now_ms - started_ms);
271 int poll_timeout_ms = keep_running != NULL && remaining_ms > 100 ? 100 : remaining_ms;
272 struct pollfd descriptor = {capture_server_output, POLLIN, 0};
273 int poll_result = poll(&descriptor, 1, poll_timeout_ms);
274 if (poll_result < 0 && errno == EINTR) continue;
275 if (poll_result == 0) continue;
276 if (poll_result < 0
277 || ((descriptor.revents & POLLIN) == 0
278 && (descriptor.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0)) {
279 return -1;
280 }
281 ssize_t bytes_read = read(capture_server_output, status_buffer, sizeof(status_buffer));
282 if (bytes_read < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) continue;
283 if (bytes_read <= 0) {
284 return -1;
285 }
286 status_buffer_size = (size_t)bytes_read;
288 }
289 char character = status_buffer[status_buffer_pos++];
290 if (character != '\n' && ((unsigned char)character < 32 || character == 127 || line_size + 1 >= sizeof(line))) return -1;
291 if (character != '\n' && line_size + 1 < sizeof(line)) {
292 line[line_size++] = character;
293 continue;
294 }
295
296 line[line_size] = '\0';
297 double delay;
298 char trailing;
299 if (strcmp(expected, "LWIR_SERVER_OK") == 0 && !capture_timing_valid(&capture_times)
300 && sscanf(line, "LWIR_SERVER_DELAY %lf %c", &delay, &trailing) == 1
301 && isfinite(delay) && delay >= 0 && delay <= 20) {
302 capture_delay_s = delay;
303 }
304 const char timing_prefix[] = "LWIR_SERVER_TIMING ";
305 if (strcmp(expected, "LWIR_SERVER_OK") == 0
306 && !capture_times.callback_arrival
307 && line_size >= sizeof(timing_prefix)
308 && strncmp(line, timing_prefix, sizeof(timing_prefix) - 1) == 0
309 && parse_capture_timing(line + sizeof(timing_prefix) - 1, &capture_times, false)) {
310 capture_delay_s = (capture_times.arrival_monotonic_us - capture_times.request_monotonic_us) / 1e6;
311 }
312 const char callback_prefix[] = "LWIR_SERVER_CALLBACK_TIMING ";
313 if (strcmp(expected, "LWIR_SERVER_OK") == 0
314 && line_size >= sizeof(callback_prefix)
315 && strncmp(line, callback_prefix, sizeof(callback_prefix) - 1) == 0
316 && parse_capture_timing(line + sizeof(callback_prefix) - 1, &capture_times, true)) {
317 capture_delay_s = (capture_times.arrival_monotonic_us - capture_times.request_monotonic_us) / 1e6;
318 }
319 if (strcmp(line, expected) == 0) {
320 return 0;
321 }
322 if (strncmp(line, "LWIR_SERVER_ERROR", 17) == 0) {
323 fprintf(stderr, "LWIR_CAM_PIPE:\t%s\n", line);
324 return -1;
325 }
326 line_size = 0;
327 }
328}
329
330/** @brief Close pipes and reap or terminate the owned capture server.
331 * @details Buffered response state is reset before the next spawn. Closing stdin asks
332 * cooperative server versions to exit; SIGTERM is used only when it remains alive. */
333static void stop_capture_server(void)
334{
336 if (capture_server_input >= 0) {
339 }
340 if (capture_server_output >= 0) {
343 }
344 if (capture_server_pid < 0) {
345 return;
346 }
347
348 int status = 0;
349 if (terminate_child(capture_server_pid, &status) <= 0) {
350 fprintf(stderr, "LWIR_CAM_PIPE:\tcapture server pid %ld could not be reaped\n",
351 (long)capture_server_pid);
352 return;
353 }
355}
356
357/** Send one line request to the running server and wait for its reply. On any
358 * failure (broken pipe, dead process, or a timed-out/erroring reply) the server
359 * state is fully reset so a caller's retry starts with a clean respawn instead of
360 * repeatedly hitting the same stale, already-dead connection. */
361/** @brief Send one newline-terminated server request and require an OK reply.
362 * @return 0 on end-to-end success or -1 after fully resetting failed server state. */
363static int send_request_and_wait(const char *request, size_t request_size, int timeout_ms, const char *expected)
364{
365 const uint64_t started_ms = monotonic_ms();
366 if (!started_ms || timeout_ms <= 0) { stop_capture_server(); return -1; }
367 size_t sent = 0;
368 while (sent < request_size) {
369 if (!capture_running(running)) { stop_capture_server(); return -1; }
370 const uint64_t now_ms = monotonic_ms();
371 if (!now_ms || now_ms < started_ms || now_ms - started_ms >= (uint64_t)timeout_ms) {
372 stop_capture_server(); return -1;
373 }
374 ssize_t written = write(capture_server_input, request + sent, request_size - sent);
375 if (written > 0) {
376 sent += (size_t)written;
377 } else if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
378 struct pollfd writable = {.fd = capture_server_input, .events = POLLOUT};
379 const int remaining = timeout_ms - (int)(now_ms - started_ms);
380 const int ready = poll(&writable, 1, running && remaining > 100 ? 100 : remaining);
381 if (ready < 0 && errno == EINTR) continue;
382 if (ready == 0 || (ready > 0 && !(writable.revents & (POLLERR | POLLHUP | POLLNVAL)))) continue;
384 return -1;
385 } else if (written == 0 || errno != EINTR) {
386 if (!written) errno = EIO;
387 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to send request: %s\n", strerror(errno));
389 return -1;
390 }
391 }
392 const uint64_t elapsed_ms = monotonic_ms() - started_ms;
393 if (elapsed_ms >= (uint64_t)timeout_ms || read_server_status(expected, timeout_ms - (int)elapsed_ms, running) != 0) {
395 return -1;
396 }
397 return 0;
398}
399
400/** @brief Start the persistent thermal capture subprocess.
401 * @param unused Reserved backend argument.
402 * @param keep_running Optional shutdown flag used during the readiness wait.
403 * @return Zero after readiness, or -1 on ownership, setup, or protocol failure.
404 * @details Resolve any old owner before launching. Connect separate command
405 * and response pipes and require the startup acknowledgement before capture. */
406static int start_capture_server(const char *unused,
407 const volatile sig_atomic_t *keep_running)
408{
409 (void)unused;
410 if (capture_server_pid >= 0) {
412 if (capture_server_pid >= 0) return -1;
413 }
414 char resolved_dir[PATH_MAX];
415 const char *photo_dir = usher_resolve_path(photo_directory, resolved_dir, sizeof(resolved_dir));
416
417 if (usher_ensure_directory(photo_dir) != 0) {
418 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to create photo directory %s: %s\n",
419 photo_dir, strerror(errno));
420 return -1;
421 }
422
423 struct stat directory_status;
424 if (stat(photo_dir, &directory_status) != 0
425 || !S_ISDIR(directory_status.st_mode)
426 || access(photo_dir, W_OK) != 0) {
427 fprintf(stderr, "LWIR_CAM_PIPE:\tphoto directory is not writable: %s\n",
428 photo_dir);
429 return -1;
430 }
431 if (access(capture_command, X_OK) != 0) {
432 fprintf(stderr, "LWIR_CAM_PIPE:\tcapture command is not executable: %s: %s\n",
433 capture_command, strerror(errno));
434 return -1;
435 }
436
437 int command_pipe[2];
438 int response_pipe[2];
439 if (create_cloexec_pipe(command_pipe) != 0) {
440 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to create capture-server pipes: %s\n",
441 strerror(errno));
442 return -1;
443 }
444 if (create_cloexec_pipe(response_pipe) != 0) {
445 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to create capture-server pipes: %s\n",
446 strerror(errno));
447 close(command_pipe[0]);
448 close(command_pipe[1]);
449 return -1;
450 }
451
452 posix_spawn_file_actions_t actions;
453 int action_result = posix_spawn_file_actions_init(&actions);
454 bool actions_initialized = action_result == 0;
455 if (action_result == 0) action_result = posix_spawn_file_actions_adddup2(&actions, command_pipe[0], STDIN_FILENO);
456 if (action_result == 0) action_result = posix_spawn_file_actions_adddup2(&actions, response_pipe[1], STDOUT_FILENO);
457 if (action_result == 0) action_result = posix_spawn_file_actions_addclose(&actions, command_pipe[1]);
458 if (action_result == 0) action_result = posix_spawn_file_actions_addclose(&actions, response_pipe[0]);
459 if (action_result != 0) {
460 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to configure capture server: %s\n",
461 strerror(action_result));
462 if (actions_initialized) posix_spawn_file_actions_destroy(&actions);
463 close(command_pipe[0]);
464 close(command_pipe[1]);
465 close(response_pipe[0]);
466 close(response_pipe[1]);
467 return -1;
468 }
469
470 char *arguments[10];
471 size_t count = 0;
472 arguments[count++] = (char *)capture_command;
473 arguments[count++] = (char *)"--capture-server";
474 arguments[count++] = (char *)"--bare";
475 if (lwir_config) {
476 arguments[count++] = (char *)"--config";
477 arguments[count++] = (char *)lwir_config;
478 }
479 if (native_raw_enabled) arguments[count++] = (char *)"--native-raw";
480 if (calibration_path != NULL) {
481 arguments[count++] = (char *)"--calibration";
482 arguments[count++] = (char *)calibration_path;
483 }
484 arguments[count] = NULL;
485 int spawn_result = posix_spawn(&capture_server_pid, capture_command,
486 &actions, NULL, arguments, environ);
487 posix_spawn_file_actions_destroy(&actions);
488 close(command_pipe[0]);
489 close(response_pipe[1]);
490 if (spawn_result != 0) {
491 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to start %s: %s\n",
492 capture_command, strerror(spawn_result));
493 close(command_pipe[1]);
494 close(response_pipe[0]);
496 return -1;
497 }
498 capture_server_input = command_pipe[1];
499 capture_server_output = response_pipe[0];
500 const int endpoints[] = {capture_server_input, capture_server_output};
501 for (size_t index = 0; index < sizeof(endpoints) / sizeof(endpoints[0]); ++index) {
502 const int flags = fcntl(endpoints[index], F_GETFL);
503 if (flags < 0 || fcntl(endpoints[index], F_SETFL, flags | O_NONBLOCK) < 0) {
505 return -1;
506 }
507 }
508 if (read_server_status("LWIR_SERVER_READY", LWIR_SERVER_START_TIMEOUT_MS, keep_running) != 0) {
509 fprintf(stderr, "LWIR_CAM_PIPE:\tcapture server did not become ready\n");
511 return -1;
512 }
513
514 printf("LWIR_CAM_PIPE:\tcapture command: %s\n", capture_command);
515 printf("LWIR_CAM_PIPE:\tphoto directory: %s\n", photo_dir);
516 printf("LWIR_CAM_PIPE:\tpersistent capture server ready\n");
517 return 0;
518}
519
520int lwir_cam_pipe_init(const char *unused)
521{
522 return start_capture_server(unused, NULL);
523}
524
525int lwir_cam_pipe_init_cancelable(const char *unused,
526 const volatile sig_atomic_t *keep_running)
527{
528 return start_capture_server(unused, keep_running);
529}
530
532{
533 /** Open the sensor once, wait past its power-on "wiggly" image, then close it
534 * again. Runs regardless of whether LWIR ends up selected for a shot, so a
535 * later real open (persistent server or standalone capture) never has to
536 * absorb that transient inline. Failure here is not fatal to USHER. */
537 if (access(USHER_LWIR_CAM_COMMAND, X_OK) != 0) {
538 fprintf(stderr, "LWIR_CAM_PIPE:\twarmup skipped, command is not executable: %s: %s\n",
539 USHER_LWIR_CAM_COMMAND, strerror(errno));
540 return -1;
541 }
542
543 char *const arguments[] = {
545 (char *)"--warmup",
546 NULL
547 };
548 pid_t warmup_pid;
549 int spawn_result = posix_spawn(&warmup_pid, USHER_LWIR_CAM_COMMAND,
550 NULL, NULL, arguments, environ);
551 if (spawn_result != 0) {
552 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to start warmup: %s\n", strerror(spawn_result));
553 return -1;
554 }
555
556 int status = 0;
557 int wait_result = wait_child(warmup_pid, &status, LWIR_WARMUP_TIMEOUT_MS);
558 if (wait_result == 0) wait_result = terminate_child(warmup_pid, &status);
559 if (wait_result <= 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
560 fprintf(stderr, "LWIR_CAM_PIPE:\tsensor not accessible or warmup failed\n");
561 return -1;
562 }
563 return 0;
564}
565
566/* Keep standalone mock/geolocation work separate from real capture: real shots
567 * use the warmed server to avoid startup latency and competing camera ownership. */
568#if LWIR_ENABLE_ANALYSIS || LWIR_ENABLE_MOCK
569static int process_image(char *filename, int geolocate)
570{
571 if (filename == NULL || filename[0] == '\0') {
572 return -1;
573 }
574
575 char *arguments[7];
576 size_t count = 0;
577 arguments[count++] = (char *)USHER_LWIR_CAM_COMMAND;
578 if (geolocate) {
579 arguments[count++] = (char *)"--geolocate";
580 arguments[count++] = filename;
581 if (calibration_path != NULL) {
582 arguments[count++] = (char *)"--calibration";
583 arguments[count++] = (char *)calibration_path;
584 }
585 } else {
586 arguments[count++] = (char *)"--mock-image";
587 arguments[count++] = filename;
588 arguments[count++] = (char *)"--output";
589 arguments[count++] = filename;
590 }
591 arguments[count] = NULL;
592 pid_t camera_pid;
593 int spawn_result = posix_spawn(&camera_pid, USHER_LWIR_CAM_COMMAND,
594 NULL, NULL, arguments, environ);
595 if (spawn_result != 0) {
596 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to start image processing: %s\n",
597 strerror(spawn_result));
598 return -1;
599 }
600
601 int status = 0;
602 int wait_result = wait_child(camera_pid, &status, IMAGE_PROCESS_TIMEOUT_MS);
603 if (wait_result == 0) wait_result = terminate_child(camera_pid, &status);
604 if (wait_result <= 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
605 fprintf(stderr, "LWIR_CAM_PIPE:\timage processing failed\n");
606 return -1;
607 }
608 return 0;
609}
610#endif
611
612int lwir_cam_pipe_process_mock(char *filename)
613{
614#if LWIR_ENABLE_MOCK
615 return process_image(filename, 0);
616#else
617 (void)filename;
618 errno = ENOTSUP;
619 return -1;
620#endif
621}
622
623int lwir_cam_pipe_geolocate(char *filename)
624{
625#if LWIR_ENABLE_ANALYSIS
626 if (filename == NULL || filename[0] == '\0') {
627 return -1;
628 }
630 /** No persistent server running (test/mock mode): fall back to a one-off process. */
631 return process_image(filename, 1);
632 }
633
634 /** Reuse the already-running, already-warmed-up server for analysis instead of
635 * spawning a fresh lwircam process for every shot. */
636 char request[PATH_MAX + 8];
637 int request_size = snprintf(request, sizeof(request), "GEO:%s\n", filename);
638 if (request_size < 0 || (size_t)request_size >= sizeof(request)) {
639 return -1;
640 }
641 if (send_request_and_wait(request, (size_t)request_size, LWIR_REQUEST_TIMEOUT_MS, "LWIR_SERVER_OK") != 0) {
642 fprintf(stderr, "LWIR_CAM_PIPE:\tcapture server failed to geolocate %s\n", filename);
643 return -1;
644 }
645 return 0;
646#else
647 (void)filename;
648 errno = ENOTSUP;
649 return -1;
650#endif
651}
652
653int lwir_cam_pipe_shoot(char *filename, size_t filename_size, int image_number)
654{
655 capture_delay_s = -1;
656 capture_times = (struct capture_timing) {0};
657 if (filename == NULL || filename_size == 0 || image_number < 0) {
658 return -1;
659 }
660
661 char resolved_dir[PATH_MAX];
662 const char *photo_dir = usher_resolve_path(photo_directory, resolved_dir, sizeof(resolved_dir));
663
664 int length = snprintf(filename, filename_size, "%s/l%06d.jpg",
665 photo_dir, image_number);
666 if (length < 0 || (size_t)length >= filename_size) {
667 filename[0] = '\0';
668 return -1;
669 }
670
671 struct stat existing;
672 if (lstat(filename, &existing) == 0 || errno != ENOENT) {
673 fprintf(stderr, "LWIR_CAM_PIPE:\tfailed to replace %s: %s\n", filename, strerror(errno));
674 filename[0] = '\0';
675 return -1;
676 }
677
679 filename[0] = '\0';
680 return -1;
681 }
682 char request[PATH_MAX + 2];
683 int request_size = snprintf(request, sizeof(request), "%s\n", filename);
684 if (request_size < 0 || (size_t)request_size >= sizeof(request)) {
685 filename[0] = '\0';
686 return -1;
687 }
688 if (send_request_and_wait(request, (size_t)request_size, LWIR_REQUEST_TIMEOUT_MS, "LWIR_SERVER_OK") != 0) {
689 fprintf(stderr, "LWIR_CAM_PIPE:\tcapture server failed to save %s\n", filename);
690 unlink(filename);
691 filename[0] = '\0';
692 return -1;
693 }
694
695 struct stat image_status;
696 if (stat(filename, &image_status) != 0 || !S_ISREG(image_status.st_mode)
697 || image_status.st_size == 0) {
698 fprintf(stderr, "LWIR_CAM_PIPE:\t%s did not create a valid image at %s\n",
699 capture_command, filename);
700 unlink(filename);
701 filename[0] = '\0';
702 return -1;
703 }
704 return 0;
705}
706
708{
710}
static const char * photo_directory
Definition ai_cam_pipe.c:85
char ** environ
Shared capability and lifecycle contract for USHER camera backends.
#define USHER_LWIR_CAM_PHOTO_DIR
Optional split-phase capture contract for USHER image backends.
static bool capture_running(const volatile sig_atomic_t *running)
Atomically poll a borrowed cancellation flag; NULL means no cancellation.
static bool capture_timing_valid(const struct capture_timing *timing)
Check whether timing evidence is internally consistent and recent.
static pid_t camera_pid
Definition chdk_pipe.c:137
int descriptor
Definition chdk_pipe.c:142
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
static unsigned remaining_ms(const struct transport *transport)
Compute the next USB call's timeout within the operation deadline.
Definition chdkbridge.c:156
static bool poll_result(struct camera_point_result *point)
Drain a bounded reply batch and publish only the active request's result.
static bool enabled(void)
Report explicit opt-in independently of process or model readiness.
union dc_shot_union request
static bool ready
static volatile sig_atomic_t keep_running
Definition earcam.c:181
static int start_capture_server(const char *unused, const volatile sig_atomic_t *keep_running)
Start the persistent thermal capture subprocess.
static const char * calibration_path
static pid_t capture_server_pid
int lwir_cam_pipe_shoot(char *filename, size_t filename_size, int image_number)
Request one thermal JPEG from an initialized capture server.
static int send_request_and_wait(const char *request, size_t request_size, int timeout_ms, const char *expected)
Send one newline-terminated server request and require an OK reply.
int lwir_cam_pipe_process_mock(char *filename)
Process a mock thermal image for hardware-free local testing.
int lwir_cam_pipe_warmup(void)
Open, stabilize, and close the sensor without writing an image.
static size_t status_buffer_size
#define LWIR_SERVER_START_TIMEOUT_MS
int lwir_cam_pipe_init_cancelable(const char *unused, const volatile sig_atomic_t *keep_running)
Start the server but abort promptly when USHER begins shutdown.
void lwir_cam_pipe_set_native_raw(int enabled)
Select whether successful captures keep an explicit .raw companion.
void lwir_cam_pipe_set_photo_directory(const char *directory)
Override the output directory for an isolated standalone benchmark.
double lwir_cam_pipe_capture_delay(void)
Return the delay of the last successful capture request in seconds.
static int capture_server_input
static int parse_capture_timing(const char *text, struct capture_timing *timing, bool callback)
Parse one server timing payload after its protocol prefix.
static int read_server_status(const char *expected, int timeout_ms, const volatile sig_atomic_t *keep_running)
Read server diagnostic lines until an expected terminal reply arrives.
static double capture_delay_s
static void stop_capture_server(void)
Close pipes and reap or terminate the owned capture server.
#define CHILD_STOP_GRACE_MS
struct capture_timing lwir_cam_pipe_capture_timing(void)
Return detailed callback or polling timing evidence for the last capture.
#define LWIR_REQUEST_TIMEOUT_MS
static char status_buffer[512]
static uint64_t monotonic_ms(void)
Read the capture-server watchdog clock.
void lwir_cam_pipe_deinit(void)
Stop, reap, and forget the persistent LWIR capture server.
static const volatile sig_atomic_t * running
static const char * lwir_config
int lwir_cam_pipe_set_calibration(const char *path)
Set the optional calibration file used by server-side geolocation.
static int create_cloexec_pipe(int descriptors[2])
Open a close-on-exec pipe for child protocol setup.
static int terminate_child(pid_t pid, int *status)
Stop an owned capture child, escalating only after its grace period.
static int wait_child(pid_t pid, int *status, int timeout_ms)
Wait up to a bounded time for the capture child to exit.
static int capture_server_output
int lwir_cam_pipe_init(const char *unused)
Start and qualify the persistent LWIR capture server.
void lwir_cam_pipe_configure(const struct camera_backend_host *host)
Bind the owner's long-lived shutdown flag before starting workers.
int lwir_cam_pipe_geolocate(char *filename)
Add thermal hotspot/geolocation metadata through the running server.
#define IMAGE_PROCESS_TIMEOUT_MS
#define LWIR_WARMUP_TIMEOUT_MS
static struct capture_timing capture_times
#define USHER_LWIR_CAM_COMMAND
static bool native_raw_enabled
#define CHILD_WAIT_INTERVAL_MS
int lwir_cam_pipe_set_config(const char *path)
Apply a bounded worker configuration before starting the capture server.
static size_t status_buffer_pos
static const char * capture_command
Parent-side protocol for USHER's persistent Tiny1-C LWIR capture server.
Positive opt-ins shared by the worker and its USHER adapter.
#define LWIR_ENABLE_ANALYSIS
1 builds the optional ONNX analysis of saved photos (lwir_inference).
Small path and writable-directory helpers shared by USHER backends.
static const char * usher_resolve_path(const char *path, char *buffer, size_t buffer_size)
Expand a leading home-directory shorthand without allocating memory.
Definition path_utils.h:74
#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 size_t count
Definition pose_log.c:79
const volatile sig_atomic_t * running
Borrowed shutdown flag; backend workers must stop when it clears.
Shared observation evidence with optional LWIR request/frame-delivery timing.
struct usher_control_result result
Definition usher.c:377