From 192674a81876a0096db2cf322c24346b4eba8837 Mon Sep 17 00:00:00 2001
From: Squatch Stack <321440025+squatchlr@users.noreply.github.com>
Date: Fri, 16 Oct 2026 12:11:13 +0000
Subject: [PATCH] feat(coreaudio): macOS tuner and tone on CoreAudio, no JACK
make live builds hosts/coreaudio on macOS and hosts/jack elsewhere (LIVE_BACKEND overrides), so squatch-tuner-live and squatch-tone start on a Mac with nothing installed. They take the JACK host's options and print its JSON lines, plus --device NAME and --list-devices, and link system frameworks only.
The release workflow's cli-macos job no longer installs JACK, fails if a binary links anything outside /System and /usr/lib, and signs with the audio-input entitlement instead of disabling library validation. CI builds the CoreAudio host on macOS for every push, and make test runs test_host_audio, which sends a test tone through the host's callback body with no audio device.
---
.github/release/cli.entitlements | 4 +-
.github/workflows/ci.yml | 24 +++
.github/workflows/release.yml | 17 +-
EXPORTED | 21 +-
Makefile | 39 +++-
README.md | 25 ++-
hosts/common/host_clock.hpp | 55 +++++
hosts/common/tone_gen.hpp | 37 ++++
hosts/common/tuner_host.hpp | 222 ++++++++++++++++++++
hosts/common/tuner_publisher.hpp | 106 ++++++++++
hosts/coreaudio/Info.plist | 14 ++
hosts/coreaudio/audio_chunks.hpp | 74 +++++++
hosts/coreaudio/coreaudio_session.hpp | 217 ++++++++++++++++++++
hosts/coreaudio/tone.cpp | 139 +++++++++++++
hosts/coreaudio/tuner_live.cpp | 132 ++++++++++++
hosts/coreaudio/tuner_render.hpp | 43 ++++
hosts/jack/jack_session.hpp | 49 +----
hosts/jack/tone.cpp | 26 +--
hosts/jack/tuner_live.cpp | 278 +++-----------------------
hosts/tests/test_host_audio.cpp | 264 ++++++++++++++++++++++++
tools/export-public | 6 +
21 files changed, 1455 insertions(+), 337 deletions(-)
create mode 100644 hosts/common/host_clock.hpp
create mode 100644 hosts/common/tone_gen.hpp
create mode 100644 hosts/common/tuner_host.hpp
create mode 100644 hosts/common/tuner_publisher.hpp
create mode 100644 hosts/coreaudio/Info.plist
create mode 100644 hosts/coreaudio/audio_chunks.hpp
create mode 100644 hosts/coreaudio/coreaudio_session.hpp
create mode 100644 hosts/coreaudio/tone.cpp
create mode 100644 hosts/coreaudio/tuner_live.cpp
create mode 100644 hosts/coreaudio/tuner_render.hpp
create mode 100644 hosts/tests/test_host_audio.cpp
diff --git a/.github/release/cli.entitlements b/.github/release/cli.entitlements
index 3f9e724..66bf28b 100644
--- a/.github/release/cli.entitlements
+++ b/.github/release/cli.entitlements
@@ -2,8 +2,8 @@
-
- com.apple.security.cs.disable-library-validation
+
+ com.apple.security.device.audio-input
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0cf6591..faa4879 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -31,3 +31,27 @@ jobs:
make test CXX=clang++
- name: The published tuner.wasm reads the test tones
run: node hosts/wasm/test/core.test.mjs docs/tuner.wasm
+
+ # The CoreAudio host only builds on a Mac, so build it on every push and pull request: a break there would
+ # otherwise show up first in a release. Only system libraries may be linked. No audio input is used.
+ macos:
+ runs-on: macos-15
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - name: Build the live tuner and tone on CoreAudio
+ run: make live CXX=clang++
+ - name: Only system libraries are linked
+ run: |
+ set -euo pipefail
+ for b in build/squatch-tuner-live build/squatch-tone; do
+ otool -L "$b"
+ bad=$(otool -L "$b" | tail -n +2 | awk '{print $1}' | grep -Ev '^(/System/|/usr/lib/)' || true)
+ if [ -n "$bad" ]; then echo "::error::$b links a library that is not part of macOS: $bad"; exit 1; fi
+ done
+ - name: Lists the audio devices
+ run: |
+ set -euo pipefail
+ build/squatch-tuner-live --list-devices
+ build/squatch-tone --list-devices
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 4b39bcd..d5b9a60 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -116,13 +116,16 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: JACK (Homebrew; the CLI needs it installed to run)
- run: brew install jack
- - name: Build for Apple silicon, build paths mapped out (ad-hoc signed by the linker)
+ - name: Build for Apple silicon on CoreAudio, build paths mapped out (ad-hoc signed by the linker)
run: |
set -euo pipefail
- jp=$(brew --prefix jack)
- make live CXX=clang++ CXXFLAGS="-std=c++17 -O3 -Wall -Wextra -Wpedantic -Wshadow -Iinclude -I$jp/include -L$jp/lib -ffile-prefix-map=$PWD=."
+ make live CXX=clang++ CXXFLAGS="-std=c++17 -O3 -Wall -Wextra -Wpedantic -Wshadow -Iinclude -ffile-prefix-map=$PWD=."
+ # The macOS CLI needs nothing installed: only system libraries may be linked.
+ for b in build/squatch-tuner-live build/squatch-tone; do
+ otool -L "$b"
+ bad=$(otool -L "$b" | tail -n +2 | awk '{print $1}' | grep -Ev '^(/System/|/usr/lib/)' || true)
+ if [ -n "$bad" ]; then echo "::error::$b links a library that is not part of macOS: $bad"; exit 1; fi
+ done
python3 tools/release-scan build/squatch-tuner-live build/squatch-tone
lipo -archs build/squatch-tuner-live
codesign --verify --strict build/squatch-tuner-live
@@ -171,7 +174,7 @@ jobs:
run: |
set -euo pipefail
mkdir stage && ditto -x -k cli-macos-unsigned.zip stage
- # Homebrew's libjack is not signed by us, so the hardened runtime must allow loading it.
+ # The hardened runtime needs the audio-input entitlement for the tuner to hear a microphone.
tools/release-signing sign --entitlements .github/release/cli.entitlements stage/squatch-tuner-live stage/squatch-tone
mkdir out
ditto -c -k stage "out/squatch-tuner-live-$TAG-macos-arm64.zip"
@@ -231,7 +234,7 @@ jobs:
- \`squatch-tuner-$TAG-source.tar.gz\`: the source.
- \`squatch-tuner-web-$TAG.zip\`: the browser demo, the same files as the published demo page.
- - \`squatch-tuner-live-$TAG-linux-x86_64.tar.gz\`, \`-linux-arm64.tar.gz\`, \`squatch-tuner-live-$TAG-macos-arm64*.zip\`: the headless tuner behind a JACK input, with \`squatch-tone\`, an exact test tone. They need a running JACK server.
+ - \`squatch-tuner-live-$TAG-linux-x86_64.tar.gz\`, \`-linux-arm64.tar.gz\`, \`squatch-tuner-live-$TAG-macos-arm64*.zip\`: the headless tuner, with \`squatch-tone\`, an exact test tone. On Linux they need a running JACK server; the macOS build uses CoreAudio and needs nothing installed.
$status
diff --git a/EXPORTED b/EXPORTED
index 37f9704..fffffcb 100644
--- a/EXPORTED
+++ b/EXPORTED
@@ -1,4 +1,4 @@
-# Written by tools/export-public from squatch-dsp at 5c5c9d9c27e037652f018974e14c57b11768053e (hosts/jack/jack_session.hpp only).
+# Written by tools/export-public from squatch-dsp at 4ce2afb79bed94dcfadd5e18afb4fa51cf8bd853.
# Do not edit these files here: change them upstream and export again (see the README).
de9ec875a3df8d6488afd6893577bd995198373ca2bd2152887dcc5008504dc2 RESULTS.md
94b7020753515c516163468fd2b55406d1701c7ba032a8683073f6216598a8cc bench/algos.hpp
@@ -36,12 +36,23 @@ c44ba12f19a44ba3c0b782f6a1564699f0ccd00275450e47c4c0f7221de8f1d2 docs/tuner.was
6b22cbbde838e4c52af1308374a0a99cb35ee80e0c3a140495ecba564383dadd docs/worklet.js
1418fa07dbbc8cacd97726623b64417bff884004726efd04226b9f264c28298c hosts/common/display.hpp
2a945c68d96879b468bcfe0e1828ef115e69ad6c0c9cc2d398c65732e25c8dcf hosts/common/hold.hpp
+67d2581b74bb60130369dfd7c36c261c9265d1fcc6489b3c8d75375e1f84f839 hosts/common/host_clock.hpp
b3665ead3181c6617fb86481539f3bcfc5d7620844488957daddfb9fbf507512 hosts/common/ir_file.hpp
3d9b651e6176dbb3897a8cbc4febcd4e461602f5cba279e9e95a095337980a17 hosts/common/latest.hpp
+134a449bd05bd627bc9962a044468e9d1416d96e8268f14ee0374ae8142f94ba hosts/common/tone_gen.hpp
a02486cb10744347717cd51882c7ad6959139443c276532ffc69b454d949d5d6 hosts/common/tuner_frames.hpp
-bfd7189893f32863cfdcdae2ca0a44638fb0893b7211aa6f400644f0336e5f40 hosts/jack/jack_session.hpp
-1b1ac06435467c26a930cb8a9f281586efa9996c76675ad114715b86e9855cef hosts/jack/tone.cpp
-52aa713ec159261e2e2b0dd329a8aa55585cb2a7e098a3c80ade9f8f6350f5e9 hosts/jack/tuner_live.cpp
+1070f089a30dcbc128684a5650d04d82c4c496033f20ac7712b491dac7e32cc3 hosts/common/tuner_host.hpp
+01aba5f2559e193676a3e4811d5f5d5a9f30d47f5ec81a7db972b9d60c561104 hosts/common/tuner_publisher.hpp
+894ad767f4daabe66df14c6104915dacfbbbb7fe0d8e71a35719f8eb2a1419c7 hosts/coreaudio/Info.plist
+0d40b74aab99e5694b923e498c7ccda1e0cafbdfa169eff5186fe78205374089 hosts/coreaudio/audio_chunks.hpp
+52bb018f635163ae0d81da359efc8fc94cff1c054adf8d56339bcd8988b3aad8 hosts/coreaudio/coreaudio_session.hpp
+3b24d9b4cdac4d6d3e280a68b0c424bad2d1245df1efea29c99d5f20501ccfe6 hosts/coreaudio/tone.cpp
+8160e00f87175633b1b217db65c4a48f89d7c5badb1bffd7fbfed66b46f6d3f2 hosts/coreaudio/tuner_live.cpp
+1f1b5d2cc9fc6b042afcdd27a0ec6d1a39d52836beb7c17f48b4e20cdd644cfe hosts/coreaudio/tuner_render.hpp
+1b4b7b68affbd4395b7d1eb611b01b1220d4d090ab5fbc3ed3a866534a4beba7 hosts/jack/jack_session.hpp
+2489d436b9dee2e69eaa0816e8f1b9679eb7150ae8bb9877dc4f678ae4cf1a00 hosts/jack/tone.cpp
+601b67e21fab60418bfef5849dbfcefca32568861c90781eac54f9a1049ce70c hosts/jack/tuner_live.cpp
+b6cc7da0e324458d7dbfa49f05b29d5d56b3ef9c9eaf0e6f4877fc6227dbe480 hosts/tests/test_host_audio.cpp
8559c84df869cdaa5f4200d8503018fa9ba54208a164f9313bf2e3523676e17b hosts/tests/test_hosts.cpp
0d8c6ad65e5ae06f9c8b1fcabf8270e783812f6d89076d0fab04a88247685a13 hosts/wasm/build.py
22863bba7ba0ee81f6095f6e463926ddf3f545836a2bdd25565f8a63ab91c7c1 hosts/wasm/demo.css
@@ -86,7 +97,7 @@ cbe66e0adc53dcf976819861a1fc3aeb862ef1c839aa1f5916d1169bdc8630db include/squatc
33d19f272b80e6d4e165d4d8c2705ff42aa2fa2f3f3092e853eed87a56958bd6 results/real.md
818c8ee6462a64bff412e3cf2113d0cf92f3a5daefb8088655381e2111e15b54 results/synth.md
2c724991273af88988ec5da7d76717814d829162e6d3680773dfa3eb48025d1b tests/test_core.cpp
-9cba71b30d7e537cd98c8f2880da323e16c3e3963018bf621870543e6e9a1331 tools/export-public
+ef551ef238d36f01bee7a4006ac35d8fff62f3a6211e25b4db043c80bcd40bed tools/export-public
27be201ebb49c36ae14442a8dd76cef12efeee46ea64e6e222769bc101a30b4a tools/release-scan
414c14c757ea09536eb85c185dcb3962b25aaba4d25b10530b24d2e1749b1c63 tools/release-signing
9942263d376c55df83073aa9cfa635f3a736e0fc9874f043483f68bf3d544b07 tools/test-release-scan
diff --git a/Makefile b/Makefile
index 1a22397..cc8a534 100644
--- a/Makefile
+++ b/Makefile
@@ -10,7 +10,7 @@ BUILD := build
BENCH_COMMON := bench/pv.cpp bench/poly_real.cpp
HEADERS := $(wildcard include/squatch/tuner/*.hpp) $(wildcard bench/*.hpp)
-HOST_HEADERS := $(wildcard hosts/common/*.hpp) $(wildcard hosts/jack/*.hpp) include/squatch/dsp/latest.hpp
+HOST_HEADERS := $(wildcard hosts/common/*.hpp) $(wildcard hosts/jack/*.hpp) $(wildcard hosts/coreaudio/*.hpp) include/squatch/dsp/latest.hpp
# The Guitar-TECHS single-note DI recordings (CC BY 4.0), downloaded separately: see RESULTS.md.
GUITAR_TECHS ?= data/guitar-techs
@@ -36,19 +36,40 @@ $(BUILD)/test_hosts: hosts/tests/test_hosts.cpp $(HEADERS) $(HOST_HEADERS) | $(B
$(BUILD):
mkdir -p $(BUILD)
-test: $(BUILD)/tests $(BUILD)/test_hosts
+# The CoreAudio host's audio path, offline: no audio device and no CoreAudio types, so it runs on any machine.
+$(BUILD)/test_host_audio: hosts/tests/test_host_audio.cpp $(HEADERS) $(HOST_HEADERS) | $(BUILD)
+ $(CXX) $(CXXFLAGS) -O1 -g -fsanitize=address,undefined -o $@ $< -lpthread
+
+test: $(BUILD)/tests $(BUILD)/test_hosts $(BUILD)/test_host_audio
./$(BUILD)/tests
./$(BUILD)/test_hosts
-
-# The live JACK host and its exact test tone (hosts/jack). Needs the JACK headers
-# (libjack-jackd2-dev on Debian and Ubuntu); not part of `all`.
+ ./$(BUILD)/test_host_audio
+
+# The live tuner and its exact test tone. On macOS they use CoreAudio directly (hosts/coreaudio): only
+# system frameworks, nothing to install. Elsewhere they use JACK (hosts/jack), which needs its headers
+# (libjack-jackd2-dev on Debian and Ubuntu). `make live LIVE_BACKEND=jack` forces JACK on a Mac that has it.
+# Not part of `all`.
+ifeq ($(shell uname -s),Darwin)
+LIVE_BACKEND ?= coreaudio
+else
+LIVE_BACKEND ?= jack
+endif
+ifeq ($(LIVE_BACKEND),coreaudio)
+LIVE_LIBS := -framework CoreAudio -framework AudioToolbox -framework CoreFoundation -lpthread
+# The tuner reads a microphone: its Info.plist (embedded in the binary) carries the text macOS shows when
+# it asks, so a launch from anywhere but Terminal is asked instead of being killed.
+TUNER_LINK := -Wl,-sectcreate,__TEXT,__info_plist,hosts/coreaudio/Info.plist
+else
+LIVE_LIBS := -ljack -lpthread
+TUNER_LINK :=
+endif
live: $(BUILD)/squatch-tuner-live $(BUILD)/squatch-tone
-$(BUILD)/squatch-tuner-live: hosts/jack/tuner_live.cpp $(HEADERS) $(HOST_HEADERS) | $(BUILD)
- $(CXX) $(CXXFLAGS) -o $@ $< -ljack -lpthread
+$(BUILD)/squatch-tuner-live: hosts/$(LIVE_BACKEND)/tuner_live.cpp $(HEADERS) $(HOST_HEADERS) | $(BUILD)
+ $(CXX) $(CXXFLAGS) -o $@ $< $(LIVE_LIBS) $(TUNER_LINK)
-$(BUILD)/squatch-tone: hosts/jack/tone.cpp $(HOST_HEADERS) | $(BUILD)
- $(CXX) $(CXXFLAGS) -o $@ $< -ljack -lpthread
+$(BUILD)/squatch-tone: hosts/$(LIVE_BACKEND)/tone.cpp $(HOST_HEADERS) | $(BUILD)
+ $(CXX) $(CXXFLAGS) -o $@ $< $(LIVE_LIBS)
# The browser demo, built into build/web-demo (docs/ holds the published copy). Needs
# Emscripten on PATH; demo-test also needs Node 22 and Chrome.
diff --git a/README.md b/README.md
index 598eacb..7545e14 100644
--- a/README.md
+++ b/README.md
@@ -121,8 +121,9 @@ void audioCallback(const float* in, int n) {
|---|---|
| `hosts/wasm/` | the browser demo: the core compiled to WebAssembly (31 kB, no imports) in an AudioWorklet, echo cancellation, noise suppression and automatic gain off, readings to the page 30 times a second |
| `hosts/web/` | the tuner page (strobe, needle, seals, A4 reference, light and dark themes, phone layout), and `serve.py`, a standard-library bridge that streams a live tuner to it |
-| `hosts/jack/` | `squatch-tuner-live`, the tuner behind a JACK input (the Pi 5 host in RESULTS.md), and `squatch-tone`, an exact test tone |
-| `hosts/common/` | what every host shares: note naming and the reading handoff |
+| `hosts/jack/` | `squatch-tuner-live`, the tuner behind a JACK input (Linux; the Pi 5 host in RESULTS.md), and `squatch-tone`, an exact test tone |
+| `hosts/coreaudio/` | the same two programs for macOS, on CoreAudio directly: no JACK, only system frameworks |
+| `hosts/common/` | what every host shares: note naming, the reading handoff, and the live tuner's real-time step and JSON line |
## Build and test
@@ -134,7 +135,7 @@ make test # core tests (ASan + UBSan, including zero heap allocations i
make all # the tests and the bench programs
make results # every number in RESULTS.md, about 20 minutes; needs the Guitar-TECHS
# recordings: make results GUITAR_TECHS=/path/to/guitar-techs
-make live # the JACK host (Linux, libjack-jackd2-dev)
+make live # CoreAudio on macOS (nothing to install); JACK elsewhere (libjack-jackd2-dev)
make demo # the browser demo into build/web-demo (needs Emscripten)
make demo-test # the module in Node, then the page in headless Chrome against test tones
make lint # complexity limits (lizard)
@@ -144,6 +145,24 @@ To run the demo locally, serve `docs/` over HTTPS or from `localhost`, which bro
trust with a microphone: `python3 -m http.server -d docs 8000`, then open
`http://localhost:8000/`.
+## Live on a Mac
+
+On macOS, `make live` builds `squatch-tuner-live` and `squatch-tone` on CoreAudio. They link system
+frameworks only, so a Mac needs nothing installed (no JACK); the options and the JSON lines are the
+JACK host's. Linux keeps JACK.
+
+```sh
+build/squatch-tuner-live --list-devices # every device: channels, rate, which are the defaults
+build/squatch-tuner-live # the default input device, channel 1
+build/squatch-tuner-live --device umc --input 2 # a device by (part of) its name, channel 2
+build/squatch-tone 110 --device umc --port 1 # an exact tone on that device's output 1
+```
+
+The first run asks, once, whether your terminal may use the microphone. If that was refused the input is
+digital silence, and the tuner says so on stderr after two seconds. The programs use a device as it is: they
+never change the Mac's default devices, a buffer size or a sample rate. `--out thru` needs one device with both
+inputs and outputs (an interface).
+
## Where the code lives
The source of truth is [squatch-dsp](https://github.com/squatch-stack/squatch-dsp), where the
diff --git a/hosts/common/host_clock.hpp b/hosts/common/host_clock.hpp
new file mode 100644
index 0000000..8c4828a
--- /dev/null
+++ b/hosts/common/host_clock.hpp
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: MIT
+// Plumbing every live host shares, JACK or CoreAudio: the run flag a signal clears, the clocks, and a
+// sleep to an absolute time. Nothing here runs in an audio callback except nowNs(), which is
+// clock_gettime (no lock, no allocation; on Linux a vDSO call, on macOS a cheap system call).
+#pragma once
+#include
+#include
+#include
+#include
+
+namespace squatch::host {
+
+inline std::atomic& running() {
+ static std::atomic flag{true};
+ return flag;
+}
+
+inline uint64_t nowNs(clockid_t clock = CLOCK_MONOTONIC) {
+ timespec t;
+ clock_gettime(clock, &t);
+ return static_cast(t.tv_sec) * 1000000000ull + static_cast(t.tv_nsec);
+}
+
+inline void onStopSignal(int) { running().store(false); }
+
+/// SIGINT and SIGTERM stop the program cleanly; so does the reader of stdout going away (SIGPIPE).
+inline void installStopSignals() {
+ std::signal(SIGINT, onStopSignal);
+ std::signal(SIGTERM, onStopSignal);
+ std::signal(SIGPIPE, onStopSignal);
+}
+
+/// Sleep until an absolute CLOCK_MONOTONIC time, then advance it by `periodNs`.
+/// macOS has no clock_nanosleep, so there it sleeps for the time left, read from the same clock.
+inline void sleepUntil(uint64_t& deadlineNs, uint64_t periodNs) {
+ deadlineNs += periodNs;
+#if defined(__APPLE__)
+ for (;;) {
+ const uint64_t now = nowNs();
+ if (now >= deadlineNs) return;
+ const uint64_t left = deadlineNs - now;
+ timespec t;
+ t.tv_sec = static_cast(left / 1000000000ull);
+ t.tv_nsec = static_cast(left % 1000000000ull);
+ if (nanosleep(&t, nullptr) == 0) return; // interrupted by a signal: go round with the time still left
+ }
+#else
+ timespec t;
+ t.tv_sec = static_cast(deadlineNs / 1000000000ull);
+ t.tv_nsec = static_cast(deadlineNs % 1000000000ull);
+ clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, nullptr);
+#endif
+}
+
+} // namespace squatch::host
diff --git a/hosts/common/tone_gen.hpp b/hosts/common/tone_gen.hpp
new file mode 100644
index 0000000..420d71b
--- /dev/null
+++ b/hosts/common/tone_gen.hpp
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: MIT
+// The sine of squatch-tone, for any audio backend. The phase is a double accumulator, so the
+// frequency is exact to the interface's own sample clock (which its input shares): the tuner's reading
+// can be compared with HZ directly. It fades in and out over 10 ms. fill() is real-time safe.
+#pragma once
+#include
+#include
+#include
+#include
+
+namespace squatch::host {
+
+struct ToneGen {
+ double phase = 0.0, step = 0.0; // turns, turns per sample
+ float amp = 0.1f, gain = 0.0f, fadeStep = 0.0f;
+ std::atomic target{0.0f}; // 0 until connected, so the start time is the real one
+
+ void configure(double hz, double db, double rate) {
+ step = hz / rate;
+ amp = static_cast(std::pow(10.0, db / 20.0));
+ fadeStep = static_cast(1.0 / (0.010 * rate));
+ }
+
+ /// Writes `n` samples to o[0], o[stride], ... and returns the gain target it saw.
+ float fill(float* o, uint32_t n, uint32_t stride = 1) {
+ const float tgt = target.load(std::memory_order_relaxed);
+ for (uint32_t i = 0; i < n; ++i) {
+ gain = gain < tgt ? std::min(gain + fadeStep, tgt) : std::max(gain - fadeStep, tgt);
+ o[static_cast(i) * stride] = amp * gain * static_cast(std::sin(6.283185307179586 * phase));
+ phase += step;
+ phase -= std::floor(phase);
+ }
+ return tgt;
+ }
+};
+
+} // namespace squatch::host
diff --git a/hosts/common/tuner_host.hpp b/hosts/common/tuner_host.hpp
new file mode 100644
index 0000000..6a7ac0c
--- /dev/null
+++ b/hosts/common/tuner_host.hpp
@@ -0,0 +1,222 @@
+// SPDX-License-Identifier: MIT
+// What squatch-tuner-live does apart from talking to an audio system, shared by the JACK host
+// (hosts/jack) and the CoreAudio host (hosts/coreaudio): the options, the real-time block step
+// (input -> Tuner -> Latest), the JSON line a display needs, the stdin commands, the 1/rate
+// publisher, and --file (a recording through the same step, offline). No JACK or CoreAudio types
+// here, so the offline test can drive the same path on any machine.
+//
+// Real-time rule: Core::processBlock() allocates nothing, takes no lock and makes no system call
+// beyond the clock read. Everything else runs on the main or the command thread.
+#pragma once
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "display.hpp"
+#include "host_clock.hpp"
+#include "ir_file.hpp"
+#include "latest.hpp"
+
+namespace squatch::host::live {
+
+constexpr float kMinA4 = 430.0f, kMaxA4 = 450.0f;
+constexpr size_t kFilePeriod = 64; // frames per block for --file: the bench's JACK period
+
+enum class OutMode { None, Mute, Thru };
+
+struct Options {
+ int input = 1;
+ OutMode out = OutMode::None;
+ float a4 = 440.0f;
+ float rateHz = 30.0f;
+ float minHz = 38.0f;
+ const char* file = nullptr;
+ const char* device = nullptr; // CoreAudio host only: a name to look for, default the system's default
+ bool listDevices = false; // CoreAudio host only
+};
+
+// What the audio callback hands over, once per callback.
+struct Frame {
+ squatch::tuner::TunerReading reading{};
+ float peak = 0.0f; // decaying |x| peak: falls 20 dB per second
+ uint64_t cycleStamp = 0; // the backend's own stamp of when this cycle began (JACK frame time, mach ns)
+ uint64_t callbacks = 0; // cumulative
+ uint64_t samples = 0; // input samples the tuner has heard: where in the audio `reading` is
+ uint64_t busyNs = 0; // cumulative time spent inside processBlock()
+ uint32_t worstNs = 0; // longest single processBlock() so far
+};
+
+inline std::atomic& liveA4() {
+ static std::atomic a4{440.0f};
+ return a4;
+}
+
+inline float blockPeak(const float* x, size_t n, float held) {
+ for (size_t i = 0; i < n; ++i) held = std::max(held, std::fabs(x[i]));
+ return held;
+}
+
+/// Everything the real-time callback touches. Keep one in static storage: the Tuner alone is ~128 kB.
+struct Core {
+ squatch::tuner::Tuner tuner;
+ Latest latest;
+ float peak = 0.0f;
+ float decayLog2PerFrame = 0.0f;
+ uint64_t callbacks = 0, busyNs = 0, samples = 0;
+ uint32_t worstNs = 0;
+
+ // configure() builds tables and is not real-time safe: call it before the audio starts.
+ void configure(float rate, float a4, float minHz) {
+ squatch::tuner::TunerConfig cfg;
+ cfg.sampleRate = rate;
+ cfg.a4 = a4;
+ cfg.minHz = minHz;
+ tuner.configure(cfg);
+ decayLog2PerFrame = 1.0f / (std::log10(2.0f) * rate); // -20 dB/s = one decade per second
+ }
+
+ float decayed(size_t n) const { return peak * std::exp2(-decayLog2PerFrame * static_cast(n)); }
+
+ /// The audio callback's body. Real-time safe.
+ void processBlock(const float* in, int n, uint64_t cycleStamp) {
+ const uint64_t t0 = nowNs();
+ tuner.process(in, n);
+ samples += static_cast(n);
+ peak = blockPeak(in, static_cast(n), decayed(static_cast(n)));
+ const auto dt = static_cast(std::min(nowNs() - t0, UINT32_MAX));
+ busyNs += dt;
+ worstNs = std::max(worstNs, dt);
+ Frame& f = latest.back();
+ f.reading = tuner.reading();
+ f.peak = peak;
+ f.cycleStamp = cycleStamp;
+ f.callbacks = ++callbacks;
+ f.samples = samples;
+ f.busyNs = busyNs;
+ f.worstNs = worstNs;
+ latest.publish();
+ }
+};
+
+// ---------------------------------------------------------------- options ----
+
+inline bool parseOut(std::string_view v, OutMode& m) {
+ if (v == "none") m = OutMode::None;
+ else if (v == "mute") m = OutMode::Mute;
+ else if (v == "thru") m = OutMode::Thru;
+ else return false;
+ return true;
+}
+
+inline bool applyOption(std::string_view key, const char* v, Options& o) {
+ if (key == "--input") return (o.input = std::atoi(v)) >= 1;
+ if (key == "--out") return parseOut(v, o.out);
+ if (key == "--a4") return (o.a4 = std::strtof(v, nullptr)) >= kMinA4 && o.a4 <= kMaxA4;
+ if (key == "--rate") return (o.rateHz = std::strtof(v, nullptr)) >= 1.0f && o.rateHz <= 120.0f;
+ if (key == "--min-hz") return (o.minHz = std::strtof(v, nullptr)) >= 20.0f && o.minHz <= 200.0f;
+ if (key == "--file") return (o.file = v) != nullptr;
+ return false;
+}
+
+/// `deviceFlags` adds the CoreAudio host's --device NAME and --list-devices.
+inline bool parseArgs(int argc, char** argv, Options& o, bool deviceFlags = false) {
+ for (int i = 1; i < argc;) {
+ const std::string_view key = argv[i];
+ if (deviceFlags && key == "--list-devices") {
+ o.listDevices = true;
+ i += 1;
+ continue;
+ }
+ if (i + 1 >= argc) return false;
+ const bool ok = (deviceFlags && key == "--device") ? (o.device = argv[i + 1]) != nullptr : applyOption(key, argv[i + 1], o);
+ if (!ok) return false;
+ i += 2;
+ }
+ return true;
+}
+
+// ---------------------------------------------------------------- commands ----
+
+inline void applyCommand(const char* line) {
+ float hz = 0.0f;
+ if (std::sscanf(line, "a4 %f", &hz) == 1 && hz >= kMinA4 && hz <= kMaxA4) liveA4().store(hz);
+}
+
+// Raw read(2), not fgets: a thread blocked in fgets holds stdin's FILE lock, and exit() takes
+// every FILE lock to flush, so the program could never exit while this thread waits for input.
+inline void readCommands() {
+ char line[128];
+ size_t len = 0;
+ char c;
+ while (read(STDIN_FILENO, &c, 1) == 1) {
+ if (c != '\n') {
+ if (len < sizeof line - 1) line[len++] = c; // an overlong line is cut, not overrun
+ continue;
+ }
+ line[len] = '\0';
+ applyCommand(line);
+ len = 0;
+ }
+}
+
+// ---------------------------------------------------------------- display line ----
+
+inline double dbfs(float x) { return 20.0 * std::log10(std::max(x, 1e-6f)); }
+
+// What the page draws, as the start of one JSON object (the caller closes it). The cents and the
+// uncertainty go at full float precision (%.9g, as the phone sends them): the page rounds the number
+// and filters its hold itself, so it must see the values every other display sees. `samples` and
+// `rate` say where in the audio the reading was taken: the page's hold runs on that clock (hold.js).
+struct AudioPos {
+ uint64_t samples;
+ double rate;
+};
+inline void printDisplay(const squatch::tuner::TunerReading& r, float peak, float a4, AudioPos at) {
+ const DisplayReading d = toDisplay(r, a4);
+ std::printf("{\"valid\":%s,\"note\":\"%s\",\"oct\":%d,\"midi\":%d,\"cents\":%.9g,\"fast\":%.3f,\"hz\":%.4f,\"shz\":%.4f,",
+ d.valid ? "true" : "false", d.note.name, d.note.octave, d.midi, d.cents, d.fastCents, d.hz, d.steadyHz);
+ std::printf("\"unc\":%.9g,\"parts\":%d,\"B\":%.3g,\"a4\":%.2f,\"lvl\":%.1f,\"pk\":%.1f,\"turns\":[", r.uncertainty, r.partials,
+ r.inharmonicity, a4, dbfs(r.level), dbfs(peak));
+ for (int k = 0; k < r.partials; ++k) std::printf(k ? ",%.4f" : "%.4f", r.strobeTurns[k]);
+ std::printf("],\"samples\":%llu,\"rate\":%.0f", static_cast(at.samples), at.rate);
+}
+
+// ---------------------------------------------------------------- --file ----
+
+/// The real-time step without an audio system: kFilePeriod-frame blocks (the bench's JACK period) through
+/// Core::processBlock, and `emit(frame, samplesHeard, tMs)` after the period that crosses each 1/rate s of audio.
+template
+inline void runSamples(const std::vector& samples, double rate, const Options& o, Core& core, Emit&& emit) {
+ constexpr size_t period = kFilePeriod;
+ core.configure(static_cast(rate), o.a4, o.minHz);
+ const double step = rate / o.rateHz;
+ double next = step;
+ for (size_t i = 0; i + period <= samples.size(); i += period) {
+ core.processBlock(&samples[i], static_cast(period), 0);
+ core.latest.update();
+ for (; next <= static_cast(i + period); next += step)
+ emit(core.latest.front(), i + period, 1000.0 * static_cast(i + period) / rate);
+ }
+}
+
+/// --file: a recording through runSamples, one display line on stdout each. Returns the exit code.
+inline int runFile(const Options& o, Core& core) {
+ const Wav w = readWav(o.file);
+ if (!w.error.empty()) return std::fprintf(stderr, "squatch-tuner-live: %s: %s\n", o.file, w.error.c_str()), 2;
+ runSamples(w.samples, w.rate, o, core, [&](const Frame& f, uint64_t heard, double tMs) {
+ printDisplay(f.reading, f.peak, o.a4, {heard, w.rate});
+ std::printf(",\"t\":%.17g}\n", tMs); // exact: the hold's 500 ms edge
+ });
+ return 0;
+}
+
+} // namespace squatch::host::live
diff --git a/hosts/common/tuner_publisher.hpp b/hosts/common/tuner_publisher.hpp
new file mode 100644
index 0000000..5c98584
--- /dev/null
+++ b/hosts/common/tuner_publisher.hpp
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: MIT
+// The main thread of squatch-tuner-live, for any audio backend: every 1/rate s, the newest Frame
+// becomes one JSON line on stdout. Non-real-time. The backend (JACK or CoreAudio) supplies only what
+// differs: its rate and period, the capture latency, when the newest audio reached the input, and
+// the server's own load figure.
+//
+// Backend::kWarnDigitalSilence true where all-zero input for two seconds means "no permission"
+// double rate(), uint32_t period()
+// void refreshLatency(), double captureMs()
+// double inputTimeMs(const Frame&) wall-clock ms (epoch) the newest audio reached the input
+// double serverLoadPct() the audio server's load, 0 where there is none
+#pragma once
+#include "tuner_host.hpp"
+
+namespace squatch::host::live {
+
+inline uint64_t processCpuNs() {
+ rusage u{};
+ getrusage(RUSAGE_SELF, &u);
+ const auto ns = [](const timeval& t) { return static_cast(t.tv_sec) * 1000000000ull + static_cast(t.tv_usec) * 1000ull; };
+ return ns(u.ru_utime) + ns(u.ru_stime);
+}
+
+struct Load {
+ double dspPct = 0.0; // time in processBlock() / time available, since the last line
+ double worstPct = 0.0; // longest processBlock() so far / one period
+ double cpuPct = 0.0; // this process, all threads, % of one core
+ double serverPct = 0.0; // the audio server's own figure for the whole graph (JACK)
+};
+
+template
+class Publisher {
+ public:
+ Publisher(Core& core, Backend& be, int input) : core_(core), be_(be), input_(input) {
+ be_.refreshLatency();
+ last_ = Sample{0, 0, processCpuNs(), nowNs()};
+ }
+
+ void run(float rateHz) {
+ const auto step = static_cast(1e9 / rateHz);
+ uint64_t deadline = nowNs();
+ while (running().load()) {
+ sleepUntil(deadline, step);
+ if (core_.latest.update()) {
+ have_ = true;
+ freshNs_ = nowNs();
+ }
+ // A stalled graph (driver stopped, server suspended) stops the callback; the last frame must
+ // not be repeated as if it were live, or the page shows a frozen note. Silence lets the
+ // bridge declare the stream stale.
+ if (have_ && nowNs() - freshNs_ < kStaleNs) line(core_.latest.front());
+ }
+ }
+
+ private:
+ struct Sample {
+ uint64_t callbacks, busyNs, cpuNs, wallNs;
+ };
+ static constexpr uint64_t kStaleNs = 250000000ull; // 250 ms: about 190 periods at 64 / 48 kHz
+
+ Load load(const Frame& f) {
+ const Sample now{f.callbacks, f.busyNs, processCpuNs(), nowNs()};
+ const double periodNs = 1e9 * be_.period() / be_.rate();
+ Load l;
+ if (now.callbacks > last_.callbacks)
+ l.dspPct = 100.0 * static_cast(now.busyNs - last_.busyNs) / (periodNs * static_cast(now.callbacks - last_.callbacks));
+ if (now.wallNs > last_.wallNs) l.cpuPct = 100.0 * static_cast(now.cpuNs - last_.cpuNs) / static_cast(now.wallNs - last_.wallNs);
+ l.worstPct = 100.0 * f.worstNs / periodNs;
+ l.serverPct = be_.serverLoadPct();
+ last_ = now;
+ return l;
+ }
+
+ // An input that has delivered nothing but exact zeros for two seconds is not a quiet guitar: on macOS it is
+ // a microphone permission that was refused. Say so once, on stderr.
+ void warnIfSilent(const Frame& f) {
+ if constexpr (Backend::kWarnDigitalSilence) {
+ if (f.peak > 0.0f) heard_ = true;
+ if (!heard_ && !warned_ && static_cast(f.samples) > 2.0 * be_.rate()) {
+ warned_ = true;
+ std::fprintf(stderr, "squatch-tuner-live: the input has been digital silence for 2 s. If this is a microphone, allow your terminal "
+ "under System Settings > Privacy & Security > Microphone, or pick another input with --device.\n");
+ }
+ }
+ }
+
+ void line(const Frame& f) {
+ const float a4 = liveA4().load();
+ const Load l = load(f);
+ be_.refreshLatency();
+ warnIfSilent(f);
+ printDisplay(f.reading, f.peak, a4, {f.samples, be_.rate()});
+ std::printf(",\"input\":%d,\"tin\":%.1f,\"capMs\":%.2f,\"period\":%u,", input_, be_.inputTimeMs(f), be_.captureMs(), be_.period());
+ std::printf("\"dsp\":%.2f,\"dspWorst\":%.1f,\"cpu\":%.2f,\"jack\":%.1f}\n", l.dspPct, l.worstPct, l.cpuPct, l.serverPct);
+ if (std::fflush(stdout) != 0) running().store(false); // the reader has gone
+ }
+
+ Core& core_;
+ Backend& be_;
+ int input_;
+ Sample last_{};
+ bool have_ = false, heard_ = false, warned_ = false;
+ uint64_t freshNs_ = 0;
+};
+
+} // namespace squatch::host::live
diff --git a/hosts/coreaudio/Info.plist b/hosts/coreaudio/Info.plist
new file mode 100644
index 0000000..22f28b9
--- /dev/null
+++ b/hosts/coreaudio/Info.plist
@@ -0,0 +1,14 @@
+
+
+
+
+ CFBundleIdentifier
+ cc.squatch.tuner-live
+ CFBundleName
+ squatch-tuner-live
+ CFBundleVersion
+ 1
+ NSMicrophoneUsageDescription
+ squatch-tuner-live listens to the audio input you choose to show the pitch of the note you play. Nothing is recorded or sent anywhere.
+
+
diff --git a/hosts/coreaudio/audio_chunks.hpp b/hosts/coreaudio/audio_chunks.hpp
new file mode 100644
index 0000000..b6c2dd9
--- /dev/null
+++ b/hosts/coreaudio/audio_chunks.hpp
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: MIT
+// The buffer shuffling of the CoreAudio host, with no CoreAudio types so that any machine can test it.
+// A Chunk is one interleaved float32 buffer, laid out as CoreAudio's AudioBuffer (channels per frame,
+// byte size, data); an AudioBufferList is a short array of them, one per stream. Everything here runs
+// in the audio callback: no allocation, no locks, no system calls.
+#pragma once
+#include
+#include
+#include
+#include
+
+namespace squatch::host::audio {
+
+struct Chunk {
+ uint32_t channels = 0;
+ uint32_t bytes = 0;
+ void* data = nullptr;
+};
+
+/// Frames in the first usable chunk (all chunks of one callback hold the same count).
+/// A callback's buffers: what an AudioBufferList holds, one Chunk per stream. May be empty.
+struct Chunks {
+ Chunk* list = nullptr;
+ uint32_t count = 0;
+};
+
+inline uint32_t framesOf(Chunks c) {
+ for (uint32_t i = 0; c.list && i < c.count; ++i)
+ if (c.list[i].channels && c.list[i].data) return c.list[i].bytes / (c.list[i].channels * static_cast(sizeof(float)));
+ return 0;
+}
+
+inline uint32_t channelsOf(Chunks c) {
+ uint32_t total = 0;
+ for (uint32_t i = 0; c.list && i < c.count; ++i) total += c.list[i].channels;
+ return total;
+}
+
+/// Copies channel `channel` (0-based across all chunks) for frames [offset, offset + cap) into `dst`;
+/// returns how many it wrote. A channel the device does not have reads as silence.
+inline uint32_t gatherChannel(Chunks in, uint32_t channel, uint32_t offset, float* dst, uint32_t cap) {
+ const uint32_t frames = framesOf(in);
+ const uint32_t count = offset < frames ? std::min(cap, frames - offset) : 0;
+ uint32_t first = 0;
+ for (uint32_t i = 0; in.list && i < in.count; first += in.list[i].channels, ++i) {
+ const Chunk& c = in.list[i];
+ if (channel >= first + c.channels || !c.data) continue;
+ const auto* src = static_cast(c.data) + (channel - first);
+ for (uint32_t k = 0; k < count; ++k) dst[k] = src[static_cast(offset + k) * c.channels];
+ return count;
+ }
+ std::fill(dst, dst + count, 0.0f);
+ return count;
+}
+
+inline void clearAll(Chunks out) {
+ for (uint32_t i = 0; out.list && i < out.count; ++i)
+ if (out.list[i].data) std::memset(out.list[i].data, 0, out.list[i].bytes);
+}
+
+/// Writes `mono` (frames [offset, offset + count)) to output channels [0, channelCount).
+inline void scatterMono(Chunks out, uint32_t channelCount, uint32_t offset, const float* mono, uint32_t count) {
+ uint32_t first = 0;
+ for (uint32_t i = 0; out.list && i < out.count; first += out.list[i].channels, ++i) {
+ const Chunk& chunk = out.list[i];
+ if (!chunk.data || first >= channelCount) continue;
+ auto* d = static_cast(chunk.data);
+ const uint32_t use = std::min(chunk.channels, channelCount - first);
+ for (uint32_t c = 0; c < use; ++c)
+ for (uint32_t k = 0; k < count; ++k) d[static_cast(offset + k) * chunk.channels + c] = mono[k];
+ }
+}
+
+} // namespace squatch::host::audio
diff --git a/hosts/coreaudio/coreaudio_session.hpp b/hosts/coreaudio/coreaudio_session.hpp
new file mode 100644
index 0000000..474ba98
--- /dev/null
+++ b/hosts/coreaudio/coreaudio_session.hpp
@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: MIT
+// Plumbing shared by the CoreAudio programs here (macOS only): list and pick devices, run one IOProc
+// on a device, and turn the HAL's buffers into audio::Chunk. Links CoreAudio and CoreFoundation only.
+//
+// The device queries and the IOProc set-up follow squatch-rig-live's src/audio.cpp (CoreAudio HAL
+// access, same author, Squatch Stack); this file differs in picking the system's default devices or a
+// name, and in taking no part in any rig. Nothing here changes the Mac's default devices, the buffer
+// size or the sample rate of any device: it uses them as they are.
+#pragma once
+#include
+#include
+
+#include
+#include
+#include
+#include
+
+#include "../common/host_clock.hpp"
+#include "audio_chunks.hpp"
+
+namespace squatch::host::ca {
+
+struct DeviceInfo {
+ AudioObjectID id = 0;
+ std::string name;
+ uint32_t inChannels = 0, outChannels = 0;
+ uint32_t inLatency = 0, outLatency = 0; // frames: device + safety offset + stream
+ uint32_t bufferFrames = 0;
+ double rate = 0.0;
+ bool floatFormat = true; // every stream's virtual format is 32-bit float PCM
+ bool defaultIn = false, defaultOut = false;
+};
+
+namespace detail {
+
+template
+bool getProp(AudioObjectID id, AudioObjectPropertySelector sel, AudioObjectPropertyScope scope, T& out) {
+ const AudioObjectPropertyAddress a{sel, scope, kAudioObjectPropertyElementMain};
+ UInt32 sz = sizeof(T);
+ return AudioObjectGetPropertyData(id, &a, 0, nullptr, &sz, &out) == noErr;
+}
+
+inline std::string nameOf(AudioObjectID id) {
+ CFStringRef s = nullptr;
+ if (!getProp(id, kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, s) || !s) return "";
+ char buf[256] = {0};
+ CFStringGetCString(s, buf, sizeof buf, kCFStringEncodingUTF8);
+ CFRelease(s);
+ return buf;
+}
+
+inline std::vector streamsOf(AudioObjectID dev, AudioObjectPropertyScope scope) {
+ const AudioObjectPropertyAddress a{kAudioDevicePropertyStreams, scope, kAudioObjectPropertyElementMain};
+ UInt32 sz = 0;
+ std::vector v;
+ if (AudioObjectGetPropertyDataSize(dev, &a, 0, nullptr, &sz) != noErr || !sz) return v;
+ v.resize(sz / sizeof(AudioObjectID));
+ if (AudioObjectGetPropertyData(dev, &a, 0, nullptr, &sz, v.data()) != noErr) v.clear();
+ return v;
+}
+
+// Channels and latency of one direction of a device; clears `floatOk` if a stream is not float32 PCM.
+inline void queryScope(AudioObjectID dev, AudioObjectPropertyScope scope, uint32_t& channels, uint32_t& latency, bool& floatOk) {
+ UInt32 device = 0, safety = 0, stream = 0;
+ getProp(dev, kAudioDevicePropertyLatency, scope, device);
+ getProp(dev, kAudioDevicePropertySafetyOffset, scope, safety);
+ for (AudioObjectID st : streamsOf(dev, scope)) {
+ UInt32 l = 0;
+ getProp(st, kAudioStreamPropertyLatency, kAudioObjectPropertyScopeGlobal, l);
+ stream = l > stream ? l : stream;
+ AudioStreamBasicDescription f{};
+ if (!getProp(st, kAudioStreamPropertyVirtualFormat, kAudioObjectPropertyScopeGlobal, f)) continue;
+ channels += f.mChannelsPerFrame;
+ if (f.mFormatID != kAudioFormatLinearPCM || !(f.mFormatFlags & kAudioFormatFlagIsFloat) || f.mBitsPerChannel != 32) floatOk = false;
+ }
+ latency = device + safety + stream;
+}
+
+inline AudioObjectID defaultId(AudioObjectPropertySelector sel) {
+ AudioObjectID id = 0;
+ getProp(kAudioObjectSystemObject, sel, kAudioObjectPropertyScopeGlobal, id);
+ return id;
+}
+
+inline bool containsNoCase(const std::string& hay, const std::string& needle) {
+ const auto lower = [](std::string s) {
+ for (char& c : s) c = static_cast(std::tolower(static_cast(c)));
+ return s;
+ };
+ return lower(hay).find(lower(needle)) != std::string::npos;
+}
+
+} // namespace detail
+
+inline uint32_t bufferFramesOf(AudioObjectID id) {
+ UInt32 frames = 0;
+ detail::getProp(id, kAudioDevicePropertyBufferFrameSize, kAudioObjectPropertyScopeGlobal, frames);
+ return frames;
+}
+
+inline DeviceInfo describeDevice(AudioObjectID id, AudioObjectID defIn, AudioObjectID defOut) {
+ DeviceInfo d;
+ d.id = id;
+ d.name = detail::nameOf(id);
+ d.defaultIn = id == defIn;
+ d.defaultOut = id == defOut;
+ detail::getProp(id, kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, d.rate);
+ detail::queryScope(id, kAudioObjectPropertyScopeInput, d.inChannels, d.inLatency, d.floatFormat);
+ detail::queryScope(id, kAudioObjectPropertyScopeOutput, d.outChannels, d.outLatency, d.floatFormat);
+ d.bufferFrames = bufferFramesOf(id);
+ return d;
+}
+
+/// Every audio device, in the HAL's order.
+inline std::vector listDevices() {
+ const AudioObjectPropertyAddress a{kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain};
+ UInt32 sz = 0;
+ std::vector out;
+ if (AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &a, 0, nullptr, &sz) != noErr) return out;
+ std::vector ids(sz / sizeof(AudioObjectID));
+ if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &a, 0, nullptr, &sz, ids.data()) != noErr) return out;
+ const AudioObjectID defIn = detail::defaultId(kAudioHardwarePropertyDefaultInputDevice);
+ const AudioObjectID defOut = detail::defaultId(kAudioHardwarePropertyDefaultOutputDevice);
+ for (AudioObjectID id : ids) out.push_back(describeDevice(id, defIn, defOut));
+ return out;
+}
+
+inline void printDevices(const std::vector& devices, std::FILE* to) {
+ std::fprintf(to, "%-4s %-40s %4s %4s %8s %s\n", "id", "name", "in", "out", "rate Hz", "default");
+ for (const DeviceInfo& d : devices)
+ std::fprintf(to, "%-4u %-40s %4u %4u %8.0f %s%s\n", d.id, d.name.c_str(), d.inChannels, d.outChannels, d.rate, d.defaultIn ? "input " : "",
+ d.defaultOut ? "output" : "");
+}
+
+/// The device to use for one direction: the first whose name contains `name` (any case) and that has
+/// channels that way; with no name, the system's default device for that direction. Says why on failure.
+inline bool pickDevice(const std::vector& devices, const char* name, bool input, DeviceInfo& pick, std::string& why) {
+ const char* dir = input ? "input" : "output";
+ for (const DeviceInfo& d : devices) {
+ const bool has = (input ? d.inChannels : d.outChannels) > 0;
+ const bool wanted = name ? detail::containsNoCase(d.name, name) : (input ? d.defaultIn : d.defaultOut);
+ if (has && wanted) return pick = d, true;
+ }
+ why = name ? std::string("no audio device with ") + dir + "s matches \"" + name + "\" (see --list-devices)"
+ : std::string("this Mac has no default audio ") + dir + " device (see --list-devices, then --device NAME)";
+ return false;
+}
+
+/// mach host time -> nanoseconds. AudioTimeStamp.mHostTime is in mach_absolute_time ticks.
+class HostClock {
+ public:
+ HostClock() { mach_timebase_info(&tb_); }
+ uint64_t ns(uint64_t ticks) const { return (ticks / tb_.denom) * tb_.numer + (ticks % tb_.denom) * tb_.numer / tb_.denom; }
+ uint64_t nowNs() const { return ns(mach_absolute_time()); }
+
+ private:
+ mach_timebase_info_data_t tb_{};
+};
+
+/// The HAL's buffers as Chunks, without allocating: at most `cap` of them.
+inline uint32_t chunksOf(const AudioBufferList* list, audio::Chunk* dst, uint32_t cap) {
+ if (!list) return 0;
+ const uint32_t n = list->mNumberBuffers < cap ? list->mNumberBuffers : cap;
+ for (uint32_t i = 0; i < n; ++i) dst[i] = {list->mBuffers[i].mNumberChannels, list->mBuffers[i].mDataByteSize, list->mBuffers[i].mData};
+ return n;
+}
+
+/// One IOProc on one device. The callback runs on the HAL's real-time thread.
+class Stream {
+ public:
+ using Fn = void (*)(void* ctx, const AudioBufferList* in, const AudioTimeStamp* inTime, AudioBufferList* out, const AudioTimeStamp* outTime);
+ Stream() = default;
+ Stream(const Stream&) = delete;
+ Stream& operator=(const Stream&) = delete;
+ ~Stream() { stop(); }
+
+ bool start(AudioObjectID device, Fn fn, void* ctx, std::string& err) {
+ bind_ = {fn, ctx};
+ OSStatus s = AudioDeviceCreateIOProcID(device, &Stream::ioproc, &bind_, &proc_);
+ if (s != noErr) return err = "AudioDeviceCreateIOProcID failed: " + std::to_string(s), false;
+ device_ = device;
+ s = AudioDeviceStart(device, proc_);
+ if (s != noErr) {
+ err = "AudioDeviceStart failed: " + std::to_string(s);
+ AudioDeviceDestroyIOProcID(device, proc_);
+ proc_ = nullptr;
+ return false;
+ }
+ return true;
+ }
+
+ void stop() {
+ if (!proc_) return;
+ AudioDeviceStop(device_, proc_);
+ AudioDeviceDestroyIOProcID(device_, proc_);
+ proc_ = nullptr;
+ }
+
+ private:
+ struct Binding {
+ Fn fn = nullptr;
+ void* ctx = nullptr;
+ };
+ // The parameter list is CoreAudio's AudioDeviceIOProc, fixed by the HAL.
+ static OSStatus ioproc(AudioObjectID, const AudioTimeStamp*, const AudioBufferList* in, const AudioTimeStamp* inTime, AudioBufferList* out,
+ const AudioTimeStamp* outTime, void* self) {
+ // #lizard forgives
+ const auto* b = static_cast(self);
+ b->fn(b->ctx, in, inTime, out, outTime);
+ return noErr;
+ }
+ Binding bind_;
+ AudioObjectID device_ = 0;
+ AudioDeviceIOProcID proc_ = nullptr;
+};
+
+} // namespace squatch::host::ca
diff --git a/hosts/coreaudio/tone.cpp b/hosts/coreaudio/tone.cpp
new file mode 100644
index 0000000..1d0f699
--- /dev/null
+++ b/hosts/coreaudio/tone.cpp
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: MIT
+// squatch-tone for macOS: a test tone at an exact frequency on one CoreAudio output channel, for
+// checking the tuner through a real loopback cable. The same options and output as the JACK host
+// (hosts/jack/tone.cpp).
+//
+// squatch-tone HZ [--db DBFS] [--device NAME] [--port N] [--seconds S]
+// squatch-tone --list-devices
+//
+// Defaults: -20 dBFS on output channel 1 of the Mac's default output device until stopped (Ctrl-C,
+// SIGTERM). --device NAME picks the first device whose name contains NAME (any case). --port takes a
+// channel number, or the JACK spelling system:playback_N. The phase is a double accumulator (see
+// common/tone_gen.hpp). Once the tone is playing it prints one JSON line on stdout: the wall-clock time
+// the first sample reached the output, and the playback latency, for end-to-end timing. Both are the
+// device's reported latency, not a loopback measurement.
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "../common/tone_gen.hpp"
+#include "coreaudio_session.hpp"
+
+namespace {
+
+using namespace squatch::host;
+
+struct Tone {
+ ToneGen gen;
+ ca::HostClock clock;
+ uint32_t channel = 0; // 0-based
+ std::atomic firstHostNs{0}; // mach ns the first audible sample is due at the device
+ std::atomic started{false};
+};
+
+Tone gTone;
+
+constexpr uint32_t kMaxStreams = 16;
+
+void onAudio(void* ctx, const AudioBufferList*, const AudioTimeStamp*, AudioBufferList* out, const AudioTimeStamp* outTime) {
+ Tone& t = *static_cast(ctx);
+ audio::Chunk oc[kMaxStreams];
+ const uint32_t n = ca::chunksOf(out, oc, kMaxStreams);
+ audio::clearAll({oc, n});
+ uint32_t first = 0;
+ for (uint32_t i = 0; i < n; first += oc[i].channels, ++i) {
+ if (t.channel < first || t.channel >= first + oc[i].channels || !oc[i].data) continue;
+ const uint32_t frames = oc[i].bytes / (oc[i].channels * static_cast(sizeof(float)));
+ const float target = t.gen.fill(static_cast(oc[i].data) + (t.channel - first), frames, oc[i].channels);
+ if (target > 0.0f && !t.started.load(std::memory_order_relaxed)) {
+ t.firstHostNs.store(outTime ? t.clock.ns(outTime->mHostTime) : t.clock.nowNs(), std::memory_order_relaxed);
+ t.started.store(true, std::memory_order_release);
+ }
+ return;
+ }
+}
+
+struct Args {
+ double hz = 0.0, db = -20.0, seconds = 0.0;
+ uint32_t channel = 1;
+ const char* device = nullptr;
+ bool list = false;
+};
+
+// "3" or "system:playback_3" -> 3; 0 if it is neither.
+uint32_t channelOf(const char* v) {
+ const char* digits = std::strrchr(v, '_');
+ const long n = std::strtol(digits ? digits + 1 : v, nullptr, 10);
+ return n >= 1 && n <= 1024 ? static_cast(n) : 0;
+}
+
+bool apply(std::string_view key, const char* v, Args& a) {
+ if (key == "--db") return (a.db = std::strtod(v, nullptr)) <= -6.0;
+ if (key == "--port") return (a.channel = channelOf(v)) != 0;
+ if (key == "--seconds") return (a.seconds = std::strtod(v, nullptr)) >= 0.0;
+ if (key == "--device") return (a.device = v) != nullptr;
+ return false;
+}
+
+bool parse(int argc, char** argv, Args& a) {
+ if (argc == 2 && std::string_view(argv[1]) == "--list-devices") return a.list = true;
+ if (argc < 2 || (a.hz = std::strtod(argv[1], nullptr)) <= 0.0) return false;
+ for (int i = 2; i < argc; i += 2)
+ if (i + 1 >= argc || !apply(argv[i], argv[i + 1], a)) return false;
+ return true;
+}
+
+void reportStart(const Tone& t, const ca::DeviceInfo& d) {
+ while (running().load() && !t.started.load(std::memory_order_acquire)) std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ const double outMs = 1000.0 * d.outLatency / d.rate;
+ // The first sample is due at the device at firstHostNs (in the future, for a buffer being filled now),
+ // and leaves the output jack outMs later.
+ const double dueMs = (static_cast(t.firstHostNs.load()) - static_cast(t.clock.nowNs())) / 1e6;
+ const double startMs = static_cast(nowNs(CLOCK_REALTIME)) / 1e6 + dueMs + outMs;
+ std::printf("{\"toneStart\":%.1f,\"playMs\":%.2f,\"hz\":%.6f}\n", startMs, outMs, t.gen.step * d.rate);
+ std::fflush(stdout);
+}
+
+void playUntilStopped(Tone& t, double seconds) {
+ const uint64_t end = seconds > 0.0 ? nowNs() + static_cast(seconds * 1e9) : UINT64_MAX;
+ while (running().load() && nowNs() < end) std::this_thread::sleep_for(std::chrono::milliseconds(20));
+ t.gen.target.store(0.0f); // fade out, then close
+ std::this_thread::sleep_for(std::chrono::milliseconds(40));
+}
+
+int play(const Args& a) {
+ const auto devices = ca::listDevices();
+ ca::DeviceInfo dev;
+ std::string why;
+ if (!ca::pickDevice(devices, a.device, false, dev, why)) return std::fprintf(stderr, "squatch-tone: %s\n", why.c_str()), 2;
+ if (!dev.floatFormat || dev.rate <= 0.0) return std::fprintf(stderr, "squatch-tone: %s: not a 32-bit float device\n", dev.name.c_str()), 2;
+ if (a.channel > dev.outChannels)
+ return std::fprintf(stderr, "squatch-tone: %s has %u output channel(s), not %u\n", dev.name.c_str(), dev.outChannels, a.channel), 2;
+ Tone& t = gTone;
+ t.channel = a.channel - 1;
+ t.gen.configure(a.hz, a.db, dev.rate);
+ installStopSignals();
+ ca::Stream stream;
+ if (!stream.start(dev.id, onAudio, &t, why)) return std::fprintf(stderr, "squatch-tone: %s\n", why.c_str()), 2;
+ t.gen.target.store(1.0f);
+ reportStart(t, dev);
+ playUntilStopped(t, a.seconds);
+ stream.stop();
+ return 0;
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ Args a;
+ if (!parse(argc, argv, a)) {
+ std::fprintf(stderr, "usage: squatch-tone HZ [--db DBFS (<= -6)] [--device NAME] [--port N] [--seconds S]\n"
+ " squatch-tone --list-devices\n");
+ return 64;
+ }
+ if (a.list) return ca::printDevices(ca::listDevices(), stdout), 0;
+ return play(a);
+}
diff --git a/hosts/coreaudio/tuner_live.cpp b/hosts/coreaudio/tuner_live.cpp
new file mode 100644
index 0000000..48ad0bc
--- /dev/null
+++ b/hosts/coreaudio/tuner_live.cpp
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: MIT
+// squatch-tuner-live for macOS: the Squatch Tuner behind a CoreAudio input, publishing what a display
+// needs as one JSON line per update on stdout. The same options and the same lines as the JACK host
+// (hosts/jack/tuner_live.cpp), on the Mac's own audio system: nothing to install.
+//
+// squatch-tuner-live [--device NAME] [--input N] [--out none|mute|thru] [--a4 HZ] [--rate HZ] [--min-hz HZ]
+// squatch-tuner-live --file take.wav [--a4 HZ] [--rate HZ] [--min-hz HZ]
+// squatch-tuner-live --list-devices
+//
+// --device NAME the audio device to use: the first whose name contains NAME, in any case.
+// Default: the Mac's default input device. Nothing here changes the Mac's defaults.
+// --input N channel N of that device (default 1: the UMC204HD's Input 1)
+// --out none (default): the outputs are left silent. mute: the same, said aloud, for a pedal
+// tuner that mutes the rig. thru: the input on outputs 1 and 2 of the device, which then
+// must have both (an interface); a Mac's microphone and speakers are two devices.
+// --list-devices every audio device with its channels, rate and which are the defaults, then exit
+// --a4, --rate, --min-hz, --file as the JACK host. "jack" in each line is 0 (CoreAudio has no server).
+//
+// First run: macOS asks once whether your terminal may use the microphone. If it is refused the input
+// is digital silence, and the tuner says so on stderr after two seconds.
+//
+// Threads: the HAL's real-time thread runs TunerRender (no allocation, no locks); the main thread
+// prints a line every 1/rate s; a command thread reads "a4 442.5" from stdin.
+#include
+#include
+
+#include "../common/tuner_publisher.hpp"
+#include "coreaudio_session.hpp"
+#include "tuner_render.hpp"
+
+namespace {
+
+using namespace squatch::host;
+using namespace squatch::host::live;
+
+struct Engine {
+ Core core;
+ alignas(64) char renderStorage[sizeof(TunerRender)];
+ TunerRender* render = nullptr;
+ ca::HostClock clock;
+};
+
+Engine gEngine;
+
+constexpr uint32_t kMaxStreams = 16;
+
+// The HAL's real-time callback: Chunks, then the shared render step.
+void onAudio(void* ctx, const AudioBufferList* in, const AudioTimeStamp* inTime, AudioBufferList* out, const AudioTimeStamp*) {
+ Engine& e = *static_cast(ctx);
+ audio::Chunk ic[kMaxStreams], oc[kMaxStreams];
+ const uint32_t ni = ca::chunksOf(in, ic, kMaxStreams), no = ca::chunksOf(out, oc, kMaxStreams);
+ const uint64_t host = inTime && (inTime->mFlags & kAudioTimeStampHostTimeValid) ? e.clock.ns(inTime->mHostTime) : e.clock.nowNs();
+ e.render->render({ic, ni}, {oc, no}, host);
+}
+
+// What the publisher needs from CoreAudio.
+class CoreAudioBackend {
+ public:
+ static constexpr bool kWarnDigitalSilence = true;
+ CoreAudioBackend(const ca::DeviceInfo& d, const ca::HostClock& clock) : dev_(d), clock_(clock) {}
+
+ double rate() const { return dev_.rate; }
+ uint32_t period() const { return period_; }
+ double captureMs() const { return 1000.0 * dev_.inLatency / dev_.rate; }
+ double serverLoadPct() const { return 0.0; }
+ void refreshLatency() { period_ = ca::bufferFramesOf(dev_.id); }
+
+ // Wall-clock time (ms since the epoch) at which the newest audio in this frame reached the input:
+ // now, minus how long ago the buffer's last frame was captured, minus the capture latency the device
+ // reports (device + safety offset + stream). The HAL's figure, not a loopback measurement.
+ double inputTimeMs(const Frame& f) const {
+ const auto ageNs = static_cast(clock_.nowNs()) - static_cast(f.cycleStamp);
+ return static_cast(nowNs(CLOCK_REALTIME)) / 1e6 - static_cast(ageNs) / 1e6 - captureMs();
+ }
+
+ private:
+ ca::DeviceInfo dev_;
+ const ca::HostClock& clock_;
+ uint32_t period_ = 0;
+};
+
+int usage() {
+ std::fprintf(stderr, "usage: squatch-tuner-live [--device NAME] [--input N] [--out none|mute|thru] [--a4 HZ] [--rate HZ] [--min-hz HZ]\n"
+ " squatch-tuner-live --file take.wav [--a4 HZ] [--rate HZ] [--min-hz HZ]\n"
+ " squatch-tuner-live --list-devices\n");
+ return 64;
+}
+
+bool checkDevice(const ca::DeviceInfo& d, const Options& o) {
+ if (!d.floatFormat) return std::fprintf(stderr, "squatch-tuner-live: %s: stream format is not 32-bit float\n", d.name.c_str()), false;
+ if (d.rate <= 0.0) return std::fprintf(stderr, "squatch-tuner-live: %s: no sample rate\n", d.name.c_str()), false;
+ if (static_cast(o.input) > d.inChannels)
+ return std::fprintf(stderr, "squatch-tuner-live: %s has %u input channel(s), not %d\n", d.name.c_str(), d.inChannels, o.input), false;
+ if (o.out == OutMode::Thru && d.outChannels == 0)
+ return std::fprintf(stderr, "squatch-tuner-live: --out thru needs a device with outputs; %s has none (try --device NAME for an interface)\n",
+ d.name.c_str()), false;
+ if (o.out == OutMode::Mute && d.outChannels == 0) std::fprintf(stderr, "note: %s has no outputs, so there is nothing to mute\n", d.name.c_str());
+ return true;
+}
+
+int runLive(const Options& o) {
+ const auto devices = ca::listDevices();
+ ca::DeviceInfo dev;
+ std::string why;
+ if (!ca::pickDevice(devices, o.device, true, dev, why)) return std::fprintf(stderr, "squatch-tuner-live: %s\n", why.c_str()), 2;
+ if (!checkDevice(dev, o)) return 2;
+ Engine& e = gEngine;
+ e.core.configure(static_cast(dev.rate), o.a4, o.minHz);
+ e.render = new (e.renderStorage) TunerRender(e.core, static_cast(o.input - 1), o.out, dev.rate);
+ liveA4().store(o.a4);
+ installStopSignals();
+ ca::Stream stream;
+ if (!stream.start(dev.id, onAudio, &e, why)) return std::fprintf(stderr, "squatch-tuner-live: %s\n", why.c_str()), 2;
+ CoreAudioBackend be(dev, e.clock);
+ be.refreshLatency();
+ std::fprintf(stderr, "squatch-tuner-live: %s, %.0f Hz, buffer %u frames, input channel %d, capture latency %.2f ms (CoreAudio)\n", dev.name.c_str(),
+ be.rate(), be.period(), o.input, be.captureMs());
+ std::thread(readCommands).detach();
+ Publisher(e.core, be, o.input).run(o.rateHz);
+ stream.stop();
+ return 0;
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ Options o;
+ if (!parseArgs(argc, argv, o, true)) return usage();
+ if (o.listDevices) return ca::printDevices(ca::listDevices(), stdout), 0;
+ if (o.file) return runFile(o, gEngine.core);
+ return runLive(o);
+}
diff --git a/hosts/coreaudio/tuner_render.hpp b/hosts/coreaudio/tuner_render.hpp
new file mode 100644
index 0000000..852605c
--- /dev/null
+++ b/hosts/coreaudio/tuner_render.hpp
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: MIT
+// The CoreAudio host's audio callback body, with no CoreAudio types: pick one input channel out of
+// the device's buffers, run Core::processBlock on it, and write the outputs the way --out says
+// (none and mute: silence; thru: the input on outputs 1 and 2). The IOProc in
+// tuner_live.cpp is a thin wrapper that turns an AudioBufferList into Chunks; the offline test calls
+// render() directly with test buffers, so the same code that runs on the device is the code tested.
+// Real-time safe: static scratch, no allocation, no locks.
+#pragma once
+#include
+
+#include "../common/tuner_host.hpp"
+#include "audio_chunks.hpp"
+
+namespace squatch::host::live {
+
+class TunerRender {
+ public:
+ TunerRender(Core& core, uint32_t channel, OutMode mode, double rate)
+ : core_(core), channel_(channel), mode_(mode), nsPerFrame_(1e9 / rate) {}
+
+ /// `firstFrameNs`: the host time of the first input frame, in the backend's clock; each block is stamped
+ /// with the time of its last frame. `in` or `out` may be empty (an output-only or input-only device).
+ void render(audio::Chunks in, audio::Chunks out, uint64_t firstFrameNs) {
+ audio::clearAll(out); // the HAL does not promise zeroed output buffers
+ const uint32_t frames = audio::framesOf(in);
+ for (uint32_t done = 0; done < frames;) {
+ const uint32_t n = audio::gatherChannel(in, channel_, done, scratch_.data(), static_cast(scratch_.size()));
+ const auto stamp = firstFrameNs + static_cast(static_cast(done + n) * nsPerFrame_);
+ core_.processBlock(scratch_.data(), static_cast(n), stamp);
+ if (mode_ == OutMode::Thru) audio::scatterMono(out, 2, done, scratch_.data(), n);
+ done += n;
+ }
+ }
+
+ private:
+ Core& core_;
+ uint32_t channel_; // 0-based
+ OutMode mode_;
+ double nsPerFrame_;
+ std::array scratch_{};
+};
+
+} // namespace squatch::host::live
diff --git a/hosts/jack/jack_session.hpp b/hosts/jack/jack_session.hpp
index 1010493..ba0f0a1 100644
--- a/hosts/jack/jack_session.hpp
+++ b/hosts/jack/jack_session.hpp
@@ -1,31 +1,16 @@
// SPDX-License-Identifier: MIT
// Plumbing shared by the JACK programs here: open a client, stop cleanly on a signal or when
-// jackd goes away, and small time helpers. Nothing in this file runs in the audio callback
-// except nowNs(), which is clock_gettime on the vDSO (no system call, no lock).
+// jackd goes away. The run flag, clocks and sleep are in ../common/host_clock.hpp.
#pragma once
#include
-#include
#include
-#include
-#include
#include
-#include
-namespace squatch::host {
-
-inline std::atomic& running() {
- static std::atomic flag{true};
- return flag;
-}
+#include "../common/host_clock.hpp"
-inline uint64_t nowNs(clockid_t clock = CLOCK_MONOTONIC) {
- timespec t;
- clock_gettime(clock, &t);
- return static_cast(t.tv_sec) * 1000000000ull + static_cast(t.tv_nsec);
-}
+namespace squatch::host {
-inline void onStopSignal(int) { running().store(false); }
inline void onJackShutdown(void*) { running().store(false); }
/// Connect to a running jackd (never start one) and arrange a clean stop. Null on failure.
@@ -37,9 +22,7 @@ inline jack_client_t* openClient(const char* name) {
return nullptr;
}
jack_on_shutdown(c, onJackShutdown, nullptr);
- std::signal(SIGINT, onStopSignal);
- std::signal(SIGTERM, onStopSignal);
- std::signal(SIGPIPE, onStopSignal); // the reader of our stdout went away
+ installStopSignals();
return c;
}
@@ -50,28 +33,4 @@ inline bool connectPorts(jack_client_t* c, const char* from, const char* to) {
return rc == 0 || rc == EEXIST;
}
-/// Sleep until an absolute CLOCK_MONOTONIC time, then advance it by `periodNs`.
-/// macOS has no clock_nanosleep, so there it sleeps for the time left, read from the same clock.
-inline void sleepUntil(uint64_t& deadlineNs, uint64_t periodNs) {
- deadlineNs += periodNs;
-#if defined(__APPLE__)
- for (;;) {
- timespec now;
- clock_gettime(CLOCK_MONOTONIC, &now);
- const uint64_t nowNs = static_cast(now.tv_sec) * 1000000000ull + static_cast(now.tv_nsec);
- if (nowNs >= deadlineNs) return;
- const uint64_t left = deadlineNs - nowNs;
- timespec t;
- t.tv_sec = static_cast(left / 1000000000ull);
- t.tv_nsec = static_cast(left % 1000000000ull);
- if (nanosleep(&t, nullptr) == 0) return; // interrupted by a signal: go round with the time still left
- }
-#else
- timespec t;
- t.tv_sec = static_cast(deadlineNs / 1000000000ull);
- t.tv_nsec = static_cast(deadlineNs % 1000000000ull);
- clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, nullptr);
-#endif
-}
-
} // namespace squatch::host
diff --git a/hosts/jack/tone.cpp b/hosts/jack/tone.cpp
index ebae8e1..9343ec3 100644
--- a/hosts/jack/tone.cpp
+++ b/hosts/jack/tone.cpp
@@ -13,24 +13,23 @@
#include
#include
-#include
#include
#include
#include
+#include "../common/tone_gen.hpp"
#include "jack_session.hpp"
namespace {
using squatch::host::nowNs;
using squatch::host::running;
+using squatch::host::ToneGen;
struct Tone {
jack_client_t* client = nullptr;
jack_port_t* out = nullptr;
- double phase = 0.0, step = 0.0; // turns, turns per sample
- float amp = 0.1f, gain = 0.0f, fadeStep = 0.0f;
- std::atomic target{0.0f}; // 0 until connected, so the start time is the real one
+ ToneGen gen;
std::atomic firstFrame{0};
std::atomic started{false};
};
@@ -40,17 +39,12 @@ Tone gTone;
int process(jack_nframes_t n, void* arg) {
Tone& t = *static_cast(arg);
auto* o = static_cast(jack_port_get_buffer(t.out, n));
- const float target = t.target.load(std::memory_order_relaxed);
+ const float target = t.gen.target.load(std::memory_order_relaxed);
if (target > 0.0f && !t.started.load(std::memory_order_relaxed)) {
t.firstFrame.store(jack_last_frame_time(t.client), std::memory_order_relaxed);
t.started.store(true, std::memory_order_release);
}
- for (jack_nframes_t i = 0; i < n; ++i) {
- t.gain = t.gain < target ? std::min(t.gain + t.fadeStep, target) : std::max(t.gain - t.fadeStep, target);
- o[i] = t.amp * t.gain * static_cast(std::sin(6.283185307179586 * t.phase));
- t.phase += t.step;
- t.phase -= std::floor(t.phase);
- }
+ t.gen.fill(o, n);
return 0;
}
@@ -82,14 +76,14 @@ void reportStart(const Tone& t) {
const double ageUs = static_cast(jack_get_time() - jack_frames_to_time(t.client, t.firstFrame.load()));
const double outMs = 1000.0 * r.max / rate;
const double startMs = static_cast(nowNs(CLOCK_REALTIME)) / 1e6 - ageUs / 1e3 + outMs;
- std::printf("{\"toneStart\":%.1f,\"playMs\":%.2f,\"hz\":%.6f}\n", startMs, outMs, t.step * rate);
+ std::printf("{\"toneStart\":%.1f,\"playMs\":%.2f,\"hz\":%.6f}\n", startMs, outMs, t.gen.step * rate);
std::fflush(stdout);
}
void playUntilStopped(Tone& t, double seconds) {
const uint64_t end = seconds > 0.0 ? nowNs() + static_cast(seconds * 1e9) : UINT64_MAX;
while (running().load() && nowNs() < end) std::this_thread::sleep_for(std::chrono::milliseconds(20));
- t.target.store(0.0f); // fade out, then close
+ t.gen.target.store(0.0f); // fade out, then close
std::this_thread::sleep_for(std::chrono::milliseconds(40));
}
@@ -104,14 +98,12 @@ int main(int argc, char** argv) {
Tone& t = gTone;
if (!(t.client = squatch::host::openClient("squatch-tone"))) return 2;
const double rate = jack_get_sample_rate(t.client);
- t.step = a.hz / rate;
- t.amp = static_cast(std::pow(10.0, a.db / 20.0));
- t.fadeStep = static_cast(1.0 / (0.010 * rate));
+ t.gen.configure(a.hz, a.db, rate);
t.out = jack_port_register(t.client, "out", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
jack_set_process_callback(t.client, process, &t);
if (!t.out || jack_activate(t.client) != 0) return 2;
if (!squatch::host::connectPorts(t.client, jack_port_name(t.out), a.port)) return 2;
- t.target.store(1.0f);
+ t.gen.target.store(1.0f);
reportStart(t);
playUntilStopped(t, a.seconds);
jack_client_close(t.client);
diff --git a/hosts/jack/tuner_live.cpp b/hosts/jack/tuner_live.cpp
index 6f4cbb3..78554ae 100644
--- a/hosts/jack/tuner_live.cpp
+++ b/hosts/jack/tuner_live.cpp
@@ -23,77 +23,31 @@
// SIGTERM or SIGINT stops it cleanly; so does jackd going away or the reader of stdout closing.
#include
#include
-#include
-#include
-#include
#include
-#include
-#include
-#include
-#include
#include
-#include "../common/display.hpp"
-#include "../common/ir_file.hpp"
-#include "../common/latest.hpp"
+#include "../common/tuner_publisher.hpp"
#include "jack_session.hpp"
namespace {
-using squatch::host::DisplayReading;
-using squatch::host::Latest;
-using squatch::host::nowNs;
-using squatch::host::running;
+using namespace squatch::host;
+using namespace squatch::host::live;
-constexpr float kMinA4 = 430.0f, kMaxA4 = 450.0f;
-
-enum class OutMode { None, Mute, Thru };
-
-struct Options {
- int input = 1;
- OutMode out = OutMode::None;
- float a4 = 440.0f;
- float rateHz = 30.0f;
- float minHz = 38.0f;
- const char* file = nullptr;
-};
-
-// What the audio callback hands over, once per callback.
-struct Frame {
- squatch::tuner::TunerReading reading{};
- float peak = 0.0f; // decaying |x| peak: falls 20 dB per second
- jack_nframes_t frameTime = 0; // JACK frame time at the start of this cycle
- uint64_t callbacks = 0; // cumulative
- uint64_t samples = 0; // input samples the tuner has heard: where in the audio `reading` is
- uint64_t busyNs = 0; // cumulative time spent inside process()
- uint32_t worstNs = 0; // longest single process() so far
-};
-
-// Everything the realtime callback touches. Static storage: the Tuner alone is ~128 kB.
+// The JACK side of the host: ports, and the real-time callback around Core::processBlock.
struct Engine {
jack_client_t* client = nullptr;
jack_port_t* in = nullptr;
std::array out{};
OutMode outMode = OutMode::None;
- squatch::tuner::Tuner tuner;
- Latest latest;
- float peak = 0.0f;
- float decayLog2PerFrame = 0.0f;
- uint64_t callbacks = 0, busyNs = 0, samples = 0;
- uint32_t worstNs = 0;
+ Core core;
};
Engine gEngine;
-std::atomic gA4{440.0f};
// ---------------------------------------------------------------- realtime ----
-float blockPeak(const float* x, jack_nframes_t n, float held) {
- for (jack_nframes_t i = 0; i < n; ++i) held = std::max(held, std::fabs(x[i]));
- return held;
-}
-
void writeOutputs(Engine& e, const float* in, jack_nframes_t n) {
for (jack_port_t* p : e.out) {
if (!p) continue;
@@ -105,53 +59,14 @@ void writeOutputs(Engine& e, const float* in, jack_nframes_t n) {
int process(jack_nframes_t n, void* arg) {
Engine& e = *static_cast(arg);
- const uint64_t t0 = nowNs();
const auto* in = static_cast(jack_port_get_buffer(e.in, n));
- e.tuner.process(in, static_cast(n));
- e.samples += n;
- e.peak = blockPeak(in, n, e.peak * std::exp2(-e.decayLog2PerFrame * static_cast(n)));
+ e.core.processBlock(in, static_cast(n), jack_last_frame_time(e.client));
writeOutputs(e, in, n);
- const auto dt = static_cast(std::min(nowNs() - t0, UINT32_MAX));
- e.busyNs += dt;
- e.worstNs = std::max(e.worstNs, dt);
- Frame& f = e.latest.back();
- f.reading = e.tuner.reading();
- f.peak = e.peak;
- f.frameTime = jack_last_frame_time(e.client);
- f.callbacks = ++e.callbacks;
- f.samples = e.samples;
- f.busyNs = e.busyNs;
- f.worstNs = e.worstNs;
- e.latest.publish();
return 0;
}
// ---------------------------------------------------------------- set-up ----
-bool parseOut(std::string_view v, OutMode& m) {
- if (v == "none") m = OutMode::None;
- else if (v == "mute") m = OutMode::Mute;
- else if (v == "thru") m = OutMode::Thru;
- else return false;
- return true;
-}
-
-bool applyOption(std::string_view key, const char* v, Options& o) {
- if (key == "--input") return (o.input = std::atoi(v)) >= 1;
- if (key == "--out") return parseOut(v, o.out);
- if (key == "--a4") return (o.a4 = std::strtof(v, nullptr)) >= kMinA4 && o.a4 <= kMaxA4;
- if (key == "--rate") return (o.rateHz = std::strtof(v, nullptr)) >= 1.0f && o.rateHz <= 120.0f;
- if (key == "--min-hz") return (o.minHz = std::strtof(v, nullptr)) >= 20.0f && o.minHz <= 200.0f;
- if (key == "--file") return (o.file = v) != nullptr;
- return false;
-}
-
-bool parseArgs(int argc, char** argv, Options& o) {
- for (int i = 1; i < argc; i += 2)
- if (i + 1 >= argc || !applyOption(argv[i], argv[i + 1], o)) return false;
- return true;
-}
-
void registerOutputs(Engine& e, OutMode mode) {
e.outMode = mode;
if (mode == OutMode::None) return;
@@ -162,24 +77,17 @@ void registerOutputs(Engine& e, OutMode mode) {
void connectAll(const Engine& e, const Options& o) {
char from[64], to[64];
std::snprintf(from, sizeof from, "system:capture_%d", o.input);
- squatch::host::connectPorts(e.client, from, jack_port_name(e.in));
+ connectPorts(e.client, from, jack_port_name(e.in));
for (int k = 0; k < 2; ++k) {
if (!e.out[k]) continue;
std::snprintf(to, sizeof to, "system:playback_%d", k + 1);
- squatch::host::connectPorts(e.client, jack_port_name(e.out[k]), to);
+ connectPorts(e.client, jack_port_name(e.out[k]), to);
}
}
-// configure() builds tables and is not real-time safe, so it runs before activation.
bool setUp(Engine& e, jack_client_t* c, const Options& o) {
e.client = c;
- const auto rate = static_cast(jack_get_sample_rate(c));
- squatch::tuner::TunerConfig cfg;
- cfg.sampleRate = rate;
- cfg.a4 = o.a4;
- cfg.minHz = o.minHz;
- e.tuner.configure(cfg);
- e.decayLog2PerFrame = 1.0f / (std::log10(2.0f) * rate); // -20 dB/s = one decade per second
+ e.core.configure(static_cast(jack_get_sample_rate(c)), o.a4, o.minHz);
e.in = jack_port_register(c, "in", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
registerOutputs(e, o.out);
if (!e.in || (o.out != OutMode::None && !e.out[1])) return false;
@@ -190,111 +98,17 @@ bool setUp(Engine& e, jack_client_t* c, const Options& o) {
return true;
}
-// ---------------------------------------------------------------- commands ----
-
-void applyCommand(const char* line) {
- float hz = 0.0f;
- if (std::sscanf(line, "a4 %f", &hz) == 1 && hz >= kMinA4 && hz <= kMaxA4) gA4.store(hz);
-}
-
-// Raw read(2), not fgets: a thread blocked in fgets holds stdin's FILE lock, and exit() takes
-// every FILE lock to flush, so the program could never exit while this thread waits for input.
-void readCommands() {
- char line[128];
- size_t len = 0;
- char c;
- while (read(STDIN_FILENO, &c, 1) == 1) {
- if (c != '\n') {
- if (len < sizeof line - 1) line[len++] = c; // an overlong line is cut, not overrun
- continue;
- }
- line[len] = '\0';
- applyCommand(line);
- len = 0;
- }
-}
-
-// ---------------------------------------------------------------- publisher ----
+// ---------------------------------------------------------------- publisher backend ----
-double dbfs(float x) { return 20.0 * std::log10(std::max(x, 1e-6f)); }
-
-// What the page draws, as the start of one JSON object (the caller closes it). The cents and the
-// uncertainty go at full float precision (%.9g, as the phone sends them): the page rounds the number
-// and filters its hold itself, so it must see the values every other display sees. `samples` and
-// `rate` say where in the audio the reading was taken: the page's hold runs on that clock (hold.js).
-struct AudioPos {
- uint64_t samples;
- double rate;
-};
-void printDisplay(const squatch::tuner::TunerReading& r, float peak, float a4, AudioPos at) {
- const DisplayReading d = squatch::host::toDisplay(r, a4);
- std::printf("{\"valid\":%s,\"note\":\"%s\",\"oct\":%d,\"midi\":%d,\"cents\":%.9g,\"fast\":%.3f,\"hz\":%.4f,\"shz\":%.4f,",
- d.valid ? "true" : "false", d.note.name, d.note.octave, d.midi, d.cents, d.fastCents, d.hz, d.steadyHz);
- std::printf("\"unc\":%.9g,\"parts\":%d,\"B\":%.3g,\"a4\":%.2f,\"lvl\":%.1f,\"pk\":%.1f,\"turns\":[", r.uncertainty, r.partials,
- r.inharmonicity, a4, dbfs(r.level), dbfs(peak));
- for (int k = 0; k < r.partials; ++k) std::printf(k ? ",%.4f" : "%.4f", r.strobeTurns[k]);
- std::printf("],\"samples\":%llu,\"rate\":%.0f", static_cast(at.samples), at.rate);
-}
-
-uint64_t processCpuNs() {
- rusage u{};
- getrusage(RUSAGE_SELF, &u);
- const auto ns = [](const timeval& t) { return static_cast(t.tv_sec) * 1000000000ull + t.tv_usec * 1000ull; };
- return ns(u.ru_utime) + ns(u.ru_stime);
-}
-
-struct Load {
- double dspPct = 0.0; // time in process() / time available, since the last line
- double worstPct = 0.0; // longest process() so far / one period
- double cpuPct = 0.0; // this process, all threads, % of one core
- double jackPct = 0.0; // jackd's own figure for the whole graph
-};
-
-class Publisher {
+class JackBackend {
public:
- Publisher(Engine& e, const Options& o) : e_(e), rate_(jack_get_sample_rate(e.client)), input_(o.input) {
- period_ = jack_get_buffer_size(e.client);
- refreshLatency();
- std::fprintf(stderr, "squatch-tuner-live: %.0f Hz, period %u, input system:capture_%d, capture latency %.2f ms, realtime %s\n",
- rate_, period_, o.input, captureMs_, jack_is_realtime(e.client) ? "yes" : "NO");
- last_ = Sample{0, 0, processCpuNs(), nowNs()};
- }
+ static constexpr bool kWarnDigitalSilence = false;
+ explicit JackBackend(const Engine& e) : e_(e), rate_(jack_get_sample_rate(e.client)), period_(jack_get_buffer_size(e.client)) {}
- void run(float rateHz) {
- const auto step = static_cast(1e9 / rateHz);
- uint64_t deadline = nowNs();
- while (running().load()) {
- squatch::host::sleepUntil(deadline, step);
- if (e_.latest.update()) {
- have_ = true;
- freshNs_ = nowNs();
- }
- // A stalled graph (driver stopped, jackd suspended) stops process(); the last frame must
- // not be repeated as if it were live, or the page shows a frozen note. Silence lets the
- // bridge declare the stream stale.
- if (have_ && nowNs() - freshNs_ < kStaleNs) line(e_.latest.front());
- }
- }
-
- private:
- struct Sample {
- uint64_t callbacks, busyNs, cpuNs, wallNs;
- };
- static constexpr uint64_t kStaleNs = 250000000ull; // 250 ms: about 190 periods at 64 / 48 kHz
- uint64_t freshNs_ = 0;
-
- Load load(const Frame& f) {
- const Sample now{f.callbacks, f.busyNs, processCpuNs(), nowNs()};
- const double periodNs = 1e9 * period_ / rate_;
- Load l;
- if (now.callbacks > last_.callbacks)
- l.dspPct = 100.0 * static_cast(now.busyNs - last_.busyNs) / (periodNs * static_cast(now.callbacks - last_.callbacks));
- if (now.wallNs > last_.wallNs) l.cpuPct = 100.0 * static_cast(now.cpuNs - last_.cpuNs) / static_cast(now.wallNs - last_.wallNs);
- l.worstPct = 100.0 * f.worstNs / periodNs;
- l.jackPct = jack_cpu_load(e_.client);
- last_ = now;
- return l;
- }
+ double rate() const { return rate_; }
+ uint32_t period() const { return period_; }
+ double captureMs() const { return captureMs_; }
+ double serverLoadPct() const { return jack_cpu_load(e_.client); }
// JACK recomputes port latencies after connections change, so this is read again each line.
void refreshLatency() {
@@ -308,28 +122,16 @@ class Publisher {
// The difference is signed: JACK's filtered cycle-start estimate can run microseconds ahead of
// jack_get_time(), and unsigned it wrapped to 2^64 us (tin came out near -1.8e16 ms).
double inputTimeMs(const Frame& f) const {
- const auto age = static_cast(jack_get_time() - jack_frames_to_time(e_.client, f.frameTime));
+ const auto age = static_cast(jack_get_time() - jack_frames_to_time(e_.client, static_cast(f.cycleStamp)));
const double ageUs = static_cast(age);
return static_cast(nowNs(CLOCK_REALTIME)) / 1e6 - ageUs / 1e3 - captureMs_;
}
- void line(const Frame& f) {
- const float a4 = gA4.load();
- const Load l = load(f);
- refreshLatency();
- printDisplay(f.reading, f.peak, a4, {f.samples, rate_});
- std::printf(",\"input\":%d,\"tin\":%.1f,\"capMs\":%.2f,\"period\":%u,", input_, inputTimeMs(f), captureMs_, period_);
- std::printf("\"dsp\":%.2f,\"dspWorst\":%.1f,\"cpu\":%.2f,\"jack\":%.1f}\n", l.dspPct, l.worstPct, l.cpuPct, l.jackPct);
- if (std::fflush(stdout) != 0) running().store(false); // the reader has gone
- }
-
- Engine& e_;
+ private:
+ const Engine& e_;
double rate_;
- int input_;
- jack_nframes_t period_ = 0;
+ jack_nframes_t period_;
double captureMs_ = 0.0;
- Sample last_{};
- bool have_ = false;
};
int usage() {
@@ -338,48 +140,26 @@ int usage() {
return 64;
}
-// --file: the realtime path without JACK. 64-frame periods, the peak meter as in process(), and a
-// display line after the period that crosses each 1/rate s of file time.
-int runFile(const Options& o) {
- constexpr size_t kPeriod = 64;
- const squatch::host::Wav w = squatch::host::readWav(o.file);
- if (!w.error.empty()) return std::fprintf(stderr, "squatch-tuner-live: %s: %s\n", o.file, w.error.c_str()), 2;
- Engine& e = gEngine;
- squatch::tuner::TunerConfig cfg;
- cfg.sampleRate = static_cast(w.rate);
- cfg.a4 = o.a4;
- cfg.minHz = o.minHz;
- e.tuner.configure(cfg);
- e.decayLog2PerFrame = 1.0f / (std::log10(2.0f) * cfg.sampleRate);
- const double step = w.rate / o.rateHz;
- double next = step;
- for (size_t i = 0; i + kPeriod <= w.samples.size(); i += kPeriod) {
- e.tuner.process(&w.samples[i], static_cast(kPeriod));
- e.peak = blockPeak(&w.samples[i], kPeriod, e.peak * std::exp2(-e.decayLog2PerFrame * static_cast(kPeriod)));
- for (; next <= static_cast(i + kPeriod); next += step) {
- printDisplay(e.tuner.reading(), e.peak, o.a4, {i + kPeriod, w.rate});
- std::printf(",\"t\":%.17g}\n", 1000.0 * static_cast(i + kPeriod) / w.rate); // exact: the hold's 500 ms edge
- }
- }
- return 0;
-}
-
} // namespace
int main(int argc, char** argv) {
Options o;
if (!parseArgs(argc, argv, o)) return usage();
- if (o.file) return runFile(o);
- gA4.store(o.a4);
- jack_client_t* c = squatch::host::openClient("squatch-tuner");
+ if (o.file) return runFile(o, gEngine.core);
+ liveA4().store(o.a4);
+ jack_client_t* c = openClient("squatch-tuner");
if (!c) return 2;
if (!setUp(gEngine, c, o)) {
std::fprintf(stderr, "squatch-tuner-live: could not register or activate the JACK client\n");
jack_client_close(c);
return 2;
}
+ JackBackend be(gEngine);
+ be.refreshLatency();
+ std::fprintf(stderr, "squatch-tuner-live: %.0f Hz, period %u, input system:capture_%d, capture latency %.2f ms, realtime %s\n", be.rate(),
+ be.period(), o.input, be.captureMs(), jack_is_realtime(c) ? "yes" : "NO");
std::thread(readCommands).detach();
- Publisher(gEngine, o).run(o.rateHz);
+ Publisher(gEngine.core, be, o.input).run(o.rateHz);
jack_client_close(c);
return 0;
}
diff --git a/hosts/tests/test_host_audio.cpp b/hosts/tests/test_host_audio.cpp
new file mode 100644
index 0000000..db12a14
--- /dev/null
+++ b/hosts/tests/test_host_audio.cpp
@@ -0,0 +1,264 @@
+// SPDX-License-Identifier: MIT
+// The CoreAudio host's audio path, tested offline with no audio device and no CoreAudio (so any CI machine
+// runs it): a test tone goes through the same TunerRender that the macOS IOProc calls, in the buffer shapes
+// CoreAudio delivers (interleaved, one stream per channel, odd sizes), and the detected pitch, the channel
+// pick, the outputs of --out none|mute|thru and the real-time rule (no allocation) are checked.
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "../common/tone_gen.hpp"
+#include "../common/tuner_host.hpp"
+#include "../coreaudio/audio_chunks.hpp"
+#include "../coreaudio/tuner_render.hpp"
+
+using namespace squatch::host;
+using namespace squatch::host::live;
+using squatch::host::audio::Chunk;
+
+static int gFailures = 0;
+#define CHECK(cond, ...) \
+ do { \
+ if (!(cond)) { \
+ ++gFailures; \
+ std::printf("FAIL %s:%d: %s ", __FILE__, __LINE__, #cond); \
+ std::printf(__VA_ARGS__); \
+ std::printf("\n"); \
+ } \
+ } while (0)
+
+// Every global allocation made while armed is counted: the audio callback must make none.
+static bool gArmed = false;
+static long gNews = 0;
+// noinline: GCC 13 otherwise sees malloc paired with free through the inlined new/delete and warns.
+[[gnu::noinline]] void* operator new(std::size_t n) {
+ if (gArmed) ++gNews;
+ void* p = std::malloc(n ? n : 1);
+ if (!p) std::abort();
+ return p;
+}
+[[gnu::noinline]] void operator delete(void* p) noexcept { std::free(p); }
+[[gnu::noinline]] void operator delete(void* p, std::size_t) noexcept { std::free(p); }
+
+namespace {
+
+constexpr double kRate = 48000.0;
+
+Core& freshCore(float a4 = 440.0f) {
+ static Core* core = nullptr;
+ delete core; // a Core is ~130 kB: heap, not stack
+ core = new Core;
+ core->configure(static_cast(kRate), a4, 38.0f);
+ return *core;
+}
+
+// `seconds` of a test tone on channel `tone` of a `channels`-wide interleaved device; the other channels
+// carry a different tone, so picking the wrong one is visible.
+std::vector deviceInput(uint32_t channels, uint32_t tone, double hz, double seconds) {
+ const auto frames = static_cast(seconds * kRate);
+ std::vector buf(static_cast(frames) * channels, 0.0f);
+ ToneGen want, other;
+ want.configure(hz, -12.0, kRate);
+ other.configure(hz * 1.5, -12.0, kRate);
+ want.target.store(1.0f);
+ other.target.store(1.0f);
+ for (uint32_t c = 0; c < channels; ++c) (c == tone ? want : other).fill(buf.data() + c, frames, channels);
+ return buf;
+}
+
+struct Result {
+ squatch::host::DisplayReading shown;
+ bool valid = false;
+};
+
+Result lastReading(Core& core) {
+ core.latest.update();
+ const auto& r = core.latest.front().reading;
+ return {toDisplay(r, 440.0f), r.valid};
+}
+
+// The device's shape: input channels, output channels (0: an input-only device), frames per callback.
+struct Shape {
+ uint32_t in, out, block;
+};
+
+// Runs the interleaved `in` through `render` in callbacks of `shape.block` frames (the last one shorter).
+void feed(TunerRender& render, std::vector& in, Shape shape, std::vector* out = nullptr) {
+ const auto frames = static_cast(in.size() / shape.in);
+ for (uint32_t at = 0; at < frames; at += shape.block) {
+ const uint32_t n = std::min(shape.block, frames - at);
+ Chunk ic{shape.in, static_cast(n * shape.in * sizeof(float)), in.data() + static_cast(at) * shape.in};
+ Chunk oc{shape.out, static_cast(n * shape.out * sizeof(float)), out ? out->data() + static_cast(at) * shape.out : nullptr};
+ render.render({&ic, 1}, {out ? &oc : nullptr, out ? 1u : 0u}, 1000 + at);
+ }
+}
+
+void testPitchThroughTheHostLayer() {
+ for (const uint32_t block : {512u, 64u, 37u, 4100u}) { // 4100 is past the render scratch: the block loop splits it
+ Core& core = freshCore();
+ TunerRender render(core, 1, OutMode::None, kRate);
+ auto in = deviceInput(4, 1, 110.0, 2.0);
+ feed(render, in, {4, 0, block});
+ const Result r = lastReading(core);
+ CHECK(r.valid, "block %u: no pitch found", block);
+ CHECK(r.shown.midi == 45, "block %u: midi %d, want 45 (A2)", block, r.shown.midi);
+ CHECK(std::fabs(r.shown.hz - 110.0) < 0.01, "block %u: %.4f Hz, want 110", block, r.shown.hz);
+ CHECK(std::fabs(r.shown.cents) < 0.2, "block %u: %.3f cents off", block, r.shown.cents);
+ }
+}
+
+void testA4Reference() {
+ Core& core = freshCore(432.0f);
+ TunerRender render(core, 0, OutMode::None, kRate);
+ auto in = deviceInput(1, 0, 108.0, 2.0); // A2 at A4 = 432 is 108 Hz
+ feed(render, in, {1, 0, 256});
+ core.latest.update();
+ const auto d = toDisplay(core.latest.front().reading, 432.0f);
+ CHECK(d.midi == 45 && std::fabs(d.cents) < 0.2, "A4=432: midi %d, %.3f cents", d.midi, d.cents);
+}
+
+void testChannelPick() {
+ Core& core = freshCore();
+ TunerRender wrong(core, 0, OutMode::None, kRate); // channel 0 carries 165 Hz, not the 110 Hz on channel 1
+ auto in = deviceInput(2, 1, 110.0, 2.0);
+ feed(wrong, in, {2, 0, 512});
+ const Result r = lastReading(core);
+ CHECK(!r.valid || std::fabs(r.shown.hz - 165.0) < 0.1, "channel 0 gave %.3f Hz", r.shown.hz);
+ Core& core2 = freshCore();
+ TunerRender missing(core2, 7, OutMode::None, kRate); // a channel the device does not have reads as silence
+ feed(missing, in, {2, 0, 512});
+ CHECK(!lastReading(core2).valid, "a missing channel produced a pitch");
+}
+
+void testOutputs() {
+ const OutMode modes[] = {OutMode::None, OutMode::Mute, OutMode::Thru};
+ for (const OutMode mode : modes) {
+ Core& core = freshCore();
+ TunerRender render(core, 1, mode, kRate);
+ auto in = deviceInput(4, 1, 110.0, 0.5);
+ std::vector out(in.size() / 4 * 4, 9.0f); // 4 outputs, pre-filled: the host must not leave them
+ feed(render, in, {4, 4, 512}, &out);
+ long wrong = 0;
+ for (size_t i = 0; i < out.size() / 4; ++i) {
+ const float want = mode == OutMode::Thru ? in[i * 4 + 1] : 0.0f;
+ wrong += out[i * 4 + 0] != want || out[i * 4 + 1] != want || out[i * 4 + 2] != 0.0f || out[i * 4 + 3] != 0.0f;
+ }
+ CHECK(wrong == 0, "mode %d: %ld frames with a wrong output", static_cast(mode), wrong);
+ }
+}
+
+void testOneStreamPerChannel() { // some devices present each channel as its own buffer
+ Core& core = freshCore();
+ TunerRender render(core, 1, OutMode::Thru, kRate);
+ const auto frames = static_cast(2.0 * kRate);
+ std::vector a(frames, 0.0f), b(frames), oa(frames, 9.0f), ob(frames, 9.0f);
+ ToneGen t;
+ t.configure(110.0, -12.0, kRate);
+ t.target.store(1.0f);
+ t.fill(b.data(), frames);
+ for (uint32_t at = 0; at < frames; at += 480) {
+ const uint32_t n = std::min(480u, frames - at), bytes = n * 4;
+ Chunk ic[2] = {{1, bytes, a.data() + at}, {1, bytes, b.data() + at}};
+ Chunk oc[2] = {{1, bytes, oa.data() + at}, {1, bytes, ob.data() + at}};
+ render.render({ic, 2}, {oc, 2}, 0);
+ }
+ const Result r = lastReading(core);
+ CHECK(r.valid && r.shown.midi == 45 && std::fabs(r.shown.hz - 110.0) < 0.01, "split streams: %.4f Hz", r.shown.hz);
+ CHECK(oa == b && ob == b, "thru over split streams did not copy input 2 to both outputs");
+}
+
+void testSameDspAsTheFilePath() { // runSamples is what --file runs; the live path must reach the same reading
+ const auto in = deviceInput(1, 0, 196.0, 2.0);
+ Core& live = freshCore();
+ std::vector copy(in);
+ TunerRender render(live, 0, OutMode::None, kRate);
+ feed(render, copy, {1, 0, 64});
+ live.latest.update();
+ const auto la = live.latest.front().reading;
+ Core& file = freshCore();
+ Options o;
+ runSamples(in, kRate, o, file, [](const Frame&, uint64_t, double) {});
+ file.latest.update();
+ const auto lb = file.latest.front().reading;
+ CHECK(la.hz == lb.hz && la.steadyHz == lb.steadyHz && la.level == lb.level, "live %.6f Hz vs file %.6f Hz", la.hz, lb.hz);
+}
+
+void testStampAndCounters() {
+ Core& core = freshCore();
+ TunerRender render(core, 0, OutMode::None, kRate);
+ std::vector in(480, 0.0f);
+ Chunk ic{1, 480 * 4, in.data()};
+ render.render({&ic, 1}, {}, 5000000);
+ core.latest.update();
+ const auto& f = core.latest.front();
+ CHECK(f.samples == 480 && f.callbacks == 1, "samples %llu callbacks %llu", static_cast(f.samples),
+ static_cast(f.callbacks));
+ CHECK(f.cycleStamp == 5000000 + 10000000, "stamp %llu, want the last frame's time 15000000", static_cast(f.cycleStamp));
+}
+
+void testNoAllocationInTheCallback() {
+ Core& core = freshCore();
+ TunerRender render(core, 1, OutMode::Thru, kRate);
+ auto in = deviceInput(4, 1, 110.0, 1.0);
+ std::vector out(in.size(), 0.0f);
+ gNews = 0;
+ gArmed = true;
+ feed(render, in, {4, 4, 512}, &out);
+ gArmed = false;
+ CHECK(gNews == 0, "the audio callback allocated %ld times", gNews);
+ gNews = 0; // negative control for the counter itself: an allocation while armed must be seen
+ gArmed = true;
+ delete new int(1);
+ gArmed = false;
+ CHECK(gNews == 1, "the allocation counter did not count (%ld)", gNews);
+}
+
+void testGatherScatterEdges() {
+ float dst[8] = {1, 1, 1, 1, 1, 1, 1, 1};
+ CHECK(audio::gatherChannel({}, 0, 0, dst, 8) == 0, "gather from nothing");
+ CHECK(audio::framesOf({}) == 0 && audio::channelsOf({}) == 0, "empty list");
+ float data[6] = {1, 2, 3, 4, 5, 6}; // 3 frames of 2 channels
+ Chunk c{2, sizeof data, data};
+ CHECK(audio::gatherChannel({&c, 1}, 1, 1, dst, 8) == 2 && dst[0] == 4 && dst[1] == 6, "gather offset 1 channel 1: %g %g", dst[0], dst[1]);
+ CHECK(audio::gatherChannel({&c, 1}, 0, 3, dst, 8) == 0, "gather past the end");
+ Chunk empty{2, 8, nullptr};
+ audio::clearAll({&empty, 1}); // a stream with no data pointer is skipped, not dereferenced
+}
+
+void testOptions() {
+ char prog[] = "squatch-tuner-live", dev[] = "--device", name[] = "umc", list[] = "--list-devices", in[] = "--input", two[] = "2";
+ char* withDevice[] = {prog, dev, name, in, two};
+ Options o;
+ CHECK(parseArgs(5, withDevice, o, true) && std::string_view(o.device) == "umc" && o.input == 2, "--device and --input");
+ Options jack;
+ CHECK(!parseArgs(5, withDevice, jack, false), "the JACK host must refuse --device");
+ char* withList[] = {prog, list};
+ Options l;
+ CHECK(parseArgs(2, withList, l, true) && l.listDevices, "--list-devices");
+ Options l2;
+ CHECK(!parseArgs(2, withList, l2, false), "the JACK host must refuse --list-devices");
+ char a4[] = "--a4", bad[] = "460";
+ char* badA4[] = {prog, a4, bad};
+ Options b;
+ CHECK(!parseArgs(3, badA4, b, true), "--a4 460 is out of range");
+}
+
+} // namespace
+
+int main() {
+ testPitchThroughTheHostLayer();
+ testA4Reference();
+ testChannelPick();
+ testOutputs();
+ testOneStreamPerChannel();
+ testSameDspAsTheFilePath();
+ testStampAndCounters();
+ testNoAllocationInTheCallback();
+ testGatherScatterEdges();
+ testOptions();
+ std::printf(gFailures ? "host audio: %d failure(s)\n" : "host audio: all tests passed\n", gFailures);
+ return gFailures ? 1 : 0;
+}
diff --git a/tools/export-public b/tools/export-public
index 7243eb9..a60a37a 100755
--- a/tools/export-public
+++ b/tools/export-public
@@ -81,10 +81,16 @@ TUNER_MAP = [
("hosts/common/hold.hpp", "hosts/common/hold.hpp"),
("hosts/common/tuner_frames.hpp", "hosts/common/tuner_frames.hpp"),
("hosts/common/ir_file.hpp", "hosts/common/ir_file.hpp"),
+ ("hosts/common/host_clock.hpp", "hosts/common/host_clock.hpp"),
+ ("hosts/common/tone_gen.hpp", "hosts/common/tone_gen.hpp"),
+ ("hosts/common/tuner_host.hpp", "hosts/common/tuner_host.hpp"),
+ ("hosts/common/tuner_publisher.hpp", "hosts/common/tuner_publisher.hpp"),
("hosts/jack/jack_session.hpp", "hosts/jack/jack_session.hpp"),
("hosts/jack/tone.cpp", "hosts/jack/tone.cpp"),
("hosts/jack/tuner_live.cpp", "hosts/jack/tuner_live.cpp"),
+ ("hosts/coreaudio", "hosts/coreaudio"),
("hosts/tests/test_hosts.cpp", "hosts/tests/test_hosts.cpp"),
+ ("hosts/tests/test_host_audio.cpp", "hosts/tests/test_host_audio.cpp"),
("hosts/web", "hosts/web"),
("hosts/wasm", "hosts/wasm"),
("tools/export-public", "tools/export-public"),