Skip to content

Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.

C

fix: player artwork retries failed clips, respects motion settings and stays readable

My-Name-Is-Jeff869423035933
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 5d9edfec..1ec2ef48 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -429,7 +429,11 @@ Redesigned:
(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 while
Spotify's music video shows, is given up when it has drawn nothing in 5 s on screen, and on a skip
- stays a moment for the next track's to cross over it. Checked in the simulator against
+ stays a moment for the next track's to cross over it. Under Reduce Motion and in Low Power Mode no
+ clip plays: the cover stays over Fluid. A black layer dims the clip by its brightness (the 75th
+ percentile of the linear luminance of three frames), so white text keeps 4.5:1 (7:1 with Increase
+ Contrast), from 0.10 to 0.80 and 0.15 more behind the lyrics. A track that changes while the player
+ cannot be seen (no window, or the app not in front) takes the last clip away at once. Checked in the simulator against
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'
diff --git a/harness/player/README.md b/harness/player/README.md
index 27acd9b5..4d71edc5 100644
--- a/harness/player/README.md
+++ b/harness/player/README.md
@@ -66,8 +66,15 @@ come late, out of order, or not at all.
and the cover crossing over half way through the switch). Then the song pauses and plays (the clip's rate
0, then 1), a mock of Spotify's video unit attaches and detaches its video (the clip goes and comes back),
a track comes with no Canvas and then again with one (the clip comes in late), and a skip to a track whose
- clip is in the store keeps the last clip until the new one is over it, the cover hidden throughout. The log
- ends with `motion checks: n of 20 right -- PASS` or `FAIL`.
+ clip is in the store keeps the last clip until the new one is over it, the cover hidden throughout. The clip's
+ dim is checked over the clip and 0.15 darker under the lyrics, with the rule at its ends; `HARNESS_DIM` is the
+ dim the clip should get (`ffmpeg -f lavfi -i "color=c=white:s=360x640:d=4"` gives 0.54, black 0.10). Uninstall
+ the app between clips, or the store answers with the last one. Then Low Power Mode, which the process is made
+ to report (the simulator has none; Reduce Motion takes the same path), takes the clip away for the cover over
+ Fluid and gives it back once off, and a track change with the app made to report the background takes the clip
+ away at once, with no fade. The log ends with `motion checks: n of 25 right -- PASS` or `FAIL`.
+ `HARNESS_CANVAS_FAILS=n` fails the first n requests for the clip on the way: with 1 the store tries again and
+ every check passes, with 2 the clip never comes.
- `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 five backgrounds'
diff --git a/harness/player/main.m b/harness/player/main.m
index cee79d58..816153a4 100644
--- a/harness/player/main.m
+++ b/harness/player/main.m
@@ -100,6 +100,14 @@ static void serve(NSString *imageURI, UIImage *image, NSTimeInterval delay, BOOL
if ([self.request.URL.host isEqualToString:@"canvas.harness"]) {
const char *file = getenv("HARNESS_CANVAS_FILE"), *delay = getenv("HARNESS_CANVAS_DELAY");
NSData *data = file ? [NSData dataWithContentsOfFile:@(file)] : nil;
+ // HARNESS_CANVAS_FAILS=n: the first n requests for it fail on the way, as a download iOS cancelled.
+ static int failing = -1;
+ if (failing < 0) failing = getenv("HARNESS_CANVAS_FAILS") ? atoi(getenv("HARNESS_CANVAS_FAILS")) : 0;
+ if (failing > 0) {
+ failing--;
+ data = nil;
+ NSLog(@"[harness] canvas server: this request fails");
+ }
NSThread *thread = NSThread.currentThread;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((delay ? atof(delay) : 0) * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
sg_canvasServed++;
@@ -389,6 +397,7 @@ static void loadLyrics(void) {
UIViewController *_background;
UIView *_tilt;
NSUInteger _failures, _checks;
+ float _dimAlone; // the motion scenario's dim before the lyrics
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options {
@@ -900,6 +909,17 @@ static BOOL fieldCovered(void) {
[self expect:seam.effect && !lyrics.effect step:@"the blur from the seam"
detail:[NSString stringWithFormat:@"seam blur %@, from %@ of the height, lyrics blur %@", seam.effect ? @"on" : @"off",
[[seam.maskView.layer.sublayers.firstObject valueForKey:@"locations"] componentsJoinedByString:@" to "], lyrics.effect ? @"on" : @"off"]];
+ // Dimmed by its brightness: HARNESS_DIM is what the clip in HARNESS_CANVAS_FILE should get (0.54 for white,
+ // 0.10 for black); the rule itself is checked at its ends.
+ CALayer *dim = [motion valueForKey:@"_dim"];
+ const char *expected = getenv("HARNESS_DIM");
+ BOOL rule = fabs(SGRPlayerClipDim(1, NO, NO) - 0.54) < 0.01 && fabs(SGRPlayerClipDim(1, YES, NO) - 0.65) < 0.01
+ && SGRPlayerClipDim(0, NO, NO) == 0.10 && fabs(SGRPlayerClipDim(0, NO, YES) - 0.25) < 1e-6
+ && fabs(SGRPlayerClipDim(0.5, NO, NO) - 0.37) < 0.01;
+ self->_dimAlone = dim.opacity;
+ [self expect:rule && dim && dim.superlayer == clip.superlayer.superlayer && (!expected || fabs(dim.opacity - atof(expected)) < 0.02)
+ step:@"the dim" detail:[NSString stringWithFormat:@"rule %@, dim %.2f over the clip%@", rule ? @"right" : @"wrong", dim.opacity,
+ expected ? [NSString stringWithFormat:@", %s expected", expected] : @""]];
NSLog(@"[harness] motion: screenshot the clip now");
});
after(7, ^{ SGRPlayerToggleLyrics(); });
@@ -910,6 +930,9 @@ static BOOL fieldCovered(void) {
if ([NSStringFromClass(view.class) isEqualToString:@"SGRPlayerLyricsOverlay"]) thumb = [view valueForKey:@"thumb"];
}
BOOL away = thumb && !CGAffineTransformIsIdentity(thumb.transform) && thumb.alpha > 0.99;
+ float dim = ((CALayer *)[motionView() valueForKey:@"_dim"]).opacity;
+ [self expect:fabsf(dim - self->_dimAlone - 0.15f) < 0.01f step:@"the dim under the lyrics"
+ detail:[NSString stringWithFormat:@"%.2f, %.2f without them", dim, self->_dimAlone]];
[self expect:SGRPlayerLyricsOpen() && lyrics.effect && away step:@"the lyrics"
detail:[NSString stringWithFormat:@"lyrics %@, clip blurred %@, thumbnail %@ at alpha %.2f", SGRPlayerLyricsOpen() ? @"up" : @"down",
lyrics.effect ? @"yes" : @"no", thumb && !CGAffineTransformIsIdentity(thumb.transform) ? @"in its corner" : @"at the cover", thumb.alpha]];
@@ -1017,7 +1040,42 @@ static BOOL fieldCovered(void) {
[self expect:SGRPlayerMotionShowing() && motionView() != before && mask && mask.opacity == 0 step:@"the next clip over the last"
detail:[NSString stringWithFormat:@"%@, cover %@", motionView() != before ? @"a new clip" : @"the same clip", mask && mask.opacity == 0 ? @"still hidden" : @"back"]];
});
- after(23, ^{
+ // Low Power Mode (Reduce Motion takes the same path): the clip goes for Fluid and the cover, and comes back
+ // once it is off. The simulator has no Low Power Mode, so the process says it is on.
+ __block BOOL lowPower = NO;
+ after(22.5, ^{
+ Class info = object_getClass(NSProcessInfo.processInfo);
+ for (NSString *name in @[@"isLowPowerModeEnabled", @"lowPowerModeEnabled"]) {
+ Method method = class_getInstanceMethod(info, NSSelectorFromString(name));
+ if (method) method_setImplementation(method, imp_implementationWithBlock(^BOOL(id process) { return lowPower; }));
+ }
+ lowPower = YES;
+ [NSNotificationCenter.defaultCenter postNotificationName:NSProcessInfoPowerStateDidChangeNotification object:nil]; });
+ after(23.5, ^{
+ [self expect:!SGRPlayerMotionShowing() && !motionView() && !self->_covers.layer.mask step:@"Low Power Mode"
+ detail:[NSString stringWithFormat:@"clip %@, cover %@", motionView() ? @"still there" : @"gone", self->_covers.layer.mask ? @"hidden" : @"back"]];
+ lowPower = NO;
+ [NSNotificationCenter.defaultCenter postNotificationName:NSProcessInfoPowerStateDidChangeNotification object:nil];
+ });
+ // A track change with the app in the background: the last clip goes at once, with no fade to come back to.
+ __block UIApplicationState state = UIApplicationStateActive;
+ after(24.5, ^{
+ [self expect:SGRPlayerMotionShowing() && self->_covers.layer.mask step:@"Low Power Mode off"
+ detail:SGRPlayerMotionShowing() ? @"the clip back" : @"no clip"];
+ Method method = class_getInstanceMethod(UIApplication.class, @selector(applicationState));
+ method_setImplementation(method, imp_implementationWithBlock(^UIApplicationState(id app) { return state; }));
+ state = UIApplicationStateBackground;
+ unsetenv("HARNESS_CANVAS");
+ SGRHarnessSetTrack(@"spotify:track:harnessD", imageURI(@"dddd"), NO);
+ });
+ after(24.6, ^{
+ CALayer *mask = self->_covers.layer.mask;
+ [self expect:!SGRPlayerMotionShowing() && !motionView() && !mask step:@"a track change in the background"
+ detail:[NSString stringWithFormat:@"clip %@, cover %@", motionView() ? @"still there" : @"gone at once",
+ mask ? [NSString stringWithFormat:@"hidden, at %.2f", mask.opacity] : @"back at once"]];
+ state = UIApplicationStateActive;
+ });
+ after(25, ^{
NSLog(@"[harness] motion checks: %lu of %lu right -- %@", (unsigned long)(self->_checks - self->_failures), (unsigned long)self->_checks,
self->_failures ? @"FAIL" : @"PASS");
});
diff --git a/tweak/Sources/Redesigned/Kit/SGRFluid.m b/tweak/Sources/Redesigned/Kit/SGRFluid.m
index 8e43c6ad..a1b6ada2 100644
--- a/tweak/Sources/Redesigned/Kit/SGRFluid.m
+++ b/tweak/Sources/Redesigned/Kit/SGRFluid.m
@@ -17,7 +17,7 @@ static const CGFloat kBlurSide = 128, kBlurRadius = 10, kSaturation = 1.5, kBrig
// The shade over the bottom of the visible rect, where the controls are.
static const CGFloat kShadeFrom = 0.45, kShadeAlpha = 0.55;
-static UIImage *blurred(UIImage *image) {
+static UIImage *blurred(UIImage *image, BOOL contrast) {
CGImageRef source = image.CGImage;
if (!source) return nil;
CIImage *input = [CIImage imageWithCGImage:source];
@@ -32,8 +32,38 @@ static UIImage *blurred(UIImage *image) {
dispatch_once(&once, ^{ context = [CIContext contextWithOptions:nil]; });
CGImageRef cg = [context createCGImage:[output imageByCroppingToRect:extent] fromRect:extent];
if (!cg) return nil;
- UIImage *result = [UIImage imageWithCGImage:cg];
+ // Each blurred pixel is capped at a linear luminance (0.04 with Increase Contrast) that keeps the player's
+ // white text at about 8.8:1 and its 65% white at about 4.7:1 on the brightest; an average alone would leave
+ // a bright patch of a cover behind the text.
+ size_t width = CGImageGetWidth(cg), height = CGImageGetHeight(cg);
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ CGContextRef bitmap = CGBitmapContextCreate(NULL, width, height, 8, width * 4, space,
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
+ CGColorSpaceRelease(space);
+ if (!bitmap) { CGImageRelease(cg); return nil; }
+ CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), cg);
CGImageRelease(cg);
+ unsigned char *pixels = CGBitmapContextGetData(bitmap);
+ CGFloat ceiling = contrast ? 0.04 : 0.07;
+ for (size_t i = 0; i < width * height; i++) {
+ unsigned char *p = pixels + i * 4;
+ CGFloat rgb[3];
+ for (int c = 0; c < 3; c++) {
+ CGFloat v = p[c] / 255.0;
+ rgb[c] = v <= 0.04045 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4);
+ }
+ CGFloat light = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
+ CGFloat gain = light > ceiling ? ceiling / light : 1;
+ for (int c = 0; c < 3; c++) {
+ CGFloat v = rgb[c] * gain;
+ p[c] = floor(255 * (v <= 0.0031308 ? v * 12.92 : 1.055 * pow(v, 1 / 2.4) - 0.055));
+ }
+ p[3] = 255;
+ }
+ cg = CGBitmapContextCreateImage(bitmap);
+ UIImage *result = cg ? [UIImage imageWithCGImage:cg] : nil;
+ if (cg) CGImageRelease(cg);
+ CGContextRelease(bitmap);
return result;
}
@@ -60,9 +90,23 @@ static UIImage *blurred(UIImage *image) {
_shade = [CAGradientLayer layer];
_shade.colors = @[(id)[UIColor colorWithWhite:0 alpha:0].CGColor, (id)[UIColor colorWithWhite:0 alpha:kShadeAlpha].CGColor];
[self addSublayer:_shade];
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(contrastChanged)
+ name:UIAccessibilityDarkerSystemColorsStatusDidChangeNotification object:nil];
return self;
}
+- (void)dealloc {
+ [NSNotificationCenter.defaultCenter removeObserver:self];
+}
+
+- (void)contrastChanged {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ UIImage *source = self->_source;
+ self->_source = nil;
+ [self setArtwork:source animated:NO];
+ });
+}
+
- (BOOL)moving {
return _moving;
}
@@ -103,9 +147,10 @@ static UIImage *blurred(UIImage *image) {
if (!image || image == _source) return;
_source = image;
NSUInteger generation = ++_generation;
+ BOOL contrast = SGRIncreaseContrast();
__weak SGRFluidLayer *weakSelf = self;
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
- UIImage *blur = blurred(image);
+ UIImage *blur = blurred(image, contrast);
dispatch_async(dispatch_get_main_queue(), ^{
SGRFluidLayer *layer = weakSelf;
if (!blur || !layer || generation != layer->_generation) return;
diff --git a/tweak/Sources/Redesigned/Player/Player.h b/tweak/Sources/Redesigned/Player/Player.h
index f089a509..8e737d07 100644
--- a/tweak/Sources/Redesigned/Player/Player.h
+++ b/tweak/Sources/Redesigned/Player/Player.h
@@ -110,6 +110,10 @@ BOOL SGRPlayerMotionShowing(void);
// `arrived` runs once on the main queue when a call would return it (never when nothing is found, or the
// track changed). Without `arrived` it only answers with a clip already in.
UIView *SGRPlayerMotionPreview(void (^arrived)(void));
+// How dark the clip is drawn (a black layer's opacity) for white text over it to keep 4.5:1, or 7:1 with
+// `contrast` (Increase Contrast), when `luminance` is the clip's bright end, its 75th percentile of linear
+// luminance; between 0.10 and 0.80, 0.15 more while the lyrics are up.
+CGFloat SGRPlayerClipDim(CGFloat luminance, BOOL contrast, BOOL lyrics);
#pragma mark - the Visualiser (PlayerVisualiser.m)
diff --git a/tweak/Sources/Redesigned/Player/PlayerMotion.x b/tweak/Sources/Redesigned/Player/PlayerMotion.x
index 309d74da..631965fc 100644
--- a/tweak/Sources/Redesigned/Player/PlayerMotion.x
+++ b/tweak/Sources/Redesigned/Player/PlayerMotion.x
@@ -13,10 +13,18 @@
// Spotify built again, gets it.
//
// The clip holds still when the moving field does (SGRField.m): out of a window, with the app not in front,
-// while the player opens or closes, under Reduce Motion and in Low Power Mode, and while the song is paused.
+// while the player opens or closes, and while the song is paused. Under Reduce Motion and in Low Power Mode
+// no clip plays at all: the cover stays over Fluid, as for a track without one, until both are off again.
// While a clip is showing, the Fluid field under it is held still too, and once the clip has faded in it is
// hidden (the field's covered): the field's colour is what shows above the clip on the pull that dismisses.
//
+// The clip is dimmed by how bright it is (SGRPlayerClipDim): three of its frames are measured as it comes in,
+// so a white Canvas is drawn darker than a black one and the white text over it keeps its contrast.
+//
+// A track that changes while the player cannot be seen (out of a window, or with the app not in front, which a
+// locked phone's player is while it stays in its window) takes the last clip away at once, without a fade, so
+// the last track's clip does not greet the player as it opens.
+//
// The clip and the cover cross over: the clip fades in from its first frame (the poster, under the video
// until the video has decoded one) as the cover fades out, and fades out as the cover comes back. A clip
// that has drawn no frame of its own after kGiveUp seconds on screen is given up, and the cover comes back.
@@ -47,6 +55,55 @@ static const CGFloat kBlurByControls = 0.6, kBlurRamp = 96;
static const NSTimeInterval kGiveUp = 5;
// Seconds the last track's clip stays on a skip for the next one's to come in over it.
static const NSTimeInterval kHandOver = 0.4;
+// The dim's floor and ceiling, and what the lyrics add to it.
+static const CGFloat kDimLeast = 0.10, kDimMost = 0.80, kDimLyrics = 0.15;
+// The frames measured for the dim besides the poster, in seconds into the clip (one past its end is skipped).
+static const double kMeasuredAt[] = {1, 2};
+
+CGFloat SGRPlayerClipDim(CGFloat luminance, BOOL contrast, BOOL lyrics) {
+ // White is 1, so (1 + 0.05) / (L + 0.05) >= ratio puts the clip's luminance at `most` or under.
+ CGFloat ratio = contrast ? 7 : 4.5, most = 1.05 / ratio - 0.05;
+ // A black layer scales the clip's encoded values, which Core Animation blends, so its linear luminance
+ // goes down by about the 2.2nd power of what the layer leaves.
+ CGFloat dim = luminance > most ? 1 - pow(most / luminance, 1 / 2.2) : 0;
+ dim = MIN(MAX(dim, kDimLeast), kDimMost);
+ return lyrics ? dim + kDimLyrics : dim;
+}
+
+// Each pixel's linear luminance, of the image drawn 16 points square, onto `into` as floats.
+static void addLuminances(CGImageRef image, NSMutableData *into) {
+ if (!image) return;
+ enum { kSide = 16 };
+ uint8_t pixels[kSide * kSide * 4];
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ CGContextRef context = CGBitmapContextCreate(pixels, kSide, kSide, 8, kSide * 4, space, (CGBitmapInfo)kCGImageAlphaNoneSkipLast);
+ CGColorSpaceRelease(space);
+ if (!context) return;
+ CGContextDrawImage(context, CGRectMake(0, 0, kSide, kSide), image);
+ CGContextRelease(context);
+ for (int i = 0; i < kSide * kSide; i++) {
+ float linear[3];
+ for (int c = 0; c < 3; c++) {
+ float v = pixels[i * 4 + c] / 255.0f;
+ linear[c] = v <= 0.04045f ? v / 12.92f : powf((v + 0.055f) / 1.055f, 2.4f);
+ }
+ float luminance = 0.2126f * linear[0] + 0.7152f * linear[1] + 0.0722f * linear[2];
+ [into appendBytes:&luminance length:sizeof luminance];
+ }
+}
+
+// The 75th percentile of the luminances: the bright end the text has to stand out against, past a few
+// highlights.
+static CGFloat brightEnd(NSData *luminances) {
+ NSUInteger count = luminances.length / sizeof(float);
+ if (!count) return 0;
+ NSMutableData *sorted = [luminances mutableCopy];
+ qsort_b(sorted.mutableBytes, count, sizeof(float), ^int(const void *a, const void *b) {
+ float x = *(const float *)a, y = *(const float *)b;
+ return x < y ? -1 : x > y;
+ });
+ return ((const float *)sorted.bytes)[(count - 1) * 3 / 4];
+}
@interface SGRPlayerMotionView : UIView <SGPlayerStateObserver>
@property (nonatomic) CGFloat screenHeight;
@@ -65,6 +122,9 @@ static const NSTimeInterval kHandOver = 0.4;
AVPlayerLayer *_clip;
CAGradientLayer *_clipMask, *_seamMask;
CALayer *_foot;
+ CALayer *_dim; // black over the clip and its foot, as dark as the clip is bright
+ NSMutableData *_luminances; // of the frames measured so far
+ BOOL _lyricsUp;
UIVisualEffectView *_seamBlur, *_lyricsBlur;
CGFloat _aspect;
BOOL _timing; // the give-up's count is running
@@ -99,6 +159,10 @@ static UIBlurEffect *blurEffect(void) {
_clipMask.locations = @[@0, @(kFootFrom), @1];
_still.mask = _clipMask;
[_picture.layer addSublayer:_still];
+ _dim = [CALayer layer];
+ _dim.backgroundColor = UIColor.blackColor.CGColor;
+ _dim.opacity = kDimLeast;
+ [_picture.layer addSublayer:_dim];
_seamBlur = [[UIVisualEffectView alloc] initWithEffect:nil];
_seamBlur.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
@@ -117,6 +181,7 @@ static UIBlurEffect *blurEffect(void) {
NSProcessInfoPowerStateDidChangeNotification, UIAccessibilityReduceMotionStatusDidChangeNotification]) {
[center addObserver:self selector:@selector(updateMotionSoon) name:name object:nil];
}
+ [center addObserver:self selector:@selector(updateDim) name:UIAccessibilityDarkerSystemColorsStatusDidChangeNotification object:nil];
SGRObservePlayerTransition(self, ^(id owner) { [owner updateMotion]; }, ^(id owner) { [owner updateMotion]; });
SGAddPlayerStateObserver(self);
return self;
@@ -154,6 +219,7 @@ static UIBlurEffect *blurEffect(void) {
_clip.frame = _still.bounds;
_clipMask.frame = _still.bounds;
_foot.frame = CGRectMake(0, seam, width, MAX(0, total - seam));
+ _dim.frame = bounds;
_seamMask.frame = bounds;
_seamMask.locations = @[@(MIN(1, blurFrom / total)), @(MIN(1, (blurFrom + kBlurRamp) / total))];
[CATransaction commit];
@@ -173,6 +239,41 @@ static UIBlurEffect *blurEffect(void) {
_clip.player = _player;
[self setNeedsLayout];
[self updateMotion];
+ [self measure:file poster:poster];
+}
+
+// The poster now, so the clip comes in already dimmed, and two later frames as they are read.
+- (void)measure:(NSURL *)file poster:(UIImage *)poster {
+ _luminances = [NSMutableData data];
+ addLuminances(poster.CGImage, _luminances);
+ [CATransaction begin];
+ [CATransaction setDisableActions:YES];
+ [self updateDim];
+ [CATransaction commit];
+ AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:[AVURLAsset assetWithURL:file]];
+ generator.appliesPreferredTrackTransform = YES;
+ generator.maximumSize = CGSizeMake(64, 64);
+ __weak SGRPlayerMotionView *weakSelf = self;
+ NSMutableData *into = _luminances;
+ for (size_t i = 0; i < sizeof kMeasuredAt / sizeof *kMeasuredAt; i++) {
+ [generator generateCGImageAsynchronouslyForTime:CMTimeMakeWithSeconds(kMeasuredAt[i], 600)
+ completionHandler:^(CGImageRef image, CMTime actual, NSError *error) {
+ if (!image) return;
+ NSMutableData *frame = [NSMutableData data];
+ addLuminances(image, frame);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ SGRPlayerMotionView *view = weakSelf;
+ if (!view || view->_luminances != into) return;
+ [into appendData:frame];
+ [view updateDim];
+ });
+ }];
+ }
+}
+
+- (void)updateDim {
+ CGFloat dim = SGRPlayerClipDim(brightEnd(_luminances), UIAccessibilityDarkerSystemColorsEnabled(), _lyricsUp);
+ _dim.opacity = (float)dim;
}
// `done` runs once the clip is opaque, unless something cut the fade in short.
@@ -201,8 +302,15 @@ static UIBlurEffect *blurEffect(void) {
}, ^(BOOL finished) { done(); });
}
+// The lyrics' blur, and their share of the dim, which a layer's own animation carries over the same fade.
- (void)setBlurred:(BOOL)blurred animated:(BOOL)animated {
+ _lyricsUp = blurred;
void (^apply)(void) = ^{ self->_lyricsBlur.effect = blurred ? blurEffect() : nil; };
+ [CATransaction begin];
+ [CATransaction setDisableActions:!animated];
+ [CATransaction setAnimationDuration:SGRCrossfade];
+ [self updateDim];
+ [CATransaction commit];
if (animated) SGRAnimate(SGRMotionFade, apply, nil);
else apply();
}
@@ -409,7 +517,17 @@ static BOOL videoShowing(void) {
return sg_videos.allObjects.count > 0;
}
-// The clip fades out over the cover coming back where the player is on screen, and goes at once where not.
+// Reduce Motion asks for no looping clip, and Low Power Mode for no video decoding behind the player.
+static BOOL motionAllowed(void) {
+ return !SGRReduceMotion() && !NSProcessInfo.processInfo.lowPowerModeEnabled;
+}
+
+// The clip can be seen: in a window, with the app in front.
+static BOOL seen(UIView *view) {
+ return view.window && UIApplication.sharedApplication.applicationState == UIApplicationStateActive;
+}
+
+// The clip fades out over the cover coming back where the player is seen, and goes at once where not.
static void clear(BOOL animated) {
SGRPlayerMotionView *old = sg_motion;
sg_motion = nil;
@@ -419,7 +537,7 @@ static void clear(BOOL animated) {
// Uncovered before the clip starts to fade, so the field is there under it.
cover(NO);
holdField();
- animated = animated && old.window != nil;
+ animated = animated && seen(old);
setCoverShown(YES, animated);
if (animated) [old disappear:^{ [old removeFromSuperview]; }];
else [old removeFromSuperview];
@@ -446,7 +564,7 @@ static void show(NSString *track, NSURL *file) {
layOut();
holdField();
[sg_motion setBlurred:SGRPlayerLyricsOpen() animated:NO];
- BOOL animated = sg_motion.window != nil;
+ BOOL animated = seen(sg_motion);
[motion appear:animated then:^{
if (sg_motion == motion) cover(YES);
}];
@@ -471,15 +589,16 @@ static void videoSurface(id unit, BOOL attached) {
}
// A skip on screen leaves the last clip a moment for the next one's to cross over, and the same track
-// walked again (its Canvas came late) keeps its clip until the new one does. Otherwise the clip goes at
-// once: off screen, for Spotify's video, and when the background is not Animated.
+// walked again (its Canvas came late) keeps its clip until the new one does. Otherwise the clip goes: at
+// once where it cannot be seen, with a fade for Spotify's video, under Reduce Motion or Low Power Mode, and
+// when the background is not Animated.
static BOOL beginTrack(NSString *track) {
sg_track = track;
sg_begun++;
// Read on every track, since the ⋯ menu switches it.
- BOOL wanted = SGRPlayerBackground() == SGRPlayerBackgroundAnimated && !videoShowing();
+ BOOL wanted = SGRPlayerBackground() == SGRPlayerBackgroundAnimated && !videoShowing() && motionAllowed();
if (wanted && [track isEqualToString:sg_shown]) return YES;
- if (!wanted || !sg_motion.window) {
+ if (!wanted || !seen(sg_motion)) {
clear(YES);
return wanted;
}
@@ -552,6 +671,20 @@ void SGPlayerMenuSetAnimatedArtwork(BOOL on) {
SGRPlayerBackgroundKind background = SGRPlayerBackground();
if (background < SGRPlayerBackgroundFluid) return;
sg_videos = [NSHashTable weakObjectsHashTable];
+ // Here rather than on the clip's view, which is gone while they hold it off: the track is walked again
+ // as either changes. The power state is reported off the main thread, which must not wait for main
+ // (AGENTS.md), so the observer takes it where it is posted and hops.
+ __block BOOL allowed = motionAllowed();
+ for (NSNotificationName name in @[NSProcessInfoPowerStateDidChangeNotification, UIAccessibilityReduceMotionStatusDidChangeNotification]) {
+ [NSNotificationCenter.defaultCenter addObserverForName:name object:nil queue:nil usingBlock:^(NSNotification *note) {
+ dispatch_async(dispatch_get_main_queue(), ^{
+ if (motionAllowed() == allowed) return;
+ allowed = !allowed;
+ SGLog(@"redesign player: animated artwork %@", allowed ? @"allowed again, the clip looked up" : @"held off by Reduce Motion or Low Power Mode, Fluid shows");
+ [sg_follower restart];
+ });
+ }];
+ }
sg_follower = [[SGMotionFollower alloc] initWithBegin:^BOOL(NSString *uri, SPTPlayerState *state) {
return beginTrack(uri);
} found:^(NSString *uri, NSURL *file) {
diff --git a/tweak/Sources/Shared/AnimatedArtwork/SGMotionStore.m b/tweak/Sources/Shared/AnimatedArtwork/SGMotionStore.m
index 0cb2688d..721d2417 100644
--- a/tweak/Sources/Shared/AnimatedArtwork/SGMotionStore.m
+++ b/tweak/Sources/Shared/AnimatedArtwork/SGMotionStore.m
@@ -49,36 +49,30 @@ NSURL *SGMotionMadeFile(NSString *key) {
static NSMutableDictionary<NSURL *, NSMutableArray *> *sg_waiting;
-void SGMotionFile(NSURL *remote, void (^done)(NSURL *file)) {
- if (!remote) {
- done(nil);
- return;
- }
- NSURL *local = localFor(remote.absoluteString);
- if ([NSFileManager.defaultManager fileExistsAtPath:local.path]) {
- done(local);
- return;
- }
- if (!sg_waiting) sg_waiting = [NSMutableDictionary dictionary];
- if (sg_waiting[remote]) {
- [sg_waiting[remote] addObject:[done copy]];
- return;
- }
- sg_waiting[remote] = [NSMutableArray arrayWithObject:[done copy]];
+// A download that failed on the way (the lock screen and the player can share one, and iOS can cancel it with
+// the lock screen's request) or met a busy server is tried `retries` more times before its waiters hear nil;
+// an answer that says the file is not there is final.
+static void download(NSURL *remote, NSURL *local, NSUInteger retries) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:remote];
request.allowsConstrainedNetworkAccess = SGFlag(SGKeyMotionLowData, NO);
[[NSURLSession.sharedSession downloadTaskWithRequest:request completionHandler:^(NSURL *temporary, NSURLResponse *response, NSError *error) {
NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;
// The temporary file is gone once this handler returns, so it moves before the hop to main.
BOOL kept = temporary && status == 200 && [NSFileManager.defaultManager moveItemAtURL:temporary toURL:local error:nil];
+ BOOL again = !kept && retries > 0 && (error || status == 0 || status == 408 || status == 429 || status >= 500);
if (kept) {
trim();
NSNumber *bytes = nil;
[local getResourceValue:&bytes forKey:NSURLFileSizeKey error:nil];
SGLog(@"motion: %@ kept, %.1f MB", local.lastPathComponent, bytes.doubleValue / 1e6);
}
- else SGLog(@"motion: %@ not downloaded (%ld, %@)", remote.lastPathComponent, (long)status, error.localizedDescription);
+ else SGLog(@"motion: %@ not downloaded (%ld, %@)%@", remote.lastPathComponent, (long)status, error.localizedDescription,
+ again ? @", tried again" : @"");
dispatch_async(dispatch_get_main_queue(), ^{
+ if (again) {
+ download(remote, local, retries - 1);
+ return;
+ }
NSArray *waiting = sg_waiting[remote];
[sg_waiting removeObjectForKey:remote];
for (void (^waiter)(NSURL *) in waiting) waiter(kept ? local : nil);
@@ -86,6 +80,25 @@ void SGMotionFile(NSURL *remote, void (^done)(NSURL *file)) {
}] resume];
}
+void SGMotionFile(NSURL *remote, void (^done)(NSURL *file)) {
+ if (!remote) {
+ done(nil);
+ return;
+ }
+ NSURL *local = localFor(remote.absoluteString);
+ if ([NSFileManager.defaultManager fileExistsAtPath:local.path]) {
+ done(local);
+ return;
+ }
+ if (!sg_waiting) sg_waiting = [NSMutableDictionary dictionary];
+ if (sg_waiting[remote]) {
+ [sg_waiting[remote] addObject:[done copy]];
+ return;
+ }
+ sg_waiting[remote] = [NSMutableArray arrayWithObject:[done copy]];
+ download(remote, local, 1);
+}
+
void SGMotionPoster(NSURL *file, void (^done)(UIImage *poster)) {
AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:[AVURLAsset assetWithURL:file]];
generator.appliesPreferredTrackTransform = YES;