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: AirPods gestures learn your nod and shake to like or skip

My-Name-Is-Jeff00f37f5c3c64
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 44dcb0ac..e5806b32 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -140,6 +140,13 @@ Shared:
catalog (SystemMusicHaptics.x), and for a song Apple has a haptic track for the mod's stands down
until the next song. The analyzer is scored on the Mac against harness/haptics/, the hook in the simulator against its
sim/, the settings against harness/haptics-page/
+ HeadGestures/ AirPods gestures (HeadGestures.h lists its files): CMHeadphoneMotionManager's attitudes, while the
+ switch is on and Spotify plays, read for a double nod, which adds the track to Liked Songs through
+ Spotify's collection platform (addURL:showUIConfirmation:completion:), and a shake, which skips; a
+ tone played through Spotify's playback session confirms each, whatever the Ring/Silent switch says.
+ Learning one's own nod and shake sets the thresholds, each kept only if the detector, set to it,
+ finds the gesture in what was recorded. The detector is
+ tested on the Mac against harness/head-gestures/, the hook and the page in the simulator against its sim/
LiveActivity/ a Live Activity on the lock screen and in the Dynamic Island in one of three views, the line being
sung with the next one under it, the tracks up next (a tap on one skipping ahead to it), or a control
menu of tabs, Controls (previous, play and pause, next, shuffle, repeat), Queue and a sleep Timer of
diff --git a/harness/head-gestures/README.md b/harness/head-gestures/README.md
new file mode 100644
index 00000000..4e287ff2
--- /dev/null
+++ b/harness/head-gestures/README.md
@@ -0,0 +1,33 @@
+# AirPods gestures harness
+
+`SGHeadDetector.m` (Shared/HeadGestures) as the tweak compiles it, on the Mac, over head motion made up to
+look like what AirPods report through `CMHeadphoneMotionManager`: 25 attitudes a second, pitch and yaw in
+radians, with a little noise. Each trace says what it should fire, and the run fails when one does not.
+The negatives (one nod, three nods, a glance each way, a turn, running, dancing, a gap in the samples)
+matter as much as the gestures. Learning is run on a small slow nod and shake: the defaults miss them, what
+was learned catches them, and a walk still fires nothing at what was learned. Learning keeps a threshold only
+when the detector, set to it, fires on the recording: three nods and a double nod of 2 s learn nothing, and a
+double nod with a hard settle, which the first margin reads as six swings, learns a closer threshold that fires.
+
+ ./build.sh && build/head-gestures # the synthetic traces
+ build/head-gestures <trace.csv> [nod] [shake] # a recording, one "time,pitch,yaw" a line
+
+The traces are synthetic. No recording from real AirPods has been run through it yet: one, logged as
+`time,pitch,yaw` from `CMDeviceMotion.attitude`, goes through the second form.
+
+## The hook and the page in the simulator (`sim/`)
+
+The real `HeadGestures.x` (through Logos), its settings page and the detector, with Spotify's player and collection
+platform stood in for and `CMHeadphoneMotionManager`'s start and stop taken over, so made-up motion reaches the
+handler on the manager's own queue. It checks that nothing listens until the switch is on, a double nod adds the
+playing track with Spotify's toast, a shake skips, an episode is not saved, pausing stops, learning listens while
+paused and stores what it learned, learning with no motion says so, a learning alert's Cancel keeps the nod
+that was stored (and a second Learn meanwhile says it is still listening), and Forget asks before it clears
+both, and says nothing is learned when nothing is.
+
+ THEOS=$HOME/theos sim/build.sh && xcrun simctl install <udid> build/sim/HeadGesturesSim.app
+ xcrun simctl launch <udid> com.vitrine.headgesturessim # then read the [harness] lines from the log
+
+2026-10-05, iPhone 17 Pro on iOS 27.0: all 15 checks pass, three runs in a row, with the cue's tones played
+through AVAudioPlayer (the harness checks the calls, not the sound). With Cancel and Forget, all 24 pass; a simulator
+slow enough to hold the alert's presentation for seconds makes the timed steps fail.
diff --git a/harness/head-gestures/build.sh b/harness/head-gestures/build.sh
new file mode 100755
index 00000000..f67542f7
--- /dev/null
+++ b/harness/head-gestures/build.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Builds the AirPods gestures harness for the Mac: SGHeadDetector.m as the tweak compiles it, and main.m.
+set -e
+cd "$(dirname "$0")"
+mkdir -p build
+xcrun clang -fobjc-arc -O2 -Wall -Werror -I ../../tweak/Sources -framework Foundation \
+ main.m ../../tweak/Sources/Shared/HeadGestures/SGHeadDetector.m -o build/head-gestures
+echo "built build/head-gestures"
diff --git a/harness/head-gestures/main.m b/harness/head-gestures/main.m
new file mode 100644
index 00000000..2ee24a01
--- /dev/null
+++ b/harness/head-gestures/main.m
@@ -0,0 +1,280 @@
+// AirPods gestures' detector (Shared/HeadGestures/SGHeadDetector.m, as the tweak compiles it) over head
+// motion made up to look like what AirPods report: 25 attitudes a second, pitch and yaw in radians, with a
+// little noise on each. Every trace says what it should fire and the run fails on the first that does
+// not; the negatives (walking, glancing, one nod, a slow turn) are the point as much as the gestures.
+//
+// ./build.sh && build/head-gestures # the synthetic traces
+// build/head-gestures <trace.csv> [nod] [shake] # a recording, one "time,pitch,yaw" a line
+#import <Foundation/Foundation.h>
+#import "Shared/HeadGestures/SGHeadDetector.h"
+
+enum { kRate = 25, kMax = 25 * 60 };
+
+typedef struct {
+ double t[kMax], pitch[kMax], yaw[kMax];
+ int count;
+ double basePitch, baseYaw; // where the head rests between moves
+} Trace;
+
+static unsigned sg_seed = 1;
+static double noise(void) {
+ sg_seed = sg_seed * 1103515245 + 12345;
+ return ((sg_seed >> 8 & 0xffff) / 65535.0 - 0.5) * 0.006; // +-0.003 rad
+}
+
+static void sample(Trace *trace, double dPitch, double dYaw) {
+ int i = trace->count++;
+ trace->t[i] = 100.0 + (double)i / kRate;
+ trace->pitch[i] = trace->basePitch + dPitch + noise();
+ trace->yaw[i] = remainder(trace->baseYaw + dYaw + noise(), 2 * M_PI);
+}
+
+static void hold(Trace *trace, double seconds) {
+ for (int n = (int)(seconds * kRate); n > 0; n--) sample(trace, 0, 0);
+}
+
+// One nod: the head down by `depth` and back up over `length` seconds.
+static void nod(Trace *trace, double depth, double length) {
+ for (int n = 0, steps = (int)(length * kRate); n < steps; n++) {
+ double s = sin(M_PI * n / steps);
+ sample(trace, -depth * s * s, 0);
+ }
+}
+
+// A shake: `swings` half cycles of the yaw at `hertz`, `width` either side.
+static void shake(Trace *trace, double width, double hertz, double swings) {
+ for (int n = 0, steps = (int)(swings / (2 * hertz) * kRate); n < steps; n++)
+ sample(trace, 0, width * sin(2 * M_PI * hertz * n / kRate));
+}
+
+// The yaw moved from where it rests to `to` over `seconds`, smoothly, and left there.
+static void turn(Trace *trace, double to, double seconds) {
+ double from = 0;
+ for (int n = 1, steps = (int)(seconds * kRate); n <= steps; n++) {
+ double s = 0.5 - 0.5 * cos(M_PI * n / steps);
+ sample(trace, 0, from + (to - from) * s);
+ }
+ trace->baseYaw += to;
+}
+
+static void walk(Trace *trace, double seconds) {
+ for (int n = 0, steps = (int)(seconds * kRate); n < steps; n++) {
+ double t = (double)n / kRate;
+ sample(trace, 0.05 * sin(2 * M_PI * 2 * t), 0.03 * sin(2 * M_PI * 1 * t));
+ }
+}
+
+// Running: the head bobs at the stride, near 3 Hz, by more than a walk and with a sway.
+static void run(Trace *trace, double seconds) {
+ for (int n = 0, steps = (int)(seconds * kRate); n < steps; n++) {
+ double t = (double)n / kRate;
+ sample(trace, 0.12 * sin(2 * M_PI * 2.8 * t), 0.08 * sin(2 * M_PI * 1.4 * t));
+ }
+}
+
+static int replayTrace(const Trace *trace, double nodThreshold, double shakeThreshold, int *likes, int *skips) {
+ SGHeadDetector detector;
+ SGHeadDetectorReset(&detector, nodThreshold, shakeThreshold);
+ *likes = *skips = 0;
+ for (int i = 0; i < trace->count; i++) {
+ SGHeadGesture gesture = SGHeadDetectorFeed(&detector, trace->t[i], trace->pitch[i], trace->yaw[i]);
+ if (gesture == SGHeadGestureDoubleNod) ++*likes;
+ if (gesture == SGHeadGestureShake) ++*skips;
+ }
+ return *likes + *skips;
+}
+
+static int failures;
+
+static void expect(const char *name, const Trace *trace, double nod, double shake, int likes, int skips) {
+ int gotLikes, gotSkips;
+ replayTrace(trace, nod, shake, &gotLikes, &gotSkips);
+ bool ok = gotLikes == likes && gotSkips == skips;
+ if (!ok) failures++;
+ printf("%-4s %-52s likes %d skips %d (want %d, %d)\n", ok ? "ok" : "FAIL", name, gotLikes, gotSkips, likes, skips);
+}
+
+static void nothingLearned(const char *name, const Trace *trace, SGHeadAxis axis) {
+ double learned = SGHeadLearn(trace->t, trace->pitch, trace->yaw, trace->count, axis,
+ axis == SGHeadAxisPitch ? SGHeadDefaultShake : SGHeadDefaultNod);
+ bool ok = learned == 0;
+ if (!ok) failures++;
+ printf("%-4s %-52s %.2f (want 0)\n", ok ? "ok" : "FAIL", name, learned);
+}
+
+static void start(Trace *trace) {
+ memset(trace, 0, sizeof *trace);
+ trace->basePitch = 0.1;
+ trace->baseYaw = 3.0; // near +-pi, so a shake crosses the wrap
+ hold(trace, 1);
+}
+
+static Trace *fresh(void) {
+ static Trace trace;
+ start(&trace);
+ return &trace;
+}
+
+// What the teaching sheet learns from its five recordings: all of them but one at least must fire.
+static double learnFive(Trace *const five[5], SGHeadAxis axis, double other) {
+ SGHeadRecording recordings[5];
+ for (int i = 0; i < 5; i++) recordings[i] = (SGHeadRecording){five[i]->t, five[i]->pitch, five[i]->yaw, five[i]->count};
+ return SGHeadLearnSamples(recordings, 5, axis, other, 4);
+}
+
+static void inRange(const char *name, double threshold) {
+ bool ok = threshold >= SGHeadMinThreshold && threshold <= SGHeadMaxThreshold;
+ if (!ok) failures++;
+ printf("%-4s %-52s %.2f (want %.1f to %.1f)\n", ok ? "ok" : "FAIL", name, threshold, SGHeadMinThreshold, SGHeadMaxThreshold);
+}
+
+static int replay(const char *path, double nod, double shake) {
+ FILE *file = fopen(path, "r");
+ if (!file) {
+ fprintf(stderr, "cannot open %s\n", path);
+ return 1;
+ }
+ SGHeadDetector detector;
+ SGHeadDetectorReset(&detector, nod, shake);
+ double t, pitch, yaw;
+ while (fscanf(file, "%lf,%lf,%lf", &t, &pitch, &yaw) == 3) {
+ SGHeadGesture gesture = SGHeadDetectorFeed(&detector, t, pitch, yaw);
+ if (gesture) printf("%.2f %s\n", t, gesture == SGHeadGestureDoubleNod ? "double nod" : "shake");
+ }
+ fclose(file);
+ return 0;
+}
+
+int main(int argc, char **argv) {
+ if (argc > 1) return replay(argv[1], argc > 2 ? atof(argv[2]) : SGHeadDefaultNod, argc > 3 ? atof(argv[3]) : SGHeadDefaultShake);
+ const double nodD = SGHeadDefaultNod, shakeD = SGHeadDefaultShake;
+ Trace *t;
+
+ // The gestures, at the defaults. A 20 degree nod in 0.4 s peaks at 2.7 rad/s; a 12 degree shake at
+ // 2.5 Hz at 3.3.
+ t = fresh(); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); hold(t, 1);
+ expect("double nod", t, nodD, shakeD, 1, 0);
+ t = fresh(); nod(t, 0.35, 0.4); hold(t, 0.1); nod(t, 0.35, 0.4); hold(t, 1);
+ expect("double nod with a pause between", t, nodD, shakeD, 1, 0);
+ t = fresh(); shake(t, 0.21, 2.5, 4); hold(t, 1);
+ expect("shake, 4 swings across the wrap of the yaw", t, nodD, shakeD, 0, 1);
+ t = fresh(); shake(t, 0.21, 2.5, 3); hold(t, 1);
+ expect("shake, 3 swings", t, nodD, shakeD, 0, 1);
+ t = fresh(); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); hold(t, 2); shake(t, 0.21, 2.5, 4); hold(t, 1);
+ expect("double nod, then a shake 2 s later", t, nodD, shakeD, 1, 1);
+ t = fresh(); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); hold(t, 0.5); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); hold(t, 1);
+ expect("two double nods in a second: the cooldown", t, nodD, shakeD, 1, 0);
+
+ // What must not fire.
+ t = fresh(); nod(t, 0.35, 0.4); hold(t, 2);
+ expect("one nod", t, nodD, shakeD, 0, 0);
+ t = fresh(); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); hold(t, 1);
+ expect("three nods", t, nodD, shakeD, 0, 0);
+ t = fresh(); turn(t, -0.8, 0.6); hold(t, 0.6); turn(t, 1.6, 1.0); hold(t, 0.6); turn(t, -0.8, 0.6); hold(t, 1);
+ expect("a glance left, then right, then back", t, nodD, shakeD, 0, 0);
+ t = fresh(); turn(t, 1.2, 0.8); hold(t, 2);
+ expect("one turn of the head", t, nodD, shakeD, 0, 0);
+ t = fresh(); walk(t, 10); hold(t, 1);
+ expect("walking, 10 s", t, nodD, shakeD, 0, 0);
+ // A walk bobs the head under the thresholds, so a double nod on the move still counts; a run bobs it
+ // over them, on and on, which is too long for a gesture.
+ t = fresh(); walk(t, 3); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); walk(t, 3); hold(t, 1);
+ expect("a double nod in the middle of a walk", t, nodD, shakeD, 1, 0);
+ t = fresh(); run(t, 10); hold(t, 1);
+ expect("running, 10 s", t, nodD, shakeD, 0, 0);
+ t = fresh(); shake(t, 0.21, 2.5, 14); hold(t, 1);
+ expect("shaking on and on (dancing)", t, nodD, shakeD, 0, 0);
+ t = fresh(); nod(t, 0.35, 0.4); hold(t, 1.2); nod(t, 0.35, 0.4); hold(t, 1);
+ expect("two nods 1.2 s apart", t, nodD, shakeD, 0, 0);
+ // The headphones stop sending for a second between the nods: a gap starts over.
+ t = fresh(); nod(t, 0.35, 0.4);
+ for (int i = 0; i < t->count; i++) t->t[i] -= 1;
+ nod(t, 0.35, 0.4); hold(t, 1);
+ expect("a 1 s gap in the samples between the nods", t, nodD, shakeD, 0, 0);
+
+ // Learning: one double nod and one shake of someone who moves small and slow.
+ t = fresh(); nod(t, 0.17, 0.5); nod(t, 0.17, 0.5); hold(t, 1);
+ double learnedNod = SGHeadLearn(t->t, t->pitch, t->yaw, t->count, SGHeadAxisPitch, shakeD);
+ expect("a small slow double nod, at the default", t, nodD, shakeD, 0, 0);
+ expect("the same, at what was learned from it", t, learnedNod, shakeD, 1, 0);
+ t = fresh(); shake(t, 0.12, 2, 4); hold(t, 1);
+ double learnedShake = SGHeadLearn(t->t, t->pitch, t->yaw, t->count, SGHeadAxisYaw, learnedNod);
+ expect("a small slow shake, at what was learned from it", t, learnedNod, learnedShake, 0, 1);
+ printf(" learned nod %.2f rad/s, shake %.2f rad/s\n", learnedNod, learnedShake);
+ t = fresh(); walk(t, 10); hold(t, 1);
+ expect("walking, at what was learned", t, learnedNod, learnedShake, 0, 0);
+ nothingLearned("learning from a walk learns nothing", t, SGHeadAxisPitch);
+ t = fresh(); nod(t, 0.35, 0.4); hold(t, 2);
+ nothingLearned("learning from one nod learns nothing", t, SGHeadAxisPitch);
+ // Enough swings, but more than a double nod has, or slower than one takes: the detector would never
+ // fire on them, so nothing is learned rather than a threshold that says Learned and then does nothing.
+ t = fresh(); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); hold(t, 1);
+ nothingLearned("learning from three nods learns nothing", t, SGHeadAxisPitch);
+ t = fresh(); nod(t, 0.35, 1.0); nod(t, 0.35, 1.0); hold(t, 1);
+ nothingLearned("learning from a double nod of 2 s learns nothing", t, SGHeadAxisPitch);
+ // A double nod whose settle bounces back hard: at the first margin the bounce counts as two more swings,
+ // six in all, which is no double nod; a closer threshold leaves it out.
+ t = fresh(); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); nod(t, 0.2, 0.3); hold(t, 1);
+ double bounced = SGHeadLearn(t->t, t->pitch, t->yaw, t->count, SGHeadAxisPitch, shakeD);
+ expect("a double nod with a hard settle, at 0.6 of its swings", t, 0.6 * 0.35 * M_PI / 0.4, shakeD, 0, 0);
+ expect("the same, at what was learned from it", t, bounced, shakeD, 1, 0);
+ printf(" learned %.2f rad/s from it\n", bounced);
+ t = fresh(); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); hold(t, 1);
+ expect("a plain double nod, at what was learned from the hard settle", t, bounced, shakeD, 1, 0);
+
+ // Sensitivity divides the threshold: a nod half the size passes at 200% and not at 100%.
+ t = fresh(); nod(t, 0.35, 0.4); nod(t, 0.35, 0.4); hold(t, 1);
+ double fullNod = SGHeadLearn(t->t, t->pitch, t->yaw, t->count, SGHeadAxisPitch, shakeD);
+ t = fresh(); nod(t, 0.17, 0.4); nod(t, 0.17, 0.4); hold(t, 1);
+ expect("a half size double nod, sensitivity 100%", t, fullNod, shakeD, 0, 0);
+ expect("a half size double nod, sensitivity 200%", t, fullNod / 2, shakeD, 1, 0);
+
+ // Teaching: five recordings of a gesture, one each, the way the sheet takes them.
+ Trace *five[5];
+ for (int i = 0; i < 5; i++) five[i] = calloc(1, sizeof(Trace));
+ const double depths[5] = {0.35, 0.28, 0.32, 0.30, 0.26}, lengths[5] = {0.4, 0.45, 0.4, 0.4, 0.45};
+ for (int i = 0; i < 5; i++) {
+ start(five[i]); nod(five[i], depths[i], lengths[i]); nod(five[i], depths[i], lengths[i]); hold(five[i], 0.8);
+ }
+ double taught = learnFive(five, SGHeadAxisPitch, shakeD);
+ inRange("five double nods of different sizes teach", taught);
+ // From the smallest of them, whose swings peak at 0.26 * pi / 0.45 = 1.8 rad/s, under it with room.
+ bool fromSmallest = taught > SGHeadMinThreshold && taught < 0.26 * M_PI / 0.45;
+ if (!fromSmallest) failures++;
+ printf("%-4s %-52s %.2f (want over %.1f, under 1.8)\n", fromSmallest ? "ok" : "FAIL", "what they teach comes from the smallest", taught, SGHeadMinThreshold);
+ for (int i = 0; i < 5; i++) {
+ char name[64];
+ snprintf(name, sizeof name, "taught from five, double nod %d (%.2f rad deep)", i + 1, depths[i]);
+ expect(name, five[i], taught, shakeD, 1, 0);
+ }
+ printf(" taught nod %.2f rad/s\n", taught);
+ t = fresh(); walk(t, 10); hold(t, 1);
+ expect("walking, at what five double nods taught", t, taught, shakeD, 0, 0);
+ // One of the five is three nods, no double nod at any threshold: four out of five still teach.
+ start(five[2]); nod(five[2], 0.3, 0.4); nod(five[2], 0.3, 0.4); nod(five[2], 0.3, 0.4); hold(five[2], 0.8);
+ taught = learnFive(five, SGHeadAxisPitch, shakeD);
+ inRange("four double nods and three nods teach", taught);
+ expect("taught from four of five, double nod 1", five[0], taught, shakeD, 1, 0);
+ expect("taught from four of five, double nod 5", five[4], taught, shakeD, 1, 0);
+ // Two of them three nods: only three out of five, nothing is taught.
+ start(five[3]); nod(five[3], 0.3, 0.4); nod(five[3], 0.3, 0.4); nod(five[3], 0.3, 0.4); hold(five[3], 0.8);
+ taught = learnFive(five, SGHeadAxisPitch, shakeD);
+ bool none = taught == 0;
+ if (!none) failures++;
+ printf("%-4s %-52s %.2f (want 0)\n", none ? "ok" : "FAIL", "three double nods and two of three nods teach nothing", taught);
+ // Five shakes, narrower and slower each time.
+ const double widths[5] = {0.21, 0.18, 0.15, 0.12, 0.2}, hertz[5] = {2.5, 2.2, 2.0, 2.0, 2.4};
+ for (int i = 0; i < 5; i++) { start(five[i]); shake(five[i], widths[i], hertz[i], 4); hold(five[i], 0.8); }
+ double taughtShake = learnFive(five, SGHeadAxisYaw, nodD);
+ inRange("five shakes of different sizes teach", taughtShake);
+ for (int i = 0; i < 5; i++) {
+ char name[64];
+ snprintf(name, sizeof name, "taught from five, shake %d (%.2f rad wide)", i + 1, widths[i]);
+ expect(name, five[i], nodD, taughtShake, 0, 1);
+ }
+ printf(" taught shake %.2f rad/s\n", taughtShake);
+ for (int i = 0; i < 5; i++) free(five[i]);
+
+ printf(failures ? "%d failed\n" : "all passed\n", failures);
+ return failures ? 1 : 0;
+}
diff --git a/harness/head-gestures/sim/build.sh b/harness/head-gestures/sim/build.sh
new file mode 100755
index 00000000..ecc27b3a
--- /dev/null
+++ b/harness/head-gestures/sim/build.sh
@@ -0,0 +1,43 @@
+#!/bin/sh
+# Builds the AirPods gestures simulator harness: HeadGestures.x through Logos, its page, the detector and
+# the Settings/ framework as they are in the tweak, main.m standing in for Spotify and the headphones.
+set -e
+SRC=$(cd "$(dirname "$0")/../../../tweak/Sources" && pwd)
+OUT=$(dirname "$0")/../build/sim # under the gitignored build/ beside the Mac harness
+rm -rf "$OUT"; mkdir -p "$OUT/gen" "$OUT/HeadGesturesSim.app"
+"$THEOS/bin/logos.pl" -c generator=internal "$SRC/Shared/HeadGestures/HeadGestures.x" > "$OUT/gen/HeadGestures.m"
+
+SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
+xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O0 \
+ -I"$SRC" -I"$SRC/Shared/HeadGestures" -isysroot "$SDK" -Wall -Werror -Wno-deprecated-declarations \
+ "$(dirname "$0")/main.m" "$(dirname "$0")/../../scene.m" "$OUT/gen/HeadGestures.m" \
+ "$SRC"/Shared/HeadGestures/HeadGesturesSettings.m "$SRC"/Shared/HeadGestures/SGHeadDetector.m \
+ "$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
+ "$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \
+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework Foundation -framework CoreMotion -framework AudioToolbox -framework AVFoundation \
+ -o "$OUT/HeadGesturesSim.app/HeadGesturesSim"
+
+cat > "$OUT/HeadGesturesSim.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>HeadGesturesSim</string>
+<key>CFBundleIdentifier</key><string>com.vitrine.headgesturessim</string>
+<key>CFBundleName</key><string>HeadGesturesSim</string>
+<key>CFBundleVersion</key><string>1</string>
+<key>CFBundleShortVersionString</key><string>1.0</string>
+<key>UIUserInterfaceStyle</key><string>Dark</string>
+<key>UILaunchScreen</key><dict/>
+<key>NSMotionUsageDescription</key><string>The harness reads made-up head motion.</string>
+<key>UIApplicationSceneManifest</key><dict>
+ <key>UIApplicationSupportsMultipleScenes</key><false/>
+ <key>UISceneConfigurations</key><dict>
+ <key>UIWindowSceneSessionRoleApplication</key><array><dict>
+ <key>UISceneConfigurationName</key><string>Default</string>
+ <key>UISceneDelegateClassName</key><string>SGRHarnessScene</string>
+ </dict></array>
+ </dict>
+</dict>
+</dict></plist>
+PLIST
+echo "built $OUT/HeadGesturesSim.app"
diff --git a/harness/head-gestures/sim/main.m b/harness/head-gestures/sim/main.m
new file mode 100644
index 00000000..f4821fba
--- /dev/null
+++ b/harness/head-gestures/sim/main.m
@@ -0,0 +1,338 @@
+// AirPods gestures in the simulator: the real HeadGestures.x (through Logos), its settings page and the
+// detector, with Spotify's player and collection platform stood in for, and CMHeadphoneMotionManager's
+// start and stop taken over so the harness hands the handler made-up motion on the manager's own queue.
+// The simulator has no headphones, so this proves the wiring (the switch, playing or not, the thresholds,
+// the like and skip calls, the learning alerts), not the motion. A fixed run of steps, one every second;
+// each check logs "ok" or "FAIL" and the last line says how many failed.
+//
+// THEOS=$HOME/theos ./build.sh && xcrun simctl install <udid> ../build/sim/HeadGesturesSim.app
+// xcrun simctl launch --console-pty <udid> com.vitrine.headgesturessim
+#import <UIKit/UIKit.h>
+#import <CoreMotion/CoreMotion.h>
+#import <objc/runtime.h>
+#import "Core/SGCore.h"
+#import "Settings/SGModPage.h"
+#import "Shared/HeadGestures/HeadGestures.h"
+#import "Shared/Player/PlayerState.h"
+
+static int failures;
+static void check(BOOL ok, NSString *what) {
+ if (!ok) failures++;
+ NSLog(@"[harness] %@ %@", ok ? @"ok " : @"FAIL", what);
+}
+
+#pragma mark - Spotify stood in for
+
+@interface FakeTrack : NSObject
+@property (nonatomic, strong) id URI;
+@end
+@implementation FakeTrack
+@end
+
+@interface FakeState : NSObject
+@property (nonatomic, strong) FakeTrack *track;
+@property (nonatomic) BOOL isPlaying, isPaused;
+@end
+@implementation FakeState
+@end
+
+static FakeState *sg_state;
+static __weak id<SGPlayerStateObserver> sg_observer;
+static NSMutableArray<NSString *> *sg_calls;
+
+NSString *SGURIString(id uri) {
+ if ([uri isKindOfClass:NSURL.class]) return [uri absoluteString];
+ return [uri isKindOfClass:NSString.class] ? uri : nil;
+}
+void SGAddPlayerStateObserver(id<SGPlayerStateObserver> observer) { sg_observer = observer; }
+SPTPlayerState *SGPlayerState(void) { return (SPTPlayerState *)sg_state; }
+
+@interface FakePlayer : NSObject
+@end
+@implementation FakePlayer
+- (id)skipToNextTrackWithOptions:(id)options {
+ [sg_calls addObject:@"skip"];
+ return nil;
+}
+@end
+static FakePlayer *sg_player;
+id SGKaraokePlayer(void) { return sg_player; }
+
+// The class HeadGestures.x hooks, with the selectors Spotify's has.
+@interface SPTCollectionPlatformImplementation : NSObject
+@end
+@implementation SPTCollectionPlatformImplementation
+- (id)stateProvider { return nil; }
+- (void)addURL:(NSURL *)url showUIConfirmation:(BOOL)show completion:(void (^)(void))completion {
+ [sg_calls addObject:[NSString stringWithFormat:@"add %@ %@", url.absoluteString, show ? @"toast" : @"quiet"]];
+ completion();
+}
+@end
+
+#pragma mark - the headphones stood in for
+
+@interface FakeAttitude : NSObject
+@property (nonatomic) double pitch, yaw;
+@end
+@implementation FakeAttitude
+@end
+
+@interface FakeMotion : NSObject
+@property (nonatomic) NSTimeInterval timestamp;
+@property (nonatomic, strong) FakeAttitude *attitude;
+@end
+@implementation FakeMotion
+@end
+
+static CMHeadphoneDeviceMotionHandler sg_handler;
+static NSOperationQueue *sg_motionQueue;
+static BOOL sg_active;
+static int sg_starts, sg_stops;
+static double sg_clock = 100;
+
+static void fakeStart(id self, SEL _cmd, NSOperationQueue *queue, CMHeadphoneDeviceMotionHandler handler) {
+ sg_handler = handler;
+ sg_motionQueue = queue;
+ sg_active = YES;
+ sg_starts++;
+}
+static void fakeStop(id self, SEL _cmd) {
+ sg_active = NO;
+ sg_stops++;
+}
+static BOOL fakeActive(id self, SEL _cmd) { return sg_active; }
+static BOOL fakeAvailable(id self, SEL _cmd) { return YES; }
+static CMAuthorizationStatus fakeAuthorized(id self, SEL _cmd) { return CMAuthorizationStatusAuthorized; }
+
+static void takeOverMotion(void) {
+ Class manager = CMHeadphoneMotionManager.class;
+ method_setImplementation(class_getInstanceMethod(manager, @selector(startDeviceMotionUpdatesToQueue:withHandler:)), (IMP)fakeStart);
+ method_setImplementation(class_getInstanceMethod(manager, @selector(stopDeviceMotionUpdates)), (IMP)fakeStop);
+ method_setImplementation(class_getInstanceMethod(manager, @selector(isDeviceMotionActive)), (IMP)fakeActive);
+ method_setImplementation(class_getInstanceMethod(manager, @selector(isDeviceMotionAvailable)), (IMP)fakeAvailable);
+ // Asked already: the page's first-time start for the permission prompt stays out of the counts.
+ method_setImplementation(class_getClassMethod(manager, @selector(authorizationStatus)), (IMP)fakeAuthorized);
+}
+
+// 25 attitudes a second, as AirPods send them, onto the manager's queue while it listens.
+static void send(double pitch, double yaw) {
+ sg_clock += 1.0 / 25;
+ if (!sg_active) return;
+ FakeMotion *motion = [FakeMotion new];
+ motion.timestamp = sg_clock;
+ motion.attitude = [FakeAttitude new];
+ motion.attitude.pitch = pitch;
+ motion.attitude.yaw = yaw;
+ CMHeadphoneDeviceMotionHandler handler = sg_handler;
+ [sg_motionQueue addOperationWithBlock:^{ handler((CMDeviceMotion *)motion, nil); }];
+}
+static void hold(double seconds) {
+ for (int n = (int)(seconds * 25); n > 0; n--) send(0.1, 3.0);
+}
+static void doubleNod(double depth, double length) {
+ for (int k = 0; k < 2; k++)
+ for (int n = 0, steps = (int)(length * 25); n < steps; n++) {
+ double s = sin(M_PI * n / steps);
+ send(0.1 - depth * s * s, 3.0);
+ }
+ hold(2);
+}
+static void shake(double width, double hertz) {
+ for (int n = 0, steps = (int)(4 / (2 * hertz) * 25); n < steps; n++) send(0.1, remainder(3.0 + width * sin(2 * M_PI * hertz * n / 25), 2 * M_PI));
+ hold(2);
+}
+
+#pragma mark - the run
+
+static void findViews(UIView *root, Class kind, NSMutableArray *found) {
+ if ([root isKindOfClass:kind]) [found addObject:root];
+ for (UIView *sub in root.subviews) findViews(sub, kind, found);
+}
+
+static NSInteger sg_nodBefore;
+
+@interface AppDelegate : UIResponder <UIApplicationDelegate>
+@property (nonatomic, strong) UIWindow *window;
+@property (nonatomic, strong) UINavigationController *nav;
+@property (nonatomic, strong) SPTCollectionPlatformImplementation *platform;
+@end
+
+@implementation AppDelegate
+
+- (UITableView *)table {
+ return ((UITableViewController *)self.nav.viewControllers.lastObject).tableView;
+}
+
+- (void)setPlaying:(BOOL)playing {
+ sg_state.isPlaying = YES; // Spotify's stays on while a loaded track is paused
+ sg_state.isPaused = !playing;
+ [sg_observer playerStateDidChange:(SPTPlayerState *)sg_state];
+}
+
+- (NSString *)alertTitle {
+ UIViewController *shown = self.nav.presentedViewController;
+ return [shown isKindOfClass:UIAlertController.class] ? shown.title : nil;
+}
+
+- (void)dismissAlert {
+ [self.nav dismissViewControllerAnimated:NO completion:nil];
+}
+
+// The alert's button of that style, pressed: the alert goes and its handler runs.
+- (void)press:(UIAlertActionStyle)style {
+ UIAlertController *alert = (UIAlertController *)self.nav.presentedViewController;
+ for (UIAlertAction *action in alert.actions) {
+ if (action.style != style) continue;
+ void (^handler)(UIAlertAction *) = [action valueForKey:@"handler"];
+ [self.nav dismissViewControllerAnimated:NO completion:^{ if (handler) handler(action); }];
+ }
+}
+
+- (NSArray<void (^)(void)> *)steps {
+ return @[
+ ^{
+ check(sg_starts == 0, @"switch off, playing: not listening");
+ UITableViewCell *cell = [self.table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
+ NSMutableArray<UISwitch *> *switches = [NSMutableArray array];
+ findViews(cell, UISwitch.class, switches);
+ [switches.firstObject setOn:YES animated:YES];
+ [switches.firstObject sendActionsForControlEvents:UIControlEventValueChanged];
+ },
+ ^{
+ check(sg_active, @"switch on, playing: listening");
+ doubleNod(0.35, 0.4);
+ },
+ ^{
+ check([sg_calls isEqualToArray:@[@"add spotify:track:4uLU6hMCjMI75M1A2tKUQC toast"]],
+ [NSString stringWithFormat:@"a double nod adds the track, calls %@", sg_calls]);
+ [sg_calls removeAllObjects];
+ shake(0.21, 2.5);
+ },
+ ^{
+ check([sg_calls isEqualToArray:@[@"skip"]], [NSString stringWithFormat:@"a shake skips, calls %@", sg_calls]);
+ [sg_calls removeAllObjects];
+ doubleNod(0.17, 0.5);
+ },
+ ^{
+ check(sg_calls.count == 0, [NSString stringWithFormat:@"a small slow double nod at the default does nothing, calls %@", sg_calls]);
+ sg_state.track.URI = [NSURL URLWithString:@"spotify:episode:512ojhOuo1ktJprKbVcKyQ"];
+ doubleNod(0.35, 0.4);
+ },
+ ^{
+ check(sg_calls.count == 0, [NSString stringWithFormat:@"a double nod on an episode saves nothing, calls %@", sg_calls]);
+ sg_state.track.URI = @"spotify:track:4uLU6hMCjMI75M1A2tKUQC";
+ [self setPlaying:NO];
+ check(!sg_active && sg_stops == 1, @"paused: stopped");
+ // Learning listens whatever plays.
+ [self.table.delegate tableView:self.table didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
+ },
+ ^{
+ NSLog(@"[harness] learning started: %@", sg_active ? @"yes" : @"no");
+ },
+ ^{
+ check([[self alertTitle] isEqualToString:@"Nod twice"], [NSString stringWithFormat:@"learning asks for a nod: %@", [self alertTitle]]);
+ check(sg_active, @"learning while paused: listening");
+ doubleNod(0.17, 0.5);
+ },
+ ^{}, ^{}, ^{},
+ ^{
+ check([[self alertTitle] isEqualToString:@"Learned"], [NSString stringWithFormat:@"after 4 s it says %@", [self alertTitle]]);
+ check(SGInt(SGKeyHeadNod, 0) > 0, [NSString stringWithFormat:@"stored nod %ld", (long)SGInt(SGKeyHeadNod, 0)]);
+ check(!sg_active, @"learning over, paused: stopped");
+ [self dismissAlert];
+ [self.table reloadData];
+ [self setPlaying:YES];
+ doubleNod(0.17, 0.5);
+ },
+ ^{
+ check([sg_calls isEqualToArray:@[@"add spotify:track:4uLU6hMCjMI75M1A2tKUQC toast"]],
+ [NSString stringWithFormat:@"the small slow double nod, at what was learned, adds the track, calls %@", sg_calls]);
+ [sg_calls removeAllObjects];
+ [self setPlaying:NO];
+ // No headphones: nothing arrives while it learns the shake.
+ [self.table.delegate tableView:self.table didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
+ },
+ ^{}, ^{}, ^{}, ^{}, ^{},
+ ^{
+ check([[self alertTitle] isEqualToString:@"No motion came"], [NSString stringWithFormat:@"learning with nothing sent says %@", [self alertTitle]]);
+ check(SGInt(SGKeyHeadShake, 0) == 0, @"nothing stored for the shake");
+ [self dismissAlert];
+ [self.table reloadData];
+ },
+ ^{
+ // Learning the nod again, cancelled while a nod comes in.
+ sg_nodBefore = SGInt(SGKeyHeadNod, 0);
+ [self.table.delegate tableView:self.table didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
+ },
+ ^{
+ check([[self alertTitle] isEqualToString:@"Nod twice"], [NSString stringWithFormat:@"learning asks again: %@", [self alertTitle]]);
+ [self press:UIAlertActionStyleCancel];
+ doubleNod(0.35, 0.4);
+ },
+ ^{
+ check([self alertTitle] == nil, [NSString stringWithFormat:@"Cancel takes the alert away: %@", [self alertTitle]]);
+ [self.table.delegate tableView:self.table didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
+ },
+ ^{
+ check([[self alertTitle] isEqualToString:@"Still listening"], [NSString stringWithFormat:@"learning again before the cancelled one ends says %@", [self alertTitle]]);
+ [self dismissAlert];
+ },
+ ^{}, ^{},
+ ^{
+ check([self alertTitle] == nil, [NSString stringWithFormat:@"a cancelled try says nothing when it ends: %@", [self alertTitle]]);
+ check(SGInt(SGKeyHeadNod, 0) == sg_nodBefore, [NSString stringWithFormat:@"a cancelled try keeps the nod %ld, stored %ld", (long)sg_nodBefore, (long)SGInt(SGKeyHeadNod, 0)]);
+ check(!sg_active, @"cancelled learning over, paused: stopped");
+ [self.table.delegate tableView:self.table didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]];
+ },
+ ^{
+ check([[self alertTitle] isEqualToString:@"Forget your nod and shake?"], [NSString stringWithFormat:@"Forget asks first: %@", [self alertTitle]]);
+ [self press:UIAlertActionStyleDestructive];
+ },
+ ^{
+ check(SGInt(SGKeyHeadNod, 0) == 0 && SGInt(SGKeyHeadShake, 0) == 0, @"Forget clears both");
+ [self.table.delegate tableView:self.table didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]];
+ },
+ ^{
+ check([[self alertTitle] isEqualToString:@"Nothing learned yet"], [NSString stringWithFormat:@"Forget with nothing learned says %@", [self alertTitle]]);
+ [self dismissAlert];
+ },
+ ^{
+ NSLog(@"[harness] %@", failures ? [NSString stringWithFormat:@"%d failed", failures] : @"all passed");
+ },
+ ];
+}
+
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;
+ for (NSString *key in store.dictionaryRepresentation.allKeys)
+ if ([key hasPrefix:@"spotifyglass.headgestures"]) [store removeObjectForKey:key];
+ takeOverMotion();
+ sg_calls = [NSMutableArray array];
+ sg_player = [FakePlayer new];
+ sg_state = [FakeState new];
+ sg_state.track = [FakeTrack new];
+ sg_state.track.URI = @"spotify:track:4uLU6hMCjMI75M1A2tKUQC";
+ // Spotify reaching for its platform's state provider is what the hook keeps it from.
+ self.platform = [SPTCollectionPlatformImplementation new];
+ [self.platform stateProvider];
+ [self setPlaying:YES];
+
+ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
+ self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
+ self.nav = [[UINavigationController alloc] initWithRootViewController:SGHeadGesturesSettingsPage()];
+ self.window.rootViewController = self.nav;
+ [self.window makeKeyAndVisible];
+
+ [[self steps] enumerateObjectsUsingBlock:^(void (^step)(void), NSUInteger i, BOOL *stop) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((1.5 + i) * NSEC_PER_SEC)), dispatch_get_main_queue(), step);
+ }];
+ return YES;
+}
+
+@end
+
+int main(int argc, char *argv[]) {
+ @autoreleasepool {
+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(AppDelegate.class));
+ }
+}
diff --git a/plist/liquid-glass.plist b/plist/liquid-glass.plist
index db76b5e1..81ff3b23 100644
--- a/plist/liquid-glass.plist
+++ b/plist/liquid-glass.plist
@@ -10,5 +10,7 @@
<true/>
<key>MusicHapticsSupported</key>
<true/>
+ <key>NSMotionUsageDescription</key>
+ <string>AirPods gestures read how your head moves, so a double nod can like a song and a shake can skip it.</string>
</dict>
</plist>
diff --git a/tweak/Makefile b/tweak/Makefile
index c7008250..54266035 100644
--- a/tweak/Makefile
+++ b/tweak/Makefile
@@ -16,7 +16,7 @@ TWEAK_NAME := spotifyglass
# is generated from the IPA by scripts/extract-flags.py.
spotifyglass_FILES := $(shell find Sources -name '*.m' -o -name '*.x' -o -name '*.swift' | sort)
spotifyglass_CFLAGS := -fobjc-arc -ISources -DSG_VERSION=\"$(SG_VERSION)\"
-spotifyglass_FRAMEWORKS := UIKit QuartzCore UniformTypeIdentifiers MediaPlayer CoreImage AudioToolbox AVFoundation CoreHaptics Accelerate
+spotifyglass_FRAMEWORKS := UIKit QuartzCore UniformTypeIdentifiers MediaPlayer CoreImage AudioToolbox AVFoundation CoreHaptics Accelerate CoreMotion
# Runtime swizzling instead of Substrate so the dylib has no extra dependency inside the IPA.
spotifyglass_LOGOS_DEFAULT_GENERATOR := internal
diff --git a/tweak/Sources/App/Pages.m b/tweak/Sources/App/Pages.m
index 16bd2ec0..0e91c744 100644
--- a/tweak/Sources/App/Pages.m
+++ b/tweak/Sources/App/Pages.m
@@ -7,6 +7,7 @@
#import "Pages.h"
#import "Shared/ArtistBlock/ArtistBlock.h"
#import "Shared/Gestures/Gestures.h"
+#import "Shared/HeadGestures/HeadGestures.h"
#import "Shared/Lyrics/Lyrics.h"
#import "Shared/LyricsMeanings/Meanings.h"
#import "Shared/Player/PlayerSettings.h"
@@ -102,6 +103,7 @@ UIViewController *SGPlayerSettingsPage(void) {
NSMutableArray<SGModSection *> *sections = [NSMutableArray arrayWithObject:SGSection(nil, @[
SGWithSymbol(SGPageRow(@"Gestures", ^UIViewController *{ return SGGesturesSettingsPage(); }), @"hand.tap"),
+ SGWithSymbol(SGPageRow(@"AirPods gestures", ^UIViewController *{ return SGHeadGesturesSettingsPage(); }), @"airpods.pro"),
SGWithSymbol(SGPageRow(@"Lyrics", ^UIViewController *{ return lyricsPage(); }), @"quote.bubble"),
SGWithSymbol(blocked, @"person.crop.circle.badge.xmark"),
])];
diff --git a/tweak/Sources/Shared/HeadGestures/HeadGestures.h b/tweak/Sources/Shared/HeadGestures/HeadGestures.h
new file mode 100644
index 00000000..9ac28283
--- /dev/null
+++ b/tweak/Sources/Shared/HeadGestures/HeadGestures.h
@@ -0,0 +1,43 @@
+// AirPods gestures (Mod Settings > Player > AirPods gestures), under either look: a double nod adds the
+// playing song to Liked Songs and a shake of the head skips it, read from the head motion that AirPods Pro,
+// AirPods 3 and later, AirPods Max and some Beats report through CMHeadphoneMotionManager.
+//
+// SGHeadDetector.m the gestures out of the motion, plain C, tested on the Mac (harness/head-gestures)
+// HeadGestures.x the motion listened to while the switch is on and Spotify plays, and what each
+// gesture does: Spotify's player skips, its collection platform saves the track
+// HeadGesturesSettings.m the page: the switch, the sensitivity, and learning one's own nod and shake
+//
+// HeadGestures.x owns the app's one CMHeadphoneMotionManager (iOS hands a manager's motion to one handler) and
+// lends its motion to other features through SGHeadMotionListen: Sing's spatial voice listens there.
+//
+// Everything applies at once, without a restart.
+// Threading: main thread only, but for the listeners' handlers.
+#import <CoreMotion/CoreMotion.h>
+#import <UIKit/UIKit.h>
+#import "SGHeadDetector.h"
+
+#define SGKeyHeadGestures @"spotifyglass.headgestures"
+// A percentage the thresholds are divided by: over 100 a smaller move counts.
+#define SGKeyHeadSensitivity @"spotifyglass.headgestures.sensitivity"
+// What learning set, in thousandths of a radian a second; unset or 0 is the detector's default.
+#define SGKeyHeadNod @"spotifyglass.headgestures.nod"
+#define SGKeyHeadShake @"spotifyglass.headgestures.shake"
+
+enum { SGHeadSensitivityMin = 50, SGHeadSensitivityMax = 200, SGHeadSensitivityStep = 10 };
+
+// From the switch, the sensitivity and learning: listens or stops, and reads the thresholds again.
+void SGHeadGesturesSettingsChanged(void);
+// Whether this iPhone can read headphone motion at all (iOS 14 and up; the headphones are another matter).
+BOOL SGHeadGesturesAvailable(void);
+// Listens for `seconds` whatever plays and answers the threshold learned for `axis` (0 when the motion held
+// no gesture) and how many samples came (0 when no headphones sent any, or motion is not allowed).
+void SGHeadGesturesLearn(SGHeadAxis axis, double seconds, void (^done)(double threshold, NSInteger samples));
+
+UIViewController *SGHeadGesturesSettingsPage(void);
+
+// Head motion for another feature, under `name`; a nil handler takes it out. While any listener is in, the
+// manager runs whatever the gestures' switch says. A handler is called on the motion's serial queue with every
+// motion, and with nil when the motion stops: the headphones gone, the manager stopped, or the listener taken out.
+void SGHeadMotionListen(NSString *name, void (^handler)(CMDeviceMotion *motion));
+// Asks for Motion & Fitness now, while a page is in front, if it was never asked and nothing listens yet.
+void SGHeadMotionAskPermission(void);
diff --git a/tweak/Sources/Shared/HeadGestures/HeadGestures.x b/tweak/Sources/Shared/HeadGestures/HeadGestures.x
new file mode 100644
index 00000000..9a3fa867
--- /dev/null
+++ b/tweak/Sources/Shared/HeadGestures/HeadGestures.x
@@ -0,0 +1,364 @@
+// AirPods gestures: CMHeadphoneMotionManager's attitudes fed to SGHeadDetector while the switch is on and
+// Spotify plays, or while the page learns a gesture, and each gesture done to Spotify's player. The same
+// manager's motion goes to the features listening through SGHeadMotionListen (Sing's spatial voice), and keeps
+// running for them with the switch off; the detector is fed only while the gestures want it.
+//
+// Skip is the player's own skipToNextTrackWithOptions: (Headers/SPTPlayer.h). Like adds the playing track to
+// the collection, which for a track is Liked Songs, through -addURL:showUIConfirmation:completion: of
+// Spotify's collection platform. Spotify 9.1.78 has four classes with that selector and with -stateProvider
+// (SPTCollectionPlatformImplementation, Collection_PlatformImpl's CollectionPlatformImpl and
+// CollectionPlatformMigration, AlignedCuration's ACUCollectionPlatform); whichever the app last reached
+// for is kept, weakly, the way Redesigned/Artist/ArtistFollow.x keeps its state provider. The lock
+// screen's like (LockScreenBaseRemoteControlPolicy's likeButtonPressedWithCompletion:identifier:) is not
+// used: it toggles, and a second nod would take the song out again.
+//
+// The cue is a tone played through Spotify's own playback session, mixed into the music in the AirPods:
+// a system sound would follow the Ring/Silent switch, and a phone in a pocket is often on silent. A rising
+// pair says the gesture was done, one low tone that it failed. A haptic comes with it while Spotify is in
+// front, and Spotify's own "Added to Liked Songs" toast shows only then too.
+#import <AudioToolbox/AudioToolbox.h>
+#import <AVFoundation/AVFoundation.h>
+#import <CoreMotion/CoreMotion.h>
+#import "Core/SGCore.h"
+#import "Shared/Lyrics/Lyrics.h"
+#import "Shared/Player/PlayerState.h"
+#import "HeadGestures.h"
+
+@protocol SGCollectionPlatform <NSObject>
+- (void)addURL:(NSURL *)url showUIConfirmation:(BOOL)show completion:(id)completion;
+@end
+
+// Tink, the passcode key's, should the cue's player not load.
+static const SystemSoundID kCueSound = 1057;
+// Each of the cue's tones, and how loud, of the most a sample holds; the player plays at the system volume.
+static const double kToneSeconds = 0.09;
+static const double kToneLevel = 0.5;
+static const double kMilli = 1000;
+
+static CMHeadphoneMotionManager *sg_manager;
+static NSOperationQueue *sg_queue; // serial: the detector, the learning buffer and the queue's copies live on it alone
+static SGHeadDetector sg_detector;
+static NSMutableData *sg_learned; // learning's samples, three doubles each
+static BOOL sg_learning;
+static BOOL sg_listening; // started with the handler, by updateListening
+static BOOL sg_detecting; // the gestures want the motion: learning, or the switch on and Spotify playing
+static BOOL sg_queueDetecting; // sg_detecting, on sg_queue
+static NSMutableDictionary<NSString *, void (^)(CMDeviceMotion *)> *sg_listeners; // other features', by name
+static NSArray<void (^)(CMDeviceMotion *)> *sg_queueListeners; // their handlers, on sg_queue
+static __weak id sg_platform;
+
+#pragma mark - the collection platform
+
+// Spotify's platforms wrap one another, so the one kept can change often: logged once per class.
+static void keepPlatform(id platform) {
+ if (platform == sg_platform || ![platform respondsToSelector:@selector(addURL:showUIConfirmation:completion:)]) return;
+ NSString *name = NSStringFromClass([platform class]);
+ static NSMutableSet<NSString *> *logged;
+ // Spotify asks for its state provider from any thread.
+ @synchronized (NSObject.class) {
+ sg_platform = platform;
+ if (!logged) logged = [NSMutableSet set];
+ if ([logged containsObject:name]) return;
+ [logged addObject:name];
+ }
+ SGLog(@"head gestures: collection platform %@", name);
+}
+
+%hook SPTCollectionPlatformImplementation
+- (id)stateProvider {
+ keepPlatform(self);
+ return %orig;
+}
+%end
+
+%hook _TtC23Collection_PlatformImpl22CollectionPlatformImpl
+- (id)stateProvider {
+ keepPlatform(self);
+ return %orig;
+}
+%end
+
+%hook _TtC23Collection_PlatformImpl27CollectionPlatformMigration
+- (id)stateProvider {
+ keepPlatform(self);
+ return %orig;
+}
+%end
+
+%hook _TtC26AlignedCuration_CommonImpl21ACUCollectionPlatform
+- (id)stateProvider {
+ keepPlatform(self);
+ return %orig;
+}
+%end
+
+#pragma mark - the gestures
+
+// A WAV in memory of short tones one after the other, each faded in and out so it does not click.
+static NSData *tones(NSArray<NSNumber *> *hertz) {
+ const uint32_t rate = 44100, perTone = (uint32_t)(rate * kToneSeconds), frames = perTone * (uint32_t)hertz.count;
+ NSMutableData *wav = [NSMutableData dataWithLength:44 + frames * sizeof(int16_t)];
+ uint8_t *header = wav.mutableBytes;
+ // RIFF, then the format chunk (PCM, one channel, 16-bit) and the data chunk; arm64 is little-endian, as WAV is.
+ uint32_t words[] = {0x46464952, 36 + frames * 2, 0x45564157, 0x20746d66, 16, 1 | 1 << 16, rate, rate * 2, 2 | 16 << 16,
+ 0x61746164, frames * 2};
+ memcpy(header, words, sizeof words);
+ int16_t *samples = (int16_t *)(header + 44);
+ for (NSUInteger tone = 0; tone < hertz.count; tone++) {
+ for (uint32_t i = 0; i < perTone; i++) {
+ double envelope = sin(M_PI * i / perTone);
+ samples[tone * perTone + i] = (int16_t)(kToneLevel * INT16_MAX * envelope * sin(2 * M_PI * hertz[tone].doubleValue * i / rate));
+ }
+ }
+ return wav;
+}
+
+// The cue's players live on a queue of their own: loading and starting one goes through the audio
+// session, which can hold the main thread up for a moment.
+static dispatch_queue_t cueQueue(void) {
+ static dispatch_queue_t queue;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ queue = dispatch_queue_create("spotifyglass.headgestures.cue", DISPATCH_QUEUE_SERIAL); });
+ return queue;
+}
+
+// A rising pair for a gesture done, one low tone for one that failed. On cueQueue only.
+static AVAudioPlayer *cuePlayer(BOOL worked) {
+ static AVAudioPlayer *done, *failed;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ NSError *error = nil;
+ done = [[AVAudioPlayer alloc] initWithData:tones(@[@880, @1320]) error:&error];
+ failed = [[AVAudioPlayer alloc] initWithData:tones(@[@330]) error:&error];
+ if (!done || !failed) SGLog(@"head gestures: no cue player, the system sound instead: %@", error);
+ [done prepareToPlay];
+ [failed prepareToPlay];
+ });
+ return worked ? done : failed;
+}
+
+static void cue(BOOL worked) {
+ dispatch_async(cueQueue(), ^{
+ AVAudioPlayer *player = cuePlayer(worked);
+ player.currentTime = 0;
+ if (![player play]) AudioServicesPlaySystemSound(kCueSound);
+ });
+ if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) return;
+ UINotificationFeedbackGenerator *generator = [UINotificationFeedbackGenerator new];
+ [generator notificationOccurred:worked ? UINotificationFeedbackTypeSuccess : UINotificationFeedbackTypeError];
+}
+
+static void like(void) {
+ NSString *uri = SGURIString(SGPlayerState().track.URI);
+ id platform = sg_platform;
+ // Only a track: an episode is saved another way, and an ad is nothing to save.
+ if (![uri hasPrefix:@"spotify:track:"] || !platform) {
+ SGLog(@"head gestures: no like for %@, platform %@", uri, platform);
+ cue(NO);
+ return;
+ }
+ BOOL inFront = UIApplication.sharedApplication.applicationState == UIApplicationStateActive;
+ // A block that reads no arguments: whatever the completion is called with, it is safe to ignore.
+ [(id<SGCollectionPlatform>)platform addURL:[NSURL URLWithString:uri] showUIConfirmation:inFront completion:^{
+ SGLog(@"head gestures: liked %@", uri);
+ }];
+ cue(YES);
+}
+
+static void skip(void) {
+ id player = SGKaraokePlayer();
+ if (![player respondsToSelector:@selector(skipToNextTrackWithOptions:)]) {
+ cue(NO);
+ return;
+ }
+ [(id<SPTPlayer>)player skipToNextTrackWithOptions:nil];
+ cue(YES);
+}
+
+// What learning stored for `key`, or the detector's default.
+static double learnedOr(NSString *key, double fallback) {
+ NSInteger learned = SGInt(key, 0);
+ return learned > 0 ? learned / kMilli : fallback;
+}
+
+static double threshold(NSString *key, double fallback) {
+ double sensitivity = MAX(SGHeadSensitivityMin, MIN(SGHeadSensitivityMax, SGInt(SGKeyHeadSensitivity, 100))) / 100.0;
+ return learnedOr(key, fallback) / sensitivity;
+}
+
+#pragma mark - listening
+
+// Nil to the other features' handlers: the motion has stopped. On sg_queue.
+static void motionStopped(void) {
+ for (void (^handler)(CMDeviceMotion *) in sg_queueListeners) handler(nil);
+}
+
+static void sample(CMDeviceMotion *motion) {
+ for (void (^handler)(CMDeviceMotion *) in sg_queueListeners) handler(motion);
+ double time = motion.timestamp, pitch = motion.attitude.pitch, yaw = motion.attitude.yaw;
+ if (sg_learned) {
+ double values[3] = {time, pitch, yaw};
+ [sg_learned appendBytes:values length:sizeof values];
+ return;
+ }
+ // Running for another feature alone, the gestures off or Spotify paused: no gestures.
+ if (!sg_queueDetecting) return;
+ SGHeadGesture gesture = SGHeadDetectorFeed(&sg_detector, time, pitch, yaw);
+ if (gesture == SGHeadGestureNone) return;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ SGLog(@"head gestures: %@", gesture == SGHeadGestureDoubleNod ? @"double nod" : @"shake");
+ if (sg_learning || !SGFlag(SGKeyHeadGestures, NO)) return;
+ if (gesture == SGHeadGestureDoubleNod) like();
+ else skip();
+ });
+}
+
+// The headphones taken out or off: the listeners hear that their motion stopped. Called on the queue the motion
+// comes on.
+@interface SGHeadMotionDelegate : NSObject <CMHeadphoneMotionManagerDelegate>
+@end
+
+@implementation SGHeadMotionDelegate
+- (void)headphoneMotionManagerDidDisconnect:(CMHeadphoneMotionManager *)manager {
+ [sg_queue addOperationWithBlock:^{ motionStopped(); }];
+}
+@end
+
+static CMHeadphoneMotionManager *manager(void) {
+ static SGHeadMotionDelegate *delegate; // the manager holds its delegate weakly
+ if (!sg_manager) {
+ sg_manager = [CMHeadphoneMotionManager new];
+ sg_queue = [NSOperationQueue new];
+ sg_queue.maxConcurrentOperationCount = 1;
+ sg_queue.qualityOfService = NSQualityOfServiceUserInitiated;
+ delegate = [SGHeadMotionDelegate new];
+ sg_manager.delegate = delegate;
+ }
+ return sg_manager;
+}
+
+// A fresh detector at the thresholds set now.
+static void resetDetector(void) {
+ double nod = threshold(SGKeyHeadNod, SGHeadDefaultNod), shake = threshold(SGKeyHeadShake, SGHeadDefaultShake);
+ [sg_queue addOperationWithBlock:^{ SGHeadDetectorReset(&sg_detector, nod, shake); }];
+}
+
+// The gestures want the motion while learning, or while the switch is on and Spotify plays; the manager runs
+// then and while another feature listens. It sends nothing until headphones that track motion are in, so
+// starting it with none costs nothing.
+static void updateListening(void) {
+ // isPlaying stays on while a track is loaded and paused; isPaused is what tells.
+ SPTPlayerState *state = SGPlayerState();
+ BOOL detect = sg_learning || (SGFlag(SGKeyHeadGestures, NO) && state.isPlaying && !state.isPaused);
+ if (detect != sg_detecting) {
+ sg_detecting = detect;
+ manager();
+ if (detect) {
+ resetDetector();
+ // Loaded now rather than with the first gesture's cue, which then plays on time.
+ dispatch_async(cueQueue(), ^{ cuePlayer(YES); });
+ }
+ [sg_queue addOperationWithBlock:^{ sg_queueDetecting = detect; }];
+ }
+ BOOL listen = detect || sg_listeners.count;
+ if (listen == sg_listening) return;
+ sg_listening = listen;
+ SGLog(@"head gestures: %@", listen ? @"listening" : @"stopped");
+ if (!listen) {
+ [sg_manager stopDeviceMotionUpdates];
+ return;
+ }
+ [sg_manager startDeviceMotionUpdatesToQueue:sg_queue withHandler:^(CMDeviceMotion *motion, NSError *error) {
+ if (motion) sample(motion);
+ }];
+}
+
+void SGHeadMotionListen(NSString *name, void (^handler)(CMDeviceMotion *motion)) {
+ if (!sg_listeners) sg_listeners = [NSMutableDictionary dictionary];
+ void (^old)(CMDeviceMotion *) = sg_listeners[name];
+ if (!old && !handler) return;
+ sg_listeners[name] = [handler copy];
+ manager();
+ NSArray<void (^)(CMDeviceMotion *)> *handlers = sg_listeners.allValues;
+ [sg_queue addOperationWithBlock:^{
+ sg_queueListeners = handlers;
+ if (old) old(nil);
+ }];
+ updateListening();
+}
+
+void SGHeadMotionAskPermission(void) {
+ // Motion's permission is asked the first time the manager starts. With nothing playing that would be the
+ // first song, maybe from the lock screen, so a page asks while it is in front.
+ if (sg_listening || CMHeadphoneMotionManager.authorizationStatus != CMAuthorizationStatusNotDetermined) return;
+ [manager() startDeviceMotionUpdates];
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{
+ if (!sg_listening) [sg_manager stopDeviceMotionUpdates];
+ });
+}
+
+void SGHeadGesturesSettingsChanged(void) {
+ if (sg_manager) resetDetector();
+ updateListening();
+ if (SGFlag(SGKeyHeadGestures, NO)) SGHeadMotionAskPermission();
+}
+
+BOOL SGHeadGesturesAvailable(void) {
+ return manager().deviceMotionAvailable;
+}
+
+void SGHeadGesturesLearn(SGHeadAxis axis, double seconds, void (^done)(double threshold, NSInteger samples)) {
+ if (sg_learning) {
+ done(0, 0);
+ return;
+ }
+ sg_learning = YES;
+ manager();
+ // The check after learning runs with the other gesture as it is set now, at a sensitivity of 100%.
+ double other = axis == SGHeadAxisPitch ? learnedOr(SGKeyHeadShake, SGHeadDefaultShake) : learnedOr(SGKeyHeadNod, SGHeadDefaultNod);
+ [sg_queue addOperationWithBlock:^{ sg_learned = [NSMutableData data]; }];
+ SGHeadGesturesSettingsChanged();
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
+ [sg_queue addOperationWithBlock:^{
+ NSData *data = sg_learned;
+ sg_learned = nil;
+ const double *values = data.bytes;
+ int count = (int)(data.length / (3 * sizeof(double)));
+ double *time = malloc(sizeof(double) * MAX(count, 1)), *pitch = malloc(sizeof(double) * MAX(count, 1)), *yaw = malloc(sizeof(double) * MAX(count, 1));
+ for (int i = 0; i < count; i++) {
+ time[i] = values[3 * i];
+ pitch[i] = values[3 * i + 1];
+ yaw[i] = values[3 * i + 2];
+ }
+ double learned = SGHeadLearn(time, pitch, yaw, count, axis, other);
+ free(time);
+ free(pitch);
+ free(yaw);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ SGLog(@"head gestures: learned %.2f rad/s for %@ from %d samples", learned, axis == SGHeadAxisPitch ? @"nod" : @"shake", count);
+ if (learned > 0) SGSetInt(axis == SGHeadAxisPitch ? SGKeyHeadNod : SGKeyHeadShake, lround(learned * kMilli));
+ sg_learning = NO;
+ SGHeadGesturesSettingsChanged();
+ done(learned, count);
+ });
+ }];
+ });
+}
+
+// Playing or not, from the one player hook every feature shares.
+@interface SGHeadGesturesObserver : NSObject <SGPlayerStateObserver>
+@end
+
+@implementation SGHeadGesturesObserver
+- (void)playerStateDidChange:(SPTPlayerState *)state {
+ updateListening();
+}
+@end
+
+%ctor {
+ %init;
+ SGRequireClasses(@[@"SPTCollectionPlatformImplementation", @"_TtC23Collection_PlatformImpl22CollectionPlatformImpl"]);
+ static SGHeadGesturesObserver *observer;
+ observer = [SGHeadGesturesObserver new];
+ SGAddPlayerStateObserver(observer);
+}
diff --git a/tweak/Sources/Shared/HeadGestures/HeadGesturesSettings.m b/tweak/Sources/Shared/HeadGestures/HeadGesturesSettings.m
new file mode 100644
index 00000000..e97c14ab
--- /dev/null
+++ b/tweak/Sources/Shared/HeadGestures/HeadGesturesSettings.m
@@ -0,0 +1,114 @@
+// The AirPods gestures page: the switch, the sensitivity, and learning one's own nod and shake. Learning
+// listens for a few seconds under an alert that says what to do, then says what it found.
+#import "Core/SGCore.h"
+#import "Settings/SGModPage.h"
+#import "Settings/SGPageStyle.h"
+#import "HeadGestures.h"
+
+// Long enough for a slow double nod and a breath before it.
+static const double kLearnSeconds = 4;
+
+static NSString *learnedValue(NSString *key) {
+ return SGInt(key, 0) > 0 ? @"Learned" : @"Default";
+}
+
+static void say(NSString *title, NSString *message) {
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
+ [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
+ [SGTopController() presentViewController:alert animated:YES completion:nil];
+}
+
+// Set while learning listens, a cancelled try too: SGHeadGesturesLearn runs its seconds out either way.
+static BOOL sg_listening;
+
+static void learn(SGHeadAxis axis) {
+ if (!SGHeadGesturesAvailable()) {
+ say(@"No head tracking", @"This iPhone cannot read the motion of headphones.");
+ return;
+ }
+ if (sg_listening) {
+ say(@"Still listening", @"The last try is finishing. Try again in a few seconds.");
+ return;
+ }
+ BOOL nod = axis == SGHeadAxisPitch;
+ NSString *key = nod ? SGKeyHeadNod : SGKeyHeadShake;
+ // SGHeadGesturesLearn stores what it found itself, so a cancelled try puts the old size back.
+ NSInteger before = SGInt(key, 0);
+ __block BOOL cancelled = NO;
+ UIAlertController *asking = [UIAlertController alertControllerWithTitle:nod ? @"Nod twice" : @"Shake your head"
+ message:nod ? @"Now, the way you would to like a song." : @"Now, the way you would to skip a song."
+ preferredStyle:UIAlertControllerStyleAlert];
+ [asking addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { cancelled = YES; }]];
+ [SGTopController() presentViewController:asking animated:YES completion:^{
+ sg_listening = YES;
+ SGHeadGesturesLearn(axis, kLearnSeconds, ^(double threshold, NSInteger samples) {
+ sg_listening = NO;
+ if (cancelled) {
+ if (SGInt(key, 0) != before) {
+ SGSetInt(key, before);
+ SGHeadGesturesSettingsChanged();
+ }
+ return;
+ }
+ [asking dismissViewControllerAnimated:YES completion:^{
+ if (samples == 0)
+ say(@"No motion came", @"Put in AirPods that track head motion (AirPods Pro, AirPods 3 or later, "
+ "AirPods Max), and allow Spotify in Settings > Privacy & Security > Motion & Fitness.");
+ else if (threshold <= 0)
+ say(nod ? @"No double nod found" : @"No shake found",
+ nod ? @"Nod twice, down and up, a little quicker." : @"Shake your head left and right, a little quicker.");
+ else
+ say(@"Learned", nod ? @"A double nod this size likes the song." : @"A shake this size skips the song.");
+ }];
+ });
+ }];
+}
+
+// Both learned sizes back to the defaults, asked first. With nothing learned there is nothing to ask.
+static void forget(void) {
+ if (SGInt(SGKeyHeadNod, 0) <= 0 && SGInt(SGKeyHeadShake, 0) <= 0) {
+ say(@"Nothing learned yet", @"Your nod and your shake use the default sizes.");
+ return;
+ }
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Forget your nod and shake?"
+ message:@"Both go back to the default sizes. You can learn them again." preferredStyle:UIAlertControllerStyleAlert];
+ [alert addAction:[UIAlertAction actionWithTitle:@"Forget" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+ SGSetInt(SGKeyHeadNod, 0);
+ SGSetInt(SGKeyHeadShake, 0);
+ SGHeadGesturesSettingsChanged();
+ }]];
+ [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
+ [SGTopController() presentViewController:alert animated:YES completion:nil];
+}
+
+UIViewController *SGHeadGesturesSettingsPage(void) {
+ SGModRow *toggle = SGOptionRow(@"AirPods gestures", @"Nod twice to like the song, shake your head to skip it", SGKeyHeadGestures);
+ toggle.changed = ^(BOOL on) { SGHeadGesturesSettingsChanged(); };
+ BOOL (^on)(void) = ^BOOL { return SGFlag(SGKeyHeadGestures, NO); };
+
+ SGModRow *sensitivity = SGSliderRow(@"Sensitivity", @"Higher counts a smaller move",
+ SGHeadSensitivityMin, SGHeadSensitivityMax, SGHeadSensitivityStep,
+ ^double { return MAX(SGHeadSensitivityMin, MIN(SGHeadSensitivityMax, SGInt(SGKeyHeadSensitivity, 100))); },
+ ^(double value) {
+ SGSetInt(SGKeyHeadSensitivity, lround(value));
+ SGHeadGesturesSettingsChanged();
+ },
+ ^NSString *(double value) { return [NSString stringWithFormat:@"%ld%%", lround(value)]; });
+ sensitivity.visible = on;
+
+ SGModRow *nod = SGStatActionRow(@"Learn your nod", nil, ^NSString *{ return learnedValue(SGKeyHeadNod); }, ^{ learn(SGHeadAxisPitch); });
+ SGModRow *shake = SGStatActionRow(@"Learn your shake", nil, ^NSString *{ return learnedValue(SGKeyHeadShake); }, ^{ learn(SGHeadAxisYaw); });
+ // Shown whenever the switch is on: SGModPage asks `visible` again only when a switch flips or the page
+ // comes back, not after an alert, so a row hidden until something is learned would stay hidden.
+ SGModRow *forgetRow = SGActionRow(@"Forget what it learned", nil, ^{ forget(); });
+ forgetRow.color = SGRed();
+ for (SGModRow *row in @[nod, shake, forgetRow]) row.visible = on;
+
+ return [[SGModPage alloc] initWithTitle:@"AirPods gestures" intro:nil sections:@[
+ SGSection(nil, @[SGWithSymbol(toggle, @"airpods.pro"), sensitivity]),
+ SGNotedSection(@"Learn", @[nod, shake, forgetRow],
+ @"Learning listens for a few seconds and sets how big a move counts, from yours. The gestures work while "
+ "Spotify plays through headphones that track head motion. A tone in the music confirms each one, a rising pair when "
+ "it worked and a low one when it did not, with the iPhone on silent too."),
+ ] footer:nil];
+}
diff --git a/tweak/Sources/Shared/HeadGestures/SGHeadDetector.h b/tweak/Sources/Shared/HeadGestures/SGHeadDetector.h
new file mode 100644
index 00000000..f22025be
--- /dev/null
+++ b/tweak/Sources/Shared/HeadGestures/SGHeadDetector.h
@@ -0,0 +1,76 @@
+// AirPods gestures' eye: the head's attitude, as the headphones report it, turned into a double nod or a
+// shake of the head.
+//
+// It works on how fast the head turns, worked out from one attitude to the next, so where the head
+// rests does not matter and nothing drifts. A swing is the head turning one way faster than the axis's
+// threshold; the next counts only once it turns the other way. Swings run together into a burst until
+// the head has been still (under both thresholds) for a moment, and then the burst is read:
+//
+// - a double nod is two downs and two ups of the pitch (4 or 5 swings, one for a settle), with at most
+// one swing sideways;
+// - a shake is 3 to 6 swings of the yaw with at most one of the pitch, quicker than a nod pair: a
+// glance left and right turns as far but holds at each side, and the hold ends the burst.
+//
+// A burst longer than a gesture takes is nobody's gesture (walking, running, looking around), and a gap
+// in the samples (the headphones taken out, the updates stopped) starts over. After a gesture the
+// detector waits a second before it takes another, so a gesture's own settle cannot fire a second one.
+//
+// Learning reads a few seconds of the user doing one gesture: the swings of its axis over a low floor,
+// and the threshold set under the weakest of the swings the gesture needs, so the next one of the same
+// size clears it with room to spare. The recording is then read again by a detector set to that
+// threshold, and the threshold is kept only if the gesture fires. Teaching records five of the gesture,
+// one at a time: each one's threshold is tried on all five, and the one that catches the most is kept,
+// if it catches all of them but one at least.
+//
+// Plain C over a struct the caller owns, Foundation only, so the harness compiles it on the Mac as is.
+#import <Foundation/Foundation.h>
+
+typedef NS_ENUM(NSInteger, SGHeadGesture) {
+ SGHeadGestureNone,
+ SGHeadGestureDoubleNod,
+ SGHeadGestureShake,
+};
+
+typedef NS_ENUM(NSInteger, SGHeadAxis) {
+ SGHeadAxisPitch, // a nod
+ SGHeadAxisYaw, // a shake
+};
+
+// Radians a second. The defaults are for someone who has not taught it yet: a brisk nod turns at 2 to
+// 3, a walking head bobs at under 0.7.
+#define SGHeadDefaultNod 1.1
+#define SGHeadDefaultShake 1.4
+// What learning will set at most and at least: under the least a walk would start to count.
+#define SGHeadMinThreshold 0.8
+#define SGHeadMaxThreshold 4.0
+
+typedef struct {
+ double nodThreshold, shakeThreshold;
+ double lastTime, lastPitch, lastYaw;
+ bool hasLast;
+ int pitchSign, yawSign; // the way the last swing went, 0 before a burst
+ int pitchSwings, yawSwings;
+ double burstStart, lastActive; // the first swing, the last sample over either threshold
+ double readyAt; // no gesture before this time
+} SGHeadDetector;
+
+void SGHeadDetectorReset(SGHeadDetector *detector, double nodThreshold, double shakeThreshold);
+// One sample: seconds, then the attitude's pitch and yaw in radians. Answers the gesture it completes.
+SGHeadGesture SGHeadDetectorFeed(SGHeadDetector *detector, double time, double pitch, double yaw);
+
+// The threshold for `axis` learned from `count` samples of one gesture, or 0 when they do not hold
+// one (too few swings, too slow to tell from a walk, or a move the detector does not read as the gesture
+// at any threshold under its swings). `otherThreshold` is the other axis's, which the check runs with.
+double SGHeadLearn(const double *time, const double *pitch, const double *yaw, int count, SGHeadAxis axis, double otherThreshold);
+
+// One recording of a gesture: `count` samples of seconds, pitch and yaw.
+typedef struct {
+ const double *time, *pitch, *yaw;
+ int count;
+} SGHeadRecording;
+
+// The threshold for `axis` learned from several recordings of the gesture, one each (the teaching sheet's
+// five). What each teaches on its own (SGHeadLearn) is a candidate; the one the detector, set to it, fires
+// on in the most recordings wins, the lowest of a tie, so the smallest of them still counts. 0 when no
+// candidate fires in `atLeast` of them.
+double SGHeadLearnSamples(const SGHeadRecording *recordings, int n, SGHeadAxis axis, double otherThreshold, int atLeast);
diff --git a/tweak/Sources/Shared/HeadGestures/SGHeadDetector.m b/tweak/Sources/Shared/HeadGestures/SGHeadDetector.m
new file mode 100644
index 00000000..8c92646f
--- /dev/null
+++ b/tweak/Sources/Shared/HeadGestures/SGHeadDetector.m
@@ -0,0 +1,171 @@
+#import "SGHeadDetector.h"
+
+// Longer between two samples than this and the head's speed is a guess: start over. AirPods send 25 a
+// second.
+static const double kGap = 0.3;
+// Still for this long and the burst is over.
+static const double kQuiet = 0.35;
+// The longest a gesture takes, first swing to last. A shake is quicker than two nods.
+static const double kNodLength = 1.6;
+static const double kShakeLength = 1.2;
+static const double kCooldown = 1.0;
+// Learning counts swings over this, under the least threshold, so a slow learner's swings are seen,
+// and sets the threshold this far under the weakest swing the gesture needs.
+static const double kLearnFloor = 0.5;
+static const double kLearnMargin = 0.6;
+// The spacing of the still samples learning adds after a recording, AirPods' own.
+static const double kStillStep = 0.04;
+
+static double wrapAngle(double angle) {
+ return remainder(angle, 2 * M_PI);
+}
+
+static void endBurst(SGHeadDetector *d) {
+ d->pitchSign = d->yawSign = 0;
+ d->pitchSwings = d->yawSwings = 0;
+}
+
+void SGHeadDetectorReset(SGHeadDetector *d, double nodThreshold, double shakeThreshold) {
+ memset(d, 0, sizeof *d);
+ d->nodThreshold = nodThreshold;
+ d->shakeThreshold = shakeThreshold;
+}
+
+// Counts a swing when `rate` is over `threshold` the other way from the last one.
+static bool swing(double rate, double threshold, int *sign, int *swings) {
+ if (fabs(rate) <= threshold) return false;
+ int way = rate > 0 ? 1 : -1;
+ if (way != *sign) {
+ *sign = way;
+ (*swings)++;
+ }
+ return true;
+}
+
+static SGHeadGesture readBurst(const SGHeadDetector *d) {
+ double length = d->lastActive - d->burstStart;
+ if (d->pitchSwings >= 4 && d->pitchSwings <= 5 && d->yawSwings <= 1 && length <= kNodLength) return SGHeadGestureDoubleNod;
+ if (d->yawSwings >= 3 && d->yawSwings <= 6 && d->pitchSwings <= 1 && length <= kShakeLength) return SGHeadGestureShake;
+ return SGHeadGestureNone;
+}
+
+SGHeadGesture SGHeadDetectorFeed(SGHeadDetector *d, double time, double pitch, double yaw) {
+ double dt = time - d->lastTime;
+ bool fresh = d->hasLast && dt > 0 && dt <= kGap;
+ double pitchRate = fresh ? (pitch - d->lastPitch) / dt : 0;
+ double yawRate = fresh ? wrapAngle(yaw - d->lastYaw) / dt : 0;
+ d->lastTime = time;
+ d->lastPitch = pitch;
+ d->lastYaw = yaw;
+ d->hasLast = true;
+ if (!fresh) {
+ endBurst(d);
+ return SGHeadGestureNone;
+ }
+
+ bool inBurst = d->pitchSwings || d->yawSwings;
+ bool pitchActive = swing(pitchRate, d->nodThreshold, &d->pitchSign, &d->pitchSwings);
+ bool yawActive = swing(yawRate, d->shakeThreshold, &d->yawSign, &d->yawSwings);
+ if (pitchActive || yawActive) {
+ if (!inBurst) d->burstStart = time;
+ d->lastActive = time;
+ return SGHeadGestureNone;
+ }
+ if (!inBurst || time - d->lastActive < kQuiet) return SGHeadGestureNone;
+
+ SGHeadGesture gesture = readBurst(d);
+ endBurst(d);
+ // A burst that began inside the cooldown is the last gesture's settle, or a repeat too quick to mean.
+ if (gesture == SGHeadGestureNone || d->burstStart < d->readyAt) return SGHeadGestureNone;
+ d->readyAt = time + kCooldown;
+ return gesture;
+}
+
+static int descending(const void *a, const void *b) {
+ double x = *(const double *)a, y = *(const double *)b;
+ return x < y ? 1 : x > y ? -1 : 0;
+}
+
+// Whether the detector, at these thresholds, fires the gesture of `axis` on the samples and nothing else.
+// Still samples follow the last one, so a gesture made at the very end of the recording is read too.
+static bool fires(const double *time, const double *pitch, const double *yaw, int count, SGHeadAxis axis,
+ double nodThreshold, double shakeThreshold) {
+ if (count < 1) return false;
+ SGHeadGesture want = axis == SGHeadAxisPitch ? SGHeadGestureDoubleNod : SGHeadGestureShake;
+ SGHeadDetector d;
+ SGHeadDetectorReset(&d, nodThreshold, shakeThreshold);
+ bool wanted = false;
+ for (int i = 0; i < count; i++) {
+ SGHeadGesture gesture = SGHeadDetectorFeed(&d, time[i], pitch[i], yaw[i]);
+ if (gesture != SGHeadGestureNone && gesture != want) return false;
+ wanted = wanted || gesture == want;
+ }
+ for (double t = time[count - 1] + kStillStep; t <= time[count - 1] + kQuiet + 2 * kStillStep; t += kStillStep) {
+ SGHeadGesture gesture = SGHeadDetectorFeed(&d, t, pitch[count - 1], yaw[count - 1]);
+ if (gesture != SGHeadGestureNone && gesture != want) return false;
+ wanted = wanted || gesture == want;
+ }
+ return wanted;
+}
+
+double SGHeadLearn(const double *time, const double *pitch, const double *yaw, int count, SGHeadAxis axis, double otherThreshold) {
+ const double *angle = axis == SGHeadAxisPitch ? pitch : yaw;
+ int needed = axis == SGHeadAxisPitch ? 4 : 3;
+ double *peaks = calloc(count > 0 ? count : 1, sizeof *peaks);
+ int lobes = 0, sign = 0;
+ for (int i = 1; i < count; i++) {
+ double dt = time[i] - time[i - 1];
+ if (dt <= 0 || dt > kGap) {
+ sign = 0;
+ continue;
+ }
+ double rate = wrapAngle(angle[i] - angle[i - 1]) / dt;
+ if (fabs(rate) <= kLearnFloor) continue;
+ int way = rate > 0 ? 1 : -1;
+ if (way != sign) {
+ sign = way;
+ peaks[lobes++] = 0;
+ }
+ peaks[lobes - 1] = fmax(peaks[lobes - 1], fabs(rate));
+ }
+ double weakest = 0;
+ if (lobes >= needed) {
+ qsort(peaks, lobes, sizeof *peaks, descending);
+ weakest = peaks[needed - 1];
+ }
+ free(peaks);
+ // Too slow to keep clear of a walk with any margin: not learned.
+ if (weakest * kLearnMargin < SGHeadMinThreshold * 0.75) return 0;
+ // A threshold is kept only once the detector, set to it, finds the gesture in what was recorded: a
+ // low one can let the settle's swings count, which makes a nod pair too many swings, so a closer one
+ // is tried before giving up. Too slow or too many moves for the detector, nothing is learned.
+ for (double margin = kLearnMargin; margin < 0.95; margin += 0.1) {
+ double threshold = fmin(SGHeadMaxThreshold, fmax(SGHeadMinThreshold, weakest * margin));
+ double nod = axis == SGHeadAxisPitch ? threshold : otherThreshold;
+ double shake = axis == SGHeadAxisPitch ? otherThreshold : threshold;
+ if (fires(time, pitch, yaw, count, axis, nod, shake)) return threshold;
+ }
+ return 0;
+}
+
+double SGHeadLearnSamples(const SGHeadRecording *recordings, int n, SGHeadAxis axis, double otherThreshold, int atLeast) {
+ double best = 0;
+ int bestFired = 0;
+ for (int c = 0; c < n; c++) {
+ const SGHeadRecording *own = &recordings[c];
+ double candidate = SGHeadLearn(own->time, own->pitch, own->yaw, own->count, axis, otherThreshold);
+ if (candidate <= 0) continue;
+ double nod = axis == SGHeadAxisPitch ? candidate : otherThreshold;
+ double shake = axis == SGHeadAxisPitch ? otherThreshold : candidate;
+ int fired = 0;
+ for (int i = 0; i < n; i++) {
+ const SGHeadRecording *r = &recordings[i];
+ fired += fires(r->time, r->pitch, r->yaw, r->count, axis, nod, shake);
+ }
+ if (fired > bestFired || (fired == bestFired && candidate < best)) {
+ best = candidate;
+ bestFired = fired;
+ }
+ }
+ return bestFired >= atLeast ? best : 0;
+}