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
17.9 KB
Raw Blame
#import <CoreImage/CoreImage.h>
#import "Core/SGCore.h"
#import "SGRPalette.h"
#import "SGRTokens.h"

static const size_t kSample = 64;      // the artwork shrunk to this square before its colors are read
static const size_t kEdgeRows = 10;    // the bottom rows of it averaged into the edge color
static const CGFloat kMaxSaturation = 0.55;
static const CGFloat kMaxLuminance = 0.07, kMaxLuminanceContrast = 0.04;
static const CGFloat kBackdropWidth = 160, kBackdropMaxHeight = 400, kBackdropSigma = 12;
static const CGFloat kDissolveWidth = 96, kDissolveSigma = 5;
static const CGFloat kFadeFrom = 0.55, kDissolveOpaque = 0.85;
// A tint: the artwork's dominant color, its saturation lifted by kTintSaturationLift up to kTintSaturationMax,
// brought down to kTintLuminance, then kTintShare of it mixed into the surface it tints. Measured off the
// reference's Home (IMG_4025, 2026-10-11): its card and tile surfaces sit at a luminance of 0.03 to 0.04 with the
// cover's saturation about 1.2 times (0.73 to 0.86, 0.57 to 0.71, 0.29 to 0.36). White text keeps better than
// 11:1 on anything under 0.04.
static const CGFloat kTintLuminance = 0.04, kTintShare = 1.0;
static const CGFloat kTintSaturationLift = 1.2, kTintSaturationMax = 0.85;
// The faint tint of before (strong NO): no lift, 35% of the color held under 0.05 mixed into the surface.
static const CGFloat kFaintTintLuminance = 0.05, kFaintTintShare = 0.35;
// A moving field's colors: luminance held between these (the ceiling 0.07 with Increase Contrast, as a
// field's), saturation lifted by this much up to a cap, and a near-black one lifted by at most this factor.
static const CGFloat kFlowLuminanceMin = 0.03, kFlowLuminanceMax = 0.13;
static const CGFloat kFlowSaturationLift = 1.25, kFlowSaturationMax = 0.9, kFlowMaxLift = 4;

@interface SGRPalette ()
@property (nonatomic, readwrite) UIColor *edgeColor;
@property (nonatomic, readwrite) UIColor *fieldColor;
@property (nonatomic, readwrite) UIImage *backdrop;
@property (nonatomic, readwrite) UIImage *dissolve;
@property (nonatomic, readwrite) NSArray<UIColor *> *flowColors;
@end

static dispatch_queue_t paletteQueue(void) {
    static dispatch_queue_t queue;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        queue = dispatch_queue_create("spotifyglass.redesign.palette", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0));
    });
    return queue;
}

static CGColorSpaceRef sRGB(void) {
    static CGColorSpaceRef space;
    static dispatch_once_t once;
    dispatch_once(&once, ^{ space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); });
    return space;
}

// One context for the whole launch; CIContext is safe to share and costly to make.
static CIContext *blurContext(void) {
    static CIContext *context;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        context = [CIContext contextWithOptions:@{kCIContextCacheIntermediates: @NO, kCIContextWorkingColorSpace: (__bridge id)sRGB()}];
    });
    return context;
}

static CGContextRef newBitmap(size_t width, size_t height) {
    return CGBitmapContextCreate(NULL, width, height, 8, width * 4, sRGB(), (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
}

static void drawFilling(CGContextRef context, CGImageRef image, size_t width, size_t height) {
    CGFloat iw = CGImageGetWidth(image), ih = CGImageGetHeight(image);
    CGFloat scale = MAX(width / iw, height / ih);
    CGContextSetInterpolationQuality(context, kCGInterpolationMedium);
    CGContextDrawImage(context, CGRectMake((width - iw * scale) / 2, (height - ih * scale) / 2, iw * scale, ih * scale), image);
}

#pragma mark - color

static CGFloat toLinear(CGFloat c) {
    return c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4);
}

static CGFloat toEncoded(CGFloat c) {
    return c <= 0.0031308 ? c * 12.92 : 1.055 * pow(c, 1 / 2.4) - 0.055;
}

static UIColor *fieldColorFor(UIColor *color, CGFloat ceiling) {
    CGFloat r = 0, g = 0, b = 0, a = 1, h = 0, s = 0, v = 0;
    if (![color getRed:&r green:&g blue:&b alpha:&a]) {
        CGFloat white = 0;
        if (![color getWhite:&white alpha:&a]) return SGRNeutralField();
        r = g = b = white;
    }
    UIColor *clamped = [UIColor colorWithRed:MIN(1, MAX(0, r)) green:MIN(1, MAX(0, g)) blue:MIN(1, MAX(0, b)) alpha:1];
    [clamped getHue:&h saturation:&s brightness:&v alpha:&a];
    [[UIColor colorWithHue:h saturation:MIN(s, kMaxSaturation) brightness:v alpha:1] getRed:&r green:&g blue:&b alpha:&a];
    CGFloat lr = toLinear(r), lg = toLinear(g), lb = toLinear(b);
    CGFloat luminance = 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;
    if (luminance > ceiling) {
        CGFloat k = ceiling / luminance;
        lr *= k, lg *= k, lb *= k;
    }
    return [UIColor colorWithRed:toEncoded(lr) green:toEncoded(lg) blue:toEncoded(lb) alpha:1];
}

UIColor *SGRFieldColorFor(UIColor *color) {
    return color ? fieldColorFor(color, SGRIncreaseContrast() ? kMaxLuminanceContrast : kMaxLuminance) : SGRNeutralField();
}

// The artwork squeezed into a small square, whatever its aspect, and the bottom rows of that averaged
// by coverage. A bitmap context keeps its rows top to bottom, so the last rows are the bottom edge.
static UIColor *edgeColorOf(CGImageRef image) {
    CGContextRef context = newBitmap(kSample, kSample);
    if (!context) return nil;
    CGContextSetInterpolationQuality(context, kCGInterpolationMedium);
    CGContextDrawImage(context, CGRectMake(0, 0, kSample, kSample), image);
    const uint8_t *px = CGBitmapContextGetData(context);
    double r = 0, g = 0, b = 0, coverage = 0;
    for (size_t y = kSample - kEdgeRows; px && y < kSample; y++) {
        for (size_t x = 0; x < kSample; x++) {
            const uint8_t *p = px + (y * kSample + x) * 4;
            r += p[0], g += p[1], b += p[2], coverage += p[3];
        }
    }
    CGContextRelease(context);
    // Premultiplied, so the sums over the summed alpha are the average of what is actually there.
    if (coverage < 1) return nil;
    return [UIColor colorWithRed:r / coverage green:g / coverage blue:b / coverage alpha:1];
}

#pragma mark - bitmaps

// The artwork drawn to fill the size, then blurred with its edges clamped so the border does not
// darken. Returned retained.
static CGImageRef newBlurred(CGImageRef image, size_t width, size_t height, CGFloat sigma) {
    CGContextRef context = newBitmap(width, height);
    if (!context) return NULL;
    drawFilling(context, image, width, height);
    CGImageRef small = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    if (!small) return NULL;
    CIImage *input = [CIImage imageWithCGImage:small];
    CGImageRelease(small);
    CIImage *output = [[input imageByClampingToExtent] imageByApplyingGaussianBlurWithSigma:sigma];
    return [blurContext() createCGImage:output fromRect:input.extent format:kCIFormatRGBA8 colorSpace:sRGB()];
}

// A black gradient from `a0` at `y0` to `a1` at `y1` (shares of the height, top down), extended
// past both ends; with kCGBlendModeDestinationIn it becomes an alpha ramp instead of a dim.
static void drawRamp(CGContextRef context, size_t height, CGFloat y0, CGFloat a0, CGFloat y1, CGFloat a1, CGBlendMode mode) {
    CGFloat components[] = {0, 0, 0, a0, 0, 0, 0, a1};
    CGFloat locations[] = {0, 1};
    CGGradientRef gradient = CGGradientCreateWithColorComponents(sRGB(), components, locations, 2);
    CGContextSetBlendMode(context, mode);
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0, y0 * height), CGPointMake(0, y1 * height),
                                kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    CGGradientRelease(gradient);
}

static UIImage *finished(CGImageRef blurred, BOOL dim, CGFloat dimBottom, CGFloat rampFrom, CGFloat alphaFrom, CGFloat rampTo, CGFloat alphaTo) {
    size_t width = CGImageGetWidth(blurred), height = CGImageGetHeight(blurred);
    CGContextRef context = newBitmap(width, height);
    if (!context) return nil;
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), blurred);
    // Top down from here on.
    CGContextTranslateCTM(context, 0, height);
    CGContextScaleCTM(context, 1, -1);
    if (dim) drawRamp(context, height, 0, 0.25, kFadeFrom, dimBottom, kCGBlendModeNormal);
    drawRamp(context, height, rampFrom, alphaFrom, rampTo, alphaTo, kCGBlendModeDestinationIn);
    CGImageRef result = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    UIImage *image = result ? [UIImage imageWithCGImage:result scale:1 orientation:UIImageOrientationUp] : nil;
    CGImageRelease(result);
    return image;
}

#pragma mark - tint

// The artwork's dominant color in linear light: its pixels binned 3 bits a channel, each bin scored by its
// count weighted toward colorful pixels, so a busy cover gives its main color instead of the gray an
// average makes. Near-black and near-white count for little unless they are nearly all there is.
// The same over the rows y0..y1 and columns x0..x1 of a kSample square bitmap (rows top down).
static BOOL dominantIn(const uint8_t *px, size_t x0, size_t y0, size_t x1, size_t y1, CGFloat out[3]) {
    enum { kBins = 512 };
    double sums[kBins][3] = {{0}}, scores[kBins] = {0};
    size_t counts[kBins] = {0};
    for (size_t i = 0; px && i < kSample * kSample; i++) {
        size_t x = i % kSample, y = i / kSample;
        if (x < x0 || x >= x1 || y < y0 || y >= y1) continue;
        const uint8_t *p = px + i * 4;
        if (p[3] < 128) continue;
        int bin = (p[0] >> 5) << 6 | (p[1] >> 5) << 3 | (p[2] >> 5);
        CGFloat high = MAX(p[0], MAX(p[1], p[2])) / 255.0, low = MIN(p[0], MIN(p[1], p[2])) / 255.0;
        CGFloat saturation = high > 0 ? (high - low) / high : 0;
        scores[bin] += (0.25 + saturation) * (high < 0.12 ? 0.3 : 1) * (low > 0.88 ? 0.3 : 1);
        counts[bin]++;
        sums[bin][0] += toLinear(p[0] / 255.0), sums[bin][1] += toLinear(p[1] / 255.0), sums[bin][2] += toLinear(p[2] / 255.0);
    }
    int best = 0;
    for (int i = 1; i < kBins; i++) {
        if (scores[i] > scores[best]) best = i;
    }
    if (!counts[best]) return NO;
    for (int k = 0; k < 3; k++) out[k] = sums[best][k] / counts[best];
    return YES;
}

static BOOL dominantColorOf(CGImageRef image, CGFloat out[3]) {
    CGContextRef context = newBitmap(kSample, kSample);
    if (!context) return NO;
    CGContextSetInterpolationQuality(context, kCGInterpolationMedium);
    CGContextDrawImage(context, CGRectMake(0, 0, kSample, kSample), image);
    BOOL found = dominantIn(CGBitmapContextGetData(context), 0, 0, kSample, kSample, out);
    CGContextRelease(context);
    return found;
}

// Saturation lifted by `lift` up to `max`, in HSB on the encoded color; `linear` in and out in linear light.
static void liftSaturation(CGFloat linear[3], CGFloat lift, CGFloat max) {
    CGFloat r = toEncoded(linear[0]), g = toEncoded(linear[1]), b = toEncoded(linear[2]), h = 0, s = 0, v = 0, a = 1;
    [[UIColor colorWithRed:r green:g blue:b alpha:1] getHue:&h saturation:&s brightness:&v alpha:&a];
    [[UIColor colorWithHue:h saturation:MIN(max, MAX(s, s * lift)) brightness:v alpha:1] getRed:&r green:&g blue:&b alpha:&a];
    linear[0] = toLinear(r), linear[1] = toLinear(g), linear[2] = toLinear(b);
}

#pragma mark - flow

// A dominant color in linear light made fit for a moving field: a little more colorful, and within
// the luminance band that keeps white text readable on it.
static UIColor *flowColorFor(const CGFloat linear[3], CGFloat ceiling) {
    CGFloat lifted[3] = {linear[0], linear[1], linear[2]};
    liftSaturation(lifted, kFlowSaturationLift, kFlowSaturationMax);
    CGFloat lr = lifted[0], lg = lifted[1], lb = lifted[2];
    CGFloat luminance = 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;
    CGFloat k = 1;
    if (luminance > ceiling) k = ceiling / luminance;
    else if (luminance > 0 && luminance < kFlowLuminanceMin) k = MIN(kFlowMaxLift, kFlowLuminanceMin / luminance);
    return [UIColor colorWithRed:toEncoded(MIN(1, lr * k)) green:toEncoded(MIN(1, lg * k)) blue:toEncoded(MIN(1, lb * k)) alpha:1];
}

// The artwork's main color in each quarter, then over the whole of it: the field keeps the artwork's
// colors roughly where the artwork has them.
static NSArray<UIColor *> *flowColorsOf(CGImageRef image, CGFloat ceiling) {
    CGContextRef context = newBitmap(kSample, kSample);
    if (!context) return nil;
    CGContextSetInterpolationQuality(context, kCGInterpolationMedium);
    CGContextDrawImage(context, CGRectMake(0, 0, kSample, kSample), image);
    const uint8_t *px = CGBitmapContextGetData(context);
    size_t half = kSample / 2;
    size_t regions[5][4] = {{0, 0, half, half}, {half, 0, kSample, half}, {0, half, half, kSample}, {half, half, kSample, kSample}, {0, 0, kSample, kSample}};
    NSMutableArray<UIColor *> *colors = [NSMutableArray arrayWithCapacity:5];
    CGFloat linear[3];
    for (int i = 0; i < 5; i++) {
        if (!dominantIn(px, regions[i][0], regions[i][1], regions[i][2], regions[i][3], linear)) break;
        [colors addObject:flowColorFor(linear, ceiling)];
    }
    CGContextRelease(context);
    return colors.count == 5 ? colors : nil;
}

static UIColor *tintOf(CGImageRef image, UIColor *surface, BOOL strong) {
    CGFloat linear[3];
    CGFloat r = 0, g = 0, b = 0, a = 1;
    if (!dominantColorOf(image, linear) || ![surface getRed:&r green:&g blue:&b alpha:&a]) return nil;
    if (strong) liftSaturation(linear, kTintSaturationLift, kTintSaturationMax);
    CGFloat cap = strong ? kTintLuminance : kFaintTintLuminance;
    CGFloat luminance = 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
    if (luminance > cap) {
        for (int k = 0; k < 3; k++) linear[k] *= cap / luminance;
    }
    CGFloat t = strong ? kTintShare : kFaintTintShare;
    CGFloat mixed[3] = {r * (1 - t) + toEncoded(linear[0]) * t,
                        g * (1 - t) + toEncoded(linear[1]) * t,
                        b * (1 - t) + toEncoded(linear[2]) * t};

    // The color mixed in is held under a luminance of 0.05 but has no floor, so a near-black cover mixes the
    // surface *down*: the tile ends up darker than the untinted surface it was meant to be a step above, and a
    // neutral one lands in the 1-10% gray band SGRAmoled.x turns pure black, which takes the whole card with
    // it -- a black square lost on a black page (The Weeknd's Trilogy, Bieber's SWAG; issue #36). So a mix
    // dimmer than the surface is lifted back to the surface's luminance, in linear light and by one factor
    // across the channels, which leaves its hue where the mix put it. Lifting cannot clip: the target
    // luminance is the surface's ~0.014, and the most one channel can carry of it is 0.014 / 0.0722.
    CGFloat want = 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b);
    CGFloat lit[3] = {toLinear(mixed[0]), toLinear(mixed[1]), toLinear(mixed[2])};
    CGFloat have = 0.2126 * lit[0] + 0.7152 * lit[1] + 0.0722 * lit[2];
    if (have <= 0) return surface;
    if (have < want) {
        for (int k = 0; k < 3; k++) mixed[k] = toEncoded(MIN(1, lit[k] * want / have));
    }

    return [UIColor colorWithRed:mixed[0] green:mixed[1] blue:mixed[2] alpha:1];
}

@implementation SGRPalette

+ (void)paletteForImage:(UIImage *)image request:(SGRPaletteRequest)request completion:(void (^)(SGRPalette *palette))completion {
    if (!completion) return;
    CGFloat ceiling = SGRIncreaseContrast() ? kMaxLuminanceContrast : kMaxLuminance;
    CGFloat flowCeiling = SGRIncreaseContrast() ? kMaxLuminance : kFlowLuminanceMax;
    dispatch_async(paletteQueue(), ^{
        SGRPalette *palette = nil;
        CGImageRef cg = image.CGImage;
        UIColor *edge = cg && CGImageGetWidth(cg) && CGImageGetHeight(cg) ? edgeColorOf(cg) : nil;
        if (edge) {
            CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
            palette = [SGRPalette new];
            palette.edgeColor = edge;
            CGFloat main[3];
            UIColor *base = request.mainColor && dominantColorOf(cg, main)
                ? [UIColor colorWithRed:toEncoded(main[0]) green:toEncoded(main[1]) blue:toEncoded(main[2]) alpha:1] : edge;
            palette.fieldColor = fieldColorFor(base, ceiling);
            CGSize area = request.backdropSize;
            if (area.width > 0 && area.height > 0) {
                size_t width = (size_t)kBackdropWidth, height = (size_t)MIN(kBackdropMaxHeight, round(kBackdropWidth * area.height / area.width));
                CGImageRef blurred = newBlurred(cg, width, MAX(height, 1), kBackdropSigma);
                if (blurred) palette.backdrop = finished(blurred, YES, request.amoled ? 0.55 : 0.45, kFadeFrom, 1, 1, 0);
                CGImageRelease(blurred);
            }
            if (request.flow) palette.flowColors = flowColorsOf(cg, flowCeiling);
            if (request.dissolve) {
                CGFloat aspect = (CGFloat)CGImageGetHeight(cg) / CGImageGetWidth(cg);
                size_t height = (size_t)MIN(kDissolveWidth * 2, MAX(kDissolveWidth / 2, round(kDissolveWidth * aspect)));
                CGImageRef blurred = newBlurred(cg, (size_t)kDissolveWidth, height, kDissolveSigma);
                if (blurred) palette.dissolve = finished(blurred, NO, 0, kFadeFrom, 0, kDissolveOpaque, 1);
                CGImageRelease(blurred);
            }
            static dispatch_once_t once;
            double ms = (CFAbsoluteTimeGetCurrent() - start) * 1000;
            dispatch_once(&once, ^{ SGLog(@"redesign kit: first palette %@ from %zux%zu in %.1f ms", palette.fieldColor, CGImageGetWidth(cg), CGImageGetHeight(cg), ms); });
        }
        dispatch_async(dispatch_get_main_queue(), ^{ completion(palette); });
    });
}

+ (void)tintForImage:(UIImage *)image surface:(UIColor *)surface strong:(BOOL)strong completion:(void (^)(UIColor *tint))completion {
    if (!completion) return;
    dispatch_async(paletteQueue(), ^{
        CGImageRef cg = image.CGImage;
        UIColor *tint = cg && CGImageGetWidth(cg) && CGImageGetHeight(cg) ? tintOf(cg, surface, strong) : nil;
        static dispatch_once_t once;
        if (tint) dispatch_once(&once, ^{ SGLog(@"redesign kit: first tint %@", tint); });
        dispatch_async(dispatch_get_main_queue(), ^{ completion(tint); });
    });
}

@end