Decompiled source of In Falsus ChartAudioFix v0.5.2

BepInEx/plugins/InFalsusChartAudio/InFalsusChartAudio.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using Iced.Intel;
using Il2CppInterop.Runtime.Runtime;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: SecurityPermission((SecurityAction)8, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : System.Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(/*Could not decode attribute arguments.*/)]
	internal sealed class NullableAttribute : System.Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(/*Could not decode attribute arguments.*/)]
	internal sealed class NullableContextAttribute : System.Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(/*Could not decode attribute arguments.*/)]
	internal sealed class RefSafetyRulesAttribute : System.Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace InFalsusChartAudio
{
	public static class AudioSourceState
	{
		public static bool IsReady(int result, int state)
		{
			if (result == 0)
			{
				if (state != 0)
				{
					return state == 6;
				}
				return true;
			}
			return false;
		}
	}
	public enum AudioRoute
	{
		Attack,
		Hold,
		MouseHold,
		MouseTransition,
		KeyboardHoldHit,
		SideKeyHit
	}
	public struct AudioCue
	{
		public long Id;

		public double TimeMs;

		public double EndMs;

		public AudioRoute Route;

		public bool Loop;
	}
	public sealed class AudioTimeline
	{
		public readonly List<AudioCue> Events = new List<AudioCue>();

		private int position;

		private double previous = 0.0 / 0.0;

		private bool armed;

		private bool skipCurrent;

		public int Position => position;

		public void Sort()
		{
			Events.Sort((Comparison<AudioCue>)delegate(AudioCue a, AudioCue b)
			{
				int num = a.TimeMs.CompareTo(b.TimeMs);
				return (num == 0) ? a.Id.CompareTo(b.Id) : num;
			});
		}

		private int LowerBound(double time)
		{
			int num = 0;
			int num2 = Events.Count;
			while (num < num2)
			{
				int num3 = num + (num2 - num) / 2;
				if (Events[num3].TimeMs < time)
				{
					num = num3 + 1;
				}
				else
				{
					num2 = num3;
				}
			}
			return num;
		}

		public void Reset(bool skipAtCurrentTime = false)
		{
			armed = false;
			previous = 0.0 / 0.0;
			position = 0;
			skipCurrent = skipAtCurrentTime;
		}

		public void Advance(double now, double ahead, Action<AudioCue, double> submit, Action cancel)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: 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)
			if (double.IsNaN(now) || double.IsInfinity(now) || ahead < 0.0 || double.IsNaN(ahead) || double.IsInfinity(ahead))
			{
				throw new ArgumentOutOfRangeException();
			}
			bool flag = armed && (now - previous < -20.0 || now - previous > 250.0);
			if (flag)
			{
				cancel.Invoke();
				armed = false;
			}
			if (!armed)
			{
				position = LowerBound(skipCurrent ? (now + 0.001) : ((!flag && now >= 0.0 && now <= 50.0) ? 0.0 : now));
				Enumerator<AudioCue> enumerator = Events.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						AudioCue current = enumerator.Current;
						if (current.Loop && (current.TimeMs < now || (skipCurrent && current.TimeMs == now)) && current.EndMs > now)
						{
							submit.Invoke(current, now);
						}
					}
				}
				finally
				{
					((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
				armed = true;
				skipCurrent = false;
			}
			else if (now < previous)
			{
				return;
			}
			while (position < Events.Count && Events[position].TimeMs <= now + ahead)
			{
				AudioCue audioCue = Events[position];
				submit.Invoke(audioCue, now);
				position++;
			}
			previous = now;
		}

		public static List<AudioCue> CoalesceAttacks(List<AudioCue> source, double windowMs, out int merged)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			source.Sort((Comparison<AudioCue>)delegate(AudioCue a, AudioCue b)
			{
				int num2 = a.TimeMs.CompareTo(b.TimeMs);
				return (num2 == 0) ? a.Id.CompareTo(b.Id) : num2;
			});
			List<AudioCue> val = new List<AudioCue>();
			Dictionary<AudioRoute, double> val2 = new Dictionary<AudioRoute, double>();
			merged = 0;
			Enumerator<AudioCue> enumerator = source.GetEnumerator();
			try
			{
				double num = default(double);
				while (enumerator.MoveNext())
				{
					AudioCue current = enumerator.Current;
					if (!current.Loop)
					{
						if (val2.TryGetValue(current.Route, ref num) && current.TimeMs - num <= windowMs)
						{
							merged++;
							continue;
						}
						val2[current.Route] = current.TimeMs;
					}
					val.Add(current);
				}
				return val;
			}
			finally
			{
				((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
		}

		public static List<AudioCue> MergeLoops(System.Collections.Generic.IEnumerable<AudioCue> source, AudioRoute route)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			List<AudioCue> val = new List<AudioCue>();
			System.Collections.Generic.IEnumerator<AudioCue> enumerator = source.GetEnumerator();
			try
			{
				while (((System.Collections.IEnumerator)enumerator).MoveNext())
				{
					AudioCue current = enumerator.Current;
					if (current.Route == route && current.Loop && current.EndMs > current.TimeMs)
					{
						val.Add(current);
					}
				}
			}
			finally
			{
				((System.IDisposable)enumerator)?.Dispose();
			}
			val.Sort((Comparison<AudioCue>)((AudioCue a, AudioCue b) => a.TimeMs.CompareTo(b.TimeMs)));
			List<AudioCue> val2 = new List<AudioCue>();
			Enumerator<AudioCue> enumerator2 = val.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					AudioCue current2 = enumerator2.Current;
					if (val2.Count == 0 || current2.TimeMs > val2[val2.Count - 1].EndMs)
					{
						val2.Add(current2);
						continue;
					}
					AudioCue audioCue = val2[val2.Count - 1];
					audioCue.EndMs = Math.Max(audioCue.EndMs, current2.EndMs);
					val2[val2.Count - 1] = audioCue;
				}
				return val2;
			}
			finally
			{
				((System.IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
			}
		}
	}
	public static class DspTiming
	{
		public static ulong Target(ulong parentClock, double deltaMs, int sampleRate, double rate)
		{
			//IL_0020: 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)
			if (sampleRate <= 0 || !Finite(deltaMs) || !Finite(rate) || rate <= 0.0)
			{
				throw new ArgumentOutOfRangeException();
			}
			double num = Math.Max(0.0, deltaMs) * (double)sampleRate / (1000.0 * rate);
			if (num > (double)(18446744073709551615uL - parentClock))
			{
				throw new ArgumentOutOfRangeException();
			}
			return checked(parentClock + (ulong)Math.Round(num));
		}

		private static bool Finite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	public enum CompatibilityMode
	{
		Auto,
		VerifiedOnly
	}
	public sealed class MethodIdentity
	{
		[field: CompilerGenerated]
		public string Key
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Assembly
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Type
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Name
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Return
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string[] Parameters
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public bool Static
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public bool Generic
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int Rva
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}
	}
	public sealed class MethodContract
	{
		[field: CompilerGenerated]
		public MethodIdentity Identity
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int Length
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Entry
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Digest
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public List<NativeReference> References
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		} = new List<NativeReference>();
	}
	public sealed class TypeContract
	{
		[field: CompilerGenerated]
		public string Assembly
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Type
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int ValueSize
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string OwnerType
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string[] FieldPath
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public bool Partial
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public List<FieldContract> Fields
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}
	}
	public sealed class FieldContract
	{
		[field: CompilerGenerated]
		public string Name
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Type
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public bool Static
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int Offset
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}
	}
	public sealed class NativeReference
	{
		[field: CompilerGenerated]
		public int Offset
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int Size
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Kind
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int Target
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Symbol
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Digest
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Section
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int TargetLength
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int[] TableTargets
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}
	}
	public sealed class CompatibilityCatalog
	{
		[field: CompilerGenerated]
		public int Schema
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Version
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Unity
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int Metadata
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string[] VerifiedHashes
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public Dictionary<string, string> Environment
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public List<MethodContract> Methods
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public List<MethodIdentity> Targets
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		} = new List<MethodIdentity>();

		[field: CompilerGenerated]
		public List<TypeContract> Types
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public Dictionary<string, int> Layout
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int EnqueueCallOffset
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string MutePattern
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public int MuteJumpOffset
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		public static CompatibilityCatalog Load()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			Stream manifestResourceStream = typeof(CompatibilityCatalog).Assembly.GetManifestResourceStream("InFalsus.compatibility.json");
			try
			{
				if (manifestResourceStream == null)
				{
					throw new InvalidDataException("Missing embedded compatibility catalog");
				}
				return Read(((TextReader)new StreamReader(manifestResourceStream)).ReadToEnd());
			}
			finally
			{
				((System.IDisposable)manifestResourceStream)?.Dispose();
			}
		}

		public static CompatibilityCatalog Read(string json)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			CompatibilityCatalog compatibilityCatalog = JsonSerializer.Deserialize<CompatibilityCatalog>(json, (JsonSerializerOptions)null);
			Version val = default(Version);
			if (compatibilityCatalog == null || compatibilityCatalog.Schema != 1 || !Version.TryParse(compatibilityCatalog.Version, ref val))
			{
				throw new InvalidDataException("Unsupported compatibility schema/version");
			}
			return compatibilityCatalog;
		}
	}
	public interface IGameMetadata
	{
		IDictionary<string, System.IntPtr> Fields { get; }

		int Resolve(MethodIdentity method);

		void Validate(TypeContract type);
	}
	public sealed class CompatibilityResult
	{
		[field: CompilerGenerated]
		public string Version
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string PluginHash
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Status
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		} = "Incompatible";

		[field: CompilerGenerated]
		public string GameHash
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public string Source
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public Dictionary<string, string> Environment
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		} = new Dictionary<string, string>();

		[field: CompilerGenerated]
		public string Failure
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public double ElapsedMs
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public List<string> Checks
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		} = new List<string>();

		[field: CompilerGenerated]
		public List<string> LayoutObservations
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		} = new List<string>();

		[field: CompilerGenerated]
		public Dictionary<string, int> Addresses
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		[field: CompilerGenerated]
		public bool UserAccepted
		{
			[CompilerGenerated]
			get;
			[CompilerGenerated]
			set;
		}

		public bool CanEnable
		{
			get
			{
				if (!(Status == "VerifiedBuild"))
				{
					return Status == "AutoCompatible";
				}
				return true;
			}
		}
	}
	public sealed class ResolvedGameApi
	{
		private readonly ReadOnlyDictionary<string, int> methods;

		private readonly ReadOnlyDictionary<string, int> layout;

		private readonly ReadOnlyDictionary<string, System.IntPtr> fields;

		[field: CompilerGenerated]
		public int MuteJump
		{
			[CompilerGenerated]
			get;
		}

		public ResolvedGameApi(IDictionary<string, int> methods, IDictionary<string, int> layout, int muteJump, IDictionary<string, System.IntPtr> fields)
		{
			this.methods = new ReadOnlyDictionary<string, int>((IDictionary<string, int>)(object)new Dictionary<string, int>(methods));
			this.layout = new ReadOnlyDictionary<string, int>((IDictionary<string, int>)(object)new Dictionary<string, int>(layout));
			this.fields = new ReadOnlyDictionary<string, System.IntPtr>((IDictionary<string, System.IntPtr>)(object)new Dictionary<string, System.IntPtr>(fields));
			MuteJump = muteJump;
		}

		public int Method(string key)
		{
			return methods[key];
		}

		public int L(string key)
		{
			return layout[key];
		}

		public System.IntPtr Field(string key)
		{
			return fields[key];
		}
	}
	public sealed class CompatibilityBudget
	{
		private readonly Stopwatch clock = Stopwatch.StartNew();

		private readonly double limit;

		public double ElapsedMs
		{
			get
			{
				//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)
				TimeSpan elapsed = clock.Elapsed;
				return ((TimeSpan)(ref elapsed)).TotalMilliseconds;
			}
		}

		public CompatibilityBudget(double milliseconds = 2000.0)
		{
			limit = milliseconds;
		}

		public void Check()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if (ElapsedMs > limit)
			{
				throw new TimeoutException("Compatibility check exceeded " + limit + " ms; original audio retained");
			}
		}
	}
	public sealed class NativeImage
	{
		public sealed class Section
		{
			public string Name;

			public int Rva;

			public int Size;

			public int Raw;

			public int RawSize;

			public uint Flags;
		}

		private readonly byte[] data;

		private readonly List<Section> sections = new List<Section>();

		[field: CompilerGenerated]
		public ulong ImageBase
		{
			[CompilerGenerated]
			get;
		}

		[field: CompilerGenerated]
		public string Hash
		{
			[CompilerGenerated]
			get;
		}

		public NativeImage(byte[] bytes)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			data = bytes;
			Hash = Digest(bytes);
			int num = U32(60);
			if (U32(num) != 17744 || U16(num + 4) != 34404 || U16(num + 24) != 523)
			{
				throw new InvalidDataException("Expected x64 PE32+ GameAssembly");
			}
			ImageBase = BitConverter.ToUInt64(data, num + 48);
			int num2 = U16(num + 6);
			int num3 = num + 24 + U16(num + 20);
			if (num2 < 1 || num2 > 96)
			{
				throw new InvalidDataException("Invalid PE sections");
			}
			sections.Add(new Section
			{
				Name = "Headers",
				Rva = 0,
				Size = U32(num + 84),
				Raw = 0,
				RawSize = U32(num + 84),
				Flags = 0u
			});
			for (int i = 0; i < num2; i++)
			{
				int num4 = num3 + i * 40;
				sections.Add(new Section
				{
					Name = Encoding.ASCII.GetString(data, num4, 8).TrimEnd('\0'),
					Size = U32(num4 + 8),
					Rva = U32(num4 + 12),
					RawSize = U32(num4 + 16),
					Raw = U32(num4 + 20),
					Flags = BitConverter.ToUInt32(data, num4 + 36)
				});
			}
		}

		private int U16(int p)
		{
			return BitConverter.ToUInt16(data, p);
		}

		private int U32(int p)
		{
			return checked((int)BitConverter.ToUInt32(data, p));
		}

		public Section At(int rva, int length = 1)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			return Enumerable.SingleOrDefault<Section>((System.Collections.Generic.IEnumerable<Section>)sections, (Func<Section, bool>)((Section x) => rva >= x.Rva && (long)rva + (long)length <= (long)x.Rva + (long)Math.Max(x.Size, x.RawSize))) ?? throw new InvalidDataException("Unmapped PE range 0x" + rva.ToString("X"));
		}

		public byte[] Read(int rva, int length)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (length < 1 || length > 1048576)
			{
				throw new InvalidDataException("Invalid native read size");
			}
			Section section = At(rva, length);
			byte[] array = new byte[length];
			int num = Math.Min(length, Math.Max(0, section.RawSize - (rva - section.Rva)));
			if (num > 0)
			{
				Buffer.BlockCopy((System.Array)data, section.Raw + rva - section.Rva, (System.Array)array, 0, num);
			}
			return array;
		}

		public void Executable(int rva, int length)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if ((At(rva, length).Flags & 0x20000000) == 0)
			{
				throw new InvalidDataException("Native entry is not executable");
			}
		}

		public static string Digest(byte[] bytes)
		{
			SHA256 val = SHA256.Create();
			try
			{
				return Convert.ToHexString(((HashAlgorithm)val).ComputeHash(bytes));
			}
			finally
			{
				((System.IDisposable)val)?.Dispose();
			}
		}

		public static byte[] Hex(string text)
		{
			return Convert.FromHexString(text);
		}
	}
	public static class NativeVerifier
	{
		public static List<NativeReference> Decode(NativeImage image, int rva, int length, CompatibilityBudget budget)
		{
			//IL_0034: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Invalid comparison between Unknown and I4
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: 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_00f9: Unknown result type (might be due to invalid IL or missing references)
			image.Executable(rva, length);
			Decoder val = Decoder.Create(64, image.Read(rva, length), image.ImageBase + (uint)rva, (DecoderOptions)0);
			List<NativeReference> val2 = new List<NativeReference>();
			while (val.IP < image.ImageBase + (uint)rva + (uint)length)
			{
				budget.Check();
				Instruction val3 = val.Decode();
				int num = checked((int)(((Instruction)(ref val3)).IP - image.ImageBase - (uint)rva));
				if (((Instruction)(ref val3)).Length == 0)
				{
					throw new InvalidDataException("Decoder made no progress");
				}
				ConstantOffsets constantOffsets = val.GetConstantOffsets(ref val3);
				if (((Instruction)(ref val3)).IsIPRelativeMemoryOperand)
				{
					val2.Add(new NativeReference
					{
						Offset = num + constantOffsets.DisplacementOffset,
						Size = constantOffsets.DisplacementSize,
						Kind = "Data",
						Target = checked((int)(((Instruction)(ref val3)).IPRelativeMemoryAddress - image.ImageBase))
					});
				}
				if ((int)((Instruction)(ref val3)).Op0Kind == 3)
				{
					int num2 = checked((int)(((Instruction)(ref val3)).NearBranchTarget - image.ImageBase));
					if (num2 < rva || num2 >= rva + length)
					{
						val2.Add(new NativeReference
						{
							Offset = num + constantOffsets.ImmediateOffset,
							Size = constantOffsets.ImmediateSize,
							Kind = "Call",
							Target = num2
						});
					}
				}
			}
			return val2;
		}

		public static string CodeDigest(NativeImage image, int rva, int length, List<NativeReference> refs)
		{
			//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)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = image.Read(rva, length);
			Enumerator<NativeReference> enumerator = refs.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					NativeReference current = enumerator.Current;
					if (current.Size < 1 || current.Offset < 0 || current.Offset + current.Size > length)
					{
						throw new InvalidDataException("Invalid relocation slot");
					}
					System.Array.Clear((System.Array)array, current.Offset, current.Size);
				}
			}
			finally
			{
				((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			return NativeImage.Digest(array);
		}

		public static void Capture(NativeImage image, MethodContract m, Dictionary<string, int> addresses, CompatibilityBudget budget)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			int rva = m.Identity.Rva;
			m.Entry = Convert.ToHexString(image.Read(rva, Math.Min(12, m.Length)));
			m.References = Decode(image, rva, m.Length, budget);
			Enumerator<NativeReference> enumerator = m.References.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					NativeReference r = enumerator.Current;
					r.Section = image.At(r.Target).Name;
					if (r.Kind == "Call")
					{
						r.Symbol = Enumerable.FirstOrDefault<KeyValuePair<string, int>>((System.Collections.Generic.IEnumerable<KeyValuePair<string, int>>)addresses, (Func<KeyValuePair<string, int>, bool>)((KeyValuePair<string, int> x) => x.Value == r.Target)).Key;
						if (r.Symbol == null)
						{
							r.TargetLength = Math.Min(32, image.At(r.Target).RawSize - (r.Target - image.At(r.Target).Rva));
							r.Digest = NativeImage.Digest(image.Read(r.Target, r.TargetLength));
						}
					}
					else if ((m.Identity.Key == "Dispatch" && r.Target == 7368704) || (m.Identity.Key == "GroupSelector" && r.Target == 4493584))
					{
						int num = ((m.Identity.Key == "Dispatch") ? 24 : 9);
						byte[] array = image.Read(r.Target, num * 4);
						r.TableTargets = new int[num];
						for (int num2 = 0; num2 < num; num2++)
						{
							r.TableTargets[num2] = BitConverter.ToInt32(array, num2 * 4) - rva;
						}
					}
					else
					{
						r.TargetLength = 8;
						r.Digest = NativeImage.Digest(image.Read(r.Target, 8));
					}
				}
			}
			finally
			{
				((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			m.Digest = CodeDigest(image, rva, m.Length, m.References);
		}

		public static void Validate(NativeImage image, MethodContract rule, int rva, Dictionary<string, int> addresses, Dictionary<string, int> sectionDeltas, CompatibilityBudget budget)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			List<NativeReference> val = Decode(image, rva, rule.Length, budget);
			if (val.Count != rule.References.Count || CodeDigest(image, rva, rule.Length, val) != rule.Digest)
			{
				throw new InvalidDataException("Native control flow/constants changed: " + rule.Identity.Key);
			}
			int num2 = default(int);
			for (int i = 0; i < val.Count; i++)
			{
				budget.Check();
				NativeReference nativeReference = val[i];
				NativeReference nativeReference2 = rule.References[i];
				if (nativeReference.Kind != nativeReference2.Kind || nativeReference.Offset != nativeReference2.Offset || nativeReference.Size != nativeReference2.Size || image.At(nativeReference.Target).Name != nativeReference2.Section)
				{
					throw new InvalidDataException("Native reference shape changed: " + rule.Identity.Key);
				}
				if (nativeReference2.Symbol != null)
				{
					if (nativeReference.Target != addresses[nativeReference2.Symbol])
					{
						throw new InvalidDataException("Native call target changed: " + rule.Identity.Key + " -> " + nativeReference2.Symbol);
					}
				}
				else if (nativeReference2.TableTargets != null)
				{
					byte[] array = image.Read(nativeReference.Target, nativeReference2.TableTargets.Length * 4);
					for (int j = 0; j < nativeReference2.TableTargets.Length; j++)
					{
						if (BitConverter.ToInt32(array, j * 4) - rva != nativeReference2.TableTargets[j])
						{
							throw new InvalidDataException("Audio dispatch table changed: " + rule.Identity.Key);
						}
					}
				}
				else if (NativeImage.Digest(image.Read(nativeReference.Target, nativeReference2.TargetLength)) != nativeReference2.Digest)
				{
					throw new InvalidDataException("Native reference content changed: " + rule.Identity.Key + " at +0x" + nativeReference.Offset.ToString("X"));
				}
				if (nativeReference2.Kind == "Data" && nativeReference2.Section == ".data")
				{
					int num = nativeReference.Target - nativeReference2.Target;
					if (sectionDeltas.TryGetValue(nativeReference2.Section, ref num2) && num2 != num)
					{
						throw new InvalidDataException("Static reference topology changed: " + rule.Identity.Key);
					}
					sectionDeltas[nativeReference2.Section] = num;
				}
			}
		}
	}
	public static class CompatibilityEngine
	{
		public static bool Verified(CompatibilityCatalog c, string hash)
		{
			return Enumerable.Any<string>((System.Collections.Generic.IEnumerable<string>)c.VerifiedHashes, (Func<string, bool>)((string x) => string.Equals(x, hash, (StringComparison)5)));
		}

		public static int ResolveEnqueue(NativeImage image, int process, int offset)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = image.Read(process + offset, 5);
			if (array[0] != 232)
			{
				throw new InvalidDataException("Keyboard queue call is missing");
			}
			return checked(process + offset + 5 + BitConverter.ToInt32(array, 1));
		}

		public static int FindMute(NativeImage image, int method, int length, string hex, int jumpOffset)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = image.Read(method, length);
			int num = hex.Length / 2;
			int num2 = -1;
			for (int i = 0; i <= array.Length - num; i++)
			{
				bool flag = true;
				for (int j = 0; j < num; j++)
				{
					string text = hex.Substring(j * 2, 2);
					if (text != "??" && array[i + j] != Convert.ToByte(text, 16))
					{
						flag = false;
						break;
					}
				}
				if (flag)
				{
					if (num2 != -1)
					{
						throw new InvalidDataException("Ambiguous offset mute gate");
					}
					num2 = method + i + jumpOffset;
				}
			}
			if (num2 == -1)
			{
				throw new InvalidDataException("Unrecognized offset mute logic; absence does not prove removal");
			}
			return num2;
		}

		public static ResolvedGameApi Resolve(CompatibilityCatalog catalog, NativeImage image, IGameMetadata metadata, CompatibilityMode mode, CompatibilityResult result, CompatibilityBudget budget, Func<int, int, byte[]> liveRead = null, bool inspectKnown = false)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_029c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: 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_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f8: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				result.Version = catalog.Version;
				result.GameHash = image.Hash;
				if (mode != CompatibilityMode.Auto && mode != CompatibilityMode.VerifiedOnly)
				{
					throw new InvalidDataException("Invalid compatibility mode");
				}
				bool flag = Verified(catalog, image.Hash);
				result.Source = (flag ? "verified profile" : "runtime metadata + native contracts");
				if (!flag && mode == CompatibilityMode.VerifiedOnly)
				{
					throw new InvalidDataException("Unknown build blocked by VerifiedOnly");
				}
				Dictionary<string, int> val = new Dictionary<string, int>();
				Enumerator<MethodContract> enumerator = catalog.Methods.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						MethodContract current = enumerator.Current;
						budget.Check();
						if (!(current.Identity.Key == "Enqueue"))
						{
							int num = metadata.Resolve(current.Identity);
							image.Executable(num, Math.Max(12, current.Length));
							if (flag && num != current.Identity.Rva)
							{
								throw new InvalidDataException("Known method address mismatch: " + current.Identity.Key);
							}
							val.Add(current.Identity.Key, num);
						}
					}
				}
				finally
				{
					((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
				val.Add("Enqueue", ResolveEnqueue(image, val["ProcessNote"], catalog.EnqueueCallOffset));
				result.Checks.Add("All method signatures and keyboard queue call resolved");
				List<string> val2 = new List<string>();
				Enumerator<TypeContract> enumerator2 = catalog.Types.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						TypeContract current2 = enumerator2.Current;
						budget.Check();
						try
						{
							metadata.Validate(current2);
						}
						catch (System.Exception ex)
						{
							val2.Add(ex.Message);
						}
					}
				}
				finally
				{
					((System.IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
				}
				if (val2.Count > 0)
				{
					throw new InvalidDataException("Layout mismatches: " + string.Join("; ", (System.Collections.Generic.IEnumerable<string>)val2));
				}
				result.Checks.Add("All game layouts match baseline");
				if (!flag || inspectKnown)
				{
					Enumerator<MethodIdentity> enumerator3 = catalog.Targets.GetEnumerator();
					try
					{
						while (enumerator3.MoveNext())
						{
							MethodIdentity current3 = enumerator3.Current;
							budget.Check();
							val[current3.Key] = metadata.Resolve(current3);
						}
					}
					finally
					{
						((System.IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose();
					}
				}
				if (flag)
				{
					new NativePreflight(catalog.VerifiedHashes, Enumerable.ToArray<NativeSignature>(Enumerable.Select<MethodContract, NativeSignature>((System.Collections.Generic.IEnumerable<MethodContract>)catalog.Methods, (Func<MethodContract, NativeSignature>)((MethodContract x) => new NativeSignature(x.Identity.Key, x.Identity.Rva, x.Entry))))).Validate(liveRead ?? new Func<int, int, byte[]>(image.Read));
				}
				Dictionary<string, int> sectionDeltas = new Dictionary<string, int>();
				enumerator = catalog.Methods.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						MethodContract current4 = enumerator.Current;
						budget.Check();
						int num2 = val[current4.Identity.Key];
						if (!flag || inspectKnown)
						{
							NativeVerifier.Validate(image, current4, num2, val, sectionDeltas, budget);
						}
						if (liveRead != null && !MemoryExtensions.SequenceEqual<byte>(MemoryExtensions.AsSpan<byte>(liveRead.Invoke(num2, Math.Min(12, current4.Length))), System.ReadOnlySpan<byte>.op_Implicit(image.Read(num2, Math.Min(12, current4.Length)))))
						{
							throw new InvalidDataException("Live entry differs: " + current4.Identity.Key);
						}
					}
				}
				finally
				{
					((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
				result.Checks.Add((flag && !inspectKnown) ? "Known hash and live entries passed" : "Native instruction, call and data-reference contracts passed");
				MethodContract methodContract = Enumerable.Single<MethodContract>((System.Collections.Generic.IEnumerable<MethodContract>)catalog.Methods, (Func<MethodContract, bool>)((MethodContract x) => x.Identity.Key == "AudioInit"));
				int num3 = FindMute(image, val["AudioInit"], methodContract.Length, catalog.MutePattern, catalog.MuteJumpOffset);
				if (liveRead != null && !MemoryExtensions.SequenceEqual<byte>(MemoryExtensions.AsSpan<byte>(liveRead.Invoke(num3, 2)), (System.ReadOnlySpan<byte>)new byte[2] { 127, 11 }))
				{
					throw new InvalidDataException("Live mute branch differs");
				}
				result.Checks.Add("Unique >100 ms mute branch verified");
				budget.Check();
				result.Status = (flag ? "VerifiedBuild" : "AutoCompatible");
				result.Addresses = val;
				return new ResolvedGameApi((IDictionary<string, int>)(object)val, (IDictionary<string, int>)(object)catalog.Layout, num3, metadata.Fields);
			}
			catch (System.Exception ex2)
			{
				result.Status = "Incompatible";
				result.Failure = ex2.Message;
				return null;
			}
			finally
			{
				result.ElapsedMs = budget.ElapsedMs;
			}
		}
	}
	internal sealed class FmodScheduler : System.IDisposable
	{
		private const string Dll = "fmodstudio";

		private static System.IntPtr nativeModule;

		private static readonly object moduleGate;

		private readonly System.IntPtr system;

		private readonly System.IntPtr[] sounds;

		private readonly System.IntPtr[] groups;

		private readonly int sampleRate;

		private readonly List<System.IntPtr> owned = new List<System.IntPtr>();

		public int SampleRate => sampleRate;

		public int OwnedCount => owned.Count;

		private static System.IntPtr ResolveModule()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			if (nativeModule != System.IntPtr.Zero)
			{
				return nativeModule;
			}
			lock (moduleGate)
			{
				if (nativeModule != System.IntPtr.Zero)
				{
					return nativeModule;
				}
				foreach (ProcessModule item in (ReadOnlyCollectionBase)Process.GetCurrentProcess().Modules)
				{
					ProcessModule val = item;
					if (val.ModuleName.Equals("fmodstudio.dll", (StringComparison)5))
					{
						nativeModule = val.BaseAddress;
						return nativeModule;
					}
				}
				throw new DllNotFoundException("The game's fmodstudio.dll has not loaded yet.");
			}
		}

		static FmodScheduler()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			moduleGate = new object();
			NativeLibrary.SetDllImportResolver(typeof(FmodScheduler).Assembly, (DllImportResolver)((string name, Assembly assembly, DllImportSearchPath? path) => (!(name == "fmodstudio")) ? System.IntPtr.Zero : ResolveModule()));
		}

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_System_GetSoftwareFormat(System.IntPtr system, out int rate, out int mode, out int speakers);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_System_PlaySound(System.IntPtr system, System.IntPtr sound, System.IntPtr group, int paused, out System.IntPtr channel);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Channel_GetDSPClock(System.IntPtr channel, out ulong own, out ulong parent);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Channel_SetDelay(System.IntPtr channel, ulong start, ulong end, int stop);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Channel_SetPaused(System.IntPtr channel, int paused);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Channel_SetMode(System.IntPtr channel, uint mode);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Channel_SetPitch(System.IntPtr channel, float pitch);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Channel_SetVolume(System.IntPtr channel, float volume);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Channel_SetPosition(System.IntPtr channel, uint position, uint unit);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Channel_Stop(System.IntPtr channel);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Sound_GetMode(System.IntPtr sound, out uint mode);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Sound_GetLength(System.IntPtr sound, out uint length, uint unit);

		[DllImport("fmodstudio", CallingConvention = (CallingConvention)2)]
		private static extern int FMOD5_Sound_GetOpenState(System.IntPtr sound, out int state, out uint percent, out int starving, out int busy);

		public static bool IsReady(System.IntPtr sound)
		{
			int result;
			int state;
			return Probe(sound, out result, out state);
		}

		public static bool Probe(System.IntPtr sound, out int result, out int state)
		{
			state = -1;
			result = -1;
			if (sound == System.IntPtr.Zero)
			{
				return false;
			}
			result = FMOD5_Sound_GetOpenState(sound, out state, out var _, out var _, out var _);
			return AudioSourceState.IsReady(result, state);
		}

		private static void Check(int result, string operation)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (result != 0)
			{
				throw new InvalidOperationException(operation + " failed, FMOD result=" + result);
			}
		}

		public FmodScheduler(System.IntPtr system, System.IntPtr[] sounds, System.IntPtr[] groups, bool[] used)
		{
			//IL_005f: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
			this.system = system;
			this.sounds = sounds;
			this.groups = groups;
			Check(FMOD5_System_GetSoftwareFormat(system, out sampleRate, out var _, out var _), "GetSoftwareFormat");
			if (sampleRate < 8000 || sampleRate > 384000)
			{
				throw new InvalidOperationException("Unexpected FMOD sample rate");
			}
			for (int i = 0; i < sounds.Length; i++)
			{
				if (used[i])
				{
					if (groups[i] == System.IntPtr.Zero || !IsReady(sounds[i]))
					{
						throw new InvalidOperationException("Sound/group is not ready for route " + i);
					}
					Check(FMOD5_Sound_GetMode(sounds[i], out var mode2), "GetMode");
					if ((mode2 & 0x80) != 0)
					{
						throw new InvalidOperationException("Stream source cannot be safely shared; route " + i);
					}
				}
			}
		}

		public void WarmUp(bool[] used)
		{
			for (int i = 0; i < used.Length; i++)
			{
				if (used[i])
				{
					Check(FMOD5_System_PlaySound(system, sounds[i], groups[i], 1, out var channel), "WarmUp.PlaySound(paused)");
					try
					{
						Check(FMOD5_Channel_SetMode(channel, 1u), "WarmUp.SetMode");
						Check(FMOD5_Channel_SetPitch(channel, 1f), "WarmUp.SetPitch");
						Check(FMOD5_Channel_SetVolume(channel, 0f), "WarmUp.SetVolume");
						Check(FMOD5_Sound_GetLength(sounds[i], out var _, 1u), "WarmUp.GetLength");
						Check(FMOD5_Channel_SetPosition(channel, 0u, 1u), "WarmUp.SetPosition");
						Check(FMOD5_Channel_GetDSPClock(channel, out var _, out var _), "WarmUp.GetDSPClock");
						Check(FMOD5_Channel_SetDelay(channel, 0uL, 0uL, 1), "WarmUp.SetDelay");
						Check(FMOD5_Channel_SetPaused(channel, 1), "WarmUp.KeepPaused");
					}
					finally
					{
						Check(FMOD5_Channel_Stop(channel), "WarmUp.Stop");
					}
				}
			}
		}

		public void Submit(AudioCue cue, double now, double offset, double rate)
		{
			int route = (int)cue.Route;
			double num = cue.TimeMs + offset;
			double num2 = cue.EndMs + offset;
			if (cue.Loop && num2 <= now)
			{
				return;
			}
			Check(FMOD5_System_PlaySound(system, sounds[route], groups[route], 1, out var channel), "PlaySound(paused)");
			try
			{
				Check(FMOD5_Channel_SetMode(channel, (!cue.Loop) ? 1u : 2u), "SetMode");
				Check(FMOD5_Channel_SetPitch(channel, (float)rate), "SetPitch");
				Check(FMOD5_Channel_SetVolume(channel, 1f), "SetVolume");
				if (cue.Loop && now > num)
				{
					Check(FMOD5_Sound_GetLength(sounds[route], out var length, 1u), "GetLength");
					if (length != 0)
					{
						Check(FMOD5_Channel_SetPosition(channel, (uint)((now - num) % (double)length), 1u), "SetPosition");
					}
				}
				Check(FMOD5_Channel_GetDSPClock(channel, out var _, out var parent), "GetDSPClock");
				ulong num3 = DspTiming.Target(parent, num - now, sampleRate, rate);
				ulong num4 = (cue.Loop ? DspTiming.Target(parent, num2 - now, sampleRate, rate) : 0);
				if (cue.Loop && num4 <= num3)
				{
					num4 = num3 + 1;
				}
				Check(FMOD5_Channel_SetDelay(channel, num3, num4, 1), "SetDelay");
				Check(FMOD5_Channel_SetPaused(channel, 0), "Unpause");
				owned.Add(channel);
			}
			catch
			{
				FMOD5_Channel_Stop(channel);
				throw;
			}
		}

		public void StopAll()
		{
			//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)
			Enumerator<System.IntPtr> enumerator = owned.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					FMOD5_Channel_Stop(enumerator.Current);
				}
			}
			finally
			{
				((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
			owned.Clear();
		}

		public void Dispose()
		{
			StopAll();
		}
	}
	public sealed class HoldHeadScope
	{
		private readonly HashSet<long> ids = new HashSet<long>();

		private System.IntPtr queue;

		public int Count => ids.Count;

		public void Register(long id)
		{
			ids.Add(id);
		}

		public System.IntPtr Enter(bool active, long id, System.IntPtr target)
		{
			System.IntPtr result = queue;
			queue = ((active && ids.Contains(id)) ? target : System.IntPtr.Zero);
			return result;
		}

		public void Restore(System.IntPtr previous)
		{
			queue = previous;
		}

		public bool Owns(System.IntPtr target, byte eventType, int keyIndex)
		{
			if (queue != System.IntPtr.Zero && queue == target && eventType == 1 && keyIndex >= 0)
			{
				return keyIndex < 6;
			}
			return false;
		}
	}
	public static class MethodSignatures
	{
		public static string Normalize(string value)
		{
			return Regex.Replace(value ?? "", "`[0-9]+", "").Replace('/', '.').Replace('+', '.')
				.Replace(" ", "");
		}

		public static bool Matches(MethodIdentity expected, MethodIdentity actual)
		{
			if (expected.Name == actual.Name && expected.Static == actual.Static && expected.Generic == actual.Generic && Normalize(expected.Return) == Normalize(actual.Return))
			{
				return Enumerable.SequenceEqual<string>(Enumerable.Select<string, string>((System.Collections.Generic.IEnumerable<string>)expected.Parameters, (Func<string, string>)Normalize), Enumerable.Select<string, string>((System.Collections.Generic.IEnumerable<string>)actual.Parameters, (Func<string, string>)Normalize));
			}
			return false;
		}

		public static MethodIdentity Unique(MethodIdentity expected, System.Collections.Generic.IEnumerable<MethodIdentity> candidates)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			MethodIdentity[] array = Enumerable.ToArray<MethodIdentity>(Enumerable.Where<MethodIdentity>(candidates, (Func<MethodIdentity, bool>)((MethodIdentity x) => Matches(expected, x))));
			if (array.Length != 1)
			{
				throw new InvalidDataException(((array.Length == 0) ? "Missing" : "Ambiguous") + " exact method signature: " + expected.Key);
			}
			return array[0];
		}
	}
	public sealed class NativeSignature
	{
		public readonly string Name;

		public readonly string Hex;

		public readonly int Rva;

		public NativeSignature(string name, int rva, string hex)
		{
			Name = name;
			Rva = rva;
			Hex = hex;
		}
	}
	public sealed class NativePreflight
	{
		private readonly string[] hashes;

		private readonly NativeSignature[] signatures;

		public NativePreflight(string[] hashes, NativeSignature[] signatures)
		{
			this.hashes = (string[])((System.Array)hashes).Clone();
			this.signatures = (NativeSignature[])((System.Array)signatures).Clone();
		}

		public bool Supports(string hash)
		{
			string[] array = hashes;
			for (int i = 0; i < array.Length; i++)
			{
				if (string.Equals(array[i], hash, (StringComparison)5))
				{
					return true;
				}
			}
			return false;
		}

		public void Validate(Func<int, int, byte[]> read)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			NativeSignature[] array = signatures;
			foreach (NativeSignature nativeSignature in array)
			{
				int num = nativeSignature.Hex.Length / 2;
				byte[] array2 = read.Invoke(nativeSignature.Rva, num);
				if (array2 == null || array2.Length != num)
				{
					throw new InvalidOperationException("Incomplete native entry: " + nativeSignature.Name);
				}
				for (int j = 0; j < num; j++)
				{
					if (array2[j] != Convert.ToByte(nativeSignature.Hex.Substring(j * 2, 2), 16))
					{
						throw new InvalidOperationException("Native signature mismatch: " + nativeSignature.Name + " RVA=0x" + nativeSignature.Rva.ToString("X"));
					}
				}
			}
		}
	}
	public static class NoteAudioPolicy
	{
		public static bool IsSide(int lane)
		{
			if (lane != 2)
			{
				return lane == 3;
			}
			return true;
		}

		public static bool OwnsKeyboardFeedback(int type, int lane)
		{
			if (lane >= 1 && lane <= 3)
			{
				if (type != 1)
				{
					return type == 2;
				}
				return true;
			}
			return false;
		}

		public static AudioRoute FeedbackRoute(int firstKey, int lastKey)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (firstKey < 0 || lastKey < firstKey || lastKey >= 6)
			{
				throw new InvalidOperationException("Invalid keyboard key range");
			}
			if (firstKey != 0 && firstKey != 5)
			{
				return AudioRoute.KeyboardHoldHit;
			}
			return AudioRoute.SideKeyHit;
		}
	}
	public static class NoteJudgements
	{
		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_object_get_class(System.IntPtr obj);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_class_get_element_class(System.IntPtr klass);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_class_get_field_from_name(System.IntPtr klass, string name);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern int il2cpp_field_get_offset(System.IntPtr field);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern int il2cpp_class_value_size(System.IntPtr klass, out uint alignment);

		private static int Offset(System.IntPtr klass, string field)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			System.IntPtr intPtr = il2cpp_class_get_field_from_name(klass, field);
			if (intPtr == System.IntPtr.Zero)
			{
				throw new InvalidOperationException("Missing dictionary field " + field);
			}
			return il2cpp_field_get_offset(intPtr);
		}

		public static Dictionary<long, List<AudioCue>> Snapshot(System.IntPtr dictionary, int total, int recordSize = 40, int recordId = 0, int recordKind = 24, int recordTime = 16)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			if (dictionary == System.IntPtr.Zero)
			{
				throw new InvalidOperationException("Missing per-note judgement dictionary");
			}
			System.IntPtr klass = il2cpp_object_get_class(dictionary);
			int num = Marshal.ReadInt32(dictionary, Offset(klass, "_count"));
			if (num < 0 || num > 200000 || Marshal.ReadInt32(dictionary, Offset(klass, "_freeCount")) != 0)
			{
				throw new InvalidOperationException("Unexpected chart dictionary state");
			}
			System.IntPtr intPtr = Marshal.ReadIntPtr(dictionary, Offset(klass, "_entries"));
			if (intPtr == System.IntPtr.Zero || Marshal.ReadInt64(intPtr, 24) < num)
			{
				throw new InvalidOperationException("Invalid per-note entries");
			}
			System.IntPtr klass2 = il2cpp_class_get_element_class(il2cpp_object_get_class(intPtr));
			uint alignment;
			int size = il2cpp_class_value_size(klass2, out alignment);
			int num2 = Offset(klass2, "hashCode");
			int key = Offset(klass2, "key") - num2;
			int value = Offset(klass2, "value") - num2;
			return ReadEntries(intPtr, num, size, key, value, total, recordSize, recordId, recordKind, recordTime);
		}

		public static Dictionary<long, List<AudioCue>> ReadEntries(System.IntPtr entries, int count, int size, int key, int value, int total, int recordSize = 40, int recordId = 0, int recordKind = 24, int recordTime = 16)
		{
			//IL_0039: 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_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			if (size != 32 || key != 8 || value != 16 || count < 0 || count > 200000 || entries == System.IntPtr.Zero || Marshal.ReadInt64(entries, 24) < count)
			{
				throw new InvalidOperationException("Unsupported per-note entry layout");
			}
			Dictionary<long, List<AudioCue>> val = new Dictionary<long, List<AudioCue>>();
			HashSet<long> val2 = new HashSet<long>();
			for (int i = 0; i < count; i++)
			{
				System.IntPtr intPtr = System.IntPtr.Add(entries, checked(32 + i * size));
				long num = Marshal.ReadInt64(intPtr, key);
				System.IntPtr intPtr2 = Marshal.ReadIntPtr(intPtr, value);
				int num2 = Marshal.ReadInt32(intPtr, value + 8) & 0x7FFFFFFF;
				int num3 = Marshal.ReadInt32(intPtr, value + 12) & 0x7FFFFFFF;
				if (num3 == 0)
				{
					val.Add(num, new List<AudioCue>());
					continue;
				}
				if (intPtr2 == System.IntPtr.Zero || num2 > Marshal.ReadInt64(intPtr2, 24) || num3 > total || (long)num2 + (long)num3 > Marshal.ReadInt64(intPtr2, 24))
				{
					throw new InvalidOperationException("Invalid per-note judgement memory");
				}
				List<AudioCue> val3 = new List<AudioCue>();
				for (int j = 0; j < num3; j++)
				{
					System.IntPtr intPtr3 = System.IntPtr.Add(intPtr2, checked(32 + (num2 + j) * recordSize));
					long num4 = Marshal.ReadInt64(intPtr3, recordId);
					int num5 = Marshal.ReadInt32(intPtr3, recordKind);
					if (num4 >= 0 && num4 < total && val2.Add(num4))
					{
						switch (num5)
						{
						case 1:
						{
							double num6 = BitConverter.Int64BitsToDouble(Marshal.ReadInt64(intPtr3, recordTime));
							if (double.IsNaN(num6) || double.IsInfinity(num6) || num6 < -60000.0 || num6 > 86400000.0)
							{
								throw new InvalidOperationException("Invalid per-note judgement time");
							}
							val3.Add(new AudioCue
							{
								Id = num4,
								TimeMs = num6,
								Route = AudioRoute.KeyboardHoldHit
							});
							continue;
						}
						case 0:
						case 2:
						case 3:
						case 4:
						case 5:
							continue;
						}
					}
					throw new InvalidOperationException("Invalid per-note judgement identity");
				}
				val.Add(num, val3);
			}
			return val;
		}
	}
	public sealed class PatchSet : System.IDisposable
	{
		private readonly List<System.IDisposable> items = new List<System.IDisposable>();

		public int Count => items.Count;

		public void Add(System.IDisposable item)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (item == null)
			{
				throw new ArgumentNullException("item");
			}
			items.Add(item);
		}

		public void Dispose()
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			List<System.Exception> val = new List<System.Exception>();
			for (int num = items.Count - 1; num >= 0; num--)
			{
				try
				{
					items[num].Dispose();
					items.RemoveAt(num);
				}
				catch (System.Exception ex)
				{
					val.Add(ex);
				}
			}
			if (val.Count > 0)
			{
				throw new AggregateException("Native patch cleanup failed", (System.Collections.Generic.IEnumerable<System.Exception>)val);
			}
		}
	}
	[BepInPlugin("local.infalsus.chartaudio", "In Falsus Chart Audio", "0.5.1")]
	public sealed class Plugin : BasePlugin
	{
		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate void VoidMethod(System.IntPtr self, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate System.IntPtr LoadSourceMethod(System.IntPtr self, byte kind, int group, System.IntPtr callback, [MarshalAs((UnmanagedType)3)] bool range, double from, double to, [MarshalAs((UnmanagedType)3)] bool flag, int extra, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate double DoubleMethod(System.IntPtr self, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate System.IntPtr GroupMethod(System.IntPtr groups, int group, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate int NoteOffsetMethod(System.IntPtr note, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		[return: MarshalAs((UnmanagedType)3)]
		private delegate bool BoolMethod(System.IntPtr self, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate void HitMethod(System.IntPtr self, byte kind, double offset, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate void DispatchMethod(System.IntPtr self, System.IntPtr results, System.IntPtr evt, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate void ProcessNoteMethod(System.IntPtr self, System.IntPtr records, System.IntPtr note, System.IntPtr queue, System.IntPtr mi);

		[UnmanagedFunctionPointer(/*Could not decode attribute arguments.*/)]
		private delegate void EnqueueMethod(System.IntPtr self, System.IntPtr evt, System.IntPtr mi);

		private readonly PatchSet patches = new PatchSet();

		private readonly List<System.Delegate> roots = new List<System.Delegate>();

		private ConfigEntry<bool> enabled;

		private ConfigEntry<bool> removeMuteLimit;

		private ConfigEntry<bool> debug;

		private ConfigEntry<CompatibilityMode> compatibilityMode;

		private ResolvedGameApi api;

		private ConfigEntry<double> soundOffset;

		private ConfigEntry<double> scheduleAhead;

		private int moduleSize;

		private System.IntPtr module;

		private System.IntPtr logicalField;

		private System.IntPtr controllerField;

		private System.IntPtr systemField;

		private System.IntPtr groupsField;

		private System.IntPtr soundManagerField;

		private System.IntPtr scene;

		private System.IntPtr chartIdentity;

		private RuntimePatch mutePatch;

		private AudioTimeline timeline;

		private FmodScheduler scheduler;

		private SourceLeases sources;

		private AudioTimeline preparedTimeline;

		private HoldHeadScope preparedHeads;

		private System.IntPtr preparedChart;

		private bool[] preparedUsed;

		private string preparedDescription;

		private long nextPrepareAttempt;

		private HoldHeadScope holdHeads = new HoldHeadScope();

		private bool ready;

		private bool faulted;

		private bool wasPlaying;

		private double appliedOffset;

		private double lastRate = 1.0;

		private long lastStatus;

		private int scheduled;

		private int suppressed;

		private int feedbackSuppressed;

		private readonly int[] scheduledByRoute = new int[System.Enum.GetValues(typeof(AudioRoute)).Length];

		private VoidMethod originalUpdate;

		private VoidMethod originalStart;

		private VoidMethod originalDisable;

		private VoidMethod originalDestroy;

		private VoidMethod originalAudioInit;

		private VoidMethod loopStart;

		private VoidMethod loopStop;

		private VoidMethod disposeSource;

		private LoadSourceMethod loadSource;

		private DispatchMethod originalDispatch;

		private HitMethod originalHit;

		private ProcessNoteMethod originalProcessNote;

		private EnqueueMethod originalEnqueue;

		private DoubleMethod musicPosition;

		private GroupMethod groupSelector;

		private NoteOffsetMethod noteOffset;

		private BoolMethod mouseHoldActive;

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern void il2cpp_field_static_get_value(System.IntPtr field, out System.IntPtr value);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2, EntryPoint = "il2cpp_field_static_get_value")]
		private static extern void ReadStaticValue(System.IntPtr field, System.IntPtr buffer);

		private static System.IntPtr Ptr(System.IntPtr p, int off)
		{
			return Marshal.ReadIntPtr(p, off);
		}

		private static int I32(System.IntPtr p, int off)
		{
			return Marshal.ReadInt32(p, off);
		}

		private static double F64(System.IntPtr p, int off)
		{
			return BitConverter.Int64BitsToDouble(Marshal.ReadInt64(p, off));
		}

		private static float F32(System.IntPtr p, int off)
		{
			return BitConverter.Int32BitsToSingle(I32(p, off));
		}

		private static bool Finite(double t)
		{
			if (!double.IsNaN(t))
			{
				return !double.IsInfinity(t);
			}
			return false;
		}

		private System.IntPtr At(int rva)
		{
			return System.IntPtr.Add(module, rva);
		}

		private T Function<T>(int rva) where T : System.Delegate
		{
			return Marshal.GetDelegateForFunctionPointer<T>(At(rva));
		}

		private void Hook<T>(int rva, T callback, out T original) where T : System.Delegate
		{
			RuntimeHelpers.PrepareDelegate((System.Delegate)callback);
			roots.Add((System.Delegate)callback);
			patches.Add((System.IDisposable)INativeDetour.CreateAndApply<T>(At(rva), callback, ref original));
		}

		private void WarmManagedPaths()
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			Stopwatch val = Stopwatch.StartNew();
			int num = 0;
			int num2 = 0;
			System.Type[] types = typeof(Plugin).Assembly.GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods((BindingFlags)62);
				foreach (MethodInfo val2 in methods)
				{
					if (!((MethodBase)val2).ContainsGenericParameters && !((MethodBase)val2).IsAbstract && ((MethodBase)val2).GetMethodBody() != null)
					{
						try
						{
							RuntimeHelpers.PrepareMethod(((MethodBase)val2).MethodHandle);
							num++;
						}
						catch (NotSupportedException)
						{
							num2++;
						}
						catch (ArgumentException)
						{
							num2++;
						}
					}
				}
			}
			ManualLogSource log = ((BasePlugin)this).Log;
			string[] obj = new string[6]
			{
				"Managed audio paths prepared: methods=",
				num.ToString(),
				" skipped=",
				num2.ToString(),
				" elapsedMs=",
				null
			};
			TimeSpan elapsed = val.Elapsed;
			obj[5] = ((TimeSpan)(ref elapsed)).TotalMilliseconds.ToString();
			log.LogInfo((object)string.Concat(obj));
		}

		private System.IntPtr StaticObject(System.IntPtr field)
		{
			il2cpp_field_static_get_value(field, out var value);
			return value;
		}

		public override void Load()
		{
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected O, but got Unknown
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, "Chart-driven audio. Restart after changing configuration.");
			removeMuteLimit = ((BasePlugin)this).Config.Bind<bool>("General", "RemoveOffsetMuteLimit", true, "Remove abs(offset)>100ms automatic hitsound mute; keep user offsets and volume settings.");
			soundOffset = ((BasePlugin)this).Config.Bind<double>("Audio", "SoundOffsetMs", 0.0, "Extra offset relative to music: positive delays, negative advances. Applied on next scene/retry.");
			scheduleAhead = ((BasePlugin)this).Config.Bind<double>("Audio", "ScheduleAheadMs", 250.0, "Submit known chart sounds ahead of time to FMOD DSP scheduling (50..1000ms). Pending sounds are cancelled on pause/seek/exit.");
			debug = ((BasePlugin)this).Config.Bind<bool>("Debug", "DebugLogging", true, "Record the first 16 scheduled sounds and periodic counters. Slow submissions and preparation timings are always logged.");
			compatibilityMode = ((BasePlugin)this).Config.Bind<CompatibilityMode>("General", "CompatibilityMode", CompatibilityMode.Auto, "Auto: resolve and validate compatible updates. VerifiedOnly: allow only explicitly verified game builds.");
			foreach (ProcessModule item in (ReadOnlyCollectionBase)Process.GetCurrentProcess().Modules)
			{
				ProcessModule val = item;
				if (val.ModuleName.Equals("GameAssembly.dll", (StringComparison)5))
				{
					module = val.BaseAddress;
					moduleSize = val.ModuleMemorySize;
				}
			}
			if (module == System.IntPtr.Zero)
			{
				throw new InvalidOperationException("Missing GameAssembly");
			}
			CompatibilityResult compatibilityResult = new CompatibilityResult();
			CompatibilityBudget compatibilityBudget = new CompatibilityBudget();
			try
			{
				CompatibilityCatalog compatibilityCatalog = CompatibilityCatalog.Load();
				compatibilityResult.Version = compatibilityCatalog.Version;
				compatibilityResult.PluginHash = NativeImage.Digest(File.ReadAllBytes(typeof(Plugin).Assembly.Location));
				NativeImage nativeImage = new NativeImage(File.ReadAllBytes(Path.Combine(Paths.GameRootPath, "GameAssembly.dll")));
				compatibilityResult.GameHash = nativeImage.Hash;
				((BasePlugin)this).Log.LogInfo((object)("GameAssembly SHA256=" + compatibilityResult.GameHash));
				CompatibilityEnvironment.Validate(compatibilityCatalog, Paths.GameRootPath, compatibilityResult, compatibilityBudget);
				System.IntPtr intPtr = module;
				List<string> layoutObservations = compatibilityResult.LayoutObservations;
				api = CompatibilityEngine.Resolve(compatibilityCatalog, nativeImage, new RuntimeGameMetadata(intPtr, layoutObservations.Add), compatibilityMode.Value, compatibilityResult, compatibilityBudget, [CompilerGenerated] (int rva, int size) =>
				{
					//IL_0018: Unknown result type (might be due to invalid IL or missing references)
					if (rva < 0 || size < 1 || rva > moduleSize - size)
					{
						throw new InvalidDataException("Live entry outside loaded module");
					}
					byte[] array = new byte[size];
					Marshal.Copy(At(rva), array, 0, size);
					return array;
				});
				if (api == null)
				{
					throw new InvalidOperationException(compatibilityResult.Failure);
				}
				((BasePlugin)this).Log.LogInfo((object)string.Concat(new string[8]
				{
					"Compatibility=",
					compatibilityResult.Status,
					" methods=",
					compatibilityCatalog.Methods.Count.ToString(),
					" elapsedMs=",
					compatibilityResult.ElapsedMs.ToString(),
					" source=",
					compatibilityResult.Source
				}));
				logicalField = api.Field("Game:ifapp.Game.LogicalNotePlayer::_Qe");
				controllerField = api.Field("Game:ifapp.Game.Scenes.GameScene::_DN");
				systemField = api.Field("Game.Audio:_J._IF::_ZSA");
				groupsField = api.Field("Game.Audio:_J._IF::_DtA");
				soundManagerField = api.Field("Game.Audio:_J._zf::_psA");
				loadSource = Function<LoadSourceMethod>(api.Method("LoadSource"));
				disposeSource = Function<VoidMethod>(api.Method("DisposeSource"));
				musicPosition = Function<DoubleMethod>(api.Method("MusicPosition"));
				groupSelector = Function<GroupMethod>(api.Method("GroupSelector"));
				noteOffset = Function<NoteOffsetMethod>(api.Method("NoteOffset"));
				loopStart = Function<VoidMethod>(api.Method("LoopStart"));
				loopStop = Function<VoidMethod>(api.Method("LoopStop"));
				mouseHoldActive = Function<BoolMethod>(api.Method("MouseHoldActive"));
				if (removeMuteLimit.Value)
				{
					mutePatch = new RuntimePatch(At(api.MuteJump), new byte[2] { 127, 11 }, new byte[2] { 144, 144 });
					patches.Add(mutePatch);
					((BasePlugin)this).Log.LogInfo((object)"Offset mute limit removed; user offset/volume settings preserved.");
				}
				Hook<VoidMethod>(api.Method("SceneUpdate"), Update, out originalUpdate);
				Hook<VoidMethod>(api.Method("SceneStart"), Start, out originalStart);
				Hook<VoidMethod>(api.Method("SceneDisable"), Disable, out originalDisable);
				Hook<VoidMethod>(api.Method("SceneDestroy"), Destroy, out originalDestroy);
				Hook<VoidMethod>(api.Method("AudioInit"), AudioInit, out originalAudioInit);
				Hook<DispatchMethod>(api.Method("Dispatch"), Dispatch, out originalDispatch);
				Hook<HitMethod>(api.Method("Hit"), Hit, out originalHit);
				Hook<ProcessNoteMethod>(api.Method("ProcessNote"), ProcessNote, out originalProcessNote);
				Hook<EnqueueMethod>(api.Method("Enqueue"), Enqueue, out originalEnqueue);
				WarmManagedPaths();
				((BasePlugin)this).Log.LogInfo((object)"Plugin initialized; chart takeover remains inactive until DSP queue ready is logged.");
			}
			catch (System.Exception ex)
			{
				compatibilityResult.Status = "Incompatible";
				compatibilityResult.Failure = ex.Message;
				compatibilityResult.ElapsedMs = compatibilityBudget.ElapsedMs;
				((BasePlugin)this).Log.LogError((object)("Compatibility disabled: " + (object)ex));
				try
				{
					patches.Dispose();
				}
				catch (System.Exception ex2)
				{
					((BasePlugin)this).Log.LogError((object)ex2);
				}
			}
			finally
			{
				try
				{
					CompatibilityEnvironment.WriteReport(Path.Combine(Paths.BepInExRootPath, "plugins", "InFalsusChartAudio", "compatibility-report.json"), compatibilityResult);
				}
				catch (System.Exception ex3)
				{
					((BasePlugin)this).Log.LogWarning((object)("Could not write compatibility report: " + ex3.Message));
				}
			}
		}

		private void ClearAudio()
		{
			scheduler?.Dispose();
			scheduler = null;
			sources?.Dispose();
			sources = null;
		}

		private void Reset(System.IntPtr self)
		{
			ClearAudio();
			ready = false;
			timeline = null;
			preparedTimeline = null;
			preparedChart = System.IntPtr.Zero;
			preparedUsed = null;
			preparedHeads = null;
			nextPrepareAttempt = 0L;
			holdHeads = new HoldHeadScope();
			scene = self;
			chartIdentity = System.IntPtr.Zero;
			faulted = false;
			wasPlaying = false;
			scheduled = 0;
			suppressed = 0;
			feedbackSuppressed = 0;
			System.Array.Clear((System.Array)scheduledByRoute, 0, scheduledByRoute.Length);
		}

		private void SetOriginalLoop(int offset, bool active)
		{
			System.IntPtr intPtr = Ptr(scene, offset);
			if (!(intPtr == System.IntPtr.Zero) && !(Ptr(intPtr, api.L("LoopSource")) == System.IntPtr.Zero))
			{
				if (active)
				{
					loopStart(intPtr, System.IntPtr.Zero);
				}
				else
				{
					loopStop(intPtr, System.IntPtr.Zero);
				}
			}
		}

		private void RestoreOriginalLoops()
		{
			if (!(scene == System.IntPtr.Zero))
			{
				System.IntPtr intPtr = StaticObject(controllerField);
				if (!(intPtr == System.IntPtr.Zero))
				{
					System.IntPtr intPtr2 = Ptr(intPtr, api.L("ControllerMain"));
					System.IntPtr intPtr3 = Ptr(intPtr, api.L("ControllerSecondary"));
					SetOriginalLoop(api.L("SceneLoopMain"), intPtr2 != System.IntPtr.Zero && I32(intPtr2, api.L("ControllerSetCount")) > 0);
					SetOriginalLoop(api.L("SceneLoopSecondary"), intPtr3 != System.IntPtr.Zero && I32(intPtr3, api.L("ControllerSetCount")) > 0);
					SetOriginalLoop(api.L("SceneLoopMouse"), mouseHoldActive(System.IntPtr.Add(intPtr, api.L("ControllerMouse")), System.IntPtr.Zero));
				}
			}
		}

		private void Fail(System.Exception e)
		{
			ClearAudio();
			if (ready)
			{
				try
				{
					RestoreOriginalLoops();
				}
				catch (System.Exception ex)
				{
					((BasePlugin)this).Log.LogError((object)("Original loop restore: " + (object)ex));
				}
			}
			ready = false;
			timeline = null;
			if (!faulted)
			{
				((BasePlugin)this).Log.LogError((object)("Chart audio disabled for this scene; original audio restored. " + (object)e));
			}
			faulted = true;
		}

		private System.IntPtr MemoryData(System.IntPtr owner, int off, int size, out int count)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			System.IntPtr intPtr = Ptr(owner, off);
			int num = I32(owner, off + api.L("MemoryStart")) & 0x7FFFFFFF;
			count = I32(owner, off + api.L("MemoryCount")) & 0x7FFFFFFF;
			if (intPtr == System.IntPtr.Zero)
			{
				if (count == 0)
				{
					return System.IntPtr.Zero;
				}
				throw new InvalidOperationException("Missing chart array");
			}
			long num2 = Marshal.ReadInt64(intPtr, api.L("ArrayLength"));
			if (num2 < 0 || num2 > 2000000 || num > num2 || count > num2 - num)
			{
				throw new InvalidOperationException("Invalid chart memory range");
			}
			return System.IntPtr.Add(intPtr, checked(api.L("ArrayData") + num * size));
		}

		private System.IntPtr SoundOf(System.IntPtr instance)
		{
			if (!(instance == System.IntPtr.Zero))
			{
				return Ptr(instance, api.L("SoundHandle"));
			}
			return System.IntPtr.Zero;
		}

		private System.IntPtr LoopSound(System.IntPtr self, int offset)
		{
			System.IntPtr intPtr = Ptr(self, offset);
			if (!(intPtr == System.IntPtr.Zero))
			{
				return SoundOf(Ptr(intPtr, api.L("LoopSource")));
			}
			return System.IntPtr.Zero;
		}

		private System.IntPtr AcquireSource(int route)
		{
			System.IntPtr intPtr = StaticObject(soundManagerField);
			System.IntPtr intPtr2 = Ptr(scene, api.L("SceneAttackSound"));
			if (intPtr == System.IntPtr.Zero || intPtr2 == System.IntPtr.Zero)
			{
				return System.IntPtr.Zero;
			}
			System.IntPtr intPtr3 = Ptr(intPtr2, api.L("SoundCallback"));
			if (intPtr3 == System.IntPtr.Zero)
			{
				return System.IntPtr.Zero;
			}
			byte kind = route switch
			{
				4 => Marshal.ReadByte(scene, api.L("SceneKeyboardSample")), 
				3 => Marshal.ReadByte(scene, api.L("SceneTransitionSample")), 
				2 => 57, 
				1 => 63, 
				0 => Marshal.ReadByte(scene, api.L("SceneAttackSample")), 
				_ => Marshal.ReadByte(scene, api.L("SceneSideSample")), 
			};
			System.IntPtr result = loadSource(intPtr, kind, (route >= 4) ? 1 : ((route == 1) ? 2 : 3), intPtr3, range: false, -1.0, -1.0, flag: false, 0, System.IntPtr.Zero);
			ManualLogSource log = ((BasePlugin)this).Log;
			string[] obj = new string[6] { "Retained paused source: route=", null, null, null, null, null };
			AudioRoute audioRoute = (AudioRoute)route;
			obj[1] = ((object)audioRoute/*cast due to .constrained prefix*/).ToString();
			obj[2] = " kind=";
			obj[3] = kind.ToString();
			obj[4] = " wrapper=";
			obj[5] = result.ToString("X");
			log.LogInfo((object)string.Concat(obj));
			return result;
		}

		private bool BuildTimeline()
		{
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b6c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_042b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d89: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d8e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0dae: Unknown result type (might be due to invalid IL or missing references)
			//IL_0db3: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0547: Unknown result type (might be due to invalid IL or missing references)
			//IL_054c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Unknown result type (might be due to invalid IL or missing references)
			//IL_063e: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0990: Unknown result type (might be due to invalid IL or missing references)
			//IL_0995: Unknown result type (might be due to invalid IL or missing references)
			long timestamp = Stopwatch.GetTimestamp();
			if (timestamp < nextPrepareAttempt)
			{
				return false;
			}
			nextPrepareAttempt = timestamp + Stopwatch.Frequency / 10;
			Stopwatch val = Stopwatch.StartNew();
			System.IntPtr intPtr = StaticObject(logicalField);
			if (intPtr == System.IntPtr.Zero)
			{
				return false;
			}
			System.IntPtr intPtr2 = Ptr(intPtr, api.L("LogicalChart"));
			if (intPtr2 == System.IntPtr.Zero)
			{
				return false;
			}
			System.IntPtr[] array = new System.IntPtr[6]
			{
				SoundOf(Ptr(scene, api.L("SceneAttackSound"))),
				LoopSound(scene, api.L("SceneLoopMain")),
				LoopSound(scene, api.L("SceneLoopMouse")),
				SoundOf(Ptr(scene, api.L("SceneTransitionSound"))),
				SoundOf(Ptr(scene, api.L("SceneKeyboardSound"))),
				SoundOf(Ptr(scene, api.L("SceneSideSound")))
			};
			TimeSpan elapsed;
			if (preparedChart != intPtr2)
			{
				if (preparedChart != System.IntPtr.Zero)
				{
					ClearAudio();
				}
				int num = I32(intPtr2, api.L("ChartCount"));
				if (num == 0)
				{
					return false;
				}
				if (num < 0 || num > 200000)
				{
					throw new InvalidOperationException("Invalid judgement count");
				}
				int count;
				System.IntPtr intPtr3 = MemoryData(intPtr2, api.L("ChartRecords"), api.L("RecordSize"), out count);
				if (num > count)
				{
					throw new InvalidOperationException("Incomplete judgement array");
				}
				AudioTimeline audioTimeline = new AudioTimeline();
				HashSet<long> val2 = new HashSet<long>();
				int[] array2 = new int[6];
				int merged = 0;
				Dictionary<long, List<AudioCue>> val3 = NoteJudgements.Snapshot(Ptr(intPtr2, api.L("ChartByNote")), num, api.L("RecordSize"), api.L("RecordId"), api.L("RecordKind"), api.L("RecordTime"));
				HoldHeadScope holdHeadScope = new HoldHeadScope();
				for (int i = 0; i < num; i++)
				{
					System.IntPtr intPtr4 = System.IntPtr.Add(intPtr3, i * api.L("RecordSize"));
					long num2 = Marshal.ReadInt64(intPtr4, api.L("RecordId"));
					int num3 = I32(intPtr4, api.L("RecordKind"));
					double num4 = F64(intPtr4, api.L("RecordTime"));
					if (num2 < 0 || num2 >= num || num3 < 0 || num3 >= 6 || !val2.Add(num2) || !Finite(num4) || num4 < -60000.0 || num4 > 86400000.0)
					{
						throw new InvalidOperationException("Unexpected judgement record");
					}
					array2[num3]++;
					if (num3 == 1 || num3 == 2 || num3 == 5)
					{
						audioTimeline.Events.Add(new AudioCue
						{
							Id = num2,
							TimeMs = num4,
							Route = AudioRoute.Attack
						});
					}
				}
				List<AudioCue> val4 = new List<AudioCue>();
				System.IntPtr intPtr5 = Ptr(intPtr, api.L("LogicalNotes"));
				int num5 = 0;
				int num6 = 0;
				int num7 = 0;
				int num8 = 0;
				int[] array3 = new int[5];
				int[] array4 = new int[30];
				if (intPtr5 == System.IntPtr.Zero)
				{
					return false;
				}
				System.IntPtr intPtr6 = Ptr(intPtr5, api.L("ListArray"));
				int num9 = I32(intPtr5, api.L("ListCount"));
				if (intPtr6 == System.IntPtr.Zero || num9 < 0 || num9 > 200000 || num9 > Marshal.ReadInt64(intPtr6, api.L("ArrayLength")))
				{
					throw new InvalidOperationException("Invalid note list");
				}
				List<AudioCue> val5 = default(List<AudioCue>);
				Enumerator<AudioCue> enumerator;
				for (int j = 0; j < num9; j++)
				{
					System.IntPtr intPtr7 = System.IntPtr.Add(intPtr6, checked(api.L("ArrayData") + j * api.L("NoteSize")));
					int num10 = I32(intPtr7, api.L("NoteType"));
					int num11 = I32(intPtr7, api.L("NoteLane"));
					if (num11 < 0 || num11 >= 5 || num10 < 0 || num10 >= 6)
					{
						throw new InvalidOperationException("Unrecognised chart note category/type; refusing partial takeover");
					}
					array3[num11]++;
					array4[num11 * 6 + num10]++;
					if (NoteAudioPolicy.OwnsKeyboardFeedback(num10, num11))
					{
						long num12 = Marshal.ReadInt64(intPtr7);
						if (!val3.TryGetValue(num12, ref val5))
						{
							throw new InvalidOperationException("Missing keyboard note judgements");
						}
						holdHeadScope.Register(num12);
						AudioRoute audioRoute = NoteAudioPolicy.FeedbackRoute(I32(intPtr7, api.L("NoteKeyStart")), I32(intPtr7, api.L("NoteKeyEnd")));
						enumerator = val5.GetEnumerator();
						try
						{
							while (enumerator.MoveNext())
							{
								AudioCue current = enumerator.Current;
								current.Route = audioRoute;
								audioTimeline.Events.Add(current);
								if (audioRoute == AudioRoute.SideKeyHit)
								{
									num8++;
								}
							}
						}
						finally
						{
							((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
						}
						if (NoteAudioPolicy.IsSide(num11))
						{
							num5++;
						}
						if (num10 == 2)
						{
							num6++;
							if (NoteAudioPolicy.IsSide(num11))
							{
								num7++;
							}
						}
					}
					if (num10 == 2 || num10 == 5)
					{
						double num13 = noteOffset(intPtr7, System.IntPtr.Zero);
						double num14 = (double)I32(intPtr7, api.L("NoteStart")) + num13;
						double num15 = (double)I32(intPtr7, api.L("NoteEnd")) + num13;
						if (num14 < -60000.0 || num15 > 86400000.0 || num15 < num14)
						{
							throw new InvalidOperationException("Invalid hold interval");
						}
						if (num15 > num14)
						{
							val4.Add(new AudioCue
							{
								Id = -1 - (long)j * 2L,
								TimeMs = num14,
								EndMs = num15,
								Loop = true,
								Route = ((num10 == 2) ? AudioRoute.Hold : AudioRoute.MouseHold)
							});
						}
					}
				}
				enumerator = AudioTimeline.MergeLoops((System.Collections.Generic.IEnumerable<AudioCue>)val4, AudioRoute.Hold).GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						AudioCue current2 = enumerator.Current;
						audioTimeline.Events.Add(current2);
					}
				}
				finally
				{
					((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
				List<AudioCue> val6 = AudioTimeline.MergeLoops((System.Collections.Generic.IEnumerable<AudioCue>)val4, AudioRoute.MouseHold);
				enumerator = val6.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						AudioCue current3 = enumerator.Current;
						audioTimeline.Events.Add(current3);
						audioTimeline.Events.Add(new AudioCue
						{
							Id = current3.Id - 1,
							TimeMs = current3.TimeMs,
							Route = AudioRoute.MouseTransition
						});
						audioTimeline.Events.Add(new AudioCue
						{
							Id = current3.Id - 2,
							TimeMs = current3.EndMs,
							Route = AudioRoute.MouseTransition
						});
					}
				}
				finally
				{
					((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
				AudioTimeline audioTimeline2 = new AudioTimeline();
				audioTimeline2.Events.AddRange((System.Collections.Generic.IEnumerable<AudioCue>)AudioTimeline.CoalesceAttacks(audioTimeline.Events, 10.0, out merged));
				if (audioTimeline2.Events.Count == 0)
				{
					return false;
				}
				bool[] array5 = new bool[array.Length];
				enumerator = audioTimeline2.Events.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						array5[(int)enumerator.Current.Route] = true;
					}
				}
				finally
				{
					((System.IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
				}
				preparedTimeline = audioTimeline2;
				preparedHeads = holdHeadScope;
				preparedUsed = array5;
				preparedChart = intPtr2;
				preparedDescription = string.Concat(new string[24]
				{
					"events=",
					audioTimeline2.Events.Count.ToString(),
					" judgementKinds=",
					string.Join<int>(",", (System.Collections.Generic.IEnumerable<int>)array2),
					" mouseAttacks=",
					array2[5].ToString(),
					" holdIntervals=",
					val4.Count.ToString(),
					" mouseLoopUnions=",
					val6.Count.ToString(),
					" mergedAttacks=",
					merged.ToString(),
					" keyboardHolds=",
					num6.ToString(),
					" sideNotes=",
					num5.ToString(),
					" sideHolds=",
					num7.ToString(),
					" sideHeads=",
					num8.ToString(),
					" laneCounts=",
					string.Join<int>(",", (System.Collections.Generic.IEnumerable<int>)array3),
					" laneTypeCounts=",
					string.Join<int>(",", (System.Collections.Generic.IEnumerable<int>)array4)
				});
				ManualLogSource log = ((BasePlugin)this).Log;
				string text = preparedDescription;
				elapsed = val.Elapsed;
				log.LogInfo((object)("Chart snapshot prepared: " + text + " elapsedMs=" + ((TimeSpan)(ref elapsed)).TotalMilliseconds));
			}
			if (sources == null)
			{
				sources = new SourceLeases(AcquireSource, SoundOf, [CompilerGenerated] (System.IntPtr p) =>
				{
					disposeSource(p, System.IntPtr.Zero);
				}, FmodScheduler.IsReady);
			}
			for (int num16 = 0; num16 < preparedUsed.Length; num16++)
			{
				if (!preparedUsed[num16])
				{
					continue;
				}
				array[num16] = sources.Resolve(num16, array[num16]);
				if (!FmodScheduler.Probe(array[num16], out var result, out var state))
				{
					long timestamp2 = Stopwatch.GetTimestamp();
					if (timestamp2 - lastStatus > Stopwatch.Frequency * 5)
					{
						lastStatus = timestamp2;
						ManualLogSource log2 = ((BasePlugin)this).Log;
						string[] obj = new string[9] { "Waiting for game sound source: ", null, null, null, null, null, null, null, null };
						AudioRoute audioRoute2 = (AudioRoute)num16;
						obj[1] = ((object)audioRoute2/*cast due to .constrained prefix*/).ToString();
						obj[2] = " sound=";
						obj[3] = array[num16].ToString("X");
						obj[4] = " result=";
						obj[5] = result.ToString();
						obj[6] = " openState=";
						obj[7] = state.ToString();
						obj[8] = "; original audio remains active.";
						log2.LogInfo((object)string.Concat(obj));
					}
					return false;
				}
			}
			if (!Finite(soundOffset.Value) || Math.Abs(soundOffset.Value) > 5000.0 || !Finite(scheduleAhead.Value) || scheduleAhead.Value < 50.0 || scheduleAhead.Value > 1000.0)
			{
				throw new InvalidOperationException("Invalid SoundOffsetMs/ScheduleAheadMs");
			}
			System.IntPtr intPtr8 = StaticObject(systemField);
			if (intPtr8 == System.IntPtr.Zero)
			{
				return false;
			}
			System.IntPtr intPtr9 = Marshal.AllocHGlobal(api.L("GroupsSize"));
			System.IntPtr[] array6 = new System.IntPtr[array.Length];
			try
			{
				ReadStaticValue(groupsField, intPtr9);
				array6[0] = groupSelector(intPtr9, 3, System.IntPtr.Zero);
				array6[1] = groupSelector(intPtr9, 2, System.IntPtr.Zero);
				array6[2] = array6[0];
				array6[3] = array6[0];
				array6[4] = groupSelector(intPtr9, 1, System.IntPtr.Zero);
				array6[5] = array6[4];
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr9);
			}
			FmodScheduler fmodScheduler = new FmodScheduler(intPtr8, array, array6, preparedUsed);
			Stopwatch val7 = Stopwatch.StartNew();
			try
			{
				fmodScheduler.WarmUp(preparedUsed);
				SetOriginalLoop(api.L("SceneLoopMain"), active: false);
				SetOriginalLoop(api.L("SceneLoopSecondary"), active: false);
				SetOriginalLoop(api.L("SceneLoopMouse"), active: false);
			}
			catch
			{
				fmodScheduler.Dispose();
				throw;
			}
			scheduler = fmodScheduler;
			timeline = preparedTimeline;
			holdHeads = preparedHeads;
			chartIdentity = intPtr2;
			appliedOffset = soundOffset.Value;
			ready = true;
			ManualLogSource log3 = ((BasePlugin)this).Log;
			string[] obj3 = new string[14]
			{
				"DSP queue ready: ",
				preparedDescription,
				" sampleRate=",
				fmodScheduler.SampleRate.ToString(),
				" aheadMs=",
				scheduleAhead.Value.ToString(),
				" offsetMs=",
				appliedOffset.ToString(),
				" gameOffsetMs=",
				I32(scene, api.L("SceneOffset")).ToString(),
				" warmUpMs=",
				null,
				null,
				null
			};
			elapsed = val7.Elapsed;
			obj3[11] = ((TimeSpan)(ref elapsed)).TotalMilliseconds.ToString();
			obj3[12] = " attemptMs=";
			elapsed = val.Elapsed;
			obj3[13] = ((TimeSpan)(ref elapsed)).TotalMilliseconds.ToString();
			log3.LogInfo((object)string.Concat(obj3));
			return true;
		}

		private void Start(System.IntPtr self, System.IntPtr mi)
		{
			Reset(self);
			originalStart(self, mi);
		}

		private void AudioInit(System.IntPtr self, System.IntPtr mi)
		{
			Reset(self);
			originalAudioInit(self, mi);
		}

		private void Disable(System.IntPtr self, System.IntPtr mi)
		{
			if (scene == self)
			{
				Reset(System.IntPtr.Zero);
			}
			originalDisable(self, mi);
		}

		private void Destroy(System.IntPtr self, System.IntPtr mi)
		{
			if (scene == self)
			{
				Reset(System.IntPtr.Zero);
			}
			originalDestroy(self, mi);
		}

		private void Update(System.IntPtr self, System.IntPtr mi)
		{
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Expected O, but got Unknown
			try
			{
				if (scene != self)
				{
					Reset(self);
				}
				if (enabled.Value && !faulted && !ready)
				{
					BuildTimeline();
				}
			}
			catch (System.Exception e)
			{
				Fail(e);
			}
			originalUpdate(self, mi);
			if (!ready)
			{
				return;
			}
			try
			{
				if (!enabled.Value)
				{
					RestoreOriginalLoops();
					Reset(self);
					return;
				}
				System.IntPtr intPtr = StaticObject(logicalField);
				if (intPtr == System.IntPtr.Zero || Ptr(intPtr, api.L("LogicalChart")) != chartIdentity)
				{
					Reset(self);
					return;
				}
				System.IntPtr audio = Ptr(self, api.L("SceneMusic"));
				if (!(audio != System.IntPtr.Zero) || I32(audio, api.L("MusicState")) != 2)
				{
					if (wasPlaying)
					{
						scheduler.StopAll();
						timeline.Reset(skipAtCurrentTime: true);
						wasPlaying = false;
					}
					return;
				}
				double num = musicPosition(audio, System.IntPtr.Zero) * 1000.0;
				double rate = F32(audio, api.L("MusicRate"));
				if (!Finite(num) || !Finite(rate) || rate <= 0.0 || rate > 10.0)
				{
					throw new InvalidOperationException("Invalid music clock/rate");
				}
				if (wasPlaying && Math.Abs(rate - lastRate) > 0.0001)
				{
					scheduler.StopAll();
					timeline.Reset(skipAtCurrentTime: true);
				}
				wasPlaying = true;
				lastRate = rate;
				timeline.Advance(num - appliedOffset, scheduleAhead.Value * rate, delegate(AudioCue cue, double _)
				{
					double num3 = musicPosition(audio, System.IntPtr.Zero) * 1000.0;
					long timestamp2 = Stopwatch.GetTimestamp();
					scheduler.Submit(cue, num3, appliedOffset, rate);
					scheduled++;
					scheduledByRoute[(int)cue.Route]++;
					double num4 = (double)(Stopwatch.GetTimestamp() - timestamp2) * 1000.0 / (double)Stopwatch.Frequency;
					if (num4 > 20.0)
					{
						((BasePlugin)this).Log.LogWarning((object)string.Concat(new string[6]
						{
							"Slow chart submit: route=",
							((object)cue.Route/*cast due to .constrained prefix*/).ToString(),
							" elapsedMs=",
							num4.ToString(),
							" musicMs=",
							num3.ToString()
						}));
					}
					if (debug.Value && scheduled <= 16)
					{
						((BasePlugin)this).Log.LogInfo((object)string.Concat(new string[14]
						{
							"SCHEDULE id=",
							cue.Id.ToString(),
							" route=",
							((object)cue.Route/*cast due to .constrained prefix*/).ToString(),
							" startMs=",
							cue.TimeMs.ToString(),
							" endMs=",
							(cue.Loop ? cue.EndMs : 0.0).ToString(),
							" submittedMs=",
							num3.ToString(),
							" leadMs=",
							(cue.TimeMs + appliedOffset - num3).ToString(),
							" submitCostMs=",
							num4.ToString()
						}));
					}
				}, (Action)([CompilerGenerated] () =>
				{
					scheduler.StopAll();
				}));
				long timestamp = Stopwatch.GetTimestamp();
				if (debug.Value && timestamp - lastStatus > Stopwatch.Frequency * 5)
				{
					lastStatus = timestamp;
					System.IntPtr intPtr2 = StaticObject(controllerField);
					double num2 = ((intPtr2 == System.IntPtr.Zero) ? (0.0 / 0.0) : (F64(intPtr2, api.L("ControllerClock")) * 1000.0));
					((BasePlugin)this).Log.LogInfo((object)string.Concat(new string[16]
					{
						"CLOCK musicMs=",
						num.ToString(),
						" calibratedMs=",
						num2.ToString(),
						" deltaMs=",
						(num2 - num).ToString(),
						" scheduled=",
						scheduled.ToString(),
						" byRoute=",
						string.Join<int>(",", (System.Collections.Generic.IEnumerable<int>)scheduledByRoute),
						" suppressed=",
						suppressed.ToString(),
						" keyboardFeedbackSuppressed=",
						feedbackSuppressed.ToString(),
						" rate=",
						rate.ToString()
					}));
				}
			}
			catch (System.Exception e2)
			{
				Fail(e2);
			}
		}

		private static bool IsOwnedEvent(byte kind)
		{
			if (kind != 0 && kind != 2 && kind != 4 && kind != 5)
			{
				return kind == 6;
			}
			return true;
		}

		private void ProcessNote(System.IntPtr self, System.IntPtr records, System.IntPtr note, System.IntPtr queue, System.IntPtr mi)
		{
			HoldHeadScope holdHeadScope = holdHeads;
			bool flag = ready && enabled.Value && note != System.IntPtr.Zero && NoteAudioPolicy.OwnsKeyboardFeedback(I32(note, api.L("NoteType")), I32(note, api.L("NoteLane")));
			System.IntPtr previous = holdHeadScope.Enter(flag, flag ? Marshal.ReadInt64(note) : 0, queue);
			try
			{
				originalProcessNote(self, records, note, queue, mi);
			}
			finally
			{
				holdHeadScope.Restore(previous);
			}
		}

		private void Enqueue(System.IntPtr self, System.IntPtr evt, System.IntPtr mi)
		{
			if (ready && enabled.Value && evt != System.IntPtr.Zero && holdHeads.Owns(self, Marshal.ReadByte(evt, api.L("EventKind")), I32(evt, api.L("EventPayload"))))
			{
				suppressed++;
				feedbackSuppressed++;
			}
			else
			{
				originalEnqueue(self, evt, mi);
			}
		}

		private void Dispatch(System.IntPtr self, System.IntPtr results, System.IntPtr evt, System.IntPtr mi)
		{
			if (ready && enabled.Value && scene == self && evt != System.IntPtr.Zero && IsOwnedEvent(Marshal.ReadByte(evt, api.L("EventKind"))))
			{
				suppressed++;
			}
			else
			{
				originalDispatch(self, results, evt, mi);
			}
		}

		private void Hit(System.IntPtr self, byte kind, double offset, System.IntPtr mi)
		{
			if (ready && enabled.Value && scene == self)
			{
				suppressed++;
			}
			else
			{
				originalHit(self, kind, offset, mi);
			}
		}

		public override bool Unload()
		{
			ClearAudio();
			if (ready)
			{
				try
				{
					RestoreOriginalLoops();
				}
				catch (System.Exception ex)
				{
					((BasePlugin)this).Log.LogError((object)ex);
				}
			}
			ready = false;
			try
			{
				patches.Dispose();
				return true;
			}
			catch (System.Exception ex2)
			{
				((BasePlugin)this).Log.LogError((object)ex2);
				return false;
			}
		}
	}
	internal sealed class RuntimeGameMetadata : IGameMetadata
	{
		private readonly System.IntPtr module;

		private readonly Action<string> observe;

		private readonly Dictionary<string, System.IntPtr> classes = new Dictionary<string, System.IntPtr>();

		[field: CompilerGenerated]
		public IDictionary<string, System.IntPtr> Fields
		{
			[CompilerGenerated]
			get;
		} = (IDictionary<string, System.IntPtr>)(object)new Dictionary<string, System.IntPtr>();

		public RuntimeGameMetadata(System.IntPtr module, Action<string> observe = null)
		{
			this.module = module;
			this.observe = observe;
		}

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_domain_get();

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_domain_assembly_open(System.IntPtr domain, string name);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_assembly_get_image(System.IntPtr assembly);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_class_from_name(System.IntPtr image, string ns, string name);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_class_get_nested_types(System.IntPtr klass, ref System.IntPtr iterator);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_class_get_name(System.IntPtr klass);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_class_get_methods(System.IntPtr klass, ref System.IntPtr iterator);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_method_get_name(System.IntPtr method);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_method_get_return_type(System.IntPtr method);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern uint il2cpp_method_get_param_count(System.IntPtr method);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_method_get_param(System.IntPtr method, uint index);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern uint il2cpp_method_get_flags(System.IntPtr method, out uint implementation);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		[return: MarshalAs((UnmanagedType)3)]
		private static extern bool il2cpp_method_is_generic(System.IntPtr method);

		[DllImport("GameAssembly", CallingConvention = (CallingConvention)2)]
		private static extern System.IntPtr il2cpp_t