using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CybergrindSRT")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+ad233f350296833e9b548882c7ffa90cf08ff5ea")]
[assembly: AssemblyProduct("CybergrindSRT")]
[assembly: AssemblyTitle("CybergrindSRT")]
[assembly: AssemblyVersion("1.0.0.0")]
[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 CybergrindSRT
{
[BepInPlugin("circuitella.cybergrindsrt", "Cybergrind SRTs", "0.2.7")]
public sealed class CybergrindSRTPlugin : BaseUnityPlugin
{
private sealed class SrtEntry
{
public float Start;
public float End;
public string Text;
}
private const float PlaybackScanInterval = 0.1f;
private const float IdleDiscoveryInterval = 2.5f;
private static readonly Regex TimestampLine = new Regex("^\\s*(\\d{1,2}):(\\d{2}):(\\d{2})[,.](\\d{1,3})\\s*-->\\s*(\\d{1,2}):(\\d{2}):(\\d{2})[,.](\\d{1,3})(?:\\s+.*)?\\s*$", RegexOptions.Compiled);
private static readonly Regex CueNumberLine = new Regex("^\\s*\\d+\\s*$", RegexOptions.Compiled);
private Type playerType;
private Type controllerType;
private float nextScan;
private string loadedAudioPath;
private List<SrtEntry> entries = new List<SrtEntry>();
private int activeEntry = -1;
private bool playbackWasActive;
private bool loadedSrtFile;
private int clockSourceId;
private int previousTimeSamples;
private double previousDspTime;
private double estimatedSampleRate;
private Harmony playbackHarmony;
private static CybergrindSRTPlugin instance;
private object actualPlaybackPlayer;
private int actualPlaybackSourceId;
private string actualPlaybackPath;
private bool playbackHookAttempted;
private bool subtitlesEnabled = true;
private bool clearOnTrackChange = true;
private bool configInitialized;
private bool configDiscoveryStopped;
private float nextConfigDiscovery;
private object configStatusField;
private object configFilenameField;
private string displayedStatus;
private string displayedFilename;
private string loadStatus = "N/A (Not Playing)";
private void Awake()
{
instance = this;
playerType = FindType("CustomMusicPlayer");
controllerType = FindType("SubtitleController");
InstallPlaybackHook();
TryInitializeConfigurator();
}
private void Update()
{
if (!configInitialized && !configDiscoveryStopped && Time.unscaledTime >= nextConfigDiscovery)
{
TryInitializeConfigurator();
}
if (!(Time.unscaledTime < nextScan))
{
Tick();
nextScan = Time.unscaledTime + (playbackWasActive ? 0.1f : 2.5f);
}
}
private void InstallPlaybackHook()
{
//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
//IL_00b7: Expected O, but got Unknown
//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
//IL_00cd: Expected O, but got Unknown
if (playerType == null || playbackHarmony != null || playbackHookAttempted)
{
return;
}
playbackHookAttempted = true;
Type type = null;
Type[] nestedTypes = playerType.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic);
for (int i = 0; i < nestedTypes.Length; i++)
{
if (nestedTypes[i].Name == "<PlaylistRoutine>d__15")
{
type = nestedTypes[i];
break;
}
}
if (type == null)
{
return;
}
MethodInfo method = type.GetMethod("MoveNext", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
MethodInfo method2 = typeof(CybergrindSRTPlugin).GetMethod("PlaylistMoveNextPostfix", BindingFlags.Static | BindingFlags.NonPublic);
if (method == null || method2 == null)
{
return;
}
try
{
playbackHarmony = new Harmony("circuitella.cybergrindsrt.playback");
playbackHarmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
catch
{
}
}
private static void PlaylistMoveNextPostfix(object __instance, bool __result)
{
if ((Object)(object)instance != (Object)null)
{
instance.CaptureActualPlayback(__instance, __result);
}
}
private void CaptureActualPlayback(object stateMachine, bool yielded)
{
if (!yielded || stateMachine == null)
{
return;
}
object obj = ReadMember(stateMachine, "<>1__state");
if (obj == null)
{
return;
}
int num;
try
{
num = Convert.ToInt32(obj, CultureInfo.InvariantCulture);
}
catch
{
return;
}
if (num != 2 && num != 4 && num != 5)
{
return;
}
object obj3 = ReadMember(stateMachine, "<>4__this");
object obj4 = ReadMember(obj3, "source");
AudioSource val = (AudioSource)((obj4 is AudioSource) ? obj4 : null);
if (!((Object)(object)val == (Object)null) && IsCybergrindMusicSource(val))
{
string text = NormalizeAudioPath(Convert.ToString(ReadMember(ReadMember(stateMachine, "<id>5__8"), "path"), CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(text) && File.Exists(text) && val.isPlaying)
{
actualPlaybackPlayer = obj3;
actualPlaybackSourceId = ((Object)val).GetInstanceID();
actualPlaybackPath = text;
playbackWasActive = true;
nextScan = 0f;
}
}
}
private void Tick()
{
if (playerType == null)
{
playerType = FindType("CustomMusicPlayer");
}
if (controllerType == null)
{
controllerType = FindType("SubtitleController");
}
if (playerType == null)
{
return;
}
if (playbackHarmony == null && !playbackHookAttempted)
{
InstallPlaybackHook();
}
Object[] array;
try
{
array = Resources.FindObjectsOfTypeAll(playerType);
}
catch
{
return;
}
AudioSource val = null;
string text = null;
foreach (object obj2 in array)
{
if (obj2 != null && obj2 == actualPlaybackPlayer)
{
object obj3 = ReadMember(obj2, "source");
AudioSource val2 = (AudioSource)((obj3 is AudioSource) ? obj3 : null);
if (!((Object)(object)val2 == (Object)null) && val2.isPlaying && ((Object)val2).GetInstanceID() == actualPlaybackSourceId)
{
val = val2;
text = actualPlaybackPath;
break;
}
}
}
if ((Object)(object)val == (Object)null || string.IsNullOrEmpty(text))
{
if (playbackWasActive)
{
ClearNativeSubtitle();
activeEntry = -1;
}
playbackWasActive = false;
UpdateConfigStatus("Not playing", "—");
return;
}
playbackWasActive = true;
if (!string.Equals(text, loadedAudioPath, StringComparison.OrdinalIgnoreCase) || (!loadedSrtFile && File.Exists(Path.ChangeExtension(text, ".srt"))))
{
LoadTrack(text, clearOnTrackChange);
}
string fileName = Path.GetFileName(Path.ChangeExtension(text, ".srt"));
string text2 = loadStatus;
if (!subtitlesEnabled)
{
text2 += " (subtitles disabled)";
}
UpdateConfigStatus(text2, fileName);
if (!subtitlesEnabled || entries.Count == 0)
{
return;
}
float playbackTime = GetPlaybackTime(val);
int num = FindEntry(playbackTime);
if (num != activeEntry)
{
activeEntry = num;
if (num < 0)
{
ClearNativeSubtitle();
}
else
{
DisplayNativeSubtitle(entries[num].Text, val);
}
}
}
private void TryInitializeConfigurator()
{
nextConfigDiscovery = Time.unscaledTime + 2.5f;
if (configInitialized || configDiscoveryStopped)
{
return;
}
Type type = FindPluginConfigType("PluginConfig.API.PluginConfigurator");
if (type == null)
{
return;
}
try
{
MethodInfo method = type.GetMethod("Create", BindingFlags.Static | BindingFlags.Public, null, new Type[2]
{
typeof(string),
typeof(string)
}, null);
if (method == null)
{
configDiscoveryStopped = true;
return;
}
object obj = method.Invoke(null, new object[2] { "Cybergrind Subtitles", "circuitella.cybergrindsrt" });
if (obj == null)
{
return;
}
configDiscoveryStopped = true;
string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty, "icon.png");
if (File.Exists(text))
{
MethodInfo method2 = type.GetMethod("SetIconWithURL", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(string) }, null);
if (method2 != null)
{
method2.Invoke(obj, new object[1] { text });
}
}
object obj2 = ReadMember(obj, "rootPanel");
if (obj2 != null)
{
CreateConfigHeader(obj2, "GENERAL");
object obj3 = CreateConfigField("BoolField", obj2, "Enable Subtitles", "enable_subtitles", true);
object obj4 = CreateConfigField("BoolField", obj2, "Clear Subtitles When Track Changes", "clear_on_track_change", true);
if (obj3 != null && obj4 != null)
{
AttachValueCallback(obj3, "OnSubtitlesEnabledChanged");
AttachValueCallback(obj4, "OnClearOnTrackChangeChanged");
subtitlesEnabled = Convert.ToBoolean(ReadMember(obj3, "value"), CultureInfo.InvariantCulture);
clearOnTrackChange = Convert.ToBoolean(ReadMember(obj4, "value"), CultureInfo.InvariantCulture);
CreateConfigHeader(obj2, "CURRENT TRACK");
configStatusField = CreateConfigField("StringField", obj2, "SRT Status", "srt_status", "Not playing");
configFilenameField = CreateConfigField("StringField", obj2, "Detected SRT Filename", "detected_srt_filename", "—");
SetMember(configStatusField, "interactable", false);
SetMember(configFilenameField, "interactable", false);
UpdateConfigStatus("Not playing", "—");
configInitialized = true;
}
}
}
catch
{
}
}
private object CreateConfigField(string typeName, object parent, params object[] arguments)
{
Type type = FindPluginConfigType("PluginConfig.API.Fields." + typeName);
if (type == null || parent == null)
{
return null;
}
object[] array = new object[arguments.Length + 1];
array[0] = parent;
Array.Copy(arguments, 0, array, 1, arguments.Length);
try
{
return Activator.CreateInstance(type, array);
}
catch
{
return null;
}
}
private void CreateConfigHeader(object parent, string title)
{
Type type = FindPluginConfigType("PluginConfig.API.Decorators.ConfigHeader");
if (type == null)
{
return;
}
try
{
Activator.CreateInstance(type, parent, title, 22);
}
catch
{
}
}
private void AttachValueCallback(object field, string methodName)
{
MethodInfo method = ((object)this).GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
if (!(method == null))
{
AttachDelegate(field, "postValueChangeEvent", method, readBooleanValue: true);
}
}
private void AttachDelegate(object target, string memberName, MethodInfo callback, bool readBooleanValue)
{
Type type = target.GetType();
EventInfo eventInfo = type.GetEvent(memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
FieldInfo field = type.GetField(memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Type type2 = ((eventInfo != null) ? eventInfo.EventHandlerType : ((field != null) ? field.FieldType : null));
if (type2 == null)
{
return;
}
Delegate obj;
if (!readBooleanValue)
{
obj = Delegate.CreateDelegate(type2, this, callback, throwOnBindFailure: false);
}
else
{
ParameterInfo[] parameters = type2.GetMethod("Invoke").GetParameters();
if (parameters.Length != 1)
{
return;
}
ParameterExpression parameterExpression = Expression.Parameter(parameters[0].ParameterType, "args");
Expression expression;
if (parameterExpression.Type == typeof(bool))
{
expression = parameterExpression;
}
else
{
MemberInfo memberInfo = (MemberInfo)(((object)parameterExpression.Type.GetProperty("value", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) ?? ((object)parameterExpression.Type.GetField("value", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)));
if (memberInfo == null)
{
return;
}
expression = ((memberInfo is PropertyInfo property) ? Expression.Property(parameterExpression, property) : Expression.Field(parameterExpression, (FieldInfo)memberInfo));
}
MethodCallExpression body = Expression.Call(Expression.Constant(this), callback, Expression.Convert(expression, typeof(bool)));
obj = Expression.Lambda(type2, body, parameterExpression).Compile();
}
if ((object)obj != null)
{
if (eventInfo != null)
{
eventInfo.AddEventHandler(target, obj);
}
else if (field != null)
{
field.SetValue(target, Delegate.Combine(field.GetValue(target) as Delegate, obj));
}
}
}
private void OnSubtitlesEnabledChanged(bool enabled)
{
subtitlesEnabled = enabled;
activeEntry = -1;
if (!enabled)
{
ClearNativeSubtitle();
}
}
private void OnClearOnTrackChangeChanged(bool enabled)
{
clearOnTrackChange = enabled;
}
private void UpdateConfigStatus(string status, string filename)
{
if (!string.Equals(displayedStatus, status, StringComparison.Ordinal) || !string.Equals(displayedFilename, filename, StringComparison.Ordinal))
{
displayedStatus = status;
displayedFilename = filename;
SetMember(configStatusField, "value", status);
SetMember(configFilenameField, "value", filename);
}
}
private static void SetMember(object target, string name, object value)
{
if (target == null)
{
return;
}
Type type = target.GetType();
PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (property != null && property.CanWrite)
{
try
{
property.SetValue(target, value, null);
return;
}
catch
{
return;
}
}
FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (!(field != null))
{
return;
}
try
{
field.SetValue(target, value);
}
catch
{
}
}
private static string NormalizeAudioPath(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return null;
}
path = path.Trim().Trim('"');
try
{
if (!Path.IsPathRooted(path))
{
return null;
}
return Path.GetFullPath(path);
}
catch
{
return path;
}
}
private static bool IsCybergrindMusicSource(AudioSource source)
{
if ((Object)(object)source == (Object)null)
{
return false;
}
Transform val = ((Component)source).transform;
while ((Object)(object)val != (Object)null)
{
if ((((Object)val).name ?? string.Empty).IndexOf("MusicChanger", StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
val = val.parent;
}
return false;
}
private void LoadTrack(string audioPath, bool clearSubtitle)
{
if (clearSubtitle)
{
ClearNativeSubtitle();
}
audioPath = NormalizeAudioPath(audioPath);
if (string.IsNullOrEmpty(audioPath))
{
return;
}
loadedAudioPath = audioPath;
loadedSrtFile = false;
activeEntry = -1;
clockSourceId = 0;
previousTimeSamples = 0;
previousDspTime = 0.0;
estimatedSampleRate = 0.0;
entries.Clear();
string path = Path.ChangeExtension(audioPath, ".srt");
if (!File.Exists(path))
{
loadStatus = "Not found";
return;
}
try
{
entries = ParseSrt(File.ReadAllText(path, Encoding.UTF8));
loadedSrtFile = true;
loadStatus = ((entries.Count > 0) ? ("Loaded (" + entries.Count.ToString(CultureInfo.InvariantCulture) + " cues)") : "No valid cues");
}
catch
{
entries.Clear();
loadedSrtFile = true;
loadStatus = "Could not read SRT";
}
}
private static List<SrtEntry> ParseSrt(string content)
{
List<SrtEntry> list = new List<SrtEntry>();
string[] array = content.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n');
int i = 0;
while (i < array.Length)
{
for (; i < array.Length && string.IsNullOrWhiteSpace(array[i]); i++)
{
}
if (i >= array.Length)
{
break;
}
string input = array[i].Trim().TrimStart('\ufeff');
if (CueNumberLine.IsMatch(input))
{
for (i++; i < array.Length && string.IsNullOrWhiteSpace(array[i]); i++)
{
}
if (i >= array.Length)
{
break;
}
input = array[i].Trim();
}
Match match = TimestampLine.Match(input);
if (!match.Success)
{
i++;
continue;
}
float num = ParseTimestamp(match, 1);
float num2 = ParseTimestamp(match, 5);
i++;
StringBuilder stringBuilder = new StringBuilder();
for (; i < array.Length; i++)
{
string text = array[i].Trim();
if (string.IsNullOrWhiteSpace(text))
{
i++;
break;
}
if (TimestampLine.IsMatch(text) || CueNumberLine.IsMatch(text))
{
break;
}
if (!TimestampLine.IsMatch(text))
{
if (stringBuilder.Length > 0)
{
stringBuilder.Append('\n');
}
stringBuilder.Append(array[i].Trim());
}
}
string text2 = stringBuilder.ToString().Trim();
if (num2 > num && text2.Length > 0)
{
list.Add(new SrtEntry
{
Start = num,
End = num2,
Text = text2
});
}
}
list.Sort((SrtEntry a, SrtEntry b) => a.Start.CompareTo(b.Start));
return list;
}
private static float ParseTimestamp(Match match, int offset)
{
int num = int.Parse(match.Groups[offset].Value, CultureInfo.InvariantCulture);
int num2 = int.Parse(match.Groups[offset + 1].Value, CultureInfo.InvariantCulture);
int num3 = int.Parse(match.Groups[offset + 2].Value, CultureInfo.InvariantCulture);
int num4 = int.Parse(match.Groups[offset + 3].Value.PadRight(3, '0').Substring(0, 3), CultureInfo.InvariantCulture);
return (float)num * 3600f + (float)num2 * 60f + (float)num3 + (float)num4 / 1000f;
}
private float GetPlaybackTime(AudioSource source)
{
if ((Object)(object)source == (Object)null)
{
return 0f;
}
int instanceID = ((Object)source).GetInstanceID();
if (clockSourceId != instanceID)
{
clockSourceId = instanceID;
previousTimeSamples = 0;
previousDspTime = 0.0;
estimatedSampleRate = 0.0;
}
float time = source.time;
int num = 0;
try
{
num = source.timeSamples;
}
catch
{
num = 0;
}
if ((Object)(object)source.clip != (Object)null && source.clip.frequency > 0 && num >= 0)
{
return (float)num / (float)source.clip.frequency;
}
double dspTime = AudioSettings.dspTime;
if (num > 0 && previousTimeSamples > 0 && dspTime > previousDspTime)
{
int num2 = num - previousTimeSamples;
double num3 = dspTime - previousDspTime;
if (num2 > 0 && num3 >= 0.2 && num3 <= 2.0)
{
double num4 = (double)num2 / num3;
if (num4 >= 8000.0 && num4 <= 192000.0)
{
estimatedSampleRate = ((estimatedSampleRate <= 0.0) ? num4 : (estimatedSampleRate * 0.75 + num4 * 0.25));
}
}
}
previousTimeSamples = num;
previousDspTime = dspTime;
if (num > 0 && estimatedSampleRate > 0.0)
{
return (float)((double)num / estimatedSampleRate);
}
return time;
}
private int FindEntry(float time)
{
for (int i = 0; i < entries.Count; i++)
{
if (time >= entries[i].Start && time < entries[i].End)
{
return i;
}
}
return -1;
}
private object GetController()
{
if (controllerType == null)
{
return null;
}
Type type = FindType("MonoSingleton`1");
if (type == null || !type.IsGenericTypeDefinition)
{
return null;
}
try
{
PropertyInfo property = type.MakeGenericType(controllerType).GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (property != null)
{
object value = property.GetValue(null, null);
if (value != null)
{
return value;
}
}
}
catch
{
}
return null;
}
private void DisplayNativeSubtitle(string text, AudioSource source)
{
object controller = GetController();
if (controller == null)
{
return;
}
MethodInfo[] methods = controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (MethodInfo methodInfo in methods)
{
if (methodInfo.Name != "DisplaySubtitle")
{
continue;
}
ParameterInfo[] parameters = methodInfo.GetParameters();
if (parameters.Length == 3 && !(parameters[0].ParameterType != typeof(string)) && !(parameters[2].ParameterType != typeof(bool)))
{
object obj = (parameters[1].ParameterType.IsInstanceOfType(source) ? source : null);
try
{
methodInfo.Invoke(controller, new object[3] { text, obj, false });
break;
}
catch
{
break;
}
}
}
}
private void ClearNativeSubtitle()
{
object controller = GetController();
if (controller == null)
{
return;
}
MethodInfo method = controllerType.GetMethod("CancelSubtitle", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
if (!(method != null))
{
return;
}
try
{
method.Invoke(controller, null);
}
catch
{
}
}
private static Type FindPluginConfigType(string fullName)
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int i = 0; i < assemblies.Length; i++)
{
Type type = assemblies[i].GetType(fullName, throwOnError: false);
if (type != null)
{
return type;
}
}
return null;
}
private static Type FindType(string name)
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int i = 0; i < assemblies.Length; i++)
{
Type type = assemblies[i].GetType(name, throwOnError: false);
if (type != null)
{
return type;
}
try
{
Type[] types = assemblies[i].GetTypes();
for (int j = 0; j < types.Length; j++)
{
if (types[j].Name == name)
{
return types[j];
}
}
}
catch (ReflectionTypeLoadException ex)
{
Type[] types2 = ex.Types;
for (int k = 0; k < types2.Length; k++)
{
if (types2[k] != null && types2[k].Name == name)
{
return types2[k];
}
}
}
catch
{
}
}
return null;
}
private static object ReadMember(object instance, string name)
{
if (instance == null)
{
return null;
}
Type type = instance.GetType();
while (type != null)
{
FieldInfo field = type.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (field != null)
{
try
{
return field.GetValue(instance);
}
catch
{
}
}
PropertyInfo property = type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (property != null && property.GetIndexParameters().Length == 0)
{
try
{
return property.GetValue(instance, null);
}
catch
{
}
}
type = type.BaseType;
}
return null;
}
}
}