Skip to content

Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.

C

feat: JamesDSP's effects on everything Spotify plays, run on each buffer its output unit finishes

Vojtěch Škopek546245ee7307
diff --git a/docs/tweaks.md b/docs/tweaks.md
index a0b93ca9..c6d1d118 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -91,6 +91,13 @@ Shared:
LockScreenLyrics/ the line being sung in the system's now playing
Navigation/ the page transition fix (PageTransition.x) and opening a spotify: link (Links.x)
Player/ the player's open and close announced (PlayerEvents.x), the lock screen widget's flags
+ JamesDSP/ JamesDSP's effects on Spotify's sound (JamesDSP.h has the keys and the page's calls): Spotify's import of
+ AudioOutputUnitStart is rebound, as Music Haptics does, and a render notify on its RemoteIO unit runs
+ each finished buffer through SGDSPEngine.m, libjamesdsp re-blocked to 1024 frames one block late, in
+ place (JamesDSP.x). The buffers are in the unit's output format, the hardware's, not the client format
+ Spotify sets. Settings apply as they change, on a queue of its own; the file effects read their files
+ from Documents/spoti.pw/JamesDSP (JamesDSPFiles.m). Tested on the Mac against harness/jamesdsp/,
+ the hook in the simulator against its sim/
Native:
diff --git a/harness/jamesdsp/README.md b/harness/jamesdsp/README.md
new file mode 100644
index 00000000..4671fa8c
--- /dev/null
+++ b/harness/jamesdsp/README.md
@@ -0,0 +1,50 @@
+# JamesDSP harness
+
+Two halves, both building libjamesdsp (`vendor/libjamesdsp`) for their platform first.
+
+## The engine on the Mac (`main.m`)
+
+`SGDSPEngine.m` as the tweak compiles it, over the Mac build of libjamesdsp. A song decoded with ExtAudioFile
+goes through the engine in the slices iOS hands its output unit (1024, 4096, 470 and 471 in turn, 512, and a
+mix down to single frames), and each check prints a line: bypass exact to the sample one block late, no
+allocation on the render thread (malloc, calloc and realloc are the executable's own here, so libjamesdsp's
+calls land in them), nothing not finite or over the limiter with every effect on, bass boost and equalizer
+presets by band, every bundled Liveprog script and DDC preset, broken inputs refused with the file's line,
+the convolver reproducing RootlessJamesDSP's Church.wav from an impulse, sample rate changes, a reset, a
+thread changing settings while another processes, and what each effect costs. WAVs go to the out dir.
+
+ ./build.sh && build/jamesdsp <song> <Church.wav> <out dir>
+ ./build.sh thread && build/jamesdsp-thread <song> <Church.wav> <out dir> stress
+ ./build.sh address && build/jamesdsp-address <song> <Church.wav> <out dir>
+
+Church.wav is in RootlessJamesDSP's `app/src/main/assets/Convolver/`, not in this repo.
+
+2026-09-18, M-series Mac: every check passes, and under ThreadSanitizer (no report) and AddressSanitizer
+(which found the interpolator's overread, fixed in the vendored copy). A 1024-frame block at 48 kHz (21.3 ms
+of sound) costs under 0.01 ms with every effect off and about 1 ms with every effect on (4.8% of real time,
+about 3 ms at the worst block); the convolver with Church.wav 0.2 ms, 2.2 to 2.8 ms at the worst, its tail
+being convolved inline. None of the 43 bundled files allocates while processing. A change of setting every
+30 ms leaves 2 to 3% of the blocks dry, at most 4 in a row (85 ms); the convolver's load holds the lock
+longest (17 to 44 ms, with other work on the machine).
+
+## The hook in the simulator (`sim/main.m`)
+
+Spotify's chain rebuilt with real units (a converter fed by a render callback, a mixer, RemoteIO, wired with
+MakeConnection), with `JamesDSP.x` (logos, internal generator), its settings and libraries and the engine
+compiled into an app whose main executable is the harness, so its `AudioOutputUnitStart` goes through the
+rebound import slot as Spotify's does. A second render notify, added after the output started and so after
+JamesDSP's, measures what JamesDSP left in the buffer while a script flips settings: the switch off and a
+gain that must not apply, the switch on and -15 dB, a Liveprog script from the library swapping the
+channels, a reverb ringing out after the source stops (the silence flag cleared), a file missing from the
+library and its error, then a 16-bit interleaved client at 48 kHz.
+
+ THEOS=$HOME/theos ./build-sim.sh
+ xcrun simctl install <udid> build/sim/JamesDSPHarness.app
+ xcrun simctl launch --console-pty <udid> com.vojta.jamesdspharness
+
+Use a device of your own (`xcrun simctl create`), by UDID. The tweak's own lines are in the unified log:
+`xcrun simctl spawn <udid> log show --last 2m --predicate 'eventMessage CONTAINS "[spotifyglass]"'`.
+
+2026-09-18: every step passes. It also showed that the notify's buffers are in the RemoteIO unit's output
+format (the hardware's: 48 kHz float, a buffer per channel), not the client format Spotify sets on its input
+(44.1 kHz, or 16-bit interleaved), so the engine reads the output scope and runs at the hardware's rate.
diff --git a/harness/jamesdsp/build-sim.sh b/harness/jamesdsp/build-sim.sh
new file mode 100755
index 00000000..7da18999
--- /dev/null
+++ b/harness/jamesdsp/build-sim.sh
@@ -0,0 +1,37 @@
+#!/bin/sh
+# Builds the simulator harness (sim/main.m): JamesDSP.x generated by logos with the internal generator as
+# the tweak builds it, its settings and libraries, and SGDSPEngine.m over the simulator build of libjamesdsp
+# (vendor/libjamesdsp, made here first), in an app whose main executable is the harness, so the rebinding
+# of AudioOutputUnitStart takes as it does in Spotify.
+# THEOS=$HOME/theos ./build-sim.sh
+set -e
+cd "$(dirname "$0")"
+SRC=../../tweak/Sources
+VENDOR=../../vendor/libjamesdsp
+OUT=build/sim
+make -s -C "$VENDOR" JDSP_PLATFORM=sim -j8
+rm -rf "$OUT"
+mkdir -p "$OUT/gen" "$OUT/JamesDSPHarness.app"
+"$THEOS/bin/logos.pl" -c generator=internal "$SRC/Shared/JamesDSP/JamesDSP.x" > "$OUT/gen/JamesDSP.m"
+SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
+xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O1 -isysroot "$SDK" -Wno-deprecated-declarations \
+ -I"$SRC" -I"$SRC/Shared/JamesDSP" -isystem "$VENDOR/subtree/Main/libjamesdsp/jni/jamesdsp/jdsp" -isystem "$VENDOR" \
+ sim/main.m "$OUT/gen/JamesDSP.m" "$SRC/Shared/JamesDSP/JamesDSPSettings.m" "$SRC/Shared/JamesDSP/JamesDSPFiles.m" \
+ "$SRC/Shared/JamesDSP/SGDSPEngine.m" "$SRC/Core/SGRebind.m" "$SRC/Core/SGLog.m" "$SRC/Core/SGPrefs.m" \
+ "$VENDOR/build/sim/libjamesdsp.a" \
+ -framework UIKit -framework AudioToolbox -framework AVFoundation -framework Foundation \
+ -o "$OUT/JamesDSPHarness.app/JamesDSPHarness"
+cat > "$OUT/JamesDSPHarness.app/Info.plist" <<'PLIST'
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0"><dict>
+<key>CFBundleExecutable</key><string>JamesDSPHarness</string>
+<key>CFBundleIdentifier</key><string>com.vojta.jamesdspharness</string>
+<key>CFBundleName</key><string>JamesDSPHarness</string>
+<key>CFBundleVersion</key><string>1</string>
+<key>CFBundleShortVersionString</key><string>1.0</string>
+<key>UILaunchScreen</key><dict/>
+<key>UIApplicationSceneManifest</key><dict><key>UIApplicationSupportsMultipleScenes</key><false/></dict>
+</dict></plist>
+PLIST
+echo "built $OUT/JamesDSPHarness.app"
diff --git a/harness/jamesdsp/build.sh b/harness/jamesdsp/build.sh
new file mode 100755
index 00000000..610a205f
--- /dev/null
+++ b/harness/jamesdsp/build.sh
@@ -0,0 +1,19 @@
+#!/bin/sh
+# Builds the JamesDSP harness for the Mac: SGDSPEngine.m as the tweak compiles it, over the Mac build of
+# libjamesdsp (vendor/libjamesdsp, made here first), and main.m.
+# ./build.sh build/jamesdsp
+# ./build.sh thread build/jamesdsp-thread, the engine and the library under ThreadSanitizer
+# ./build.sh address build/jamesdsp-address, under AddressSanitizer
+set -e
+cd "$(dirname "$0")"
+VENDOR=../../vendor/libjamesdsp
+SANITIZE=$1
+make -s -C "$VENDOR" JDSP_PLATFORM=mac ${SANITIZE:+JDSP_SANITIZE=$SANITIZE} -j8
+LIB="$VENDOR/build/mac${SANITIZE:+-$SANITIZE}/libjamesdsp.a"
+OUT=build/jamesdsp${SANITIZE:+-$SANITIZE}
+mkdir -p build
+xcrun clang -fobjc-arc -O2 -g -Wall -Werror -target arm64-apple-macos13.0 ${SANITIZE:+-fsanitize=$SANITIZE -O1 -fno-omit-frame-pointer} \
+ -I ../../tweak/Sources -isystem "$VENDOR/subtree/Main/libjamesdsp/jni/jamesdsp/jdsp" -isystem "$VENDOR" \
+ main.m ../../tweak/Sources/Shared/JamesDSP/SGDSPEngine.m "$LIB" \
+ -framework Foundation -framework AudioToolbox -o "$OUT"
+echo "built $OUT"
diff --git a/harness/jamesdsp/main.m b/harness/jamesdsp/main.m
new file mode 100644
index 00000000..05f0d030
--- /dev/null
+++ b/harness/jamesdsp/main.m
@@ -0,0 +1,861 @@
+// Runs SGDSPEngine.m over the Mac build of libjamesdsp the way the tweak runs them: a song decoded with
+// ExtAudioFile goes through the engine in slices of the sizes iOS hands its output unit (1024, 4096, 470 and
+// 471 in turn, 512, and a mix), and each check prints a line.
+//
+// - bypass: every effect off, the output is the input one block later, sample for sample;
+// - the same while another thread keeps changing settings, so blocks that pass dry keep the latency;
+// - nothing allocated on the render thread, with every effect on;
+// - no NaN, infinity or level over the limiter with every effect on;
+// - bass boost lifts the lows, an equalizer preset moves each band by its gain;
+// - every bundled Liveprog script compiles and runs, every DDC preset parses, a broken script names its line;
+// - the convolver reproduces an impulse response (RootlessJamesDSP's Church.wav, 4 channels, 10 s);
+// - a sample rate change, a reset and a restart;
+// - what each effect costs per 1024-frame block.
+//
+// ./build.sh && build/jamesdsp <song> <Church.wav> <out dir>
+// ./build.sh thread && build/jamesdsp-thread <song> <Church.wav> <out dir> stress (and address)
+#import <Foundation/Foundation.h>
+#import <AudioToolbox/AudioToolbox.h>
+#import <mach/mach_time.h>
+#import <malloc/malloc.h>
+#import <pthread.h>
+#import <stdatomic.h>
+#import "Shared/JamesDSP/SGDSPEngine.h"
+#include "JdspImpResToolbox.h"
+
+static const double kRate = 48000;
+static int sg_failures;
+
+#define CHECK(ok, ...) do { bool _ok = (ok); if (!_ok) sg_failures++; printf("%s ", _ok ? " ok " : "FAILED"); printf(__VA_ARGS__); printf("\n"); } while (0)
+
+#pragma mark - allocations on the render thread
+
+// Defined in the executable, so the calls libjamesdsp and the engine make bind here rather than to libc's.
+static _Thread_local bool sg_inRender;
+static atomic_uint sg_renderAllocations;
+
+#if !__has_feature(address_sanitizer) && !__has_feature(thread_sanitizer)
+void *malloc(size_t size) {
+ if (sg_inRender) atomic_fetch_add(&sg_renderAllocations, 1);
+ return malloc_zone_malloc(malloc_default_zone(), size);
+}
+
+void *calloc(size_t count, size_t size) {
+ if (sg_inRender) atomic_fetch_add(&sg_renderAllocations, 1);
+ return malloc_zone_calloc(malloc_default_zone(), count, size);
+}
+
+void *realloc(void *pointer, size_t size) {
+ if (sg_inRender) atomic_fetch_add(&sg_renderAllocations, 1);
+ if (!pointer) return malloc_zone_malloc(malloc_default_zone(), size);
+ malloc_zone_t *zone = malloc_zone_from_ptr(pointer);
+ return malloc_zone_realloc(zone ?: malloc_default_zone(), pointer, size);
+}
+#define SG_COUNTS_ALLOCATIONS 1
+#endif
+
+#pragma mark - audio
+
+typedef struct {
+ float *left, *right;
+ size_t frames;
+} Audio;
+
+static Audio makeAudio(size_t frames) {
+ return (Audio){calloc(frames, sizeof(float)), calloc(frames, sizeof(float)), frames};
+}
+
+static Audio copyAudio(Audio audio) {
+ Audio copy = makeAudio(audio.frames);
+ memcpy(copy.left, audio.left, audio.frames * sizeof(float));
+ memcpy(copy.right, audio.right, audio.frames * sizeof(float));
+ return copy;
+}
+
+static void freeAudio(Audio audio) {
+ free(audio.left);
+ free(audio.right);
+}
+
+static void scaleAudio(Audio audio, float gain) {
+ for (size_t i = 0; i < audio.frames; i++) {
+ audio.left[i] *= gain;
+ audio.right[i] *= gain;
+ }
+}
+
+static AudioStreamBasicDescription floatFormat(double rate) {
+ return (AudioStreamBasicDescription){
+ .mSampleRate = rate, .mFormatID = kAudioFormatLinearPCM,
+ .mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved,
+ .mBytesPerPacket = 4, .mFramesPerPacket = 1, .mBytesPerFrame = 4, .mChannelsPerFrame = 2, .mBitsPerChannel = 32,
+ };
+}
+
+static Audio decode(NSString *path, double rate, double seconds) {
+ ExtAudioFileRef file;
+ if (ExtAudioFileOpenURL((__bridge CFURLRef)[NSURL fileURLWithPath:path], &file)) {
+ printf("cannot open %s\n", path.UTF8String);
+ exit(1);
+ }
+ AudioStreamBasicDescription format = floatFormat(rate);
+ ExtAudioFileSetProperty(file, kExtAudioFileProperty_ClientDataFormat, sizeof format, &format);
+ Audio audio = makeAudio((size_t)(rate * seconds));
+ size_t done = 0;
+ while (done < audio.frames) {
+ UInt32 frames = (UInt32)MIN((size_t)8192, audio.frames - done);
+ struct { AudioBufferList list; AudioBuffer second; } buffers = {{2, {{1, frames * 4, audio.left + done}}}, {1, frames * 4, audio.right + done}};
+ if (ExtAudioFileRead(file, &frames, &buffers.list) || !frames) break;
+ done += frames;
+ }
+ ExtAudioFileDispose(file);
+ audio.frames = done;
+ return audio;
+}
+
+static void writeWav(NSString *path, Audio audio, double rate) {
+ ExtAudioFileRef file;
+ AudioStreamBasicDescription wav = {
+ .mSampleRate = rate, .mFormatID = kAudioFormatLinearPCM,
+ .mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked,
+ .mBytesPerPacket = 4, .mFramesPerPacket = 1, .mBytesPerFrame = 4, .mChannelsPerFrame = 2, .mBitsPerChannel = 16,
+ };
+ if (ExtAudioFileCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path], kAudioFileWAVEType, &wav, NULL, kAudioFileFlags_EraseFile, &file)) {
+ printf("cannot write %s\n", path.UTF8String);
+ return;
+ }
+ AudioStreamBasicDescription format = floatFormat(rate);
+ ExtAudioFileSetProperty(file, kExtAudioFileProperty_ClientDataFormat, sizeof format, &format);
+ for (size_t done = 0; done < audio.frames;) {
+ UInt32 frames = (UInt32)MIN((size_t)8192, audio.frames - done);
+ struct { AudioBufferList list; AudioBuffer second; } buffers = {{2, {{1, frames * 4, audio.left + done}}}, {1, frames * 4, audio.right + done}};
+ ExtAudioFileWrite(file, frames, &buffers.list);
+ done += frames;
+ }
+ ExtAudioFileDispose(file);
+}
+
+#pragma mark - running the engine
+
+enum { kPattern1024, kPattern4096, kPatternOdd, kPattern512, kPatternMixed, kPatternCount };
+static const char *kPatternNames[] = {"1024", "4096", "470/471", "512", "mixed"};
+
+static uint32_t sliceAt(int pattern, size_t index) {
+ static const uint32_t mixed[] = {1024, 4096, 470, 471, 512, 941, 1, 2048, 1023, 1025};
+ switch (pattern) {
+ case kPattern1024: return 1024;
+ case kPattern4096: return 4096;
+ case kPatternOdd: return index % 2 ? 471 : 470;
+ case kPattern512: return 512;
+ default: return mixed[index % 10];
+ }
+}
+
+typedef struct {
+ double meanMS, peakMS;
+ uint64_t calls;
+} Timing;
+
+static double ticksToMS(uint64_t ticks) {
+ static mach_timebase_info_data_t timebase;
+ if (!timebase.denom) mach_timebase_info(&timebase);
+ return ticks * (double)timebase.numer / timebase.denom / 1e6;
+}
+
+// The audio processed in place through the engine, a slice at a time, as the notify does.
+static Timing run(SGDSPEngine *engine, Audio audio, int pattern) {
+ Timing timing = {0};
+ uint64_t total = 0, peak = 0;
+ size_t index = 0;
+ for (size_t done = 0; done < audio.frames;) {
+ uint32_t frames = (uint32_t)MIN((size_t)sliceAt(pattern, index++), audio.frames - done);
+ uint64_t start = mach_absolute_time();
+ sg_inRender = true;
+ SGDSPEngineProcess(engine, audio.left + done, audio.right + done, frames);
+ sg_inRender = false;
+ uint64_t ticks = mach_absolute_time() - start;
+ total += ticks;
+ if (ticks > peak) peak = ticks;
+ done += frames;
+ timing.calls++;
+ }
+ timing.meanMS = ticksToMS(total) / timing.calls;
+ timing.peakMS = ticksToMS(peak);
+ return timing;
+}
+
+// How far the output is from the input one block earlier: samples that differ, and the largest difference.
+static size_t delayedDifferences(Audio input, Audio output, float *largest) {
+ size_t differ = 0;
+ *largest = 0;
+ for (size_t i = 0; i < output.frames; i++) {
+ float wantLeft = i < kSGDSPEngineBlock ? 0 : input.left[i - kSGDSPEngineBlock];
+ float wantRight = i < kSGDSPEngineBlock ? 0 : input.right[i - kSGDSPEngineBlock];
+ float d = fmaxf(fabsf(output.left[i] - wantLeft), fabsf(output.right[i] - wantRight));
+ if (output.left[i] != wantLeft || output.right[i] != wantRight) differ++;
+ if (d > *largest) *largest = d;
+ }
+ return differ;
+}
+
+static bool finiteAndBounded(Audio audio, float bound, float *peak) {
+ *peak = 0;
+ for (size_t i = 0; i < audio.frames; i++) {
+ if (!isfinite(audio.left[i]) || !isfinite(audio.right[i])) return false;
+ *peak = fmaxf(*peak, fmaxf(fabsf(audio.left[i]), fabsf(audio.right[i])));
+ }
+ return *peak <= bound;
+}
+
+static void discardLine(const char *text, void *context) {
+}
+
+static void drainLog(void) {
+ SGDSPEngineReadLog(discardLine, NULL, 1000);
+}
+
+static void printLine(const char *text, void *context) {
+ int *count = context;
+ if ((*count)++ < 12) printf(" jamesdsp: %s%s", text, text[strlen(text) - 1] == '\n' ? "" : "\n");
+}
+
+#pragma mark - settings
+
+static const double kEqFrequencies[15] = {25, 40, 63, 100, 160, 250, 400, 630, 1000, 1600, 2500, 4000, 6300, 10000, 16000};
+static const double kCompanderFrequencies[7] = {95, 200, 400, 800, 1600, 3400, 7500};
+// JamesDSP's Bass and Vocal Booster presets (SGDSPEqualizerPreset).
+static const double kPresetBass[15] = {10.00, 8.80, 8.50, 6.50, 2.50, 1.50, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+static const double kPresetVocal[15] = {-1.5, -2.0, -3.0, -3.0, -0.5, 1.5, 3.5, 3.5, 3.5, 3.0, 2.0, 1.5, 0.0, 0.0, -1.5};
+
+static const void *bundled(const char *wantKind, const char *wantName) {
+ const char *kind, *name;
+ const void *data;
+ for (unsigned i = 0; SGDSPEngineBundledFile(i, &kind, &name, &data, NULL); i++) {
+ if (!strcmp(kind, wantKind) && !strcmp(name, wantName)) return data;
+ }
+ return NULL;
+}
+
+static void allOff(SGDSPEngine *engine) {
+ char error[300];
+ double zeros[15] = {0};
+ SGDSPEngineSetOutput(engine, 0, -0.1, 60);
+ SGDSPEngineSetCompander(engine, false, 0.22, 2, 0, kCompanderFrequencies, zeros);
+ SGDSPEngineSetBassBoost(engine, false, 5);
+ SGDSPEngineSetEqualizer(engine, false, 0, 0, kEqFrequencies, zeros);
+ SGDSPEngineSetGraphicEq(engine, false, "GraphicEQ: 0.0 0.0;", error, sizeof error);
+ SGDSPEngineSetConvolver(engine, false, NULL, 0, NULL, error, sizeof error);
+ SGDSPEngineSetDDC(engine, false, NULL, error, sizeof error);
+ SGDSPEngineSetLiveprog(engine, false, NULL, error, sizeof error);
+ SGDSPEngineSetReverb(engine, false, 15);
+ SGDSPEngineSetStereoWide(engine, false, 60);
+ SGDSPEngineSetCrossfeed(engine, false, 5);
+ SGDSPEngineSetTube(engine, false, 2);
+}
+
+typedef enum {
+ kCompander, kBass, kEqFIR, kEqIIR, kGraphicEq, kConvolver, kDDC, kLiveprog, kLiveprogHeavy, kReverb, kWide,
+ kCrossfeedBS2B, kCrossfeedSurround, kTube, kEffectCount
+} Effect;
+
+static const char *kEffectNames[] = {
+ "compander (STFT)", "bass boost 5 dB", "equalizer FIR", "equalizer IIR 8th", "graphic EQ", "convolver Church.wav",
+ "DDC Butterworth", "Liveprog stereowide", "Liveprog DRX10K compander", "reverb plate high", "stereo wide 60%",
+ "crossfeed BS2B weak", "crossfeed realistic surround", "tube 2 dB",
+};
+
+static NSString *sg_church;
+
+static bool setEffect(SGDSPEngine *engine, Effect effect, bool on) {
+ char error[300] = "";
+ static const double companderGains[7] = {0.3, 0.2, 0, -0.1, 0.1, 0.3, 0.4};
+ bool ok = true;
+ switch (effect) {
+ case kCompander: SGDSPEngineSetCompander(engine, on, 0.22, 2, 0, kCompanderFrequencies, companderGains); break;
+ case kBass: SGDSPEngineSetBassBoost(engine, on, 5); break;
+ case kEqFIR: SGDSPEngineSetEqualizer(engine, on, 0, 0, kEqFrequencies, kPresetVocal); break;
+ case kEqIIR: SGDSPEngineSetEqualizer(engine, on, 3, 0, kEqFrequencies, kPresetVocal); break;
+ case kGraphicEq:
+ ok = SGDSPEngineSetGraphicEq(engine, on, "GraphicEQ: 20 4; 60 3; 200 0; 1000 -1; 3000 2; 8000 1; 16000 -3; 20000 -6", error, sizeof error);
+ break;
+ case kConvolver: ok = SGDSPEngineSetConvolver(engine, on, sg_church.UTF8String, 0, "-80;-100;0;0;0;0", error, sizeof error); break;
+ case kDDC: ok = SGDSPEngineSetDDC(engine, on, bundled("DDC", "Butterworth.vdc"), error, sizeof error); break;
+ case kLiveprog: ok = SGDSPEngineSetLiveprog(engine, on, bundled("Liveprog", "stereowide.eel"), error, sizeof error); break;
+ case kLiveprogHeavy:
+ ok = SGDSPEngineSetLiveprog(engine, on, bundled("Liveprog", "Joe0Bloggs DRX10K compander-HR.eel"), error, sizeof error);
+ break;
+ case kReverb: SGDSPEngineSetReverb(engine, on, 15); break;
+ case kWide: SGDSPEngineSetStereoWide(engine, on, 60); break;
+ case kCrossfeedBS2B: SGDSPEngineSetCrossfeed(engine, on, 0); break;
+ case kCrossfeedSurround: SGDSPEngineSetCrossfeed(engine, on, 5); break;
+ case kTube: SGDSPEngineSetTube(engine, on, 2); break;
+ default: break;
+ }
+ if (!ok) printf(" %s: %s\n", kEffectNames[effect], error);
+ return ok;
+}
+
+static void allOn(SGDSPEngine *engine) {
+ for (Effect e = 0; e < kEffectCount; e++) {
+ if (e == kEqFIR || e == kLiveprogHeavy || e == kCrossfeedBS2B) continue; // one of each
+ setEffect(engine, e, true);
+ }
+}
+
+#pragma mark - measuring
+
+// A band's level: two cascaded RBJ biquads (low pass, high pass or band), then RMS, in dB.
+typedef struct { double b0, b1, b2, a1, a2, x1, x2, y1, y2; } Biquad;
+
+static Biquad biquad(int kind, double frequency, double rate) {
+ double w = 2 * M_PI * frequency / rate, cw = cos(w), alpha = sin(w) / (2 * M_SQRT1_2);
+ double b0, b1, b2, a0 = 1 + alpha, a1 = -2 * cw, a2 = 1 - alpha;
+ if (kind == 0) { b0 = (1 - cw) / 2; b1 = 1 - cw; b2 = (1 - cw) / 2; }
+ else { b0 = (1 + cw) / 2; b1 = -(1 + cw); b2 = (1 + cw) / 2; }
+ return (Biquad){b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0};
+}
+
+static double bandLevel(Audio audio, size_t from, int kind, double frequency) {
+ Biquad filters[2] = {biquad(kind, frequency, kRate), biquad(kind, frequency, kRate)};
+ double sum = 0;
+ for (size_t i = 0; i < audio.frames; i++) {
+ double x = 0.5 * (audio.left[i] + audio.right[i]);
+ for (int f = 0; f < 2; f++) {
+ Biquad *q = &filters[f];
+ double y = q->b0 * x + q->b1 * q->x1 + q->b2 * q->x2 - q->a1 * q->y1 - q->a2 * q->y2;
+ q->x2 = q->x1; q->x1 = x; q->y2 = q->y1; q->y1 = y;
+ x = y;
+ }
+ if (i >= from) sum += x * x;
+ }
+ return 10 * log10(sum / (audio.frames - from) + 1e-30);
+}
+
+// A tone's amplitude by a Hann-windowed DFT at its frequency.
+static double toneLevel(const float *samples, size_t count, double frequency) {
+ double re = 0, im = 0, window = 0;
+ for (size_t i = 0; i < count; i++) {
+ double w = 0.5 - 0.5 * cos(2 * M_PI * i / (count - 1));
+ double phase = 2 * M_PI * frequency * i / kRate;
+ re += samples[i] * w * cos(phase);
+ im += samples[i] * w * sin(phase);
+ window += w;
+ }
+ return 20 * log10(2 * hypot(re, im) / window);
+}
+
+#pragma mark - the checks
+
+static void checkBypass(Audio song) {
+ printf("\nbypass: every effect off, the output is the input one block later\n");
+ for (int pattern = 0; pattern < kPatternCount; pattern++) {
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ Audio quiet = copyAudio(song);
+ scaleAudio(quiet, 0.5f); // under the limiter's -0.1 dB
+ Audio output = copyAudio(quiet);
+ run(engine, output, pattern);
+ float largest;
+ size_t differ = delayedDifferences(quiet, output, &largest);
+ CHECK(differ == 0, "slices of %-8s at -6 dB: %zu of %zu samples differ from the input 1024 frames earlier", kPatternNames[pattern], differ, output.frames * 2);
+ freeAudio(output);
+ freeAudio(quiet);
+
+ // At full level the limiter at -0.1 dB takes the song's peaks, and only those.
+ SGDSPEngineRestart(engine);
+ output = copyAudio(song);
+ run(engine, output, pattern);
+ differ = delayedDifferences(song, output, &largest);
+ size_t over = 0;
+ for (size_t i = 0; i < song.frames; i++) over += fabsf(song.left[i]) > 0.98855f || fabsf(song.right[i]) > 0.98855f;
+ if (pattern == kPattern1024) {
+ printf(" at full level: %zu samples (%.3f%%) differ, the largest by %.4f, where the song has %zu samples over the limiter's %.4f\n",
+ differ, 100.0 * differ / (output.frames * 2), largest, over, 0.98855);
+ }
+ freeAudio(output);
+ SGDSPEngineFree(engine);
+ }
+}
+
+static void checkRestart(Audio song) {
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ Audio quiet = copyAudio(song);
+ quiet.frames = (size_t)kRate * 4;
+ scaleAudio(quiet, 0.5f);
+ Audio first = copyAudio(quiet);
+ run(engine, first, kPatternOdd);
+ SGDSPEngineRestart(engine);
+ Audio second = copyAudio(quiet);
+ run(engine, second, kPatternOdd);
+ float largest;
+ size_t differ = delayedDifferences(quiet, second, &largest);
+ CHECK(differ == 0, "after a restart the stream starts over one block late (%zu samples differ)", differ);
+ freeAudio(first);
+ freeAudio(second);
+ freeAudio(quiet);
+ SGDSPEngineFree(engine);
+}
+
+static void checkAllOn(Audio song, NSString *outDir) {
+ printf("\nevery effect on\n");
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ allOn(engine);
+ drainLog();
+ Audio output = copyAudio(song);
+ atomic_store(&sg_renderAllocations, 0);
+ Timing timing = run(engine, output, kPatternMixed);
+ float peak = 0;
+ bool fine = finiteAndBounded(output, 0.98856f, &peak);
+ CHECK(fine, "no NaN or infinity and nothing over the limiter's threshold: peak %.4f (%.2f dBFS)", peak, 20 * log10(peak));
+ SGDSPEngineStats stats = SGDSPEngineReadStats(engine, true);
+ CHECK(stats.faults == 0, "no block silenced as not finite (%llu of %llu)", stats.faults, stats.blocks);
+#if SG_COUNTS_ALLOCATIONS
+ unsigned allocations = atomic_load(&sg_renderAllocations);
+ CHECK(allocations == 0, "no allocation on the render thread over %llu calls in mixed slices (%u)", timing.calls, allocations);
+#endif
+ writeWav([outDir stringByAppendingPathComponent:@"all-on.wav"], output, kRate);
+ freeAudio(output);
+ SGDSPEngineFree(engine);
+ (void)timing;
+}
+
+static void checkBass(Audio song, NSString *outDir) {
+ printf("\nbass boost and the equalizer\n");
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ SGDSPEngineSetOutput(engine, -6, -0.1, 60); // headroom, so the limiter does not take the boost back
+ Audio reference = copyAudio(song);
+ run(engine, reference, kPattern1024);
+ SGDSPEngineSetBassBoost(engine, true, 5);
+ SGDSPEngineRestart(engine);
+ Audio boosted = copyAudio(song);
+ run(engine, boosted, kPattern1024);
+ size_t skip = (size_t)kRate;
+ double lowBefore = bandLevel(reference, skip, 0, 100), lowAfter = bandLevel(boosted, skip, 0, 100);
+ double highBefore = bandLevel(reference, skip, 1, 2000), highAfter = bandLevel(boosted, skip, 1, 2000);
+ CHECK(lowAfter - lowBefore > 2, "bass boost 5 dB: under 100 Hz %+.1f dB, over 2 kHz %+.1f dB", lowAfter - lowBefore, highAfter - highBefore);
+ writeWav([outDir stringByAppendingPathComponent:@"bass-5dB.wav"], boosted, kRate);
+ freeAudio(boosted);
+ SGDSPEngineSetBassBoost(engine, false, 5);
+
+ // The Bass preset on the song: lows up, the rest as it was.
+ SGDSPEngineSetEqualizer(engine, true, 0, 0, kEqFrequencies, kPresetBass);
+ SGDSPEngineRestart(engine);
+ Audio bass = copyAudio(song);
+ run(engine, bass, kPattern1024);
+ lowAfter = bandLevel(bass, skip, 0, 60);
+ lowBefore = bandLevel(reference, skip, 0, 60);
+ highAfter = bandLevel(bass, skip, 1, 2000);
+ highBefore = bandLevel(reference, skip, 1, 2000);
+ CHECK(lowAfter - lowBefore > 5 && fabs(highAfter - highBefore) < 1, "EQ preset Bass on the song: under 60 Hz %+.1f dB, over 2 kHz %+.1f dB",
+ lowAfter - lowBefore, highAfter - highBefore);
+ writeWav([outDir stringByAppendingPathComponent:@"eq-bass-preset.wav"], bass, kRate);
+ freeAudio(bass);
+ freeAudio(reference);
+
+ // Tones at the fifteen bands, each moved by its gain: Vocal Booster, FIR and IIR.
+ size_t frames = (size_t)kRate * 6;
+ Audio tones = makeAudio(frames);
+ for (size_t i = 0; i < frames; i++) {
+ double sum = 0;
+ for (int b = 0; b < 15; b++) sum += 0.02 * sin(2 * M_PI * kEqFrequencies[b] * i / kRate + b);
+ tones.left[i] = tones.right[i] = (float)sum;
+ }
+ SGDSPEngineSetOutput(engine, 0, -0.1, 60);
+ for (int filter = 0; filter <= 3; filter += 3) {
+ SGDSPEngineSetEqualizer(engine, true, filter, 0, kEqFrequencies, kPresetVocal);
+ SGDSPEngineRestart(engine);
+ Audio out = copyAudio(tones);
+ run(engine, out, kPatternOdd);
+ double worst = 0;
+ char line[512] = "";
+ size_t from = (size_t)kRate * 2 + kSGDSPEngineBlock, count = (size_t)kRate * 3;
+ for (int b = 0; b < 15; b++) {
+ double gain = toneLevel(out.left + from, count, kEqFrequencies[b]) - toneLevel(tones.left + from - kSGDSPEngineBlock, count, kEqFrequencies[b]);
+ worst = fmax(worst, fabs(gain - kPresetVocal[b]));
+ snprintf(line + strlen(line), sizeof line - strlen(line), " %+.1f", gain);
+ }
+ CHECK(worst < 1.5, "Vocal Booster, %s: each band's tone off its gain by %.2f dB at most; measured%s", filter ? "IIR 8th order" : "FIR", worst, line);
+ freeAudio(out);
+ }
+ freeAudio(tones);
+ SGDSPEngineFree(engine);
+}
+
+static void checkLiveprogAndDDC(Audio song) {
+ printf("\nbundled files\n");
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ Audio clip = copyAudio(song);
+ clip.frames = (size_t)kRate;
+ const char *kind, *name;
+ const void *data;
+ size_t length;
+ unsigned scripts = 0, compiled = 0, presets = 0, parsed = 0, scriptsAllocating = 0;
+ char error[300];
+ for (unsigned i = 0; SGDSPEngineBundledFile(i, &kind, &name, &data, &length); i++) {
+ bool isScript = !strcmp(kind, "Liveprog");
+ uint64_t start = mach_absolute_time();
+ bool ok = isScript ? SGDSPEngineSetLiveprog(engine, true, data, error, sizeof error) : SGDSPEngineSetDDC(engine, true, data, error, sizeof error);
+ double ms = ticksToMS(mach_absolute_time() - start);
+ Audio out = copyAudio(clip);
+ unsigned allocationsBefore = atomic_load(&sg_renderAllocations);
+ Timing timing = run(engine, out, kPattern1024);
+ unsigned allocations = atomic_load(&sg_renderAllocations) - allocationsBefore;
+ scriptsAllocating += allocations > 0;
+ float peak = 0;
+ bool fine = finiteAndBounded(out, 0.98856f, &peak);
+ if (isScript) scripts++, compiled += ok && fine;
+ else presets++, parsed += ok && fine;
+ if (!ok || !fine) printf("FAILED %s %s: %s%s\n", kind, name, ok ? "" : error, fine ? "" : " (output not finite)");
+ else printf(" %-8s %-40s %6zu bytes, set in %7.1f ms, %.3f ms a block%s\n", kind, name, length, ms, timing.meanMS,
+ allocations ? [NSString stringWithFormat:@", %u allocations while processing", allocations].UTF8String : "");
+ freeAudio(out);
+ if (isScript) SGDSPEngineSetLiveprog(engine, false, NULL, error, sizeof error);
+ else SGDSPEngineSetDDC(engine, false, NULL, error, sizeof error);
+ }
+ CHECK(compiled == scripts && scripts == 40, "%u of %u bundled Liveprog scripts compile and run finite", compiled, scripts);
+ CHECK(parsed == presets && presets == 3, "%u of %u bundled DDC presets parse and run finite", parsed, presets);
+#if SG_COUNTS_ALLOCATIONS
+ printf(" %u of them allocate while processing (EEL gives a script memory the first time it touches it)\n", scriptsAllocating);
+#endif
+
+ // A broken script names the line of the file, in either section.
+ const char *brokenInit = "desc: broken\n// a comment\n@init\nx = 1;\ny = (2 + ;\n@sample\nspl0 = spl0;\n";
+ bool ok = SGDSPEngineSetLiveprog(engine, true, brokenInit, error, sizeof error);
+ CHECK(!ok && !strncmp(error, "Line 5:", 7), "a script broken in @init at line 5: \"%s\"", error);
+ const char *brokenSample = "desc: broken\n@init\nx = 1;\n@sample\nspl0 = spl0;\nspl1 = spl1 * ;\n";
+ ok = SGDSPEngineSetLiveprog(engine, true, brokenSample, error, sizeof error);
+ CHECK(!ok && !strncmp(error, "Line 6:", 7), "a script broken in @sample at line 6: \"%s\"", error);
+ ok = SGDSPEngineSetLiveprog(engine, true, "desc: none\nspl0 = 0;\n", error, sizeof error);
+ CHECK(!ok, "a script without sections: \"%s\"", error);
+ ok = SGDSPEngineSetDDC(engine, true, "SR_44100:1,2,3\nSR_48000:1,2,3,", error, sizeof error);
+ CHECK(!ok, "a malformed DDC file is refused before libjamesdsp's parser: \"%s\"", error);
+ ok = SGDSPEngineSetGraphicEq(engine, true, "GraphicEQ: 20 -1; 30", error, sizeof error);
+ CHECK(ok, "a GraphicEQ with an odd count of numbers loads its whole pairs");
+ ok = SGDSPEngineSetGraphicEq(engine, true, "20 -1; 30 2", error, sizeof error);
+ CHECK(!ok, "text without \"GraphicEQ:\" is refused: \"%s\"", error);
+
+ // Liveprog's printf comes out through the log.
+ int lines = 0;
+ SGDSPEngineReadLog(printLine, &lines, 1000);
+ lines = 0;
+ SGDSPEngineSetLiveprog(engine, true, "desc: talk\n@init\nprintf(\"hello from @init %d\", 42);\n@sample\nspl0 = spl0;\n", error, sizeof error);
+ SGDSPEngineReadLog(printLine, &lines, 1000);
+ CHECK(lines > 0, "Liveprog's printf reaches the engine's log (%d line)", lines);
+ freeAudio(clip);
+ SGDSPEngineFree(engine);
+}
+
+static void writeMonoWav(NSString *from, NSString *to) {
+ ExtAudioFileRef in, out;
+ ExtAudioFileOpenURL((__bridge CFURLRef)[NSURL fileURLWithPath:from], &in);
+ AudioStreamBasicDescription mono = {48000, kAudioFormatLinearPCM, kAudioFormatFlagsNativeFloatPacked, 4, 1, 4, 1, 32, 0};
+ AudioStreamBasicDescription four = {48000, kAudioFormatLinearPCM, kAudioFormatFlagsNativeFloatPacked, 16, 1, 16, 4, 32, 0};
+ ExtAudioFileSetProperty(in, kExtAudioFileProperty_ClientDataFormat, sizeof four, &four);
+ ExtAudioFileCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:to], kAudioFileWAVEType, &mono, NULL, kAudioFileFlags_EraseFile, &out);
+ float frame[4 * 4096], left[4096];
+ for (;;) {
+ UInt32 frames = 4096;
+ AudioBufferList list = {1, {{4, sizeof frame, frame}}};
+ if (ExtAudioFileRead(in, &frames, &list) || !frames) break;
+ for (UInt32 i = 0; i < frames; i++) left[i] = frame[i * 4];
+ AudioBufferList outList = {1, {{1, frames * 4, left}}};
+ ExtAudioFileWrite(out, frames, &outList);
+ }
+ ExtAudioFileDispose(in);
+ ExtAudioFileDispose(out);
+}
+
+static void checkConvolver(Audio song, NSString *outDir) {
+ printf("\nconvolver\n");
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ char error[300];
+ uint64_t start = mach_absolute_time();
+ bool ok = SGDSPEngineSetConvolver(engine, true, sg_church.UTF8String, 0, "-80;-100;0;0;0;0", error, sizeof error);
+ CHECK(ok, "Church.wav loads (%.0f ms)%s%s", ticksToMS(mach_absolute_time() - start), ok ? "" : ": ", ok ? "" : error);
+
+ // An impulse in the left channel comes out as the response's LL and LR channels, one block later.
+ int info[2], wave[6] = {-80, -100, 0, 0, 0, 0};
+ float *ir = ReadImpulseResponseToFloat(sg_church.UTF8String, 48000, info, 0, wave);
+ size_t frames = (size_t)info[1] + 8192;
+ Audio impulse = makeAudio(frames);
+ impulse.left[100] = 0.5f;
+ Audio out = copyAudio(impulse);
+ SGDSPEngineSetOutput(engine, 0, 0, 60);
+ run(engine, out, kPatternMixed);
+ double error2 = 0, energy = 0;
+ for (int i = 0; i < info[1] && 100 + kSGDSPEngineBlock + (size_t)i < frames; i++) {
+ size_t at = 100 + kSGDSPEngineBlock + i;
+ float wantLeft = 0.5f * ir[i * info[0] + 0], wantRight = 0.5f * ir[i * info[0] + 1];
+ error2 += (out.left[at] - wantLeft) * (out.left[at] - wantLeft) + (out.right[at] - wantRight) * (out.right[at] - wantRight);
+ energy += wantLeft * wantLeft + wantRight * wantRight;
+ }
+ CHECK(10 * log10(error2 / energy) < -60, "an impulse comes out as the response (%d channels, %d frames): error %.0f dB under it", info[0], info[1], 10 * log10(error2 / energy));
+ free(ir);
+ freeAudio(out);
+ freeAudio(impulse);
+
+ // On the song, and its cost.
+ SGDSPEngineSetOutput(engine, -6, -0.1, 60);
+ Audio wet = copyAudio(song);
+ wet.frames = MIN(wet.frames, (size_t)kRate * 30);
+ SGDSPEngineRestart(engine);
+ Timing timing = run(engine, wet, kPattern1024);
+ float peak = 0;
+ CHECK(finiteAndBounded(wet, 0.98856f, &peak), "Church.wav on the song: %.3f ms a block on average, %.3f ms at most", timing.meanMS, timing.peakMS);
+ writeWav([outDir stringByAppendingPathComponent:@"convolver-church.wav"], wet, kRate);
+ freeAudio(wet);
+
+ // Shrink, and minimum phase on a mono response (the case the reader wrote out of bounds in).
+ ok = SGDSPEngineSetConvolver(engine, true, sg_church.UTF8String, 1, "-80;-100;0;0;0;0", error, sizeof error);
+ CHECK(ok, "shrink mode loads");
+ NSString *mono = [outDir stringByAppendingPathComponent:@"church-mono.wav"];
+ writeMonoWav(sg_church, mono);
+ ok = SGDSPEngineSetConvolver(engine, true, mono.UTF8String, 2, "-80;-100;0;0;0;0", error, sizeof error);
+ CHECK(ok, "minimum phase and shrink loads a mono response");
+ ok = SGDSPEngineSetConvolver(engine, true, mono.UTF8String, 0, "-80;-100;999999999;0;0;0", error, sizeof error);
+ CHECK(ok, "a waveform shift past the response falls back to the defaults");
+ ok = SGDSPEngineSetConvolver(engine, true, "/nonexistent.wav", 0, NULL, error, sizeof error);
+ CHECK(!ok, "a missing file: \"%s\"", error);
+ ok = SGDSPEngineSetConvolver(engine, true, [outDir stringByAppendingPathComponent:@"all-on.wav"].UTF8String, 0, NULL, error, sizeof error);
+ CHECK(ok, "a 16-bit stereo WAV reads as a response too");
+ SGDSPEngineFree(engine);
+}
+
+static void checkRateAndReset(Audio song) {
+ printf("\nsample rate change and reset\n");
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ allOn(engine);
+ Audio a = copyAudio(song);
+ a.frames = (size_t)kRate * 3;
+ run(engine, a, kPattern1024);
+ SGDSPEngineSetSampleRate(engine, 44100);
+ allOn(engine);
+ Audio b = copyAudio(song);
+ b.frames = 44100 * 3;
+ run(engine, b, kPattern4096);
+ float peak = 0;
+ CHECK(SGDSPEngineSampleRate(engine) == 44100 && finiteAndBounded(b, 0.98856f, &peak), "48 -> 44.1 kHz with every effect on: runs finite, peak %.3f", peak);
+ SGDSPEngineSetSampleRate(engine, 96000);
+ allOn(engine);
+ Audio c = copyAudio(song);
+ c.frames = 96000 * 2;
+ run(engine, c, kPatternOdd);
+ CHECK(finiteAndBounded(c, 0.98856f, &peak), "-> 96 kHz (libjamesdsp resamples to 48 inside): runs finite, peak %.3f", peak);
+ SGDSPEngineSetSampleRate(engine, kRate);
+ SGDSPEngineReset(engine);
+ allOff(engine);
+ SGDSPEngineRestart(engine);
+ Audio quiet = copyAudio(song);
+ quiet.frames = (size_t)kRate * 3;
+ scaleAudio(quiet, 0.5f);
+ Audio out = copyAudio(quiet);
+ run(engine, out, kPatternMixed);
+ float largest;
+ size_t differ = delayedDifferences(quiet, out, &largest);
+ CHECK(differ == 0, "after a reset every effect is off and the output is the input one block later (%zu differ)", differ);
+ freeAudio(a);
+ freeAudio(b);
+ freeAudio(c);
+ freeAudio(quiet);
+ freeAudio(out);
+ SGDSPEngineFree(engine);
+}
+
+static void checkCost(Audio song) {
+ printf("\ncost per 1024-frame block at 48 kHz (21.33 ms of sound), 20 s of the song\n");
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ Audio clip = copyAudio(song);
+ clip.frames = MIN(clip.frames, (size_t)kRate * 20);
+ double blockMS = kSGDSPEngineBlock / kRate * 1000;
+ for (int e = -1; e <= kEffectCount; e++) {
+ const char *name = e < 0 ? "every effect off" : e == kEffectCount ? "every effect on" : kEffectNames[e];
+ if (e == kEffectCount) allOn(engine);
+ else if (e >= 0) setEffect(engine, (Effect)e, true);
+ Audio out = copyAudio(clip);
+ Timing timing = run(engine, out, kPattern1024);
+ printf(" %-30s %7.3f ms (%5.2f%% of real time), peak %7.3f ms\n", name, timing.meanMS, timing.meanMS / blockMS * 100, timing.peakMS);
+ freeAudio(out);
+ if (e >= 0 && e < kEffectCount) setEffect(engine, (Effect)e, false);
+ }
+ freeAudio(clip);
+ SGDSPEngineFree(engine);
+}
+
+#pragma mark - stress
+
+typedef struct {
+ SGDSPEngine *engine;
+ atomic_bool stop;
+ unsigned changes;
+ bool effectsOn;
+ useconds_t pause; // between changes; the apply queue waits 30 ms for a burst to end
+ double longestMS[kEffectCount + 1]; // the longest a setter took, per effect and the output's
+} Hammer;
+
+static void *hammer(void *context) {
+ Hammer *h = context;
+ char error[300];
+ double zeros[15] = {0};
+ unsigned i = 0;
+ while (!atomic_load(&h->stop)) {
+ if (!h->effectsOn) {
+ // Setters that leave the sound as it is, so every block, processed or passed dry, must be exact.
+ switch (i % 6) {
+ case 0: SGDSPEngineSetOutput(h->engine, 0, -0.1, 60); break;
+ case 1: SGDSPEngineSetReverb(h->engine, false, 15); break;
+ case 2: SGDSPEngineSetEqualizer(h->engine, false, 0, 0, kEqFrequencies, zeros); break;
+ case 3: SGDSPEngineSetCrossfeed(h->engine, false, 5); break;
+ case 4: SGDSPEngineSetLiveprog(h->engine, false, NULL, error, sizeof error); break;
+ case 5: SGDSPEngineSetDDC(h->engine, false, NULL, error, sizeof error); break;
+ }
+ } else {
+ // Every effect in turn, on and off, the output now and then; as fast as the setters go.
+ Effect e = (Effect)(i % kEffectCount);
+ uint64_t start = mach_absolute_time();
+ setEffect(h->engine, e, (i / kEffectCount) % 2 == 0);
+ h->longestMS[e] = fmax(h->longestMS[e], ticksToMS(mach_absolute_time() - start));
+ if (i % 7 == 0) {
+ start = mach_absolute_time();
+ SGDSPEngineSetOutput(h->engine, (i % 7) - 3.0, -0.1 - (i % 5), 30 + i % 100);
+ h->longestMS[kEffectCount] = fmax(h->longestMS[kEffectCount], ticksToMS(mach_absolute_time() - start));
+ }
+ }
+ i++;
+ h->changes++;
+ drainLog();
+ if (h->pause) usleep(h->pause);
+ }
+ return NULL;
+}
+
+// The song through the engine in mixed slices, at `speed` times real time, while a hammer runs; the longest
+// stretch of blocks passed dry.
+static unsigned runPaced(Hammer *h, Audio out, double speed) {
+ pthread_t thread;
+ pthread_create(&thread, NULL, hammer, h);
+ uint64_t began = mach_absolute_time(), lastDry = 0, lastBlocks = 0;
+ unsigned streak = 0, longest = 0;
+ size_t index = 0;
+ for (size_t done = 0; done < out.frames;) {
+ uint32_t frames = (uint32_t)MIN((size_t)sliceAt(kPatternMixed, index++), out.frames - done);
+ SGDSPEngineProcess(h->engine, out.left + done, out.right + done, frames);
+ done += frames;
+ SGDSPEngineStats now = SGDSPEngineReadStats(h->engine, false);
+ if (now.dry != lastDry && now.blocks == lastBlocks) streak += (unsigned)(now.dry - lastDry);
+ else if (now.blocks != lastBlocks) streak = now.dry != lastDry ? 1 : 0;
+ longest = MAX(longest, streak);
+ lastDry = now.dry;
+ lastBlocks = now.blocks;
+ if (speed > 0) {
+ double due = done / kRate / speed * 1000, elapsed = ticksToMS(mach_absolute_time() - began);
+ if (due > elapsed) usleep((useconds_t)((due - elapsed) * 1000));
+ }
+ }
+ atomic_store(&h->stop, true);
+ pthread_join(thread, NULL);
+ return longest;
+}
+
+static void checkStress(Audio song, bool quick) {
+ printf("\na thread changing settings while another processes\n");
+ // As fast as it goes, with settings that leave the sound alone: blocks passed dry must keep the latency.
+ Hammer h = {.engine = SGDSPEngineCreate(kRate)};
+ allOff(h.engine);
+ Audio quiet = copyAudio(song);
+ quiet.frames = MIN(quiet.frames, (size_t)kRate * (quick ? 8 : 40));
+ scaleAudio(quiet, 0.5f);
+ Audio out = copyAudio(quiet);
+ pthread_t thread;
+ pthread_create(&thread, NULL, hammer, &h);
+ run(h.engine, out, kPatternMixed);
+ atomic_store(&h.stop, true);
+ pthread_join(thread, NULL);
+ SGDSPEngineStats stats = SGDSPEngineReadStats(h.engine, true);
+ float largest = 0, peak = 0;
+ size_t differ = delayedDifferences(quiet, out, &largest);
+ CHECK(differ == 0 && stats.dry > 0, "settings that leave the sound alone, %u changes: %llu blocks processed, %llu passed dry, %zu samples off the input one block earlier",
+ h.changes, stats.blocks, stats.dry, differ);
+ freeAudio(out);
+ SGDSPEngineFree(h.engine);
+
+ // Every effect switched on and off as fast as the setters go, the song unpaced: no crash, nothing not
+ // finite.
+ Hammer e = {.engine = SGDSPEngineCreate(kRate), .effectsOn = true};
+ allOff(e.engine);
+ out = copyAudio(quiet);
+ runPaced(&e, out, 0);
+ stats = SGDSPEngineReadStats(e.engine, true);
+ CHECK(finiteAndBounded(out, 0.98856f, &peak) && stats.faults == 0, "every effect switched on and off as fast as it goes, %u changes: %llu blocks processed, %llu dry, output finite, peak %.3f",
+ e.changes, stats.blocks, stats.dry, peak);
+ freeAudio(out);
+ SGDSPEngineFree(e.engine);
+
+ // The same at the pace the apply queue can go (a change every 30 ms at most) and the song in real time:
+ // how long a change leaves the sound dry.
+ Hammer p = {.engine = SGDSPEngineCreate(kRate), .effectsOn = true, .pause = 30000};
+ allOff(p.engine);
+ out = copyAudio(quiet);
+ out.frames = MIN(out.frames, (size_t)kRate * (quick ? 4 : 10));
+ unsigned longest = runPaced(&p, out, 1);
+ stats = SGDSPEngineReadStats(p.engine, true);
+ CHECK(finiteAndBounded(out, 0.98856f, &peak) && stats.faults == 0,
+ "a change every 30 ms in real time, %u changes: %llu blocks processed, %llu dry (%.1f%%), the longest dry stretch %u blocks (%.0f ms), peak %.3f",
+ p.changes, stats.blocks, stats.dry, 100.0 * stats.dry / (stats.blocks + stats.dry), longest, longest * kSGDSPEngineBlock / kRate * 1000, peak);
+ printf(" the longest each setter held on:");
+ for (int i = 0; i <= kEffectCount; i++) printf("%s %s %.1f ms", i ? "," : "", i < kEffectCount ? kEffectNames[i] : "output", p.longestMS[i]);
+ printf("\n");
+ freeAudio(out);
+ freeAudio(quiet);
+ SGDSPEngineFree(p.engine);
+}
+
+int main(int argc, const char *argv[]) {
+ @autoreleasepool {
+ setvbuf(stdout, NULL, _IOLBF, 0);
+ if (argc < 4) {
+ printf("usage: %s <song> <Church.wav> <out dir> [stress]\n", argv[0]);
+ return 2;
+ }
+ NSString *songPath = @(argv[1]);
+ sg_church = @(argv[2]);
+ NSString *outDir = @(argv[3]);
+ bool stressOnly = argc > 4 && !strcmp(argv[4], "stress");
+ [NSFileManager.defaultManager createDirectoryAtPath:outDir withIntermediateDirectories:YES attributes:nil error:nil];
+ Audio song = decode(songPath, kRate, stressOnly ? 12 : 60);
+ printf("song: %.1f s at %.0f Hz\n", song.frames / kRate, kRate);
+ if (stressOnly) {
+ checkStress(song, true);
+ checkRateAndReset(song);
+ } else {
+ checkBypass(song);
+ checkRestart(song);
+ checkAllOn(song, outDir);
+ checkBass(song, outDir);
+ checkLiveprogAndDDC(song);
+ checkConvolver(song, outDir);
+ checkRateAndReset(song);
+ checkStress(song, false);
+ checkCost(song);
+ Audio original = copyAudio(song);
+ original.frames = MIN(original.frames, (size_t)kRate * 30);
+ writeWav([outDir stringByAppendingPathComponent:@"original.wav"], original, kRate);
+ SGDSPEngine *engine = SGDSPEngineCreate(kRate);
+ allOff(engine);
+ SGDSPEngineSetReverb(engine, true, 15);
+ SGDSPEngineSetOutput(engine, -3, -0.1, 60);
+ Audio reverb = copyAudio(original);
+ run(engine, reverb, kPattern1024);
+ writeWav([outDir stringByAppendingPathComponent:@"reverb-plate-high.wav"], reverb, kRate);
+ SGDSPEngineFree(engine);
+ }
+ printf("\n%s: %d failed\n", sg_failures ? "FAILED" : "all passed", sg_failures);
+ return sg_failures ? 1 : 0;
+ }
+}
diff --git a/harness/jamesdsp/sim/main.m b/harness/jamesdsp/sim/main.m
new file mode 100644
index 00000000..169bd7b7
--- /dev/null
+++ b/harness/jamesdsp/sim/main.m
@@ -0,0 +1,291 @@
+// Spotify's audio chain rebuilt with real Core Audio units in the simulator (AudioUnitDriver2: a converter fed
+// by a render callback, a mixer and RemoteIO, wired with MakeConnection, slices of 4096), with JamesDSP.x,
+// its settings, its libraries and SGDSPEngine over the simulator build of libjamesdsp compiled in. The
+// harness is the main executable, so its AudioOutputUnitStart goes through the rebound import slot exactly
+// as Spotify's does. A second render notify, added after the output started and so after JamesDSP's, reads
+// what JamesDSP left in the buffer, and a script of settings checks the level it measures.
+//
+// The generator plays a 440 Hz sine at -12 dBFS peak in the left channel and nothing in the right, so a
+// channel swap shows as well as a gain.
+//
+// THEOS=$HOME/theos ../build-sim.sh
+// xcrun simctl install <udid> build/JamesDSPHarness.app
+// xcrun simctl launch --console-pty <udid> com.vojta.jamesdspharness
+#import <UIKit/UIKit.h>
+#import <AudioToolbox/AudioToolbox.h>
+#import <AVFoundation/AVFoundation.h>
+#import <stdatomic.h>
+#import "Shared/JamesDSP/JamesDSP.h"
+
+static const float kAmplitude = 0.25f;
+
+static atomic_bool sg_mute;
+static atomic_uint_fast64_t sg_phase;
+static double sg_generatorRate;
+
+static OSStatus generate(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,
+ UInt32 frames, AudioBufferList *data) {
+ uint64_t start = atomic_fetch_add(&sg_phase, frames);
+ BOOL mute = atomic_load(&sg_mute);
+ float *left = data->mBuffers[0].mData, *right = data->mNumberBuffers > 1 ? data->mBuffers[1].mData : NULL;
+ for (UInt32 i = 0; i < frames; i++) {
+ left[i] = mute ? 0 : kAmplitude * sinf(2 * M_PI * 440 * (start + i) / sg_generatorRate);
+ if (right) right[i] = 0;
+ }
+ if (mute) *flags |= kAudioUnitRenderAction_OutputIsSilence;
+ return noErr;
+}
+
+#pragma mark - the probe, after JamesDSP's notify
+
+enum { kProbeCalls = 64 };
+typedef struct { float left, right; UInt32 frames; bool silent; } ProbeCall;
+static ProbeCall sg_calls[kProbeCalls];
+static atomic_uint sg_callCount;
+
+static OSStatus probe(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,
+ UInt32 frames, AudioBufferList *data) {
+ if (!(*flags & kAudioUnitRenderAction_PostRender) || bus != 0 || !frames) return noErr;
+ // The notify's buffers are in the unit's output (hardware) format, float with a buffer per channel here,
+ // whatever the client format.
+ if (data->mNumberBuffers < 2 || data->mBuffers[0].mDataByteSize != frames * sizeof(float)) return noErr;
+ const float *l = data->mBuffers[0].mData, *r = data->mBuffers[1].mData;
+ double left = 0, right = 0;
+ for (UInt32 i = 0; i < frames; i++) {
+ left += l[i] * l[i];
+ right += r[i] * r[i];
+ }
+ unsigned n = atomic_load(&sg_callCount);
+ sg_calls[n % kProbeCalls] = (ProbeCall){(float)(left / frames), (float)(right / frames), frames, (*flags & kAudioUnitRenderAction_OutputIsSilence) != 0};
+ atomic_store(&sg_callCount, n + 1);
+ return noErr;
+}
+
+// The level of the last `calls` renders, in dB RMS, per channel.
+static void level(unsigned calls, double *left, double *right, unsigned *frames, unsigned *silentCalls) {
+ unsigned n = atomic_load(&sg_callCount);
+ double l = 0, r = 0;
+ unsigned count = 0;
+ *frames = 0;
+ *silentCalls = 0;
+ for (unsigned i = 0; i < calls && i < n && i < kProbeCalls; i++) {
+ ProbeCall call = sg_calls[(n - 1 - i) % kProbeCalls];
+ l += call.left;
+ r += call.right;
+ *frames = call.frames;
+ *silentCalls += call.silent;
+ count++;
+ }
+ *left = count ? 10 * log10(l / count + 1e-20) : -200;
+ *right = count ? 10 * log10(r / count + 1e-20) : -200;
+}
+
+static int sg_failures;
+
+static void report(NSString *what, double wantLeft, double wantRight) {
+ double left, right;
+ unsigned frames, silent;
+ level(8, &left, &right, &frames, &silent);
+ BOOL ok = (isnan(wantLeft) || fabs(left - wantLeft) < 0.6) && (isnan(wantRight) || fabs(right - wantRight) < 0.6);
+ if (!ok) sg_failures++;
+ NSLog(@"[harness] %@ %-44@ left %6.1f dB, right %6.1f dB (want %@, %@), slices of %u, %u silent; status \"%@\"", ok ? @" ok " : @"FAILED",
+ what, left, right, isnan(wantLeft) ? @"any" : [NSString stringWithFormat:@"%.1f", wantLeft],
+ isnan(wantRight) ? @"any" : [NSString stringWithFormat:@"%.1f", wantRight], frames, silent, SGDSPStatus());
+}
+
+#pragma mark - the chain
+
+static AudioUnit make(OSType type, OSType subType) {
+ AudioComponentDescription description = {type, subType, kAudioUnitManufacturer_Apple, 0, 0};
+ AudioUnit unit = NULL;
+ AudioComponentInstanceNew(AudioComponentFindNext(NULL, &description), &unit);
+ return unit;
+}
+
+static void check(OSStatus status, const char *what) {
+ if (status) NSLog(@"[harness] %s failed: %d", what, (int)status);
+}
+
+@interface SGDSPHarnessDelegate : UIResponder <UIApplicationDelegate>
+@property (nonatomic, strong) UIWindow *window;
+@end
+
+@implementation SGDSPHarnessDelegate {
+ AudioUnit _converter, _mixer, _output;
+}
+
+// Spotify's way: float, one buffer per channel, converter -> mixer -> RemoteIO, slices of 4096.
+- (void)startSpotifyChainAt:(double)rate {
+ sg_generatorRate = rate;
+ _converter = make(kAudioUnitType_FormatConverter, kAudioUnitSubType_AUConverter);
+ _mixer = make(kAudioUnitType_Mixer, kAudioUnitSubType_MultiChannelMixer);
+ _output = make(kAudioUnitType_Output, kAudioUnitSubType_RemoteIO);
+ AURenderCallbackStruct callback = {generate, NULL};
+ check(AudioUnitSetProperty(_converter, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof callback), "callback");
+ AudioUnitConnection toMixer = {_converter, 0, 0}, toOutput = {_mixer, 0, 0};
+ check(AudioUnitSetProperty(_mixer, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &toMixer, sizeof toMixer), "connect mixer");
+ check(AudioUnitSetProperty(_output, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &toOutput, sizeof toOutput), "connect output");
+ AudioStreamBasicDescription format = {rate, kAudioFormatLinearPCM, kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved, 4, 1, 4, 2, 32, 0};
+ check(AudioUnitSetProperty(_converter, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof format), "converter in");
+ check(AudioUnitSetProperty(_converter, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format, sizeof format), "converter out");
+ check(AudioUnitSetProperty(_mixer, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof format), "mixer in");
+ check(AudioUnitSetProperty(_mixer, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format, sizeof format), "mixer out");
+ check(AudioUnitSetProperty(_output, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof format), "output in");
+ UInt32 slice = 4096;
+ AudioUnit units[] = {_converter, _mixer, _output};
+ for (int i = 0; i < 3; i++) check(AudioUnitSetProperty(units[i], kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &slice, sizeof slice), "slice");
+ for (int i = 0; i < 3; i++) check(AudioUnitInitialize(units[i]), "initialize");
+ check(AudioOutputUnitStart(_output), "start");
+ check(AudioUnitAddRenderNotify(_output, probe, NULL), "probe");
+ [self logScopes];
+}
+
+// What the client format is and what the notify gets: the output scope, the hardware's.
+- (void)logScopes {
+ AudioStreamBasicDescription client = {0}, hardware = {0};
+ UInt32 size = sizeof client;
+ AudioUnitGetProperty(_output, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &client, &size);
+ size = sizeof hardware;
+ AudioUnitGetProperty(_output, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &hardware, &size);
+ NSLog(@"[harness] RemoteIO's client format %.0f Hz %u-bit flags 0x%x; its output side, which the notifies get, %.0f Hz %u-bit flags 0x%x",
+ client.mSampleRate, (unsigned)client.mBitsPerChannel, (unsigned)client.mFormatFlags, hardware.mSampleRate,
+ (unsigned)hardware.mBitsPerChannel, (unsigned)hardware.mFormatFlags);
+}
+
+// Another client format: 16-bit interleaved at another rate, converter straight into RemoteIO. The notify
+// still gets the output side's float, now with the engine following the rate change.
+- (void)startInt16ChainAt:(double)rate {
+ AudioOutputUnitStop(_output);
+ AudioUnitRemoveRenderNotify(_output, probe, NULL);
+ AudioUnit old[] = {_output, _mixer, _converter};
+ for (int i = 0; i < 3; i++) {
+ if (!old[i]) continue;
+ AudioUnitUninitialize(old[i]);
+ AudioComponentInstanceDispose(old[i]);
+ }
+ sg_generatorRate = rate;
+ _converter = make(kAudioUnitType_FormatConverter, kAudioUnitSubType_AUConverter);
+ _output = make(kAudioUnitType_Output, kAudioUnitSubType_RemoteIO);
+ _mixer = NULL;
+ AURenderCallbackStruct callback = {generate, NULL};
+ check(AudioUnitSetProperty(_converter, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof callback), "callback");
+ AudioStreamBasicDescription floats = {rate, kAudioFormatLinearPCM, kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved, 4, 1, 4, 2, 32, 0};
+ AudioStreamBasicDescription shorts = {rate, kAudioFormatLinearPCM, kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked, 4, 1, 4, 2, 16, 0};
+ check(AudioUnitSetProperty(_converter, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &floats, sizeof floats), "converter in");
+ check(AudioUnitSetProperty(_converter, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &shorts, sizeof shorts), "converter out");
+ check(AudioUnitSetProperty(_output, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &shorts, sizeof shorts), "output in");
+ AudioUnitConnection toOutput = {_converter, 0, 0};
+ check(AudioUnitSetProperty(_output, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &toOutput, sizeof toOutput), "connect output");
+ check(AudioUnitInitialize(_converter), "initialize converter");
+ check(AudioUnitInitialize(_output), "initialize output");
+ check(AudioOutputUnitStart(_output), "start");
+ check(AudioUnitAddRenderNotify(_output, probe, NULL), "probe");
+ [self logScopes];
+}
+
+- (void)after:(double)seconds do:(void (^)(void))block {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
+}
+
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
+ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
+ self.window.rootViewController = [UIViewController new];
+ [self.window makeKeyAndVisible];
+ [AVAudioSession.sharedInstance setCategory:AVAudioSessionCategoryPlayback error:nil];
+ [AVAudioSession.sharedInstance setActive:YES error:nil];
+ double sine = 20 * log10(kAmplitude / M_SQRT2), nothing = -200, any = NAN;
+ NSLog(@"[harness] the sine's level is %.1f dB RMS in the left channel", sine);
+ SGDSPSetSwitch(SGKeyDSP, NO);
+ [self startSpotifyChainAt:44100];
+
+ NSArray *script = @[
+ @[@"master off", ^{}, @(sine), @(nothing)],
+ @[@"master off, post gain -15 dB (bypassed)", ^{ SGDSPSetNumber(SGKeyDSPPostGain, -15); }, @(sine), @(nothing)],
+ @[@"master on, post gain -15 dB", ^{ SGDSPSetSwitch(SGKeyDSP, YES); }, @(sine - 15), @(nothing)],
+ @[@"post gain back to 0 dB, every effect off", ^{ SGDSPSetNumber(SGKeyDSPPostGain, 0); }, @(sine), @(nothing)],
+ @[@"Liveprog swapChannels.eel from the library", ^{
+ SGDSPSetString(SGKeyDSPLiveprogFile, @"swapChannels.eel");
+ SGDSPSetSwitch(SGKeyDSPLiveprog, YES);
+ }, @(nothing), @(sine)],
+ @[@"Liveprog off, reverb on (plate high)", ^{
+ SGDSPSetSwitch(SGKeyDSPLiveprog, NO);
+ SGDSPSetSwitch(SGKeyDSPReverb, YES);
+ }, @(any), @(any)],
+ @[@"the source goes silent, the reverb rings out", ^{ atomic_store(&sg_mute, true); }, @(any), @(any)],
+ @[@"reverb off, silent: silence", ^{ SGDSPSetSwitch(SGKeyDSPReverb, NO); }, @(nothing), @(nothing)],
+ @[@"a convolver file not in the library", ^{
+ atomic_store(&sg_mute, false);
+ SGDSPSetString(SGKeyDSPConvolverFile, @"missing.wav");
+ SGDSPSetSwitch(SGKeyDSPConvolver, YES);
+ }, @(sine), @(nothing)],
+ @[@"16-bit interleaved at 48 kHz, post gain -15 dB", ^{
+ SGDSPSetSwitch(SGKeyDSPConvolver, NO);
+ SGDSPSetNumber(SGKeyDSPPostGain, -15);
+ [self startInt16ChainAt:48000];
+ }, @(sine - 15), @(nothing)],
+ @[@"16-bit, Liveprog swapChannels.eel", ^{
+ SGDSPSetNumber(SGKeyDSPPostGain, 0);
+ SGDSPSetSwitch(SGKeyDSPLiveprog, YES);
+ }, @(nothing), @(sine)],
+ @[@"master off again", ^{ SGDSPSetSwitch(SGKeyDSP, NO); }, @(sine), @(nothing)],
+ ];
+ __block NSString *label = nil;
+ __block double wantLeft = 0, wantRight = 0;
+ double step = 2.5, at = 1;
+ for (NSArray *entry in script) {
+ [self after:at do:^{
+ if (label) report(label, wantLeft, wantRight);
+ if ([label hasPrefix:@"the source goes silent"]) {
+ // The tail: the level over the renders since the source stopped, loud at first, then less.
+ double left, right;
+ unsigned frames, silent;
+ level(3, &left, &right, &frames, &silent);
+ NSLog(@"[harness] the tail's last renders: left %.1f dB, right %.1f dB, %u of them flagged silent", left, right, silent);
+ }
+ if ([label hasPrefix:@"a convolver file"]) {
+ NSString *error = SGDSPError(SGKeyDSPConvolver);
+ if (!error) sg_failures++;
+ NSLog(@"[harness] %@ its error: \"%@\"", error ? @" ok " : @"FAILED", error);
+ }
+ label = entry[0];
+ wantLeft = [entry[2] doubleValue];
+ wantRight = [entry[3] doubleValue];
+ ((void (^)(void))entry[1])();
+ }];
+ if ([entry[0] hasPrefix:@"the source goes silent"]) {
+ // Right after the source stops, the reverb's tail is still coming out.
+ [self after:at + 0.4 do:^{
+ double left, right;
+ unsigned frames, silent;
+ level(2, &left, &right, &frames, &silent);
+ BOOL ringing = left > -80 || right > -80;
+ if (!ringing) sg_failures++;
+ NSLog(@"[harness] %@ 0.4 s after the source stopped: left %.1f dB, right %.1f dB, %u of 2 renders flagged silent after JamesDSP",
+ ringing ? @" ok " : @"FAILED", left, right, silent);
+ }];
+ }
+ at += step;
+ }
+ [self after:at do:^{
+ report(label, wantLeft, wantRight);
+ NSLog(@"[harness] %@: %d failed", sg_failures ? @"FAILED" : @"all passed", sg_failures);
+ exit(sg_failures ? 1 : 0);
+ }];
+ return YES;
+}
+
+@end
+
+// Every JamesDSP key back to what it holds until set, before anything reads them.
+__attribute__((constructor(101))) static void sgr_harnessDefaults(void) {
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
+ for (NSString *key in defaults.dictionaryRepresentation.allKeys) {
+ if ([key hasPrefix:@"spotifyglass.dsp"]) [defaults removeObjectForKey:key];
+ }
+}
+
+int main(int argc, char *argv[]) {
+ @autoreleasepool {
+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(SGDSPHarnessDelegate.class));
+ }
+}
diff --git a/tweak/Sources/Shared/JamesDSP/JamesDSP.h b/tweak/Sources/Shared/JamesDSP/JamesDSP.h
new file mode 100644
index 00000000..161df9a7
--- /dev/null
+++ b/tweak/Sources/Shared/JamesDSP/JamesDSP.h
@@ -0,0 +1,146 @@
+// JamesDSP on Spotify's sound: the effects engine of JamesDSP Manager, RootlessJamesDSP and JamesDSP for
+// Linux (libjamesdsp, vendor/libjamesdsp), run on every buffer Spotify's output unit finishes, before the
+// speaker. Either look: it draws nothing on Spotify's screens. Mod Settings > Audio effects is its page.
+//
+// What it offers is RootlessJamesDSP's list: output gain and limiter, dynamic range compressor, dynamic bass
+// boost, the 15 band multimodal equalizer, the arbitrary response (graphic) equalizer, the convolver
+// (impulse responses), ViPER DDC, Liveprog (EEL scripts), reverb, stereo widening, crossfeed and analog
+// modelling. Each effect has a switch and its own values, kept under its own keys.
+//
+// Unlike the mod's other switches these apply as they change, not at launch: every setter below stores the
+// value and hands the effect it belongs to to the engine, which re-reads that effect's keys off the main
+// thread. The engine is made the first time Spotify starts its output with the master switch on.
+//
+// Threading: everything here is main thread, except SGDSPStatus and SGDSPError, which any thread may call.
+#import <Foundation/Foundation.h>
+
+#pragma mark - keys
+
+// The master switch, off until asked for. Off, Spotify's sound is left exactly as it was.
+#define SGKeyDSP @"spotifyglass.dsp"
+
+// Output control, always applied while the master switch is on.
+#define SGKeyDSPPostGain @"spotifyglass.dsp.postGain" // dB
+#define SGKeyDSPLimiterThreshold @"spotifyglass.dsp.limiterThreshold" // dB
+#define SGKeyDSPLimiterRelease @"spotifyglass.dsp.limiterRelease" // ms
+
+#define SGKeyDSPCompander @"spotifyglass.dsp.compander"
+#define SGKeyDSPCompanderTime @"spotifyglass.dsp.compander.time" // s, the time constant
+#define SGKeyDSPCompanderGranularity @"spotifyglass.dsp.compander.granularity"
+#define SGKeyDSPCompanderTransform @"spotifyglass.dsp.compander.transform" // SGDSPCompanderTransformNames index
+// Seven gains, "g;g;g;g;g;g;g", at SGDSPCompanderFrequencies, each within SGDSPCompanderGainLimit.
+#define SGKeyDSPCompanderGains @"spotifyglass.dsp.compander.gains"
+
+#define SGKeyDSPBass @"spotifyglass.dsp.bass"
+#define SGKeyDSPBassGain @"spotifyglass.dsp.bass.gain" // dB, the most it lifts
+
+#define SGKeyDSPEqualizer @"spotifyglass.dsp.eq"
+#define SGKeyDSPEqualizerFilter @"spotifyglass.dsp.eq.filter" // SGDSPEqualizerFilterNames index
+#define SGKeyDSPEqualizerInterpolation @"spotifyglass.dsp.eq.interpolation" // SGDSPEqualizerInterpolationNames index
+// Fifteen gains in dB, "g;g;...;g", at SGDSPEqualizerFrequencies, each within SGDSPEqualizerGainLimit.
+#define SGKeyDSPEqualizerGains @"spotifyglass.dsp.eq.gains"
+
+// The arbitrary response equalizer, in AutoEq's GraphicEQ format: "GraphicEQ: 20 -1.2; 21 -1.1; ...".
+#define SGKeyDSPGraphicEq @"spotifyglass.dsp.geq"
+#define SGKeyDSPGraphicEqNodes @"spotifyglass.dsp.geq.nodes"
+
+// File effects name a file in their library (SGDSPLibraryFiles), by its name alone: the app's container
+// moves on every reinstall, the name does not.
+#define SGKeyDSPConvolver @"spotifyglass.dsp.convolver"
+#define SGKeyDSPConvolverFile @"spotifyglass.dsp.convolver.file"
+#define SGKeyDSPConvolverMode @"spotifyglass.dsp.convolver.mode" // SGDSPConvolverModeNames index
+// "-80;-100;0;0;0;0", JamesDSP's advanced waveform editing of the impulse response; no page edits it yet.
+#define SGKeyDSPConvolverWaveEdit @"spotifyglass.dsp.convolver.waveEdit"
+
+#define SGKeyDSPDDC @"spotifyglass.dsp.ddc"
+#define SGKeyDSPDDCFile @"spotifyglass.dsp.ddc.file"
+
+#define SGKeyDSPLiveprog @"spotifyglass.dsp.liveprog"
+#define SGKeyDSPLiveprogFile @"spotifyglass.dsp.liveprog.file"
+
+#define SGKeyDSPReverb @"spotifyglass.dsp.reverb"
+#define SGKeyDSPReverbPreset @"spotifyglass.dsp.reverb.preset" // SGDSPReverbPresets index
+
+#define SGKeyDSPStereoWide @"spotifyglass.dsp.wide"
+#define SGKeyDSPStereoWideLevel @"spotifyglass.dsp.wide.level" // percent
+
+#define SGKeyDSPCrossfeed @"spotifyglass.dsp.crossfeed"
+#define SGKeyDSPCrossfeedMode @"spotifyglass.dsp.crossfeed.mode" // SGDSPCrossfeedModeNames index
+
+#define SGKeyDSPTube @"spotifyglass.dsp.tube"
+#define SGKeyDSPTubeDrive @"spotifyglass.dsp.tube.drive" // dB
+
+#pragma mark - values
+
+// A number setting's bounds, the value it has until set, and the step a slider moves it by. Ranges are
+// RootlessJamesDSP's.
+typedef struct {
+ double min, max, fallback, step;
+} SGDSPRange;
+
+SGDSPRange SGDSPRangeFor(NSString *key);
+
+// Switches, numbers (clamped to their range) and strings. Setting one applies it.
+BOOL SGDSPSwitch(NSString *key);
+void SGDSPSetSwitch(NSString *key, BOOL on);
+double SGDSPNumber(NSString *key);
+void SGDSPSetNumber(NSString *key, double value);
+NSString *SGDSPString(NSString *key);
+void SGDSPSetString(NSString *key, NSString *value);
+
+// The equalizer's and the compressor's gains as numbers (15 and 7 of them), from and to their keys.
+NSArray<NSNumber *> *SGDSPGains(NSString *key);
+void SGDSPSetGains(NSString *key, NSArray<NSNumber *> *gains);
+
+// Every key above back to its value until set; the master switch stays as it is.
+void SGDSPResetAll(void);
+
+#pragma mark - the lists the choices pick from
+
+extern const double SGDSPEqualizerFrequencies[15]; // Hz, 25 ... 16000
+extern const double SGDSPEqualizerGainLimit; // ±12 dB
+extern const double SGDSPCompanderFrequencies[7]; // Hz, 95 ... 7500
+extern const double SGDSPCompanderGainLimit; // ±1.2
+
+NSArray<NSString *> *SGDSPEqualizerFilterNames(void);
+NSArray<NSString *> *SGDSPEqualizerInterpolationNames(void);
+NSArray<NSString *> *SGDSPCompanderTransformNames(void);
+NSArray<NSString *> *SGDSPConvolverModeNames(void);
+NSArray<NSString *> *SGDSPCrossfeedModeNames(void);
+NSArray<NSString *> *SGDSPReverbPresetNames(void);
+// The equalizer presets of JamesDSP (Acoustic, Bass, ... Vocal Booster), names and their 15 gains.
+NSArray<NSString *> *SGDSPEqualizerPresetNames(void);
+NSArray<NSNumber *> *SGDSPEqualizerPreset(NSInteger index);
+
+#pragma mark - file libraries
+
+typedef NS_ENUM(NSInteger, SGDSPFileKind) {
+ SGDSPFileImpulseResponse, // the convolver's: .wav .flac .irs (a WAV by another name)
+ SGDSPFileDDC, // ViPER DDC's .vdc
+ SGDSPFileLiveprog, // Liveprog's .eel
+};
+
+// Documents/spoti.pw/JamesDSP/<Convolver|DDC|Liveprog>, made on first use and holding the files JamesDSP
+// ships (Liveprog scripts, DDC presets) the first time it is made.
+NSString *SGDSPLibraryDirectory(SGDSPFileKind kind);
+NSArray<NSString *> *SGDSPLibraryFiles(SGDSPFileKind kind); // names, sorted
+NSArray<NSString *> *SGDSPFileExtensions(SGDSPFileKind kind); // lowercase, without the dot
+// Copies a picked file into the library, replacing one of the same name; answers its name, nil and an
+// error when it is not a file of that kind.
+NSString *SGDSPImportFile(SGDSPFileKind kind, NSURL *url, NSError **error);
+BOOL SGDSPDeleteFile(SGDSPFileKind kind, NSString *name);
+
+#pragma mark - what the engine is doing
+
+// One line for the page: off, waiting for Spotify to play, or running (sample rate, load).
+NSString *SGDSPStatus(void);
+// Why an effect's last change did not take, nil when it did: a script that did not compile (with the
+// line), an impulse response that could not be read, a DDC file that was not one. Keyed by the effect's
+// switch key (SGKeyDSPLiveprog, SGKeyDSPConvolver, SGKeyDSPDDC, SGKeyDSPGraphicEq).
+NSString *SGDSPError(NSString *switchKey);
+
+// The equalizer's magnitude response for the stored filter and the given gains, for drawing the curve:
+// `count` points log-spaced from 20 Hz to 20 kHz into `frequencies` and `decibels`.
+void SGDSPEqualizerResponse(NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *decibels);
+// The compressor's response curve for the given gains, the same way.
+void SGDSPCompanderResponse(NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *values);
diff --git a/tweak/Sources/Shared/JamesDSP/JamesDSP.x b/tweak/Sources/Shared/JamesDSP/JamesDSP.x
new file mode 100644
index 00000000..ba2eee29
--- /dev/null
+++ b/tweak/Sources/Shared/JamesDSP/JamesDSP.x
@@ -0,0 +1,596 @@
+// JamesDSP on Spotify's sound (JamesDSP.h): every buffer Spotify's output unit finishes runs through
+// SGDSPEngine before it reaches the speaker.
+//
+// Spotify plays through Core Audio units of its own (AudioUnitDriver2 in the binary: converter, EQ, mixer
+// and a RemoteIO output unit, started with AudioOutputUnitStart), with no Objective-C method between it and
+// the unit. So Spotify's import of AudioOutputUnitStart is rebound (Core/SGRebind.h; Music Haptics and Speed
+// and pitch rebind it too, and each replacement calls on what the slot held), and every RemoteIO unit it
+// starts gets a render notify. After each render the notify reads the buffer bound for the speaker into
+// float lanes, runs the engine over them and writes them back, in place: the way the first version of Pitch
+// worked on the phone. Speed and pitch feeds the unit's input, so its sound reaches the notify changed.
+//
+// The engine is made the first time the output starts with the master switch on, at the output's rate,
+// and lives as long as Spotify: the render thread may be holding it at any time. With the switch off the
+// notify returns straight away, and Spotify's sound is untouched. Silence goes through the engine too, so a
+// reverb or a convolver rings out after a track stops.
+//
+// Settings apply as they change: SGDSPApply marks the effect, and a serial queue reads its keys a moment
+// later and sets them, so a slider dragged across comes down to the last few values. The queue also makes
+// the engine, follows the output to a new sample rate, and once a second logs what libjamesdsp printed.
+//
+// Threading: the notify runs on the render thread and touches only atomics, its scratch lanes and the
+// engine's render side. Spotify starts its output on a thread of its own. The effects are set on the queue;
+// SGDSPApply and the curves are main thread; SGDSPStatus and SGDSPError any thread.
+#import <AudioToolbox/AudioToolbox.h>
+#import <os/lock.h>
+#import <stdatomic.h>
+#import "Core/SGCore.h"
+#import "Core/SGRebind.h"
+#import "JamesDSP.h"
+#import "JamesDSPEngine.h"
+#import "SGDSPEngine.h"
+
+// A burst of changes to a setting is gathered this long before it applies.
+static const double kApplyAfter = 0.03;
+// libjamesdsp's printed lines logged per second at most; the rest are counted.
+static const unsigned kLogLinesPerSecond = 8;
+// How often a summary of the engine's work goes to the log while it runs.
+static const double kSummaryEvery = 60;
+
+enum { kScratchFrames = 4096 };
+
+// The switches of the effects, in the order they are set when everything is.
+static NSArray<NSString *> *effectSwitches(void) {
+ return @[SGKeyDSPCompander, SGKeyDSPBass, SGKeyDSPEqualizer, SGKeyDSPGraphicEq, SGKeyDSPConvolver, SGKeyDSPDDC,
+ SGKeyDSPLiveprog, SGKeyDSPReverb, SGKeyDSPStereoWide, SGKeyDSPCrossfeed, SGKeyDSPTube];
+}
+
+#pragma mark - shared between the threads
+
+typedef enum { SGOutputUnseen, SGOutputPCM, SGOutputUnsupported } SGOutputState;
+
+static _Atomic(SGDSPEngine *) sg_engine; // made once on the queue, never freed
+static atomic_bool sg_running; // the switch on and the engine set up for the output
+static atomic_int sg_outputState;
+// The format of the buffers the notify gets: the rate, and the layout packed into one word so the render
+// thread never reads half of a change (flags in the low 32 bits, then channels, then bytes per sample).
+static atomic_uint_fast64_t sg_rateBits;
+static atomic_uint_fast64_t sg_layout;
+static atomic_uint_fast64_t sg_skipped; // renders whose buffers were not laid out as the format says
+
+static os_unfair_lock sg_errorLock = OS_UNFAIR_LOCK_INIT;
+static NSMutableDictionary<NSString *, NSString *> *sg_errors;
+
+static void storeDouble(atomic_uint_fast64_t *slot, double value) {
+ uint64_t bits;
+ memcpy(&bits, &value, sizeof bits);
+ atomic_store(slot, bits);
+}
+
+static double loadDouble(atomic_uint_fast64_t *slot) {
+ uint64_t bits = atomic_load_explicit(slot, memory_order_relaxed);
+ double value;
+ memcpy(&value, &bits, sizeof value);
+ return value;
+}
+
+#pragma mark - the render thread
+
+static float sg_left[kScratchFrames], sg_right[kScratchFrames];
+
+static inline float readSample(const void *data, UInt32 index, UInt32 bytes, BOOL isFloat, UInt32 fraction) {
+ if (bytes == 4) {
+ if (isFloat) return ((const float *)data)[index];
+ int32_t value = ((const int32_t *)data)[index];
+ return fraction ? (float)((double)value / (double)(1u << fraction)) : (float)(value / 2147483648.0);
+ }
+ return ((const int16_t *)data)[index] / 32768.0f;
+}
+
+static inline void writeSample(void *data, UInt32 index, float value, UInt32 bytes, BOOL isFloat, UInt32 fraction) {
+ if (bytes == 4 && isFloat) {
+ ((float *)data)[index] = value;
+ return;
+ }
+ value = fmaxf(-1, fminf(value, 1));
+ if (bytes == 4) {
+ double scale = fraction ? (double)(1u << fraction) : 2147483647.0;
+ ((int32_t *)data)[index] = (int32_t)(value * scale);
+ } else {
+ ((int16_t *)data)[index] = (int16_t)(value * 32767);
+ }
+}
+
+static BOOL anySound(const float *samples, UInt32 count) {
+ for (UInt32 i = 0; i < count; i++) if (samples[i] != 0) return YES;
+ return NO;
+}
+
+// The buffer through the engine in place, whatever its format: the buffers themselves as the engine's lanes
+// when they are float, one per channel (the hardware's usual), otherwise read into the scratch lanes and
+// written back. The first two channels are the engine's; a mono output is fed to both and gets their mean.
+static void processBuffer(SGDSPEngine *engine, AudioUnitRenderActionFlags *flags, UInt32 frames, AudioBufferList *data) {
+ uint64_t layout = atomic_load_explicit(&sg_layout, memory_order_relaxed);
+ UInt32 formatFlags = (UInt32)layout, channels = (UInt32)(layout >> 32) & 0xffff, bytes = (UInt32)(layout >> 48);
+ BOOL isFloat = (formatFlags & kAudioFormatFlagIsFloat) != 0;
+ BOOL split = (formatFlags & kAudioFormatFlagIsNonInterleaved) != 0;
+ UInt32 fraction = (formatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift;
+ if ((bytes != 2 && bytes != 4) || channels < 1) return;
+ // Buffers not laid out as the format says are left alone rather than read as noise: the format read at
+ // the start can be a moment old.
+ BOOL fits = split ? data->mNumberBuffers == channels : data->mNumberBuffers == 1 && data->mBuffers[0].mNumberChannels == channels;
+ for (UInt32 b = 0; fits && b < data->mNumberBuffers; b++) {
+ fits = data->mBuffers[b].mData && data->mBuffers[b].mDataByteSize == frames * bytes * (split ? 1 : channels);
+ }
+ if (!fits) {
+ atomic_fetch_add_explicit(&sg_skipped, 1, memory_order_relaxed);
+ return;
+ }
+ // A silent buffer's contents are not promised; the engine gets zeros, and its tail replaces them.
+ BOOL silent = (*flags & kAudioUnitRenderAction_OutputIsSilence) != 0;
+ BOOL loud = NO;
+
+ if (split && isFloat && bytes == 4 && channels >= 2) {
+ float *left = data->mBuffers[0].mData, *right = data->mBuffers[1].mData;
+ if (silent) {
+ memset(left, 0, frames * sizeof(float));
+ memset(right, 0, frames * sizeof(float));
+ }
+ SGDSPEngineProcess(engine, left, right, frames);
+ loud = !silent || anySound(left, frames) || anySound(right, frames);
+ } else {
+ for (UInt32 done = 0; done < frames;) {
+ UInt32 count = MIN(frames - done, (UInt32)kScratchFrames);
+ const void *first = data->mBuffers[0].mData, *second = split && channels > 1 ? data->mBuffers[1].mData : first;
+ UInt32 stride = split ? 1 : channels, secondOffset = !split && channels > 1 ? 1 : 0;
+ for (UInt32 i = 0; i < count; i++) {
+ UInt32 at = (done + i) * stride;
+ sg_left[i] = silent ? 0 : readSample(first, at, bytes, isFloat, fraction);
+ sg_right[i] = silent ? 0 : readSample(second, at + secondOffset, bytes, isFloat, fraction);
+ }
+ SGDSPEngineProcess(engine, sg_left, sg_right, count);
+ loud = loud || !silent || anySound(sg_left, count) || anySound(sg_right, count);
+ void *firstOut = data->mBuffers[0].mData, *secondOut = split && channels > 1 ? data->mBuffers[1].mData : firstOut;
+ for (UInt32 i = 0; i < count; i++) {
+ UInt32 at = (done + i) * stride;
+ if (channels == 1) {
+ writeSample(firstOut, at, 0.5f * (sg_left[i] + sg_right[i]), bytes, isFloat, fraction);
+ } else {
+ writeSample(firstOut, at, sg_left[i], bytes, isFloat, fraction);
+ writeSample(secondOut, at + secondOffset, sg_right[i], bytes, isFloat, fraction);
+ }
+ }
+ done += count;
+ }
+ }
+ if (loud) *flags &= ~kAudioUnitRenderAction_OutputIsSilence;
+}
+
+static OSStatus rendered(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,
+ UInt32 frames, AudioBufferList *data) {
+ if (!(*flags & kAudioUnitRenderAction_PostRender) || bus != 0 || !data || !data->mNumberBuffers || !frames) return noErr;
+ if (!atomic_load_explicit(&sg_running, memory_order_acquire)) return noErr;
+ SGDSPEngine *engine = atomic_load_explicit(&sg_engine, memory_order_acquire);
+ // A new rate is being set up on the queue: until then the sound passes as it is.
+ if (!engine || SGDSPEngineSampleRate(engine) != loadDouble(&sg_rateBits)) return noErr;
+ processBuffer(engine, flags, frames, data);
+ return noErr;
+}
+
+#pragma mark - Spotify's audio thread
+
+static NSString *fourCC(UInt32 code) {
+ char text[5] = {(char)(code >> 24), (char)(code >> 16), (char)(code >> 8), (char)code, 0};
+ return @(text);
+}
+
+static BOOL isRemoteIO(AudioUnit unit) {
+ AudioComponentDescription description = {0};
+ if (!unit || AudioComponentGetDescription(AudioComponentInstanceGetComponent(unit), &description) != noErr) return NO;
+ return description.componentType == kAudioUnitType_Output && description.componentSubType == kAudioUnitSubType_RemoteIO;
+}
+
+static NSString *formatText(AudioStreamBasicDescription format) {
+ if (format.mFormatID != kAudioFormatLinearPCM) return [NSString stringWithFormat:@"'%@'", fourCC(format.mFormatID)];
+ return [NSString stringWithFormat:@"%.0f Hz, %u channels, %u-bit %@%@", format.mSampleRate, (unsigned)format.mChannelsPerFrame,
+ (unsigned)format.mBitsPerChannel, (format.mFormatFlags & kAudioFormatFlagIsFloat) ? @"float" : @"integer",
+ (format.mFormatFlags & kAudioFormatFlagIsNonInterleaved) ? @", a buffer per channel" : @", interleaved"];
+}
+
+// The format the notify's buffers are in, which is the RemoteIO unit's output side (element 0, output scope):
+// the hardware's, not the one Spotify hands the unit (the input scope). In the simulator a 44.1 kHz client
+// comes out at 48 kHz, and a 16-bit interleaved one as float, a buffer per channel (harness/jamesdsp/sim).
+// Answers whether the engine can take it.
+static BOOL readFormat(AudioUnit unit) {
+ AudioStreamBasicDescription format = {0}, client = {0};
+ UInt32 size = sizeof format;
+ OSStatus status = AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format, &size);
+ size = sizeof client;
+ AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &client, &size);
+ UInt32 bytes = format.mBitsPerChannel / 8;
+ BOOL takes = status == noErr && format.mFormatID == kAudioFormatLinearPCM && format.mSampleRate > 0 && format.mChannelsPerFrame >= 1
+ && (bytes == 2 || bytes == 4) && ((format.mFormatFlags & kAudioFormatFlagIsFloat) || (format.mFormatFlags & kAudioFormatFlagIsSignedInteger));
+ // Spotify starts its output again after every pause; the format is logged when it is not the last one.
+ // Spotify's thread and a format change's may both be here.
+ static os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;
+ static NSString *logged;
+ NSString *text = [NSString stringWithFormat:@"jamesdsp: Spotify's output renders %@, from %@ Spotify hands it%@", formatText(format),
+ formatText(client), takes ? @"" : [NSString stringWithFormat:@"; not a format the engine takes (status %d), its sound passes as it is", (int)status]];
+ os_unfair_lock_lock(&lock);
+ BOOL changed = ![text isEqualToString:logged];
+ logged = text;
+ os_unfair_lock_unlock(&lock);
+ if (changed) SGLog(@"%@", text);
+ if (!takes) {
+ atomic_store(&sg_layout, 0);
+ atomic_store(&sg_outputState, SGOutputUnsupported);
+ return NO;
+ }
+ storeDouble(&sg_rateBits, format.mSampleRate);
+ atomic_store(&sg_layout, (uint64_t)format.mFormatFlags | (uint64_t)(format.mChannelsPerFrame & 0xffff) << 32 | (uint64_t)bytes << 48);
+ atomic_store(&sg_outputState, SGOutputPCM);
+ // The engine is made, or follows a new rate, when the switch is on.
+ dispatch_async(dispatch_get_main_queue(), ^{
+ SGDSPApply(SGKeyDSP);
+ });
+ return YES;
+}
+
+// The hardware's format changing under a running unit (a route to a device at another rate).
+static void formatChanged(void *refCon, AudioUnit unit, AudioUnitPropertyID property, AudioUnitScope scope, AudioUnitElement element) {
+ if (property == kAudioUnitProperty_StreamFormat && scope == kAudioUnitScope_Output && element == 0) readFormat(unit);
+}
+
+static void listenTo(AudioUnit unit) {
+ AudioUnitRemoveRenderNotify(unit, rendered, NULL);
+ AudioUnitRemovePropertyListenerWithUserData(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);
+ AudioUnitAddPropertyListener(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);
+ if (!readFormat(unit)) return;
+ // The sound held from before the output stopped would play first; the stream starts over instead.
+ SGDSPEngine *engine = atomic_load(&sg_engine);
+ if (engine) SGDSPEngineRestart(engine);
+ OSStatus status = AudioUnitAddRenderNotify(unit, rendered, NULL);
+ if (status != noErr) SGLog(@"jamesdsp: the render notify could not be added (%d)", (int)status);
+}
+
+static OSStatus (*sg_startOutput)(AudioUnit unit);
+
+static OSStatus startOutput(AudioUnit unit) {
+ if (isRemoteIO(unit)) listenTo(unit);
+ return sg_startOutput(unit);
+}
+
+#pragma mark - errors
+
+// An effect's name in the log, by its switch key.
+static NSString *effectName(NSString *effect) {
+ NSDictionary<NSString *, NSString *> *names = @{
+ SGKeyDSPCompander: @"compander", SGKeyDSPBass: @"bass boost", SGKeyDSPEqualizer: @"equalizer", SGKeyDSPGraphicEq: @"graphic EQ",
+ SGKeyDSPConvolver: @"convolver", SGKeyDSPDDC: @"DDC", SGKeyDSPLiveprog: @"Liveprog", SGKeyDSPReverb: @"reverb",
+ SGKeyDSPStereoWide: @"stereo widening", SGKeyDSPCrossfeed: @"crossfeed", SGKeyDSPTube: @"analog modelling",
+ };
+ return names[effect] ?: effect;
+}
+
+static void setError(NSString *effect, NSString *message) {
+ os_unfair_lock_lock(&sg_errorLock);
+ if (!sg_errors) sg_errors = [NSMutableDictionary dictionary];
+ sg_errors[effect] = message;
+ os_unfair_lock_unlock(&sg_errorLock);
+ if (message) SGLog(@"jamesdsp: %@ did not take: %@", effectName(effect), message);
+}
+
+NSString *SGDSPError(NSString *switchKey) {
+ if (!switchKey) return nil;
+ os_unfair_lock_lock(&sg_errorLock);
+ NSString *message = sg_errors[switchKey];
+ os_unfair_lock_unlock(&sg_errorLock);
+ return message;
+}
+
+#pragma mark - the queue: setting the effects
+
+static NSString *onOff(BOOL on) {
+ return on ? @"on" : @"off";
+}
+
+static NSString *gainsText(NSArray<NSNumber *> *gains) {
+ NSMutableArray<NSString *> *parts = [NSMutableArray arrayWithCapacity:gains.count];
+ for (NSNumber *gain in gains) [parts addObject:[NSString stringWithFormat:@"%g", gain.doubleValue]];
+ return [parts componentsJoinedByString:@" "];
+}
+
+static NSString *choice(NSArray<NSString *> *names, NSString *key) {
+ NSInteger index = (NSInteger)SGDSPNumber(key);
+ return index >= 0 && index < (NSInteger)names.count ? names[index] : @(index).stringValue;
+}
+
+// A file effect's file, from its library by name: its path, nil and an error when there is none to read.
+static NSString *libraryFile(SGDSPFileKind kind, NSString *nameKey, NSString *effect, BOOL on) {
+ NSString *name = SGDSPString(nameKey);
+ if (!on) return nil;
+ if (!name.length) {
+ setError(effect, @"No file is chosen");
+ return nil;
+ }
+ NSString *path = [SGDSPLibraryDirectory(kind) stringByAppendingPathComponent:name.lastPathComponent];
+ if (![NSFileManager.defaultManager fileExistsAtPath:path]) {
+ setError(effect, [NSString stringWithFormat:@"%@ is not in the library any more", name]);
+ return nil;
+ }
+ return path;
+}
+
+// A text file with a NUL after it, for libjamesdsp's parsers.
+static NSData *textFile(NSString *path) {
+ NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
+ [data appendBytes:"" length:1];
+ return data;
+}
+
+static void applyOutput(SGDSPEngine *engine) {
+ double gain = SGDSPNumber(SGKeyDSPPostGain), threshold = SGDSPNumber(SGKeyDSPLimiterThreshold), release = SGDSPNumber(SGKeyDSPLimiterRelease);
+ SGDSPEngineSetOutput(engine, gain, threshold, release);
+ // Set again on every start of Spotify's output; logged when it changed.
+ static NSString *logged;
+ NSString *text = [NSString stringWithFormat:@"jamesdsp: output gain %+.1f dB, limiter at %.1f dB releasing in %.1f ms", gain, threshold, release];
+ if (![text isEqualToString:logged]) SGLog(@"%@", text);
+ logged = text;
+}
+
+static void applyEffect(SGDSPEngine *engine, NSString *effect) {
+ BOOL on = SGDSPSwitch(effect);
+ char error[300] = "";
+ BOOL ok = YES;
+ NSString *what = @"";
+ if ([effect isEqualToString:SGKeyDSPCompander]) {
+ NSArray<NSNumber *> *gains = SGDSPGains(SGKeyDSPCompanderGains);
+ double values[7];
+ for (int i = 0; i < 7; i++) values[i] = gains[i].doubleValue;
+ double time = SGDSPNumber(SGKeyDSPCompanderTime);
+ int granularity = (int)SGDSPNumber(SGKeyDSPCompanderGranularity), transform = (int)SGDSPNumber(SGKeyDSPCompanderTransform);
+ SGDSPEngineSetCompander(engine, on, time, granularity, transform, SGDSPCompanderFrequencies, values);
+ what = [NSString stringWithFormat:@"compander %@, %.2f s, granularity %d, %@, gains %@", onOff(on), time, granularity,
+ choice(SGDSPCompanderTransformNames(), SGKeyDSPCompanderTransform), gainsText(gains)];
+ } else if ([effect isEqualToString:SGKeyDSPBass]) {
+ double gain = SGDSPNumber(SGKeyDSPBassGain);
+ SGDSPEngineSetBassBoost(engine, on, gain);
+ what = [NSString stringWithFormat:@"bass boost %@, %.1f dB", onOff(on), gain];
+ } else if ([effect isEqualToString:SGKeyDSPEqualizer]) {
+ NSArray<NSNumber *> *gains = SGDSPGains(SGKeyDSPEqualizerGains);
+ double values[15];
+ for (int i = 0; i < 15; i++) values[i] = gains[i].doubleValue;
+ int filter = (int)SGDSPNumber(SGKeyDSPEqualizerFilter), interpolation = (int)SGDSPNumber(SGKeyDSPEqualizerInterpolation);
+ SGDSPEngineSetEqualizer(engine, on, filter, interpolation, SGDSPEqualizerFrequencies, values);
+ what = [NSString stringWithFormat:@"equalizer %@, %@, %@, gains %@", onOff(on), choice(SGDSPEqualizerFilterNames(), SGKeyDSPEqualizerFilter),
+ choice(SGDSPEqualizerInterpolationNames(), SGKeyDSPEqualizerInterpolation), gainsText(gains)];
+ } else if ([effect isEqualToString:SGKeyDSPGraphicEq]) {
+ NSString *nodes = SGDSPString(SGKeyDSPGraphicEqNodes);
+ ok = SGDSPEngineSetGraphicEq(engine, on, nodes.UTF8String, error, sizeof error);
+ NSUInteger count = [nodes componentsSeparatedByString:@";"].count;
+ what = [NSString stringWithFormat:@"graphic EQ %@, about %lu nodes", onOff(on), (unsigned long)(count > 1 ? count - 1 : count)];
+ } else if ([effect isEqualToString:SGKeyDSPConvolver]) {
+ NSString *path = libraryFile(SGDSPFileImpulseResponse, SGKeyDSPConvolverFile, effect, on);
+ if (on && !path) {
+ SGDSPEngineSetConvolver(engine, false, NULL, 0, NULL, error, sizeof error);
+ return;
+ }
+ ok = SGDSPEngineSetConvolver(engine, on, path.fileSystemRepresentation, (int)SGDSPNumber(SGKeyDSPConvolverMode),
+ SGDSPString(SGKeyDSPConvolverWaveEdit).UTF8String, error, sizeof error);
+ what = [NSString stringWithFormat:@"convolver %@%@%@", onOff(on), on ? @", " : @"", on ? [NSString stringWithFormat:@"%@ (%@)",
+ path.lastPathComponent, choice(SGDSPConvolverModeNames(), SGKeyDSPConvolverMode)] : @""];
+ } else if ([effect isEqualToString:SGKeyDSPDDC]) {
+ NSString *path = libraryFile(SGDSPFileDDC, SGKeyDSPDDCFile, effect, on);
+ if (on && !path) {
+ SGDSPEngineSetDDC(engine, false, NULL, error, sizeof error);
+ return;
+ }
+ NSData *text = on ? textFile(path) : nil;
+ ok = SGDSPEngineSetDDC(engine, on && text, text.bytes, error, sizeof error);
+ what = [NSString stringWithFormat:@"DDC %@%@%@", onOff(on), on ? @", " : @"", on ? path.lastPathComponent : @""];
+ } else if ([effect isEqualToString:SGKeyDSPLiveprog]) {
+ NSString *path = libraryFile(SGDSPFileLiveprog, SGKeyDSPLiveprogFile, effect, on);
+ if (on && !path) {
+ SGDSPEngineSetLiveprog(engine, false, NULL, error, sizeof error);
+ return;
+ }
+ NSData *script = on ? textFile(path) : nil;
+ CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
+ ok = SGDSPEngineSetLiveprog(engine, on && script, script.bytes, error, sizeof error);
+ what = [NSString stringWithFormat:@"Liveprog %@%@%@", onOff(on), on ? @", " : @"", on ? [NSString stringWithFormat:@"%@ compiled in %.0f ms",
+ path.lastPathComponent, (CFAbsoluteTimeGetCurrent() - start) * 1000] : @""];
+ } else if ([effect isEqualToString:SGKeyDSPReverb]) {
+ // The page's list leaves out some of libjamesdsp's presets, as RootlessJamesDSP's does.
+ static const int presets[] = {0, 1, 2, 4, 5, 7, 8, 9, 11, 15, 16, 17, 18};
+ NSInteger index = MAX(0, MIN((NSInteger)(sizeof presets / sizeof *presets) - 1, (NSInteger)SGDSPNumber(SGKeyDSPReverbPreset)));
+ SGDSPEngineSetReverb(engine, on, presets[index]);
+ what = [NSString stringWithFormat:@"reverb %@, %@", onOff(on), choice(SGDSPReverbPresetNames(), SGKeyDSPReverbPreset)];
+ } else if ([effect isEqualToString:SGKeyDSPStereoWide]) {
+ double level = SGDSPNumber(SGKeyDSPStereoWideLevel);
+ SGDSPEngineSetStereoWide(engine, on, level);
+ what = [NSString stringWithFormat:@"stereo widening %@, %.0f%%", onOff(on), level];
+ } else if ([effect isEqualToString:SGKeyDSPCrossfeed]) {
+ SGDSPEngineSetCrossfeed(engine, on, (int)SGDSPNumber(SGKeyDSPCrossfeedMode));
+ what = [NSString stringWithFormat:@"crossfeed %@, %@", onOff(on), choice(SGDSPCrossfeedModeNames(), SGKeyDSPCrossfeedMode)];
+ } else if ([effect isEqualToString:SGKeyDSPTube]) {
+ double drive = SGDSPNumber(SGKeyDSPTubeDrive);
+ SGDSPEngineSetTube(engine, on, drive);
+ what = [NSString stringWithFormat:@"analog modelling %@, %.1f dB", onOff(on), drive];
+ } else {
+ return;
+ }
+ setError(effect, ok ? nil : @(error));
+ if (ok) SGLog(@"jamesdsp: %@", what);
+}
+
+#pragma mark - the queue: the engine
+
+static dispatch_queue_t applyQueue(void) {
+ static dispatch_queue_t queue;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ queue = dispatch_queue_create("spotifyglass.dsp", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0));
+ });
+ return queue;
+}
+
+static void logPrinted(const char *text, void *context) {
+ unsigned *count = context;
+ for (NSString *line in [@(text) componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
+ NSString *trimmed = [line stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
+ if (trimmed.length && (*count)++ < kLogLinesPerSecond) SGLog(@"jamesdsp: %@", trimmed);
+ }
+}
+
+static void applyAll(SGDSPEngine *engine) {
+ applyOutput(engine);
+ for (NSString *effect in effectSwitches()) applyEffect(engine, effect);
+}
+
+// Once a second while the engine lives: what libjamesdsp printed, an engine gone non-finite started over,
+// and now and then a summary.
+static void tend(void) {
+ SGDSPEngine *engine = atomic_load(&sg_engine);
+ unsigned count = 0;
+ unsigned dropped = SGDSPEngineReadLog(logPrinted, &count, 64);
+ if (count > kLogLinesPerSecond || dropped) {
+ SGLog(@"jamesdsp: %u more lines of libjamesdsp's output left out", count - MIN(count, kLogLinesPerSecond) + dropped);
+ }
+ static uint64_t faults, blocks, skipped;
+ static CFAbsoluteTime summarized, skipsLogged;
+ SGDSPEngineStats stats = SGDSPEngineReadStats(engine, true);
+ if (stats.faults != faults) {
+ faults = stats.faults;
+ SGLog(@"jamesdsp: the output stopped being finite (%llu blocks silenced), the engine starts over", stats.faults);
+ SGDSPEngineReset(engine);
+ applyAll(engine);
+ }
+ CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
+ uint64_t skippedNow = atomic_load(&sg_skipped);
+ if (skippedNow != skipped && now - skipsLogged >= 10) {
+ SGLog(@"jamesdsp: %llu renders left alone, their buffers not laid out as the output's format says", skippedNow - skipped);
+ skipped = skippedNow;
+ skipsLogged = now;
+ }
+ if (stats.blocks != blocks && now - summarized >= kSummaryEvery) {
+ summarized = now;
+ SGLog(@"jamesdsp: %llu blocks processed, %llu passed dry while settings changed, %.2f ms a block (%.1f%% of its time), %.2f ms at most",
+ stats.blocks - blocks, stats.dry, stats.averageMS, stats.load * 100, stats.peakMS);
+ blocks = stats.blocks;
+ }
+}
+
+// The switch and the output's format: the engine made or moved to the output's rate, everything set when
+// it was, and the notify let in or kept out. Answers whether every effect was set.
+static BOOL applyMaster(void) {
+ if (!SGDSPSwitch(SGKeyDSP)) {
+ if (atomic_exchange(&sg_running, false)) SGLog(@"jamesdsp: off, Spotify's sound passes as it is");
+ return NO;
+ }
+ double rate = loadDouble(&sg_rateBits);
+ if (atomic_load(&sg_outputState) != SGOutputPCM || rate <= 0) {
+ SGLog(@"jamesdsp: on, waiting for Spotify to start its output");
+ return NO;
+ }
+ SGDSPEngine *engine = atomic_load(&sg_engine);
+ BOOL everything = NO;
+ if (!engine) {
+ engine = SGDSPEngineCreate(rate);
+ if (!engine) {
+ SGLog(@"jamesdsp: the engine could not be made at %.0f Hz", rate);
+ return NO;
+ }
+ SGLog(@"jamesdsp: engine made at %.0f Hz, blocks of %d frames, so the sound is %.1f ms later", rate, kSGDSPEngineBlock,
+ kSGDSPEngineBlock / rate * 1000);
+ atomic_store(&sg_engine, engine);
+ static dispatch_source_t timer;
+ timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, applyQueue());
+ dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC, NSEC_PER_SEC / 4);
+ dispatch_source_set_event_handler(timer, ^{
+ tend();
+ });
+ dispatch_resume(timer);
+ everything = YES;
+ } else if (SGDSPEngineSampleRate(engine) != rate) {
+ SGDSPEngineSetSampleRate(engine, rate);
+ SGLog(@"jamesdsp: the engine follows the output to %.0f Hz", rate);
+ everything = YES;
+ }
+ if (everything) applyAll(engine);
+ else applyOutput(engine);
+ if (!atomic_load(&sg_running)) {
+ SGDSPEngineRestart(engine);
+ atomic_store_explicit(&sg_running, true, memory_order_release);
+ SGLog(@"jamesdsp: on");
+ }
+ return everything;
+}
+
+static os_unfair_lock sg_pendingLock = OS_UNFAIR_LOCK_INIT;
+static NSMutableOrderedSet<NSString *> *sg_pending;
+static BOOL sg_drainScheduled;
+
+static void drain(void) {
+ os_unfair_lock_lock(&sg_pendingLock);
+ NSArray<NSString *> *effects = sg_pending.array;
+ sg_pending = nil;
+ sg_drainScheduled = NO;
+ os_unfair_lock_unlock(&sg_pendingLock);
+ if ([effects containsObject:SGKeyDSP] && applyMaster()) return;
+ SGDSPEngine *engine = atomic_load(&sg_engine);
+ // Without an engine nothing is set: it is set up with every effect when it is made.
+ if (!engine) return;
+ for (NSString *effect in effects) {
+ if (![effect isEqualToString:SGKeyDSP]) applyEffect(engine, effect);
+ }
+}
+
+void SGDSPApply(NSString *effect) {
+ if (!effect) return;
+ os_unfair_lock_lock(&sg_pendingLock);
+ if (!sg_pending) sg_pending = [NSMutableOrderedSet orderedSet];
+ [sg_pending addObject:effect];
+ BOOL schedule = !sg_drainScheduled;
+ sg_drainScheduled = YES;
+ os_unfair_lock_unlock(&sg_pendingLock);
+ if (schedule) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kApplyAfter * NSEC_PER_SEC)), applyQueue(), ^{
+ drain();
+ });
+}
+
+#pragma mark - what the page shows
+
+NSString *SGDSPStatus(void) {
+ if (!SGDSPSwitch(SGKeyDSP)) return @"Off";
+ if (atomic_load(&sg_outputState) == SGOutputUnsupported) return @"Spotify's output is in a format the engine does not take";
+ SGDSPEngine *engine = atomic_load(&sg_engine);
+ if (!sg_startOutput) return @"Unavailable: Spotify's output could not be reached";
+ if (!engine || !atomic_load(&sg_running)) return @"Waiting for Spotify to play";
+ double rate = SGDSPEngineSampleRate(engine);
+ double load = SGDSPEngineReadStats(engine, false).load;
+ return [NSString stringWithFormat:@"Running at %@ kHz, %.1f%% load", [NSString stringWithFormat:@"%g", rate / 1000], load * 100];
+}
+
+void SGDSPEqualizerResponse(NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *decibels) {
+ if (count <= 0 || !frequencies || !decibels) return;
+ double values[15] = {0};
+ for (NSUInteger i = 0; i < 15 && i < gains.count; i++) values[i] = gains[i].doubleValue;
+ SGDSPEngineEqualizerCurve((int)SGDSPNumber(SGKeyDSPEqualizerFilter), (int)SGDSPNumber(SGKeyDSPEqualizerInterpolation),
+ SGDSPEqualizerFrequencies, values, (int)count, frequencies, decibels);
+}
+
+void SGDSPCompanderResponse(NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *values) {
+ if (count <= 0 || !frequencies || !values) return;
+ double bands[7] = {0};
+ for (NSUInteger i = 0; i < 7 && i < gains.count; i++) bands[i] = gains[i].doubleValue;
+ SGDSPEngineCompanderCurve(SGDSPCompanderFrequencies, bands, (int)count, frequencies, values);
+}
+
+%ctor {
+ if (!SGRebindImport("AudioOutputUnitStart", startOutput, (void **)&sg_startOutput) || !sg_startOutput) {
+ sg_startOutput = NULL;
+ SGLog(@"jamesdsp: Spotify does not import AudioOutputUnitStart, the effects cannot reach its sound");
+ return;
+ }
+ SGLog(@"jamesdsp: listening for Spotify's output unit (%@)", SGDSPSwitch(SGKeyDSP) ? @"on" : @"off");
+}
diff --git a/tweak/Sources/Shared/JamesDSP/JamesDSPEngine.h b/tweak/Sources/Shared/JamesDSP/JamesDSPEngine.h
new file mode 100644
index 00000000..cbe0de8e
--- /dev/null
+++ b/tweak/Sources/Shared/JamesDSP/JamesDSPEngine.h
@@ -0,0 +1,11 @@
+// Between JamesDSP's settings (JamesDSPSettings.m) and its engine (JamesDSP.x), inside Shared/JamesDSP.
+#import <Foundation/Foundation.h>
+
+// The effect a key belongs to, named by its switch key. The master switch and output control's keys
+// belong to SGKeyDSP.
+NSString *SGDSPEffectOf(NSString *key);
+
+// Re-reads the effect's keys into the engine off the main thread, a burst of calls (a slider being dragged)
+// coming down to the last. SGKeyDSP starts the engine when Spotify's output has started, or bypasses it.
+// Main thread.
+void SGDSPApply(NSString *effect);
diff --git a/tweak/Sources/Shared/JamesDSP/JamesDSPFiles.m b/tweak/Sources/Shared/JamesDSP/JamesDSPFiles.m
new file mode 100644
index 00000000..822bf738
--- /dev/null
+++ b/tweak/Sources/Shared/JamesDSP/JamesDSPFiles.m
@@ -0,0 +1,157 @@
+// JamesDSP's file libraries: Documents/spoti.pw/JamesDSP/<Convolver|DDC|Liveprog>, where the file effects
+// find their files by name. Documents, which the app's backups keep.
+//
+// The first time a library is made it gets the files JamesDSP ships (RootlessJamesDSP's Liveprog scripts
+// and DDC presets, compiled into the tweak by vendor/libjamesdsp/embed-assets.pl); a file deleted after
+// that stays deleted. The convolver's impulse responses are the user's own: RootlessJamesDSP's samples
+// are 7 MB.
+//
+// Threading: any thread (the engine's queue reads the paths too); a library is made once.
+#import <os/lock.h>
+#import "Core/SGCore.h"
+#import "JamesDSP.h"
+#import "JamesDSPEngine.h"
+#import "SGDSPEngine.h"
+
+static NSString *const SGDSPFileErrorDomain = @"spotifyglass.dsp.files";
+
+static NSString *libraryName(SGDSPFileKind kind) {
+ switch (kind) {
+ case SGDSPFileImpulseResponse: return @"Convolver";
+ case SGDSPFileDDC: return @"DDC";
+ case SGDSPFileLiveprog: return @"Liveprog";
+ }
+ return @"Other";
+}
+
+// The key naming the file an effect uses, and its switch, for a library.
+static NSString *fileKey(SGDSPFileKind kind) {
+ switch (kind) {
+ case SGDSPFileImpulseResponse: return SGKeyDSPConvolverFile;
+ case SGDSPFileDDC: return SGKeyDSPDDCFile;
+ case SGDSPFileLiveprog: return SGKeyDSPLiveprogFile;
+ }
+ return nil;
+}
+
+NSArray<NSString *> *SGDSPFileExtensions(SGDSPFileKind kind) {
+ switch (kind) {
+ case SGDSPFileImpulseResponse: return @[@"wav", @"flac", @"irs"];
+ case SGDSPFileDDC: return @[@"vdc"];
+ case SGDSPFileLiveprog: return @[@"eel"];
+ }
+ return @[];
+}
+
+// The bundled files of the library's kind written into it, none replacing a file already there.
+static void installBundled(SGDSPFileKind kind, NSString *directory) {
+ NSString *wanted = libraryName(kind);
+ NSUInteger installed = 0;
+ const char *bundledKind, *name;
+ const void *data;
+ size_t length;
+ for (unsigned i = 0; SGDSPEngineBundledFile(i, &bundledKind, &name, &data, &length); i++) {
+ if (![wanted isEqualToString:@(bundledKind)]) continue;
+ NSString *path = [directory stringByAppendingPathComponent:@(name)];
+ if ([NSFileManager.defaultManager fileExistsAtPath:path]) continue;
+ if ([[NSData dataWithBytes:data length:length] writeToFile:path atomically:YES]) installed++;
+ }
+ if (installed) SGLog(@"jamesdsp: the %@ library holds the %lu files JamesDSP ships", wanted, (unsigned long)installed);
+}
+
+NSString *SGDSPLibraryDirectory(SGDSPFileKind kind) {
+ static os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;
+ NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
+ NSString *directory = [[documents stringByAppendingPathComponent:@"spoti.pw/JamesDSP"] stringByAppendingPathComponent:libraryName(kind)];
+ os_unfair_lock_lock(&lock);
+ BOOL isDirectory = NO;
+ if (![NSFileManager.defaultManager fileExistsAtPath:directory isDirectory:&isDirectory] || !isDirectory) {
+ NSError *error = nil;
+ if ([NSFileManager.defaultManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error]) {
+ installBundled(kind, directory);
+ } else {
+ SGLog(@"jamesdsp: the %@ library could not be made: %@", libraryName(kind), error);
+ }
+ }
+ os_unfair_lock_unlock(&lock);
+ return directory;
+}
+
+NSArray<NSString *> *SGDSPLibraryFiles(SGDSPFileKind kind) {
+ NSString *directory = SGDSPLibraryDirectory(kind);
+ NSArray<NSString *> *extensions = SGDSPFileExtensions(kind);
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil]) {
+ if ([name hasPrefix:@"."] || ![extensions containsObject:name.pathExtension.lowercaseString]) continue;
+ BOOL isDirectory = NO;
+ if ([NSFileManager.defaultManager fileExistsAtPath:[directory stringByAppendingPathComponent:name] isDirectory:&isDirectory] && !isDirectory) {
+ [names addObject:name];
+ }
+ }
+ return [names sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
+}
+
+static NSError *fileError(NSString *message) {
+ return [NSError errorWithDomain:SGDSPFileErrorDomain code:1 userInfo:@{NSLocalizedDescriptionKey: message}];
+}
+
+// Whether the bytes look like a file of the kind, before it goes into the library: a WAV (RIFF, RF64) or
+// FLAC stream, a DDC file's two rates, a Liveprog script's @sample section.
+static BOOL looksLike(SGDSPFileKind kind, NSData *data) {
+ if (kind == SGDSPFileImpulseResponse) {
+ if (data.length < 12) return NO;
+ const char *bytes = data.bytes;
+ return !memcmp(bytes, "RIFF", 4) || !memcmp(bytes, "RF64", 4) || !memcmp(bytes, "fLaC", 4);
+ }
+ NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]
+ ?: [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
+ if (kind == SGDSPFileDDC) return [text containsString:@"SR_44100"] && [text containsString:@"SR_48000"];
+ return [text containsString:@"@sample"];
+}
+
+NSString *SGDSPImportFile(SGDSPFileKind kind, NSURL *url, NSError **error) {
+ NSString *name = url.lastPathComponent;
+ NSArray<NSString *> *extensions = SGDSPFileExtensions(kind);
+ NSString *kindName = kind == SGDSPFileImpulseResponse ? @"an impulse response" : kind == SGDSPFileDDC ? @"a DDC file" : @"a Liveprog script";
+ if (!name.length || [name hasPrefix:@"."] || ![extensions containsObject:name.pathExtension.lowercaseString]) {
+ if (error) *error = fileError([NSString stringWithFormat:@"%@ is not %@ (.%@)", name ?: @"The file", kindName,
+ [extensions componentsJoinedByString:@", ."]]);
+ return nil;
+ }
+ BOOL scoped = [url startAccessingSecurityScopedResource];
+ NSError *readError = nil;
+ NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&readError];
+ if (scoped) [url stopAccessingSecurityScopedResource];
+ if (!data) {
+ if (error) *error = readError ?: fileError([NSString stringWithFormat:@"%@ could not be read", name]);
+ return nil;
+ }
+ if (!looksLike(kind, data)) {
+ if (error) *error = fileError([NSString stringWithFormat:@"%@ is not %@", name, kindName]);
+ return nil;
+ }
+ NSString *path = [SGDSPLibraryDirectory(kind) stringByAppendingPathComponent:name];
+ NSError *writeError = nil;
+ if (![data writeToFile:path options:NSDataWritingAtomic error:&writeError]) {
+ if (error) *error = writeError;
+ return nil;
+ }
+ SGLog(@"jamesdsp: %@ added to the %@ library (%lu bytes)", name, libraryName(kind), (unsigned long)data.length);
+ // A file replaced while an effect uses it is read again.
+ if ([SGDSPString(fileKey(kind)) isEqualToString:name]) SGDSPApply(SGDSPEffectOf(fileKey(kind)));
+ return name;
+}
+
+BOOL SGDSPDeleteFile(SGDSPFileKind kind, NSString *name) {
+ if (!name.length || ![name.lastPathComponent isEqualToString:name] || [name hasPrefix:@"."]) return NO;
+ NSString *path = [SGDSPLibraryDirectory(kind) stringByAppendingPathComponent:name];
+ NSError *error = nil;
+ if (![NSFileManager.defaultManager removeItemAtPath:path error:&error]) {
+ SGLog(@"jamesdsp: %@ could not be deleted: %@", name, error);
+ return NO;
+ }
+ SGLog(@"jamesdsp: %@ deleted from the %@ library", name, libraryName(kind));
+ // The effect using it lets it go (and says the file is gone).
+ if ([SGDSPString(fileKey(kind)) isEqualToString:name]) SGDSPApply(SGDSPEffectOf(fileKey(kind)));
+ return YES;
+}
diff --git a/tweak/Sources/Shared/JamesDSP/JamesDSPSettings.m b/tweak/Sources/Shared/JamesDSP/JamesDSPSettings.m
new file mode 100644
index 00000000..a29b9337
--- /dev/null
+++ b/tweak/Sources/Shared/JamesDSP/JamesDSPSettings.m
@@ -0,0 +1,209 @@
+// JamesDSP's settings: what each key holds until set, its bounds, and the lists the page's choices pick
+// from. The values, ranges and lists are RootlessJamesDSP's (its preferences and arrays.xml), so a setup
+// described for it reads the same here.
+#import "Core/SGCore.h"
+#import "JamesDSP.h"
+#import "JamesDSPEngine.h"
+
+const double SGDSPEqualizerFrequencies[15] = {25, 40, 63, 100, 160, 250, 400, 630, 1000, 1600, 2500, 4000, 6300, 10000, 16000};
+const double SGDSPEqualizerGainLimit = 12;
+const double SGDSPCompanderFrequencies[7] = {95, 200, 400, 800, 1600, 3400, 7500};
+const double SGDSPCompanderGainLimit = 1.2;
+
+#pragma mark - the keys
+
+typedef struct {
+ NSString *__unsafe_unretained key;
+ SGDSPRange range;
+} SGDSPNumberKey;
+
+static const SGDSPNumberKey kNumbers[] = {
+ {SGKeyDSPPostGain, {-15, 15, 0, 0.5}},
+ {SGKeyDSPLimiterThreshold, {-60, -0.1, -0.1, 0.1}},
+ {SGKeyDSPLimiterRelease, {1.5, 500, 60, 0.5}},
+ {SGKeyDSPCompanderTime, {0.06, 0.3, 0.22, 0.01}},
+ {SGKeyDSPCompanderGranularity, {0, 4, 2, 1}},
+ {SGKeyDSPCompanderTransform, {0, 3, 0, 1}},
+ {SGKeyDSPBassGain, {3, 15, 5, 0.5}},
+ {SGKeyDSPEqualizerFilter, {0, 5, 0, 1}},
+ {SGKeyDSPEqualizerInterpolation, {0, 1, 0, 1}},
+ {SGKeyDSPConvolverMode, {0, 2, 0, 1}},
+ {SGKeyDSPReverbPreset, {0, 12, 9, 1}}, // Plate high, RootlessJamesDSP's
+ {SGKeyDSPStereoWideLevel, {30, 75, 60, 1}},
+ {SGKeyDSPCrossfeedMode, {0, 5, 5, 1}}, // Realistic surround, RootlessJamesDSP's
+ {SGKeyDSPTubeDrive, {-3, 12, 2, 0.5}},
+};
+
+static NSDictionary<NSString *, NSString *> *stringDefaults(void) {
+ static NSDictionary<NSString *, NSString *> *defaults;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ defaults = @{
+ SGKeyDSPCompanderGains: @"0;0;0;0;0;0;0",
+ SGKeyDSPEqualizerGains: @"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0",
+ SGKeyDSPGraphicEqNodes: @"GraphicEQ: 0.0 0.0;",
+ SGKeyDSPConvolverFile: @"",
+ SGKeyDSPConvolverWaveEdit: @"-80;-100;0;0;0;0",
+ SGKeyDSPDDCFile: @"",
+ SGKeyDSPLiveprogFile: @"",
+ };
+ });
+ return defaults;
+}
+
+// The switches of the effects, each the prefix of its own keys' names.
+static NSArray<NSString *> *effectSwitches(void) {
+ return @[SGKeyDSPCompander, SGKeyDSPBass, SGKeyDSPEqualizer, SGKeyDSPGraphicEq, SGKeyDSPConvolver, SGKeyDSPDDC,
+ SGKeyDSPLiveprog, SGKeyDSPReverb, SGKeyDSPStereoWide, SGKeyDSPCrossfeed, SGKeyDSPTube];
+}
+
+NSString *SGDSPEffectOf(NSString *key) {
+ for (NSString *effect in effectSwitches()) {
+ if ([key isEqualToString:effect] || [key hasPrefix:[effect stringByAppendingString:@"."]]) return effect;
+ }
+ return SGKeyDSP;
+}
+
+SGDSPRange SGDSPRangeFor(NSString *key) {
+ for (size_t i = 0; i < sizeof kNumbers / sizeof *kNumbers; i++) {
+ if ([kNumbers[i].key isEqualToString:key]) return kNumbers[i].range;
+ }
+ return (SGDSPRange){0, 1, 0, 0};
+}
+
+#pragma mark - reading and writing
+
+static NSUserDefaults *store(void) {
+ return NSUserDefaults.standardUserDefaults;
+}
+
+BOOL SGDSPSwitch(NSString *key) {
+ return SGHidden(key);
+}
+
+void SGDSPSetSwitch(NSString *key, BOOL on) {
+ SGSetEnabled(key, on);
+ SGDSPApply(SGDSPEffectOf(key));
+}
+
+double SGDSPNumber(NSString *key) {
+ SGDSPRange range = SGDSPRangeFor(key);
+ id value = [store() objectForKey:key];
+ if (![value isKindOfClass:NSNumber.class]) return range.fallback;
+ return MAX(range.min, MIN(range.max, [value doubleValue]));
+}
+
+void SGDSPSetNumber(NSString *key, double value) {
+ SGDSPRange range = SGDSPRangeFor(key);
+ [store() setDouble:MAX(range.min, MIN(range.max, value)) forKey:key];
+ SGDSPApply(SGDSPEffectOf(key));
+}
+
+NSString *SGDSPString(NSString *key) {
+ id value = [store() objectForKey:key];
+ return [value isKindOfClass:NSString.class] ? value : (stringDefaults()[key] ?: @"");
+}
+
+void SGDSPSetString(NSString *key, NSString *value) {
+ [store() setObject:value ?: @"" forKey:key];
+ SGDSPApply(SGDSPEffectOf(key));
+}
+
+static NSUInteger gainCount(NSString *key) {
+ return [key isEqualToString:SGKeyDSPCompanderGains] ? 7 : 15;
+}
+
+static double gainLimit(NSString *key) {
+ return [key isEqualToString:SGKeyDSPCompanderGains] ? SGDSPCompanderGainLimit : SGDSPEqualizerGainLimit;
+}
+
+NSArray<NSNumber *> *SGDSPGains(NSString *key) {
+ NSArray<NSString *> *parts = [SGDSPString(key) componentsSeparatedByString:@";"];
+ NSUInteger count = gainCount(key);
+ double limit = gainLimit(key);
+ NSMutableArray<NSNumber *> *gains = [NSMutableArray arrayWithCapacity:count];
+ for (NSUInteger i = 0; i < count; i++) {
+ double gain = i < parts.count ? parts[i].doubleValue : 0;
+ [gains addObject:@(MAX(-limit, MIN(limit, gain)))];
+ }
+ return gains;
+}
+
+void SGDSPSetGains(NSString *key, NSArray<NSNumber *> *gains) {
+ NSUInteger count = gainCount(key);
+ double limit = gainLimit(key);
+ NSMutableArray<NSString *> *parts = [NSMutableArray arrayWithCapacity:count];
+ for (NSUInteger i = 0; i < count; i++) {
+ double gain = i < gains.count ? gains[i].doubleValue : 0;
+ [parts addObject:[NSString stringWithFormat:@"%.2f", MAX(-limit, MIN(limit, gain))]];
+ }
+ SGDSPSetString(key, [parts componentsJoinedByString:@";"]);
+}
+
+void SGDSPResetAll(void) {
+ for (size_t i = 0; i < sizeof kNumbers / sizeof *kNumbers; i++) [store() removeObjectForKey:kNumbers[i].key];
+ for (NSString *key in stringDefaults()) [store() removeObjectForKey:key];
+ for (NSString *effect in effectSwitches()) [store() removeObjectForKey:effect];
+ SGDSPApply(SGKeyDSP);
+ for (NSString *effect in effectSwitches()) SGDSPApply(effect);
+}
+
+#pragma mark - lists
+
+NSArray<NSString *> *SGDSPEqualizerFilterNames(void) {
+ return @[@"FIR minimum phase", @"IIR 4th order", @"IIR 6th order", @"IIR 8th order", @"IIR 10th order", @"IIR 12th order"];
+}
+
+NSArray<NSString *> *SGDSPEqualizerInterpolationNames(void) {
+ return @[@"Cubic Hermite", @"Modified Akima"];
+}
+
+NSArray<NSString *> *SGDSPCompanderTransformNames(void) {
+ return @[@"Uniform (short-time Fourier)", @"Multiresolution (continuous wavelet)",
+ @"Pseudo multiresolution (undersampling)", @"Pseudo multiresolution (time domain)"];
+}
+
+NSArray<NSString *> *SGDSPConvolverModeNames(void) {
+ return @[@"Original", @"Shrink", @"Minimum phase and shrink"];
+}
+
+NSArray<NSString *> *SGDSPCrossfeedModeNames(void) {
+ return @[@"BS2B weak", @"BS2B strong", @"Out of head", @"Surround 1", @"Surround 2", @"Realistic surround"];
+}
+
+NSArray<NSString *> *SGDSPReverbPresetNames(void) {
+ return @[@"Default", @"Small hall 1", @"Small hall 2", @"Medium hall", @"Large hall", @"Small room 1", @"Small room 2",
+ @"Medium room", @"Large room", @"Plate high", @"Plate low", @"Long reverb 1", @"Long reverb 2"];
+}
+
+NSArray<NSString *> *SGDSPEqualizerPresetNames(void) {
+ return @[@"Acoustic", @"Bass", @"Beats", @"Classic", @"Clear", @"Deep", @"Dubstep", @"Electronic", @"Flat",
+ @"Hardstyle", @"Hip-Hop", @"Jazz", @"Metal", @"Movie", @"Pop", @"R&B", @"Rock", @"Vocal Booster"];
+}
+
+NSArray<NSNumber *> *SGDSPEqualizerPreset(NSInteger index) {
+ static const double presets[][15] = {
+ {5.00, 4.50, 4.00, 3.50, 1.50, 1.00, 1.50, 1.50, 2.00, 3.00, 3.50, 4.00, 3.70, 3.00, 3.00},
+ {10.00, 8.80, 8.50, 6.50, 2.50, 1.50, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+ {-5.5, -5.0, -4.5, -4.2, -3.5, -3.0, -1.9, 0, 0, 0, 0, 0, 0, 0, 0},
+ {-0.3, 0.3, -3.5, -9.0, -1.0, 0.0, 1.8, 2.1, 0.0, 0.0, 0.0, 4.4, 9.0, 9.0, 9.0},
+ {3.5, 5.5, 6.5, 9.5, 8.0, 6.5, 3.5, 2.5, 1.3, 5.0, 7.0, 9.0, 10.0, 11.0, 9.0},
+ {12.0, 8.0, 0.0, -6.7, -12.0, -9.0, -3.5, -3.5, -6.1, 0.0, -3.0, -5.0, 0.0, 1.2, 3.0},
+ {12.0, 10.0, 0.5, -1.0, -3.0, -5.0, -5.0, -4.8, -4.5, -2.5, -1.0, 0.0, -2.5, -2.5, 0.0},
+ {4.0, 4.0, 3.5, 1.0, 0.0, -0.5, -2.0, 0.0, 2.0, 0.0, 0.0, 1.0, 3.0, 4.0, 4.5},
+ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+ {6.1, 7.0, 12.0, 6.1, -5.0, -12.0, -2.5, 3.0, 6.5, 0.0, -2.2, -4.5, -6.1, -9.2, -10.0},
+ {4.5, 4.3, 4.0, 2.5, 1.5, 3.0, -1.0, -1.5, -1.5, 1.5, 0.0, -1.0, 0.0, 1.5, 3.0},
+ {0.0, 0.0, 0.0, 2.0, 4.0, 5.9, -5.9, -4.5, -2.5, 2.5, 1.0, -0.8, -0.8, -0.8, -0.8},
+ {10.5, 10.5, 7.5, 0.0, 2.0, 5.5, 0.0, 0.0, 0.0, 6.1, 0.0, 0.0, 6.1, 10.0, 12.0},
+ {3.0, 3.0, 6.1, 8.5, 9.0, 7.0, 6.1, 6.1, 5.0, 8.0, 3.5, 3.5, 8.0, 10.0, 8.0},
+ {0.0, 0.0, 0.0, 0.0, 0.0, 1.3, 2.0, 2.5, 5.0, -1.5, -2.0, -3.0, -3.0, -3.0, -3.0},
+ {3.0, 3.0, 7.0, 6.1, 4.5, 1.5, -1.5, -2.0, -1.5, 2.0, 2.5, 3.0, 3.5, 3.8, 4.0},
+ {0.0, 0.0, 0.0, 3.0, 3.0, -10.0, -4.0, -1.0, 0.8, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0},
+ {-1.5, -2.0, -3.0, -3.0, -0.5, 1.5, 3.5, 3.5, 3.5, 3.0, 2.0, 1.5, 0.0, 0.0, -1.5},
+ };
+ if (index < 0 || index >= (NSInteger)(sizeof presets / sizeof *presets)) return nil;
+ NSMutableArray<NSNumber *> *gains = [NSMutableArray arrayWithCapacity:15];
+ for (int i = 0; i < 15; i++) [gains addObject:@(presets[index][i])];
+ return gains;
+}
diff --git a/tweak/Sources/Shared/JamesDSP/SGDSPEngine.h b/tweak/Sources/Shared/JamesDSP/SGDSPEngine.h
new file mode 100644
index 00000000..d20ecb41
--- /dev/null
+++ b/tweak/Sources/Shared/JamesDSP/SGDSPEngine.h
@@ -0,0 +1,106 @@
+// JamesDSP's engine, libjamesdsp (vendor/libjamesdsp), made fit for Core Audio's render thread: one per
+// process, fed the finished output a slice at a time, whatever size the slice.
+//
+// libjamesdsp wants a fixed block: every change of the frame count reallocates its buffers and rebuilds
+// its convolutions (pfloat32 -> JamesDSPRefreshConvolutions), and iOS hands the output unit 1024 frames,
+// 4096 with the screen locked, sometimes an odd count. So the engine re-blocks: frames go into a block of
+// kSGDSPEngineBlock, a full block is processed, and the processed frames come out of a FIFO primed with one
+// block of silence. The sound is always exactly one block later than it went in (21 ms at 48 kHz),
+// whatever the slices.
+//
+// libjamesdsp's setters are mostly not safe against processing, so every setter here takes the engine's
+// lock, and the render thread only tries it: a block that finds it taken passes through unprocessed, one
+// block late all the same, so nothing jumps while a setting changes.
+//
+// Threading: SGDSPEngineProcess runs on the render thread and never allocates, blocks, logs or messages
+// (libjamesdsp takes a mutex of its own around three effects there, which only this lock's holder can
+// hold, so it never waits). SGDSPEngineRestart and the diagnostics are for any thread. Everything else is
+// the config side: one thread at a time, never the render thread. Plain C; compiles on the Mac as is
+// (harness/jamesdsp).
+#import <stdbool.h>
+#import <stddef.h>
+#import <stdint.h>
+
+enum { kSGDSPEngineBlock = 1024 };
+
+typedef struct SGDSPEngine SGDSPEngine;
+
+// Stereo at `sampleRate`, every effect off, output gain 0 dB. NULL when libjamesdsp could not start.
+SGDSPEngine *SGDSPEngineCreate(double sampleRate);
+// Only once nothing renders through it.
+void SGDSPEngineFree(SGDSPEngine *engine);
+
+// Any thread.
+double SGDSPEngineSampleRate(const SGDSPEngine *engine);
+// A new rate, every effect rebuilt for it by libjamesdsp; the file effects (convolver, DDC, Liveprog) and
+// the ones it does not refresh itself (reverb, tube, the IIR equalizer) are set again by the caller.
+void SGDSPEngineSetSampleRate(SGDSPEngine *engine, double sampleRate);
+// libjamesdsp started over, every effect off, for when its output stopped being finite.
+void SGDSPEngineReset(SGDSPEngine *engine);
+
+#pragma mark - effects, the config side
+
+void SGDSPEngineSetOutput(SGDSPEngine *engine, double postGainDB, double limiterThresholdDB, double limiterReleaseMS);
+void SGDSPEngineSetCompander(SGDSPEngine *engine, bool on, double timeConstant, int granularity, int transform,
+ const double frequencies[7], const double gains[7]);
+void SGDSPEngineSetBassBoost(SGDSPEngine *engine, bool on, double maxGainDB);
+// filter: 0 FIR minimum phase, 1...5 IIR of order 4, 6, 8, 10, 12. interpolation: 0 cubic Hermite, 1 Akima.
+void SGDSPEngineSetEqualizer(SGDSPEngine *engine, bool on, int filter, int interpolation, const double frequencies[15],
+ const double gains[15]);
+// preset: libjamesdsp's own number (sf_reverb_preset), not a list index.
+void SGDSPEngineSetReverb(SGDSPEngine *engine, bool on, int preset);
+void SGDSPEngineSetStereoWide(SGDSPEngine *engine, bool on, double levelPercent);
+// mode: 0 BS2B weak, 1 BS2B strong, 2 out of head, 3 surround 1, 4 surround 2, 5 realistic surround.
+void SGDSPEngineSetCrossfeed(SGDSPEngine *engine, bool on, int mode);
+void SGDSPEngineSetTube(SGDSPEngine *engine, bool on, double driveDB);
+
+// These answer false and say why in `error` when the effect could not take; it is then off.
+// AutoEq's GraphicEQ format, "GraphicEQ: 20 -1.2; 21 -1.1; ...".
+bool SGDSPEngineSetGraphicEq(SGDSPEngine *engine, bool on, const char *nodes, char *error, size_t errorSize);
+// An impulse response file (.wav, .irs, .flac) read at the engine's rate. mode: 0 original, 1 shrink, 2
+// minimum phase and shrink. waveEdit: JamesDSP's advanced waveform editing, "-80;-100;0;0;0;0".
+bool SGDSPEngineSetConvolver(SGDSPEngine *engine, bool on, const char *path, int mode, const char *waveEdit,
+ char *error, size_t errorSize);
+// A ViPER DDC file's text.
+bool SGDSPEngineSetDDC(SGDSPEngine *engine, bool on, const char *text, char *error, size_t errorSize);
+// A Liveprog script's text; a compile error names the file's line.
+bool SGDSPEngineSetLiveprog(SGDSPEngine *engine, bool on, const char *script, char *error, size_t errorSize);
+
+#pragma mark - the render thread
+
+// Replaces `frames` samples of each lane with the processed sound one block before them.
+void SGDSPEngineProcess(SGDSPEngine *engine, float *left, float *right, uint32_t frames);
+// The next SGDSPEngineProcess starts over from a block of silence, for a stream that stopped and starts
+// again (the sound held from before it would otherwise play first). Any thread.
+void SGDSPEngineRestart(SGDSPEngine *engine);
+
+#pragma mark - diagnostics, any thread
+
+typedef struct {
+ uint64_t blocks; // processed
+ uint64_t dry; // passed through because a setting was being changed
+ uint64_t faults; // came out not finite and were silenced
+ double averageMS; // processing time of a block, a running average
+ double peakMS; // the longest since the peak was last taken
+ double load; // averageMS over the block's duration
+} SGDSPEngineStats;
+
+// takePeak starts the peak over; one reader takes it, the others leave it.
+SGDSPEngineStats SGDSPEngineReadStats(SGDSPEngine *engine, bool takePeak);
+
+// What libjamesdsp printed (printf, its Android log, Liveprog's printf), a line at a time, oldest first, at
+// most `max` of them; answers how many were dropped because the lines came faster than they were read. The
+// lines are kept by the engine's handlers, which any thread (the render thread too) may call.
+unsigned SGDSPEngineReadLog(void (*line)(const char *text, void *context), void *context, unsigned max);
+
+#pragma mark - curves and files, any thread but not at once
+
+// `count` points log-spaced from 20 Hz to 20 kHz into `frequencies`, and the curve at them.
+void SGDSPEngineEqualizerCurve(int filter, int interpolation, const double bandFrequencies[15], const double gains[15],
+ int count, double *frequencies, double *decibels);
+void SGDSPEngineCompanderCurve(const double bandFrequencies[7], const double gains[7], int count, double *frequencies,
+ double *values);
+
+// The files RootlessJamesDSP ships with the engine (vendor/libjamesdsp/assets), compiled in: kind is
+// "Liveprog" or "DDC". false past the last.
+bool SGDSPEngineBundledFile(unsigned index, const char **kind, const char **name, const void **data, size_t *length);
diff --git a/tweak/Sources/Shared/JamesDSP/SGDSPEngine.m b/tweak/Sources/Shared/JamesDSP/SGDSPEngine.m
new file mode 100644
index 00000000..0483bdda
--- /dev/null
+++ b/tweak/Sources/Shared/JamesDSP/SGDSPEngine.m
@@ -0,0 +1,609 @@
+// SGDSPEngine.h says what this is. The effect setters follow RootlessJamesDSP's JamesDspWrapper.cpp call for
+// call, with its fixes where it had a bug (noted where they are).
+#import "SGDSPEngine.h"
+#import <mach/mach_time.h>
+#import <math.h>
+#import <pthread.h>
+#import <stdatomic.h>
+#import <stdio.h>
+#import <stdlib.h>
+#import <string.h>
+// vendor/libjamesdsp, on the include path of this file alone (tweak/Makefile).
+#include "jdsp_header.h"
+#include "JdspImpResToolbox.h"
+#include "EELStdOutExtension.h"
+#include "PrintfStdOutExtension.h"
+#include "JdspBundledFiles.h"
+
+// The FIFO the processed blocks wait in: a power of two holding the primed block, the one being handed out
+// and the one just made, with room to spare.
+enum { kRing = 4 * kSGDSPEngineBlock };
+
+struct SGDSPEngine {
+ JamesDSPLib *dsp;
+ pthread_mutex_t lock; // held by every setter, tried by the render thread
+ atomic_uint_fast64_t rateBits;
+ atomic_bool restart;
+
+ // The render thread's alone.
+ uint32_t fill; // frames in the block being gathered
+ uint64_t written, read; // frames into and out of the ring, the written ones a block ahead
+ float blockLeft[kSGDSPEngineBlock], blockRight[kSGDSPEngineBlock];
+ float ringLeft[kRing], ringRight[kRing];
+
+ atomic_uint_fast64_t blocks, dry, faults;
+ atomic_uint_fast64_t averageBits, peakNanos;
+};
+
+static double sg_nanosPerTick;
+
+static void storeDouble(atomic_uint_fast64_t *slot, double value) {
+ uint64_t bits;
+ memcpy(&bits, &value, sizeof bits);
+ atomic_store_explicit(slot, bits, memory_order_relaxed);
+}
+
+static double loadDouble(const atomic_uint_fast64_t *slot) {
+ uint64_t bits = atomic_load_explicit((atomic_uint_fast64_t *)slot, memory_order_relaxed);
+ double value;
+ memcpy(&value, &bits, sizeof value);
+ return value;
+}
+
+static void copyError(char *error, size_t errorSize, const char *text) {
+ if (error && errorSize) snprintf(error, errorSize, "%s", text);
+}
+
+#pragma mark - what libjamesdsp prints
+
+// A ring of lines any thread may add to, the render thread included (Liveprog's printf runs inside the
+// processing), and one reader takes from: claimed by a compare and swap, published by a flag.
+enum { kLogSlots = 64, kLogBytes = 200 };
+
+typedef struct {
+ atomic_uint ready;
+ char text[kLogBytes];
+} LogSlot;
+
+static LogSlot sg_log[kLogSlots];
+static atomic_uint sg_logHead, sg_logTail, sg_logDropped;
+
+static void keepLine(const char *text, void *context) {
+ if (!text || !*text) return;
+ unsigned head = atomic_load_explicit(&sg_logHead, memory_order_relaxed);
+ do {
+ if (head - atomic_load_explicit(&sg_logTail, memory_order_acquire) >= kLogSlots) {
+ atomic_fetch_add_explicit(&sg_logDropped, 1, memory_order_relaxed);
+ return;
+ }
+ } while (!atomic_compare_exchange_weak_explicit(&sg_logHead, &head, head + 1, memory_order_acq_rel, memory_order_relaxed));
+ LogSlot *slot = &sg_log[head % kLogSlots];
+ size_t length = strnlen(text, kLogBytes - 1);
+ memcpy(slot->text, text, length);
+ slot->text[length] = 0;
+ atomic_store_explicit(&slot->ready, 1, memory_order_release);
+}
+
+unsigned SGDSPEngineReadLog(void (*line)(const char *text, void *context), void *context, unsigned max) {
+ for (unsigned done = 0; done < max; done++) {
+ unsigned tail = atomic_load_explicit(&sg_logTail, memory_order_relaxed);
+ LogSlot *slot = &sg_log[tail % kLogSlots];
+ if (!atomic_load_explicit(&slot->ready, memory_order_acquire)) break;
+ char text[kLogBytes];
+ memcpy(text, slot->text, sizeof text);
+ atomic_store_explicit(&slot->ready, 0, memory_order_relaxed);
+ atomic_store_explicit(&sg_logTail, tail + 1, memory_order_release);
+ line(text, context);
+ }
+ return atomic_exchange_explicit(&sg_logDropped, 0, memory_order_relaxed);
+}
+
+#pragma mark - making one
+
+// EEL's global tables and the handlers are the process's, set up once.
+static void startLibrary(void) {
+ mach_timebase_info_data_t timebase;
+ mach_timebase_info(&timebase);
+ sg_nanosPerTick = (double)timebase.numer / timebase.denom;
+ JamesDSPGlobalMemoryAllocation();
+ setStdOutHandler(keepLine, NULL);
+ setPrintfStdOutHandler(keepLine, NULL);
+}
+
+static bool validRate(double rate) {
+ return rate >= 8000 && rate <= 384000;
+}
+
+// The FIFO back to one block of silence ahead of the first frame in.
+static void startOver(SGDSPEngine *engine) {
+ engine->fill = 0;
+ engine->read = 0;
+ engine->written = kSGDSPEngineBlock;
+ memset(engine->ringLeft, 0, kSGDSPEngineBlock * sizeof(float));
+ memset(engine->ringRight, 0, kSGDSPEngineBlock * sizeof(float));
+}
+
+SGDSPEngine *SGDSPEngineCreate(double sampleRate) {
+ static pthread_once_t once = PTHREAD_ONCE_INIT;
+ if (!validRate(sampleRate)) return NULL;
+ pthread_once(&once, startLibrary);
+ SGDSPEngine *engine = calloc(1, sizeof *engine);
+ JamesDSPLib *dsp = calloc(1, sizeof *dsp);
+ if (!engine || !dsp || pthread_mutex_init(&engine->lock, NULL) != 0) {
+ free(engine);
+ free(dsp);
+ return NULL;
+ }
+ JamesDSPInit(dsp, kSGDSPEngineBlock, (float)sampleRate);
+ if (!JamesDSPGetMutexStatus(dsp)) {
+ JamesDSPFree(dsp);
+ free(dsp);
+ pthread_mutex_destroy(&engine->lock);
+ free(engine);
+ return NULL;
+ }
+ engine->dsp = dsp;
+ storeDouble(&engine->rateBits, sampleRate);
+ startOver(engine);
+ return engine;
+}
+
+void SGDSPEngineFree(SGDSPEngine *engine) {
+ if (!engine) return;
+ pthread_mutex_lock(&engine->lock);
+ JamesDSPFree(engine->dsp);
+ free(engine->dsp);
+ pthread_mutex_unlock(&engine->lock);
+ pthread_mutex_destroy(&engine->lock);
+ free(engine);
+}
+
+double SGDSPEngineSampleRate(const SGDSPEngine *engine) {
+ return loadDouble(&engine->rateBits);
+}
+
+void SGDSPEngineSetSampleRate(SGDSPEngine *engine, double sampleRate) {
+ if (!validRate(sampleRate) || sampleRate == SGDSPEngineSampleRate(engine)) return;
+ pthread_mutex_lock(&engine->lock);
+ JamesDSPSetSampleRate(engine->dsp, (float)sampleRate, 1);
+ storeDouble(&engine->rateBits, sampleRate);
+ pthread_mutex_unlock(&engine->lock);
+}
+
+void SGDSPEngineReset(SGDSPEngine *engine) {
+ pthread_mutex_lock(&engine->lock);
+ JamesDSPFree(engine->dsp);
+ JamesDSPInit(engine->dsp, kSGDSPEngineBlock, (float)SGDSPEngineSampleRate(engine));
+ pthread_mutex_unlock(&engine->lock);
+}
+
+#pragma mark - the render thread
+
+static bool allFinite(const float *left, const float *right) {
+ // Anything times zero is zero, but for NaN and infinity: the sum is NaN when one of them is.
+ float sum = 0;
+ for (uint32_t i = 0; i < kSGDSPEngineBlock; i++) sum += left[i] * 0.0f + right[i] * 0.0f;
+ return sum == sum;
+}
+
+// The gathered block, processed (or as it is, when a setter holds the lock) into the ring. The ring is a
+// whole number of blocks and blocks are written whole, so a block never wraps.
+static void runBlock(SGDSPEngine *engine) {
+ uint64_t at = engine->written & (kRing - 1);
+ float *left = engine->ringLeft + at, *right = engine->ringRight + at;
+ if (pthread_mutex_trylock(&engine->lock) != 0) {
+ memcpy(left, engine->blockLeft, sizeof engine->blockLeft);
+ memcpy(right, engine->blockRight, sizeof engine->blockRight);
+ atomic_fetch_add_explicit(&engine->dry, 1, memory_order_relaxed);
+ } else {
+ uint64_t start = mach_absolute_time();
+ JamesDSPLib *dsp = engine->dsp;
+ dsp->processFloatDeinterleaved(dsp, engine->blockLeft, engine->blockRight, left, right, kSGDSPEngineBlock);
+ pthread_mutex_unlock(&engine->lock);
+ uint64_t nanos = (uint64_t)((mach_absolute_time() - start) * sg_nanosPerTick);
+ double average = loadDouble(&engine->averageBits);
+ storeDouble(&engine->averageBits, average ? average + (nanos - average) * 0.05 : nanos);
+ if (nanos > atomic_load_explicit(&engine->peakNanos, memory_order_relaxed)) {
+ atomic_store_explicit(&engine->peakNanos, nanos, memory_order_relaxed);
+ }
+ atomic_fetch_add_explicit(&engine->blocks, 1, memory_order_relaxed);
+ // An effect gone unstable would put NaN into its own state and every block after; silence rather
+ // than noise, and the config side resets the engine when it sees the count move.
+ if (!allFinite(left, right)) {
+ memset(left, 0, sizeof engine->blockLeft);
+ memset(right, 0, sizeof engine->blockRight);
+ atomic_fetch_add_explicit(&engine->faults, 1, memory_order_relaxed);
+ }
+ }
+ engine->written += kSGDSPEngineBlock;
+}
+
+void SGDSPEngineProcess(SGDSPEngine *engine, float *left, float *right, uint32_t frames) {
+ if (atomic_exchange_explicit(&engine->restart, false, memory_order_acquire)) startOver(engine);
+ uint32_t in = 0, out = 0;
+ while (in < frames) {
+ uint32_t take = kSGDSPEngineBlock - engine->fill;
+ if (take > frames - in) take = frames - in;
+ memcpy(engine->blockLeft + engine->fill, left + in, take * sizeof(float));
+ memcpy(engine->blockRight + engine->fill, right + in, take * sizeof(float));
+ engine->fill += take;
+ in += take;
+ if (engine->fill == kSGDSPEngineBlock) {
+ runBlock(engine);
+ engine->fill = 0;
+ }
+ // As many frames out as came in: the ring is always a block ahead, so it has them, and the frames
+ // overwritten were copied into the block already.
+ while (out < in) {
+ uint32_t at = (uint32_t)(engine->read & (kRing - 1));
+ uint32_t count = in - out;
+ if (count > kRing - at) count = kRing - at;
+ memcpy(left + out, engine->ringLeft + at, count * sizeof(float));
+ memcpy(right + out, engine->ringRight + at, count * sizeof(float));
+ engine->read += count;
+ out += count;
+ }
+ }
+}
+
+void SGDSPEngineRestart(SGDSPEngine *engine) {
+ atomic_store_explicit(&engine->restart, true, memory_order_release);
+}
+
+SGDSPEngineStats SGDSPEngineReadStats(SGDSPEngine *engine, bool takePeak) {
+ SGDSPEngineStats stats = {
+ .blocks = atomic_load_explicit(&engine->blocks, memory_order_relaxed),
+ .dry = atomic_load_explicit(&engine->dry, memory_order_relaxed),
+ .faults = atomic_load_explicit(&engine->faults, memory_order_relaxed),
+ .averageMS = loadDouble(&engine->averageBits) / 1e6,
+ .peakMS = (takePeak ? atomic_exchange_explicit(&engine->peakNanos, 0, memory_order_relaxed)
+ : atomic_load_explicit(&engine->peakNanos, memory_order_relaxed)) / 1e6,
+ };
+ double blockMS = kSGDSPEngineBlock / SGDSPEngineSampleRate(engine) * 1000;
+ stats.load = stats.averageMS / blockMS;
+ return stats;
+}
+
+#pragma mark - effects
+
+void SGDSPEngineSetOutput(SGDSPEngine *engine, double postGainDB, double limiterThresholdDB, double limiterReleaseMS) {
+ pthread_mutex_lock(&engine->lock);
+ JamesDSPSetPostGain(engine->dsp, postGainDB);
+ JLimiterSetCoefficients(engine->dsp, limiterThresholdDB, limiterReleaseMS);
+ pthread_mutex_unlock(&engine->lock);
+}
+
+void SGDSPEngineSetCompander(SGDSPEngine *engine, bool on, double timeConstant, int granularity, int transform,
+ const double frequencies[7], const double gains[7]) {
+ pthread_mutex_lock(&engine->lock);
+ if (on) {
+ double freq[7], gain[7];
+ memcpy(freq, frequencies, sizeof freq);
+ memcpy(gain, gains, sizeof gain);
+ CompressorSetParam(engine->dsp, (float)timeConstant, granularity, transform, 0);
+ CompressorSetGain(engine->dsp, freq, gain, 1);
+ CompressorEnable(engine->dsp, 1);
+ } else {
+ CompressorDisable(engine->dsp);
+ }
+ pthread_mutex_unlock(&engine->lock);
+}
+
+void SGDSPEngineSetBassBoost(SGDSPEngine *engine, bool on, double maxGainDB) {
+ pthread_mutex_lock(&engine->lock);
+ if (on) {
+ BassBoostSetParam(engine->dsp, (float)maxGainDB);
+ BassBoostEnable(engine->dsp);
+ } else {
+ BassBoostDisable(engine->dsp);
+ }
+ pthread_mutex_unlock(&engine->lock);
+}
+
+void SGDSPEngineSetEqualizer(SGDSPEngine *engine, bool on, int filter, int interpolation, const double frequencies[15],
+ const double gains[15]) {
+ pthread_mutex_lock(&engine->lock);
+ if (on) {
+ double freq[15], gain[15];
+ memcpy(freq, frequencies, sizeof freq);
+ memcpy(gain, gains, sizeof gain);
+ MultimodalEqualizerAxisInterpolation(engine->dsp, interpolation, filter, freq, gain);
+ MultimodalEqualizerEnable(engine->dsp, 1);
+ } else {
+ MultimodalEqualizerDisable(engine->dsp);
+ }
+ pthread_mutex_unlock(&engine->lock);
+}
+
+void SGDSPEngineSetReverb(SGDSPEngine *engine, bool on, int preset) {
+ pthread_mutex_lock(&engine->lock);
+ if (on) {
+ // The preset first: it sets up the reverb's state for the rate, which enabling does not.
+ Reverb_SetParam(engine->dsp, preset);
+ ReverbEnable(engine->dsp);
+ } else {
+ ReverbDisable(engine->dsp);
+ }
+ pthread_mutex_unlock(&engine->lock);
+}
+
+void SGDSPEngineSetStereoWide(SGDSPEngine *engine, bool on, double levelPercent) {
+ pthread_mutex_lock(&engine->lock);
+ StereoEnhancementDisable(engine->dsp);
+ StereoEnhancementSetParam(engine->dsp, (float)(levelPercent / 100));
+ if (on) StereoEnhancementEnable(engine->dsp);
+ pthread_mutex_unlock(&engine->lock);
+}
+
+void SGDSPEngineSetCrossfeed(SGDSPEngine *engine, bool on, int mode) {
+ pthread_mutex_lock(&engine->lock);
+ // CrossfeedChangeMode alone leaves BS2B weak's filter zeroed (JDSP4Linux's "audio loss"); enabling
+ // after it sets both BS2B filters up, so it is always followed by CrossfeedEnable while on.
+ CrossfeedChangeMode(engine->dsp, mode);
+ if (on) CrossfeedEnable(engine->dsp, 1);
+ else CrossfeedDisable(engine->dsp);
+ pthread_mutex_unlock(&engine->lock);
+}
+
+void SGDSPEngineSetTube(SGDSPEngine *engine, bool on, double driveDB) {
+ pthread_mutex_lock(&engine->lock);
+ if (on) {
+ // Enabling sets the tube up anew with its gain at 0 dB, so the drive goes in after, in dB, which the
+ // library clamps to -3...12 (RootlessJamesDSP sets it first, and divided by 100).
+ VacuumTubeEnable(engine->dsp);
+ VacuumTubeSetGain(engine->dsp, driveDB);
+ } else {
+ VacuumTubeDisable(engine->dsp);
+ }
+ pthread_mutex_unlock(&engine->lock);
+}
+
+#pragma mark - effects that read something
+
+// "GraphicEQ: f g; f g; ..." rewritten from the pairs found in it, so libjamesdsp's parser, which writes
+// past its nodes on an odd count of numbers, only ever sees whole pairs. NULL when there are none.
+static char *graphicEqNodes(const char *text) {
+ const char *p = strchr(text, ':');
+ if (!p) return NULL;
+ p++;
+ size_t capacity = 64, length = 0;
+ char *result = malloc(capacity);
+ if (!result) return NULL;
+ length = (size_t)snprintf(result, capacity, "GraphicEQ:");
+ unsigned pairs = 0;
+ while (*p) {
+ char *end;
+ double frequency = strtod(p, &end);
+ if (end == p) {
+ p++;
+ continue;
+ }
+ p = end;
+ while (*p == ' ' || *p == '\t') p++;
+ double gain = strtod(p, &end);
+ if (end == p) break;
+ p = end;
+ if (!isfinite(frequency) || !isfinite(gain) || frequency < 0) continue;
+ char pair[64];
+ int written = snprintf(pair, sizeof pair, " %.6g %.6g;", frequency, gain);
+ if (length + written + 1 > capacity) {
+ capacity = (length + written + 1) * 2;
+ char *grown = realloc(result, capacity);
+ if (!grown) {
+ free(result);
+ return NULL;
+ }
+ result = grown;
+ }
+ memcpy(result + length, pair, written + 1);
+ length += written;
+ pairs++;
+ }
+ if (!pairs) {
+ free(result);
+ return NULL;
+ }
+ return result;
+}
+
+bool SGDSPEngineSetGraphicEq(SGDSPEngine *engine, bool on, const char *nodes, char *error, size_t errorSize) {
+ char *canonical = on && nodes && strstr(nodes, "GraphicEQ:") ? graphicEqNodes(nodes) : NULL;
+ pthread_mutex_lock(&engine->lock);
+ if (canonical) {
+ ArbitraryResponseEqualizerStringParser(engine->dsp, canonical);
+ ArbitraryResponseEqualizerEnable(engine->dsp, 1);
+ } else {
+ ArbitraryResponseEqualizerDisable(engine->dsp);
+ }
+ pthread_mutex_unlock(&engine->lock);
+ free(canonical);
+ if (on && !canonical) {
+ copyError(error, errorSize, "Not in AutoEq's GraphicEQ format (\"GraphicEQ: 20 -1.2; 21 -1.1; ...\")");
+ return false;
+ }
+ return true;
+}
+
+bool SGDSPEngineSetConvolver(SGDSPEngine *engine, bool on, const char *path, int mode, const char *waveEdit,
+ char *error, size_t errorSize) {
+ if (!on || !path || !*path) {
+ pthread_mutex_lock(&engine->lock);
+ Convolver1DDisable(engine->dsp);
+ pthread_mutex_unlock(&engine->lock);
+ return true;
+ }
+ // JamesDSP's defaults unless the setting is six whole numbers; the reader checks the shifts fit.
+ int wave[6] = {-80, -100, 0, 0, 0, 0}, parsed[6];
+ if (waveEdit && sscanf(waveEdit, "%d;%d;%d;%d;%d;%d", &parsed[0], &parsed[1], &parsed[2], &parsed[3], &parsed[4], &parsed[5]) == 6) {
+ memcpy(wave, parsed, sizeof wave);
+ }
+ if (mode < 0 || mode > 2) mode = 0;
+ // Read and resampled outside the lock: the render thread keeps processing meanwhile. At the rate the
+ // effects run at, which is the output's but for rates libjamesdsp resamples to 44.1 or 48 kHz.
+ int info[2] = {0, 0};
+ float *impulse = ReadImpulseResponseToFloat(path, (int)engine->dsp->fs, info, mode, wave);
+ int result = 0;
+ pthread_mutex_lock(&engine->lock);
+ Convolver1DDisable(engine->dsp);
+ if (impulse && info[1] > 0) {
+ result = Convolver1DLoadImpulseResponse(engine->dsp, impulse, (unsigned)info[0], (size_t)info[1], 1);
+ if (result > 0) Convolver1DEnable(engine->dsp);
+ }
+ pthread_mutex_unlock(&engine->lock);
+ free(impulse);
+ if (!impulse) {
+ copyError(error, errorSize, "The impulse response could not be read: a WAV or FLAC file of 1, 2 or 4 channels");
+ return false;
+ }
+ if (info[1] <= 0 || result <= 0) {
+ copyError(error, errorSize, info[1] <= 0 ? "The impulse response is empty" : "The impulse response could not be loaded");
+ return false;
+ }
+ return true;
+}
+
+// Whether libjamesdsp's DDC parser can read the text without running off its end or past its filters:
+// both rates' sections, as many numbers after each as the 48 kHz section has fields, five to a filter.
+static bool readableDDC(const char *text) {
+ const char *at441 = strstr(text, "SR_44100"), *at48 = strstr(text, "SR_48000");
+ if (!at441 || !at48 || strlen(text) > (1 << 20)) return false;
+ unsigned fields = 1;
+ for (const char *p = at48; *p; p++) fields += *p == ',';
+ if (fields < 5 || fields % 5) return false;
+ const char *starts[2] = {at441 + 9, at48 + 9};
+ for (int s = 0; s < 2; s++) {
+ if (starts[s] > text + strlen(text)) return false;
+ unsigned numbers = 0;
+ for (const char *p = starts[s]; *p && numbers < fields;) {
+ char *end;
+ strtod(p, &end);
+ if (end != p) {
+ numbers++;
+ p = end;
+ } else {
+ p++;
+ }
+ }
+ if (numbers < fields) return false;
+ }
+ return true;
+}
+
+bool SGDSPEngineSetDDC(SGDSPEngine *engine, bool on, const char *text, char *error, size_t errorSize) {
+ bool readable = on && text && readableDDC(text);
+ pthread_mutex_lock(&engine->lock);
+ bool loaded = false;
+ if (readable) {
+ int parsed = DDCStringParser(engine->dsp, (char *)text);
+ loaded = parsed >= 0 && DDCEnable(engine->dsp, 1) > 0;
+ }
+ if (!loaded) DDCDisable(engine->dsp);
+ pthread_mutex_unlock(&engine->lock);
+ if (on && !loaded) {
+ copyError(error, errorSize, "Not a ViPER DDC file (SR_44100 and SR_48000 filters)");
+ return false;
+ }
+ return true;
+}
+
+// The line of the file a section's line is: libjamesdsp compiles @init and @sample apart, each numbered from
+// its own start, which is the line after its marker.
+static int fileLine(const char *script, const char *marker, int sectionLine) {
+ const char *at = strstr(script, marker);
+ if (!at) return sectionLine;
+ int line = 1;
+ for (const char *p = script; p < at; p++) line += *p == '\n';
+ return line + sectionLine;
+}
+
+bool SGDSPEngineSetLiveprog(SGDSPEngine *engine, bool on, const char *script, char *error, size_t errorSize) {
+ pthread_mutex_lock(&engine->lock);
+ LiveProgDisable(engine->dsp);
+ if (!on || !script || !*script) {
+ pthread_mutex_unlock(&engine->lock);
+ return true;
+ }
+ // Compiled and its @init run under the lock: libjamesdsp takes its own processing mutex for all of it,
+ // which the render thread would otherwise wait on.
+ int result = LiveProgStringParser(engine->dsp, (char *)script);
+ const char *compileError = NSEEL_code_getcodeerror(engine->dsp->eel.vm);
+ char message[300] = "";
+ if (result <= 0) {
+ // -1 and -3 are a section that did not compile, whose error EEL kept; 0 and -2 a section missing.
+ int line = 0, used = 0;
+ bool compiled = result == -1 || result == -3;
+ if (compiled && compileError && sscanf(compileError, "%d:%n", &line, &used) == 1 && used > 0) {
+ const char *marker = result == -1 ? "@init" : "@sample";
+ snprintf(message, sizeof message, "Line %d: %s", fileLine(script, marker, line), compileError + used + (compileError[used] == ' '));
+ } else if (compiled && compileError) {
+ snprintf(message, sizeof message, "%s: %s", checkErrorCode(result), compileError);
+ } else {
+ snprintf(message, sizeof message, "%s", checkErrorCode(result));
+ }
+ } else {
+ LiveProgEnable(engine->dsp);
+ }
+ pthread_mutex_unlock(&engine->lock);
+ if (result <= 0) {
+ copyError(error, errorSize, message);
+ return false;
+ }
+ return true;
+}
+
+#pragma mark - curves
+
+static void logSpaced(int count, double *frequencies) {
+ for (int i = 0; i < count; i++) {
+ frequencies[i] = count > 1 ? 20 * pow(1000, (double)i / (count - 1)) : 1000;
+ }
+}
+
+void SGDSPEngineEqualizerCurve(int filter, int interpolation, const double bandFrequencies[15], const double gains[15],
+ int count, double *frequencies, double *decibels) {
+ if (count <= 0) return;
+ logSpaced(count, frequencies);
+ double gain[15];
+ memcpy(gain, gains, sizeof gain);
+ if (filter <= 0) {
+ // The FIR equalizer's curve is its gains interpolated, as JamesDSP draws it.
+ float *response = malloc(count * sizeof(float));
+ if (!response) return;
+ ComputeEqResponse(bandFrequencies, gain, interpolation, count, frequencies, response);
+ for (int i = 0; i < count; i++) decibels[i] = response[i];
+ free(response);
+ return;
+ }
+ static const int orders[] = {4, 6, 8, 10, 12};
+ int order = orders[filter > 5 ? 4 : filter - 1];
+ double *re = malloc(count * sizeof(double)), *im = malloc(count * sizeof(double));
+ if (re && im) {
+ ComputeIIREqualizerCplx(48000, order, bandFrequencies, gain, count, frequencies, re, im);
+ for (int i = 0; i < count; i++) decibels[i] = 20 * log10(fmax(hypot(re[i], im[i]), 1e-12));
+ }
+ free(re);
+ free(im);
+}
+
+void SGDSPEngineCompanderCurve(const double bandFrequencies[7], const double gains[7], int count, double *frequencies,
+ double *values) {
+ if (count <= 0) return;
+ logSpaced(count, frequencies);
+ float *response = malloc(count * sizeof(float));
+ if (!response) return;
+ ComputeCompResponse(7, bandFrequencies, gains, count, frequencies, response);
+ for (int i = 0; i < count; i++) values[i] = response[i];
+ free(response);
+}
+
+#pragma mark - bundled files
+
+bool SGDSPEngineBundledFile(unsigned index, const char **kind, const char **name, const void **data, size_t *length) {
+ if (index >= jdspBundledFileCount) return false;
+ const JdspBundledFile *file = &jdspBundledFiles[index];
+ if (kind) *kind = file->kind;
+ if (name) *name = file->name;
+ if (data) *data = file->data;
+ if (length) *length = file->length;
+ return true;
+}