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: Vibrations settings, a strength for the controls' taps and for Music Haptics, and what Music Haptics follows

Vojtěch Škopek94058a06536f
diff --git a/docs/tweaks.md b/docs/tweaks.md
index d7f0c01c..6c57c809 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -8,7 +8,8 @@
functions Spotify imports hooked by rebinding its import slots (SGRebind.h)
tweak/Sources/Headers/ reverse-engineered Spotify classes, one header each, only the selectors used
tweak/Sources/Settings/ the Mod Settings framework: SGPage (a page on Spotify's stack), SGModPage (sections
- of rows), SGPageStyle (Spotify's list look), SGGlowSwitch
+ of rows: switches, choices, sliders, links, and rows shown only while a switch
+ is on), SGPageStyle (Spotify's list look), SGGlowSwitch
tweak/Sources/Shared/ what works the same with either look, see Layers below
tweak/Sources/Native/ tweaks on Spotify's own screens, running only while Redesigned UI is off
tweak/Sources/Redesigned/ the redesign, running only while Redesigned UI is on
@@ -159,11 +160,14 @@ Redesigned:
files). Laid out on the Mac against harness/album/
Haptics/ Vibrations (Haptics.h lists its files): a tap of UIKit's feedback generators for the player's and the now
playing bar's controls, the scrubber's tenths and ends, cover swipes, gestures and the lyrics page's tap to
- seek (ControlHaptics.x, SGRFeedback.m); and Music Haptics, Core Haptics playing along with the song:
- Spotify's import of AudioOutputUnitStart is rebound so its RemoteIO output unit gets a render notify, the
- samples go through a drum and bass analyzer on the render thread (SGRMusicAnalyzer.m, plain C), and a
- thread of its own schedules the taps and the rumble for when the sound is heard (MusicHaptics.x). Both
- switches apply at once; nothing plays while Spotify is not the active app
+ seek, at the strength set for them (ControlHaptics.x, SGRFeedback.m); and Music Haptics, Core Haptics
+ playing along with the song: Spotify's import of AudioOutputUnitStart is rebound so its RemoteIO output
+ unit gets a render notify, the samples, in the unit's output format (the hardware's), go through a drum
+ and bass analyzer on the render thread (SGRMusicAnalyzer.m, plain C), and a thread of its own schedules
+ the taps and the rumble for when the sound is heard, at their strength and leaving out what Follows
+ leaves out (MusicHaptics.x). Everything applies at once; nothing plays while Spotify is not the active
+ app. The analyzer is scored on the Mac against harness/haptics/, the hook in the simulator against its
+ sim/, the settings against harness/haptics-page/
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
@@ -218,9 +222,13 @@ naming the source in the redesign, the lock screen, and glass lyrics in the nati
in the native look also Now playing bar (its device button and its flags), Queue & devices, and
Spotify's own player screen (artwork background, glass header buttons, Disable Canvas and the sheet,
header, slider and sticky header flags, the cards under the player and the lyrics preview and player
-buttons to hide); in the redesign instead Now playing (its device button), Vibrations, Controls (on until switched off) and Music Haptics
-(off until switched on, with an ⓘ saying it follows the sound this iPhone plays while Spotify is open), both
-applying straight away. Live Activity, in the redesign only: its switch and which view it shows, Lyrics, Queue or Control menu, both
+buttons to hide); in the redesign instead Now playing (its device button) and Vibrations, a card for
+Controls (on until switched off) and one for Music Haptics (off until switched on, with an ⓘ saying it
+follows the sound this iPhone plays while Spotify is open), each opening out while its switch is on:
+Controls into its Strength (10 to 100%, a tap at the new strength with each step), Music Haptics into its
+Strength (20 to 200%, 100% being how it first shipped) and Follows, Everything (a tap on each kick and
+snare and a rumble under the bass), Beat (the taps without the rumble) or Bass (the kicks' taps and the
+rumble), all applying straight away. Live Activity, in the redesign only: its switch and which view it shows, Lyrics, Queue or Control menu, both
applying straight away, the row reading out the view or Off. Audio effects, in either look (Shared/JamesDSP/JamesDSPPage.m):
JamesDSP's switch with what the engine is doing under it, then a card per effect in RootlessJamesDSP's order, each
opening out into its sliders, choices, curve or file library while its switch is on, everything applying as it
@@ -261,8 +269,8 @@ icons alone and applies straight away too.
Spotify's paint, and end with `%ctor { %init; SGRequireClasses(@[...]); }`, gated first on the layer's look
(`SGNativeUI()` or `SGRedesignedUI()`) in Native/ and Redesigned/.
4. Add `<Feature>Settings.m` returning an `SGModPage` of `SGSection`s of `SGSwitchRow`/`SGHideRow`/
- `SGFlagRow` (Settings/SGModPage.h), and put it on the page of the part of Spotify it changes in `App/Pages.m`
- or `App/ModSettings.x`.
+ `SGFlagRow`/`SGChoiceRow`/`SGSliderRow` (Settings/SGModPage.h), and put it on the page of the part of
+ Spotify it changes in `App/Pages.m` or `App/ModSettings.x`.
5. `make install`. Log lines are prefixed `[spotifyglass]`. A FLEX build serves the visible screen's
tree on the phone's port 8085, which `make trees` reaches over USB through iproxy.
diff --git a/harness/haptics-page/README.md b/harness/haptics-page/README.md
new file mode 100644
index 00000000..32240352
--- /dev/null
+++ b/harness/haptics-page/README.md
@@ -0,0 +1,28 @@
+# Vibrations settings harness
+
+Mod Settings > Player's Vibrations cards (`tweak/Sources/Redesigned/Haptics/HapticsSettings.m`) on an SGModPage laid
+out like the Player page in the redesign: the real Settings/ framework (its slider row and its rows shown while a
+switch is on), the real control taps (`SGRFeedback.m`, which the simulator plays silently), and `stubs.m` for Music
+Haptics' engine, which logs each call with the strength and the Follows choice the hook would read.
+
+ THEOS=$HOME/theos ./build.sh
+ xcrun simctl install <udid> build/HapticsPageHarness.app
+ xcrun simctl launch <udid> com.vojta.hapticspageharness controls-off music follows=1 bottom dump
+ xcrun simctl io <udid> screenshot shot.png
+
+Other agents use the simulator too: make a device of your own (`xcrun simctl create`) and address it by UDID.
+Every launch clears the `spotifyglass.redesign.haptics` keys first unless `keep` is on the line; `main.m` lists the
+setup words (`controls-off`, `music`, `follows=<n>`, `slow`) and the actions, played one every 0.7 s from 1 s in:
+flipping a switch, dragging a slider and letting go, VoiceOver's swipe on one, the ⓘ, a tap on a row (the Follows
+row, then a name in its list), and `dump`, which logs the stored keys, what the hooks read and the rows shown:
+
+ xcrun simctl launch --console-pty <udid> com.vojta.hapticspageharness controls-off bottom toggle=2.0 slide=2.1:40 \
+ toggle=3.0 slide=3.1:150 swipe=3.1:-3 dump select=3.2 select=0.1 dump
+
+2026-09-19, iPhone 17 Pro (402pt) and iPhone 13 mini (375pt) on iOS 26.5: both switches off, Controls on with its
+Strength, Music Haptics on in each Follows choice, the Follows list with a line under each choice, and the rows
+fading in under a switch (`slow`); Controls at 40%, Music Haptics at 150% then 120% by VoiceOver and Beat stored
+under their keys and read back by the hooks. The Audio effects page and an SGModPage without shown-while rows
+(`harness/jamesdsp-page`, `push=reference`) draw the same pixels as before the slider and visibility were added.
+
+What it does not cover: a real finger on the slider, and how any strength feels, which only a phone can tell.
diff --git a/harness/haptics-page/build.sh b/harness/haptics-page/build.sh
new file mode 100755
index 00000000..0c182e02
--- /dev/null
+++ b/harness/haptics-page/build.sh
@@ -0,0 +1,35 @@
+#!/bin/sh
+# Builds the Vibrations settings harness for the simulator: Redesigned/Haptics' settings and control taps, the
+# Settings/ framework as they are in the tweak, stubs.m for Music Haptics.
+set -e
+SRC=$(cd "$(dirname "$0")/../../tweak/Sources" && pwd)
+OUT=$(dirname "$0")/build
+rm -rf "$OUT"; mkdir -p "$OUT/HapticsPageHarness.app"
+
+SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
+xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O0 \
+ -I"$SRC" -isysroot "$SDK" -Wall -Werror -Wno-deprecated-declarations \
+ "$(dirname "$0")/main.m" "$(dirname "$0")/stubs.m" \
+ "$SRC"/Redesigned/Haptics/HapticsSettings.m "$SRC"/Redesigned/Haptics/SGRFeedback.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 \
+ -o "$OUT/HapticsPageHarness.app/HapticsPageHarness"
+
+cat > "$OUT/HapticsPageHarness.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>HapticsPageHarness</string>
+<key>CFBundleIdentifier</key><string>com.vojta.hapticspageharness</string>
+<key>CFBundleName</key><string>HapticsPageHarness</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>UIApplicationSceneManifest</key><dict>
+ <key>UIApplicationSupportsMultipleScenes</key><false/>
+</dict>
+</dict></plist>
+PLIST
+echo "built $OUT/HapticsPageHarness.app"
diff --git a/harness/haptics-page/main.m b/harness/haptics-page/main.m
new file mode 100644
index 00000000..00ff4d2d
--- /dev/null
+++ b/harness/haptics-page/main.m
@@ -0,0 +1,168 @@
+// Mod Settings > Player's Vibrations cards (Redesigned/Haptics/HapticsSettings.m) on an SGModPage laid out like the
+// Player page in the redesign, with the real Settings/ framework and SGRFeedback.m behind them and stubs.m for
+// Music Haptics' engine. The launch line sets the switches up and then plays actions, one every 0.7 s from 1 s
+// in; screenshot after.
+//
+// THEOS=$HOME/theos ./build.sh && xcrun simctl install <udid> build/HapticsPageHarness.app
+// xcrun simctl launch <udid> com.vojta.hapticspageharness [setup...] [action...]
+//
+// Setup: keep (the stored settings stay; otherwise every spotifyglass.redesign.haptics key is cleared first),
+// controls-off (Controls switched off), music (Music Haptics on), follows=<n>, slow (animations at a twentieth
+// of their speed).
+// Actions: toggle=<section>.<row> (that row's switch flipped the way a tap does), slide=<section>.<row>:<value>
+// (that slider dragged there and let go), swipe=<section>.<row>:<n> (VoiceOver's swipe up on it, n times, down
+// for a negative n), info=<section>.<row> (a tap on its ⓘ), select=<section>.<row> (a tap on a row of the page
+// on top), pop, bottom (scrolled to the end), dump (the stored haptics keys, what the hooks would read, and the
+// rows each section shows, to the log).
+#import <UIKit/UIKit.h>
+#import "Core/SGCore.h"
+#import "Settings/SGModPage.h"
+#import "Redesigned/Haptics/Haptics.h"
+
+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);
+}
+
+@interface AppDelegate : UIResponder <UIApplicationDelegate>
+@property (nonatomic, strong) UIWindow *window;
+@property (nonatomic, strong) UINavigationController *nav;
+@end
+
+@implementation AppDelegate
+
+// The Player page as App/Pages.m builds it in the redesign, its links standing in for the pages they open.
+- (UIViewController *)playerPage {
+ UIViewController *(^none)(void) = ^UIViewController *{ return nil; };
+ SGModRow *blocked = SGPageRow(@"Blocked artists", none);
+ blocked.value = ^NSString *{ return @"Off"; };
+ NSMutableArray<SGModSection *> *sections = [NSMutableArray arrayWithArray:@[
+ SGSection(nil, @[SGWithSymbol(SGPageRow(@"Gestures", none), @"hand.tap"), SGWithSymbol(SGPageRow(@"Lyrics", none), @"quote.bubble"),
+ SGWithSymbol(blocked, @"person.crop.circle.badge.xmark")]),
+ SGSection(nil, @[SGWithSymbol(SGPageRow(@"Now playing", none), @"rectangle.bottomthird.inset.filled"),
+ SGWithSymbol(SGPageRow(@"Lock screen widget", none), @"lock")]),
+ ]];
+ [sections addObjectsFromArray:SGRVibrationsSections()];
+ return [[SGModPage alloc] initWithTitle:@"Player" intro:@"Changes apply after you restart Spotify. Gestures, Blocked artists and Vibrations apply straight away."
+ sections:sections footer:nil];
+}
+
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
+ NSArray<NSString *> *args = NSProcessInfo.processInfo.arguments;
+ NSUserDefaults *store = NSUserDefaults.standardUserDefaults;
+ if (![args containsObject:@"keep"]) {
+ for (NSString *key in store.dictionaryRepresentation.allKeys) {
+ if ([key hasPrefix:@"spotifyglass.redesign.haptics"]) [store removeObjectForKey:key];
+ }
+ }
+ NSMutableArray<NSString *> *actions = [NSMutableArray array];
+ for (NSString *arg in [args subarrayWithRange:NSMakeRange(1, args.count - 1)]) {
+ if ([arg isEqualToString:@"controls-off"]) SGSetEnabled(SGRKeyControlHaptics, NO);
+ else if ([arg isEqualToString:@"music"]) SGSetEnabled(SGRKeyMusicHaptics, YES);
+ else if ([arg hasPrefix:@"follows="]) SGSetInt(SGRKeyMusicFollows, [arg substringFromIndex:8].integerValue);
+ else if (![@[@"keep", @"slow"] containsObject:arg]) [actions addObject:arg];
+ }
+
+ self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
+ self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
+ self.nav = [[UINavigationController alloc] initWithRootViewController:[self playerPage]];
+ self.window.rootViewController = self.nav;
+ [self.window makeKeyAndVisible];
+ if ([args containsObject:@"slow"]) self.window.layer.speed = 0.05;
+
+ [actions enumerateObjectsUsingBlock:^(NSString *action, NSUInteger i, BOOL *stop) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((1 + 0.7 * i) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
+ NSLog(@"[harness] %@", action);
+ [self run:action];
+ });
+ }];
+ return YES;
+}
+
+- (UITableView *)table {
+ return ((UITableViewController *)self.nav.topViewController).tableView;
+}
+
+- (NSIndexPath *)pathFrom:(NSString *)text {
+ NSArray<NSString *> *at = [text componentsSeparatedByString:@"."];
+ return [NSIndexPath indexPathForRow:at[1].integerValue inSection:at[0].integerValue];
+}
+
+- (void)run:(NSString *)action {
+ NSArray<NSString *> *parts = [action componentsSeparatedByString:@"="];
+ NSString *verb = parts.firstObject, *value = parts.count > 1 ? parts[1] : @"";
+ UITableView *table = self.table;
+ if ([verb isEqualToString:@"toggle"]) {
+ UITableViewCell *cell = [table cellForRowAtIndexPath:[self pathFrom:value]];
+ NSMutableArray<UISwitch *> *switches = [NSMutableArray array];
+ findViews(cell, UISwitch.class, switches);
+ UISwitch *toggle = switches.firstObject;
+ [toggle setOn:!toggle.on animated:YES];
+ [toggle sendActionsForControlEvents:UIControlEventValueChanged];
+ } else if ([verb isEqualToString:@"slide"] || [verb isEqualToString:@"swipe"]) {
+ NSArray<NSString *> *at = [value componentsSeparatedByString:@":"];
+ UITableViewCell *cell = [table cellForRowAtIndexPath:[self pathFrom:at[0]]];
+ NSMutableArray<UISlider *> *sliders = [NSMutableArray array];
+ findViews(cell, UISlider.class, sliders);
+ UISlider *slider = sliders.firstObject;
+ if ([verb isEqualToString:@"swipe"]) {
+ NSInteger n = at[1].integerValue;
+ for (NSInteger i = 0; i < labs(n); i++) {
+ if (n > 0) [slider accessibilityIncrement];
+ else [slider accessibilityDecrement];
+ }
+ } else {
+ // A drag: a few values on the way, off the steps, then let go.
+ float from = slider.value, to = at[1].floatValue;
+ for (int step = 1; step <= 4; step++) {
+ slider.value = from + (to - from) * step / 4 + (step < 4 ? 1.3f : 0);
+ [slider sendActionsForControlEvents:UIControlEventValueChanged];
+ }
+ [slider sendActionsForControlEvents:UIControlEventTouchUpInside];
+ }
+ NSLog(@"[harness] slider %@ reads %@ (thumb at %.1f)", slider.accessibilityLabel, slider.accessibilityValue, slider.value);
+ } else if ([verb isEqualToString:@"info"]) {
+ UITableViewCell *cell = [table cellForRowAtIndexPath:[self pathFrom:value]];
+ NSMutableArray<UIButton *> *buttons = [NSMutableArray array];
+ findViews(cell, UIButton.class, buttons);
+ [buttons.firstObject sendActionsForControlEvents:UIControlEventTouchUpInside];
+ UIAlertController *alert = (UIAlertController *)self.nav.topViewController.presentedViewController;
+ NSLog(@"[harness] the ⓘ shows \"%@\": %@", alert.title, [alert.message substringToIndex:MIN(60, alert.message.length)]);
+ } else if ([verb isEqualToString:@"select"]) {
+ [table.delegate tableView:table didSelectRowAtIndexPath:[self pathFrom:value]];
+ } else if ([verb isEqualToString:@"pop"]) {
+ [self.nav popViewControllerAnimated:YES];
+ } else if ([verb isEqualToString:@"bottom"]) {
+ CGFloat max = MAX(-table.adjustedContentInset.top, table.contentSize.height - table.bounds.size.height + table.adjustedContentInset.bottom);
+ [table setContentOffset:CGPointMake(0, max) animated:NO];
+ } else if ([verb isEqualToString:@"dump"]) {
+ NSDictionary *all = NSUserDefaults.standardUserDefaults.dictionaryRepresentation;
+ for (NSString *key in [all.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
+ if ([key hasPrefix:@"spotifyglass.redesign.haptics"]) NSLog(@"[harness] stored %@ = %@", key, all[key]);
+ }
+ NSLog(@"[harness] the hooks read: Controls %@ at %.0f%%, Music Haptics %@ at %.0f%% following %ld", SGEnabled(SGRKeyControlHaptics) ? @"on" : @"off",
+ SGRHapticsStrength(SGRKeyControlStrength) * 100, SGFlag(SGRKeyMusicHaptics, NO) ? @"on" : @"off",
+ SGRHapticsStrength(SGRKeyMusicStrength) * 100, (long)SGRMusicHapticsFollows());
+ for (NSInteger section = 0; section < table.numberOfSections; section++) {
+ NSMutableArray<NSString *> *rows = [NSMutableArray array];
+ for (NSInteger row = 0; row < [table numberOfRowsInSection:section]; row++) {
+ UITableViewCell *cell = [table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
+ NSString *title = [(UIListContentConfiguration *)cell.contentConfiguration text];
+ NSMutableArray<UILabel *> *labels = [NSMutableArray array];
+ if (!title) findViews(cell.contentView, UILabel.class, labels);
+ [rows addObject:[NSString stringWithFormat:@"%@ (%.0fpt)", title ?: labels.firstObject.text ?: @"?", [table rectForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]].size.height]];
+ }
+ NSLog(@"[harness] section %ld: %@", (long)section, [rows componentsJoinedByString:@", "]);
+ }
+ }
+}
+
+@end
+
+int main(int argc, char *argv[]) {
+ @autoreleasepool {
+ // The redesign's look: black, the redesign's own accent.
+ [NSUserDefaults.standardUserDefaults setBool:YES forKey:SGKeyRedesign];
+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(AppDelegate.class));
+ }
+}
diff --git a/harness/haptics-page/stubs.m b/harness/haptics-page/stubs.m
new file mode 100644
index 00000000..d782895a
--- /dev/null
+++ b/harness/haptics-page/stubs.m
@@ -0,0 +1,12 @@
+// Music Haptics' side of Haptics.h (MusicHaptics.x in the tweak), which the page calls as its switch and its
+// settings change: each call is logged with what the hook would read at that moment.
+#import "Core/SGCore.h"
+#import "Redesigned/Haptics/Haptics.h"
+
+void SGRSetMusicHapticsEnabled(BOOL on) {
+ NSLog(@"[harness] Music Haptics %@", on ? @"on" : @"off");
+}
+
+void SGRMusicHapticsSettingsChanged(void) {
+ NSLog(@"[harness] Music Haptics reads strength %.0f%%, follows %ld", SGRHapticsStrength(SGRKeyMusicStrength) * 100, (long)SGRMusicHapticsFollows());
+}
diff --git a/harness/haptics/README.md b/harness/haptics/README.md
new file mode 100644
index 00000000..8677e715
--- /dev/null
+++ b/harness/haptics/README.md
@@ -0,0 +1,60 @@
+# Music Haptics harness
+
+Two halves: the analyzer on the Mac, and the hook in the simulator.
+
+## The analyzer on the Mac (`main.m`, `score.py`)
+
+`SGRMusicAnalyzer.m` as the tweak compiles it, over a song decoded at the output's rate and handed over in IO
+buffers, the way `MusicHaptics.x` hands it the output's buffers. Every event goes to a CSV (K a kick's tap, S a
+snare's, L the rumble's level); `score.py` matches the taps one to one within 50 ms (mir_eval) against librosa's
+onsets for each Follows choice, beside what random taps at the same rate score. With demucs' stems beside the
+song (`<song>.drums.wav`, `.bass.wav`, `.vocals.wav`, htdemucs) it also scores against the drums, the low end
+and the vocals.
+
+ ./build.sh && build/haptics <song> <events.csv> [rate] [frames]
+ python score.py <song.wav> <events.csv> # numpy, scipy, soundfile, librosa, mir_eval
+
+2026-09-19, `song.mp3` beside the repo (`test.mp3` is the same audio with a cover, and gives the same events), at
+48 kHz in buffers of 1024: the event stream for Everything is identical to the analyzer's before Follows existed
+(19,938 events at 48 kHz, 19,896 at 44.1; only the taps' kind is new), and 44.1 kHz scores within 0.01 of 48 kHz.
+
+| Follows | taps a second | against | precision | recall (stronger half) | at random |
+|---|---|---|---|---|---|
+| Everything, Beat | 3.31 | the mix's percussive onsets | 0.73 | 0.68 (0.84) | 0.30 / 0.28 |
+| Everything, Beat | 3.31 | the drums stem | 0.66 | 0.89 (0.94) | 0.21 / 0.28 |
+| Bass | 2.03 | the low end (drums and bass under 150 Hz) | 0.84 | 0.70 (0.73) | 0.22 / 0.18 |
+
+The rumble is over its start level 76% of the time in Everything and Bass, and never plays in Beat.
+
+A Vocals choice was tried and left out. Without a separation model the one cheap handle on a voice is that it is
+mixed in the middle: per FFT bin (2048 at 44.1 kHz, hops of 512) the centre was kept by L/R similarity, 250 Hz to
+4 kHz, broadband rises (a drum lifts every bin at once) held down, onsets picked from SuperFlux-style flux,
+causally. Against the onsets of demucs' vocal stem it scored, at its best, precision 0.53 and recall 0.59 on
+`song.mp3` (3.4 taps a second; at random 0.26 and 0.29), 0.35 / 0.55 on a sung line (`say -v Cellos` over a
+beat; at random 0.19) and 0.66 / 0.65 on a spoken one; the same picker on the vocal stem alone scores 0.72 / 0.74,
+so what fails is the separation, not the picking. Of the taps that hit no syllable, 47% fell where nobody sings,
+and no cheap cue told those stretches apart (the best, the share of the sound in the centre, AUC 0.6). It needs
+a real separation model.
+
+## The hook in the simulator (`sim/`)
+
+Spotify's chain rebuilt with real units (as `harness/jamesdsp/sim`), with `MusicHaptics.x` (logos, internal
+generator), the analyzer and the Vibrations settings compiled into an app whose main executable is the harness,
+so its `AudioOutputUnitStart` goes through the rebound import slot as Spotify's does. `sim/fakehaptics.m`
+stands in for Core Haptics and counts what it is asked to play. A beat of a kick and a snare a second plays
+through a 44.1 kHz client into the simulator's 48 kHz hardware while a script checks each Follows choice, the
+strength at 50% and 200%, the switch off and on, then a 16-bit interleaved client.
+
+ THEOS=$HOME/theos ./build-sim.sh
+ xcrun simctl install <udid> build/sim/HapticsHarness.app
+ xcrun simctl launch --console-pty <udid> com.vojta.hapticsharness
+ xcrun simctl spawn <udid> log show --last 2m --predicate 'eventMessage CONTAINS "music haptics"'
+
+`./build-sim.sh before <dir>` builds the same against an older `MusicHaptics.x`, `Haptics.h` and analyzer put in
+`<dir>`, running only the format steps. Use a device of your own (`xcrun simctl create`), by UDID.
+
+2026-09-19: every step passes. Beat sends no rumble, Bass no snare, 50% halves the taps (0.44 from 0.88) and the
+rumble's loudest (0.162 from 0.322), 200% doubles the rumble (0.64). The hook now listens at the hardware's
+48 kHz float, a buffer per channel, whatever the client ("from 44100 Hz ... Spotify hands it"). Before, it read
+the client format off the input scope: it ran the analyzer at 44.1 kHz on 48 kHz buffers, and a 16-bit
+interleaved client made it read the float buffers as integers (taps 0.57 strong instead of 0.89).
diff --git a/harness/haptics/build-sim.sh b/harness/haptics/build-sim.sh
new file mode 100755
index 00000000..727be3b8
--- /dev/null
+++ b/harness/haptics/build-sim.sh
@@ -0,0 +1,45 @@
+#!/bin/sh
+# Builds the simulator harness (sim/main.m): MusicHaptics.x generated by logos with the internal generator as the
+# tweak builds it, the analyzer, the Vibrations settings and the Settings/ framework, fakehaptics.m in place of
+# CoreHaptics.framework, 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
+# THEOS=$HOME/theos ./build-sim.sh before <dir> the same against <dir>/MusicHaptics.x, <dir>/Haptics.h and
+# <dir>/SGRMusicAnalyzer.{h,m} of an older commit, format steps only
+set -e
+cd "$(dirname "$0")"
+SRC=../../tweak/Sources
+OUT=build/sim
+HAPTICS="$SRC/Redesigned/Haptics"
+EXTRA=""
+SETTINGS="$SRC/Redesigned/Haptics/HapticsSettings.m $SRC/Redesigned/Haptics/SGRFeedback.m $SRC/Settings/SGPage.m $SRC/Settings/SGPageStyle.m $SRC/Settings/SGModPage.m $SRC/Settings/SGGlowSwitch.m"
+if [ "$1" = before ]; then
+ HAPTICS=$2
+ OUT=build/sim-before
+ EXTRA="-DBEFORE -I$HAPTICS"
+ SETTINGS=""
+fi
+rm -rf "$OUT"
+mkdir -p "$OUT/gen" "$OUT/HapticsHarness.app"
+"$THEOS/bin/logos.pl" -c generator=internal "$HAPTICS/MusicHaptics.x" > "$OUT/gen/MusicHaptics.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 \
+ $EXTRA -I"$SRC" -I"$SRC/Redesigned/Haptics" -Isim \
+ sim/main.m sim/fakehaptics.m "$OUT/gen/MusicHaptics.m" "$HAPTICS/SGRMusicAnalyzer.m" $SETTINGS \
+ "$SRC/Core/SGRebind.m" "$SRC/Core/SGLog.m" "$SRC/Core/SGPrefs.m" "$SRC/Core/SGUIMode.m" "$SRC/Core/SGViewTree.m" "$SRC/Core/SGFlagForce.m" \
+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework AudioToolbox -framework AVFoundation -framework Foundation \
+ -o "$OUT/HapticsHarness.app/HapticsHarness"
+cat > "$OUT/HapticsHarness.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>HapticsHarness</string>
+<key>CFBundleIdentifier</key><string>com.vojta.hapticsharness</string>
+<key>CFBundleName</key><string>HapticsHarness</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/HapticsHarness.app"
diff --git a/harness/haptics/build.sh b/harness/haptics/build.sh
new file mode 100755
index 00000000..073c3f53
--- /dev/null
+++ b/harness/haptics/build.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+# Builds the Music Haptics analyzer harness for the Mac: SGRMusicAnalyzer.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 -framework AudioToolbox \
+ main.m ../../tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.m -o build/haptics
+echo "built build/haptics"
diff --git a/harness/haptics/main.m b/harness/haptics/main.m
new file mode 100644
index 00000000..601a0103
--- /dev/null
+++ b/harness/haptics/main.m
@@ -0,0 +1,69 @@
+// Music Haptics' analyzer (Redesigned/Haptics/SGRMusicAnalyzer.m, as the tweak compiles it) over a song on the
+// Mac: the song is decoded at the rate asked for (the output's, 48 kHz on an iPhone), mixed to mono the way
+// MusicHaptics.x mixes the output's buffers, handed over in IO buffers of the size asked for, and every event
+// is written out one a line: K (a kick's tap), S (a snare's), L (the rumble's level), then the time in seconds,
+// the intensity and the sharpness. score.py reads it against a song's onsets; `summary` prints what each
+// Follows choice would play.
+//
+// ./build.sh && build/haptics <song> <events.csv> [rate] [frames]
+#import <Foundation/Foundation.h>
+#import <AudioToolbox/AudioToolbox.h>
+#import "Redesigned/Haptics/SGRMusicAnalyzer.h"
+
+typedef struct {
+ FILE *out;
+ unsigned kicks, snares, levels, rumbling;
+ double lastTime;
+} Run;
+
+static void emit(const SGRMusicEvent *event, void *context) {
+ Run *run = context;
+ char kind = event->kind == SGRMusicEventKick ? 'K' : event->kind == SGRMusicEventSnare ? 'S' : 'L';
+ fprintf(run->out, "%c,%.5f,%.4f,%.4f\n", kind, event->hostTime / 1e9, event->intensity, event->sharpness);
+ if (kind == 'K') run->kicks++;
+ else if (kind == 'S') run->snares++;
+ else {
+ run->levels++;
+ run->rumbling += event->intensity >= 0.05f; // MusicHaptics.x's kRumbleStart
+ }
+ run->lastTime = event->hostTime / 1e9;
+}
+
+int main(int argc, char **argv) {
+ @autoreleasepool {
+ if (argc < 3) {
+ fprintf(stderr, "usage: %s <song> <events.csv> [rate] [frames]\n", argv[0]);
+ return 2;
+ }
+ double rate = argc > 3 ? atof(argv[3]) : 44100;
+ UInt32 frames = argc > 4 ? (UInt32)atoi(argv[4]) : 1024;
+ ExtAudioFileRef file;
+ if (ExtAudioFileOpenURL((__bridge CFURLRef)[NSURL fileURLWithPath:@(argv[1])], &file)) {
+ fprintf(stderr, "cannot open %s\n", argv[1]);
+ return 1;
+ }
+ AudioStreamBasicDescription format = {rate, kAudioFormatLinearPCM, kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked, 8, 1, 8, 2, 32, 0};
+ ExtAudioFileSetProperty(file, kExtAudioFileProperty_ClientDataFormat, sizeof format, &format);
+ Run run = {fopen(argv[2], "w")};
+ SGRMusicAnalyzer analyzer;
+ SGRMusicAnalyzerReset(&analyzer, rate, 1e9);
+ float *stereo = malloc(frames * 2 * sizeof(float)), *mono = malloc(frames * sizeof(float));
+ uint64_t done = 0;
+ for (;;) {
+ AudioBufferList list = {1, {{2, frames * 2 * (UInt32)sizeof(float), stereo}}};
+ UInt32 count = frames;
+ if (ExtAudioFileRead(file, &count, &list) || !count) break;
+ for (UInt32 i = 0; i < count; i++) mono[i] = 0.5f * (stereo[2 * i] + stereo[2 * i + 1]);
+ SGRMusicAnalyzerProcess(&analyzer, mono, count, (uint64_t)(done / rate * 1e9), emit, &run);
+ done += count;
+ }
+ fclose(run.out);
+ ExtAudioFileDispose(file);
+ double seconds = done / rate;
+ printf("%.1f s at %.0f Hz in buffers of %u: kicks %u, snares %u (%.2f taps a second); Everything and Beat tap %.2f a second, "
+ "Bass %.2f; the rumble is on for %.0f%% of the levels (Everything, Bass)\n",
+ seconds, rate, (unsigned)frames, run.kicks, run.snares, (run.kicks + run.snares) / seconds, (run.kicks + run.snares) / seconds,
+ run.kicks / seconds, run.levels ? 100.0 * run.rumbling / run.levels : 0);
+ }
+ return 0;
+}
diff --git a/harness/haptics/score.py b/harness/haptics/score.py
new file mode 100644
index 00000000..1eefa934
--- /dev/null
+++ b/harness/haptics/score.py
@@ -0,0 +1,54 @@
+# Scores build/haptics' events against onsets librosa finds, per Follows choice: precision, recall (of all the
+# onsets, and of the stronger half) and F, matched one to one within 50 ms (mir_eval), and taps a second, each
+# beside what taps at random times at the same rate would score.
+#
+# python score.py <song.wav> <events.csv>
+#
+# The references: the onsets of the mix's percussive part (librosa's HPSS, what the analyzer was first tuned
+# against), and, when demucs' stems lie beside the song as <song>.drums.wav, .bass.wav and .vocals.wav, the
+# onsets of the drums, of the low end (drums and bass under 150 Hz, for Bass) and of the vocals.
+# Needs numpy, scipy, soundfile, librosa and mir_eval.
+import sys, os, numpy as np, soundfile as sf, librosa, mir_eval, scipy.signal as ss
+
+SR, HOP, WINDOW = 22050, 256, 0.05
+
+def mono(path):
+ x, sr = sf.read(path, dtype='float32', always_2d=True)
+ return librosa.resample(x.mean(1), orig_sr=sr, target_sr=SR)
+
+def onsets(y):
+ env = librosa.onset.onset_strength(y=y, sr=SR, hop_length=HOP)
+ t = librosa.onset.onset_detect(onset_envelope=env, sr=SR, hop_length=HOP, units='time')
+ return t, env[librosa.time_to_frames(t, sr=SR, hop_length=HOP)]
+
+def score(ref, strength, taps, seconds):
+ f, p, r = mir_eval.onset.f_measure(ref, taps, window=WINDOW)
+ strong = ref[strength > np.median(strength)]
+ rs = mir_eval.onset.f_measure(strong, taps, window=WINDOW)[2]
+ rng = np.random.default_rng(1)
+ chance = np.mean([mir_eval.onset.f_measure(ref, np.sort(rng.uniform(0, seconds, len(taps))), window=WINDOW)[1:] for _ in range(10)], 0)
+ return f'{len(taps) / seconds:.2f}/s P {p:.2f} R {r:.2f} R strong {rs:.2f} F {f:.2f} (at random: P {chance[0]:.2f} R {chance[1]:.2f})'
+
+song, events = sys.argv[1], sys.argv[2]
+rows = [line.strip().split(',') for line in open(events)]
+kicks = np.array([float(r[1]) for r in rows if r[0] == 'K'])
+snares = np.array([float(r[1]) for r in rows if r[0] == 'S'])
+levels = np.array([float(r[2]) for r in rows if r[0] == 'L'])
+drums = np.sort(np.concatenate([kicks, snares]))
+mix = mono(song)
+seconds = len(mix) / SR
+refs = {}
+_, percussive = librosa.effects.hpss(mix)
+refs['the mix, percussive'] = onsets(percussive)
+stem = lambda name: song[:-4] + f'.{name}.wav'
+if all(os.path.exists(stem(n)) for n in ('drums', 'bass', 'vocals')):
+ d, b = mono(stem('drums')), mono(stem('bass'))
+ refs['the drums stem'] = onsets(d)
+ refs['the low end (drums and bass under 150 Hz)'] = onsets(ss.sosfilt(ss.butter(4, 150, 'low', fs=SR, output='sos'), d + b))
+ refs['the vocals stem'] = onsets(mono(stem('vocals')))
+print(f'{os.path.basename(song)}: {seconds:.1f} s; the rumble over its start level for {np.mean(levels >= 0.05) * 100:.0f}% of the time, '
+ f'its level {levels.mean():.3f} on average')
+for name, (ref, strength) in refs.items():
+ print(f' against {name} ({len(ref) / seconds:.2f} onsets a second):')
+ print(f' Everything, Beat (kicks and snares) {score(ref, strength, drums, seconds)}')
+ print(f' Bass (kicks) {score(ref, strength, kicks, seconds)}')
diff --git a/harness/haptics/sim/fakehaptics.h b/harness/haptics/sim/fakehaptics.h
new file mode 100644
index 00000000..18470136
--- /dev/null
+++ b/harness/haptics/sim/fakehaptics.h
@@ -0,0 +1,13 @@
+// What the stand-in Core Haptics (fakehaptics.m) was asked to play since it was last asked.
+#import <Foundation/Foundation.h>
+
+typedef struct {
+ unsigned kicks, snares; // taps, told apart by their sharpness
+ double tapIntensity; // their intensities, summed
+ unsigned rumbleStarts, rumbleStops, levels;
+ double levelSum, levelMax; // the rumble's intensities as sent
+ BOOL rumbling; // carried over
+} FakeHaptics;
+
+// The counts since the last call, and a fresh start.
+FakeHaptics FakeHapticsTake(void);
diff --git a/harness/haptics/sim/fakehaptics.m b/harness/haptics/sim/fakehaptics.m
new file mode 100644
index 00000000..9bfabee7
--- /dev/null
+++ b/harness/haptics/sim/fakehaptics.m
@@ -0,0 +1,128 @@
+// Core Haptics stood in for, since the simulator has no Taptic Engine: the classes MusicHaptics.x uses, which
+// record what it schedules instead of playing it. The harness links this rather than CoreHaptics.framework.
+#import <CoreHaptics/CoreHaptics.h>
+#import <QuartzCore/QuartzCore.h>
+#import <os/lock.h>
+#import "fakehaptics.h"
+
+// Only what MusicHaptics.x calls is stood in for.
+#pragma clang diagnostic ignored "-Wincomplete-implementation"
+#pragma clang diagnostic ignored "-Wprotocol"
+
+CHHapticEventParameterID CHHapticEventParameterIDHapticIntensity = @"HapticIntensity";
+CHHapticEventParameterID CHHapticEventParameterIDHapticSharpness = @"HapticSharpness";
+CHHapticDynamicParameterID CHHapticDynamicParameterIDHapticIntensityControl = @"HapticIntensityControl";
+CHHapticDynamicParameterID CHHapticDynamicParameterIDHapticSharpnessControl = @"HapticSharpnessControl";
+CHHapticEventType CHHapticEventTypeHapticTransient = @"HapticTransient";
+CHHapticEventType CHHapticEventTypeHapticContinuous = @"HapticContinuous";
+
+static os_unfair_lock sg_lock = OS_UNFAIR_LOCK_INIT;
+static FakeHaptics sg_counts;
+
+FakeHaptics FakeHapticsTake(void) {
+ os_unfair_lock_lock(&sg_lock);
+ FakeHaptics counts = sg_counts;
+ sg_counts = (FakeHaptics){0};
+ sg_counts.rumbling = counts.rumbling;
+ os_unfair_lock_unlock(&sg_lock);
+ return counts;
+}
+
+static void record(void (^change)(FakeHaptics *counts)) {
+ os_unfair_lock_lock(&sg_lock);
+ change(&sg_counts);
+ os_unfair_lock_unlock(&sg_lock);
+}
+
+// An event's parameters or a player's dynamic ones: both classes answer parameterID and value.
+static float valueOf(NSArray *parameters, NSString *identifier) {
+ for (CHHapticEventParameter *parameter in parameters) {
+ if ([parameter.parameterID isEqualToString:identifier]) return parameter.value;
+ }
+ return -1;
+}
+
+@interface FakeCapability : NSObject <CHHapticDeviceCapability> @end
+@implementation FakeCapability
+- (BOOL)supportsHaptics { return YES; }
+- (BOOL)supportsAudio { return NO; }
+- (id<CHHapticParameterAttributes>)attributesForEventParameter:(CHHapticEventParameterID)p eventType:(CHHapticEventType)t error:(NSError **)e { return nil; }
+- (id<CHHapticParameterAttributes>)attributesForDynamicParameter:(CHHapticDynamicParameterID)p error:(NSError **)e { return nil; }
+@end
+
+@implementation CHHapticEventParameter
+- (instancetype)initWithParameterID:(CHHapticEventParameterID)parameterID value:(float)value { if ((self = [super init])) { _parameterID = parameterID; _value = value; } return self; }
+@end
+@implementation CHHapticDynamicParameter
+- (instancetype)initWithParameterID:(CHHapticDynamicParameterID)parameterID value:(float)value relativeTime:(NSTimeInterval)time { if ((self = [super init])) { _parameterID = parameterID; _value = value; _relativeTime = time; } return self; }
+@end
+@implementation CHHapticEvent
+- (instancetype)initWithEventType:(CHHapticEventType)type parameters:(NSArray *)parameters relativeTime:(NSTimeInterval)time { if ((self = [super init])) { _type = type; _eventParameters = parameters; _relativeTime = time; } return self; }
+- (instancetype)initWithEventType:(CHHapticEventType)type parameters:(NSArray *)parameters relativeTime:(NSTimeInterval)time duration:(NSTimeInterval)duration { if ((self = [self initWithEventType:type parameters:parameters relativeTime:time])) { _duration = duration; } return self; }
+@end
+@interface CHHapticPattern ()
+@property NSArray<CHHapticEvent *> *fakeEvents;
+@end
+@implementation CHHapticPattern
+- (instancetype)initWithEvents:(NSArray<CHHapticEvent *> *)events parameters:(NSArray *)parameters error:(NSError **)error { if ((self = [super init])) { _fakeEvents = events; } return self; }
+@end
+
+@interface FakePlayer : NSObject <CHHapticAdvancedPatternPlayer>
+@property CHHapticPattern *pattern;
+@end
+
+@implementation CHHapticEngine
+@synthesize stoppedHandler = _stoppedHandler, resetHandler = _resetHandler, playsHapticsOnly = _playsHapticsOnly, autoShutdownEnabled = _autoShutdownEnabled;
++ (id<CHHapticDeviceCapability>)capabilitiesForHardware { return [FakeCapability new]; }
+- (instancetype)initAndReturnError:(NSError **)error { return [super init]; }
+- (instancetype)initWithAudioSession:(AVAudioSession *)audioSession error:(NSError **)error { return [super init]; }
+- (NSTimeInterval)currentTime { return CACurrentMediaTime(); }
+- (BOOL)startAndReturnError:(NSError **)outError { return YES; }
+- (void)stopWithCompletionHandler:(CHHapticCompletionHandler)handler {}
+- (id<CHHapticPatternPlayer>)createPlayerWithPattern:(CHHapticPattern *)pattern error:(NSError **)outError { FakePlayer *p = [FakePlayer new]; p.pattern = pattern; return p; }
+- (id<CHHapticAdvancedPatternPlayer>)createAdvancedPlayerWithPattern:(CHHapticPattern *)pattern error:(NSError **)outError { FakePlayer *p = [FakePlayer new]; p.pattern = pattern; return p; }
+@end
+
+@implementation FakePlayer
+@synthesize loopEnabled, loopEnd, playbackRate, isMuted, completionHandler;
+- (BOOL)startAtTime:(NSTimeInterval)time error:(NSError **)outError {
+ CHHapticEvent *event = self.pattern.fakeEvents.firstObject;
+ if ([event.type isEqualToString:CHHapticEventTypeHapticTransient]) {
+ float intensity = valueOf(event.eventParameters, CHHapticEventParameterIDHapticIntensity);
+ float sharpness = valueOf(event.eventParameters, CHHapticEventParameterIDHapticSharpness);
+ record(^(FakeHaptics *counts) {
+ // The analyzer's kicks are 0.15 to 0.45 sharp, its snares 0.55 to 0.95.
+ if (sharpness < 0.5f) counts->kicks++;
+ else counts->snares++;
+ counts->tapIntensity += intensity;
+ });
+ } else {
+ record(^(FakeHaptics *counts) {
+ counts->rumbleStarts++;
+ counts->rumbling = YES;
+ });
+ }
+ return YES;
+}
+- (BOOL)stopAtTime:(NSTimeInterval)time error:(NSError **)outError {
+ record(^(FakeHaptics *counts) {
+ counts->rumbleStops++;
+ counts->rumbling = NO;
+ });
+ return YES;
+}
+- (BOOL)sendParameters:(NSArray *)parameters atTime:(NSTimeInterval)time error:(NSError **)outError {
+ float level = valueOf(parameters, CHHapticDynamicParameterIDHapticIntensityControl);
+ record(^(FakeHaptics *counts) {
+ counts->levels++;
+ counts->levelSum += level;
+ counts->levelMax = MAX(counts->levelMax, level);
+ });
+ return YES;
+}
+- (BOOL)scheduleParameterCurve:(CHHapticParameterCurve *)parameterCurve atTime:(NSTimeInterval)time error:(NSError **)outError { return YES; }
+- (BOOL)cancelAndReturnError:(NSError **)outError { return YES; }
+- (BOOL)pauseAtTime:(NSTimeInterval)time error:(NSError **)outError { return YES; }
+- (BOOL)resumeAtTime:(NSTimeInterval)time error:(NSError **)outError { return YES; }
+- (BOOL)seekToOffset:(NSTimeInterval)offsetTime error:(NSError **)outError { return YES; }
+@end
diff --git a/harness/haptics/sim/main.m b/harness/haptics/sim/main.m
new file mode 100644
index 00000000..4c714a93
--- /dev/null
+++ b/harness/haptics/sim/main.m
@@ -0,0 +1,265 @@
+// Music Haptics on Spotify's audio chain rebuilt with real Core Audio units in the simulator (as harness/jamesdsp/sim
+// does: a converter fed by a render callback, a mixer and RemoteIO, wired with MakeConnection, slices of 4096),
+// with MusicHaptics.x, the analyzer and the Vibrations settings compiled in and fakehaptics.m standing in for Core
+// Haptics. The harness is the main executable, so its AudioOutputUnitStart goes through the rebound import slot as
+// Spotify's does. The client format is Spotify's, 44.1 kHz float with a buffer per channel; the simulator's
+// hardware is 48 kHz, and MusicHaptics.x logs which of the two it listens at.
+//
+// The generator plays a beat at 120 BPM, a kick on each whole second and a snare on each half, so the analyzer
+// hears a kick and a snare a second. A script changes the settings every 6 s and checks what the stand-in was
+// asked to play in the 4 s after the change has settled: what each Follows choice leaves out, the strength
+// scaling the taps and the rumble, then a 16-bit interleaved client at 48 kHz.
+//
+// THEOS=$HOME/theos ../build-sim.sh
+// xcrun simctl install <udid> build/sim/HapticsHarness.app
+// xcrun simctl launch --console-pty <udid> com.vojta.hapticsharness
+//
+// Built with -DBEFORE against the MusicHaptics.x of before the output format fix (build-sim.sh before), it runs
+// only the format steps, which have no settings to change.
+#import <UIKit/UIKit.h>
+#import <AudioToolbox/AudioToolbox.h>
+#import <AVFoundation/AVFoundation.h>
+#import <QuartzCore/QuartzCore.h>
+#import <stdatomic.h>
+#import "Core/SGCore.h"
+#import "Redesigned/Haptics/Haptics.h"
+#import "fakehaptics.h"
+
+static atomic_uint_fast64_t sg_frame;
+static double sg_generatorRate;
+
+// A kick (a falling sine, 120 to 50 Hz) on each whole second, a snare (noise and 190 Hz) on each half.
+static float beatAt(uint64_t frame, double rate) {
+ double t = frame / rate, beat = fmod(t, 1.0), half = fmod(t, 0.5);
+ float out = 0;
+ if (beat < 0.25) {
+ double phase = 2 * M_PI * (50 * beat + 70 / 30.0 * (1 - exp(-30 * beat)));
+ out += 0.8f * (float)(sin(phase) * exp(-14 * beat));
+ }
+ if (beat >= 0.5 && half < 0.15) {
+ uint32_t noise = (uint32_t)frame;
+ noise ^= noise >> 16; noise *= 0x7feb352du; noise ^= noise >> 15; noise *= 0x846ca68bu; noise ^= noise >> 16;
+ out += (float)((0.35 * ((noise & 0xffff) / 32768.0 - 1) + 0.3 * sin(2 * M_PI * 190 * half)) * exp(-28 * half));
+ }
+ return 0.5f * out;
+}
+
+static OSStatus generate(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,
+ UInt32 frames, AudioBufferList *data) {
+ uint64_t start = atomic_fetch_add(&sg_frame, frames);
+ float *left = data->mBuffers[0].mData, *right = data->mNumberBuffers > 1 ? data->mBuffers[1].mData : NULL;
+ for (UInt32 i = 0; i < frames; i++) {
+ left[i] = beatAt(start + i, sg_generatorRate);
+ if (right) right[i] = left[i];
+ }
+ return noErr;
+}
+
+#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);
+}
+
+static int sg_failures;
+
+@interface HapticsHarnessDelegate : UIResponder <UIApplicationDelegate>
+@property (nonatomic, strong) UIWindow *window;
+@end
+
+@implementation HapticsHarnessDelegate {
+ AudioUnit _converter, _mixer, _output;
+}
+
+- (void)stopChain {
+ if (_output) AudioOutputUnitStop(_output);
+ AudioUnit old[] = {_output, _mixer, _converter};
+ for (int i = 0; i < 3; i++) {
+ if (!old[i]) continue;
+ AudioUnitUninitialize(old[i]);
+ AudioComponentInstanceDispose(old[i]);
+ }
+ _output = _mixer = _converter = NULL;
+}
+
+// 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");
+ [self logScopes];
+}
+
+// 16-bit interleaved at another rate, the converter straight into RemoteIO: the notify still gets the output
+// side's float, a buffer per channel.
+- (void)startInt16ChainAt:(double)rate {
+ [self stopChain];
+ atomic_store(&sg_frame, 0);
+ sg_generatorRate = rate;
+ _converter = make(kAudioUnitType_FormatConverter, kAudioUnitSubType_AUConverter);
+ _output = make(kAudioUnitType_Output, kAudioUnitSubType_RemoteIO);
+ 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");
+ [self logScopes];
+}
+
+- (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 notify gets, %.0f Hz %u-bit flags 0x%x",
+ client.mSampleRate, (unsigned)client.mBitsPerChannel, (unsigned)client.mFormatFlags, hardware.mSampleRate,
+ (unsigned)hardware.mBitsPerChannel, (unsigned)hardware.mFormatFlags);
+}
+
+// A timer rather than dispatch_after, whose leeway grows with the delay (a tenth of it) and lets a script's
+// later steps fire out of order.
+- (void)after:(double)seconds do:(void (^)(void))block {
+ [NSTimer scheduledTimerWithTimeInterval:seconds repeats:NO block:^(NSTimer *timer) { block(); }];
+}
+
+// What the stand-in played over the last `seconds`, checked against a kick and a snare a second (one more or
+// less, for where the window falls), the taps' mean intensity and the rumble's loudest.
+- (void)report:(NSString *)what seconds:(double)seconds kicks:(double)kicks snares:(double)snares rumble:(BOOL)rumble
+ intensity:(double)intensity level:(double)level {
+ FakeHaptics c = FakeHapticsTake();
+ double tapMean = c.kicks + c.snares ? c.tapIntensity / (c.kicks + c.snares) : 0;
+ BOOL ok = fabs(c.kicks - kicks * seconds) <= 1 && fabs(c.snares - snares * seconds) <= 1 && (rumble ? c.levels > 0 : c.levels == 0)
+ && (isnan(intensity) || fabs(tapMean - intensity) <= 0.05) && (isnan(level) || fabs(c.levelMax - level) <= 0.02);
+ if (!ok) sg_failures++;
+ NSLog(@"[harness] %@ %-36@ %u kicks, %u snares in %.1f s (want %.0f, %.0f), taps %.2f strong on average (want %@), rumble %u levels, "
+ @"%.3f at most (want %@)", ok ? @" ok " : @"FAILED", what, c.kicks, c.snares, seconds, kicks * seconds, snares * seconds, tapMean,
+ isnan(intensity) ? @"any" : [NSString stringWithFormat:@"%.2f", intensity], c.levels, c.levelMax,
+ rumble ? (isnan(level) ? @"some" : [NSString stringWithFormat:@"%.3f", level]) : @"none");
+}
+
+- (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];
+ [self startSpotifyChainAt:44100];
+
+ // Each step: the change, then after 1.5 s to settle, 4 s measured. The first measures what 100% and
+ // Everything play, which the strength steps are held against.
+ __block double tap100 = 0, level100 = 0;
+ NSMutableArray *steps = [NSMutableArray arrayWithObject:@[@"44.1 kHz client, Everything, 100%", ^{}, ^(double s) {
+ FakeHaptics peek = FakeHapticsTake();
+ tap100 = peek.kicks + peek.snares ? peek.tapIntensity / (peek.kicks + peek.snares) : 0;
+ level100 = peek.levelMax;
+ BOOL ok = fabs(peek.kicks - s) <= 1 && fabs(peek.snares - s) <= 1 && peek.levels > 0;
+ if (!ok) sg_failures++;
+ NSLog(@"[harness] %@ %-36@ %u kicks, %u snares in %.1f s (want %.0f, %.0f), taps %.2f strong on average, rumble %u levels, %.3f at most",
+ ok ? @" ok " : @"FAILED", @"44.1 kHz client, Everything, 100%", peek.kicks, peek.snares, s, s, s, tap100, peek.levels, level100);
+ }]];
+#ifndef BEFORE
+ void (^set)(NSInteger, NSInteger) = ^(NSInteger follows, NSInteger strength) {
+ SGSetInt(SGRKeyMusicFollows, follows);
+ SGSetInt(SGRKeyMusicStrength, strength);
+ SGRMusicHapticsSettingsChanged();
+ };
+ [steps addObjectsFromArray:@[
+ @[@"Beat: no rumble", ^{ set(SGRMusicFollowsBeat, 100); }, ^(double s) {
+ [self report:@"Beat: no rumble" seconds:s kicks:1 snares:1 rumble:NO intensity:tap100 level:NAN];
+ }],
+ @[@"Bass: no snares", ^{ set(SGRMusicFollowsBass, 100); }, ^(double s) {
+ [self report:@"Bass: no snares" seconds:s kicks:1 snares:0 rumble:YES intensity:NAN level:level100];
+ }],
+ @[@"Everything at 50%", ^{ set(SGRMusicFollowsEverything, 50); }, ^(double s) {
+ [self report:@"Everything at 50%" seconds:s kicks:1 snares:1 rumble:YES intensity:tap100 / 2 level:level100 / 2];
+ }],
+ @[@"Everything at 200%", ^{ set(SGRMusicFollowsEverything, 200); }, ^(double s) {
+ [self report:@"Everything at 200%" seconds:s kicks:1 snares:1 rumble:YES intensity:NAN level:MIN(1, level100 * 2)];
+ }],
+ @[@"the switch off", ^{ SGRSetMusicHapticsEnabled(NO); }, ^(double s) {
+ [self report:@"the switch off" seconds:s kicks:0 snares:0 rumble:NO intensity:NAN level:NAN];
+ }],
+ @[@"on again, Everything, 100%", ^{
+ set(SGRMusicFollowsEverything, 100);
+ SGRSetMusicHapticsEnabled(YES);
+ }, ^(double s) {
+ [self report:@"on again, Everything, 100%" seconds:s kicks:1 snares:1 rumble:YES intensity:tap100 level:level100];
+ }],
+ ]];
+#endif
+ [steps addObject:@[@"16-bit interleaved client at 48 kHz", ^{ [self startInt16ChainAt:48000]; }, ^(double s) {
+ [self report:@"16-bit interleaved client at 48 kHz" seconds:s kicks:1 snares:1 rumble:YES intensity:NAN level:NAN];
+ }]];
+
+ // The window is measured as it was, however late its ends fired.
+ __block double from = 0;
+ double at = 0.5;
+ for (NSArray *step in steps) {
+ [self after:at do:^{
+ NSLog(@"[harness] -> %@", step[0]);
+ ((void (^)(void))step[1])();
+ }];
+ [self after:at + 1.5 do:^{
+ FakeHapticsTake();
+ from = CACurrentMediaTime();
+ }];
+ [self after:at + 5.5 do:^{ ((void (^)(double))step[2])(CACurrentMediaTime() - from); }];
+ at += 6;
+ }
+ [self after:at do:^{
+ NSLog(@"[harness] %@: %d failed", sg_failures ? @"FAILED" : @"all passed", sg_failures);
+ exit(sg_failures ? 1 : 0);
+ }];
+ return YES;
+}
+
+@end
+
+// Music Haptics on, and its settings at their defaults, before MusicHaptics.x's constructor reads them; the
+// redesign on, which gates it.
+__attribute__((constructor(101))) static void sgr_harnessDefaults(void) {
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
+ for (NSString *key in defaults.dictionaryRepresentation.allKeys) {
+ if ([key hasPrefix:@"spotifyglass."]) [defaults removeObjectForKey:key];
+ }
+ [defaults setBool:YES forKey:SGKeyRedesign];
+ [defaults setBool:YES forKey:SGRKeyMusicHaptics];
+}
+
+int main(int argc, char *argv[]) {
+ @autoreleasepool {
+ return UIApplicationMain(argc, argv, nil, NSStringFromClass(HapticsHarnessDelegate.class));
+ }
+}
diff --git a/tweak/Sources/App/Pages.m b/tweak/Sources/App/Pages.m
index 5d6eaed8..4a87bdd6 100644
--- a/tweak/Sources/App/Pages.m
+++ b/tweak/Sources/App/Pages.m
@@ -84,7 +84,7 @@ UIViewController *SGPlayerSettingsPage(void) {
[pages addObject:SGWithSymbol(SGPageRow(@"Lock screen widget", ^UIViewController *{ return SGLockScreenWidgetPage(); }), @"lock")];
[sections addObject:SGSection(nil, pages)];
if (native) [sections addObjectsFromArray:SGNativePlayerScreenSections()];
- else [sections addObject:SGRVibrationsSection()];
+ else [sections addObjectsFromArray:SGRVibrationsSections()];
NSString *intro = native ? @"Changes apply after you restart Spotify. Gestures and Blocked artists apply straight away."
: @"Changes apply after you restart Spotify. Gestures, Blocked artists and Vibrations apply straight away.";
diff --git a/tweak/Sources/Redesigned/Haptics/Haptics.h b/tweak/Sources/Redesigned/Haptics/Haptics.h
index 83fac62a..493d296a 100644
--- a/tweak/Sources/Redesigned/Haptics/Haptics.h
+++ b/tweak/Sources/Redesigned/Haptics/Haptics.h
@@ -5,15 +5,34 @@
// ControlHaptics.x the player's and the now playing bar's controls, the scrubber, the cover swipes, the gestures
// MusicHaptics.x Spotify's audio output listened to, and Core Haptics played along with it
// SGRMusicAnalyzer.m the listening: taps and a rumble out of the samples
-// HapticsSettings.m the Vibrations section
+// HapticsSettings.m the Vibrations cards, with each switch's strength and what Music Haptics follows
//
-// Both switches apply at once, without a restart. The lyrics page's tap to seek plays its feedback from
-// Redesigned/Lyrics/SGRKaraokeView.m.
+// Everything on them applies at once, without a restart. The lyrics page's tap to seek plays its feedback
+// from Redesigned/Lyrics/SGRKaraokeView.m.
// Threading: main thread only.
#import <UIKit/UIKit.h>
#define SGRKeyControlHaptics @"spotifyglass.redesign.haptics.controls"
#define SGRKeyMusicHaptics @"spotifyglass.redesign.haptics.music"
+// How hard the taps are, a percentage within the range below; 100 is the feel each shipped with.
+#define SGRKeyControlStrength @"spotifyglass.redesign.haptics.controls.strength"
+#define SGRKeyMusicStrength @"spotifyglass.redesign.haptics.music.strength"
+// What Music Haptics plays along with, an SGRMusicFollows.
+#define SGRKeyMusicFollows @"spotifyglass.redesign.haptics.music.follows"
+
+// Controls go softer only: most of their taps are UIKit's at full intensity already. Music Haptics goes
+// either way: at 200% the rumble reaches 0.7 of the Taptic Engine's most, and most taps their most.
+enum {
+ SGRControlStrengthMin = 10, SGRControlStrengthMax = 100,
+ SGRMusicStrengthMin = 20, SGRMusicStrengthMax = 200,
+ SGRStrengthStep = 10,
+};
+
+typedef NS_ENUM(NSInteger, SGRMusicFollows) {
+ SGRMusicFollowsEverything, // a tap on each kick and snare, and the rumble under the bass
+ SGRMusicFollowsBeat, // a tap on each kick and snare, no rumble
+ SGRMusicFollowsBass, // a tap on each kick, and the rumble
+};
typedef NS_ENUM(NSInteger, SGRFeedback) {
SGRFeedbackPlay, // playback starts
@@ -34,7 +53,14 @@ void SGRPrepareFeedback(SGRFeedback feedback);
// From the Music Haptics switch: starts or stops listening at once.
void SGRSetMusicHapticsEnabled(BOOL on);
+// From its strength and its choice of what to follow: reads them again, for the next tap.
+void SGRMusicHapticsSettingsChanged(void);
+
+// A strength key's percentage as a factor, 1 for 100%, kept within its range.
+double SGRHapticsStrength(NSString *key);
+SGRMusicFollows SGRMusicHapticsFollows(void);
@class SGModSection;
-// The Vibrations section of the Player page.
-SGModSection *SGRVibrationsSection(void);
+// The Vibrations sections of the Player page: a card for Controls and one for Music Haptics, each opening
+// out into its settings while its switch is on.
+NSArray<SGModSection *> *SGRVibrationsSections(void);
diff --git a/tweak/Sources/Redesigned/Haptics/HapticsSettings.m b/tweak/Sources/Redesigned/Haptics/HapticsSettings.m
index 9c5ee983..2a8a3693 100644
--- a/tweak/Sources/Redesigned/Haptics/HapticsSettings.m
+++ b/tweak/Sources/Redesigned/Haptics/HapticsSettings.m
@@ -1,17 +1,75 @@
-// The Vibrations section of the Player page, in the redesign only (App/Pages.m puts it there).
+// The Vibrations sections of the Player page, in the redesign only (App/Pages.m puts them there): a card
+// per switch, the way the Audio effects page has one per effect, each opening out into its settings while
+// its switch is on. Controls has its strength; Music Haptics its strength and what it follows, a choice
+// that also says whether the rumble plays, rather than a switch of its own that one choice would leave
+// with nothing to do.
#import "Core/SGCore.h"
#import "Settings/SGModPage.h"
#import "Haptics.h"
static NSString *const kMusicHapticsInfo = @"The iPhone taps along with the drums and rumbles under the bass of whatever Spotify is playing, worked out from the sound as it plays, much like Music Haptics in Apple Music.\n\nIt follows the sound this iPhone plays, through its speaker or headphones, while Spotify is open: iOS plays no haptics for an app in the background, and a song playing on another device through Connect has no sound here to follow.";
-SGModSection *SGRVibrationsSection(void) {
+static NSArray<NSString *> *followsNames(void) {
+ return @[@"Everything", @"Beat", @"Bass"];
+}
+
+static NSArray<NSString *> *followsNotes(void) {
+ return @[@"A tap on each kick and snare, and a rumble under the bass",
+ @"A tap on each kick and snare, no rumble",
+ @"A tap on each kick, and a rumble under the bass"];
+}
+
+static void strengthRange(NSString *key, NSInteger *minimum, NSInteger *maximum) {
+ BOOL music = [key isEqualToString:SGRKeyMusicStrength];
+ *minimum = music ? SGRMusicStrengthMin : SGRControlStrengthMin;
+ *maximum = music ? SGRMusicStrengthMax : SGRControlStrengthMax;
+}
+
+double SGRHapticsStrength(NSString *key) {
+ NSInteger minimum, maximum;
+ strengthRange(key, &minimum, &maximum);
+ return MAX(minimum, MIN(maximum, SGInt(key, 100))) / 100.0;
+}
+
+SGRMusicFollows SGRMusicHapticsFollows(void) {
+ NSInteger follows = SGInt(SGRKeyMusicFollows, SGRMusicFollowsEverything);
+ return follows >= SGRMusicFollowsEverything && follows <= SGRMusicFollowsBass ? (SGRMusicFollows)follows : SGRMusicFollowsEverything;
+}
+
+// A percentage slider over a strength key, telling `changed` each step it stores.
+static SGModRow *strengthRow(NSString *key, void (^changed)(void)) {
+ NSInteger minimum, maximum;
+ strengthRange(key, &minimum, &maximum);
+ return SGSliderRow(@"Strength", nil, minimum, maximum, SGRStrengthStep,
+ ^double { return SGRHapticsStrength(key) * 100; },
+ ^(double value) {
+ SGSetInt(key, lround(value));
+ if (changed) changed();
+ },
+ ^NSString *(double value) { return [NSString stringWithFormat:@"%ld%%", lround(value)]; });
+}
+
+NSArray<SGModSection *> *SGRVibrationsSections(void) {
SGModRow *controls = SGSwitchRow(@"Controls", @"Play, pause, skipping, scrubbing, shuffle, repeat and adding a song", SGRKeyControlHaptics);
+ SGModRow *controlStrength = strengthRow(SGRKeyControlStrength, ^{
+ // Felt as it is set: a tap at the new strength with each step.
+ SGRPlayFeedback(SGRFeedbackAdd);
+ });
+ controlStrength.visible = ^BOOL { return SGEnabled(SGRKeyControlHaptics); };
+
SGModRow *music = SGOptionRow(@"Music Haptics", @"Taps and rumbles along with the music", SGRKeyMusicHaptics);
music.info = kMusicHapticsInfo;
music.changed = ^(BOOL on) { SGRSetMusicHapticsEnabled(on); };
- return SGSection(@"Vibrations", @[
- SGWithSymbol(controls, @"hand.tap"),
- SGWithSymbol(music, @"waveform"),
- ]);
+ BOOL (^musicOn)(void) = ^BOOL { return SGFlag(SGRKeyMusicHaptics, NO); };
+ SGModRow *musicStrength = strengthRow(SGRKeyMusicStrength, ^{ SGRMusicHapticsSettingsChanged(); });
+ musicStrength.visible = musicOn;
+ SGModRow *follows = SGChoiceRow(@"Follows", nil, SGRKeyMusicFollows, followsNames(), SGRMusicFollowsEverything);
+ follows.choiceNotes = followsNotes();
+ follows.chosen = ^(NSInteger index) { SGRMusicHapticsSettingsChanged(); };
+ follows.visible = musicOn;
+
+ return @[
+ SGSection(@"Vibrations", @[SGWithSymbol(controls, @"hand.tap"), controlStrength]),
+ SGSection(nil, @[SGWithSymbol(music, @"waveform"), musicStrength, follows]),
+ ];
}
diff --git a/tweak/Sources/Redesigned/Haptics/MusicHaptics.x b/tweak/Sources/Redesigned/Haptics/MusicHaptics.x
index 2b90ba66..74f2a730 100644
--- a/tweak/Sources/Redesigned/Haptics/MusicHaptics.x
+++ b/tweak/Sources/Redesigned/Haptics/MusicHaptics.x
@@ -6,11 +6,16 @@
// method between it and the unit. So Spotify's import of AudioOutputUnitStart is rebound
// (Core/SGRebind.h), and every RemoteIO unit it starts gets a render notify: after each render, the
// buffer bound for the speaker is mixed to mono and handed to the analyzer (SGRMusicAnalyzer.h) on
-// the render thread, which puts what it hears into a ring of events. The render timestamp says when
+// the render thread, which puts what it hears into a ring of events. That buffer is in the unit's output
+// format, the hardware's, not the one Spotify hands the unit (in the simulator 48 kHz float with a buffer
+// per channel, whatever the client: harness/jamesdsp/sim, harness/haptics/sim), so the analyzer runs at
+// the hardware's rate, and a listener on the format follows it to a new one. The render timestamp says when
// that buffer reaches the output; AVAudioSession's output latency (large over Bluetooth) is added, so
// a tap lands when its drum is heard. A thread of this file's own takes the events off the ring and
// schedules them with Core Haptics at those times: each hit a transient, the rumble one looping
-// continuous event whose intensity follows the level.
+// continuous event whose intensity follows the level. The strength scales both as they are played, and
+// what Music Haptics follows leaves out the snares' taps (Bass) or the rumble (Beat) there too, so a change
+// applies to the next event.
//
// The rebinding and the notify are in place while Redesigned UI is on, so the switch works at once;
// with the switch off the notify returns straight away. Nothing listens while Spotify is not the active
@@ -18,12 +23,13 @@
// output (Connect, AirPlay to another device, video) never passes the unit, and plays no haptics.
//
// Threading: the notify runs on the render thread and only touches atomics, the analyzer and the
-// ring; the Core Haptics objects belong to the player thread; the switch and the app's state are set
-// on the main thread.
+// ring; the Core Haptics objects belong to the player thread; the switch, its settings and the app's
+// state are set on the main thread.
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreHaptics/CoreHaptics.h>
#import <mach/mach_time.h>
+#import <os/lock.h>
#import <pthread.h>
#import <stdatomic.h>
#import "Core/SGCore.h"
@@ -35,7 +41,7 @@
static const double kHapticLead = 0.012;
// A tap this late is left out rather than played off the beat.
static const double kLatestTap = 0.05;
-// Taps are this strong at most, and the rumble this strong at its level's most.
+// Taps are this strong at most, and the rumble this strong at its level's most, at a strength of 100%.
static const float kTapGain = 1, kRumbleGain = 1;
// The rumble starts over this level and stops once it has stayed under the other this long.
static const float kRumbleStart = 0.05f, kRumbleStop = 0.02f;
@@ -57,8 +63,14 @@ enum { kRingSize = 1024, kMonoFrames = 4096 };
static atomic_bool sg_enabled, sg_active, sg_listening;
static atomic_uint sg_generation;
static atomic_uint_fast64_t sg_latencyBits;
-static atomic_uint sg_formatFlags, sg_lastFrames;
-static atomic_uint_fast64_t sg_sampleRateBits;
+static atomic_uint sg_lastFrames;
+// 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_sampleRateBits, sg_layout;
+static atomic_uint_fast64_t sg_skipped; // renders whose buffers were not laid out as the format says
+// The strength's factor and what is followed, set on the main thread, read on the player thread.
+static atomic_uint_fast64_t sg_strengthBits;
+static atomic_int sg_follows;
static SGRMusicEvent sg_ring[kRingSize];
static atomic_uint sg_head, sg_tail; // head moved by the render thread, tail by the player thread
@@ -92,26 +104,39 @@ static void pushEvent(const SGRMusicEvent *event, void *context) {
atomic_store_explicit(&sg_head, head + 1, memory_order_relaxed);
}
-static inline float sampleAt(const AudioBuffer *buffer, UInt32 index, UInt32 bytes, BOOL isFloat, UInt32 fraction) {
- const void *data = buffer->mData;
+static inline float sampleAt(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);
}
- if (bytes == 2) return ((const int16_t *)data)[index] / 32768.0f;
- if (bytes == 8 && isFloat) return (float)((const double *)data)[index];
- return 0;
+ return ((const int16_t *)data)[index] / 32768.0f;
}
-// Spotify's own format is float, non-interleaved stereo coming out of its EQ, but the unit's format is
-// read rather than assumed: what the buffers look like decides how they are read.
+// The hardware's format is float with a buffer per channel, but it is read rather than assumed (readFormat),
+// and buffers not laid out the way it says are left alone rather than read as noise: the format read at the
+// start can be a moment old.
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_listening, memory_order_relaxed)) return noErr;
if (*flags & kAudioUnitRenderAction_OutputIsSilence) return noErr;
+ 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 noErr;
+ 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 noErr;
+ }
+
double sampleRate = loadDouble(&sg_sampleRateBits);
static double analyzedRate;
static unsigned analyzedGeneration;
@@ -124,31 +149,17 @@ static OSStatus rendered(void *refCon, AudioUnitRenderActionFlags *flags, const
}
atomic_store_explicit(&sg_lastFrames, frames, memory_order_relaxed);
- UInt32 formatFlags = atomic_load_explicit(&sg_formatFlags, memory_order_relaxed);
- BOOL isFloat = (formatFlags & kAudioFormatFlagIsFloat) != 0;
- UInt32 fraction = (formatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift;
- const AudioBuffer *first = &data->mBuffers[0];
- BOOL split = data->mNumberBuffers > 1;
- UInt32 channels = split ? 1 : MAX(first->mNumberChannels, 1u);
- if (!first->mData || first->mDataByteSize < frames * channels) return noErr;
- UInt32 bytes = first->mDataByteSize / (frames * channels);
- const AudioBuffer *second = split && data->mBuffers[1].mData && data->mBuffers[1].mDataByteSize >= frames * bytes ? &data->mBuffers[1] : NULL;
+ // The first two channels; a mono output is both.
+ const void *left = data->mBuffers[0].mData, *right = split && channels > 1 ? data->mBuffers[1].mData : left;
+ UInt32 stride = split ? 1 : channels, rightOffset = !split && channels > 1 ? 1 : 0;
uint64_t hostTime = (timestamp->mFlags & kAudioTimeStampHostTimeValid) ? timestamp->mHostTime : mach_absolute_time();
unsigned headBefore = atomic_load_explicit(&sg_head, memory_order_relaxed);
for (UInt32 done = 0; done < frames;) {
UInt32 count = MIN(frames - done, (UInt32)kMonoFrames);
for (UInt32 i = 0; i < count; i++) {
- UInt32 frame = done + i;
- float left, right;
- if (split) {
- left = sampleAt(first, frame, bytes, isFloat, fraction);
- right = second ? sampleAt(second, frame, bytes, isFloat, fraction) : left;
- } else {
- left = sampleAt(first, frame * channels, bytes, isFloat, fraction);
- right = channels > 1 ? sampleAt(first, frame * channels + 1, bytes, isFloat, fraction) : left;
- }
- sg_mono[i] = 0.5f * (left + right);
+ UInt32 at = (done + i) * stride;
+ sg_mono[i] = 0.5f * (sampleAt(left, at, bytes, isFloat, fraction) + sampleAt(right, at + rightOffset, bytes, isFloat, fraction));
}
uint64_t chunkTime = hostTime + (uint64_t)(done / sampleRate / sg_secondsPerTick);
SGRMusicAnalyzerProcess(&sg_analyzer, sg_mono, count, chunkTime, pushEvent, NULL);
@@ -167,26 +178,63 @@ static NSString *fourCC(UInt32 code) {
return @(text);
}
+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: the RemoteIO unit's output side (element 0, output scope), the
+// hardware's, not the one Spotify hands the unit (the input scope). A format the analyzer cannot read
+// leaves the buffers alone.
+static void 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:@"music haptics: listening to Spotify's output at %@, from %@ Spotify hands it%@", formatText(format),
+ formatText(client), takes ? @"" : [NSString stringWithFormat:@"; not a format the analyzer reads (status %d), nothing plays", (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);
+ return;
+ }
+ storeDouble(&sg_sampleRateBits, format.mSampleRate);
+ atomic_store(&sg_layout, (uint64_t)format.mFormatFlags | (uint64_t)(format.mChannelsPerFrame & 0xffff) << 32 | (uint64_t)bytes << 48);
+}
+
+// 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) {
AudioComponentDescription description = {0};
if (AudioComponentGetDescription(AudioComponentInstanceGetComponent(unit), &description) != noErr) return;
- static int logged;
if (description.componentType != kAudioUnitType_Output || description.componentSubType != kAudioUnitSubType_RemoteIO) {
+ static int logged;
if (logged++ < 8) SGLog(@"music haptics: a started unit is not RemoteIO ('%@' '%@'), not listened to", fourCC(description.componentType), fourCC(description.componentSubType));
return;
}
- AudioStreamBasicDescription format = {0};
- UInt32 size = sizeof(format);
- OSStatus status = AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, &size);
- if (status != noErr || format.mFormatID != kAudioFormatLinearPCM || format.mSampleRate <= 0) {
- if (logged++ < 8) SGLog(@"music haptics: the output's format is not linear PCM (%d, '%@'), not listened to", (int)status, fourCC(format.mFormatID));
- return;
- }
- atomic_store(&sg_formatFlags, format.mFormatFlags);
- storeDouble(&sg_sampleRateBits, format.mSampleRate);
AudioUnitRemoveRenderNotify(unit, rendered, NULL);
- status = AudioUnitAddRenderNotify(unit, rendered, NULL);
- if (logged++ < 8) SGLog(@"music haptics: listening to Spotify's output, %.0f Hz, %u channels, %u bits, flags 0x%x (status %d)", format.mSampleRate, (unsigned)format.mChannelsPerFrame, (unsigned)format.mBitsPerChannel, (unsigned)format.mFormatFlags, (int)status);
+ AudioUnitRemovePropertyListenerWithUserData(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);
+ AudioUnitAddPropertyListener(unit, kAudioUnitProperty_StreamFormat, formatChanged, NULL);
+ readFormat(unit);
+ OSStatus status = AudioUnitAddRenderNotify(unit, rendered, NULL);
+ if (status != noErr) SGLog(@"music haptics: the render notify could not be added (%d)", (int)status);
}
static OSStatus startOutput(AudioUnit unit) {
@@ -214,6 +262,10 @@ static double hostSeconds(uint64_t ticks) {
return ticks * sg_secondsPerTick;
}
+static float strength(void) {
+ return (float)loadDouble(&sg_strengthBits);
+}
+
static BOOL startEngine(void) {
static BOOL supported, checked;
static double retryAt;
@@ -288,7 +340,7 @@ static void playTap(const SGRMusicEvent *event) {
return;
}
CHHapticEvent *hit = [[CHHapticEvent alloc] initWithEventType:CHHapticEventTypeHapticTransient parameters:@[
- parameter(CHHapticEventParameterIDHapticIntensity, MIN(1, event->intensity * kTapGain)),
+ parameter(CHHapticEventParameterIDHapticIntensity, MIN(1, event->intensity * kTapGain * strength())),
parameter(CHHapticEventParameterIDHapticSharpness, event->sharpness),
] relativeTime:0];
NSError *error = nil;
@@ -316,7 +368,9 @@ static void playLevel(const SGRMusicEvent *event) {
double lead;
NSTimeInterval at = engineTime(event->hostTime, &lead);
double heard = hostSeconds(event->hostTime);
+ // Whether it rumbles is decided at 100%, so the strength changes how hard, not how often.
float level = MIN(1, event->intensity * kRumbleGain);
+ float played = MIN(1, level * strength());
if (level < kRumbleStop) {
if (!sg_quietSince) sg_quietSince = heard;
@@ -344,7 +398,7 @@ static void playLevel(const SGRMusicEvent *event) {
}
}
NSArray<CHHapticDynamicParameter *> *controls = @[
- [[CHHapticDynamicParameter alloc] initWithParameterID:CHHapticDynamicParameterIDHapticIntensityControl value:level relativeTime:0],
+ [[CHHapticDynamicParameter alloc] initWithParameterID:CHHapticDynamicParameterIDHapticIntensityControl value:played relativeTime:0],
[[CHHapticDynamicParameter alloc] initWithParameterID:CHHapticDynamicParameterIDHapticSharpnessControl value:event->sharpness relativeTime:0],
];
if (!sg_rumbling) {
@@ -371,9 +425,10 @@ static void report(void) {
if (now - lastReport < 30 || reports >= 4 || !sg_stats.levels) return;
lastReport = now;
reports++;
- SGLog(@"music haptics: %lu taps (%lu too late), lead %.0f ms on average and %.0f ms at the least, %lu levels, rumble %@, buffers of %u frames, output latency %.0f ms",
+ SGLog(@"music haptics: %lu taps (%lu too late), lead %.0f ms on average and %.0f ms at the least, %lu levels, rumble %@, buffers of %u frames at %.0f Hz (%llu skipped), output latency %.0f ms, strength %.0f%%, follows %d",
(unsigned long)sg_stats.taps, (unsigned long)sg_stats.late, sg_stats.taps ? sg_stats.leadSum / sg_stats.taps * 1000 : 0, sg_stats.leadMin * 1000,
- (unsigned long)sg_stats.levels, sg_rumbling ? @"on" : @"off", atomic_load(&sg_lastFrames), loadDouble(&sg_latencyBits) * 1000);
+ (unsigned long)sg_stats.levels, sg_rumbling ? @"on" : @"off", atomic_load(&sg_lastFrames), loadDouble(&sg_sampleRateBits),
+ (unsigned long long)atomic_load(&sg_skipped), loadDouble(&sg_latencyBits) * 1000, strength() * 100, atomic_load(&sg_follows));
sg_stats = (Stats){0};
}
@@ -398,13 +453,19 @@ static void *playerLoop(void *unused) {
idle = YES;
continue;
}
+ SGRMusicFollows follows = (SGRMusicFollows)atomic_load(&sg_follows);
+ BOOL rumbles = follows != SGRMusicFollowsBeat, snares = follows != SGRMusicFollowsBass;
+ if (!rumbles) stopRumble(CHHapticTimeImmediate);
BOOL any = NO;
unsigned head = atomic_load(&sg_head), tail = atomic_load(&sg_tail);
if (tail != head && startEngine()) {
for (; tail != head; tail++) {
SGRMusicEvent event = sg_ring[tail & (kRingSize - 1)];
- if (event.kind == SGRMusicEventTap) playTap(&event);
- else playLevel(&event);
+ if (event.kind == SGRMusicEventLevel) {
+ if (rumbles) playLevel(&event);
+ } else if (event.kind == SGRMusicEventKick || snares) {
+ playTap(&event);
+ }
}
any = YES;
}
@@ -459,6 +520,18 @@ void SGRSetMusicHapticsEnabled(BOOL on) {
updateListening();
}
+static void readSettings(void) {
+ storeDouble(&sg_strengthBits, SGRHapticsStrength(SGRKeyMusicStrength));
+ atomic_store(&sg_follows, (int)SGRMusicHapticsFollows());
+}
+
+void SGRMusicHapticsSettingsChanged(void) {
+ if (!SGRedesignedUI() || !sg_wake) return;
+ readSettings();
+ // A rumble that is not to play any more stops now rather than with the next event.
+ dispatch_semaphore_signal(sg_wake);
+}
+
%ctor {
if (!SGRedesignedUI()) return;
mach_timebase_info_data_t timebase;
@@ -469,6 +542,7 @@ void SGRSetMusicHapticsEnabled(BOOL on) {
return;
}
sg_wake = dispatch_semaphore_create(0);
+ readSettings();
atomic_store(&sg_enabled, SGFlag(SGRKeyMusicHaptics, NO));
NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
[center addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
diff --git a/tweak/Sources/Redesigned/Haptics/SGRFeedback.m b/tweak/Sources/Redesigned/Haptics/SGRFeedback.m
index 1cca3236..53063887 100644
--- a/tweak/Sources/Redesigned/Haptics/SGRFeedback.m
+++ b/tweak/Sources/Redesigned/Haptics/SGRFeedback.m
@@ -3,6 +3,10 @@
// under the finger (Apple's Playing haptics: impact complements a physical action, selection a changing
// value). Starting playback is a crisp tap and stopping it a soft one, so the two can be told apart
// without looking.
+//
+// Controls' strength scales every impact's intensity. A selection tick has no intensity to scale, so under
+// 100% it becomes a rigid impact, the nearest thing UIKit has to it, at about a tick's weight times the
+// strength; at 100% it stays the system's own tick.
#import "Core/SGCore.h"
#import "Haptics.h"
@@ -12,6 +16,8 @@ typedef struct {
} Tap;
static const NSInteger kSelection = -1;
+// A rigid impact at this intensity stands in for a selection tick (a bet: UIKit gives the tick no number).
+static const CGFloat kTickIntensity = 0.5;
static Tap tapFor(SGRFeedback feedback) {
switch (feedback) {
@@ -28,6 +34,14 @@ static Tap tapFor(SGRFeedback feedback) {
return (Tap){kSelection, 1};
}
+static Tap tapAtStrength(SGRFeedback feedback) {
+ Tap tap = tapFor(feedback);
+ double strength = SGRHapticsStrength(SGRKeyControlStrength);
+ if (strength >= 1) return tap;
+ if (tap.style == kSelection) return (Tap){UIImpactFeedbackStyleRigid, kTickIntensity * strength};
+ return (Tap){tap.style, tap.intensity * strength};
+}
+
static UIFeedbackGenerator *generatorFor(NSInteger style) {
static NSMutableDictionary<NSNumber *, UIFeedbackGenerator *> *generators;
if (!generators) generators = [NSMutableDictionary dictionary];
@@ -41,7 +55,7 @@ static UIFeedbackGenerator *generatorFor(NSInteger style) {
void SGRPlayFeedback(SGRFeedback feedback) {
if (!SGEnabled(SGRKeyControlHaptics)) return;
- Tap tap = tapFor(feedback);
+ Tap tap = tapAtStrength(feedback);
UIFeedbackGenerator *generator = generatorFor(tap.style);
if (tap.style == kSelection) [(UISelectionFeedbackGenerator *)generator selectionChanged];
else [(UIImpactFeedbackGenerator *)generator impactOccurredWithIntensity:tap.intensity];
@@ -49,5 +63,5 @@ void SGRPlayFeedback(SGRFeedback feedback) {
void SGRPrepareFeedback(SGRFeedback feedback) {
if (!SGEnabled(SGRKeyControlHaptics)) return;
- [generatorFor(tapFor(feedback).style) prepare];
+ [generatorFor(tapAtStrength(feedback).style) prepare];
}
diff --git a/tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.h b/tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.h
index 2fd11cee..1a3cfda5 100644
--- a/tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.h
+++ b/tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.h
@@ -16,8 +16,10 @@
// allocates, locks, logs or sends a message. Compiles on the Mac as is, for tuning against a file.
#import <Foundation/Foundation.h>
+// A hit says which band it came from, so what Music Haptics follows (Haptics.h) can leave some out.
typedef NS_ENUM(uint8_t, SGRMusicEventKind) {
- SGRMusicEventTap, // a hit: one transient
+ SGRMusicEventKick, // a hit in the bass (a kick, an 808): one transient
+ SGRMusicEventSnare, // a hit in the top (a snare, a clap): one transient
SGRMusicEventLevel, // the continuous vibration from here on, sent about 60 times a second
};
diff --git a/tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.m b/tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.m
index a0f99e0e..977b2941 100644
--- a/tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.m
+++ b/tweak/Sources/Redesigned/Haptics/SGRMusicAnalyzer.m
@@ -158,7 +158,6 @@ static int listen(SGRMusicAnalyzer *analyzer, SGRMusicBand *band, const BandTuni
float over = 10 * log10(band->pendingRatio / tuning->ratio);
float strength = clamp01(over / tuning->rangeDb);
float loud = clamp01((band->pendingDb - (loudDbOf(band, tuning) - kLoudRangeDb)) / kLoudRangeDb);
- event->kind = SGRMusicEventTap;
event->hostTime = band->pendingTime;
event->intensity = (0.45f + 0.55f * strength) * (0.3f + 0.7f * loud);
event->sharpness = band->pendingBright;
@@ -212,12 +211,14 @@ static void endHop(SGRMusicAnalyzer *analyzer, SGRMusicEmit emit, void *context)
SGRMusicEvent event;
analyzer->sinceKick++;
if (listen(analyzer, &analyzer->kick, &kKickTuning, low, time, bright, midRatio, &event)) {
+ event.kind = SGRMusicEventKick;
event.sharpness = 0.15f + 0.3f * event.sharpness;
analyzer->sinceKick = 0;
emit(&event, context);
}
if (listen(analyzer, &analyzer->snap, &kSnapTuning, high, time, bright, midRatio, &event)) {
if (analyzer->sinceKick * hop > kSnapAfterKickSeconds) {
+ event.kind = SGRMusicEventSnare;
event.intensity *= 0.8f;
event.sharpness = 0.55f + 0.4f * event.sharpness;
emit(&event, context);
diff --git a/tweak/Sources/Redesigned/Player/PlayerSpeedPitch.x b/tweak/Sources/Redesigned/Player/PlayerSpeedPitch.x
index d2d44071..37a192bb 100644
--- a/tweak/Sources/Redesigned/Player/PlayerSpeedPitch.x
+++ b/tweak/Sources/Redesigned/Player/PlayerSpeedPitch.x
@@ -23,7 +23,9 @@
//
// When the connection is never seen, pitch falls back to the way it first shipped: a render notify on the
// RemoteIO unit (after Music Haptics' own rebinding of AudioOutputUnitStart) runs each finished buffer
-// through a unit working in place; speed is then unavailable.
+// through a unit working in place; speed is then unavailable. Those buffers are in the unit's output format,
+// the hardware's, not the one Spotify hands the unit (harness/jamesdsp/sim), so the fallback's unit is made
+// for that one.
//
// Speed and pitch last until Spotify quits.
//
@@ -59,9 +61,13 @@ static _Atomic(SGRTimePitch *) sg_pull, sg_inPlace;
static atomic_bool sg_engaged, sg_busy;
static pthread_mutex_t sg_buildLock = PTHREAD_MUTEX_INITIALIZER;
-// The output's format when Spotify started it, for the in place fallback.
-static atomic_uint_fast64_t sg_rateBits;
-static atomic_uint sg_formatFlags, sg_formatChannels, sg_formatBytes;
+// The formats when Spotify started its output: the one it hands the RemoteIO unit, which the chain's unit
+// feeds, and the unit's output side, the hardware's, which the in place fallback's notify gets.
+typedef struct {
+ atomic_uint_fast64_t rateBits;
+ atomic_uint flags, channels, bytes;
+} Format;
+static Format sg_client, sg_hardware;
static BOOL tapped(void) {
return atomic_load(&sg_source) != NULL;
@@ -179,8 +185,8 @@ static inline void writeSample(void *data, UInt32 index, float value, UInt32 byt
}
static void shiftInPlace(SGRTimePitch *unit, AudioUnitRenderActionFlags *flags, UInt32 frames, AudioBufferList *data) {
- UInt32 formatFlags = atomic_load_explicit(&sg_formatFlags, memory_order_relaxed);
- UInt32 bytes = atomic_load_explicit(&sg_formatBytes, memory_order_relaxed);
+ UInt32 formatFlags = atomic_load_explicit(&sg_hardware.flags, memory_order_relaxed);
+ UInt32 bytes = atomic_load_explicit(&sg_hardware.bytes, memory_order_relaxed);
UInt32 channels = SGRTimePitchChannels(unit);
BOOL isFloat = (formatFlags & kAudioFormatFlagIsFloat) != 0;
BOOL split = (formatFlags & kAudioFormatFlagIsNonInterleaved) != 0;
@@ -265,24 +271,33 @@ static OSStatus setProperty(AudioUnit unit, AudioUnitPropertyID property, AudioU
static OSStatus (*sg_startOutput)(AudioUnit unit);
+// One side of the RemoteIO unit's element 0 into `into`; a side that is not linear PCM is left as it was.
+static BOOL readScope(AudioUnit unit, AudioUnitScope scope, Format *into, AudioStreamBasicDescription *format) {
+ UInt32 size = sizeof *format;
+ OSStatus status = AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, scope, 0, format, &size);
+ if (status != noErr || format->mFormatID != kAudioFormatLinearPCM || format->mSampleRate <= 0) return NO;
+ uint64_t bits;
+ memcpy(&bits, &format->mSampleRate, sizeof bits);
+ atomic_store(&into->rateBits, bits);
+ atomic_store(&into->flags, format->mFormatFlags);
+ atomic_store(&into->channels, format->mChannelsPerFrame);
+ atomic_store(&into->bytes, format->mBitsPerChannel / 8);
+ return YES;
+}
+
static void readFormat(AudioUnit unit) {
- AudioStreamBasicDescription format = {0};
- UInt32 size = sizeof format;
- OSStatus status = AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, &size);
+ AudioStreamBasicDescription client = {0}, hardware = {0};
+ BOOL clientRead = readScope(unit, kAudioUnitScope_Input, &sg_client, &client);
+ BOOL hardwareRead = readScope(unit, kAudioUnitScope_Output, &sg_hardware, &hardware);
static int logged;
- if (status != noErr || format.mFormatID != kAudioFormatLinearPCM || format.mSampleRate <= 0) {
- if (logged++ < 6) SGLog(@"redesign speed: the output is not linear PCM (%d)", (int)status);
- return;
+ if (!clientRead || !hardwareRead) {
+ if (logged++ < 6) SGLog(@"redesign speed: the output is not linear PCM (Spotify's side %@, the hardware's %@)", clientRead ? @"is" : @"is not", hardwareRead ? @"is" : @"is not");
+ if (!clientRead) return;
}
- uint64_t bits;
- memcpy(&bits, &format.mSampleRate, sizeof bits);
- atomic_store(&sg_rateBits, bits);
- atomic_store(&sg_formatFlags, format.mFormatFlags);
- atomic_store(&sg_formatChannels, format.mChannelsPerFrame);
- atomic_store(&sg_formatBytes, format.mBitsPerChannel / 8);
- if (logged++ < 6) SGLog(@"redesign speed: Spotify's output is %.0f Hz, %u channels, %u bits, flags 0x%x, slices of %u, %@",
- format.mSampleRate, (unsigned)format.mChannelsPerFrame, (unsigned)format.mBitsPerChannel,
- (unsigned)format.mFormatFlags, atomic_load(&sg_chunk), tapped() ? @"fed through the menu's unit" : @"not taken over");
+ if (logged++ < 6) SGLog(@"redesign speed: Spotify's output is %.0f Hz, %u channels, %u bits, flags 0x%x, into the hardware's %.0f Hz, %u channels, %u bits, flags 0x%x, slices of %u, %@",
+ client.mSampleRate, (unsigned)client.mChannelsPerFrame, (unsigned)client.mBitsPerChannel, (unsigned)client.mFormatFlags,
+ hardware.mSampleRate, (unsigned)hardware.mChannelsPerFrame, (unsigned)hardware.mBitsPerChannel, (unsigned)hardware.mFormatFlags,
+ atomic_load(&sg_chunk), tapped() ? @"fed through the menu's unit" : @"not taken over");
}
static void apply(void);
@@ -311,15 +326,16 @@ static void disengage(void) {
// The unit for the output's format and the way in use, made when there is none or the format changed. A
// replaced one is never freed: the render thread may still hold it, and a format change is rare.
static SGRTimePitch *unitForFormat(void) {
+ BOOL pull = tapped();
+ Format *format = pull ? &sg_client : &sg_hardware;
double rate;
- uint64_t bits = atomic_load(&sg_rateBits);
+ uint64_t bits = atomic_load(&format->rateBits);
memcpy(&rate, &bits, sizeof rate);
- UInt32 channels = atomic_load(&sg_formatChannels);
- BOOL pull = tapped();
+ UInt32 channels = atomic_load(&format->channels);
if (pull) {
// In the chain the unit hands its buffers to the RemoteIO unit as they are: float, one per channel.
- UInt32 flags = atomic_load(&sg_formatFlags);
- BOOL canonical = (flags & kAudioFormatFlagIsFloat) && (flags & kAudioFormatFlagIsNonInterleaved) && atomic_load(&sg_formatBytes) == 4;
+ UInt32 flags = atomic_load(&format->flags);
+ BOOL canonical = (flags & kAudioFormatFlagIsFloat) && (flags & kAudioFormatFlagIsNonInterleaved) && atomic_load(&format->bytes) == 4;
if (!canonical) {
static int logged;
if (logged++ < 3) SGLog(@"redesign speed: the output is not float per channel (flags 0x%x), speed cannot apply", (unsigned)flags);
diff --git a/tweak/Sources/Settings/SGModPage.h b/tweak/Sources/Settings/SGModPage.h
index 1e600336..72644932 100644
--- a/tweak/Sources/Settings/SGModPage.h
+++ b/tweak/Sources/Settings/SGModPage.h
@@ -1,7 +1,8 @@
// A page of sections of rows, the shape of every feature's settings page.
#import "SGPage.h"
-// A row is a switch when it has a key and a link to another page when it has a page. A flag row
+// A row is a switch when it has a key, a link to another page when it has a page and a slider when it has
+// a number. A flag row
// switches one of Spotify's remote-config flags: on forces it (off for a forceOff row, which is how
// a flag Spotify ships on is turned off), the switch off leaves Spotify's own value. A row
// with a value reads one out on the right and is asked again while the page is open; a page row
@@ -25,6 +26,18 @@
@property (nonatomic) BOOL glows;
// An ⓘ button beside the row's switch, whose tap reads this out under the row's title.
@property (nonatomic, copy) NSString *info;
+// The row shows only while this answers YES, asked again whenever a switch on the page is flipped or the
+// page comes back from a choice's list: the row fades in or out where it sits. Nil shows it always.
+@property (nonatomic, copy) BOOL (^visible)(void);
+// A choice row's: a line under each name in its list, in the same order, and what runs once one is stored.
+@property (nonatomic, copy) NSArray<NSString *> *choiceNotes;
+@property (nonatomic, copy) void (^chosen)(NSInteger index);
+// A slider row's (SGSliderRow): its range and step, and the blocks that read its number, store one and
+// write one out.
+@property (nonatomic) double minimum, maximum, step;
+@property (nonatomic, copy) double (^number)(void);
+@property (nonatomic, copy) void (^setNumber)(double value);
+@property (nonatomic, copy) NSString *(^format)(double value);
@end
@interface SGModSection : NSObject
@@ -56,6 +69,11 @@ SGModRow *SGPageRow(NSString *title, UIViewController *(^page)(void));
// A setting picked from a list of names, stored under `key` as the index into it: the row reads the
// name of the current one out and opens a list of them, a checkmark against that one.
SGModRow *SGChoiceRow(NSString *title, NSString *subtitle, NSString *key, NSArray<NSString *> *choices, NSInteger fallback);
+// A number on a slider under the row's title, written out by `format` on the right: the thumb snaps to
+// `step` and each step is stored through `set` as the thumb reaches it, so a setting applying as it
+// changes applies while it is dragged. `subtitle` may be nil.
+SGModRow *SGSliderRow(NSString *title, NSString *subtitle, double minimum, double maximum, double step,
+ double (^get)(void), void (^set)(double value), NSString *(^format)(double value));
SGModRow *SGLinkRow(NSString *title, NSString *subtitle, NSString *url);
SGModRow *SGStatActionRow(NSString *title, NSString *subtitle, NSString *(^value)(void), void (^action)(void));
SGModSection *SGSection(NSString *title, NSArray<SGModRow *> *rows);
diff --git a/tweak/Sources/Settings/SGModPage.m b/tweak/Sources/Settings/SGModPage.m
index db99bec4..5bd18847 100644
--- a/tweak/Sources/Settings/SGModPage.m
+++ b/tweak/Sources/Settings/SGModPage.m
@@ -1,3 +1,4 @@
+#import <CoreText/SFNTLayoutTypes.h>
#import "SGModPage.h"
#import "SGPageStyle.h"
#import "SGGlowSwitch.h"
@@ -86,25 +87,30 @@ SGModRow *SGPageRow(NSString *title, UIViewController *(^page)(void)) {
return row;
}
-// The list a choice row opens: the names it was given, a green checkmark against the one set.
-// Picking one writes the index and goes back, where the row it came from reads the new name out
-// and the page it sits on rebuilds around it.
+// The list a choice row opens: the names it was given, each over its note where it has one, a green
+// checkmark against the one set. Picking one writes the index, tells the row, and goes back, where the row
+// it came from reads the new name out and the page it sits on rebuilds around it.
@interface SGChoicePage : SGPage
-- (instancetype)initWithTitle:(NSString *)title key:(NSString *)key choices:(NSArray<NSString *> *)choices fallback:(NSInteger)fallback;
+- (instancetype)initWithTitle:(NSString *)title key:(NSString *)key choices:(NSArray<NSString *> *)choices notes:(NSArray<NSString *> *)notes
+ fallback:(NSInteger)fallback chosen:(void (^)(NSInteger index))chosen;
@end
@implementation SGChoicePage {
NSString *_key;
- NSArray<NSString *> *_choices;
+ NSArray<NSString *> *_choices, *_notes;
NSInteger _fallback;
+ void (^_chosen)(NSInteger index);
}
-- (instancetype)initWithTitle:(NSString *)title key:(NSString *)key choices:(NSArray<NSString *> *)choices fallback:(NSInteger)fallback {
+- (instancetype)initWithTitle:(NSString *)title key:(NSString *)key choices:(NSArray<NSString *> *)choices notes:(NSArray<NSString *> *)notes
+ fallback:(NSInteger)fallback chosen:(void (^)(NSInteger index))chosen {
if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;
self.title = title;
_key = key;
_choices = choices;
+ _notes = notes;
_fallback = fallback;
+ _chosen = chosen;
return self;
}
@@ -128,7 +134,8 @@ SGModRow *SGPageRow(NSString *title, UIViewController *(^page)(void)) {
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
UITableViewCell *cell = SGDequeueCell(table, @"choice");
- SGFillCell(cell, _choices[(NSUInteger)path.row], nil, nil, nil);
+ NSUInteger index = (NSUInteger)path.row;
+ SGFillCell(cell, _choices[index], index < _notes.count ? _notes[index] : nil, nil, nil);
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
if (path.row == SGInt(_key, _fallback)) {
UIImageView *tick = SGSymbolView(@"checkmark", 13, UIImageSymbolWeightSemibold, 16);
@@ -141,6 +148,7 @@ SGModRow *SGPageRow(NSString *title, UIViewController *(^page)(void)) {
- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
[table deselectRowAtIndexPath:path animated:NO];
SGSetInt(_key, path.row);
+ if (_chosen) _chosen(path.row);
[table reloadData];
[self.navigationController popViewControllerAnimated:YES];
}
@@ -148,7 +156,8 @@ SGModRow *SGPageRow(NSString *title, UIViewController *(^page)(void)) {
@end
// No key on the row: the key lives in the blocks, so the page draws the row as the link it is
-// rather than as a switch.
+// rather than as a switch. The notes and the callback are read off the row when its list opens, so they
+// can be set after this returns.
SGModRow *SGChoiceRow(NSString *title, NSString *subtitle, NSString *key, NSArray<NSString *> *choices, NSInteger fallback) {
SGModRow *row = [SGModRow new];
row.title = title;
@@ -157,12 +166,27 @@ SGModRow *SGChoiceRow(NSString *title, NSString *subtitle, NSString *key, NSArra
NSInteger index = SGInt(key, fallback);
return index >= 0 && index < (NSInteger)choices.count ? choices[(NSUInteger)index] : choices.firstObject;
};
+ __weak SGModRow *weakRow = row;
row.page = ^UIViewController *{
- return [[SGChoicePage alloc] initWithTitle:title key:key choices:choices fallback:fallback];
+ return [[SGChoicePage alloc] initWithTitle:title key:key choices:choices notes:weakRow.choiceNotes fallback:fallback chosen:weakRow.chosen];
};
return row;
}
+SGModRow *SGSliderRow(NSString *title, NSString *subtitle, double minimum, double maximum, double step,
+ double (^get)(void), void (^set)(double value), NSString *(^format)(double value)) {
+ SGModRow *row = [SGModRow new];
+ row.title = title;
+ row.subtitle = subtitle;
+ row.minimum = minimum;
+ row.maximum = maximum;
+ row.step = step;
+ row.number = get;
+ row.setNumber = set;
+ row.format = format;
+ return row;
+}
+
SGModRow *SGLinkRow(NSString *title, NSString *subtitle, NSString *url) {
return SGActionRow(title, subtitle, ^{ SGOpenURL(url); });
}
@@ -234,8 +258,147 @@ static BOOL lockedRowOn(SGModRow *row) {
return value ? [value boolValue] != row.forceOff : YES;
}
+#pragma mark - the slider row
+
+// On the row's step, counted from its minimum, without the float noise of getting there.
+static double snapped(SGModRow *row, double value) {
+ if (row.step > 0) value = row.minimum + round(round((value - row.minimum) / row.step) * row.step * 1e6) / 1e6;
+ return MAX(row.minimum, MIN(row.maximum, value));
+}
+
+// Figures that do not shift sideways as they change, in whatever face the titles are in.
+static UIFont *tabular(UIFont *font) {
+ UIFontDescriptor *descriptor = [font.fontDescriptor fontDescriptorByAddingAttributes:@{
+ UIFontDescriptorFeatureSettingsAttribute: @[@{UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType),
+ UIFontFeatureSelectorIdentifierKey: @(kMonospacedNumbersSelector)}],
+ }];
+ return [UIFont fontWithDescriptor:descriptor size:font.pointSize];
+}
+
+// A step at a time for VoiceOver, or a twentieth of the range where the steps are too fine to swipe through.
+@interface SGModSlider : UISlider
+@property (nonatomic) float spokenStep;
+@end
+
+@implementation SGModSlider
+
+- (void)accessibilityIncrement {
+ self.value += self.spokenStep;
+ [self sendActionsForControlEvents:UIControlEventValueChanged];
+}
+
+- (void)accessibilityDecrement {
+ self.value -= self.spokenStep;
+ [self sendActionsForControlEvents:UIControlEventValueChanged];
+}
+
+@end
+
+// The Audio effects page's slider row (Shared/JamesDSP/JamesDSPPage.m), for any page: the title and the
+// value over a slider in the accent colour, a subtitle between them when there is one, each step stored
+// as the thumb reaches it.
+@interface SGModSliderCell : UITableViewCell
++ (CGFloat)heightFor:(SGModRow *)row;
+- (void)showRow:(SGModRow *)row;
+@end
+
+@implementation SGModSliderCell {
+ SGModRow *_row;
+ UILabel *_title, *_subtitle, *_value;
+ SGModSlider *_slider;
+ double _shown;
+ BOOL _detents; // few enough steps that the thumb jumps between them as it is dragged
+}
+
+static const CGFloat kSliderTop = 12, kSliderLine = 18, kSliderSubtitle = 14, kSliderGap = 6, kSliderHeight = 28, kSliderBottom = 10;
+
++ (CGFloat)heightFor:(SGModRow *)row {
+ return kSliderTop + kSliderLine + (row.subtitle ? kSliderSubtitle : 0) + kSliderGap + kSliderHeight + kSliderBottom;
+}
+
+- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)identifier {
+ if (!(self = [super initWithStyle:style reuseIdentifier:identifier])) return nil;
+ self.selectionStyle = UITableViewCellSelectionStyleNone;
+ _title = [UILabel new];
+ _title.textColor = UIColor.whiteColor;
+ _title.isAccessibilityElement = NO;
+ _subtitle = [UILabel new];
+ _subtitle.textColor = SGGrey();
+ _subtitle.isAccessibilityElement = NO;
+ _value = [UILabel new];
+ _value.textColor = SGGrey();
+ _value.textAlignment = NSTextAlignmentRight;
+ _value.isAccessibilityElement = NO;
+ _slider = [SGModSlider new];
+ _slider.maximumTrackTintColor = [UIColor colorWithWhite:1 alpha:0.16];
+ [_slider addTarget:self action:@selector(moved) forControlEvents:UIControlEventValueChanged];
+ [_slider addTarget:self action:@selector(released) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchCancel];
+ for (UIView *view in @[_title, _subtitle, _value, _slider]) [self.contentView addSubview:view];
+ return self;
+}
+
+- (void)showRow:(SGModRow *)row {
+ _row = row;
+ NSInteger count = row.step > 0 ? (NSInteger)lround((row.maximum - row.minimum) / row.step) : 0;
+ _detents = count > 0 && count <= 24;
+ _title.font = SGTitleFont();
+ _subtitle.font = SGSubtitleFont();
+ _value.font = tabular(SGTitleFont());
+ _title.text = row.title;
+ _subtitle.text = row.subtitle;
+ _subtitle.hidden = !row.subtitle;
+ _slider.minimumTrackTintColor = SGGreen();
+ _slider.minimumValue = (float)row.minimum;
+ _slider.maximumValue = (float)row.maximum;
+ _slider.spokenStep = (float)(count > 0 && count <= 40 ? row.step : snapped(row, row.minimum + (row.maximum - row.minimum) / 20) - row.minimum);
+ _shown = snapped(row, row.number());
+ _slider.value = (float)_shown;
+ _slider.accessibilityLabel = row.title;
+ _slider.accessibilityHint = row.subtitle;
+ [self showValue];
+}
+
+- (void)showValue {
+ _value.text = _row.format ? _row.format(_shown) : [NSString stringWithFormat:@"%g", _shown];
+ _slider.accessibilityValue = _value.text;
+ [self setNeedsLayout];
+}
+
+- (void)layoutSubviews {
+ [super layoutSubviews];
+ CGFloat width = self.contentView.bounds.size.width, side = 16, y = kSliderTop;
+ [_value sizeToFit];
+ CGFloat valueWidth = MAX(_value.bounds.size.width, 44);
+ _value.frame = CGRectMake(width - side - valueWidth, y, valueWidth, kSliderLine);
+ _title.frame = CGRectMake(side, y, CGRectGetMinX(_value.frame) - side - 8, kSliderLine);
+ y += kSliderLine;
+ if (_row.subtitle) {
+ _subtitle.frame = CGRectMake(side, y, width - 2 * side, kSliderSubtitle);
+ y += kSliderSubtitle;
+ }
+ _slider.frame = CGRectMake(side, y + kSliderGap, width - 2 * side, kSliderHeight);
+}
+
+- (void)moved {
+ double value = snapped(_row, _slider.value);
+ if (_detents) _slider.value = (float)value;
+ if (value == _shown) return;
+ _shown = value;
+ if (_row.setNumber) _row.setNumber(value);
+ [self showValue];
+}
+
+- (void)released {
+ [_slider setValue:(float)_shown animated:YES];
+}
+
+@end
+
+#pragma mark - the page
+
@implementation SGModPage {
NSArray<SGModSection *> *_sections;
+ NSArray<NSArray<SGModRow *> *> *_shown; // each section's rows that show now (SGModRow.visible)
UIView *_intro;
UIView *_footer;
NSTimer *_ticker;
@@ -246,6 +409,7 @@ static BOOL lockedRowOn(SGModRow *row) {
if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;
self.title = title;
_sections = sections;
+ _shown = [self rowsToShow];
_intro = intro ? SGNote(intro) : nil;
_footer = footer ? SGNote(footer) : nil;
// A page row reads its value out when the page appears rather than on the ticker, so only the
@@ -254,6 +418,58 @@ static BOOL lockedRowOn(SGModRow *row) {
return self;
}
+- (NSArray<NSArray<SGModRow *> *> *)rowsToShow {
+ NSMutableArray<NSArray<SGModRow *> *> *shown = [NSMutableArray arrayWithCapacity:_sections.count];
+ for (SGModSection *s in _sections) {
+ NSMutableArray<SGModRow *> *rows = [NSMutableArray arrayWithCapacity:s.rows.count];
+ for (SGModRow *row in s.rows) if (!row.visible || row.visible()) [rows addObject:row];
+ [shown addObject:rows];
+ }
+ return shown;
+}
+
+// The rows that are to show now fade in where they sit and the others fade out, and whatever came in is
+// scrolled into view: it opens under the switch that brought it, which may be the page's last row. Answers
+// whether anything moved; `done` runs once it has, and only then.
+- (BOOL)showRowsThen:(void (^)(void))done {
+ NSArray<NSArray<SGModRow *> *> *next = [self rowsToShow];
+ if ([next isEqualToArray:_shown]) return NO;
+ NSMutableArray<NSIndexPath *> *gone = [NSMutableArray array], *coming = [NSMutableArray array];
+ [_sections enumerateObjectsUsingBlock:^(SGModSection *s, NSUInteger section, BOOL *stop) {
+ NSArray<SGModRow *> *before = self->_shown[section], *after = next[section];
+ [before enumerateObjectsUsingBlock:^(SGModRow *row, NSUInteger i, BOOL *stop) {
+ if (![after containsObject:row]) [gone addObject:[NSIndexPath indexPathForRow:(NSInteger)i inSection:(NSInteger)section]];
+ }];
+ [after enumerateObjectsUsingBlock:^(SGModRow *row, NSUInteger i, BOOL *stop) {
+ if (![before containsObject:row]) [coming addObject:[NSIndexPath indexPathForRow:(NSInteger)i inSection:(NSInteger)section]];
+ }];
+ }];
+ UITableView *table = self.tableView;
+ [table performBatchUpdates:^{
+ self->_shown = next;
+ [table deleteRowsAtIndexPaths:gone withRowAnimation:UITableViewRowAnimationFade];
+ [table insertRowsAtIndexPaths:coming withRowAnimation:UITableViewRowAnimationFade];
+ } completion:^(BOOL finished) {
+ if (coming.count) {
+ CGRect rows = CGRectNull;
+ for (NSIndexPath *path in coming) rows = CGRectUnion(rows, [table rectForRowAtIndexPath:path]);
+ CGFloat room = table.bounds.size.height - table.adjustedContentInset.top - table.adjustedContentInset.bottom;
+ rows.size.height = MIN(rows.size.height, room);
+ [table scrollRectToVisible:rows animated:YES];
+ }
+ if (done) done();
+ }];
+ return YES;
+}
+
+// The row a switch or an ⓘ belongs to, by the cell it sits in: rows coming and going move the rows under
+// them, so a position remembered when the cell was made may be stale.
+- (NSIndexPath *)pathOf:(UIView *)control {
+ UIView *view = control;
+ while (view && ![view isKindOfClass:UITableViewCell.class]) view = view.superview;
+ return view ? [self.tableView indexPathForCell:(UITableViewCell *)view] : nil;
+}
+
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.tableHeaderView = _intro;
@@ -274,7 +490,8 @@ static BOOL lockedRowOn(SGModRow *row) {
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Reloaded whether or not anything ticks: a choice row is showing whatever was picked on the
- // page it opened, which is gone by the time this one comes back.
+ // page it opened, which is gone by the time this one comes back, and may bring rows or take them.
+ _shown = [self rowsToShow];
[self.tableView reloadData];
if (!_live) return;
// The counters climb while the page is open; the labels are written straight into the cells so
@@ -302,7 +519,7 @@ static BOOL lockedRowOn(SGModRow *row) {
}
- (SGModRow *)rowAt:(NSIndexPath *)path {
- return _sections[(NSUInteger)path.section].rows[(NSUInteger)path.row];
+ return _shown[(NSUInteger)path.section][(NSUInteger)path.row];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {
@@ -310,7 +527,13 @@ static BOOL lockedRowOn(SGModRow *row) {
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
- return (NSInteger)_sections[(NSUInteger)section].rows.count;
+ return (NSInteger)_shown[(NSUInteger)section].count;
+}
+
+// A slider row is laid out by hand; every other row sizes itself.
+- (CGFloat)tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
+ SGModRow *row = [self rowAt:path];
+ return row.number ? [SGModSliderCell heightFor:row] : UITableViewAutomaticDimension;
}
- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {
@@ -334,6 +557,12 @@ static BOOL lockedRowOn(SGModRow *row) {
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
SGModRow *row = [self rowAt:path];
+ if (row.number) {
+ SGModSliderCell *cell = [table dequeueReusableCellWithIdentifier:@"slider"] ?: [[SGModSliderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"slider"];
+ cell.backgroundColor = SGCardBackground();
+ [cell showRow:row];
+ return cell;
+ }
UITableViewCell *cell = SGDequeueCell(table, @"row");
SGFillCell(cell, row.title, row.subtitle, row.color, row.symbol);
UIListContentConfiguration *content = (UIListContentConfiguration *)cell.contentConfiguration;
@@ -365,9 +594,8 @@ static BOOL lockedRowOn(SGModRow *row) {
toggle.enabled = !locked;
// A disabled switch would swallow the tap; letting it through is what gets the row asked.
toggle.userInteractionEnabled = !locked;
- toggle.tag = path.section * 1000 + path.row;
[toggle addTarget:self action:@selector(toggled:) forControlEvents:UIControlEventValueChanged];
- cell.accessoryView = row.info ? [self infoButtonBeside:toggle tag:toggle.tag] : toggle;
+ cell.accessoryView = row.info ? [self infoButtonBeside:toggle] : toggle;
cell.selectionStyle = locked ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
} else if (row.page) {
cell.accessoryView = row.value ? valueAndChevron(row.value()) : SGSymbolView(@"chevron.right", 13, UIImageSymbolWeightSemibold, 16);
@@ -401,12 +629,11 @@ static BOOL lockedRowOn(SGModRow *row) {
}
// The ⓘ to the left of the switch, the grey of a subtitle, 30pt across so it is easy to hit next to it.
-- (UIView *)infoButtonBeside:(UIControl *)toggle tag:(NSInteger)tag {
+- (UIView *)infoButtonBeside:(UIControl *)toggle {
UIButton *info = [UIButton buttonWithType:UIButtonTypeSystem];
UIImageSymbolConfiguration *symbol = [UIImageSymbolConfiguration configurationWithPointSize:17 weight:UIImageSymbolWeightRegular];
[info setImage:[UIImage systemImageNamed:@"info.circle" withConfiguration:symbol] forState:UIControlStateNormal];
info.tintColor = SGGrey();
- info.tag = tag;
info.accessibilityLabel = @"About this switch";
[info addTarget:self action:@selector(infoTapped:) forControlEvents:UIControlEventTouchUpInside];
[toggle sizeToFit];
@@ -420,7 +647,9 @@ static BOOL lockedRowOn(SGModRow *row) {
}
- (void)infoTapped:(UIButton *)button {
- SGModRow *row = [self rowAt:[NSIndexPath indexPathForRow:button.tag % 1000 inSection:button.tag / 1000]];
+ NSIndexPath *path = [self pathOf:button];
+ if (!path) return;
+ SGModRow *row = [self rowAt:path];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:row.title message:row.info preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
@@ -429,15 +658,20 @@ static BOOL lockedRowOn(SGModRow *row) {
// A UISwitch or an SGGlowSwitch, both answering isOn.
- (void)toggled:(UIControl *)toggle {
BOOL on = [(UISwitch *)toggle isOn];
- SGModRow *row = [self rowAt:[NSIndexPath indexPathForRow:toggle.tag % 1000 inSection:toggle.tag / 1000]];
+ NSIndexPath *path = [self pathOf:toggle];
+ if (!path) return;
+ SGModRow *row = [self rowAt:path];
if (row.flag) SGSetFlagOverride(row.key, on ? @(!row.forceOff) : nil);
else SGSetEnabled(row.key, on);
- if (row.changed) {
- row.changed(on);
- // A glowing switch is let finish its slide before the reload puts a new one in its place.
- NSTimeInterval wait = [toggle isKindOfClass:SGGlowSwitch.class] ? 0.45 : 0;
+ if (row.changed) row.changed(on);
+ // A glowing switch is let finish its slide before the reload puts a new one in its place; rows coming
+ // or going are let finish first too.
+ NSTimeInterval wait = [toggle isKindOfClass:SGGlowSwitch.class] ? 0.45 : 0;
+ void (^reload)(void) = ^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(wait * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self.tableView reloadData]; });
- }
+ };
+ BOOL moved = [self showRowsThen:row.changed ? reload : nil];
+ if (row.changed && !moved) reload();
if (on && row.warning) [self warn:row];
}