Liquid Glass and Apple Music touches for the Spotify iOS app. A GPL-3.0 fork of spoti.pw 0.21.1.
C
feat: lyrics from a list of sources you put in order, and the word timing CJK always had
Vojtěch Škopeke0e007660992
diff --git a/docs/tweaks.md b/docs/tweaks.mdindex 071f369b..fc8451ee 100644--- a/docs/tweaks.md+++ b/docs/tweaks.md@@ -47,9 +47,12 @@ app:ArtistBlock/ tracks by blocked artists skipped as they start (ArtistSkip.x), the list and the Blocked artists page under PlayerKaraoke/ Apple Music style lyrics on the full screen page: lines read from color-lyrics and the player's clock (KaraokeSource.x),words timed by estimate inside Spotify's line times (KaraokeTiming.m), drawn by KaraokeView.m over the page (KaraokePage.x)- Musixmatch/ lyrics from Musixmatch with an anonymous token (Musixmatch.m), word timed where it has richsync; color-lyrics- answered with them and has_lyrics forced for every track (MusixmatchLyrics.x); word timing from NetEase's yrc- for the karaoke page when Musixmatch has none (NetEase.m); rows on the Lyrics page+ LyricsSources/ the sources lyrics come from, asked in the order the Lyrics page puts them in and merged into the+ best answer (LyricsSources.m, the list to drag in LyricsSourcesPage.m): Apple Music's TTML from+ BiniLyrics.m and Unison.m, read by SGTTML.m, which is the only shape carrying a second voice and the+ backing vocals; Musixmatch.m, matched by Spotify's track id with an anonymous token, word timed where+ it has richsync; NetEase.m, word timing from yrc for what the others only line time. color-lyrics is+ answered with whichever won and has_lyrics forced for every track (LyricsHook.x)Onboarding/ the welcome tour over Home on the first launch (Onboarding.x, the pages in Tour.m), offered again from the Mod pageAbout/ the update check and the Mod page: the build, its updates, the links and the reset@@ -80,8 +83,8 @@ one page, the mod's own rows first and Spotify's flags below them or on a sub pathey change. It opens on the Appearance card, the three switches that style the whole app: LiquidGlass UI, AMOLED and the accent colour (Spotify's green is offered from the colour row once a colouris set). Then a card of parts. Navbar: the glass tab bar and search field, then the tab editor.-Player: Gestures, Lyrics (Apple Music style, glass lyrics, lyrics from Musixmatch and for every track,-hiding the lyrics card and preview, the lyrics flags), Blocked artists (with the count on the row) and Now playing bar (its glass, its device+Player: Gestures, Lyrics (Apple Music style, glass lyrics, the ordered list of lyrics sources, lyrics+for every track, naming the source, hiding the lyrics card and preview, the lyrics flags), Blocked artists (with the count on the row) and Now playing bar (its glass, its devicebutton and its flags) as pages; then the player screen (artwork background, glass header buttons,Disable Canvas and the sheet, header, slider and sticky header flags), the cards under the player andthe player buttons to hide, and Queue & devices and Lock screen widget as flag pages. Home & Library:diff --git a/tweak/Sources/Features/Karaoke/Karaoke.h b/tweak/Sources/Features/Karaoke/Karaoke.hindex 714a281e..e13b01c8 100644--- a/tweak/Sources/Features/Karaoke/Karaoke.h+++ b/tweak/Sources/Features/Karaoke/Karaoke.h@@ -1,24 +1,50 @@// Apple Music style lyrics on the full screen lyrics page: the line being sung lights up word by// word, the rest dim and blur with distance. Spotify only times whole lines, so the words inside a-// line are timed by an estimate (KaraokeTiming.m), unless Musixmatch times the words. The lines are-// read from the color-lyrics response as it arrives, or handed over by Features/Musixmatch, and the-// position from the player's state (KaraokeSource.x); a track without synced lyrics keeps Spotify's-// own page.+// line are timed by an estimate (KaraokeTiming.m), unless a source of the mod's times them. The+// lines are read from the color-lyrics response as it arrives, or handed over by+// Features/LyricsSources, and the position from the player's state (KaraokeSource.x); a track+// without synced lyrics keeps Spotify's own page.#import <UIKit/UIKit.h>#define SGKeyKaraokeLyrics @"spotifyglass.karaokeLyrics"+// Which edge a line is laid against. Apple Music puts a duet's second voice against the far one, so+// the two sides of the song read apart; a track sung by one voice stays leading throughout.+typedef NS_ENUM(NSUInteger, SGKaraokeAlign) {+ SGKaraokeAlignLeading = 0,+ SGKaraokeAlignTrailing,+};+// Times in milliseconds from the start of the track.@interface SGKaraokeWord : NSObject@property (nonatomic, copy) NSString *text;@property (nonatomic) NSInteger start, end;+// Set when nothing separates the word from the one before it, as between Japanese, Chinese or Korean+// syllables: the line lays it flush instead of leaving a space for a word break that is not there.+@property (nonatomic) BOOL joined;@end@interface SGKaraokeLine : NSObject@property (nonatomic, copy) NSArray<SGKaraokeWord *> *words;@property (nonatomic) NSInteger start, end;+// The voice singing the line, named as the source names it ("v1", "v2"), nil when it names none.+// SGKaraokeAlignVoices turns these into alignments; nothing else reads it.+@property (nonatomic, copy) NSString *voice;+@property (nonatomic) SGKaraokeAlign align;+// The (oh, aye) sung under the line, smaller and dimmer, nil for nearly every line. Its words are+// timed like any other and it is lit by the same sweep, a beat behind the line it hangs off.+@property (nonatomic, strong) SGKaraokeLine *backing;@end+// The line as one string, a space between the words that are not joined.+NSString *SGKaraokeLineText(SGKaraokeLine *line);+// Whether the text is written in a script that does not space its words, so the pieces of a line+// are words in their own right rather than halves of one.+BOOL SGKaraokeUnspacedScript(NSString *text);+// Gives every line the alignment its voice earns: the voice heard first leads, the next one to be+// named trails, and any after that lead again. A track naming one voice or none is left alone.+void SGKaraokeAlignVoices(NSArray<SGKaraokeLine *> *lines);+// A color-lyrics body, protobuf or JSON, as timed lines; nil unless Spotify synced it by line.NSArray<SGKaraokeLine *> *SGKaraokeLinesFromBody(NSData *body);// Lines timed only by their starts, the words inside them estimated; a ♪ or empty text is a break.diff --git a/tweak/Sources/Features/Karaoke/KaraokeSource.x b/tweak/Sources/Features/Karaoke/KaraokeSource.xindex e84bc060..dc513ac9 100644--- a/tweak/Sources/Features/Karaoke/KaraokeSource.x+++ b/tweak/Sources/Features/Karaoke/KaraokeSource.x@@ -2,11 +2,12 @@// the same URLSession delegates AdBlock/AdNetwork.x reads, untouched, and kept per track, since the// page may open long after the request finished. The clock is SPTEsperantoPlayer's state, asked for on// every frame: the player is caught the first time the app asks it, and its position runs on by itself.-// With Musixmatch on, the color-lyrics body is Features/Musixmatch's to answer and it hands the lines over.+// With a source of the mod's on, the color-lyrics body is Features/LyricsSources' to answer and it+// hands the lines over.#import "Core/SGCore.h"#import "Karaoke.h"#import "Features/LockScreenLyrics/LockScreenLyrics.h"-#import "Features/Musixmatch/Musixmatch.h"+#import "Features/LyricsSources/LyricsSources.h"#import "Headers/SPTPlayer.h"static const NSUInteger kKeptTracks = 40;@@ -17,7 +18,7 @@ static NSMutableDictionary<NSString *, NSArray<SGKaraokeLine *> *> *sg_lyrics;static NSMutableSet<NSString *> *sg_requested;static NSDictionary<NSString *, NSString *> *sg_spclientHeaders;static __weak id sg_player;-static BOOL sg_musixmatch;+static BOOL sg_ownSources; // a source of the mod's answers the color-lyrics request, not Spotifystatic char kBodyKey;static NSString *trackInURL(NSURL *url) {@@ -55,7 +56,7 @@ void SGKaraokeKeepLines(NSString *track, NSArray<SGKaraokeLine *> *lines) {static void received(NSURLSession *session, NSURLSessionTask *task, NSData *data) {rememberHeaders(session, task.currentRequest);- if (sg_musixmatch || !trackInURL(task.currentRequest.URL)) return;+ if (sg_ownSources || !trackInURL(task.currentRequest.URL)) return;NSMutableData *body = objc_getAssociatedObject(task, &kBodyKey);if (!body) objc_setAssociatedObject(task, &kBodyKey, (body = [NSMutableData data]), OBJC_ASSOCIATION_RETAIN_NONATOMIC);[body appendData:data];@@ -65,7 +66,7 @@ static void completed(NSURLSessionTask *task, NSError *error) {NSMutableData *body = objc_getAssociatedObject(task, &kBodyKey);if (!body) {NSString *path = task.currentRequest.URL.path;- if (!sg_musixmatch && [path.lowercaseString containsString:@"lyrics"]) SGLog(@"karaoke: lyrics request not read: %@ (error %@)", path, error);+ if (!sg_ownSources && [path.lowercaseString containsString:@"lyrics"]) SGLog(@"karaoke: lyrics request not read: %@ (error %@)", path, error);return;}objc_setAssociatedObject(task, &kBodyKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);@@ -94,20 +95,24 @@ static void requestFromSpotify(NSString *trackID) {NSArray<SGKaraokeLine *> *lines = SGKaraokeLinesFromBody(body);SGLog(@"karaoke: fetched lyrics for %@: status %ld, %lu synced lines, error %@", trackID,(long)[(NSHTTPURLResponse *)response statusCode], (unsigned long)lines.count, error);- if (lines) SGKaraokeKeepLines(trackID, lines);+ if (lines) {+ SGKaraokeKeepLines(trackID, lines);+ SGLyricsSetCredit(trackID, @"Spotify");+ }}] resume];}void SGKaraokeRequestLyrics(NSString *trackID) {if (!trackID || sg_lyrics[trackID] || [sg_requested containsObject:trackID]) return;- if (!sg_musixmatch) {+ if (!sg_ownSources) {requestFromSpotify(trackID);return;}[sg_requested addObject:trackID];- SGMusixmatchFetch(trackID, ^(SGMusixmatchLyrics *lyrics) {+ SGLyricsFetch(trackID, ^(SGLyricsResult *lyrics) {if (lyrics.karaokeLines) {SGKaraokeKeepLines(trackID, lyrics.karaokeLines);+ SGLyricsSetCredit(trackID, lyrics.provider);return;}[sg_requested removeObject:trackID];@@ -175,7 +180,7 @@ void SGKaraokeSeek(NSInteger ms) {if (!SGFlag(SGKeyKaraokeLyrics, NO) && !SGFlag(SGKeyLockScreenLyrics, NO)) return;sg_lyrics = [NSMutableDictionary dictionary];sg_requested = [NSMutableSet set];- sg_musixmatch = SGFlag(SGKeyMusixmatchLyrics, NO);+ sg_ownSources = SGLyricsEnabled();%init;SGLog(@"karaoke: on");SGRequireClasses(@[diff --git a/tweak/Sources/Features/Karaoke/KaraokeTiming.m b/tweak/Sources/Features/Karaoke/KaraokeTiming.mindex 607a608b..4b496c83 100644--- a/tweak/Sources/Features/Karaoke/KaraokeTiming.m+++ b/tweak/Sources/Features/Karaoke/KaraokeTiming.m@@ -14,16 +14,111 @@ static const NSInteger kLineBaseMs = 350, kMsPerLetter = 75;static const double kMinGapShare = 0.6, kMaxStretch = 1.8;// Added to every word's letters, for the breath between words and so a one-letter word still shows.static const NSUInteger kWordWeight = 2;+// A syllable of an unspaced script is one character but a whole beat, so it counts for this many+// letters; without it a Japanese line reads as a handful of letters and its sweep finishes early.+static const NSUInteger kSyllableLetters = 3;-static NSUInteger lettersIn(NSString *text) {- NSUInteger count = 0;- NSCharacterSet *letters = NSCharacterSet.alphanumericCharacterSet;- for (NSUInteger i = 0; i < text.length; i++) {- if ([letters characterIsMember:[text characterAtIndex:i]]) count++;+#pragma mark - the model++NSString *SGKaraokeLineText(SGKaraokeLine *line) {+ NSMutableString *text = [NSMutableString string];+ for (SGKaraokeWord *word in line.words) {+ if (text.length && !word.joined) [text appendString:@" "];+ [text appendString:word.text ?: @""];}+ return text;+}++// Japanese, Chinese and Korean, and the punctuation set with them. Kana and Hangul are listed as+// well as the ideographs: a line of either is written without spaces just the same.+static NSCharacterSet *unspacedScript(void) {+ static NSCharacterSet *set;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ NSMutableCharacterSet *building = [NSMutableCharacterSet new];+ [building addCharactersInRange:NSMakeRange(0x3000, 0x40)]; // CJK punctuation+ [building addCharactersInRange:NSMakeRange(0x3040, 0xC0)]; // hiragana and katakana+ [building addCharactersInRange:NSMakeRange(0x3400, 0x9C0)]; // ideographs, extension A+ [building addCharactersInRange:NSMakeRange(0x4E00, 0x5200)]; // ideographs+ [building addCharactersInRange:NSMakeRange(0xAC00, 0x2BA4)]; // hangul syllables+ [building addCharactersInRange:NSMakeRange(0xF900, 0x200)]; // compatibility ideographs+ [building addCharactersInRange:NSMakeRange(0xFF66, 0x38)]; // halfwidth katakana+ set = [building copy];+ });+ return set;+}++BOOL SGKaraokeUnspacedScript(NSString *text) {+ return text.length && [text rangeOfCharacterFromSet:unspacedScript()].location != NSNotFound;+}++void SGKaraokeAlignVoices(NSArray<SGKaraokeLine *> *lines) {+ NSMutableArray<NSString *> *heard = [NSMutableArray array];+ for (SGKaraokeLine *line in lines) {+ if (!line.voice.length || [heard containsObject:line.voice]) continue;+ [heard addObject:line.voice];+ }+ if (heard.count < 2) return; // one voice, or none named: every line leads, as it already does+ NSString *trailing = heard[1];+ for (SGKaraokeLine *line in lines) {+ line.align = [line.voice isEqualToString:trailing] ? SGKaraokeAlignTrailing : SGKaraokeAlignLeading;+ line.backing.align = line.align;+ }+}++#pragma mark - estimating the words inside a line++static NSUInteger lettersIn(NSString *text) {+ __block NSUInteger count = 0;+ NSCharacterSet *letters = NSCharacterSet.alphanumericCharacterSet, *unspaced = unspacedScript();+ [text enumerateSubstringsInRange:NSMakeRange(0, text.length)+ options:NSStringEnumerationByComposedCharacterSequences+ usingBlock:^(NSString *piece, NSRange a, NSRange b, BOOL *stop) {+ if ([unspaced characterIsMember:[piece characterAtIndex:0]]) count += kSyllableLetters;+ else if ([letters characterIsMember:[piece characterAtIndex:0]]) count++;+ }];return count;}+static void appendPiece(NSMutableArray<SGKaraokeWord *> *pieces, NSString *text) {+ if (!text.length) return;+ SGKaraokeWord *word = [SGKaraokeWord new];+ word.text = text;+ [pieces addObject:word];+}++// The line split into what the sweep lights one at a time: words where the script spaces them, a+// syllable at a time where it does not, so a Japanese line sweeps instead of lighting up whole.+// Everything a token holds past its first piece is joined to the one before it.+static NSArray<SGKaraokeWord *> *piecesOf(NSString *line) {+ NSMutableArray<SGKaraokeWord *> *pieces = [NSMutableArray array];+ for (NSString *token in [line componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]) {+ if (!token.length) continue;+ NSUInteger first = pieces.count;+ if (!SGKaraokeUnspacedScript(token)) {+ appendPiece(pieces, token);+ } else {+ // Latin letters or digits caught between two syllables stay together as one piece.+ NSMutableString *run = [NSMutableString string];+ NSCharacterSet *unspaced = unspacedScript();+ [token enumerateSubstringsInRange:NSMakeRange(0, token.length)+ options:NSStringEnumerationByComposedCharacterSequences+ usingBlock:^(NSString *piece, NSRange a, NSRange b, BOOL *stop) {+ if (![unspaced characterIsMember:[piece characterAtIndex:0]]) {+ [run appendString:piece];+ return;+ }+ appendPiece(pieces, [run copy]);+ [run setString:@""];+ appendPiece(pieces, piece);+ }];+ appendPiece(pieces, [run copy]);+ }+ for (NSUInteger i = first + 1; i < pieces.count; i++) pieces[i].joined = YES;+ }+ return pieces;+}+static BOOL isBreak(NSString *text) {NSString *trimmed = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];return trimmed.length == 0 || [trimmed isEqualToString:@"♪"];@@ -31,13 +126,10 @@ static BOOL isBreak(NSString *text) {// gap is the time to the next line, 0 for the last one.static SGKaraokeLine *timedLine(NSString *text, NSInteger start, NSInteger gap) {- NSMutableArray<NSString *> *tokens = [NSMutableArray array];- for (NSString *token in [text componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]) {- if (token.length) [tokens addObject:token];- }+ NSArray<SGKaraokeWord *> *words = piecesOf(text);NSUInteger weight = 0, letters = 0;- for (NSString *token in tokens) {- NSUInteger count = lettersIn(token);+ for (SGKaraokeWord *word in words) {+ NSUInteger count = lettersIn(word.text);letters += count;weight += count + kWordWeight;}@@ -49,15 +141,11 @@ static SGKaraokeLine *timedLine(NSString *text, NSInteger start, NSInteger gap)sung = MIN(sung, gap);}- NSMutableArray<SGKaraokeWord *> *words = [NSMutableArray array];double at = start;- for (NSString *token in tokens) {- SGKaraokeWord *word = [SGKaraokeWord new];- word.text = token;+ for (SGKaraokeWord *word in words) {word.start = (NSInteger)at;- at += (double)sung * (lettersIn(token) + kWordWeight) / weight;+ at += weight ? (double)sung * (lettersIn(word.text) + kWordWeight) / weight : 0;word.end = (NSInteger)at;- [words addObject:word];}SGKaraokeLine *line = [SGKaraokeLine new];line.words = words;@@ -77,6 +165,8 @@ NSArray<SGKaraokeLine *> *SGKaraokeEstimatedLines(NSArray<NSNumber *> *starts, Nreturn lines.count ? lines : nil;}+#pragma mark - Spotify's own bodies+// Lyrics { 1 data: { 1 time_synchronized, 2 repeated line: { 1 offset_ms, 2 content } }, 2 colors }static NSArray<SGKaraokeLine *> *fromProtobuf(NSData *body) {SGPBField *data = SGPBFirst(SGPBParse(body), 1);diff --git a/tweak/Sources/Features/Karaoke/KaraokeView.m b/tweak/Sources/Features/Karaoke/KaraokeView.mindex 5da64711..120233cd 100644--- a/tweak/Sources/Features/Karaoke/KaraokeView.m+++ b/tweak/Sources/Features/Karaoke/KaraokeView.m@@ -1,11 +1,16 @@#import "Core/SGCore.h"#import "Karaoke.h"+#import "Features/LyricsSources/LyricsSources.h"static const CGFloat kFontSize = 30, kMargin = 24, kLineGap = 24, kRowTighten = 2;static const CGFloat kDimAlpha = 0.3, kFillEdge = 22, kLift = 2.5, kDimScale = 0.97;static const CGFloat kAnchor = 0.28; // where the sung line rests, as a share of the heightstatic const CGFloat kEdgeFade = 0.1; // the lines fade out over this share at the top and bottomstatic const CGFloat kBlurPerLine = 1.4, kMaxBlur = 6;+// The (oh, aye) hanging under a line: smaller, a little dimmer, and just clear of it.+static const CGFloat kBackingScale = 0.62, kBackingAlpha = 0.8, kBackingGap = 4;+// The line naming the source, under the lyrics and outside the fade so it does not dim with them.+static const CGFloat kCreditSize = 12, kCreditAlpha = 0.4, kCreditBottom = 10;static const NSTimeInterval kBrowseHold = 3; // after scrolling by hand, how long until it follows the song againstatic const double kFloatMinMs = 700, kFloatLeadMs = 80; // a short word still floats up this slowlystatic const double kClockSnapMs = 250, kClockPull = 0.08;@@ -97,6 +102,7 @@ static UILabel *wordLabel(NSString *text, UIFont *font, UIColor *color, CGRect f@property (nonatomic, readonly) SGKaraokeLine *line;@property (nonatomic) BOOL active;@property (nonatomic) CGFloat blur;+- (instancetype)initWithLine:(SGKaraokeLine *)line width:(CGFloat)width font:(UIFont *)font backing:(BOOL)backing;- (void)showTime:(double)ms;@end@@ -109,35 +115,64 @@ typedef struct {NSUInteger _generation;SGSweepKnot *_knots;NSUInteger _knotCount;+ SGKaraokeLineView *_backing;}-- (instancetype)initWithLine:(SGKaraokeLine *)line width:(CGFloat)width font:(UIFont *)font {+- (instancetype)initWithLine:(SGKaraokeLine *)line width:(CGFloat)width font:(UIFont *)font backing:(BOOL)backing {self = [super initWithFrame:CGRectZero];if (!self) return nil;_line = line;CGFloat space = ceil([@" " sizeWithAttributes:@{NSFontAttributeName: font}].width);CGFloat row = ceil(font.lineHeight) - kRowTighten, x = 0, y = 0, offset = 0;NSMutableArray<SGKaraokeWordView *> *words = [NSMutableArray array];+ NSMutableArray<NSMutableArray<SGKaraokeWordView *> *> *rows = [NSMutableArray arrayWithObject:[NSMutableArray array]];for (SGKaraokeWord *word in line.words) {SGKaraokeWordView *view = [[SGKaraokeWordView alloc] initWithWord:word font:font];CGSize size = view.bounds.size;- if (x > 0 && x + size.width > width) {- x = 0;+ // A joined word follows the one before it flush: the scripts that do not space their words+ // would otherwise read with a gap between every syllable.+ CGFloat lead = x > 0 && !word.joined ? space : 0;+ if (x > 0 && x + lead + size.width > width) {+ x = lead = 0;y += row;+ [rows addObject:[NSMutableArray array]];}+ x += lead;+ offset += lead;view.center = CGPointMake(x + size.width / 2, y + size.height / 2);view.offset = offset;- x += size.width + space;- offset += size.width + space;+ x += size.width;+ offset += size.width;[self addSubview:view];[words addObject:view];+ [rows.lastObject addObject:view];+ }+ // A second voice is laid against the far edge, as Apple Music sets the two sides of a duet apart.+ if (line.align == SGKaraokeAlignTrailing) {+ for (NSArray<SGKaraokeWordView *> *wrapped in rows) {+ if (!wrapped.count) continue;+ CGFloat shift = width - CGRectGetMaxX(wrapped.lastObject.frame);+ if (shift <= 0) continue;+ for (SGKaraokeWordView *view in wrapped) view.center = CGPointMake(view.center.x + shift, view.center.y);+ }}_words = words;- self.frame = CGRectMake(0, 0, width, y + ceil(font.lineHeight));- // Scales toward its left edge, where the text is aligned.- self.layer.anchorPoint = CGPointMake(0, 0.5);++ CGFloat height = y + ceil(font.lineHeight);+ if (line.backing.words.count && !backing) {+ UIFont *smaller = [UIFont systemFontOfSize:round(font.pointSize * kBackingScale) weight:UIFontWeightBold];+ _backing = [[SGKaraokeLineView alloc] initWithLine:line.backing width:width font:smaller backing:YES];+ _backing.alpha = kBackingAlpha;+ _backing.frame = CGRectMake(0, height + kBackingGap, width, _backing.bounds.size.height);+ [self addSubview:_backing];+ height = CGRectGetMaxY(_backing.frame);+ }+ self.frame = CGRectMake(0, 0, width, height);[self buildSweep];+ // Scales toward the edge its text is aligned to, and a backing row rides its line's blur.+ if (backing) return self;+ self.layer.anchorPoint = CGPointMake(line.align == SGKaraokeAlignTrailing ? 1 : 0, 0.5);CAFilter *blur = [NSClassFromString(@"CAFilter") filterWithType:@"gaussianBlur"];if (blur) self.layer.filters = @[blur];return self;@@ -211,6 +246,7 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {- (void)setActive:(BOOL)active {if (active == _active) return;_active = active;+ _backing.active = active;NSUInteger generation = ++_generation;if (active) {for (SGKaraokeWordView *word in _words) {@@ -246,6 +282,7 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {[word fillTo:cursor];[word floatAt:ms];}+ [_backing showTime:ms]; // timed on its own, so it lags the line as it is sung}@end@@ -266,6 +303,8 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {CGFloat _builtWidth;BOOL _showing;CAGradientLayer *_fade;+ UILabel *_credit;+ BOOL _crediting; // the switch is read once: the page asks for the source on every frame until it has onedouble _clock;NSInteger _reported;CFTimeInterval _clockTime;@@ -280,8 +319,8 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {_fade.colors = @[(id)UIColor.clearColor.CGColor, (id)UIColor.whiteColor.CGColor,(id)UIColor.whiteColor.CGColor, (id)UIColor.clearColor.CGColor];_fade.locations = @[@0, @(kEdgeFade), @(1 - kEdgeFade), @1];- self.layer.mask = _fade;_scroll = [[UIScrollView alloc] initWithFrame:self.bounds];+ _scroll.layer.mask = _fade;_scroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;_scroll.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;_scroll.showsVerticalScrollIndicator = NO;@@ -289,6 +328,12 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {_scroll.scrollsToTop = NO;_scroll.delegate = self;[self addSubview:_scroll];+ _credit = [[UILabel alloc] initWithFrame:CGRectZero];+ _credit.font = [UIFont systemFontOfSize:kCreditSize weight:UIFontWeightSemibold];+ _credit.textColor = [UIColor colorWithWhite:1 alpha:kCreditAlpha];+ _credit.hidden = YES;+ _crediting = SGFlag(SGKeyLyricsCredit, NO);+ [self addSubview:_credit];[self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]];return self;}@@ -352,6 +397,9 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {_fade.frame = self.bounds;[CATransaction commit];_scroll.contentSize = self.bounds.size;+ [_credit sizeToFit];+ _credit.frame = CGRectMake(kMargin, self.bounds.size.height - _credit.bounds.size.height - kCreditBottom,+ _credit.bounds.size.width, _credit.bounds.size.height);if (_lines && self.bounds.size.width != _builtWidth) [self rebuild];}@@ -367,7 +415,7 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {UIFont *font = [UIFont systemFontOfSize:kFontSize weight:UIFontWeightBold];NSMutableArray<SGKaraokeLineView *> *views = [NSMutableArray array];for (SGKaraokeLine *line in _lines) {- SGKaraokeLineView *view = [[SGKaraokeLineView alloc] initWithLine:line width:width font:font];+ SGKaraokeLineView *view = [[SGKaraokeLineView alloc] initWithLine:line width:width font:font backing:NO];[_scroll addSubview:view];[views addObject:view];}@@ -392,7 +440,9 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {NSInteger distance = (NSInteger)i - _active;CGFloat y = height * kAnchor + tops[i].doubleValue - focusTop;CGRect frame = CGRectMake(kMargin, y, view.bounds.size.width, view.bounds.size.height);- CGPoint center = CGPointMake(kMargin, CGRectGetMidY(frame));+ // The anchor sits on the edge the line is aligned to, so it scales toward its own text.+ BOOL trailing = view.line.align == SGKaraokeAlignTrailing;+ CGPoint center = CGPointMake(trailing ? CGRectGetMaxX(frame) : kMargin, CGRectGetMidY(frame));CGFloat scale = distance == 0 ? 1 : kDimScale;CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);view.blur = distance == 0 ? 0 : MIN(kMaxBlur, labs(distance) * kBlurPerLine);@@ -416,6 +466,14 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {_scroll.contentInset = UIEdgeInsetsMake(focusTop, 0, MAX(0, lastTop - focusTop), 0);}+- (void)creditTo:(NSString *)source {+ NSString *text = source.length && _crediting ? [NSString stringWithFormat:@"Lyrics from %@", source] : nil;+ if (text == _credit.text || [text isEqualToString:_credit.text]) return;+ _credit.text = text;+ _credit.hidden = !_showing || !text.length;+ [self setNeedsLayout];+}+- (void)syncSiblings {for (UIView *sibling in self.superview.subviews) {if (sibling != self && _showing) sibling.alpha = 0;@@ -426,6 +484,7 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {if (showing == _showing) return;_showing = showing;self.hidden = !showing;+ _credit.hidden = !showing || !_credit.text.length;for (UIView *sibling in self.superview.subviews) {if (sibling != self) sibling.alpha = showing ? 0 : 1;}@@ -454,6 +513,7 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {_track = track;_lines = nil;_builtWidth = 0;+ [self creditTo:nil];for (UIView *view in _lineViews) [view removeFromSuperview];_lineViews = nil;}@@ -462,6 +522,8 @@ static double secant(SGSweepKnot *knots, NSUInteger i) {[self setNeedsLayout];}[self setShowing:_lines != nil];+ // The source is settled a moment after the lines are, so it is asked for until it answers.+ if (_crediting && _lines && !_credit.text.length) [self creditTo:SGLyricsCreditFor(track)];if (!_lineViews) return;double now = [self clockMs];diff --git a/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.x b/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.xindex 637fa783..12e04071 100644--- a/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.x+++ b/tweak/Sources/Features/LockScreenLyrics/LockScreenLyrics.x@@ -20,7 +20,9 @@ static NSString *sg_shownLine;static BOOL sg_resending;static NSString *textOf(NSArray<SGKaraokeWord *> *words) {- return [[words valueForKey:@"text"] componentsJoinedByString:@" "];+ SGKaraokeLine *line = [SGKaraokeLine new];+ line.words = words;+ return SGKaraokeLineText(line);}// A line longer than the artist row holds, split into even pieces rather than a full one and a stub.@@ -33,7 +35,8 @@ static NSArray<NSArray<SGKaraokeWord *> *> *piecesOf(SGKaraokeLine *line) {NSMutableArray<SGKaraokeWord *> *piece = [NSMutableArray array];NSUInteger pieceLength = 0;for (SGKaraokeWord *word in line.words) {- NSUInteger withWord = pieceLength ? pieceLength + 1 + word.text.length : word.text.length;+ NSUInteger gap = pieceLength && !word.joined ? 1 : 0;+ NSUInteger withWord = pieceLength ? pieceLength + gap + word.text.length : word.text.length;if (pieceLength && (withWord > kMaxChars || (withWord > target && pieces.count + 1 < count))) {[pieces addObject:piece];piece = [NSMutableArray array];diff --git a/tweak/Sources/Features/LyricsSources/BiniLyrics.m b/tweak/Sources/Features/LyricsSources/BiniLyrics.mnew file mode 100644index 00000000..2e03f7a4--- /dev/null+++ b/tweak/Sources/Features/LyricsSources/BiniLyrics.m@@ -0,0 +1,72 @@+// BiniLyrics, the widest of the sources that serve Apple Music's own TTML: over a million recordings,+// word timed, and no key to ask for. Searched by title, artist and length, so it needs a source+// before it in the order — or the player — to have named the track. The search answers with metadata+// and a link; the TTML itself is a second request, to a plain file host.+#import "Core/SGCore.h"+#import "LyricsSources.h"++static NSString *const kAPI = @"https://lyrics-api.binimum.org/";+// A recording is only taken when its length is this close to the track's, so the words fall on the+// same beat. The search is by name, and a live or sped up cut of the same song is a different take.+static const NSInteger kLengthSlack = 4;++// The best of what the search found: word timing wins over line timing, then the closest length.+static NSDictionary *bestOf(id results, NSInteger seconds) {+ NSDictionary *best = nil;+ BOOL bestWordTimed = NO;+ NSInteger bestOff = NSIntegerMax;+ for (NSDictionary *found in [results isKindOfClass:NSArray.class] ? results : @[]) {+ if (![found isKindOfClass:NSDictionary.class] || ![found[@"lyricsUrl"] isKindOfClass:NSString.class]) continue;+ NSInteger length = [found[@"duration"] integerValue];+ NSInteger off = seconds > 0 && length > 0 ? labs(length - seconds) : 0;+ if (off > kLengthSlack) continue;+ BOOL wordTimed = [found[@"timing_type"] isEqual:@"word"];+ if (best && !(wordTimed && !bestWordTimed) && (bestWordTimed != wordTimed || off >= bestOff)) continue;+ best = found;+ bestWordTimed = wordTimed;+ bestOff = off;+ }+ return best;+}++SGLyricsAsk SGBiniLyricsAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {+ if (!query.title.length || !query.artist.length) {+ SGLog(@"binilyrics: nothing to search with for %@", query.trackID);+ done(nil);+ return;+ }+ NSMutableDictionary<NSString *, NSString *> *search = [NSMutableDictionary dictionaryWithDictionary:@{+ @"track": query.title,+ @"artist": query.artist,+ }];+ if (query.seconds > 0) search[@"duration"] = @(query.seconds).stringValue;+ if (query.album.length) search[@"album"] = query.album;+ SGLyricsGetJSON(SGLyricsURL(kAPI, search), nil, ^(id root) {+ NSDictionary *found = bestOf([root isKindOfClass:NSDictionary.class] ? root[@"results"] : nil, query.seconds);+ if (!found) {+ SGLog(@"binilyrics: nothing within %lds of %@ by %@", (long)kLengthSlack, query.title, query.artist);+ done(nil);+ return;+ }+ SGLyricsGetText([NSURL URLWithString:found[@"lyricsUrl"]], ^(NSString *ttml) {+ NSArray<SGKaraokeLine *> *lines = SGTTMLLines(ttml);+ if (!lines) {+ SGLog(@"binilyrics: %@ gave nothing the page could show", found[@"lyricsUrl"]);+ done(nil);+ return;+ }+ SGLyricsResult *result = [SGLyricsResult new];+ result.synced = YES;+ result.wordTimed = [found[@"timing_type"] isEqual:@"word"];+ result.karaokeLines = lines;+ NSArray<NSNumber *> *starts;+ NSArray<NSString *> *texts;+ SGTTMLPageLines(lines, &starts, &texts);+ result.starts = starts;+ result.texts = texts;+ SGLog(@"binilyrics: %@ by %@ has %lu %@ lines", query.title, query.artist,+ (unsigned long)lines.count, result.wordTimed ? @"word timed" : @"line timed");+ done(result);+ });+ });+};diff --git a/tweak/Sources/Features/Musixmatch/MusixmatchLyrics.x b/tweak/Sources/Features/LyricsSources/LyricsHook.xsimilarity index 83%rename from tweak/Sources/Features/Musixmatch/MusixmatchLyrics.xrename to tweak/Sources/Features/LyricsSources/LyricsHook.xindex 7bc92359..04d51ca5 100644--- a/tweak/Sources/Features/Musixmatch/MusixmatchLyrics.x+++ b/tweak/Sources/Features/LyricsSources/LyricsHook.x@@ -1,14 +1,14 @@-// Spotify's /color-lyrics/v2/track/<id> answered with Musixmatch's lyrics. An NSURLProtocol, put into+// Spotify's /color-lyrics/v2/track/<id> answered with the chain's lyrics. An NSURLProtocol, put into// every session the app makes, takes the request over, sends it on itself and gives Spotify one reply:-// timed lines from Musixmatch first, then Spotify's timed ones, then untimed ones from Musixmatch. A-// request Spotify's server has no lyrics for (404) becomes a 200 when Musixmatch has some. Whichever-// lines win go to the karaoke page as well.+// timed lines from the chain first, then Spotify's timed ones, then untimed ones from the chain. A+// request Spotify's server has no lyrics for (404) becomes a 200 when a source has some. Whichever+// lines win go to the karaoke page as well, and the source that supplied them is credited there.//// It is a protocol and not a rewrite in the URLSession delegates: a 200 handed to// Connectivity_HttpClientKit's delegate in place of a 404 still showed no lyrics, so the task's own// response has to be the 200.#import "Core/SGCore.h"-#import "Musixmatch.h"+#import "LyricsSources.h"#import "Features/AdBlock/Protobuf.h"#import "Headers/SPTPlayer.h"@@ -35,26 +35,27 @@ static NSInteger statusOf(NSURLResponse *response) {// Lyrics { 1 data: { 1 time_synchronized, 2 repeated line { 1 offset_ms, 2 content }, 5 provided_by },// 2 colors { 1 background, 2 line, 3 active_line } }-static NSData *lyricsBody(SGMusixmatchLyrics *lyrics, NSData *spotify) {+static NSData *lyricsBody(SGLyricsResult *lyrics, NSData *spotify) {NSMutableArray<SGPBField *> *data = [NSMutableArray array];if (lyrics.synced) [data addObject:SGPBVarint(1, 1)];for (NSUInteger i = 0; i < lyrics.texts.count; i++) {NSData *line = SGPBSerialize(@[SGPBVarint(1, (uint64_t)MAX(lyrics.starts[i].integerValue, 0)), SGPBString(2, lyrics.texts[i])]);[data addObject:SGPBBytes(2, line)];}- [data addObject:SGPBString(5, @"Musixmatch")];+ [data addObject:SGPBString(5, lyrics.provider ?: @"Musixmatch")];SGPBField *colors = SGPBFirst(SGPBParse(spotify), 2);if (colors.wire != 2) colors = SGPBBytes(2, SGPBSerialize(@[SGPBVarint(1, kBackground), SGPBVarint(2, kLine), SGPBVarint(3, kActiveLine)]));return SGPBSerialize(@[SGPBBytes(1, SGPBSerialize(data)), colors]);}-// Musixmatch's body, or nil to hand Spotify's reply on as it came.-static NSData *chosenBody(NSString *track, SGMusixmatchLyrics *lyrics, NSData *spotify) {+// The chain's body, or nil to hand Spotify's reply on as it came.+static NSData *chosenBody(NSString *track, SGLyricsResult *lyrics, NSData *spotify) {NSArray<SGKaraokeLine *> *spotifyLines = SGKaraokeLinesFromBody(spotify);BOOL ours = lyrics.texts.count && (lyrics.synced || !spotifyLines);NSArray<SGKaraokeLine *> *karaoke = lyrics.wordTimed || ours ? lyrics.karaokeLines : spotifyLines;if (karaoke) SGKaraokeKeepLines(track, karaoke);- SGLog(@"musixmatch: lyrics page of %@ gets %@, %@ word timing", track, ours ? @"Musixmatch's lines" : spotify.length ? @"Spotify's own lines" : @"no lyrics",+ SGLyricsSetCredit(track, karaoke == lyrics.karaokeLines ? lyrics.provider : @"Spotify");+ SGLog(@"lyrics: page of %@ gets %@, %@ word timing", track, ours ? [NSString stringWithFormat:@"%@'s lines", lyrics.provider] : spotify.length ? @"Spotify's own lines" : @"no lyrics",lyrics.wordTimed ? @"real" : @"estimated");return ours ? lyricsBody(lyrics, spotify) : nil;}@@ -125,12 +126,12 @@ static NSData *chosenBody(NSString *track, SGMusixmatchLyrics *lyrics, NSData *s}NSInteger status = statusOf(response);BOOL json = data.length && ((const uint8_t *)data.bytes)[0] == '{';- SGLog(@"musixmatch: Spotify answered %ld with %lu bytes for %@", (long)status, (unsigned long)data.length, track);+ SGLog(@"lyrics: Spotify answered %ld with %lu bytes for %@", (long)status, (unsigned long)data.length, track);if ((status != 200 && status < 400) || (status == 200 && json)) {[self replyWith:response data:data];return;}- SGMusixmatchFetch(track, ^(SGMusixmatchLyrics *lyrics) {+ SGLyricsFetch(track, ^(SGLyricsResult *lyrics) {NSData *body = chosenBody(track, lyrics, status == 200 ? data : nil);if (!body) {[self replyWith:response data:data];@@ -177,9 +178,9 @@ static NSData *chosenBody(NSString *track, SGMusixmatchLyrics *lyrics, NSData *sif ([metadata[@"has_lyrics"] isEqual:@"true"]) return metadata;id uri = self.URI;NSString *text = [uri isKindOfClass:NSURL.class] ? [(NSURL *)uri absoluteString] : [uri description];- if (![text hasPrefix:@"spotify:track:"] || !SGMusixmatchMayHave([text substringFromIndex:@"spotify:track:".length])) return metadata;+ if (![text hasPrefix:@"spotify:track:"] || !SGLyricsMayHave([text substringFromIndex:@"spotify:track:".length])) return metadata;static dispatch_once_t once;- dispatch_once(&once, ^{ SGLog(@"musixmatch: marking tracks without Spotify lyrics as having some, first %@", text); });+ dispatch_once(&once, ^{ SGLog(@"lyrics: marking tracks without Spotify lyrics as having some, first %@", text); });NSMutableDictionary *marked = [metadata mutableCopy] ?: [NSMutableDictionary dictionary];marked[@"has_lyrics"] = @"true";return marked;@@ -188,11 +189,12 @@ static NSData *chosenBody(NSString *track, SGMusixmatchLyrics *lyrics, NSData *s%end%ctor {- if (!SGFlag(SGKeyMusixmatchLyrics, NO)) return;+ SGLyricsMigrateLegacyKeys();+ if (!SGLyricsEnabled()) return;sg_sessionHeaders = [NSMutableDictionary dictionary];%init;- BOOL allTracks = SGFlag(SGKeyMusixmatchAllTracks, NO);+ BOOL allTracks = SGFlag(SGKeyLyricsAllTracks, NO);if (allTracks) %init(AllTracks);- SGLog(@"musixmatch: on, every track %@", allTracks ? @"on" : @"off");+ SGLog(@"lyrics: sources %@, every track %@", [SGLyricsOrder() componentsJoinedByString:@", "], allTracks ? @"on" : @"off");SGRequireClasses(@[@"SPTPlayerTrack"]);}diff --git a/tweak/Sources/Features/LyricsSources/LyricsSources.h b/tweak/Sources/Features/LyricsSources/LyricsSources.hnew file mode 100644index 00000000..9caccc38--- /dev/null+++ b/tweak/Sources/Features/LyricsSources/LyricsSources.h@@ -0,0 +1,91 @@+// Where lyrics come from. Every source answers the same question — what are this track's lines, and+// how finely are they timed — and the chain asks them in the order the Lyrics page puts them in,+// keeping the best answer rather than the first: a source with only plain text does not shut out a+// later one that times every word.+//+// SGTTML.m reads the TTML that Apple Music's own lyrics are written in, which is what BiniLyrics and+// Unison serve; it is the only shape carrying a second voice and the (oh, aye) sung under a line.+#import <UIKit/UIKit.h>+#import "Features/Karaoke/Karaoke.h"++// The sources in the order they are asked, as their keys. Unset means the order below, so a source+// added in a later version joins the end of everyone's list instead of shuffling it.+#define SGKeyLyricsProviders @"spotifyglass.lyricsProviders"+// Offers the lyrics card on tracks Spotify itself has no lyrics for.+#define SGKeyLyricsAllTracks @"spotifyglass.lyricsAllTracks"+// Names the source the shown lines came from, on the full screen page.+#define SGKeyLyricsCredit @"spotifyglass.lyricsCredit"++// What a source answers with, and what the chain merges several of into one.+@interface SGLyricsResult : NSObject+@property (nonatomic, copy) NSString *provider; // the key of the source the lines came from+@property (nonatomic) BOOL synced; // the lines have starts of their own+@property (nonatomic) BOOL wordTimed; // the words inside them are timed, not estimated+// Every line as Spotify's lyrics page takes it: ♪ over a break and an empty last line where the+// singing ends. Starts are in milliseconds, all 0 when not synced. nil when a source times words+// but has no text for Spotify's own page.+@property (nonatomic, copy) NSArray<NSNumber *> *starts;+@property (nonatomic, copy) NSArray<NSString *> *texts;+@property (nonatomic, copy) NSArray<SGKaraokeLine *> *karaokeLines;+// What the source learned about the track on the way, for the sources asked after it: one that+// matched the track by Spotify's id knows the title and artist the ones searching by name need.+@property (nonatomic, copy) NSString *title, *artist, *album;+@property (nonatomic) NSInteger seconds;+@property (nonatomic) BOOL instrumental;+@end++// What is known about the track when a source is asked. Only trackID is always there; the rest is+// filled in by the player, and by whichever source answered before.+@interface SGLyricsQuery : NSObject+@property (nonatomic, copy) NSString *trackID; // Spotify's base62 id+@property (nonatomic, copy) NSString *title, *artist, *album;+@property (nonatomic) NSInteger seconds;+@end++// Calls back on the main queue, nil when the source has nothing for the track.+typedef void (^SGLyricsAsk)(SGLyricsQuery *query, void (^done)(SGLyricsResult *result));++@interface SGLyricsProvider : NSObject+@property (nonatomic, copy) NSString *key; // stored in the order, never shown+@property (nonatomic, copy) NSString *name; // "BiniLyrics", what the credit reads+@property (nonatomic, copy) NSString *detail; // one line under the name on the Lyrics page+@property (nonatomic, copy) SGLyricsAsk ask;+@end++// Every source there is, in the order a fresh install asks them.+NSArray<SGLyricsProvider *> *SGLyricsAllProviders(void);+SGLyricsProvider *SGLyricsProviderFor(NSString *key);+// The keys in the user's order, the ones switched off left out. An empty list means the mod leaves+// Spotify's own lyrics alone.+NSArray<NSString *> *SGLyricsOrder(void);+void SGLyricsSetOrder(NSArray<NSString *> *keys);+BOOL SGLyricsEnabled(void); // any source at all is on++// Asks the sources in order and merges what they give, on the main queue. nil when none had lyrics.+void SGLyricsFetch(NSString *trackID, void (^done)(SGLyricsResult *result));+// NO once every source has said it has nothing for the track; safe from any thread.+BOOL SGLyricsMayHave(NSString *trackID);+// The name of the source the lines shown for the track came from, nil until they arrive.+NSString *SGLyricsCreditFor(NSString *trackID);+void SGLyricsSetCredit(NSString *trackID, NSString *name);+// Turns an install's old Musixmatch switches into an order. Called once, before anything reads one.+void SGLyricsMigrateLegacyKeys(void);++// The requests the sources share; each calls back on the main queue, with nil when it failed.+NSURL *SGLyricsURL(NSString *base, NSDictionary<NSString *, NSString *> *query);+void SGLyricsGetJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root));+void SGLyricsGetText(NSURL *url, void (^done)(NSString *text));++// SGTTML.m. Apple Music's TTML as timed lines, the voices already turned into alignments; nil when+// the document holds no line the page could show.+NSArray<SGKaraokeLine *> *SGTTMLLines(NSString *xml);+// The lines as Spotify's own page takes them, ♪ over a break and an empty line at the end.+void SGTTMLPageLines(NSArray<SGKaraokeLine *> *lines, NSArray<NSNumber *> **starts, NSArray<NSString *> **texts);++// The sources themselves, each in its own file.+extern SGLyricsAsk SGBiniLyricsAsk;+extern SGLyricsAsk SGMusixmatchAsk;+extern SGLyricsAsk SGUnisonAsk;+extern SGLyricsAsk SGNetEaseAsk;++UIViewController *SGLyricsSourcesPage(void); // the ordered list on the Lyrics pagediff --git a/tweak/Sources/Features/LyricsSources/LyricsSources.m b/tweak/Sources/Features/LyricsSources/LyricsSources.mnew file mode 100644index 00000000..d5173d62--- /dev/null+++ b/tweak/Sources/Features/LyricsSources/LyricsSources.m@@ -0,0 +1,286 @@+// The chain: every source in the order the Lyrics page puts them in, asked one after another until+// there is nothing better left to learn.+//+// It keeps the best answer rather than the first, because the two halves of an answer come apart.+// A source can have the words of a song and no timing (Musixmatch, for a track it may only show as+// plain text), or the timing of every word and no text worth putting on Spotify's own page+// (NetEase). So the lines shown on the karaoke page and the lines handed to Spotify are chosen+// separately, and the walk stops once both are as good as they can get: every word timed, and text+// for the page.+#import "Core/SGCore.h"+#import "LyricsSources.h"+#import "Features/Karaoke/Karaoke.h"+#import "Headers/SPTPlayer.h"++static const NSTimeInterval kTimeout = 6;+static const NSUInteger kKeptTracks = 40;++// What the switches were called while Musixmatch was the only source; read once, to carry an+// existing install's settings over to the order.+static NSString *const kLegacyMusixmatch = @"spotifyglass.musixmatchLyrics";+static NSString *const kLegacyAllTracks = @"spotifyglass.musixmatchAllTracks";+static NSString *const kLegacyNetEase = @"spotifyglass.neteaseWordTiming";++@implementation SGLyricsResult+@end++@implementation SGLyricsQuery+@end++@implementation SGLyricsProvider+@end++#pragma mark - the requests the sources share++NSURL *SGLyricsURL(NSString *base, NSDictionary<NSString *, NSString *> *query) {+ NSURLComponents *url = [NSURLComponents componentsWithString:base];+ NSMutableArray<NSURLQueryItem *> *items = [NSMutableArray array];+ [query enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {+ [items addObject:[NSURLQueryItem queryItemWithName:name value:value]];+ }];+ url.queryItems = items;+ return url.URL;+}++static void get(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(NSData *body)) {+ if (!url) {+ dispatch_async(dispatch_get_main_queue(), ^{ done(nil); });+ return;+ }+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:kTimeout];+ [headers enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *stop) {+ [request setValue:value forHTTPHeaderField:name];+ }];+ [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {+ NSInteger status = [response isKindOfClass:NSHTTPURLResponse.class] ? ((NSHTTPURLResponse *)response).statusCode : 0;+ if (error || status >= 400) SGLog(@"lyrics: %@ answered %ld, error %@", url.host, (long)status, error);+ dispatch_async(dispatch_get_main_queue(), ^{ done(status >= 400 ? nil : data); });+ }] resume];+}++void SGLyricsGetJSON(NSURL *url, NSDictionary<NSString *, NSString *> *headers, void (^done)(id root)) {+ get(url, headers, ^(NSData *body) {+ done(body.length ? [NSJSONSerialization JSONObjectWithData:body options:0 error:nil] : nil);+ });+}++void SGLyricsGetText(NSURL *url, void (^done)(NSString *text)) {+ get(url, nil, ^(NSData *body) {+ done(body.length ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil);+ });+}++#pragma mark - which sources there are, and in what order++NSArray<SGLyricsProvider *> *SGLyricsAllProviders(void) {+ static NSArray<SGLyricsProvider *> *all;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ SGLyricsProvider *(^make)(NSString *, NSString *, NSString *, SGLyricsAsk) =+ ^(NSString *key, NSString *name, NSString *detail, SGLyricsAsk ask) {+ SGLyricsProvider *provider = [SGLyricsProvider new];+ provider.key = key;+ provider.name = name;+ provider.detail = detail;+ provider.ask = ask;+ return provider;+ };+ all = @[+ make(@"binilyrics", @"BiniLyrics", @"Apple Music's own word timing, over a million tracks", SGBiniLyricsAsk),+ make(@"musixmatch", @"Musixmatch", @"The catalogue Spotify licenses; matched by track, never by name", SGMusixmatchAsk),+ make(@"unison", @"Unison", @"Written by hand for Better Lyrics: few tracks, the best of them", SGUnisonAsk),+ make(@"netease", @"NetEase", @"Word timing only, for what the others line time; swearing is starred out", SGNetEaseAsk),+ ];+ });+ return all;+}++SGLyricsProvider *SGLyricsProviderFor(NSString *key) {+ for (SGLyricsProvider *provider in SGLyricsAllProviders()) {+ if ([provider.key isEqualToString:key]) return provider;+ }+ return nil;+}++// An install from before the order existed keeps what it had: the sources it was using, in the only+// order there was. Nothing is switched on for it that it had not already asked for.+static NSArray<NSString *> *fromLegacyKeys(void) {+ if (!SGFlag(kLegacyMusixmatch, NO)) return @[];+ NSMutableArray<NSString *> *order = [NSMutableArray arrayWithObject:@"musixmatch"];+ if (SGFlag(kLegacyNetEase, NO)) [order addObject:@"netease"];+ return order;+}++NSArray<NSString *> *SGLyricsOrder(void) {+ id stored = [NSUserDefaults.standardUserDefaults arrayForKey:SGKeyLyricsProviders];+ NSArray *keys = [stored isKindOfClass:NSArray.class] ? stored : fromLegacyKeys();+ NSMutableArray<NSString *> *order = [NSMutableArray array];+ for (id key in keys) {+ if ([key isKindOfClass:NSString.class] && SGLyricsProviderFor(key) && ![order containsObject:key]) [order addObject:key];+ }+ return order;+}++void SGLyricsSetOrder(NSArray<NSString *> *keys) {+ [NSUserDefaults.standardUserDefaults setObject:keys ?: @[] forKey:SGKeyLyricsProviders];+}++BOOL SGLyricsEnabled(void) {+ return SGLyricsOrder().count > 0;+}++#pragma mark - what is known about the track++// The player knows the track it is playing by name, which is what every source but Musixmatch+// searches by. A track that is not the one playing — a page opened for something else — starts with+// nothing, and the first source that matches by id fills the rest in.+static SGLyricsQuery *queryFor(NSString *trackID) {+ SGLyricsQuery *query = [SGLyricsQuery new];+ query.trackID = trackID;+ if (![trackID isEqualToString:SGKaraokePlayingTrack()]) return query;+ SPTPlayerTrack *track = [(id<SPTPlayer>)SGKaraokePlayer() state].track;+ query.title = track.trackTitle;+ query.artist = track.artistName;+ NSDictionary<NSString *, NSString *> *metadata = track.metadata;+ id album = metadata[@"album_title"];+ id length = metadata[@"duration"];+ if ([album isKindOfClass:NSString.class]) query.album = album;+ if ([length respondsToSelector:@selector(integerValue)]) query.seconds = [length integerValue] / 1000;+ return query;+}++static void learnFrom(SGLyricsQuery *query, SGLyricsResult *result) {+ if (!query.title.length && result.title.length) query.title = result.title;+ if (!query.artist.length && result.artist.length) query.artist = result.artist;+ if (!query.album.length && result.album.length) query.album = result.album;+ if (query.seconds <= 0 && result.seconds > 0) query.seconds = result.seconds;+}++#pragma mark - the walk++// Main queue only, except sg_missing and sg_credits.+static NSMutableDictionary<NSString *, id> *sg_kept;+static NSMutableDictionary<NSString *, NSMutableArray *> *sg_waiting;+static NSMutableSet<NSString *> *sg_missing;+static NSMutableDictionary<NSString *, NSString *> *sg_credits;++static void setUp(void) {+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ sg_kept = [NSMutableDictionary dictionary];+ sg_waiting = [NSMutableDictionary dictionary];+ sg_missing = [NSMutableSet set];+ sg_credits = [NSMutableDictionary dictionary];+ });+}++// Whether the source's lines are better than what the walk already has: any lines beat none, and+// timing every word beats estimating them.+static BOOL betterLines(SGLyricsResult *merged, SGLyricsResult *fresh) {+ if (!fresh.karaokeLines.count) return NO;+ return !merged.karaokeLines.count || (fresh.wordTimed && !merged.wordTimed);+}++// The same for the text Spotify's own page shows: any text beats none, timed beats untimed.+static BOOL betterTexts(SGLyricsResult *merged, SGLyricsResult *fresh) {+ if (!fresh.texts.count) return NO;+ return !merged.texts.count || (fresh.synced && !merged.synced);+}++static void finish(NSString *trackID, SGLyricsResult *merged) {+ SGLyricsResult *lyrics = merged.karaokeLines.count || merged.texts.count ? merged : nil;+ if (sg_kept.count >= kKeptTracks) [sg_kept removeAllObjects];+ sg_kept[trackID] = lyrics ?: NSNull.null;+ if (!lyrics) {+ @synchronized (sg_missing) { [sg_missing addObject:trackID]; }+ }+ SGLog(@"lyrics: %@ ends with %@", trackID, !lyrics ? @"nothing"+ : [NSString stringWithFormat:@"%lu %@ lines from %@, %lu page lines",+ (unsigned long)lyrics.karaokeLines.count, lyrics.wordTimed ? @"word timed" : @"estimated",+ lyrics.provider, (unsigned long)lyrics.texts.count]);+ NSArray *waiting = sg_waiting[trackID];+ [sg_waiting removeObjectForKey:trackID];+ for (void (^done)(SGLyricsResult *) in waiting) done(lyrics);+}++static void askFrom(NSUInteger index, NSArray<NSString *> *order, SGLyricsQuery *query, SGLyricsResult *merged) {+ // Nothing left to gain: every word is timed and Spotify's page has its text.+ if (index >= order.count || (merged.wordTimed && merged.texts.count)) {+ finish(query.trackID, merged);+ return;+ }+ SGLyricsProvider *provider = SGLyricsProviderFor(order[index]);+ provider.ask(query, ^(SGLyricsResult *fresh) {+ learnFrom(query, fresh);+ if (fresh.instrumental) {+ SGLog(@"lyrics: %@ is instrumental, by %@", query.trackID, provider.key);+ finish(query.trackID, merged);+ return;+ }+ if (betterLines(merged, fresh)) {+ merged.karaokeLines = fresh.karaokeLines;+ merged.wordTimed = fresh.wordTimed;+ merged.provider = provider.name;+ }+ if (betterTexts(merged, fresh)) {+ merged.starts = fresh.starts;+ merged.texts = fresh.texts;+ merged.synced = fresh.synced;+ if (!merged.provider) merged.provider = provider.name;+ }+ askFrom(index + 1, order, query, merged);+ });+}++void SGLyricsFetch(NSString *trackID, void (^done)(SGLyricsResult *result)) {+ setUp();+ dispatch_async(dispatch_get_main_queue(), ^{+ if (!trackID.length) {+ done(nil);+ return;+ }+ id kept = sg_kept[trackID];+ if (kept) {+ done(kept == NSNull.null ? nil : kept);+ return;+ }+ NSMutableArray *waiting = sg_waiting[trackID];+ if (waiting) {+ [waiting addObject:[done copy]];+ return;+ }+ sg_waiting[trackID] = [NSMutableArray arrayWithObject:[done copy]];+ askFrom(0, SGLyricsOrder(), queryFor(trackID), [SGLyricsResult new]);+ });+}++BOOL SGLyricsMayHave(NSString *trackID) {+ setUp();+ @synchronized (sg_missing) { return ![sg_missing containsObject:trackID]; }+}++NSString *SGLyricsCreditFor(NSString *trackID) {+ setUp();+ @synchronized (sg_credits) { return trackID ? sg_credits[trackID] : nil; }+}++void SGLyricsSetCredit(NSString *trackID, NSString *name) {+ setUp();+ if (!trackID.length) return;+ @synchronized (sg_credits) {+ if (sg_credits.count >= kKeptTracks) [sg_credits removeAllObjects];+ sg_credits[trackID] = name ?: @"Spotify";+ }+}++// Once, at launch: the keys Musixmatch owned alone become an order, so the Lyrics page opens on what+// the install was already doing rather than on nothing.+void SGLyricsMigrateLegacyKeys(void) {+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;+ if ([defaults objectForKey:SGKeyLyricsProviders]) return;+ NSArray<NSString *> *order = fromLegacyKeys();+ if (!order.count) return;+ SGLyricsSetOrder(order);+ SGSetEnabled(SGKeyLyricsAllTracks, SGFlag(kLegacyAllTracks, NO));+ SGLog(@"lyrics: carried the Musixmatch switches over as %@", [order componentsJoinedByString:@", "]);+}diff --git a/tweak/Sources/Features/LyricsSources/LyricsSourcesPage.m b/tweak/Sources/Features/LyricsSources/LyricsSourcesPage.mnew file mode 100644index 00000000..6fcac87a--- /dev/null+++ b/tweak/Sources/Features/LyricsSources/LyricsSourcesPage.m@@ -0,0 +1,156 @@+// The order the sources are asked in, as a list to drag into shape. Switched-on sources sit at the+// top in the order they are asked; the rest wait below. Dragging one up makes it the first asked,+// which is the whole point: the source you trust most answers first, and the ones under it only+// fill in what it could not.+#import "Core/SGCore.h"+#import "Settings/SGPage.h"+#import "Settings/SGPageStyle.h"+#import "LyricsSources.h"++typedef NS_ENUM(NSInteger, SGSourcesSection) {+ SGSourcesSectionOn = 0,+ SGSourcesSectionOff,+ SGSourcesSectionCount,+};++@interface SGSourcesPage : SGPage+@end++@implementation SGSourcesPage {+ NSMutableArray<NSString *> *_on; // keys, in the order they are asked+ NSMutableArray<NSString *> *_off;+ UIView *_footer;+}++- (instancetype)init {+ if (!(self = [super initWithStyle:UITableViewStyleInsetGrouped])) return nil;+ self.title = @"Lyrics sources";+ return self;+}++- (void)read {+ _on = [SGLyricsOrder() mutableCopy];+ _off = [NSMutableArray array];+ for (SGLyricsProvider *provider in SGLyricsAllProviders()) {+ if (![_on containsObject:provider.key]) [_off addObject:provider.key];+ }+}++- (void)save {+ SGLyricsSetOrder(_on);+}++- (void)viewDidLoad {+ [super viewDidLoad];+ [self read];+ self.tableView.editing = YES;+ self.tableView.allowsSelectionDuringEditing = YES;+ _footer = SGNote(@"Each source is asked in turn until every word is timed. A source that only has "+ "the plain words does not shut out a later one that times them.\n\n"+ "Musixmatch is sent the track's id with an anonymous token; the rest are sent the "+ "title, artist and length. None of them is told anything of your Spotify account. "+ "Changes apply after you restart Spotify.");+ self.tableView.tableFooterView = _footer;+}++- (void)viewWillLayoutSubviews {+ [super viewWillLayoutSubviews];+ SGFitNote(self.tableView, _footer, 16, 24);+}++- (void)viewDidLayoutSubviews {+ [super viewDidLayoutSubviews];+ SGInsetForBars(self.tableView);+}++- (NSMutableArray<NSString *> *)keysIn:(NSInteger)section {+ return section == SGSourcesSectionOn ? _on : _off;+}++- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {+ return SGSourcesSectionCount;+}++- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {+ return (NSInteger)[self keysIn:section].count;+}++- (UIView *)tableView:(UITableView *)table viewForHeaderInSection:(NSInteger)section {+ if (section == SGSourcesSectionOn) return SGSectionHeader(table, _on.count ? @"Asked in this order" : @"None on");+ return _off.count ? SGSectionHeader(table, @"Off") : nil;+}++- (CGFloat)tableView:(UITableView *)table heightForHeaderInSection:(NSInteger)section {+ return section == SGSourcesSectionOn || _off.count ? SGSectionHeaderHeight : CGFLOAT_MIN;+}++- (CGFloat)tableView:(UITableView *)table heightForFooterInSection:(NSInteger)section {+ return CGFLOAT_MIN;+}++- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {+ UITableViewCell *cell = SGDequeueCell(table, @"source");+ SGLyricsProvider *provider = SGLyricsProviderFor([self keysIn:path.section][(NSUInteger)path.row]);+ BOOL on = path.section == SGSourcesSectionOn;+ // The asked ones are numbered, so the order reads as an order rather than a list.+ NSString *title = on ? [NSString stringWithFormat:@"%ld. %@", (long)path.row + 1, provider.name] : provider.name;+ SGFillCell(cell, title, provider.detail, on ? nil : SGGrey(), on ? @"checkmark.circle.fill" : @"circle");+ cell.selectionStyle = UITableViewCellSelectionStyleDefault;+ return cell;+}++- (BOOL)tableView:(UITableView *)table canMoveRowAtIndexPath:(NSIndexPath *)path {+ return path.section == SGSourcesSectionOn;+}++- (BOOL)tableView:(UITableView *)table canEditRowAtIndexPath:(NSIndexPath *)path {+ return YES;+}++- (UITableViewCellEditingStyle)tableView:(UITableView *)table editingStyleForRowAtIndexPath:(NSIndexPath *)path {+ return UITableViewCellEditingStyleNone;+}++- (BOOL)tableView:(UITableView *)table shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)path {+ return NO;+}++// Dragging stays inside the order; a source is switched on and off by tapping it, not by dropping+// it into the other section, so an order is never lost to a stray drag.+- (NSIndexPath *)tableView:(UITableView *)table targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)from toProposedIndexPath:(NSIndexPath *)to {+ return to.section == SGSourcesSectionOn ? to : from;+}++- (void)tableView:(UITableView *)table moveRowAtIndexPath:(NSIndexPath *)from toIndexPath:(NSIndexPath *)to {+ NSString *key = _on[(NSUInteger)from.row];+ [_on removeObjectAtIndex:(NSUInteger)from.row];+ [_on insertObject:key atIndex:(NSUInteger)to.row];+ [self save];+ [table reloadData]; // the numbers in front of the names have all moved+}++- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {+ [table deselectRowAtIndexPath:path animated:YES];+ NSString *key = [self keysIn:path.section][(NSUInteger)path.row];+ if (path.section == SGSourcesSectionOn) {+ [_on removeObject:key];+ // Back to where it sits among the sources that are off, in the order they all come in.+ NSUInteger at = 0;+ for (SGLyricsProvider *provider in SGLyricsAllProviders()) {+ if ([provider.key isEqualToString:key]) break;+ if ([_off containsObject:provider.key]) at++;+ }+ [_off insertObject:key atIndex:at];+ } else {+ [_off removeObject:key];+ [_on addObject:key];+ }+ [self save];+ [table reloadData];+}++@end++UIViewController *SGLyricsSourcesPage(void) {+ return [SGSourcesPage new];+}diff --git a/tweak/Sources/Features/Musixmatch/Musixmatch.m b/tweak/Sources/Features/LyricsSources/Musixmatch.msimilarity index 75%rename from tweak/Sources/Features/Musixmatch/Musixmatch.mrename to tweak/Sources/Features/LyricsSources/Musixmatch.mindex 69dd2696..2edfe2dc 100644--- a/tweak/Sources/Features/Musixmatch/Musixmatch.m+++ b/tweak/Sources/Features/LyricsSources/Musixmatch.m@@ -1,5 +1,10 @@+// Lyrics from Musixmatch. It is the catalogue Spotify licenses, and for part of it Musixmatch also+// has the time of every word (richsync), which Spotify never sends. The token is an anonymous one+// asked for as Musixmatch's iOS app, so Musixmatch learns the track's id and nothing of the Spotify+// account. It is the one source that matches by Spotify's own track id, so it never has to guess at+// a title, and what it learns about the track is passed to the sources asked after it.#import "Core/SGCore.h"-#import "Musixmatch.h"+#import "LyricsSources.h"static NSString *const kAPI = @"https://apic-appmobile.musixmatch.com/ws/1.1/";static NSString *const kAppID = @"mac-ios-v2.0";@@ -11,15 +16,11 @@ static const NSTimeInterval kTokenPause = 600;static const NSInteger kBreakMs = 3000;static const NSUInteger kKeptTracks = 40;-@implementation SGMusixmatchLyrics-@end--// Main queue only, except sg_missing. NSNull is kept for a track Musixmatch has nothing for.+// Main queue only. NSNull is kept for a track Musixmatch has nothing for.static NSMutableDictionary<NSString *, id> *sg_kept;static NSMutableDictionary<NSString *, NSMutableArray *> *sg_waiting;static NSMutableArray<void (^)(NSString *)> *sg_tokenWaiting;static NSDate *sg_tokenRefused;-static NSMutableSet<NSString *> *sg_missing;static void setUp(void) {static dispatch_once_t once;@@ -27,7 +28,6 @@ static void setUp(void) {sg_kept = [NSMutableDictionary dictionary];sg_waiting = [NSMutableDictionary dictionary];sg_tokenWaiting = [NSMutableArray array];- sg_missing = [NSMutableSet set];});}@@ -109,25 +109,37 @@ static void withToken(void (^use)(NSString *token)) {// one entry ("Milion", "+", ","), so everything between two spaces is one word.static SGKaraokeLine *richsyncLine(NSDictionary *entry, NSInteger start, NSInteger end) {NSMutableArray<SGKaraokeWord *> *words = [NSMutableArray array];- SGKaraokeWord *open = nil;+ BOOL open = NO; // the word last added may still take further entries+ BOOL spaced = YES; // a space has gone by since the last word, so the next one is not joinedid parts = entry[@"l"];for (NSDictionary *part in [parts isKindOfClass:NSArray.class] ? parts : @[]) {id text = dig(part, @"c");if (![text isKindOfClass:NSString.class]) continue;NSInteger at = start + msOf(part[@"o"]);NSString *trimmed = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ SGKaraokeWord *last = words.lastObject;if (!trimmed.length) {- open.end = MAX(at, open.start);- open = nil;- } else if (open) {- open.text = [open.text stringByAppendingString:trimmed];- } else {- open = [SGKaraokeWord new];- open.text = trimmed;- open.start = at;- open.end = MAX(end, at);- [words addObject:open];+ last.end = MAX(at, last.start);+ open = NO;+ spaced = YES;+ continue;+ }+ if (open && !SGKaraokeUnspacedScript(trimmed)) {+ last.text = [last.text stringByAppendingString:trimmed];+ continue;}+ // A syllable of an unspaced script stands as a word of its own. Musixmatch times each one,+ // but sends no space to end it, so running them together is what left a Japanese or Chinese+ // line lighting up whole instead of sweeping.+ last.end = MAX(at, last.start);+ SGKaraokeWord *word = [SGKaraokeWord new];+ word.text = trimmed;+ word.start = at;+ word.end = MAX(end, at);+ word.joined = !spaced;+ [words addObject:word];+ open = !SGKaraokeUnspacedScript(trimmed);+ spaced = NO;}if (!words.count) return nil;SGKaraokeLine *line = [SGKaraokeLine new];@@ -137,7 +149,7 @@ static SGKaraokeLine *richsyncLine(NSDictionary *entry, NSInteger start, NSIntegreturn line;}-static SGMusixmatchLyrics *fromRichsync(id body) {+static SGLyricsResult *fromRichsync(id body) {if (![body isKindOfClass:NSArray.class]) return nil;NSMutableArray<NSNumber *> *starts = [NSMutableArray array];NSMutableArray<NSString *> *texts = [NSMutableArray array];@@ -152,13 +164,13 @@ static SGMusixmatchLyrics *fromRichsync(id body) {}id text = entry[@"x"];[starts addObject:@(line.start)];- [texts addObject:[text isKindOfClass:NSString.class] ? text : [[line.words valueForKey:@"text"] componentsJoinedByString:@" "]];+ [texts addObject:[text isKindOfClass:NSString.class] ? text : SGKaraokeLineText(line)];[karaoke addObject:line];}if (!karaoke.count) return nil;[starts addObject:@(karaoke.lastObject.end)];[texts addObject:@""];- SGMusixmatchLyrics *lyrics = [SGMusixmatchLyrics new];+ SGLyricsResult *lyrics = [SGLyricsResult new];lyrics.synced = lyrics.wordTimed = YES;lyrics.starts = starts;lyrics.texts = texts;@@ -168,7 +180,7 @@ static SGMusixmatchLyrics *fromRichsync(id body) {// [{ "text": "Yeah, yeah", "time": { "total": 3.32 } }, …, { "text": "", "time": { "total": 241.15 } }]// An empty text is a break, and the last one marks the end.-static SGMusixmatchLyrics *fromSubtitles(id body) {+static SGLyricsResult *fromSubtitles(id body) {if (![body isKindOfClass:NSArray.class] || ![body count]) return nil;NSMutableArray<NSNumber *> *starts = [NSMutableArray array];NSMutableArray<NSString *> *texts = [NSMutableArray array];@@ -180,7 +192,7 @@ static SGMusixmatchLyrics *fromSubtitles(id body) {[starts addObject:@(msOf(dig(lines[i], @"time/total")))];[texts addObject:last ? @"" : ([text length] ? text : @"♪")];}- SGMusixmatchLyrics *lyrics = [SGMusixmatchLyrics new];+ SGLyricsResult *lyrics = [SGLyricsResult new];lyrics.synced = YES;lyrics.starts = starts;lyrics.texts = texts;@@ -188,7 +200,7 @@ static SGMusixmatchLyrics *fromSubtitles(id body) {return lyrics.karaokeLines ? lyrics : nil;}-static SGMusixmatchLyrics *fromPlain(id body) {+static SGLyricsResult *fromPlain(id body) {if (![body isKindOfClass:NSString.class] || ![body length]) return nil;NSMutableArray<NSNumber *> *starts = [NSMutableArray array];NSMutableArray<NSString *> *texts = [NSMutableArray array];@@ -196,17 +208,17 @@ static SGMusixmatchLyrics *fromPlain(id body) {[starts addObject:@0];[texts addObject:line.length ? line : @"♪"];}- SGMusixmatchLyrics *lyrics = [SGMusixmatchLyrics new];+ SGLyricsResult *lyrics = [SGLyricsResult new];lyrics.starts = starts;lyrics.texts = texts;return lyrics;}// macro.subtitles.get runs the matcher and every lookup in one call; the best shape it has wins.-static SGMusixmatchLyrics *fromCalls(NSDictionary *calls) {+static SGLyricsResult *fromCalls(NSDictionary *calls) {if (truthy(dig(calls, @"matcher.track.get/message/body/track/instrumental"))) return nil;id richsync = dig(calls, @"track.richsync.get/message/body/richsync");- SGMusixmatchLyrics *lyrics = nil;+ SGLyricsResult *lyrics = nil;if (richsync && !truthy(dig(richsync, @"restricted"))) lyrics = fromRichsync(jsonOf(dig(richsync, @"richsync_body")));if (lyrics) return lyrics;id list = dig(calls, @"track.subtitles.get/message/body/subtitle_list");@@ -219,17 +231,28 @@ static SGMusixmatchLyrics *fromCalls(NSDictionary *calls) {#pragma mark - asking-static void finish(NSString *trackID, SGMusixmatchLyrics *lyrics, BOOL answered) {+static void finish(NSString *trackID, SGLyricsResult *lyrics, BOOL answered) {if (answered) {if (sg_kept.count >= kKeptTracks) [sg_kept removeAllObjects];sg_kept[trackID] = lyrics ?: NSNull.null;- if (!lyrics.texts.count) {- @synchronized (sg_missing) { [sg_missing addObject:trackID]; }- }}NSArray *waiting = sg_waiting[trackID];[sg_waiting removeObjectForKey:trackID];- for (void (^done)(SGMusixmatchLyrics *) in waiting) done(lyrics);+ for (void (^done)(SGLyricsResult *) in waiting) done(lyrics);+}++// What the matcher settled on, kept even when Musixmatch may show no lyrics: the sources asked after+// this one search by name, and this is the best name anyone has.+static SGLyricsResult *withTrack(SGLyricsResult *lyrics, id track) {+ if (![track isKindOfClass:NSDictionary.class]) return lyrics;+ SGLyricsResult *result = lyrics ?: [SGLyricsResult new];+ id title = track[@"track_name"], artist = track[@"artist_name"], album = track[@"album_name"];+ if ([title isKindOfClass:NSString.class]) result.title = title;+ if ([artist isKindOfClass:NSString.class]) result.artist = artist;+ if ([album isKindOfClass:NSString.class]) result.album = album;+ result.seconds = [track[@"track_length"] integerValue];+ result.instrumental = truthy(track[@"instrumental"]);+ return result;}static void ask(NSString *trackID, BOOL renewToken) {@@ -258,50 +281,33 @@ static void ask(NSString *trackID, BOOL renewToken) {finish(trackID, nil, NO);return;}- SGMusixmatchLyrics *lyrics = fromCalls(calls);+ SGLyricsResult *lyrics = fromCalls(calls);SGLog(@"musixmatch: %@ has %@", trackID, !lyrics ? @"no lyrics it may show": lyrics.wordTimed ? [NSString stringWithFormat:@"%lu word timed lines", (unsigned long)lyrics.karaokeLines.count]: lyrics.synced ? [NSString stringWithFormat:@"%lu line timed lines", (unsigned long)lyrics.karaokeLines.count]: [NSString stringWithFormat:@"%lu untimed lines", (unsigned long)lyrics.texts.count]);- id track = dig(calls, @"matcher.track.get/message/body/track");- if (lyrics.wordTimed || !SGFlag(SGKeyNetEaseWordTiming, NO) || ![track isKindOfClass:NSDictionary.class] || truthy(track[@"instrumental"])) {- finish(trackID, lyrics, YES);- return;- }- id title = track[@"track_name"], artist = track[@"artist_name"];- SGNetEaseWordLines([title isKindOfClass:NSString.class] ? title : nil, [artist isKindOfClass:NSString.class] ? artist : nil,- [track[@"track_length"] integerValue], ^(NSArray<SGKaraokeLine *> *lines) {- SGMusixmatchLyrics *merged = lyrics;- if (lines) {- merged = lyrics ?: [SGMusixmatchLyrics new];- merged.karaokeLines = lines;- merged.wordTimed = YES;- }- finish(trackID, merged, YES);- });+ finish(trackID, withTrack(lyrics, dig(calls, @"matcher.track.get/message/body/track")), YES);});});}-void SGMusixmatchFetch(NSString *trackID, void (^done)(SGMusixmatchLyrics *lyrics)) {- setUp();- dispatch_async(dispatch_get_main_queue(), ^{- id kept = sg_kept[trackID];- if (kept) {- done(kept == NSNull.null ? nil : kept);- return;- }- NSMutableArray *waiting = sg_waiting[trackID];- if (waiting) {- [waiting addObject:done];- return;- }- sg_waiting[trackID] = [NSMutableArray arrayWithObject:done];- ask(trackID, YES);- });-}--BOOL SGMusixmatchMayHave(NSString *trackID) {+SGLyricsAsk SGMusixmatchAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *lyrics)) {setUp();- @synchronized (sg_missing) { return ![sg_missing containsObject:trackID]; }-}+ NSString *trackID = query.trackID;+ if (!trackID.length) {+ done(nil);+ return;+ }+ id kept = sg_kept[trackID];+ if (kept) {+ done(kept == NSNull.null ? nil : kept);+ return;+ }+ NSMutableArray *waiting = sg_waiting[trackID];+ if (waiting) {+ [waiting addObject:[done copy]];+ return;+ }+ sg_waiting[trackID] = [NSMutableArray arrayWithObject:[done copy]];+ ask(trackID, YES);+};diff --git a/tweak/Sources/Features/Musixmatch/NetEase.m b/tweak/Sources/Features/LyricsSources/NetEase.msimilarity index 75%rename from tweak/Sources/Features/Musixmatch/NetEase.mrename to tweak/Sources/Features/LyricsSources/NetEase.mindex c1bdd81a..7ee04389 100644--- a/tweak/Sources/Features/Musixmatch/NetEase.m+++ b/tweak/Sources/Features/LyricsSources/NetEase.m@@ -1,5 +1,9 @@+// Word timing from NetEase Cloud Music, for the tracks the other sources only line-time, e.g. most+// of Eminem. It has no text of its own to offer Spotify's page, only the time of every word, so it+// earns its place at the end of the order rather than the front. Searched by title, artist and+// length; NetEase censors swear words with asterisks.#import "Core/SGCore.h"-#import "Musixmatch.h"+#import "LyricsSources.h"static const NSTimeInterval kTimeout = 3;// A NetEase recording is only taken when its length is this close to the track's, so the words fall@@ -40,23 +44,33 @@ static NSArray<SGKaraokeLine *> *linesFromYrc(NSString *yrc) {NSArray<NSTextCheckingResult *> *pieces = [piece matchesInString:row options:0 range:NSMakeRange(NSMaxRange(head.range), row.length - NSMaxRange(head.range))];NSMutableArray<SGKaraokeWord *> *words = [NSMutableArray array];SGKaraokeWord *open = nil;+ BOOL spaced = YES; // a space has gone by, so the next word is not joined to the lastfor (NSUInteger i = 0; i < pieces.count; i++) {NSUInteger from = NSMaxRange(pieces[i].range), to = i + 1 < pieces.count ? pieces[i + 1].range.location : row.length;NSString *raw = [row substringWithRange:NSMakeRange(from, to - from)];NSString *text = [raw stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];NSInteger start = [row substringWithRange:[pieces[i] rangeAtIndex:1]].integerValue;NSInteger end = start + [row substringWithRange:[pieces[i] rangeAtIndex:2]].integerValue;- if (text.length && open) {+ // yrc times a Chinese or Japanese syllable a piece at a time and never spaces them, so+ // each one is a word of its own; only a spaced script runs its pieces together.+ BOOL unspaced = SGKaraokeUnspacedScript(text);+ if (text.length && open && !unspaced) {open.text = [open.text stringByAppendingString:text];open.end = end;} else if (text.length) {- open = [SGKaraokeWord new];- open.text = text;- open.start = start;- open.end = end;- [words addObject:open];+ SGKaraokeWord *word = [SGKaraokeWord new];+ word.text = text;+ word.start = start;+ word.end = end;+ word.joined = !spaced;+ [words addObject:word];+ open = unspaced ? nil : word;+ spaced = NO;+ }+ if (raw.length > text.length || !text.length) {+ open = nil;+ spaced = YES;}- if (raw.length > text.length || !text.length) open = nil;}if (!words.count) continue;SGKaraokeLine *line = [SGKaraokeLine new];@@ -85,10 +99,24 @@ static void tryLyrics(NSArray<NSNumber *> *songs, NSUInteger index, void (^done)});}-void SGNetEaseWordLines(NSString *title, NSString *artist, NSInteger seconds, void (^done)(NSArray<SGKaraokeLine *> *lines)) {- NSString *lead = [artist componentsSeparatedByString:@" feat"].firstObject.lowercaseString;+// A recording is only taken when its length is this close to the track's, so the words fall on the+// same beat as the recording Spotify is playing.+SGLyricsAsk SGNetEaseAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {+ void (^answer)(NSArray<SGKaraokeLine *> *) = ^(NSArray<SGKaraokeLine *> *lines) {+ if (!lines.count) {+ done(nil);+ return;+ }+ SGLyricsResult *result = [SGLyricsResult new];+ result.wordTimed = result.synced = YES;+ result.karaokeLines = lines;+ done(result);+ };+ NSString *lead = [query.artist componentsSeparatedByString:@" feat"].firstObject.lowercaseString;+ NSString *title = query.title;+ NSInteger seconds = query.seconds;if (!title.length || !lead.length || seconds <= 0) {- done(nil);+ answer(nil);return;}get(@"search/get", @{@"s": [NSString stringWithFormat:@"%@ %@", title, lead], @"type": @"1", @"limit": @"10"}, ^(NSDictionary *root) {@@ -110,6 +138,6 @@ void SGNetEaseWordLines(NSString *title, NSString *artist, NSInteger seconds, vo}];NSArray *ids = [[fitting valueForKey:@"id"] subarrayWithRange:NSMakeRange(0, MIN(fitting.count, kTriedSongs))];if (!ids.count) SGLog(@"netease: no recording of %@ by %@ within %lds of %lds", title, lead, (long)kLengthSlack, (long)seconds);- tryLyrics(ids, 0, done);+ tryLyrics(ids, 0, answer);});-}+};diff --git a/tweak/Sources/Features/LyricsSources/SGTTML.m b/tweak/Sources/Features/LyricsSources/SGTTML.mnew file mode 100644index 00000000..5fa79e96--- /dev/null+++ b/tweak/Sources/Features/LyricsSources/SGTTML.m@@ -0,0 +1,224 @@+// TTML, the shape Apple Music writes its lyrics in and the one BiniLyrics and Unison serve.+//+// <p begin="0:13.148" end="0:15.705" ttm:agent="v1">+// <span begin="0:13.148" end="0:13.385">You</span> <span …>called</span>+// <span ttm:role="x-bg"><span begin="0:15.083" end="0:15.401">(Aye,</span> …</span>+// </p>+//+// Two things here exist in no other source the mod reads. ttm:agent names the voice, which is how a+// duet ends up on two sides of the page; a span with the x-bg role holds the backing vocals sung+// under the line. The third is quieter but matters more: the spans of a Japanese or Chinese line sit+// flush against each other with no whitespace between them, and that is the only way to tell that a+// syllable continues a word rather than starting one.+#import "LyricsSources.h"++// A begin or end: seconds ("1.241"), minutes ("0:01.241"), hours ("1:02:03.456"), or a clock value+// with a unit after it ("1.5s", "500ms"). Negative on a value that is none of these.+static NSInteger msOfClock(NSString *clock) {+ NSString *text = [clock stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ if (!text.length) return -1;+ double scale = 1000;+ if ([text hasSuffix:@"ms"]) {+ scale = 1;+ text = [text substringToIndex:text.length - 2];+ } else if ([text hasSuffix:@"s"]) {+ text = [text substringToIndex:text.length - 1];+ }+ double total = 0;+ NSArray<NSString *> *parts = [text componentsSeparatedByString:@":"];+ if (parts.count > 3) return -1;+ for (NSString *part in parts) {+ if (!part.length || [part rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789."].invertedSet].location != NSNotFound) return -1;+ total = total * 60 + part.doubleValue;+ }+ return (NSInteger)llround(total * (parts.count > 1 ? 1000 : scale));+}++// The words of one container: a <p>, or the x-bg span inside it.+@interface SGTTMLContainer : NSObject+@property (nonatomic, strong) NSMutableArray<SGKaraokeWord *> *words;+@property (nonatomic) BOOL spaced; // whitespace has gone by, so the next word is not joined+@end++@implementation SGTTMLContainer+- (instancetype)init {+ if (!(self = [super init])) return nil;+ _words = [NSMutableArray array];+ _spaced = YES;+ return self;+}+@end++@interface SGTTMLReader : NSObject <NSXMLParserDelegate>+@property (nonatomic, strong) NSMutableArray<SGKaraokeLine *> *lines;+@end++@implementation SGTTMLReader {+ NSMutableArray<SGTTMLContainer *> *_stack; // the <p>, then its x-bg span while one is open+ SGTTMLContainer *_backing; // the x-bg container of the line being read+ NSInteger _lineStart, _lineEnd;+ NSString *_voice;+ NSMutableString *_plain; // every character of the line, for a line-timed <p>+ NSMutableString *_word; // the characters of the span being read+ NSInteger _wordStart, _wordEnd;+ NSUInteger _spanDepth, _bgDepth, _wordDepth;+}++- (instancetype)init {+ if (!(self = [super init])) return nil;+ _lines = [NSMutableArray array];+ _stack = [NSMutableArray array];+ return self;+}++- (SGTTMLContainer *)top {+ return _stack.lastObject;+}++- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)element namespaceURI:(NSString *)uri+ qualifiedName:(NSString *)qualified attributes:(NSDictionary<NSString *, NSString *> *)attributes {+ if ([element isEqualToString:@"p"]) {+ [_stack removeAllObjects];+ [_stack addObject:[SGTTMLContainer new]];+ _backing = nil;+ _word = nil;+ _spanDepth = _bgDepth = _wordDepth = 0;+ _plain = [NSMutableString string];+ _lineStart = msOfClock(attributes[@"begin"]);+ _lineEnd = msOfClock(attributes[@"end"]);+ _voice = attributes[@"ttm:agent"] ?: attributes[@"agent"];+ return;+ }+ if (![element isEqualToString:@"span"] || !_stack.count) return;+ _spanDepth++;+ NSString *role = attributes[@"ttm:role"] ?: attributes[@"role"];+ if ([role isEqualToString:@"x-bg"] && !_backing) {+ _backing = [SGTTMLContainer new];+ [_stack addObject:_backing];+ _bgDepth = _spanDepth;+ return;+ }+ // A span nested inside one that is already being read is ruby or a translation: its characters+ // belong to the word around it rather than making a word of their own.+ if (_word) return;+ NSInteger start = msOfClock(attributes[@"begin"]), end = msOfClock(attributes[@"end"]);+ if (start < 0) return;+ _word = [NSMutableString string];+ _wordStart = start;+ _wordEnd = MAX(end, start);+ _wordDepth = _spanDepth;+}++- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)characters {+ if (!_stack.count) return;+ [_plain appendString:characters];+ if (_word) {+ [_word appendString:characters];+ return;+ }+ // Whitespace between two spans is the only record that a space belongs between the words.+ if ([characters stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length) return;+ if (characters.length) self.top.spaced = YES;+}++- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)element namespaceURI:(NSString *)uri+ qualifiedName:(NSString *)qualified {+ if ([element isEqualToString:@"p"]) {+ [self finishLine];+ [_stack removeAllObjects];+ return;+ }+ if (![element isEqualToString:@"span"] || !_stack.count) return;+ if (_word && _spanDepth == _wordDepth) {+ NSString *text = [_word stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ SGTTMLContainer *into = self.top;+ if (text.length) {+ SGKaraokeWord *word = [SGKaraokeWord new];+ word.text = text;+ word.start = _wordStart;+ word.end = _wordEnd;+ word.joined = into.words.count > 0 && !into.spaced;+ [into.words addObject:word];+ into.spaced = NO;+ }+ _word = nil;+ _wordDepth = 0;+ }+ if (_bgDepth && _spanDepth == _bgDepth) {+ [_stack removeLastObject];+ _bgDepth = 0;+ }+ if (_spanDepth) _spanDepth--;+}++- (SGKaraokeLine *)lineFrom:(NSArray<SGKaraokeWord *> *)words {+ if (!words.count) return nil;+ SGKaraokeLine *line = [SGKaraokeLine new];+ line.words = words;+ line.start = words.firstObject.start;+ line.end = MAX(words.lastObject.end, line.start);+ return line;+}++- (void)finishLine {+ SGTTMLContainer *main = _stack.firstObject;+ SGKaraokeLine *line = [self lineFrom:main.words];+ // A document timed only by the line has no spans: its words are estimated, as Spotify's are.+ if (!line) {+ NSString *text = [_plain stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];+ if (!text.length || _lineStart < 0) return;+ NSInteger end = MAX(_lineEnd, _lineStart);+ line = [SGKaraokeEstimatedLines(@[@(_lineStart), @(end)], @[text, @""]) firstObject];+ if (!line) return;+ }+ if (_lineStart >= 0) line.start = _lineStart;+ if (_lineEnd > line.start) line.end = _lineEnd;+ line.voice = _voice;+ line.backing = [self lineFrom:_backing.words];+ [_lines addObject:line];+}++@end++NSArray<SGKaraokeLine *> *SGTTMLLines(NSString *xml) {+ if (![xml isKindOfClass:NSString.class] || !xml.length) return nil;+ NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];+ if (!data) return nil;+ SGTTMLReader *reader = [SGTTMLReader new];+ NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];+ parser.delegate = reader;+ // The TTML namespaces carry nothing the reader needs, and the prefixes it matches on+ // ("ttm:agent") only survive while they are left alone.+ parser.shouldProcessNamespaces = NO;+ [parser parse];+ if (!reader.lines.count) return nil;+ SGKaraokeAlignVoices(reader.lines);+ return reader.lines;+}++// A pause this long between two lines gets a ♪, so Spotify's page does not hold the last one.+static const NSInteger kBreakMs = 3000;++void SGTTMLPageLines(NSArray<SGKaraokeLine *> *lines, NSArray<NSNumber *> **starts, NSArray<NSString *> **texts) {+ NSMutableArray<NSNumber *> *at = [NSMutableArray array];+ NSMutableArray<NSString *> *said = [NSMutableArray array];+ SGKaraokeLine *last = nil;+ for (SGKaraokeLine *line in lines) {+ if (last && line.start - last.end >= kBreakMs) {+ [at addObject:@(last.end)];+ [said addObject:@"♪"];+ }+ NSString *text = SGKaraokeLineText(line);+ // The backing vocals read on the same line on Spotify's own page, which has one row a line.+ if (line.backing) text = [text stringByAppendingFormat:@" %@", SGKaraokeLineText(line.backing)];+ [at addObject:@(line.start)];+ [said addObject:text];+ last = line;+ }+ if (last) {+ [at addObject:@(last.end)];+ [said addObject:@""];+ }+ *starts = at;+ *texts = said;+}diff --git a/tweak/Sources/Features/LyricsSources/Unison.m b/tweak/Sources/Features/LyricsSources/Unison.mnew file mode 100644index 00000000..2770af51--- /dev/null+++ b/tweak/Sources/Features/LyricsSources/Unison.m@@ -0,0 +1,63 @@+// Unison, the lyrics people write for Better Lyrics by hand. It is a small corpus next to the rest,+// but what is in it is Apple Music's own TTML at its best, so it earns being asked early: what it+// misses the next source answers, and what it has beats what that source would have given.+//+// Reads need no key. The write half of its API — submitting, voting, reporting — is signed, and the+// mod does none of it: it asks for lyrics and nothing else.+#import "Core/SGCore.h"+#import "LyricsSources.h"++static NSString *const kAPI = @"https://unison.boidu.dev/lyrics";+static const NSInteger kLengthSlack = 4;++SGLyricsAsk SGUnisonAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *result)) {+ if (!query.title.length || !query.artist.length) {+ SGLog(@"unison: nothing to search with for %@", query.trackID);+ done(nil);+ return;+ }+ // song and artist alone answer with the highest scored match; album and duration narrow it.+ NSMutableDictionary<NSString *, NSString *> *search = [NSMutableDictionary dictionaryWithDictionary:@{+ @"song": query.title,+ @"artist": query.artist,+ }];+ if (query.seconds > 0) search[@"duration"] = @(query.seconds).stringValue;+ if (query.album.length) search[@"album"] = query.album;+ SGLyricsGetJSON(SGLyricsURL(kAPI, search), nil, ^(id root) {+ id data = [root isKindOfClass:NSDictionary.class] ? root[@"data"] : nil;+ if (![data isKindOfClass:NSDictionary.class]) {+ SGLog(@"unison: no lyrics for %@ by %@", query.title, query.artist);+ done(nil);+ return;+ }+ // Unison also keeps LRC and plain text, which carry nothing the other sources do not.+ if (![data[@"format"] isEqual:@"ttml"]) {+ SGLog(@"unison: %@ by %@ is %@, not ttml", query.title, query.artist, data[@"format"]);+ done(nil);+ return;+ }+ NSInteger length = [data[@"duration"] integerValue];+ if (query.seconds > 0 && length > 0 && labs(length - query.seconds) > kLengthSlack) {+ SGLog(@"unison: %@ is %lds against the track's %lds", query.title, (long)length, (long)query.seconds);+ done(nil);+ return;+ }+ NSArray<SGKaraokeLine *> *lines = SGTTMLLines(data[@"lyrics"]);+ if (!lines) {+ done(nil);+ return;+ }+ SGLyricsResult *result = [SGLyricsResult new];+ result.synced = YES;+ result.wordTimed = [data[@"syncType"] isEqual:@"richsync"];+ result.karaokeLines = lines;+ NSArray<NSNumber *> *starts;+ NSArray<NSString *> *texts;+ SGTTMLPageLines(lines, &starts, &texts);+ result.starts = starts;+ result.texts = texts;+ SGLog(@"unison: %@ by %@ has %lu %@ lines (%@ confidence)", query.title, query.artist,+ (unsigned long)lines.count, result.wordTimed ? @"word timed" : @"line timed", data[@"confidence"]);+ done(result);+ });+};diff --git a/tweak/Sources/Features/Musixmatch/Musixmatch.h b/tweak/Sources/Features/Musixmatch/Musixmatch.hdeleted file mode 100644index 2d341a96..00000000--- a/tweak/Sources/Features/Musixmatch/Musixmatch.h+++ /dev/null@@ -1,33 +0,0 @@-// Lyrics from Musixmatch in place of Spotify's. It is the catalogue Spotify licenses, and for part of-// it Musixmatch also has the time of every word (richsync), which Spotify never sends; the karaoke-// page then sweeps real timing instead of an estimate. The token is an anonymous one asked for as-// Musixmatch's iOS app, so Musixmatch learns the track's id and nothing of the Spotify account.-// MusixmatchLyrics.x answers Spotify's color-lyrics requests with what comes back.-#import <Foundation/Foundation.h>-#import "Features/Karaoke/Karaoke.h"--#define SGKeyMusixmatchLyrics @"spotifyglass.musixmatchLyrics"-#define SGKeyMusixmatchAllTracks @"spotifyglass.musixmatchAllTracks"-// Word timing for the karaoke page from NetEase Cloud Music when Musixmatch has none, e.g. for the-// tracks it is not licensed to show. Searched by the title, artist and length Musixmatch matched.-#define SGKeyNetEaseWordTiming @"spotifyglass.neteaseWordTiming"--@interface SGMusixmatchLyrics : NSObject-@property (nonatomic) BOOL synced;-@property (nonatomic) BOOL wordTimed;-// Every line as Spotify's lyrics page takes it: ♪ over a break and an empty last line where the-// singing ends. Starts are in milliseconds, all 0 when not synced. nil when only NetEase had words.-@property (nonatomic, copy) NSArray<NSNumber *> *starts;-@property (nonatomic, copy) NSArray<NSString *> *texts;-@property (nonatomic, copy) NSArray<SGKaraokeLine *> *karaokeLines; // nil unless synced or word timed-@end--// Calls back on the main queue with nil when Musixmatch has nothing it may show for the track, or-// could not be reached.-void SGMusixmatchFetch(NSString *trackID, void (^done)(SGMusixmatchLyrics *lyrics));-// NO once Musixmatch answered that it has no lyrics for the track; safe from any thread.-BOOL SGMusixmatchMayHave(NSString *trackID);--// NetEase.m. Calls back on the main queue, nil when no recording of about that length has word timing.-// NetEase censors swear words with asterisks.-void SGNetEaseWordLines(NSString *title, NSString *artist, NSInteger seconds, void (^done)(NSArray<SGKaraokeLine *> *lines));diff --git a/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m b/tweak/Sources/Features/NowPlaying/NowPlayingSettings.mindex 5f5f9456..d56edffb 100644--- a/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m+++ b/tweak/Sources/Features/NowPlaying/NowPlayingSettings.m@@ -6,7 +6,7 @@#import "Features/ArtistBlock/ArtistBlock.h"#import "Features/Karaoke/Karaoke.h"#import "Features/LockScreenLyrics/LockScreenLyrics.h"-#import "Features/Musixmatch/Musixmatch.h"+#import "Features/LyricsSources/LyricsSources.h"static UIViewController *nowPlayingBarPage(void) {return [[SGModPage alloc] initWithTitle:@"Now playing bar" intro:SGRestartNote sections:@[@@ -27,17 +27,26 @@ static UIViewController *nowPlayingBarPage(void) {}static UIViewController *lyricsPage(void) {+ // The row reads the order out, so which sources are on is visible without opening it.+ SGModRow *sources = SGPageRow(@"Lyrics sources", ^UIViewController *{ return SGLyricsSourcesPage(); });+ sources.subtitle = @"BiniLyrics, Musixmatch, Unison and NetEase, in the order you put them";+ sources.value = ^NSString *{+ NSMutableArray<NSString *> *names = [NSMutableArray array];+ for (NSString *key in SGLyricsOrder()) [names addObject:SGLyricsProviderFor(key).name];+ return names.count ? [names componentsJoinedByString:@", "] : @"Off";+ };+return [[SGModPage alloc] initWithTitle:@"Lyrics" intro:SGRestartNote sections:@[SGSection(nil, @[SGOptionRow(@"Apple Music style", @"Word by word on the full screen page; timing inside a line is estimated unless Musixmatch has it", SGKeyKaraokeLyrics),SGOptionRow(@"Glass lyrics", @"Glass card, and the page it expands into", SGKeyLyricsCard),SGOptionRow(@"Lyrics on the lock screen", @"The line being sung in place of the artist, also in the Dynamic Island, Control Center and CarPlay", SGKeyLockScreenLyrics),]),- SGNotedSection(@"Musixmatch", @[- SGOptionRow(@"Lyrics from Musixmatch", @"In place of Spotify's, with the time of every word where Musixmatch has it", SGKeyMusixmatchLyrics),- SGOptionRow(@"Lyrics for every track", @"Offers the lyrics card on tracks Spotify has no lyrics for; needs Lyrics from Musixmatch", SGKeyMusixmatchAllTracks),- SGOptionRow(@"Word timing from NetEase", @"For Apple Music style when Musixmatch has none, as for most Eminem; needs Lyrics from Musixmatch", SGKeyNetEaseWordTiming),- ], @"Musixmatch is sent the track's id with an anonymous token, NetEase the title and artist; neither gets anything of your Spotify account."),+ SGNotedSection(@"Where lyrics come from", @[+ sources,+ SGOptionRow(@"Lyrics for every track", @"Offers the lyrics card on tracks Spotify has no lyrics for; needs a source above", SGKeyLyricsAllTracks),+ SGOptionRow(@"Name the source", @"Reads out which source the lines on the full screen page came from", SGKeyLyricsCredit),+ ], @"With no source on, Spotify's own lyrics are left alone."),SGSection(@"Hide in the player", @[SGHideRow(@"Lyrics card", @"The lyrics card below the player", SGHideLyricsCard),SGHideRow(@"Lyrics preview", @"The lyric lines shown under the artwork", SGHideLyricsInline),