using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Layout; using Avalonia.Media; namespace UltraParadise.Linux { internal sealed class LyricsResult { public List<(double t, string s)> Synced; public string[] Plain; public bool Instrumental, Failed; public bool Empty => (Synced == null || Synced.Count == 0) && Plain == null && !Instrumental; } internal static class LyricsSource { private static string Folder => Path.Combine(Dirs.Cache, "lyrics"); private static string CacheFile(string artist, string title) { byte[] h = SHA1.HashData(Encoding.UTF8.GetBytes(artist.ToLowerInvariant() + "\n" + title.ToLowerInvariant())); return Path.Combine(Folder, Convert.ToHexString(h).ToLowerInvariant() + ".txt"); } public static async Task Find(string artist, string title, double len) { string file = CacheFile(artist, title); LyricsResult cached = ReadCache(file); if (cached != null) return cached; LyricsResult r; try { r = await Search(title, artist, len); if (r == null) { string ct = CleanTitle(title), ca = CleanArtist(artist); if (ct != title || ca != artist) r = await Search(ct, ca, len); } } catch (Exception) { return new LyricsResult { Failed = true }; } WriteCache(file, r); return r ?? new LyricsResult(); } public static string CleanTitle(string t) { 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); s = Regex.Replace(s, @"\s+-\s+(\d{4}\s+)?remaster(ed)?.*$", "", RegexOptions.IgnoreCase); s = Regex.Replace(s, @"\s+(feat\.?|ft\.?)\s+.*$", "", RegexOptions.IgnoreCase); return s.Trim().Length > 0 ? s.Trim() : t; } public static string CleanArtist(string a) { string s = Regex.Replace(a, @"\s*-\s*Topic$", "", RegexOptions.IgnoreCase); s = Regex.Replace(s, "VEVO$", "", RegexOptions.IgnoreCase); int c = s.IndexOfAny(new[] { ',', '&' }); if (c > 0) s = s[..c]; s = Regex.Replace(s, @"\s+(feat\.?|ft\.?|x)\s+.*$", "", RegexOptions.IgnoreCase); return s.Trim().Length > 0 ? s.Trim() : a; } private static string Norm(string s) => new(s.ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray()); private static async Task Search(string title, string artist, double len) { if (title.Trim().Length == 0) return null; string url = "https://lrclib.net/api/search?track_name=" + Uri.EscapeDataString(title) + (artist.Trim().Length > 0 ? "&artist_name=" + Uri.EscapeDataString(artist) : ""); using HttpRequestMessage req = new(HttpMethod.Get, url); req.Headers.UserAgent.ParseAdd("UltraParadiseCUTrainer-Linux/" + Program.Version + " (https://www.nexusmods.com/scavprototype/mods/1203)"); using CancellationTokenSource cts = new(TimeSpan.FromSeconds(15)); using HttpResponseMessage res = await Http.Client.SendAsync(req, cts.Token); res.EnsureSuccessStatusCode(); byte[] body = await res.Content.ReadAsByteArrayAsync(cts.Token); if (body.Length > 8 * 1024 * 1024) return null; using JsonDocument doc = JsonDocument.Parse(body); if (doc.RootElement.ValueKind != JsonValueKind.Array) return null; string na = Norm(artist), nt = Norm(CleanTitle(title)); JsonElement? best = null; int bestScore = int.MinValue; foreach (JsonElement d in doc.RootElement.EnumerateArray()) { string nra = Norm(Str(d, "artistName")), nrt = Norm(CleanTitle(Str(d, "trackName"))); if (na.Length > 0 && !(nra.Contains(na) || na.Contains(nra))) continue; if (nt.Length > 0 && !(nrt.Contains(nt) || nt.Contains(nrt))) continue; double dur = d.TryGetProperty("duration", out JsonElement de) && de.ValueKind == JsonValueKind.Number ? de.GetDouble() : 0; if (len > 0 && dur > 0 && Math.Abs(dur - len) > 6) continue; int score; if (Str(d, "syncedLyrics").Length > 0) score = 100; else if (Str(d, "plainLyrics").Length > 0) score = 40; else if (Inst(d)) score = 20; else continue; if (nrt == nt) score += 10; if (nra == na) score += 10; if (len > 0 && dur > 0) score -= (int)Math.Abs(dur - len); if (score > bestScore) { bestScore = score; best = d; } } if (best == null) return null; JsonElement b = best.Value; LyricsResult r = new() { Instrumental = Inst(b) }; string synced = Str(b, "syncedLyrics"); if (synced.Length > 0) r.Synced = ParseLrc(synced); string plain = Str(b, "plainLyrics"); if (plain.Length > 0) r.Plain = plain.Replace("\r", "").Split('\n'); return r.Empty ? null : r; } private static string Str(JsonElement d, string k) => d.TryGetProperty(k, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; private static bool Inst(JsonElement d) => d.TryGetProperty("instrumental", out JsonElement v) && v.ValueKind == JsonValueKind.True; public static List<(double, string)> ParseLrc(string lrc) { List<(double, string)> list = new(); Regex tag = new(@"\[(\d+):(\d+(?:[\.:]\d+)?)\]"); foreach (string raw in lrc.Replace("\r", "").Split('\n')) { MatchCollection ms = tag.Matches(raw); if (ms.Count == 0) continue; Match last = ms[^1]; string text = raw[(last.Index + last.Length)..].Trim(); foreach (Match m in ms) { double min = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); if (!double.TryParse(m.Groups[2].Value.Replace(':', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out double sec)) continue; list.Add((min * 60 + sec, text)); } } list.Sort((a, b) => a.Item1.CompareTo(b.Item1)); return list; } private static LyricsResult ReadCache(string file) { try { if (!File.Exists(file)) return null; string[] lines = File.ReadAllText(file, Encoding.UTF8).Replace("\r", "").Split('\n'); if (lines.Length < 2 || lines[0] != "UPLYRICS 1") return null; string body = string.Join("\n", lines.Skip(2)); LyricsResult r = new(); switch (lines[1]) { case "S": r.Synced = ParseLrc(body); break; case "P": r.Plain = body.Split('\n'); break; case "I": r.Instrumental = true; break; case "N": if ((DateTime.UtcNow - File.GetLastWriteTimeUtc(file)).TotalDays > 3) return null; break; default: return null; } return r; } catch (Exception) { return null; } } private static void WriteCache(string file, LyricsResult r) { try { Private.Dir(Dirs.Cache); Private.Dir(Folder); StringBuilder sb = new("UPLYRICS 1\n"); if (r != null && r.Synced != null && r.Synced.Count > 0) { sb.Append("S\n"); foreach (var (t, s) in r.Synced) { int cs = (int)Math.Round(t * 100); sb.Append('[').Append((cs / 6000).ToString("00", CultureInfo.InvariantCulture)).Append(':') .Append((cs / 100 % 60).ToString("00", CultureInfo.InvariantCulture)).Append('.') .Append((cs % 100).ToString("00", CultureInfo.InvariantCulture)).Append(']').Append(s).Append('\n'); } } else if (r != null && r.Plain != null) sb.Append("P\n").Append(string.Join("\n", r.Plain)); else if (r != null && r.Instrumental) sb.Append("I\n"); else sb.Append("N\n"); Private.Write(file, Encoding.UTF8.GetBytes(sb.ToString())); } catch (Exception) { } } } internal sealed partial class MainWindow { private const int LyrRows = 7; private const double LyrLh = 32; private readonly TextBlock[] lyrLines = new TextBlock[LyrRows + 3]; private readonly Canvas lyrCanvas = new() { Height = LyrRows * LyrLh, ClipToBounds = true }; private readonly Border lyrPill = new() { ClipToBounds = true, IsVisible = false }; private readonly Border lyrSweep = new() { HorizontalAlignment = HorizontalAlignment.Left }; private readonly TextBlock lyrMeasure = new() { FontSize = 17, FontWeight = FontWeight.SemiBold }; private double lyrFrom = double.NaN, lyrTo = double.NaN, lyrCenter; private DateTime lyrAnimAt = DateTime.MinValue; private LyricsResult lyrAnimFor; private readonly TextBlock lyrSong = T("", 12, Ui.B(Ui.Dim), false, true); private readonly TextBlock lyrState = T("", 13, Ui.B(Ui.Dim), false, true); private readonly TextBlock lyrNote = T("", 11, Ui.B(Ui.Faint), false, true); private readonly Button lyrToggle = new(); private LyricsResult lyrResult; private string lyrKey; private int lyrReq, lyrSource; private DateTime lyrRetry = DateTime.MaxValue, gmStamp = DateTime.UtcNow; private bool lyrOn = true; private Border BuildLyrics() { Border sec = Section("LYRICS", out StackPanel lb); lyrOn = Settings.On("lyrics", true); lyrToggle.Content = lyrOn ? "Hide Lyrics" : "Show Lyrics"; lyrToggle.Click += (_, _) => { lyrOn = !lyrOn; Settings.Set("lyrics", lyrOn ? "1" : "0"); lyrToggle.Content = lyrOn ? "Hide Lyrics" : "Show Lyrics"; lyrKey = null; LyricsCheck(); LyricsDraw(); }; lb.Children.Add(lyrToggle); lyrSong.TextAlignment = TextAlignment.Center; lb.Children.Add(lyrSong); lyrNote.TextAlignment = TextAlignment.Center; lb.Children.Add(lyrNote); lyrPill.Child = lyrSweep; lyrCanvas.Children.Add(lyrPill); for (int i = 0; i < lyrLines.Length; i++) { lyrLines[i] = T("", 14, Ui.B(Ui.Text), false, false); lyrLines[i].TextAlignment = TextAlignment.Center; lyrLines[i].Height = LyrLh; lyrLines[i].VerticalAlignment = VerticalAlignment.Center; lyrLines[i].TextTrimming = TextTrimming.CharacterEllipsis; lyrLines[i].Padding = new Thickness(0, 6, 0, 0); lyrCanvas.Children.Add(lyrLines[i]); } lb.Children.Add(lyrCanvas); Avalonia.Threading.DispatcherTimer anim = new() { Interval = TimeSpan.FromMilliseconds(16) }; anim.Tick += (_, _) => { if (MusicVisible && lyrOn && lyrResult != null && lyrResult.Synced != null && lyrResult.Synced.Count > 0) LyricsDraw(); }; anim.Start(); lyrState.TextAlignment = TextAlignment.Center; lb.Children.Add(lyrState); TextBlock credit = T("Lyrics from LRCLIB (lrclib.net)", 11, Ui.B(Ui.Faint), false, true); credit.TextAlignment = TextAlignment.Center; lb.Children.Add(credit); lyrState.Text = "Play a song on Spotify or YouTube Music Desktop to see its lyrics here."; LyricsDraw(); return sec; } private double LyricsPos() { if (lyrSource == 2) return gmPos + (gmPlaying ? Math.Clamp((DateTime.UtcNow - gmStamp).TotalSeconds, 0, 2) : 0); return LivePosUs() / 1_000_000.0; } private double LyricsLen() => lyrSource == 2 ? gmLen : (np != null ? np.LengthUs / 1_000_000.0 : 0); private static bool SplitFileSong(string file, out string artist, out string title) { artist = title = ""; string n = Regex.Replace(Path.GetFileNameWithoutExtension(file ?? ""), @"^\d{1,3}[\s\.\-_]+", ""); int d = n.IndexOf(" - ", StringComparison.Ordinal); if (d <= 0 || d >= n.Length - 3) return false; artist = n[..d].Trim(); title = n[(d + 3)..].Trim(); return artist.Length > 0 && title.Length > 0; } private void LyricsTick() { if (++lyrTicks % 4 == 0) LyricsCheck(); LyricsDraw(); } private int lyrTicks; private void LyricsCheck() { if (!lyrOn) { lyrResult = null; lyrSong.Text = ""; lyrState.Text = "Lyrics are off."; return; } string title = "", artist = ""; double len = 0; int src = 0; bool npHas = np != null && np.Title.Length > 0; if (npHas && (np.Playing || !(gmRun && gmPlaying))) { title = np.Title; artist = np.Artist; len = np.LengthUs / 1_000_000.0; src = 1; } else if (gmRun && gmPlaying && gmSong.Length > 0) { src = 2; len = gmLen; if (!SplitFileSong(gmSong, out artist, out title)) { lyrSource = 2; if (lyrKey != "file:" + gmSong) { lyrKey = "file:" + gmSong; lyrResult = null; lyrSong.Text = gmSong; 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\")."; } return; } } if (src == 0) { if (lyrKey != null) { lyrKey = null; lyrResult = null; lyrSong.Text = ""; lyrState.Text = "Play a song on Spotify or YouTube Music Desktop to see its lyrics here."; } return; } lyrSource = src; string key = artist + "\u0001" + title; if (key == lyrKey && DateTime.UtcNow < lyrRetry) return; lyrKey = key; lyrRetry = DateTime.MaxValue; lyrResult = null; lyrSong.Text = (artist.Length > 0 ? artist + " - " : "") + title; lyrState.Text = "Looking up the lyrics..."; int req = ++lyrReq; _ = Task.Run(async () => { LyricsResult r = await LyricsSource.Find(artist, title, len); Avalonia.Threading.Dispatcher.UIThread.Post(() => { if (req != lyrReq) return; if (r.Failed) { lyrState.Text = "Couldn't reach the lyrics service. Trying again in a minute."; lyrRetry = DateTime.UtcNow.AddMinutes(1); lyrResult = null; } else { lyrResult = r; lyrState.Text = r.Empty ? "No lyrics found for this song." : ""; } LyricsDraw(); }); }); } private static Color LMix(Color a, Color b, double t) { t = Math.Clamp(t, 0, 1); 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)); } private static Color LFade(Color c, double a) => Color.FromArgb((byte)Math.Clamp(255 * a, 0, 255), c.R, c.G, c.B); private static IBrush HGrad(params (double at, Color c)[] stops) { LinearGradientBrush g = new() { StartPoint = new RelativePoint(0, 0.5, RelativeUnit.Relative), EndPoint = new RelativePoint(1, 0.5, RelativeUnit.Relative) }; foreach (var (at, c) in stops) g.GradientStops.Add(new GradientStop(c, at)); return g; } private void LyricsDraw() { int half = LyrRows / 2; lyrNote.Text = ""; lyrNote.IsVisible = false; lyrCanvas.IsVisible = lyrOn && lyrResult != null && !lyrResult.Empty && (lyrResult.Synced != null || lyrResult.Plain != null); lyrPill.IsVisible = false; if (!lyrOn || lyrResult == null || lyrResult.Empty || lyrResult.Instrumental && lyrResult.Synced == null && lyrResult.Plain == null) { foreach (TextBlock tb in lyrLines) { tb.Text = ""; tb.IsVisible = false; } if (lyrOn && lyrResult != null && lyrResult.Instrumental && lyrResult.Synced == null && lyrResult.Plain == null) lyrState.Text = "Instrumental. No lyrics to show."; lyrState.IsVisible = lyrState.Text.Length > 0; return; } lyrState.IsVisible = false; double w = lyrCanvas.Bounds.Width; if (w < 10) return; double mid = lyrCanvas.Height / 2; if (lyrResult.Synced != null && lyrResult.Synced.Count > 0) { var sl = lyrResult.Synced; double pos = LyricsPos() + 0.2; int i = -1; for (int k = 0; k < sl.Count; k++) { if (sl[k].t <= pos) i = k; else break; } DateTime now = DateTime.UtcNow; if (lyrAnimFor != lyrResult || double.IsNaN(lyrTo)) { lyrAnimFor = lyrResult; lyrFrom = lyrTo = lyrCenter = i; lyrAnimAt = DateTime.MinValue; } else if (i != lyrTo) { lyrFrom = Math.Abs(i - lyrCenter) > 3 ? i : lyrCenter; lyrTo = i; lyrAnimAt = now; } double tt = Math.Clamp((now - lyrAnimAt).TotalMilliseconds / 380.0, 0, 1); double e = 1 - Math.Pow(1 - tt, 3); lyrCenter = lyrFrom + (lyrTo - lyrFrom) * e; if (i >= 0) { lyrMeasure.Text = sl[i].s.Length > 0 ? sl[i].s : "♪"; lyrMeasure.Measure(Size.Infinity); double pw = Math.Min(w, lyrMeasure.DesiredSize.Width + 44); double fade = 0.45 + 0.55 * e; lyrPill.Width = pw; lyrPill.Height = LyrLh - 2; lyrPill.CornerRadius = new CornerRadius((LyrLh - 2) / 2); lyrPill.BorderThickness = new Thickness(1); lyrPill.BorderBrush = Ui.B(LFade(Ui.Orange, 0.55 * fade)); 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))); double start = sl[i].t, end = i + 1 < sl.Count ? sl[i + 1].t : start + 4; double prog = Math.Clamp((LyricsPos() - start) / Math.Max(0.3, end - start), 0, 1); lyrSweep.Width = Math.Max(0, pw * prog); lyrSweep.Background = HGrad((0, LFade(Ui.Orange, 0.04 * fade)), (1, LFade(Ui.Orange, 0.42 * fade))); Canvas.SetLeft(lyrPill, (w - pw) / 2); Canvas.SetTop(lyrPill, mid + (i - lyrCenter) * LyrLh - LyrLh / 2 + 1); lyrPill.IsVisible = true; } int top = (int)Math.Floor(lyrCenter) - half - 1; for (int k = 0; k < lyrLines.Length; k++) { TextBlock tb = lyrLines[k]; int idx = top + k; tb.Width = w; Canvas.SetLeft(tb, 0); if (idx < 0 || idx >= sl.Count) { bool intro = i < 0 && idx == -1; tb.IsVisible = intro; if (intro) { tb.Text = "♪"; tb.FontSize = 17; tb.Foreground = Ui.B(Ui.Dim); Canvas.SetTop(tb, mid + (idx - lyrCenter) * LyrLh - LyrLh / 2); } continue; } double d = Math.Abs(idx - lyrCenter); tb.Text = sl[idx].s.Length > 0 ? sl[idx].s : "♪"; tb.FontSize = idx == i ? 17 : 14; tb.FontWeight = idx == i ? FontWeight.SemiBold : FontWeight.Normal; tb.Padding = new Thickness(0, idx == i ? 5 : 7, 0, 0); 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); Canvas.SetTop(tb, mid + (idx - lyrCenter) * LyrLh - LyrLh / 2); tb.IsVisible = true; } return; } List lines = lyrResult.Plain.Select(x => x.Trim()).Where(x => x.Length > 0).ToList(); lyrNote.Text = "Not synced: these lyrics have no timings"; lyrNote.IsVisible = true; double len = LyricsLen(); int at = len > 0 ? (int)(lines.Count * Math.Clamp(LyricsPos() / len, 0, 1)) : 0; int first = Math.Max(0, Math.Min(lines.Count - LyrRows, at - half)); for (int k = 0; k < lyrLines.Length; k++) { TextBlock tb = lyrLines[k]; tb.Text = k < LyrRows && first + k < lines.Count ? lines[first + k] : ""; tb.IsVisible = k < LyrRows; tb.Width = w; tb.FontSize = 14; tb.FontWeight = FontWeight.Normal; tb.Foreground = Ui.B(Ui.Text); Canvas.SetLeft(tb, 0); Canvas.SetTop(tb, k * LyrLh); } } } }