using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Globalization; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace UltraParadise { internal sealed class LyricsResult { public List> Synced; public string[] Plain; public bool Instrumental; public bool Failed; } internal static class LyricsSource { private static string Dir { get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UltraParadise"), "lyrics"); } } private static string CacheFile(string artist, string title) { using (SHA1 sha = SHA1.Create()) { byte[] h = sha.ComputeHash(Encoding.UTF8.GetBytes(artist.ToLowerInvariant() + "\n" + title.ToLowerInvariant())); StringBuilder sb = new StringBuilder(); foreach (byte b in h) sb.Append(b.ToString("x2", CultureInfo.InvariantCulture)); return Path.Combine(Dir, sb.ToString() + ".txt"); } } public static LyricsResult Find(string artist, string title, string album, double len) { string file = CacheFile(artist, title); LyricsResult cached = ReadCache(file); if (cached != null) return cached; LyricsResult r; try { r = Search(title, artist, len); if (r == null) { string ct = CleanTitle(title); string ca = CleanArtist(artist); if (ct != title || ca != artist) r = 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 char[] { ',', '&' }); if (c > 0) s = s.Substring(0, 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) { StringBuilder sb = new StringBuilder(); foreach (char c in s.ToLowerInvariant()) if (char.IsLetterOrDigit(c)) sb.Append(c); return sb.ToString(); } private static LyricsResult 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) : ""); ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "GET"; req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version + " (https://www.nexusmods.com/scavprototype/mods/1203)"; req.Timeout = 10000; req.ReadWriteTimeout = 15000; string json; using (WebResponse res = req.GetResponse()) using (StreamReader rd = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) { char[] buf = new char[4 * 1024 * 1024]; int total = 0, n; while (total < buf.Length && (n = rd.Read(buf, total, buf.Length - total)) > 0) total += n; json = new string(buf, 0, total); } System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); js.MaxJsonLength = 8 * 1024 * 1024; object[] arr = js.DeserializeObject(json) as object[]; if (arr == null) return null; string na = Norm(artist), nt = Norm(CleanTitle(title)); Dictionary best = null; int bestScore = int.MinValue; foreach (object o in arr) { Dictionary d = o as Dictionary; if (d == null) continue; string ra = Str(d, "artistName"), rt = Str(d, "trackName"); string nra = Norm(ra), nrt = Norm(CleanTitle(rt)); if (na.Length > 0 && !(nra.Contains(na) || na.Contains(nra))) continue; if (nt.Length > 0 && !(nrt.Contains(nt) || nt.Contains(nrt))) continue; double dur = Num(d, "duration"); if (len > 0 && dur > 0 && Math.Abs(dur - len) > 6) continue; int score = 0; if (Str(d, "syncedLyrics").Length > 0) score += 100; else if (Str(d, "plainLyrics").Length > 0) score += 40; else if (Bool(d, "instrumental")) 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; LyricsResult r = new LyricsResult(); r.Instrumental = Bool(best, "instrumental"); string synced = Str(best, "syncedLyrics"); if (synced.Length > 0) r.Synced = ParseLrc(synced); string plain = Str(best, "plainLyrics"); if (plain.Length > 0) r.Plain = plain.Replace("\r", "").Split('\n'); if ((r.Synced == null || r.Synced.Count == 0) && r.Plain == null && !r.Instrumental) return null; return r; } private static string Str(Dictionary d, string k) { object v; return d.TryGetValue(k, out v) && v != null ? v.ToString() : ""; } private static double Num(Dictionary d, string k) { object v; if (!d.TryGetValue(k, out v) || v == null) return 0; double x; return double.TryParse(Convert.ToString(v, CultureInfo.InvariantCulture), NumberStyles.Float, CultureInfo.InvariantCulture, out x) ? x : 0; } private static bool Bool(Dictionary d, string k) { object v; return d.TryGetValue(k, out v) && v is bool && (bool)v; } public static List> ParseLrc(string lrc) { List> list = new List>(); Regex tag = new Regex("\\[(\\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[ms.Count - 1]; string text = raw.Substring(last.Index + last.Length).Trim(); foreach (Match m in ms) { double min = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); double sec; if (!double.TryParse(m.Groups[2].Value.Replace(':', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out sec)) continue; list.Add(new KeyValuePair(min * 60 + sec, text)); } } list.Sort(delegate (KeyValuePair a, KeyValuePair b) { return a.Key.CompareTo(b.Key); }); 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; LyricsResult r = new LyricsResult(); string body = string.Join("\n", lines, 2, lines.Length - 2); 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 { Directory.CreateDirectory(Dir); StringBuilder sb = new StringBuilder("UPLYRICS 1\n"); if (r != null && r.Synced != null && r.Synced.Count > 0) { sb.Append("S\n"); foreach (KeyValuePair kv in r.Synced) { int cs = (int)Math.Round(kv.Key * 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(kv.Value).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"); File.WriteAllText(file, sb.ToString(), new UTF8Encoding(false)); } catch (Exception) { } } } internal class LyricsCard : Control { public LyricsResult Result; public string State = ""; public string Song = ""; public bool On = true; public Func Position; public Func Length; public event Action Toggle; private Rectangle toggleRect; private bool hoverToggle; private readonly Font head = Theme.F("Segoe UI Semibold", 8f); private readonly Font cur = Theme.F("Segoe UI Semibold", 12.5f); private readonly Font line = Theme.F("Segoe UI", 10.5f); private readonly Font small = Theme.F("Segoe UI", 8.5f); public LyricsCard() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); } private static GraphicsPath Round(Rectangle r, int rad) { int d = Math.Max(1, rad * 2); GraphicsPath p = new GraphicsPath(); p.AddArc(r.X, r.Y, d, d, 180, 90); p.AddArc(r.Right - d, r.Y, d, d, 270, 90); p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90); p.AddArc(r.X, r.Bottom - d, d, d, 90, 90); p.CloseFigure(); return p; } public int CurrentIndex() { if (Result == null || Result.Synced == null || Result.Synced.Count == 0 || Position == null) return -1; double pos = Position() + 0.2; int i = -1; for (int k = 0; k < Result.Synced.Count; k++) { if (Result.Synced[k].Key <= pos) i = k; else break; } return i; } public string CurrentLine() { int i = CurrentIndex(); return i >= 0 ? Result.Synced[i].Value : null; } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; g.Clear(Theme.Back); int W = Width, H = Height, pad = Theme.S(16); using (GraphicsPath p = Round(new Rectangle(0, 0, W - 1, H - 1), Theme.S(10))) { using (SolidBrush b = new SolidBrush(Theme.Panel)) g.FillPath(b, p); using (Pen pe = new Pen(Theme.Line)) g.DrawPath(pe, p); } StringFormat l = new StringFormat(); l.LineAlignment = StringAlignment.Center; l.Trimming = StringTrimming.EllipsisCharacter; l.FormatFlags = StringFormatFlags.NoWrap; StringFormat c = new StringFormat(l); c.Alignment = StringAlignment.Center; StringFormat r = new StringFormat(l); r.Alignment = StringAlignment.Far; int y = Theme.S(12); using (SolidBrush o = new SolidBrush(Theme.Orange)) g.DrawString(Theme.Spaced("LYRICS"), head, o, new RectangleF(pad, y, W - pad * 2, Theme.S(18)), l); string tg = On ? "Hide" : "Show"; SizeF ts = g.MeasureString(tg, small); toggleRect = new Rectangle(W - pad - (int)ts.Width - Theme.S(8), y - Theme.S(2), (int)ts.Width + Theme.S(8), Theme.S(22)); using (SolidBrush tb = new SolidBrush(hoverToggle ? Theme.Orange : Theme.Soft)) g.DrawString(tg, small, tb, toggleRect, c); y += Theme.S(22); if (On && Song.Length > 0) using (SolidBrush sb = new SolidBrush(Theme.Dim)) g.DrawString(Song, small, sb, new RectangleF(pad, y, W - pad * 2, Theme.S(18)), l); y += Theme.S(22); int footH = Theme.S(22); Rectangle body = new Rectangle(pad, y, W - pad * 2, Math.Max(Theme.S(30), H - y - footH)); if (!On) Message(g, body, "Lyrics are off. Click Show to turn them back on."); else if (Result != null && Result.Synced != null && Result.Synced.Count > 0) DrawSynced(g, body, c); else if (Result != null && Result.Plain != null) DrawPlain(g, body, c); else if (Result != null && Result.Instrumental) Message(g, body, "Instrumental. No lyrics to show."); else Message(g, body, State); using (SolidBrush fb = new SolidBrush(Theme.Faint)) g.DrawString(On ? "Lyrics from LRCLIB (lrclib.net)" : "", small, fb, new RectangleF(pad, H - footH - Theme.S(4), W - pad * 2, footH), c); } private void Message(Graphics g, Rectangle body, string text) { StringFormat m = new StringFormat(); m.Alignment = StringAlignment.Center; m.LineAlignment = StringAlignment.Center; using (SolidBrush b = new SolidBrush(Theme.Dim)) g.DrawString(text ?? "", line, b, body, m); } private double animFrom = double.NaN, animTo = double.NaN, center; private DateTime animAt = DateTime.MinValue; private object animFor; public bool Animating { get { return On && Visible && Result != null && Result.Synced != null && Result.Synced.Count > 0; } } private static double Ease(double t) { t = Math.Max(0, Math.Min(1, t)); return 1 - Math.Pow(1 - t, 3); } private static Color Mix(Color a, Color b, double t) { t = Math.Max(0, Math.Min(1, t)); return Color.FromArgb((int)(a.A + (b.A - a.A) * t), (int)(a.R + (b.R - a.R) * t), (int)(a.G + (b.G - a.G) * t), (int)(a.B + (b.B - a.B) * t)); } private static Color Fade(Color c, double a) { return Color.FromArgb(Math.Max(0, Math.Min(255, (int)(255 * a))), c); } private void DrawSynced(Graphics g, Rectangle body, StringFormat c) { List> s = Result.Synced; int i = CurrentIndex(); DateTime now = DateTime.UtcNow; if (animFor != Result || double.IsNaN(animTo)) { animFor = Result; animFrom = animTo = center = i; animAt = DateTime.MinValue; } else if (i != animTo) { animFrom = Math.Abs(i - center) > 3 ? i : center; animTo = i; animAt = now; } double e = Ease((now - animAt).TotalMilliseconds / 380.0); center = animFrom + (animTo - animFrom) * e; int lh = Theme.S(30); int half = Math.Max(1, body.Height / lh / 2); float mid = body.Y + body.Height / 2f; GraphicsState st = g.Save(); g.SetClip(body); if (i >= 0) { string ct = s[i].Value.Length > 0 ? s[i].Value : "♪"; SizeF sz = g.MeasureString(ct, cur); float hw = Math.Min(body.Width, sz.Width + Theme.S(40)); float hy = mid + (float)((i - center) * lh) - lh / 2f; Rectangle hr = Rectangle.Round(new RectangleF(body.X + (body.Width - hw) / 2f, hy + Theme.S(1), hw, lh - Theme.S(2))); double fade = 0.45 + 0.55 * e; if (hr.Width > 2 && hr.Height > 2) using (GraphicsPath hp = Round(hr, hr.Height / 2)) { using (LinearGradientBrush lg = new LinearGradientBrush(hr, Color.Black, Color.Black, LinearGradientMode.Horizontal)) { ColorBlend cb = new ColorBlend(3); cb.Colors = new Color[] { Fade(Theme.Orange, 0.06 * fade), Fade(Theme.Orange, 0.34 * fade), Fade(Theme.Orange, 0.06 * fade) }; cb.Positions = new float[] { 0f, 0.5f, 1f }; lg.InterpolationColors = cb; g.FillPath(lg, hp); } double start = s[i].Key; double end = i + 1 < s.Count ? s[i + 1].Key : start + 4; double prog = Position != null ? Math.Max(0, Math.Min(1, (Position() - start) / Math.Max(0.3, end - start))) : 0; int pw = (int)(hr.Width * prog); if (pw > 2) { Rectangle pr = new Rectangle(hr.X, hr.Y, pw, hr.Height); GraphicsState ps = g.Save(); g.SetClip(hp, CombineMode.Intersect); using (LinearGradientBrush sweep = new LinearGradientBrush(new Rectangle(pr.X - 1, pr.Y, pr.Width + 2, pr.Height), Fade(Theme.Orange, 0.04 * fade), Fade(Theme.Orange, 0.42 * fade), LinearGradientMode.Horizontal)) g.FillRectangle(sweep, pr); g.Restore(ps); } using (Pen pe = new Pen(Fade(Theme.Orange, 0.55 * fade), Math.Max(1f, Theme.S(1)))) g.DrawPath(pe, hp); } } int from = (int)Math.Floor(center) - half - 1, to = (int)Math.Ceiling(center) + half + 1; for (int idx = Math.Max(0, from); idx <= to && idx < s.Count; idx++) { double d = Math.Abs(idx - center); float y = mid + (float)((idx - center) * lh) - lh / 2f; string t = s[idx].Value.Length > 0 ? s[idx].Value : "♪"; Color col = idx == i ? Mix(Theme.Bright, Theme.Text, d) : d <= 1 ? Mix(Theme.Text, Theme.Soft, d * 0.6) : d <= 2 ? Mix(Theme.Soft, Theme.Faint, d - 1) : Theme.Faint; using (SolidBrush b = new SolidBrush(col)) g.DrawString(t, idx == i ? cur : line, b, new RectangleF(body.X, y, body.Width, lh), c); } if (i < 0) using (SolidBrush b = new SolidBrush(Theme.Dim)) g.DrawString("♪", cur, b, new RectangleF(body.X, mid - lh / 2f, body.Width, lh), c); g.Restore(st); } private void DrawPlain(Graphics g, Rectangle body, StringFormat c) { List lines = new List(); foreach (string s in Result.Plain) if (s.Trim().Length > 0) lines.Add(s.Trim()); if (lines.Count == 0) { Message(g, body, "No lyrics found for this song."); return; } double len = Length != null ? Length() : 0, pos = Position != null ? Position() : 0; int lh = Theme.S(24); int rows = Math.Max(1, (body.Height - Theme.S(20)) / lh); int at = len > 0 ? (int)(lines.Count * Math.Max(0, Math.Min(1, pos / len))) : 0; int first = Math.Max(0, Math.Min(lines.Count - rows, at - rows / 2)); using (SolidBrush nb = new SolidBrush(Theme.Faint)) g.DrawString("Not synced: these lyrics have no timings", Theme.F("Segoe UI", 8f), nb, new RectangleF(body.X, body.Y, body.Width, Theme.S(18)), c); for (int k = 0; k < rows && first + k < lines.Count; k++) using (SolidBrush b = new SolidBrush(Theme.Text)) g.DrawString(lines[first + k], line, b, new RectangleF(body.X, body.Y + Theme.S(20) + k * lh, body.Width, lh), c); } protected override void OnMouseMove(MouseEventArgs e) { bool h = toggleRect.Contains(e.Location); if (h != hoverToggle) { hoverToggle = h; Invalidate(); } Cursor = h ? Cursors.Hand : Cursors.Default; } protected override void OnMouseLeave(EventArgs e) { if (hoverToggle) { hoverToggle = false; Invalidate(); } } protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left && toggleRect.Contains(e.Location) && Toggle != null) Toggle(); } } internal partial class MainForm { private readonly LyricsCard lyr = new LyricsCard(); private string lyrKey; private int lyrReq, lyrSource; private DateTime lyrRetry = DateTime.MaxValue; private DateTime gmStamp = DateTime.UtcNow; private void SetupLyrics() { lyr.Visible = false; lyr.On = Get("lyrics", "1") == "1"; lyr.State = "Play a song on Spotify or YouTube Music Desktop to see its lyrics here."; lyr.Position = LyricsPos; lyr.Length = delegate { return lyrSource == 2 ? gmLen : np.End.TotalSeconds; }; lyr.Toggle += delegate { lyr.On = !lyr.On; settings["lyrics"] = lyr.On ? "1" : "0"; Settings.Save(settings); lyrKey = null; LyricsCheck(); lyr.Invalidate(); }; view.Controls.Add(lyr); System.Windows.Forms.Timer anim = new System.Windows.Forms.Timer(); anim.Interval = 16; anim.Tick += delegate { if (lyr.Animating) lyr.Invalidate(); }; anim.Start(); } private double LyricsPos() { if (lyrSource == 2) { double p = gmPos; if (gmPlaying) p += Math.Max(0, Math.Min(2, (DateTime.UtcNow - gmStamp).TotalSeconds)); return p; } return np.LivePos().TotalSeconds; } private static bool SplitFileSong(string file, out string artist, out string title) { artist = title = ""; string n = Path.GetFileNameWithoutExtension(file ?? ""); n = Regex.Replace(n, "^\\d{1,3}[\\s\\.\\-_]+", ""); int d = n.IndexOf(" - ", StringComparison.Ordinal); if (d <= 0 || d >= n.Length - 3) return false; artist = n.Substring(0, d).Trim(); title = n.Substring(d + 3).Trim(); return artist.Length > 0 && title.Length > 0; } private void LyricsCheck() { if (!lyr.On) { lyr.Result = null; lyr.Song = ""; return; } string title = "", artist = "", album = ""; double len = 0; int src = 0; if (np.Has && np.Title.Length > 0 && (np.Playing || !(gmRun && gmPlaying))) { title = np.Title; artist = np.Artist; album = np.Album; len = np.End.TotalSeconds; 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; lyr.Result = null; lyr.Song = gmSong; lyr.State = "To get lyrics for songs in the game's MP3 player, name the file \"Artist - Title\" (for example \"Daft Punk - One More Time.mp3\")."; lyr.Invalidate(); } return; } } if (src == 0) { if (lyrKey != null) { lyrKey = null; lyr.Result = null; lyr.Song = ""; lyr.State = "Play a song on Spotify or YouTube Music Desktop to see its lyrics here."; lyr.Invalidate(); } return; } lyrSource = src; string key = artist + "\u0001" + title; if (key == lyrKey && DateTime.UtcNow < lyrRetry) return; lyrKey = key; lyrRetry = DateTime.MaxValue; lyr.Result = null; lyr.Song = (artist.Length > 0 ? artist + " - " : "") + title; lyr.State = "Looking up the lyrics..."; lyr.Invalidate(); int req = ++lyrReq; string a = artist, t = title, al = album; double ln = len; Task.Run(delegate { LyricsResult r = LyricsSource.Find(a, t, al, ln); try { BeginInvoke((Action)delegate { if (req != lyrReq) return; if (r.Failed) { lyr.State = "Couldn't reach the lyrics service. Trying again in a minute."; lyrRetry = DateTime.UtcNow.AddMinutes(1); } else if (r.Synced == null && r.Plain == null && !r.Instrumental) lyr.State = "No lyrics found for this song."; lyr.Result = r.Failed ? null : r; lyr.Invalidate(); }); } catch (Exception) { } }); } } }