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: Music Haptics plays generated taps and iOS's exact recording

My-Name-Is-Jeffabcbaed93889
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 4f82dcfb..cc6eaf01 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -185,10 +185,13 @@ Shared:
and bass analyzer on the render thread (SGMusicAnalyzer.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. iOS's own Music Haptics, when on in Accessibility, is handed the song's ISRC from Apple Music's
- catalog (SystemMusicHaptics.x), and for a song Apple has a haptic track for the mod's stands down
- until the next song. The analyzer is scored on the Mac against harness/haptics/, the hook in the simulator against its
- sim/, the settings against harness/haptics-page/
+ app. Music Haptics is a choice of None, Generated (the above) or Native iOS (iOS 18 and up), never
+ both: Native iOS asks Spotify's extended-metadata for the track's ISRC with Spotify's own spclient
+ headers, asks Apple Music's catalog for that ISRC, and names the matched song's catalog id (same ISRC,
+ length within 2 s, a haptic track) or else the ISRC in the now playing info for iOS's own Music
+ Haptics (SystemMusicHaptics.x, its pure steps in SGHapticTrack.m). The analyzer is scored on the Mac
+ against harness/haptics/, as are Native iOS's pure steps (build/track), the hook in the simulator
+ against its sim/, the settings against harness/haptics-page/
HeadGestures/ AirPods gestures (HeadGestures.h lists its files): CMHeadphoneMotionManager's attitudes, while the
switch is on and Spotify plays, read for a double nod, which adds the track to Liked Songs through
Spotify's collection platform (addURL:showUIConfirmation:completion:), and a shake, which skips; a
@@ -367,12 +370,14 @@ in the native look also Now playing bar (its device button and its flags), Queue
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). Then Vibrations under either look, 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, on iOS 17 and up under either look: its switch and which view it
+Controls (on until switched off) and one for Music Haptics, a choice of None, Generated or Native iOS
+(left out below iOS 18) with an ⓘ saying what each does. Someone with no choice stored gets Native iOS
+when Music Haptics is on in Accessibility, else Generated if the old switch was on, else None. Controls
+opens out while its switch is on into its Strength (10 to 100%, a tap at the new strength with each step);
+Generated 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); Native iOS into a Status row (Off in iOS, Paused, Waiting, Checking, Ready, Playing
+or Unavailable), all applying straight away. Live Activity, on iOS 17 and up under either look: its switch and which view it
shows, Lyrics, Queue or Control menu, and for Lyrics its Translations (off until switched on) and Text
size (Small, Medium or Large), all applying straight away, the row reading out the view or Off. Audio effects, in either look (Shared/AudioEffects/AudioEffectsPage.m):
the effects' switch with what the engine is doing under it, Presets (built-in ones and your own, saved, loaded
diff --git a/harness/haptics-page/main.m b/harness/haptics-page/main.m
index 56e5322e..e555778c 100644
--- a/harness/haptics-page/main.m
+++ b/harness/haptics-page/main.m
@@ -6,8 +6,8 @@
// 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
+// Setup: keep (the stored settings stay; otherwise every haptics key is cleared first),
+// controls-off (Controls switched off), music (Music Haptics on Generated), native (on Native iOS), 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
@@ -52,13 +52,14 @@ static void findViews(UIView *root, Class kind, NSMutableArray *found) {
NSUserDefaults *store = NSUserDefaults.standardUserDefaults;
if (![args containsObject:@"keep"]) {
for (NSString *key in store.dictionaryRepresentation.allKeys) {
- if ([key hasPrefix:@"spotifyglass.redesign.haptics"]) [store removeObjectForKey:key];
+ if ([key hasPrefix:@"spotifyglass."] && [key containsString:@"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(SGKeyControlHaptics, NO);
- else if ([arg isEqualToString:@"music"]) SGSetEnabled(SGKeyMusicHaptics, YES);
+ else if ([arg isEqualToString:@"music"]) SGSetInt(SGKeyMusicHapticsMode, SGMusicHapticsGenerated);
+ else if ([arg isEqualToString:@"native"]) SGSetInt(SGKeyMusicHapticsMode, SGMusicHapticsNative);
else if ([arg hasPrefix:@"follows="]) SGSetInt(SGKeyMusicFollows, [arg substringFromIndex:8].integerValue);
else if (![@[@"keep", @"slow"] containsObject:arg]) [actions addObject:arg];
}
@@ -138,10 +139,10 @@ static void findViews(UIView *root, Class kind, NSMutableArray *found) {
} 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]);
+ if ([key hasPrefix:@"spotifyglass."] && [key containsString:@"haptics"]) NSLog(@"[harness] stored %@ = %@", key, all[key]);
}
NSLog(@"[harness] the hooks read: Controls %@ at %.0f%%, Music Haptics %@ at %.0f%% following %ld", SGEnabled(SGKeyControlHaptics) ? @"on" : @"off",
- SGHapticsStrength(SGKeyControlStrength) * 100, SGFlag(SGKeyMusicHaptics, NO) ? @"on" : @"off",
+ SGHapticsStrength(SGKeyControlStrength) * 100, @[@"None", @"Generated", @"Native iOS"][SGMusicHapticsModeNow()],
SGHapticsStrength(SGKeyMusicStrength) * 100, (long)SGMusicHapticsFollows());
for (NSInteger section = 0; section < table.numberOfSections; section++) {
NSMutableArray<NSString *> *rows = [NSMutableArray array];
diff --git a/harness/haptics-page/stubs.m b/harness/haptics-page/stubs.m
index 5a65f10c..b7da4d00 100644
--- a/harness/haptics-page/stubs.m
+++ b/harness/haptics-page/stubs.m
@@ -1,10 +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.
+// Music Haptics' side of Haptics.h (MusicHaptics.x in the tweak), which the page calls as its choice and its
+// settings change: each is logged with what the hooks would read at that moment.
#import "Core/SGCore.h"
#import "Shared/Haptics/Haptics.h"
-void SGSetMusicHapticsEnabled(BOOL on) {
- NSLog(@"[harness] Music Haptics %@", on ? @"on" : @"off");
+__attribute__((constructor)) static void sg_logModeChanges(void) {
+ [NSNotificationCenter.defaultCenter addObserverForName:SGMusicHapticsModeChangedNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
+ NSLog(@"[harness] Music Haptics plays %@", @[@"None", @"Generated", @"Native iOS"][SGMusicHapticsModeNow()]);
+ }];
}
void SGMusicHapticsSettingsChanged(void) {
diff --git a/harness/haptics/README.md b/harness/haptics/README.md
index 353f3526..470710d5 100644
--- a/harness/haptics/README.md
+++ b/harness/haptics/README.md
@@ -1,6 +1,8 @@
# Music Haptics harness
-Two halves: the analyzer on the Mac, and the hook in the simulator.
+Two halves: the analyzer on the Mac, and the hook in the simulator. Beside them, `track.m` checks Native iOS's
+pure steps on the Mac (`./build.sh && build/track`): the ISRC check, hand-built TRACK_V4 replies and Apple's
+catalog songs matched or turned down.
## The analyzer on the Mac (`main.m`, `score.py`)
diff --git a/harness/haptics/build.sh b/harness/haptics/build.sh
index e735c591..9eb6505f 100755
--- a/harness/haptics/build.sh
+++ b/harness/haptics/build.sh
@@ -1,8 +1,11 @@
#!/bin/sh
-# Builds the Music Haptics analyzer harness for the Mac: SGMusicAnalyzer.m as the tweak compiles it, and main.m.
+# Builds the Music Haptics harnesses for the Mac: SGMusicAnalyzer.m as the tweak compiles it under main.m, and
+# Native iOS's pure steps (SGHapticTrack.m and the protobuf reader) under track.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/Shared/Haptics/SGMusicAnalyzer.m -o build/haptics
-echo "built build/haptics"
+xcrun clang -fobjc-arc -O2 -Wall -Werror -I ../../tweak/Sources -framework Foundation \
+ track.m ../../tweak/Sources/Shared/Haptics/SGHapticTrack.m ../../tweak/Sources/Shared/AdBlock/Protobuf.m -o build/track
+echo "built build/haptics and build/track"
diff --git a/harness/haptics/sim/main.m b/harness/haptics/sim/main.m
index e7563b01..3e0db00b 100644
--- a/harness/haptics/sim/main.m
+++ b/harness/haptics/sim/main.m
@@ -190,6 +190,11 @@ static int sg_failures;
ok ? @" ok " : @"FAILED", @"44.1 kHz client, Everything, 100%", peek.kicks, peek.snares, s, s, s, tap100, peek.levels, level100);
}]];
#ifndef BEFORE
+ // What the settings' choice does: stores it and tells both engines.
+ void (^choose)(SGMusicHapticsMode) = ^(SGMusicHapticsMode mode) {
+ SGSetInt(SGKeyMusicHapticsMode, mode);
+ [NSNotificationCenter.defaultCenter postNotificationName:SGMusicHapticsModeChangedNotification object:nil];
+ };
void (^set)(NSInteger, NSInteger) = ^(NSInteger follows, NSInteger strength) {
SGSetInt(SGKeyMusicFollows, follows);
SGSetInt(SGKeyMusicStrength, strength);
@@ -208,21 +213,21 @@ static int sg_failures;
@[@"Everything at 200%", ^{ set(SGMusicFollowsEverything, 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", ^{ SGSetMusicHapticsEnabled(NO); }, ^(double s) {
- [self report:@"the switch off" seconds:s kicks:0 snares:0 rumble:NO intensity:NAN level:NAN];
+ @[@"None chosen", ^{ choose(SGMusicHapticsOff); }, ^(double s) {
+ [self report:@"None chosen" seconds:s kicks:0 snares:0 rumble:NO intensity:NAN level:NAN];
}],
- @[@"on again, Everything, 100%", ^{
+ @[@"Generated again, Everything, 100%", ^{
set(SGMusicFollowsEverything, 100);
- SGSetMusicHapticsEnabled(YES);
+ choose(SGMusicHapticsGenerated);
}, ^(double s) {
- [self report:@"on again, Everything, 100%" seconds:s kicks:1 snares:1 rumble:YES intensity:tap100 level:level100];
+ [self report:@"Generated again, Everything, 100%" seconds:s kicks:1 snares:1 rumble:YES intensity:tap100 level:level100];
}],
- // What SystemMusicHaptics.x says when Apple has a haptic track for the song, and at the next song.
- @[@"iOS's own Music Haptics plays", ^{ SGMusicHapticsSetSystemPlaying(YES); }, ^(double s) {
- [self report:@"iOS's own Music Haptics plays" seconds:s kicks:0 snares:0 rumble:NO intensity:NAN level:NAN];
+ // With Native iOS chosen the mod's stays quiet, whatever iOS does with the song.
+ @[@"Native iOS chosen", ^{ choose(SGMusicHapticsNative); }, ^(double s) {
+ [self report:@"Native iOS chosen" seconds:s kicks:0 snares:0 rumble:NO intensity:NAN level:NAN];
}],
- @[@"a song iOS has none for", ^{ SGMusicHapticsSetSystemPlaying(NO); }, ^(double s) {
- [self report:@"a song iOS has none for" seconds:s kicks:1 snares:1 rumble:YES intensity:tap100 level:level100];
+ @[@"Generated chosen again", ^{ choose(SGMusicHapticsGenerated); }, ^(double s) {
+ [self report:@"Generated chosen again" seconds:s kicks:1 snares:1 rumble:YES intensity:tap100 level:level100];
}],
]];
#endif
@@ -254,8 +259,8 @@ static int sg_failures;
@end
-// Music Haptics on, and its settings at their defaults, before MusicHaptics.x's constructor reads them; the
-// redesign on, which gates it.
+// Music Haptics on (the old switch, which reads as Generated with no choice stored), 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) {
diff --git a/harness/haptics/track.m b/harness/haptics/track.m
new file mode 100644
index 00000000..a18f3230
--- /dev/null
+++ b/harness/haptics/track.m
@@ -0,0 +1,94 @@
+// The pure steps of Native iOS Music Haptics (Shared/Haptics/SGHapticTrack.m) on the Mac: the ISRC check,
+// TRACK_V4 replies built by hand (a good one, one for another URI, one whose entity is not 200, one cut short,
+// one from a provider that failed, one with no ISRC), and Apple's catalog songs matched and each rejection.
+// ./build.sh && build/track
+#import "Shared/Haptics/SGHapticTrack.h"
+#import "Shared/AdBlock/Protobuf.h"
+
+static int failures;
+
+static void check(BOOL ok, NSString *what) {
+ if (!ok) failures++;
+ printf("%s %s\n", ok ? " ok " : "FAILED", what.UTF8String);
+}
+
+static NSData *message(NSArray<SGPBField *> *fields) {
+ return SGPBSerialize(fields);
+}
+
+// A BatchedExtensionResponse with one array of one entry, as Spotify 9.1.78 sends it.
+static NSData *reply(NSString *uri, uint64_t entityStatus, NSString *isrc, NSNumber *providerStatus) {
+ NSMutableArray *externals = [NSMutableArray arrayWithObject:SGPBBytes(10, message(@[SGPBString(1, @"upc"), SGPBString(2, @"00602547288233")]))];
+ if (isrc) [externals addObject:SGPBBytes(10, message(@[SGPBString(1, @"isrc"), SGPBString(2, isrc)]))];
+ NSData *track = message([@[SGPBString(2, @"Song"), SGPBVarint(7, 215000)] arrayByAddingObjectsFromArray:externals]);
+ NSData *any = message(@[SGPBString(1, @"type.googleapis.com/spotify.metadata.Track"), SGPBBytes(2, track)]);
+ NSData *entry = message(@[SGPBBytes(1, message(@[SGPBVarint(1, entityStatus), SGPBString(2, @"etag")])), SGPBString(2, uri), SGPBBytes(3, any)]);
+ NSMutableArray *array = [NSMutableArray array];
+ if (providerStatus) [array addObject:SGPBBytes(1, message(@[SGPBVarint(1, providerStatus.unsignedLongLongValue)]))];
+ [array addObjectsFromArray:@[SGPBVarint(2, 10), SGPBBytes(3, entry)]];
+ return message(@[SGPBBytes(1, [NSData data]), SGPBBytes(2, message(array))]);
+}
+
+int main(void) {
+ @autoreleasepool {
+ NSString *uri = @"spotify:track:4uLU6hMCjMI75M1A2tKUQC";
+ check([SGHapticISRC(@"usrc17607839") isEqualToString:@"USRC17607839"], @"an ISRC is uppercased");
+ check([SGHapticISRC(@"GBAYE0601498") isEqualToString:@"GBAYE0601498"], @"letters in the registrant");
+ check(!SGHapticISRC(@"USRC1760783") && !SGHapticISRC(@"USRC176078390"), @"11 or 13 characters are not one");
+ check(!SGHapticISRC(@"1SRC17607839") && !SGHapticISRC(@"USRC1760783A") && !SGHapticISRC(@"US-C17607839"), @"a digit, letter or dash out of place is not one");
+ check(!SGHapticISRC(nil) && !SGHapticISRC((id)@12), @"nil or a number is not one");
+ check(SGHapticIsTrackURI(uri), @"a track URI");
+ check(!SGHapticIsTrackURI(@"spotify:episode:4uLU6hMCjMI75M1A2tKUQC") && !SGHapticIsTrackURI(@"spotify:local:a:b:c:215")
+ && !SGHapticIsTrackURI(@"spotify:track:4uLU6hMCjMI75M1A2tKUQ"), @"an episode, a local file or a short id is not");
+
+ NSArray<SGPBField *> *request = SGPBParse(SGHapticTrackRequest(uri));
+ NSArray<SGPBField *> *entity = SGPBParse(SGPBFirst(request, 2).payload);
+ NSArray<SGPBField *> *query = SGPBParse(SGPBFirst(entity, 2).payload);
+ check([SGPBText(SGPBFirst(entity, 1)) isEqualToString:uri] && SGPBFirst(query, 1).varint == 10, @"the request names the URI and TRACK_V4");
+
+ BOOL answered;
+ NSString *isrc = SGHapticISRCInReply(reply(uri, 200, @"usrc17607839", @200), uri, &answered);
+ check([isrc isEqualToString:@"USRC17607839"] && answered, @"a good reply gives its ISRC");
+ isrc = SGHapticISRCInReply(reply(uri, 200, @"USRC17607839", nil), uri, &answered);
+ check([isrc isEqualToString:@"USRC17607839"] && answered, @"a reply without a provider status is taken");
+ isrc = SGHapticISRCInReply(reply(@"spotify:track:0000000000000000000000", 200, @"USRC17607839", @200), uri, &answered);
+ check(!isrc && !answered, @"a reply for another URI is not");
+ isrc = SGHapticISRCInReply(reply(uri, 404, @"USRC17607839", @200), uri, &answered);
+ check(!isrc && !answered, @"an entity status of 404 is not");
+ isrc = SGHapticISRCInReply(reply(uri, 200, @"USRC17607839", @500), uri, &answered);
+ check(!isrc && !answered, @"a provider status of 500 is not");
+ NSData *whole = reply(uri, 200, @"USRC17607839", @200);
+ isrc = SGHapticISRCInReply([whole subdataWithRange:NSMakeRange(0, whole.length - 5)], uri, &answered);
+ check(!isrc && !answered, @"a reply cut short is not");
+ isrc = SGHapticISRCInReply(reply(uri, 200, nil, @200), uri, &answered);
+ check(!isrc && answered, @"a good reply with no ISRC is final");
+ isrc = SGHapticISRCInReply(reply(uri, 200, @"USRC1760783", @200), uri, &answered);
+ check(!isrc && answered, @"a malformed ISRC is none");
+ isrc = SGHapticISRCInReply([NSData data], uri, &answered);
+ check(!isrc && !answered, @"an empty reply is not");
+
+ NSDictionary *(^song)(NSString *, id, id, id) = ^NSDictionary *(NSString *identifier, id code, id length, id haptics) {
+ NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
+ if (code) attributes[@"isrc"] = code;
+ if (length) attributes[@"durationInMillis"] = length;
+ if (haptics) attributes[@"hasHaptics"] = haptics;
+ return @{@"id": identifier, @"type": @"songs", @"attributes": attributes};
+ };
+ NSString *code = @"USRC17607839";
+ check([SGHapticSongIn(@[song(@"1440857781", code, @215400, @YES)], code, 215000) isEqualToString:@"1440857781"], @"the same ISRC, 0.4 s apart, with haptics");
+ check([SGHapticSongIn(@[song(@"1", @"usrc17607839", @213001, @YES)], code, 215000) isEqualToString:@"1"], @"1.999 s apart and a lowercase ISRC still match");
+ check(!SGHapticSongIn(@[song(@"1", code, @212999, @YES)], code, 215000), @"2.001 s apart does not");
+ check(!SGHapticSongIn(@[song(@"1", @"USRC17607840", @215000, @YES)], code, 215000), @"another ISRC does not");
+ check(!SGHapticSongIn(@[song(@"1", code, @215000, @NO)], code, 215000), @"no haptic track does not");
+ check(!SGHapticSongIn(@[song(@"1", code, @215000, nil)], code, 215000), @"hasHaptics missing does not");
+ check(!SGHapticSongIn(@[song(@"1", nil, @215000, @YES)], code, 215000), @"an ISRC missing does not");
+ check(!SGHapticSongIn(@[song(@"1", code, nil, @YES)], code, 215000), @"a length missing does not");
+ check(!SGHapticSongIn(@[song(@"1", code, @215000, @YES)], code, 0), @"Spotify's length unknown does not");
+ check([SGHapticSongIn(@[song(@"live", code, @260000, @YES), song(@"studio", code, @215000, @YES)], code, 215000) isEqualToString:@"studio"],
+ @"of two with the ISRC, the one of the right length");
+ check(!SGHapticSongIn((id)@{}, code, 215000) && !SGHapticSongIn(@[@"x", @{}], code, 215000), @"anything but songs is passed over");
+
+ printf("%s: %d failed\n", failures ? "FAILED" : "all passed", failures);
+ }
+ return failures ? 1 : 0;
+}
diff --git a/tweak/Sources/Settings/SGModPage.m b/tweak/Sources/Settings/SGModPage.m
index 07114cdd..95086ab8 100644
--- a/tweak/Sources/Settings/SGModPage.m
+++ b/tweak/Sources/Settings/SGModPage.m
@@ -622,7 +622,8 @@ static const CGFloat kSliderTop = 12, kSliderLine = 18, kSliderSubtitle = 14, kS
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);
+ UIView *link = row.value ? valueAndChevron(row.value()) : SGSymbolView(@"chevron.right", 13, UIImageSymbolWeightSemibold, 16);
+ cell.accessoryView = row.info ? [self infoButtonBeside:link] : link;
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
} else if (row.value) {
UILabel *label = [UILabel new];
@@ -652,13 +653,14 @@ static const CGFloat kSliderTop = 12, kSliderLine = 18, kSliderSubtitle = 14, kS
[self readValues];
}
-// 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 {
+// The ⓘ to the left of the switch (or of a choice's name and chevron), the grey of a subtitle, 30pt across
+// so it is easy to hit next to it.
+- (UIView *)infoButtonBeside:(UIView *)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.accessibilityLabel = @"About this switch";
+ info.accessibilityLabel = @"About this setting";
[info addTarget:self action:@selector(infoTapped:) forControlEvents:UIControlEventTouchUpInside];
[toggle sizeToFit];
CGFloat side = 30, gap = 8, height = MAX(side, toggle.bounds.size.height);
diff --git a/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtwork.h b/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtwork.h
index bb0aa366..5510a4c7 100644
--- a/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtwork.h
+++ b/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtwork.h
@@ -38,8 +38,9 @@ void SGMotionArtistLogo(NSString *artist, CGFloat pixels, void (^done)(UIImage *
// screen's full width ran to 29 MB a song; at this width it was 7 MB and looks the same in motion.
CGFloat SGMotionPixels(void);
-// A song's ISRC from Apple Music's catalog, or nil. Main queue.
-void SGMotionSongISRC(NSString *artist, NSString *title, void (^done)(NSString *isrc));
+// Apple Music's catalog songs with this ISRC, each with its isrc, durationInMillis and hasHaptics, or nil
+// when the catalog could not be asked. Kept for the launch. Main queue.
+void SGMotionSongsWithISRC(NSString *isrc, void (^done)(NSArray *songs));
// Any remote video (a Canvas) as a local file, or nil. Main queue.
void SGMotionFile(NSURL *remote, void (^done)(NSURL *file));
diff --git a/tweak/Sources/Shared/AnimatedArtwork/SGMotionCatalog.m b/tweak/Sources/Shared/AnimatedArtwork/SGMotionCatalog.m
index 48ecfba1..29298a59 100644
--- a/tweak/Sources/Shared/AnimatedArtwork/SGMotionCatalog.m
+++ b/tweak/Sources/Shared/AnimatedArtwork/SGMotionCatalog.m
@@ -1,4 +1,4 @@
-// Animated album covers and artist logos from Apple Music's catalog. The catalog takes the developer
+// Animated album covers, artist logos and songs by ISRC from Apple Music's catalog. The catalog takes the developer
// token Apple Music's web player carries, so the token is read out of the web player's script and
// kept until it is about to expire. Answers are kept for the launch.
#import "Core/SGCore.h"
@@ -7,6 +7,7 @@
static NSString *const kTokenKey = @"spotifyglass.motion.token";
static NSString *const kBrowse = @"https://music.apple.com/us/browse";
static NSString *const kSearch = @"https://amp-api.music.apple.com/v1/catalog/us/search";
+static NSString *const kSongs = @"https://amp-api.music.apple.com/v1/catalog/us/songs";
static NSString *const kSafari = @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15";
// A token this close to its expiry is read again rather than used.
static const NSTimeInterval kTokenMargin = 3600;
@@ -224,28 +225,27 @@ static NSString *escaped(NSString *value) {
return [value stringByAddingPercentEncodingWithAllowedCharacters:unreserved] ?: @"";
}
-// `found` is the search's results of that type, empty when it has none; `answered` is NO when the
-// catalog could not be asked, so the caller does not remember the absence.
-static void search(NSString *type, NSString *term, NSString *extend, BOOL renew, void (^done)(NSArray *found, BOOL answered)) {
+// The array at `path` in the catalog's answer, empty when it has none; `answered` is NO when the catalog
+// could not be asked, so the caller does not remember the absence. A refused token is read again once.
+static void askCatalog(NSString *address, NSString *path, BOOL renew, void (^done)(NSArray *found, BOOL answered)) {
withToken(^(NSString *token) {
if (!token) {
done(nil, NO);
return;
}
- NSString *address = [NSString stringWithFormat:@"%@?term=%@&types=%@&limit=10&extend=%@", kSearch, escaped(term), type, extend];
NSMutableURLRequest *request = requestFor([NSURL URLWithString:address]);
[request setValue:[@"Bearer " stringByAppendingString:token] forHTTPHeaderField:@"Authorization"];
// The catalog refuses the web player's token without the web player's origin.
[request setValue:@"https://music.apple.com" forHTTPHeaderField:@"Origin"];
fetch(request, ^id(NSData *data) {
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
- id found = dig(json, [NSString stringWithFormat:@"results/%@/data", type]);
+ id found = dig(json, path);
return [found isKindOfClass:NSArray.class] ? found : @[];
}, ^(NSArray *found, NSInteger status) {
if (status == 401 && renew) {
SGLog(@"motion: token refused, reading it again");
forgetToken(token);
- search(type, term, extend, NO, done);
+ askCatalog(address, path, NO, done);
return;
}
done(found, status == 200);
@@ -253,6 +253,12 @@ static void search(NSString *type, NSString *term, NSString *extend, BOOL renew,
});
}
+// `found` is the search's results of that type.
+static void search(NSString *type, NSString *term, NSString *extend, BOOL renew, void (^done)(NSArray *found, BOOL answered)) {
+ NSString *address = [NSString stringWithFormat:@"%@?term=%@&types=%@&limit=10&extend=%@", kSearch, escaped(term), type, extend];
+ askCatalog(address, [NSString stringWithFormat:@"results/%@/data", type], renew, done);
+}
+
// Runs `look` once per key and launch. `look` calls `answer` exactly once; `keep` is NO for a failure
// worth asking again.
static void lookUp(NSString *key, void (^done)(id value), void (^look)(void (^answer)(id value, BOOL keep))) {
@@ -398,34 +404,19 @@ void SGMotionArtistLogo(NSString *artist, CGFloat pixels, void (^done)(UIImage *
#pragma mark - recordings
-// The song's ISRC, for iOS's Music Haptics, which plays haptics for a recording it knows by that code.
-void SGMotionSongISRC(NSString *artist, NSString *title, void (^done)(NSString *isrc)) {
+// The catalog's songs with this ISRC, for iOS's Music Haptics: the recording itself, not a search by name.
+void SGMotionSongsWithISRC(NSString *isrc, void (^done)(NSArray *songs)) {
if (!NSThread.isMainThread) {
- dispatch_async(dispatch_get_main_queue(), ^{ SGMotionSongISRC(artist, title, done); });
+ dispatch_async(dispatch_get_main_queue(), ^{ SGMotionSongsWithISRC(isrc, done); });
return;
}
- NSString *artistKey = SGMotionNameKey(artist), *titleKey = SGMotionNameKey(title);
- if (!artistKey.length || !titleKey.length) {
+ if (!isrc.length) {
done(nil);
return;
}
- NSString *key = [NSString stringWithFormat:@"isrc\n%@\n%@", artistKey, titleKey];
- lookUp(key, ^(NSString *isrc) { done(isrc); }, ^(void (^answer)(id, BOOL)) {
- search(@"songs", [NSString stringWithFormat:@"%@ %@", artist, title], @"", YES, ^(NSArray *found, BOOL answered) {
- if (!answered) {
- answer(nil, NO);
- return;
- }
- NSString *isrc = nil;
- for (id result in found) {
- id attributes = dig(result, @"attributes");
- if (!sameArtist(artistKey, SGMotionNameKey(dig(attributes, @"artistName")))) continue;
- if (![SGMotionNameKey(dig(attributes, @"name")) isEqualToString:titleKey]) continue;
- id code = dig(attributes, @"isrc");
- if ([code isKindOfClass:NSString.class] && [code length]) isrc = code;
- break;
- }
- answer(isrc, YES);
- });
+ lookUp([@"isrc\n" stringByAppendingString:isrc], done, ^(void (^answer)(id, BOOL)) {
+ // filter[isrc] and fields[songs], the brackets escaped: iOS before 17 makes no URL of them bare.
+ NSString *address = [NSString stringWithFormat:@"%@?filter%%5Bisrc%%5D=%@&fields%%5Bsongs%%5D=isrc,durationInMillis,hasHaptics", kSongs, escaped(isrc)];
+ askCatalog(address, @"data", YES, ^(NSArray *found, BOOL answered) { answer(found, answered); });
});
}
diff --git a/tweak/Sources/Shared/Haptics/Haptics.h b/tweak/Sources/Shared/Haptics/Haptics.h
index 41819791..23f72f84 100644
--- a/tweak/Sources/Shared/Haptics/Haptics.h
+++ b/tweak/Sources/Shared/Haptics/Haptics.h
@@ -5,8 +5,9 @@
// 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
// SGMusicAnalyzer.m the listening: taps and a rumble out of the samples
-// SystemMusicHaptics.x iOS's own Music Haptics given the song's ISRC; the mod's stands down for its songs
-// HapticsSettings.m the Vibrations cards, with each switch's strength and what Music Haptics follows
+// SystemMusicHaptics.x iOS's own Music Haptics given the song's Apple Music id or ISRC (Native iOS)
+// SGHapticTrack.m the pure steps behind it: Spotify's extended metadata asked and read, Apple's songs matched
+// HapticsSettings.m the Vibrations cards, with each one's strength, what Music Haptics plays and follows
//
// Everything on them applies at once, without a restart. Everything hooked is Spotify's own (its controls
// by accessibility identifier, its scrubber, its cover and title lists, its audio unit), so all of it works
@@ -16,7 +17,10 @@
#import <UIKit/UIKit.h>
#define SGKeyControlHaptics @"spotifyglass.haptics.controls"
+// The Music Haptics switch of before the choice below; read once to pick the choice for someone who had it.
#define SGKeyMusicHaptics @"spotifyglass.haptics.music"
+// Which Music Haptics plays, an SGMusicHapticsMode.
+#define SGKeyMusicHapticsMode @"spotifyglass.haptics.music.mode"
// How hard the taps are, a percentage within the range below; 100 is the feel each shipped with.
#define SGKeyControlStrength @"spotifyglass.haptics.controls.strength"
#define SGKeyMusicStrength @"spotifyglass.haptics.music.strength"
@@ -43,6 +47,13 @@ typedef NS_ENUM(NSInteger, SGMusicFollows) {
SGMusicFollowsBass, // a tap on each kick, and the rumble
};
+// Stored as the index into the settings' list, which leaves the last one out below iOS 18.
+typedef NS_ENUM(NSInteger, SGMusicHapticsMode) {
+ SGMusicHapticsOff,
+ SGMusicHapticsGenerated, // the mod's, worked out from the sound (MusicHaptics.x)
+ SGMusicHapticsNative, // iOS's own, iOS 18 and later (SystemMusicHaptics.x)
+};
+
typedef NS_ENUM(NSInteger, SGFeedback) {
SGFeedbackPlay, // playback starts
SGFeedbackPause, // playback stops
@@ -60,13 +71,16 @@ void SGPlayFeedback(SGFeedback feedback);
// Wakes the Taptic Engine for feedback about to follow quickly (a finger on the scrubber).
void SGPrepareFeedback(SGFeedback feedback);
-// From the Music Haptics switch: starts or stops listening at once.
-void SGSetMusicHapticsEnabled(BOOL on);
+// Which Music Haptics plays. Native reads Off below iOS 18; nothing stored yet reads the old switch, on as
+// Generated. Main thread.
+SGMusicHapticsMode SGMusicHapticsModeNow(void);
+// Posted on the main thread when the choice changes; both engines take it up at once.
+extern NSNotificationName const SGMusicHapticsModeChangedNotification;
// From its strength and its choice of what to follow: reads them again, for the next tap.
void SGMusicHapticsSettingsChanged(void);
-// From SystemMusicHaptics.x: iOS's own Music Haptics has a haptic track for the song playing, so the mod's
-// stands down (YES), or the song changed and it may play again (NO).
-void SGMusicHapticsSetSystemPlaying(BOOL playing);
+// What iOS's own Music Haptics is doing, for the settings to read out: SystemMusicHaptics.x sets it. Main thread.
+NSString *SGMusicHapticsStatus(void);
+void SGSetMusicHapticsStatus(NSString *status);
// A strength key's percentage as a factor, 1 for 100%, kept within its range.
double SGHapticsStrength(NSString *key);
diff --git a/tweak/Sources/Shared/Haptics/HapticsSettings.m b/tweak/Sources/Shared/Haptics/HapticsSettings.m
index 6fb012ab..f0909dce 100644
--- a/tweak/Sources/Shared/Haptics/HapticsSettings.m
+++ b/tweak/Sources/Shared/Haptics/HapticsSettings.m
@@ -1,13 +1,50 @@
// The Vibrations sections of the Player page, under either look (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.
+// per kind, the way the Audio effects page has one per effect. Controls is a switch that opens out into its
+// strength. Music Haptics is a choice of which plays, None, Generated or Native iOS, since the two never play
+// at once: Generated opens out into 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), Native
+// into what iOS's own is doing.
#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.\n\nWith Music Haptics on in Settings > Accessibility, iOS plays its own haptics for songs Apple Music has them for, in the background and on the lock screen too, and this one steps aside for those songs.";
+static NSString *const kMusicHapticsInfo = @"Generated: 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. It follows the sound this iPhone plays 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.\n\nNative iOS: iOS plays Apple Music's own haptic track for the song, in the background and on the lock screen too, for songs Apple Music has one for. It needs iOS 18 and Music Haptics on in Settings > Accessibility, and stays quiet for podcasts and songs Apple has none for.\n\nNone: no Music Haptics. Controls is separate.";
+
+NSNotificationName const SGMusicHapticsModeChangedNotification = @"SGMusicHapticsModeChangedNotification";
+
+static NSString *sg_status;
+
+NSString *SGMusicHapticsStatus(void) {
+ return sg_status ?: @"Waiting";
+}
+
+void SGSetMusicHapticsStatus(NSString *status) {
+ sg_status = [status copy];
+}
+
+static BOOL nativeAvailable(void) {
+ if (@available(iOS 18.0, *)) return YES;
+ return NO;
+}
+
+SGMusicHapticsMode SGMusicHapticsModeNow(void) {
+ NSInteger mode = SGInt(SGKeyMusicHapticsMode, -1);
+ if (mode < SGMusicHapticsOff || mode > SGMusicHapticsNative) mode = SGFlag(SGKeyMusicHaptics, NO) ? SGMusicHapticsGenerated : SGMusicHapticsOff;
+ if (mode == SGMusicHapticsNative && !nativeAvailable()) mode = SGMusicHapticsOff;
+ return (SGMusicHapticsMode)mode;
+}
+
+// In SGMusicHapticsMode's order, Native iOS left out where iOS has none.
+static NSArray<NSString *> *modeNames(void) {
+ NSArray<NSString *> *names = @[@"None", @"Generated", @"Native iOS"];
+ return nativeAvailable() ? names : [names subarrayWithRange:NSMakeRange(0, 2)];
+}
+
+static NSArray<NSString *> *modeNotes(void) {
+ return @[@"No Music Haptics",
+ @"The mod's own, from the sound, while Spotify is open",
+ @"Apple Music's haptic track, in the background too"];
+}
static NSArray<NSString *> *followsNames(void) {
return @[@"Everything", @"Beat", @"Bass"];
@@ -57,19 +94,26 @@ NSArray<SGModSection *> *SGVibrationsSections(void) {
});
controlStrength.visible = ^BOOL { return SGEnabled(SGKeyControlHaptics); };
- SGModRow *music = SGOptionRow(@"Music Haptics", nil, SGKeyMusicHaptics);
+ // The list reads the stored index, so someone with none stored gets the one picked for them.
+ if (SGInt(SGKeyMusicHapticsMode, -1) < 0) SGSetInt(SGKeyMusicHapticsMode, SGMusicHapticsModeNow());
+ SGModRow *music = SGChoiceRow(@"Music Haptics", nil, SGKeyMusicHapticsMode, modeNames(), SGMusicHapticsOff);
music.info = kMusicHapticsInfo;
- music.changed = ^(BOOL on) { SGSetMusicHapticsEnabled(on); };
- BOOL (^musicOn)(void) = ^BOOL { return SGFlag(SGKeyMusicHaptics, NO); };
+ music.choiceNotes = modeNotes();
+ music.chosen = ^(NSInteger index) {
+ [NSNotificationCenter.defaultCenter postNotificationName:SGMusicHapticsModeChangedNotification object:nil];
+ };
+ BOOL (^generated)(void) = ^BOOL { return SGMusicHapticsModeNow() == SGMusicHapticsGenerated; };
SGModRow *musicStrength = strengthRow(SGKeyMusicStrength, ^{ SGMusicHapticsSettingsChanged(); });
- musicStrength.visible = musicOn;
+ musicStrength.visible = generated;
SGModRow *follows = SGChoiceRow(@"Follows", nil, SGKeyMusicFollows, followsNames(), SGMusicFollowsEverything);
follows.choiceNotes = followsNotes();
follows.chosen = ^(NSInteger index) { SGMusicHapticsSettingsChanged(); };
- follows.visible = musicOn;
+ follows.visible = generated;
+ SGModRow *status = SGStatRow(@"Status", ^NSString *{ return SGMusicHapticsStatus(); });
+ status.visible = ^BOOL { return SGMusicHapticsModeNow() == SGMusicHapticsNative; };
return @[
SGSection(@"Vibrations", @[SGWithSymbol(controls, @"hand.tap"), controlStrength]),
- SGSection(nil, @[SGWithSymbol(music, @"waveform"), musicStrength, follows]),
+ SGSection(nil, @[SGWithSymbol(music, @"waveform"), musicStrength, follows, status]),
];
}
diff --git a/tweak/Sources/Shared/Haptics/MusicHaptics.x b/tweak/Sources/Shared/Haptics/MusicHaptics.x
index f2bd98f9..f2e47b9a 100644
--- a/tweak/Sources/Shared/Haptics/MusicHaptics.x
+++ b/tweak/Sources/Shared/Haptics/MusicHaptics.x
@@ -17,15 +17,15 @@
// 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 under either look, so the switch works at once;
-// with the switch off the notify returns straight away. Nothing listens while Spotify is not the active
-// app, since iOS plays no haptics for an app in the background. Sound that is not Spotify's own
+// The rebinding and the notify are in place under either look, so the choice works at once; with
+// anything but Generated chosen the notify returns straight away. Nothing listens while Spotify is not the
+// active app, since iOS plays no haptics for an app in the background. Sound that is not Spotify's own
// output (Connect, AirPlay to another device, video) never passes the unit, and plays no haptics.
-// Nothing listens either while iOS's own Music Haptics plays a haptic track of the song
-// (SystemMusicHaptics.x), so the two never play at once; the mod's fills in for songs Apple has none for.
+// The choice is read again every time listening could start, not kept from launch, so with Native iOS
+// chosen (SystemMusicHaptics.x) this one stays quiet whatever order the two came up in.
//
// 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, its settings and the app's
+// ring; the Core Haptics objects belong to the player thread; the choice, its settings and the app's
// state are set on the main thread.
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
@@ -62,7 +62,7 @@ enum { kRingSize = 1024, kMonoFrames = 4096 };
#pragma mark - shared between the threads
-static atomic_bool sg_enabled, sg_active, sg_systemPlaying, sg_listening;
+static atomic_bool sg_active, sg_listening;
static atomic_uint sg_generation;
static atomic_uint_fast64_t sg_latencyBits;
static atomic_uint sg_lastFrames;
@@ -498,7 +498,7 @@ static void readLatency(void) {
}
static void updateListening(void) {
- BOOL listening = atomic_load(&sg_enabled) && atomic_load(&sg_active) && !atomic_load(&sg_systemPlaying);
+ BOOL listening = SGMusicHapticsModeNow() == SGMusicHapticsGenerated && atomic_load(&sg_active);
if (atomic_exchange(&sg_listening, listening) == listening) return;
if (listening) {
atomic_fetch_add(&sg_generation, 1);
@@ -516,18 +516,6 @@ static void updateListening(void) {
dispatch_semaphore_signal(sg_wake);
}
-void SGSetMusicHapticsEnabled(BOOL on) {
- if (!sg_wake) return;
- atomic_store(&sg_enabled, on);
- updateListening();
-}
-
-void SGMusicHapticsSetSystemPlaying(BOOL playing) {
- if (atomic_exchange(&sg_systemPlaying, playing) == playing || !sg_wake) return;
- if (atomic_load(&sg_enabled)) SGLog(@"music haptics: %@", playing ? @"iOS's own plays this song, standing down" : @"playing along again");
- updateListening();
-}
-
static void readSettings(void) {
storeDouble(&sg_strengthBits, SGHapticsStrength(SGKeyMusicStrength));
atomic_store(&sg_follows, (int)SGMusicHapticsFollows());
@@ -553,8 +541,10 @@ void SGMusicHapticsSettingsChanged(void) {
}
sg_wake = dispatch_semaphore_create(0);
readSettings();
- atomic_store(&sg_enabled, SGFlag(SGKeyMusicHaptics, NO));
NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
+ [center addObserverForName:SGMusicHapticsModeChangedNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
+ updateListening();
+ }];
[center addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
atomic_store(&sg_active, true);
updateListening();
diff --git a/tweak/Sources/Shared/Haptics/SGHapticTrack.h b/tweak/Sources/Shared/Haptics/SGHapticTrack.h
new file mode 100644
index 00000000..718bb59d
--- /dev/null
+++ b/tweak/Sources/Shared/Haptics/SGHapticTrack.h
@@ -0,0 +1,26 @@
+// The pure steps of Native iOS Music Haptics (SystemMusicHaptics.x), Foundation only so the Mac harness
+// (harness/haptics/track.m) runs them as the tweak does.
+//
+// Spotify's ISRC comes from its own metadata, asked as the app asks it: a BatchedEntityRequest to spclient's
+// extended-metadata with one entity and the TRACK_V4 extension, answered by a BatchedExtensionResponse whose
+// entry holds the track's spotify.metadata.Track in a google.protobuf.Any. The field numbers are the ones
+// in the descriptors Spotify 9.1.78's binary carries (extended_metadata.proto, entity_extension_data.proto,
+// extension_kind.proto, metadata.proto). Apple's song is the one of its catalog's answers that is the same
+// recording: the same ISRC, the same length within kHapticLengthSlack, and a haptic track.
+#import <Foundation/Foundation.h>
+
+// Milliseconds two lengths of one recording may differ by.
+static const double kHapticLengthSlack = 2000;
+
+// The code uppercased when it is an ISRC: two letters, three letters or digits, seven digits. Else nil.
+NSString *SGHapticISRC(NSString *code);
+// YES for spotify:track: and a 22-character base62 id, the only kind of URI with an ISRC to ask for.
+BOOL SGHapticIsTrackURI(NSString *uri);
+// The body of the extended-metadata request for one track's Track message.
+NSData *SGHapticTrackRequest(NSString *trackURI);
+// The ISRC in a reply to SGHapticTrackRequest(trackURI), or nil. `answered` says the reply did hold the track's
+// Track message, with a 200 status for it, so a nil ISRC is final; NO means it may be worth asking again.
+NSString *SGHapticISRCInReply(NSData *reply, NSString *trackURI, BOOL *answered);
+// The catalog id of the song among Apple's (the data array of /v1/catalog/{storefront}/songs) that is the
+// recording `isrc` names and is `ms` long, with a haptic track. Nil when none is.
+NSString *SGHapticSongIn(NSArray *songs, NSString *isrc, double ms);
diff --git a/tweak/Sources/Shared/Haptics/SGHapticTrack.m b/tweak/Sources/Shared/Haptics/SGHapticTrack.m
new file mode 100644
index 00000000..6c696ba9
--- /dev/null
+++ b/tweak/Sources/Shared/Haptics/SGHapticTrack.m
@@ -0,0 +1,102 @@
+// SGHapticTrack.h says what this reads and where its field numbers come from.
+#import "SGHapticTrack.h"
+#import "Shared/AdBlock/Protobuf.h"
+
+// BatchedEntityRequest.entity_request, EntityRequest.entity_uri and .query, ExtensionQuery.extension_kind.
+enum { kRequestEntity = 2, kEntityURI = 1, kEntityQuery = 2, kQueryKind = 1 };
+// BatchedExtensionResponse.extended_metadata; EntityExtensionDataArray.header, .extension_kind and
+// .extension_data; its header's provider_error_status.
+enum { kReplyArrays = 2, kArrayHeader = 1, kArrayKind = 2, kArrayData = 3, kArrayStatus = 1 };
+// EntityExtensionData.header, .entity_uri and .extension_data; its header's status_code; Any.type_url and .value.
+enum { kDataHeader = 1, kDataURI = 2, kDataAny = 3, kDataStatus = 1, kAnyType = 1, kAnyValue = 2 };
+// Track.external_id; ExternalId.type and .id.
+enum { kTrackExternalID = 10, kExternalType = 1, kExternalID = 2 };
+static const uint64_t kTrackV4 = 10;
+static NSString *const kTrackType = @"type.googleapis.com/spotify.metadata.Track";
+
+NSString *SGHapticISRC(NSString *code) {
+ if (![code isKindOfClass:NSString.class] || code.length != 12) return nil;
+ NSString *upper = code.uppercaseString;
+ NSRange whole = [upper rangeOfString:@"^[A-Z]{2}[A-Z0-9]{3}[0-9]{7}$" options:NSRegularExpressionSearch];
+ return whole.location == NSNotFound ? nil : upper;
+}
+
+BOOL SGHapticIsTrackURI(NSString *uri) {
+ if (![uri isKindOfClass:NSString.class]) return NO;
+ return [uri rangeOfString:@"^spotify:track:[0-9A-Za-z]{22}$" options:NSRegularExpressionSearch].location != NSNotFound;
+}
+
+NSData *SGHapticTrackRequest(NSString *trackURI) {
+ NSData *query = SGPBSerialize(@[SGPBVarint(kQueryKind, kTrackV4)]);
+ NSData *entity = SGPBSerialize(@[SGPBString(kEntityURI, trackURI), SGPBBytes(kEntityQuery, query)]);
+ return SGPBSerialize(@[SGPBBytes(kRequestEntity, entity)]);
+}
+
+static NSArray<SGPBField *> *allOf(NSArray<SGPBField *> *fields, uint32_t number, uint8_t wire) {
+ NSMutableArray<SGPBField *> *found = [NSMutableArray array];
+ for (SGPBField *field in fields) {
+ if (field.number == number && field.wire == wire) [found addObject:field];
+ }
+ return found;
+}
+
+static NSArray<SGPBField *> *messageIn(NSArray<SGPBField *> *fields, uint32_t number) {
+ SGPBField *field = allOf(fields, number, 2).firstObject;
+ return field ? SGPBParse(field.payload) : nil;
+}
+
+// An explicit status other than 200 is a failure; proto3 leaves a 0 off the wire, so a missing one reads 0.
+static uint64_t statusIn(NSArray<SGPBField *> *header, uint32_t number) {
+ return allOf(header, number, 0).firstObject.varint;
+}
+
+NSString *SGHapticISRCInReply(NSData *reply, NSString *trackURI, BOOL *answered) {
+ *answered = NO;
+ for (SGPBField *arrayField in allOf(SGPBParse(reply), kReplyArrays, 2)) {
+ NSArray<SGPBField *> *array = SGPBParse(arrayField.payload);
+ NSArray<SGPBField *> *arrayHeader = messageIn(array, kArrayHeader);
+ // A provider's status may be missing, but not other than 200 when it is there.
+ if (!array || (allOf(arrayHeader, kArrayStatus, 0).count && statusIn(arrayHeader, kArrayStatus) != 200)) continue;
+ SGPBField *kind = allOf(array, kArrayKind, 0).firstObject;
+ if (kind && kind.varint != kTrackV4) continue;
+ for (SGPBField *dataField in allOf(array, kArrayData, 2)) {
+ NSArray<SGPBField *> *data = SGPBParse(dataField.payload);
+ if (![SGPBText(allOf(data, kDataURI, 2).firstObject) isEqualToString:trackURI]) continue;
+ if (statusIn(messageIn(data, kDataHeader), kDataStatus) != 200) continue;
+ NSArray<SGPBField *> *any = messageIn(data, kDataAny);
+ if (![SGPBText(allOf(any, kAnyType, 2).firstObject) isEqualToString:kTrackType]) continue;
+ SGPBField *value = allOf(any, kAnyValue, 2).firstObject;
+ NSArray<SGPBField *> *track = value ? SGPBParse(value.payload) : nil;
+ if (!track) continue;
+ *answered = YES;
+ for (SGPBField *externalField in allOf(track, kTrackExternalID, 2)) {
+ NSArray<SGPBField *> *external = SGPBParse(externalField.payload);
+ if ([SGPBText(allOf(external, kExternalType, 2).firstObject).lowercaseString isEqualToString:@"isrc"]) {
+ NSString *isrc = SGHapticISRC(SGPBText(allOf(external, kExternalID, 2).firstObject));
+ if (isrc) return isrc;
+ }
+ }
+ return nil;
+ }
+ }
+ return nil;
+}
+
+static id valueAt(id dictionary, NSString *key) {
+ return [dictionary isKindOfClass:NSDictionary.class] ? dictionary[key] : nil;
+}
+
+NSString *SGHapticSongIn(NSArray *songs, NSString *isrc, double ms) {
+ NSString *wanted = SGHapticISRC(isrc);
+ if (!wanted || ms <= 0 || ![songs isKindOfClass:NSArray.class]) return nil;
+ for (id song in songs) {
+ id identifier = valueAt(song, @"id"), attributes = valueAt(song, @"attributes");
+ id length = valueAt(attributes, @"durationInMillis"), haptics = valueAt(attributes, @"hasHaptics");
+ if (![identifier isKindOfClass:NSString.class] || ![identifier length]) continue;
+ if (![SGHapticISRC(valueAt(attributes, @"isrc")) isEqualToString:wanted]) continue;
+ if (![length isKindOfClass:NSNumber.class] || fabs([length doubleValue] - ms) > kHapticLengthSlack) continue;
+ if (![haptics isKindOfClass:NSNumber.class] || ![haptics boolValue]) continue;
+ return identifier;
+ }
+ return nil;
+}
diff --git a/tweak/Sources/Shared/Haptics/SystemMusicHaptics.x b/tweak/Sources/Shared/Haptics/SystemMusicHaptics.x
index b73b9c0f..83f5d14d 100644
--- a/tweak/Sources/Shared/Haptics/SystemMusicHaptics.x
+++ b/tweak/Sources/Shared/Haptics/SystemMusicHaptics.x
@@ -1,67 +1,296 @@
-// iOS's own Music Haptics for Spotify: the system plays a haptic track along with a recording it knows by
-// its ISRC, in the background and on the lock screen too, for an app that declares MusicHapticsSupported
-// (plist/liquid-glass.plist) and names the ISRC in its now playing info. Spotify names none, so the song is
-// looked up in Apple Music's catalog and its ISRC rides on Spotify's info as an extra. Nothing is asked
-// while Music Haptics is off in Settings > Accessibility, and turning it on there looks the playing song up
-// at once. When Apple has a haptic track for the song, the mod's own Music Haptics (MusicHaptics.x) stands
-// down until the next one, so the two never play over each other.
+// Music Haptics > Native iOS: iOS's own Music Haptics for Spotify. The system plays Apple Music's haptic track
+// for a recording, in the background and on the lock screen too, for an app that declares
+// MusicHapticsSupported (plist/liquid-glass.plist) and names the recording in its now playing info. Spotify
+// names none, so the mod adds one to Spotify's info (Shared/Player/NowPlayingExtras.h), exactly one:
+//
+// 1. The track's ISRC, from Spotify's own metadata (SGHapticTrack.h), asked with the headers of Spotify's
+// own spclient requests. No search by name: a live take or a remaster has a name of the same song.
+// 2. Apple Music's song for that ISRC, asked of its catalog by ISRC and taken only when it is the same
+// length within 2 s and has a haptic track. Its catalog id goes under MediaPlayer's iTunes Store
+// identifier key, the name MediaPlayer exports for it, resolved at runtime and skipped when missing.
+// The ISRC is left off then: MediaRemoteUI asks for the ISRC first when both are there, and an ISRC it
+// cannot find showed "Music Haptics unavailable" over the matched song playing (iOS 27.2).
+// 3. Failing a song, the ISRC itself, and iOS asked whether it has a haptic track for it.
+//
+// A new track or a new choice takes the old identifier off at once, before anything is asked, and every
+// answer carries the revision it was asked under, so one for an earlier track is dropped. Nothing is
+// published while Music Haptics is off in Settings > Accessibility, or with another choice than Native iOS.
+// iOS repeats its notifications as the now playing info changes; only a change in whether it is on or
+// paused is acted on, since sending the info again on each would feed back into the system service.
+//
+// ponytail: the identifier rides on Spotify's info by title, as NowPlayingExtras matches it, so a next track
+// with the same title can carry the last one's for the moment before the player reports it. Matching by the
+// info's external content identifier would close that, in NowPlayingExtras for every owner.
+// ponytail: an answer for an earlier track is dropped rather than its request cancelled; the lookups are
+// kept and shared, and a cancel would take the answer from another asker waiting on it.
#import <MediaAccessibility/MediaAccessibility.h>
#import <MediaPlayer/MediaPlayer.h>
+#import <dlfcn.h>
+#import <objc/message.h>
#import "Core/SGCore.h"
#import "Shared/AnimatedArtwork/AnimatedArtwork.h"
+#import "Shared/Lyrics/Lyrics.h"
#import "Shared/Player/NowPlayingExtras.h"
#import "Shared/Player/PlayerState.h"
#import "Haptics.h"
+#import "SGHapticTrack.h"
+static NSString *const kExtendedMetadata = @"https://spclient.wg.spotify.com/extended-metadata/v0/extended-metadata";
+// A request that got no answer is sent this many times in all, this far apart.
+static const NSUInteger kSpotifyTries = 3;
+static const NSTimeInterval kSpotifyRetryAfter = 4;
+static const NSUInteger kKeptISRCs = 100;
+
+#pragma mark - Spotify's ISRC
+
+// By track URI; NSNull for a track Spotify answered for with no ISRC.
+static NSCache<NSString *, id> *sg_isrcs;
+
+// `done` gets the ISRC, or nil, on the main queue. The headers are read again for every try: a refused one
+// may have expired, and Spotify's next request of its own brings a fresh one. They are never logged.
+static void askSpotify(NSString *uri, NSUInteger triesLeft, void (^done)(NSString *isrc)) {
+ SGSpclientHeaders(^(NSDictionary<NSString *, NSString *> *headers) {
+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kExtendedMetadata]];
+ request.HTTPMethod = @"POST";
+ [headers enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {
+ [request setValue:value forHTTPHeaderField:name];
+ }];
+ [request setValue:@"application/x-protobuf" forHTTPHeaderField:@"Content-Type"];
+ [request setValue:@"application/x-protobuf" forHTTPHeaderField:@"Accept"];
+ request.HTTPBody = SGHapticTrackRequest(uri);
+ [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
+ NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;
+ BOOL answered = NO;
+ NSString *isrc = status == 200 ? SGHapticISRCInReply(data, uri, &answered) : nil;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (answered) {
+ [sg_isrcs setObject:isrc ?: (id)NSNull.null forKey:uri];
+ done(isrc);
+ return;
+ }
+ SGLog(@"music haptics: Spotify's metadata for %@ not answered (%ld, %@), %lu tries left", uri, (long)status,
+ error.localizedDescription, (unsigned long)triesLeft - 1);
+ if (triesLeft <= 1) {
+ done(nil);
+ return;
+ }
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kSpotifyRetryAfter * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
+ askSpotify(uri, triesLeft - 1, done);
+ });
+ });
+ }] resume];
+ });
+}
+
+static void spotifyISRC(NSString *uri, void (^done)(NSString *isrc)) {
+ id kept = [sg_isrcs objectForKey:uri];
+ if (kept) {
+ done(kept == NSNull.null ? nil : kept);
+ return;
+ }
+ askSpotify(uri, kSpotifyTries, done);
+}
+
+#pragma mark - iOS
+
+// MediaPlayer's iTunes Store identifier key: exported as _MPNowPlayingInfoPropertyiTunesStoreIdentifier
+// (the iOS 27 SDK's MediaPlayer.tbd lists __MPNowPlayingInfoPropertyiTunesStoreIdentifier), not in its headers.
+static NSString *storeIDKey(void) {
+ static NSString *key;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ void *slot = dlsym(RTLD_DEFAULT, "_MPNowPlayingInfoPropertyiTunesStoreIdentifier");
+ id value = slot ? (__bridge id)*(void **)slot : nil;
+ key = [value isKindOfClass:NSString.class] ? value : nil;
+ if (!key) SGLog(@"music haptics: MediaPlayer has no iTunes Store identifier key, the ISRC is named instead");
+ });
+ return key;
+}
+
+// Whether Music Haptics is on in Settings > Accessibility. On iOS 27 isActive follows Control Center's pause
+// instead and stays YES with the switch off; the read-only musicHapticsEnabled tells them apart where it is.
API_AVAILABLE(ios(18.0))
-@interface SGSystemMusicHaptics : NSObject <SGPlayerStateObserver>
-- (void)follow:(SPTPlayerState *)state;
+static BOOL systemEnabled(MAMusicHapticsManager *manager) {
+ SEL enabled = NSSelectorFromString(@"musicHapticsEnabled");
+ if ([manager respondsToSelector:enabled]) return ((BOOL (*)(id, SEL))objc_msgSend)(manager, enabled);
+ return manager.isActive;
+}
+
+#pragma mark - following the player
+
+typedef NS_ENUM(NSInteger, SGNativePhase) {
+ SGNativeWaiting, // nothing to look up yet
+ SGNativeChecking, // asking Spotify, Apple or iOS
+ SGNativeReady, // an identifier with a haptic track is named
+ SGNativeUnavailable, // nothing named, or iOS has no haptic track for it
+};
+
+API_AVAILABLE(ios(18.0))
+@interface SGNativeMusicHaptics : NSObject <SGPlayerStateObserver>
+- (void)follow:(SPTPlayerState *)state again:(BOOL)again;
+- (void)systemChanged;
@end
-@implementation SGSystemMusicHaptics {
+@implementation SGNativeMusicHaptics {
NSString *_track;
+ NSUInteger _revision;
+ SGNativePhase _phase;
+ NSString *_isrc, *_songID; // what the track is known by, and Apple's song when one matched
+ BOOL _known, _enabled, _active;
+ id _observer;
+ NSString *_observedCode;
+ BOOL _observedActive;
}
- (void)playerStateDidChange:(SPTPlayerState *)state {
- NSString *track = SGURIString(state.track.URI);
- if (!track || [track isEqualToString:_track]) return;
- [self follow:state];
+ [self follow:state again:NO];
}
-- (void)follow:(SPTPlayerState *)state {
+- (void)setPhase:(SGNativePhase)phase {
+ _phase = phase;
+ [self showStatus];
+}
+
+- (void)showStatus {
+ NSString *status;
+ if (!_enabled) status = @"Off in iOS";
+ else if (!_active) status = @"Paused";
+ else if (_phase == SGNativeChecking) status = @"Checking";
+ else if (_phase == SGNativeUnavailable) status = @"Unavailable";
+ else if (_phase == SGNativeWaiting) status = @"Waiting";
+ // A status callback alone is not proof: it has to be for the identifier named, and iOS active for it.
+ else status = _observedActive && ([_observedCode isEqualToString:_isrc] || [_observedCode isEqualToString:_songID]) ? @"Playing" : @"Ready";
+ SGSetMusicHapticsStatus(status);
+}
+
+- (void)publish:(NSDictionary *)extras title:(NSString *)title {
+ SGNowPlayingSetExtras(@"haptics", extras, title);
+ static NSUInteger logged;
+ if (logged++ < 3) SGLog(@"music haptics: %@ named for iOS's Music Haptics", extras.allValues.firstObject);
+}
+
+// `again` follows the same track anew: the choice, or iOS's switch, changed.
+- (void)follow:(SPTPlayerState *)state again:(BOOL)again {
NSString *track = SGURIString(state.track.URI);
+ if (!again && (track == _track || [track isEqualToString:_track])) return;
_track = track;
+ NSUInteger revision = ++_revision;
+ _isrc = _songID = nil;
+ _observedCode = nil;
+ _observedActive = NO;
+ // Off before anything is asked, so no answer can arrive while the last track's is still named.
SGNowPlayingSetExtras(@"haptics", nil, nil);
- SGMusicHapticsSetSystemPlaying(NO);
- MAMusicHapticsManager *manager = MAMusicHapticsManager.sharedManager;
- // Only a song can have a recording code: an episode or an ad is not looked up.
- if (!manager.isActive || !([track hasPrefix:@"spotify:track:"] || [track hasPrefix:@"spotify:local:"])) return;
+ if (SGMusicHapticsModeNow() != SGMusicHapticsNative || !_enabled || !track) {
+ self.phase = SGNativeWaiting;
+ return;
+ }
+ // Episodes, ads and local files have no ISRC of Spotify's.
+ if (!SGHapticIsTrackURI(track)) {
+ self.phase = SGNativeUnavailable;
+ return;
+ }
NSString *title = state.track.trackTitle;
- SGMotionSongISRC(state.track.artistName, title, ^(NSString *isrc) {
- if (!isrc || ![track isEqualToString:self->_track]) return;
- SGNowPlayingSetExtras(@"haptics", @{MPNowPlayingInfoPropertyInternationalStandardRecordingCode: isrc}, title);
- static NSUInteger logged;
- if (logged++ < 3) SGLog(@"music haptics: %@ named for iOS's Music Haptics", isrc);
- [manager checkHapticTrackAvailabilityForMediaMatchingCode:isrc completionHandler:^(BOOL available) {
- dispatch_async(dispatch_get_main_queue(), ^{
- if (!available || ![track isEqualToString:self->_track] || !manager.isActive) return;
- SGMusicHapticsSetSystemPlaying(YES);
- });
- }];
+ id length = state.track.metadata[@"duration"];
+ double ms = [length respondsToSelector:@selector(doubleValue)] && [length doubleValue] > 0 ? [length doubleValue] : state.duration * 1000;
+ self.phase = SGNativeChecking;
+ spotifyISRC(track, ^(NSString *isrc) {
+ if (revision != self->_revision) return;
+ if (!isrc) {
+ self.phase = SGNativeUnavailable;
+ return;
+ }
+ self->_isrc = isrc;
+ SGMotionSongsWithISRC(isrc, ^(NSArray *songs) {
+ if (revision != self->_revision) return;
+ NSString *song = SGHapticSongIn(songs, isrc, ms), *key = storeIDKey();
+ if (song && key) {
+ self->_songID = song;
+ [self publish:@{key: @(song.longLongValue)} title:title];
+ self.phase = SGNativeReady;
+ return;
+ }
+ [self publish:@{MPNowPlayingInfoPropertyInternationalStandardRecordingCode: isrc} title:title];
+ [MAMusicHapticsManager.sharedManager checkHapticTrackAvailabilityForMediaMatchingCode:isrc completionHandler:^(BOOL available) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (revision == self->_revision) self.phase = available ? SGNativeReady : SGNativeUnavailable;
+ });
+ }];
+ });
});
}
+// addStatusObserver: can answer nil while the switch in Accessibility is off, so it is asked again whenever
+// iOS's state or the app's comes back.
+- (void)observe {
+ if (_observer || !_enabled) return;
+ __weak SGNativeMusicHaptics *weakSelf = self;
+ _observer = [MAMusicHapticsManager.sharedManager addStatusObserver:^(NSString *code, BOOL active) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ SGNativeMusicHaptics *strongSelf = weakSelf;
+ if (!strongSelf) return;
+ strongSelf->_observedCode = code;
+ strongSelf->_observedActive = active;
+ static NSUInteger logged;
+ if (logged++ < 6) SGLog(@"music haptics: iOS reports %@ %@", code, active ? @"playing" : @"not playing");
+ [strongSelf showStatus];
+ });
+ }];
+}
+
+- (void)systemChanged {
+ MAMusicHapticsManager *manager = MAMusicHapticsManager.sharedManager;
+ BOOL enabled = systemEnabled(manager), active = manager.isActive;
+ BOOL first = !_known, wasEnabled = _enabled;
+ if (!first && enabled == _enabled && active == _active) {
+ [self observe];
+ return;
+ }
+ _known = YES;
+ _enabled = enabled;
+ _active = active;
+ SGLog(@"music haptics: iOS's Music Haptics %@, %@", enabled ? @"on" : @"off", active ? @"active" : @"paused");
+ [self observe];
+ if (first || enabled != wasEnabled) [self follow:SGPlayerState() again:YES];
+ else [self showStatus];
+}
+
@end
+// For someone with no choice stored: Native iOS when iOS's Music Haptics is on, as the mod named songs to it
+// before there was a choice, else what the old switch says. A reset leaves it unpicked, which reads None.
+static void pickMode(void) {
+ // MusicHaptics.x's constructor moves this too, but may run after this one.
+ SGMigrateKey(SGKeyMusicHapticsWas, SGKeyMusicHaptics);
+ if (SGInt(SGKeyMusicHapticsMode, -1) >= 0 || [NSUserDefaults.standardUserDefaults boolForKey:SGKeyStock]) return;
+ SGMusicHapticsMode mode = SGMusicHapticsModeNow();
+ if (@available(iOS 18.0, *)) {
+ if (systemEnabled(MAMusicHapticsManager.sharedManager)) mode = SGMusicHapticsNative;
+ }
+ SGSetInt(SGKeyMusicHapticsMode, mode);
+ SGLog(@"music haptics: picked %ld for the choice", (long)mode);
+}
+
%ctor {
+ pickMode();
if (@available(iOS 18.0, *)) {
- static SGSystemMusicHaptics *watcher;
- watcher = [SGSystemMusicHaptics new];
- SGAddPlayerStateObserver(watcher);
- [NSNotificationCenter.defaultCenter addObserverForName:MAMusicHapticsManagerActiveStatusDidChangeNotification object:nil
- queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
- SGLog(@"music haptics: iOS's Music Haptics %@", MAMusicHapticsManager.sharedManager.isActive ? @"on" : @"off");
- [watcher follow:SGPlayerState()];
+ sg_isrcs = [NSCache new];
+ sg_isrcs.countLimit = kKeptISRCs;
+ static SGNativeMusicHaptics *native;
+ native = [SGNativeMusicHaptics new];
+ SGAddPlayerStateObserver(native);
+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
+ void (^changed)(NSNotification *) = ^(NSNotification *note) { [native systemChanged]; };
+ [center addObserverForName:MAMusicHapticsManagerActiveStatusDidChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:changed];
+ // Not in the SDK's headers, though MediaAccessibility exports it: posted as the switch in Accessibility moves.
+ void *enabledName = dlsym(RTLD_DEFAULT, "MAMusicHapticsEnabledStatusDidChangeNotification");
+ id name = enabledName ? (__bridge id)*(void **)enabledName : nil;
+ if ([name isKindOfClass:NSString.class]) [center addObserverForName:name object:nil queue:NSOperationQueue.mainQueue usingBlock:changed];
+ [center addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:changed];
+ [center addObserverForName:SGMusicHapticsModeChangedNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
+ [native follow:SGPlayerState() again:YES];
}];
+ dispatch_async(dispatch_get_main_queue(), ^{ [native systemChanged]; });
+ } else {
+ SGSetMusicHapticsStatus(@"Needs iOS 18");
}
}
diff --git a/tweak/Sources/Shared/Lyrics/KaraokeSource.x b/tweak/Sources/Shared/Lyrics/KaraokeSource.x
index f99624fb..94593cd4 100644
--- a/tweak/Sources/Shared/Lyrics/KaraokeSource.x
+++ b/tweak/Sources/Shared/Lyrics/KaraokeSource.x
@@ -28,6 +28,7 @@ static NSMutableSet<NSString *> *sg_asking;
static NSMutableDictionary<NSString *, NSNumber *> *sg_losses; // requests lost in a row, by track
static NSMutableSet<NSString *> *sg_looking; // asked of the sources or spclient right now (SGKaraokeLooking)
static NSDictionary<NSString *, NSString *> *sg_spclientHeaders;
+static NSMutableArray<void (^)(NSDictionary<NSString *, NSString *> *)> *sg_headersWaiting; // SGSpclientHeaders
static __weak id sg_player;
// Every track the player has reported, by id, so a source can name a track that is not the one
// playing at the moment it is asked: a lyrics request routinely lands a beat before the player
@@ -62,7 +63,21 @@ static void rememberHeaders(NSURLSession *session, NSURLRequest *request) {
NSString *name = kSpclientHeaders[i];
if (all[name]) headers[name] = all[name];
}
- dispatch_async(dispatch_get_main_queue(), ^{ sg_spclientHeaders = headers; });
+ dispatch_async(dispatch_get_main_queue(), ^{
+ sg_spclientHeaders = headers;
+ NSArray *waiting = sg_headersWaiting;
+ sg_headersWaiting = nil;
+ for (void (^waiter)(NSDictionary<NSString *, NSString *> *) in waiting) waiter(headers);
+ });
+}
+
+void SGSpclientHeaders(void (^use)(NSDictionary<NSString *, NSString *> *headers)) {
+ if (sg_spclientHeaders) {
+ use(sg_spclientHeaders);
+ return;
+ }
+ if (!sg_headersWaiting) sg_headersWaiting = [NSMutableArray array];
+ [sg_headersWaiting addObject:[use copy]];
}
static SPTPlayerState *playerState(void);
@@ -415,11 +430,32 @@ static void prefetch(SPTPlayerTrack *track, NSString *trackID, SPTPlayerState *s
}
%end
+// With nothing of the karaoke's on, the headers are still read for SGSpclientHeaders' other askers
+// (Native iOS Music Haptics, which can be picked at any moment).
+%group SGSpclientHeadersOnly
+%hook SPTDataLoaderService
+- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
+ rememberHeaders(session, task.currentRequest);
+ %orig;
+}
+%end
+
+%hook _TtC26Connectivity_HttpClientKit20HttpClientURLSession
+- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
+ rememberHeaders(session, task.currentRequest);
+ %orig;
+}
+%end
+%end
+
%ctor {
// The sources that search by name learn the name from the player, so the player is caught
// whenever one is on, not only for the redesign's lyrics and the lock screen.
if (!SGRedesignedUI() && !SGFlag(SGKeyLockScreenLyrics, NO) && !SGLyricsEnabled()
- && SGLockScreenArtwork() != SGLockArtworkLyrics) return;
+ && SGLockScreenArtwork() != SGLockArtworkLyrics) {
+ %init(SGSpclientHeadersOnly);
+ return;
+ }
sg_seenTracks = [NSMutableDictionary dictionary];
sg_lyrics = [NSMutableDictionary dictionary];
sg_requested = [NSMutableSet set];
diff --git a/tweak/Sources/Shared/Lyrics/Lyrics.h b/tweak/Sources/Shared/Lyrics/Lyrics.h
index 149ea36e..10a5c557 100644
--- a/tweak/Sources/Shared/Lyrics/Lyrics.h
+++ b/tweak/Sources/Shared/Lyrics/Lyrics.h
@@ -105,6 +105,9 @@ extern NSNotificationName const SGKaraokeLinesKeptNotification;
// them: the ask in flight, not the pause before a lost one is asked again. A local file's walk can take
// tens of seconds. A walk LyricsSources runs for Spotify's own request is not seen here. Main queue.
BOOL SGKaraokeLooking(NSString *trackID);
+// The headers spclient needs to answer a request as the signed-in app, read off Spotify's own requests:
+// `use` runs at once when one has been seen, else with the first. Never logged or stored. Main queue.
+void SGSpclientHeaders(void (^use)(NSDictionary<NSString *, NSString *> *headers));
// Asks spclient for a track's lyrics once, with the headers of Spotify's own requests, for when no
// page of Spotify's has asked for them, e.g. with the app in the background.
void SGKaraokeRequestLyrics(NSString *trackID);