Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Multipla v0.5.0
plugins/Multipla.dll
Decompiled an hour ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Coroner; using Dissonance; using Dissonance.Audio.Capture; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Multipla.Diagnostics; using Multipla.Il; using Multipla.Networking; using Multipla.Performance; using Multipla.PortableMap; using Multipla.Recordings; using Multipla.Recordings.Web; using Multipla.Stamina; using NAudio.Wave; using TMPro; using Unity.AI.Navigation; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Experimental.Rendering; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.LowLevel; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Multipla")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Multipla")] [assembly: AssemblyTitle("Multipla")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : 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(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } internal static class IsExternalInit { } } namespace Multipla { [BepInPlugin("jurtomasz13.Multipla", "Multipla", "0.5.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { public const string Guid = "jurtomasz13.Multipla"; public const string Name = "Multipla"; public const string Version = "0.5.0"; internal static ManualLogSource Log { get; private set; } private void Awake() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Harmony val = new Harmony("jurtomasz13.Multipla"); StaminaState.Install(((BaseUnityPlugin)this).Config, val); val.PatchAll(typeof(NamedMessages)); ConfigSync.Install(); OutsideNavMesh.Install(((BaseUnityPlugin)this).Config, val); JllPropNavMesh.Install(((BaseUnityPlugin)this).Config, val); PortableMapPatches.Install(((BaseUnityPlugin)this).Config, val); RecordingPatches.Install(((BaseUnityPlugin)this).Config, val); RoundProfiler.Install(((BaseUnityPlugin)this).Config, val); Log.LogInfo((object)"Multipla 0.5.0 loaded."); } } } namespace Multipla.Stamina { internal static class StaminaIl { public static readonly IlPattern StartThreshold = new IlPattern("Update: start threshold 0.3", 1, new IlStep("ldarg.0"), new IlStep("ldfld", "sprintMeter"), new IlStep("ldc.r4", null, 0.3f)); public static readonly IlPattern RecoverThreshold = new IlPattern("LateUpdate: recover threshold 0.2", 1, new IlStep("ldarg.0"), new IlStep("ldfld", "sprintMeter"), new IlStep("ldc.r4", null, 0.2f)); public static readonly IlPattern DrainTime = new IlPattern("LateUpdate: drain by sprintTime", 2, new IlStep("ldfld", "sprintTime"), new IlStep("div")); public static readonly IlPattern JumpCost = new IlPattern("Jump_performed: jump cost 0.08", 1, new IlStep("ldfld", "sprintMeter"), new IlStep("ldc.r4", null, 0.08f), new IlStep("sub")); } [HarmonyPatch(typeof(PlayerControllerB))] internal static class StaminaPatches { private static readonly Color ExhaustedColor = new Color(0.9f, 0.1f, 0f); private static Color? normalColor; private static float emptyAt = float.NegativeInfinity; private static float SecondsSinceEmpty => Time.time - emptyAt; public static float StartThreshold() { return StaminaRules.StartThreshold(StaminaState.Active, SecondsSinceEmpty); } public static float RecoverThreshold() { return StaminaRules.RecoverThreshold(StaminaState.Active); } public static float DrainTime(PlayerControllerB player) { return StaminaRules.DrainTime(player.sprintTime, StaminaState.Active); } public static float JumpCost() { return StaminaRules.JumpCost(StaminaState.Active); } [HarmonyPatch("Update")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> UpdateTranspiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); HarmonyIl.TryReplace(list, StaminaIl.StartThreshold, 2, () => (CodeInstruction[])(object)new CodeInstruction[1] { CodeInstruction.Call(typeof(StaminaPatches), "StartThreshold", (Type[])null, (Type[])null) }); return list; } [HarmonyPatch("LateUpdate")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> LateUpdateTranspiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); HarmonyIl.TryReplace(list, StaminaIl.RecoverThreshold, 2, () => (CodeInstruction[])(object)new CodeInstruction[1] { CodeInstruction.Call(typeof(StaminaPatches), "RecoverThreshold", (Type[])null, (Type[])null) }); HarmonyIl.TryReplace(list, StaminaIl.DrainTime, 0, () => (CodeInstruction[])(object)new CodeInstruction[1] { CodeInstruction.Call(typeof(StaminaPatches), "DrainTime", (Type[])null, (Type[])null) }); return list; } [HarmonyPatch("Jump_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> JumpTranspiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); HarmonyIl.TryReplace(list, StaminaIl.JumpCost, 1, () => (CodeInstruction[])(object)new CodeInstruction[1] { CodeInstruction.Call(typeof(StaminaPatches), "JumpCost", (Type[])null, (Type[])null) }); return list; } [HarmonyPatch("LateUpdate")] [HarmonyPostfix] private static void DrawWholeMeter(PlayerControllerB __instance) { //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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: 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_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { if (__instance.sprintMeter < 0.1f) { emptyAt = Time.time; } Image sprintMeterUI = __instance.sprintMeterUI; Color valueOrDefault = normalColor.GetValueOrDefault(); if (!normalColor.HasValue) { valueOrDefault = ((Graphic)sprintMeterUI).color; normalColor = valueOrDefault; } if (!StaminaState.Active.Enabled) { ((Graphic)sprintMeterUI).color = normalColor.Value; return; } sprintMeterUI.fillAmount = StaminaRules.HudFill(__instance.sprintMeter); ((Graphic)sprintMeterUI).color = ((__instance.isExhausted || StaminaRules.IsResting(StaminaState.Active, SecondsSinceEmpty)) ? ExhaustedColor : normalColor.Value); } } } internal readonly record struct StaminaSettings(bool Enabled, float DurationMultiplier, float JumpCostMultiplier, float RestAfterEmptySeconds) { public static readonly StaminaSettings Vanilla = new StaminaSettings(Enabled: false, 1f, 1f, 0f); } internal static class StaminaRules { public const float VanillaEmpty = 0.1f; public const float VanillaStartThreshold = 0.3f; public const float VanillaRecoverThreshold = 0.2f; public const float VanillaJumpCost = 0.08f; public const float HudEmptyFill = 0.29767f; public const float HudFullFill = 0.911f; public static float ToVisible(float meter) { return Clamp01((meter - 0.1f) / 0.9f); } public static float StartThreshold(StaminaSettings settings, float secondsSinceEmpty) { if (!settings.Enabled) { return 0.3f; } if (!IsResting(settings, secondsSinceEmpty)) { return 0.1f; } return float.PositiveInfinity; } public static bool IsResting(StaminaSettings settings, float secondsSinceEmpty) { if (settings.Enabled) { return secondsSinceEmpty < settings.RestAfterEmptySeconds; } return false; } public static float RecoverThreshold(StaminaSettings settings) { if (!settings.Enabled) { return 0.2f; } return 0.1f; } public static float DrainTime(float sprintTime, StaminaSettings settings) { if (!settings.Enabled) { return sprintTime; } return sprintTime * settings.DurationMultiplier; } public static float JumpCost(StaminaSettings settings) { if (!settings.Enabled) { return 0.08f; } return 0.08f * settings.JumpCostMultiplier; } public static float HudFill(float meter) { return 0.29767f + 0.61333f * ToVisible(meter); } private static float Clamp01(float value) { return Math.Min(1f, Math.Max(0f, value)); } } internal static class StaminaState { private static ConfigEntry<bool> enabled = null; private static ConfigEntry<float> durationMultiplier = null; private static ConfigEntry<float> jumpCostMultiplier = null; private static ConfigEntry<float> restAfterEmptySeconds = null; private static bool patched; public static StaminaSettings Active { get; private set; } = StaminaSettings.Vanilla; public static StaminaSettings Local => new StaminaSettings(patched && enabled.Value, durationMultiplier.Value, jumpCostMultiplier.Value, restAfterEmptySeconds.Value); public static void Install(ConfigFile config, Harmony harmony) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected O, but got Unknown enabled = config.Bind<bool>("Stamina", "Enabled", true, "Pasek pokazuje całą staminę, bez ukrytego zapasu i bez progu startu biegu (poza krótką przerwą po całkowitym wyczerpaniu, RestAfterEmptySeconds). W grze wieloosobowej obowiązuje ustawienie hosta. Wyłączone przy starcie gry nie zmienia niczego (np. gdy używasz innego moda do staminy)."); durationMultiplier = config.Bind<float>("Stamina", "DurationMultiplier", 1.5f, new ConfigDescription("Ile razy dłużej trwa pełny bieg niż w grze bez moda. Odnawianie pełnego paska trwa tyle co w grze.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 5f), Array.Empty<object>())); jumpCostMultiplier = config.Bind<float>("Stamina", "JumpCostMultiplier", 0.5f, new ConfigDescription("Koszt skoku względem gry bez moda: 0.5 to połowa, 0.67 to o 1/3 mniej.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>())); restAfterEmptySeconds = config.Bind<float>("Stamina", "RestAfterEmptySeconds", 1.5f, new ConfigDescription("Po całkowitym zużyciu staminy bieg da się zacząć dopiero po tylu sekundach (w grze bez moda trzeba czekać, aż wróci 30% paska). 0 to bez przerwy. Obowiązuje ustawienie hosta.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); patched = enabled.Value; if (patched) { harmony.PatchAll(typeof(StaminaPatches)); } Active = Local; } public static void ApplyHostSettings(StaminaSettings settings) { Active = settings; } public static void ResetToLocal() { Active = Local; } } } namespace Multipla.Recordings { internal sealed class Resampler { private readonly double step; private double position; private float previous; public Resampler(int fromRate, int toRate) { step = (double)fromRate / (double)toRate; } public void Process(float[] data, int offset, int count, int channels, Action<float> output) { for (int i = offset; i + channels <= offset + count; i += channels) { float num = 0f; for (int j = 0; j < channels; j++) { num += data[i + j]; } num /= (float)channels; while (position < 1.0) { output(previous + (num - previous) * (float)position); position += step; } position -= 1.0; previous = num; } } } internal sealed class AudioRing { private readonly short[] buffer; private long written; public AudioRing(int capacity) { buffer = new short[capacity]; } public void Write(float sample) { float num = Math.Max(-1f, Math.Min(1f, sample)); buffer[written % buffer.Length] = (short)(num * 32767f); written++; } public short[] Latest(int count) { int num = (int)Math.Min(Math.Min(count, buffer.Length), written); short[] array = new short[num]; for (int i = 0; i < num; i++) { array[i] = buffer[(written - num + i) % buffer.Length]; } return array; } public void Clear() { written = 0L; } } internal sealed class SampleQueue { private readonly float[] buffer; private readonly int prefill; private long head; private long tail; private bool primed; private int Count => (int)(tail - head); public SampleQueue(int prefill, int maxLag) { this.prefill = prefill; buffer = new float[maxLag]; } public void Enqueue(float sample) { if (Count == buffer.Length) { head = tail - prefill; } buffer[tail % buffer.Length] = sample; tail++; } public float DequeueOrSilence() { if (!primed && Count >= prefill) { primed = true; } if (!primed) { return 0f; } if (Count == 0) { primed = false; return 0f; } return buffer[head++ % buffer.Length]; } public void Clear() { head = tail; primed = false; } } internal sealed class AudioTap : MonoBehaviour, IMicrophoneSubscriber { private const float VoicePrefillSeconds = 0.06f; private const float VoiceMaxLagSeconds = 0.15f; private readonly object gate = new object(); private readonly AudioRing heard = new AudioRing(1952000); private readonly AudioRing voice = new AudioRing(1952000); private readonly SampleQueue voiceQueue = new SampleQueue(960, 2400); private Resampler listenerResampler; private Resampler? voiceResampler; private int voiceRate; private Action<float> writeHeard; private Action<float> writeVoice; private long lastWrite; private DissonanceComms comms; private VoicePlayerState? self; private volatile bool recording; private volatile bool transmitting; public bool Recording { set { if (value && !recording) { lock (gate) { heard.Clear(); voice.Clear(); voiceQueue.Clear(); } } recording = value; } } public static AudioTap AttachTo(AudioListener listener) { AudioTap component = ((Component)listener).GetComponent<AudioTap>(); if (!((Object)(object)component != (Object)null)) { return ((Component)listener).gameObject.AddComponent<AudioTap>(); } return component; } public (short[] GameSound, short[] Voice, long EndTimestamp) Latest(float seconds) { int count = (int)(seconds * 16000f); lock (gate) { return (GameSound: heard.Latest(count), Voice: voice.Latest(count), EndTimestamp: lastWrite); } } private void Awake() { listenerResampler = new Resampler(AudioSettings.outputSampleRate, 16000); writeHeard = delegate(float sample) { heard.Write(sample); voice.Write(voiceQueue.DequeueOrSilence()); }; writeVoice = delegate(float sample) { voiceQueue.Enqueue(sample); }; comms = StartOfRound.Instance.voiceChatModule; comms.SubscribeToRecordedAudio((IMicrophoneSubscriber)(object)this); } private void Update() { if (self == null) { self = comms.FindPlayer(comms.LocalPlayerName); } VoicePlayerState val = self; transmitting = val != null && val.IsSpeaking; } private void OnDestroy() { if ((Object)(object)comms != (Object)null) { comms.UnsubscribeFromRecordedAudio((IMicrophoneSubscriber)(object)this); } } private void OnAudioFilterRead(float[] data, int channels) { if (!recording) { return; } lock (gate) { listenerResampler.Process(data, 0, data.Length, channels, writeHeard); lastWrite = Stopwatch.GetTimestamp(); } } public void ReceiveMicrophoneData(ArraySegment<float> buffer, WaveFormat format) { if (!recording || !transmitting) { return; } lock (gate) { if (voiceResampler == null || voiceRate != format.SampleRate) { voiceRate = format.SampleRate; voiceResampler = new Resampler(voiceRate, 16000); } voiceResampler.Process(buffer.Array, buffer.Offset, buffer.Count, format.Channels, writeVoice); } } public void Reset() { lock (gate) { voiceQueue.Clear(); voiceResampler = null; } } } internal sealed class CopyTransfer { public const int WindowBytes = 262144; public const int AckEveryPieces = 16; public const float StallSeconds = 10f; private const float MaxFrameSeconds = 1f; private readonly List<(int CopyId, string FileName)> waiting = new List<(int, string)>(); private string fileName = ""; private float sinceProgress; public PieceRate Rate { get; } = new PieceRate(); public byte[]? File { get; private set; } public int CopyId { get; private set; } public int Offset { get; private set; } public int Acked { get; private set; } public bool Urgent { get; set; } public bool IsIdle { get { if (File == null) { return waiting.Count == 0; } return false; } } public static bool IsAckDue(int receivedBytes, int fileBytes) { if (receivedBytes != fileBytes) { return receivedBytes % 64000 == 0; } return true; } public bool IsSending(int copyId) { if (File != null) { return CopyId == copyId; } return false; } public void Enqueue(int copyId, string name) { if (!waiting.Exists(((int CopyId, string FileName) w) => w.CopyId == copyId)) { int num = waiting.FindIndex(((int CopyId, string FileName) w) => string.CompareOrdinal(w.FileName, name) < 0); waiting.Insert((num < 0) ? waiting.Count : num, (copyId, name)); } } public void Remove(int copyId) { waiting.RemoveAll(((int CopyId, string FileName) w) => w.CopyId == copyId); } public bool TryDequeue(out int copyId) { copyId = 0; if (waiting.Count == 0) { return false; } copyId = waiting[0].CopyId; waiting.RemoveAt(0); return true; } public void Start(int copyId, string name, byte[] file, bool urgent) { File = file; CopyId = copyId; fileName = name; Offset = 0; Acked = 0; sinceProgress = 0f; Urgent = urgent; } public void Interrupt() { if (File != null) { Enqueue(CopyId, fileName); File = null; } } public void Stop() { File = null; } public bool TryNextPiece(out int offset, out int length) { offset = Offset; length = 0; if (File == null || Offset == File.Length || Offset - Acked >= 262144) { return false; } length = FilePieces.LengthAt(File.Length, Offset); Offset += length; return true; } public void Acknowledge(int copyId, int bytes) { byte[] file = File; if (file != null && CopyId == copyId && bytes > Acked && bytes <= Offset) { Acked = bytes; sinceProgress = 0f; if (Acked == file.Length) { File = null; } } } public bool Stalled(float deltaTime) { if (File == null || Offset == Acked) { sinceProgress = 0f; return false; } sinceProgress += Math.Min(deltaTime, 1f); return sinceProgress >= 10f; } } internal static class DeathCause { public const string CoronerGuid = "com.elitemastereric.coroner"; public static string Describe(PlayerControllerB player) { if (!Chainloader.PluginInfos.ContainsKey("com.elitemastereric.coroner")) { return ((object)Unsafe.As<CauseOfDeath, CauseOfDeath>(ref player.causeOfDeath)/*cast due to .constrained prefix*/).ToString(); } return FromCoroner(player) ?? ((object)Unsafe.As<CauseOfDeath, CauseOfDeath>(ref player.causeOfDeath)/*cast due to .constrained prefix*/).ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] private static string? FromCoroner(PlayerControllerB player) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) AdvancedCauseOfDeath? causeOfDeath = API.GetCauseOfDeath(player); if (causeOfDeath.HasValue) { AdvancedCauseOfDeath valueOrDefault = causeOfDeath.GetValueOrDefault(); return API.StringifyCauseOfDeath(valueOrDefault, (Random)null); } return null; } } internal sealed class DeathRecorder : MonoBehaviour { private readonly ScreenCapture screen = new ScreenCapture(); private readonly ConcurrentQueue<byte[]> finished = new ConcurrentQueue<byte[]>(); private AudioTap? tap; private bool capturing; private bool wasDead; private float? snapshotAt; private void Update() { byte[] result; while (finished.TryDequeue(out result)) { RecordingNetwork.Deliver(result); } PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if ((Object)(object)val == (Object)null || (Object)(object)StartOfRound.Instance == (Object)null) { SetCapturing(on: false, null); wasDead = false; snapshotAt = null; return; } if (val.isPlayerDead && !wasDead && capturing) { snapshotAt = Time.time + 2f; } wasDead = val.isPlayerDead; float? num = snapshotAt; if (num.HasValue) { float valueOrDefault = num.GetValueOrDefault(); if (Time.time >= valueOrDefault) { snapshotAt = null; Snapshot(val); } } int num2; if (RecordingState.RecordMyDeaths && !StartOfRound.Instance.inShipPhase) { if (val.isPlayerDead) { num = snapshotAt; num2 = (num.HasValue ? 1 : 0); } else { num2 = 1; } } else { num2 = 0; } SetCapturing((byte)num2 != 0, val); if (capturing) { screen.Tick(Time.unscaledDeltaTime); } } private void OnDestroy() { screen.Dispose(); } private void SetCapturing(bool on, PlayerControllerB? player) { if (on && !capturing) { screen.Clear(); tap = AudioTap.AttachTo(player.activeAudioListener); } if ((Object)(object)tap != (Object)null) { tap.Recording = on; } capturing = on; } private void Snapshot(PlayerControllerB player) { double num = Seconds(Stopwatch.GetTimestamp()); float keptSeconds = RecordingState.KeptSeconds; (short[] GameSound, short[] Voice, long EndTimestamp) tuple = tap.Latest(keptSeconds); short[] item = tuple.GameSound; short[] item2 = tuple.Voice; long item3 = tuple.EndTimestamp; double start = ((item.Length != 0) ? (Seconds(item3) - (double)item.Length / 16000.0) : (num - (double)keptSeconds)); List<VideoFrame> list = (from f in screen.Since((long)Math.Ceiling(start * (double)Stopwatch.Frequency)) orderby f.Timestamp select new VideoFrame((int)Math.Round((Seconds(f.Timestamp) - start) * 1000.0), f.Jpeg)).ToList(); StartOfRound instance = StartOfRound.Instance; RecordingInfo recordingInfo = new RecordingInfo(player.playerUsername, instance.currentLevel.PlanetName, instance.gameStats.daysSpent + 1, DeathCause.Describe(player), DateTime.UtcNow); Recording recording = new Recording(recordingInfo, list, 16000, item, item2); Plugin.Log.LogInfo((object)$"Recorded the last {recording.DurationMs / 1000} s before the death of {recordingInfo.Player} ({list.Count} frames)."); ThreadPool.QueueUserWorkItem(delegate { try { finished.Enqueue(RecordingFile.Write(recording)); } catch (Exception arg) { Plugin.Log.LogError((object)$"Could not write the recording: {arg}"); } }); } private static double Seconds(long timestamp) { return (double)timestamp / (double)Stopwatch.Frequency; } } internal static class FilePieces { public const int PieceBytes = 4000; public const int MaxFileBytes = 67108864; public static bool IsValidSize(int fileBytes) { if (fileBytes > 0) { return fileBytes <= 67108864; } return false; } public static bool IsValid(int fileBytes, int offset, int length) { if (IsValidSize(fileBytes) && length > 0 && length <= 4000 && offset >= 0) { return offset <= fileBytes - length; } return false; } public static int LengthAt(int fileBytes, int offset) { return Math.Min(4000, fileBytes - offset); } } internal sealed class MonitorPlayback : MonoBehaviour { private const float SoundMaxDistance = 30f; private const float ControlDistance = 8f; private const float ControlAngle = 30f; private const int BarHeight = 4; private const int StillWidth = 256; private const int StillHeight = 144; private static readonly Color32 BarDone = new Color32((byte)220, (byte)220, (byte)220, byte.MaxValue); private static readonly Color32 BarLeft = new Color32((byte)60, (byte)60, (byte)60, byte.MaxValue); private static readonly Color32[] Black = (Color32[])(object)new Color32[36864]; private int playId = -1; private Recording? recording; private int[] frameTimesMs = Array.Empty<int>(); private float downloadProgress; private (int Ready, int Players)? waiting; private bool started; private int shownFrame = -1; private AudioSource? speaker; private AudioClip? clip; private Texture2D? picture; private Material? screen; private Material? replaced; public bool IsPlaying { get; private set; } public bool Finished { get; private set; } public int PositionMs { get { if (!((Object)(object)speaker == (Object)null) && !((Object)(object)clip == (Object)null)) { return (int)((long)speaker.timeSamples * 1000L / clip.frequency); } return 0; } } public int DurationMs => recording?.DurationMs ?? 0; public void ShowDownload(int id, string label) { Begin(id, label); DrawStill(0f); } public void DownloadProgress(int id, float progress) { if (id == playId && (object)recording == null) { downloadProgress = progress; DrawStill(progress); } } public void Show(int id, Recording loaded, string label) { if (playId != id) { Begin(id, label); } recording = loaded; frameTimesMs = loaded.Frames.Select((VideoFrame frame) => frame.TimeMs).ToArray(); short[] array = loaded.MixedSound(); int num = Math.Max(array.Length, (int)((long)loaded.DurationMs * (long)loaded.SampleRate / 1000)) + 1; clip = AudioClip.Create("Multipla recording", num, 1, loaded.SampleRate, false); float[] array2 = new float[array.Length]; for (int num2 = 0; num2 < array2.Length; num2++) { array2[num2] = (float)array[num2] / 32767f; } clip.SetData(array2, 0); speaker.clip = clip; speaker.timeSamples = 0; shownFrame = -1; if (loaded.Frames.Count == 0) { DrawStill(0f); return; } ImageConversion.LoadImage(picture, loaded.Frames[0].Jpeg); DrawBar(0f); } public void Receive(PlaybackPacket packet) { if (packet.PlayId != playId) { return; } if (!(packet is PlaybackWaiting playbackWaiting)) { if (!(packet is PlaybackState playbackState)) { if (packet is PlaybackEnd) { Stop(); } } else if ((object)recording != null) { Apply(playbackState.Playing, playbackState.PositionMs); } } else { waiting = (playbackWaiting.Ready, playbackWaiting.Players); if ((object)recording == null) { DrawStill(downloadProgress); } } } public void Stop() { if (playId != -1) { ManualCameraRenderer mapScreen = StartOfRound.Instance.mapScreen; Material[] sharedMaterials = ((Renderer)mapScreen.mesh).sharedMaterials; if ((Object)(object)sharedMaterials[mapScreen.materialIndex] == (Object)(object)screen) { sharedMaterials[mapScreen.materialIndex] = replaced; ((Renderer)mapScreen.mesh).sharedMaterials = sharedMaterials; } speaker.Stop(); Abandon(); } } public void Abandon() { if (playId != -1) { playId = -1; recording = null; waiting = null; started = false; IsPlaying = false; Finished = false; Object.Destroy((Object)(object)clip); Object.Destroy((Object)(object)picture); Object.Destroy((Object)(object)screen); } } private void Begin(int id, string label) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown Stop(); playId = id; downloadProgress = 0f; shownFrame = -1; ManualCameraRenderer mapScreen = StartOfRound.Instance.mapScreen; picture = new Texture2D(256, 144, (TextureFormat)3, false); screen = new Material(mapScreen.onScreenMat) { mainTexture = (Texture)(object)picture }; Material[] sharedMaterials = ((Renderer)mapScreen.mesh).sharedMaterials; replaced = sharedMaterials[mapScreen.materialIndex]; sharedMaterials[mapScreen.materialIndex] = screen; ((Renderer)mapScreen.mesh).sharedMaterials = sharedMaterials; if ((Object)(object)speaker == (Object)null) { speaker = CreateSpeaker(((Component)mapScreen.mesh).transform); } speaker.volume = RecordingState.PlaybackVolume; HUDManager.Instance.DisplayTip("Nagranie na monitorze", label, false, false, "LC_Tip1"); } private void Apply(bool playing, int positionMs) { if (playing) { speaker.Play(); } else { speaker.Pause(); } speaker.timeSamples = Math.Min(clip.samples - 1, (int)((long)positionMs * (long)clip.frequency / 1000)); started = true; IsPlaying = playing; Finished = false; shownFrame = -1; } private void Update() { if ((object)recording == null || !started) { return; } if (IsPlaying && !speaker.isPlaying) { IsPlaying = false; Finished = true; return; } int positionMs = PositionMs; int num = RecordingRules.FrameAt(frameTimesMs, positionMs); if (num != shownFrame && num != -1) { shownFrame = num; ImageConversion.LoadImage(picture, recording.Frames[num].Jpeg); DrawBar((float)positionMs / (float)recording.DurationMs); } } private void LateUpdate() { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) if (playId == -1) { return; } PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if ((Object)(object)val == (Object)null || val.isPlayerDead || val.inTerminalMenu || val.isTypingChat || val.quickMenuManager.isMenuOpen) { return; } Transform transform = ((Component)val.gameplayCamera).transform; Vector3 val2 = ((Component)StartOfRound.Instance.mapScreen.mesh).transform.position - transform.position; if (((Vector3)(ref val2)).magnitude > 8f || Vector3.Angle(transform.forward, val2) > 30f) { return; } if (((TMP_Text)val.cursorTip).text.Length == 0) { ((TMP_Text)val.cursorTip).text = Status(); } Keyboard current = Keyboard.current; if (current != null && started) { if (((ButtonControl)current.downArrowKey).wasPressedThisFrame) { RecordingNetwork.Request(RecordingRequest.TogglePause, playId); } else if (((ButtonControl)current.leftArrowKey).wasPressedThisFrame) { RecordingNetwork.Request(RecordingRequest.Seek, -RecordingState.SeekStepMs); } else if (((ButtonControl)current.rightArrowKey).wasPressedThisFrame) { RecordingNetwork.Request(RecordingRequest.Seek, RecordingState.SeekStepMs); } else if (((ButtonControl)current.upArrowKey).wasPressedThisFrame) { RecordingNetwork.Request(RecordingRequest.Stop, playId); } } } private string Status() { if ((object)recording == null) { return RecordingTexts.Downloading(downloadProgress); } if (!started) { return RecordingTexts.WaitingForPlayers(waiting); } return RecordingTexts.Controls(PositionMs, recording.DurationMs, IsPlaying); } private void DrawStill(float progress) { if (((Texture)picture).width != 256 || ((Texture)picture).height != 144) { picture.Reinitialize(256, 144); } picture.SetPixels32(Black); DrawBar(progress); } private void DrawBar(float fraction) { //IL_0040: 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_0045: Unknown result type (might be due to invalid IL or missing references) int width = ((Texture)picture).width; int num = Mathf.RoundToInt(Mathf.Clamp01(fraction) * (float)width); Color32[] array = (Color32[])(object)new Color32[width * 4]; for (int i = 0; i < 4; i++) { for (int j = 0; j < width; j++) { array[i * width + j] = ((j < num) ? BarDone : BarLeft); } } picture.SetPixels32(0, 0, width, 4, array); picture.Apply(false); } private static AudioSource CreateSpeaker(Transform monitor) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("Multipla.RecordingSpeaker"); val.transform.SetParent(monitor, false); AudioSource obj = val.AddComponent<AudioSource>(); obj.spatialBlend = 1f; obj.rolloffMode = (AudioRolloffMode)1; obj.maxDistance = 30f; obj.playOnAwake = false; return obj; } } internal sealed class PieceAssembly { public long Id { get; } public byte[] File { get; } public int Received { get; private set; } public bool IsComplete => Received == File.Length; public float Progress => (float)Received / (float)File.Length; public PieceAssembly(long id, int totalBytes) { Id = id; File = new byte[totalBytes]; } public static PieceAssembly? Continue(PieceAssembly? current, long id, int fileBytes, int offset, byte[] piece) { PieceAssembly pieceAssembly = ((offset == 0) ? new PieceAssembly(id, fileBytes) : current); if (pieceAssembly == null || pieceAssembly.Id != id || pieceAssembly.File.Length != fileBytes || !pieceAssembly.TryAdd(offset, piece)) { return null; } return pieceAssembly; } public bool TryAdd(int offset, byte[] piece) { if (offset != Received || piece.Length == 0 || piece.Length > File.Length - Received) { return false; } Array.Copy(piece, 0, File, offset, piece.Length); Received += piece.Length; return true; } } internal sealed class PieceRate { private const float MaxBacklogSeconds = 0.25f; private float since; public int Due(float deltaTime, int perSecond) { since = Math.Min(since + deltaTime, 0.25f); int num = (int)(since * (float)perSecond); since -= (float)num / (float)perSecond; return num; } public void Reset() { since = 0f; } } internal abstract record PlaybackPacket(int PlayId); internal sealed record PlaybackPrepare : PlaybackPacket { public int Number { get; init; } public RecordingInfo Info { get; init; } public int FileBytes { get; init; } public int CopyId { get; init; } public PlaybackPrepare(int PlayId, int Number, RecordingInfo Info, int FileBytes, int CopyId) { this.Number = Number; this.Info = Info; this.FileBytes = FileBytes; this.CopyId = CopyId; base..ctor(PlayId); } [CompilerGenerated] public void Deconstruct(out int PlayId, out int Number, out RecordingInfo Info, out int FileBytes, out int CopyId) { PlayId = base.PlayId; Number = this.Number; Info = this.Info; FileBytes = this.FileBytes; CopyId = this.CopyId; } } internal sealed record PlaybackWaiting : PlaybackPacket { public int Ready { get; init; } public int Players { get; init; } public PlaybackWaiting(int PlayId, int Ready, int Players) { this.Ready = Ready; this.Players = Players; base..ctor(PlayId); } [CompilerGenerated] public void Deconstruct(out int PlayId, out int Ready, out int Players) { PlayId = base.PlayId; Ready = this.Ready; Players = this.Players; } } internal sealed record PlaybackState : PlaybackPacket { public bool Playing { get; init; } public int PositionMs { get; init; } public PlaybackState(int PlayId, bool Playing, int PositionMs) { this.Playing = Playing; this.PositionMs = PositionMs; base..ctor(PlayId); } [CompilerGenerated] public void Deconstruct(out int PlayId, out bool Playing, out int PositionMs) { PlayId = base.PlayId; Playing = this.Playing; PositionMs = this.PositionMs; } } internal sealed record PlaybackEnd : PlaybackPacket { public PlaybackEnd(int PlayId) : base(PlayId) { } [CompilerGenerated] public new void Deconstruct(out int PlayId) { PlayId = base.PlayId; } } internal sealed class RecordingCopies : MonoBehaviour { private const int BackgroundPiecesPerSecond = 32; private const int UrgentPiecesPerSecond = 48; private readonly Dictionary<int, string> paths = new Dictionary<int, string>(); private readonly Dictionary<string, int> ids = new Dictionary<string, int>(); private readonly HashSet<ulong> receivers = new HashSet<ulong>(); private readonly Dictionary<ulong, CopyTransfer> transfers = new Dictionary<ulong, CopyTransfer>(); private PieceAssembly? incoming; private int? lost; public int IdOf(string path) { if (ids.TryGetValue(path, out var value)) { return value; } value = ids.Count + 1; ids[path] = value; paths[value] = path; return value; } public void OfferToReceivers(RecordingFolder.Entry entry) { if (!FilePieces.IsValidSize(entry.Bytes)) { Plugin.Log.LogWarning((object)$"The recording {entry.Path} ({entry.Bytes / 1024 / 1024} MB) is over the {64} MB that can be sent; the other players do not get it."); return; } List<ulong> clients = NamedMessages.OtherClients(0uL).Where(receivers.Contains).ToList(); RecordingNetwork.SendCopyOffer(IdOf(entry.Path), entry, clients); } public void AddReceiver(ulong client) { receivers.Add(client); foreach (RecordingFolder.Entry item in from e in RecordingLibrary.Lobby.Files.Reverse() where FilePieces.IsValidSize(e.Bytes) select e) { RecordingNetwork.SendCopyOffer(IdOf(item.Path), item, new ulong[1] { client }); } } public void Request(ulong client, int copyId, bool urgent) { if (!paths.ContainsKey(copyId)) { Plugin.Log.LogWarning((object)$"Player {client} asked for an unknown recording copy {copyId}."); RecordingNetwork.SendCopyGone(client, copyId); return; } if (!transfers.TryGetValue(client, out CopyTransfer value)) { value = (transfers[client] = new CopyTransfer()); } if (urgent) { if (value.IsSending(copyId)) { value.Urgent = true; return; } if (receivers.Contains(client)) { value.Interrupt(); } else { value.Stop(); } value.Remove(copyId); Start(client, value, copyId, urgent: true); } else { if (value.IsSending(copyId)) { value.Stop(); } if (receivers.Contains(client)) { value.Enqueue(copyId, NameOf(copyId)); } } } public void Received(ulong client, int copyId, int bytes) { if (transfers.TryGetValue(client, out CopyTransfer value)) { value.Acknowledge(copyId, bytes); } } public void Offered(int copyId, RecordingInfo info, int fileBytes) { if (RecordingState.KeepOthersRecordings && RecordingLibrary.FindLocal(RecordingRules.FileName(info), fileBytes) == null) { RecordingNetwork.Ask(RecordingRequest.Missing, copyId); } } public void Piece(int copyId, int fileBytes, int offset, byte[] bytes) { if (lost == copyId && offset != 0) { return; } PieceAssembly pieceAssembly = PieceAssembly.Continue(incoming, copyId, fileBytes, offset, bytes); if (pieceAssembly == null) { Lost(copyId); return; } lost = null; incoming = pieceAssembly; if (CopyTransfer.IsAckDue(pieceAssembly.Received, pieceAssembly.File.Length)) { RecordingNetwork.Ask(RecordingRequest.CopyReceived, copyId, pieceAssembly.Received); } if (pieceAssembly.IsComplete) { incoming = null; if (RecordingState.KeepOthersRecordings) { RecordingLibrary.Save(RecordingLibrary.Others, pieceAssembly.File); } } RecordingNetwork.CopyChanged(copyId, pieceAssembly); } public void Lost(int copyId) { if (lost != copyId) { Plugin.Log.LogWarning((object)$"A piece of recording copy {copyId} is missing or broken; the copy is dropped."); lost = copyId; Broken(copyId); RecordingNetwork.Ask(RecordingRequest.Missing, copyId); } } public void Broken(int copyId) { PieceAssembly? pieceAssembly = incoming; if (pieceAssembly != null && pieceAssembly.Id == copyId) { incoming = null; } RecordingNetwork.CopyChanged(copyId, null); } public void Reset() { paths.Clear(); ids.Clear(); receivers.Clear(); transfers.Clear(); incoming = null; lost = null; } private void Update() { if (transfers.Count == 0) { return; } IReadOnlyList<ulong> connectedClientsIds = NetworkManager.Singleton.ConnectedClientsIds; foreach (ulong item in transfers.Keys.ToList()) { CopyTransfer copyTransfer = transfers[item]; if (connectedClientsIds.Contains(item)) { SendPieces(item, copyTransfer); } if (!connectedClientsIds.Contains(item) || copyTransfer.IsIdle) { transfers.Remove(item); } } } private void SendPieces(ulong client, CopyTransfer transfer) { if (transfer.Stalled(Time.unscaledDeltaTime)) { Plugin.Log.LogWarning((object)$"Player {client} has not confirmed recording copy {transfer.CopyId} for {10f} s; it is dropped."); transfer.Stop(); RecordingNetwork.SendCopyGone(client, transfer.CopyId); } int num = transfer.Rate.Due(Time.unscaledDeltaTime, transfer.Urgent ? 48 : 32); for (int i = 0; i < num; i++) { int copyId; while (transfer.File == null && transfer.TryDequeue(out copyId)) { Start(client, transfer, copyId, urgent: false); } byte[] file = transfer.File; if (file == null || !transfer.TryNextPiece(out var offset, out var length)) { break; } RecordingNetwork.SendCopyPiece(client, transfer.CopyId, file, offset, length); } } private void Start(ulong client, CopyTransfer transfer, int copyId, bool urgent) { try { transfer.Start(copyId, NameOf(copyId), File.ReadAllBytes(paths[copyId]), urgent); } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { Plugin.Log.LogWarning((object)("Could not read " + paths[copyId] + " to copy it: " + ex.Message)); RecordingNetwork.SendCopyGone(client, copyId); } } private string NameOf(int copyId) { return Path.GetFileName(paths[copyId]); } } internal sealed record RecordingInfo(string Player, string Moon, int Day, string Cause, DateTime RecordedAtUtc); internal readonly record struct VideoFrame(int TimeMs, byte[] Jpeg); internal sealed record Recording { public RecordingInfo Info { get; init; } public IReadOnlyList<VideoFrame> Frames { get; init; } public int SampleRate { get; init; } public short[] GameSound { get; init; } public short[] Voice { get; } public int DurationMs => RecordingFile.Duration((Frames.Count != 0) ? Frames[Frames.Count - 1].TimeMs : 0, GameSound.LongLength, SampleRate); public Recording(RecordingInfo Info, IReadOnlyList<VideoFrame> Frames, int SampleRate, short[] GameSound, short[] Voice) { this.Info = Info; this.Frames = Frames; this.SampleRate = SampleRate; this.GameSound = GameSound; if (Voice.Length != 0 && Voice.Length != GameSound.Length) { throw new ArgumentException($"The voice has {Voice.Length} samples, the game sound {GameSound.Length}.", "Voice"); } this.Voice = Voice; base..ctor(); } public short[] MixedSound() { short[] array = (short[])GameSound.Clone(); for (int i = 0; i < Voice.Length; i++) { array[i] = (short)Math.Max(-32768, Math.Min(32767, GameSound[i] + Voice[i])); } return array; } [CompilerGenerated] public void Deconstruct(out RecordingInfo Info, out IReadOnlyList<VideoFrame> Frames, out int SampleRate, out short[] GameSound, out short[] Voice) { Info = this.Info; Frames = this.Frames; SampleRate = this.SampleRate; GameSound = this.GameSound; Voice = this.Voice; } } internal readonly record struct FrameSpan(int TimeMs, long Offset, int Length); internal sealed record RecordingLayout(RecordingInfo Info, IReadOnlyList<FrameSpan> Frames, int DurationMs); internal static class RecordingFile { public const string Extension = ".lckrec"; private const uint Magic = 1380664140u; private const byte Version = 2; private const byte MixedSoundVersion = 1; public static byte[] Write(Recording recording) { using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(1380664140u); binaryWriter.Write((byte)2); RecordingInfo info = recording.Info; binaryWriter.Write(info.Player); binaryWriter.Write(info.Moon); binaryWriter.Write(info.Day); binaryWriter.Write(info.Cause); binaryWriter.Write(info.RecordedAtUtc.Ticks); binaryWriter.Write(recording.Frames.Count); foreach (VideoFrame frame in recording.Frames) { binaryWriter.Write(frame.TimeMs); binaryWriter.Write(frame.Jpeg.Length); binaryWriter.Write(frame.Jpeg); } binaryWriter.Write(recording.SampleRate); binaryWriter.Write(recording.GameSound.Length); WriteSamples(binaryWriter, recording.GameSound); WriteSamples(binaryWriter, (recording.Voice.Length == 0) ? new short[recording.GameSound.Length] : recording.Voice); } return memoryStream.ToArray(); } public static Recording Read(byte[] data) { using BinaryReader binaryReader = new BinaryReader(new MemoryStream(data), Encoding.UTF8); var (info, b) = ReadHeader(binaryReader); try { VideoFrame[] array = new VideoFrame[Count(binaryReader)]; for (int i = 0; i < array.Length; i++) { int timeMs = binaryReader.ReadInt32(); array[i] = new VideoFrame(timeMs, ReadExactly(binaryReader, Count(binaryReader))); } int sampleRate = SampleRate(binaryReader); int count = Count(binaryReader); short[] gameSound = ReadSamples(binaryReader, count); short[] voice = ((b == 1) ? Array.Empty<short>() : ReadSamples(binaryReader, count)); return new Recording(info, array, sampleRate, gameSound, voice); } catch (EndOfStreamException innerException) { throw new InvalidDataException("Recording is cut off.", innerException); } } public static RecordingLayout ReadLayout(Stream stream) { using BinaryReader binaryReader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); var (info, b) = ReadHeader(binaryReader); try { FrameSpan[] array = new FrameSpan[Count(binaryReader)]; for (int i = 0; i < array.Length; i++) { int timeMs = binaryReader.ReadInt32(); int num = Count(binaryReader); array[i] = new FrameSpan(timeMs, stream.Position, num); Skip(stream, num); } int sampleRate = SampleRate(binaryReader); int num2 = Count(binaryReader); Skip(stream, (long)num2 * 2L * ((b == 1) ? 1 : 2)); return new RecordingLayout(info, array, Duration((array.Length != 0) ? array[^1].TimeMs : 0, num2, sampleRate)); } catch (EndOfStreamException innerException) { throw new InvalidDataException("Recording is cut off.", innerException); } } public static byte[] ReadFrame(Stream stream, FrameSpan frame) { stream.Position = frame.Offset; using BinaryReader reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); return ReadExactly(reader, frame.Length); } public static int Duration(int lastFrameMs, long samples, int sampleRate) { return Math.Max(lastFrameMs, (int)(samples * 1000 / sampleRate)); } public static RecordingInfo ReadInfo(Stream stream) { using BinaryReader reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); return ReadHeader(reader).Info; } private static (RecordingInfo Info, byte Version) ReadHeader(BinaryReader reader) { try { if (reader.ReadUInt32() != 1380664140) { throw new InvalidDataException("Not a Multipla recording."); } byte b = reader.ReadByte(); if (b != 2 && b != 1) { throw new InvalidDataException($"Recording format {b}, this version of the mod reads {(byte)1} and {(byte)2}."); } return (Info: new RecordingInfo(reader.ReadString(), reader.ReadString(), reader.ReadInt32(), reader.ReadString(), new DateTime(reader.ReadInt64(), DateTimeKind.Utc)), Version: b); } catch (EndOfStreamException innerException) { throw new InvalidDataException("Recording header is cut off.", innerException); } catch (Exception ex) when (((ex is FormatException || ex is ArgumentOutOfRangeException) ? 1 : 0) != 0) { throw new InvalidDataException("Recording header is broken: " + ex.Message, ex); } } private static int Count(BinaryReader reader) { int num = reader.ReadInt32(); if (num < 0 || num > reader.BaseStream.Length) { throw new InvalidDataException($"Recording has an impossible length {num}."); } return num; } private static int SampleRate(BinaryReader reader) { int num = reader.ReadInt32(); if (num <= 0) { throw new InvalidDataException($"Recording has an impossible sample rate {num}."); } return num; } private static void Skip(Stream stream, long count) { if (stream.Length - stream.Position < count) { throw new InvalidDataException("Recording is cut off."); } stream.Seek(count, SeekOrigin.Current); } private static void WriteSamples(BinaryWriter writer, short[] samples) { byte[] array = new byte[samples.Length * 2]; Buffer.BlockCopy(samples, 0, array, 0, array.Length); writer.Write(array); } private static short[] ReadSamples(BinaryReader reader, int count) { short[] array = new short[count]; Buffer.BlockCopy(ReadExactly(reader, count * 2), 0, array, 0, count * 2); return array; } private static byte[] ReadExactly(BinaryReader reader, int count) { byte[] array = reader.ReadBytes(count); if (array.Length != count) { throw new InvalidDataException("Recording is cut off."); } return array; } } internal sealed class RecordingFolder { public readonly record struct Entry(string Path, RecordingInfo Info, int Bytes); private readonly string folder; private List<Entry>? entries; public IReadOnlyList<Entry> Files => Entries; private List<Entry> Entries => entries ?? (entries = Load()); public RecordingFolder(string folder) { this.folder = Path.GetFullPath(folder); } public Entry? Save(byte[] file) { try { using MemoryStream stream = new MemoryStream(file); RecordingInfo recordingInfo = RecordingFile.ReadInfo(stream); Directory.CreateDirectory(folder); string path = Path.Combine(folder, RecordingRules.FileName(recordingInfo)); File.WriteAllBytes(path, file); Entry entry = new Entry(path, recordingInfo, file.Length); Entries.RemoveAll((Entry e) => e.Path == path); Entries.Add(entry); Entries.Sort((Entry a, Entry b) => string.CompareOrdinal(Path.GetFileName(a.Path), Path.GetFileName(b.Path))); Plugin.Log.LogInfo((object)$"Saved recording of {recordingInfo.Player} ({file.Length / 1024} KB) to {path}"); return entry; } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException || ex is InvalidDataException) ? 1 : 0) != 0) { Plugin.Log.LogError((object)("Could not save a recording in " + folder + ": " + ex.Message)); return null; } } public Entry? At(int number) { if (number >= 1 && number <= Entries.Count) { return Entries[number - 1]; } return null; } public string? Find(string fileName, int bytes) { string text = Path.Combine(folder, fileName); FileInfo fileInfo = new FileInfo(text); if (!fileInfo.Exists || fileInfo.Length != bytes) { return null; } return text; } public bool Forget(string path) { if (entries != null) { return entries.RemoveAll((Entry e) => e.Path == path) > 0; } return false; } public void Delete() { entries = new List<Entry>(); if (!Directory.Exists(folder)) { return; } try { Directory.Delete(folder, recursive: true); Plugin.Log.LogInfo((object)("Deleted the recordings in " + folder + ".")); } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { Plugin.Log.LogError((object)("Could not delete the recordings in " + folder + ": " + ex.Message)); } } private List<Entry> Load() { List<Entry> list = new List<Entry>(); if (!Directory.Exists(folder)) { return list; } foreach (string item in Directory.GetFiles(folder, "*.lckrec").OrderBy<string, string>((string p) => Path.GetFileName(p), StringComparer.Ordinal)) { try { using FileStream fileStream = File.OpenRead(item); list.Add(new Entry(item, RecordingFile.ReadInfo(fileStream), (int)fileStream.Length)); } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException || ex is InvalidDataException) ? 1 : 0) != 0) { Plugin.Log.LogWarning((object)("Recording " + item + " is left out of the list: " + ex.Message)); } } return list; } } internal static class RecordingLibrary { public static readonly string Root = RecordingRules.Root(Application.persistentDataPath); private static RecordingFolder? lobby; public static readonly RecordingFolder Own = new RecordingFolder(Path.Combine(Root, "Moje")); public static readonly RecordingFolder Others = new RecordingFolder(Path.Combine(Root, "Od innych")); public static RecordingFolder Lobby => lobby ?? throw new InvalidOperationException("The lobby's recordings were used before the host's lobby started."); public static event Action? Changed; public static void Load() { lobby = new RecordingFolder(SaveFolder(GameNetworkManager.Instance.currentSaveFileName)); RecordingLibrary.Changed?.Invoke(); } public static RecordingFolder.Entry? Save(RecordingFolder folder, byte[] file) { RecordingFolder.Entry? result = folder.Save(file); bool flag = result.HasValue && folder == lobby; List<string> list = KeepWithinLimit(); foreach (string item in list) { Own.Forget(item); Others.Forget(item); RecordingFolder? recordingFolder = lobby; if (recordingFolder != null && recordingFolder.Forget(item)) { flag = true; } } if (flag) { RecordingLibrary.Changed?.Invoke(); } if (!result.HasValue || !list.Contains(result.GetValueOrDefault().Path)) { return result; } return null; } public static List<string> LobbyLabels() { return Lobby.Files.Select((RecordingFolder.Entry file, int i) => RecordingRules.Label(i + 1, file.Info)).ToList(); } public static string? FindLocal(string fileName, int bytes) { return new RecordingFolder[2] { Own, Others }.Select((RecordingFolder folder) => folder.Find(fileName, bytes)).FirstOrDefault((string path) => path != null); } public static void DeleteFor(string saveFileName) { new RecordingFolder(SaveFolder(saveFileName)).Delete(); if (lobby != null && (Object)(object)GameNetworkManager.Instance != (Object)null && GameNetworkManager.Instance.currentSaveFileName == saveFileName) { Load(); } } private static string SaveFolder(string saveFileName) { return Path.Combine(Root, saveFileName); } private static List<string> KeepWithinLimit() { List<string> list = new List<string>(); if (!Directory.Exists(Root)) { return list; } foreach (string item in RecordingRules.OldestOverLimit(from path in Directory.GetFiles(Root, "*.lckrec", SearchOption.AllDirectories) select new FileInfo(path) into file select (FullName: file.FullName, Length: file.Length), RecordingState.MaxBytes)) { try { File.Delete(item); list.Add(item); Plugin.Log.LogInfo((object)$"Deleted the oldest recording {item} to keep all recordings within {RecordingState.MaxBytes / 1024 / 1024} MB."); } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { Plugin.Log.LogWarning((object)("Could not delete the old recording " + item + ": " + ex.Message)); } } return list; } } internal enum RecordingRequest : byte { List, Play, Stop, TogglePause, Seek, Ready, Failed, KeepCopies, Missing, MissingNow, CopyReceived } internal static class RecordingNetwork { private enum CopyKind : byte { Offer, Piece, Gone } private enum PacketKind : byte { Prepare, Waiting, State, End } [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__OnUpload; public static HandleNamedMessageDelegate <1>__OnRequest; public static HandleNamedMessageDelegate <2>__OnList; public static HandleNamedMessageDelegate <3>__OnCopy; public static HandleNamedMessageDelegate <4>__OnPlayback; public static Action <5>__Load; } private const byte ProtocolVersion = 2; private const string UploadMessage = "Multipla.RecordingUpload"; private const string RequestMessage = "Multipla.RecordingRequest"; private const string ListMessage = "Multipla.RecordingList"; private const string CopyMessage = "Multipla.RecordingCopy"; private const string PlaybackMessage = "Multipla.RecordingPlayback"; private const int WriterStartBytes = 256; private const int WriterMaxBytes = 262144; private static readonly Dictionary<ulong, PieceAssembly> Uploads = new Dictionary<ulong, PieceAssembly>(); private static readonly Dictionary<ulong, long> DroppedUploads = new Dictionary<ulong, long>(); private static readonly HashSet<ulong> ModClients = new HashSet<ulong>(); private static IReadOnlyList<string>? clientList; private static (int PlayId, string Label, int CopyId)? download; private static RecordingUploader uploader = null; private static RecordingCopies copies = null; private static SharedPlayback shared = null; private static MonitorPlayback playback = null; private static bool IsHost => NetworkManager.Singleton.IsServer; public static void Install(RecordingUploader uploaderComponent, RecordingCopies copiesComponent, SharedPlayback sharedComponent, MonitorPlayback playbackComponent) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown uploader = uploaderComponent; copies = copiesComponent; shared = sharedComponent; playback = playbackComponent; object obj = <>O.<0>__OnUpload; if (obj == null) { HandleNamedMessageDelegate val = OnUpload; <>O.<0>__OnUpload = val; obj = (object)val; } NamedMessages.OnHost("Multipla.RecordingUpload", (HandleNamedMessageDelegate)obj); object obj2 = <>O.<1>__OnRequest; if (obj2 == null) { HandleNamedMessageDelegate val2 = OnRequest; <>O.<1>__OnRequest = val2; obj2 = (object)val2; } NamedMessages.OnHost("Multipla.RecordingRequest", (HandleNamedMessageDelegate)obj2); object obj3 = <>O.<2>__OnList; if (obj3 == null) { HandleNamedMessageDelegate val3 = OnList; <>O.<2>__OnList = val3; obj3 = (object)val3; } NamedMessages.OnClient("Multipla.RecordingList", (HandleNamedMessageDelegate)obj3); object obj4 = <>O.<3>__OnCopy; if (obj4 == null) { HandleNamedMessageDelegate val4 = OnCopy; <>O.<3>__OnCopy = val4; obj4 = (object)val4; } NamedMessages.OnClient("Multipla.RecordingCopy", (HandleNamedMessageDelegate)obj4); object obj5 = <>O.<4>__OnPlayback; if (obj5 == null) { HandleNamedMessageDelegate val5 = OnPlayback; <>O.<4>__OnPlayback = val5; obj5 = (object)val5; } NamedMessages.OnClient("Multipla.RecordingPlayback", (HandleNamedMessageDelegate)obj5); NamedMessages.HostStarted += RecordingLibrary.Load; NamedMessages.JoinedAsClient += delegate { Ask(RecordingRequest.List, 0); if (RecordingState.KeepOthersRecordings) { Ask(RecordingRequest.KeepCopies, 0); } }; NamedMessages.Left += delegate { Uploads.Clear(); DroppedUploads.Clear(); ModClients.Clear(); clientList = null; download = null; uploader.Cancel(); copies.Reset(); shared.Cancel(); playback.Abandon(); }; RecordingLibrary.Changed += delegate { if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsServer) { SendList(NamedMessages.OtherClients(0uL)); } }; } public static List<ulong> ClientsWithMod() { return NamedMessages.OtherClients(0uL).Where(ModClients.Contains).ToList(); } public static void Deliver(byte[] file) { if (RecordingState.KeepOwnCopies) { RecordingLibrary.Save(RecordingLibrary.Own, file); } NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsListening) { Plugin.Log.LogWarning((object)"A recording was finished after leaving the lobby; only this player's copy is kept."); } else if (singleton.IsServer) { KeepInLobby(file); } else if (clientList == null) { Plugin.Log.LogWarning((object)"The host sent no recording list, so it lacks Multipla; the recording stays only with this player."); } else if (!FilePieces.IsValidSize(file.Length)) { Plugin.Log.LogWarning((object)$"The recording ({file.Length / 1024 / 1024} MB) is over the {64} MB that can be sent; it is not sent to the host."); } else { uploader.Enqueue(file); } } public static string Handle(TerminalCommand command) { if (IsHost) { return command.Action switch { TerminalAction.Play => shared.Play(command.Number), TerminalAction.Stop => shared.Stop(), _ => RecordingTexts.List(RecordingLibrary.LobbyLabels()), }; } if (clientList == null) { return "\nHost nie przysłał listy nagrań. Nagrania działają tylko wtedy, gdy host też ma Multiplę.\n\n"; } switch (command.Action) { case TerminalAction.Play: if (command.Number > clientList.Count) { return RecordingTexts.NoSuchRecording(command.Number); } Ask(RecordingRequest.Play, command.Number); return RecordingTexts.AskedToPlay(command.Number); case TerminalAction.Stop: Ask(RecordingRequest.Stop, 0); return "\nPoproszono hosta o zatrzymanie nagrania.\n\n"; default: return RecordingTexts.List(clientList); } } public static void Request(RecordingRequest request, int number) { if (IsHost) { shared.Handle(0uL, request, number); } else { Ask(request, number); } } public unsafe static void Ask(RecordingRequest request, int number, int bytes = 0) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(10, (Allocator)2, -1); try { byte b = 2; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<RecordingRequest>(ref request, default(ForEnums)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref number, default(ForPrimitives)); if (request == RecordingRequest.CopyReceived) { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref bytes, default(ForPrimitives)); } NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Multipla.RecordingRequest", 0uL, val, (NetworkDelivery)3); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } public unsafe static void SendUploadPiece(long id, byte[] file, int offset, int length) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 262144); try { byte b = 2; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<long>(ref id, default(ForPrimitives)); WritePiece(val, file, offset, length); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Multipla.RecordingUpload", 0uL, val, (NetworkDelivery)4); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } public unsafe static void SendCopyOffer(int copyId, RecordingFolder.Entry entry, IReadOnlyList<ulong> clients) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_0050: 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_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) if (clients.Count == 0) { return; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 262144); try { byte b = 2; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); CopyKind copyKind = CopyKind.Offer; ((FastBufferWriter)(ref val)).WriteValueSafe<CopyKind>(ref copyKind, default(ForEnums)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref copyId, default(ForPrimitives)); int bytes = entry.Bytes; ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref bytes, default(ForPrimitives)); WriteInfo(val, entry.Info); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Multipla.RecordingCopy", clients, val, (NetworkDelivery)4); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } public unsafe static void SendCopyPiece(ulong client, int copyId, byte[] file, int offset, int length) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 262144); try { byte b = 2; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); CopyKind copyKind = CopyKind.Piece; ((FastBufferWriter)(ref val)).WriteValueSafe<CopyKind>(ref copyKind, default(ForEnums)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref copyId, default(ForPrimitives)); WritePiece(val, file, offset, length); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Multipla.RecordingCopy", client, val, (NetworkDelivery)4); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } public unsafe static void SendCopyGone(ulong client, int copyId) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_003f: 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) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(6, (Allocator)2, -1); try { byte b = 2; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); CopyKind copyKind = CopyKind.Gone; ((FastBufferWriter)(ref val)).WriteValueSafe<CopyKind>(ref copyKind, default(ForEnums)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref copyId, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Multipla.RecordingCopy", client, val, (NetworkDelivery)4); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } public static void Broadcast(PlaybackPacket packet) { playback.Receive(packet); Send(packet, NamedMessages.OtherClients(0uL)); } public unsafe static void Send(PlaybackPacket packet, IReadOnlyList<ulong> clients) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if (clients.Count == 0) { return; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 262144); try { byte b = 2; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); WritePacket(val, packet); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Multipla.RecordingPlayback", clients, val, (NetworkDelivery)4); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } public static void CopyChanged(int copyId, PieceAssembly? file) { (int, string, int)? tuple = download; if (!tuple.HasValue) { return; } (int, string, int) valueOrDefault = tuple.GetValueOrDefault(); if (valueOrDefault.Item3 == copyId) { if (file == null) { download = null; Ask(RecordingRequest.Failed, valueOrDefault.Item1); } else if (!file.IsComplete) { playback.DownloadProgress(valueOrDefault.Item1, file.Progress); } else { download = null; Show(valueOrDefault.Item1, file.File, valueOrDefault.Item2); } } } private static void KeepInLobby(byte[] file) { RecordingFolder.Entry? entry = RecordingLibrary.Save(RecordingLibrary.Lobby, file); if (entry.HasValue) { RecordingFolder.Entry valueOrDefault = entry.GetValueOrDefault(); copies.OfferToReceivers(valueOrDefault); } } private unsafe static void SendList(IReadOnlyList<ulong> clients) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) if (clients.Count == 0) { return; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 262144); try { byte b = 2; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); List<string> list = RecordingLibrary.LobbyLabels(); int count = list.Count; ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref count, default(ForPrimitives)); foreach (string item in list) { ((FastBufferWriter)(ref val)).WriteValueSafe(item, false); } NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("Multipla.RecordingList", clients, val, (NetworkDelivery)4); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } private static bool VersionMatches(ulong senderId, FastBufferReader reader) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return NamedMessages.VersionMatches(reader, 2, "recording", senderId); } private static void OnUpload(ulong senderId, FastBufferReader reader) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (!VersionMatches(senderId, reader)) { return; } long num = default(long); ((FastBufferReader)(ref reader)).ReadValueSafe<long>(ref num, default(ForPrimitives)); if (DroppedUploads.TryGetValue(senderId, out var value) && value == num) { return; } int fileBytes; int offset; byte[] piece; bool flag = ReadPiece(reader, out fileBytes, out offset, out piece); Uploads.TryGetValue(senderId, out PieceAssembly value2); PieceAssembly pieceAssembly = (flag ? PieceAssembly.Continue(value2, num, fileBytes, offset, piece) : null); if (pieceAssembly == null) { Plugin.Log.LogWarning((object)(flag ? $"Player {senderId} sent a recording piece out of order; the recording is dropped." : $"Player {senderId} sent a recording piece that does not fit a file of {fileBytes} bytes (at most {67108864}); the recording is dropped.")); Uploads.Remove(senderId); DroppedUploads[senderId] = num; return; } DroppedUploads.Remove(senderId); if (!pieceAssembly.IsComplete) { Uploads[senderId] = pieceAssembly; return; } Uploads.Remove(senderId); KeepInLobby(pieceAssembly.File); } private static void OnRequest(ulong senderId, FastBufferReader reader) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) if (VersionMatches(senderId, reader)) { RecordingRequest recordingRequest = default(RecordingRequest); ((FastBufferReader)(ref reader)).ReadValueSafe<RecordingRequest>(ref recordingRequest, default(ForEnums)); int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); ModClients.Add(senderId); switch (recordingRequest) { case RecordingRequest.List: SendList(new ulong[1] { senderId }); break; case RecordingRequest.Play: Plugin.Log.LogInfo((object)$"Player {senderId} asked to show recording {num}."); shared.Play(num); break; case RecordingRequest.KeepCopies: copies.AddReceiver(senderId); break; case RecordingRequest.Missing: case RecordingRequest.MissingNow: copies.Request(senderId, num, recordingRequest == RecordingRequest.MissingNow); break; case RecordingRequest.CopyReceived: { int bytes = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref bytes, default(ForPrimitives)); copies.Received(senderId, num, bytes); break; } default: shared.Handle(senderId, recordingRequest, num); break; } } } private static void OnList(ulong senderId, FastBufferReader reader) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (VersionMatches(senderId, reader)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); string[] array = new string[num]; for (int i = 0; i < num; i++) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref array[i], false); } clientList = array; } } private static void OnCopy(ulong senderId, FastBufferReader reader) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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) //IL_0070: Unknown result type (might be due to invalid IL or missing references) if (!VersionMatches(senderId, reader)) { return; } CopyKind copyKind = default(CopyKind); ((FastBufferReader)(ref reader)).ReadValueSafe<CopyKind>(ref copyKind, default(ForEnums)); int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); switch (copyKind) { case CopyKind.Gone: Plugin.Log.LogWarning((object)$"The host cannot send recording copy {num}."); copies.Broken(num); break; case CopyKind.Offer: { int num2 = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num2, default(ForPrimitives)); RecordingInfo info = ReadInfo(reader); if (FilePieces.IsValidSize(num2)) { copies.Offered(num, info, num2); } else { Plugin.Log.LogWarning((object)$"The host offered a recording of {num2} bytes; it is refused."); } break; } default: { if (ReadPiece(reader, out int fileBytes, out int offset, out byte[] piece)) { copies.Piece(num, fileBytes, offset, piece); } else { copies.Lost(num); } break; } } } private static void OnPlayback(ulong senderId, FastBufferReader reader) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (!VersionMatches(senderId, reader)) { return; } PlaybackPacket playbackPacket = ReadPacket(reader); if (playbackPacket is PlaybackPrepare prepare) { Prepare(prepare); return; } if (playbackPacket is PlaybackEnd && download?.PlayId == playbackPacket.PlayId) { download = null; } playback.Receive(playbackPacket); } private static void Prepare(PlaybackPrepare prepare) { download = null; string text = RecordingRules.Label(prepare.Number, prepare.Info); string text2 = RecordingLibrary.FindLocal(RecordingRules.FileName(prepare.Info), prepare.FileBytes); if (text2 != null) { try { Show(prepare.PlayId, File.ReadAllBytes(text2), text); return; } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { Plugin.Log.LogWarning((object)("Could not read " + text2 + ", asking the host for it again: " + ex.Message)); } } if (!FilePieces.IsValidSize(prepare.FileBytes)) { Plugin.Log.LogWarning((object)$"The host announced a recording of {prepare.FileBytes} bytes; it is refused."); Ask(RecordingRequest.Failed, prepare.PlayId); } else { download = (prepare.PlayId, text, prepare.CopyId); playback.ShowDownload(prepare.PlayId, text); Ask(RecordingRequest.MissingNow, prepare.CopyId); } } private static void Show(int playId, byte[] file, string label) { try { playback.Show(playId, RecordingFile.Read(file), label); } catch (InvalidDataException ex) { Plugin.Log.LogError((object)("The recording to watch is broken: " + ex.Message)); Ask(RecordingRequest.Failed, playId); return; } Ask(RecordingRequest.Ready, playId); } private static void WritePiece(FastBufferWriter writer, byte[] file, int offset, int length) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) int num = file.Length; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref offset, default(ForPrimitives)); ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref length, default(ForPrimitives)); ((FastBufferWriter)(ref writer)).WriteBytesSafe(file, length, offset); } private static bool ReadPiece(FastBufferReader reader, out int fileBytes, out int offset, out byte[] piece) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref fileBytes, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref offset, default(ForPrimitives)); int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); piece = Array.Empty<byte>(); if (!FilePieces.IsValid(fileBytes, offset, num)) { return false; } piece = new byte[num]; ((FastBufferReader)(ref reader)).ReadBytesSafe(ref piece, num, 0); return true; } private static void WriteInfo(FastBufferWriter writer, RecordingInfo info) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) ((FastBufferWriter)(ref writer)).WriteValueSafe(info.Player, false); ((FastBufferWriter)(ref writer)).WriteValueSafe(info.Moon, false); int day = info.Day; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref day, default(ForPrimitives)); ((FastBufferWriter)(ref writer)).WriteValueSafe(info.Cause, false); long ticks = info.RecordedAtUtc.Ticks; ((FastBufferWriter)(ref writer)).WriteValueSafe<long>(ref ticks, default(ForPrimitives)); } private static RecordingInfo ReadInfo(FastBufferReader reader) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) string player = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref player, false); string moon = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref moon, false); int day = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref day, default(ForPrimitives)); string cause = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref cause, false); long ticks = default(long); ((FastBufferReader)(ref reader)).ReadValueSafe<long>(ref ticks, default(ForPrimitives)); return new RecordingInfo(player, moon, day, cause, new DateTime(ticks, DateTimeKind.Utc)); } private static void WritePacket(FastBufferWriter writer, PlaybackPacket packet) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: 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_00e9: 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_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) if (!(packet is PlaybackPrepare playbackPrepare)) { if (!(packet is PlaybackWaiting playbackWaiting)) { if (!(packet is PlaybackState playbackState)) { if (!(packet is PlaybackEnd playbackEnd)) { throw new ArgumentOutOfRangeException("packet", packet.GetType().Name, "Unknown playback packet."); } PacketKind packetKind = PacketKind.End; ((FastBufferWriter)(ref writer)).WriteValueSafe<PacketKind>(ref packetKind, default(ForEnums)); int playId = playbackEnd.PlayId; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); } else { PacketKind packetKind = PacketKind.State; ((FastBufferWriter)(ref writer)).WriteValueSafe<PacketKind>(ref packetKind, default(ForEnums)); int playId = playbackState.PlayId; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); bool playing = playbackState.Playing; ((FastBufferWriter)(ref writer)).WriteValueSafe<bool>(ref playing, default(ForPrimitives)); playId = playbackState.PositionMs; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); } } else { PacketKind packetKind = PacketKind.Waiting; ((FastBufferWriter)(ref writer)).WriteValueSafe<PacketKind>(ref packetKind, default(ForEnums)); int playId = playbackWaiting.PlayId; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); playId = playbackWaiting.Ready; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); playId = playbackWaiting.Players; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); } } else { PacketKind packetKind = PacketKind.Prepare; ((FastBufferWriter)(ref writer)).WriteValueSafe<PacketKind>(ref packetKind, default(ForEnums)); int playId = playbackPrepare.PlayId; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); playId = playbackPrepare.Number; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); playId = playbackPrepare.FileBytes; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); playId = playbackPrepare.CopyId; ((FastBufferWriter)(ref writer)).WriteValueSafe<int>(ref playId, default(ForPrimitives)); WriteInfo(writer, playbackPrepare.Info); } } private static PlaybackPacket ReadPacket(FastBufferReader reader) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) PacketKind packetKind = default(PacketKind); ((FastBufferReader)(ref reader)).ReadValueSafe<PacketKind>(ref packetKind, default(ForEnums)); int playId = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref playId, default(ForPrimitives)); switch (packetKind) { case PacketKind.Prepare: { int number = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref number, default(ForPrimitives)); int fileBytes = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref fileBytes, default(ForPrimitives)); int copyId = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref copyId, default(ForPrimitives)); return new PlaybackPrepare(playId, number, ReadInfo(reader), fileBytes, copyId); } case PacketKind.Waiting: { int ready = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref ready, default(ForPrimitives)); int players = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref players, default(ForPrimitives)); return new PlaybackWaiting(playId, ready, players); } case PacketKind.State: { bool playing = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref playing, default(ForPrimitives)); int positionMs = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref positionMs, default(ForPrimitives)); return new PlaybackState(playId, playing, positionMs); } case PacketKind.End: return new PlaybackEnd(playId); default: throw new ArgumentOutOfRangeException("kind", packetKind, "Unknown playback packet from the host."); } } } [HarmonyPatch] internal static class RecordingPatches { private static TerminalNode? page; private static RecordingServer? webPage; public static void Install(ConfigFile config, Harmony harmony) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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) RecordingState.Bind(config); if (!RecordingState.Enabled) { Plugin.Log.LogInfo((object)"Recordings are turned off in the config."); return; } GameObject val = new GameObject("Multipla.Recordings") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)val); val.AddComponent<DeathRecorder>(); MonitorPlayback monitorPlayback = val.AddComponent<MonitorPlayback>(); RecordingCopies recordingCopies = val.AddComponent<RecordingCopies>(); SharedPlayback sharedPlayback = val.AddComponent<SharedPlayback>(); sharedPlayback.Attach(monitorPlayback, recordingCopies); RecordingNetwork.Install(val.AddComponent<RecordingUploader>(), recordingCopies, sharedPlayback, monitorPlayback); harmony.PatchAll(typeof(RecordingPatches)); if (RecordingState.WebPage) { StartWebPage(); } } private static void StartWebPage() { RecordingServer recordingServer = new RecordingServer(RecordingLibrary.Root, RecordingState.WebPagePort, delegate(string message) { Plugin.Log.LogWarning((object)message); }); if (!recordingServer.Start()) { recordingServer.Dispose(); return; } webPage = recordingServer; Application.quitting += recordingServer.Dispose; Plugin.Log.LogInfo((object)("Recordings web page: " + recordingServer.Address)); } private static string OpenWebPage() { if (webPage == null) { if (!RecordingState.WebPage) { return