Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: a Visualizer background draws the song as calm hills behind the player
My-Name-Is-Jeff0c08884f9822
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex ae9663e4..cd188d37 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -204,7 +204,8 @@ Shared: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+ in place (AudioEffects.x, SGDSPEngine.m), then hands it, mixed to mono, to one reader that only+ reads it, switch on or off (SGAudioSetOutputReader: the player's Visualiser). The buffers are in the unit's output format, thehardware's, not the client format Spotify sets. The effects are the SGDSP*.m files, on Accelerate,Apple's Reverb2 unit, libbs2b and EEL2 (vendor/audio). Settings apply as they change, on a queue ofits own; the file effects read their files from Documents/Vitrine/Audio effects@@ -352,7 +353,7 @@ Redesigned:dismisses it. Checked in the simulator against harness/system-menu/Player/ the redesigned full screen player (Player.h lists its files); its more button opens the systemmenu (ContextMenu/), Spotify's rows and then Playback Speed, Pitch (with Pitch follows speed),- Reverb and Animated artwork (PlayerMenu.m), and a hold on either side of the+ Reverb and the backgrounds it can switch to (PlayerMenu.m), and a hold on either side of thecover plays at 2x until the finger lifts (PlayerArtwork.x), an octave higher while Pitch followsspeed is on. A Free account gets it too: Spotify's Reinvented Free player mode, whose units none ofthe hooks reach, declines while the redesign runs, so the track falls to Spotify's other Free mode,@@ -362,11 +363,20 @@ Redesigned:from the seam under the controls and over the whole clip behind the lyrics. The clip and the covercross over as one comes and the other goes, the clip from its poster frame before the video hasdecoded one, and the Fluid field under a clip holds still and, once the clip has faded in, is hidden- (SGRArtworkField's covered); the menu switches it between Animated- and Fluid without a restart. The clip holds its frame while the song is paused, goes while+ (SGRArtworkField's covered); the menu switches between Animated, Fluid and the Visualiser without+ a restart. The clip holds its frame while the song is paused, goes whileSpotify's music video shows, is given up when it has drawn nothing in 5 s on screen, and on a skipstays a moment for the next track's to cross over it. Checked in the simulator against- harness/player/ (`motion`)+ harness/player/ (`motion`). The Visualiser+ (PlayerVisualiser.m) draws two soft hills of the song's spectrum across the foot of the player in the+ cover's flow colours, over the Fluid field held still, blurred behind the lyrics: the audio effects'+ render notify on the music's output hands what it plays, mixed to mono, to one reader (SGAudioSetOutputReader), and+ SGRSpectrum.m cuts it into 24 bands with Accelerate's FFT on the render thread, without allocating or+ locking, and publishes them atomically; a display link of at most 60 Hz (30 behind the lyrics, 15+ with Reduce Motion, where the bands ease over seconds) draws them while the player is on screen,+ Spotify is in front, the player is not opening or closing and Low Power Mode is off, and stops once+ a paused song's hills have settled. The spectrum is checked on the Mac against harness/visualiser/,+ the view in the simulator against harness/player/ (`visualiser`)Lyrics/ the full screen lyrics page on glass with Apple Music style lyrics over it, always on (SGRKaraokeView,which the player shows in itself too, Player/PlayerLyrics.x): lines sung over each other lit together,the stack moving on once the first is sung out; an instrumental break of 7 s or more held by three dots@@ -505,7 +515,7 @@ Spotify's own player screen (artwork background, glass header buttons, Disable Cheader, slider and sticky header flags, the cards under the player and the lyrics preview and playerbuttons to hide); in the redesign the page instead leads with a card of the player (Redesigned/Player/PlayerSettings.m): the background chosen edge to edge, and over its foot the cover, title, artist and progress;-under it a segmented control of the four backgrounds (Still, Colours, Fluid, Animated, changing the card at once)+under it a segmented control of the five backgrounds (Still, Colours, Fluid, Animated, Visualiser, changing the card at once)with a note on what the one picked does, Artwork sources and Download in Low Data Mode while Animated is chosen,and Mini player: Apple Music style (the tab bar's minimize on scroll), Device button (the now playing bar keepsSpotify's device button in that minimized row, off by default) and the device button hidden on the full bar,diff --git a/harness/audio-effects/README.md b/harness/audio-effects/README.mdindex c8131b80..7a74fd4d 100644--- a/harness/audio-effects/README.md+++ b/harness/audio-effects/README.md@@ -47,7 +47,8 @@ switch on and -12 dB, a Liveprog script from the library swapping the channels,source stops, a file missing from the library and its error, then a 16-bit interleaved client at 48 kHz, then asecond chain at 44.1 kHz started beside it: the effects move to the second chain and the first plays untouched,and when the second stops they move back. SpeedPitch.x is compiled in, since it names the output the effects-follow.+follow. At each step the output's reader (`SGAudioSetOutputReader`, the player's Visualiser's tap) is checked too:+the mono mix it gets is the measured level 6 dB down, the sine being in one channel, at the output's rate.THEOS=$HOME/theos ./build-sim.shxcrun simctl install <udid> build/sim/AudioEffectsHarness.appdiff --git a/harness/audio-effects/sim/main.m b/harness/audio-effects/sim/main.mindex 1fa4030e..13ff80e7 100644--- a/harness/audio-effects/sim/main.m+++ b/harness/audio-effects/sim/main.m@@ -96,6 +96,7 @@ static void level(unsigned calls, double *left, double *right, unsigned *frames,}static int sg_failures;+static void reportReader(double wantLeft, double wantRight);static void reportOutput(int which, NSString *what, double wantLeft, double wantRight) {double left, right;@@ -106,6 +107,36 @@ static void reportOutput(int which, NSString *what, double wantLeft, double wantNSLog(@"[harness] %@ %-44@ left %6.1f dB, right %6.1f dB (want %@, %@), slices of %u, %u silent; status \"%@\"", ok ? @" ok " : @"FAILED",what, left, right, isnan(wantLeft) ? @"any" : [NSString stringWithFormat:@"%.1f", wantLeft],isnan(wantRight) ? @"any" : [NSString stringWithFormat:@"%.1f", wantRight], frames, silent, SGDSPStatus());+ reportReader(wantLeft, wantRight);+}++#pragma mark - the output's reader (SGAudioSetOutputReader)++// What AudioEffects.x hands its one reader: the buffer after the effects, mixed to mono. The sine is in one+// channel only, so the mix is it at half, 6 dB down.+static float sg_readerLevels[kProbeCalls];+static atomic_uint sg_readerCalls;+static atomic_uint_fast64_t sg_readerRate;++static void reader(const float *samples, uint32_t count, double rate) {+ double sum = 0;+ for (uint32_t i = 0; i < count; i++) sum += samples[i] * samples[i];+ unsigned n = atomic_load(&sg_readerCalls);+ sg_readerLevels[n % kProbeCalls] = count ? (float)(sum / count) : 0;+ atomic_store(&sg_readerCalls, n + 1);+ atomic_store(&sg_readerRate, (uint64_t)rate);+}++static void reportReader(double wantLeft, double wantRight) {+ if (isnan(wantLeft) || isnan(wantRight)) return;+ unsigned n = atomic_load(&sg_readerCalls), count = 0;+ double sum = 0;+ for (unsigned i = 0; i < 8 && i < n; i++, count++) sum += sg_readerLevels[(n - 1 - i) % kProbeCalls];+ double got = count ? 10 * log10(sum / count + 1e-20) : -200, want = MAX(wantLeft, wantRight) - 6.02;+ BOOL ok = count && (want < -150 ? got < -150 : fabs(got - want) < 0.6);+ if (!ok) sg_failures++;+ NSLog(@"[harness] %@ the reader: %6.1f dB (want %.1f) at %llu Hz, %u calls", ok ? @" ok " : @"FAILED", got, want,+ (unsigned long long)atomic_load(&sg_readerRate), n);}static void report(NSString *what, double wantLeft, double wantRight) {@@ -240,6 +271,7 @@ static void check(OSStatus status, const char *what) {double sine = 20 * log10(kAmplitude / M_SQRT2), nothing = -200, any = NAN;NSLog(@"[harness] the sine's level is %.1f dB RMS in the left channel", sine);SGDSPSetSwitch(SGKeyDSP, NO);+ SGAudioSetOutputReader(reader);[self startSpotifyChainAt:44100];NSArray *script = @[diff --git a/harness/player/README.md b/harness/player/README.mdindex 5f8a1f71..77ef2cae 100644--- a/harness/player/README.md+++ b/harness/player/README.md@@ -15,7 +15,7 @@ sources, for example an older commit, to see a bug before its fix.`build.sh` runs `logos.pl -c generator=internal` over `PlayerLyrics.x`, `PlayerArtwork.x`,`PlayerControls.x`, `PlayerFooter.x`, `PlayerScroll.x`, `PlayerField.x` and the Kit's `SGRBridges.x`, and links them with-the real `Core/`, `Redesigned/Kit/`, `SGRKaraokeView`, `Settings/` and the Player page. `stubs.m` stands in for the hooks the harness+the real `Core/`, `Redesigned/Kit/`, `SGRKaraokeView`, `Settings/`, the Player page and the Visualiser (`PlayerVisualiser.m`, `SGRSpectrum.m`). `stubs.m` stands in for the hooks the harnessdoes not compile (the Kit's accent and repaint, the rest of the player, the lyrics store, the haptics,Sing's mic) and plays a mock player: `SGRHarnessSetTrack` reports a track, with the image ids Spotify'smetadata carries, to every state observer. A song of ten timed lines plays on from launch. `main.m` also answers@@ -69,11 +69,17 @@ come late, out of order, or not at all.ends with `motion checks: n of 20 right -- PASS` or `FAIL`.- `settings` opens the redesign's Player page (`PlayerSettings.m`, with the real `Settings/` framework) over the- player at 3 s, with the clip of `motion` in. It checks the card leads the page with the four backgrounds'- segmented control under it, the Mini player section's three rows are on the page, and then, as the control- picks each in turn, that the card shows Animated (the clip, the sources and Low Data Mode's rows in), Fluid,- Colours, Still and Animated again, with a note for each and the header the same height throughout. The log- ends with `settings checks: n of 7 right -- PASS` or `FAIL`.+ player at 3 s, with the clip of `motion` in. It checks the card leads the page with the five backgrounds'+ segmented control under it, every name whole, the Mini player section's three rows are on the page, and then,+ as the control picks each in turn, that the card shows Animated (the clip, the sources and Low Data Mode's rows+ in), Fluid, Colours, Still, Visualiser (the hills over Fluid held still) and Animated again, with a note for+ each and the header the same height throughout. The log ends with `settings checks: n of 8 right -- PASS` or+ `FAIL`.+- `visualiser` plays the Visualiser background, fed by `stubs.m`'s stand-in for the audio effects' reader: a song+ of its own at 120 beats a minute, handed over in buffers of 1024 at 48 kHz. It checks the hills stand on the+ Fluid field held still with the reader on and the link at up to 60 fps, blur behind the lyrics with the link at+ 30, settle and stop with the reader off on a pause, come back on play, and go and come back through the ⋯+ menu's switch to Fluid and back. The log ends with `visualiser checks: n of 7 right -- PASS` or `FAIL`.- `seek` is the tap around the progress bar (`PlayerControls.x`): a mock slider with Spotify's identifier andthe two times beside it. It checks that a tap counts below the bar and up to 12 pt past its ends, not on thediff --git a/harness/player/build.sh b/harness/player/build.shindex 9186d082..4ecaf651 100755--- a/harness/player/build.sh+++ b/harness/player/build.sh@@ -23,10 +23,10 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar"$SRC"/Shared/AnimatedArtwork/SGMotionFollower.m "$SRC"/Shared/AnimatedArtwork/SGMotionClip.m \"$SRC"/Redesigned/Kit/SGRGlass.m "$SRC"/Redesigned/Kit/SGRMarquee.m "$SRC"/Redesigned/Kit/SGRGlyph.m "$SRC"/Redesigned/Kit/SGRRestyle.m \"$SRC"/Redesigned/Kit/SGRedesign.m \- "$SRC"/Redesigned/Player/PlayerSettings.m "$SRC"/Redesigned/NowPlayingBar/NowPlayingBarSettings.m \+ "$SRC"/Redesigned/Player/PlayerSettings.m "$SRC"/Redesigned/Player/PlayerVisualiser.m "$SRC"/Redesigned/Player/SGRSpectrum.m "$SRC"/Redesigned/NowPlayingBar/NowPlayingBarSettings.m \"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \"$SRC"/Redesigned/Lyrics/SGRKaraokeView.m "$SRC"/Redesigned/Lyrics/LyricsLook.m "$SRC"/Redesigned/Lyrics/SGRSingButton.m "$SRC"/Redesigned/Lyrics/MeaningSheet.m "$SRC"/Redesigned/Lyrics/LyricsText.m "$SRC"/Shared/Lyrics/KaraokeTiming.m "$SRC"/Shared/Lyrics/Romanise.m "$SRC"/Shared/AdBlock/Protobuf.m \- -framework UIKit -framework QuartzCore -framework CoreGraphics -framework CoreImage -framework Foundation -framework Symbols -framework AVFoundation -framework CoreMedia -framework CoreVideo \+ -framework UIKit -framework QuartzCore -framework CoreGraphics -framework CoreImage -framework Foundation -framework Symbols -framework AVFoundation -framework CoreMedia -framework CoreVideo -framework Accelerate \-o "$OUT/PlayerHarness.app/PlayerHarness"cat > "$OUT/PlayerHarness.app/Info.plist" <<'PLIST'diff --git a/harness/player/main.m b/harness/player/main.mindex 31a3d06b..bb4731f7 100644--- a/harness/player/main.m+++ b/harness/player/main.m@@ -20,9 +20,13 @@// laid out, then the field, the lyrics, a field built again, the menu's switch and the player// closed, each step checked; the log ends with motion checks n of m right -- PASS or FAIL// settings the redesign's Player page (PlayerSettings.m) over the player with the clip of `motion`: the-// card over Animated, then Fluid, Colours and Still as the segmented control picks them, and-// Animated again, the note under it changing and the rows under the header holding still;-// each step checked, the log ends with settings checks n of m right -- PASS or FAIL+// card over Animated, then Fluid, Colours, Still and Visualiser as the segmented control picks+// them, and Animated again, the note under it changing and the rows under the header holding+// still; each step checked, the log ends with settings checks n of m right -- PASS or FAIL+// visualiser the Visualiser background (PlayerVisualiser.m) fed a song of the harness's own (stubs.m):+// the hills moving, blurred behind the lyrics, settling and stopping on a pause, back on play,+// and the ⋯ menu's switch to Fluid and back; the log ends with visualiser checks n of m right+// -- PASS or FAIL// HARNESS_VOLUME=0 leaves out the volume row the phone has (trees/clean/player/01.txt has none).#import <AVFoundation/AVFoundation.h>#import <UIKit/UIKit.h>@@ -563,6 +567,7 @@ static void loadLyrics(void) {else if ([scenario() isEqualToString:@"immersive"]) [self runImmersiveChecks];else if ([scenario() isEqualToString:@"settings"]) [self runSettingsChecks];else if ([scenario() isEqualToString:@"seek"]) [self runSeekChecks];+ else if ([scenario() isEqualToString:@"visualiser"]) [self runVisualiserChecks];// Opened, closed and opened again, so a screenshot can be taken of each state and of the move itself.else for (NSNumber *at in @[@2, @6, @10]) {dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(at.doubleValue * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{@@ -1001,19 +1006,20 @@ static UIView *firstOfClass(UIView *root, NSString *name) {segments.selectedSegmentIndex = (NSInteger)index;[segments sendActionsForControlEvents:UIControlEventValueChanged];};- void (^expectBackground)(NSString *, BOOL, BOOL, BOOL) = ^(NSString *step, BOOL fluid, BOOL flows, BOOL clip) {+ void (^expectBackground)(NSString *, BOOL, BOOL, BOOL, BOOL) = ^(NSString *step, BOOL fluid, BOOL flows, BOOL clip, BOOL hills) {UIView *view = showcase();SGRArtworkField *field = (SGRArtworkField *)firstOfClass(view, @"SGRArtworkField");- UIView *motion = firstOfClass(view, @"SGRPlayerMotionView");+ UIView *motion = firstOfClass(view, @"SGRPlayerMotionView"), *visualiser = firstOfClass(view, @"SGRVisualiserView");UIView *cover = [view valueForKey:@"_cover"];UILabel *note = [nav.topViewController valueForKey:@"_note"];NSInteger rows = [table() numberOfRowsInSection:0];CGFloat height = table().tableHeaderView.bounds.size.height;- BOOL ok = field && field.fluid == fluid && field.flows == flows && (motion != nil) == clip && !cover.hidden && rows == (clip ? 2 : 0)+ BOOL ok = field && field.fluid == fluid && field.flows == flows && (motion != nil) == clip && (visualiser != nil) == hills+ && field.motionHeld == (clip || hills) && !cover.hidden && rows == (clip ? 2 : 0)&& note.text.length && (headerHeight == 0 || fabs(height - headerHeight) < 0.5);headerHeight = height;- [self expect:ok step:step detail:[NSString stringWithFormat:@"field %@ fluid %d flows %d, clip %@, cover %@, %ld rows over the Mini player (%@), header %.0f, note \"%@\"",- field ? @"in" : @"missing", field.fluid, field.flows, motion ? @"on" : @"off", cover.hidden ? @"hidden" : @"shown",+ [self expect:ok step:step detail:[NSString stringWithFormat:@"field %@ fluid %d flows %d held %d, clip %@, hills %@, cover %@, %ld rows over the Mini player (%@), header %.0f, note \"%@\"",+ field ? @"in" : @"missing", field.fluid, field.flows, field.motionHeld, motion ? @"on" : @"off", visualiser ? @"on" : @"off", cover.hidden ? @"hidden" : @"shown",(long)rows, view.accessibilityValue, height, note.text]];};// The clip is in by 3 s (the motion scenario's first step), and the page opens over the player then.@@ -1027,26 +1033,123 @@ static UIView *firstOfClass(UIView *root, NSString *name) {UISegmentedControl *segments = control();CGRect card = view.frame, header = table().tableHeaderView.frame;BOOL shaped = view.window && card.size.width > card.size.height && card.size.width > header.size.width - 48;- [self expect:shaped && segments.numberOfSegments == 4 && CGRectGetMinY(segments.frame) > CGRectGetMaxY(card)- step:@"the card leads the page, the four backgrounds under it"+ // Every segment's title whole: the widest, Visualiser's, is not cut short.+ BOOL whole = YES;+ for (UILabel *label in [self labelsIn:segments]) whole = whole && label.intrinsicContentSize.width <= label.bounds.size.width + 0.5;+ [self expect:shaped && segments.numberOfSegments == 5 && whole && CGRectGetMinY(segments.frame) > CGRectGetMaxY(card)+ step:@"the card leads the page, the five backgrounds under it, their names whole"detail:[NSString stringWithFormat:@"card %@ in a header of %@, control %@ with %ld segments", NSStringFromCGRect(card),NSStringFromCGRect(header), NSStringFromCGRect(segments.frame), (long)segments.numberOfSegments]];NSInteger sections = table().numberOfSections;[self expect:sections == 2 && [table() numberOfRowsInSection:1] == 3 step:@"the Mini player section on the page"detail:[NSString stringWithFormat:@"%ld sections, %ld rows in the second", (long)sections, (long)[table() numberOfRowsInSection:1]]];- expectBackground(@"Animated", YES, NO, YES);+ expectBackground(@"Animated", YES, NO, YES, NO);pick(2);});- after(5, ^{ expectBackground(@"Fluid", YES, NO, NO); pick(1); });- after(6, ^{ expectBackground(@"Colours", NO, YES, NO); pick(0); });- after(7, ^{ expectBackground(@"Still", NO, NO, NO); pick(3); });+ after(5, ^{ expectBackground(@"Fluid", YES, NO, NO, NO); pick(1); });+ after(6, ^{ expectBackground(@"Colours", NO, YES, NO, NO); pick(0); });+ after(7, ^{ expectBackground(@"Still", NO, NO, NO, NO); pick(4); });after(8, ^{- expectBackground(@"Animated again", YES, NO, YES);+ expectBackground(@"Visualiser", YES, NO, NO, YES);+ NSLog(@"[harness] settings: screenshot the Visualiser card now");+ });+ // Held a little longer, so the screenshot catches it.+ after(10, ^{ pick(3); });+ after(11, ^{+ expectBackground(@"Animated again", YES, NO, YES, NO);NSLog(@"[harness] settings checks: %lu of %lu right -- %@", (unsigned long)(self->_checks - self->_failures), (unsigned long)self->_checks,self->_failures ? @"FAIL" : @"PASS");});}+- (NSArray<UILabel *> *)labelsIn:(UIView *)view {+ NSMutableArray<UILabel *> *labels = [NSMutableArray array];+ for (UIView *sub in view.subviews) {+ if ([sub isKindOfClass:UILabel.class]) [labels addObject:(UILabel *)sub];+ [labels addObjectsFromArray:[self labelsIn:sub]];+ }+ return labels;+}++#pragma mark - the Visualiser++BOOL SGRHarnessReading(void);++static UIView *visualiserView(void) {+ for (UIView *view in SGRPlayerField().subviews) {+ if ([NSStringFromClass(view.class) isEqualToString:@"SGRVisualiserView"]) return view;+ }+ return nil;+}++// The tallest a hill stands over the screen's foot, in points, from its path's bounding box.+static CGFloat hillHeight(UIView *view, NSString *ivar) {+ CAShapeLayer *shape = [view valueForKey:ivar];+ if (!shape.path) return 0;+ return view.bounds.size.height > 0 ? [[view valueForKey:@"baseline"] doubleValue] - CGPathGetPathBoundingBox(shape.path).origin.y : 0;+}++- (void)runVisualiserChecks {+ after(3, ^{+ UIView *hills = visualiserView();+ CADisplayLink *link = [hills valueForKey:@"_link"];+ CGFloat front = hillHeight(hills, @"_frontShape"), back = hillHeight(hills, @"_backShape");+ [self expect:hills && SGRPlayerVisualiserShowing() && SGRPlayerField().fluid && SGRPlayerField().motionHeld && link && SGRHarnessReading() && front > 40+ step:@"playing"+ detail:[NSString stringWithFormat:@"hills %@, field fluid %d held %d, link %@ at up to %.0f fps, reader %@, front %.0f pt, back %.0f pt",+ hills ? @"on the field" : @"missing", SGRPlayerField().fluid, SGRPlayerField().motionHeld, link ? @"running" : @"stopped",+ link.preferredFrameRateRange.maximum, SGRHarnessReading() ? @"on" : @"off", front, back]];+ NSLog(@"[harness] visualiser: screenshot the hills now");+ });+ after(4, ^{ SGRPlayerToggleLyrics(); });+ after(5.5, ^{+ UIView *hills = visualiserView();+ UIVisualEffectView *blur = [hills valueForKey:@"_lyricsBlur"];+ CADisplayLink *link = [hills valueForKey:@"_link"];+ [self expect:SGRPlayerLyricsOpen() && blur.effect && link.preferredFrameRateRange.maximum == 30 step:@"behind the lyrics"+ detail:[NSString stringWithFormat:@"lyrics %@, blur %@, link at up to %.0f fps", SGRPlayerLyricsOpen() ? @"up" : @"down",+ blur.effect ? @"on" : @"off", link.preferredFrameRateRange.maximum]];+ NSLog(@"[harness] visualiser: screenshot the lyrics now");+ });+ after(6.5, ^{ SGRPlayerToggleLyrics(); });+ after(7.5, ^{ SGRHarnessSetTrack(@"spotify:track:harnessA", imageURI(@"aaaa"), YES); });+ after(8, ^{+ CADisplayLink *link = [visualiserView() valueForKey:@"_link"];+ [self expect:link && !SGRHarnessReading() step:@"paused, settling"+ detail:[NSString stringWithFormat:@"link %@, reader %@", link ? @"still running" : @"stopped", SGRHarnessReading() ? @"on" : @"off"]];+ });+ after(12, ^{+ UIView *hills = visualiserView();+ CADisplayLink *link = [hills valueForKey:@"_link"];+ CGFloat front = hillHeight(hills, @"_frontShape");+ [self expect:!link && !SGRHarnessReading() && front < 15 step:@"paused, settled"+ detail:[NSString stringWithFormat:@"link %@, reader %@, front %.0f pt", link ? @"running" : @"stopped", SGRHarnessReading() ? @"on" : @"off", front]];+ NSLog(@"[harness] visualiser: screenshot the paused hills now");+ SGRHarnessSetTrack(@"spotify:track:harnessA", imageURI(@"aaaa"), NO);+ });+ after(13.5, ^{+ UIView *hills = visualiserView();+ [self expect:[hills valueForKey:@"_link"] && SGRHarnessReading() && hillHeight(hills, @"_frontShape") > 40 step:@"playing again"+ detail:[NSString stringWithFormat:@"front %.0f pt", hillHeight(hills, @"_frontShape")]];+ SGRPlayerMenuSetBackground(SGRPlayerBackgroundFluid);+ });+ after(14.2, ^{+ [self expect:!visualiserView() && !SGRPlayerVisualiserShowing() && !SGRPlayerField().motionHeld && !SGRHarnessReading()+ step:@"switched to Fluid from the menu"+ detail:[NSString stringWithFormat:@"hills %@, field %@, reader %@", visualiserView() ? @"still there" : @"gone",+ SGRPlayerField().motionHeld ? @"held" : @"moving", SGRHarnessReading() ? @"on" : @"off"]];+ SGRPlayerMenuSetBackground(SGRPlayerBackgroundVisualiser);+ });+ after(15.5, ^{+ UIView *hills = visualiserView();+ [self expect:hills && SGRPlayerField().motionHeld && SGRHarnessReading() && hillHeight(hills, @"_frontShape") > 40 step:@"back from the menu"+ detail:[NSString stringWithFormat:@"hills %@, field %@, front %.0f pt", hills ? @"on the field" : @"missing",+ SGRPlayerField().motionHeld ? @"held" : @"moving", hillHeight(hills, @"_frontShape")]];+ NSLog(@"[harness] visualiser checks: %lu of %lu right -- %@", (unsigned long)(self->_checks - self->_failures), (unsigned long)self->_checks,+ self->_failures ? @"FAIL" : @"PASS");+ });+}+- (void)runScrollChecks {after(2, ^{UIScrollView *list = self->_list;@@ -1405,6 +1508,7 @@ static BOOL linesSeek(SGRKaraokeView *lyrics) {__attribute__((constructor(101))) static void sgr_harnessDefaults(void) {[NSUserDefaults.standardUserDefaults setBool:YES forKey:@"spotifyglass.redesign"];// Animated artwork, its clip served by the picture server to the shared session too.+ if ([scenario() isEqualToString:@"visualiser"]) [NSUserDefaults.standardUserDefaults setInteger:4 forKey:@"spotifyglass.redesign.player.background"];if ([scenario() isEqualToString:@"motion"] || [scenario() isEqualToString:@"settings"]) {[NSUserDefaults.standardUserDefaults setInteger:3 forKey:@"spotifyglass.redesign.player.background"];setenv("HARNESS_CANVAS", "https://canvas.harness/clip.mp4", 1);diff --git a/harness/player/stubs.m b/harness/player/stubs.mindex 12fbeb88..30543610 100644--- a/harness/player/stubs.m+++ b/harness/player/stubs.m@@ -144,6 +144,48 @@ double SGPlayerSpeed(void) { return sg_speed; }BOOL SGPlayerSpeedAllowed(void) { return YES; }void SGSetPlayerSpeed(double speed) { sg_speed = speed; NSLog(@"[harness] speed %.2f", speed); }+// The audio effects' reader (AudioEffects.x): a song of the harness's own, 120 beats a minute at 48 kHz, a kick on+// every beat, hats between, a bass line, a chord and a tune, handed to the reader in buffers of 1024 on a queue of+// its own, as the render thread would, for as long as one is set.+#import <stdatomic.h>+#import "Shared/AudioEffects/AudioEffects.h"++static _Atomic(SGAudioOutputReader) sg_reader;+static dispatch_source_t sg_audio;++BOOL SGRHarnessReading(void) { return atomic_load(&sg_reader) != NULL; }++static void synthesize(float *out, uint64_t start, int count, double rate) {+ static const double bass[] = {55, 73.42, 65.41, 49}, tune[] = {440, 523.25, 587.33, 659.25, 783.99, 659.25, 587.33, 523.25};+ for (int i = 0; i < count; i++) {+ double t = (start + i) / rate, beat = fmod(t, 0.5), half = fmod(t + 0.25, 0.5);+ int bar = (int)(t / 2) % 4, note = (int)(t / 0.5) % 8;+ double kick = 0.55 * sin(2 * M_PI * 52 * beat) * exp(-9 * beat);+ double hat = 0.12 * (2.0 * arc4random_uniform(1 << 16) / (1 << 16) - 1) * exp(-50 * half);+ double low = 0.22 * sin(2 * M_PI * bass[bar] * t);+ double chord = 0.05 * (0.6 + 0.4 * sin(2 * M_PI * 0.25 * t)) * (sin(2 * M_PI * 220 * t) + sin(2 * M_PI * 277.18 * t) + sin(2 * M_PI * 329.63 * t));+ double lead = 0.08 * sin(2 * M_PI * tune[note] * t) * (1 - exp(-20 * beat));+ out[i] = (float)(kick + hat + low + chord + lead);+ }+}++void SGAudioSetOutputReader(SGAudioOutputReader reader) {+ atomic_store(&sg_reader, reader);+ NSLog(@"[harness] output reader %@", reader ? @"on" : @"off");+ if (sg_audio) return;+ __block uint64_t played = 0;+ sg_audio = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_queue_create("harness.audio", DISPATCH_QUEUE_SERIAL));+ dispatch_source_set_timer(sg_audio, DISPATCH_TIME_NOW, (uint64_t)(1024 / 48000.0 * NSEC_PER_SEC), NSEC_PER_MSEC);+ dispatch_source_set_event_handler(sg_audio, ^{+ static float buffer[1024];+ synthesize(buffer, played, 1024, 48000);+ played += 1024;+ SGAudioOutputReader now = atomic_load(&sg_reader);+ if (now) now(buffer, 1024, 48000);+ });+ dispatch_resume(sg_audio);+}+// Sing (the mic on the lyrics, SGRSingButton.m): never available, as on a phone that cannot run it.#import "Shared/Sing/Sing.h"NSString *const SGSingChangedNotification = @"harness.singChanged";diff --git a/harness/visualiser/README.md b/harness/visualiser/README.mdnew file mode 100644index 00000000..b88f5c6b--- /dev/null+++ b/harness/visualiser/README.md@@ -0,0 +1,15 @@+# Visualiser harness++The player's Visualiser background reads Spotify's sound through `Redesigned/Player/SGRSpectrum.m`. `main.m`+runs it on the Mac as the tweak compiles it, fed in IO buffers of 1024 the way `PlayerVisualiser.x` is fed by+`AudioEffects.x`'s reader:++ ./build.sh && build/spectrum++It checks that nothing is analysed before the tables are made, that a full scale 1 kHz sine reads 0 dB in its band+(and a tenth of it -20 dB) with every band more than one away at least 30 dB under, that 56 Hz and 10 kHz land in+the lowest band and the last but one at 48 and 44.1 kHz, that silence reads the floor, that white noise rises+about 3 dB an octave over the bands, and that it analyses about 47 times a second at 48 kHz. The log ends with+`spectrum checks: n of 11 right -- PASS` or `FAIL`.++The view itself is laid out in the player harness (`harness/player`, scenario `visualiser`).diff --git a/harness/visualiser/build.sh b/harness/visualiser/build.shnew file mode 100755index 00000000..fd90a584--- /dev/null+++ b/harness/visualiser/build.sh@@ -0,0 +1,8 @@+#!/bin/sh+# Builds the Visualiser's spectrum check for the Mac: SGRSpectrum.m as the tweak compiles it, under main.m.+set -e+cd "$(dirname "$0")"+mkdir -p build+xcrun clang -fobjc-arc -O2 -Wall -Werror -I ../../tweak/Sources -framework Foundation -framework Accelerate \+ main.m ../../tweak/Sources/Redesigned/Player/SGRSpectrum.m -o build/spectrum+echo "built build/spectrum"diff --git a/harness/visualiser/main.m b/harness/visualiser/main.mnew file mode 100644index 00000000..89cd0961--- /dev/null+++ b/harness/visualiser/main.m@@ -0,0 +1,107 @@+// The Visualiser's spectrum (Redesigned/Player/SGRSpectrum.m, as the tweak compiles it) on the Mac: tones and+// noise handed over in IO buffers of 1024 at an output's rate, the way PlayerVisualiser.x gets them through+// AudioEffects.x's reader, and each check printed with ok or WRONG.+//+// ./build.sh && build/spectrum+#import <Foundation/Foundation.h>+#import "Redesigned/Player/SGRSpectrum.h"++static int checks, right;++static void check(BOOL ok, NSString *what) {+ checks++;+ right += ok;+ printf("%s %s\n", ok ? "ok " : "WRONG", what.UTF8String);+}++// `seconds` of a sine of `amplitude` at `hz` (0: silence; negative: white noise of that amplitude), fed in+// buffers of 1024. Answers how many analyses there have been.+static uint64_t feed(double hz, float amplitude, double rate, double seconds) {+ static double phase;+ float buffer[1024];+ uint32_t total = (uint32_t)(seconds * rate);+ for (uint32_t done = 0; done < total; done += 1024) {+ for (int i = 0; i < 1024; i++) {+ if (hz > 0) {+ buffer[i] = amplitude * (float)sin(phase);+ phase += 2 * M_PI * hz / rate;+ } else if (hz < 0) {+ buffer[i] = amplitude * (2 * (float)arc4random_uniform(1 << 16) / (1 << 16) - 1);+ } else {+ buffer[i] = 0;+ }+ }+ SGRSpectrumFeed(buffer, 1024, rate);+ }+ float levels[SGRSpectrumBands];+ return SGRSpectrumRead(levels);+}++// The loudest band, its level, and the loudest more than one band away from it (a tone near an edge spills into+// its neighbour).+static int loudest(const float *levels, float *level, float *outside) {+ int best = 0;+ for (int i = 1; i < SGRSpectrumBands; i++) if (levels[i] > levels[best]) best = i;+ *level = levels[best];+ *outside = SGRSpectrumFloor;+ for (int i = 0; i < SGRSpectrumBands; i++) if (abs(i - best) > 1) *outside = fmaxf(*outside, levels[i]);+ return best;+}++static void tone(double hz, float amplitude, double rate, int band, float expected, float within) {+ feed(hz, amplitude, rate, 0.5);+ float levels[SGRSpectrumBands], level, outside;+ SGRSpectrumRead(levels);+ int best = loudest(levels, &level, &outside);+ check(best == band && fabsf(level - expected) < within && outside < level - 30,+ [NSString stringWithFormat:@"%.0f Hz at %.1f kHz: band %d (want %d) at %.1f dB (want %.0f), the rest %.1f dB under",+ hz, rate / 1000, best, band, level, expected, level - outside]);+}++int main(void) {+ @autoreleasepool {+ float levels[SGRSpectrumBands];+ check(feed(1000, 1, 48000, 0.5) == 0, @"nothing analysed before SGRSpectrumPrepare");+ SGRSpectrumPrepare();+ SGRSpectrumPrepare();+ SGRSpectrumRead(levels);+ check(levels[0] == SGRSpectrumFloor && levels[SGRSpectrumBands - 1] == SGRSpectrumFloor, @"every band at the floor to begin with");++ // The bands are spaced by (14000/50)^(1/24): 1 kHz is in band 12, 56 Hz in band 0, 10 kHz in band 22. The+ // lowest bands are a bin or two wide, narrower than a tone's spread under the window, so they keep only+ // part of it.+ tone(1000, 1, 48000, 12, 0, 1);+ tone(1000, 0.1f, 48000, 12, -20, 1);+ tone(56, 0.5f, 48000, 0, -6, 3);+ tone(10000, 0.5f, 48000, 22, -6, 1);+ tone(1000, 1, 44100, 12, 0, 1);+ tone(56, 0.5f, 44100, 0, -6, 3);++ uint64_t before = feed(0, 0, 44100, 0.01);+ uint64_t after = feed(0, 0, 44100, 0.5);+ SGRSpectrumRead(levels);+ float loudestSilence = SGRSpectrumFloor;+ for (int i = 0; i < SGRSpectrumBands; i++) loudestSilence = fmaxf(loudestSilence, levels[i]);+ check(after > before && loudestSilence == SGRSpectrumFloor, @"silence: still analysed, every band at the floor");++ // White noise has as much power per hertz, so a band's level rises with its width: about 3 dB an octave,+ // and bands 8 to 20 span about 3.9 octaves. One analysis of noise over a narrow band swings by a few dB,+ // so the rise is averaged over a second of them.+ feed(-1, 0.5f, 48000, 0.2);+ float rise = 0;+ for (int i = 0; i < 48; i++) {+ feed(-1, 0.5f, 48000, 1024 / 48000.0);+ SGRSpectrumRead(levels);+ rise += (levels[20] - levels[8]) / 48;+ }+ check(rise > 9 && rise < 15, [NSString stringWithFormat:@"white noise rises %.1f dB from band 8 to 20 (want about 12)", rise]);++ // About 47 analyses a second at 48 kHz: one every 1024 samples once the ring is full.+ uint64_t start = feed(0, 0, 48000, 0.01);+ uint64_t end = feed(0, 0, 48000, 1);+ check(end - start >= 45 && end - start <= 48, [NSString stringWithFormat:@"%llu analyses in a second at 48 kHz", end - start]);++ printf("spectrum checks: %d of %d right -- %s\n", right, checks, right == checks ? "PASS" : "FAIL");+ return right == checks ? 0 : 1;+ }+}diff --git a/tweak/Sources/Redesigned/Player/Player.h b/tweak/Sources/Redesigned/Player/Player.hindex 212938d2..e3d73a10 100644--- a/tweak/Sources/Redesigned/Player/Player.h+++ b/tweak/Sources/Redesigned/Player/Player.h@@ -18,8 +18,10 @@// PlayerGestures.x the gestures' hookup// PlayerMorph.x the open and close grown out of the now playing bar's card, the cover flown// PlayerMotion.x Animated artwork: the Canvas or Apple Music's animated cover behind the player+// PlayerVisualiser.m the Visualiser background: a calm spectrum of the song in the cover's colours, read+// through SGRSpectrum.m from the audio effects' tap on Spotify's output// PlayerMenu.m the more button's system menu: Share, Add to playlist and Add to queue on top, then-// speed, pitch and reverb and Show Animated or Fluid artwork, and Spotify's other rows+// speed, pitch and reverb, the backgrounds it can switch to, and Spotify's other rows// under More (Redesigned/ContextMenu)// PlayerSettings.m the Player page in Mod Settings, led by a showcase of the player// PlayerFree.x a Spotify Free account given the player mode these units belong to@@ -42,15 +44,19 @@ typedef NS_ENUM(NSInteger, SGRPlayerBackgroundKind) {SGRPlayerBackgroundStill, // the artwork blurred and held stillSGRPlayerBackgroundColours, // the artwork's colours drifting (SGRFlow.h)SGRPlayerBackgroundFluid, // the artwork itself blurred and turning (SGRFluid.h)- SGRPlayerBackgroundAnimated, // the track's Canvas or Apple Music's animated cover, over Fluid (PlayerMotion.x);- // the player's ⋯ menu switches between this and Fluid+ SGRPlayerBackgroundAnimated, // the track's Canvas or Apple Music's animated cover, over Fluid (PlayerMotion.x)+ SGRPlayerBackgroundVisualiser, // a spectrum of the song over Fluid held still (PlayerVisualiser.m)};+// The player's ⋯ menu switches between the last three, which share the Fluid field, without a restart.SGRPlayerBackgroundKind SGRPlayerBackground(void);// The names of the choices, in order.NSArray<NSString *> *SGRPlayerBackgroundNames(void);// The field behind the player, nil until the player has laid out once (PlayerField.x).SGRArtworkField *SGRPlayerField(void);+// Holds the field still, or lets it move, for what is over it now: a paused song, an Animated artwork clip, the+// Visualiser (PlayerField.x).+void SGRPlayerHoldField(void);#pragma mark - the cover (PlayerArtwork.x)@@ -101,6 +107,21 @@ BOOL SGRPlayerMotionShowing(void);// for the Player page's showcase; nil while no clip plays. It plays only in a window, like the player's.UIView *SGRPlayerMotionPreview(void);+#pragma mark - the Visualiser (PlayerVisualiser.m)++// The background is the Visualiser.+BOOL SGRPlayerVisualiserShowing(void);+// Puts the hills on the field or takes them off as the background says, lays them out, and blurs them while the+// lyrics are open. Called on every layout pass of the field (PlayerField.x), when the lyrics come or go+// (PlayerFooter.x), and when the ⋯ menu switches the background (PlayerMotion.x and here); cheap when nothing+// changed.+void SGRPlayerVisualiserUpdate(void);+// A view of its own drawing the same hills, for the Player page's showcase. It moves only in a window.+UIView *SGRPlayerVisualiserPreview(void);+// Switches the background to `kind` from the ⋯ menu, at once: Fluid, Animated or Visualiser, while it is one of+// them (SGPlayerMenuOffersAnimatedArtwork); nothing otherwise.+void SGRPlayerMenuSetBackground(SGRPlayerBackgroundKind kind);+#pragma mark - Mod Settings (PlayerSettings.m)// The redesign's Player page: a card of the player over the background chosen and the control that picksdiff --git a/tweak/Sources/Redesigned/Player/PlayerField.x b/tweak/Sources/Redesigned/Player/PlayerField.xindex 4f768374..791d2deb 100644--- a/tweak/Sources/Redesigned/Player/PlayerField.x+++ b/tweak/Sources/Redesigned/Player/PlayerField.x@@ -43,11 +43,22 @@ SGRArtworkField *SGRPlayerField(void) {SGRPlayerBackgroundKind SGRPlayerBackground(void) {NSInteger kind = SGInt(SGRKeyPlayerBackground, SGEnabled(SGRKeyPlayerMotion) ? SGRPlayerBackgroundColours : SGRPlayerBackgroundStill);- return kind >= SGRPlayerBackgroundStill && kind <= SGRPlayerBackgroundAnimated ? kind : SGRPlayerBackgroundColours;+ return kind >= SGRPlayerBackgroundStill && kind <= SGRPlayerBackgroundVisualiser ? kind : SGRPlayerBackgroundColours;}NSArray<NSString *> *SGRPlayerBackgroundNames(void) {- return @[@"Still", @"Colours", @"Fluid", @"Animated"];+ return @[@"Still", @"Colours", @"Fluid", @"Animated", @"Visualiser"];+}++// A paused song holds the colours still, the way it rests the cover (PlayerArtwork.x), and so does what lies over+// the field: an animated artwork's clip, which covers it (PlayerMotion.x), or the Visualiser's hills, which are+// the one thing moving.+static BOOL fieldHeld(void) {+ return SGPlayerState().isPaused || SGRPlayerMotionShowing() || SGRPlayerVisualiserShowing();+}++void SGRPlayerHoldField(void) {+ sg_field.motionHeld = fieldHeld();}#pragma mark - the field@@ -66,9 +77,7 @@ static SGRArtworkField *fieldIn(UIView *plane) {SGRPlayerBackgroundKind background = SGRPlayerBackground();field.flows = background == SGRPlayerBackgroundColours;field.fluid = background >= SGRPlayerBackgroundFluid;- // A paused song holds the colours still, the way it rests the cover (PlayerArtwork.x), and so does an- // animated artwork's clip, which covers the field (PlayerMotion.x).- field.motionHeld = SGPlayerState().isPaused || SGRPlayerMotionShowing();+ field.motionHeld = fieldHeld();field.bleed = kBleed;objc_setAssociatedObject(plane, &kFieldKey, field, OBJC_ASSOCIATION_RETAIN_NONATOMIC);sg_field = field;@@ -91,6 +100,7 @@ static SGRArtworkField *fieldIn(UIView *plane) {else if (plane.subviews.lastObject != field) [plane bringSubviewToFront:field];if (!CGRectEqualToRect(field.frame, plane.bounds)) field.frame = plane.bounds;SGRPlayerMotionFieldLaidOut();+ SGRPlayerVisualiserUpdate();}- (void)backgroundViewModel:(id)model didChangeColor:(id)color playerState:(id)state {@@ -155,7 +165,7 @@ static void publishCover(void) {}- (void)playerStateDidChange:(SPTPlayerState *)state {- sg_field.motionHeld = state.isPaused || SGRPlayerMotionShowing();+ SGRPlayerHoldField();NSString *track = SGURIString(state.track.URI);if (!track || [track isEqualToString:_track]) return;_track = track;diff --git a/tweak/Sources/Redesigned/Player/PlayerFooter.x b/tweak/Sources/Redesigned/Player/PlayerFooter.xindex e757d07a..dce5ca23 100644--- a/tweak/Sources/Redesigned/Player/PlayerFooter.x+++ b/tweak/Sources/Redesigned/Player/PlayerFooter.x@@ -69,6 +69,7 @@ static CGFloat moveTo(UIView *arranged, UIView *view, CGPoint point, UIView *hosvoid SGRPlayerLyricsChanged(void) {SGRPlayerMotionLyricsChanged();+ SGRPlayerVisualiserUpdate();SGRGlyphButton *glyph = sg_lyricsGlyph;if (!glyph) return;BOOL enabled = SGRPlayerLyricsAvailable() || SGRPlayerLyricsOpen(), open = SGRPlayerLyricsOpen();diff --git a/tweak/Sources/Redesigned/Player/PlayerMenu.m b/tweak/Sources/Redesigned/Player/PlayerMenu.mindex 9c8983c0..b36d82e1 100644--- a/tweak/Sources/Redesigned/Player/PlayerMenu.m+++ b/tweak/Sources/Redesigned/Player/PlayerMenu.m@@ -6,8 +6,9 @@// Playback Speed 0.5× to 2× in the steps Podcasts offers, the current one checked// Pitch Pitch Follows Speed, then three semitones down to three up, Original between them// Reverb Off and a quarter at a time up to 100%, the audio effects' reverb-// Show Animated Artwork or Show Fluid Artwork: a button that switches the background between the two,-// while it is one of them, named for what it switches to+// Show Fluid Artwork, Show Animated Artwork, Show Visualiser+// a button for each of the two the background is not, while it is one of the+// three, named for what it switches to//// Each submenu says what it is set to under its name, so the menu reads as a settings summary without opening// anything. A public menu has no sliders, so the steps stand in for them: the sheet's block, with its finer@@ -119,12 +120,19 @@ static UIMenu *soundMenu(void) {static NSArray<UIMenuElement *> *playerItems(void) {NSMutableArray<UIMenuElement *> *items = [NSMutableArray arrayWithObject:soundMenu()];if (SGPlayerMenuOffersAnimatedArtwork()) {- // A button named for what it does, not a checkmark: the HIG's changeable label for a toggled item.- BOOL on = SGPlayerMenuAnimatedArtwork();- UIAction *animated = [UIAction actionWithTitle:on ? @"Show Fluid Artwork" : @"Show Animated Artwork"- image:symbol(on ? @"drop" : @"play.rectangle.on.rectangle") identifier:nil- handler:^(UIAction *action) { SGPlayerMenuSetAnimatedArtwork(!on); }];- [items addObject:animated];+ // Buttons named for what they do, not checkmarks: the HIG's changeable label for a toggled item.+ NSArray<NSArray *> *backgrounds = @[+ @[@(SGRPlayerBackgroundFluid), @"Show Fluid Artwork", @"drop"],+ @[@(SGRPlayerBackgroundAnimated), @"Show Animated Artwork", @"play.rectangle.on.rectangle"],+ @[@(SGRPlayerBackgroundVisualiser), @"Show Visualiser", @"waveform"],+ ];+ SGRPlayerBackgroundKind current = SGRPlayerBackground();+ for (NSArray *background in backgrounds) {+ SGRPlayerBackgroundKind kind = [background[0] integerValue];+ if (kind == current) continue;+ [items addObject:[UIAction actionWithTitle:background[1] image:symbol(background[2]) identifier:nil+ handler:^(UIAction *action) { SGRPlayerMenuSetBackground(kind); }]];+ }}return items;}diff --git a/tweak/Sources/Redesigned/Player/PlayerMotion.x b/tweak/Sources/Redesigned/Player/PlayerMotion.xindex 3d9e0232..af4c6030 100644--- a/tweak/Sources/Redesigned/Player/PlayerMotion.x+++ b/tweak/Sources/Redesigned/Player/PlayerMotion.x@@ -274,7 +274,7 @@ static void cover(BOOL covering) {// The Fluid field under a clip holds still, as it does for a paused song (PlayerField.x): the clip covers it.static void holdField(void) {- SGRPlayerField().motionHeld = SGPlayerState().isPaused || sg_motion != nil;+ SGRPlayerHoldField();}// The mask's opacity to `opacity`, from where it is drawn now, over the clip's own fade. The frame reaches a@@ -441,12 +441,10 @@ static BOOL beginTrack(NSString *track) {#pragma mark - the ⋯ menu's switch (Shared/Player/SpeedPitch.h)-// Fluid and Animated share the field, so the menu moves between the two without a restart. The other-// backgrounds are a field of another kind, chosen on the Player page (PlayerSettings.m).+// Fluid, Animated and the Visualiser share the field, so the menu moves between them without a restart. The+// other backgrounds are a field of another kind, chosen on the Player page (PlayerSettings.m).BOOL SGPlayerMenuOffersAnimatedArtwork(void) {- if (!sg_follower) return NO;- SGRPlayerBackgroundKind background = SGRPlayerBackground();- return background == SGRPlayerBackgroundFluid || background == SGRPlayerBackgroundAnimated;+ return sg_follower && SGRPlayerBackground() >= SGRPlayerBackgroundFluid;}BOOL SGPlayerMenuAnimatedArtwork(void) {@@ -460,6 +458,8 @@ void SGPlayerMenuSetAnimatedArtwork(BOOL on) {// The playing track is let go, and looked up again when switched on.clear(YES);[sg_follower restart];+ // From the Visualiser, whose hills go.+ SGRPlayerVisualiserUpdate();}%group SGRVideoSurfaces@@ -500,7 +500,7 @@ void SGPlayerMenuSetAnimatedArtwork(BOOL on) {%ctor {if (!SGRedesignedUI()) return;SGRPlayerBackgroundKind background = SGRPlayerBackground();- if (background != SGRPlayerBackgroundFluid && background != SGRPlayerBackgroundAnimated) return;+ if (background < SGRPlayerBackgroundFluid) return;sg_videos = [NSHashTable weakObjectsHashTable];sg_follower = [[SGMotionFollower alloc] initWithBegin:^BOOL(NSString *uri, SPTPlayerState *state) {return beginTrack(uri);diff --git a/tweak/Sources/Redesigned/Player/PlayerSettings.m b/tweak/Sources/Redesigned/Player/PlayerSettings.mindex b39ee15e..d31f66b9 100644--- a/tweak/Sources/Redesigned/Player/PlayerSettings.m+++ b/tweak/Sources/Redesigned/Player/PlayerSettings.m@@ -4,12 +4,13 @@// page edge to edge, and over its foot the cover, the title, the artist and how far the track has played.// The progress is where the track was when the page appeared.//-// The background is the player's own: a field of the same kind (Still, Colours, Fluid), and for Animated+// The background is the player's own: a field of the same kind (Still, Colours, Fluid), for Animated// the clip the player is playing (SGRPlayerMotionPreview) in place of the field, or Fluid while there is-// none, as in the player. It moves under the field's own conditions (in a window, Spotify in front, Reduce-// Motion and Low Power Mode off). Under the card a segmented control picks the background, all four of-// them: the names are one short word each, so they fit side by side at the narrowest iPhone width, and-// every choice stays one tap away with the card showing it at once. A note under the control says what the+// none, as in the player, and for Visualiser the hills over Fluid held still (SGRPlayerVisualiserPreview),+// moving with the song. It moves under the field's own conditions (in a window, Spotify in front, Reduce+// Motion and Low Power Mode off). Under the card a segmented control picks the background, all five of+// them: the names are one word each, each segment as wide as its name, so they fit side by side at an iPhone's+// width, and every choice stays one tap away with the card showing it at once. A note under the control says what the// choice does; it is given the room of the longest note, so the rows under it hold still as it changes.//// Under the header: the rows that follow the choice (Animated's sources and its Low Data Mode switch;@@ -36,7 +37,8 @@ static NSArray<NSString *> *backgroundNotes(void) {@"The cover, blurred and held still.",@"The cover's colours, drifting slowly.",@"The cover itself, blurred and slowly turning. It rests while a song is paused.",- @"The song's Canvas or the album's moving cover, else Fluid. The player's ⋯ menu switches between the two.",+ @"The song's Canvas or the album's moving cover, else Fluid. The player's ⋯ menu switches between this, Fluid and Visualiser.",+ @"The song's sound as gentle hills in the cover's colours, over Fluid held still. They settle while a song is paused.",];}@@ -47,7 +49,7 @@ static NSArray<NSString *> *backgroundNotes(void) {@implementation SGRPlayerShowcase {SGRArtworkField *_field;- UIView *_motion;+ UIView *_motion, *_visualiser;UIImageView *_cover;UILabel *_title, *_artist;UIView *_progress, *_progressFill;@@ -129,8 +131,8 @@ static NSArray<NSString *> *backgroundNotes(void) {_title.text = track.trackTitle.length ? track.trackTitle : @"Not Playing";_artist.text = track.artistName ?: @"";_position = state.duration > 0 ? MIN(1, MAX(0, state.position / state.duration)) : 0;- // The clip covers the field, which then holds still, as in the player (PlayerMotion.x).- _field.motionHeld = state.isPaused || _motion != nil;+ // The clip covers the field, and the hills move over it, which then holds still, as in the player.+ _field.motionHeld = state.isPaused || _motion != nil || _visualiser != nil;if (SGRNowPlayingArtwork(NULL, NULL)) {[self artworkChanged];} else {@@ -150,7 +152,10 @@ static NSArray<NSString *> *backgroundNotes(void) {[self->_motion removeFromSuperview];self->_motion = kind == SGRPlayerBackgroundAnimated ? SGRPlayerMotionPreview() : nil;if (self->_motion) [self insertSubview:self->_motion aboveSubview:self->_field];- self->_field.motionHeld = SGPlayerState().isPaused || self->_motion != nil;+ [self->_visualiser removeFromSuperview];+ self->_visualiser = kind == SGRPlayerBackgroundVisualiser ? SGRPlayerVisualiserPreview() : nil;+ if (self->_visualiser) [self insertSubview:self->_visualiser aboveSubview:self->_field];+ self->_field.motionHeld = SGPlayerState().isPaused || self->_motion != nil || self->_visualiser != nil;};self.accessibilityValue = [SGRPlayerBackgroundNames()[(NSUInteger)kind] stringByAppendingString:@" background"];if (animated && self.window) {@@ -172,6 +177,7 @@ static NSArray<NSString *> *backgroundNotes(void) {_field.frame = bounds;_field.backdropHeight = h;_motion.frame = bounds;+ _visualiser.frame = bounds;_cover.frame = CGRectMake(kCardPadding, h - kCardPadding - kCoverSide, kCoverSide, kCoverSide);CGFloat x = CGRectGetMaxX(_cover.frame) + 12, width = w - kCardPadding - x;@@ -271,6 +277,7 @@ UIViewController *SGRPlayerSettingsPage(NSArray *more) {UISegmentedControl *backgrounds = [[UISegmentedControl alloc] initWithItems:SGRPlayerBackgroundNames()];backgrounds.selectedSegmentIndex = SGRPlayerBackground();backgrounds.accessibilityLabel = @"Background";+ backgrounds.apportionsSegmentWidthsByContent = YES;SGModRow *lowData = SGOptionRow(@"Download in Low Data Mode", @"Up to about 7 MB a song", SGKeyMotionLowData);lowData.visible = ^BOOL { return SGRPlayerBackground() == SGRPlayerBackgroundAnimated; };diff --git a/tweak/Sources/Redesigned/Player/PlayerVisualiser.m b/tweak/Sources/Redesigned/Player/PlayerVisualiser.mnew file mode 100644index 00000000..4641e3b3--- /dev/null+++ b/tweak/Sources/Redesigned/Player/PlayerVisualiser.m@@ -0,0 +1,454 @@+// Player redesign: the Visualiser background, a calm spectrum of what is playing behind the player, in the+// cover's colours, over the Fluid field held still (PlayerField.x keeps the field Fluid for this choice, as for+// Animated, so the ⋯ menu moves between the three without a restart).+//+// The sound is Spotify's output as it plays, read on the render thread through the audio effects' notify+// (SGAudioSetOutputReader, Shared/AudioEffects/AudioEffects.h) into SGRSpectrum.m's bands. Here, on the main+// thread, a display link reads the bands, brings them to a share of the song's own loudness (the loudest band of+// the last few seconds at the top, so a quiet track moves as much as a loud one), eases each band up quickly+// and down slowly, and draws two soft hills across the foot of the screen, mirrored about its middle, the bass+// in the middle and the treble at either edge: a slow one behind, a quicker one in front. Each is a gradient of+// the cover's colours (SGRPalette's flow colours, kept dark enough that white text on them stays over 5.5:1)+// masked by a shape layer, so the render server does the drawing and the app only hands it two paths a frame.+//+// It moves only while it is in a window, Spotify is in front, the player is not opening or closing, Low Power+// Mode is off and the song plays; a pause lets the hills settle and the link stops, and nothing is read from+// the sound while it is stopped. At most 60 frames a second, 30 while the lyrics, which have a link of their own,+// are open and the hills are blurred behind them, and with Reduce Motion 15, with every band easing over+// seconds. While the player opens or closes the link is down, and comes back only once the animation is over:+// a link at 60 would hold the transition's 120 Hz down with it.+//+// ponytail: the hills follow what the output is handed, which a Bluetooth headset plays a fifth of a second or+// so later. Music Haptics schedules for the output latency; do the same here if the beat looks early on AirPods.+//+// Threading: main thread only, but for the reader, which runs on the render thread.+#import "Core/SGCore.h"+#import "Redesigned/Kit/SGRKit.h"+#import "Shared/AudioEffects/AudioEffects.h"+#import "Shared/Player/PlayerEvents.h"+#import "Shared/Player/PlayerState.h"+#import "Shared/Player/SpeedPitch.h"+#import "Player.h"+#import "SGRSpectrum.h"++enum { kBands = SGRSpectrumBands, kPoints = 2 * kBands - 1 };+// The loudness a band is drawn against: the loudest band of late at the top, kRange dB under it at the floor,+// the top falling kPeakFall dB a second after a loud passage and never under kPeakFloor, so silence stays flat.+static const float kRange = 40, kPeakFall = 4, kPeakFloor = -60;+// A rise towards the treble, in dB a band (three bands an octave), since music has less there: a tuning knob.+static const float kTilt = 0.6f;+// How quickly a band eases towards its level, up and down, in seconds; the hill behind is slower. With Reduce+// Motion both ease over kStillEase.+static const double kFrontUp = 0.08, kFrontDown = 0.4, kBackUp = 0.3, kBackDown = 0.9, kStillEase = 3;+// No new bands for this long reads as silence (a pause, a stall, a tap that never ran).+static const double kStale = 0.3;+// The hills' height at their tallest and at rest, as shares of the screen's height; the one behind is taller.+static const CGFloat kFrontHeight = 0.24, kBackHeight = 0.3, kRestHeight = 0.012;+// Below this every band has settled (under 2 pt at the top of the front hill), and a paused song's link can stop.+static const float kSettled = 0.02f;+// Each band shares this much with either neighbour, twice over, so one loud band is a hill and not a spike.+static const float kSpread = 0.25f;+static const NSTimeInterval kTransitionSlack = 0.05;++static NSUInteger sg_readers;++// The reader on while any view is moving, so nothing is analysed while none is.+static void needReader(BOOL need) {+ if (need) {+ if (sg_readers++ == 0) {+ SGRSpectrumPrepare();+ SGAudioSetOutputReader(SGRSpectrumFeed);+ }+ } else if (sg_readers && --sg_readers == 0) {+ SGAudioSetOutputReader(NULL);+ }+}++static NSDictionary *noActions(void) {+ static NSDictionary *none;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ NSNull *off = NSNull.null;+ none = @{@"bounds": off, @"position": off, @"frame": off, @"path": off, @"colors": off};+ });+ return none;+}++@interface SGRVisualiserView : UIView <SGPlayerStateObserver>+// Where the hills stand, in points from the top: the screen's foot in the player. 0 is the bounds' foot.+@property (nonatomic) CGFloat baseline;+// The height the hills are a share of; 0 is the bounds' height.+@property (nonatomic) CGFloat screenHeight;+@property (nonatomic, readonly) BOOL blurred;+- (void)setBlurred:(BOOL)blurred animated:(BOOL)animated;+- (void)appear:(BOOL)animated;+- (void)disappear:(void (^)(void))done;+@end++@implementation SGRVisualiserView {+ UIView *_content; // the hills, faded in and out as one+ CAGradientLayer *_backFill, *_frontFill;+ CAShapeLayer *_backShape, *_frontShape;+ UIVisualEffectView *_lyricsBlur;+ CADisplayLink *_link;+ BOOL _reading, _idle;+ float _front[kBands], _back[kBands], _peak;+ uint64_t _generation;+ CFTimeInterval _fresh, _last;+ NSUInteger _palette;+}++// As PlayerMotion.x: what fades is the effect view's effect, never its alpha or an ancestor's.+static UIBlurEffect *blurEffect(void) {+ return [UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemUltraThinMaterialDark];+}++static CAGradientLayer *fill(CAShapeLayer *shape) {+ CAGradientLayer *layer = [CAGradientLayer layer];+ layer.actions = noActions();+ layer.startPoint = CGPointMake(0, 0.5);+ layer.endPoint = CGPointMake(1, 0.5);+ shape.actions = noActions();+ layer.mask = shape;+ return layer;+}++- (instancetype)initWithFrame:(CGRect)frame {+ if (!(self = [super initWithFrame:frame])) return nil;+ self.userInteractionEnabled = NO;+ self.accessibilityElementsHidden = YES;+ _peak = kPeakFloor;+ _content = [[UIView alloc] initWithFrame:frame];+ _backShape = [CAShapeLayer layer];+ _backFill = fill(_backShape);+ _backFill.opacity = 0.55f;+ [_content.layer addSublayer:_backFill];+ _frontShape = [CAShapeLayer layer];+ _frontFill = fill(_frontShape);+ [_content.layer addSublayer:_frontFill];+ [self addSubview:_content];+ _lyricsBlur = [[UIVisualEffectView alloc] initWithEffect:nil];+ _lyricsBlur.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ [self addSubview:_lyricsBlur];+ [self applyColors:@[UIColor.darkGrayColor, UIColor.darkGrayColor, UIColor.darkGrayColor, UIColor.darkGrayColor, UIColor.darkGrayColor]];++ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;+ for (NSNotificationName name in @[UIApplicationDidBecomeActiveNotification, UIApplicationWillResignActiveNotification,+ NSProcessInfoPowerStateDidChangeNotification, UIAccessibilityReduceMotionStatusDidChangeNotification]) {+ [center addObserver:self selector:@selector(updateMotionSoon) name:name object:nil];+ }+ [center addObserver:self selector:@selector(artworkChanged) name:SGRNowPlayingArtworkDidChangeNotification object:nil];+ SGRObservePlayerTransition(self, ^(id owner) { [owner updateMotion]; }, ^(id owner) { [owner updateMotion]; });+ SGAddPlayerStateObserver(self);+ [self artworkChanged];+ [self draw];+ return self;+}++- (void)dealloc {+ [NSNotificationCenter.defaultCenter removeObserver:self];+ [_link invalidate];+ if (_reading) needReader(NO);+}++#pragma mark - colour++// Bottom left, the whole cover and bottom right in front, the top two behind, so the hills read as the cover's+// lower half under its upper.+- (void)applyColors:(NSArray<UIColor *> *)colors {+ if (colors.count < 5) return;+ _frontFill.colors = @[(id)colors[2].CGColor, (id)colors[4].CGColor, (id)colors[3].CGColor];+ _backFill.colors = @[(id)colors[0].CGColor, (id)colors[1].CGColor];+}++- (void)artworkChanged {+ UIImage *image = SGRNowPlayingArtwork(NULL, NULL);+ if (!image) return;+ NSUInteger generation = ++_palette;+ SGRPaletteRequest request = {CGSizeZero, NO, YES, YES, NO};+ __weak SGRVisualiserView *weakSelf = self;+ [SGRPalette paletteForImage:image request:request completion:^(SGRPalette *palette) {+ SGRVisualiserView *view = weakSelf;+ if (!view || !palette.flowColors || generation != view->_palette) return;+ if (!view.window) {+ [view applyColors:palette.flowColors];+ return;+ }+ // The colours cross over as the field's do.+ [CATransaction begin];+ [CATransaction setAnimationDuration:SGRCrossfade];+ [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];+ for (CAGradientLayer *layer in @[view->_frontFill, view->_backFill]) {+ CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"colors"];+ fade.fromValue = (layer.presentationLayer ?: layer).colors;+ [layer addAnimation:fade forKey:@"colors"];+ }+ [view applyColors:palette.flowColors];+ [CATransaction commit];+ }];+}++#pragma mark - showing++- (void)setBaseline:(CGFloat)baseline {+ if (baseline == _baseline) return;+ _baseline = baseline;+ [self setNeedsLayout];+}++- (void)layoutSubviews {+ [super layoutSubviews];+ CGRect bounds = self.bounds;+ _content.frame = bounds;+ _lyricsBlur.frame = bounds;+ _backFill.frame = bounds;+ _frontFill.frame = bounds;+ _backShape.frame = bounds;+ _frontShape.frame = bounds;+ [self draw];+}++- (void)appear:(BOOL)animated {+ _content.alpha = 0;+ if (animated) SGRAnimate(SGRMotionFade, ^{ self->_content.alpha = 1; }, nil);+ else _content.alpha = 1;+}++- (void)disappear:(void (^)(void))done {+ SGRAnimate(SGRMotionFade, ^{+ self->_content.alpha = 0;+ self->_lyricsBlur.effect = nil;+ }, ^(BOOL finished) { done(); });+}++- (BOOL)blurred {+ return _lyricsBlur.effect != nil;+}++- (void)setBlurred:(BOOL)blurred animated:(BOOL)animated {+ void (^apply)(void) = ^{ self->_lyricsBlur.effect = blurred ? blurEffect() : nil; };+ if (animated) SGRAnimate(SGRMotionFade, apply, nil);+ else apply();+ [self updateMotion];+}++#pragma mark - moving++- (void)playerStateDidChange:(SPTPlayerState *)state {+ [self updateMotion];+}++- (void)didMoveToWindow {+ [super didMoveToWindow];+ [self updateMotion];+}++// The power state is reported off the main thread.+- (void)updateMotionSoon {+ dispatch_async(dispatch_get_main_queue(), ^{ [self updateMotion]; });+}++- (BOOL)settled {+ for (int band = 0; band < kBands; band++) if (_front[band] > kSettled || _back[band] > kSettled) return NO;+ return YES;+}++// Moving while it may and there is something to show: the song playing, or the hills still settling after it+// stopped. While the player animates, it comes back once the animation is expected to be over.+- (void)updateMotion {+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateMotion) object:nil];+ BOOL front = UIApplication.sharedApplication.applicationState == UIApplicationStateActive;+ BOOL may = self.window && front && !NSProcessInfo.processInfo.lowPowerModeEnabled;+ NSTimeInterval wait = SGPlayerTransitionEnds() - CACurrentMediaTime();+ if (may && (wait > 0 || SGRPlayerIsTransitioning())) {+ may = NO;+ // Without an expected end, the transition's ended notification brings it back.+ if (wait > 0) [self performSelector:@selector(updateMotion) withObject:nil afterDelay:wait + kTransitionSlack inModes:@[NSRunLoopCommonModes]];+ }+ BOOL playing = !SGPlayerState().isPaused;+ [self setMoving:may && (playing || !self.settled)];+ [self setReading:may && playing];+}++- (void)setReading:(BOOL)reading {+ if (reading == _reading) return;+ _reading = reading;+ needReader(reading);+}++- (void)setMoving:(BOOL)moving {+ if (moving) {+ if (!_link) {+ _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(tick:)];+ [_link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];+ _last = 0;+ }+ // Calmer behind the lyrics, whose own link runs at the display's rate, and calmest with Reduce Motion.+ // While a playing song sends nothing (a stall, or no tap at all), a few frames a second watch for it.+ float most = _idle ? 4 : SGRReduceMotion() ? 15 : _lyricsBlur.effect ? 30 : 60;+ _link.preferredFrameRateRange = CAFrameRateRangeMake(most / 2, most, most);+ } else if (_link) {+ [_link invalidate];+ _link = nil;+ }+}++static float ease(float value, float target, double dt, double up, double down) {+ double tau = target > value ? up : down;+ return value + (target - value) * (float)(1 - exp(-dt / tau));+}++- (void)tick:(CADisplayLink *)link {+ CFTimeInterval now = link.timestamp;+ double dt = _last ? MIN(now - _last, 0.1) : link.duration;+ _last = now;+ float levels[kBands];+ uint64_t generation = SGRSpectrumRead(levels);+ if (generation != _generation) {+ _generation = generation;+ _fresh = now;+ }+ BOOL silent = !_reading || now - _fresh > kStale;+ float loudest = kPeakFloor;+ for (int band = 0; band < kBands; band++) {+ levels[band] += kTilt * band;+ loudest = fmaxf(loudest, levels[band]);+ }+ if (!silent) _peak = fmaxf(fmaxf(loudest, _peak - kPeakFall * (float)dt), kPeakFloor);+ BOOL still = SGRReduceMotion();+ float targets[kBands];+ for (int band = 0; band < kBands; band++) targets[band] = silent ? 0 : fminf(1, fmaxf(0, (levels[band] - (_peak - kRange)) / kRange));+ for (int pass = 0; pass < 2; pass++) {+ float before = targets[0];+ for (int band = 0; band < kBands; band++) {+ float here = targets[band], next = targets[MIN(band + 1, kBands - 1)];+ targets[band] = kSpread * before + (1 - 2 * kSpread) * here + kSpread * next;+ before = here;+ }+ }+ for (int band = 0; band < kBands; band++) {+ float target = targets[band];+ _front[band] = ease(_front[band], target, dt, still ? kStillEase : kFrontUp, still ? kStillEase : kFrontDown);+ _back[band] = ease(_back[band], target, dt, still ? kStillEase : kBackUp, still ? kStillEase : kBackDown);+ }+ [self draw];+ BOOL idle = silent && self.settled;+ if (idle && !_idle) {+ // The last step down to rest, too small to see, so a settled hill is drawn exactly at rest.+ memset(_front, 0, sizeof _front);+ memset(_back, 0, sizeof _back);+ [self draw];+ }+ if (idle != _idle) {+ _idle = idle;+ [self updateMotion];+ }+}++#pragma mark - drawing++// A smooth line through the points (Catmull-Rom as cubic Béziers), closed down to the foot of the bounds.+static CGPathRef hillPath(const CGPoint *points, int count, CGFloat foot) {+ CGMutablePathRef path = CGPathCreateMutable();+ CGPathMoveToPoint(path, NULL, points[0].x, foot);+ CGPathAddLineToPoint(path, NULL, points[0].x, points[0].y);+ for (int i = 0; i < count - 1; i++) {+ CGPoint before = points[MAX(i - 1, 0)], from = points[i], to = points[i + 1], after = points[MIN(i + 2, count - 1)];+ CGPathAddCurveToPoint(path, NULL, from.x + (to.x - before.x) / 6, from.y + (to.y - before.y) / 6,+ to.x - (after.x - from.x) / 6, to.y - (after.y - from.y) / 6, to.x, to.y);+ }+ CGPathAddLineToPoint(path, NULL, points[count - 1].x, foot);+ CGPathCloseSubpath(path);+ return path;+}++// The bass in the middle, each band out to either side, the treble at the edges; a band's height eased in so+// quiet bands lie low and only the strong ones stand up.+static void shape(CAShapeLayer *layer, const float *bands, CGFloat width, CGFloat baseline, CGFloat foot, CGFloat tallest, CGFloat rest) {+ CGPoint points[kPoints];+ for (int i = 0; i < kPoints; i++) {+ float value = bands[abs(i - (kBands - 1))];+ CGFloat height = rest + (tallest - rest) * powf(value, 1.2f);+ points[i] = CGPointMake(width * i / (kPoints - 1), baseline - height);+ }+ CGPathRef path = hillPath(points, kPoints, foot);+ layer.path = path;+ CGPathRelease(path);+}++- (void)draw {+ CGRect bounds = self.bounds;+ if (bounds.size.width <= 0) return;+ CGFloat baseline = _baseline > 0 ? _baseline : bounds.size.height;+ CGFloat screen = _screenHeight > 0 ? _screenHeight : bounds.size.height;+ CGFloat foot = MAX(baseline, bounds.size.height), rest = round(screen * kRestHeight);+ [CATransaction begin];+ [CATransaction setDisableActions:YES];+ shape(_backShape, _back, bounds.size.width, baseline, foot, screen * kBackHeight, rest * 1.5);+ shape(_frontShape, _front, bounds.size.width, baseline, foot, screen * kFrontHeight, rest);+ [CATransaction commit];+}++@end++#pragma mark - in the player++static SGRVisualiserView *sg_view;++BOOL SGRPlayerVisualiserShowing(void) {+ return SGRPlayerBackground() == SGRPlayerBackgroundVisualiser;+}++UIView *SGRPlayerVisualiserPreview(void) {+ return [[SGRVisualiserView alloc] initWithFrame:CGRectZero];+}++// The hills from the top of the field to the foot of its bleed, standing on the screen's foot.+static void layOut(SGRArtworkField *field) {+ if (sg_view.superview != field) [field addSubview:sg_view];+ else if (field.subviews.lastObject != sg_view) [field bringSubviewToFront:sg_view];+ CGSize size = field.bounds.size;+ CGFloat screen = field.window.bounds.size.height ?: size.height;+ CGRect frame = CGRectMake(0, 0, size.width, MAX(size.height, screen) + field.bleed.bottom);+ if (!CGRectEqualToRect(sg_view.frame, frame)) sg_view.frame = frame;+ sg_view.baseline = screen;+ sg_view.screenHeight = screen;+}++void SGRPlayerVisualiserUpdate(void) {+ SGRArtworkField *field = SGRPlayerField();+ // Not over an Animated artwork clip still playing: the Player page can change the choice under it, which the+ // player takes up when it next starts.+ BOOL wanted = SGRPlayerVisualiserShowing() && field && !SGRPlayerMotionShowing();+ if (!wanted) {+ SGRVisualiserView *old = sg_view;+ sg_view = nil;+ if (old.window) [old disappear:^{ [old removeFromSuperview]; }];+ else [old removeFromSuperview];+ return;+ }+ BOOL made = !sg_view;+ if (made) sg_view = [[SGRVisualiserView alloc] initWithFrame:CGRectZero];+ layOut(field);+ if (made) {+ [sg_view setBlurred:SGRPlayerLyricsOpen() animated:NO];+ [sg_view appear:field.window != nil];+ SGLog(@"redesign player: visualiser on the field");+ } else {+ BOOL open = SGRPlayerLyricsOpen();+ if (open != sg_view.blurred) [sg_view setBlurred:open animated:sg_view.window != nil];+ }+}++#pragma mark - the ⋯ menu's switch++void SGRPlayerMenuSetBackground(SGRPlayerBackgroundKind kind) {+ SGRPlayerBackgroundKind current = SGRPlayerBackground();+ if (!SGPlayerMenuOffersAnimatedArtwork() || kind < SGRPlayerBackgroundFluid || kind == current) return;+ // Animated's own switch lets the clip go or looks it up, and calls back here.+ if (kind == SGRPlayerBackgroundAnimated || current == SGRPlayerBackgroundAnimated) SGPlayerMenuSetAnimatedArtwork(kind == SGRPlayerBackgroundAnimated);+ if (kind != SGRPlayerBackgroundAnimated) SGSetInt(SGRKeyPlayerBackground, kind);+ SGLog(@"redesign player: background switched to %@ from the menu", SGRPlayerBackgroundNames()[(NSUInteger)kind]);+ SGRPlayerHoldField();+ SGRPlayerVisualiserUpdate();+}diff --git a/tweak/Sources/Redesigned/Player/SGRSpectrum.h b/tweak/Sources/Redesigned/Player/SGRSpectrum.hnew file mode 100644index 00000000..c68445f5--- /dev/null+++ b/tweak/Sources/Redesigned/Player/SGRSpectrum.h@@ -0,0 +1,24 @@+// The player's Visualiser background (PlayerVisualiser.x) reads the sound through this: what Spotify's+// output plays, cut into SGRSpectrumBands bands spaced evenly in pitch from kLowest to kHighest Hz (SGRSpectrum.m),+// each band's level in dB, 0 dB being a full scale sine in it.+//+// Every 1024 samples the last 4096, through a Hann window and Accelerate's real FFT, are summed into the bands+// and published, so at 48 kHz about 47 times a second. Plain C, so harness/visualiser/ runs it on the Mac.+//+// Threading: SGRSpectrumPrepare on the main thread, once, before anything is fed. SGRSpectrumFeed on the render+// thread only, one thread at a time: it allocates nothing and takes no lock. SGRSpectrumRead from any thread.+// What it reads can mix two analyses, a band from each, which nothing drawn can show.+#import <stdint.h>++enum { SGRSpectrumBands = 24 };+// What a band reads with nothing in it, and the least SGRSpectrumRead hands out.+#define SGRSpectrumFloor (-100.0f)++// Makes the FFT's tables. Repeat calls do nothing. Lives as long as the process: the render thread may be in+// SGRSpectrumFeed at any time.+void SGRSpectrumPrepare(void);+// Samples, mono, at `sampleRate`. A new rate starts the window over. Does nothing before SGRSpectrumPrepare.+void SGRSpectrumFeed(const float *samples, uint32_t count, double sampleRate);+// The last levels into `levels`, low band first; answers how many analyses there have been, so a caller can+// tell when nothing new came (paused, or the tap never ran).+uint64_t SGRSpectrumRead(float levels[SGRSpectrumBands]);diff --git a/tweak/Sources/Redesigned/Player/SGRSpectrum.m b/tweak/Sources/Redesigned/Player/SGRSpectrum.mnew file mode 100644index 00000000..824d27b0--- /dev/null+++ b/tweak/Sources/Redesigned/Player/SGRSpectrum.m@@ -0,0 +1,101 @@+// The Visualiser's spectrum (SGRSpectrum.h): a ring of the last kSize samples, analysed every kHop.+#import <Accelerate/Accelerate.h>+#import <math.h>+#import <stdatomic.h>+#import <string.h>+#import "SGRSpectrum.h"++enum { kLog2Size = 12, kSize = 1 << kLog2Size, kHalf = kSize / 2, kHop = 1024 };+// The bands' edges: a kick's fundamental at the bottom, the air of cymbals at the top.+static const double kLowest = 50, kHighest = 14000;++// Main thread, once, before the render thread reads them.+static FFTSetup sg_setup;+static float sg_window[kSize];+static atomic_bool sg_prepared;++// The render thread's own.+static float sg_ring[kSize], sg_windowed[kSize], sg_real[kHalf], sg_imag[kHalf], sg_power[kHalf];+static uint32_t sg_at, sg_sinceLast, sg_filled;+static double sg_rate;+static uint32_t sg_from[SGRSpectrumBands], sg_to[SGRSpectrumBands]; // bins, the end not included++// Published.+static _Atomic(float) sg_levels[SGRSpectrumBands];+static _Atomic(uint64_t) sg_generation;++void SGRSpectrumPrepare(void) {+ if (atomic_load(&sg_prepared)) return;+ sg_setup = vDSP_create_fftsetup(kLog2Size, kFFTRadix2);+ vDSP_hann_window(sg_window, kSize, vDSP_HANN_DENORM);+ for (int band = 0; band < SGRSpectrumBands; band++) atomic_store(&sg_levels[band], SGRSpectrumFloor);+ atomic_store_explicit(&sg_prepared, true, memory_order_release);+}++// A band takes the bins whose middles are in it, and at least one, so the low bands, narrower than a bin, still+// read something; two of them can read the same bin.+static void setRate(double rate) {+ sg_rate = rate;+ sg_at = sg_sinceLast = sg_filled = 0;+ memset(sg_ring, 0, sizeof sg_ring);+ double binHz = rate / kSize, ratio = pow(kHighest / kLowest, 1.0 / SGRSpectrumBands);+ for (int band = 0; band < SGRSpectrumBands; band++) {+ double low = kLowest * pow(ratio, band), high = low * ratio;+ uint32_t from = (uint32_t)fmax(1, ceil(low / binHz)), to = (uint32_t)fmin(kHalf, ceil(high / binHz));+ if (from >= kHalf) from = kHalf - 1;+ sg_from[band] = from;+ sg_to[band] = to > from ? to : from + 1;+ }+}++// The power over a band, summed, as a full scale sine's: a Hann window keeps 3/8 of a sine's power over its+// bins, and vDSP's real FFT gives twice the DFT, so a sine of amplitude A sums to 3/8 * kSize^2 * A^2 here.+static void analyse(void) {+ // The ring from its oldest sample, windowed.+ uint32_t tail = kSize - sg_at;+ vDSP_vmul(sg_ring + sg_at, 1, sg_window, 1, sg_windowed, 1, tail);+ vDSP_vmul(sg_ring, 1, sg_window + tail, 1, sg_windowed + tail, 1, sg_at);+ DSPSplitComplex split = {sg_real, sg_imag};+ vDSP_ctoz((const DSPComplex *)sg_windowed, 2, &split, 1, kHalf);+ vDSP_fft_zrip(sg_setup, &split, 1, kLog2Size, kFFTDirection_Forward);+ // The first bin's imaginary part is the Nyquist bin's real one, which no band reaches.+ sg_imag[0] = 0;+ vDSP_zvmags(&split, 1, sg_power, 1, kHalf);+ const float scale = 1.0f / (0.375f * (float)kSize * (float)kSize);+ for (int band = 0; band < SGRSpectrumBands; band++) {+ float sum = 0;+ vDSP_sve(sg_power + sg_from[band], 1, &sum, sg_to[band] - sg_from[band]);+ float level = sum > 0 ? 10 * log10f(sum * scale) : SGRSpectrumFloor;+ atomic_store_explicit(&sg_levels[band], fmaxf(SGRSpectrumFloor, level), memory_order_relaxed);+ }+ atomic_fetch_add_explicit(&sg_generation, 1, memory_order_release);+}++void SGRSpectrumFeed(const float *samples, uint32_t count, double sampleRate) {+ if (!samples || sampleRate <= 0 || !atomic_load_explicit(&sg_prepared, memory_order_acquire)) return;+ if (sampleRate != sg_rate) setRate(sampleRate);+ while (count) {+ uint32_t run = count;+ if (run > kSize - sg_at) run = kSize - sg_at;+ if (run > kHop - sg_sinceLast) run = kHop - sg_sinceLast;+ memcpy(sg_ring + sg_at, samples, run * sizeof(float));+ samples += run;+ count -= run;+ sg_at = (sg_at + run) & (kSize - 1);+ sg_sinceLast += run;+ if (sg_filled < kSize) sg_filled += run;+ if (sg_sinceLast == kHop) {+ sg_sinceLast = 0;+ // Not before the ring is full once: a window half of zeros would read a step in the sound.+ if (sg_filled >= kSize) analyse();+ }+ }+}++uint64_t SGRSpectrumRead(float levels[SGRSpectrumBands]) {+ uint64_t generation = atomic_load_explicit(&sg_generation, memory_order_acquire);+ for (int band = 0; band < SGRSpectrumBands; band++) {+ levels[band] = atomic_load_explicit(&sg_levels[band], memory_order_relaxed);+ }+ return generation;+}diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffects.h b/tweak/Sources/Shared/AudioEffects/AudioEffects.hindex 1093be37..ddb4b44c 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffects.h+++ b/tweak/Sources/Shared/AudioEffects/AudioEffects.h@@ -11,7 +11,8 @@// value and hands the effect it belongs to to the engine, which re-reads that effect's keys off the main// thread. The engine is made the first time Spotify starts its output with the master switch on.//-// Threading: everything here is main thread, except SGDSPStatus and SGDSPError, which any thread may call.+// Threading: everything here is main thread, except SGDSPStatus, SGDSPError and SGAudioSetOutputReader, which any+// thread may call.#import <Foundation/Foundation.h>#pragma mark - keys@@ -138,3 +139,15 @@ NSString *SGDSPError(NSString *switchKey);void SGDSPEqualizerResponse(NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *decibels);// The compander's amounts drawn as a smooth curve, the same way.void SGDSPCompanderResponse(NSArray<NSNumber *> *gains, NSInteger count, double *frequencies, double *values);++#pragma mark - the output's sound, read++// Called on the render thread with what Spotify's music output plays (SGPlayerMusicOutput), after the effects+// (and Speed and pitch, and Sing): each buffer the notify sees, mixed to mono, as floats, in runs of up to 4096+// frames, at the output's rate; zeros for a buffer marked silent. It runs whether the master switch is on or off,+// but only once Spotify has started its output, and never when Shared/Player cannot reach Spotify's output. It must not allocate, lock, block or+// send an Objective-C message.+typedef void (*SGAudioOutputReader)(const float *samples, uint32_t count, double sampleRate);+// One reader at a time; NULL takes it off. Any thread. A reader taken off can still be in a call that began+// before, so what it touches has to outlive it.+void SGAudioSetOutputReader(SGAudioOutputReader reader);diff --git a/tweak/Sources/Shared/AudioEffects/AudioEffects.x b/tweak/Sources/Shared/AudioEffects/AudioEffects.xindex 4dea0be6..afd3a8a6 100644--- a/tweak/Sources/Shared/AudioEffects/AudioEffects.x+++ b/tweak/Sources/Shared/AudioEffects/AudioEffects.x@@ -8,7 +8,9 @@// reads the buffer bound for the speaker into float lanes, runs the engine over them and writes them back, in// place: the way the first version of Pitch worked on the phone. A notify stays on a unit that was the music's// once and does nothing there, so one engine never runs on two render threads. Speed and pitch feeds the-// unit's input, so its sound reaches the notify changed.+// unit's input, so its sound reaches the notify changed. After the engine, with the switch on or off, the notify+// hands the music's buffer mixed to mono to one reader (SGAudioSetOutputReader), the player's Visualiser, which+// only reads it.//// The engine is made the first time the output starts with the master switch on, at the output's rate,// and lives as long as Spotify: the render thread may be holding it at any time. With the switch off the@@ -108,6 +110,14 @@ static BOOL anySound(const float *samples, UInt32 count) {return NO;}+static BOOL laidOut(const AudioBufferList *data, UInt32 frames, UInt32 channels, UInt32 bytes, BOOL split) {+ BOOL fits = split ? data->mNumberBuffers == channels : data->mNumberBuffers == 1 && data->mBuffers[0].mNumberChannels == channels;+ for (UInt32 b = 0; fits && b < data->mNumberBuffers; b++) {+ fits = data->mBuffers[b].mData && data->mBuffers[b].mDataByteSize == frames * bytes * (split ? 1 : channels);+ }+ return fits;+}+// The buffer through the engine in place, whatever its format: the buffers themselves as the engine's lanes// when they are float, one per channel (the hardware's usual), otherwise read into the scratch lanes and// written back. The first two channels are the engine's; a mono output is fed to both and gets their mean.@@ -120,11 +130,7 @@ static void processBuffer(SGDSPEngine *engine, AudioUnitRenderActionFlags *flagsif ((bytes != 2 && bytes != 4) || channels < 1) return;// Buffers not laid out as the format says are left alone rather than read as noise: the format read at// the start can be a moment old.- BOOL fits = split ? data->mNumberBuffers == channels : data->mNumberBuffers == 1 && data->mBuffers[0].mNumberChannels == channels;- for (UInt32 b = 0; fits && b < data->mNumberBuffers; b++) {- fits = data->mBuffers[b].mData && data->mBuffers[b].mDataByteSize == frames * bytes * (split ? 1 : channels);- }- if (!fits) {+ if (!laidOut(data, frames, channels, bytes, split)) {atomic_fetch_add_explicit(&sg_skipped, 1, memory_order_relaxed);return;}@@ -168,16 +174,49 @@ static void processBuffer(SGDSPEngine *engine, AudioUnitRenderActionFlags *flagsif (loud) *flags &= ~kAudioUnitRenderAction_OutputIsSilence;}-// `refCon` is the unit; only the music's output is processed.+#pragma mark - the output's sound, read (AudioEffects.h)++static _Atomic(SGAudioOutputReader) sg_reader;+static float sg_mono[kScratchFrames];++void SGAudioSetOutputReader(SGAudioOutputReader reader) {+ atomic_store_explicit(&sg_reader, reader, memory_order_release);+}++// The buffer, as the effects left it, mixed to mono for the reader: its first two channels, or its one.+static void readOut(SGAudioOutputReader reader, AudioUnitRenderActionFlags flags, UInt32 frames, const AudioBufferList *data) {+ uint64_t layout = atomic_load_explicit(&sg_layout, memory_order_relaxed);+ UInt32 formatFlags = (UInt32)layout, channels = (UInt32)(layout >> 32) & 0xffff, bytes = (UInt32)(layout >> 48);+ BOOL isFloat = (formatFlags & kAudioFormatFlagIsFloat) != 0, split = (formatFlags & kAudioFormatFlagIsNonInterleaved) != 0;+ UInt32 fraction = (formatFlags & kLinearPCMFormatFlagsSampleFractionMask) >> kLinearPCMFormatFlagsSampleFractionShift;+ if ((bytes != 2 && bytes != 4) || channels < 1 || !laidOut(data, frames, channels, bytes, split)) return;+ BOOL silent = (flags & kAudioUnitRenderAction_OutputIsSilence) != 0;+ double rate = loadDouble(&sg_rateBits);+ const void *first = data->mBuffers[0].mData, *second = split && channels > 1 ? data->mBuffers[1].mData : first;+ UInt32 stride = split ? 1 : channels, secondOffset = !split && channels > 1 ? 1 : 0;+ for (UInt32 done = 0; done < frames;) {+ UInt32 count = MIN(frames - done, (UInt32)kScratchFrames);+ for (UInt32 i = 0; i < count; i++) {+ UInt32 at = (done + i) * stride;+ sg_mono[i] = silent ? 0 : 0.5f * (readSample(first, at, bytes, isFloat, fraction) + readSample(second, at + secondOffset, bytes, isFloat, fraction));+ }+ reader(sg_mono, count, rate);+ done += count;+ }+}++// `refCon` is the unit; only the music's output is processed and read.static OSStatus rendered(void *refCon, AudioUnitRenderActionFlags *flags, const AudioTimeStamp *timestamp, UInt32 bus,UInt32 frames, AudioBufferList *data) {if (!(*flags & kAudioUnitRenderAction_PostRender) || bus != 0 || !data || !data->mNumberBuffers || !frames) return noErr;if (refCon != SGPlayerMusicOutput()) return noErr;- if (!atomic_load_explicit(&sg_running, memory_order_acquire)) return noErr;- SGDSPEngine *engine = atomic_load_explicit(&sg_engine, memory_order_acquire);- // A new rate is being set up on the queue: until then the sound passes as it is.- if (!engine || SGDSPEngineSampleRate(engine) != loadDouble(&sg_rateBits)) return noErr;- processBuffer(engine, flags, frames, data);+ if (atomic_load_explicit(&sg_running, memory_order_acquire)) {+ SGDSPEngine *engine = atomic_load_explicit(&sg_engine, memory_order_acquire);+ // A new rate is being set up on the queue: until then the sound passes as it is.+ if (engine && SGDSPEngineSampleRate(engine) == loadDouble(&sg_rateBits)) processBuffer(engine, flags, frames, data);+ }+ SGAudioOutputReader reader = atomic_load_explicit(&sg_reader, memory_order_acquire);+ if (reader) readOut(reader, *flags, frames, data);return noErr;}diff --git a/tweak/Sources/Shared/Player/SpeedPitch.h b/tweak/Sources/Shared/Player/SpeedPitch.hindex dba0a182..278b628a 100644--- a/tweak/Sources/Shared/Player/SpeedPitch.h+++ b/tweak/Sources/Shared/Player/SpeedPitch.h@@ -50,8 +50,9 @@ float SGPlayerReverb(void);void SGPlayerSetReverb(float amount);// The redesign's Animated artwork, switched in the same block: whether the player offers the switch (the-// redesign is running and its background is Fluid or Animated, the two that share a field), whether it is-// on, and switching it, which applies at once and is stored as the Background choice. Defined by+// redesign is running and its background is Fluid, Animated or Visualiser, the three that share a field),+// whether it is on, and switching it, which applies at once and is stored as the Background choice (off is+// Fluid, and from the Visualiser changes nothing). Defined by// Redesigned/Player/PlayerMotion.x; NO from the first under the native look.BOOL SGPlayerMenuOffersAnimatedArtwork(void);BOOL SGPlayerMenuAnimatedArtwork(void);