Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Lyriclib v2.0.0
BepInEx/plugins/Lyriclib/Lyriclib.dll
Decompiled 5 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Lyriclib.Flac; using Lyriclib.Lyrics; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.TextCore; using UnityEngine.TextCore.LowLevel; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Lyriclib { public readonly struct LyriclibStatus { public bool IsReady { get; } public bool IsOverlayEnabled { get; } public bool IsOverlayVisible { get; } public bool HasLyrics { get; } public string TrackName { get; } public string AudioPath { get; } public string LyricPath { get; } public string CurrentLine { get; } public string NextLine { get; } public double PlaybackTime { get; } public int TrackCount { get; } public int LyricTrackCount { get; } public bool IsCatalogScanRunning { get; } public bool IsFlacSupportEnabled { get; } public bool IsBoomboxAvailable { get; } internal LyriclibStatus(bool isReady, bool overlayEnabled, bool overlayVisible, bool hasLyrics, string trackName, string audioPath, string lyricPath, string currentLine, string nextLine, double playbackTime, int trackCount, int lyricTrackCount, bool catalogScanRunning, bool flacSupportEnabled, bool boomboxAvailable) { IsReady = isReady; IsOverlayEnabled = overlayEnabled; IsOverlayVisible = overlayVisible; HasLyrics = hasLyrics; TrackName = trackName ?? string.Empty; AudioPath = audioPath ?? string.Empty; LyricPath = lyricPath ?? string.Empty; CurrentLine = currentLine ?? string.Empty; NextLine = nextLine ?? string.Empty; PlaybackTime = playbackTime; TrackCount = trackCount; LyricTrackCount = lyricTrackCount; IsCatalogScanRunning = catalogScanRunning; IsFlacSupportEnabled = flacSupportEnabled; IsBoomboxAvailable = boomboxAvailable; } public override string ToString() { return "Lyriclib ready=" + IsReady + " overlay=" + ((!IsOverlayEnabled) ? "disabled" : (IsOverlayVisible ? "visible" : "hidden")) + " track='" + TrackName + "' lyrics=" + (HasLyrics ? "yes" : "no") + " catalog=" + LyricTrackCount + "/" + TrackCount + " flac=" + (IsFlacSupportEnabled ? "on" : "off"); } } public readonly struct LyricTrackInfo { public string Name { get; } public string AudioPath { get; } public string LyricPath { get; } public bool HasLyrics { get; } public string Title { get; } public string Artist { get; } internal LyricTrackInfo(string name, string audioPath, string lyricPath, bool hasLyrics, string title, string artist) { Name = name ?? string.Empty; AudioPath = audioPath ?? string.Empty; LyricPath = lyricPath ?? string.Empty; HasLyrics = hasLyrics; Title = title ?? string.Empty; Artist = artist ?? string.Empty; } public override string ToString() { if (Artist.Length <= 0) { return Title; } return Artist + " - " + Title; } } public static class LyriclibApi { public const string ApiVersion = "2.0.0"; public const string Version = "2.0.0"; public static bool IsFlacSupportEnabled => FlacMusicSupport.IsEnabled; public static bool IsBoomboxAvailable => FlacMusicSupport.IsCatalogReady; public static bool IsLyricsReady => LyriclibLyrics.IsReady; public static bool HasLyrics => LyriclibLyrics.HasLyrics; public static string CurrentLyricTrack => LyriclibLyrics.CurrentTrackName; public static string CurrentLine => LyriclibLyrics.CurrentLine; public static string NextLine => LyriclibLyrics.NextLine; public static double PlaybackTime => LyriclibLyrics.PlaybackTime; public static string CurrentLyricPath => LyriclibLyrics.CurrentLyricPath; public static event Action<LyricTrackInfo> TrackChanged; public static event Action TrackStopped; public static event Action<bool> VisibilityChanged; public static bool IsInCustomBoomboxMusicFolder(string path) { if (!string.IsNullOrEmpty(path)) { return FlacMusicSupport.IsUnderMusicFolder(path); } return false; } public static bool IsFlac(byte[] bytes) { if (bytes == null || bytes.Length < 4) { return false; } if (bytes[0] == 102 && bytes[1] == 76 && bytes[2] == 97) { return bytes[3] == 67; } return false; } public static FlacAudio DecodeFile(string path, out string error) { if (string.IsNullOrEmpty(path)) { error = "no path given"; return null; } byte[] bytes; try { bytes = File.ReadAllBytes(path); } catch (Exception ex) { error = "could not read the file: " + ex.Message; return null; } return Decode(bytes, out error); } public static FlacAudio Decode(byte[] bytes, out string error) { if (bytes == null || bytes.Length == 0) { error = "no data given"; return null; } if (!IsFlac(bytes)) { error = "not a native FLAC stream (the fLaC marker is missing)"; return null; } try { FlacAudio flacAudio = FlacDecoder.Decode(bytes); if (flacAudio == null || flacAudio.Samples == null || flacAudio.Samples.Length == 0) { error = "no audio frames decoded"; return null; } error = null; return flacAudio; } catch (Exception ex) { error = ex.Message; return null; } } public static uint ComputeTrackCrc(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } return Crc32.Calculate(bytes); } public static AudioClip CreateClip(FlacAudio audio, string clipName) { if (audio == null) { throw new ArgumentNullException("audio"); } if (audio.Channels <= 0 || audio.SampleRate <= 0 || audio.Samples == null || audio.Samples.Length == 0) { throw new ArgumentException("the decoded audio is incomplete", "audio"); } int num = audio.Samples.Length / audio.Channels; AudioClip val = AudioClip.Create(string.IsNullOrEmpty(clipName) ? "flac" : clipName, num, audio.Channels, audio.SampleRate, false); if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("Unity refused to create the AudioClip"); } if (!val.SetData(audio.ToFloatArray(), 0)) { Object.Destroy((Object)(object)val); throw new InvalidOperationException("uploading the PCM data to the clip failed"); } return val; } public static bool TryRegisterTrack(string path, AudioClip clip, uint crc, out string error) { return FlacMusicSupport.TryRegisterClip(path, crc, clip, out error); } public static bool IsTrackRegistered(uint crc) { return FlacMusicSupport.IsTrackRegistered(crc); } public static AudioClip LoadTrack(string path, out string error) { TryLoadTrack(path, out var clip, out error); return clip; } public static bool TryLoadTrack(string path, out AudioClip clip, out string error) { clip = null; if (string.IsNullOrEmpty(path)) { error = "no path given"; return false; } byte[] bytes; try { bytes = File.ReadAllBytes(path); } catch (Exception ex) { error = "could not read the file: " + ex.Message; return false; } FlacAudio flacAudio = Decode(bytes, out error); if (flacAudio == null) { return false; } AudioClip val; try { val = CreateClip(flacAudio, Path.GetFileNameWithoutExtension(path)); } catch (Exception ex2) { error = ex2.Message; return false; } if (!TryRegisterTrack(path, val, ComputeTrackCrc(bytes), out error)) { Object.Destroy((Object)(object)val); return false; } clip = val; return true; } public static LyriclibStatus GetStatus() { return new LyriclibStatus(LyriclibLyrics.IsReady, LyriclibLyrics.IsOverlayEnabled, LyriclibLyrics.IsOverlayVisible, LyriclibLyrics.HasLyrics, LyriclibLyrics.CurrentTrackName, LyriclibLyrics.CurrentAudioPath, LyriclibLyrics.CurrentLyricPath, LyriclibLyrics.CurrentLine, LyriclibLyrics.NextLine, LyriclibLyrics.PlaybackTime, TrackCatalog.Count, TrackCatalog.LyricCount, TrackCatalog.ScanRunning, FlacMusicSupport.IsEnabled, FlacMusicSupport.IsCatalogReady); } internal static void RaiseTrackChanged(LyricTrackInfo info) { Action<LyricTrackInfo> trackChanged = LyriclibApi.TrackChanged; if (trackChanged == null) { return; } try { trackChanged(info); } catch (Exception ex) { ManualLogSource log = LyriclibPlugin.Log; if (log != null) { log.LogError((object)("[Lyriclib] TrackChanged handler threw: " + ex)); } } } internal static void RaiseTrackStopped() { Action trackStopped = LyriclibApi.TrackStopped; if (trackStopped == null) { return; } try { trackStopped(); } catch (Exception ex) { ManualLogSource log = LyriclibPlugin.Log; if (log != null) { log.LogError((object)("[Lyriclib] TrackStopped handler threw: " + ex)); } } } internal static void RaiseVisibilityChanged(bool visible) { Action<bool> visibilityChanged = LyriclibApi.VisibilityChanged; if (visibilityChanged == null) { return; } try { visibilityChanged(visible); } catch (Exception ex) { ManualLogSource log = LyriclibPlugin.Log; if (log != null) { log.LogError((object)("[Lyriclib] VisibilityChanged handler threw: " + ex)); } } } public static void PushPlayback(string audioPath, double timeSeconds, double durationSeconds, string displayName = null) { if (string.IsNullOrEmpty(audioPath)) { throw new ArgumentException("an audio path is required", "audioPath"); } if (LyriclibLyrics.IsReady) { LyriclibLyrics.PushPlayback(audioPath, timeSeconds, durationSeconds, displayName); } } public static void ClearPlayback() { if (LyriclibLyrics.IsReady) { LyriclibLyrics.ClearPlayback(); } } public static void ReloadLyrics() { if (LyriclibLyrics.IsReady) { LyriclibLyrics.ReloadCatalog(); } } public static void SetLyricsVisible(bool visible) { if (LyriclibLyrics.IsReady) { LyriclibLyrics.SetVisible(visible); } } } public static class LyriclibInfo { public const string Guid = "Lyriclib"; public const string Name = "Lyriclib"; public const string Version = "1.0.0"; } [BepInPlugin("Lyriclib", "Lyriclib", "2.0.1")] public sealed class LyriclibPlugin : BaseUnityPlugin { public const string Guid = "Lyriclib"; public const string Name = "Lyriclib"; public const string Version = "2.0.1"; internal static ManualLogSource Log; private static ConfigEntry<bool> _flacEnabled; private static bool _flacReady; internal static LyriclibPlugin Instance { get; private set; } private void Awake() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) Instance = this; Log = ((BaseUnityPlugin)this).Logger; string pluginDir = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location) ?? Paths.PluginPath; try { _flacEnabled = new ConfigFile(Path.Combine(Paths.ConfigPath, "Lyriclib.Flac.cfg"), true).Bind<bool>("General", "Enabled", true, "Decode FLAC (and other formats Unity cannot read) inside CustomBoomboxMusic folders with Lyriclib's native decoder. Off = stock CustomBoomboxMusic behaviour."); FlacMusicSupport.Initialize(_flacEnabled, ((BaseUnityPlugin)this).Logger); _flacReady = true; } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("[Lyriclib] FLAC bridge failed to start: " + ex)); } try { LyriclibLyrics.Initialize(((BaseUnityPlugin)this).Logger, ((BaseUnityPlugin)this).Config, pluginDir); LyriclibLyrics.PullSettings(); } catch (Exception ex2) { ((BaseUnityPlugin)this).Logger.LogError((object)("[Lyriclib] lyric engine failed to start: " + ex2)); } ((BaseUnityPlugin)this).Logger.LogInfo((object)(string.Format("{0} {1} ready | tracks: {2} ({3} with lyrics)", "Lyriclib", "2.0.1", TrackCatalog.Count, TrackCatalog.LyricCount) + " | font: " + (string.IsNullOrEmpty(FontProvider.ResolvedFamily) ? "<TMP default>" : FontProvider.ResolvedFamily) + " | flac: " + ((_flacEnabled != null && _flacEnabled.Value) ? "on" : "off"))); } private void Update() { try { if (_flacReady) { FlacMusicSupport.Instance?.Tick(); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("[Lyriclib] flac tick failed: " + ex.Message)); _flacReady = false; } try { LyriclibLyrics.Tick(Time.unscaledDeltaTime); } catch (Exception ex2) { ((BaseUnityPlugin)this).Logger.LogError((object)("[Lyriclib] lyric tick failed: " + ex2.Message)); } } private void OnDestroy() { try { LyriclibLyrics.Shutdown(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogDebug((object)("[Lyriclib] shutdown: " + ex.Message)); } Instance = null; } } } namespace Lyriclib.Lyrics { public static class FontProvider { private static readonly string[] LxgwKeywords = new string[4] { "lxgw", "wenkai", "霞鹜", "文楷" }; private static readonly string[] DefaultFamilies = new string[17] { "LXGW WenKai", "LXGW WenKai Screen", "LXGW WenKai GB", "霞鹜文楷", "Microsoft YaHei UI", "Microsoft YaHei", "微软雅黑", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC", "思源黑体", "SimHei", "黑体", "DengXian", "等线", "KaiTi", "楷体" }; private static TMP_FontAsset _asset; private static bool _resolved; private static ManualLogSource _log; private const uint FrPrivate = 16u; private static bool _bundledRegistered; public static string ResolvedFamily { get; private set; } = string.Empty; public static string LastError { get; private set; } = string.Empty; public static bool IsLxgw { get; private set; } public static string BundledFamily { get; private set; } = string.Empty; public static bool HasBundledFont => _bundledRegistered; [DllImport("gdi32.dll", CharSet = CharSet.Unicode)] private static extern int AddFontResourceEx(string lpszFilename, uint fl, IntPtr pdv); public static void LoadBundledFont(string ttfPath) { BundledFamily = string.Empty; if (_bundledRegistered || string.IsNullOrWhiteSpace(ttfPath) || !File.Exists(ttfPath)) { return; } try { string[] before = InstalledFamilies(); if (AddFontResourceEx(ttfPath, 16u, IntPtr.Zero) <= 0) { ManualLogSource log = _log; if (log != null) { log.LogWarning((object)("[Lyriclib] the bundled font could not be registered: " + ttfPath)); } return; } _bundledRegistered = true; BundledFamily = NewFamilyName(before, InstalledFamilies()); ManualLogSource log2 = _log; if (log2 != null) { log2.LogInfo((object)("[Lyriclib] bundled font loaded privately, nothing installed: " + ttfPath + ((BundledFamily.Length > 0) ? (" -> family \"" + BundledFamily + "\"") : string.Empty))); } } catch (Exception ex) { LastError = "bundled font registration failed: " + ex.Message; ManualLogSource log3 = _log; if (log3 != null) { log3.LogWarning((object)("[Lyriclib] " + LastError)); } } } private static string[] InstalledFamilies() { try { return Font.GetOSInstalledFontNames() ?? Array.Empty<string>(); } catch { return Array.Empty<string>(); } } private static string NewFamilyName(string[] before, string[] after) { string text = string.Empty; if (after == null) { return text; } foreach (string text2 in after) { if (string.IsNullOrEmpty(text2)) { continue; } bool flag = false; if (before != null) { for (int j = 0; j < before.Length; j++) { if (string.Equals(before[j], text2, StringComparison.OrdinalIgnoreCase)) { flag = true; break; } } } if (!flag) { if (text.Length == 0) { text = text2; } if (ContainsAny(text2, LxgwKeywords)) { return text2; } } } return text; } public static void Initialize(ManualLogSource log) { _log = log; } public static void Reset() { _resolved = false; _asset = null; ResolvedFamily = string.Empty; IsLxgw = false; } public static TMP_FontAsset GetFont(string preferredFamily, string extraFamilies, string fontAssetName, string fontFile) { if (_resolved) { return _asset; } if (!string.IsNullOrWhiteSpace(fontAssetName)) { TMP_FontAsset val = FindLoadedAsset(fontAssetName.Trim()); if ((Object)(object)val != (Object)null) { _resolved = true; return Accept(val, ((Object)val).name); } ManualLogSource log = _log; if (log != null) { log.LogWarning((object)("[Lyriclib] font asset '" + fontAssetName + "' is not loaded, falling back")); } } TMP_FontAsset val2 = FindLoadedByKeywords(LxgwKeywords); if ((Object)(object)val2 != (Object)null) { _resolved = true; return Accept(val2, ((Object)val2).name); } List<string> list = new List<string>(); if (!string.IsNullOrWhiteSpace(BundledFamily)) { list.Add(BundledFamily); } if (!string.IsNullOrWhiteSpace(preferredFamily) && !list.Contains(preferredFamily.Trim())) { list.Add(preferredFamily.Trim()); } string[] array; if (!string.IsNullOrWhiteSpace(extraFamilies)) { array = extraFamilies.Split(new char[3] { ';', ',', '|' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length > 0 && !list.Contains(text)) { list.Add(text); } } } array = DefaultFamilies; foreach (string item in array) { if (!list.Contains(item)) { list.Add(item); } } for (int j = 0; j < list.Count; j++) { TMP_FontAsset val3 = TryCreateFromFamily(list[j]); if (!((Object)(object)val3 == (Object)null)) { _resolved = true; return Accept(val3, list[j]); } } TMP_FontAsset val4 = FindLoadedCjk(); if ((Object)(object)val4 != (Object)null) { _resolved = true; return Accept(val4, ((Object)val4).name); } LogAvailableAssets(); LastError = "no CJK capable TMP font asset found"; _resolved = true; _asset = null; ResolvedFamily = "<TMP default>"; IsLxgw = false; ManualLogSource log2 = _log; if (log2 != null) { log2.LogWarning((object)"[Lyriclib] no CJK TMP font found, the game's default font is used. Install LXGWWenKai-Regular.ttf (plugin's fonts folder) and restart, or set FontAssetName to a loaded TMP asset."); } return null; } private static TMP_FontAsset Accept(TMP_FontAsset asset, string label) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 _asset = asset; ResolvedFamily = label; IsLxgw = ContainsAny(label, LxgwKeywords); try { if ((int)asset.atlasPopulationMode != 1) { asset.atlasPopulationMode = (AtlasPopulationMode)1; } asset.isMultiAtlasTexturesEnabled = true; } catch (Exception ex) { ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("[Lyriclib] could not make the font atlas growable: " + ex.Message)); } } ManualLogSource log2 = _log; if (log2 != null) { log2.LogInfo((object)("[Lyriclib] lyric font: " + label + (IsLxgw ? " (LXGW, as requested)" : string.Empty))); } if (!IsLxgw) { ManualLogSource log3 = _log; if (log3 != null) { log3.LogInfo((object)"[Lyriclib] hint: install the bundled fonts\\LXGWWenKai-Regular.ttf to get the LXGW look"); } } return asset; } private static string FaceFamilyName(TMP_FontAsset asset) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)asset != (Object)null) { FaceInfo faceInfo = asset.faceInfo; return ((FaceInfo)(ref faceInfo)).familyName ?? string.Empty; } } catch { } return string.Empty; } private static bool FaceFamilyMatches(TMP_FontAsset asset) { string text = FaceFamilyName(asset); if (text.Length == 0) { return true; } return ContainsAny(text, LxgwKeywords); } private static bool ContainsAny(string value, string[] keywords) { if (string.IsNullOrEmpty(value)) { return false; } string text = value.ToLowerInvariant(); for (int i = 0; i < keywords.Length; i++) { if (text.IndexOf(keywords[i], StringComparison.Ordinal) >= 0) { return true; } } return false; } private static TMP_FontAsset[] LoadedAssets() { try { return Resources.FindObjectsOfTypeAll<TMP_FontAsset>() ?? Array.Empty<TMP_FontAsset>(); } catch (Exception ex) { ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("[Lyriclib] asset scan failed: " + ex.Message)); } return Array.Empty<TMP_FontAsset>(); } } private static TMP_FontAsset FindLoadedAsset(string name) { TMP_FontAsset[] array = LoadedAssets(); for (int i = 0; i < array.Length; i++) { if (!((Object)(object)array[i] == (Object)null) && string.Equals(((Object)array[i]).name, name, StringComparison.OrdinalIgnoreCase)) { return array[i]; } } for (int j = 0; j < array.Length; j++) { if (!((Object)(object)array[j] == (Object)null) && ((Object)array[j]).name != null && ((Object)array[j]).name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0) { return array[j]; } } return null; } private static TMP_FontAsset FindLoadedByKeywords(string[] keywords) { TMP_FontAsset[] array = LoadedAssets(); foreach (TMP_FontAsset val in array) { if (!((Object)(object)val == (Object)null) && ContainsAny(((Object)val).name, keywords) && HasCjk(val)) { return val; } } return null; } private static TMP_FontAsset FindLoadedCjk() { TMP_FontAsset[] array = LoadedAssets(); TMP_FontAsset val = null; foreach (TMP_FontAsset val2 in array) { if (!((Object)(object)val2 == (Object)null) && (((Object)val2).name == null || !((Object)val2).name.StartsWith("Lyriclib ", StringComparison.Ordinal)) && HasCjk(val2)) { if ((Object)(object)val == (Object)null) { val = val2; } if (val2.characterTable != null && val2.characterTable.Count > 2000) { return val2; } } } return val; } private static void LogAvailableAssets() { try { TMP_FontAsset[] array = LoadedAssets(); List<string> list = new List<string>(); for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] != (Object)null && !string.IsNullOrEmpty(((Object)array[i]).name)) { list.Add(((Object)array[i]).name); } } ManualLogSource log = _log; if (log != null) { log.LogInfo((object)("[Lyriclib] loaded TMP font assets: " + string.Join(", ", list.ToArray()))); } } catch { } } private static TMP_FontAsset TryCreateFromFamily(string family) { try { TMP_FontAsset val = CreateDynamicFontAsset(family); if ((Object)(object)val == (Object)null) { return null; } if (!HasCjk(val)) { Object.Destroy((Object)(object)val); return null; } if (ContainsAny(family, LxgwKeywords) && !FaceFamilyMatches(val)) { ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("[Lyriclib] family '" + family + "' resolved to '" + FaceFamilyName(val) + "', not LXGW; trying the next candidate")); } Object.Destroy((Object)(object)val); return null; } ((Object)val).name = "Lyriclib " + family; return val; } catch (Exception ex) { ManualLogSource log2 = _log; if (log2 != null) { log2.LogDebug((object)("[Lyriclib] font family '" + family + "' rejected: " + ex.Message)); } return null; } } private static TMP_FontAsset CreateDynamicFontAsset(string family) { Type typeFromHandle = typeof(TMP_FontAsset); MethodInfo method = typeFromHandle.GetMethod("CreateFontAsset", new Type[8] { typeof(string), typeof(string), typeof(int), typeof(GlyphRenderMode), typeof(int), typeof(int), typeof(AtlasPopulationMode), typeof(bool) }); if (method != null) { object? obj = method.Invoke(null, new object[8] { family, "Regular", 90, (object)(GlyphRenderMode)4165, 1024, 1024, (object)(AtlasPopulationMode)1, true }); return (TMP_FontAsset)((obj is TMP_FontAsset) ? obj : null); } MethodInfo method2 = typeFromHandle.GetMethod("CreateFontAsset", new Type[3] { typeof(string), typeof(string), typeof(int) }); if (method2 != null) { object? obj2 = method2.Invoke(null, new object[3] { family, "Regular", 90 }); return (TMP_FontAsset)((obj2 is TMP_FontAsset) ? obj2 : null); } Font val; try { val = Font.CreateDynamicFontFromOSFont(family, 64); } catch { val = null; } if ((Object)(object)val == (Object)null) { return null; } MethodInfo method3 = typeFromHandle.GetMethod("CreateFontAsset", new Type[8] { typeof(Font), typeof(int), typeof(int), typeof(GlyphRenderMode), typeof(int), typeof(int), typeof(AtlasPopulationMode), typeof(bool) }); if (method3 != null) { object? obj4 = method3.Invoke(null, new object[8] { val, 64, 6, (object)(GlyphRenderMode)4165, 2048, 2048, (object)(AtlasPopulationMode)1, true }); TMP_FontAsset val2 = (TMP_FontAsset)((obj4 is TMP_FontAsset) ? obj4 : null); if ((Object)(object)val2 != (Object)null) { return val2; } } MethodInfo method4 = typeFromHandle.GetMethod("CreateFontAsset", new Type[1] { typeof(Font) }); if (method4 != null) { object? obj5 = method4.Invoke(null, new object[1] { val }); return (TMP_FontAsset)((obj5 is TMP_FontAsset) ? obj5 : null); } return null; } private static bool HasCjk(TMP_FontAsset asset) { if ((Object)(object)asset == (Object)null) { return false; } try { if (asset.HasCharacters("歌词")) { return true; } } catch { } try { return asset.HasCharacter('歌', false, true); } catch { return false; } } } public sealed class LyricWord { public double Time; public string Text; public LyricWord(double time, string text) { Time = time; Text = text ?? string.Empty; } } public sealed class LyricLine { public double Time; public double EndTime = -1.0; public string Text = string.Empty; public List<LyricWord> Words; public bool HasWordTiming { get { if (Words != null) { return Words.Count > 0; } return false; } } public double DisplayEnd { get { if (!(EndTime > Time)) { return Time + 4.0; } return EndTime; } } public override string ToString() { return Time.ToString("0.00", CultureInfo.InvariantCulture) + " " + Text; } } public sealed class LyricDocument { public string Path = string.Empty; public string Title = string.Empty; public string Artist = string.Empty; public string Album = string.Empty; public LyricLine[] Lines = Array.Empty<LyricLine>(); public double OffsetMs; public bool IsEmpty { get { if (Lines != null) { return Lines.Length == 0; } return true; } } public double Duration { get { if (!IsEmpty) { return Lines[Lines.Length - 1].DisplayEnd; } return 0.0; } } public int IndexAt(double seconds) { LyricLine[] lines = Lines; if (lines == null || lines.Length == 0) { return -1; } if (seconds < lines[0].Time) { return -1; } int num = 0; int num2 = lines.Length - 1; int result = -1; while (num <= num2) { int num3 = num + num2 >> 1; if (lines[num3].Time <= seconds) { result = num3; num = num3 + 1; } else { num2 = num3 - 1; } } return result; } public double LineProgress(int index, double seconds) { LyricLine[] lines = Lines; if (lines == null || index < 0 || index >= lines.Length) { return 0.0; } LyricLine lyricLine = lines[index]; double num = lyricLine.DisplayEnd - lyricLine.Time; if (num <= 0.05) { return 1.0; } double num2 = (seconds - lyricLine.Time) / num; if (num2 < 0.0) { return 0.0; } if (num2 > 1.0) { return 1.0; } return num2; } } public static class LrcParser { private static readonly Regex TimeTag = new Regex("\\[(\\d{1,3}):(\\d{1,2})(?:[\\.:](\\d{1,3}))?\\]", RegexOptions.Compiled); private static readonly Regex MetaTag = new Regex("^\\[(ti|ar|al|by|offset|length|re|ve):(.*)\\]$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex WordTag = new Regex("<(\\d{1,3}):(\\d{1,2})(?:[\\.:](\\d{1,3}))?>", RegexOptions.Compiled); public static LyricDocument ParseFile(string path) { if (string.IsNullOrEmpty(path) || !File.Exists(path)) { return null; } string text = ReadAllTextSmart(path); if (text == null) { return null; } LyricDocument lyricDocument = Parse(text); if (lyricDocument != null) { lyricDocument.Path = path; } return lyricDocument; } public static LyricDocument Parse(string text) { if (string.IsNullOrEmpty(text)) { return null; } LyricDocument lyricDocument = new LyricDocument(); List<LyricLine> list = new List<LyricLine>(); double num = 0.0; string[] array = text.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n'); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.Length == 0) { continue; } Match match = MetaTag.Match(text2); if (match.Success) { string text3 = match.Groups[1].Value.ToLowerInvariant(); string text4 = match.Groups[2].Value.Trim(); switch (text3) { case "ti": lyricDocument.Title = text4; break; case "ar": lyricDocument.Artist = text4; break; case "al": lyricDocument.Album = text4; break; case "offset": { if (double.TryParse(text4, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { num = result; } break; } } continue; } MatchCollection matchCollection = TimeTag.Matches(text2); if (matchCollection.Count != 0) { string plain = TimeTag.Replace(text2, string.Empty).Trim(); List<LyricWord> words = ParseWordTiming(plain, out plain); for (int j = 0; j < matchCollection.Count; j++) { Match match2 = matchCollection[j]; double time = ToSeconds(match2.Groups[1].Value, match2.Groups[2].Value, match2.Groups[3].Value); LyricLine item = new LyricLine { Time = time, Text = plain, Words = words }; list.Add(item); } } } if (list.Count == 0) { return null; } if (Math.Abs(num) > 0.001) { double num2 = num / 1000.0; HashSet<List<LyricWord>> hashSet = new HashSet<List<LyricWord>>(); for (int k = 0; k < list.Count; k++) { LyricLine lyricLine = list[k]; lyricLine.Time -= num2; List<LyricWord> words2 = lyricLine.Words; if (words2 != null && hashSet.Add(words2)) { for (int l = 0; l < words2.Count; l++) { words2[l].Time -= num2; } } } } list.Sort((LyricLine a, LyricLine b) => a.Time.CompareTo(b.Time)); List<LyricLine> list2 = new List<LyricLine>(list.Count); for (int num3 = 0; num3 < list.Count; num3++) { if (list2.Count > 0 && Math.Abs(list2[list2.Count - 1].Time - list[num3].Time) < 0.001) { if (list2[list2.Count - 1].Text.Length == 0) { list2[list2.Count - 1] = list[num3]; } } else { list2.Add(list[num3]); } } for (int num4 = 0; num4 < list2.Count - 1; num4++) { list2[num4].EndTime = list2[num4 + 1].Time; } list2[list2.Count - 1].EndTime = list2[list2.Count - 1].Time + 5.0; lyricDocument.OffsetMs = num; lyricDocument.Lines = list2.ToArray(); return lyricDocument; } private static List<LyricWord> ParseWordTiming(string body, out string plain) { plain = body; if (body.IndexOf('<') < 0) { return null; } MatchCollection matchCollection = WordTag.Matches(body); if (matchCollection.Count == 0) { return null; } List<LyricWord> list = new List<LyricWord>(matchCollection.Count); StringBuilder stringBuilder = new StringBuilder(body.Length); for (int i = 0; i < matchCollection.Count; i++) { Match match = matchCollection[i]; double time = ToSeconds(match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value); int num = match.Index + match.Length; int num2 = ((i + 1 < matchCollection.Count) ? matchCollection[i + 1].Index : body.Length); if (num2 > num) { string text = body.Substring(num, num2 - num); list.Add(new LyricWord(time, text)); stringBuilder.Append(text); } } if (list.Count == 0) { return null; } plain = stringBuilder.ToString(); return list; } private static double ToSeconds(string minutes, string seconds, string fraction) { int num = int.Parse(minutes, CultureInfo.InvariantCulture); int num2 = int.Parse(seconds, CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(fraction)) { return (double)num * 60.0 + (double)num2; } int num3 = Math.Min(fraction.Length, 3); double num4 = (double)int.Parse(fraction, CultureInfo.InvariantCulture) / Math.Pow(10.0, num3); return (double)num * 60.0 + (double)num2 + num4; } private static string ReadAllTextSmart(string path) { try { byte[] array = File.ReadAllBytes(path); if (array.Length == 0) { return null; } if (array.Length >= 3 && array[0] == 239 && array[1] == 187 && array[2] == 191) { return Encoding.UTF8.GetString(array, 3, array.Length - 3); } if (array.Length >= 2 && array[0] == byte.MaxValue && array[1] == 254) { return Encoding.Unicode.GetString(array, 2, array.Length - 2); } if (array.Length >= 2 && array[0] == 254 && array[1] == byte.MaxValue) { return Encoding.BigEndianUnicode.GetString(array, 2, array.Length - 2); } string text = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(array); if (text.IndexOf('\ufffd') < 0) { return text; } } catch { } try { Encoding encoding; try { encoding = Encoding.GetEncoding(936); } catch { encoding = Encoding.UTF8; } return encoding.GetString(File.ReadAllBytes(path)); } catch (Exception) { return null; } } } public static class LyriclibLyrics { private static ManualLogSource _log; private static LyricDocument _document; private static TrackEntry _entry; private static string _lastAudioPath; private static string _lastDisplayName; private static string _cachedTitle; private static bool _cachedShowTitle; private static double _timeOffsetSeconds; private static bool _visible = true; private static bool _overlayShown; private static string _currentLineText = string.Empty; private static string _nextLineText = string.Empty; private static double _playbackTime; private static string _lastDiag = string.Empty; private static string _lastShownName; private static bool _settingsDirty = true; private static IEnumerable<string> _rootCache; private static string _rootCacheRaw; private static string _sharedCache; private static string _sharedCacheRaw; private static bool _roundTypeSearched; private static Type _roundType; private static PropertyInfo _roundInstance; private static float _screenCheck; private static int _lastScreenW = -1; private static int _lastScreenH = -1; private static ConfigEntry<bool> _enabled; private static ConfigEntry<bool> _autoDetect; private static ConfigEntry<float> _minTrackSeconds; private static ConfigEntry<string> _musicRoots; private static ConfigEntry<string> _sharedLyricDir; private static ConfigEntry<OverlayMode> _mode; private static ConfigEntry<float> _fontSize; private static ConfigEntry<float> _lineWidth; private static ConfigEntry<float> _offsetX; private static ConfigEntry<float> _offsetY; private static ConfigEntry<float> _anchorY; private static ConfigEntry<float> _backgroundAlpha; private static ConfigEntry<bool> _showNextLine; private static ConfigEntry<bool> _showTitle; private static ConfigEntry<int> _sortingOrder; private static ConfigEntry<bool> _hideInMenus; private static ConfigEntry<bool> _karaoke; private static ConfigEntry<string> _playedColor; private static ConfigEntry<string> _unplayedColor; private static ConfigEntry<double> _syncOffsetSeconds; private static ConfigEntry<string> _fontFamily; private static ConfigEntry<string> _fontFallbacks; private static ConfigEntry<string> _fontFile; private static ConfigEntry<string> _fontAssetName; public static bool IsReady { get; private set; } public static bool HasLyrics { get { if (_document != null) { return !_document.IsEmpty; } return false; } } public static string CurrentTrackName { get { if (_entry == null) { return string.Empty; } return _entry.Name; } } public static string CurrentAudioPath { get { string text; if (_entry == null) { text = _lastAudioPath; if (text == null) { return string.Empty; } } else { text = _entry.AudioPath; } return text; } } public static string CurrentLyricPath { get { if (_document == null) { return string.Empty; } return _document.Path; } } public static string CurrentLine => _currentLineText; public static string NextLine => _nextLineText; public static double PlaybackTime => _playbackTime; public static bool IsOverlayEnabled { get { if (_enabled != null) { return _enabled.Value; } return false; } } public static bool IsOverlayVisible => _overlayShown; public static void Initialize(ManualLogSource log, ConfigFile config, string pluginDir) { _log = log; BindConfig(config, pluginDir); TrackCatalog.Initialize(log); PlaybackTracker.Initialize(log); FontProvider.Initialize(log); LyricOverlay.Initialize(log); IsReady = true; } private static void BindConfig(ConfigFile config, string pluginDir) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Expected O, but got Unknown //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Expected O, but got Unknown //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Expected O, but got Unknown //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Expected O, but got Unknown //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Expected O, but got Unknown _enabled = config.Bind<bool>("1. General", "Enabled", true, "Master switch for the lyric overlay."); _autoDetect = config.Bind<bool>("1. General", "AutoDetectSources", true, "Watch every AudioSource in the scene and show lyrics for any file that has a matching .lrc. Turn off if you only drive the overlay through the API."); _minTrackSeconds = config.Bind<float>("1. General", "MinTrackSeconds", 8f, new ConfigDescription("Ignore clips shorter than this (sound effects, footsteps, one-shots).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 120f), Array.Empty<object>())); _musicRoots = config.Bind<string>("1. General", "MusicRoots", Path.Combine(Paths.PluginPath, "CustomBoomboxMusic"), "Folders scanned for music files, separated by ';'. Defaults to the CustomBoomboxMusic library only; add the folders of any other mod (or any absolute path) yourself to get lyrics for music played by them. Relative paths are resolved against BepInEx."); _sharedLyricDir = config.Bind<string>("1. General", "SharedLyricFolder", "config\\Lyriclib\\lyrics", "Extra folder holding .lrc files named after the song (no .lrc next to the audio needed). Relative paths are resolved against BepInEx."); _mode = config.Bind<OverlayMode>("2. Display", "Mode", OverlayMode.HudAboveHotbar, "HudAboveHotbar = lyrics floating directly above the hotbar (no panel).\nFloatingWindow = a separate UI panel with its own (transparent by default) background."); _fontSize = config.Bind<float>("2. Display", "FontSize", 30f, new ConfigDescription("Font size at 1080p.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 90f), Array.Empty<object>())); _lineWidth = config.Bind<float>("2. Display", "LineWidth", 1100f, new ConfigDescription("Maximum width of a lyric line in reference pixels.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(300f, 3000f), Array.Empty<object>())); _offsetX = config.Bind<float>("2. Display", "OffsetX", 0f, new ConfigDescription("Horizontal nudge of the overlay.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1500f, 1500f), Array.Empty<object>())); _offsetY = config.Bind<float>("2. Display", "OffsetY", 0f, new ConfigDescription("Vertical nudge of the overlay (positive = up).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1500f, 1500f), Array.Empty<object>())); _anchorY = config.Bind<float>("2. Display", "WindowAnchorY", 0.28f, new ConfigDescription("Vertical screen position of the floating window, 0 = bottom, 1 = top.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); _backgroundAlpha = config.Bind<float>("2. Display", "BackgroundOpacity", 0f, new ConfigDescription("Background opacity of the floating window. 0 = fully transparent (default).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); _showNextLine = config.Bind<bool>("2. Display", "ShowNextLine", true, "Preview the next line under the current one."); _showTitle = config.Bind<bool>("2. Display", "ShowTrackTitle", false, "Show the file name above the lyric line."); _sortingOrder = config.Bind<int>("2. Display", "SortingOrder", 30000, "Canvas sorting order; keep it high so the lyrics sit above the HUD."); _hideInMenus = config.Bind<bool>("2. Display", "HideWhenNotInGame", true, "Hide the overlay while the title screen / main menu is open."); _karaoke = config.Bind<bool>("3. Karaoke", "EnableSweep", true, "Colour the already sung part of the line."); _playedColor = config.Bind<string>("3. Karaoke", "PlayedColor", "#FFD24A", "Colour of the already sung text (hex)."); _unplayedColor = config.Bind<string>("3. Karaoke", "UnplayedColor", "#FFFFFF", "Colour of the text that is still to be sung (hex)."); _syncOffsetSeconds = config.Bind<double>("3. Karaoke", "SyncOffsetSeconds", 0.0, "Shift the lyrics against the audio. Negative = earlier, positive = later."); _fontFamily = config.Bind<string>("4. Font", "FontFamily", "LXGW WenKai", "Preferred TMP font family. LXGW WenKai (霞鹜文楷) is expected first; if it is not installed the first CJK family of FontFallbacks is used."); _fontFallbacks = config.Bind<string>("4. Font", "FontFallbacks", "LXGW WenKai Screen;Microsoft YaHei;Noto Sans CJK SC;SimHei", "Fallback families, separated by ';'."); _fontFile = config.Bind<string>("4. Font", "FontFile", Path.Combine(pluginDir, "fonts", "LXGWWenKai-Regular.ttf"), "Convenience copy of the LXGW file shipped with the plugin. Unity can only use installed fonts, so this path is checked and reported, not loaded directly."); _fontAssetName = config.Bind<string>("4. Font", "FontAssetName", string.Empty, "Name of an already loaded TMP font asset to use (highest priority). Leave empty for automatic: LXGW asset -> installed family -> any CJK asset. The loaded asset names are written to the log."); Watch<bool>(_enabled); Watch<bool>(_autoDetect); Watch<float>(_minTrackSeconds); Watch<OverlayMode>(_mode); Watch<float>(_fontSize); Watch<float>(_lineWidth); Watch<float>(_offsetX); Watch<float>(_offsetY); Watch<float>(_anchorY); Watch<float>(_backgroundAlpha); Watch<bool>(_showNextLine); Watch<bool>(_showTitle); Watch<int>(_sortingOrder); Watch<bool>(_hideInMenus); Watch<bool>(_karaoke); Watch<string>(_musicRoots); Watch<string>(_sharedLyricDir); Watch<string>(_fontFamily); Watch<string>(_fontFallbacks); Watch<string>(_fontFile); Watch<string>(_fontAssetName); Watch<string>(_playedColor); Watch<string>(_unplayedColor); Watch<double>(_syncOffsetSeconds); } public static void PullSettings() { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) try { _timeOffsetSeconds = _syncOffsetSeconds.Value; if (!IsOverlayEnabled) { SetOverlayVisible(visible: false); return; } FontProvider.LoadBundledFont(_fontFile.Value); LyricOverlay.EnsureBuilt(FontProvider.GetFont(_fontFamily.Value, _fontFallbacks.Value, _fontAssetName.Value, _fontFile.Value), _fontSize.Value, _sortingOrder.Value); LyricOverlay.SetColors(ParseColor(_playedColor.Value, new Color(1f, 0.82f, 0.29f, 1f)), ParseColor(_unplayedColor.Value, Color.white)); ApplyDisplaySettings(); } catch (Exception ex) { ManualLogSource log = _log; if (log != null) { log.LogError((object)("[Lyriclib] settings apply failed: " + ex)); } } } private static void ApplyDisplaySettings() { LyricOverlay.ApplySettings(_mode.Value, _fontSize.Value, _lineWidth.Value, _offsetX.Value, _offsetY.Value, _anchorY.Value, _backgroundAlpha.Value); } private static Color ParseColor(string hex, Color fallback) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrWhiteSpace(hex)) { return fallback; } string text = hex.Trim(); if (!text.StartsWith("#", StringComparison.Ordinal)) { text = "#" + text; } Color result = default(Color); if (!ColorUtility.TryParseHtmlString(text, ref result)) { return fallback; } return result; } public static void Tick(float deltaTime) { if (!IsReady || !IsOverlayEnabled) { SetOverlayVisible(visible: false); return; } if (_settingsDirty) { _settingsDirty = false; PullSettings(); } UpdateScreenCheck(deltaTime); TrackCatalog.ApplyPending(); TrackCatalog.Refresh(CachedMusicRoots(), CachedSharedLyricDir()); PlaybackTracker.Tick(deltaTime, _autoDetect.Value, _minTrackSeconds.Value); PlaybackState current = PlaybackTracker.Current; if (!current.Active) { Diag("idle:no track detected"); SetOverlayVisible(visible: false); } else if (!_visible) { Diag("hidden by api"); SetOverlayVisible(visible: false); } else if (_hideInMenus.Value && !current.Playing && IsMenuScreen()) { Diag("hidden:menu screen detected (HideWhenNotInGame)"); SetOverlayVisible(visible: false); } else { DiagShown(current.DisplayName); SetOverlayVisible(visible: true); Render(current); } } private static void UpdateScreenCheck(float deltaTime) { _screenCheck += deltaTime; if (!(_screenCheck <= 1f)) { _screenCheck = 0f; if (Screen.width != _lastScreenW || Screen.height != _lastScreenH) { _lastScreenW = Screen.width; _lastScreenH = Screen.height; ApplyDisplaySettings(); } } } private static void SetOverlayVisible(bool visible) { if (_overlayShown != visible) { _overlayShown = visible; LyricOverlay.SetVisible(visible); LyriclibApi.RaiseVisibilityChanged(visible); } } private static void DiagShown(string displayName) { if (_lastDiag == null || !_lastDiag.StartsWith("shown:", StringComparison.Ordinal) || !string.Equals(_lastShownName, displayName, StringComparison.Ordinal)) { _lastShownName = displayName; Diag("shown:" + displayName); } } private static void Watch<T>(ConfigEntry<T> entry) { if (entry != null) { entry.SettingChanged += delegate { _settingsDirty = true; }; } } private static void Diag(string reason) { if (!string.Equals(_lastDiag, reason, StringComparison.Ordinal)) { _lastDiag = reason; ManualLogSource log = _log; if (log != null) { log.LogInfo((object)("[Lyriclib] overlay " + reason)); } } } private static bool IsMenuScreen() { PropertyInfo propertyInfo = RoundInstanceProperty(); if (propertyInfo == null) { Diag("menu state unknown, assuming in game"); return false; } try { return propertyInfo.GetValue(null, null) == null; } catch { return false; } } private static PropertyInfo RoundInstanceProperty() { if (_roundTypeSearched) { return _roundInstance; } _roundTypeSearched = true; _roundType = FindType("StartOfRound"); if (_roundType != null) { _roundInstance = _roundType.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("[Lyriclib] StartOfRound type: " + ((_roundType != null) ? _roundType.FullName : "<not found>") + " | Instance property: " + ((_roundInstance != null) ? "found" : "<missing>"))); } return _roundInstance; } private static Type FindType(string simpleName) { try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type[] types; try { types = assemblies[i].GetTypes(); } catch { continue; } foreach (Type type in types) { if (type != null && string.Equals(type.Name, simpleName, StringComparison.Ordinal)) { return type; } } } } catch { } return null; } private static void Render(PlaybackState state) { if (!string.Equals(state.AudioPath, _lastAudioPath, StringComparison.OrdinalIgnoreCase) || !string.Equals(state.DisplayName, _lastDisplayName, StringComparison.OrdinalIgnoreCase)) { ResolveTrack(state); } if (_document == null || _document.IsEmpty) { SetOverlayVisible(visible: false); return; } _playbackTime = state.Time + _timeOffsetSeconds; int num = _document.IndexAt(_playbackTime); _currentLineText = ((num >= 0) ? _document.Lines[num].Text : string.Empty); _nextLineText = ((num + 1 < _document.Lines.Length) ? _document.Lines[num + 1].Text : string.Empty); float fill = 0f; if (num >= 0) { LyricLine lyricLine = _document.Lines[num]; fill = (lyricLine.HasWordTiming ? WordProgress(lyricLine, _playbackTime) : ((float)_document.LineProgress(num, _playbackTime))); } if (_cachedTitle == null || _cachedShowTitle != _showTitle.Value) { _cachedShowTitle = _showTitle.Value; _cachedTitle = BuildTitle(state); } LyricOverlay.UpdateView(_cachedTitle, _currentLineText, _nextLineText, fill, _karaoke.Value, _showNextLine.Value); } private static void ResolveTrack(PlaybackState state) { _lastAudioPath = state.AudioPath; _lastDisplayName = state.DisplayName; _cachedTitle = null; _entry = TrackCatalog.FindByAudioPath(state.AudioPath); if (_entry == null && !string.IsNullOrEmpty(state.DisplayName)) { _entry = TrackCatalog.FindByName(state.DisplayName); } _document = TrackCatalog.GetDocument(_entry); if (_entry == null || !_entry.HasLyric) { _document = TrackCatalog.GetDocument(TrackCatalog.ResolveLyric((_entry != null) ? _entry.AudioPath : state.AudioPath, ResolveBepInExPath(_sharedLyricDir.Value))); } if (_document != null) { ManualLogSource log = _log; if (log != null) { log.LogInfo((object)("[Lyriclib] lyrics loaded: " + _document.Path)); } } else { ManualLogSource log2 = _log; if (log2 != null) { log2.LogWarning((object)("[Lyriclib] no lyric for: path='" + (state.AudioPath ?? "<null>") + "' name='" + (state.DisplayName ?? "<null>") + "' entry=" + ((_entry == null) ? "<none>" : (_entry.LyricPath ?? "<no lrc>")))); } } bool hasLyrics = _document != null && !_document.IsEmpty; string title = ((!string.IsNullOrEmpty(_document?.Title)) ? _document.Title : state.DisplayName); LyriclibApi.RaiseTrackChanged(new LyricTrackInfo(state.DisplayName, state.AudioPath, (_document != null) ? _document.Path : ((_entry != null) ? _entry.LyricPath : string.Empty), hasLyrics, title, (_document != null) ? _document.Artist : string.Empty)); } private static string BuildTitle(PlaybackState state) { if (!_showTitle.Value) { return string.Empty; } string text = ((!string.IsNullOrEmpty(_document.Title)) ? _document.Title : state.DisplayName); if (!string.IsNullOrEmpty(_document.Artist)) { text = _document.Artist + " - " + text; } return text ?? string.Empty; } private static void InvalidateTrackKey() { _lastAudioPath = null; _lastDisplayName = null; _cachedTitle = null; } private static float WordProgress(LyricLine line, double time) { List<LyricWord> words = line.Words; if (words == null || words.Count == 0) { return 0f; } if (line.DisplayEnd - line.Time <= 0.05) { return 1f; } int num = 0; for (int i = 0; i < words.Count; i++) { num += words[i].Text.Length; } if (num == 0) { return 0f; } int num2 = 0; for (int j = 0; j < words.Count; j++) { LyricWord lyricWord = words[j]; double num3 = ((j + 1 < words.Count) ? words[j + 1].Time : line.DisplayEnd); if (time >= num3) { num2 += lyricWord.Text.Length; continue; } if (time < lyricWord.Time) { break; } double num4 = Math.Max(0.001, num3 - lyricWord.Time); double num5 = Math.Min(1.0, Math.Max(0.0, (time - lyricWord.Time) / num4)); return (float)(((double)num2 + (double)lyricWord.Text.Length * num5) / (double)num); } return (float)((double)num2 / (double)num); } private static IEnumerable<string> CachedMusicRoots() { string text = _musicRoots.Value ?? string.Empty; if (_rootCache != null && string.Equals(text, _rootCacheRaw, StringComparison.Ordinal)) { return _rootCache; } _rootCacheRaw = text; _rootCache = new List<string>(SplitRoots(text)); return _rootCache; } private static string CachedSharedLyricDir() { string text = _sharedLyricDir.Value ?? string.Empty; if (_sharedCache != null && string.Equals(text, _sharedCacheRaw, StringComparison.Ordinal)) { return _sharedCache; } _sharedCacheRaw = text; _sharedCache = ResolveBepInExPath(text); return _sharedCache; } private static IEnumerable<string> SplitRoots(string raw) { if (string.IsNullOrWhiteSpace(raw)) { yield break; } string[] array = raw.Split(new char[2] { ';', '|' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string text = ResolveBepInExPath(array[i]); if (!string.IsNullOrEmpty(text)) { yield return text; } } } private static string ResolveBepInExPath(string raw) { if (string.IsNullOrWhiteSpace(raw)) { return null; } string text = raw.Trim().Trim('"'); if (text.Length == 0) { return null; } try { if (!Path.IsPathRooted(text)) { text = Path.Combine(Paths.BepInExRootPath ?? ".", text); } return Path.GetFullPath(text); } catch { return null; } } internal static void OnTrackChanged(PlaybackState state) { InvalidateTrackKey(); ManualLogSource log = _log; if (log != null) { log.LogInfo((object)("[Lyriclib] track playing: " + state.DisplayName)); } } internal static void OnTrackStopped() { _document = null; _entry = null; _currentLineText = string.Empty; _nextLineText = string.Empty; _playbackTime = 0.0; InvalidateTrackKey(); SetOverlayVisible(visible: false); ManualLogSource log = _log; if (log != null) { log.LogDebug((object)"[Lyriclib] track stopped"); } LyriclibApi.RaiseTrackStopped(); } public static void PushPlayback(string audioPath, double timeSeconds, double durationSeconds, string displayName = null) { PlaybackTracker.PushExternal(audioPath, displayName, timeSeconds, durationSeconds, 1.5f); } public static void ClearPlayback() { PlaybackTracker.ClearExternal(); OnTrackStopped(); } public static void ReloadCatalog() { TrackCatalog.InvalidateCache(); TrackCatalog.Refresh(SplitRoots(_musicRoots.Value), ResolveBepInExPath(_sharedLyricDir.Value), force: true); InvalidateTrackKey(); } public static void SetVisible(bool visible) { _visible = visible; if (!visible) { SetOverlayVisible(visible: false); } } public static void Shutdown() { PlaybackTracker.Shutdown(); LyricOverlay.Destroy(); _overlayShown = false; _currentLineText = string.Empty; _nextLineText = string.Empty; _playbackTime = 0.0; _document = null; _entry = null; IsReady = false; } } public enum OverlayMode { HudAboveHotbar, FloatingWindow } public static class LyricOverlay { private static ManualLogSource _log; private static GameObject _root; private static RectTransform _container; private static Image _background; private static TextMeshProUGUI _title; private static TextMeshProUGUI _current; private static TextMeshProUGUI _next; private static Canvas _canvas; private static string _currentText = string.Empty; private static string _nextText = string.Empty; private static string _titleText = string.Empty; private static bool _layoutDirty = true; private static Color32 _playedColor = new Color32(byte.MaxValue, (byte)214, (byte)74, byte.MaxValue); private static Color32 _unplayedColor = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue); public static bool IsBuilt => (Object)(object)_root != (Object)null; public static void Initialize(ManualLogSource log) { _log = log; } public static void SetColors(Color played, Color unplayed) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) _playedColor = Color32.op_Implicit(played); _unplayedColor = Color32.op_Implicit(unplayed); } public static void Destroy() { if ((Object)(object)_root != (Object)null) { Object.Destroy((Object)(object)_root); } _root = null; _canvas = null; _container = null; _background = null; _title = null; _current = null; _next = null; _currentText = (_nextText = (_titleText = string.Empty)); } public static void EnsureBuilt(TMP_FontAsset font, float fontSize, int sortingOrder) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_root != (Object)null)) { _root = new GameObject("LyriclibOverlay"); Object.DontDestroyOnLoad((Object)(object)_root); _canvas = _root.AddComponent<Canvas>(); _canvas.renderMode = (RenderMode)0; _canvas.sortingOrder = sortingOrder; CanvasScaler obj = _root.AddComponent<CanvasScaler>(); obj.uiScaleMode = (ScaleMode)1; obj.referenceResolution = new Vector2(1920f, 1080f); obj.screenMatchMode = (ScreenMatchMode)0; obj.matchWidthOrHeight = 0.5f; GameObject val = new GameObject("Lyrics"); val.transform.SetParent(_root.transform, false); _container = val.AddComponent<RectTransform>(); _container.anchorMin = new Vector2(0.5f, 0f); _container.anchorMax = new Vector2(0.5f, 0f); _container.pivot = new Vector2(0.5f, 0.5f); _container.sizeDelta = new Vector2(1200f, 180f); _background = val.AddComponent<Image>(); ((Graphic)_background).color = new Color(0f, 0f, 0f, 0f); ((Graphic)_background).raycastTarget = false; _title = CreateText(val.transform, "Title", font, fontSize * 0.7f); _current = CreateText(val.transform, "Current", font, fontSize); _next = CreateText(val.transform, "Next", font, fontSize * 0.75f); ((Graphic)_next).color = new Color(1f, 1f, 1f, 0.55f); ((TMP_Text)_title).rectTransform.anchoredPosition = new Vector2(0f, fontSize * 1.5f); ((TMP_Text)_current).rectTransform.anchoredPosition = new Vector2(0f, 0f); ((TMP_Text)_next).rectTransform.anchoredPosition = new Vector2(0f, (0f - fontSize) * 1.7f); ManualLogSource log = _log; if (log != null) { log.LogInfo((object)("[Lyriclib] overlay built" + (((Object)(object)font == (Object)null) ? " (TMP default font)" : (" with " + ((Object)font).name)))); } } } private static TextMeshProUGUI CreateText(Transform parent, string name, TMP_FontAsset font, float size) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(name); val.transform.SetParent(parent, false); RectTransform obj = val.AddComponent<RectTransform>(); obj.anchorMin = new Vector2(0f, 1f); obj.anchorMax = new Vector2(1f, 1f); obj.pivot = new Vector2(0.5f, 1f); obj.anchoredPosition = Vector2.zero; obj.sizeDelta = new Vector2(0f, size * 1.6f); TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>(); if ((Object)(object)font != (Object)null) { ((TMP_Text)val2).font = font; } ((TMP_Text)val2).fontSize = size; ((TMP_Text)val2).alignment = (TextAlignmentOptions)514; ((TMP_Text)val2).enableWordWrapping = true; ((TMP_Text)val2).overflowMode = (TextOverflowModes)0; ((Graphic)val2).raycastTarget = false; ((TMP_Text)val2).richText = false; ((TMP_Text)val2).text = string.Empty; return val2; } public static void ApplySettings(OverlayMode mode, float fontSize, float maxWidth, float offsetX, float offsetY, float anchorY, float backgroundAlpha) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_container == (Object)null)) { _container.sizeDelta = new Vector2(Mathf.Max(200f, maxWidth), _container.sizeDelta.y); ApplyTextStyle((TMP_Text)(object)_current, fontSize); ApplyTextStyle((TMP_Text)(object)_next, fontSize * 0.75f); ApplyTextStyle((TMP_Text)(object)_title, fontSize * 0.7f); if ((Object)(object)_background != (Object)null) { Color color = ((Graphic)_background).color; color.a = Mathf.Clamp01(backgroundAlpha); ((Graphic)_background).color = color; ((Behaviour)_background).enabled = backgroundAlpha > 0.001f || mode == OverlayMode.FloatingWindow; } bool flag = mode == OverlayMode.FloatingWindow; float num = (flag ? Mathf.Clamp01(anchorY) : 0f); Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(0.5f, num); _container.anchorMin = val; _container.anchorMax = val; _container.pivot = new Vector2(0.5f, 0.5f); _container.anchoredPosition = (flag ? new Vector2(offsetX, offsetY) : new Vector2(offsetX, 250f + offsetY)); ForceMesh((TMP_Text)(object)_title); ForceMesh((TMP_Text)(object)_current); ForceMesh((TMP_Text)(object)_next); _layoutDirty = true; } } private static void ApplyTextStyle(TMP_Text text, float size) { if (!((Object)(object)text == (Object)null)) { text.fontSize = size; text.alignment = (TextAlignmentOptions)514; } } private static void ForceMesh(TMP_Text text) { if ((Object)(object)text != (Object)null) { text.ForceMeshUpdate(false, false); } } public static void SetVisible(bool visible) { if (!((Object)(object)_root == (Object)null) && _root.activeSelf != visible) { _root.SetActive(visible); } } public static void UpdateView(string title, string currentLine, string nextLine, float fill, bool karaoke, bool showNext) { if (!((Object)(object)_root == (Object)null) && !((Object)(object)_current == (Object)null)) { bool flag = false; string text = title ?? string.Empty; if (_titleText != text) { _titleText = text; ((TMP_Text)_title).text = text; ((Component)_title).gameObject.SetActive(text.Length > 0); flag = true; } string text2 = currentLine ?? string.Empty; if (_currentText != text2) { _currentText = text2; ((TMP_Text)_current).text = text2; ((TMP_Text)_current).ForceMeshUpdate(false, false); flag = true; } string text3 = (showNext ? (nextLine ?? string.Empty) : string.Empty); if (_nextText != text3) { _nextText = text3; ((TMP_Text)_next).text = text3; ((TMP_Text)_next).ForceMeshUpdate(false, false); flag = true; } if (karaoke) { ApplyKaraoke((TMP_Text)(object)_current, Mathf.Clamp01(fill)); } else { RestoreColor((TMP_Text)(object)_current); } if (flag) { _layoutDirty = true; } if (_layoutDirty) { _layoutDirty = false; Layout(); } } } private static void RestoreColor(TMP_Text text) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)text == (Object)null)) { ((Graphic)text).color = new Color((float)(int)_unplayedColor.r / 255f, (float)(int)_unplayedColor.g / 255f, (float)(int)_unplayedColor.b / 255f, (float)(int)_unplayedColor.a / 255f); } } private static void ApplyKaraoke(TMP_Text text, float fill) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)text == (Object)null) { return; } TMP_TextInfo textInfo = text.textInfo; if (textInfo == null || textInfo.characterCount == 0) { return; } float num = 0f; for (int i = 0; i < textInfo.characterCount; i++) { TMP_CharacterInfo val = textInfo.characterInfo[i]; if (val.isVisible) { num += Mathf.Max(0.0001f, val.xAdvance); } } if (num <= 0f) { return; } float num2 = 0f; for (int j = 0; j < textInfo.characterCount; j++) { TMP_CharacterInfo val2 = textInfo.characterInfo[j]; if (val2.isVisible) { float num3 = Mathf.Max(0.0001f, val2.xAdvance); float num4 = num2 / num; float num5 = num3 / num; num2 += num3; float num6 = ((num5 <= 0f) ? 1f : Mathf.Clamp01((fill - num4) / num5)); Color32 val3 = Color32.Lerp(_unplayedColor, _playedColor, num6); TMP_MeshInfo val4 = textInfo.meshInfo[val2.materialReferenceIndex]; int vertexIndex = val2.vertexIndex; if (val4.colors32 != null && vertexIndex + 3 < val4.colors32.Length) { val4.colors32[vertexIndex] = val3; val4.colors32[vertexIndex + 1] = val3; val4.colors32[vertexIndex + 2] = val3; val4.colors32[vertexIndex + 3] = val3; } } } text.UpdateVertexData((TMP_VertexDataUpdateFlags)16); } private static void Layout() { //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) float num = (((Object)(object)_title != (Object)null && ((Component)_title).gameObject.activeSelf) ? ((TMP_Text)_title).preferredHeight : 0f); float num2 = (((Object)(object)_current != (Object)null) ? ((TMP_Text)_current).preferredHeight : 0f); float num3 = (((Object)(object)_next != (Object)null && !string.IsNullOrEmpty(_nextText)) ? ((TMP_Text)_next).preferredHeight : 0f); float num4 = 24f + num + num2 + num3 + ((num > 0f) ? 6f : 0f) + ((num3 > 0f) ? 6f : 0f); if (Mathf.Abs(_container.sizeDelta.y - num4) > 0.5f) { _container.sizeDelta = new Vector2(_container.sizeDelta.x, num4); } float num5 = num4 * 0.5f - 12f; if ((Object)(object)_title != (Object)null && num > 0f) { ((TMP_Text)_title).rectTransform.anchoredPosition = new Vector2(0f, num5); ((TMP_Text)_title).rectTransform.sizeDelta = new Vector2(-24f, num); num5 -= num + 6f; } if ((Object)(object)_current != (Object)null) { ((TMP_Text)_current).rectTransform.anchoredPosition = new Vector2(0f, num5); ((TMP_Text)_current).rectTransform.sizeDelta = new Vector2(-24f, num2); num5 -= num2 + 6f; } if ((Object)(object)_next != (Object)null && num3 > 0f) { ((TMP_Text)_next).rectTransform.anchoredPosition = new Vector2(0f, num5); ((TMP_Text)_next).rectTransform.sizeDelta = new Vector2(-24f, num3); } } } internal sealed class PlaybackState { public bool Active; public bool Playing; public string AudioPath = string.Empty; public string DisplayName = string.Empty; public double Time; public double Duration; public string Source = string.Empty; public bool SameTrack(PlaybackState other) { if (other == null) { return false; } if (Active != other.Active) { return false; } if (!Active) { return true; } return string.Equals(AudioPath, other.AudioPath, StringComparison.OrdinalIgnoreCase); } } internal static class PlaybackTracker { private const float ScanInterval = 0.25f; private static readonly Dictionary<int, string> ClipToPath = new Dictionary<int, string>(); private static readonly List<AudioSource> SourceBuffer = new List<AudioSource>(); private static ManualLogSource _log; private static PlaybackState _current = new PlaybackState(); private static bool _hasCurrent; private static float _nextScan; private static float _nextClipMap; private static int _clipMapAttempts; private static Type _audioFileType; private static Type _audioManagerType; private static MemberInfo _audioClipsMember; private static bool _memberNamesLogged; private static int _diagCount; private static PropertyInfo _audioFileClip; private static PropertyInfo _audioFileFilePath; private static Type _boomboxType; private static FieldInfo _boomboxAudioField; private static float _nextDiag; private static bool _externalActive; private static float _externalExpiry; private static PlaybackState _external = new PlaybackState(); public static PlaybackState Current => _current; public static void Initialize(ManualLogSource log) { _log = log; ClipToPath.Clear(); _current = new PlaybackState(); _hasCurrent = false; _externalActive = false; _nextScan = 0f; _nextClipMap = 0f; _clipMapAttempts = 0; RebuildClipMap(); } public static void Shutdown() { _current = new PlaybackState(); _hasCurrent = false; _externalActive = false; ClipToPath.Clear(); } public static void PushExternal(string audioPath, string displayName, double timeSeconds, double durationSeconds, float holdSeconds) { _external = new PlaybackState { Active = !string.IsNullOrEmpty(audioPath), AudioPath = (audioPath ?? string.Empty), DisplayName = (displayName ?? string.Empty), Time = timeSeconds, Duration = durationSeconds, Source = "external" }; _externalActive = _external.Active; _externalExpiry = Time.unscaledTime + Mathf.Max(0.5f, holdSeconds); if (_externalActive) { Commit(_external); } } public static void ClearExternal() { _externalActive = false; } public static void Tick(float deltaTime, bool autoDetect, float minTrackSeconds) { if (_externalActive && Time.unscaledTime <= _externalExpiry) { _external.Time += deltaTime; Commit(_external); return; } _externalActive = false; if (!autoDetect) { Release(); } else if (!(Time.unscaledTime < _nextScan)) { _nextScan = Time.unscaledTime + 0.25f; if (Time.unscaledTime >= _nextClipMap) { RebuildClipMap(); } Poll(minTrackSeconds); } } private static void Poll(float minTrackSeconds) { float minLength = Mathf.Max(3f, minTrackSeconds); AudioSource val = null; TrackEntry trackEntry = null; int num = -1; float num2 = 0f; AudioSource val2 = null; try { val2 = FindBoomboxSource(); } catch (Exception ex) { Diagnose("boombox lookup failed: " + ex.Message); } if (TryGetMusicClip(val2, minLength, out var clip)) { TrackEntry trackEntry2 = MatchEntry(clip); if (trackEntry2 != null) { Commit(BuildState(val2, trackEntry2)); Diagnose("boombox source: " + ((Object)clip).name + " -> " + trackEntry2.Name); return; } } SourceBuffer.Clear(); try { AudioSource[] array = Resources.FindObjectsOfTypeAll<AudioSource>(); if (array != null) { foreach (AudioSource val3 in array) { if ((Object)(object)val3 != (Object)null && (Object)(object)val3.clip != (Object)null) { SourceBuffer.Add(val3); } } } } catch (Exception ex2) { ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("[Lyriclib] AudioSource scan failed: " + ex2.Message)); } return; } for (int j = 0; j < SourceBuffer.Count; j++) { AudioSource val4 = SourceBuffer[j]; if (!TryGetMusicClip(val4, minLength, out var clip2)) { continue; } TrackEntry trackEntry3 = MatchEntry(clip2); if (trackEntry3 != null) { int num3 = 8; if (val4.isPlaying) { num3 += 4; } if (!val4.mute && val4.volume > 0.01f) { num3++; } if (num3 >= num && (num3 != num || !(clip2.length <= num2))) { val = val4; trackEntry = trackEntry3; num = num3; num2 = clip2.length; } } } if ((Object)(object)val == (Object)null || trackEntry == null) { Release(); Diagnose("no lyrical source among " + SourceBuffer.Count + " audio source(s), boombox=" + (((Object)(object)val2 == (Object)null) ? "none" : (((Object)(object)val2.clip == (Object)null) ? "no clip" : ((Object)val2.clip).name))); } else { Commit(BuildState(val, trackEntry)); Diagnose("scan source: " + ((Object)val.clip).name + " -> " + trackEntry.Name); } } private static bool TryGetMusicClip(AudioSource source, float minLength, out AudioClip clip) { clip = (((Object)(object)source != (Object)null) ? source.clip : null); if ((Object)(object)clip != (Object)null) { return clip.length >= minLength; } return false; } private static TrackEntry MatchEntry(AudioClip clip) { if ((Object)(object)clip == (Object)null) { return null; } string text = ResolveClipPath(clip); TrackEntry trackEntry = null; if (!string.IsNullOrEmpty(text)) { trackEntry = TrackCatalog.FindByAudioPath(text); } if (trackEntry == null && !string.IsNullOrEmpty(((Object)clip).name)) { trackEntry = TrackCatalog.FindByName(((Object)clip).name); } if (trackEntry == null && !string.IsNullOrEmpty(text)) { trackEntry = TrackCatalog.FindByName(Path.GetFileNameWithoutExtension(text)); } if (trackEntry == null || !trackEntry.HasLyric) { return null; } return trackEntry; } private static PlaybackState BuildState(AudioSource source, TrackEntry entry) { return new PlaybackState { Active = true, Playing = ((Object)(object)source != (Object)null && source.isPlaying), AudioPath = entry.AudioPath, DisplayName = entry.Name, Time = (((Object)(object)source != (Object)null) ? source.time : 0f), Duration = (((Object)(object)source != (Object)null && (Object)(object)source.clip != (Object)null) ? source.clip.length : 0f), Source = "boombox" }; } private static AudioSource FindBoomboxSource() { if (_boomboxType == null) { _boomboxType = FindType("BoomboxItem", null); if (_boomboxType == null) { return null; } string[] array = new string[4] { "musicAudioSource", "boomboxAudio", "audioSource", "musicSource" }; for (int i = 0; i < array.Length; i++) { if (!(_boomboxAudioField == null)) { break; } _boomboxAudioField = _boomboxType.GetField(array[i], BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } } if (_boomboxAudioField == null) { return null; } Object[] array2 = Resources.FindObjectsOfTypeAll(_boomboxType); if (array2 == null || array2.Length == 0) { return null; } AudioSource val = null; for (int j = 0; j < array2.Length; j++) { if (array2[j] == (Object)null) { continue; } object? value = _boomboxAudioField.GetValue(array2[j]); AudioSource val2 = (AudioSource)((value is AudioSource) ? value : null); if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.clip == (Object)null)) { if (val2.isPlaying) { return val2; } if ((Object)(object)val == (Object)null) { val = val2; } } } return val; } private static void Diagnose(string message) { if (Time.unscaledTime < _nextDiag) { return; } _nextDiag = Time.unscaledTime + 3f; if (_diagCount < 30) { _diagCount++; ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("[Lyriclib] detect: " + message)); } } } private static void Commit(PlaybackState state) { bool num = !_hasCurrent || !_current.SameTrack(state); _current = state; _hasCurrent = true; if (num) { LyriclibLyrics.OnTrackChanged(_current); } } private static void Release() { if (_current.Active) { _current = new PlaybackState(); _hasCurrent = true; LyriclibLyrics.OnTrackStopped(); } } private static string ResolveClipPath(AudioClip clip) { if ((Object)(object)clip == (Object)null) { return null; } if (ClipToPath.TryGetValue(((Object)clip).GetInstanceID(), out var value)) { return value; } string name = ((Object)clip).name; if (string.IsNullOrEmpty(name)) { return null; } if (name.StartsWith("file://", StringComparison.OrdinalIgnoreCase) || name.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || name.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { try { string localPath = new Uri(name).LocalPath; if (!string.IsNullOrEmpty(localPath)) { return localPath; } } catch { } } if (name.Length > 3 && name[1] == ':') { return name; } return null; } private static object ReadMember(MemberInfo member, object target) { if (member == null) { return null; } try { PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) { return propertyInfo.GetValue(target, null); } FieldInfo fieldInfo = member as FieldInfo; if (fieldInfo != null) { return fieldInfo.GetValue(target); } } catch { } return null; } private static object EntryValue(object entry, string name) { if (entry == null) { return null; } Type type = entry.GetType(); PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { try { return property.GetValue(entry, null); } catch { } } FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { try { return field.GetValue(entry); } catch { } } return null; } private static MemberInfo FindClipsMember(Type managerType, BindingFlags flags) { if (managerType == null) { return null; } List<MemberInfo> list = new List<MemberInfo>(); list.AddRange(managerType.GetProperties(flags)); list.AddRange(managerType.GetFields(flags)); MemberInfo memberInfo = null; MemberInfo memberInfo2 = null; for (int i = 0; i < list.Count; i++) { MemberInfo memberInfo3 = list[i]; PropertyInfo propertyInfo = memberInfo3 as PropertyInfo; Type type; if (propertyInfo != null) { if (propertyInfo.GetIndexParameters().Length != 0) { continue; } type = propertyInfo.PropertyType; } else { type = ((FieldInfo)memberInfo3).FieldType; } if (type == null || type == typeof(string) || !typeof(IEnumerable).IsAssignableFrom(type)) { continue; } Type type2 = ElementTypeOf(type); if (!(type2 == null)) { if (HasAudioClipMember(type2)) { memberInfo = memberInfo3; break; } if (memberInfo2 == null && type2.Name == "AudioFile") { memberInfo2 = memberInfo3; } } } return memberInfo ?? memberInfo2; } private static Type ElementTypeOf(Type collectionType) { if (collectionType.IsArray) { return collectionType.GetElementType(); } if (collectionType.IsGenericType) { return collectionType.GetGenericArguments()[0]; } return null; } private static bool HasAudioClipMember(Type type) { if (!(type.GetProperty("AudioClip", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null)) { return type.GetField("AudioClip", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null; } return true; } private static void DiagMemberNames(Type managerType, BindingFlags flags) { if (_memberNamesLogged || managerType == null) { return; } _memberNamesLogged = true; try { StringBuilder stringBuilder = new StringBuilder(); PropertyInfo[] properties = managerType.GetProperties(flags); for (int i = 0; i < properties.Length && i < 24; i++) { stringBuilder.Append(properties[i].Name).Append(' '); } FieldInfo[] fields = managerType.GetFields(flags); for (int j = 0; j < fields.Length && j < 24; j++) { stringBuilder.Append(fields[j].Name).Append(' '); } ManualLogSource log = _log; if (log != null) { log.LogInfo((object)("[Lyriclib] " + managerType.Name + " members: " + stringBuilder.ToString().Trim() + " | clips member: " + ((_audioClipsMember != null) ? _audioClipsMember.Name : "<none>"))); } } catch (Exception ex) { ManualLogSource log2 = _log; if (log2 != null) { log2.LogInfo((object)("[Lyriclib] member dump failed: " + ex.Message)); } } } private static void RebuildClipMap() { _nextClipMap = Time.unscaledTime + ((_clipMapAttempts < 3) ? 2f : 30f); if (_audioManagerType == null) { _audioManagerType = FindType("AudioManager", "CustomBoomboxMusic") ?? FindType("AudioManager", null); if (_audioManagerType == null) { Diagnose("CustomBoomboxMusic AudioManager type not found"); return; } _audioClipsMember = FindClipsMember(_audioManagerType, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (_audioClipsMember == null) { _audioClipsMember = FindClipsMember(_audioManagerType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } DiagMemberNames(_audioManagerType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } if (_audioClipsMember == null) { Diagnose("no clip collection member found on " + _audioManagerType.Name); return; } try { List<object> list = new List<object>(); object obj = ReadMember(_audioClipsMember, null); if (obj != null) { list.Add(obj); } if (list.Count == 0 && typeof(Object).IsAssignableFrom(_audioManagerType)) { Object[] array = Resources.FindObjectsOfTypeAll(_audioManagerType); if (array != null) { for (int i = 0; i < array.Length; i++) { if (!(array[i] == (Object)null)) { object obj2 = ReadMember(_audioClipsMember, array[i]); if (obj2 != null) { list.Add(obj2); } } } } } if (list.Count == 0) { Diagnose("no playlist reachable on " + _audioManagerType.Name + "." + _audioClipsMember.Name); return; } int num = 0; for (int j = 0; j < list.Count; j++) { if (!(list[j] is IEnumerable enumerable)) { continue; } foreach (object item in enumerable) { if (item == null) { continue; } if (_audioFileType == null) { _audioFileType = item.GetType(); _audioFileClip = _audioFileType.GetProperty("AudioClip", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _audioFileFilePath = _audioFileType.GetProperty("FilePath", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); ManualLogSource log = _log; if (log != null) { log.LogInfo((object)("[Lyriclib] playlist entry type " + _audioFileType.Name + ": AudioClip=" + ((_audioFileClip != null) ? "ok" : "<missing>") + ", FilePath=" + ((_audioFileFilePath != null) ? "ok" : "<missing>"))); } } object obj3 = EntryValue(item, "AudioClip"); AudioClip val = (AudioClip)((obj3 is AudioClip) ? obj3 : null); string value = EntryValue(item, "FilePath") as string; if (!((Object)(object)val == (Object)null) && !string.IsNullOrEmpty(value)) { int instanceID = ((Object)val).GetInstanceID(); if (!ClipToPath.ContainsKey(instanceID)) { ClipToPath[instanceID] = value; num++; } } } } if (num > 0) { _clipMapAttempts = 99; ManualLogSource log2 = _log; if (log2 != null) { log2.LogInfo((object)("[Lyriclib] mapped " + num + " CustomBoomboxMusic clip(s) to their files (total " + ClipToPath.Count + ")")); } } else if (_clipMapAttempts < 3) { _clipMapAttempts++; } } catch (Exception ex) { ManualLogSource log3 = _log; if (log3 != null) { log3.LogDebug((object)("[Lyriclib] clip map rebuild failed: " + ex.Message)); } } } private static Type FindType(string name, string namespaceHint) { try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type[] types; try { types = assemblies[i].GetTypes(); } catch { continue; } for (int j = 0; j < types.Length; j++) { if (!(types[j].Name != name) && (namespaceHint == null || !(types[j].Namespace != namespaceHint))) { return types[j]; } } } } catch (Exception ex) { ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("[Lyriclib] type lookup for '" + name + "' failed: " + ex.Message)); } } return null; } } public sealed class TrackEntry { public string AudioPath; public string LyricPath; public string Name; public string Key; public bool HasLyric => !string.IsNullOrEmpty(LyricPath); } public static class TrackCatalog { private sealed class ScanResult { public Dictionary<string, TrackEntry> ByKey; public Dictionary<string, TrackEntry> ByPath; public Dictionary<string, LyricDocument> Docs; public Dictionary<string, long> DocTicks; public Dictionary<string, long> RootStamps; } private static readonly string[] AudioExtensions = new string[8] { ".ogg", ".mp3", ".wav", ".flac", ".m4a", ".aiff", ".aif", ".opus" }; private static readonly string[] LyricExtensions = new string[2] { ".lrc", ".txt" }; private static Dictionary<string, TrackEntry> ByKey = new Dictionary<string, TrackEntry>(StringComparer.Ordinal); private static Dictionary<string, TrackEntry> ByPath = new Dictionary<string, TrackEntry>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, LyricDocument> DocCache = new Dictionary<string, LyricDocument>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, long> DocCacheTicks = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, string> ResolvedCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, long> RootStamps = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase); private static ManualLogSource _log; private static DateTime _lastScan = DateTime.MinValue; private static readonly TimeSpan ScanInterval = TimeSpan.FromSeconds(45.0); private static readonly object ScanLock = new object(); private static ScanResult _pending; private static volatile bool _scanRunning; public static int Count => ByKey.Count; public static int LyricCount => ByKey.Values.Count((TrackEntry v) => v.HasLyric); public static bool ScanRunning => _scanRunning; public static void Initialize(ManualLogSource log) { _log = log; } public static void Refresh(IEnumerable<string> roots, string sharedLyricDir, bool force = false) { if ((!force && DateTime.UtcNow - _lastScan < ScanInterval) || _scanRunning) { return; } _lastScan = DateTime.UtcNow; List<string> rootList = CollectRoots(roots, logMissing: true); if (!force && rootList.Count > 0 && StampsUnchanged(rootList)) { ManualLogSource log = _log; if (log != null) { log.LogDebug((object)"[Lyriclib] catalog unchanged, rescan skipped"); } return; } string shared = sharedLyricDir; _scanRunning = true; Thread thread = new Thread((ThreadStart)delegate { try { RunScan(rootList, shared); } catch (Exception ex2) { ManualLogSource log3 = _log; if (log3 != null) { log3.LogWarning((object)("[Lyriclib] background scan failed: " + ex2.Message)); } } finally { _scanRunning = false; } }); thread.IsBackground = true; thread.Name = "Lyriclib.CatalogScan"; try { thread.Start(); } catch (Exception ex) { _scanRunning = false; ManualLogSource log2 = _log; if (log2 != null) { log2.LogWarning((object)("[Lyriclib] could not start background scan: " + ex.Message)); } } } private static bool StampsUnchanged(List<string> rootList) { if (RootStamps.Count != rootList.Count) { return false; } for (int i = 0; i < rootList.Count; i++) { if (!RootStamps.TryGetValue(rootList[i], out var value)) { return false; } if (DirectoryStamp(rootList[i]) != value) { return false; } } return true; } private static long DirectoryStamp(string dir) { try { return Directory.GetLastWriteTimeUtc(dir).Ticks; } catch { return -1L; } } private static void RunScan(List<string> rootList, string sharedLyricDir) { ScanResult scanResult = new ScanResult { ByKey = new Dictionary<string, TrackEntry>(StringComparer.Ordinal), ByPath = new Dictionary<string, TrackEntry>(StringComparer.OrdinalIgnoreCase), Docs = new Dictionary<string, LyricDocument>(StringComparer.OrdinalIgnoreCase), DocTicks = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase), RootStamps = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase) }; for (int i = 0; i < rootList.Count; i++) { string text = rootList[i]; scanResult.RootStamps[text] = DirectoryStamp(text); ScanRoot(text, sharedLyricDir, scanResult); } PrewarmDocuments(scanResult); lock (ScanLock) { _pending = scanResult; } ManualLogSource log = _log; if (log != null) { log.LogInfo((object)($"[Lyriclib] catalog scan finished: {scanResult.ByKey.Count} track(s), " + $"{scanResult.Docs.Count} lyric document(s) prewarmed")); } } private static void PrewarmDocuments(ScanResult result) { foreach (KeyValuePair<string, TrackEntry> item in result.ByPath) { string lyricPath = item.Value.LyricPath; if (string.IsNullOrEmpty(lyricPath) || result.Docs.ContainsKey(lyricPath)) { continue; } if (TryGetCachedDocument(lyricPath, SafeTicks(lyricPath), out var doc, out var docTicks)) { result.Docs[lyricPath] = doc; result.DocTicks[lyricPath] = docTicks; continue; } try { LyricDocument lyricDocument = LrcParser.ParseFile(lyricPath); if (lyricDocument != null) { result.Docs[lyricPath] = lyricDocument; result.DocTicks[lyricPath] = SafeTicks(lyricPath); } } catch (Exception ex) { ManualLogSource log = _log; if (log != null) { log.LogDebug((object)("[Lyriclib] prewarm failed for " + lyricPath + ": " + ex.Message)); } } } } private static long SafeTicks(string path) { try { return File.GetLastWriteTimeUtc(path).Ticks; } catch { return 0L; } } public static void ApplyPending() { ScanResult pending; lock (ScanLock) { pending = _pending; _pending = null; } if (pending == null) { return; } ByKey = pending.ByKey; ByPath = pending.ByPath; RootStamps.Clear(); foreach (KeyValuePair<string, long> rootStamp in pending.RootStamps) { RootStamps[rootStamp.Key] = rootStamp.Value;