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 LethalTV v1.1.0
LethalTV.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using Microsoft.CodeAnalysis; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.Video; [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("LethalTV")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0")] [assembly: AssemblyProduct("LethalTV")] [assembly: AssemblyTitle("LethalTV")] [assembly: AssemblyVersion("1.1.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LethalTV { internal interface IByteSource { long Length { get; } int Read(long position, IntPtr dest, int count, int timeoutMs, Func<bool> abort); void Close(); } internal sealed class FileByteSource : IByteSource { private readonly FileStream stream; private readonly byte[] scratch = new byte[65536]; private readonly object gate = new object(); private bool closed; public long Length { get; } public FileByteSource(string path) { stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 65536); Length = stream.Length; } public int Read(long position, IntPtr dest, int count, int timeoutMs, Func<bool> abort) { lock (gate) { if (closed) { return -1; } if (position >= Length || count <= 0) { return 0; } try { stream.Position = position; int i; int num; for (i = 0; i < count; i += num) { num = stream.Read(scratch, 0, Math.Min(scratch.Length, count - i)); if (num <= 0) { break; } Marshal.Copy(scratch, 0, dest + i, num); } return i; } catch (Exception ex) when (ex is IOException || ex is ObjectDisposedException) { return -1; } } } public void Close() { lock (gate) { if (!closed) { closed = true; stream.Dispose(); } } } } internal static class MF { [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int QueryInterfaceFn(IntPtr self, ref Guid iid, out IntPtr obj); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint ReleaseFn(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NoArgsFn(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SetUInt32Fn(IntPtr self, ref Guid key, uint value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SetGuidFn(IntPtr self, ref Guid key, ref Guid value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetUInt32Fn(IntPtr self, ref Guid key, out uint value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetUInt64Fn(IntPtr self, ref Guid key, out ulong value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateFromByteStreamFn(IntPtr self, IntPtr byteStream, [MarshalAs(UnmanagedType.LPWStr)] string url, uint flags, IntPtr props, out uint objectType, out IntPtr obj); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SetStreamSelectionFn(IntPtr self, uint stream, int selected); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SetCurrentMediaTypeFn(IntPtr self, uint stream, IntPtr reserved, IntPtr type); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetCurrentMediaTypeFn(IntPtr self, uint stream, out IntPtr type); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SetCurrentPositionFn(IntPtr self, ref Guid format, IntPtr position); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int ReadSampleFn(IntPtr self, uint stream, uint control, out uint actualStream, out uint flags, out long timestamp, out IntPtr sample); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetLongFn(IntPtr self, out long value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetPointerFn(IntPtr self, out IntPtr value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int LockFn(IntPtr self, out IntPtr data, out uint maxLength, out uint currentLength); public const int S_OK = 0; public const int S_FALSE = 1; public const int E_NOTIMPL = -2147467263; public const int E_NOINTERFACE = -2147467262; public const int E_POINTER = -2147467261; public const int E_FAIL = -2147467259; public const uint FirstVideoStream = 4294967292u; public const uint FirstAudioStream = 4294967293u; public const uint AllStreams = 4294967294u; public const uint ReaderFlagError = 1u; public const uint ReaderFlagEndOfStream = 2u; public const uint ReaderFlagCurrentTypeChanged = 32u; public static Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046"); public static Guid IID_ISequentialStream = new Guid("0c733a30-2a1c-11ce-ade5-00aa0044773d"); public static Guid IID_IStream = new Guid("0000000c-0000-0000-C000-000000000046"); public static Guid IID_IMFMediaSource = new Guid("279a808d-aec7-40c8-9c6b-a6b492c78a66"); public static Guid MT_MajorType = new Guid("48eba18e-f8c9-4687-bf11-0a74c9f96a8f"); public static Guid MT_Subtype = new Guid("f7e34c9a-42e8-4714-b74b-cb29d72c35e5"); public static Guid MT_FrameSize = new Guid("1652c33d-d6b2-4012-b834-72030849a37d"); public static Guid MT_DefaultStride = new Guid("644b4e48-1e02-4516-b0eb-c01ca9d49ac6"); public static Guid MT_PixelAspectRatio = new Guid("c6376a1e-8d0a-4027-be45-6d9a0ad39bb6"); public static Guid MT_AudioChannels = new Guid("37e48bf5-645e-4c5b-89de-ada9e29b696a"); public static Guid MT_AudioSampleRate = new Guid("5faeeae7-0290-4c31-9e8a-c534f68d9dba"); public static Guid MT_AudioBitsPerSample = new Guid("f2deb57f-40fa-4764-aa33-ed4f2d1ff669"); public static Guid Reader_EnableVideoProcessing = new Guid("fb394f3d-ccf1-42ee-bbb3-f9b845d5681d"); public static Guid MediaType_Video = new Guid("73646976-0000-0010-8000-00AA00389B71"); public static Guid MediaType_Audio = new Guid("73647561-0000-0010-8000-00AA00389B71"); public static Guid VideoFormat_RGB32 = new Guid("00000016-0000-0010-8000-00AA00389B71"); public static Guid AudioFormat_Float = new Guid("00000003-0000-0010-8000-00AA00389B71"); private const uint Version = 131184u; private const uint StartupLite = 1u; private const uint ResolutionMediaSource = 1u; private const uint ResolutionAnyContent = 16u; private const uint ResolutionRead = 65536u; private static readonly Dictionary<IntPtr, Delegate> delegates = new Dictionary<IntPtr, Delegate>(); [DllImport("ole32.dll")] public static extern int CoInitializeEx(IntPtr reserved, uint coInit); [DllImport("ole32.dll")] public static extern void CoUninitialize(); [DllImport("mfplat.dll")] public static extern int MFStartup(uint version, uint flags); [DllImport("mfplat.dll")] public static extern int MFShutdown(); [DllImport("mfplat.dll")] private static extern int MFCreateAttributes(out IntPtr attributes, uint initialSize); [DllImport("mfplat.dll")] private static extern int MFCreateMediaType(out IntPtr type); [DllImport("mfplat.dll")] private static extern int MFCreateSourceResolver(out IntPtr resolver); [DllImport("mfplat.dll")] private static extern int MFCreateMFByteStreamOnStream(IntPtr stream, out IntPtr byteStream); [DllImport("mfreadwrite.dll")] private static extern int MFCreateSourceReaderFromMediaSource(IntPtr source, IntPtr attributes, out IntPtr reader); public static void Startup() { Check(MFStartup(131184u, 1u), "MFStartup"); } public static void Check(int hr, string what) { if (hr < 0) { throw new COMException($"{what} failed (0x{hr:X8})", hr); } } private static T Method<T>(IntPtr obj, int slot) where T : Delegate { if (obj == IntPtr.Zero) { throw new NullReferenceException("COM object is null"); } IntPtr intPtr = Marshal.ReadIntPtr(Marshal.ReadIntPtr(obj), slot * IntPtr.Size); lock (delegates) { if (!delegates.TryGetValue(intPtr, out var value) || !(value is T)) { value = (delegates[intPtr] = Marshal.GetDelegateForFunctionPointer(intPtr, typeof(T))); } return (T)value; } } public static void Release(ref IntPtr obj) { if (obj != IntPtr.Zero) { Method<ReleaseFn>(obj, 2)(obj); obj = IntPtr.Zero; } } public static IntPtr QueryInterface(IntPtr obj, Guid iid) { Check(Method<QueryInterfaceFn>(obj, 0)(obj, ref iid, out var obj2), "QueryInterface"); return obj2; } public static void SetUInt32(IntPtr attrs, Guid key, uint value) { Check(Method<SetUInt32Fn>(attrs, 21)(attrs, ref key, value), "SetUINT32"); } public static void SetGuid(IntPtr attrs, Guid key, Guid value) { Check(Method<SetGuidFn>(attrs, 24)(attrs, ref key, ref value), "SetGUID"); } public static bool TryGetUInt32(IntPtr attrs, Guid key, out uint value) { return Method<GetUInt32Fn>(attrs, 7)(attrs, ref key, out value) >= 0; } public static bool TryGetUInt64(IntPtr attrs, Guid key, out ulong value) { return Method<GetUInt64Fn>(attrs, 8)(attrs, ref key, out value) >= 0; } public static IntPtr CreateAttributes() { Check(MFCreateAttributes(out var attributes, 2u), "MFCreateAttributes"); return attributes; } public static IntPtr CreateMediaType(Guid major, Guid subtype) { Check(MFCreateMediaType(out var type), "MFCreateMediaType"); SetGuid(type, MT_MajorType, major); SetGuid(type, MT_Subtype, subtype); return type; } public static IntPtr CreateMediaSource(IntPtr stream, string nameHint, out IntPtr byteStream) { Check(MFCreateMFByteStreamOnStream(stream, out byteStream), "MFCreateMFByteStreamOnStream"); IntPtr resolver = IntPtr.Zero; IntPtr obj = IntPtr.Zero; try { Check(MFCreateSourceResolver(out resolver), "MFCreateSourceResolver"); Check(Method<CreateFromByteStreamFn>(resolver, 4)(resolver, byteStream, nameHint, 65553u, IntPtr.Zero, out var _, out obj), "CreateObjectFromByteStream"); return QueryInterface(obj, IID_IMFMediaSource); } finally { Release(ref obj); Release(ref resolver); } } public static void ShutdownSource(IntPtr source) { Method<NoArgsFn>(source, 12)(source); } public static IntPtr CreateSourceReader(IntPtr source, IntPtr attrs) { Check(MFCreateSourceReaderFromMediaSource(source, attrs, out var reader), "MFCreateSourceReaderFromMediaSource"); return reader; } public static int SetStreamSelection(IntPtr reader, uint stream, bool selected) { return Method<SetStreamSelectionFn>(reader, 4)(reader, stream, selected ? 1 : 0); } public static int SetCurrentMediaType(IntPtr reader, uint stream, IntPtr type) { return Method<SetCurrentMediaTypeFn>(reader, 7)(reader, stream, IntPtr.Zero, type); } public static IntPtr GetCurrentMediaType(IntPtr reader, uint stream) { Check(Method<GetCurrentMediaTypeFn>(reader, 6)(reader, stream, out var type), "GetCurrentMediaType"); return type; } public static void SetPosition(IntPtr reader, long hundredNs) { IntPtr intPtr = Marshal.AllocHGlobal(24); try { for (int i = 0; i < 24; i += 8) { Marshal.WriteInt64(intPtr, i, 0L); } Marshal.WriteInt16(intPtr, 0, 20); Marshal.WriteInt64(intPtr, 8, hundredNs); Guid format = Guid.Empty; Check(Method<SetCurrentPositionFn>(reader, 8)(reader, ref format, intPtr), "SetCurrentPosition"); } finally { Marshal.FreeHGlobal(intPtr); } } public static int ReadSample(IntPtr reader, uint stream, out uint actualStream, out uint flags, out long timestamp, out IntPtr sample) { return Method<ReadSampleFn>(reader, 9)(reader, stream, 0u, out actualStream, out flags, out timestamp, out sample); } public static long SampleDuration(IntPtr sample) { if (Method<GetLongFn>(sample, 37)(sample, out var value) < 0) { return 0L; } return value; } public static IntPtr ContiguousBuffer(IntPtr sample) { Check(Method<GetPointerFn>(sample, 41)(sample, out var value), "ConvertToContiguousBuffer"); return value; } public static IntPtr Lock(IntPtr buffer, out int length) { Check(Method<LockFn>(buffer, 3)(buffer, out var data, out var _, out var currentLength), "Lock"); length = (int)currentLength; return data; } public static void Unlock(IntPtr buffer) { Method<NoArgsFn>(buffer, 4)(buffer); } } internal sealed class NativeStream : IDisposable { [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int QueryInterfaceFn(IntPtr self, ref Guid iid, out IntPtr obj); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint RefFn(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int ReadFn(IntPtr self, IntPtr pv, uint cb, IntPtr read); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int WriteFn(IntPtr self, IntPtr pv, uint cb, IntPtr written); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SeekFn(IntPtr self, long move, uint origin, IntPtr newPosition); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SetSizeFn(IntPtr self, ulong size); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CopyToFn(IntPtr self, IntPtr target, ulong cb, IntPtr read, IntPtr written); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CommitFn(IntPtr self, uint flags); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int RevertFn(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int RegionFn(IntPtr self, ulong offset, ulong cb, uint type); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int StatFn(IntPtr self, IntPtr stat, uint flags); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CloneFn(IntPtr self, IntPtr clone); public static Action<string> Log; private static readonly Delegate[] Methods = new Delegate[14] { new QueryInterfaceFn(QueryInterface), new RefFn(AddRef), new RefFn(Release), new ReadFn(Read), new WriteFn(Write), new SeekFn(Seek), new SetSizeFn(SetSize), new CopyToFn(CopyTo), new CommitFn(Commit), new RevertFn(Revert), new RegionFn(LockRegion), new RegionFn(UnlockRegion), new StatFn(Stat), new CloneFn(Clone) }; private static IntPtr vtable; private static readonly Dictionary<IntPtr, NativeStream> live = new Dictionary<IntPtr, NativeStream>(); private readonly IByteSource buffer; private readonly int timeoutMs; private readonly Func<bool> abort; private readonly object positionLock = new object(); private long position; private int refs = 1; private bool disposed; public IntPtr Pointer { get; } public NativeStream(IByteSource buffer, int timeoutMs, Func<bool> abort) { this.buffer = buffer; this.timeoutMs = timeoutMs; this.abort = abort; lock (live) { if (vtable == IntPtr.Zero) { vtable = Marshal.AllocHGlobal(IntPtr.Size * Methods.Length); for (int i = 0; i < Methods.Length; i++) { Marshal.WriteIntPtr(vtable, i * IntPtr.Size, Marshal.GetFunctionPointerForDelegate(Methods[i])); } } Pointer = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(Pointer, vtable); live[Pointer] = this; } } public void Dispose() { if (!disposed) { disposed = true; Release(Pointer); } } private static NativeStream Find(IntPtr self) { lock (live) { NativeStream value; return live.TryGetValue(self, out value) ? value : null; } } private static int QueryInterface(IntPtr self, ref Guid iid, out IntPtr obj) { obj = IntPtr.Zero; if (iid != MF.IID_IUnknown && iid != MF.IID_ISequentialStream && iid != MF.IID_IStream) { return -2147467262; } if (Find(self) == null) { return -2147467259; } AddRef(self); obj = self; return 0; } private static uint AddRef(IntPtr self) { lock (live) { NativeStream value; return live.TryGetValue(self, out value) ? ((uint)(++value.refs)) : 0u; } } private static uint Release(IntPtr self) { lock (live) { if (!live.TryGetValue(self, out var value)) { return 0u; } int num = --value.refs; if (num <= 0) { live.Remove(self); Marshal.FreeHGlobal(self); } return (uint)Math.Max(0, num); } } private static int Read(IntPtr self, IntPtr pv, uint cb, IntPtr read) { try { if (read != IntPtr.Zero) { Marshal.WriteInt32(read, 0); } NativeStream nativeStream = Find(self); if (nativeStream == null || pv == IntPtr.Zero) { return -2147467259; } lock (nativeStream.positionLock) { int num = nativeStream.buffer.Read(nativeStream.position, pv, (int)Math.Min(cb, 2147483647u), nativeStream.timeoutMs, nativeStream.abort); if (num < 0) { return -2147467259; } nativeStream.position += num; if (read != IntPtr.Zero) { Marshal.WriteInt32(read, num); } return (num == 0 && cb != 0) ? 1 : 0; } } catch (Exception ex) { Log?.Invoke("IStream.Read: " + ex.Message); return -2147467259; } } private static int Seek(IntPtr self, long move, uint origin, IntPtr newPosition) { NativeStream nativeStream = Find(self); if (nativeStream == null) { return -2147467259; } lock (nativeStream.positionLock) { long num = origin switch { 1u => nativeStream.position, 0u => 0L, _ => nativeStream.buffer.Length, } + move; if (num < 0) { return -2147287015; } nativeStream.position = num; if (newPosition != IntPtr.Zero) { Marshal.WriteInt64(newPosition, num); } return 0; } } private static int Stat(IntPtr self, IntPtr stat, uint flags) { NativeStream nativeStream = Find(self); if (nativeStream == null || stat == IntPtr.Zero) { return -2147467259; } int num = ((IntPtr.Size == 8) ? 80 : 72); for (int i = 0; i < num; i += 4) { Marshal.WriteInt32(stat, i, 0); } Marshal.WriteInt32(stat, IntPtr.Size, 2); Marshal.WriteInt64(stat, (IntPtr.Size == 8) ? 16 : 8, nativeStream.buffer.Length); return 0; } private static int Unsupported(string what) { Log?.Invoke("IStream." + what + " called (not supported)"); return -2147467263; } private static int Write(IntPtr self, IntPtr pv, uint cb, IntPtr written) { return Unsupported("Write"); } private static int SetSize(IntPtr self, ulong size) { return Unsupported("SetSize"); } private static int CopyTo(IntPtr self, IntPtr target, ulong cb, IntPtr read, IntPtr written) { return Unsupported("CopyTo"); } private static int Commit(IntPtr self, uint flags) { return 0; } private static int Revert(IntPtr self) { return Unsupported("Revert"); } private static int LockRegion(IntPtr self, ulong offset, ulong cb, uint type) { return Unsupported("LockRegion"); } private static int UnlockRegion(IntPtr self, ulong offset, ulong cb, uint type) { return Unsupported("UnlockRegion"); } private static int Clone(IntPtr self, IntPtr clone) { if (clone != IntPtr.Zero) { Marshal.WriteIntPtr(clone, IntPtr.Zero); } return Unsupported("Clone"); } } internal sealed class MfDecoder : IDisposable { public sealed class Frame { public double Time; public byte[] Pixels; } public sealed class AudioChunk { public double Time; public float[] Samples; } private const int MaxQueuedFrames = 6; private const double MaxQueuedAudio = 1.5; public long FramesDecoded; public double DecodeSeconds; private readonly IByteSource buffer; private readonly bool closeSource; private readonly string nameHint; private readonly Func<double, bool> canRead; private readonly Thread thread; private volatile bool stopping; private readonly object gate = new object(); private readonly Queue<Frame> frames = new Queue<Frame>(); private readonly Stack<byte[]> pool = new Stack<byte[]>(); private readonly Queue<AudioChunk> audio = new Queue<AudioChunk>(); private double queuedAudioSeconds; private double seekRequest = -1.0; private int stride; public int Width { get; private set; } public int Height { get; private set; } public float PixelAspect { get; private set; } = 1f; public int Channels { get; private set; } public int SampleRate { get; private set; } public bool HasVideo { get; private set; } public bool HasAudio { get; private set; } public bool Opened { get; private set; } public bool VideoEnded { get; private set; } public bool AudioEnded { get; private set; } public string Error { get; private set; } public MfDecoder(IByteSource buffer, bool closeSource, string nameHint, double startAt, Func<double, bool> canRead) { this.buffer = buffer; this.closeSource = closeSource; this.nameHint = nameHint; this.canRead = canRead; seekRequest = Math.Max(0.0, startAt); thread = new Thread(Run) { IsBackground = true, Name = "LethalTV decoder" }; thread.Start(); } public void Seek(double seconds) { lock (gate) { seekRequest = Math.Max(0.0, seconds); while (frames.Count > 0) { pool.Push(frames.Dequeue().Pixels); } audio.Clear(); queuedAudioSeconds = 0.0; } } public Frame TakeFrame(double clock) { lock (gate) { Frame frame = null; while (frames.Count > 0 && frames.Peek().Time <= clock) { if (frame != null) { pool.Push(frame.Pixels); } frame = frames.Dequeue(); } return frame; } } public double NextFrameTime() { lock (gate) { return (frames.Count > 0) ? frames.Peek().Time : double.NaN; } } public void Recycle(Frame f) { if (f == null) { return; } lock (gate) { if (f.Pixels != null && f.Pixels.Length == Width * Height * 4) { pool.Push(f.Pixels); } } } public double NextAudioTime() { lock (gate) { return (audio.Count > 0) ? audio.Peek().Time : double.NaN; } } public AudioChunk TakeAudio() { lock (gate) { if (audio.Count == 0) { return null; } AudioChunk audioChunk = audio.Dequeue(); queuedAudioSeconds -= (double)audioChunk.Samples.Length / (double)Math.Max(1, Channels * SampleRate); return audioChunk; } } public void Dispose() { stopping = true; } private void Run() { IntPtr obj = IntPtr.Zero; IntPtr byteStream = IntPtr.Zero; IntPtr obj2 = IntPtr.Zero; NativeStream nativeStream = null; bool flag = false; bool flag2 = false; try { flag = MF.CoInitializeEx(IntPtr.Zero, 0u) >= 0; MF.Startup(); flag2 = true; nativeStream = new NativeStream(buffer, 20000, () => stopping); obj = MF.CreateMediaSource(nativeStream.Pointer, nameHint, out byteStream); IntPtr obj3 = MF.CreateAttributes(); try { MF.SetUInt32(obj3, MF.Reader_EnableVideoProcessing, 1u); obj2 = MF.CreateSourceReader(obj, obj3); } finally { MF.Release(ref obj3); } MF.SetStreamSelection(obj2, 4294967294u, selected: false); HasVideo = MF.SetStreamSelection(obj2, 4294967292u, selected: true) >= 0 && SetOutput(obj2, 4294967292u, MF.MediaType_Video, MF.VideoFormat_RGB32); HasAudio = MF.SetStreamSelection(obj2, 4294967293u, selected: true) >= 0 && SetOutput(obj2, 4294967293u, MF.MediaType_Audio, MF.AudioFormat_Float); if (!HasVideo && !HasAudio) { throw new Exception("no playable video or audio track"); } if (HasVideo) { ReadVideoFormat(obj2); } if (HasAudio) { ReadAudioFormat(obj2); } Opened = true; Loop(obj2); } catch (Exception ex) { if (!stopping) { Error = ex.Message; } } finally { MF.Release(ref obj2); if (obj != IntPtr.Zero) { try { MF.ShutdownSource(obj); } catch (Exception) { } } MF.Release(ref obj); MF.Release(ref byteStream); nativeStream?.Dispose(); if (closeSource) { buffer.Close(); } if (flag2) { MF.MFShutdown(); } if (flag) { MF.CoUninitialize(); } } } private static bool SetOutput(IntPtr reader, uint stream, Guid major, Guid subtype) { IntPtr obj = MF.CreateMediaType(major, subtype); try { return MF.SetCurrentMediaType(reader, stream, obj) >= 0; } finally { MF.Release(ref obj); } } private void ReadVideoFormat(IntPtr reader) { IntPtr obj = MF.GetCurrentMediaType(reader, 4294967292u); try { if (!MF.TryGetUInt64(obj, MF.MT_FrameSize, out var value)) { throw new Exception("video has no frame size"); } int num = (int)(value >> 32); int num2 = (int)(value & 0xFFFFFFFFu); if (num <= 0 || num2 <= 0 || num > 8192 || num2 > 8192) { throw new Exception($"bad frame size {num}x{num2}"); } stride = (MF.TryGetUInt32(obj, MF.MT_DefaultStride, out var value2) ? ((int)value2) : (num * 4)); PixelAspect = ((MF.TryGetUInt64(obj, MF.MT_PixelAspectRatio, out var value3) && (value3 & 0xFFFFFFFFu) != 0L) ? ((float)(value3 >> 32) / (float)(value3 & 0xFFFFFFFFu)) : 1f); lock (gate) { if (num != Width || num2 != Height) { pool.Clear(); } Width = num; Height = num2; } } finally { MF.Release(ref obj); } } private void ReadAudioFormat(IntPtr reader) { IntPtr obj = MF.GetCurrentMediaType(reader, 4294967293u); try { MF.TryGetUInt32(obj, MF.MT_AudioChannels, out var value); MF.TryGetUInt32(obj, MF.MT_AudioSampleRate, out var value2); MF.TryGetUInt32(obj, MF.MT_AudioBitsPerSample, out var value3); if (value == 0 || value2 == 0 || value3 != 32) { throw new Exception($"unexpected audio format ({value} ch, {value2} Hz, {value3} bit)"); } Channels = (int)value; SampleRate = (int)value2; } finally { MF.Release(ref obj); } } private void Loop(IntPtr reader) { double num = 0.0; double num2 = 0.0; while (!stopping) { double num3; lock (gate) { num3 = seekRequest; seekRequest = -1.0; } if (num3 >= 0.0) { MF.SetPosition(reader, (long)(num3 * 10000000.0)); num = (num2 = num3); VideoEnded = !HasVideo; AudioEnded = !HasAudio; } bool flag; bool flag2; lock (gate) { flag = HasVideo && !VideoEnded && frames.Count < 6; flag2 = HasAudio && !AudioEnded && queuedAudioSeconds < 1.5; } if (!flag && !flag2) { Thread.Sleep(5); continue; } bool flag3 = flag && (!flag2 || num <= num2); double num4 = (flag3 ? num : num2); if (!canRead(num4 + 1.0)) { Thread.Sleep(10); continue; } DateTime utcNow = DateTime.UtcNow; uint actualStream; uint flags; long timestamp; IntPtr sample; int hr = MF.ReadSample(reader, flag3 ? 4294967292u : 4294967293u, out actualStream, out flags, out timestamp, out sample); DecodeSeconds += (DateTime.UtcNow - utcNow).TotalSeconds; if (stopping) { MF.Release(ref sample); break; } MF.Check(hr, "ReadSample"); if ((flags & 1) != 0) { throw new Exception("decoder reported an error"); } if ((flags & 0x20) != 0) { if (flag3) { ReadVideoFormat(reader); } else { ReadAudioFormat(reader); } } bool flag4; lock (gate) { flag4 = seekRequest >= 0.0; } try { if (sample != IntPtr.Zero && !flag4) { double num5 = (double)timestamp / 10000000.0; if (flag3) { num = num5; QueueFrame(sample, num5); } else { num2 = num5; QueueAudio(sample, num5); } } } finally { MF.Release(ref sample); } if ((flags & 2) != 0) { if (flag3) { VideoEnded = true; } else { AudioEnded = true; } } } } private void QueueFrame(IntPtr sample, double time) { IntPtr obj = MF.ContiguousBuffer(sample); try { int length; IntPtr intPtr = MF.Lock(obj, out length); try { int width = Width; int height = Height; int num = width * 4; if (length < num * height) { return; } byte[] array; lock (gate) { array = ((pool.Count > 0) ? pool.Pop() : null); } if (array == null || array.Length != num * height) { array = new byte[num * height]; } if (stride < 0) { Marshal.Copy(intPtr, array, 0, num * height); } else { int num2 = Math.Max(num, stride); for (int i = 0; i < height; i++) { Marshal.Copy(intPtr + (height - 1 - i) * num2, array, i * num, num); } } for (int j = 3; j < array.Length; j += 4) { array[j] = byte.MaxValue; } lock (gate) { frames.Enqueue(new Frame { Time = time, Pixels = array }); } FramesDecoded++; } finally { MF.Unlock(obj); } } finally { MF.Release(ref obj); } } private void QueueAudio(IntPtr sample, double time) { IntPtr obj = MF.ContiguousBuffer(sample); try { int length; IntPtr source = MF.Lock(obj, out length); try { float[] array = new float[length / 4]; Marshal.Copy(source, array, 0, array.Length); lock (gate) { audio.Enqueue(new AudioChunk { Time = time, Samples = array }); queuedAudioSeconds += (double)array.Length / (double)Math.Max(1, Channels * SampleRate); } } finally { MF.Unlock(obj); } } finally { MF.Release(ref obj); } } } internal sealed class Mp4Index { private sealed class Track { public bool Video; public uint Timescale; public uint[] SttsCount; public uint[] SttsDelta; public uint[] Sync; public uint[] StscFirst; public uint[] StscPer; public uint FixedSize; public uint[] Sizes; public long[] ChunkOffsets; public long SampleCount; } private struct Box { public string Type; public int Start; public int End; } private const long MaxMoovBytes = 67108864L; public long FileSize; public double Duration; public readonly List<KeyValuePair<long, long>> Header = new List<KeyValuePair<long, long>>(); public long[] StartAt; public long[] EndBy; public int Seconds => EndBy.Length; public long Start(double t) { return StartAt[Clamp((int)Math.Floor(t))]; } public long End(double t) { return EndBy[Clamp((int)Math.Floor(t))]; } public double PlayableUntil(long end) { int num = 0; int num2 = EndBy.Length - 1; int num3 = -1; while (num <= num2) { int num4 = (num + num2) / 2; if (EndBy[num4] <= end) { num3 = num4; num = num4 + 1; } else { num2 = num4 - 1; } } return num3 + 1; } private int Clamp(int s) { if (s >= 0) { if (s < EndBy.Length) { return s; } return EndBy.Length - 1; } return 0; } public static Mp4Index Build(string path) { using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 65536); long length = fileStream.Length; Mp4Index mp4Index = new Mp4Index { FileSize = length }; byte[] array = null; bool flag = false; long num = 0L; byte[] array2 = new byte[16]; long num2; for (; num + 8 <= length; num += num2) { fileStream.Position = num; if (ReadFully(fileStream, array2, 8) < 8) { return null; } num2 = U32(array2, 0); string text = Encoding.ASCII.GetString(array2, 4, 4); int num3 = 8; switch (num2) { case 1L: if (ReadFully(fileStream, array2, 8) < 8) { return null; } num2 = (long)U64(array2, 0); num3 = 16; break; case 0L: num2 = length - num; break; } if (num2 < num3 || num + num2 > length) { return null; } switch (text) { case "mdat": flag = true; mp4Index.Header.Add(new KeyValuePair<long, long>(num, num + num3)); break; case "moof": return null; case "moov": if (num2 > 67108864) { return null; } array = new byte[num2 - num3]; fileStream.Position = num + num3; if (ReadFully(fileStream, array, array.Length) < array.Length) { return null; } mp4Index.Header.Add(new KeyValuePair<long, long>(num, num + num2)); break; default: mp4Index.Header.Add(new KeyValuePair<long, long>(num, num + num2)); break; } } if (array == null || !flag) { return null; } return mp4Index.ParseMoov(array) ? mp4Index : null; } private bool ParseMoov(byte[] moov) { List<Track> list = new List<Track>(); foreach (Box item in Children(moov, 0, moov.Length)) { if (item.Type == "mvex") { return false; } if (!(item.Type != "trak")) { Track track = ParseTrak(moov, item.Start, item.End); if (track == null) { return false; } if (track.SampleCount > 0) { list.Add(track); } } } if (list.Count == 0) { return false; } foreach (Track item2 in list) { double num = 0.0; for (int i = 0; i < item2.SttsCount.Length; i++) { num += (double)item2.SttsCount[i] * (double)item2.SttsDelta[i]; } Duration = Math.Max(Duration, num / (double)item2.Timescale); } if (!(Duration > 0.0) || Duration > 86400.0) { return false; } int num2 = (int)Math.Ceiling(Duration) + 1; long[] array = new long[num2]; long[] array2 = new long[num2]; for (int j = 0; j < num2; j++) { array2[j] = long.MaxValue; } List<double> list2 = new List<double>(); bool flag = false; foreach (Track item3 in list) { bool flag2 = item3.Video && !flag; flag |= item3.Video; if (!WalkSamples(item3, num2, array, array2, flag2 ? list2 : null)) { return false; } } EndBy = new long[num2]; long num3 = 0L; for (int k = 0; k < num2; k++) { num3 = Math.Max(num3, array[k]); EndBy[k] = num3; } long[] array3 = new long[num2 + 1]; array3[num2] = FileSize; for (int num4 = num2 - 1; num4 >= 0; num4--) { array3[num4] = Math.Min(array3[num4 + 1], array2[num4]); } StartAt = new long[num2]; int l = 0; for (int m = 0; m < num2; m++) { for (; l + 1 < list2.Count && list2[l + 1] <= (double)m; l++) { } double d = ((list2.Count == 0) ? ((double)m) : ((list2[l] <= (double)m) ? list2[l] : 0.0)); int num5 = Math.Max(0, (int)Math.Floor(d) - 1); StartAt[m] = Math.Min(array3[num5], EndBy[m]); } return true; } private bool WalkSamples(Track t, int n, long[] maxEnd, long[] minOff, List<double> keyframes) { long num = 0L; int num2 = 0; uint num3 = ((t.SttsCount.Length != 0) ? t.SttsCount[0] : 0u); long num4 = 0L; int i = 0; int j = 0; for (long num5 = 1L; num5 <= t.ChunkOffsets.Length; num5++) { if (num >= t.SampleCount) { break; } for (; j + 1 < t.StscFirst.Length && t.StscFirst[j + 1] <= num5; j++) { } long num6 = t.ChunkOffsets[num5 - 1]; uint num7 = t.StscPer[j]; uint num8 = 0u; while (num8 < num7 && num < t.SampleCount) { long num9 = ((t.Sizes != null) ? t.Sizes[num] : t.FixedSize); if (num6 < 0 || num6 + num9 > FileSize) { return false; } while (num3 == 0) { if (++num2 >= t.SttsCount.Length) { return false; } num3 = t.SttsCount[num2]; } double num10 = (double)num4 / (double)t.Timescale; int num11 = Math.Min(n - 1, Math.Max(0, (int)Math.Floor(num10))); if (num6 + num9 > maxEnd[num11]) { maxEnd[num11] = num6 + num9; } if (num6 < minOff[num11]) { minOff[num11] = num6; } if (keyframes != null) { if (t.Sync == null) { keyframes.Add(num10); } else { for (; i < t.Sync.Length && t.Sync[i] < num + 1; i++) { } if (i < t.Sync.Length && t.Sync[i] == num + 1) { keyframes.Add(num10); } } } num4 += t.SttsDelta[num2]; num3--; num6 += num9; num8++; num++; } } return num == t.SampleCount; } private static Track ParseTrak(byte[] d, int start, int end) { Track track = new Track(); Box? box = Find(d, start, end, "mdia"); if (!box.HasValue) { return null; } foreach (Box item in Children(d, box.Value.Start, box.Value.End)) { if (item.Type == "mdhd") { int start2 = item.Start; byte b = d[start2]; track.Timescale = ((b == 1) ? U32(d, start2 + 4 + 16) : U32(d, start2 + 4 + 8)); } else if (item.Type == "hdlr") { track.Video = Encoding.ASCII.GetString(d, item.Start + 8, 4) == "vide"; } } if (track.Timescale == 0) { return null; } Box? box2 = Find(d, box.Value.Start, box.Value.End, "minf"); Box? box3 = ((!box2.HasValue) ? ((Box?)null) : Find(d, box2.Value.Start, box2.Value.End, "stbl")); if (!box3.HasValue) { return null; } foreach (Box item2 in Children(d, box3.Value.Start, box3.Value.End)) { int num = item2.Start + 4; switch (item2.Type) { case "stts": { uint num7 = U32(d, num); if (!Fits(item2, 8, num7, 8)) { return null; } track.SttsCount = new uint[num7]; track.SttsDelta = new uint[num7]; for (int n = 0; n < num7; n++) { track.SttsCount[n] = U32(d, num + 4 + n * 8); track.SttsDelta[n] = U32(d, num + 8 + n * 8); } break; } case "stss": { uint num3 = U32(d, num); if (!Fits(item2, 8, num3, 4)) { return null; } track.Sync = new uint[num3]; for (int j = 0; j < num3; j++) { track.Sync[j] = U32(d, num + 4 + j * 4); } Array.Sort(track.Sync); break; } case "stsc": { uint num5 = U32(d, num); if (!Fits(item2, 8, num5, 12)) { return null; } track.StscFirst = new uint[num5]; track.StscPer = new uint[num5]; for (int l = 0; l < num5; l++) { track.StscFirst[l] = U32(d, num + 4 + l * 12); track.StscPer[l] = U32(d, num + 8 + l * 12); } break; } case "stsz": track.FixedSize = U32(d, num); track.SampleCount = U32(d, num + 4); if (track.FixedSize == 0) { if (!Fits(item2, 12, (uint)track.SampleCount, 4)) { return null; } track.Sizes = new uint[track.SampleCount]; for (int num8 = 0; num8 < track.SampleCount; num8++) { track.Sizes[num8] = U32(d, num + 8 + num8 * 4); } } break; case "stz2": { int num4 = d[num + 3]; track.SampleCount = U32(d, num + 4); if (num4 != 4 && num4 != 8 && num4 != 16) { return null; } if (item2.End - (num + 8) < (track.SampleCount * num4 + 7) / 8) { return null; } track.Sizes = new uint[track.SampleCount]; for (int k = 0; k < track.SampleCount; k++) { switch (num4) { case 16: track.Sizes[k] = (uint)((d[num + 8 + k * 2] << 8) | d[num + 9 + k * 2]); break; case 8: track.Sizes[k] = d[num + 8 + k]; break; default: track.Sizes[k] = (uint)((d[num + 8 + k / 2] >> ((k % 2 == 0) ? 4 : 0)) & 0xF); break; } } break; } case "stco": { uint num6 = U32(d, num); if (!Fits(item2, 8, num6, 4)) { return null; } track.ChunkOffsets = new long[num6]; for (int m = 0; m < num6; m++) { track.ChunkOffsets[m] = U32(d, num + 4 + m * 4); } break; } case "co64": { uint num2 = U32(d, num); if (!Fits(item2, 8, num2, 8)) { return null; } track.ChunkOffsets = new long[num2]; for (int i = 0; i < num2; i++) { track.ChunkOffsets[i] = (long)U64(d, num + 4 + i * 8); } break; } } } if (track.SampleCount == 0L) { return track; } if (track.SttsCount == null || track.StscFirst == null || track.StscFirst.Length == 0 || track.ChunkOffsets == null) { return null; } return track; } private static IEnumerable<Box> Children(byte[] d, int start, int end) { long size; for (int p = start; p + 8 <= end; p += (int)size) { size = U32(d, p); int num = 8; switch (size) { case 1L: if (p + 16 > end) { yield break; } size = (long)U64(d, p + 8); num = 16; break; case 0L: size = end - p; break; } if (size < num || p + size > end) { break; } yield return new Box { Type = Encoding.ASCII.GetString(d, p + 4, 4), Start = p + num, End = (int)(p + size) }; } } private static Box? Find(byte[] d, int start, int end, string type) { foreach (Box item in Children(d, start, end)) { if (item.Type == type) { return item; } } return null; } private static bool Fits(Box box, int fixedHeader, uint count, int entry) { return (long)box.End - (long)box.Start >= fixedHeader + count * entry; } private static uint U32(byte[] b, int p) { return (uint)((b[p] << 24) | (b[p + 1] << 16) | (b[p + 2] << 8) | b[p + 3]); } private static ulong U64(byte[] b, int p) { return ((ulong)U32(b, p) << 32) | U32(b, p + 4); } private static int ReadFully(Stream s, byte[] buffer, int count) { int i; int num; for (i = 0; i < count; i += num) { num = s.Read(buffer, i, count - i); if (num <= 0) { break; } } return i; } } [BepInPlugin("brant.LethalTV", "LethalTV", "1.1.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public const string Guid = "brant.LethalTV"; public const string Name = "LethalTV"; public const string Version = "1.1.0"; internal static ManualLogSource Log; internal static PluginConfig Cfg; internal static TVRemoteInputs Inputs; private void Awake() { //IL_004e: 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) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; NativeStream.Log = delegate(string s) { Log.LogWarning((object)s); }; Cfg = new PluginConfig(((BaseUnityPlugin)this).Config); Inputs = new TVRemoteInputs(); new Harmony("brant.LethalTV").PatchAll(typeof(TVScriptPatches)); GameObject val = new GameObject("LethalTV") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)val); val.AddComponent<TVSyncManager>(); Log.LogInfo((object)("LethalTV 1.1.0 loaded. Host video folder: " + VideoLibrary.Folder)); } } internal sealed class PluginConfig { public readonly ConfigEntry<string> VideoFolder; public readonly ConfigEntry<bool> Shuffle; public readonly ConfigEntry<bool> AllowClientControl; public readonly ConfigEntry<int> StreamUploadCapKBps; public readonly ConfigEntry<float> Volume; public readonly ConfigEntry<bool> Muted; public readonly ConfigEntry<float> VolumeStep; public readonly ConfigEntry<float> RemoteRange; public readonly ConfigEntry<bool> ShowHud; public readonly ConfigEntry<int> BufferSeconds; public PluginConfig(ConfigFile cfg) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Expected O, but got Unknown VideoFolder = cfg.Bind<string>("Host", "VideoFolder", "", "Folder the host's videos are loaded from. Leave empty to use <your Videos folder>\\LethalTV. Videos must be .mp4, .m4v or .mov; H.264 video + AAC audio works best."); Shuffle = cfg.Bind<bool>("Host", "Shuffle", false, "Shuffle the playlist order each time you host. Otherwise videos play in file name order."); AllowClientControl = cfg.Bind<bool>("Host", "AllowClientControl", true, "Let other players change videos with the TV remote. Anyone can still turn the TV on/off, like vanilla."); StreamUploadCapKBps = cfg.Bind<int>("Host", "StreamUploadCapKBps", 0, "Most upload bandwidth (KB/s, shared by everyone) used to stream the TV to other players. Each player only receives the video they're watching, at about its bitrate, and streams slow down by themselves if they start adding lag. 0 = no cap."); Volume = cfg.Bind<float>("Player", "Volume", 1f, new ConfigDescription("Your personal TV volume (only affects what you hear).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); Muted = cfg.Bind<bool>("Player", "Muted", false, "Your personal TV mute."); VolumeStep = cfg.Bind<float>("Player", "VolumeStep", 0.1f, new ConfigDescription("How much one volume button press changes the volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 0.5f), Array.Empty<object>())); RemoteRange = cfg.Bind<float>("Player", "RemoteRange", 20f, "How close to the TV (in meters) you need to be to use the remote when you're not inside the ship."); ShowHud = cfg.Bind<bool>("Player", "ShowHud", true, "Show the on-screen TV banner when you use the remote or the video changes."); BufferSeconds = cfg.Bind<int>("Player", "BufferSeconds", 10, new ConfigDescription("How many seconds of video to load ahead while watching. Kept in memory only, never saved to disk. Raise it if the TV stutters on a bad connection.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(4, 60), Array.Empty<object>())); } } internal sealed class StreamBuffer : IByteSource { public const int BlockSize = 16384; public const int UnitSize = 1024; private readonly byte[][] blocks; private readonly int[] units; private readonly object gate = new object(); private bool closed; private long held; public Action<long, int> SlowRead; public long Length { get; } public int BlockCount => blocks.Length; public long BytesHeld { get { lock (gate) { return held; } } } public long ReadAhead { get; private set; } public StreamBuffer(long length) { Length = length; int num = (int)((length + 16384 - 1) / 16384); blocks = new byte[num][]; units = new int[num]; } private int BlockLength(int b) { return (int)Math.Min(16384L, Length - (long)b * 16384L); } private int FullMask(int b) { return (int)((1L << (BlockLength(b) + 1024 - 1) / 1024) - 1); } private bool Complete(int b) { if (blocks[b] != null) { return units[b] == FullMask(b); } return false; } public bool HasBlock(int b) { lock (gate) { return b >= 0 && b < blocks.Length && Complete(b); } } public bool Write(long offset, byte[] data, int start, int count) { if (offset < 0 || count <= 0 || offset % 1024 != 0L || offset + count > Length) { return false; } int num = (int)(offset / 16384); int num2 = (int)(offset % 16384); if (num2 + count > BlockLength(num) || (count % 1024 != 0 && offset + count != Length)) { return false; } lock (gate) { if (closed) { return false; } if (blocks[num] == null) { blocks[num] = new byte[BlockLength(num)]; units[num] = 0; held += blocks[num].Length; } Buffer.BlockCopy(data, start, blocks[num], num2, count); for (int i = num2 / 1024; i < (num2 + count + 1024 - 1) / 1024; i++) { units[num] |= 1 << i; } if (Complete(num)) { Monitor.PulseAll(gate); } } return true; } public long ContiguousEnd(long from) { if (from >= Length) { return Length; } lock (gate) { int i; for (i = (int)(Math.Max(0L, from) / 16384); i < blocks.Length && Complete(i); i++) { } return Math.Max(from, Math.Min(Length, (long)i * 16384L)); } } public List<int> Missing(long from, long to, int max) { List<int> list = new List<int>(); if (to <= from) { return list; } lock (gate) { int num = (int)(Math.Max(0L, from) / 16384); int num2 = (int)Math.Min(blocks.Length - 1, (Math.Min(to, Length) - 1) / 16384); for (int i = num; i <= num2; i++) { if (list.Count >= max) { break; } if (!Complete(i)) { list.Add(i); } } } return list; } public void Drop(long keepFrom, long keepTo, IList<KeyValuePair<long, long>> pinned) { lock (gate) { for (int i = 0; i < blocks.Length; i++) { if (blocks[i] == null) { continue; } long num = (long)i * 16384L; long num2 = num + BlockLength(i); if (num2 > keepFrom && num < keepTo) { continue; } bool flag = false; if (pinned != null) { foreach (KeyValuePair<long, long> item in pinned) { if (num2 > item.Key && num < item.Value) { flag = true; break; } } } if (!flag) { held -= blocks[i].Length; blocks[i] = null; units[i] = 0; } } } } public void ResetReadAhead(long position) { lock (gate) { ReadAhead = position; } } public int Read(long position, IntPtr dest, int count, int timeoutMs, Func<bool> abort) { if (position >= Length || count <= 0) { return 0; } count = (int)Math.Min(count, Length - position); int num = 0; int num2 = 0; lock (gate) { while (num < count) { if (closed || (abort != null && abort())) { return -1; } long num3 = position + num; int num4 = (int)(num3 / 16384); if (!Complete(num4)) { if (num > 0) { break; } if (num2 >= timeoutMs) { return -1; } Monitor.Wait(gate, 50); num2 += 50; } else { int num5 = (int)(num3 % 16384); int num6 = Math.Min(count - num, blocks[num4].Length - num5); Marshal.Copy(blocks[num4], num5, dest + num, num6); num += num6; } } } if (num2 >= 200) { SlowRead?.Invoke(position, num2); } lock (gate) { if (position + count > ReadAhead) { ReadAhead = position + count; } } return num; } public void Close() { lock (gate) { closed = true; for (int i = 0; i < blocks.Length; i++) { blocks[i] = null; } held = 0L; Monitor.PulseAll(gate); } } } internal sealed class TVController : MonoBehaviour { private static readonly FieldRef<TVScript, bool> WasTvOnLastFrame = AccessTools.FieldRefAccess<TVScript, bool>("wasTvOnLastFrame"); private static readonly FieldRef<TVScript, int> VanillaClip = AccessTools.FieldRefAccess<TVScript, int>("currentClip"); private float baseVolume; private bool customMode; private bool screenOn; private TVPlayer player; private int playerSeq = -1; private string failedId; private string lastEntryId; private RenderTexture screen; private RenderTexture ownScreen; private string screenProperty; private Texture originalScreenTexture; private InteractTrigger trigger; private string baseHoverTip; private float nextTipUpdate; public static TVController Current { get; private set; } public TVScript Script { get; private set; } public bool Buffering { get { if (player != null) { return player.Buffering; } return true; } } public bool Failed { get { if (failedId != null) { return failedId == lastEntryId; } return false; } } public static void Attach(TVScript tv) { TVController tVController = ((Component)tv).GetComponent<TVController>(); if ((Object)(object)tVController == (Object)null) { tVController = ((Component)tv).gameObject.AddComponent<TVController>(); } tVController.Init(tv); } private void Init(TVScript tv) { Current = this; if (!((Object)(object)Script != (Object)null)) { Script = tv; baseVolume = tv.tvSFX.volume; FindTrigger(); } } private void OnEnable() { if ((Object)(object)Script != (Object)null) { Current = this; } } private void OnDisable() { ClosePlayer(); if ((Object)(object)Current == (Object)(object)this) { Current = null; } } private void OnDestroy() { ClosePlayer(); ReleaseScreen(); } private void Update() { if (!((Object)(object)Script == (Object)null)) { PluginConfig cfg = Plugin.Cfg; Script.tvSFX.volume = baseVolume * (cfg.Muted.Value ? 0f : cfg.Volume.Value); TVSyncManager instance = TVSyncManager.Instance; if ((Object)(object)instance != (Object)null && instance.CustomActive) { CustomUpdate(instance); } else if (customMode) { ExitCustomMode(); } UpdateHoverTip(instance); } } private void CustomUpdate(TVSyncManager mgr) { if (!customMode) { EnterCustomMode(); } VideoEntry currentEntry = mgr.CurrentEntry; if (currentEntry?.Id != lastEntryId) { lastEntryId = currentEntry?.Id; failedId = null; } PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if (!(mgr.Watching = Script.tvOn && currentEntry != null && currentEntry.Invalid == null && currentEntry.Id != failedId && (Object)(object)val != (Object)null && !val.isInsideFactory)) { ClosePlayer(); SetScreen(on: false); return; } double elapsed = mgr.Elapsed; if (player != null && player.Id != currentEntry.Id) { ClosePlayer(); } if (player == null) { if (elapsed >= currentEntry.Duration - 0.5 || !mgr.TryOpenSource(currentEntry, elapsed, out var source, out var owns, out var canRead)) { return; } player = new TVPlayer(currentEntry.Id, source, owns, "video" + currentEntry.Ext, elapsed, canRead, Script.tvSFX); playerSeq = mgr.Seq; } else if (playerSeq != mgr.Seq) { playerSeq = mgr.Seq; player.Seek(elapsed); } player.Update(elapsed, screen); if (player.Error != null) { Plugin.Log.LogError((object)("TV couldn't play '" + currentEntry.Name + "': " + player.Error)); failedId = currentEntry.Id; ClosePlayer(); SetScreen(on: false); } else { SetScreen(player.HasPicture); } } private void ClosePlayer() { if (player != null) { player.Dispose(); player = null; } } private void EnterCustomMode() { customMode = true; Script.tvSFX.Stop(); Script.video.Stop(); FindScreen(); WasTvOnLastFrame.Invoke(Script) = false; failedId = null; lastEntryId = null; screenOn = true; SetScreen(on: false); } private void ExitCustomMode() { customMode = false; ClosePlayer(); ReleaseScreen(); screenOn = true; SetScreen(on: false); WasTvOnLastFrame.Invoke(Script) = false; int num = VanillaClip.Invoke(Script); if (Script.tvOn && num >= 0 && num < Script.tvAudioClips.Length) { Script.tvSFX.clip = Script.tvAudioClips[num]; Script.tvSFX.Play(); } } private void FindScreen() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_0070: 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_0085: Expected O, but got Unknown //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Invalid comparison between Unknown and I4 //IL_0118: Unknown result type (might be due to invalid IL or missing references) VideoPlayer video = Script.video; if ((int)video.renderMode == 2 && (Object)(object)video.targetTexture != (Object)null) { screen = video.targetTexture; Plugin.Log.LogInfo((object)$"Drawing on the TV's render texture ({((Texture)screen).width}x{((Texture)screen).height})"); return; } ownScreen = new RenderTexture(1024, 768, 0) { name = "LethalTV screen" }; ownScreen.Create(); screen = ownScreen; screenProperty = (((int)video.renderMode == 3 && !string.IsNullOrEmpty(video.targetMaterialProperty)) ? video.targetMaterialProperty : "_MainTex"); Material tvOnMaterial = Script.tvOnMaterial; if ((Object)(object)tvOnMaterial != (Object)null && tvOnMaterial.HasProperty(screenProperty)) { originalScreenTexture = tvOnMaterial.GetTexture(screenProperty); tvOnMaterial.SetTexture(screenProperty, (Texture)(object)ownScreen); } Plugin.Log.LogInfo((object)$"TV video render mode is {video.renderMode}; drawing on '{screenProperty}' of the screen material"); } private void ReleaseScreen() { if ((Object)(object)ownScreen != (Object)null) { Material val = (((Object)(object)Script != (Object)null) ? Script.tvOnMaterial : null); if ((Object)(object)val != (Object)null && screenProperty != null && val.HasProperty(screenProperty) && (Object)(object)val.GetTexture(screenProperty) == (Object)(object)ownScreen) { val.SetTexture(screenProperty, originalScreenTexture); } ownScreen.Release(); Object.Destroy((Object)(object)ownScreen); ownScreen = null; } screen = null; } private void SetScreen(bool on) { if (screenOn != on) { screenOn = on; Material[] sharedMaterials = ((Renderer)Script.tvMesh).sharedMaterials; if (sharedMaterials.Length > 1) { sharedMaterials[1] = (on ? Script.tvOnMaterial : Script.tvOffMaterial); ((Renderer)Script.tvMesh).sharedMaterials = sharedMaterials; } if ((Object)(object)Script.tvLight != (Object)null) { ((Behaviour)Script.tvLight).enabled = on; } } } private void FindTrigger() { NetworkObject componentInParent = ((Component)Script).GetComponentInParent<NetworkObject>(); InteractTrigger[] componentsInChildren = ((Component)(((Object)(object)componentInParent != (Object)null) ? ((Component)componentInParent).transform : ((Component)Script).transform.root)).GetComponentsInChildren<InteractTrigger>(true); foreach (InteractTrigger val in componentsInChildren) { for (int j = 0; j < ((UnityEventBase)val.onInteract).GetPersistentEventCount(); j++) { if (((UnityEventBase)val.onInteract).GetPersistentTarget(j) == (Object)(object)Script) { trigger = val; baseHoverTip = val.hoverTip; return; } } } } private void UpdateHoverTip(TVSyncManager mgr) { if (!((Object)(object)trigger == (Object)null) && !(Time.unscaledTime < nextTipUpdate)) { nextTipUpdate = Time.unscaledTime + 0.25f; bool playing; string text = (((Object)(object)mgr != (Object)null) ? mgr.TvStatusLine(out playing) : null); string text2 = ((text == null) ? baseHoverTip : (baseHoverTip + "\n" + text)); if (trigger.hoverTip != text2) { trigger.hoverTip = text2; } } } } internal sealed class TVPlayer : IDisposable { private const double AudioLatency = 0.12; private const double AudioSlack = 0.08; private const double ResyncAfter = 2.5; public readonly string Id; private readonly MfDecoder decoder; private readonly AudioSource speaker; private Texture2D frame; private AudioClip clip; private double shownTime; private double lastSeek; private readonly object audioLock = new object(); private readonly Stopwatch watch = Stopwatch.StartNew(); private double clockAt = double.NaN; private double clockStamp; private MfDecoder.AudioChunk chunk; private int chunkPos; private int channels; private int rate; public bool HasPicture { get; private set; } public bool Buffering { get; private set; } = true; public string Error => decoder.Error; public TVPlayer(string id, IByteSource source, bool ownsSource, string nameHint, double startAt, Func<double, bool> canRead, AudioSource speaker) { Id = id; this.speaker = speaker; shownTime = startAt; lastSeek = watch.Elapsed.TotalSeconds; decoder = new MfDecoder(source, ownsSource, nameHint, startAt, canRead); } public void Seek(double clock) { decoder.Seek(clock); lock (audioLock) { chunk = null; } shownTime = clock; lastSeek = watch.Elapsed.TotalSeconds; Buffering = true; } public void Update(double clock, RenderTexture screen) { if (decoder.Error != null) { return; } lock (audioLock) { clockAt = clock; clockStamp = watch.Elapsed.TotalSeconds; } if (decoder.Opened) { if (decoder.HasAudio && (Object)(object)clip == (Object)null && (Object)(object)speaker != (Object)null) { StartSound(); } MfDecoder.Frame frame = decoder.TakeFrame(clock); if (frame != null) { Show(frame, screen); shownTime = frame.Time; HasPicture = true; decoder.Recycle(frame); } double num = decoder.NextFrameTime(); bool flag = decoder.HasVideo && !decoder.VideoEnded && (double.IsNaN(num) || num > clock + 0.25); Buffering = flag && clock - shownTime > 0.5; if (clock - shownTime > 2.5 && (double.IsNaN(num) || num < clock - 2.5) && !decoder.VideoEnded && watch.Elapsed.TotalSeconds - lastSeek > 4.0) { Seek(clock); } } } private void Show(MfDecoder.Frame f, RenderTexture screen) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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_0079: Expected O, but got Unknown //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) int width = decoder.Width; int height = decoder.Height; if ((Object)(object)frame == (Object)null || ((Texture)frame).width != width || ((Texture)frame).height != height) { if ((Object)(object)frame != (Object)null) { Object.Destroy((Object)(object)frame); } frame = new Texture2D(width, height, (TextureFormat)14, false) { wrapMode = (TextureWrapMode)1, filterMode = (FilterMode)1 }; } frame.LoadRawTextureData(f.Pixels); frame.Apply(false); if (!((Object)(object)screen == (Object)null)) { float num = ((Texture)screen).width; float num2 = ((Texture)screen).height; float num3 = (float)width * decoder.PixelAspect / (float)height; Rect val = ((num3 > num / num2) ? new Rect(0f, (num2 - num / num3) / 2f, num, num / num3) : new Rect((num - num2 * num3) / 2f, 0f, num2 * num3, num2)); RenderTexture active = RenderTexture.active; RenderTexture.active = screen; GL.Clear(true, true, Color.black); GL.PushMatrix(); GL.LoadPixelMatrix(0f, num, num2, 0f); Graphics.DrawTexture(val, (Texture)(object)frame); GL.PopMatrix(); RenderTexture.active = active; } } private void StartSound() { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown channels = decoder.Channels; rate = decoder.SampleRate; clip = AudioClip.Create("LethalTV", rate * 10, channels, rate, true, new PCMReaderCallback(ReadSound)); speaker.clip = clip; speaker.loop = true; speaker.Play(); } private void ReadSound(float[] data) { int num = Math.Max(1, channels); int num2 = data.Length / num; int num3 = 0; lock (audioLock) { if (double.IsNaN(clockAt) || rate <= 0) { Array.Clear(data, 0, data.Length); return; } double num4 = clockAt + (watch.Elapsed.TotalSeconds - clockStamp) + 0.12; while (num3 < num2) { if (chunk == null || chunkPos >= chunk.Samples.Length) { chunk = decoder.TakeAudio(); chunkPos = 0; if (chunk == null) { break; } } double num5 = chunk.Time + (double)(chunkPos / num) / (double)rate - (num4 + (double)num3 / (double)rate); if (num5 < -0.08) { chunkPos = Math.Min(chunk.Samples.Length, chunkPos + (int)Math.Ceiling((0.0 - num5) * (double)rate) * num); continue; } if (num5 > 0.08) { int num6 = Math.Min(num2 - num3, (int)Math.Ceiling(num5 * (double)rate)); Array.Clear(data, num3 * num, num6 * num); num3 += num6; continue; } int num7 = Math.Min(num2 - num3, (chunk.Samples.Length - chunkPos) / num); if (num7 <= 0) { chunkPos = chunk.Samples.Length; continue; } Array.Copy(chunk.Samples, chunkPos, data, num3 * num, num7 * num); num3 += num7; chunkPos += num7 * num; } } if (num3 < num2) { Array.Clear(data, num3 * num, (num2 - num3) * num); } } public void Dispose() { if ((Object)(object)speaker != (Object)null && (Object)(object)clip != (Object)null) { speaker.Stop(); if ((Object)(object)speaker.clip == (Object)(object)clip) { speaker.clip = null; } } decoder.Dispose(); if ((Object)(object)clip != (Object)null) { Object.Destroy((Object)(object)clip); } if ((Object)(object)frame != (Object)null) { Object.Destroy((Object)(object)frame); } } } public class TVRemoteInputs : LcInputActions { [InputAction("<Keyboard>/backslash", Name = "TV Remote: Power")] public InputAction Power { get; set; } [InputAction("<Keyboard>/rightBracket", Name = "TV Remote: Next Video")] public InputAction Next { get; set; } [InputAction("<Keyboard>/leftBracket", Name = "TV Remote: Previous Video")] public InputAction Previous { get; set; } [InputAction("<Keyboard>/equals", Name = "TV Remote: Volume Up")] public InputAction VolumeUp { get; set; } [InputAction("<Keyboard>/minus", Name = "TV Remote: Volume Down")] public InputAction VolumeDown { get; set; } [InputAction("<Keyboard>/quote", Name = "TV Remote: Mute")] public InputAction Mute { get; set; } } [HarmonyPatch(typeof(TVScript))] internal static class TVScriptPatches { private static bool CustomActive { get { if ((Object)(object)TVSyncManager.Instance != (Object)null) { return TVSyncManager.Instance.CustomActive; } return false; } } [HarmonyPatch("OnEnable")] [HarmonyPostfix] private static void OnEnablePostfix(TVScript __instance) { TVController.Attach(__instance); } [HarmonyPatch("Update")] [HarmonyPrefix] private static bool UpdatePrefix() { return !CustomActive; } [HarmonyPatch("TVFinishedClip")] [HarmonyPrefix] private static bool TVFinishedClipPrefix() { return !CustomActive; } [HarmonyPatch("TurnTVOnOff")] [HarmonyPrefix] private static bool TurnTVOnOffPrefix(TVScript __instance, bool on) { if (!CustomActive) { return true; } __instance.tvOn = on; AudioClip val = (on ? __instance.switchTVOn : __instance.switchTVOff); __instance.tvSFX.PlayOneShot(val); WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, val, 1f); return false; } } internal enum RemoteCommand : byte { Next = 1, Previous } internal sealed class TVSyncManager : MonoBehaviour { private delegate void Writer(ref FastBufferWriter w); private struct Sent { public uint Seq; public int Bytes; public float Time; } private sealed class Viewer { public VideoEntry Entry; public FileStream File; public readonly LinkedList<int> Queue = new LinkedList<int>(); public readonly HashSet<int> Queued = new HashSet<int>(); public int Block = -1; public int BlockSent; public int Window; public long InFlightBytes; public readonly Queue<Sent> InFlight = new Queue<Sent>(); public uint NextSeq; public float LastAck; public float MinRttThisMinute = float.MaxValue; public float MinRttLastMinute = float.MaxValue; public float MinuteStarted; public float LastCut; public float LastRtt; public long BytesSent; public long ReportedBytes; public float LastReport; public float BaseRtt => Math.Min(MinRttThisMinute, MinRttLastMinute); } private sealed class ClientStream { public VideoEntry Entry; public StreamBuffer Buffer; public Mp4Index Index; public float IndexAsked = -999f; public readonly Dictionary<int, float> Asked = new Dictionary<int, float>(); public bool HostQueueActive; public float LastData; public long WindowFrom = -1L; public long WindowTo = -1L; public float LastDrop; public long BytesReceived; public long ReportedBytes; public float LastReport; } private const string MsgHello = "LethalTV2.Hello"; private const string MsgManifest = "LethalTV2.Manifest"; private const string MsgState = "LethalTV2.State"; private const string MsgCommand = "LethalTV2.Command"; private const string MsgIndexRequest = "LethalTV2.IndexRequest"; private const string MsgIndex = "LethalTV2.Index"; private const string MsgWant = "LethalTV2.Want"; private const string MsgData = "LethalTV2.Data"; private const string MsgAck = "LethalTV2.Ack"; private static readonly string[] AllMessages = new string[9] { "LethalTV2.Hello", "LethalTV2.Manifest", "LethalTV2.State", "LethalTV2.Command", "LethalTV2.IndexRequest", "LethalTV2.Index", "LethalTV2.Want", "LethalTV2.Data", "LethalTV2.Ack" }; private const NetworkDelivery Delivery = (NetworkDelivery)4; private const int MaxMessageSize = 1048576; private const int MaxPlaylist = 2000; private const int MaxQueuedBlocks = 4096; private const float AskTimeout = 8f; private NetworkManager net; private CustomMessagingManager messaging; private bool isServer; private bool manifestReceived; private bool clientControlAllowed = true; public readonly List<VideoEntry> Playlist = new List<VideoEntry>(); private const float TargetQueueDelay = 0.05f; private readonly Dictionary<ulong, Viewer> viewers = new Dictionary<ulong, Viewer>(); private readonly Dictionary<ulong, float> lastCommandTime = new Dictionary<ulong, float>(); private int chunkSize = 16384; private int maxWindow = 262144; private int maxOutstandingBlocks = 32; private byte[] sendBuffer = new byte[16384]; private float uploadAllowance; private ClientStream stream; private readonly Dictionary<string, Mp4Index> indexCache = new Dictionary<string, Mp4Index>(); private float lastWant; private byte[] recvBuffer = new byte[65536]; private float hudUntil; private string hudNote; private GUIStyle hudStyle; private GUIStyle hudShadowStyle; public static TVSyncManager Instance { get; private set; } public int CurrentIndex { get; private set; } public double ClipStart { get; private set; } public int Seq { get; private set; } public bool InSession => messaging != null; public bool IsHost { get { if (InSession) { return isServer; } return false; } } public bool CustomActive { get { if (InSession && Playlist.Count > 0) { if (!isServer) { return manifestReceived; } return true; } return false; } } public VideoEntry CurrentEntry { get { if (!CustomActive || CurrentIndex < 0 || CurrentIndex >= Playlist.Count) { return null; } return Playlist[CurrentIndex]; } } public double Now { get { //IL_001e: 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) if (!((Object)(object)net != (Object)null)) { return 0.0; } NetworkTime serverTime = net.ServerTime; return ((NetworkTime)(ref serverTime)).Time; } } public double Elapsed => Math.Max(0.0, Now - ClipStart); public bool Watching { get; set; } private static PlayerControllerB LocalPlayer { get { if (!((Object)(object)GameNetworkManager.Instance != (Object)null)) { return null; } return GameNetworkManager.Instance.localPlayerController; } } private void Awake() { Instance = this; VideoLibrary.DeleteOldDownloads(); VideoLibrary.Changed += OnLibraryChanged; ((MonoBehaviour)this).StartCoroutine(VideoLibrary.Scan()); } private void OnDestroy() { VideoLibrary.Changed -= OnLibraryChanged; EndSession(); } private void Update() { TrackSession(); if (InSession) { try { if (isServer) { AdvanceTimeline(); PumpViewers(); } else { PumpStream(); } } catch (Exception ex) { Plugin.Log.LogError((object)ex); } } HandleRemote(); } private void TrackSession() { NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton != (Object)null) || !singleton.IsListening || singleton.ShutdownInProgress || (!singleton.IsServer && !singleton.IsConnectedClient) || singleton.CustomMessagingManager == null) { if (InSession) { EndSession(); } } else if (messaging != singleton.CustomMessagingManager) { if (InSession) { EndSession(); } BeginSession(singleton); } } private void BeginSession(NetworkManager nm) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected O, but got Unknown //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Expected O, but got Unknown //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown net = nm; isServer = nm.IsServer; messaging = nm.CustomMessagingManager; messaging.RegisterNamedMessageHandler("LethalTV2.Hello", new HandleNamedMessageDelegate(OnHello)); messaging.RegisterNamedMessageHandler("LethalTV2.Manifest", new HandleNamedMessageDelegate(OnManifest)); messaging.RegisterNamedMessageHandler("LethalTV2.State", new HandleNamedMessageDelegate(OnState)); messaging.RegisterNamedMessageHandler("LethalTV2.Command", new HandleNamedMessageDelegate(OnCommand)); messaging.RegisterNamedMessageHandler("LethalTV2.IndexRequest", new HandleNamedMessageDelegate(OnIndexRequest)); messaging.RegisterNamedMessageHandler("LethalTV2.Index", new HandleNamedMessageDelegate(OnIndex)); messaging.RegisterNamedMessageHandler("LethalTV2.Want", new HandleNamedMessageDelegate(OnWant)); messaging.RegisterNamedMessageHandler("LethalTV2.Data", new HandleNamedMessageDelegate(OnData)); messaging.RegisterNamedMessageHandler("LethalTV2.Ack", new HandleNamedMessageDelegate(OnAck)); ConfigureTransfer(nm); Playlist.Clear(); manifestReceived = false; CurrentIndex = 0; ClipStart = Now; Seq = 0; if (isServer) { nm.OnClientDisconnectCallback += OnClientDisconnected; clientControlAllowed = Plugin.Cfg.AllowClientControl.Value; RebuildPlaylist(broadcast: false); ((MonoBehaviour)this).StartCoroutine(VideoLibrary.Scan()); Plugin.Log.LogInfo((object)$"Hosting with {Playlist.Count} custom video(s)."); } else { SendToServer("LethalTV2.Hello", 8, delegate { }); } } private void EndSession() { if (messaging != null) { try { string[] allMessages = AllMessages; foreach (string text in allMessages) { messaging.UnregisterNamedMessageHandler(text); } } catch (Exception) { } } if ((Object)(object)net != (Object)null && isServer) { try { net.OnClientDisconnectCallback -= OnClientDisconnected; } catch (Exception) { } } foreach (Viewer value in viewers.Values) { value.File?.Dispose(); } viewers.Clear(); lastCommandTime.Clear(); stream = null; Watching = false; Playlist.Clear(); manifestReceived = false; messaging = null; net = null; } private void OnClientDisconnected(ulong clientId) { CloseViewer(clientId); lastCommandTime.Remove(clientId); } private void ConfigureTransfer(NetworkManager nm) { NetworkTransport val = nm.NetworkConfig?.NetworkTransport; if ((Object)(object)val != (Object)null && ((object)val).GetType().Name == "UnityTransport") { int num = 6144; try { PropertyInfo property = ((object)val).GetType().GetProperty("MaxPayloadSize"); if (property != null) { num = (int)property.GetValue(val); } } catch (Exception) { } chunkSize = Mathf.Clamp((num - 512) / 1024 * 1024, 1024, 16384); maxWindow = Math.Max(chunkSize * 4, 49152); } else { chunkSize = 16384; maxWindow = 262144; } sendBuffer = new byte[chunkSize]; maxOutstandingBlocks = Math.Max(16, 2 * maxWindow / 16384); } private void Send(string name, ulong clientId, int initialSize, Writer write) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter w = default(FastBufferWriter); ((FastBufferWriter)(ref w))..ctor(initialSize, (Allocator)2, 1048576); try { write(ref w); messaging.SendNamedMessage(name, clientId, w, (NetworkDelivery)4); } finally { ((FastBufferWriter)(ref w)).Dispose(); } } private void SendToServer(string name, int initialSize, Writer write) { Send(name, 0uL, initialSize, write); } private void Broadcast(string name, int initialSize, Writer write) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) List<ulong> list = net.ConnectedClientsIds.Where((ulong id) => id != net.LocalClientId).ToList(); if (list.Count == 0) { return; } FastBufferWriter w = default(FastBufferWriter); ((FastBufferWriter)(ref w))..ctor(initialSize, (Allocator)2, 1048576); try { write(ref w); messaging.SendNamedMessage(name, (IReadOnlyList<ulong>)list, w, (NetworkDelivery)4); } finally { ((FastBufferWriter)(ref w)).Dispose(); } } private void OnLibraryChanged() { if (InSession && isServer) { RebuildPlaylist(broadcast: true); } } private void RebuildPlaylist(bool broadcast) { string currentId = ((CurrentIndex >= 0 && CurrentIndex < Playlist.Count) ? Playlist[CurrentIndex].Id : null); List<VideoEntry> list = VideoLibrary.Ready.ToList(); if (Plugin.Cfg.Shuffle.Value) { Random random = new Random(); for (int num = list.Count - 1; num > 0; num--) { int num2 = random.Next(num + 1); List<VideoEntry> list2 = list; int index = num; int index2 = num2; VideoEntry value = list[num2]; VideoEntry value2 = list[num]; list2[index] = value; list[index2] = value2; } } Playlist.Clear(); Playlist.AddRange(list); int num3 = ((currentId != null) ? Playlist.FindIndex((VideoEntry e) => e.Id == currentId) : (-1)); if (num3 >= 0) { CurrentIndex = num3; } else { CurrentIndex = 0; ClipStart = Now; } Seq++; if (broadcast) { Broadcast("LethalTV2.Manifest", 1024, WriteManifest); Broadcast("LethalTV2.State", 64, WriteState); Plugin.Log.LogInfo((object)$"Playlist updated: {Playlist.Count} video(s)."); } } private void AdvanceTimeline() { if (Playlist.Count == 0) { return; } if (CurrentIndex >= Playlist.Count) { CurrentIndex = 0; } bool flag = false; for (int i = 0; i <= Playlist.Count; i++) { if (!(Now - ClipStart >= Playlist[CurrentIndex].Duration)) { break; } ClipStart += Playlist[CurrentIndex].Duration; CurrentIndex = (CurrentIndex + 1) % Playlist.Count; flag = true; } if (Now - ClipStart >= Playlist[CurrentIndex].Duration) { ClipStart = Now; } if (flag) { Seq++; Broadcast("LethalTV2.State", 64, WriteState); NotifyChannelChanged(); } } private void ApplyCommand(RemoteCommand cmd) { if (Playlist.Count != 0) { int count = Playlist.Count; switch (cmd) { default: return; case RemoteCommand.Next: CurrentIndex = (CurrentIndex + 1) % count; break; case RemoteCommand.Previous: CurrentIndex = (CurrentIndex - 1 + count) % count; break; } ClipStart = Now; Seq++; Broadcast("LethalTV2.State", 64, WriteState); NotifyChannelChanged(); } } private void WriteManifest(ref FastBufferWriter w) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_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_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) ((FastBufferWriter)(ref w)).WriteValueSafe<bool>(ref clientControlAllowed, default(ForPrimitives)); int count = Playlist.Count; ((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref count, default(ForPrimitives)); foreach (VideoEntry item in Playlist) { ((FastBufferWriter)(ref w)).WriteValueSafe(item.Id, true); ((FastBufferWriter)(ref w)).WriteValueSafe(item.Name, false); ((FastBufferWriter)(ref w)).WriteValueSafe(item.Ext, true); ((FastBufferWriter)(ref w)).WriteValueSafe<long>(ref item.Size, default(ForPrimitives)); ((FastBufferWriter)(ref w)).WriteValueSafe<double>(ref item.Duration, default(ForPrimitives)); } } private void WriteState(ref FastBufferWriter w) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_0042: Unknown result type (might be due to invalid IL or missing references) int currentIndex = CurrentIndex; ((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref currentIndex, default(ForPrimitives)); double clipStart = ClipStart; ((FastBufferWriter)(ref w)).WriteValueSafe<double>(ref clipStart, default(ForPrimitives)); currentIndex = Seq; ((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref currentIndex, default(ForPrimitives)); } private void OnHello(ulong sender, FastBufferReader reader) { if (isServer) { Send("LethalTV2.Manifest", sender, 1024, WriteManifest); Send("LethalTV2.State", sender, 64, WriteState); } } private void OnCommand(ulong sender, FastBufferReader reader) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (isServer) { byte cmd = default(byte); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref cmd, default(ForPrimitives)); if (clientControlAllowed && (!lastCommandTime.TryGetValue(sender, out var value) || !(Time.unscaledTime - value < 0.2f))) { lastCommandTime[sender] = Time.unscaledTime; ApplyCommand((RemoteCommand)cmd); } } } private void OnIndexRequest(ulong sender, FastBufferReader reader) { if (!isServer) { return; } string id = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref id, true); Mp4Index idx = Playlist.Find((VideoEntry p) => p.Id == id)?.Index; if (idx == null) { return; } Send("LethalTV2.Index", sender, 256 + 16 * (idx.Header.Count + idx.Seconds), delegate(ref FastBufferWriter w) { //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_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) //IL_0072: 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: 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_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) ((FastBufferWriter)(ref w)).WriteValueSafe(id, true); int count = idx.Header.Count; ((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref count, default(ForPrimitives)); foreach (KeyValuePair<long, long> item in idx.Header) { long key = item.Key; ((FastBufferWriter)(ref w)).WriteValueSafe<long>(ref key, default(ForPrimitives)); key = item.Value; ((FastBufferWriter)(ref w)).WriteValueSafe<long>(ref key, default(ForPrimitives)); } count = idx.Seconds; ((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref count, default(ForPrimitives)); for (int i = 0; i < idx.Seconds; i++) { ((FastBufferWriter)(ref w)).WriteValueSafe<long>(ref idx.StartAt[i], default(ForPrimitives)); } for (int j = 0; j < idx.Seconds; j++) { ((FastBufferWriter)(ref w)).WriteValueSafe<long>(ref idx.EndBy[j], default(ForPrimitives)); } }); } private void OnWant(ulong sender, FastBufferReader reader) { //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_0036: 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_0199: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) if (!isServer) { return; } string id = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref id, true); bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); if (num < 0 || num > 4096) { return; } VideoEntry videoEntry = Playlist.Find((VideoEntry e) => e.Id == id); if (videoEntry == null || videoEntry.Path == null) { CloseViewer(sender); return; } if (!viewers.TryGetValue(sender, out var value) || value.Entry.Id != id) { CloseViewer(sender); try { value = new Viewer { Entry = videoEntry, File = new FileStream(videoEntry.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 65536), Window = chunkSize * 2, LastAck = Time.unscaledTime, MinuteStarted = Time.realtimeSinceStartup }; } catch (Exception ex) { Plugin.Log.LogError((object)("Couldn't open '" + videoEntry.Path + "' to stream: " + ex.Message)); return; } viewers[sender] = value; Plugin.Log.LogInfo((object)$"Streaming '{videoEntry.Name}' to client {sender}"); } if (flag) { value.Queue.Clear(); value.Queued.Clear(); } int num2 = (int)((videoEntry.Size + 16384 - 1) / 16384); int num4 = default(int); int num5 = default(int); for (int num3 = 0; num3 < num; num3++) { ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num4, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num5, default(ForPrimitives)); if (num4 < 0 || num5 <= 0 || num4 >= num2) { continue; } int num6 = (int)Math.Min(num2, (long)num4 + (long)num5); for (int num7 = num4; num7 < num6; num7++) { if (value.Queued.Count >= 4096) { break; } if (value.Queued.Add(num7)) { value.Queue.AddLast(num7); } } } } private void OnAck(ulong sender, FastBufferReader reader) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (!isServer) { return; } uint num = default(uint); ((FastBufferReader)(ref reader)).ReadValueSafe<uint>(ref num, default(ForPrimitives)); if (viewers.TryGetValue(sender, out var value)) { float num2 = -1f; long num3 = 0L; while (value.InFlight.Count > 0 && (int)(num - value.InFlight.Peek().Seq) >= 0) { Sent sent = value.InFlight.Dequeue(); value.InFlightBytes -= sent.Bytes; num3 += sent.Bytes; num2 = sent.Time; } if (num2 >= 0f) { AdjustWindow(value, Time.realtimeSinceStartup - num2, num3); value.LastAck = Time.unscaledTime; } } } private void AdjustWindow(Viewer v, float rtt, long ackedBytes) { float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup - v.MinuteStarted > 60f) { v.MinRttLastMinute = v.MinRttThisMinute; v.MinRttThisMinute = float.MaxValue; v.MinuteStarted = realtimeSinceStartup; } v.MinRttThisMinute = Math.Min(v.MinRttThisMinute, rtt); v.LastRtt = rtt; float num = rtt - v.BaseRtt; if (num > 0.05f) { if (realtimeSinceStartup - v.LastCut > Math.Max(rtt, 0.1f)) { v.Window = Math.Max(chunkSize, (int)((float)v.Window * 0.6f)); v.LastCut = realtimeSinceStartup; } } else { float num2 = (0.05f - num) / 0.05f; long val = (long)((double)chunkSize * (double)ackedBytes / (double)v.Window * (double)num2); v.Window = (int)Math.Min(maxWindow, v.Window + Math.Max(1L, val)); } } private void CloseViewer(ulong clientId) { if (viewers.TryGetValue(clientId, out var value)) { value.File?.Dispose(); viewers.Remove(clientId); } } private void PumpViewers() { if (viewers.Count == 0) { uploadAllowance = 0f; return; } int value = Plugin.Cfg.StreamUploadCapKBps.Value; if (value > 0) { float num = (float)value * 1024f; uploadAllowance = Mathf.Min(uploadAllowance + num * Time.unscaledDeltaTime, num * 0.1f + (float)chunkSize); } else { uploadAllowance = float.MaxValue; } foreach (KeyValuePair<ulong, Viewer> item in viewers.ToList()) { Viewer value2 = item.Value; if (Time.unscaledTime - value2.LastReport >= 2f) { if (value2.BytesSent != value2.ReportedBytes) { Plugin.Log.LogDebug((object)($"Streaming to client {item.Key}: {(float)(value2.BytesSent - value2.ReportedBytes) / 1024f / (Time.unscaledTime - value2.LastReport):0} KB/s, " + $"window {value2.Window / 1024} KB, round trip {value2.LastRtt * 1000f:0} ms (base {value2.BaseRtt * 1000f:0} ms), {value2.Queue.Count} blocks queued")); } value2.LastReport = Time.unscaledTime; value2.ReportedBytes = value2.BytesSent; } if (value2.InFlightBytes > 0 && Time.unscaledTime - value2.LastAck > 5f) { value2.InFlight.Clear(); value2.InFlightBytes = 0L; value2.Window = chunkSize; value2.LastAck = Time.unscaledTime; } while (value2.InFlightBytes < value2.Window && uploadAllowance > 0f) { if (value2.Block < 0) { if (value2.Queue.Count == 0) { break; } value2.Block = value2.Queue.First.Value; value2.Queue.RemoveFirst(); value2.Queued.Remove(value2.Block); value2.BlockSent = 0; } long num2 = (long)value2.Block * 16384L; int num3 = (int)Math.Min(16384L, value2.Entry.Size - num2); int length = Math.Min(chunkSize, num3 - value2.BlockSent); long offset = num2 + value2.BlockSent; int num4; try { value2.File.Position = offset; num4 = ReadFully(value2.File, sendBuffer, length); } catch (Exception ex) { Plugin.Log.LogError((object)("Error reading '" + value2.Entry.Path + "': " + ex.Message)); num4 = 0; } if (num4 != length) { CloseViewer(item.Key); break; } string id = value2.Entry.Id; uint seq = value2.NextSeq++; Send("LethalTV2.Data", item.Key, length + 256, delegate(ref FastBufferWriter w) { //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_002b: 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) //IL_0040: 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) ((FastBufferWriter)(ref w)).WriteValueSafe(id, true); ((FastBufferWriter)(ref w)).WriteValueSafe<long>(ref offset, default(ForPrimitives)); ((FastBufferWriter)(ref w)).WriteValueSafe<uint>(ref seq, default(ForPrimitives)); ((FastBufferWriter)(ref w)).WriteValueSafe<int>(ref length, default(ForPrimitives)); ((FastBufferWriter)(ref w)).WriteBytesSafe(sendBuffer, length, 0); }); value2.InFlight.Enqueue(new Sent { Seq = seq, Bytes = length, Time = Time.realtimeSinceStartup }); value2.InFlightBytes += length; value2.BytesSent += length; uploadAllowance -= length; value2.BlockSent += length; if (value2.BlockSent >= num3) { value2.Block = -1; } } } } private static int ReadFully(Stream s, byte[] buffer, int count) { int i; int num; for (i = 0; i < count; i += num) { num = s.Read(buffer, i, count - i); if (num <= 0) { break; } } return i; } private void OnManifest(ulong sender, FastBufferReader reader) { //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_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: 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) //IL_009b: Unknown result type (might be due to invalid IL or missing references) if (isServer) { return; } try { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); if (num < 0 || num > 2000) { throw new InvalidDataException($"bad playlist size {num}"); } List<VideoEntry> list = new List<VideoEntry>(num); string id = default(string); string text = default(string); string ext = default(string); long num2 = default(long); double num3 = default(double); for (int i = 0; i < num; i++) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref id, true); ((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false); ((FastBufferReader)(ref reader)).ReadValueSafe(ref ext, true); ((FastBufferReader)(ref reader)).ReadValueSafe<long>(ref num2, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<double>(ref num3, default(ForPrimitives)); VideoEntry videoEntry = new VideoEntry { Id = id, Name = (text ?? "video"), Ext = ext, Size = num2, Duration = num3 }; if (!VideoLibrary.IsValidId(id) || !VideoLibrary.IsSupportedExtension(ext) || num2 <= 0 || !(num3 > 0.0)) { videoEntry.Invalid = "Invalid video"; } list.Add(videoEntry); } clientControlAllowed = flag; Playlist.Clear(); Playlist.AddRange(list); manifestReceived = true; Plugin.Log.LogInfo((object)$"Host playlist: {Playlist.Count} video(s)."); } catch (Exception ex) { Plugin.Log.LogError((object)("Bad playlist from host: " + ex.Message)); } } private void OnState(ulong sender, FastBufferReader reader) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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_0033: 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) if (!isServer) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); double clipStart = default(double); ((FastBufferReader)(ref reader)).ReadValueSafe<double>(ref clipStart, default(ForPrimitives)); int num2 = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num2, default(ForPrimitives)); bool num3 = num != CurrentIndex || num2 != Seq; CurrentIndex = num; ClipStart = clipStart; Seq = num2; if (num3 && CustomActive) { NotifyChannelChanged(); } } } private void OnIndex(ulong sender, FastBufferReader reader) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00f4