casualexpiesource

cu-trainer/Ultra Paradise Linux/app/Lyrics.cs

471 lines · 22.4 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Globalization;
4using System.IO;
5using System.Linq;
6using System.Net.Http;
7using System.Security.Cryptography;
8using System.Text;
9using System.Text.Json;
10using System.Text.RegularExpressions;
11using System.Threading;
12using System.Threading.Tasks;
13using Avalonia;
14using Avalonia.Controls;
15using Avalonia.Layout;
16using Avalonia.Media;
17
18namespace UltraParadise.Linux
19{
20 internal sealed class LyricsResult
21 {
22 public List<(double t, string s)> Synced;
23 public string[] Plain;
24 public bool Instrumental, Failed;
25 public bool Empty => (Synced == null || Synced.Count == 0) && Plain == null && !Instrumental;
26 }
27
28 internal static class LyricsSource
29 {
30 private static string Folder => Path.Combine(Dirs.Cache, "lyrics");
31
32 private static string CacheFile(string artist, string title)
33 {
34 byte[] h = SHA1.HashData(Encoding.UTF8.GetBytes(artist.ToLowerInvariant() + "\n" + title.ToLowerInvariant()));
35 return Path.Combine(Folder, Convert.ToHexString(h).ToLowerInvariant() + ".txt");
36 }
37
38 public static async Task<LyricsResult> Find(string artist, string title, double len)
39 {
40 string file = CacheFile(artist, title);
41 LyricsResult cached = ReadCache(file);
42 if (cached != null) return cached;
43 LyricsResult r;
44 try
45 {
46 r = await Search(title, artist, len);
47 if (r == null)
48 {
49 string ct = CleanTitle(title), ca = CleanArtist(artist);
50 if (ct != title || ca != artist) r = await Search(ct, ca, len);
51 }
52 }
53 catch (Exception) { return new LyricsResult { Failed = true }; }
54 WriteCache(file, r);
55 return r ?? new LyricsResult();
56 }
57
58 public static string CleanTitle(string t)
59 {
60 string s = Regex.Replace(t, @"\s*[\(\[](feat\.?|ft\.?|with|official|lyric|lyrics|audio|video|visuali[sz]er|remaster|hd|hq|4k|mv|explicit)[^\)\]]*[\)\]]", "", RegexOptions.IgnoreCase);
61 s = Regex.Replace(s, @"\s+-\s+(\d{4}\s+)?remaster(ed)?.*$", "", RegexOptions.IgnoreCase);
62 s = Regex.Replace(s, @"\s+(feat\.?|ft\.?)\s+.*$", "", RegexOptions.IgnoreCase);
63 return s.Trim().Length > 0 ? s.Trim() : t;
64 }
65
66 public static string CleanArtist(string a)
67 {
68 string s = Regex.Replace(a, @"\s*-\s*Topic$", "", RegexOptions.IgnoreCase);
69 s = Regex.Replace(s, "VEVO$", "", RegexOptions.IgnoreCase);
70 int c = s.IndexOfAny(new[] { ',', '&' });
71 if (c > 0) s = s[..c];
72 s = Regex.Replace(s, @"\s+(feat\.?|ft\.?|x)\s+.*$", "", RegexOptions.IgnoreCase);
73 return s.Trim().Length > 0 ? s.Trim() : a;
74 }
75
76 private static string Norm(string s) => new(s.ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray());
77
78 private static async Task<LyricsResult> Search(string title, string artist, double len)
79 {
80 if (title.Trim().Length == 0) return null;
81 string url = "https://lrclib.net/api/search?track_name=" + Uri.EscapeDataString(title) + (artist.Trim().Length > 0 ? "&artist_name=" + Uri.EscapeDataString(artist) : "");
82 using HttpRequestMessage req = new(HttpMethod.Get, url);
83 req.Headers.UserAgent.ParseAdd("UltraParadiseCUTrainer-Linux/" + Program.Version + " (https://www.nexusmods.com/scavprototype/mods/1203)");
84 using CancellationTokenSource cts = new(TimeSpan.FromSeconds(15));
85 using HttpResponseMessage res = await Http.Client.SendAsync(req, cts.Token);
86 res.EnsureSuccessStatusCode();
87 byte[] body = await res.Content.ReadAsByteArrayAsync(cts.Token);
88 if (body.Length > 8 * 1024 * 1024) return null;
89 using JsonDocument doc = JsonDocument.Parse(body);
90 if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
91 string na = Norm(artist), nt = Norm(CleanTitle(title));
92 JsonElement? best = null;
93 int bestScore = int.MinValue;
94 foreach (JsonElement d in doc.RootElement.EnumerateArray())
95 {
96 string nra = Norm(Str(d, "artistName")), nrt = Norm(CleanTitle(Str(d, "trackName")));
97 if (na.Length > 0 && !(nra.Contains(na) || na.Contains(nra))) continue;
98 if (nt.Length > 0 && !(nrt.Contains(nt) || nt.Contains(nrt))) continue;
99 double dur = d.TryGetProperty("duration", out JsonElement de) && de.ValueKind == JsonValueKind.Number ? de.GetDouble() : 0;
100 if (len > 0 && dur > 0 && Math.Abs(dur - len) > 6) continue;
101 int score;
102 if (Str(d, "syncedLyrics").Length > 0) score = 100;
103 else if (Str(d, "plainLyrics").Length > 0) score = 40;
104 else if (Inst(d)) score = 20;
105 else continue;
106 if (nrt == nt) score += 10;
107 if (nra == na) score += 10;
108 if (len > 0 && dur > 0) score -= (int)Math.Abs(dur - len);
109 if (score > bestScore) { bestScore = score; best = d; }
110 }
111 if (best == null) return null;
112 JsonElement b = best.Value;
113 LyricsResult r = new() { Instrumental = Inst(b) };
114 string synced = Str(b, "syncedLyrics");
115 if (synced.Length > 0) r.Synced = ParseLrc(synced);
116 string plain = Str(b, "plainLyrics");
117 if (plain.Length > 0) r.Plain = plain.Replace("\r", "").Split('\n');
118 return r.Empty ? null : r;
119 }
120
121 private static string Str(JsonElement d, string k) => d.TryGetProperty(k, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
122 private static bool Inst(JsonElement d) => d.TryGetProperty("instrumental", out JsonElement v) && v.ValueKind == JsonValueKind.True;
123
124 public static List<(double, string)> ParseLrc(string lrc)
125 {
126 List<(double, string)> list = new();
127 Regex tag = new(@"\[(\d+):(\d+(?:[\.:]\d+)?)\]");
128 foreach (string raw in lrc.Replace("\r", "").Split('\n'))
129 {
130 MatchCollection ms = tag.Matches(raw);
131 if (ms.Count == 0) continue;
132 Match last = ms[^1];
133 string text = raw[(last.Index + last.Length)..].Trim();
134 foreach (Match m in ms)
135 {
136 double min = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
137 if (!double.TryParse(m.Groups[2].Value.Replace(':', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out double sec)) continue;
138 list.Add((min * 60 + sec, text));
139 }
140 }
141 list.Sort((a, b) => a.Item1.CompareTo(b.Item1));
142 return list;
143 }
144
145 private static LyricsResult ReadCache(string file)
146 {
147 try
148 {
149 if (!File.Exists(file)) return null;
150 string[] lines = File.ReadAllText(file, Encoding.UTF8).Replace("\r", "").Split('\n');
151 if (lines.Length < 2 || lines[0] != "UPLYRICS 1") return null;
152 string body = string.Join("\n", lines.Skip(2));
153 LyricsResult r = new();
154 switch (lines[1])
155 {
156 case "S": r.Synced = ParseLrc(body); break;
157 case "P": r.Plain = body.Split('\n'); break;
158 case "I": r.Instrumental = true; break;
159 case "N": if ((DateTime.UtcNow - File.GetLastWriteTimeUtc(file)).TotalDays > 3) return null; break;
160 default: return null;
161 }
162 return r;
163 }
164 catch (Exception) { return null; }
165 }
166
167 private static void WriteCache(string file, LyricsResult r)
168 {
169 try
170 {
171 Private.Dir(Dirs.Cache);
172 Private.Dir(Folder);
173 StringBuilder sb = new("UPLYRICS 1\n");
174 if (r != null && r.Synced != null && r.Synced.Count > 0)
175 {
176 sb.Append("S\n");
177 foreach (var (t, s) in r.Synced)
178 {
179 int cs = (int)Math.Round(t * 100);
180 sb.Append('[').Append((cs / 6000).ToString("00", CultureInfo.InvariantCulture)).Append(':')
181 .Append((cs / 100 % 60).ToString("00", CultureInfo.InvariantCulture)).Append('.')
182 .Append((cs % 100).ToString("00", CultureInfo.InvariantCulture)).Append(']').Append(s).Append('\n');
183 }
184 }
185 else if (r != null && r.Plain != null) sb.Append("P\n").Append(string.Join("\n", r.Plain));
186 else if (r != null && r.Instrumental) sb.Append("I\n");
187 else sb.Append("N\n");
188 Private.Write(file, Encoding.UTF8.GetBytes(sb.ToString()));
189 }
190 catch (Exception) { }
191 }
192 }
193
194 internal sealed partial class MainWindow
195 {
196 private const int LyrRows = 7;
197 private const double LyrLh = 32;
198 private readonly TextBlock[] lyrLines = new TextBlock[LyrRows + 3];
199 private readonly Canvas lyrCanvas = new() { Height = LyrRows * LyrLh, ClipToBounds = true };
200 private readonly Border lyrPill = new() { ClipToBounds = true, IsVisible = false };
201 private readonly Border lyrSweep = new() { HorizontalAlignment = HorizontalAlignment.Left };
202 private readonly TextBlock lyrMeasure = new() { FontSize = 17, FontWeight = FontWeight.SemiBold };
203 private double lyrFrom = double.NaN, lyrTo = double.NaN, lyrCenter;
204 private DateTime lyrAnimAt = DateTime.MinValue;
205 private LyricsResult lyrAnimFor;
206 private readonly TextBlock lyrSong = T("", 12, Ui.B(Ui.Dim), false, true);
207 private readonly TextBlock lyrState = T("", 13, Ui.B(Ui.Dim), false, true);
208 private readonly TextBlock lyrNote = T("", 11, Ui.B(Ui.Faint), false, true);
209 private readonly Button lyrToggle = new();
210 private LyricsResult lyrResult;
211 private string lyrKey;
212 private int lyrReq, lyrSource;
213 private DateTime lyrRetry = DateTime.MaxValue, gmStamp = DateTime.UtcNow;
214 private bool lyrOn = true;
215
216 private Border BuildLyrics()
217 {
218 Border sec = Section("LYRICS", out StackPanel lb);
219 lyrOn = Settings.On("lyrics", true);
220 lyrToggle.Content = lyrOn ? "Hide Lyrics" : "Show Lyrics";
221 lyrToggle.Click += (_, _) =>
222 {
223 lyrOn = !lyrOn;
224 Settings.Set("lyrics", lyrOn ? "1" : "0");
225 lyrToggle.Content = lyrOn ? "Hide Lyrics" : "Show Lyrics";
226 lyrKey = null;
227 LyricsCheck();
228 LyricsDraw();
229 };
230 lb.Children.Add(lyrToggle);
231 lyrSong.TextAlignment = TextAlignment.Center;
232 lb.Children.Add(lyrSong);
233 lyrNote.TextAlignment = TextAlignment.Center;
234 lb.Children.Add(lyrNote);
235 lyrPill.Child = lyrSweep;
236 lyrCanvas.Children.Add(lyrPill);
237 for (int i = 0; i < lyrLines.Length; i++)
238 {
239 lyrLines[i] = T("", 14, Ui.B(Ui.Text), false, false);
240 lyrLines[i].TextAlignment = TextAlignment.Center;
241 lyrLines[i].Height = LyrLh;
242 lyrLines[i].VerticalAlignment = VerticalAlignment.Center;
243 lyrLines[i].TextTrimming = TextTrimming.CharacterEllipsis;
244 lyrLines[i].Padding = new Thickness(0, 6, 0, 0);
245 lyrCanvas.Children.Add(lyrLines[i]);
246 }
247 lb.Children.Add(lyrCanvas);
248 Avalonia.Threading.DispatcherTimer anim = new() { Interval = TimeSpan.FromMilliseconds(16) };
249 anim.Tick += (_, _) => { if (MusicVisible && lyrOn && lyrResult != null && lyrResult.Synced != null && lyrResult.Synced.Count > 0) LyricsDraw(); };
250 anim.Start();
251 lyrState.TextAlignment = TextAlignment.Center;
252 lb.Children.Add(lyrState);
253 TextBlock credit = T("Lyrics from LRCLIB (lrclib.net)", 11, Ui.B(Ui.Faint), false, true);
254 credit.TextAlignment = TextAlignment.Center;
255 lb.Children.Add(credit);
256 lyrState.Text = "Play a song on Spotify or YouTube Music Desktop to see its lyrics here.";
257 LyricsDraw();
258 return sec;
259 }
260
261 private double LyricsPos()
262 {
263 if (lyrSource == 2) return gmPos + (gmPlaying ? Math.Clamp((DateTime.UtcNow - gmStamp).TotalSeconds, 0, 2) : 0);
264 return LivePosUs() / 1_000_000.0;
265 }
266
267 private double LyricsLen() => lyrSource == 2 ? gmLen : (np != null ? np.LengthUs / 1_000_000.0 : 0);
268
269 private static bool SplitFileSong(string file, out string artist, out string title)
270 {
271 artist = title = "";
272 string n = Regex.Replace(Path.GetFileNameWithoutExtension(file ?? ""), @"^\d{1,3}[\s\.\-_]+", "");
273 int d = n.IndexOf(" - ", StringComparison.Ordinal);
274 if (d <= 0 || d >= n.Length - 3) return false;
275 artist = n[..d].Trim();
276 title = n[(d + 3)..].Trim();
277 return artist.Length > 0 && title.Length > 0;
278 }
279
280 private void LyricsTick()
281 {
282 if (++lyrTicks % 4 == 0) LyricsCheck();
283 LyricsDraw();
284 }
285
286 private int lyrTicks;
287
288 private void LyricsCheck()
289 {
290 if (!lyrOn) { lyrResult = null; lyrSong.Text = ""; lyrState.Text = "Lyrics are off."; return; }
291 string title = "", artist = "";
292 double len = 0;
293 int src = 0;
294 bool npHas = np != null && np.Title.Length > 0;
295 if (npHas && (np.Playing || !(gmRun && gmPlaying)))
296 {
297 title = np.Title; artist = np.Artist; len = np.LengthUs / 1_000_000.0; src = 1;
298 }
299 else if (gmRun && gmPlaying && gmSong.Length > 0)
300 {
301 src = 2;
302 len = gmLen;
303 if (!SplitFileSong(gmSong, out artist, out title))
304 {
305 lyrSource = 2;
306 if (lyrKey != "file:" + gmSong)
307 {
308 lyrKey = "file:" + gmSong;
309 lyrResult = null;
310 lyrSong.Text = gmSong;
311 lyrState.Text = "To get lyrics for songs in the game's MP3 player, name the file \"Artist - Title\" (for example \"Daft Punk - One More Time.mp3\").";
312 }
313 return;
314 }
315 }
316 if (src == 0)
317 {
318 if (lyrKey != null)
319 {
320 lyrKey = null;
321 lyrResult = null;
322 lyrSong.Text = "";
323 lyrState.Text = "Play a song on Spotify or YouTube Music Desktop to see its lyrics here.";
324 }
325 return;
326 }
327 lyrSource = src;
328 string key = artist + "\u0001" + title;
329 if (key == lyrKey && DateTime.UtcNow < lyrRetry) return;
330 lyrKey = key;
331 lyrRetry = DateTime.MaxValue;
332 lyrResult = null;
333 lyrSong.Text = (artist.Length > 0 ? artist + " - " : "") + title;
334 lyrState.Text = "Looking up the lyrics...";
335 int req = ++lyrReq;
336 _ = Task.Run(async () =>
337 {
338 LyricsResult r = await LyricsSource.Find(artist, title, len);
339 Avalonia.Threading.Dispatcher.UIThread.Post(() =>
340 {
341 if (req != lyrReq) return;
342 if (r.Failed) { lyrState.Text = "Couldn't reach the lyrics service. Trying again in a minute."; lyrRetry = DateTime.UtcNow.AddMinutes(1); lyrResult = null; }
343 else { lyrResult = r; lyrState.Text = r.Empty ? "No lyrics found for this song." : ""; }
344 LyricsDraw();
345 });
346 });
347 }
348
349 private static Color LMix(Color a, Color b, double t)
350 {
351 t = Math.Clamp(t, 0, 1);
352 return Color.FromArgb((byte)(a.A + (b.A - a.A) * t), (byte)(a.R + (b.R - a.R) * t), (byte)(a.G + (b.G - a.G) * t), (byte)(a.B + (b.B - a.B) * t));
353 }
354
355 private static Color LFade(Color c, double a) => Color.FromArgb((byte)Math.Clamp(255 * a, 0, 255), c.R, c.G, c.B);
356
357 private static IBrush HGrad(params (double at, Color c)[] stops)
358 {
359 LinearGradientBrush g = new() { StartPoint = new RelativePoint(0, 0.5, RelativeUnit.Relative), EndPoint = new RelativePoint(1, 0.5, RelativeUnit.Relative) };
360 foreach (var (at, c) in stops) g.GradientStops.Add(new GradientStop(c, at));
361 return g;
362 }
363
364 private void LyricsDraw()
365 {
366 int half = LyrRows / 2;
367 lyrNote.Text = "";
368 lyrNote.IsVisible = false;
369 lyrCanvas.IsVisible = lyrOn && lyrResult != null && !lyrResult.Empty && (lyrResult.Synced != null || lyrResult.Plain != null);
370 lyrPill.IsVisible = false;
371 if (!lyrOn || lyrResult == null || lyrResult.Empty || lyrResult.Instrumental && lyrResult.Synced == null && lyrResult.Plain == null)
372 {
373 foreach (TextBlock tb in lyrLines) { tb.Text = ""; tb.IsVisible = false; }
374 if (lyrOn && lyrResult != null && lyrResult.Instrumental && lyrResult.Synced == null && lyrResult.Plain == null) lyrState.Text = "Instrumental. No lyrics to show.";
375 lyrState.IsVisible = lyrState.Text.Length > 0;
376 return;
377 }
378 lyrState.IsVisible = false;
379 double w = lyrCanvas.Bounds.Width;
380 if (w < 10) return;
381 double mid = lyrCanvas.Height / 2;
382 if (lyrResult.Synced != null && lyrResult.Synced.Count > 0)
383 {
384 var sl = lyrResult.Synced;
385 double pos = LyricsPos() + 0.2;
386 int i = -1;
387 for (int k = 0; k < sl.Count; k++) { if (sl[k].t <= pos) i = k; else break; }
388 DateTime now = DateTime.UtcNow;
389 if (lyrAnimFor != lyrResult || double.IsNaN(lyrTo))
390 {
391 lyrAnimFor = lyrResult;
392 lyrFrom = lyrTo = lyrCenter = i;
393 lyrAnimAt = DateTime.MinValue;
394 }
395 else if (i != lyrTo)
396 {
397 lyrFrom = Math.Abs(i - lyrCenter) > 3 ? i : lyrCenter;
398 lyrTo = i;
399 lyrAnimAt = now;
400 }
401 double tt = Math.Clamp((now - lyrAnimAt).TotalMilliseconds / 380.0, 0, 1);
402 double e = 1 - Math.Pow(1 - tt, 3);
403 lyrCenter = lyrFrom + (lyrTo - lyrFrom) * e;
404
405 if (i >= 0)
406 {
407 lyrMeasure.Text = sl[i].s.Length > 0 ? sl[i].s : "♪";
408 lyrMeasure.Measure(Size.Infinity);
409 double pw = Math.Min(w, lyrMeasure.DesiredSize.Width + 44);
410 double fade = 0.45 + 0.55 * e;
411 lyrPill.Width = pw;
412 lyrPill.Height = LyrLh - 2;
413 lyrPill.CornerRadius = new CornerRadius((LyrLh - 2) / 2);
414 lyrPill.BorderThickness = new Thickness(1);
415 lyrPill.BorderBrush = Ui.B(LFade(Ui.Orange, 0.55 * fade));
416 lyrPill.Background = HGrad((0, LFade(Ui.Orange, 0.06 * fade)), (0.5, LFade(Ui.Orange, 0.34 * fade)), (1, LFade(Ui.Orange, 0.06 * fade)));
417 double start = sl[i].t, end = i + 1 < sl.Count ? sl[i + 1].t : start + 4;
418 double prog = Math.Clamp((LyricsPos() - start) / Math.Max(0.3, end - start), 0, 1);
419 lyrSweep.Width = Math.Max(0, pw * prog);
420 lyrSweep.Background = HGrad((0, LFade(Ui.Orange, 0.04 * fade)), (1, LFade(Ui.Orange, 0.42 * fade)));
421 Canvas.SetLeft(lyrPill, (w - pw) / 2);
422 Canvas.SetTop(lyrPill, mid + (i - lyrCenter) * LyrLh - LyrLh / 2 + 1);
423 lyrPill.IsVisible = true;
424 }
425
426 int top = (int)Math.Floor(lyrCenter) - half - 1;
427 for (int k = 0; k < lyrLines.Length; k++)
428 {
429 TextBlock tb = lyrLines[k];
430 int idx = top + k;
431 tb.Width = w;
432 Canvas.SetLeft(tb, 0);
433 if (idx < 0 || idx >= sl.Count)
434 {
435 bool intro = i < 0 && idx == -1;
436 tb.IsVisible = intro;
437 if (intro) { tb.Text = "♪"; tb.FontSize = 17; tb.Foreground = Ui.B(Ui.Dim); Canvas.SetTop(tb, mid + (idx - lyrCenter) * LyrLh - LyrLh / 2); }
438 continue;
439 }
440 double d = Math.Abs(idx - lyrCenter);
441 tb.Text = sl[idx].s.Length > 0 ? sl[idx].s : "♪";
442 tb.FontSize = idx == i ? 17 : 14;
443 tb.FontWeight = idx == i ? FontWeight.SemiBold : FontWeight.Normal;
444 tb.Padding = new Thickness(0, idx == i ? 5 : 7, 0, 0);
445 tb.Foreground = Ui.B(idx == i ? LMix(Ui.Bright, Ui.Text, d) : d <= 1 ? LMix(Ui.Text, Ui.Soft, d * 0.6) : d <= 2 ? LMix(Ui.Soft, Ui.Faint, d - 1) : Ui.Faint);
446 Canvas.SetTop(tb, mid + (idx - lyrCenter) * LyrLh - LyrLh / 2);
447 tb.IsVisible = true;
448 }
449 return;
450 }
451 List<string> lines = lyrResult.Plain.Select(x => x.Trim()).Where(x => x.Length > 0).ToList();
452 lyrNote.Text = "Not synced: these lyrics have no timings";
453 lyrNote.IsVisible = true;
454 double len = LyricsLen();
455 int at = len > 0 ? (int)(lines.Count * Math.Clamp(LyricsPos() / len, 0, 1)) : 0;
456 int first = Math.Max(0, Math.Min(lines.Count - LyrRows, at - half));
457 for (int k = 0; k < lyrLines.Length; k++)
458 {
459 TextBlock tb = lyrLines[k];
460 tb.Text = k < LyrRows && first + k < lines.Count ? lines[first + k] : "";
461 tb.IsVisible = k < LyrRows;
462 tb.Width = w;
463 tb.FontSize = 14;
464 tb.FontWeight = FontWeight.Normal;
465 tb.Foreground = Ui.B(Ui.Text);
466 Canvas.SetLeft(tb, 0);
467 Canvas.SetTop(tb, k * LyrLh);
468 }
469 }
470 }
471}