Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: Spotify's own sleep timer follows the fade-out choice
My-Name-Is-Jefff28d3817c982
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 276b442a..3cef7cac 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -202,8 +202,13 @@ Shared:having played already when it repeats. Over the last seconds (the Live Activity page's Fade out: Off,10 s, 30 s, 1 minute or 2 minutes, 30 s unless picked; at the end of a track, over the whole trackwhen it is shorter) it fades the sound 60 dB through a gain of the mod's own, applied by SpeedPitch.x's notify on the music's RemoteIO unit (never the system- volume), and puts the gain back a second after the pause. Tested on the Mac against- harness/sleep-timer/, the gain in the simulator against harness/speed/+ volume), and puts the gain back a second after the pause. Spotify's own timer, from the player's+ ⋯ menu, fades by the same choice and gain (SpotifySleepTimer.m): the core reports it in the player's+ state (SPTPlayerState's sleepTimer: type 1 at a timestamp, 2 at the end of the track), checked four+ times a second while Spotify plays; Spotify pauses, the gain is held down from its end until that+ pause and back a second later, at once on a cancel or a later time. It stands aside while the mod's+ own timer runs and while Spotify's own Fade out flag (its DuckHandlerImpl's duck) is forced on.+ Tested on the Mac against harness/sleep-timer/, the gain in the simulator against harness/speed/AudioEffects/ the audio effects on Spotify's sound (AudioEffects.h has the keys and the page's calls): a rendernotify on the music's RemoteIO unit (SGPlayerMusicOutput, Shared/Player) runs each finished buffer through the mod's own engine, re-blocked to 1024 frames one block late,in place (AudioEffects.x, SGDSPEngine.m), then hands it, mixed to mono, to one reader that onlydiff --git a/harness/menu/README.md b/harness/menu/README.mdindex 99b976a5..aa4419ec 100644--- a/harness/menu/README.md+++ b/harness/menu/README.md@@ -7,7 +7,7 @@ class name and presented from a now playing controller on a tap of the player'sTHEOS=$HOME/theos ./build.shxcrun simctl install <udid> build/MenuHarness.app- xcrun simctl launch --console-pty <udid> com.vojta.menuharness [footer] [nospeed] [loading] [stuck] [open] [animated] [sleep] [notap]+ xcrun simctl launch --console-pty <udid> com.vojta.menuharness [footer] [nospeed] [loading] [stuck] [open] [animated] [sleep] [notap] [minute]It has a scene delegate, so it runs on the iOS 27 simulator as well as 26. The mod's own lines(`SGLog`) go to the unified log: `xcrun simctl spawn <udid> log stream --predicate 'eventMessage CONTAINS "[spotifyglass]"'`.@@ -34,6 +34,9 @@ the Pitch and the row read "−3 st".- `sleep` opens the ⋯ card, checks it has the block, then pushes a second sheet into it with no tap, asthe card's Sleep timer row does: `PASS` when that sheet has no block.- `notap` presents a sheet from the player with no tap on the more button: `PASS` when it has no block.+- `minute` runs `MinuteLabel.x` on Spotify's two sleep timer cells, mocked under their class names: a label+ reading "1 minutes" in each reads "1 minute" in the font it had, and "5 minutes", "1 minuto" and a label+ outside those cells stay as they were.For the first second the block is on screen, every frame is checked for anything it draws in thesystem tint (`tint check: 0 of the block's first N frames ...`).diff --git a/harness/menu/build.sh b/harness/menu/build.shindex ca913210..e35733e8 100755--- a/harness/menu/build.sh+++ b/harness/menu/build.sh@@ -6,6 +6,7 @@ SRC=$(cd "$(dirname "$0")/../../tweak/Sources" && pwd)OUT=$(dirname "$0")/buildrm -rf "$OUT"; mkdir -p "$OUT/gen" "$OUT/MenuHarness.app""$THEOS/bin/logos.pl" -c generator=internal "$SRC/Shared/Player/SpeedPitchMenu.x" > "$OUT/gen/SpeedPitchMenu.m"+"$THEOS/bin/logos.pl" -c generator=internal "$SRC/Shared/Player/MinuteLabel.x" > "$OUT/gen/MinuteLabel.m"SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-arc -g -O0 \diff --git a/harness/menu/main.m b/harness/menu/main.mindex 01baa1f8..0562257e 100644--- a/harness/menu/main.m+++ b/harness/menu/main.m@@ -4,7 +4,7 @@// neither may get the block.//// THEOS=$HOME/theos ./build.sh && xcrun simctl install <udid> build/MenuHarness.app-// xcrun simctl launch --console-pty <udid> com.vojta.menuharness [footer] [nospeed] [loading] [stuck] [open] [animated] [sleep] [notap]+// xcrun simctl launch --console-pty <udid> com.vojta.menuharness [footer] [nospeed] [loading] [stuck] [open] [animated] [sleep] [notap] [minute]//// The plain run opens the menu at 1 s, opens the block at 3 s, moves the sliders at 5 s, checks what the// block says at 6 s (PASS or FAIL lines), closes the block at 7 s and checks its row at 8 s. `loading` builds the sheet the way Spotify's is (the ivars of ContextMenuViewController in@@ -313,6 +313,46 @@ static void report(_TtC24ContextMenu_InternalImpl25ContextMenuViewController *metable.tableHeaderView == block ? @"header" : table.tableFooterView == block ? @"footer" : @"nowhere");}+#pragma mark - the sleep timer's cells++// Spotify's two cells that list the sleep timer's durations, under their class names (MinuteLabel.x).+@interface _TtC24ContextMenu_InternalImpl24ContextMenuTableViewCell : UITableViewCell+@end+@implementation _TtC24ContextMenu_InternalImpl24ContextMenuTableViewCell+@end+@interface _TtC30PlaybackControl_SleepTimerImpl10OptionCell : UICollectionViewCell+@end+@implementation _TtC30PlaybackControl_SleepTimerImpl10OptionCell+@end++// `minute`: a label reading "1 minutes" in each cell reads "1 minute" once laid out, in the font it had; "5+// minutes", another language's text and a label outside those cells stay as they were.+static void checkMinute(UIWindow *window) {+ UIFont *font = [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold];+ UILabel *(^label)(UIView *, NSString *) = ^UILabel *(UIView *host, NSString *text) {+ UILabel *made = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];+ made.attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];+ [host addSubview:made];+ return made;+ };+ UIView *row = [[_TtC24ContextMenu_InternalImpl24ContextMenuTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];+ UIView *option = [[_TtC30PlaybackControl_SleepTimerImpl10OptionCell alloc] initWithFrame:CGRectMake(0, 100, 300, 50)];+ UIView *elsewhere = [[UIView alloc] initWithFrame:CGRectMake(0, 200, 300, 50)];+ UILabel *inRow = label(((UITableViewCell *)row).contentView, @"1 minutes"), *five = label(((UITableViewCell *)row).contentView, @"5 minutes");+ UILabel *inOption = label(((UICollectionViewCell *)option).contentView, @"1 minutes"), *other = label(((UICollectionViewCell *)option).contentView, @"1 minuto");+ UILabel *outside = label(elsewhere, @"1 minutes");+ row.frame = CGRectMake(0, 0, 300, 50);+ for (UIView *view in @[row, option, elsewhere]) {+ [window addSubview:view];+ [view setNeedsLayout];+ [view layoutIfNeeded];+ }+ check([inRow.text isEqualToString:@"1 minute"] && [inRow.font isEqual:font], [NSString stringWithFormat:@"the context menu row reads \"%@\" in its own font", inRow.text]);+ check([inOption.text isEqualToString:@"1 minute"] && [inOption.font isEqual:font], [NSString stringWithFormat:@"the options cell reads \"%@\" in its own font", inOption.text]);+ check([five.text isEqualToString:@"5 minutes"] && [other.text isEqualToString:@"1 minuto"] && [outside.text isEqualToString:@"1 minutes"],+ [NSString stringWithFormat:@"the rest is left alone (\"%@\", \"%@\", \"%@\" outside the cells)", five.text, other.text, outside.text]);+}+#pragma mark - the run@interface SGHarnessApp : UIResponder <UIApplicationDelegate>@@ -359,6 +399,10 @@ static void tapRow(UIViewController *menu) {[[CADisplayLink displayLinkWithTarget:watch selector:@selector(tick:)] addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];[player presentViewController:navigation animated:YES completion:nil];};+ if (argument(@"minute")) {+ after(1, ^{ checkMinute(self.window); });+ return;+ }if (argument(@"sleep") || argument(@"notap")) {// `sleep`: the ⋯ card's Sleep timer row opens a context menu sheet of its own in the card, with no tap// on the more button; it must stay Spotify's. `notap`: a sheet the player puts up with no tap at all.diff --git a/harness/sleep-timer/README.md b/harness/sleep-timer/README.mdindex 088bf229..d7963985 100644--- a/harness/sleep-timer/README.md+++ b/harness/sleep-timer/README.md@@ -13,6 +13,14 @@ answered by `main.m`): each length's curve, Off at full volume all the way, noneread as 30 s; a change applies to a timer already running; at the end of the track or the album the fadespans a track shorter than it, from its start; a time fades over the last seconds before its end.+`SpotifySleepTimer.m` too, Spotify's own timer as the player's state reports it (`main.m` gives the state a+`sleepTimer` and calls the observer the file adds at load): a time fades by the choice, a later time and a+cancel bring the gain back at once; at its time, or dropped from the state at its end, the gain stays down,+with no pause from the mod, until Spotify's pause and comes back a second after it; the expired timer still+reported is not faded again; End of track fades over the track's last seconds, takes a skip mid track as the+new track's end, and holds the gain down into the next track until the pause; Off, a choice picked while it+runs, Spotify's own Fade out forced on and the mod's own timer running each leave or bring the gain right.+./build.sh && build/sleep-timer-2026-10-06: all held (52 checks). The gain itself is checked on Spotify's audio chain in harness/speed/.+2026-10-06: all held (77 checks). The gain itself is checked on Spotify's audio chain in harness/speed/.diff --git a/harness/sleep-timer/build.sh b/harness/sleep-timer/build.shindex 3c93c579..3c1fdaed 100755--- a/harness/sleep-timer/build.sh+++ b/harness/sleep-timer/build.sh@@ -1,9 +1,10 @@#!/bin/sh# Builds the sleep timer harness for the Mac: SleepTimer.m as the tweak compiles it, the UIKit headers it-# imports stood in for by stub/, and main.m.+# imports stood in for by stub/, SpotifySleepTimer.m (Spotify's own timer followed) and main.m.set -ecd "$(dirname "$0")"mkdir -p buildxcrun clang -fobjc-arc -O2 -Wall -Werror -I stub -I ../../tweak/Sources -framework Foundation \- main.m ../../tweak/Sources/Shared/Player/SleepTimer.m -o build/sleep-timer+ main.m ../../tweak/Sources/Shared/Player/SleepTimer.m ../../tweak/Sources/Shared/Player/SpotifySleepTimer.m \+ -o build/sleep-timerecho "built build/sleep-timer"diff --git a/harness/sleep-timer/main.m b/harness/sleep-timer/main.mindex 3701ba05..bacada92 100644--- a/harness/sleep-timer/main.m+++ b/harness/sleep-timer/main.m@@ -7,6 +7,7 @@#import <Foundation/Foundation.h>#import "Headers/SPTPlayer.h"#import "Shared/Player/SleepTimer.h"+#import "Shared/Player/PlayerState.h"#import "Core/SGPrefs.h"@interface SPTPlayerTrack ()@@ -24,11 +25,20 @@@implementation SPTPlayerOptions@end+@interface SPTSleepTimer ()+@property (nonatomic, readwrite) NSUInteger type;+@property (nonatomic, readwrite) NSDate *timestamp;+@end+@implementation SPTSleepTimer+@end+@interface SPTPlayerState ()@property (nonatomic, readwrite) SPTPlayerTrack *track;@property (nonatomic, readwrite) id contextURI;@property (nonatomic, readwrite) SPTPlayerOptions *options;@property (nonatomic, readwrite) BOOL isPaused;+@property (nonatomic, readwrite) BOOL isPlaying;+@property (nonatomic, readwrite) SPTSleepTimer *sleepTimer;@property (nonatomic, readwrite) double duration;@property (nonatomic, readwrite) NSArray *future;@property (nonatomic, readwrite) NSArray *reverse;@@ -45,10 +55,19 @@- (id)pause:(id)options {self.pauses++;self.state.isPaused = YES;+ self.state.isPlaying = NO;return nil;}@end+// SpotifySleepTimer.m's player state observer, and Spotify's own Fade out flag as forced (nil for not).+static id<SGPlayerStateObserver> sg_observer;+void SGAddPlayerStateObserver(id<SGPlayerStateObserver> observer) { sg_observer = observer; }+static NSNumber *sg_spotifyFadeForced;+id SGForcedFlagValue(NSString *key) {+ return [key isEqualToString:@"ios-feature-sleeptimer.enable_fade_out"] ? sg_spotifyFadeForced : nil;+}+static MockPlayer *sg_player;static NSInteger sg_positionMs = -1;static float sg_gain = 1;@@ -100,6 +119,14 @@ static SPTPlayerState *state(SPTPlayerTrack *playing, NSArray *future, NSArray *return state;}+// Spotify's own timer as its state reports it: type 1 at `seconds` from now, 2 at the end of the track.+static SPTSleepTimer *spotifyTimer(NSUInteger type, NSTimeInterval seconds) {+ SPTSleepTimer *timer = [SPTSleepTimer new];+ timer.type = type;+ if (type == 1) timer.timestamp = [NSDate dateWithTimeIntervalSinceNow:seconds];+ return timer;+}+static void runFor(NSTimeInterval seconds) {[NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:seconds]];}@@ -276,6 +303,122 @@ int main(void) {CHECK(near(sg_gain, SGSleepTimerGain(15, 30)) && near(sg_gain, 0.0316f), "a time, 30 s fade, 15 s to go: 30 dB down");SGSetSleepTimer(SGSleepTimerOff, 0);CHECK(sg_gain == 1, "cancelled: full volume");++ // Spotify's own timer (SpotifySleepTimer.m), read off the state; the core pauses, never the mod.+ CHECK(sg_observer != nil, "Spotify's timer: an observer of the player's state is added at load");+ sg_fadeChoice = @2; // 30 s+ NSInteger pauses = sg_player.pauses;+ sg_player.state = state(a, @[b, c], @[], NO);+ sg_player.state.isPlaying = YES;+ [sg_observer playerStateDidChange:sg_player.state];+ runFor(0.4);+ CHECK(sg_gain == 1, "Spotify's: playing with no timer, full volume");+ sg_player.state.sleepTimer = spotifyTimer(1, 20);+ runFor(0.4);+ CHECK(sg_gain < SGSleepTimerGain(20.5, 30) && sg_gain > SGSleepTimerGain(19, 30), "Spotify's, at a time 20 s on: faded as 20 s into a 30 s fade");+ sg_player.state.sleepTimer = spotifyTimer(1, 15 * 60);+ runFor(0.4);+ CHECK(sg_gain == 1, "Spotify's moved 15 minutes on: the gain is back");+ sg_player.state.sleepTimer = spotifyTimer(1, 15);+ runFor(0.4);+ CHECK(sg_gain < 0.1f, "Spotify's 15 s on: 30 dB down or so");+ sg_player.state.sleepTimer = nil;+ runFor(0.4);+ CHECK(sg_gain == 1, "Spotify's cancelled mid fade: the gain is back at once");++ sg_player.state.sleepTimer = spotifyTimer(1, 1.5);+ runFor(0.4);+ CHECK(sg_gain < 0.01f, "Spotify's 1.5 s on: nearly silent");+ runFor(1.5);+ CHECK(sg_gain < 0.002f && sg_player.pauses == pauses, "its time came: held down, and no pause from the mod");+ sg_player.state.isPaused = YES; // the core pauses, the expired timer still in its state+ sg_player.state.isPlaying = NO;+ runFor(0.4);+ CHECK(sg_gain < 0.002f, "Spotify paused: still down while the pause lands");+ runFor(1.2);+ CHECK(sg_gain == 1, "a second after Spotify's pause the gain is back");+ sg_player.state.isPaused = NO;+ sg_player.state.isPlaying = YES;+ [sg_observer playerStateDidChange:sg_player.state];+ runFor(0.4);+ CHECK(sg_gain == 1, "played again with the expired timer still reported: not faded again");+ sg_player.state.sleepTimer = nil;+ runFor(0.4);++ sg_player.state.sleepTimer = spotifyTimer(1, 1);+ runFor(0.5);+ sg_player.state.sleepTimer = nil; // dropped at its end, before the pause+ runFor(0.4);+ CHECK(sg_gain < 0.002f, "Spotify's dropped at its end while still playing: held down");+ sg_player.state.isPaused = YES;+ sg_player.state.isPlaying = NO;+ runFor(1.6);+ CHECK(sg_gain == 1, "then paused: the gain is back a second later");++ sg_player.state = state(a, @[b, c], @[], NO);+ sg_player.state.isPlaying = YES;+ [sg_observer playerStateDidChange:sg_player.state];+ sg_positionMs = 85000;+ sg_player.state.sleepTimer = spotifyTimer(2, 0);+ runFor(0.4);+ CHECK(near(sg_gain, SGSleepTimerGain(15, 30)), "Spotify's end of track, 15 s left of a 30 s fade: 30 dB down");+ sg_player.state = state(b, @[c], @[a], NO);+ sg_player.state.isPlaying = YES;+ sg_player.state.sleepTimer = spotifyTimer(2, 0);+ sg_positionMs = 1000;+ runFor(0.4);+ CHECK(sg_gain == 1, "skipped to another track with time to go: its end is the one now, full volume");+ sg_positionMs = 99500;+ runFor(0.4);+ CHECK(sg_gain < 0.002f, "half a second before that track's end: nearly silent");+ sg_player.state = state(c, @[], @[a, b], NO); // the next track, the timer still reported+ sg_player.state.isPlaying = YES;+ sg_player.state.sleepTimer = spotifyTimer(2, 0);+ sg_positionMs = 0;+ runFor(0.4);+ CHECK(sg_gain < 0.002f && sg_player.pauses == pauses, "the track ended into the next: held down, no pause from the mod");+ sg_player.state.isPaused = YES;+ sg_player.state.isPlaying = NO;+ runFor(1.6);+ CHECK(sg_gain == 1, "Spotify paused: the gain is back");+ sg_player.state.sleepTimer = nil;+ sg_player.state.isPaused = NO;+ sg_player.state.isPlaying = YES;+ [sg_observer playerStateDidChange:sg_player.state];+ runFor(0.4);++ sg_player.state.duration = 20;+ sg_positionMs = 10000;+ sg_player.state.sleepTimer = spotifyTimer(2, 0);+ runFor(0.4);+ CHECK(near(sg_gain, 0.0316f), "Spotify's end of a 20 s track, halfway: the fade spans the track, 30 dB down");+ sg_player.state.sleepTimer = nil;+ runFor(0.4);++ sg_fadeChoice = @0; // Off+ sg_player.state.sleepTimer = spotifyTimer(1, 5);+ runFor(0.4);+ CHECK(sg_gain == 1, "Spotify's with fade Off: full volume");+ sg_fadeChoice = @2;+ runFor(0.4);+ CHECK(sg_gain < 0.1f, "30 s picked while it runs: faded");+ sg_spotifyFadeForced = @YES;+ runFor(0.4);+ CHECK(sg_gain == 1, "Spotify's own Fade out forced on: the mod stands aside, full volume");+ sg_spotifyFadeForced = nil;+ sg_player.state.sleepTimer = nil;+ runFor(0.4);++ SGSetSleepTimer(SGSleepTimerAtTime, 300);+ sg_player.state.sleepTimer = spotifyTimer(1, 10);+ runFor(0.4);+ CHECK(sg_gain == 1, "the mod's own timer running (300 s): it has the gain, Spotify's is not faded");+ SGSetSleepTimer(SGSleepTimerOff, 0);+ runFor(0.4);+ CHECK(sg_gain < 0.1f, "the mod's own cancelled: Spotify's, 10 s on, is faded");+ sg_player.state.sleepTimer = nil;+ runFor(0.4);+ CHECK(sg_gain == 1 && sg_player.pauses == pauses, "and cancelled: full volume; the mod sent no pause for Spotify's");}printf("%s\n", sg_failures ? "FAILED" : "all held");return sg_failures ? 1 : 0;diff --git a/harness/sleep-timer/stub/Shared/Player/PlayerState.h b/harness/sleep-timer/stub/Shared/Player/PlayerState.hindex d1101ea6..8f5f7ff1 100644--- a/harness/sleep-timer/stub/Shared/Player/PlayerState.h+++ b/harness/sleep-timer/stub/Shared/Player/PlayerState.h@@ -1,3 +1,8 @@-// The call SleepTimer.m makes of PlayerState.h, without UIKit; main.m answers it.+// The calls SleepTimer.m and SpotifySleepTimer.m make of PlayerState.h, without UIKit; main.m answers them.#import <Foundation/Foundation.h>+#import "Headers/SPTPlayer.h"NSString *SGURIString(id uri);+@protocol SGPlayerStateObserver <NSObject>+- (void)playerStateDidChange:(SPTPlayerState *)state;+@end+void SGAddPlayerStateObserver(id<SGPlayerStateObserver> observer);diff --git a/tweak/Sources/Headers/SPTPlayer.h b/tweak/Sources/Headers/SPTPlayer.hindex 58712a1e..cf09c240 100644--- a/tweak/Sources/Headers/SPTPlayer.h+++ b/tweak/Sources/Headers/SPTPlayer.h@@ -20,8 +20,18 @@@property (nonatomic, readonly) BOOL repeatingTrack;@end+// Spotify's own sleep timer as the player core reports it: es_sleep_timer.proto's oneof, which the state+// builder maps (hasSleepTimer, then setSleepTimer:) to type 0 none, 1 at `timestamp` (the proto's ms since+// 1970), 2 at the end of the track (Shared/Player/SpotifySleepTimer.m reads it).+@interface SPTSleepTimer : NSObject+@property (nonatomic, readonly) NSUInteger type;+@property (nonatomic, readonly) NSDate *timestamp;+@end+@interface SPTPlayerState : NSObject@property (nonatomic, readonly) SPTPlayerTrack *track;+// Nil while the core reports none.+@property (nonatomic, readonly) SPTSleepTimer *sleepTimer;@property (nonatomic, readonly) id contextURI;@property (nonatomic, readonly) SPTPlayerOptions *options;@property (nonatomic, readonly) BOOL isPaused;diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m b/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.mindex 13a96ffd..a4407c02 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m+++ b/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m@@ -16,14 +16,15 @@ UIViewController *SGLiveActivitySettingsPage(void) {SGModRow *translation = SGOptionRow(@"Translations", @"Under the line, when the lyrics have one", SGKeyLiveActivityTranslation);SGModRow *size = SGChoiceRow(@"Text size", nil, SGKeyLiveActivityTextSize, @[@"Small", @"Medium", @"Large"], SGLiveActivityTextMedium);for (SGModRow *row in @[translation, size]) row.visible = ^BOOL { return SGInt(SGKeyLiveActivityView, SGLiveActivityLyrics) == SGLiveActivityLyrics; };- // The sleep timer's own: the card's Timer tab, the Sleep Timer shortcut and its control all fade by it, card on or off.+ // The sleep timer's own: the card's Timer tab, the Sleep Timer shortcut and its control all fade by it, card on or+ // off, and so does Spotify's own timer from the player's menu (Shared/Player/SpotifySleepTimer.m).NSArray<NSString *> *fades = SGSleepTimerFadeNames();SGModRow *fade = SGMenuRow(@"Fade out", fades, ^NSString *{ return fades[(NSUInteger)SGSleepTimerFadeChoice()]; },^(NSInteger index) { SGSetInt(SGKeySleepTimerFade, index); });return [[SGModPage alloc] initWithTitle:@"Live Activity" intro:nil sections:@[SGSection(nil, @[on, view, translation, size]),SGNotedSection(@"Sleep timer", @[fade],- @"How long the sound fades before the sleep timer pauses Spotify, from the Timer tab, the Sleep Timer shortcut or Control Center."),+ @"How long the sound fades before a sleep timer pauses Spotify: the one set from the Timer tab, the Sleep Timer shortcut or Control Center, and Spotify's own from the player's ⋯ menu."),] footer:nil];}diff --git a/tweak/Sources/Shared/Player/MinuteLabel.x b/tweak/Sources/Shared/Player/MinuteLabel.xnew file mode 100644index 00000000..de007853--- /dev/null+++ b/tweak/Sources/Shared/Player/MinuteLabel.x@@ -0,0 +1,38 @@+// Spotify's sleep timer calls its one minute option (the flag ios-feature-sleeptimer.enable_one_minute_option)+// "1 minutes", in both places it lists the durations: the rows of its context menu sheet+// (SleepTimerActionsProviderImplementation's actions, drawn in ContextMenu_InternalImpl.ContextMenuTableViewCell)+// and the options sheet (PlaybackControl_SleepTimerImpl.OptionCell, a collection view cell). The text comes from+// Swift with no way in, so each of those cells has a label reading exactly "1 minutes" set right as it lays out.+// Only that English text is touched: any other language's, and every other label, stay as Spotify set them.+#import "Core/SGCore.h"++static void fixMinute(UIView *cell) {+ SGForEachView(cell, ^(UIView *view) {+ if (![view isKindOfClass:UILabel.class]) return;+ UILabel *label = (UILabel *)view;+ if (label.text.length != 9 || ![label.text isEqualToString:@"1 minutes"]) return;+ // Through the attributed text, so the label keeps the font and colour Spotify gave it.+ NSMutableAttributedString *text = [label.attributedText mutableCopy];+ [text replaceCharactersInRange:NSMakeRange(0, text.length) withString:@"1 minute"];+ label.attributedText = text;+ });+}++%hook _TtC24ContextMenu_InternalImpl24ContextMenuTableViewCell+- (void)layoutSubviews {+ %orig;+ fixMinute((UIView *)self);+}+%end++%hook _TtC30PlaybackControl_SleepTimerImpl10OptionCell+- (void)layoutSubviews {+ %orig;+ fixMinute((UIView *)self);+}+%end++%ctor {+ %init;+ SGRequireClasses(@[@"_TtC24ContextMenu_InternalImpl24ContextMenuTableViewCell", @"_TtC30PlaybackControl_SleepTimerImpl10OptionCell"]);+}diff --git a/tweak/Sources/Shared/Player/SleepTimer.h b/tweak/Sources/Shared/Player/SleepTimer.hindex 25973f20..bd86f020 100644--- a/tweak/Sources/Shared/Player/SleepTimer.h+++ b/tweak/Sources/Shared/Player/SleepTimer.h@@ -51,3 +51,6 @@ float SGSleepTimerGain(NSTimeInterval left, NSTimeInterval fade);// the state's tracks to come (tracks queued by hand and autoplay's don't count), or the next one already// played, which is repeat starting the album over.BOOL SGSleepTimerOnLastOfContext(SPTPlayerState *state);+// Seconds of the playing track left, by the player's position and the track's length; -1 when either is+// not known. Spotify's own timer's End of track fades by it too (SpotifySleepTimer.m).+NSTimeInterval SGSleepTimerTrackLeft(SPTPlayerState *state);diff --git a/tweak/Sources/Shared/Player/SleepTimer.m b/tweak/Sources/Shared/Player/SleepTimer.mindex b8918093..1a75075e 100644--- a/tweak/Sources/Shared/Player/SleepTimer.m+++ b/tweak/Sources/Shared/Player/SleepTimer.m@@ -96,8 +96,7 @@ BOOL SGSleepTimerOnLastOfContext(SPTPlayerState *state) {return NO;}-// Seconds of the track left to play, or -1 when its length or the position is not known.-static NSTimeInterval trackLeft(SPTPlayerState *state) {+NSTimeInterval SGSleepTimerTrackLeft(SPTPlayerState *state) {double duration = [state respondsToSelector:@selector(duration)] ? state.duration : 0;NSInteger position = SGKaraokePositionMs();return duration > 0 && position >= 0 ? MAX(0, duration - position / 1000.0) : -1;@@ -122,11 +121,11 @@ static NSTimeInterval secondsLeft(SPTPlayerState *state) {return MAX(0, sg_end.timeIntervalSinceNow);case SGSleepTimerEndOfTrack:// On the next track already, should the length not have been known.- return [track isEqualToString:sg_track] ? trackLeft(state) : 0;+ return [track isEqualToString:sg_track] ? SGSleepTimerTrackLeft(state) : 0;case SGSleepTimerEndOfAlbum: {NSString *context = SGURIString(state.contextURI);if (!(context == sg_context || [context isEqualToString:sg_context]) || isAutoplay(state.track)) return 0;- return SGSleepTimerOnLastOfContext(state) ? trackLeft(state) : -1;+ return SGSleepTimerOnLastOfContext(state) ? SGSleepTimerTrackLeft(state) : -1;}default:return -1;diff --git a/tweak/Sources/Shared/Player/SpotifySleepTimer.m b/tweak/Sources/Shared/Player/SpotifySleepTimer.mnew file mode 100644index 00000000..0275b9fe--- /dev/null+++ b/tweak/Sources/Shared/Player/SpotifySleepTimer.m@@ -0,0 +1,174 @@+// Spotify's own sleep timer, the one set from the player's ⋯ menu (its sheet of times and End of track),+// faded out the way the mod's own is (SleepTimer.h): the same Fade out choice, curve and gain. Spotify's+// player core keeps that timer and pauses at its end; this only reads it off the player's state+// (SPTPlayerState's sleepTimer, Headers/SPTPlayer.h) and never pauses or changes anything of Spotify's.+//+// A check four times a second runs while Spotify plays, or while one of its timers is followed or has just+// gone off; a player state observer starts and stops it. Over the last seconds before the time, or before+// the end of the track, the gain comes down. Once the timer is up (its time came, the track it ended changed,+// Spotify paused or dropped the timer within a couple of seconds of its end) the gain stays down until+// Spotify's pause has landed and comes back a second later, or 5 s on without a pause. A timer cancelled or+// moved later brings the gain back at once. The core may keep a timer that went off in its state for a while,+// so one that went off is not followed again.+//+// It stands aside while the mod's own timer runs, which has the gain then, and while Spotify's own fade is+// forced on (ios-feature-sleeptimer.enable_fade_out, the Labs page's Fade out): with it, Spotify's+// DuckHandlerImpl ducks the core's volume itself (a DuckRequest of a volume and a fade_duration_ms). Off in+// the flag table 9.1.78 ships; a fade that sounds twice as deep means the server turned it on.+//+// Threading: main thread only.+#import "Core/SGFlagForce.h"+#import "Core/SGLog.h"+#import "Headers/SPTPlayer.h"+#import "Shared/Lyrics/Lyrics.h"+#import "Shared/Player/PlayerState.h"+#import "Shared/Player/SleepTimer.h"+#import "Shared/Player/SpeedPitch.h"++static NSString *const kSpotifyFadeFlag = @"ios-feature-sleeptimer.enable_fade_out";+// SPTSleepTimer's types.+static const NSUInteger kAtTime = 1, kEndOfTrack = 2;+static const NSTimeInterval kCheckEvery = 0.25;+// A timer that goes away, or a track that changes, this close to the end means the timer went off.+static const NSTimeInterval kUpWithin = 2;+static const NSTimeInterval kRestoreAfter = 1;+static const NSTimeInterval kPauseWait = 5;++static NSTimer *sg_check;+// The timer followed, as "type|timestamp", and one that went off; nil for none.+static NSString *sg_following, *sg_wentOff;+// For End of track, the track whose end it is.+static NSString *sg_track;+// Seconds to its end at the last check, -1 for not known.+static NSTimeInterval sg_left = -1;+// The gain is below 1 for Spotify's timer.+static BOOL sg_lowered;+// Set once it went off: the gain stays down until Spotify pauses, or until then.+static NSDate *sg_holdUntil;+static BOOL sg_stoodAside;++static void restoreGain(BOOL now) {+ sg_lowered = NO;+ if (SGSleepTimerCurrentMode() != SGSleepTimerOff) return;+ if (now) {+ SGPlayerSetGain(1);+ return;+ }+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kRestoreAfter * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ if (!sg_lowered && !sg_holdUntil && SGSleepTimerCurrentMode() == SGSleepTimerOff) SGPlayerSetGain(1);+ });+}++static void wentOff(NSString *why) {+ SGLog(@"sleep timer: Spotify's up (%@, %.1f s left), gain held until its pause", why, sg_left);+ sg_wentOff = sg_following;+ sg_following = nil;+ sg_left = -1;+ sg_holdUntil = [NSDate dateWithTimeIntervalSinceNow:kPauseWait];+}++// Fades for the timer `key` (of `type`, ending at `at` for a time), or finds it went off.+static void follow(SPTPlayerState *state, NSString *key, NSUInteger type, NSDate *at) {+ NSString *track = SGURIString(state.track.URI);+ if (![key isEqualToString:sg_following]) {+ sg_following = key;+ sg_track = track;+ sg_stoodAside = NO;+ SGLog(@"sleep timer: Spotify's set (type %lu, %@), fade %.0f s", (unsigned long)type,+ type == kAtTime ? [NSString stringWithFormat:@"ends in %.0f s", at.timeIntervalSinceNow] : @"end of track",+ SGSleepTimerFade());+ }+ if ([SGForcedFlagValue(kSpotifyFadeFlag) boolValue]) {+ if (!sg_stoodAside) SGLog(@"sleep timer: Spotify's own Fade out is forced on, its fade is left to it");+ sg_stoodAside = YES;+ if (sg_lowered) restoreGain(YES);+ return;+ }+ if (type == kEndOfTrack && !(track == sg_track || [track isEqualToString:sg_track])) {+ if (sg_left >= 0 && sg_left < kUpWithin) {+ wentOff(@"the track ended");+ return;+ }+ sg_track = track; // skipped to another track, whose end it is now+ }+ NSTimeInterval left = type == kAtTime ? MAX(0, at.timeIntervalSinceNow) : SGSleepTimerTrackLeft(state);+ sg_left = left;+ if (type == kAtTime && left <= 0) {+ wentOff(@"its time came");+ return;+ }+ if (state.isPaused && sg_lowered && left >= 0 && left < kUpWithin) {+ wentOff(@"Spotify paused");+ return;+ }+ NSTimeInterval fade = SGSleepTimerFade();+ double duration = [state respondsToSelector:@selector(duration)] ? state.duration : 0;+ if (type == kEndOfTrack && duration > 0) fade = MIN(fade, duration);+ float gain = left >= 0 ? SGSleepTimerGain(left, fade) : 1;+ if (gain < 1 && !sg_lowered) SGLog(@"sleep timer: Spotify's, fading over %.0f s, %.1f s left", fade, left);+ if (gain < 1 || sg_lowered) SGPlayerSetGain(gain);+ sg_lowered = gain < 1;+}++static void check(void);++// Runs the check while Spotify plays or a timer of its needs it.+static void watch(SPTPlayerState *state) {+ BOOL needed = (state.isPlaying && !state.isPaused) || sg_following || sg_holdUntil || sg_lowered;+ if (needed == (sg_check != nil)) return;+ if (!needed) {+ [sg_check invalidate];+ sg_check = nil;+ return;+ }+ sg_check = [NSTimer timerWithTimeInterval:kCheckEvery repeats:YES block:^(NSTimer *timer) { check(); }];+ [NSRunLoop.mainRunLoop addTimer:sg_check forMode:NSRunLoopCommonModes];+}++static void check(void) {+ SPTPlayerState *state = [(id<SPTPlayer>)SGKaraokePlayer() state];+ if (!state) return; // the player not reached yet: keep checking until it is+ SPTSleepTimer *timer = [state respondsToSelector:@selector(sleepTimer)] ? state.sleepTimer : nil;+ NSUInteger type = [timer respondsToSelector:@selector(type)] ? timer.type : 0;+ NSDate *at = type == kAtTime && [timer respondsToSelector:@selector(timestamp)] ? timer.timestamp : nil;+ if (type != kEndOfTrack && !(type == kAtTime && [at isKindOfClass:NSDate.class])) type = 0;+ NSString *key = type ? [NSString stringWithFormat:@"%lu|%.3f", (unsigned long)type, at.timeIntervalSince1970] : nil;+ if (!key) sg_wentOff = nil;++ if (sg_holdUntil) {+ if (state.isPaused || sg_holdUntil.timeIntervalSinceNow <= 0) {+ SGLog(@"sleep timer: Spotify's %@, gain back in %.0f s", state.isPaused ? @"paused" : @"did not pause", kRestoreAfter);+ sg_holdUntil = nil;+ restoreGain(NO);+ }+ } else if (SGSleepTimerCurrentMode() != SGSleepTimerOff) {+ sg_lowered = NO; // the mod's own timer has the gain+ sg_following = nil;+ } else if (key && ![key isEqualToString:sg_wentOff]) {+ follow(state, key, type, at);+ } else if (sg_following) {+ if (!key && sg_left >= 0 && sg_left < kUpWithin) wentOff(@"timer cleared at its end");+ else {+ SGLog(@"sleep timer: Spotify's cancelled%@", sg_lowered ? @", gain back" : @"");+ sg_following = nil;+ sg_left = -1;+ if (sg_lowered) restoreGain(YES);+ }+ }+ watch(state);+}++@interface SGSpotifySleepTimerWatch : NSObject <SGPlayerStateObserver>+@end++@implementation SGSpotifySleepTimerWatch+- (void)playerStateDidChange:(SPTPlayerState *)state {+ watch(state);+}+@end++__attribute__((constructor)) static void sg_watchSpotifySleepTimer(void) {+ static SGSpotifySleepTimerWatch *watcher; // the observers are held weakly+ watcher = [SGSpotifySleepTimerWatch new];+ SGAddPlayerStateObserver(watcher);+}