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 lock screen accepts Canvas in its own shape and from later reports
My-Name-Is-Jeff95ba579f5a81
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 42d2d414..302563c2 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -130,7 +130,13 @@ Shared:(SGMotionCatalog.m), kept as local files (SGMotionStore.m), on iOS 26 the lock screen's full-screenartwork (LockScreenMotion.x). With Every song, a song with neither gets its cover over copies of itblurred and swaying, a seamless 8 s 3:4 loop drawn on the CPU only when the lock screen asks for it- and kept per picture (SGFluidClip.m). Rendered on the Mac against harness/fluid-clip/+ and kept per picture (SGFluidClip.m). Rendered on the Mac against harness/fluid-clip/. A track whose+ metadata names no Canvas has it asked of Spotify's Canvas service (MotionSources.m); each track is+ looked up again when its Canvas comes in a later state, and the next track's clip is fetched ahead+ (SGMotionFollower.m). The lock screen takes a clip under a key the system lists, cut to that key's+ shape when it is not, with its still filled to the size asked (SGMotionClip.m), and a change of the+ choice applies at once, but to or from Lyrics. The cut and the service's wire format are checked on+ the Mac against harness/motion/LocalFiles/ local files (LocalFiles.h lists its files): Edit info in the player's ⋯ menu, the table's footerunder Speed and pitch, which closes the menu and opens a form sheet (the three names, the coverwith a menu to change it, Restore file's info; nothing is stored before Save, and a swipe awaydiff --git a/harness/motion/README.md b/harness/motion/README.mdnew file mode 100644index 00000000..b54f852f--- /dev/null+++ b/harness/motion/README.md@@ -0,0 +1,13 @@+# Moving artwork harness++`SGMotionClip.m`, the steps of moving artwork that need no phone, run on the Mac: the size of the cut+for each shape, a 9:16 stand-in Canvas cut to 3:4 and read back (720 x 960, every frame, its length, and+by the colour of its bands that it was cut about its middle, not squeezed), the same Canvas stored on its+side, the request for Spotify's Canvas service and its replies (a still then a video, each video type,+a GIF, empty and foreign replies), and when a Canvas that turned up late is asked for, for each order of+the sources.++ ./build.sh && build/motion++The clips land in `build/clips/`. It prints how long the cut took,+on the Mac this was written on (about 10 s for a 10 s clip); it was not timed on a phone.diff --git a/harness/motion/build.sh b/harness/motion/build.shnew file mode 100755index 00000000..aedd244e--- /dev/null+++ b/harness/motion/build.sh@@ -0,0 +1,10 @@+#!/bin/sh+# Builds the moving artwork harness for the Mac: SGMotionClip.m as the tweak compiles it, with the+# protobuf reader it uses, and main.m.+set -e+cd "$(dirname "$0")"+mkdir -p build+xcrun clang -fobjc-arc -O2 -I ../../tweak/Sources \+ -framework Foundation -framework AVFoundation -framework CoreMedia -framework CoreVideo -framework CoreGraphics \+ main.m ../../tweak/Sources/Shared/AnimatedArtwork/SGMotionClip.m ../../tweak/Sources/Shared/AdBlock/Protobuf.m \+ -o build/motiondiff --git a/harness/motion/main.m b/harness/motion/main.mnew file mode 100644index 00000000..e68f6e3d--- /dev/null+++ b/harness/motion/main.m@@ -0,0 +1,198 @@+// Runs the steps of moving artwork that need no phone (Shared/AnimatedArtwork/SGMotionClip.m) on the Mac:+// the cut's size, a tall clip cut to 3:4 and read back (its size, its frames, and that it was cut about its+// middle rather than squeezed), a clip stored on its side, Spotify's Canvas service's request and reply,+// and when a Canvas that turned up late is asked for. Exits 1 on any failure.+#import <AVFoundation/AVFoundation.h>+#import "Shared/AdBlock/Protobuf.h"+#import "Shared/AnimatedArtwork/SGMotionClip.h"++static int failures;++static void check(BOOL ok, NSString *what) {+ printf(" %s %s\n", ok ? "ok " : "FAIL", what.UTF8String);+ if (!ok) failures++;+}++// A stand-in Canvas, `size` as stored, of `count` frames at 30 fps, in three bands from the top as shown:+// red to a quarter, green to three quarters, blue below. `turn` stands it up when it is stored on its side.+static BOOL writeBands(NSURL *file, CGSize size, int count, CGAffineTransform turn, BOOL sideways) {+ [NSFileManager.defaultManager removeItemAtURL:file error:nil];+ AVAssetWriter *writer = [AVAssetWriter assetWriterWithURL:file fileType:AVFileTypeMPEG4 error:nil];+ AVAssetWriterInput *input = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:@{+ AVVideoCodecKey: AVVideoCodecTypeH264, AVVideoWidthKey: @(size.width), AVVideoHeightKey: @(size.height),+ }];+ input.transform = turn;+ AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:input+ sourcePixelBufferAttributes:@{(id)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA),+ (id)kCVPixelBufferWidthKey: @(size.width), (id)kCVPixelBufferHeightKey: @(size.height)}];+ [writer addInput:input];+ [writer startWriting];+ [writer startSessionAtSourceTime:kCMTimeZero];+ for (int i = 0; i < count; i++) {+ while (!input.readyForMoreMediaData) [NSThread sleepForTimeInterval:0.002];+ CVPixelBufferRef buffer = NULL;+ CVPixelBufferPoolCreatePixelBuffer(NULL, adaptor.pixelBufferPool, &buffer);+ CVPixelBufferLockBaseAddress(buffer, 0);+ uint8_t *base = CVPixelBufferGetBaseAddress(buffer);+ size_t row = CVPixelBufferGetBytesPerRow(buffer);+ for (size_t y = 0; y < size.height; y++) {+ for (size_t x = 0; x < size.width; x++) {+ // Along the shown picture's height: the stored rows, or, on its side, the stored columns.+ double along = sideways ? (double)x / size.width : (double)y / size.height;+ uint8_t *pixel = base + y * row + x * 4; // BGRA+ pixel[0] = along >= 0.75 ? 255 : 0;+ pixel[1] = along >= 0.25 && along < 0.75 ? 255 : 0;+ pixel[2] = along < 0.25 ? 255 : 0;+ pixel[3] = 255;+ }+ }+ CVPixelBufferUnlockBaseAddress(buffer, 0);+ [adaptor appendPixelBuffer:buffer withPresentationTime:CMTimeMake(i, 30)];+ CVPixelBufferRelease(buffer);+ }+ [input markAsFinished];+ dispatch_semaphore_t done = dispatch_semaphore_create(0);+ [writer finishWritingWithCompletionHandler:^{ dispatch_semaphore_signal(done); }];+ dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);+ return writer.status == AVAssetWriterStatusCompleted;+}++static AVAssetTrack *videoOf(NSURL *file) {+ __block AVAssetTrack *track = nil;+ dispatch_semaphore_t loaded = dispatch_semaphore_create(0);+ [[AVURLAsset assetWithURL:file] loadTracksWithMediaType:AVMediaTypeVideo completionHandler:^(NSArray *tracks, NSError *error) {+ track = tracks.firstObject;+ dispatch_semaphore_signal(loaded);+ }];+ dispatch_semaphore_wait(loaded, DISPATCH_TIME_FOREVER);+ return track;+}++static int framesIn(NSURL *file) {+ AVAssetTrack *track = videoOf(file);+ AVAssetReader *reader = [AVAssetReader assetReaderWithAsset:track.asset error:nil];+ AVAssetReaderTrackOutput *output = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:track outputSettings:nil];+ [reader addOutput:output];+ [reader startReading];+ int count = 0;+ CMSampleBufferRef sample;+ while ((sample = [output copyNextSampleBuffer])) {+ if (CMSampleBufferGetNumSamples(sample)) count++;+ CFRelease(sample);+ }+ return count;+}++// The colour at `y`, a share of the shown picture's height, in its middle column: 'r', 'g', 'b' or '?'.+static char colourAt(NSURL *file, double y) {+ AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:[AVURLAsset assetWithURL:file]];+ generator.appliesPreferredTrackTransform = YES;+ generator.requestedTimeToleranceBefore = generator.requestedTimeToleranceAfter = kCMTimeZero;+ __block CGImageRef image = NULL;+ dispatch_semaphore_t made = dispatch_semaphore_create(0);+ [generator generateCGImageAsynchronouslyForTime:kCMTimeZero completionHandler:^(CGImageRef frame, CMTime actual, NSError *error) {+ image = frame ? CGImageRetain(frame) : NULL;+ dispatch_semaphore_signal(made);+ }];+ dispatch_semaphore_wait(made, DISPATCH_TIME_FOREVER);+ if (!image) return '?';+ size_t width = CGImageGetWidth(image), height = CGImageGetHeight(image);+ uint8_t pixel[4] = {0};+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);+ CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, space, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);+ // The one pixel wanted lands on the 1x1 context: Core Graphics counts rows from the bottom.+ CGContextDrawImage(context, CGRectMake(-(double)(width / 2), -(double)height * (1 - y), width, height), image);+ CGContextRelease(context);+ CGColorSpaceRelease(space);+ CGImageRelease(image);+ if (pixel[0] > 160 && pixel[1] < 90 && pixel[2] < 90) return 'r';+ if (pixel[1] > 160 && pixel[0] < 90 && pixel[2] < 90) return 'g';+ if (pixel[2] > 160 && pixel[0] < 90 && pixel[1] < 90) return 'b';+ return '?';+}++static CGSize shownSize(AVAssetTrack *track) {+ CGRect shown = CGRectApplyAffineTransform((CGRect){CGPointZero, track.naturalSize}, track.preferredTransform);+ return CGSizeMake(fabs(shown.size.width), fabs(shown.size.height));+}++int main(void) {+ @autoreleasepool {+ printf("the cut\n");+ check(CGSizeEqualToSize(SGMotionClipCut(CGSizeMake(720, 1280), 0.75), CGSizeMake(720, 960)), @"a 9:16 Canvas to 3:4 keeps its width");+ check(CGSizeEqualToSize(SGMotionClipCut(CGSizeMake(1000, 1000), 0.75), CGSizeMake(750, 1000)), @"a square to 3:4 keeps its height");+ check(CGSizeEqualToSize(SGMotionClipCut(CGSizeMake(720, 1280), 1), CGSizeMake(720, 720)), @"a 9:16 Canvas to 1:1");+ CGSize odd = SGMotionClipCut(CGSizeMake(721, 1281), 0.75);+ check((int)odd.width % 2 == 0 && (int)odd.height % 2 == 0 && odd.width <= 721 && odd.height <= 1281, @"odd sides come out even, inside the picture");+ check(CGSizeEqualToSize(SGMotionClipCut(CGSizeZero, 0.75), CGSizeZero), @"no picture, no cut");++ NSURL *folder = [NSURL fileURLWithPath:@"build/clips" isDirectory:YES];+ [NSFileManager.defaultManager createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:nil];+ NSURL *tall = [folder URLByAppendingPathComponent:@"canvas-9x16.mp4"], *cut = [folder URLByAppendingPathComponent:@"canvas-3x4.mp4"];+ printf("a 9:16 Canvas cut to 3:4\n");+ check(writeBands(tall, CGSizeMake(720, 1280), 60, CGAffineTransformIdentity, NO), @"the stand-in Canvas written");+ CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();+ BOOL shaped = SGMotionClipShape(tall, 0.75, cut);+ printf(" (cut in %.0f ms)\n", (CFAbsoluteTimeGetCurrent() - start) * 1000);+ check(shaped, @"cut and written");+ AVAssetTrack *track = videoOf(cut);+ check(CGSizeEqualToSize(shownSize(track), CGSizeMake(720, 960)), [NSString stringWithFormat:@"720 x 960 (%@)", NSStringFromSize(shownSize(track))]);+ check(framesIn(cut) == 60 && framesIn(tall) == 60, [NSString stringWithFormat:@"every frame kept (%d of %d)", framesIn(cut), framesIn(tall)]);+ check(fabs(CMTimeGetSeconds(track.timeRange.duration) - 2) < 0.05, [NSString stringWithFormat:@"2 s long (%.3f)", CMTimeGetSeconds(track.timeRange.duration)]);+ // Cut about the middle, 160 rows off each end, the bands sit at 0-1/6, 1/6-5/6 and 5/6-1; squeezed+ // they would sit at 0-1/4, 1/4-3/4 and 3/4-1.+ NSString *seen = [NSString stringWithFormat:@"%c%c%c%c", colourAt(cut, 0.08), colourAt(cut, 0.21), colourAt(cut, 0.79), colourAt(cut, 0.92)];+ check([seen isEqualToString:@"rggb"], [NSString stringWithFormat:@"cut about its middle, not squeezed (%@ at 8, 21, 79, 92 %%; rggb wanted)", seen]);+ check(![NSFileManager.defaultManager fileExistsAtPath:[cut URLByAppendingPathExtension:@"partial"].path], @"no partial file left");+ check(!SGMotionClipShape([folder URLByAppendingPathComponent:@"missing.mp4"], 0.75, [folder URLByAppendingPathComponent:@"none.mp4"]),+ @"a file that is not there is not cut");++ printf("a Canvas stored on its side\n");+ NSURL *side = [folder URLByAppendingPathComponent:@"canvas-side.mp4"], *sideCut = [folder URLByAppendingPathComponent:@"canvas-side-3x4.mp4"];+ // Stored 1280 x 720 and turned a quarter: shown 720 x 1280.+ CGAffineTransform quarter = CGAffineTransformMake(0, 1, -1, 0, 720, 0);+ check(writeBands(side, CGSizeMake(1280, 720), 30, quarter, YES), @"written");+ check(CGSizeEqualToSize(shownSize(videoOf(side)), CGSizeMake(720, 1280)), @"shown 720 x 1280");+ check(SGMotionClipShape(side, 0.75, sideCut), @"cut and written");+ AVAssetTrack *sideTrack = videoOf(sideCut);+ check(CGSizeEqualToSize(shownSize(sideTrack), CGSizeMake(720, 960)), [NSString stringWithFormat:@"shown 720 x 960 (%@, stored %@)",+ NSStringFromSize(shownSize(sideTrack)), NSStringFromSize(sideTrack.naturalSize)]);+ NSString *sideSeen = [NSString stringWithFormat:@"%c%c%c%c", colourAt(sideCut, 0.08), colourAt(sideCut, 0.21), colourAt(sideCut, 0.79), colourAt(sideCut, 0.92)];+ check([sideSeen isEqualToString:@"rggb"], [NSString stringWithFormat:@"stood up and cut about its middle (%@)", sideSeen]);++ printf("Spotify's Canvas service\n");+ NSData *ask = SGMotionCanvasAsk(@"spotify:track:x");+ const uint8_t wanted[] = {0x0a, 0x11, 0x0a, 0x0f, 's', 'p', 'o', 't', 'i', 'f', 'y', ':', 't', 'r', 'a', 'c', 'k', ':', 'x'};+ check([ask isEqualToData:[NSData dataWithBytes:wanted length:sizeof wanted]], [NSString stringWithFormat:@"the request: an entity naming the track (%@)", ask]);+ check(SGMotionCanvasAsk(nil) == nil, @"no track, no request");+ NSData *(^canvas)(NSString *, int) = ^NSData *(NSString *address, int type) {+ NSMutableArray *fields = [NSMutableArray arrayWithObjects:SGPBString(1, @"id"), SGPBString(2, address), SGPBString(3, @"file"), nil];+ if (type) [fields addObject:SGPBVarint(4, type)];+ return SGPBSerialize(@[SGPBBytes(1, SGPBSerialize(fields))]);+ };+ NSMutableData *both = [canvas(@"https://canvaz.scdn.co/still.jpg", 0) mutableCopy];+ [both appendData:canvas(@"https://canvaz.scdn.co/loop.mp4", 2)];+ check([SGMotionCanvasInReply(both) isEqualToString:@"https://canvaz.scdn.co/loop.mp4"], @"a still then a video: the video");+ check([SGMotionCanvasInReply(canvas(@"https://canvaz.scdn.co/v.mp4", 1)) isEqualToString:@"https://canvaz.scdn.co/v.mp4"], @"type 1 is a video");+ check([SGMotionCanvasInReply(canvas(@"https://canvaz.scdn.co/v.mp4", 3)) isEqualToString:@"https://canvaz.scdn.co/v.mp4"], @"type 3 is a video");+ check(SGMotionCanvasInReply(canvas(@"https://canvaz.scdn.co/a.gif", 4)) == nil, @"a GIF is no clip");+ check(SGMotionCanvasInReply(canvas(@"https://canvaz.scdn.co/still.jpg", 0)) == nil, @"a still alone is no clip");+ check(SGMotionCanvasInReply(canvas(@"", 2)) == nil, @"a video with no address is no clip");+ check(SGMotionCanvasInReply([NSData data]) == nil, @"an empty reply");+ check(SGMotionCanvasInReply([@"<html>not found" dataUsingEncoding:NSUTF8StringEncoding]) == nil, @"a page that is not a reply");+ check(SGMotionCanvasInReply(nil) == nil, @"no reply");++ printf("a Canvas that turns up late\n");+ NSArray *canvasFirst = @[@"canvas", @"applemusic"], *appleFirst = @[@"applemusic", @"canvas"];+ check(SGMotionCanvasOutranks(canvasFirst, nil), @"nothing showing: asked");+ check(SGMotionCanvasOutranks(canvasFirst, @"applemusic"), @"Apple Music's below Canvas showing: asked");+ check(!SGMotionCanvasOutranks(canvasFirst, @"canvas"), @"the Canvas already showing: not asked");+ check(!SGMotionCanvasOutranks(appleFirst, @"applemusic"), @"Apple Music's above Canvas showing: not asked");+ check(SGMotionCanvasOutranks(appleFirst, nil), @"Apple Music first with nothing: asked");+ check(!SGMotionCanvasOutranks(@[@"applemusic"], nil), @"Canvas switched off: not asked");+ check(!SGMotionCanvasOutranks(@[], nil), @"no sources: not asked");++ printf(failures ? "motion: %d FAILED\n" : "motion: all passed\n", failures);+ return failures ? 1 : 0;+ }+}diff --git a/harness/player/build.sh b/harness/player/build.shindex bbbf4311..2b26d36f 100755--- a/harness/player/build.sh+++ b/harness/player/build.sh@@ -20,12 +20,13 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar"$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGViewTree.m "$SRC"/Core/SGGlass.m \"$SRC"/Core/SGBackdrop.m "$SRC"/Core/SGFlagForce.m "$SRC"/Core/SGUIMode.m \"$SRC"/Redesigned/Kit/SGRTokens.m "$SRC"/Redesigned/Kit/SGRPalette.m "$SRC"/Redesigned/Kit/SGRField.m "$SRC"/Redesigned/Kit/SGRFlow.m "$SRC"/Redesigned/Kit/SGRFluid.m "$SRC"/Shared/AnimatedArtwork/SGMotionCatalog.m "$SRC"/Shared/AnimatedArtwork/SGMotionStore.m \+ "$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"/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 UIKit -framework QuartzCore -framework CoreGraphics -framework CoreImage -framework Foundation -framework Symbols -framework AVFoundation -framework CoreMedia -framework CoreVideo \-o "$OUT/PlayerHarness.app/PlayerHarness"cat > "$OUT/PlayerHarness.app/Info.plist" <<'PLIST'diff --git a/harness/player/stubs.m b/harness/player/stubs.mindex d6092968..1e15f5b0 100644--- a/harness/player/stubs.m+++ b/harness/player/stubs.m@@ -170,12 +170,19 @@ NSString *SGSingModelSizeText(void) { return @""; }void SGSingDownloadModel(void) {}void SGSingCancelModelDownload(void) {}-// MotionSources.m: the default order, Canvas then Apple Music, over the catalog the harness builds.+// MotionSources.m: the default order, Canvas then Apple Music, over the catalog the harness builds. No+// Canvas service: a track whose metadata names no Canvas goes to Apple Music.#import "Shared/AnimatedArtwork/AnimatedArtwork.h"-void SGMotionClipFor(NSURL *canvas, NSString *artist, NSString *album, SGMotionShape shape, CGFloat pixels, void (^done)(NSURL *file)) {- void (^apple)(void) = ^{ SGMotionAlbumCover(artist, album, shape, pixels, done); };+NSArray<NSString *> *SGMotionSourceOrder(void) { return @[@"canvas", @"applemusic"]; }+NSURL *SGMotionCanvasIn(NSDictionary *metadata) {+ id address = metadata[@"canvas.url"];+ return [metadata[@"canvas.type"] hasPrefix:@"VIDEO"] && [address isKindOfClass:NSString.class] ? [NSURL URLWithString:address] : nil;+}+void SGMotionClipFor(NSString *uri, NSURL *canvas, NSString *artist, NSString *album, SGMotionShape shape, CGFloat pixels,+ void (^done)(NSURL *file, NSString *source)) {+ void (^apple)(void) = ^{ SGMotionAlbumCover(artist, album, shape, pixels, ^(NSURL *file) { done(file, file ? @"applemusic" : nil); }); };if (!canvas) { apple(); return; }- SGMotionFile(canvas, ^(NSURL *file) { if (file) done(file); else apple(); });+ SGMotionFile(canvas, ^(NSURL *file) { if (file) done(file, @"canvas"); else apple(); });}// The Artwork sources row as a link to nowhere, so the Player page's rows under the card can be counted.#import "Settings/SGModPage.h"diff --git a/tweak/Sources/Redesigned/Player/PlayerMotion.x b/tweak/Sources/Redesigned/Player/PlayerMotion.xindex ccce4aca..bb32abe7 100644--- a/tweak/Sources/Redesigned/Player/PlayerMotion.x+++ b/tweak/Sources/Redesigned/Player/PlayerMotion.x@@ -357,37 +357,14 @@ void SGRPlayerMotionLyricsChanged(void) {[sg_motion setBlurred:SGRPlayerLyricsOpen() animated:sg_motion.window != nil];}-@interface SGRPlayerMotionWatcher : NSObject <SGPlayerStateObserver>-@end--@implementation SGRPlayerMotionWatcher-- (void)playerStateDidChange:(SPTPlayerState *)state {- NSString *track = SGURIString(state.track.URI);- if (!track || [track isEqualToString:sg_track]) return;- sg_track = track;- clear(YES);- // Read on every track, since the ⋯ menu switches it.- if (SGRPlayerBackground() != SGRPlayerBackgroundAnimated) return;- NSDictionary *metadata = [state.track.metadata isKindOfClass:NSDictionary.class] ? state.track.metadata : nil;- id type = metadata[@"canvas.type"], address = metadata[@"canvas.url"];- BOOL video = [type isKindOfClass:NSString.class] && [type rangeOfString:@"video" options:NSCaseInsensitiveSearch].location != NSNotFound;- NSURL *canvas = video && [address isKindOfClass:NSString.class] ? [NSURL URLWithString:address] : nil;- NSString *artist = state.track.artistName, *album = metadata[@"album_title"];- CGFloat pixels = SGMotionPixels();- static NSUInteger logged;- if (logged++ < 3) SGLog(@"redesign player: canvas %@ (%@)", canvas ? @"found" : @"none", type ?: @"no type");- SGMotionClipFor(canvas, artist, album, SGMotionTall, pixels, ^(NSURL *file) { show(track, file); });-}-@end--static SGRPlayerMotionWatcher *sg_watcher;+static SGMotionFollower *sg_follower;#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).BOOL SGPlayerMenuOffersAnimatedArtwork(void) {- if (!sg_watcher) return NO;+ if (!sg_follower) return NO;SGRPlayerBackgroundKind background = SGRPlayerBackground();return background == SGRPlayerBackgroundFluid || background == SGRPlayerBackgroundAnimated;}@@ -401,15 +378,21 @@ void SGPlayerMenuSetAnimatedArtwork(BOOL on) {SGSetInt(SGRKeyPlayerBackground, on ? SGRPlayerBackgroundAnimated : SGRPlayerBackgroundFluid);SGLog(@"redesign player: animated artwork switched %@ from the menu", on ? @"on" : @"off");// The playing track is let go, and looked up again when switched on.- sg_track = nil;clear(YES);- [sg_watcher playerStateDidChange:SGPlayerState()];+ [sg_follower restart];}%ctor {if (!SGRedesignedUI()) return;SGRPlayerBackgroundKind background = SGRPlayerBackground();if (background != SGRPlayerBackgroundFluid && background != SGRPlayerBackgroundAnimated) return;- sg_watcher = [SGRPlayerMotionWatcher new];- SGAddPlayerStateObserver(sg_watcher);+ sg_follower = [[SGMotionFollower alloc] initWithBegin:^BOOL(NSString *uri, SPTPlayerState *state) {+ sg_track = uri;+ clear(YES);+ // Read on every track, since the ⋯ menu switches it.+ return SGRPlayerBackground() == SGRPlayerBackgroundAnimated;+ } found:^(NSString *uri, NSURL *file) {+ if (file) show(uri, file);+ else clear(YES);+ }];}diff --git a/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtwork.h b/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtwork.hindex 2a317db4..a77a9290 100644--- a/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtwork.h+++ b/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtwork.h@@ -47,10 +47,27 @@ void SGMotionSongsWithISRC(NSString *isrc, void (^done)(NSArray *songs));#define SGKeyMotionSources @"spotifyglass.motion.sources"NSArray<NSString *> *SGMotionSourceOrder(void);BOOL SGMotionAppleMusicOn(void);-// The first clip the order finds for a track, as a local file, or nil. `canvas` is the track's Canvas-// video, nil when it has none. Main queue.-void SGMotionClipFor(NSURL *canvas, NSString *artist, NSString *album, SGMotionShape shape, CGFloat pixels,- void (^done)(NSURL *file));+// The track's Canvas video as its metadata names it (canvas.url, of a canvas.type that is a video), or nil.+NSURL *SGMotionCanvasIn(NSDictionary *metadata);+// The first clip the order finds for the track `uri`, as a local file, or nil, and the key of the source it+// came from. `canvas` is the track's Canvas video, nil when its metadata names none, and then Spotify's+// Canvas service is asked for it. Main queue.+void SGMotionClipFor(NSString *uri, NSURL *canvas, NSString *artist, NSString *album, SGMotionShape shape, CGFloat pixels,+ void (^done)(NSURL *file, NSString *source));++// Follows the player for one user of moving artwork, the lock screen or the redesign's player+// (SGMotionFollower.m). Each track's sources are walked once, and again when its Canvas turns up in a later+// state, as it does on a skip, where Spotify reports the track before its extended metadata, unless the clip+// showing came from a source above Canvas. `begin` runs as a walk starts, to take the last clip off, and+// says whether to walk at all; `found` gets the walk's clip, nil for none, and never runs for a walk a newer+// one overtook. Once a walk has ended, the next track's clip is fetched ahead. Main queue.+@class SPTPlayerState;+@interface SGMotionFollower : NSObject+- (instancetype)initWithBegin:(BOOL (^)(NSString *uri, SPTPlayerState *state))begin+ found:(void (^)(NSString *uri, NSURL *file))found;+// The track is walked again from the player's last state: a setting it depends on changed.+- (void)restart;+@end// The row that opens the ordered list, for the Player page and the lock screen's.@class SGModRow;SGModRow *SGMotionSourcesRow(void);diff --git a/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtworkSettings.m b/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtworkSettings.mindex edfa7ad9..bfe3dd13 100644--- a/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtworkSettings.m+++ b/tweak/Sources/Shared/AnimatedArtwork/AnimatedArtworkSettings.m@@ -29,7 +29,8 @@ NSArray *SGLockScreenMotionRows(void) {sources.visible = lowData.visible;return @[SGChoiceRow(@"Full-screen artwork", @"The Canvas or Apple Music's animated cover, or the lyrics a line at a time. "- @"Every song puts the cover over a moving blur of it where a song has neither",+ @"Every song puts the cover over a moving blur of it where a song has neither. "+ @"A change to or from Lyrics applies after a restart, the others at once",SGKeyLockScreenArtwork, @[@"Off", @"Moving artwork", @"Lyrics", @"Every song"], SGLockArtworkOff),style,sources,diff --git a/tweak/Sources/Shared/AnimatedArtwork/LockScreenMotion.x b/tweak/Sources/Shared/AnimatedArtwork/LockScreenMotion.xindex 8e5c7c87..6061bd79 100644--- a/tweak/Sources/Shared/AnimatedArtwork/LockScreenMotion.x+++ b/tweak/Sources/Shared/AnimatedArtwork/LockScreenMotion.x@@ -1,36 +1,102 @@// The lock screen's artwork moves: the track's Canvas, else Apple Music's animated album cover, and with// Every song chosen, failing both, the cover over a moving blur of itself (SGFluidClip.h). iOS 26 takes a-// local video through MPMediaItemAnimatedArtwork under one of two now playing keys, 1:1 or 3:4, picked-// here by the video's own shape. It rides on Spotify's now playing info as an extra-// (Shared/Player/NowPlayingExtras.h).+// local video through MPMediaItemAnimatedArtwork under one of two now playing keys, 1:1 or 3:4, of those+// the system lists. It rides on Spotify's now playing info as an extra (Shared/Player/NowPlayingExtras.h).//-// The cover's clip is made only when the lock screen asks for its video, from the cover Spotify gave the-// system, and kept by the picture the track names, so an album's songs share one.+// The system turns down a clip of another shape than its key's, and a preview still of another shape with+// it, so a clip that does not fit (a Canvas is mostly 9:16) is cut to the key's shape about its middle, and+// the still is filled to the size the system asks for. The cut, like the cover's clip, is made only when the+// lock screen asks for the video, and kept: the cut by the clip and shape, the cover's clip by the picture+// the track names, so an album's songs share one.+//+// The choice is read on every track, and a change applies at once: Off takes the clip away, Moving artwork+// and Every song look the playing track up. Lyrics is LyricsArtwork.x's, which reads it only at launch, so+// a launch with Lyrics leaves this off until the next one.#import <MediaPlayer/MediaPlayer.h>#import "Core/SGCore.h"#import "AnimatedArtwork.h"#import "SGFluidClip.h"+#import "SGMotionClip.h"#import "Shared/LockScreenLyrics/SGLyricsClip.h"#import "Shared/Player/NowPlayingExtras.h"#import "Shared/Player/PlayerState.h"-static NSString *sg_track; // the URI the artwork is for+// How far a clip's width over height may be from its key's and still be taken as it is.+static const CGFloat kSameShape = 0.02;+static NSString *sg_title;-static dispatch_queue_t sg_queue; // makes the cover's clips, one at a time+static NSString *sg_picture; // the picture the track names, for the cover's clip+static NSUInteger sg_walk; // counts the tracks walked, so a poster that comes late is told from the newest+static SGLockArtwork sg_choice, sg_launchChoice;+static dispatch_queue_t sg_queue; // cuts clips and makes the cover's, one at a time+static SGMotionFollower *sg_follower;++static BOOL motionOn(SGLockArtwork choice) {+ return sg_launchChoice != SGLockArtworkLyrics && (choice == SGLockArtworkMotion || choice == SGLockArtworkEverySong);+}++// The key a clip shown at `shown` goes under, and the shape it is cut to (width over height): 1:1 for a+// square clip, else 3:4, each where the system lists it, else the other. nil while it lists neither, before+// MediaPlayer has started: the next track asks again.+API_AVAILABLE(ios(26.0))+static NSString *keyFor(CGSize shown, CGFloat *ratio) {+ NSArray<NSString *> *keys = MPNowPlayingInfoCenter.supportedAnimatedArtworkKeys;+ BOOL square = shown.height > 0 && fabs(shown.width / shown.height - 1) <= kSameShape;+ BOOL tall = [keys containsObject:MPNowPlayingInfoProperty3x4AnimatedArtwork];+ if ([keys containsObject:MPNowPlayingInfoProperty1x1AnimatedArtwork] && (square || !tall)) {+ *ratio = 1;+ return MPNowPlayingInfoProperty1x1AnimatedArtwork;+ }+ *ratio = 0.75;+ return tall ? MPNowPlayingInfoProperty3x4AnimatedArtwork : nil;+}++// `image` filled into `size` about its middle, at scale 1 and opaque, as the preview the system asked for.+static UIImage *filled(UIImage *image, CGSize size) {+ size = CGSizeMake(round(size.width), round(size.height));+ if (!image || size.width < 1 || size.height < 1 || image.size.width <= 0 || image.size.height <= 0) return image;+ UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat];+ format.scale = 1;+ format.opaque = YES;+ CGFloat scale = MAX(size.width / image.size.width, size.height / image.size.height);+ CGSize drawn = CGSizeMake(image.size.width * scale, image.size.height * scale);+ return [[[UIGraphicsImageRenderer alloc] initWithSize:size format:format] imageWithActions:^(UIGraphicsImageRendererContext *context) {+ [image drawInRect:CGRectMake((size.width - drawn.width) / 2, (size.height - drawn.height) / 2, drawn.width, drawn.height)];+ }];+}API_AVAILABLE(ios(26.0))-static void show(NSString *uri, NSURL *file) {- if (!file || ![uri isEqualToString:sg_track]) return;+static void show(NSURL *file) {+ NSUInteger walk = sg_walk;+ NSString *title = sg_title;SGMotionPoster(file, ^(UIImage *poster) {- if (!poster || ![uri isEqualToString:sg_track]) return;- CGSize size = poster.size;- BOOL square = fabs(size.width - size.height) < size.height * 0.05;- NSString *key = square ? MPNowPlayingInfoProperty1x1AnimatedArtwork : MPNowPlayingInfoProperty3x4AnimatedArtwork;- MPMediaItemAnimatedArtwork *artwork = [[MPMediaItemAnimatedArtwork alloc] initWithArtworkID:file.lastPathComponent- previewImageRequestHandler:^(CGSize wanted, void (^completion)(UIImage *)) { completion(poster); }- videoAssetFileURLRequestHandler:^(CGSize wanted, void (^completion)(NSURL *)) { completion(file); }];- SGNowPlayingSetExtras(@"motion", @{key: artwork}, sg_title);- SGLog(@"lock motion: %@ as %@", file.lastPathComponent, square ? @"1:1" : @"3:4");+ if (!poster || poster.size.height <= 0 || walk != sg_walk) return;+ CGFloat ratio;+ NSString *key = keyFor(poster.size, &ratio);+ if (!key) {+ SGLog(@"lock motion: the system lists no key yet (%@)", MPNowPlayingInfoCenter.supportedAnimatedArtworkKeys);+ return;+ }+ BOOL fits = fabs(poster.size.width / poster.size.height - ratio) <= kSameShape;+ NSURL *shaped = fits ? file : SGMotionMadeFile([NSString stringWithFormat:@"cut\n%@\n%g", file.lastPathComponent, ratio]);+ MPMediaItemAnimatedArtwork *artwork = [[MPMediaItemAnimatedArtwork alloc] initWithArtworkID:shaped.lastPathComponent+ previewImageRequestHandler:^(CGSize wanted, void (^completion)(UIImage *)) { completion(filled(poster, wanted)); }+ videoAssetFileURLRequestHandler:^(CGSize wanted, void (^completion)(NSURL *)) {+ if (fits) {+ completion(file);+ return;+ }+ dispatch_async(sg_queue, ^{+ CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();+ BOOL ok = [NSFileManager.defaultManager fileExistsAtPath:shaped.path] || SGMotionClipShape(file, ratio, shaped);+ SGLog(@"lock motion: %@ cut to %@ %@ in %.0f ms", file.lastPathComponent, ratio == 1 ? @"1:1" : @"3:4",+ ok ? @"ready" : @"not written", (CFAbsoluteTimeGetCurrent() - start) * 1000);+ completion(ok ? shaped : nil);+ });+ }];+ SGNowPlayingSetExtras(@"motion", @{key: artwork}, title);+ SGLog(@"lock motion: %@, %.0fx%.0f, as %@%@", file.lastPathComponent, poster.size.width, poster.size.height,+ ratio == 1 ? @"1:1" : @"3:4", fits ? @"" : @", cut to fit");});}@@ -55,9 +121,10 @@ static NSString *pictureOf(SPTPlayerTrack *track, NSDictionary *metadata) {return SGURIString(track.URI);}+// The cover's clip is 3:4 (SGLyricsClipSize), so it goes only where the system lists that key.API_AVAILABLE(ios(26.0))-static void showCover(NSString *uri, NSString *picture) {- if (![uri isEqualToString:sg_track]) return;+static void showCover(NSString *picture) {+ if (![MPNowPlayingInfoCenter.supportedAnimatedArtworkKeys containsObject:MPNowPlayingInfoProperty3x4AnimatedArtwork]) return;NSURL *file = SGMotionMadeFile([@"fluid\n" stringByAppendingString:picture]);NSString *title = sg_title;CGSize size = SGLyricsClipSize(SGMotionPixels());@@ -65,7 +132,7 @@ static void showCover(NSString *uri, NSString *picture) {previewImageRequestHandler:^(CGSize wanted, void (^completion)(UIImage *)) {withCover(title, ^(CGImageRef cover) {CGImageRef frame = SGFluidClipFrame(cover, size);- completion(frame ? [UIImage imageWithCGImage:frame] : nil);+ completion(frame ? filled([UIImage imageWithCGImage:frame], wanted) : nil);CGImageRelease(frame);});}@@ -82,42 +149,32 @@ static void showCover(NSString *uri, NSString *picture) {SGLog(@"lock motion: no moving artwork, the cover's clip offered as %@", file.lastPathComponent);}-@interface SGLockScreenMotion : NSObject <SGPlayerStateObserver>-@end--@implementation SGLockScreenMotion-- (void)playerStateDidChange:(SPTPlayerState *)state {- if (@available(iOS 26.0, *)) {- NSString *uri = SGURIString(state.track.URI);- if (!uri || [uri isEqualToString:sg_track]) return;- sg_track = uri;- sg_title = state.track.trackTitle;- SGNowPlayingSetExtras(@"motion", nil, nil);- NSDictionary *metadata = [state.track.metadata isKindOfClass:NSDictionary.class] ? state.track.metadata : nil;- NSString *artist = state.track.artistName, *album = metadata[@"album_title"];- id type = metadata[@"canvas.type"], address = metadata[@"canvas.url"];- BOOL video = [type isKindOfClass:NSString.class] && [type rangeOfString:@"video" options:NSCaseInsensitiveSearch].location != NSNotFound;- NSURL *canvas = video && [address isKindOfClass:NSString.class] ? [NSURL URLWithString:address] : nil;- CGFloat pixels = SGMotionPixels();- BOOL everySong = SGLockScreenArtwork() == SGLockArtworkEverySong;- NSString *picture = pictureOf(state.track, metadata);- SGMotionClipFor(canvas, artist, album, SGMotionTall, pixels, ^(NSURL *file) {- if (file) show(uri, file);- else if (everySong) showCover(uri, picture);- });- }-}-@end-%ctor {- SGLockArtwork choice = SGLockScreenArtwork();- if (choice != SGLockArtworkMotion && choice != SGLockArtworkEverySong) return;if (@available(iOS 26.0, *)) {+ sg_launchChoice = sg_choice = SGLockScreenArtwork();sg_queue = dispatch_queue_create("spotifyglass.lockscreen.motion", DISPATCH_QUEUE_SERIAL);- static SGLockScreenMotion *observer;- observer = [SGLockScreenMotion new];- SGAddPlayerStateObserver(observer);- SGLog(@"lock motion: on%@, the lock screen takes %@", choice == SGLockArtworkEverySong ? @" for every song" : @"",+ // Each walk takes the last one's clip off first, so the lock screen falls back to the still cover.+ sg_follower = [[SGMotionFollower alloc] initWithBegin:^BOOL(NSString *uri, SPTPlayerState *state) {+ sg_walk++;+ SGNowPlayingSetExtras(@"motion", nil, nil);+ NSDictionary *metadata = [state.track.metadata isKindOfClass:NSDictionary.class] ? state.track.metadata : nil;+ sg_title = state.track.trackTitle;+ sg_picture = pictureOf(state.track, metadata);+ sg_choice = SGLockScreenArtwork();+ return motionOn(sg_choice);+ } found:^(NSString *uri, NSURL *file) {+ if (file) show(file);+ else if (sg_choice == SGLockArtworkEverySong) showCover(sg_picture);+ }];+ [NSNotificationCenter.defaultCenter addObserverForName:NSUserDefaultsDidChangeNotification object:nil queue:NSOperationQueue.mainQueue+ usingBlock:^(NSNotification *note) {+ SGLockArtwork choice = SGLockScreenArtwork();+ if (choice == sg_choice) return;+ SGLog(@"lock motion: the choice changed to %ld, the playing track looked up again", (long)choice);+ sg_choice = choice;+ [sg_follower restart];+ }];+ SGLog(@"lock motion: %@, the lock screen takes %@", motionOn(sg_choice) ? (sg_choice == SGLockArtworkEverySong ? @"on for every song" : @"on") : @"off",MPNowPlayingInfoCenter.supportedAnimatedArtworkKeys);}}diff --git a/tweak/Sources/Shared/AnimatedArtwork/MotionSources.m b/tweak/Sources/Shared/AnimatedArtwork/MotionSources.mindex fde0df36..c32039c3 100644--- a/tweak/Sources/Shared/AnimatedArtwork/MotionSources.m+++ b/tweak/Sources/Shared/AnimatedArtwork/MotionSources.m@@ -1,10 +1,15 @@// Where a track's moving artwork comes from, in the user's order: the Canvas Spotify gives the track and// Apple Music's animated album cover. Either can be switched off. The player and the lock screen walk the// order (SGMotionClipFor); the album page's animated cover asks only whether Apple Music is on.+//+// A track whose metadata names no Canvas has it asked of Spotify's Canvas service, the way Spotify's own+// player is told of one, as the signed-in app (SGSpclientHeaders).#import "Core/SGCore.h"#import "Settings/SGModPage.h"#import "Settings/SGSourcesPage.h"+#import "Shared/Lyrics/Lyrics.h"#import "AnimatedArtwork.h"+#import "SGMotionClip.h"static NSString *const kCanvas = @"canvas", *const kAppleMusic = @"applemusic";@@ -29,27 +34,91 @@ BOOL SGMotionAppleMusicOn(void) {return [SGMotionSourceOrder() containsObject:kAppleMusic];}-void SGMotionClipFor(NSURL *canvas, NSString *artist, NSString *album, SGMotionShape shape, CGFloat pixels,- void (^done)(NSURL *file)) {+NSURL *SGMotionCanvasIn(NSDictionary *metadata) {+ if (![metadata isKindOfClass:NSDictionary.class]) return nil;+ id type = metadata[@"canvas.type"], address = metadata[@"canvas.url"];+ BOOL video = [type isKindOfClass:NSString.class] && [type rangeOfString:@"video" options:NSCaseInsensitiveSearch].location != NSNotFound;+ return video && [address isKindOfClass:NSString.class] ? [NSURL URLWithString:address] : nil;+}++// What the service answered for each track this launch, its Canvas's address or NSNull for none, and the+// askers waiting on an answer in flight. A request that failed is not kept, so the next walk asks again.+static NSMutableDictionary<NSString *, id> *sg_answers;+static NSMutableDictionary<NSString *, NSMutableArray *> *sg_asking;++static void canvasFromService(NSString *uri, void (^done)(NSURL *canvas)) {+ // Songs only: a local file, an episode or an ad has no Canvas to ask for.+ id answer = [uri hasPrefix:@"spotify:track:"] ? sg_answers[uri] : NSNull.null;+ if (answer) {+ done([answer isKindOfClass:NSString.class] ? [NSURL URLWithString:answer] : nil);+ return;+ }+ if (sg_asking[uri]) {+ [sg_asking[uri] addObject:[done copy]];+ return;+ }+ // Asked only with the headers already seen: the walk does not wait for Spotify's first request.+ __block NSDictionary<NSString *, NSString *> *headers = nil;+ __block BOOL waited = NO;+ SGSpclientHeaders(^(NSDictionary<NSString *, NSString *> *seen) {+ if (!waited) headers = seen;+ });+ waited = YES;+ NSData *body = SGMotionCanvasAsk(uri);+ if (!headers || !body) {+ done(nil);+ return;+ }+ if (!sg_answers) sg_answers = [NSMutableDictionary dictionary];+ if (!sg_asking) sg_asking = [NSMutableDictionary dictionary];+ sg_asking[uri] = [NSMutableArray arrayWithObject:[done copy]];+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://spclient.wg.spotify.com/canvaz-cache/v0/canvases"]];+ request.HTTPMethod = @"POST";+ request.HTTPBody = body;+ [headers enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {+ [request setValue:value forHTTPHeaderField:name];+ }];+ [request setValue:@"application/x-protobuf" forHTTPHeaderField:@"Content-Type"];+ request.allowsConstrainedNetworkAccess = SGFlag(SGKeyMotionLowData, NO);+ [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *reply, NSURLResponse *response, NSError *error) {+ NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;+ NSString *address = status == 200 ? SGMotionCanvasInReply(reply) : nil;+ dispatch_async(dispatch_get_main_queue(), ^{+ static NSUInteger logged;+ if (logged++ < 5 || status != 200) SGLog(@"motion: Canvas service for %@: %ld, %@", uri, (long)status, address ? @"a video" : @"none");+ if (status == 200) sg_answers[uri] = address ?: (id)NSNull.null;+ NSArray *waiting = sg_asking[uri];+ [sg_asking removeObjectForKey:uri];+ for (void (^waiter)(NSURL *) in waiting) waiter(address ? [NSURL URLWithString:address] : nil);+ });+ }] resume];+}++void SGMotionClipFor(NSString *uri, NSURL *canvas, NSString *artist, NSString *album, SGMotionShape shape, CGFloat pixels,+ void (^done)(NSURL *file, NSString *source)) {NSArray<NSString *> *order = SGMotionSourceOrder();// The walk holds itself until it ends, when it lets go.__block void (^ask)(NSUInteger) = nil;- void (^finish)(NSURL *) = ^(NSURL *file) {+ void (^finish)(NSURL *, NSString *) = ^(NSURL *file, NSString *source) {ask = nil;- done(file);+ done(file, source);};void (^step)(NSUInteger) = ^(NSUInteger index) {if (index >= order.count) {- finish(nil);+ finish(nil, nil);return;}+ NSString *source = order[index];void (^next)(NSURL *) = ^(NSURL *file) {- if (file) finish(file);+ if (file) finish(file, source);else ask(index + 1);};- if ([order[index] isEqualToString:kCanvas]) {+ if ([source isEqualToString:kCanvas]) {if (canvas) SGMotionFile(canvas, next);- else next(nil);+ else canvasFromService(uri, ^(NSURL *found) {+ if (found) SGMotionFile(found, next);+ else next(nil);+ });} else {SGMotionAlbumCover(artist, album, shape, pixels, next);}diff --git a/tweak/Sources/Shared/AnimatedArtwork/SGMotionClip.h b/tweak/Sources/Shared/AnimatedArtwork/SGMotionClip.hnew file mode 100644index 00000000..d12d11b0--- /dev/null+++ b/tweak/Sources/Shared/AnimatedArtwork/SGMotionClip.h@@ -0,0 +1,22 @@+// Steps of moving artwork with no UIKit in them, so harness/motion runs them on the Mac: a clip cut to the+// shape the lock screen takes, Spotify's Canvas service's request and reply, and when a Canvas that turned+// up late is still wanted.+#import <CoreGraphics/CoreGraphics.h>+#import <Foundation/Foundation.h>++// The largest size of `ratio` (width over height) inside `shown`, about its middle, in even pixels.+CGSize SGMotionClipCut(CGSize shown, CGFloat ratio);+// Writes `file` cut about its middle to `ratio` to `out` (H.264, the clip's own frame times), replacing it,+// and returns once it is written; NO if it was not. Blocks, so never on the main queue.+BOOL SGMotionClipShape(NSURL *file, CGFloat ratio, NSURL *out);++// The body that asks Spotify's Canvas service (canvaz-cache) for a track's Canvas: field 1, an entity+// whose field 1 is the track's URI.+NSData *SGMotionCanvasAsk(NSString *uri);+// The address of the first video in the service's reply (field 1, a Canvas each: 2 its address, 4 its+// type, of which 1 to 3 are videos), nil when it names none, only a still or a GIF.+NSString *SGMotionCanvasInReply(NSData *reply);++// Whether a Canvas found after a track's walk began is asked for: Canvas is in `order` (source keys, asked+// first to last) and `source`, the source of the clip showing, nil for none, comes after it.+BOOL SGMotionCanvasOutranks(NSArray<NSString *> *order, NSString *source);diff --git a/tweak/Sources/Shared/AnimatedArtwork/SGMotionClip.m b/tweak/Sources/Shared/AnimatedArtwork/SGMotionClip.mnew file mode 100644index 00000000..657f1e5f--- /dev/null+++ b/tweak/Sources/Shared/AnimatedArtwork/SGMotionClip.m@@ -0,0 +1,112 @@+// SGMotionClip.h says what these are. The cut is the encoder's: the writer is given the cut's size and told+// to fill it keeping the picture's shape, so it drops what overhangs either side and scales nothing.+#import <AVFoundation/AVFoundation.h>+#import "Shared/AdBlock/Protobuf.h"+#import "SGMotionClip.h"++static NSString *const kCanvas = @"canvas";++CGSize SGMotionClipCut(CGSize shown, CGFloat ratio) {+ if (shown.width <= 0 || shown.height <= 0 || ratio <= 0) return CGSizeZero;+ CGSize cut = shown.width / shown.height > ratio ? CGSizeMake(shown.height * ratio, shown.height)+ : CGSizeMake(shown.width, shown.width / ratio);+ // H.264 takes even sides; rounded down, so the cut stays inside the picture.+ return CGSizeMake(floor(cut.width / 2) * 2, floor(cut.height / 2) * 2);+}++BOOL SGMotionClipShape(NSURL *file, CGFloat ratio, NSURL *out) {+ AVURLAsset *asset = [AVURLAsset URLAssetWithURL:file options:nil];+ __block AVAssetTrack *track = nil;+ dispatch_semaphore_t loaded = dispatch_semaphore_create(0);+ [asset loadTracksWithMediaType:AVMediaTypeVideo completionHandler:^(NSArray<AVAssetTrack *> *tracks, NSError *error) {+ track = tracks.firstObject;+ dispatch_semaphore_signal(loaded);+ }];+ dispatch_semaphore_wait(loaded, DISPATCH_TIME_FOREVER);+ if (!track) return NO;+ // A quarter turn in the track's transform stands the stored picture on its side: the cut is made in the+ // stored picture, and the transform is carried over to stand it up the same way.+ CGAffineTransform turn = track.preferredTransform;+ BOOL sideways = fabs(turn.b) > 0.5;+ CGSize stored = track.naturalSize, shown = sideways ? CGSizeMake(stored.height, stored.width) : stored;+ CGSize cut = SGMotionClipCut(shown, ratio);+ if (cut.width < 2 || cut.height < 2) return NO;+ if (sideways) cut = CGSizeMake(cut.height, cut.width);++ AVAssetReader *reader = [AVAssetReader assetReaderWithAsset:asset error:nil];+ AVAssetReaderTrackOutput *frames = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:track outputSettings:@{+ (id)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange),+ }];+ if (!reader || ![reader canAddOutput:frames]) return NO;+ [reader addOutput:frames];++ // Written beside the file and moved over it once whole, as SGLyricsClip.m writes, so a clip cut off+ // halfway is never found.+ NSURL *partial = [out URLByAppendingPathExtension:@"partial"];+ [NSFileManager.defaultManager removeItemAtURL:partial error:nil];+ AVAssetWriter *writer = [AVAssetWriter assetWriterWithURL:partial fileType:AVFileTypeMPEG4 error:nil];+ AVAssetWriterInput *input = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:@{+ AVVideoCodecKey: AVVideoCodecTypeH264,+ AVVideoWidthKey: @(cut.width),+ AVVideoHeightKey: @(cut.height),+ AVVideoScalingModeKey: AVVideoScalingModeResizeAspectFill,+ // About 2 Mbit/s at a Canvas's 720 x 960, near what Spotify streams it at.+ AVVideoCompressionPropertiesKey: @{AVVideoAverageBitRateKey: @(cut.width * cut.height * 3)},+ }];+ input.transform = turn;+ if (!writer || ![writer canAddInput:input]) return NO;+ [writer addInput:input];+ if (![reader startReading] || ![writer startWriting]) {+ [reader cancelReading];+ return NO;+ }+ BOOL ok = YES, started = NO;+ while (ok) {+ CMSampleBufferRef sample = [frames copyNextSampleBuffer];+ if (!sample) break;+ if (!started) {+ [writer startSessionAtSourceTime:CMSampleBufferGetPresentationTimeStamp(sample)];+ started = YES;+ }+ while (!input.readyForMoreMediaData && writer.status == AVAssetWriterStatusWriting) [NSThread sleepForTimeInterval:0.002];+ ok = writer.status == AVAssetWriterStatusWriting && [input appendSampleBuffer:sample];+ CFRelease(sample);+ }+ if (!ok || !started || reader.status != AVAssetReaderStatusCompleted) {+ [reader cancelReading];+ [writer cancelWriting];+ return NO;+ }+ [input markAsFinished];+ dispatch_semaphore_t written = dispatch_semaphore_create(0);+ [writer finishWritingWithCompletionHandler:^{ dispatch_semaphore_signal(written); }];+ dispatch_semaphore_wait(written, DISPATCH_TIME_FOREVER);+ if (writer.status != AVAssetWriterStatusCompleted) return NO;+ [NSFileManager.defaultManager removeItemAtURL:out error:nil];+ return [NSFileManager.defaultManager moveItemAtURL:partial toURL:out error:nil];+}++NSData *SGMotionCanvasAsk(NSString *uri) {+ if (!uri.length) return nil;+ return SGPBSerialize(@[SGPBBytes(1, SGPBSerialize(@[SGPBString(1, uri)]))]);+}++NSString *SGMotionCanvasInReply(NSData *reply) {+ for (SGPBField *field in SGPBParse(reply)) {+ if (field.number != 1 || field.wire != 2) continue;+ NSArray<SGPBField *> *canvas = SGPBParse(field.payload);+ SGPBField *type = SGPBFirst(canvas, 4);+ NSString *address = SGPBText(SGPBFirst(canvas, 2));+ // 0, the type a message leaves out, is a still; 4 and on are a GIF and kinds not seen.+ if (type.wire == 0 && type.varint >= 1 && type.varint <= 3 && address.length) return address;+ }+ return nil;+}++BOOL SGMotionCanvasOutranks(NSArray<NSString *> *order, NSString *source) {+ NSUInteger canvas = [order indexOfObject:kCanvas];+ if (canvas == NSNotFound) return NO;+ if (!source) return YES;+ NSUInteger shown = [order indexOfObject:source];+ return shown != NSNotFound && shown > canvas;+}diff --git a/tweak/Sources/Shared/AnimatedArtwork/SGMotionFollower.m b/tweak/Sources/Shared/AnimatedArtwork/SGMotionFollower.mnew file mode 100644index 00000000..b5e50aba--- /dev/null+++ b/tweak/Sources/Shared/AnimatedArtwork/SGMotionFollower.m@@ -0,0 +1,84 @@+// SGMotionFollower (AnimatedArtwork.h): one track's walk of the sources at a time, for the lock screen+// (LockScreenMotion.x) and the redesign's player (Redesigned/Player/PlayerMotion.x) alike.+#import <objc/runtime.h>+#import "Core/SGCore.h"+#import "Shared/Player/PlayerState.h"+#import "AnimatedArtwork.h"+#import "SGMotionClip.h"++@interface SGMotionFollower () <SGPlayerStateObserver>+@end++@implementation SGMotionFollower {+ BOOL (^_begin)(NSString *, SPTPlayerState *);+ void (^_found)(NSString *, NSURL *);+ NSString *_track; // the URI walked last+ BOOL _walked; // whether `begin` let it be walked+ NSURL *_canvas; // the Canvas its metadata named as the walk began, nil for none+ NSString *_source; // where the clip found came from, nil for none or not found yet+ NSUInteger _walk; // counts the walks, so an overtaken one is told from the newest+ NSString *_ahead; // the next track whose clip was fetched ahead+}++- (instancetype)initWithBegin:(BOOL (^)(NSString *, SPTPlayerState *))begin found:(void (^)(NSString *, NSURL *))found {+ if (!(self = [super init])) return nil;+ _begin = [begin copy];+ _found = [found copy];+ SGAddPlayerStateObserver(self);+ return self;+}++- (void)playerStateDidChange:(SPTPlayerState *)state {+ NSString *uri = SGURIString(state.track.URI);+ if (!uri) return;+ NSURL *canvas = SGMotionCanvasIn(state.track.metadata);+ if ([uri isEqualToString:_track]) {+ if (!_walked || _canvas || !canvas || !SGMotionCanvasOutranks(SGMotionSourceOrder(), _source)) return;+ SGLog(@"motion: the Canvas of %@ came after the track, asked again", uri);+ }+ [self walk:state uri:uri canvas:canvas];+}++- (void)walk:(SPTPlayerState *)state uri:(NSString *)uri canvas:(NSURL *)canvas {+ _track = uri;+ _canvas = canvas;+ _source = nil;+ NSUInteger walk = ++_walk;+ _walked = _begin(uri, state);+ if (!_walked) return;+ NSDictionary *metadata = [state.track.metadata isKindOfClass:NSDictionary.class] ? state.track.metadata : nil;+ __weak SGMotionFollower *weakSelf = self;+ SGMotionClipFor(uri, canvas, state.track.artistName, metadata[@"album_title"], SGMotionTall, SGMotionPixels(), ^(NSURL *file, NSString *source) {+ SGMotionFollower *follower = weakSelf;+ if (!follower || walk != follower->_walk) return;+ follower->_source = source;+ follower->_found(uri, file);+ [follower fetchAhead];+ });+}++// The next track's clip, fetched into the store once, so a skip finds it there.+- (void)fetchAhead {+ SPTPlayerState *state = SGPlayerState();+ id future = [state respondsToSelector:@selector(future)] ? state.future : nil;+ id next = [future isKindOfClass:NSArray.class] ? [(NSArray *)future firstObject] : nil;+ if (![next isKindOfClass:objc_getClass("SPTPlayerTrack")]) return;+ SPTPlayerTrack *track = next;+ NSString *uri = SGURIString(track.URI);+ if (!uri || [uri isEqualToString:_track] || [uri isEqualToString:_ahead]) return;+ _ahead = uri;+ NSDictionary *metadata = [track.metadata isKindOfClass:NSDictionary.class] ? track.metadata : nil;+ SGMotionClipFor(uri, SGMotionCanvasIn(metadata), track.artistName, metadata[@"album_title"], SGMotionTall, SGMotionPixels(),+ ^(NSURL *file, NSString *source) {+ SGLog(@"motion: the next track's clip fetched ahead: %@", file ? source : @"none");+ });+}++- (void)restart {+ _track = nil;+ _walk++;+ SPTPlayerState *state = SGPlayerState();+ if (state) [self playerStateDidChange:state];+}++@end