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
ear_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/**
19 * @file ear_cam_pipe.c
20 * @brief USHER-side audio supervision, pose association and immutable EAR snapshots.
21 * @details A persistent EARcam child produces newline-delimited acoustic measurements.
22 * A reader thread retains only the latest measurement while USHER geotags it at shots;
23 * the bounded session can be detached without copying for the backend's finalizer.
24 * Numerical fusion and JPEG rendering live in the standalone EAR core, not USHER's
25 * serial loop. Missing microphones remain nonfatal and are retried.
26 * Thread ownership: the supervisor owns child lifecycle, the reader publishes
27 * latest under ear_mutex, the serial owner handles sessions/pending poses/log
28 * enqueue, and the log worker alone accesses its FILE. The finalizer borrows
29 * detached snapshots until release; it must not touch active-session APIs.
30 */
31#include "ear_cam_pipe.h"
33#include "path_utils.h"
34
35#include <errno.h>
36#include <fcntl.h>
37#include <limits.h>
38#include <math.h>
39#include <poll.h>
40#include <pthread.h>
41#include <signal.h>
42#include <spawn.h>
43#include <stdatomic.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#include <sys/stat.h>
48#include <sys/types.h>
49#include <sys/wait.h>
50#include <time.h>
51#include <unistd.h>
52
53#ifndef USHER_EAR_CAM_COMMAND
54 #define USHER_EAR_CAM_COMMAND "./bin/earcam"
55#endif
56
57#ifndef USHER_EAR_CAM_DEVICE
58 #define USHER_EAR_CAM_DEVICE "auto" // earcam picks the first USB capture card
59#endif
60
61#ifndef USHER_EAR_CAM_LOG_DIR
62 #define USHER_EAR_CAM_LOG_DIR "earlogs"
63#endif
64
65#ifndef USHER_EAR_CAM_PHOTO_DIR
66 #define USHER_EAR_CAM_PHOTO_DIR "~/Pictures/sensoraia"
67#endif
68
69#ifndef EAR_READY_TIMEOUT_MS
70 #define EAR_READY_TIMEOUT_MS 15000
71#endif
72#ifndef EAR_RESTART_INTERVAL_MS
73 #define EAR_RESTART_INTERVAL_MS 3000U
74#endif
75#define EAR_WARNING_INTERVAL_MS 1000U
76#define EAR_SAMPLE_STALE_MS 500U
77#define EAR_LINE_MAX 512U
78#define ANGLE_BFP_SCALE 4096.0
79#define POSITION_BFP_SCALE 256.0
80#define EARTH_RADIUS_M 6378137.0
81#define DEG_TO_RAD 0.017453292519943295
82#define RAD_TO_DEG 57.29577951308232
83
84/** Storage/admission policies; two snapshots match the backend's two finalizer jobs. */
85#define EAR_SESSION_BUFFER_COUNT 2
86#define EAR_MICROPHONE_NAME_CAPACITY 256
87#define EAR_LOG_PATH_CAPACITY 512
88#define EAR_LOG_ROW_CAPACITY 512
89#define EAR_LOG_QUEUE_ROWS 128
90#define EAR_LOG_BATCH_ROWS 16
91#define EAR_SESSION_MARKER_CAPACITY 128
92#define EAR_PENDING_AUDIO_WINDOWS 16
93#define EAR_BAND_ARGUMENT_CAPACITY 32
94#define EAR_READER_CHUNK_BYTES 256
95#define EAR_READER_POLL_MS 200
96#define EAR_POSE_WAIT_MS 200
97#define EAR_SAMPLE_FUTURE_SLACK_MS 1
98/** The shutdown loop escalates QUIT -> SIGTERM -> SIGKILL; it does not block waitpid. */
99#define EAR_CHILD_REAP_ATTEMPTS 25
100#define EAR_CHILD_TERM_ATTEMPT 10
101#define EAR_CHILD_KILL_ATTEMPT 20
102#define EAR_SUPERVISOR_TICK_MS 20
103#define EAR_LOG_FILENAME_ATTEMPTS 128
104#define EAR_EVIDENCE_FILENAME_ATTEMPTS 32
105#define EAR_LOG_FILE_MODE 0644
106#define EAR_EVIDENCE_FILE_MODE 0600
107#define EAR_TM_YEAR_ORIGIN 1900
108#define EAR_JPEG_SUFFIX_LENGTH 4
109#define EAR_MS_PER_SECOND 1000U
110#define EAR_NS_PER_MS 1000000U
111#define EAR_SLEEP_NS_PER_MS 1000000L
112#define EAR_US_PER_MS 1000
113#define EAR_COORDINATE_UNITS_PER_DEG 1e7
114#define EAR_ALTITUDE_UNITS_PER_METER 1000.0
115/** Plausibility limits for producer capture windows, not clock synchronization guarantees. */
116#define EAR_AUDIO_WINDOW_LIMIT_US 1000000
117#define EAR_AUDIO_TIMING_ERROR_LIMIT_US 100000
118#define EAR_AUDIO_FUTURE_SLACK_US 1000
119#define EAR_SAMPLE_PREFIX_LENGTH 7
120#define EAR_READY_PREFIX_LENGTH 12
121#define EAR_ERROR_PREFIX_LENGTH 12
122#define EAR_STOPPED_PREFIX_LENGTH 14
123/** xorshift32 parameters are algorithm invariants; the nonzero seed is process-local. */
124#define EAR_SIM_NOISE_INITIAL_STATE 0x2545F491U
125#define EAR_SIM_XORSHIFT_LEFT_FIRST 13
126#define EAR_SIM_XORSHIFT_RIGHT 17
127#define EAR_SIM_XORSHIFT_LEFT_LAST 5
128#define EAR_SIM_NOISE_STEPS 30001U
129#define EAR_SIM_NOISE_STEPS_PER_DB 10000.0
130#define EAR_SIM_NOISE_HALF_RANGE_DB 1.5
131#define EAR_SIM_REFERENCE_DISTANCE_M 1.0
132#define EAR_SIM_DISTANCE_DB_PER_DECADE 20.0
133#define EAR_SIM_CONTRAST_DB 6.0
134#define EAR_SIM_FREQUENCY_HZ 2700.0
135
136extern char **environ;
137
138/** @brief Latest parsed window plus optional producer timing; published under ear_mutex. */
153
154static pid_t server_pid = -1;
155static int server_input = -1;
156static int server_output = -1;
157static pthread_t reader_thread;
158static bool reader_running;
159static atomic_bool reader_stop;
160static pthread_t supervisor_thread;
164
165bool ear_cam_pipe_set_settings(const char *settings)
166{
167 if (!settings || !settings[0] || supervisor_running || reader_running) return false;
168 const size_t length = strnlen(settings, sizeof(ear_settings));
169 if (length >= sizeof(ear_settings)) return false;
170 for (size_t index = 0; index <= length; ++index) ear_settings[index] = settings[index];
171 return true;
172}
173static atomic_bool supervisor_stop;
174static pthread_mutex_t ear_mutex = PTHREAD_MUTEX_INITIALIZER;
176static bool server_ready;
177static uint64_t server_error_count;
178static uint64_t server_started_ms;
179static uint64_t last_warning_ms;
180
181/**
182 * @brief Statically reserved sample buffer with a single active or detached owner.
183 * @details Count is finalized before handoff. Atomic ownership lets the worker
184 * release storage without racing serial-owner admission. Detached contents need
185 * no lock because the producer and active session must not modify them.
186 */
192static struct ear_session_snapshot session_buffers[EAR_SESSION_BUFFER_COUNT] = {{.owned = true}, {.owned = false}};
194static struct ear_sample *session = session_buffers[0].samples;
195static size_t session_count;
196static uint32_t log_session_id;
197static FILE *session_log;
200static size_t log_head, log_count;
201static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
202static pthread_cond_t log_available = PTHREAD_COND_INITIALIZER;
203static pthread_t log_thread;
205static atomic_uint_fast64_t log_dropped;
206static const char session_log_header[] =
207 "t_ms,shot,lat_deg,lon_deg,agl_m,alt_m,level_db,trend_db,contrast_db,freq_hz,alarm,clip,"
208 "pose_aligned,pose_uncertainty_m,window_earliest_us,window_latest_us,sequence,request_lat_deg,request_lon_deg,session_id,detector_kind,classification_score,classification_class\n";
209static struct {
212 uint64_t queued_ms;
215static uint64_t last_window_end;
216static bool (*pose_lookup)(struct capture_observation *, uint64_t);
217static void flush_pending_audio(bool force);
218
219void ear_cam_pipe_set_pose_lookup(bool (*lookup)(struct capture_observation *, uint64_t))
220{
221 pose_lookup = lookup;
222}
223
224bool ear_cam_pipe_set_device(const char *device)
225{
226 if (!device || supervisor_running || reader_running) return false;
227 const size_t length = strnlen(device, sizeof(microphone_device));
228 if (!length || length >= sizeof(microphone_device)) return false;
229 for (size_t index = 0; index <= length; ++index) microphone_device[index] = device[index];
230 return true;
231}
232
233static bool simulated;
234static double simulated_lat_deg;
235static double simulated_lon_deg;
238
239/** @brief Select deterministic virtual acoustic measurements for simulation.
240 * @details Must precede initialization so no microphone child is launched. */
241void ear_cam_pipe_set_simulated_source(double lat_deg, double lon_deg, double level_db_at_1m)
242{
243 simulated = true;
244 simulated_lat_deg = lat_deg;
245 simulated_lon_deg = lon_deg;
246 simulated_level_db_at_1m = level_db_at_1m;
247}
248
251static bool band_set;
252
253/** @brief Set the detector band forwarded to a subsequently spawned EARcam child. */
254void ear_cam_pipe_set_band(double low_cut_hz, double high_cut_hz)
255{
256 if (supervisor_running || reader_running) return;
257 band_set = isfinite(low_cut_hz) && isfinite(high_cut_hz) && low_cut_hz > 0.0 && high_cut_hz > low_cut_hz;
258 if (band_set) {
259 snprintf(band_low_arg, sizeof(band_low_arg), "%.17g", low_cut_hz);
260 snprintf(band_high_arg, sizeof(band_high_arg), "%.17g", high_cut_hz);
261 }
262}
263
264// Deterministic +/-1.5 dB microphone noise (xorshift), independent of libc rand().
265/** @brief Produce reproducible bounded simulation noise without shared libc PRNG state. */
266static double simulated_noise_db(void)
267{
268 uint32_t x = simulated_noise_state;
270 x ^= x >> EAR_SIM_XORSHIFT_RIGHT;
274}
275
276/**
277 * @brief Model a virtual point source using free-field inverse-distance attenuation.
278 * @details This fixture includes height and bounded noise, not terrain,
279 * directivity, aircraft noise, microphone calibration or physical alarm validation.
280 */
281static struct latest_measurement simulated_measurement(const union dc_shot_union *shot, uint64_t now)
282{
283 double lat = shot->data.lat / EAR_COORDINATE_UNITS_PER_DEG;
284 double lon = shot->data.lon / EAR_COORDINATE_UNITS_PER_DEG;
285 double agl = shot->data.groundalt / POSITION_BFP_SCALE;
286 double north = (lat - simulated_lat_deg) * DEG_TO_RAD * EARTH_RADIUS_M;
288 double distance = sqrt(north * north + east * east + agl * agl);
289 if (distance < EAR_SIM_REFERENCE_DISTANCE_M) {
291 }
292 struct latest_measurement measurement = {0};
293 measurement.timestamp_ms = now;
295 distance) + simulated_noise_db();
296 measurement.contrast_db = EAR_SIM_CONTRAST_DB;
297 measurement.trend_db = 0.0;
298 measurement.frequency_hz = EAR_SIM_FREQUENCY_HZ;
299 measurement.alarm = true;
300 measurement.clipped = false;
301 measurement.valid = true;
302 return measurement;
303}
304
305/** @brief Return monotonic milliseconds for server freshness and retry decisions. */
306static uint64_t monotonic_ms(void)
307{
308 struct timespec now;
309 clock_gettime(CLOCK_MONOTONIC, &now);
310 return (uint64_t)now.tv_sec * EAR_MS_PER_SECOND + (uint64_t)now.tv_nsec / EAR_NS_PER_MS;
311}
312
313/** @brief Sleep through signal interruption for bounded lifecycle polling. */
314static void sleep_ms(unsigned int milliseconds)
315{
316 struct timespec interval = {
319 };
320 while (nanosleep(&interval, &interval) != 0 && errno == EINTR) {
321 continue;
322 }
323}
324
325/** @brief Parse one named numeric field from an EARcam server line.
326 * @return 0 on one finite complete value, otherwise -1.
327 * @details Field-boundary checks prevent a short key from matching a suffix of another key. */
328static int parse_field(const char *line, const char *key, double *value)
329{
330 if (!line || !key || !*key || !value) return -1;
331 const char *position = line;
332 size_t key_length = strlen(key);
333 bool found = false;
334 double result = 0;
335 while ((position = strstr(position, key)) != NULL) {
336 if ((position == line || position[-1] == ' ') && position[key_length] == '=') {
337 if (found) return -1;
338 char *end = NULL;
339 errno = 0;
340 double parsed = strtod(position + key_length + 1, &end);
341 if (errno || end == position + key_length + 1 || !isfinite(parsed)
342 || (*end && *end != ' ' && *end != '\r' && *end != '\n')) {
343 return -1;
344 }
345 result = parsed;
346 found = true;
347 }
348 position += key_length;
349 }
350 if (found) *value = result;
351 return found ? 0 : -1;
352}
353
354/** @brief Parse exact unsigned timing/sequence evidence without rounding through double. */
355static bool parse_unsigned_field(const char *line, const char *key, uint64_t *value)
356{
357 if (!line || !key || !*key || !value) return false;
358 const size_t length = strlen(key);
359 const char *position = line;
360 bool found = false;
361 uint64_t result = 0;
362 while ((position = strstr(position, key)) != NULL) {
363 if ((position == line || position[-1] == ' ') && position[length] == '=') {
364 if (found) return false;
365 position += length + 1;
366 if (*position < '0' || *position > '9') return false;
367 char *end = NULL;
368 errno = 0;
369 const unsigned long long parsed = strtoull(position, &end, 10);
370 if (errno || end == position || (*end && *end != ' ' && *end != '\r' && *end != '\n')) return false;
371 result = parsed;
372 found = true;
373 }
374 position += length;
375 }
376 if (found) *value = result;
377 return found;
378}
379
380/** @brief Interpret one complete server output line and atomically update shared state.
381 * @details Malformed samples are ignored rather than poisoning the latest valid reading. */
382static void handle_server_line(const char *line)
383{
384 if (!line) return;
385 const bool classifier = !strncmp(line, "CLASS ", 6);
386 if (classifier || strncmp(line, "SAMPLE ", EAR_SAMPLE_PREFIX_LENGTH) == 0) {
387 struct latest_measurement measurement = {0};
388 uint64_t timestamp = 0;
389 double alarm = 0.0;
390 double clipped = 0.0;
391 if (!parse_unsigned_field(line, "t", &timestamp)
392 || parse_field(line, "level", &measurement.level_db) != 0
393 || (!classifier && parse_field(line, "freq", &measurement.frequency_hz) != 0)
394 || (!classifier && parse_field(line, "contrast", &measurement.contrast_db) != 0)
395 || (!classifier && parse_field(line, "trend", &measurement.trend_db) != 0)
396 || parse_field(line, "alarm", &alarm) != 0
397 || parse_field(line, "clip", &clipped) != 0) {
398 return;
399 }
400 if (classifier) {
401 uint64_t category;
402 if (parse_field(line, "score", &measurement.classifier_score) ||
403 measurement.classifier_score < 0 || measurement.classifier_score > 1 ||
404 !parse_unsigned_field(line, "class", &category) || category > 4095) return;
405 measurement.classifier = true;
406 measurement.classifier_class = (unsigned)category;
407 }
408 if (timestamp > UINT64_MAX / EAR_US_PER_MS - 1 ||
409 (alarm != 0 && alarm != 1) || (clipped != 0 && clipped != 1)) return;
410 measurement.timestamp_ms = timestamp;
411 if (strstr(line, " begin_us=")) {
412 uint64_t begin_us, end_us, error_us, sequence;
413 if (!parse_unsigned_field(line, "begin_us", &begin_us) || !parse_unsigned_field(line, "end_us", &end_us)
414 || !parse_unsigned_field(line, "error_us", &error_us) || !parse_unsigned_field(line, "sequence", &sequence)) return;
415 if (begin_us || end_us) {
416 /* Widen producer bounds by its error only after plausibility/overflow
417 * checks. Legacy/all-zero timing stays explicitly unaligned rather
418 * than being treated as a precise capture timestamp. */
419 if (begin_us <= error_us || end_us < begin_us || end_us - begin_us > EAR_AUDIO_WINDOW_LIMIT_US
421 || end_us > measurement.timestamp_ms * EAR_US_PER_MS + EAR_AUDIO_FUTURE_SLACK_US
422 || end_us > UINT64_MAX - error_us || !sequence) return;
423 measurement.observation = (struct capture_observation) {
424 .earliest_us = begin_us - error_us, .latest_us = end_us + error_us,
425 .sequence = sequence, .kind = CAPTURE_TIME_AUDIO_WINDOW
426 };
427 }
428 }
429 measurement.alarm = alarm != 0.0;
430 measurement.clipped = clipped != 0.0;
431 measurement.valid = true;
432 pthread_mutex_lock(&ear_mutex);
434 pthread_mutex_unlock(&ear_mutex);
435 return;
436 }
437 if (strncmp(line, "EARCAM_READY", EAR_READY_PREFIX_LENGTH) == 0) {
438 pthread_mutex_lock(&ear_mutex);
439 server_ready = true;
440 pthread_mutex_unlock(&ear_mutex);
441 printf("EAR_CAM_PIPE:\t%s\n", line);
442 return;
443 }
444 if (strncmp(line, "EARCAM_ERROR", EAR_ERROR_PREFIX_LENGTH) == 0) {
445 pthread_mutex_lock(&ear_mutex);
447 pthread_mutex_unlock(&ear_mutex);
448 fprintf(stderr, "EAR_CAM_PIPE:\t%s\n", line);
449 return;
450 }
451 if (strncmp(line, "EARCAM_STOPPED", EAR_STOPPED_PREFIX_LENGTH) == 0) {
452 printf("EAR_CAM_PIPE:\t%s\n", line);
453 }
454}
455
456/** @brief Read and frame EARcam output in a dedicated thread.
457 * @details Chunked reads avoid per-byte syscalls; only the latest measurement is retained
458 * because USHER correlates a shot to current acoustic evidence, not a delayed backlog. */
459static void *reader_main(void *unused)
460{
461 (void)unused;
462 char line[EAR_LINE_MAX];
463 size_t line_size = 0;
464 bool discarding_line = false;
465
466 while (!reader_stop && server_output >= 0) {
467 struct pollfd descriptor = {.fd = server_output, .events = POLLIN, .revents = 0};
469 if (poll_result < 0) {
470 if (errno == EINTR) {
471 continue;
472 }
473 break;
474 }
475 if (poll_result == 0) {
476 continue;
477 }
478 char chunk[EAR_READER_CHUNK_BYTES];
479 ssize_t count = read(server_output, chunk, sizeof(chunk));
480 if (count == 0) {
481 break;
482 }
483 if (count < 0) {
484 if (errno == EINTR || errno == EAGAIN) {
485 continue;
486 }
487 break;
488 }
489 for (ssize_t index = 0; index < count; index++) {
490 if (chunk[index] == '\n') {
491 if (!discarding_line) {
492 line[line_size] = '\0';
493 handle_server_line(line);
494 }
495 line_size = 0;
496 discarding_line = false;
497 } else if (!discarding_line && line_size + 1 < sizeof(line) &&
498 (((unsigned char)chunk[index] >= 32 && (unsigned char)chunk[index] < 127) || chunk[index] == '\r')) {
499 line[line_size++] = chunk[index];
500 } else {
501 line_size = 0;
502 discarding_line = true;
503 }
504 }
505 }
506 pthread_mutex_lock(&ear_mutex);
507 server_ready = false;
508 latest.valid = false;
509 pthread_mutex_unlock(&ear_mutex);
510 return NULL;
511}
512
513/** @brief Request child shutdown, join its reader, and reap the owned process.
514 * @details Joining precedes descriptor teardown so the reader cannot race reused state. */
515static void stop_server(void)
516{
517 reader_stop = 1;
518 if (server_input >= 0) {
519 static const char quit[] = "QUIT\n";
520 ssize_t written = write(server_input, quit, sizeof(quit) - 1);
521 (void)written;
523 server_input = -1;
524 }
525 if (reader_running) {
526 pthread_join(reader_thread, NULL);
527 reader_running = false;
528 }
529 if (server_output >= 0) {
531 server_output = -1;
532 }
533 if (server_pid > 0) {
534 int status;
535 pid_t wait_result;
536 for (int attempt = 0; attempt < EAR_CHILD_REAP_ATTEMPTS; attempt++) {
537 wait_result = waitpid(server_pid, &status, WNOHANG);
538 if (wait_result == server_pid || (wait_result < 0 && errno == ECHILD)) {
539 break;
540 }
541 if (attempt == EAR_CHILD_TERM_ATTEMPT) kill(server_pid, SIGTERM);
542 if (attempt == EAR_CHILD_KILL_ATTEMPT) kill(server_pid, SIGKILL);
544 }
545 if (wait_result == server_pid || (wait_result < 0 && errno == ECHILD)) {
546 server_pid = -1;
547 } else {
548 fprintf(stderr, "EAR_CAM_PIPE:\tchild %ld not reaped; replacement deferred\n", (long)server_pid);
549 }
550 }
551 pthread_mutex_lock(&ear_mutex);
552 server_ready = false;
553 latest.valid = false;
554 pthread_mutex_unlock(&ear_mutex);
555}
556
557/** @brief Create the CSV audit log lazily on the first accepted acoustic sample. */
558static int open_session_log(void)
559{
560 char resolved_log[PATH_MAX];
561 const char *log_dir = usher_resolve_path(USHER_EAR_CAM_LOG_DIR, resolved_log, sizeof(resolved_log));
562
563 if (usher_ensure_directory(log_dir) != 0) {
564 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to create %s: %s\n",
565 log_dir, strerror(errno));
566 return -1;
567 }
568 time_t now = time(NULL);
569 struct tm stamp;
570 localtime_r(&now, &stamp);
571 int descriptor = -1;
572 for (unsigned attempt = 0; attempt < EAR_LOG_FILENAME_ATTEMPTS; ++attempt) {
573 int length = snprintf(session_log_path, sizeof(session_log_path),
574 "%s/ear_%04d%02d%02d_%02d%02d%02d_%03u.csv", log_dir,
575 stamp.tm_year + EAR_TM_YEAR_ORIGIN, stamp.tm_mon + 1, stamp.tm_mday,
576 stamp.tm_hour, stamp.tm_min, stamp.tm_sec, attempt);
577 if (length < 0 || (size_t)length >= sizeof(session_log_path)) return -1;
578 descriptor = open(session_log_path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, EAR_LOG_FILE_MODE);
579 if (descriptor >= 0 || errno != EEXIST) break;
580 }
581 session_log = descriptor >= 0 ? fdopen(descriptor, "w") : NULL;
582 if (descriptor >= 0 && !session_log) close(descriptor);
583 if (session_log == NULL) {
584 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to open %s: %s\n", session_log_path, strerror(errno));
585 return -1;
586 }
588 fflush(session_log);
589 return 0;
590}
591
592/**
593 * @brief Drain bounded row batches; this worker alone opens/writes/flushes/closes the log.
594 * @details Release log_mutex before filesystem I/O. A latched write failure counts
595 * lost rows without repeatedly blocking capture on an already failed destination.
596 */
597static void *write_session_log(void *unused)
598{
599 (void)unused;
600 bool failed = false;
601 for (;;) {
603 pthread_mutex_lock(&log_mutex);
604 while (!log_count && !log_stopping) pthread_cond_wait(&log_available, &log_mutex);
605 if (!log_count && log_stopping) {
606 pthread_mutex_unlock(&log_mutex);
607 break;
608 }
610 for (size_t row = 0; row < count; ++row) {
611 for (size_t index = 0; index < sizeof(batch[row]); ++index) batch[row][index] = log_queue[log_head][index];
612 log_head = (log_head + 1) % (sizeof(log_queue) / sizeof(log_queue[0]));
613 }
614 log_count -= count;
615 pthread_mutex_unlock(&log_mutex);
616 if (!failed && !session_log && open_session_log() != 0) failed = true;
617 if (!failed) {
618 for (size_t row = 0; row < count; ++row) if (fputs(batch[row], session_log) == EOF) failed = true;
619 if (fflush(session_log) != 0) failed = true;
620 }
621 if (failed) atomic_fetch_add(&log_dropped, count);
622 }
623 if (session_log && fclose(session_log) != 0) atomic_fetch_add(&log_dropped, 1);
624 session_log = NULL;
625 return NULL;
626}
627
628/**
629 * @brief Best-effort serial-owner enqueue with copied rows and no filesystem wait.
630 * @details A busy/full queue drops an audit row rather than delaying UART/audio;
631 * snapshot CSV is written separately from immutable samples at stop.
632 */
633static void queue_session_log(const char *line)
634{
635 if (!log_running) {
636 log_stopping = false;
637 log_head = log_count = 0;
638 atomic_store(&log_dropped, 0);
639 if (pthread_create(&log_thread, NULL, write_session_log, NULL) != 0) {
640 atomic_fetch_add(&log_dropped, 1);
641 return;
642 }
643 log_running = true;
644 }
645 if (pthread_mutex_trylock(&log_mutex) != 0) {
646 atomic_fetch_add(&log_dropped, 1);
647 return;
648 }
649 const size_t capacity = sizeof(log_queue) / sizeof(log_queue[0]);
650 const size_t length = strnlen(line, sizeof(log_queue[0]));
651 if (log_count == capacity || length >= sizeof(log_queue[0])) atomic_fetch_add(&log_dropped, 1);
652 else {
653 const size_t slot = (log_head + log_count++) % capacity;
654 for (size_t index = 0; index <= length; ++index) log_queue[slot][index] = line[index];
655 pthread_cond_signal(&log_available);
656 }
657 pthread_mutex_unlock(&log_mutex);
658}
659
660/** @brief Join the log writer after queued rows drain; not a hard filesystem deadline. */
661static void close_session_log(void)
662{
663 if (!log_running) return;
664 pthread_mutex_lock(&log_mutex);
665 log_stopping = true;
666 pthread_cond_signal(&log_available);
667 pthread_mutex_unlock(&log_mutex);
668 pthread_join(log_thread, NULL);
669 log_running = false;
670 if (atomic_load(&log_dropped)) fprintf(stderr, "EAR_CAM_PIPE:\taudio log dropped/failed rows: %llu\n",
671 (unsigned long long)atomic_load(&log_dropped));
672}
673
674/**
675 * @brief Prevent the audio child from inheriting unrelated USHER descriptors.
676 * @details Only intended stdin/stdout pipes survive setup; leaked UART/SODA FDs
677 * could keep channels alive after their real owners close them. Supervisor-only.
678 */
679static int add_inherited_descriptor_closes(posix_spawn_file_actions_t *actions,
680 const int command_pipe[2],
681 const int response_pipe[2])
682{
683 long descriptor_limit = sysconf(_SC_OPEN_MAX);
684 if (descriptor_limit < 0) {
685 return errno != 0 ? errno : EINVAL;
686 }
687 if (descriptor_limit > INT_MAX) {
688 descriptor_limit = INT_MAX;
689 }
690 for (int descriptor = STDERR_FILENO + 1; descriptor < descriptor_limit; ++descriptor) {
691 if (descriptor == command_pipe[0] || descriptor == command_pipe[1]
692 || descriptor == response_pipe[0] || descriptor == response_pipe[1]) {
693 continue;
694 }
695 if (fcntl(descriptor, F_GETFD) < 0) {
696 if (errno == EBADF) {
697 continue;
698 }
699 return errno;
700 }
701 int result = posix_spawn_file_actions_addclose(actions, descriptor);
702 if (result != 0) {
703 return result;
704 }
705 }
706 return 0;
707}
708
709// Spawn `earcam --server` with a reader thread; returns without waiting for EARCAM_READY.
710/** @brief Spawn `earcam --server` and its asynchronous line reader.
711 * @return 0 after ownership is established, otherwise -1 with all partial resources closed.
712 * @details Readiness is observed asynchronously so process spawn cannot block USHER's
713 * startup indefinitely on a missing microphone. */
714static int start_server(void)
715{
716 if (server_pid > 0) return -1;
717 int command_pipe[2];
718 int response_pipe[2];
719 if (pipe(command_pipe) != 0) {
720 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to create pipes: %s\n", strerror(errno));
721 return -1;
722 }
723 if (pipe(response_pipe) != 0) {
724 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to create pipes: %s\n", strerror(errno));
725 close(command_pipe[0]);
726 close(command_pipe[1]);
727 return -1;
728 }
729 int *endpoints[] = {&command_pipe[0], &command_pipe[1], &response_pipe[0], &response_pipe[1]};
730 for (size_t index = 0; index < sizeof(endpoints) / sizeof(endpoints[0]); ++index) {
731 int descriptor = *endpoints[index];
732 if (descriptor <= STDERR_FILENO) {
733 descriptor = fcntl(descriptor, F_DUPFD_CLOEXEC, STDERR_FILENO + 1);
734 if (descriptor >= 0) { close(*endpoints[index]); *endpoints[index] = descriptor; }
735 }
736 if (descriptor < 0 || fcntl(descriptor, F_SETFD, FD_CLOEXEC) != 0) {
737 const int saved_errno = errno;
738 close(command_pipe[0]);
739 close(command_pipe[1]);
740 close(response_pipe[0]);
741 close(response_pipe[1]);
742 errno = saved_errno;
743 return -1;
744 }
745 }
746 int flags = fcntl(command_pipe[1], F_GETFL);
747 if (flags < 0 || fcntl(command_pipe[1], F_SETFL, flags | O_NONBLOCK) != 0) {
748 close(command_pipe[0]);
749 close(command_pipe[1]);
750 close(response_pipe[0]);
751 close(response_pipe[1]);
752 return -1;
753 }
754
755 posix_spawn_file_actions_t actions;
756 if (posix_spawn_file_actions_init(&actions) != 0) {
757 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to configure earcam server\n");
758 close(command_pipe[0]);
759 close(command_pipe[1]);
760 close(response_pipe[0]);
761 close(response_pipe[1]);
762 return -1;
763 }
764 if (posix_spawn_file_actions_adddup2(&actions, command_pipe[0], STDIN_FILENO) != 0
765 || posix_spawn_file_actions_adddup2(&actions, response_pipe[1], STDOUT_FILENO) != 0
766 || add_inherited_descriptor_closes(&actions, command_pipe, response_pipe) != 0
767 || posix_spawn_file_actions_addclose(&actions, command_pipe[0]) != 0
768 || posix_spawn_file_actions_addclose(&actions, command_pipe[1]) != 0
769 || posix_spawn_file_actions_addclose(&actions, response_pipe[0]) != 0
770 || posix_spawn_file_actions_addclose(&actions, response_pipe[1]) != 0) {
771 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to configure earcam server\n");
772 posix_spawn_file_actions_destroy(&actions);
773 close(command_pipe[0]);
774 close(command_pipe[1]);
775 close(response_pipe[0]);
776 close(response_pipe[1]);
777 return -1;
778 }
779
780 char *arguments[13];
781 size_t argument_count = 0;
782 arguments[argument_count++] = (char *)USHER_EAR_CAM_COMMAND;
783 arguments[argument_count++] = (char *)"--server";
784 arguments[argument_count++] = (char *)"--device";
785 arguments[argument_count++] = microphone_device;
786 if (ear_settings[0]) {
787 arguments[argument_count++] = (char *)"--settings";
788 arguments[argument_count++] = ear_settings;
789 }
790 if (band_set) {
791 arguments[argument_count++] = (char *)"--low-cut";
792 arguments[argument_count++] = band_low_arg;
793 arguments[argument_count++] = (char *)"--high-cut";
794 arguments[argument_count++] = band_high_arg;
795 }
796 arguments[argument_count] = NULL;
797 int spawn_result = posix_spawn(&server_pid, USHER_EAR_CAM_COMMAND, &actions, NULL,
798 arguments, environ);
799 posix_spawn_file_actions_destroy(&actions);
800 close(command_pipe[0]);
801 close(response_pipe[1]);
802 if (spawn_result != 0) {
803 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to start %s: %s\n",
804 USHER_EAR_CAM_COMMAND, strerror(spawn_result));
805 close(command_pipe[1]);
806 close(response_pipe[0]);
807 server_pid = -1;
808 return -1;
809 }
810 server_input = command_pipe[1];
811 server_output = response_pipe[0];
812 reader_stop = 0;
813 pthread_mutex_lock(&ear_mutex);
814 server_ready = false;
816 latest.valid = false;
817 pthread_mutex_unlock(&ear_mutex);
819 if (pthread_create(&reader_thread, NULL, reader_main, NULL) != 0) {
820 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to start reader thread\n");
821 stop_server();
822 return -1;
823 }
824 reader_running = true;
825 return 0;
826}
827
828/**
829 * @brief Retry missing/disconnected capture independently of optical operation.
830 * @details Error, lost readiness or startup timeout triggers owned teardown
831 * before another spawn. The retry delay checks shutdown in small polling ticks.
832 */
833static void *supervise_server(void *unused)
834{
835 (void)unused;
836 while (!supervisor_stop) {
837 if (start_server() == 0) {
838 bool was_ready = false;
839 for (;;) {
840 pthread_mutex_lock(&ear_mutex);
841 bool ready = server_ready;
842 uint64_t errors = server_error_count;
843 pthread_mutex_unlock(&ear_mutex);
844 if (supervisor_stop || errors > 0
845 || (was_ready && !ready)
847 was_ready = was_ready || ready;
849 }
850 }
851 stop_server();
852 uint64_t retry_at = monotonic_ms() + EAR_RESTART_INTERVAL_MS;
854 }
855 stop_server();
856 return NULL;
857}
858
859/** @brief Rate-limit repeated unavailable/stale microphone diagnostics. */
860static bool warning_due(uint64_t now)
861{
863 return false;
864 }
865 last_warning_ms = now;
866 return true;
867}
868
869/** @brief Reset session storage and start or configure the acoustic backend.
870 * @return -1 only for unrecoverable setup errors; missing hardware stays retryable. */
871int ear_cam_pipe_init(const char *unused)
872{
873 (void)unused;
874 if (supervisor_running) return 0;
875
876 session_count = 0;
878 last_window_end = 0;
879
880 if (simulated) {
881 pthread_mutex_lock(&ear_mutex);
882 server_ready = true;
883 latest.valid = false;
884 pthread_mutex_unlock(&ear_mutex);
885 printf("EAR_CAM_PIPE:\tSIMULATED loudspeaker at %.7f %.7f, %.1f dB at 1 m (no microphone)\n",
887 return 0;
888 }
889
890 if (access(USHER_EAR_CAM_COMMAND, X_OK) != 0) {
891 fprintf(stderr, "EAR_CAM_PIPE:\tcapture command is not executable: %s: %s\n",
892 USHER_EAR_CAM_COMMAND, strerror(errno));
893 return -1;
894 }
895 supervisor_stop = false;
896 int result = pthread_create(&supervisor_thread, NULL, supervise_server, NULL);
897 if (result != 0) {
898 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to start supervisor: %s\n", strerror(result));
899 return -1;
900 }
901 supervisor_running = true;
902 printf("EAR_CAM_PIPE:\tcapture command: %s\n", USHER_EAR_CAM_COMMAND);
903 printf("EAR_CAM_PIPE:\tmicrophone: %s\n", microphone_device);
904 printf("EAR_CAM_PIPE:\tasynchronous microphone supervisor started\n");
905 return 0;
906}
907
908/** @brief Stop the child and clear all bounded session state. */
910{
911 if (supervisor_running) {
912 supervisor_stop = true;
913 pthread_join(supervisor_thread, NULL);
914 supervisor_running = false;
915 }
916 pthread_mutex_lock(&ear_mutex);
917 server_ready = false;
918 pthread_mutex_unlock(&ear_mutex);
921 session_count = 0;
922}
923
924/** @brief Report whether an actual or simulated measurement source is ready. */
926{
927 pthread_mutex_lock(&ear_mutex);
928 bool ready = server_ready;
929 pthread_mutex_unlock(&ear_mutex);
930 return ready;
931}
932
933/** @brief Format one evidence row with both chosen pose and original request provenance. */
934static int format_session_row(const struct ear_sample *sample, uint32_t session_id, char *line, size_t size)
935{
936 return snprintf(line, size,
937 "%llu,%d,%.7f,%.7f,%.2f,%.2f,%.2f,%.2f,%.2f,%.0f,%d,%d,%d,%.3f,%llu,%llu,%llu,%.7f,%.7f,%u,%s,%.6f,%u\n",
938 (unsigned long long)sample->timestamp_ms, sample->shot_nr, sample->lat_deg,
939 sample->lon_deg, sample->agl_m, sample->alt_m, sample->level_db,
940 sample->trend_db, sample->contrast_db, sample->frequency_hz,
941 sample->alarm ? 1 : 0, sample->clipped ? 1 : 0, sample->pose_aligned ? 1 : 0, sample->pose_uncertainty_m,
942 (unsigned long long)sample->window_earliest_us, (unsigned long long)sample->window_latest_us,
943 (unsigned long long)sample->window_sequence, sample->request_lat / EAR_COORDINATE_UNITS_PER_DEG,
945 session_id, sample->classifier ? "onnx_pcm" : "tone", sample->classifier_score, sample->classifier_class);
946}
947
948/**
949 * @brief Append on the serial owner using aligned pose when available, labelled request pose otherwise.
950 * @details At capacity keep the newest half of active evidence. This cannot
951 * overwrite a detached snapshot; admission must acquire its own buffer first.
952 */
954{
955 const union dc_shot_union *shot = measurement->observation.pose_valid ? &measurement->observation.pose : request;
957 // Keep the newest data: drop the oldest half to stay bounded on a small board.
958 size_t keep = EAR_MAX_SAMPLES / 2;
959 for (size_t index = 0; index < keep; index++) {
960 session[index] = session[index + keep];
961 }
962 session_count = keep;
963 }
964 struct ear_sample *sample = &session[session_count++];
965 sample->timestamp_ms = measurement->timestamp_ms;
966 sample->shot_nr = request->data.nr;
967 sample->lat_deg = shot->data.lat / EAR_COORDINATE_UNITS_PER_DEG;
968 sample->lon_deg = shot->data.lon / EAR_COORDINATE_UNITS_PER_DEG;
969 sample->agl_m = shot->data.groundalt / POSITION_BFP_SCALE;
970 sample->alt_m = shot->data.alt / EAR_ALTITUDE_UNITS_PER_METER;
971 sample->level_db = measurement->level_db;
972 sample->trend_db = measurement->trend_db;
973 sample->contrast_db = measurement->contrast_db;
974 sample->frequency_hz = measurement->frequency_hz;
975 sample->classifier = measurement->classifier;
976 sample->classifier_score = measurement->classifier_score;
977 sample->classifier_class = measurement->classifier_class;
978 sample->alarm = measurement->alarm;
979 sample->clipped = measurement->clipped;
980 sample->pose_aligned = measurement->observation.pose_valid;
981 sample->pose_uncertainty_m = measurement->observation.pose_valid ? measurement->observation.pose_uncertainty_m : -1;
982 sample->window_earliest_us = measurement->observation.earliest_us;
983 sample->window_latest_us = measurement->observation.latest_us;
984 sample->window_sequence = measurement->observation.sequence;
985 sample->request_lat = request->data.lat;
986 sample->request_lon = request->data.lon;
987 char line[EAR_LOG_ROW_CAPACITY];
988 const int length = format_session_row(sample, log_session_id, line, sizeof(line));
989 if (length > 0 && (size_t)length < sizeof(line)) queue_session_log(line);
990 else atomic_fetch_add(&log_dropped, 1);
991}
992
993/**
994 * @brief Retry pose lookup without waiting; bound unresolved evidence by count and age.
995 * @details FIFO ordering keeps window provenance stable. Stop/full-queue forces
996 * request-pose fallback rather than waiting for poses or losing admitted audio.
997 */
998static void flush_pending_audio(bool force)
999{
1000 const uint64_t now = monotonic_ms();
1001 while (pending_count) {
1002 struct capture_observation *observation = &pending_audio[pending_head].measurement.observation;
1003 const bool aligned = pose_lookup && pose_lookup(observation, 0);
1004 if (!aligned && !force && now >= pending_audio[pending_head].queued_ms
1007 pending_head = (pending_head + 1) % (sizeof(pending_audio) / sizeof(pending_audio[0]));
1008 --pending_count;
1009 }
1010}
1011
1013{
1014 if (!session) return;
1015 flush_pending_audio(false);
1016}
1017
1019{
1020 if (!shot || !session) return -1;
1021 flush_pending_audio(false);
1022 const uint64_t now = monotonic_ms();
1023 pthread_mutex_lock(&ear_mutex);
1025 const bool ready = server_ready;
1026 pthread_mutex_unlock(&ear_mutex);
1027 const uint64_t window_end_ms = measurement.observation.latest_us / EAR_US_PER_MS;
1028 if (!ready || !measurement.valid || measurement.timestamp_ms > now + EAR_SAMPLE_FUTURE_SLACK_MS
1029 || (now > measurement.timestamp_ms && now - measurement.timestamp_ms > EAR_SAMPLE_STALE_MS)
1030 || (capture_observation_valid(&measurement.observation) && now > window_end_ms &&
1031 now - window_end_ms > EAR_SAMPLE_STALE_MS)) {
1032 if (warning_due(now)) fprintf(stderr, "EAR_CAM_PIPE-%d:\tno fresh microphone measurement available\n", shot->data.nr);
1033 return -1;
1034 }
1036 if (measurement.observation.latest_us <= last_window_end) return -1;
1037 last_window_end = measurement.observation.latest_us;
1038 const size_t capacity = sizeof(pending_audio) / sizeof(pending_audio[0]);
1040 const size_t slot = (pending_head + pending_count++) % capacity;
1041 pending_audio[slot].measurement = measurement;
1042 pending_audio[slot].request = *shot;
1043 pending_audio[slot].queued_ms = now;
1044 flush_pending_audio(false);
1046 return 0;
1047}
1048
1050{
1051 return session_count > 0 ? session[session_count - 1].shot_nr : 0;
1052}
1053
1054bool ear_cam_pipe_begin_session(uint32_t session_id)
1055{
1056 if (!active_session) {
1057 for (size_t slot = 0; slot < EAR_SESSION_BUFFER_COUNT; ++slot) {
1058 bool available = false;
1059 if (atomic_compare_exchange_strong(&session_buffers[slot].owned, &available, true)) {
1061 break;
1062 }
1063 }
1064 if (!active_session) return false;
1065 }
1066 flush_pending_audio(true);
1067 session = active_session->samples;
1068 session_count = 0;
1070 last_window_end = 0;
1071 log_session_id = session_id;
1072 char line[EAR_SESSION_MARKER_CAPACITY];
1073 snprintf(line, sizeof(line), "# start session_id=%u\n", session_id);
1074 queue_session_log(line);
1075 return true;
1076}
1077
1079{
1080 if (!active_session) return NULL;
1081 flush_pending_audio(true);
1082 struct ear_session_snapshot *snapshot = active_session;
1083 snapshot->count = session_count;
1084 char line[EAR_SESSION_MARKER_CAPACITY];
1085 snprintf(line, sizeof(line), "# stop session_id=%u samples=%zu\n", log_session_id, session_count);
1086 queue_session_log(line);
1087 active_session = NULL;
1088 session = NULL;
1089 session_count = 0;
1091 last_window_end = 0;
1092 return snapshot;
1093}
1094
1096{
1097 if (!snapshot || !result) return -1;
1098 *result = (struct ear_loudest_spot) {0};
1099 return calculated_loudestspot(snapshot->samples, snapshot->count, result);
1100}
1101
1103{
1104 return snapshot && snapshot->count ? snapshot->samples[snapshot->count - 1].shot_nr : 0;
1105}
1106
1108{
1109 if (snapshot) atomic_store(&snapshot->owned, false);
1110}
1111
1112/**
1113 * @brief Write evidence from borrowed active or immutable snapshot samples.
1114 * @details Nonzero session IDs reserve JPEG and CSV names together with O_EXCL;
1115 * old evidence is never silently overwritten. Snapshot CSV failure and optional
1116 * field/.geo failure are reported separately from decorated JPEG success.
1117 */
1118static int render_session(const struct ear_sample *samples, size_t count, int32_t number, uint32_t session_id,
1119 const struct ear_loudest_spot *result, char *filename, size_t filename_size,
1120 bool simulated)
1121{
1122 if (filename == NULL || filename_size == 0) {
1123 return -1;
1124 }
1125 filename[0] = '\0';
1126 if (count == 0) {
1127 return -1;
1128 }
1129
1130 char resolved_photo[PATH_MAX];
1131 const char *photo_dir = usher_resolve_path(USHER_EAR_CAM_PHOTO_DIR, resolved_photo, sizeof(resolved_photo));
1132
1133 if (usher_ensure_directory(photo_dir) != 0) {
1134 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to create %s: %s\n", photo_dir, strerror(errno));
1135 return -1;
1136 }
1137 const char *prefix = simulated ? "me" : "e";
1138 int length = snprintf(filename, filename_size, "%s/%s%06d.jpg", photo_dir,
1139 prefix, number);
1140 if (session_id) {
1141 bool reserved = false;
1142 int csv_descriptor = -1;
1143 char csv_path[PATH_MAX];
1144 for (unsigned attempt = 0; attempt < EAR_EVIDENCE_FILENAME_ATTEMPTS; ++attempt) {
1145 length = snprintf(filename, filename_size, "%s/%s%06d_s%08x_%02u.jpg", photo_dir,
1146 prefix, number, session_id, attempt);
1147 if (length < 0 || (size_t)length >= filename_size) break;
1148 int descriptor = open(filename, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, EAR_EVIDENCE_FILE_MODE);
1149 if (descriptor < 0) {
1150 if (errno == EEXIST) continue;
1151 break;
1152 }
1153 int csv_length = snprintf(csv_path, sizeof(csv_path), "%.*s.csv", length - EAR_JPEG_SUFFIX_LENGTH, filename);
1154 if (csv_length > 0 && (size_t)csv_length < sizeof(csv_path))
1155 csv_descriptor = open(csv_path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, EAR_EVIDENCE_FILE_MODE);
1156 if (csv_descriptor < 0) {
1157 const int error = errno;
1159 unlink(filename);
1160 if (error == EEXIST) continue;
1161 break;
1162 }
1163 if (close(descriptor) != 0) {
1164 close(csv_descriptor);
1165 unlink(filename);
1166 break;
1167 }
1168 reserved = true;
1169 break;
1170 }
1171 if (!reserved) {
1172 filename[0] = '\0';
1173 return -1;
1174 }
1175 FILE *csv = fdopen(csv_descriptor, "w");
1176 bool csv_saved = csv != NULL;
1177 if (csv) {
1178 if (fputs(session_log_header, csv) == EOF) csv_saved = false;
1179 for (size_t index = 0; index < count && csv_saved; ++index) {
1180 char line[EAR_LOG_ROW_CAPACITY];
1181 int row_length = format_session_row(&samples[index], session_id, line, sizeof(line));
1182 csv_saved = row_length > 0 && (size_t)row_length < sizeof(line) && fputs(line, csv) != EOF;
1183 }
1184 if (fprintf(csv,
1185 "# result session_id=%u valid=%d lat=%.7f lon=%.7f agl=%.2f alt=%.2f level=%.2f conf=%.3f used=%u/%u\n",
1186 session_id, result->valid, result->lat_deg, result->lon_deg, result->agl_m,
1187 result->alt_m, result->level_db, result->confidence, result->used_count, result->sample_count) < 0)
1188 csv_saved = false;
1189 if (fclose(csv) != 0) csv_saved = false;
1190 } else close(csv_descriptor);
1191 if (!csv_saved) fprintf(stderr, "EAR_CAM_PIPE:\tfailed/incomplete snapshot CSV retained: %s\n", csv_path);
1192 }
1193 if (length < 0 || (size_t)length >= filename_size) {
1194 filename[0] = '\0';
1195 return -1;
1196 }
1197 if (ear_heatmap_write(filename, samples, count, result) != 0) {
1198 fprintf(stderr, "EAR_CAM_PIPE:\tfailed to render %s\n", filename);
1199 unlink(filename);
1200 filename[0] = '\0';
1201 return -1;
1202 }
1203 // Preserve a clean raster for map compositing; reusing the decorated JPEG would blend
1204 // observation dots, the estimate marker and scale bar a second time over the basemap.
1205 char field[PATH_MAX];
1206 length = snprintf(field, sizeof(field), "%.*s_field.jpg", (int)strlen(filename) - EAR_JPEG_SUFFIX_LENGTH, filename);
1207 if (length > 0 && (size_t)length < sizeof(field)) {
1208 if (ear_heatmap_write_field(field, samples, count, result) != 0)
1209 fprintf(stderr, "EAR_CAM_PIPE:\tfield rendering failed: %s\n", field);
1210 } else fprintf(stderr, "EAR_CAM_PIPE:\tfield filename too long for %s\n", filename);
1211 return 0;
1212}
1213
1214int ear_cam_pipe_render(const struct ear_loudest_spot *result, char *filename, size_t filename_size,
1215 bool simulated)
1216{
1218 result, filename, filename_size, simulated);
1219}
1220
1221int ear_cam_pipe_snapshot_render(const struct ear_session_snapshot *snapshot, uint32_t session_id,
1222 const struct ear_loudest_spot *result, char *filename,
1223 size_t filename_size, bool simulated)
1224{
1225 if (!snapshot || !session_id || !result) return -1;
1226 return render_session(snapshot->samples, snapshot->count, ear_cam_pipe_snapshot_number(snapshot),
1227 session_id, result, filename, filename_size, simulated);
1228}
1229
1230/** @brief Solve the current session without consuming it, for intermediate mission feedback. */
1232{
1233 flush_pending_audio(true);
1234 if (result == NULL) {
1235 return -1;
1236 }
1237 memset(result, 0, sizeof(*result));
1239 char line[EAR_LOG_ROW_CAPACITY];
1240 snprintf(line, sizeof(line), "# interim session_id=%u valid=%d lat=%.7f lon=%.7f agl=%.2f conf=%.3f used=%u/%u\n",
1241 log_session_id, result->valid ? 1 : 0, result->lat_deg, result->lon_deg, result->agl_m,
1242 result->confidence, result->used_count, result->sample_count);
1243 queue_session_log(line);
1244 return status;
1245}
1246
1247void ear_cam_pipe_log_result(uint32_t session_id, const struct ear_loudest_spot *result)
1248{
1249 if (!result) return;
1250 char line[EAR_LOG_ROW_CAPACITY];
1251 snprintf(line, sizeof(line),
1252 "# result session_id=%u valid=%d lat=%.7f lon=%.7f agl=%.2f alt=%.2f level=%.2f conf=%.3f used=%u/%u\n",
1253 session_id, result->valid ? 1 : 0, result->lat_deg, result->lon_deg, result->agl_m,
1254 result->alt_m, result->level_db, result->confidence, result->used_count, result->sample_count);
1255 queue_session_log(line);
1256}
1257
1258/** @brief Solve and close the current session, clearing accumulated samples afterward. */
1260{
1261 if (result == NULL) {
1262 return -1;
1263 }
1264 memset(result, 0, sizeof(*result));
1268 printf("EAR_CAM_PIPE:\tsession saved to %s\n", session_log_path);
1269 session_count = 0;
1270 return status;
1271}
char ** environ
static unsigned capacity[COVERAGE_CAMERAS]
static uint32_t session
static bool capture_observation_valid(const struct capture_observation *observation)
Check that an observation supplies a usable time interval.
@ CAPTURE_TIME_AUDIO_WINDOW
size_t size
Definition chdk_pipe.c:143
int descriptor
Definition chdk_pipe.c:142
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
int(* open)(const struct usbfs_device *, struct usbfs_handle *)
Definition chdkbridge.c:56
static bool poll_result(struct camera_point_result *point)
Drain a bounded reply batch and publish only the active request's result.
static uint64_t milliseconds(void)
Read elapsed-time evidence unaffected by changes to civil time.
static uint32_t active_session
static uint64_t last_window_end
#define EAR_SIM_REFERENCE_DISTANCE_M
static size_t log_count
static pid_t server_pid
static bool parse_unsigned_field(const char *line, const char *key, uint64_t *value)
Parse exact unsigned timing/sequence evidence without rounding through double.
static void * supervise_server(void *unused)
Retry missing/disconnected capture independently of optical operation.
#define EAR_LOG_ROW_CAPACITY
#define USHER_EAR_CAM_DEVICE
#define EAR_STOPPED_PREFIX_LENGTH
bool ear_cam_pipe_set_settings(const char *settings)
Copy an assignment path before the microphone supervisor starts.
bool ear_cam_pipe_set_device(const char *device)
Copy a startup ALSA PCM name into bounded adapter-owned storage.
#define EAR_SIM_CONTRAST_DB
struct latest_measurement measurement
static struct ear_session_snapshot session_buffers[EAR_SESSION_BUFFER_COUNT]
union dc_shot_union request
int ear_cam_pipe_snapshot_solve(const struct ear_session_snapshot *snapshot, struct ear_loudest_spot *result)
Solve immutable detached evidence without touching current-session state.
static int format_session_row(const struct ear_sample *sample, uint32_t session_id, char *line, size_t size)
Format one evidence row with both chosen pose and original request provenance.
#define USHER_EAR_CAM_PHOTO_DIR
bool ear_cam_pipe_ready(void)
Report whether an actual or simulated measurement source is ready.
#define EAR_ALTITUDE_UNITS_PER_METER
static atomic_bool reader_stop
static uint32_t simulated_noise_state
int ear_cam_pipe_init(const char *unused)
Reset session storage and start or configure the acoustic backend.
int ear_cam_pipe_snapshot_render(const struct ear_session_snapshot *snapshot, uint32_t session_id, const struct ear_loudest_spot *result, char *filename, size_t filename_size, bool simulated)
Render detached evidence using collision-safe session-tagged JPEG/CSV names.
int32_t ear_cam_pipe_snapshot_number(const struct ear_session_snapshot *snapshot)
Read the last request number from immutable evidence.
#define EAR_READY_PREFIX_LENGTH
static pthread_t reader_thread
#define EAR_SIM_XORSHIFT_LEFT_LAST
#define EAR_SUPERVISOR_TICK_MS
#define EAR_POSE_WAIT_MS
#define EAR_SIM_NOISE_STEPS_PER_DB
void ear_cam_pipe_set_pose_lookup(bool(*lookup)(struct capture_observation *, uint64_t))
Set the startup-only pose callback, later called without waiting on the serial owner.
#define EAR_EVIDENCE_FILE_MODE
void ear_cam_pipe_log_result(uint32_t session_id, const struct ear_loudest_spot *result)
Best-effort enqueue of a correlated result row on the serial owner.
static struct latest_measurement simulated_measurement(const union dc_shot_union *shot, uint64_t now)
Model a virtual point source using free-field inverse-distance attenuation.
static int parse_field(const char *line, const char *key, double *value)
Parse one named numeric field from an EARcam server line.
#define EAR_WARNING_INTERVAL_MS
uint64_t queued_ms
#define EAR_TM_YEAR_ORIGIN
int ear_cam_pipe_finish(struct ear_loudest_spot *result)
Solve and close the current session, clearing accumulated samples afterward.
static struct latest_measurement latest
static pthread_t log_thread
static char band_high_arg[EAR_BAND_ARGUMENT_CAPACITY]
#define EAR_LINE_MAX
static pthread_mutex_t log_mutex
#define EAR_SAMPLE_STALE_MS
#define EAR_READER_CHUNK_BYTES
static double simulated_noise_db(void)
Produce reproducible bounded simulation noise without shared libc PRNG state.
static void sleep_ms(unsigned int milliseconds)
Sleep through signal interruption for bounded lifecycle polling.
static bool(* pose_lookup)(struct capture_observation *, uint64_t)
void ear_cam_pipe_deinit(void)
Stop the child and clear all bounded session state.
#define EAR_NS_PER_MS
struct ear_session_snapshot * ear_cam_pipe_detach_session(void)
Transfer active storage to an immutable worker snapshot without copying samples.
static char band_low_arg[EAR_BAND_ARGUMENT_CAPACITY]
static atomic_bool supervisor_stop
static bool log_running
#define EAR_SIM_XORSHIFT_LEFT_FIRST
static bool warning_due(uint64_t now)
Rate-limit repeated unavailable/stale microphone diagnostics.
#define EAR_MS_PER_SECOND
bool ear_cam_pipe_begin_session(uint32_t session_id)
Begin/reset active collection without solving or waiting for log I/O.
#define EAR_LOG_FILE_MODE
#define EAR_ERROR_PREFIX_LENGTH
int ear_cam_pipe_solve(struct ear_loudest_spot *result)
Solve the current session without consuming it, for intermediate mission feedback.
int ear_cam_pipe_render(const struct ear_loudest_spot *result, char *filename, size_t filename_size, bool simulated)
Render the current session as a north-up acoustic evidence JPEG.
#define EAR_CHILD_REAP_ATTEMPTS
static size_t log_head
#define EAR_EVIDENCE_FILENAME_ATTEMPTS
static struct @264130032040232221072363340307106354175135130231 pending_audio[EAR_PENDING_AUDIO_WINDOWS]
static bool simulated
static bool supervisor_running
#define EAR_SLEEP_NS_PER_MS
static void flush_pending_audio(bool force)
Retry pose lookup without waiting; bound unresolved evidence by count and age.
#define EAR_COORDINATE_UNITS_PER_DEG
void ear_cam_pipe_update_pose(void)
Retry bounded pending audio windows when the serial owner receives new poses.
#define EAR_SESSION_BUFFER_COUNT
#define EAR_LOG_FILENAME_ATTEMPTS
static double simulated_lon_deg
#define EAR_SAMPLE_FUTURE_SLACK_MS
#define EAR_LOG_BATCH_ROWS
#define EAR_READER_POLL_MS
static pthread_t supervisor_thread
static int server_output
static void queue_session_log(const char *line)
Best-effort serial-owner enqueue with copied rows and no filesystem wait.
static void * write_session_log(void *unused)
Drain bounded row batches; this worker alone opens/writes/flushes/closes the log.
static int server_input
int ear_cam_pipe_record(const union dc_shot_union *shot)
Associate the newest sound window with one flight-controller shot pose.
#define USHER_EAR_CAM_COMMAND
static uint64_t monotonic_ms(void)
Return monotonic milliseconds for server freshness and retry decisions.
#define EAR_AUDIO_WINDOW_LIMIT_US
static uint64_t last_warning_ms
void ear_cam_pipe_set_band(double low_cut_hz, double high_cut_hz)
Set the detector band forwarded to a subsequently spawned EARcam child.
#define EAR_PENDING_AUDIO_WINDOWS
#define EAR_SIM_FREQUENCY_HZ
#define EAR_AUDIO_FUTURE_SLACK_US
static char log_queue[EAR_LOG_QUEUE_ROWS][EAR_LOG_ROW_CAPACITY]
static int start_server(void)
Spawn earcam --server and its asynchronous line reader.
#define EAR_SIM_NOISE_HALF_RANGE_DB
static int add_inherited_descriptor_closes(posix_spawn_file_actions_t *actions, const int command_pipe[2], const int response_pipe[2])
Prevent the audio child from inheriting unrelated USHER descriptors.
#define EAR_CHILD_TERM_ATTEMPT
#define EAR_US_PER_MS
static void close_session_log(void)
Join the log writer after queued rows drain; not a hard filesystem deadline.
#define EAR_LOG_QUEUE_ROWS
#define EAR_CHILD_KILL_ATTEMPT
#define EAR_RESTART_INTERVAL_MS
static pthread_cond_t log_available
#define EAR_SIM_NOISE_INITIAL_STATE
static const char session_log_header[]
#define USHER_EAR_CAM_LOG_DIR
static double simulated_level_db_at_1m
void ear_cam_pipe_snapshot_release(struct ear_session_snapshot *snapshot)
Return detached storage to admission after all snapshot access has ended.
static size_t pending_head
#define EAR_MICROPHONE_NAME_CAPACITY
static uint64_t server_error_count
static uint32_t log_session_id
#define EAR_AUDIO_TIMING_ERROR_LIMIT_US
#define EAR_SIM_DISTANCE_DB_PER_DECADE
static void handle_server_line(const char *line)
Interpret one complete server output line and atomically update shared state.
#define EAR_SAMPLE_PREFIX_LENGTH
static bool log_stopping
static bool reader_running
static double simulated_lat_deg
static uint64_t server_started_ms
static size_t pending_count
static int render_session(const struct ear_sample *samples, size_t count, int32_t number, uint32_t session_id, const struct ear_loudest_spot *result, char *filename, size_t filename_size, bool simulated)
Write evidence from borrowed active or immutable snapshot samples.
static int open_session_log(void)
Create the CSV audit log lazily on the first accepted acoustic sample.
#define EAR_JPEG_SUFFIX_LENGTH
static pthread_mutex_t ear_mutex
#define POSITION_BFP_SCALE
static void commit_audio_sample(const union dc_shot_union *request, const struct latest_measurement *measurement)
Append on the serial owner using aligned pose when available, labelled request pose otherwise.
static bool server_ready
static void * reader_main(void *unused)
Read and frame EARcam output in a dedicated thread.
#define EAR_SESSION_MARKER_CAPACITY
#define EAR_LOG_PATH_CAPACITY
static atomic_uint_fast64_t log_dropped
static void stop_server(void)
Request child shutdown, join its reader, and reap the owned process.
#define EAR_BAND_ARGUMENT_CAPACITY
static bool band_set
#define EAR_SIM_NOISE_STEPS
static char ear_settings[PATH_MAX]
static char session_log_path[EAR_LOG_PATH_CAPACITY]
static char microphone_device[EAR_MICROPHONE_NAME_CAPACITY]
#define EAR_READY_TIMEOUT_MS
static size_t session_count
#define EAR_SIM_XORSHIFT_RIGHT
int32_t ear_cam_pipe_last_shot_nr(void)
Get the shot number associated with the newest stored acoustic sample.
void ear_cam_pipe_set_simulated_source(double lat_deg, double lon_deg, double level_db_at_1m)
Select deterministic virtual acoustic measurements for simulation.
static FILE * session_log
Audio/pose adapter and zero-copy snapshot API for the EAR backend.
#define DEG_TO_RAD
Definition ear_fusion.c:34
int calculated_loudestspot(const struct ear_sample *samples, size_t count, struct ear_loudest_spot *result)
Estimate a ground source from relative loudness along a survey track.
Definition ear_fusion.c:129
#define EARTH_RADIUS_M
Definition ear_fusion.c:33
int ear_heatmap_write(const char *filename, const struct ear_sample *samples, size_t count, const struct ear_loudest_spot *spot)
Write a decorated north-up JPEG of relative measured acoustic intensity.
int ear_heatmap_write_field(const char *filename, const struct ear_sample *samples, size_t count, const struct ear_loudest_spot *spot)
Write the same field without track dots, source marker or scale bar.
Render geotagged acoustic measurements into north-up JPEG heatmaps.
static struct ear_sample samples[EAR_MAX_SAMPLES]
static bool ready
#define EAR_MAX_SAMPLES
Definition earcam_core.h:34
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
struct jpeg_error_mgr error
Definition lwir_image.c:60
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 pthread_cond_t available
Definition pose_log.c:73
static size_t count
Definition pose_log.c:79
Estimated ground source, not a surveyed target or guaranteed alarm detection.
Definition earcam_core.h:37
One audio window associated with microphone position and provenance.
Definition earcam_core.h:55
int32_t shot_nr
Definition earcam_core.h:57
double lat_deg
Definition earcam_core.h:58
double trend_db
Definition earcam_core.h:63
int32_t request_lat
Definition earcam_core.h:73
uint64_t window_latest_us
Definition earcam_core.h:71
int32_t request_lon
Definition earcam_core.h:73
bool classifier
Definition earcam_core.h:74
double pose_uncertainty_m
Definition earcam_core.h:69
uint64_t window_sequence
Definition earcam_core.h:71
double frequency_hz
Definition earcam_core.h:65
double agl_m
Definition earcam_core.h:60
double lon_deg
Definition earcam_core.h:59
double contrast_db
Definition earcam_core.h:64
double alt_m
Definition earcam_core.h:61
unsigned classifier_class
Definition earcam_core.h:76
double level_db
Definition earcam_core.h:62
bool pose_aligned
Definition earcam_core.h:68
double classifier_score
Definition earcam_core.h:75
uint64_t window_earliest_us
Definition earcam_core.h:71
uint64_t timestamp_ms
Definition earcam_core.h:56
Statically reserved sample buffer with a single active or detached owner.
struct ear_sample samples[EAR_MAX_SAMPLES]
Latest parsed window plus optional producer timing; published under ear_mutex.
unsigned classifier_class
struct capture_observation observation
struct usher_control_result result
Definition usher.c:377
union dc_shot_union shot
Definition usher.c:534