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
earcam.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#define _POSIX_C_SOURCE 200809L
19#include "version.h"
20
21/**
22 * @file earcam.c
23 * @brief ALSA acoustic detector for motionSCOUT-style narrow-band alarm tones.
24 * @details EARcam captures mono PCM, isolates the configured frequency band with
25 * cascaded Butterworth biquads, measures a bank of Goertzel tone bins over short Hann
26 * windows, and emits either an operator display or machine-readable samples for USHER.
27 * The process remains independently useful for bench work and deliberately keeps the
28 * USHER server protocol simple: newline-delimited output plus STOP/QUIT input.
29 */
30
31#include <alsa/asoundlib.h>
32#include <errno.h>
33#include <fcntl.h>
34#include <math.h>
35#include <poll.h>
36#include <signal.h>
37#include <stdbool.h>
38#include <stddef.h>
39#include <stdint.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <time.h>
44#include <unistd.h>
45#include "ear_inference.h"
47
48// "auto" = first USB audio card that offers a capture PCM (any vendor/device id).
49#define DEFAULT_DEVICE "auto"
50#define AUTO_DEVICE_NAME_MAX 64U
51#define DEFAULT_RATE 48000U
52#define DEFAULT_INTERVAL_MS 50U
53#define MIN_RATE_HZ 8000U
54#define MIN_INTERVAL_MS 20U
55#define MAX_RATE 384000U
56#define MAX_INTERVAL_MS 10000U
57#define MILLISECONDS_PER_SECOND 1000U
58#define MICROSECONDS_PER_SECOND 1000000U
59#define NANOSECONDS_PER_SECOND 1000000000L
60#define NANOSECONDS_PER_MILLISECOND 1000000U
61#define NANOSECONDS_PER_MICROSECOND 1000U
62#define MILLISECONDS_PER_SECOND_F 1000.0
63/** ALSA asks for 5 ms periods and a 20 ms buffer; accepted periods remain bounded. */
64#define CAPTURE_PERIODS_PER_SECOND 200U
65#define CAPTURE_BUFFERS_PER_SECOND 50U
66#define CAPTURE_MONO_CHANNELS 1U
67#define CAPTURE_WAIT_MS 100
68#define CAPTURE_STALL_TIMEOUT_MS 2000U
69#define MAX_INTERVAL_FRAMES ((MAX_RATE * MAX_INTERVAL_MS) / MILLISECONDS_PER_SECOND)
70#define MAX_PERIOD_FRAMES (MAX_RATE / CAPTURE_BUFFERS_PER_SECOND)
71/** Guard opaque ALSA ABI sizes at runtime rather than using direct EARcam heap storage. */
72#define ALSA_OBJECT_CAPACITY 4096U
73#define EARCAM_MAX_ARGUMENTS 64
74#define EARCAM_MAX_PARSED_ARGUMENTS (EARCAM_MAX_ARGUMENTS * 2 + 1)
75#define DEFAULT_LOW_CUT_HZ 1800.0
76#define DEFAULT_HIGH_CUT_HZ 3200.0
77/** Level and contrast gates operate before calibration; clipping is reported separately. */
78#define DEFAULT_MIN_LEVEL_DBFS (-90.0)
79#define DB_FLOOR (-120.0)
80#define METER_WIDTH 50U
81#define TONE_BIN_COUNT 57U
82#define TONE_CONTRAST_THRESHOLD_DB (-3.0)
83#define TREND_THRESHOLD_DB 0.8
84#define ENVELOPE_RELEASE_DB_PER_SECOND 6.0
85/** Bench distance display assumes this reference source and free-field attenuation,
86 * not a measured range. Use only with an independently calibrated microphone chain. */
87#define SOURCE_LEVEL_DB_SPL 95.0
88#define SOURCE_REFERENCE_METERS 3.0
89#define CLIP_THRESHOLD 32700
90#define PI 3.14159265358979323846
91
92/** Parsing bounds retain room below the maximum supported sample-rate Nyquist limit. */
93#define MAX_CUTOFF_HZ 190000.0
94#define MIN_CALIBRATION_DB -300.0
95#define MAX_CALIBRATION_DB 300.0
96#define CONTROL_DEVICE_NAME_CAPACITY 32
97#define SHORT_OPTION_STORAGE 3
98#define SERVER_SAMPLE_LINE_CAPACITY 384
99#define SERVER_COMMAND_CAPACITY 64
100#define SERVER_READ_CHUNK_CAPACITY 64
101/** q = 1/sqrt(2) for each second-order Butterworth section; two sections per edge. */
102#define BUTTERWORTH_Q 0.7071067811865476
103#define FILTER_SECTIONS_PER_EDGE 2
104#define PCM_S16_FULL_SCALE 32768.0
105#define AMPLITUDE_FLOOR 0.000001
106#define AMPLITUDE_DB_PER_DECADE 20.0
107#define DB_LOG_BASE 10.0
108/** Hann coherent gain and sinusoid amplitude recovery combine to this factor. */
109#define HANN_TONE_AMPLITUDE_SCALE 4.0
110/** Fast/slow peak-envelope smoothing in seconds; minimum alarm windows avoids early labels. */
111#define HOMING_FAST_TIME_CONSTANT_S 0.20
112#define HOMING_SLOW_TIME_CONSTANT_S 1.20
113#define HOMING_ACQUISITION_WINDOWS 4U
114/** Deterministic self-test fixtures, not live detector thresholds or measured calibration. */
115#define TEST_TIMESTAMP_US 1000000
116#define TEST_UNDERFLOW_TIMESTAMP_US 100
117#define TEST_UNREAD_FRAMES 480
118#define TEST_RATE_HZ 48000
119#define TEST_EXPECTED_READ_END_US 990000
120#define TEST_TARGET_HZ 2700.0
121#define TEST_INTERFERENCE_HZ 800.0
122#define TEST_TARGET_AMPLITUDE 0.02
123#define TEST_INTERFERENCE_AMPLITUDE 0.20
124#define TEST_TONE_MIN_DB -36.0
125#define TEST_TONE_MAX_DB -32.0
126#define TEST_CONTRAST_MAX_DB -15.0
127#define TEST_TREND_WINDOWS 40U
128#define TEST_APPROACH_START_DB -65.0
129#define TEST_RECEDE_START_DB -45.0
130#define TEST_TREND_STEP_DB 0.3
131
132/**
133 * @brief Validated capture and reporting policy, fixed before the sample loop.
134 * @details Calibration is a caller-supplied offset, not automatic microphone
135 * calibration. It changes reported levels, not the dBFS alarm decision.
136 */
137struct options {
138 const char *device; /**< Borrowed ALSA PCM name; auto selects a USB capture card. */
139 unsigned int rate; /**< Exact requested sample rate, hertz. */
140 unsigned int interval_ms; /**< Analysis/report window duration, milliseconds. */
141 double low_cut_hz; /**< High-pass edge and first tone-bank frequency, hertz. */
142 double high_cut_hz; /**< Low-pass edge and last tone-bank frequency, hertz. */
143 double min_level_dbfs; /**< Absolute uncalibrated tone gate before contrast testing. */
144 double calibration_db; /**< Additive report offset from dBFS to caller-calibrated dB SPL. */
145 bool calibrated; /**< Caller explicitly supplied the calibration offset. */
146 bool self_test; /**< Run deterministic software checks without opening ALSA. */
147 bool server; /**< Use nonblocking line protocol instead of a terminal meter. */
148 const char *settings, *audio_file;
150};
151
152/** @brief Normalized biquad coefficients and transposed-direct-form-II delay state. */
153struct biquad {
154 double b0;
155 double b1;
156 double b2;
157 double a1;
158 double a2;
159 double z1;
160 double z2;
162};
163
164/** @brief One Goertzel recurrence; state resets at each analysis-window boundary. */
165struct tone_bin {
167 double first;
168 double second;
170};
171
172/** @brief Peak hold and fast/slow averages; direction is guidance, not a bearing measurement. */
175 double fast_db;
176 double slow_db;
177 unsigned int alarm_windows;
179};
180
181static volatile sig_atomic_t keep_running = 1;
182
183/** @brief Aligned bounded storage for an opaque ALSA object after its sizeof guard succeeds. */
185 max_align_t alignment;
187};
188
193/* The largest supported configuration sets workspace bounds. Only the active
194 * period/window is touched; changing the CLI maxima also changes static RAM cost. */
198
199/**
200 * @brief Subtract unread PCM duration from a monotonic ALSA timestamp.
201 * @return End of consumed audio in microseconds, or zero if the calculation is unusable.
202 * @details Arrival time alone includes buffered audio delay. This correction lets
203 * USHER associate a window with flight poses closer to its actual capture time.
204 */
205static uint64_t audio_read_end_us(uint64_t hardware_us, uint64_t unread_frames, unsigned int rate)
206{
207 if (!rate || unread_frames > UINT64_MAX / MICROSECONDS_PER_SECOND) return 0;
208 const uint64_t delay_us = unread_frames * MICROSECONDS_PER_SECOND / rate;
209 return hardware_us > delay_us ? hardware_us - delay_us : 0;
210}
211
212/** @brief Long-to-short option mapping; borrowed values are passed to standard getopt. */
218
219/**
220 * @brief Normalize --name value and --name=value into bounded getopt arguments.
221 * @return Argument count, or -1 for unknown options, missing values or capacity exhaustion.
222 * @details Pointers borrow argv/static alias strings; no copied argument payload or heap is needed.
223 */
224static int normalize_long_options(int argc, char *const argv[], char *normalized[],
225 size_t capacity, const struct option_alias aliases[],
226 size_t alias_count)
227{
228 if (argc < 1 || argc > EARCAM_MAX_ARGUMENTS || capacity == 0) {
229 return -1;
230 }
231 size_t output_count = 0;
232 normalized[output_count++] = argv[0];
233 for (int index = 1; index < argc; ++index) {
234 const char *argument = argv[index];
235 if (strcmp(argument, "--") == 0) {
236 if (output_count >= capacity) {
237 return -1;
238 }
239 normalized[output_count++] = argv[index];
240 for (++index; index < argc; ++index) {
241 if (output_count >= capacity) {
242 return -1;
243 }
244 normalized[output_count++] = argv[index];
245 }
246 break;
247 }
248 if (strncmp(argument, "--", 2) != 0 || argument[2] == '\0') {
249 if (output_count >= capacity) {
250 return -1;
251 }
252 normalized[output_count++] = argv[index];
253 continue;
254 }
255 const char *name = argument + 2;
256 size_t name_length = strcspn(name, "=");
257 const char *inline_value = name[name_length] == '=' ? name + name_length + 1 : NULL;
258 const struct option_alias *alias = NULL;
259 for (size_t alias_index = 0; alias_index < alias_count; ++alias_index) {
260 if (strlen(aliases[alias_index].name) == name_length
261 && strncmp(name, aliases[alias_index].name, name_length) == 0) {
262 alias = &aliases[alias_index];
263 break;
264 }
265 }
266 if (alias == NULL || (!alias->requires_argument && inline_value != NULL)
267 || output_count >= capacity) {
268 return -1;
269 }
270 normalized[output_count++] = (char *)alias->option;
271 if (alias->requires_argument) {
272 if (inline_value == NULL) {
273 if (++index >= argc) {
274 return -1;
275 }
276 inline_value = argv[index];
277 }
278 if (output_count >= capacity) {
279 return -1;
280 }
281 normalized[output_count++] = (char *)inline_value;
282 }
283 }
284 if (output_count >= capacity) {
285 return -1;
286 }
287 normalized[output_count] = NULL;
288 return (int)output_count;
289}
290
291/** @brief Request orderly capture-loop termination from a signal handler.
292 * @param signal_number Delivered signal, intentionally unused.
293 * @details sig_atomic_t is used because complex cleanup is unsafe in signal context. */
294static void handle_signal(int signal_number)
295{
296 (void)signal_number;
297 keep_running = 0;
298}
299
300/** @brief Return monotonic milliseconds for correlating samples without wall-clock jumps.
301 * @return Monotonic timestamp in milliseconds. */
302static uint64_t monotonic_ms(void)
303{
304 struct timespec now;
305 if (clock_gettime(CLOCK_MONOTONIC, &now) != 0 || now.tv_sec < 0 || now.tv_nsec < 0 ||
306 now.tv_nsec >= NANOSECONDS_PER_SECOND) return 0;
307 return (uint64_t)now.tv_sec * MILLISECONDS_PER_SECOND
308 + (uint64_t)now.tv_nsec / NANOSECONDS_PER_MILLISECOND;
309}
310
311/** @brief Print command-line help or version-led usage text.
312 * @param stream Destination stream.
313 * @param program Executable name shown in examples. */
314static void print_usage(FILE *stream, const char *program)
315{
316 fprintf(stream, "%s\n", EARCAM_BUILD_VERSION);
317 fprintf(stream, "Model options: --settings FILE, --check-model, --analyze-audio MONO_S16LE.pcm\n");
318 fprintf(stream,
319 "Usage: %s [options]\n"
320 "Measure microphone level and display it in the terminal.\n\n"
321 "Options:\n"
322 " -d, --device NAME ALSA capture device (default: %s = first USB capture card)\n"
323 " -r, --rate HZ Sample rate (default: %u)\n"
324 " -i, --interval MS Display interval (default: %u)\n"
325 " -l, --low-cut HZ Search band lower edge (default: %.0f)\n"
326 " -u, --high-cut HZ Search band upper edge (default: %.0f)\n"
327 " -n, --min-level DBFS Minimum alarm tone level (default: %.0f)\n"
328 " -c, --calibration DB Add DB to dBFS readings to report dB SPL\n"
329 " --server Machine-readable SAMPLE lines for USHER; STOP/QUIT on stdin\n"
330 " --self-test Test detector without a microphone\n"
331 " --version Show application version and build Git revision\n"
332 " -h, --help Show this help\n\n"
333 "Examples:\n"
334 " %s --device plughw:1,0\n"
335 " %s -d default motionSCOUT rescue profile\n"
336 " arecord -L List ALSA capture device names\n",
339 program, program);
340}
341
342/** @brief Parse a bounded unsigned command-line value.
343 * @return 0 on success, otherwise -1 without modifying the output value. */
344static int parse_unsigned(const char *text, unsigned int minimum,
345 unsigned int maximum, unsigned int *value)
346{
347 char *end = NULL;
348 unsigned long parsed;
349
350 errno = 0;
351 parsed = strtoul(text, &end, 10);
352 if (errno != 0 || end == text || *end != '\0' || parsed < minimum ||
353 parsed > maximum) {
354 return -1;
355 }
356 *value = (unsigned int)parsed;
357 return 0;
358}
359
360// Find the first USB audio card with a capture PCM. Writes "hw:CARD=<id>,DEV=<n>"
361// into name; returns 0 on success, -1 when no USB capture device is present.
362/** @brief Discover the first USB ALSA card offering a capture PCM.
363 * @param name Destination ALSA device name.
364 * @param name_size Capacity of @p name.
365 * @return 0 when a usable device is found, otherwise -1.
366 * @details USB-Audio matching prevents an arbitrary onboard sound device from silently
367 * becoming the payload sensor when `--device auto` is used. */
368static int find_usb_capture_device(char *name, size_t name_size)
369{
370 if (snd_ctl_card_info_sizeof() > sizeof(card_info_storage.bytes)
371 || snd_pcm_info_sizeof() > sizeof(pcm_info_storage.bytes)) {
372 errno = EOVERFLOW;
373 return -1;
374 }
375 snd_ctl_card_info_t *info = (snd_ctl_card_info_t *)card_info_storage.bytes;
376 snd_pcm_info_t *pcm_info = (snd_pcm_info_t *)pcm_info_storage.bytes;
377 int found = -1;
378 int card = -1;
379 while (found != 0 && snd_card_next(&card) == 0 && card >= 0) {
380 char control_name[CONTROL_DEVICE_NAME_CAPACITY];
381 if (snprintf(control_name, sizeof(control_name), "hw:%d", card) <= 0) {
382 continue;
383 }
384 snd_ctl_t *control = NULL;
385 if (snd_ctl_open(&control, control_name, 0) < 0) {
386 continue;
387 }
388 if (snd_ctl_card_info(control, info) < 0) {
389 snd_ctl_close(control);
390 continue;
391 }
392 const char *driver = snd_ctl_card_info_get_driver(info);
393 const char *card_id = snd_ctl_card_info_get_id(info);
394 if (driver == NULL || card_id == NULL || strcmp(driver, "USB-Audio") != 0) {
395 snd_ctl_close(control);
396 continue;
397 }
398 int device = -1;
399 while (snd_ctl_pcm_next_device(control, &device) == 0 && device >= 0) {
400 snd_pcm_info_set_device(pcm_info, (unsigned int)device);
401 snd_pcm_info_set_subdevice(pcm_info, 0);
402 snd_pcm_info_set_stream(pcm_info, SND_PCM_STREAM_CAPTURE);
403 if (snd_ctl_pcm_info(control, pcm_info) < 0) {
404 continue;
405 }
406 int length = snprintf(name, name_size, "hw:CARD=%s,DEV=%d", card_id, device);
407 found = (length > 0 && (size_t)length < name_size) ? 0 : -1;
408 break;
409 }
410 snd_ctl_close(control);
411 }
412 return found;
413}
414
415/** @brief Parse a finite bounded floating-point command-line value.
416 * @return 0 on success or -1 for malformed, non-finite, or out-of-range input. */
417static int parse_double_value(const char *text, double minimum, double maximum,
418 double *value)
419{
420 char *end = NULL;
421 double parsed;
422
423 errno = 0;
424 parsed = strtod(text, &end);
425 if (errno != 0 || end == text || *end != '\0' || !isfinite(parsed) ||
426 parsed < minimum || parsed > maximum) {
427 return -1;
428 }
429 *value = parsed;
430 return 0;
431}
432
433/** @brief Parse and cross-validate EARcam command-line configuration.
434 * @return 0 for a runnable configuration, 1 after help/version output, or -1 on error.
435 * @details Nyquist and band-order checks happen here rather than in the DSP loop so a
436 * misconfigured filter cannot produce misleading field measurements. */
437static int parse_options(int argc, char **argv, struct options *options)
438{
439 static const struct option_alias long_options[] = {
440 {"device", "-d", true},
441 {"rate", "-r", true},
442 {"interval", "-i", true},
443 {"low-cut", "-l", true},
444 {"high-cut", "-u", true},
445 {"min-level", "-n", true},
446 {"calibration", "-c", true},
447 {"self-test", "-S", false},
448 {"server", "-M", false},
449 {"settings", "-Z", true},
450 {"analyze-audio", "-X", true},
451 {"check-model", "-Q", false},
452 {"version", "-V", false},
453 {"help", "-h", false}
454 };
455 int option;
456 char *normalized_argv[EARCAM_MAX_PARSED_ARGUMENTS];
457 int normalized_argc = normalize_long_options(argc, argv, normalized_argv,
458 EARCAM_MAX_PARSED_ARGUMENTS, long_options,
459 sizeof(long_options) / sizeof(long_options[0]));
460 if (normalized_argc < 0) {
461 fprintf(stderr, "Invalid or excessive command-line arguments.\n");
462 return -1;
463 }
464 optind = 1;
465 while ((option = getopt(normalized_argc, normalized_argv,
466 "d:r:i:l:u:n:c:hSMVZ:X:Q")) != -1) {
467 switch (option) {
468 case 'Z': options->settings = optarg; break;
469 case 'X': options->audio_file = optarg; break;
470 case 'Q': options->check_model = true; break;
471 case 'd':
472 options->device = optarg;
473 break;
474 case 'r':
475 if (parse_unsigned(optarg, MIN_RATE_HZ, MAX_RATE, &options->rate) != 0) {
476 fprintf(stderr, "Invalid sample rate: %s\n", optarg);
477 return -1;
478 }
479 break;
480 case 'i':
482 fprintf(stderr, "Invalid display interval: %s\n", optarg);
483 return -1;
484 }
485 break;
486 case 'l':
487 if (parse_double_value(optarg, 0.0, MAX_CUTOFF_HZ, &options->low_cut_hz) != 0) {
488 fprintf(stderr, "Invalid low-cut frequency: %s\n", optarg);
489 return -1;
490 }
491 break;
492 case 'u':
493 if (parse_double_value(optarg, 0.0, MAX_CUTOFF_HZ, &options->high_cut_hz) != 0) {
494 fprintf(stderr, "Invalid high-cut frequency: %s\n", optarg);
495 return -1;
496 }
497 break;
498 case 'n':
499 if (parse_double_value(optarg, DB_FLOOR, 0.0,
500 &options->min_level_dbfs) != 0) {
501 fprintf(stderr, "Invalid minimum level: %s\n", optarg);
502 return -1;
503 }
504 break;
505 case 'c':
507 fprintf(stderr, "Invalid calibration offset: %s\n", optarg);
508 return -1;
509 }
510 options->calibrated = true;
511 break;
512 case 'S':
513 options->self_test = true;
514 break;
515 case 'M':
516 options->server = true;
517 break;
518 case 'h':
519 print_usage(stdout, argv[0]);
520 return 1;
521 case 'V':
523 return 1;
524 default:
525 print_usage(stderr, argv[0]);
526 return -1;
527 }
528 }
529
530 if (optind != normalized_argc) {
531 fprintf(stderr, "Unexpected argument: %s\n", normalized_argv[optind]);
532 return -1;
533 }
534 if (options->low_cut_hz <= 0.0 || options->high_cut_hz <= 0.0) {
535 fprintf(stderr, "Search-band frequencies must be greater than zero.\n");
536 return -1;
537 }
538 if (options->low_cut_hz >= (double)options->rate / 2.0 ||
539 options->high_cut_hz >= (double)options->rate / 2.0) {
540 fprintf(stderr, "Filter cutoffs must be below the Nyquist frequency (%.0f Hz).\n",
541 (double)options->rate / 2.0);
542 return -1;
543 }
545 fprintf(stderr, "Low-cut frequency must be below high-cut frequency.\n");
546 return -1;
547 }
548 return 0;
549}
550
551/** @brief Configure a second-order Butterworth high- or low-pass section.
552 * @details Two identical sections are cascaded to give useful out-of-band rejection
553 * before tone analysis without the latency and allocation cost of an FFT filter bank. */
554static void configure_biquad(struct biquad *filter, double cutoff_hz,
555 unsigned int sample_rate, bool high_pass)
556{
557 const double q = BUTTERWORTH_Q;
558 double omega;
559 double cosine;
560 double alpha;
561 double a0;
562
563 memset(filter, 0, sizeof(*filter));
564 if (cutoff_hz <= 0.0) {
565 return;
566 }
567
568 /* Factors of two and unity below belong to the biquad equations, not tuning:
569 * omega is radians/sample; a0 normalizes both numerator and feedback terms. */
570 omega = 2.0 * PI * cutoff_hz / (double)sample_rate;
571 cosine = cos(omega);
572 alpha = sin(omega) / (2.0 * q);
573 a0 = 1.0 + alpha;
574
575 if (high_pass) {
576 filter->b0 = (1.0 + cosine) / (2.0 * a0);
577 filter->b1 = -(1.0 + cosine) / a0;
578 filter->b2 = filter->b0;
579 } else {
580 filter->b0 = (1.0 - cosine) / (2.0 * a0);
581 filter->b1 = (1.0 - cosine) / a0;
582 filter->b2 = filter->b0;
583 }
584 filter->a1 = (-2.0 * cosine) / a0;
585 filter->a2 = (1.0 - alpha) / a0;
586 filter->enabled = true;
587}
588
589/** @brief Filter one PCM sample while retaining the section delay state.
590 * @return Filtered sample, or @p input when the section is disabled. */
591static double apply_biquad(struct biquad *filter, double input)
592{
593 double output;
594
595 if (!filter->enabled) {
596 return input;
597 }
598 output = filter->b0 * input + filter->z1;
599 filter->z1 = filter->b1 * input - filter->a1 * output + filter->z2;
600 filter->z2 = filter->b2 * input - filter->a2 * output;
601 return output;
602}
603
604/** @brief Convert a linear amplitude to bounded dBFS.
605 * @details Flooring avoids negative infinity propagating into detector thresholds. */
606static double amplitude_to_db(double amplitude)
607{
608 if (amplitude <= AMPLITUDE_FLOOR) {
609 return DB_FLOOR;
610 }
611 return AMPLITUDE_DB_PER_DECADE * log10(amplitude);
612}
613
614/** @brief Initialize evenly spaced Goertzel bins across the selected search band.
615 * @details The small fixed bank is cheaper and more targeted than a broad FFT because
616 * mission alarms occupy a known band and only the strongest frequency is needed. */
617static void configure_tone_bins(struct tone_bin *bins,
618 const struct options *options)
619{
620 double frequency_step = (options->high_cut_hz - options->low_cut_hz) /
621 (double)(TONE_BIN_COUNT - 1U);
622 unsigned int index;
623
624 for (index = 0; index < TONE_BIN_COUNT; ++index) {
625 double frequency = options->low_cut_hz + frequency_step * (double)index;
626 bins[index].coefficient =
627 2.0 * cos(2.0 * PI * frequency / (double)options->rate);
628 bins[index].first = 0.0;
629 bins[index].second = 0.0;
630 bins[index].frequency_hz = frequency;
631 }
632}
633
634/** @brief Feed one windowed, band-passed sample into every Goertzel recurrence.
635 * @param bins Persistent Goertzel states for the search frequencies.
636 * @param sample Current band-passed PCM value normalized to [-1, 1].
637 * @param window Precomputed Hann weight for this sample's interval position.
638 * @details Windowing reduces spectral leakage; precomputation keeps trigonometry out of
639 * the realtime sample loop. */
640static void update_tone_bins(struct tone_bin *bins, double sample, double window)
641{
642 unsigned int index;
643
644 for (index = 0; index < TONE_BIN_COUNT; ++index) {
645 double value = sample * window + bins[index].coefficient * bins[index].first -
646 bins[index].second;
647 bins[index].second = bins[index].first;
648 bins[index].first = value;
649 }
650}
651
652/** @brief Extract and reset the strongest Goertzel-bin power estimate.
653 * @param bins Goertzel states to inspect and reset for the next interval.
654 * @param sample_count Number of samples represented by the states.
655 * @param frequency_hz Receives the winning bin frequency.
656 * @return Window-normalized tone level in dBFS. */
657static double strongest_tone_db(struct tone_bin *bins, uint64_t sample_count,
658 double *frequency_hz)
659{
660 double maximum_power = 0.0;
661 unsigned int index;
662
663 for (index = 0; index < TONE_BIN_COUNT; ++index) {
664 double power = bins[index].first * bins[index].first +
665 bins[index].second * bins[index].second -
666 bins[index].coefficient * bins[index].first *
667 bins[index].second;
668 if (power > maximum_power) {
669 maximum_power = power;
670 *frequency_hz = bins[index].frequency_hz;
671 }
672 bins[index].first = 0.0;
673 bins[index].second = 0.0;
674 }
675 return amplitude_to_db(HANN_TONE_AMPLITUDE_SCALE * sqrt(maximum_power) / (double)sample_count);
676}
677
678/** @brief Update envelope and fast/slow trend estimates for operator guidance.
679 * @return Stable direction label for the current acoustic evidence.
680 * @details The peak-hold envelope falls gradually while two exponential averages make
681 * direction less sensitive to individual noisy windows. */
682static const char *update_homing_state(struct homing_state *state,
683 double tone_db, bool alarm_present,
684 const struct options *options,
685 double *trend_db)
686{
687 double elapsed = (double)options->interval_ms / MILLISECONDS_PER_SECOND_F;
688 double fast_alpha = 1.0 - exp(-elapsed / HOMING_FAST_TIME_CONSTANT_S);
689 double slow_alpha = 1.0 - exp(-elapsed / HOMING_SLOW_TIME_CONSTANT_S);
690
691 if (!state->initialized) {
692 state->envelope_db = tone_db;
693 state->fast_db = tone_db;
694 state->slow_db = tone_db;
695 state->initialized = true;
696 }
697
699 if (alarm_present) {
700 if (tone_db > state->envelope_db) {
701 state->envelope_db = tone_db;
702 }
703 ++state->alarm_windows;
704 }
705 if (state->envelope_db < DB_FLOOR) {
706 state->envelope_db = DB_FLOOR;
707 }
708
709 state->fast_db += fast_alpha * (state->envelope_db - state->fast_db);
710 state->slow_db += slow_alpha * (state->envelope_db - state->slow_db);
711 *trend_db = state->fast_db - state->slow_db;
712
714 return "ACQUIRING ";
715 }
716 if (*trend_db > TREND_THRESHOLD_DB) {
717 return "APPROACH ";
718 }
719 if (*trend_db < -TREND_THRESHOLD_DB) {
720 return "RECEDING ";
721 }
722 return "STEADY ";
723}
724
725/** @brief Analyze a deterministic synthetic tone mixture for self-test coverage. */
726static void analyze_test_window(struct tone_bin *bins,
727 const struct options *options,
728 double target_amplitude,
729 double interference_amplitude,
730 double *tone_db, double *contrast_db)
731{
732 uint64_t sample_count =
734 uint64_t sample_index;
735 double sum_squares = 0.0;
736 double frequency_hz = 0.0;
737 if (sample_count == 0U || sample_count > MAX_INTERVAL_FRAMES) {
738 *tone_db = DB_FLOOR;
739 *contrast_db = 0.0;
740 return;
741 }
742 for (sample_index = 0; sample_index < sample_count; ++sample_index) {
743 analysis_window[sample_index] = sample_count > 1U
744 ? 0.5 - 0.5 * cos(2.0 * PI * (double)sample_index /
745 (double)(sample_count - 1U))
746 : 1.0;
747 }
748
749 for (sample_index = 0; sample_index < sample_count; ++sample_index) {
750 double time = (double)sample_index / (double)options->rate;
751 double sample = target_amplitude * sin(2.0 * PI * TEST_TARGET_HZ * time) +
752 interference_amplitude * sin(2.0 * PI * TEST_INTERFERENCE_HZ * time);
753 update_tone_bins(bins, sample, analysis_window[sample_index]);
754 sum_squares += sample * sample;
755 }
756 *tone_db = strongest_tone_db(bins, sample_count, &frequency_hz);
757 *contrast_db = *tone_db -
758 amplitude_to_db(sqrt(sum_squares / (double)sample_count));
759}
760
761/** @brief Verify selectivity and trend classification without ALSA hardware.
762 * @return 0 on expected detector behavior, otherwise -1. */
763static int run_self_test(const struct options *options)
764{
765 /* A 10 ms unread tail must shift the timestamp back by exactly that duration;
766 * underflow and missing sample rate must not manufacture a plausible time. */
770 struct tone_bin bins[TONE_BIN_COUNT];
771 struct homing_state approaching = {0};
772 struct homing_state receding = {0};
773 double tone_db;
774 double contrast_db;
775 double trend_db = 0.0;
776 const char *direction = NULL;
777 unsigned int index;
778
780 /* A weak in-band tone amid stronger out-of-band interference checks bin
781 * selectivity. The tolerance is software-fixture evidence, not sensor accuracy. */
783 if (tone_db < TEST_TONE_MIN_DB || tone_db > TEST_TONE_MAX_DB || contrast_db > TEST_CONTRAST_MAX_DB) {
784 fprintf(stderr, "Self-test failed: tone selectivity (%.1f, %.1f dB)\n",
785 tone_db, contrast_db);
786 return -1;
787 }
788
789 for (index = 0; index < TEST_TREND_WINDOWS; ++index) {
790 double level = TEST_APPROACH_START_DB + (double)index * TEST_TREND_STEP_DB;
791 direction = update_homing_state(&approaching, level, true, options,
792 &trend_db);
793 }
794 if (strcmp(direction, "APPROACH ") != 0) {
795 fprintf(stderr, "Self-test failed: approaching trend (%.1f dB)\n",
796 trend_db);
797 return -1;
798 }
799
800 for (index = 0; index < TEST_TREND_WINDOWS; ++index) {
801 double level = TEST_RECEDE_START_DB - (double)index * TEST_TREND_STEP_DB;
802 direction = update_homing_state(&receding, level, true, options,
803 &trend_db);
804 }
805 if (strcmp(direction, "RECEDING ") != 0) {
806 fprintf(stderr, "Self-test failed: receding trend (%.1f dB)\n", trend_db);
807 return -1;
808 }
809
810 printf("motionSCOUT detector self-test passed\n");
811 return 0;
812}
813
814/** @brief Render one human-facing measurement line for bench use. */
815static void display_homing(double level_db, double frequency_hz,
816 double contrast_db, bool alarm_present,
817 const char *direction, double trend_db,
818 const struct homing_state *state,
819 const struct options *options)
820{
821 double displayed_level = level_db + options->calibration_db;
822 double meter_level = (state->envelope_db - DB_FLOOR) / -DB_FLOOR;
823 unsigned int filled;
824 unsigned int index;
825
826 if (meter_level < 0.0) {
827 meter_level = 0.0;
828 } else if (meter_level > 1.0) {
829 meter_level = 1.0;
830 }
831 filled = (unsigned int)(meter_level * (double)METER_WIDTH + 0.5);
832
833 printf("\r[");
834 for (index = 0; index < METER_WIDTH; ++index) {
835 putchar(index < filled ? '#' : ' ');
836 }
837 printf("] %s %s %6.1f %s %4.0f Hz trend %+5.1f dB conf %+4.1f dB",
838 alarm_present ? "ALARM" : "listen", direction, displayed_level,
839 options->calibrated ? "dB SPL" : "dBFS", frequency_hz, trend_db,
840 contrast_db);
841 if (options->calibrated && alarm_present) {
842 double distance = SOURCE_REFERENCE_METERS *
843 pow(DB_LOG_BASE, (SOURCE_LEVEL_DB_SPL - displayed_level) / AMPLITUDE_DB_PER_DECADE);
844 printf(" ~%5.1f m", distance);
845 }
846 fflush(stdout);
847}
848
849/** @brief Configure mono signed-16 ALSA capture with low-latency period sizes.
850 * @return ALSA status code.
851 * @details Periods target five milliseconds to keep USHER samples timely without
852 * forcing an excessively interrupt-heavy capture configuration. */
853static int configure_capture(snd_pcm_t *pcm, unsigned int sample_rate)
854{
855 if (snd_pcm_hw_params_sizeof() > sizeof(hardware_params_storage.bytes)
856 || snd_pcm_sw_params_sizeof() > sizeof(software_params_storage.bytes)) {
857 errno = EOVERFLOW;
858 return -EOVERFLOW;
859 }
860 snd_pcm_hw_params_t *hardware = (snd_pcm_hw_params_t *)hardware_params_storage.bytes;
861 snd_pcm_sw_params_t *software = (snd_pcm_sw_params_t *)software_params_storage.bytes;
862 snd_pcm_uframes_t period_frames = sample_rate / CAPTURE_PERIODS_PER_SECOND;
863 snd_pcm_uframes_t buffer_frames = sample_rate / CAPTURE_BUFFERS_PER_SECOND;
864 int direction = 0;
865 int result;
866
867 result = snd_pcm_hw_params_any(pcm, hardware);
868 if (result >= 0) {
869 result = snd_pcm_hw_params_set_access(
870 pcm, hardware, SND_PCM_ACCESS_RW_INTERLEAVED);
871 }
872 if (result >= 0) {
873 result = snd_pcm_hw_params_set_format(pcm, hardware,
874 SND_PCM_FORMAT_S16_LE);
875 }
876 if (result >= 0) {
877 result = snd_pcm_hw_params_set_channels(pcm, hardware, CAPTURE_MONO_CHANNELS);
878 }
879 if (result >= 0) {
880 result = snd_pcm_hw_params_set_rate(pcm, hardware, sample_rate, 0);
881 }
882 if (result >= 0) {
883 result = snd_pcm_hw_params_set_period_size_near(
884 pcm, hardware, &period_frames, &direction);
885 }
886 if (result >= 0) {
887 result = snd_pcm_hw_params_set_buffer_size_near(
888 pcm, hardware, &buffer_frames);
889 }
890 if (result >= 0) {
891 result = snd_pcm_hw_params(pcm, hardware);
892 }
893 if (result < 0) {
894 return result;
895 }
896
897 result = snd_pcm_sw_params_current(pcm, software);
899 && snd_pcm_sw_params_set_tstamp_mode(pcm, software, SND_PCM_TSTAMP_ENABLE) >= 0
900 && snd_pcm_sw_params_set_tstamp_type(pcm, software, SND_PCM_TSTAMP_TYPE_MONOTONIC) >= 0;
901 if (result >= 0) {
902 result = snd_pcm_sw_params_set_avail_min(pcm, software, period_frames);
903 }
904 if (result >= 0) {
905 result = snd_pcm_sw_params_set_start_threshold(pcm, software, 1U);
906 }
907 if (result >= 0) {
908 result = snd_pcm_sw_params_set_stop_threshold(pcm, software,
909 buffer_frames);
910 }
911 if (result >= 0) {
912 result = snd_pcm_sw_params(pcm, software);
913 }
914 if (result >= 0) {
915 result = snd_pcm_prepare(pcm);
916 }
917 return result;
918}
919
920// Server output: one self-describing line per analysis window. A slow reader
921// must never stall audio capture, so stdout is non-blocking and drops count.
922static unsigned long server_dropped_lines = 0;
923
924/** @brief Emit one classifier window to the server's nonblocking output.
925 * @param result Classification, clipping and monotonic window evidence.
926 * @param options Level calibration and its qualification flag.
927 * @details Format and write the record as a unit. Count incomplete writes
928 * instead of letting parent backpressure stall audio acquisition. */
929static void emit_classifier_sample(const struct ear_inference_result *result, const struct options *options)
930{
932 const int length = snprintf(line, sizeof(line),
933 "CLASS t=%llu level=%.2f score=%.6f class=%u alarm=%u clip=%u cal=%u "
934 "begin_us=%llu end_us=%llu error_us=%llu sequence=%llu\n",
935 (unsigned long long)monotonic_ms(), result->level_dbfs + options->calibration_db,
936 result->score, result->category, result->alarm ? 1U : 0U, result->clipped ? 1U : 0U,
937 options->calibrated ? 1U : 0U, (unsigned long long)result->begin_us,
938 (unsigned long long)result->end_us, (unsigned long long)result->error_us,
939 (unsigned long long)result->sequence);
940 if (length <= 0 || (size_t)length >= sizeof(line)) return;
941 const ssize_t written = write(STDOUT_FILENO, line, (size_t)length);
942 if (written != length) ++server_dropped_lines;
943}
944
945/** @brief Emit one self-describing USHER server sample without blocking capture.
946 * @details A slow parent loses a measurement rather than stalling ALSA; the drop count
947 * remains observable for diagnostics. */
948static void emit_server_sample(uint64_t timestamp_ms, double level_db,
949 double frequency_hz, double contrast_db,
950 double trend_db, double envelope_db,
951 bool alarm_present, bool clipped,
952 const struct options *options, uint64_t begin_us,
953 uint64_t end_us, uint64_t error_us, uint64_t sequence)
954{
956 int length = snprintf(line, sizeof(line),
957 "SAMPLE t=%llu level=%.2f freq=%.0f contrast=%.2f "
958 "trend=%.2f env=%.2f alarm=%d clip=%d cal=%d"
959 " begin_us=%llu end_us=%llu error_us=%llu sequence=%llu\n",
960 (unsigned long long)timestamp_ms,
961 level_db + options->calibration_db, frequency_hz,
962 contrast_db, trend_db,
964 alarm_present ? 1 : 0, clipped ? 1 : 0,
965 options->calibrated ? 1 : 0,
966 (unsigned long long)begin_us, (unsigned long long)end_us,
967 (unsigned long long)error_us, (unsigned long long)sequence);
968 if (length <= 0 || (size_t)length >= sizeof(line)) {
969 return;
970 }
971 size_t sent = 0;
972 while (sent < (size_t)length) {
973 ssize_t written = write(STDOUT_FILENO, line + sent, (size_t)length - sent);
974 if (written > 0) {
975 sent += (size_t)written;
976 continue;
977 }
978 if (written < 0 && errno == EINTR) {
979 continue;
980 }
982 return;
983 }
984}
985
986// Returns 1 when the controller asked us to stop, 0 otherwise.
987/** @brief Consume non-blocking STOP/QUIT commands from USHER.
988 * @return 1 when capture should stop, otherwise 0.
989 * @details Chunked input accepts fragmented commands while avoiding one syscall per
990 * character and never delaying audio acquisition. */
991static int poll_server_stdin(void)
992{
993 struct pollfd descriptor = {.fd = STDIN_FILENO, .events = POLLIN, .revents = 0};
994 static char command[SERVER_COMMAND_CAPACITY];
995 static size_t command_size = 0;
996
997 if (poll(&descriptor, 1, 0) <= 0) {
998 return 0;
999 }
1000 if ((descriptor.revents & (POLLHUP | POLLERR | POLLNVAL)) != 0
1001 && (descriptor.revents & POLLIN) == 0) {
1002 return 1;
1003 }
1004 char chunk[SERVER_READ_CHUNK_CAPACITY];
1005 ssize_t count = read(STDIN_FILENO, chunk, sizeof(chunk));
1006 if (count == 0) {
1007 return 1;
1008 }
1009 if (count < 0) {
1010 return (errno == EAGAIN || errno == EINTR) ? 0 : 1;
1011 }
1012 for (ssize_t index = 0; index < count; ++index) {
1013 if (chunk[index] == '\n') {
1014 command[command_size] = '\0';
1015 command_size = 0;
1016 if (strcmp(command, "STOP") == 0 || strcmp(command, "QUIT") == 0) {
1017 return 1;
1018 }
1019 } else if (command_size + 1 < sizeof(command)) {
1020 command[command_size++] = chunk[index];
1021 }
1022 }
1023 return 0;
1024}
1025
1026/** @brief Capture, filter, analyze, and report audio until stopped.
1027 * @return 0 for orderly stop or -1 for unrecoverable ALSA or bounds failure.
1028 * @details ALSA recovery handles transient overruns. Each reporting window produces
1029 * band RMS, strongest tone, contrast, and homing trend. */
1030static int run_meter(snd_pcm_t *pcm, const struct options *options)
1031{
1032 snd_pcm_uframes_t buffer_frames;
1033 snd_pcm_uframes_t period_frames;
1034 struct biquad high_pass[FILTER_SECTIONS_PER_EDGE];
1035 struct biquad low_pass[FILTER_SECTIONS_PER_EDGE];
1036 struct tone_bin tone_bins[TONE_BIN_COUNT];
1037 struct homing_state homing = {0};
1038 uint64_t interval_frames =
1040 uint64_t accumulated_frames = 0U;
1041 double sum_squares = 0.0;
1042 bool window_clipped = false;
1043 bool window_timing_valid = true;
1044 uint64_t window_sequence = 0;
1045
1046 if (snd_pcm_get_params(pcm, &buffer_frames, &period_frames) < 0 ||
1047 period_frames == 0U || period_frames > MAX_PERIOD_FRAMES) {
1048 fprintf(stderr, "Cannot determine ALSA capture period size.\n");
1049 return -1;
1050 }
1051 if (interval_frames == 0U || interval_frames > MAX_INTERVAL_FRAMES) {
1052 fprintf(stderr, "Analysis interval exceeds the fixed workspace.\n");
1053 return -1;
1054 }
1055 /* The Hann equation uses half-scale/half-offset and a full 2*pi cycle. These
1056 * mathematical coefficients stay literal; detector policy lives in named constants. */
1057 for (uint64_t index = 0; index < interval_frames; ++index) {
1058 analysis_window[index] = interval_frames > 1U
1059 ? 0.5 - 0.5 * cos(2.0 * PI * (double)index /
1060 (double)(interval_frames - 1U))
1061 : 1.0;
1062 }
1063
1064 configure_biquad(&high_pass[0], options->low_cut_hz, options->rate, true);
1065 configure_biquad(&high_pass[1], options->low_cut_hz, options->rate, true);
1066 configure_biquad(&low_pass[0], options->high_cut_hz, options->rate, false);
1067 configure_biquad(&low_pass[1], options->high_cut_hz, options->rate, false);
1068 configure_tone_bins(tone_bins, options);
1069 if (snd_pcm_nonblock(pcm, 1) < 0) { errno = EIO; return -1; }
1070 uint64_t last_progress_ms = monotonic_ms();
1071 if (!last_progress_ms) { errno = EIO; return -1; }
1072 while (keep_running) {
1073 if (options->server && poll_server_stdin()) {
1074 break;
1075 }
1076 const uint64_t now_ms = monotonic_ms();
1077 if (!now_ms || now_ms < last_progress_ms || now_ms - last_progress_ms >= CAPTURE_STALL_TIMEOUT_MS) {
1078 fprintf(stderr, "Capture made no progress within its deadline.\n");
1079 errno = ETIMEDOUT;
1080 return -1;
1081 }
1082 snd_pcm_sframes_t frames_read = snd_pcm_readi(pcm, capture_samples, period_frames);
1083 snd_pcm_sframes_t frame;
1084
1085 if (!keep_running) break;
1086 const uint64_t completed_ms = monotonic_ms();
1087 if (!completed_ms || completed_ms < last_progress_ms || completed_ms - last_progress_ms >= CAPTURE_STALL_TIMEOUT_MS) {
1088 errno = ETIMEDOUT;
1089 return -1;
1090 }
1091 const int remaining_ms = (int)(CAPTURE_STALL_TIMEOUT_MS - (completed_ms - last_progress_ms));
1093 if (frames_read == 0 || frames_read == -EAGAIN || frames_read == -EINTR) {
1094 const int ready = snd_pcm_wait(pcm, wait_ms);
1095 if (ready >= 0 || ready == -EINTR || ready == -EAGAIN) continue;
1096 frames_read = ready;
1097 }
1098 if (frames_read < 0) {
1099 int recovery;
1100 if (frames_read == -ESTRPIPE) {
1101 recovery = snd_pcm_resume(pcm);
1102 if (recovery == -EAGAIN) {
1103 if (poll(NULL, 0, wait_ms) < 0 && errno != EINTR) return -1;
1104 continue;
1105 }
1106 if (recovery < 0) recovery = snd_pcm_prepare(pcm);
1107 } else recovery = snd_pcm_recover(pcm, (int)frames_read, 1);
1108 if (recovery < 0) {
1109 fprintf(stderr, "\nCapture failed: %s\n", snd_strerror(recovery));
1110 if (options->server) {
1111 printf("EARCAM_ERROR capture %s\n", snd_strerror(recovery));
1112 fflush(stdout);
1113 }
1114 return -1;
1115 }
1116 /* An overrun breaks window continuity and pose timing. Discard accumulated
1117 * spectral/envelope evidence rather than joining audio across that gap. */
1118 accumulated_frames = 0;
1120 sum_squares = 0;
1121 window_clipped = false;
1122 window_timing_valid = false;
1123 homing = (struct homing_state){0};
1124 configure_tone_bins(tone_bins, options);
1125 continue;
1126 }
1127
1128 if ((snd_pcm_uframes_t)frames_read > period_frames) { errno = EOVERFLOW; return -1; }
1129 last_progress_ms = completed_ms;
1130 snd_pcm_uframes_t available_frames = 0;
1131 snd_htimestamp_t timestamp = {0};
1132 uint64_t read_end_us = 0;
1133 if (capture_timestamps && snd_pcm_htimestamp(pcm, &available_frames, &timestamp) == 0
1134 && timestamp.tv_sec > 0 && timestamp.tv_nsec >= 0 && timestamp.tv_nsec < NANOSECONDS_PER_SECOND
1135 && available_frames <= buffer_frames) {
1136 const uint64_t hardware_us = (uint64_t)timestamp.tv_sec * MICROSECONDS_PER_SECOND
1137 + (uint64_t)timestamp.tv_nsec / NANOSECONDS_PER_MICROSECOND;
1138 read_end_us = audio_read_end_us(hardware_us, available_frames, options->rate);
1139 }
1140 if (options->onnx) {
1141 const uint64_t error_us = ((uint64_t)period_frames * MICROSECONDS_PER_SECOND + options->rate - 1) / options->rate + 1;
1142 ear_inference_push(capture_samples, (size_t)frames_read, read_end_us, error_us);
1143 struct ear_inference_result classified;
1144 if (ear_inference_take(&classified)) {
1145 if (options->server) emit_classifier_sample(&classified, options);
1146 else printf("class=%u score=%.6f alarm=%u pcm_rms=%.2f dBFS\n", classified.category,
1147 classified.score, classified.alarm ? 1U : 0U, classified.level_dbfs);
1148 }
1149 continue;
1150 }
1151 window_timing_valid = (accumulated_frames == 0 || window_timing_valid) && read_end_us != 0;
1152
1153 for (frame = 0; frame < frames_read; ++frame) {
1154 int16_t raw = capture_samples[frame];
1155 double sample = (double)raw / PCM_S16_FULL_SCALE;
1156 if (raw >= CLIP_THRESHOLD || raw <= -CLIP_THRESHOLD) {
1157 window_clipped = true;
1158 }
1159
1160 sample = apply_biquad(&high_pass[0], sample);
1161 sample = apply_biquad(&high_pass[1], sample);
1162 sample = apply_biquad(&low_pass[0], sample);
1163 sample = apply_biquad(&low_pass[1], sample);
1164 update_tone_bins(tone_bins, sample, analysis_window[accumulated_frames]);
1165 sum_squares += sample * sample;
1166 ++accumulated_frames;
1167
1168 if (accumulated_frames == interval_frames) {
1169 double band_db = amplitude_to_db(
1170 sqrt(sum_squares / (double)accumulated_frames));
1171 double frequency_hz = 0.0;
1172 double tone_db = strongest_tone_db(tone_bins, accumulated_frames,
1173 &frequency_hz);
1174 double contrast_db = tone_db - band_db;
1175 double trend_db;
1176 /* A level gate alone accepts broadband aircraft noise. Requiring bin
1177 * contrast adds tone-like evidence, but remains a heuristic alarm flag. */
1178 bool alarm_present = tone_db >= options->min_level_dbfs &&
1179 contrast_db >= TONE_CONTRAST_THRESHOLD_DB;
1180 const char *direction = update_homing_state(
1181 &homing, tone_db, alarm_present, options, &trend_db);
1182
1183 if (options->server) {
1184 uint64_t end_us = window_timing_valid
1185 ? audio_read_end_us(read_end_us, (uint64_t)(frames_read - frame - 1), options->rate) : 0;
1186 /* A reporting boundary may lie inside this read. Subtract its remaining
1187 * tail too; otherwise all windows in a read would get the same end time.
1188 * Missing hardware timing stays zero for the parent's explicit fallback. */
1189 const uint64_t duration_us = interval_frames * MICROSECONDS_PER_SECOND / options->rate;
1190 uint64_t begin_us = end_us > duration_us ? end_us - duration_us : 0;
1191 if (!begin_us) end_us = 0;
1192 const uint64_t error_us = ((uint64_t)period_frames * MICROSECONDS_PER_SECOND + options->rate - 1) / options->rate + 1;
1193 emit_server_sample(monotonic_ms(), tone_db, frequency_hz, contrast_db,
1194 trend_db, homing.envelope_db, alarm_present,
1195 window_clipped, options, begin_us, end_us, error_us, ++window_sequence);
1196 } else {
1197 display_homing(tone_db, frequency_hz, contrast_db, alarm_present,
1198 direction, trend_db, &homing, options);
1199 }
1200 accumulated_frames = 0U;
1201 sum_squares = 0.0;
1202 window_clipped = false;
1203 window_timing_valid = read_end_us != 0;
1204 }
1205 }
1206 }
1207 if (!options->server) {
1208 putchar('\n');
1209 }
1210 return 0;
1211}
1212
1213/** @brief Configure EARcam, optionally self-test it, then run the ALSA meter.
1214 * @return EXIT_SUCCESS on normal termination, EXIT_FAILURE on configuration/capture errors. */
1215int main(int argc, char **argv)
1216{
1217 struct options options = {
1218 .device = DEFAULT_DEVICE,
1219 .rate = DEFAULT_RATE,
1220 .interval_ms = DEFAULT_INTERVAL_MS,
1221 .low_cut_hz = DEFAULT_LOW_CUT_HZ,
1222 .high_cut_hz = DEFAULT_HIGH_CUT_HZ,
1223 .min_level_dbfs = DEFAULT_MIN_LEVEL_DBFS,
1224 .calibration_db = 0.0,
1225 .calibrated = false,
1226 .self_test = false,
1227 .server = false
1228 };
1229 snd_pcm_t *pcm = NULL;
1230 struct sigaction action;
1231 int result;
1232
1233 result = parse_options(argc, argv, &options);
1234 if (result != 0) {
1235 return result > 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1236 }
1237 if (options.self_test) {
1238 return run_self_test(&options) == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1239 }
1240 char settings_path[INFERENCE_PATH_CAPACITY], inference_error[2048] = {0};
1241 if (!options.settings && inference_settings_find("earcam", "ear_cam", settings_path, sizeof(settings_path)))
1242 options.settings = settings_path;
1244 inference_error, sizeof(inference_error))) {
1245 fprintf(stderr, "earcam: %s\n", inference_error);
1246 return EXIT_FAILURE;
1247 }
1248 if (atexit(ear_inference_stop)) { ear_inference_stop(); return EXIT_FAILURE; }
1249 if (options.check_model) {
1250 puts(options.onnx ? "earcam model ready adapter=ear_pcm_classifier_v1" : "earcam native detector ready");
1251 return EXIT_SUCCESS;
1252 }
1253 if (options.audio_file) return options.onnx ? ear_inference_file(options.audio_file) : EXIT_FAILURE;
1254 if (options.onnx && !ear_inference_start(inference_error, sizeof(inference_error))) {
1255 fprintf(stderr, "earcam: %s\n", inference_error);
1256 return EXIT_FAILURE;
1257 }
1258
1259 memset(&action, 0, sizeof(action));
1260 action.sa_handler = handle_signal;
1261 sigemptyset(&action.sa_mask);
1262 sigaction(SIGINT, &action, NULL);
1263 sigaction(SIGTERM, &action, NULL);
1264 if (options.server) {
1265 signal(SIGPIPE, SIG_IGN);
1266 int flags = fcntl(STDOUT_FILENO, F_GETFL);
1267 if (flags >= 0) {
1268 fcntl(STDOUT_FILENO, F_SETFL, flags | O_NONBLOCK);
1269 }
1270 flags = fcntl(STDIN_FILENO, F_GETFL);
1271 if (flags >= 0) {
1272 fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
1273 }
1274 }
1275
1276 char auto_device[AUTO_DEVICE_NAME_MAX];
1277 if (strcmp(options.device, "auto") == 0) {
1278 if (find_usb_capture_device(auto_device, sizeof(auto_device)) != 0) {
1279 fprintf(stderr, "No USB audio capture device found (use --device to select one).\n");
1280 if (options.server) {
1281 printf("EARCAM_ERROR open no USB capture device\n");
1282 fflush(stdout);
1283 }
1284 return EXIT_FAILURE;
1285 }
1286 options.device = auto_device;
1287 }
1288
1289 result = snd_pcm_open(&pcm, options.device, SND_PCM_STREAM_CAPTURE, 0);
1290 if (result < 0) {
1291 fprintf(stderr, "Cannot open ALSA capture device '%s': %s\n",
1292 options.device, snd_strerror(result));
1293 if (options.server) {
1294 printf("EARCAM_ERROR open %s\n", snd_strerror(result));
1295 fflush(stdout);
1296 }
1297 return EXIT_FAILURE;
1298 }
1299
1301 if (result < 0) {
1302 fprintf(stderr, "Cannot configure '%s' for %u Hz mono capture: %s\n",
1303 options.device, options.rate, snd_strerror(result));
1304 if (options.server) {
1305 printf("EARCAM_ERROR configure %s\n", snd_strerror(result));
1306 fflush(stdout);
1307 }
1308 snd_pcm_close(pcm);
1309 return EXIT_FAILURE;
1310 }
1311
1312 if (options.server) {
1313 printf("EARCAM_READY device=%s rate=%u interval_ms=%u low=%.0f high=%.0f cal=%d\n",
1316 fflush(stdout);
1317 } else {
1318 printf("earcam motionSCOUT: device=%s, rate=%u Hz, search=%.0f..%.0f Hz, "
1319 "update=%u ms, output=%s\n",
1322 options.calibrated ? "calibrated dB SPL" : "uncalibrated dBFS");
1323 printf("Press Ctrl+C to stop.\n");
1324 }
1325
1326 result = run_meter(pcm, &options);
1327 snd_pcm_drop(pcm);
1328 snd_pcm_close(pcm);
1329 if (options.server) {
1330 printf("EARCAM_STOPPED dropped=%lu\n", server_dropped_lines);
1331 fflush(stdout);
1332 }
1333 return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
1334}
static void wait_ms(int milliseconds)
Wait until a short polling interval elapses.
static unsigned capacity[COVERAGE_CAMERAS]
int descriptor
Definition chdk_pipe.c:142
static unsigned remaining_ms(const struct transport *transport)
Compute the next USB call's timeout within the operation deadline.
Definition chdkbridge.c:156
void ear_inference_stop(void)
Request termination, join the classifier and release its model; repeat calls are harmless.
bool ear_inference_start(char *error, size_t capacity)
Start the sole classifier thread after successful ONNX configuration.
bool ear_inference_take(struct ear_inference_result *result)
Consume at most one completed original-window result without blocking capture.
static bool ready
int ear_inference_file(const char *filename)
Classify exact whole windows from a regular little-endian signed-16 mono PCM file.
bool ear_inference_configure(const char *settings_path, unsigned rate, bool *enabled, char *error, size_t capacity)
Select the explicit detector and qualify an ONNX PCM contract before capture starts.
void ear_inference_push(const int16_t *samples, size_t count, uint64_t end_us, uint64_t error_us)
Supply capture samples without waiting for model execution or a busy model mailbox.
void ear_inference_discontinuity(void)
Invalidate queued/completed evidence after capture continuity breaks, including in-flight generations...
Bounded PCM classification without allowing model latency to stall ALSA capture.
#define HOMING_ACQUISITION_WINDOWS
Definition earcam.c:113
static int parse_options(int argc, char **argv, struct options *options)
Parse and cross-validate EARcam command-line configuration.
Definition earcam.c:437
#define SOURCE_LEVEL_DB_SPL
Definition earcam.c:87
static int run_meter(snd_pcm_t *pcm, const struct options *options)
Capture, filter, analyze, and report audio until stopped.
Definition earcam.c:1030
#define DEFAULT_LOW_CUT_HZ
Definition earcam.c:75
#define DEFAULT_HIGH_CUT_HZ
Definition earcam.c:76
#define TEST_RECEDE_START_DB
Definition earcam.c:129
static void update_tone_bins(struct tone_bin *bins, double sample, double window)
Feed one windowed, band-passed sample into every Goertzel recurrence.
Definition earcam.c:640
#define PCM_S16_FULL_SCALE
Definition earcam.c:104
#define TEST_TIMESTAMP_US
Definition earcam.c:115
static union alsa_object_storage software_params_storage
Definition earcam.c:192
static int find_usb_capture_device(char *name, size_t name_size)
Discover the first USB ALSA card offering a capture PCM.
Definition earcam.c:368
#define TEST_CONTRAST_MAX_DB
Definition earcam.c:126
#define ENVELOPE_RELEASE_DB_PER_SECOND
Definition earcam.c:84
#define FILTER_SECTIONS_PER_EDGE
Definition earcam.c:103
static int parse_unsigned(const char *text, unsigned int minimum, unsigned int maximum, unsigned int *value)
Parse a bounded unsigned command-line value.
Definition earcam.c:344
static double analysis_window[MAX_INTERVAL_FRAMES]
Definition earcam.c:196
static uint64_t audio_read_end_us(uint64_t hardware_us, uint64_t unread_frames, unsigned int rate)
Subtract unread PCM duration from a monotonic ALSA timestamp.
Definition earcam.c:205
#define MAX_CUTOFF_HZ
Definition earcam.c:93
static int normalize_long_options(int argc, char *const argv[], char *normalized[], size_t capacity, const struct option_alias aliases[], size_t alias_count)
Normalize –name value and –name=value into bounded getopt arguments.
Definition earcam.c:224
static void emit_classifier_sample(const struct ear_inference_result *result, const struct options *options)
Emit one classifier window to the server's nonblocking output.
Definition earcam.c:929
int main(int argc, char **argv)
Configure EARcam, optionally self-test it, then run the ALSA meter.
Definition earcam.c:1215
#define NANOSECONDS_PER_MICROSECOND
Definition earcam.c:61
#define TREND_THRESHOLD_DB
Definition earcam.c:83
#define TEST_TREND_STEP_DB
Definition earcam.c:130
static void display_homing(double level_db, double frequency_hz, double contrast_db, bool alarm_present, const char *direction, double trend_db, const struct homing_state *state, const struct options *options)
Render one human-facing measurement line for bench use.
Definition earcam.c:815
#define TEST_INTERFERENCE_AMPLITUDE
Definition earcam.c:123
#define AUTO_DEVICE_NAME_MAX
Definition earcam.c:50
#define DEFAULT_INTERVAL_MS
Definition earcam.c:52
#define TONE_BIN_COUNT
Definition earcam.c:81
static void configure_tone_bins(struct tone_bin *bins, const struct options *options)
Initialize evenly spaced Goertzel bins across the selected search band.
Definition earcam.c:617
static unsigned long server_dropped_lines
Definition earcam.c:922
#define PI
Definition earcam.c:90
#define BUTTERWORTH_Q
Definition earcam.c:102
#define HOMING_SLOW_TIME_CONSTANT_S
Definition earcam.c:112
static const char * update_homing_state(struct homing_state *state, double tone_db, bool alarm_present, const struct options *options, double *trend_db)
Update envelope and fast/slow trend estimates for operator guidance.
Definition earcam.c:682
#define CONTROL_DEVICE_NAME_CAPACITY
Definition earcam.c:96
#define NANOSECONDS_PER_SECOND
Definition earcam.c:59
#define MIN_RATE_HZ
Definition earcam.c:53
static volatile sig_atomic_t keep_running
Definition earcam.c:181
#define CLIP_THRESHOLD
Definition earcam.c:89
#define MAX_PERIOD_FRAMES
Definition earcam.c:70
static void configure_biquad(struct biquad *filter, double cutoff_hz, unsigned int sample_rate, bool high_pass)
Configure a second-order Butterworth high- or low-pass section.
Definition earcam.c:554
#define MIN_INTERVAL_MS
Definition earcam.c:54
#define TEST_INTERFERENCE_HZ
Definition earcam.c:121
#define DEFAULT_RATE
Definition earcam.c:51
#define DB_LOG_BASE
Definition earcam.c:107
#define METER_WIDTH
Definition earcam.c:80
static int parse_double_value(const char *text, double minimum, double maximum, double *value)
Parse a finite bounded floating-point command-line value.
Definition earcam.c:417
#define CAPTURE_MONO_CHANNELS
Definition earcam.c:66
#define DEFAULT_DEVICE
Definition earcam.c:49
static void emit_server_sample(uint64_t timestamp_ms, double level_db, double frequency_hz, double contrast_db, double trend_db, double envelope_db, bool alarm_present, bool clipped, const struct options *options, uint64_t begin_us, uint64_t end_us, uint64_t error_us, uint64_t sequence)
Emit one self-describing USHER server sample without blocking capture.
Definition earcam.c:948
#define MILLISECONDS_PER_SECOND_F
Definition earcam.c:62
#define MICROSECONDS_PER_SECOND
Definition earcam.c:58
#define HOMING_FAST_TIME_CONSTANT_S
Definition earcam.c:111
#define TEST_UNDERFLOW_TIMESTAMP_US
Definition earcam.c:116
#define SERVER_COMMAND_CAPACITY
Definition earcam.c:99
#define MAX_INTERVAL_FRAMES
Definition earcam.c:69
static bool capture_timestamps
Definition earcam.c:197
#define TEST_TARGET_HZ
Definition earcam.c:120
#define NANOSECONDS_PER_MILLISECOND
Definition earcam.c:60
#define MIN_CALIBRATION_DB
Definition earcam.c:94
#define TONE_CONTRAST_THRESHOLD_DB
Definition earcam.c:82
static void analyze_test_window(struct tone_bin *bins, const struct options *options, double target_amplitude, double interference_amplitude, double *tone_db, double *contrast_db)
Analyze a deterministic synthetic tone mixture for self-test coverage.
Definition earcam.c:726
static uint64_t monotonic_ms(void)
Return monotonic milliseconds for correlating samples without wall-clock jumps.
Definition earcam.c:302
#define CAPTURE_BUFFERS_PER_SECOND
Definition earcam.c:65
#define SHORT_OPTION_STORAGE
Definition earcam.c:97
#define TEST_UNREAD_FRAMES
Definition earcam.c:117
static int run_self_test(const struct options *options)
Verify selectivity and trend classification without ALSA hardware.
Definition earcam.c:763
static void print_usage(FILE *stream, const char *program)
Print command-line help or version-led usage text.
Definition earcam.c:314
#define SERVER_SAMPLE_LINE_CAPACITY
Definition earcam.c:98
static union alsa_object_storage card_info_storage
Definition earcam.c:189
#define TEST_APPROACH_START_DB
Definition earcam.c:128
#define EARCAM_MAX_PARSED_ARGUMENTS
Definition earcam.c:74
static double amplitude_to_db(double amplitude)
Convert a linear amplitude to bounded dBFS.
Definition earcam.c:606
#define MAX_RATE
Definition earcam.c:55
#define CAPTURE_WAIT_MS
Definition earcam.c:67
#define TEST_EXPECTED_READ_END_US
Definition earcam.c:119
#define AMPLITUDE_FLOOR
Definition earcam.c:105
#define TEST_TONE_MAX_DB
Definition earcam.c:125
#define CAPTURE_STALL_TIMEOUT_MS
Definition earcam.c:68
static int16_t capture_samples[MAX_PERIOD_FRAMES]
Definition earcam.c:195
static union alsa_object_storage pcm_info_storage
Definition earcam.c:190
#define EARCAM_MAX_ARGUMENTS
Definition earcam.c:73
#define ALSA_OBJECT_CAPACITY
Definition earcam.c:72
#define MAX_CALIBRATION_DB
Definition earcam.c:95
#define TEST_TARGET_AMPLITUDE
Definition earcam.c:122
#define CAPTURE_PERIODS_PER_SECOND
Definition earcam.c:64
#define DB_FLOOR
Definition earcam.c:79
static int configure_capture(snd_pcm_t *pcm, unsigned int sample_rate)
Configure mono signed-16 ALSA capture with low-latency period sizes.
Definition earcam.c:853
#define SOURCE_REFERENCE_METERS
Definition earcam.c:88
static double apply_biquad(struct biquad *filter, double input)
Filter one PCM sample while retaining the section delay state.
Definition earcam.c:591
#define HANN_TONE_AMPLITUDE_SCALE
Definition earcam.c:109
#define DEFAULT_MIN_LEVEL_DBFS
Definition earcam.c:78
#define MAX_INTERVAL_MS
Definition earcam.c:56
#define AMPLITUDE_DB_PER_DECADE
Definition earcam.c:106
static int poll_server_stdin(void)
Consume non-blocking STOP/QUIT commands from USHER.
Definition earcam.c:991
#define SERVER_READ_CHUNK_CAPACITY
Definition earcam.c:100
#define TEST_TREND_WINDOWS
Definition earcam.c:127
#define TEST_RATE_HZ
Definition earcam.c:118
static union alsa_object_storage hardware_params_storage
Definition earcam.c:191
#define MILLISECONDS_PER_SECOND
Definition earcam.c:57
static void handle_signal(int signal_number)
Request orderly capture-loop termination from a signal handler.
Definition earcam.c:294
static double strongest_tone_db(struct tone_bin *bins, uint64_t sample_count, double *frequency_hz)
Extract and reset the strongest Goertzel-bin power estimate.
Definition earcam.c:657
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.
Shared application_settings.ini discovery with module-owned extra keys.
#define INFERENCE_PATH_CAPACITY
jmp_buf recovery
Definition lwir_image.c:61
uint8_t frame[LWIR_MAX_FRAME_BYTES]
Definition lwir_mock.c:58
Compile-time EARcam version and source-revision identity strings.
#define EARCAM_BUILD_VERSION
Definition version.h:29
static size_t count
Definition pose_log.c:79
static FILE * output
Definition pose_log.c:77
Normalized biquad coefficients and transposed-direct-form-II delay state.
Definition earcam.c:153
double a1
Definition earcam.c:157
bool enabled
Definition earcam.c:161
double b1
Definition earcam.c:155
double b2
Definition earcam.c:156
double a2
Definition earcam.c:158
double z2
Definition earcam.c:160
double b0
Definition earcam.c:154
double z1
Definition earcam.c:159
One classified audio window; probability and measured level are different evidence.
Peak hold and fast/slow averages; direction is guidance, not a bearing measurement.
Definition earcam.c:173
double slow_db
Definition earcam.c:176
unsigned int alarm_windows
Definition earcam.c:177
double fast_db
Definition earcam.c:175
double envelope_db
Definition earcam.c:174
bool initialized
Definition earcam.c:178
Long-to-short option mapping; borrowed values are passed to standard getopt.
Definition earcam.c:213
char option[SHORT_OPTION_STORAGE]
Definition earcam.c:215
const char * name
Definition earcam.c:214
bool requires_argument
Definition earcam.c:216
Validated capture and reporting policy, fixed before the sample loop.
Definition earcam.c:137
double low_cut_hz
Definition earcam.c:141
bool server
Definition earcam.c:147
double calibration_db
Definition earcam.c:144
bool calibrated
Definition earcam.c:145
bool check_model
Definition earcam.c:149
unsigned int rate
Definition earcam.c:139
const char * settings
Definition earcam.c:148
double min_level_dbfs
Definition earcam.c:143
bool self_test
Definition earcam.c:146
unsigned int interval_ms
Definition earcam.c:140
const char * device
Definition earcam.c:138
bool onnx
Definition earcam.c:149
double high_cut_hz
Definition earcam.c:142
const char * audio_file
Definition earcam.c:148
One Goertzel recurrence; state resets at each analysis-window boundary.
Definition earcam.c:165
double second
Definition earcam.c:168
double frequency_hz
Definition earcam.c:169
double coefficient
Definition earcam.c:166
double first
Definition earcam.c:167
Aligned bounded storage for an opaque ALSA object after its sizeof guard succeeds.
Definition earcam.c:184
unsigned char bytes[ALSA_OBJECT_CAPACITY]
Definition earcam.c:186
max_align_t alignment
Definition earcam.c:185
struct usher_control_result result
Definition usher.c:377