Skip to content

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

C

fix: LRCLIB's search answers only with a record that is the track

My-Name-Is-Jeffa88162d760e2
diff --git a/docs/tweaks.md b/docs/tweaks.md
index 183d76ea..4566d6f4 100644
--- a/docs/tweaks.md
+++ b/docs/tweaks.md
@@ -117,7 +117,7 @@ Shared:
pronunciation of a line, each keyed to the line by its itunes:key or lrc:key, the pronunciation
timed word by word (the translation taken in the Lyrics page's language); 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; LrcLib.m, open and
- keyless and timed by the line, by the word where a record carries a Lyricsfile (Lyricsfile.m reads its YAML), the floor under the rest. SpicyLyrics.m, Spicy Lyrics' Developer Platform
+ keyless and timed by the line, by the word where a record carries a Lyricsfile (Lyricsfile.m reads its YAML), the floor under the rest; its search answers with whole songs, so only a record that is the track (SongMatch.m) can win. SpicyLyrics.m, Spicy Lyrics' Developer Platform
by track id on the user's own publishable key (Keychain), syllable timed where it has a sync, with
its pronunciations and translations; its credit, which its terms require, shows whatever Show source
says and opens the uploader's and maker's pages from a tap (both looks), its answers and misses are
@@ -125,7 +125,7 @@ Shared:
source's row; checked on the Mac against harness/spicy-lyrics/. QQMusic.m (line timed LRC) and KuGou.m (word timed KRC, unpacked with
zlib and read by NetEase.m's parser) for Chinese and other Asian songs, matched by title, singer
and length; checked on the Mac against harness/lyrics-sources/. Genius.m, last: untimed words for a track no
- other source has, the song found by the line meanings' search (SGGeniusSongIn in LyricsMeanings/Meanings.m)
+ other source has, the song found by the line meanings' search (SGGeniusSongIn in LyricsMeanings/Meanings.m, the match itself in SongMatch.m, which LRCLIB's search shares)
and the words read from its embed script, which is scraping (no API gives the text); checked on
the Mac against harness/genius-lyrics/. color-lyrics is answered with whichever won
(LyricsHook.x): Spotify's own 200 gets our lines swapped in; a track Spotify's metadata says has none has
diff --git a/harness/genius-lyrics/build.sh b/harness/genius-lyrics/build.sh
index 35144a1f..9a1d62ff 100755
--- a/harness/genius-lyrics/build.sh
+++ b/harness/genius-lyrics/build.sh
@@ -6,6 +6,6 @@ HERE=$(cd "$(dirname "$0")" && pwd)
SRC=$(cd "$HERE/../../tweak/Sources" && pwd)
mkdir -p "$HERE/build"
xcrun -sdk macosx clang -target arm64-apple-ios17.0-macabi -isysroot "$(xcrun --sdk macosx --show-sdk-path)" -iframework "$(xcrun --sdk macosx --show-sdk-path)/System/iOSSupport/System/Library/Frameworks" -fobjc-arc -g -Wall -I"$SRC" -DSG_VERSION=\"0.0.0\" \
- "$HERE/check.m" "$SRC/Shared/LyricsSources/Genius.m" "$SRC/Shared/LyricsSources/LrcLib.m" "$SRC/Shared/LyricsSources/Lyricsfile.m" "$SRC/Shared/LyricsSources/QQMusic.m" "$SRC/Shared/LyricsMeanings/Meanings.m" "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \
+ "$HERE/check.m" "$SRC/Shared/LyricsSources/Genius.m" "$SRC/Shared/LyricsSources/LrcLib.m" "$SRC/Shared/LyricsSources/Lyricsfile.m" "$SRC/Shared/LyricsSources/SongMatch.m" "$SRC/Shared/LyricsSources/QQMusic.m" "$SRC/Shared/LyricsMeanings/Meanings.m" "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \
-framework UIKit -framework Foundation -o "$HERE/build/check"
"$HERE/build/check" "$@"
diff --git a/harness/lyrics-page/build.sh b/harness/lyrics-page/build.sh
index 2bea737b..f0dcf0cf 100755
--- a/harness/lyrics-page/build.sh
+++ b/harness/lyrics-page/build.sh
@@ -14,7 +14,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$HERE/main.m" "$HERE/../scene.m" "$HERE/../lyrics/stubs.m" "$HERE/../sing/button/sing-stubs.m" \
"$SRC"/Redesigned/Lyrics/LyricsLookSettings.m "$SRC"/Redesigned/Lyrics/LyricsLook.m \
"$SRC"/Redesigned/Lyrics/SGRKaraokeView.m "$SRC"/Redesigned/Lyrics/LyricsText.m "$SRC"/Redesigned/Lyrics/SGRSingButton.m \
- "$SRC"/Redesigned/Lyrics/MeaningSheet.m "$SRC"/Shared/LyricsMeanings/Meanings.m \
+ "$SRC"/Redesigned/Lyrics/MeaningSheet.m "$SRC"/Shared/LyricsMeanings/Meanings.m "$SRC"/Shared/LyricsSources/SongMatch.m \
"$SRC"/Shared/Lyrics/KaraokeTiming.m "$SRC"/Shared/Lyrics/Romanise.m "$SRC"/Shared/AdBlock/Protobuf.m \
"$SRC"/Redesigned/Kit/SGRTokens.m "$SRC"/Redesigned/Kit/SGRGlass.m \
"$SRC"/Settings/SGPage.m "$SRC"/Settings/SGPageStyle.m "$SRC"/Settings/SGModPage.m "$SRC"/Settings/SGGlowSwitch.m \
diff --git a/harness/lyrics-sources/build.sh b/harness/lyrics-sources/build.sh
index 54ddc13e..87d46666 100755
--- a/harness/lyrics-sources/build.sh
+++ b/harness/lyrics-sources/build.sh
@@ -7,6 +7,6 @@ SRC=$(cd "$HERE/../../tweak/Sources" && pwd)
LS="$SRC/Shared/LyricsSources"
mkdir -p "$HERE/build"
xcrun -sdk macosx clang -target arm64-apple-ios17.0-macabi -isysroot "$(xcrun --sdk macosx --show-sdk-path)" -iframework "$(xcrun --sdk macosx --show-sdk-path)/System/iOSSupport/System/Library/Frameworks" -fobjc-arc -g -Wall -I"$SRC" -DSG_VERSION=\"0.0.0\" \
- "$HERE/check.m" "$LS/KuGou.m" "$LS/QQMusic.m" "$LS/NetEase.m" "$LS/Musixmatch.m" "$LS/LrcLib.m" "$LS/Lyricsfile.m" "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \
+ "$HERE/check.m" "$LS/KuGou.m" "$LS/QQMusic.m" "$LS/NetEase.m" "$LS/Musixmatch.m" "$LS/LrcLib.m" "$LS/Lyricsfile.m" "$LS/SongMatch.m" "$SRC/Shared/Lyrics/KaraokeTiming.m" "$SRC/Shared/AdBlock/Protobuf.m" \
-framework UIKit -framework Foundation -lz -o "$HERE/build/check"
"$HERE/build/check" "$@"
diff --git a/harness/lyrics-sources/check.m b/harness/lyrics-sources/check.m
index f86b57a5..b5dcd29a 100644
--- a/harness/lyrics-sources/check.m
+++ b/harness/lyrics-sources/check.m
@@ -386,13 +386,27 @@ int main(int argc, char **argv) {
got = lrclibAnswer(query, &atOnce);
CHECK(got.instrumental && atOnce);
record = nil;
- found = @[@{@"id": @2, @"duration": @200, @"syncedLyrics": twoLines},
- @{@"id": @3, @"duration": @202, @"hasWordSync": @YES, @"syncedLyrics": twoLines, @"lyricsfile": wordFile}];
+ found = @[@{@"id": @2, @"trackName": @"a", @"artistName": @"b", @"duration": @200, @"syncedLyrics": twoLines},
+ @{@"id": @3, @"trackName": @"a", @"artistName": @"b", @"duration": @202, @"hasWordSync": @YES, @"syncedLyrics": twoLines, @"lyricsfile": wordFile}];
+ got = lrclibAnswer(query, nil);
+ CHECK(got.wordTimed && got.karaokeLines.count == 1);
+ // Only a record that is the track can win, however it is timed: not another song of the artist's, nor
+ // the song by someone whose name only begins with the artist's. A record that names the artist first of
+ // several is theirs, and another version of the song ("a - Live") is still the song.
+ NSDictionary *otherSong = @{@"id": @6, @"trackName": @"c", @"artistName": @"b", @"duration": @200, @"hasWordSync": @YES, @"syncedLyrics": twoLines, @"lyricsfile": wordFile};
+ NSDictionary *otherArtist = @{@"id": @7, @"trackName": @"a", @"artistName": @"b key", @"duration": @200, @"hasWordSync": @YES, @"syncedLyrics": twoLines, @"lyricsfile": wordFile};
+ found = @[otherSong, otherArtist, found[0]];
+ got = lrclibAnswer(query, nil);
+ CHECK(got.synced && !got.wordTimed && got.karaokeLines.count == 2);
+ found = @[otherSong, otherArtist];
+ CHECK(!lrclibAnswer(query, nil));
+ found = @[@{@"id": @8, @"trackName": @"a - Live", @"artistName": @"b, x", @"duration": @200, @"hasWordSync": @YES, @"syncedLyrics": twoLines, @"lyricsfile": wordFile}];
got = lrclibAnswer(query, nil);
CHECK(got.wordTimed && got.karaokeLines.count == 1);
// With no length to go on, a record whose LRC is null against one whose LRC is empty: the plain text wins.
query.seconds = 0;
- found = @[@{@"id": @4, @"syncedLyrics": NSNull.null, @"plainLyrics": @"x"}, @{@"id": @5, @"syncedLyrics": @"", @"plainLyrics": @"y\nz"}];
+ found = @[@{@"id": @4, @"trackName": @"a", @"artistName": @"b", @"syncedLyrics": NSNull.null, @"plainLyrics": @"x"},
+ @{@"id": @5, @"trackName": @"a", @"artistName": @"b", @"syncedLyrics": @"", @"plainLyrics": @"y\nz"}];
got = lrclibAnswer(query, nil);
CHECK(got && !got.synced);
diff --git a/harness/lyrics/build.sh b/harness/lyrics/build.sh
index 9cbed732..9671746f 100755
--- a/harness/lyrics/build.sh
+++ b/harness/lyrics/build.sh
@@ -21,7 +21,7 @@ xcrun -sdk iphonesimulator clang -target arm64-apple-ios17.0-simulator -fobjc-ar
"$HERE/main.m" "$HERE/../scene.m" "$HERE/stubs.m" \
"$SRC"/Redesigned/Lyrics/SGRKaraokeView.m $( [ -f "$SRC"/Redesigned/Lyrics/LyricsText.m ] && echo "$SRC"/Redesigned/Lyrics/LyricsText.m ) $( [ -f "$SRC"/Redesigned/Lyrics/LyricsLook.m ] && echo "$SRC"/Redesigned/Lyrics/LyricsLook.m ) "$SRC"/Shared/Lyrics/KaraokeTiming.m $( [ -f "$SRC"/Shared/Lyrics/Romanise.m ] && echo "$SRC"/Shared/Lyrics/Romanise.m ) "$SRC"/Shared/AdBlock/Protobuf.m \
"$SRC"/Shared/LyricsSources/SGTTML.m "$SRC"/Redesigned/Kit/SGRTokens.m \
- $( [ -f "$SRC"/Shared/LyricsMeanings/Meanings.m ] && echo "$SRC"/Shared/LyricsMeanings/Meanings.m "$SRC"/Redesigned/Lyrics/MeaningSheet.m ) \
+ $( [ -f "$SRC"/Shared/LyricsMeanings/Meanings.m ] && echo "$SRC"/Shared/LyricsMeanings/Meanings.m "$SRC"/Redesigned/Lyrics/MeaningSheet.m ) $( [ -f "$SRC"/Shared/LyricsSources/SongMatch.m ] && echo "$SRC"/Shared/LyricsSources/SongMatch.m ) \
"$SRC"/Core/SGLog.m "$SRC"/Core/SGPrefs.m "$SRC"/Core/SGGlass.m \
$( [ -f "$SRC"/Redesigned/Lyrics/SGRSingButton.m ] && echo "$SRC"/Redesigned/Lyrics/SGRSingButton.m "$SRC"/Redesigned/Kit/SGRGlass.m "$HERE"/../sing/button/sing-stubs.m ) \
-framework UIKit -framework QuartzCore -framework CoreGraphics -framework CoreText -framework Foundation -framework Symbols -framework NaturalLanguage \
diff --git a/tweak/Sources/Shared/LyricsMeanings/Meanings.h b/tweak/Sources/Shared/LyricsMeanings/Meanings.h
index 5e3b24f6..acff8129 100644
--- a/tweak/Sources/Shared/LyricsMeanings/Meanings.h
+++ b/tweak/Sources/Shared/LyricsMeanings/Meanings.h
@@ -38,10 +38,10 @@ void SGLyricsMeaningsFor(NSString *trackID, NSArray<SGKaraokeLine *> *lines,
void (^done)(NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *byLine));
// Genius's search, which the lyrics source asks too (Shared/LyricsSources/Genius.m): its address, what
-// it is asked for a track, and the song in its reply that is the track. That song's title is the
-// track's once a version in brackets or after " - " is set aside, and one of its own artists is the
-// track's lead; of several, the same version wins, then the plain song. nil when none is, or the
-// track is an instrumental or karaoke version, since Genius files the words under the song.
+// it is asked for a track, and the song in its reply that is the track, as SGLyricsSongRank
+// (Shared/LyricsSources/SongMatch.m) tells: of several, the same version wins, then the plain song.
+// nil when none is, or the track is an instrumental or karaoke version, since Genius files the words
+// under the song.
#define SGGeniusSearchURL @"https://genius.com/api/search/song"
NSDictionary<NSString *, NSString *> *SGGeniusSearchQuery(NSString *title, NSString *artist);
NSNumber *SGGeniusSongIn(NSDictionary *response, NSString *title, NSString *artist);
diff --git a/tweak/Sources/Shared/LyricsMeanings/Meanings.m b/tweak/Sources/Shared/LyricsMeanings/Meanings.m
index 60758cab..620f8e93 100644
--- a/tweak/Sources/Shared/LyricsMeanings/Meanings.m
+++ b/tweak/Sources/Shared/LyricsMeanings/Meanings.m
@@ -27,42 +27,6 @@ SGModRow *SGLyricsMeaningsRow(void) {
#pragma mark - text
-// Letters and digits only, lowercase, accents gone and apostrophes closed up, so "Don’t" and "dont"
-// read alike across sources.
-static NSString *folded(NSString *text) {
- static NSCharacterSet *kept;
- static dispatch_once_t once;
- dispatch_once(&once, ^{ kept = NSCharacterSet.alphanumericCharacterSet; });
- NSString *plain = [text stringByFoldingWithOptions:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch
- locale:nil];
- NSMutableString *out = [NSMutableString stringWithCapacity:plain.length];
- BOOL space = NO;
- for (NSUInteger i = 0; i < plain.length; i++) {
- unichar c = [plain characterAtIndex:i];
- if (c == '\'' || c == 0x2019 || c == 0x2018 || c == '`') continue;
- if ([kept characterIsMember:c]) {
- if (space && out.length) [out appendString:@" "];
- space = NO;
- [out appendFormat:@"%C", c];
- } else {
- space = YES;
- }
- }
- return out;
-}
-
-// "Song (feat. X) - Remastered 2011" as Genius titles it: "Song".
-static NSString *bareTitle(NSString *title) {
- NSString *bare = title ?: @"";
- NSRange dash = [bare rangeOfString:@" - "];
- if (dash.location != NSNotFound) bare = [bare substringToIndex:dash.location];
- static NSRegularExpression *brackets;
- static dispatch_once_t once;
- dispatch_once(&once, ^{ brackets = [NSRegularExpression regularExpressionWithPattern:@"\\s*[\\(\\[][^\\)\\]]*[\\)\\]]" options:0 error:nil]; });
- bare = [brackets stringByReplacingMatchesInString:bare options:0 range:NSMakeRange(0, bare.length) withTemplate:@""];
- return [bare stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
-}
-
static BOOL sameLine(NSString *a, NSString *b) {
if (!a.length || !b.length) return NO;
if ([a isEqualToString:b]) return YES;
@@ -85,7 +49,7 @@ static NSArray<NSString *> *fragmentLines(NSString *fragment) {
for (NSString *row in [fragment componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
NSString *trimmed = [row stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
if ([trimmed hasPrefix:@"["] && [trimmed hasSuffix:@"]"]) continue;
- NSString *text = folded(trimmed);
+ NSString *text = SGLyricsFoldedText(trimmed);
if (text.length) [lines addObject:text];
}
return lines;
@@ -127,65 +91,14 @@ static NSString *stringIn(id value) {
}
NSDictionary<NSString *, NSString *> *SGGeniusSearchQuery(NSString *title, NSString *artist) {
- return @{@"q": [NSString stringWithFormat:@"%@ %@", bareTitle(title), artist], @"per_page": @"10"};
-}
-
-// What a title says beyond the song's name: "Old Town Road - Remix" is {remix}, "Blinding Lights (Live)" {live}.
-static NSSet<NSString *> *versionOf(NSString *title) {
- NSMutableSet<NSString *> *words = [NSMutableSet setWithArray:[folded(title) componentsSeparatedByString:@" "]];
- [words minusSet:[NSSet setWithArray:[folded(bareTitle(title)) componentsSeparatedByString:@" "]]];
- [words removeObject:@""];
- return words;
-}
-
-// The track's title without Spotify's "(feat. Billy Ray Cyrus)" or "(with Diplo)": who sings with the lead
-// is not which recording it is. Genius's titles keep theirs, so a version of its own with a guest stays apart.
-static NSString *withoutGuests(NSString *title) {
- static NSRegularExpression *guests;
- static dispatch_once_t once;
- dispatch_once(&once, ^{
- guests = [NSRegularExpression regularExpressionWithPattern:@"\\s*[\\(\\[](feat\\.?|ft\\.?|featuring|with)\\s[^\\)\\]]*[\\)\\]]"
- options:NSRegularExpressionCaseInsensitive error:nil];
- });
- return [guests stringByReplacingMatchesInString:title options:0 range:NSMakeRange(0, title.length) withTemplate:@""];
-}
-
-// Spotify joins a track's artists with ", ", which a name can hold too ("Tyler, The Creator"), so the
-// lead artist is any run of the first names; a local file's tag may name the lead before " feat." instead.
-static NSSet<NSString *> *leadNames(NSString *artist) {
- NSMutableSet<NSString *> *names = [NSMutableSet setWithObject:folded(SGLyricsLeadArtist(artist))];
- NSString *run = @"";
- for (NSString *part in [artist componentsSeparatedByString:@", "]) {
- run = run.length ? [run stringByAppendingFormat:@" %@", folded(part)] : folded(part);
- if (run.length) [names addObject:run];
- }
- return names;
-}
-
-// Whether one of the song's own artists is the track's lead, the way Genius names them or by either name
-// of one it writes twice over ("BTS (방탄소년단)", "Дора (Dora)"); a featured singer or a translation page's "Genius English Translations"
-// never is.
-static BOOL byLead(NSDictionary *song, NSSet<NSString *> *leads) {
- id primaries = song[@"primary_artists"];
- for (NSDictionary *primary in [primaries isKindOfClass:NSArray.class] ? primaries : @[]) {
- NSString *name = [primary isKindOfClass:NSDictionary.class] ? stringIn(primary[@"name"]) : nil;
- if (!name) continue;
- NSArray<NSString *> *parts = [name componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"()"]];
- for (NSString *part in [parts arrayByAddingObject:name]) {
- if ([leads containsObject:folded(part)]) return YES;
- }
- }
- return NO;
+ return @{@"q": [NSString stringWithFormat:@"%@ %@", SGLyricsBareTitle(title), artist], @"per_page": @"10"};
}
NSNumber *SGGeniusSongIn(NSDictionary *response, NSString *title, NSString *artist) {
if (![response isKindOfClass:NSDictionary.class] || !title.length || !artist.length) return nil;
- NSString *wantTitle = folded(bareTitle(title));
- if (!wantTitle.length) return nil;
- NSSet<NSString *> *wantVersion = versionOf(withoutGuests(title));
// Genius files a song's words under the song; a track with none sung would get them anyway.
- if ([wantVersion containsObject:@"instrumental"] || [wantVersion containsObject:@"karaoke"]) return nil;
- NSSet<NSString *> *leads = leadNames(artist);
+ NSSet<NSString *> *version = SGLyricsTitleVersion(title);
+ if ([version containsObject:@"instrumental"] || [version containsObject:@"karaoke"]) return nil;
// Best first: the same version, then the plain song, then any other version of it.
NSNumber *best = nil;
NSInteger bestRank = 0;
@@ -195,10 +108,14 @@ NSNumber *SGGeniusSongIn(NSDictionary *response, NSString *title, NSString *arti
for (NSDictionary *hit in [hits isKindOfClass:NSArray.class] ? hits : @[]) {
NSDictionary *song = [hit isKindOfClass:NSDictionary.class] ? hit[@"result"] : nil;
if (![song isKindOfClass:NSDictionary.class] || ![song[@"id"] isKindOfClass:NSNumber.class]) continue;
- NSString *hitTitle = stringIn(song[@"title"]);
- if ([song[@"instrumental"] isEqual:@YES] || ![folded(bareTitle(hitTitle)) isEqualToString:wantTitle] || !byLead(song, leads)) continue;
- NSSet<NSString *> *version = versionOf(hitTitle);
- NSInteger rank = [version isEqualToSet:wantVersion] ? 3 : version.count == 0 ? 2 : 1;
+ if ([song[@"instrumental"] isEqual:@YES]) continue;
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
+ id primaries = song[@"primary_artists"];
+ for (NSDictionary *primary in [primaries isKindOfClass:NSArray.class] ? primaries : @[]) {
+ NSString *name = [primary isKindOfClass:NSDictionary.class] ? stringIn(primary[@"name"]) : nil;
+ if (name) [names addObject:name];
+ }
+ NSInteger rank = SGLyricsSongRank(title, artist, stringIn(song[@"title"]), names);
if (rank > bestRank) {
best = song[@"id"];
bestRank = rank;
@@ -308,7 +225,7 @@ static NSDictionary<NSNumber *, NSArray<SGLyricsMeaning *> *> *matched(NSArray<S
NSArray<SGKaraokeLine *> *lines,
SGLyricsMeaningsLevel level) {
NSMutableArray<NSString *> *texts = [NSMutableArray arrayWithCapacity:lines.count];
- for (SGKaraokeLine *line in lines) [texts addObject:folded(SGKaraokeLineText(line))];
+ for (SGKaraokeLine *line in lines) [texts addObject:SGLyricsFoldedText(SGKaraokeLineText(line))];
SGLyricsMeaningAuthor furthest = level == SGLyricsMeaningsArtist ? SGLyricsMeaningByArtist
: level == SGLyricsMeaningsEditors ? SGLyricsMeaningByEditors : SGLyricsMeaningByCommunity;
NSMutableDictionary<NSNumber *, NSMutableArray<SGLyricsMeaning *> *> *byLine = [NSMutableDictionary dictionary];
diff --git a/tweak/Sources/Shared/LyricsSources/LrcLib.m b/tweak/Sources/Shared/LyricsSources/LrcLib.m
index 7676a9fe..6cc34fd0 100644
--- a/tweak/Sources/Shared/LyricsSources/LrcLib.m
+++ b/tweak/Sources/Shared/LyricsSources/LrcLib.m
@@ -158,13 +158,18 @@ static BOOL betterRecord(NSDictionary *record, NSDictionary *best, NSInteger sec
return [text isKindOfClass:NSString.class] && (![wasText isKindOfClass:NSString.class] || text.length > wasText.length);
}
-static NSDictionary *bestOf(id found, NSInteger seconds) {
+// The search ranks by its own lights, and its first hit is often another song of the artist's or the
+// song by someone else, so a record has to be the track (SongMatch.m) before its timing counts. The
+// artists are written as one name, "A, B" for several.
+static NSDictionary *bestOf(id found, SGLyricsQuery *query) {
NSDictionary *best = nil;
for (NSDictionary *record in [found isKindOfClass:NSArray.class] ? found : @[]) {
if (![record isKindOfClass:NSDictionary.class]) continue;
NSInteger length = (NSInteger)[record[@"duration"] doubleValue];
- if (seconds > 0 && length > 0 && labs(length - seconds) > kLengthSlack) continue;
- if (betterRecord(record, best, seconds)) best = record;
+ if (query.seconds > 0 && length > 0 && labs(length - query.seconds) > kLengthSlack) continue;
+ NSString *artists = [record[@"artistName"] isKindOfClass:NSString.class] ? record[@"artistName"] : @"";
+ if (!SGLyricsSongRank(query.title, query.artist, record[@"trackName"], [artists componentsSeparatedByString:@", "])) continue;
+ if (betterRecord(record, best, query.seconds)) best = record;
}
return best;
}
@@ -183,7 +188,7 @@ SGLyricsAsk SGLrcLibAsk = ^(SGLyricsQuery *query, void (^done)(SGLyricsResult *r
void (^bySearch)(void) = ^{
SGLyricsGetJSON(SGLyricsURL(kSearch, search), headers(), ^(id found) {
- resultFor(bestOf(found, query.seconds), ^(SGLyricsResult *result) {
+ resultFor(bestOf(found, query), ^(SGLyricsResult *result) {
SGLog(@"lrclib: search for %@ by %@ gave %@", query.title, query.artist,
!result ? @"nothing" : result.instrumental ? @"an instrumental"
: result.synced ? [NSString stringWithFormat:@"%lu %@ lines", (unsigned long)result.karaokeLines.count, result.wordTimed ? @"word timed" : @"timed"]
diff --git a/tweak/Sources/Shared/LyricsSources/LyricsSources.h b/tweak/Sources/Shared/LyricsSources/LyricsSources.h
index 94f6f901..c275cecd 100644
--- a/tweak/Sources/Shared/LyricsSources/LyricsSources.h
+++ b/tweak/Sources/Shared/LyricsSources/LyricsSources.h
@@ -197,6 +197,18 @@ BOOL SGLyricsSameArtist(NSString *credited, NSString *artist);
// KuGou.m. A download's base64 content as lines, nil when it is not KRC or holds no timed line.
NSArray<SGKaraokeLine *> *SGKuGouLines(NSString *content);
+// SongMatch.m, for the searches that answer with whole songs (Genius, LRCLIB). Text as the two are
+// matched by: letters and digits only, lowercase, accents gone and apostrophes closed up, so "Don’t"
+// and "dont" read alike across sources. A title with a version in brackets or after " - " set aside
+// ("Song (feat. X) - Remastered 2011" is "Song"), and the version words of the track's title, its
+// guests left out ("Old Town Road (feat. Billy Ray Cyrus) - Remix" is {remix}). How closely a song
+// a catalog names by title and artists is the track: 0 when it is not (another title, or none of its
+// artists is the track's lead), 1 for another version of it, 2 for the plain song, 3 for the same version.
+NSString *SGLyricsFoldedText(NSString *text);
+NSString *SGLyricsBareTitle(NSString *title);
+NSSet<NSString *> *SGLyricsTitleVersion(NSString *title);
+NSInteger SGLyricsSongRank(NSString *title, NSString *artist, NSString *songTitle, NSArray<NSString *> *songArtists);
+
// SpicyLyrics.m. Its key in the order; whether the user's own API key is in the Keychain; what keeps
// it from answering, for its row on the sources page ("Needs a key", why the key was refused), nil
// while nothing does; the Lyrics page's row that sets or removes the key; and an API response as
diff --git a/tweak/Sources/Shared/LyricsSources/SongMatch.m b/tweak/Sources/Shared/LyricsSources/SongMatch.m
new file mode 100644
index 00000000..9aea4363
--- /dev/null
+++ b/tweak/Sources/Shared/LyricsSources/SongMatch.m
@@ -0,0 +1,96 @@
+// Whether a song a catalog offers is the track playing, for the searches that answer with whole songs
+// and no id to match on: Genius's (LyricsMeanings/Meanings.m, Genius.m) and LRCLIB's (LrcLib.m).
+#import "Core/SGCore.h"
+#import "LyricsSources.h"
+
+NSString *SGLyricsFoldedText(NSString *text) {
+ static NSCharacterSet *kept;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ kept = NSCharacterSet.alphanumericCharacterSet; });
+ NSString *plain = [text stringByFoldingWithOptions:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch
+ locale:nil];
+ NSMutableString *out = [NSMutableString stringWithCapacity:plain.length];
+ BOOL space = NO;
+ for (NSUInteger i = 0; i < plain.length; i++) {
+ unichar c = [plain characterAtIndex:i];
+ if (c == '\'' || c == 0x2019 || c == 0x2018 || c == '`') continue;
+ if ([kept characterIsMember:c]) {
+ if (space && out.length) [out appendString:@" "];
+ space = NO;
+ [out appendFormat:@"%C", c];
+ } else {
+ space = YES;
+ }
+ }
+ return out;
+}
+
+NSString *SGLyricsBareTitle(NSString *title) {
+ NSString *bare = title ?: @"";
+ NSRange dash = [bare rangeOfString:@" - "];
+ if (dash.location != NSNotFound) bare = [bare substringToIndex:dash.location];
+ static NSRegularExpression *brackets;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ brackets = [NSRegularExpression regularExpressionWithPattern:@"\\s*[\\(\\[][^\\)\\]]*[\\)\\]]" options:0 error:nil]; });
+ bare = [brackets stringByReplacingMatchesInString:bare options:0 range:NSMakeRange(0, bare.length) withTemplate:@""];
+ return [bare stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
+}
+
+// What a title says beyond the song's name: "Old Town Road - Remix" is {remix}, "Blinding Lights (Live)" {live}.
+static NSSet<NSString *> *versionOf(NSString *title) {
+ NSMutableSet<NSString *> *words = [NSMutableSet setWithArray:[SGLyricsFoldedText(title) componentsSeparatedByString:@" "]];
+ [words minusSet:[NSSet setWithArray:[SGLyricsFoldedText(SGLyricsBareTitle(title)) componentsSeparatedByString:@" "]]];
+ [words removeObject:@""];
+ return words;
+}
+
+// The track's title without Spotify's "(feat. Billy Ray Cyrus)" or "(with Diplo)": who sings with the lead
+// is not which recording it is. A catalog's titles keep theirs, so a version of its own with a guest stays apart.
+static NSString *withoutGuests(NSString *title) {
+ static NSRegularExpression *guests;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ guests = [NSRegularExpression regularExpressionWithPattern:@"\\s*[\\(\\[](feat\\.?|ft\\.?|featuring|with)\\s[^\\)\\]]*[\\)\\]]"
+ options:NSRegularExpressionCaseInsensitive error:nil];
+ });
+ return [guests stringByReplacingMatchesInString:title options:0 range:NSMakeRange(0, title.length) withTemplate:@""];
+}
+
+NSSet<NSString *> *SGLyricsTitleVersion(NSString *title) {
+ return versionOf(withoutGuests(title ?: @""));
+}
+
+// Spotify joins a track's artists with ", ", which a name can hold too ("Tyler, The Creator"), so the
+// lead artist is any run of the first names; a local file's tag may name the lead before " feat." instead.
+static NSSet<NSString *> *leadNames(NSString *artist) {
+ NSMutableSet<NSString *> *names = [NSMutableSet setWithObject:SGLyricsFoldedText(SGLyricsLeadArtist(artist))];
+ NSString *run = @"";
+ for (NSString *part in [artist componentsSeparatedByString:@", "]) {
+ run = run.length ? [run stringByAppendingFormat:@" %@", SGLyricsFoldedText(part)] : SGLyricsFoldedText(part);
+ if (run.length) [names addObject:run];
+ }
+ return names;
+}
+
+// Whether one of the song's own artists is the track's lead, by either name of one written twice over
+// ("BTS (방탄소년단)", "Дора (Dora)") or by the name before its " feat."; a featured singer or a translation
+// page's "Genius English Translations" never is.
+static BOOL byLead(NSArray<NSString *> *songArtists, NSSet<NSString *> *leads) {
+ for (NSString *name in songArtists) {
+ if (![name isKindOfClass:NSString.class]) continue;
+ NSArray<NSString *> *parts = [name componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"()"]];
+ for (NSString *part in [parts arrayByAddingObjectsFromArray:@[name, SGLyricsLeadArtist(name)]]) {
+ if ([leads containsObject:SGLyricsFoldedText(part)]) return YES;
+ }
+ }
+ return NO;
+}
+
+NSInteger SGLyricsSongRank(NSString *title, NSString *artist, NSString *songTitle, NSArray<NSString *> *songArtists) {
+ if (!title.length || !artist.length || ![songTitle isKindOfClass:NSString.class]) return 0;
+ NSString *wantTitle = SGLyricsFoldedText(SGLyricsBareTitle(title));
+ if (!wantTitle.length || ![SGLyricsFoldedText(SGLyricsBareTitle(songTitle)) isEqualToString:wantTitle]) return 0;
+ if (!byLead(songArtists, leadNames(artist))) return 0;
+ NSSet<NSString *> *version = versionOf(songTitle);
+ return [version isEqualToSet:SGLyricsTitleVersion(title)] ? 3 : version.count == 0 ? 2 : 1;
+}