Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: the sleep timer fades out by your choice and can stop at album end
My-Name-Is-Jeff32f0f13798c7
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 8aa60a42..ae9663e4 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -193,7 +193,15 @@ Shared:sheet as the system menu (Redesigned/ContextMenu), whose own items stand in for the block, so theblock stays out of it unless the sheet itself is shown (SGPlayerMenuReplaced). Switch to video,the chip over the title of a song with a music video, is hidden under either look on request- (VideoSwitch.x, spotifyglass.hide.videoSwitch), by its identifier in FloatingElementsUnit+ (VideoSwitch.x, spotifyglass.hide.videoSwitch), by its identifier in FloatingElementsUnit.+ The sleep timer (SleepTimer.m, set from the Live Activity) pauses Spotify at a time, at the end of+ the track or at the end of the album or playlist, the last track of it found by the tracks to come+ that are neither queued by hand nor autoplay's (SPTPlayerTrack's provider), or by the next one+ 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 track+ when 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/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). The buffers are in the unit's output format, the@@ -263,7 +271,8 @@ Shared:LiveActivity/ a Live Activity on the lock screen and in the Dynamic Island in one of three views, the line beingsung with the next one under it, the tracks up next (a tap on one skipping ahead to it), or a controlmenu of tabs, Controls (previous, play and pause, next, shuffle, repeat), Queue and a sleep Timer of- the mod's own that pauses Spotify (LiveActivity.h lists its files): a timer polls the player and+ the mod's own (Player/SleepTimer.m: 15 min, 30 min, 1 hour, End of track, End of album) that fades+ the sound out and pauses Spotify, and stays set when the card is switched off (LiveActivity.h lists its files): a timer polls the player andsends a new state only when what the view shows changes, local updates only, no push. The cardis tinted with the cover's colour and shows the cover itself, a JPEG of a few dozen pixels insidethe state, which ActivityKit caps at 4 KB (the bridge sends it without the cover when it woulddiff --git a/extension/LiveActivity/LiveActivityWidget.swift b/extension/LiveActivity/LiveActivityWidget.swiftindex 27572644..5cf17c23 100644--- a/extension/LiveActivity/LiveActivityWidget.swift+++ b/extension/LiveActivity/LiveActivityWidget.swift@@ -451,6 +451,8 @@ private struct Summary: View {Text("Music stops in \(Text(timerInterval: Date()...end, countsDown: true))")} else if state.timerEndOfTrack {Text("Music stops at the end of this track")+ } else if state.timerEndOfAlbum == true {+ Text("Music stops at the end of this album")} else {Text("No sleep timer")}@@ -626,7 +628,7 @@ private struct TimerPage: View {var body: some View {Group {- if (state.timerEnd.map { $0 > Date() } ?? false) || state.timerEndOfTrack {+ if (state.timerEnd.map { $0 > Date() } ?? false) || state.timerEndOfTrack || state.timerEndOfAlbum == true {HStack(alignment: .center, spacing: 12) {VStack(alignment: .leading, spacing: 0) {Text("Music stops")@@ -637,7 +639,7 @@ private struct TimerPage: View {.font(.system(size: 34, weight: .bold).monospacedDigit()).foregroundStyle(green)} else {- Text("End of track")+ Text(state.timerEndOfAlbum == true ? "End of album" : "End of track").font(.title2.weight(.bold)).foregroundStyle(green)}@@ -657,6 +659,7 @@ private struct TimerPage: View {ChipButton(action: "timer:30", symbol: "moon", label: "30 min")ChipButton(action: "timer:60", symbol: "moon", label: "1 hour")ChipButton(action: "timer:track", symbol: "music.note", label: "End of track")+ ChipButton(action: "timer:album", symbol: "square.stack", label: "End of album")}}}diff --git a/harness/sleep-timer/README.md b/harness/sleep-timer/README.mdnew file mode 100644index 00000000..088bf229--- /dev/null+++ b/harness/sleep-timer/README.md@@ -0,0 +1,18 @@+# Sleep timer harness++`SleepTimer.m` (Shared/Player) as the tweak compiles it, on the Mac, over a player stood in for (`stub/` stands+in for the three UIKit headers it imports, `main.m` answers their calls). It checks the fade's curve (1 until+the last minute, 30 dB down halfway, 60 dB at the end, falling every second), which track ends the album+(tracks queued by hand and autoplay's, by provider or by the is_queued and autoplay.is_autoplay keys, don't+count; repeating, the next track having played already does), and the timer in real time: a 2 s timer starts+faded, pauses at its end and gives the gain back a second later; 15 minutes more and Cancel bring the gain+back at once; End of track pauses half a second before the end, or at once on the next track; End of album+plays past a track with more of the album to come, fades and pauses on the last one, and pauses at once when+autoplay or another album or playlist is playing; a timer up while paused sends no pause. The Fade out choice (`SGInt`,+answered by `main.m`): each length's curve, Off at full volume all the way, none picked and one out of range+read as 30 s; a change applies to a timer already running; at the end of the track or the album the fade+spans a track shorter than it, from its start; a time fades over the last seconds before its end.++ ./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/.diff --git a/harness/sleep-timer/build.sh b/harness/sleep-timer/build.shnew file mode 100755index 00000000..3c93c579--- /dev/null+++ b/harness/sleep-timer/build.sh@@ -0,0 +1,9 @@+#!/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.+set -e+cd "$(dirname "$0")"+mkdir -p build+xcrun 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+echo "built build/sleep-timer"diff --git a/harness/sleep-timer/main.m b/harness/sleep-timer/main.mnew file mode 100644index 00000000..3701ba05--- /dev/null+++ b/harness/sleep-timer/main.m@@ -0,0 +1,282 @@+// SleepTimer.m on the Mac, over a player stood in for: the fade's curve and its length (the Fade out choice,+// per mode), which track ends the album, and the timer itself in real time (a 2 s timer fades, pauses and+// gives the gain back a second later). Fails+// with the checks that did not hold.+//+// ./build.sh && build/sleep-timer+#import <Foundation/Foundation.h>+#import "Headers/SPTPlayer.h"+#import "Shared/Player/SleepTimer.h"+#import "Core/SGPrefs.h"++@interface SPTPlayerTrack ()+@property (nonatomic, readwrite) id URI;+@property (nonatomic, readwrite, copy) NSString *provider;+@property (nonatomic, readwrite) NSDictionary<NSString *, NSString *> *metadata;+@property (nonatomic, readwrite) NSString *trackTitle;+@end+@implementation SPTPlayerTrack+@end++@interface SPTPlayerOptions ()+@property (nonatomic, readwrite) BOOL repeatingContext;+@end+@implementation SPTPlayerOptions+@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) double duration;+@property (nonatomic, readwrite) NSArray *future;+@property (nonatomic, readwrite) NSArray *reverse;+@end+@implementation SPTPlayerState+@end++// The player: its state, and the pauses asked of it.+@interface MockPlayer : NSObject+@property (nonatomic) SPTPlayerState *state;+@property (nonatomic) NSInteger pauses;+@end+@implementation MockPlayer+- (id)pause:(id)options {+ self.pauses++;+ self.state.isPaused = YES;+ return nil;+}+@end++static MockPlayer *sg_player;+static NSInteger sg_positionMs = -1;+static float sg_gain = 1;+// The Fade out choice as stored, nil for none picked.+static NSNumber *sg_fadeChoice;++NSInteger SGInt(NSString *key, NSInteger fallback) {+ return [key isEqualToString:SGKeySleepTimerFade] && sg_fadeChoice ? sg_fadeChoice.integerValue : fallback;+}+// The curve over a one minute fade, the one the timer checks below run with.+static float SGSleepTimerGainAt(NSTimeInterval left) {+ return SGSleepTimerGain(left, 60);+}++NSInteger SGKaraokePositionMs(void) { return sg_positionMs; }+id SGKaraokePlayer(void) { return sg_player; }+void SGPlayerSetGain(float gain) { sg_gain = gain; }+NSString *SGURIString(id uri) {+ if ([uri isKindOfClass:NSString.class]) return uri;+ if ([uri isKindOfClass:NSURL.class]) return ((NSURL *)uri).absoluteString;+ return nil;+}++static int sg_failures;+#define CHECK(condition, what) do { \+ BOOL held = (condition); \+ if (!held) sg_failures++; \+ printf("%s %s\n", held ? "ok " : "FAIL", what); \+} while (0)++static SPTPlayerTrack *track(NSString *name, NSString *provider, NSDictionary *metadata) {+ SPTPlayerTrack *track = [SPTPlayerTrack new];+ track.URI = [NSURL URLWithString:[@"spotify:track:" stringByAppendingString:name]];+ track.trackTitle = name;+ track.provider = provider;+ track.metadata = metadata ?: @{};+ return track;+}++static SPTPlayerState *state(SPTPlayerTrack *playing, NSArray *future, NSArray *reverse, BOOL repeating) {+ SPTPlayerState *state = [SPTPlayerState new];+ state.track = playing;+ state.contextURI = @"spotify:album:one";+ state.options = [SPTPlayerOptions new];+ state.options.repeatingContext = repeating;+ state.duration = 100;+ state.future = future;+ state.reverse = reverse;+ return state;+}++static void runFor(NSTimeInterval seconds) {+ [NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:seconds]];+}++static BOOL near(float a, float b) {+ return fabsf(a - b) < 0.0005f;+}++int main(void) {+ @autoreleasepool {+ // The fade.+ CHECK(SGSleepTimerGainAt(120) == 1 && SGSleepTimerGainAt(60) == 1, "gain is 1 until the last minute");+ CHECK(near(SGSleepTimerGainAt(30), 0.0316f), "halfway through the minute it is 30 dB down");+ CHECK(near(SGSleepTimerGainAt(0), 0.001f) && near(SGSleepTimerGainAt(-3), 0.001f), "at the end it is 60 dB down");+ BOOL falls = YES;+ for (int left = 59; left > 0; left--) falls = falls && SGSleepTimerGainAt(left) < SGSleepTimerGainAt(left + 1);+ CHECK(falls, "it falls every second of the minute");+ BOOL ends = YES;+ for (NSNumber *fade in @[@10, @30, @60, @120]) {+ NSTimeInterval f = fade.doubleValue;+ ends = ends && SGSleepTimerGain(f, f) == 1 && SGSleepTimerGain(f + 5, f) == 1 && near(SGSleepTimerGain(0, f), 0.001f)+ && near(SGSleepTimerGain(f / 2, f), 0.0316f);+ }+ CHECK(ends, "each fade length: 1 at its start, 30 dB down halfway, 60 dB at the end");+ CHECK(SGSleepTimerGain(0, 0) == 1 && SGSleepTimerGain(5, 0) == 1, "fade Off: 1 all the way");++ // The choice.+ CHECK(SGSleepTimerFadeChoice() == 2 && SGSleepTimerFade() == 30, "none picked: 30 s");+ NSArray *lengths = @[@0, @10, @30, @60, @120];+ BOOL picks = SGSleepTimerFadeNames().count == lengths.count;+ for (NSInteger i = 0; i < (NSInteger)lengths.count; i++) {+ sg_fadeChoice = @(i);+ picks = picks && SGSleepTimerFade() == [lengths[i] doubleValue];+ }+ CHECK(picks, "Off, 10 s, 30 s, 1 minute, 2 minutes read as 0, 10, 30, 60, 120 s");+ sg_fadeChoice = @9;+ CHECK(SGSleepTimerFade() == 30, "a choice out of range: 30 s");+ sg_fadeChoice = @3;++ // Which track ends the album.+ SPTPlayerTrack *a = track(@"a", @"context", nil), *b = track(@"b", @"context", nil), *c = track(@"c", @"context", nil);+ SPTPlayerTrack *queued = track(@"q", @"queue", nil), *queuedByKey = track(@"k", nil, @{@"is_queued": @"true"});+ SPTPlayerTrack *autoplay = track(@"r", @"autoplay", nil), *autoplayByKey = track(@"s", nil, @{@"autoplay.is_autoplay": @"true"});+ SPTPlayerTrack *unknown = track(@"u", nil, nil);+ CHECK(!SGSleepTimerOnLastOfContext(state(b, @[c], @[a], NO)), "a track of the album to come: not the last");+ CHECK(SGSleepTimerOnLastOfContext(state(c, @[], @[a, b], NO)), "nothing to come: the last");+ CHECK(SGSleepTimerOnLastOfContext(state(c, @[queued, queuedByKey], @[a, b], NO)), "only tracks queued by hand to come: the last");+ CHECK(SGSleepTimerOnLastOfContext(state(c, @[autoplay, autoplayByKey], @[a, b], NO)), "only autoplay's to come: the last");+ CHECK(!SGSleepTimerOnLastOfContext(state(b, @[queued, c, autoplay], @[a], NO)), "a queued track, then the album's: not the last");+ CHECK(!SGSleepTimerOnLastOfContext(state(b, @[unknown], @[a], NO)), "a track that names no provider counts as the album's");+ CHECK(SGSleepTimerOnLastOfContext(state(c, @[a, b], @[b, a], YES)), "repeating, the album starting over: the last");+ CHECK(SGSleepTimerOnLastOfContext(state(a, @[a], @[], YES)), "repeating a one track album: the last");+ CHECK(!SGSleepTimerOnLastOfContext(state(b, @[c, a], @[a], YES)), "repeating, mid album: not the last");+ CHECK(!SGSleepTimerOnLastOfContext(state(c, @[a, b], @[b, a], NO)), "not repeating, a track played before to come: not the last");+ CHECK(!SGSleepTimerOnLastOfContext(state(b, @[@"not a track", c], @[a], NO)), "what is not a track is skipped");++ // The timer, in real time.+ sg_player = [MockPlayer new];+ sg_player.state = state(a, @[b, c], @[], NO);+ sg_positionMs = 10000;+ SGSetSleepTimer(SGSleepTimerAtTime, 2);+ CHECK(SGSleepTimerCurrentMode() == SGSleepTimerAtTime && SGSleepTimerEnd() != nil, "a 2 s timer is set");+ CHECK(sg_gain < SGSleepTimerGainAt(2.1) && sg_gain > SGSleepTimerGainAt(1.9), "a timer inside the last minute starts faded");+ runFor(1);+ CHECK(sg_player.pauses == 0 && sg_gain < 0.002f, "a second on, still playing, quieter");+ runFor(1.4);+ CHECK(sg_player.pauses == 1 && SGSleepTimerCurrentMode() == SGSleepTimerOff && !SGSleepTimerEnd(), "at its end it paused and is off");+ CHECK(sg_gain < 0.002f, "the gain stays down while the pause lands");+ runFor(1.2);+ CHECK(sg_gain == 1, "a second after the pause the gain is back");++ sg_player.state = state(a, @[b, c], @[], NO);+ SGSetSleepTimer(SGSleepTimerAtTime, 30);+ CHECK(near(sg_gain, SGSleepTimerGainAt(30)), "30 s to go: 30 dB down");+ SGSleepTimerAdd(15 * 60);+ CHECK(fabs(SGSleepTimerEnd().timeIntervalSinceNow - 930) < 1 && sg_gain == 1, "15 minutes more: the end moves on and the gain is back");+ SGSetSleepTimer(SGSleepTimerOff, 0);+ CHECK(SGSleepTimerCurrentMode() == SGSleepTimerOff && sg_gain == 1, "cancelled");+ SGSleepTimerAdd(15 * 60);+ CHECK(fabs(SGSleepTimerEnd().timeIntervalSinceNow - 900) < 1, "15 minutes more with none set: 15 minutes from now");+ SGSetSleepTimer(SGSleepTimerOff, 0);++ // The end of the track.+ sg_positionMs = 70000;+ SGSetSleepTimer(SGSleepTimerEndOfTrack, 0);+ CHECK(!SGSleepTimerEnd() && near(sg_gain, SGSleepTimerGainAt(30)), "end of track, 30 s left: 30 dB down");+ sg_positionMs = 99700;+ runFor(0.4);+ CHECK(sg_player.pauses == 2 && SGSleepTimerCurrentMode() == SGSleepTimerOff, "end of track: paused just before the end");+ sg_player.state = state(a, @[b, c], @[], NO);+ sg_positionMs = 5000;+ SGSetSleepTimer(SGSleepTimerEndOfTrack, 0);+ CHECK(sg_gain == 1, "end of track, more than a minute left: full volume");+ sg_player.state = state(b, @[c], @[a], NO);+ runFor(0.4);+ CHECK(sg_player.pauses == 3, "end of track, the next track already on: paused at once");+ sg_player.state = state(a, @[b, c], @[], NO);+ sg_player.state.isPaused = YES;+ sg_positionMs = 99900;+ SGSetSleepTimer(SGSleepTimerEndOfTrack, 0);+ CHECK(sg_player.pauses == 3 && SGSleepTimerCurrentMode() == SGSleepTimerOff, "up while paused: no pause sent, and off");+ runFor(1.2);++ // The end of the album.+ sg_player.state = state(b, @[c, autoplay], @[a], NO);+ sg_positionMs = 99800;+ SGSetSleepTimer(SGSleepTimerEndOfAlbum, 0);+ CHECK(SGSleepTimerCurrentMode() == SGSleepTimerEndOfAlbum && sg_gain == 1 && sg_player.pauses == 3,+ "end of album, a track still to come: plays on at full volume past this track's end");+ sg_player.state = state(c, @[autoplay], @[a, b], NO);+ sg_positionMs = 70000;+ runFor(0.4);+ CHECK(sg_player.pauses == 3 && near(sg_gain, SGSleepTimerGainAt(30)), "on the last track, 30 s left: 30 dB down");+ sg_positionMs = 99700;+ runFor(0.4);+ CHECK(sg_player.pauses == 4 && SGSleepTimerCurrentMode() == SGSleepTimerOff, "end of album: paused just before the last track's end");+ sg_player.state = state(a, @[b, c], @[], NO);+ sg_positionMs = 1000;+ SGSetSleepTimer(SGSleepTimerEndOfAlbum, 0);+ sg_player.state = state(autoplay, @[autoplayByKey], @[a, b, c], NO);+ runFor(0.4);+ CHECK(sg_player.pauses == 5, "end of album, autoplay playing already: paused at once");+ sg_player.state = state(a, @[b, c], @[], NO);+ SGSetSleepTimer(SGSleepTimerEndOfAlbum, 0);+ sg_player.state = state(b, @[c], @[a], NO);+ sg_player.state.contextURI = @"spotify:playlist:other";+ runFor(0.4);+ CHECK(sg_player.pauses == 6, "end of album, another album or playlist on: paused at once");+ runFor(1.2);+ CHECK(sg_gain == 1, "and the gain is back after");++ // The fade's length, per mode.+ sg_fadeChoice = @1; // 10 s+ sg_player.state = state(a, @[b, c], @[], NO);+ sg_positionMs = 80000;+ SGSetSleepTimer(SGSleepTimerEndOfTrack, 0);+ CHECK(sg_gain == 1, "end of track, 10 s fade, 20 s left: full volume");+ sg_positionMs = 95000;+ runFor(0.4);+ CHECK(near(sg_gain, SGSleepTimerGain(5, 10)), "end of track, 10 s fade, 5 s left: 30 dB down");+ sg_fadeChoice = @4; // 2 minutes, picked while it runs+ runFor(0.4);+ CHECK(near(sg_gain, SGSleepTimerGain(5, 100)), "2 minutes picked while it runs, on a 100 s track: the fade spans the track");+ sg_fadeChoice = @0; // Off+ runFor(0.4);+ CHECK(sg_gain == 1, "Off picked while it runs: full volume");+ sg_positionMs = 99700;+ runFor(0.4);+ CHECK(sg_player.pauses == 7 && sg_gain == 1, "fade Off: paused at the end at full volume");+ runFor(1.2);++ sg_fadeChoice = @3; // 1 minute+ sg_player.state = state(a, @[b, c], @[], NO);+ sg_player.state.duration = 20;+ sg_positionMs = 0;+ SGSetSleepTimer(SGSleepTimerEndOfTrack, 0);+ CHECK(sg_gain == 1, "end of track, a 20 s track and a 1 minute fade: full volume at its start");+ sg_positionMs = 10000;+ runFor(0.4);+ CHECK(near(sg_gain, SGSleepTimerGain(10, 20)) && near(sg_gain, 0.0316f), "halfway through it: 30 dB down, the fade spanning the track");+ SGSetSleepTimer(SGSleepTimerOff, 0);++ sg_player.state = state(c, @[], @[a, b], NO);+ sg_player.state.duration = 20;+ sg_positionMs = 10000;+ SGSetSleepTimer(SGSleepTimerEndOfAlbum, 0);+ CHECK(near(sg_gain, 0.0316f), "end of album, its last track 20 s long, halfway: 30 dB down");+ SGSetSleepTimer(SGSleepTimerOff, 0);++ sg_fadeChoice = @2; // 30 s+ SGSetSleepTimer(SGSleepTimerAtTime, 45);+ CHECK(sg_gain == 1, "a time, 30 s fade, 45 s to go: full volume");+ SGSetSleepTimer(SGSleepTimerAtTime, 15);+ 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");+ }+ printf("%s\n", sg_failures ? "FAILED" : "all held");+ return sg_failures ? 1 : 0;+}diff --git a/harness/sleep-timer/stub/Shared/Lyrics/Lyrics.h b/harness/sleep-timer/stub/Shared/Lyrics/Lyrics.hnew file mode 100644index 00000000..8f4b90d3--- /dev/null+++ b/harness/sleep-timer/stub/Shared/Lyrics/Lyrics.h@@ -0,0 +1,4 @@+// The two calls SleepTimer.m makes of Shared/Lyrics, without UIKit; main.m answers them.+#import <Foundation/Foundation.h>+NSInteger SGKaraokePositionMs(void);+id SGKaraokePlayer(void);diff --git a/harness/sleep-timer/stub/Shared/Player/PlayerState.h b/harness/sleep-timer/stub/Shared/Player/PlayerState.hnew file mode 100644index 00000000..d1101ea6--- /dev/null+++ b/harness/sleep-timer/stub/Shared/Player/PlayerState.h@@ -0,0 +1,3 @@+// The call SleepTimer.m makes of PlayerState.h, without UIKit; main.m answers it.+#import <Foundation/Foundation.h>+NSString *SGURIString(id uri);diff --git a/harness/sleep-timer/stub/Shared/Player/SpeedPitch.h b/harness/sleep-timer/stub/Shared/Player/SpeedPitch.hnew file mode 100644index 00000000..c6d08dae--- /dev/null+++ b/harness/sleep-timer/stub/Shared/Player/SpeedPitch.h@@ -0,0 +1,3 @@+// The call SleepTimer.m makes of SpeedPitch.h, without UIKit; main.m answers it.+#import <Foundation/Foundation.h>+void SGPlayerSetGain(float gain);diff --git a/tweak/Sources/Headers/SPTPlayer.h b/tweak/Sources/Headers/SPTPlayer.hindex 3a3d12f7..5440080e 100644--- a/tweak/Sources/Headers/SPTPlayer.h+++ b/tweak/Sources/Headers/SPTPlayer.h@@ -9,6 +9,9 @@@property (nonatomic, readonly) NSString *trackTitle;// Every credited artist: artist_uri and artist_name, then artist_uri:1, artist_name:1 and on.@property (nonatomic, readonly) NSDictionary<NSString *, NSString *> *metadata;+// Where the track came from in the tracks to come: the album or playlist, a hand queue, autoplay+// (Shared/Player/SleepTimer.m reads it).+@property (nonatomic, readonly, copy) NSString *provider;@end@interface SPTPlayerOptions : NSObjectdiff --git a/tweak/Sources/Shared/LiveActivity/LiveActivity.h b/tweak/Sources/Shared/LiveActivity/LiveActivity.hindex b75506a0..64cb56a7 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivity.h+++ b/tweak/Sources/Shared/LiveActivity/LiveActivity.h@@ -1,7 +1,9 @@// The Live Activity (Mod Settings > Live Activity), on the lock screen and in the Dynamic// Island (iOS 17+), under either look: it draws on no Spotify screen of its own. In one of three views: the line being sung with the next one under it, the tracks// up next (a tap on one skipping ahead to it), or the control menu, tabs of Controls (previous, play and-// pause, next, shuffle, repeat), Queue and a sleep Timer of the mod's own that pauses Spotify.+// pause, next, shuffle, repeat), Queue and a sleep Timer of the mod's own (Shared/Player/SleepTimer.h)+// that fades the sound out (over the page's Fade out choice) and pauses Spotify, at a time or at the end of+// the track, album or playlist.//// LiveActivity.x polls the player, sends the activity a new state when what it shows changes// LiveActivityBridge.swift ActivityKit, which is Swift onlydiff --git a/tweak/Sources/Shared/LiveActivity/LiveActivity.x b/tweak/Sources/Shared/LiveActivity/LiveActivity.xindex a11f2692..88d81f3c 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivity.x+++ b/tweak/Sources/Shared/LiveActivity/LiveActivity.x@@ -1,13 +1,15 @@// Polls the player and sends the activity a new state only when what its view shows changes: the// lyrics' line, what is up next, the control menu's tab, track, shuffle, repeat or sleep timer, or a// pause. The view is read on every tick, so picking another one shows within a tick. Spotify keeps-// playing in the background, so the timer keeps running there too, and with it the sleep timer.+// playing in the background, so the timer keeps running there too. The sleep timer is+// Shared/Player/SleepTimer's, which keeps its own time; the card only sets it and shows it.// The activity is started only while the app is in front, the one place ActivityKit allows it.#import <UIKit/UIKit.h>#import <objc/runtime.h>#import <MediaPlayer/MediaPlayer.h>#import "Core/SGCore.h"#import "Shared/Player/PlayerState.h"+#import "Shared/Player/SleepTimer.h"#import "Headers/SPTPlayer.h"#import "Shared/Lyrics/Lyrics.h"#import "LiveActivity.h"@@ -18,7 +20,7 @@ API_AVAILABLE(ios(17.0))+ (void)showWithView:(NSInteger)view paused:(BOOL)paused line:(NSString *)line nextLine:(NSString *)nextLinetitles:(NSArray<NSString *> *)titles artists:(NSArray<NSString *> *)artists uris:(NSArray<NSString *> *)uristab:(NSInteger)tab title:(NSString *)title artist:(NSString *)artist shuffle:(BOOL)shuffle repeatMode:(NSInteger)repeatMode- timerEnd:(NSDate *)timerEnd timerEndOfTrack:(BOOL)timerEndOfTrack+ timerEnd:(NSDate *)timerEnd timerEndOfTrack:(BOOL)timerEndOfTrack timerEndOfAlbum:(BOOL)timerEndOfAlbumtint:(NSString *)tint trackStart:(NSDate *)trackStart trackEnd:(NSDate *)trackEnd pausedAt:(NSNumber *)pausedAttranslation:(NSString *)translation cover:(NSData *)cover textSize:(NSInteger)textSize;+ (void)end;@@ -33,7 +35,7 @@ typedef NS_ENUM(NSInteger, SGLiveActivityTab) {};static const NSTimeInterval kTick = 0.25;-// Paused, the only thing on the card that still moves is the sleep timer, and a slower tick catches+// Paused, the only thing on the card that still moves is the sleep timer, and a slower tick shows// its end well within the second the card shows. Four ticks a second for a still card is a wake up// eighty times a minute for a picture that does not change.static const NSTimeInterval kPausedTick = 1;@@ -48,8 +50,6 @@ static const NSTimeInterval kRefresh = 20;// control menu's queue tab three.static const NSUInteger kUpNextQueue = 4;static const NSUInteger kUpNextPanel = 3;-// The end of track timer pauses this close to the end, so the next track never starts.-static const NSInteger kEndOfTrackMs = 500;// The cover goes to the card in the state itself, which ActivityKit caps at 4 KB with everything else in// it and encodes as JSON, the cover in base64: this many bytes of JPEG come to about 1.9 KB of it.static const NSUInteger kCoverBytes = 1400;@@ -69,9 +69,6 @@ static NSString *sg_missingLyrics;static NSDate *sg_lastStart;static NSDate *sg_lastSent;static SGLiveActivityTab sg_tab;-// The sleep timer: an end, or the end of the track it was set on.-static NSDate *sg_sleepEnd;-static NSString *sg_sleepTrack;static void tick(void) API_AVAILABLE(ios(17.0));@@ -217,36 +214,12 @@ static void readArtwork(SPTPlayerState *state, NSString *trackID) {if (logged++ < 6) SGLog(@"live activity: cover of %@, %lu bytes", trackID, (unsigned long)sg_cover.length);}-static void clearSleepTimer(void) {- sg_sleepEnd = nil;- sg_sleepTrack = nil;-}--// Pauses once the sleep timer is up: at its end, or just before the end of the track it was set on-// (on the next track, should the length not be known).-static void checkSleepTimer(id<SPTPlayer> player, SPTPlayerState *state, NSString *trackID) {- BOOL up = NO;- if (sg_sleepEnd) {- up = sg_sleepEnd.timeIntervalSinceNow <= 0;- } else if (sg_sleepTrack) {- double duration = [state respondsToSelector:@selector(duration)] ? state.duration : 0;- NSInteger position = SGKaraokePositionMs();- up = ![trackID isEqualToString:sg_sleepTrack]- || (duration > 0 && position >= 0 && duration * 1000 - position < kEndOfTrackMs);- }- if (!up) return;- clearSleepTimer();- if (!state.isPaused) [player pause:nil];- SGLog(@"live activity: sleep timer up, paused");-}-static void tick(void) API_AVAILABLE(ios(17.0)) {id<SPTPlayer> player = SGKaraokePlayer();SPTPlayerState *state = player.state;SPTPlayerTrack *track = state.track;if (!track.trackTitle.length) return;NSString *trackID = SGKaraokePlayingTrack();- checkSleepTimer(player, state, trackID);NSInteger view = SGInt(SGKeyLiveActivityView, SGLiveActivityLyrics);BOOL paused = state.isPaused;@@ -294,19 +267,20 @@ static void tick(void) API_AVAILABLE(ios(17.0)) {BOOL shuffle = panel && state.options.shufflingContext;NSInteger repeatMode = panel ? repeatModeOf(state.options) : 0;NSInteger tab = panel ? sg_tab : 0;- NSDate *sleepEnd = sg_sleepEnd;- BOOL endOfTrack = sg_sleepTrack != nil;+ SGSleepTimerMode sleepMode = SGSleepTimerCurrentMode();+ NSDate *sleepEnd = SGSleepTimerEnd();NSMutableArray<NSString *> *parts = [NSMutableArray arrayWithObjects:@(view).stringValue, paused ? @"1" : @"0", line, next,@(tab).stringValue, title, artist, shuffle ? @"1" : @"0", @(repeatMode).stringValue,- @((long long)sleepEnd.timeIntervalSince1970).stringValue, endOfTrack ? @"1" : @"0", tint ?: @"", translation ?: @"",+ @((long long)sleepEnd.timeIntervalSince1970).stringValue, @(sleepMode).stringValue, tint ?: @"", translation ?: @"",paused ? @"" : @((long long)trackStart.timeIntervalSince1970).stringValue, paused ? @(round(pausedAt.doubleValue * 100)).stringValue : @"",cover ? sg_artTrack : @"", @(textSize).stringValue, nil];for (NSUInteger i = 0; i < titles.count; i++) [parts addObject:[NSString stringWithFormat:@"%@\t%@\t%@", titles[i], artists[i], uris[i]]];send([parts componentsJoinedByString:@"\n"], ^{[SGLiveActivityBridge showWithView:view paused:paused line:line nextLine:next titles:titles artists:artists uris:uristab:tab title:title artist:artist shuffle:shuffle repeatMode:repeatMode- timerEnd:sleepEnd timerEndOfTrack:endOfTrack+ timerEnd:sleepEnd timerEndOfTrack:sleepMode == SGSleepTimerEndOfTrack+ timerEndOfAlbum:sleepMode == SGSleepTimerEndOfAlbumtint:tint trackStart:trackStart trackEnd:trackEnd pausedAt:pausedAt translation:translationcover:cover textSize:textSize];});@@ -355,18 +329,11 @@ static void runAction(NSString *action) {result = [player setRepeatingContext:NO];}} else if ([name isEqualToString:@"timer"]) {- if ([value isEqualToString:@"cancel"]) {- clearSleepTimer();- } else if ([value isEqualToString:@"track"]) {- clearSleepTimer();- sg_sleepTrack = SGKaraokePlayingTrack();- } else if ([value isEqualToString:@"add"]) {- NSDate *from = sg_sleepEnd && sg_sleepEnd.timeIntervalSinceNow > 0 ? sg_sleepEnd : [NSDate date];- sg_sleepEnd = [from dateByAddingTimeInterval:15 * 60];- } else if (value.integerValue > 0) {- clearSleepTimer();- sg_sleepEnd = [NSDate dateWithTimeIntervalSinceNow:value.integerValue * 60];- }+ if ([value isEqualToString:@"cancel"]) SGSetSleepTimer(SGSleepTimerOff, 0);+ else if ([value isEqualToString:@"track"]) SGSetSleepTimer(SGSleepTimerEndOfTrack, 0);+ else if ([value isEqualToString:@"album"]) SGSetSleepTimer(SGSleepTimerEndOfAlbum, 0);+ else if ([value isEqualToString:@"add"]) SGSleepTimerAdd(15 * 60);+ else if (value.integerValue > 0) SGSetSleepTimer(SGSleepTimerAtTime, value.integerValue * 60);} else {SGLog(@"live activity: unknown action %@", action);return;@@ -380,7 +347,8 @@ void SGSetLiveActivityEnabled(BOOL on) {sg_timer = nil;sg_shown = nil;sg_lastStart = nil;- clearSleepTimer();+ // A sleep timer runs on its own clock (SleepTimer.m) and stays set: the shortcut and the control set it+ // with the card off, and a card switched back on shows it from its first tick.if (!on) {[SGLiveActivityBridge end];SGLog(@"live activity: off");diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift b/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swiftindex b0b49374..2ceea468 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift+++ b/tweak/Sources/Shared/LiveActivity/LiveActivityBridge.swift@@ -91,7 +91,7 @@ public final class SGLiveActivityBridge: NSObject {@objc public static func show(view: Int, paused: Bool, line: String, nextLine: String,titles: [String], artists: [String], uris: [String],tab: Int, title: String, artist: String, shuffle: Bool, repeatMode: Int,- timerEnd: Date?, timerEndOfTrack: Bool,+ timerEnd: Date?, timerEndOfTrack: Bool, timerEndOfAlbum: Bool,tint: String?, trackStart: Date?, trackEnd: Date?, pausedAt: NSNumber?, translation: String?,cover: Data?, textSize: Int) {let tracks = titles.indices.map {@@ -103,7 +103,7 @@ public final class SGLiveActivityBridge: NSObject {tab: SGLyricsAttributes.Tab(rawValue: tab) ?? .controls, title: title, artist: artist,shuffle: shuffle, repeatMode: repeatMode, timerEnd: timerEnd, timerEndOfTrack: timerEndOfTrack,tint: tint, trackStart: trackStart, trackEnd: trackEnd, pausedAt: pausedAt?.doubleValue,- translation: translation, cover: cover, textSize: textSize)+ translation: translation, cover: cover, textSize: textSize, timerEndOfAlbum: timerEndOfAlbum)// ActivityKit drops a state over 4 KB without a word and the card freezes, so with long lines and// a busy cover the cover gives way.if cover != nil, let size = try? JSONEncoder().encode(state).count, size > maxStateBytes {diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m b/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.mindex ac46e26c..13a96ffd 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m+++ b/tweak/Sources/Shared/LiveActivity/LiveActivitySettings.m@@ -1,6 +1,7 @@// The Live Activity page (App/ModSettings.x links it from the root, under either look).#import "Core/SGCore.h"#import "Settings/SGModPage.h"+#import "Shared/Player/SleepTimer.h"#import "LiveActivity.h"static NSArray<NSString *> *viewNames(void) {@@ -15,8 +16,14 @@ 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.+ 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."),] footer:nil];}diff --git a/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift b/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swiftindex ba5bad29..0addb93e 100644--- a/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift+++ b/tweak/Sources/Shared/LiveActivity/LiveActivityShared.swift@@ -53,6 +53,8 @@ struct SGLyricsAttributes: ActivityAttributes {var cover: Data?// The lyrics' size, SGLiveActivityTextSize's values: 0 small, 1 medium, 2 large.var textSize: Int?+ // The sleep timer pauses at the end of the album or playlist playing.+ var timerEndOfAlbum: Bool?}}@@ -89,7 +91,7 @@ struct SGPlayQueuedTrackIntent: LiveActivityIntent {}}-// A control menu action: tab:N, toggle, previous, next, shuffle, repeat, timer:15|30|60|track|add|cancel.+// A control menu action: tab:N, toggle, previous, next, shuffle, repeat, timer:15|30|60|track|album|add|cancel.@available(iOS 17.0, *)struct SGLiveActivityActionIntent: LiveActivityIntent {static let title: LocalizedStringResource = "Control menu action"diff --git a/tweak/Sources/Shared/Player/SleepTimer.h b/tweak/Sources/Shared/Player/SleepTimer.hnew file mode 100644index 00000000..25973f20--- /dev/null+++ b/tweak/Sources/Shared/Player/SleepTimer.h@@ -0,0 +1,53 @@+// The sleep timer, the mod's own, under either look: it pauses Spotify at a time, at the end of the track+// playing, or at the end of the album or playlist playing, and over the last seconds before that (the Fade+// out choice, 30 s unless picked) it fades the sound out through the mod's own gain (SGPlayerSetGain), not+// the system volume. A second after the pause the gain is back to normal, so the next play is at full+// volume. The Live Activity's Timer tab, the Sleep Timer shortcut and its Control Center control set it+// (Shared/LiveActivity), and the card reads it back.+//+// It lasts until it is up or cancelled, or Spotify quits; nothing is stored but the fade's length. While one+// is set a timer checks it four times a second, on the main thread, playing or paused.+//+// Threading: main thread only.+#import <Foundation/Foundation.h>++@class SPTPlayerState;++typedef NS_ENUM(NSInteger, SGSleepTimerMode) {+ SGSleepTimerOff = 0,+ SGSleepTimerAtTime, // at SGSleepTimerEnd()+ SGSleepTimerEndOfTrack, // just before the end of the track playing when it was set+ SGSleepTimerEndOfAlbum, // just before the end of the last track of the album or playlist playing+};++// The fade's length, an index into SGSleepTimerFadeNames() (Live Activity page, Sleep timer section). Read+// on every check, so a change applies to a timer already running. For a time it fades over the last seconds+// before the end; at the end of the track or the album over the last seconds of the (last) track, by the+// player's position and the track's length, and over the whole track when the track is shorter.+#define SGKeySleepTimerFade @"spotifyglass.sleepTimer.fade"+NSArray<NSString *> *SGSleepTimerFadeNames(void);+// The index picked, the default for none or one out of range.+NSInteger SGSleepTimerFadeChoice(void);+// The fade picked, in seconds; 0 for Off, which pauses at full volume.+NSTimeInterval SGSleepTimerFade(void);++SGSleepTimerMode SGSleepTimerCurrentMode(void);+// The end of an SGSleepTimerAtTime timer, nil for the others.+NSDate *SGSleepTimerEnd(void);++// Sets a timer up `seconds` from now (SGSleepTimerAtTime, `seconds` then counting) or at the end of the+// track or the album (`seconds` ignored), in place of any set before. SGSleepTimerOff cancels.+void SGSetSleepTimer(SGSleepTimerMode mode, NSTimeInterval seconds);+// Moves an SGSleepTimerAtTime timer's end `seconds` on; starts one from now when none is set or another kind is.+void SGSleepTimerAdd(NSTimeInterval seconds);++// What the timer goes by, here for harness/sleep-timer to check on the Mac.+//+// The gain `left` seconds before the pause, fading over `fade` seconds: 1 until the fade, then down by the+// same number of decibels each second, 60 dB over the fade, which the ear hears as an even fade. 1 all the+// way when `fade` is 0.+float SGSleepTimerGain(NSTimeInterval left, NSTimeInterval fade);+// Whether the playing track is the last of its album or playlist: no track of the context follows it in+// 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);diff --git a/tweak/Sources/Shared/Player/SleepTimer.m b/tweak/Sources/Shared/Player/SleepTimer.mnew file mode 100644index 00000000..b8918093--- /dev/null+++ b/tweak/Sources/Shared/Player/SleepTimer.m@@ -0,0 +1,205 @@+// The sleep timer (SleepTimer.h): a check four times a second while one is set, which fades the gain over+// the last seconds (the Fade out choice) and pauses once it is up.+//+// The end of the album is read from the player's tracks to come: SPTPlayerTrack's provider (a property+// with its own ivar in the binary, beside albumURI and contextSource) and the metadata keys is_queued and+// autoplay.is_autoplay (strings in the binary) tell a track queued by hand or picked by autoplay from one+// of the album or playlist. What they read on a real queue is logged once each time the mode is set.+#import "Core/SGLog.h"+#import "Core/SGPrefs.h"+#import "Headers/SPTPlayer.h"+#import "Shared/Lyrics/Lyrics.h"+#import "Shared/Player/PlayerState.h"+#import "Shared/Player/SpeedPitch.h"+#import "Shared/Player/SleepTimer.h"++static const NSTimeInterval kCheckEvery = 0.25;+// The end of track and end of album timers pause this close to the end, so the next track never starts.+static const NSTimeInterval kBeforeEnd = 0.5;+// The fade's depth: 60 dB down is as good as silent, and the pause takes it from there.+static const float kFadeDecibels = 60;+// The Fade out choices, by index, and the one unless another is picked.+static const NSTimeInterval kFades[] = {0, 10, 30, 60, 120};+static const NSInteger kFadeDefault = 2;+// The gain goes back to normal this long after the pause, once what was still on its way out has played.+static const NSTimeInterval kRestoreAfter = 1;++static SGSleepTimerMode sg_mode;+static NSDate *sg_end;+// The track and the context playing when it was set, by URI.+static NSString *sg_track, *sg_context;+static NSTimer *sg_timer;+// Whether this timer's fade has started, so the log says so once.+static BOOL sg_fading;++NSArray<NSString *> *SGSleepTimerFadeNames(void) {+ return @[@"Off", @"10 s", @"30 s", @"1 minute", @"2 minutes"];+}++NSInteger SGSleepTimerFadeChoice(void) {+ NSInteger index = SGInt(SGKeySleepTimerFade, kFadeDefault);+ return index >= 0 && index < (NSInteger)(sizeof kFades / sizeof *kFades) ? index : kFadeDefault;+}++NSTimeInterval SGSleepTimerFade(void) {+ return kFades[SGSleepTimerFadeChoice()];+}++SGSleepTimerMode SGSleepTimerCurrentMode(void) {+ return sg_mode;+}++NSDate *SGSleepTimerEnd(void) {+ return sg_mode == SGSleepTimerAtTime ? sg_end : nil;+}++float SGSleepTimerGain(NSTimeInterval left, NSTimeInterval fade) {+ if (fade <= 0 || left >= fade) return 1;+ return powf(10, -kFadeDecibels / 20 * (float)(1 - MAX(left, 0) / fade));+}++static BOOL metadataSays(SPTPlayerTrack *track, NSString *key) {+ NSDictionary *metadata = [track respondsToSelector:@selector(metadata)] ? track.metadata : nil;+ return [metadata isKindOfClass:NSDictionary.class] && [[metadata[key] description] isEqualToString:@"true"];+}++static NSString *providerOf(SPTPlayerTrack *track) {+ NSString *provider = [track respondsToSelector:@selector(provider)] ? track.provider : nil;+ return [provider isKindOfClass:NSString.class] ? provider : nil;+}++static BOOL isAutoplay(SPTPlayerTrack *track) {+ return [providerOf(track) isEqualToString:@"autoplay"] || metadataSays(track, @"autoplay.is_autoplay");+}++// A track of the album or playlist itself, not one queued by hand or picked by autoplay.+static BOOL isContextTrack(id track) {+ if (![track isKindOfClass:NSClassFromString(@"SPTPlayerTrack")] || !SGURIString([(SPTPlayerTrack *)track URI])) return NO;+ return ![providerOf(track) isEqualToString:@"queue"] && !metadataSays(track, @"is_queued") && !isAutoplay(track);+}++BOOL SGSleepTimerOnLastOfContext(SPTPlayerState *state) {+ id future = [state respondsToSelector:@selector(future)] ? state.future : nil;+ SPTPlayerTrack *next = nil;+ for (id track in [future isKindOfClass:NSArray.class] ? future : @[]) {+ if (isContextTrack(track)) { next = track; break; }+ }+ if (!next) return YES;+ // Repeating, the album comes round again: the next track is this one or one already played.+ if (!state.options.repeatingContext) return NO;+ NSString *uri = SGURIString(next.URI);+ if ([uri isEqualToString:SGURIString(state.track.URI)]) return YES;+ id reverse = [state respondsToSelector:@selector(reverse)] ? state.reverse : nil;+ for (id track in [reverse isKindOfClass:NSArray.class] ? reverse : @[]) {+ if ([track isKindOfClass:NSClassFromString(@"SPTPlayerTrack")] && [SGURIString([(SPTPlayerTrack *)track URI]) isEqualToString:uri]) return YES;+ }+ 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) {+ double duration = [state respondsToSelector:@selector(duration)] ? state.duration : 0;+ NSInteger position = SGKaraokePositionMs();+ return duration > 0 && position >= 0 ? MAX(0, duration - position / 1000.0) : -1;+}++static void stopChecking(void) {+ [sg_timer invalidate];+ sg_timer = nil;+ sg_mode = SGSleepTimerOff;+ sg_end = nil;+ sg_track = nil;+ sg_context = nil;+ sg_fading = NO;+}++// Seconds until the pause, or -1 when it is not in sight yet (a track whose length is not known, or the+// album still has tracks to go); 0 to pause now.+static NSTimeInterval secondsLeft(SPTPlayerState *state) {+ NSString *track = SGURIString(state.track.URI);+ switch (sg_mode) {+ case SGSleepTimerAtTime:+ 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;+ 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;+ }+ default:+ return -1;+ }+}++static void check(void) {+ if (sg_mode == SGSleepTimerOff) return;+ id<SPTPlayer> player = SGKaraokePlayer();+ SPTPlayerState *state = player.state;+ NSTimeInterval left = secondsLeft(state);+ BOOL up = left >= 0 && (sg_mode == SGSleepTimerAtTime ? left <= 0 : left < kBeforeEnd);+ if (!up) {+ NSTimeInterval fade = SGSleepTimerFade();+ // At the end of a track shorter than the fade, the fade starts with the track.+ double duration = [state respondsToSelector:@selector(duration)] ? state.duration : 0;+ if (sg_mode != SGSleepTimerAtTime && duration > 0) fade = MIN(fade, duration);+ float gain = left >= 0 ? SGSleepTimerGain(left, fade) : 1;+ if (gain < 1 && !sg_fading) {+ sg_fading = YES;+ SGLog(@"sleep timer: fading over %.0f s, %.1f s left (mode %ld, track %.1f s, at %ld ms)", fade, left, (long)sg_mode,+ duration, (long)SGKaraokePositionMs());+ }+ SGPlayerSetGain(gain);+ return;+ }+ SGSleepTimerMode mode = sg_mode;+ stopChecking();+ if (!state.isPaused) [player pause:nil];+ SGLog(@"sleep timer: up (mode %ld), %@%@", (long)mode, state.isPaused ? @"already paused" : @"paused",+ SGSleepTimerFade() > 0 ? @"" : @", no fade (Off)");+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kRestoreAfter * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ if (sg_mode == SGSleepTimerOff) SGPlayerSetGain(1);+ });+}++// What the tracks to come say about themselves, once per End of album, so the phone's log shows whether+// the provider and the two keys read the way SGSleepTimerOnLastOfContext expects.+static void logQueue(SPTPlayerState *state) {+ NSMutableArray<NSString *> *seen = [NSMutableArray array];+ id future = [state respondsToSelector:@selector(future)] ? state.future : nil;+ for (id track in [future isKindOfClass:NSArray.class] ? future : @[]) {+ if (seen.count == 4) break;+ if (![track isKindOfClass:NSClassFromString(@"SPTPlayerTrack")]) continue;+ [seen addObject:[NSString stringWithFormat:@"%@ provider %@ is_queued %@ autoplay %@ -> %@", [(SPTPlayerTrack *)track trackTitle],+ providerOf(track), [(SPTPlayerTrack *)track metadata][@"is_queued"],+ [(SPTPlayerTrack *)track metadata][@"autoplay.is_autoplay"], isContextTrack(track) ? @"album" : @"not album"]];+ }+ SGLog(@"sleep timer: end of album, context %@, playing %@ (provider %@), %lu to come, last of it %@: %@", SGURIString(state.contextURI),+ state.track.trackTitle, providerOf(state.track), (unsigned long)[future count], SGSleepTimerOnLastOfContext(state) ? @"yes" : @"no",+ [seen componentsJoinedByString:@"; "]);+}++void SGSetSleepTimer(SGSleepTimerMode mode, NSTimeInterval seconds) {+ stopChecking();+ if (mode == SGSleepTimerOff || (mode == SGSleepTimerAtTime && seconds <= 0)) {+ SGPlayerSetGain(1);+ return;+ }+ SPTPlayerState *state = [(id<SPTPlayer>)SGKaraokePlayer() state];+ sg_mode = mode;+ if (mode == SGSleepTimerAtTime) sg_end = [NSDate dateWithTimeIntervalSinceNow:seconds];+ sg_track = SGURIString(state.track.URI);+ sg_context = SGURIString(state.contextURI);+ if (mode == SGSleepTimerEndOfAlbum) logQueue(state);+ SGLog(@"sleep timer: set (mode %ld, %.0f s), fade %.0f s", (long)mode, seconds, SGSleepTimerFade());+ sg_timer = [NSTimer timerWithTimeInterval:kCheckEvery repeats:YES block:^(NSTimer *timer) { check(); }];+ [NSRunLoop.mainRunLoop addTimer:sg_timer forMode:NSRunLoopCommonModes];+ check();+}++void SGSleepTimerAdd(NSTimeInterval seconds) {+ NSDate *end = SGSleepTimerEnd();+ NSTimeInterval from = end && end.timeIntervalSinceNow > 0 ? end.timeIntervalSinceNow : 0;+ SGSetSleepTimer(SGSleepTimerAtTime, from + seconds);+}