Decompiled source of Bing Bong AI v0.9.1
plugins/CavyCrew.BingBongAI.dll
Decompiled 2 weeks 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.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using BingBongAI.Ai; using BingBongAI.BingBong; using BingBongAI.Brain; using BingBongAI.Game; using BingBongAI.Net; using BingBongAI.Pigs; using BingBongAI.Secrets; using BingBongAI.UI; using BingBongAI.Voice; using ExitGames.Client.Photon; using GuineaPigsAndTreats; using HarmonyLib; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Peak.Afflictions; using Photon.Pun; using Photon.Realtime; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.Networking; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.UI; using Zorro.Core; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("CavyCrew.BingBongAI")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.9.1.0")] [assembly: AssemblyInformationalVersion("0.9.1")] [assembly: AssemblyProduct("CavyCrew.BingBongAI")] [assembly: AssemblyTitle("Bing Bong AI")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.9.1.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } 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; } } } namespace BepInEx { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] [Conditional("CodeGeneration")] [Embedded] internal sealed class BepInAutoPluginAttribute : Attribute { public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null) { } } } namespace BepInEx.Preloader.Core.Patching { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] [Conditional("CodeGeneration")] [Embedded] internal sealed class PatcherAutoPluginAttribute : Attribute { public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null) { } } } namespace Microsoft.CodeAnalysis { [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace BingBongAI { internal static class GameHooks { private sealed class Hook(MethodBase? original) { public MethodBase? Original { get; } = original; public HarmonyMethod? Prefix { get; set; } public HarmonyMethod? Postfix { get; set; } public Exception? Error { get; set; } } private static readonly List<string> s_broken = new List<string>(); public static IReadOnlyList<string> Broken => s_broken; public static void PatchAll(Harmony harmony) { //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Expected O, but got Unknown int num = 0; Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(typeof(Plugin).Assembly); foreach (Type type in typesFromAssembly) { HarmonyMethod val; List<MethodInfo> declaredMethods; try { if (!type.IsDefined(typeof(HarmonyPatch), inherit: false)) { continue; } val = ((HarmonyAttribute)(((MemberInfo)type).GetCustomAttributes<HarmonyPatch>(inherit: false).FirstOrDefault()?)).info; declaredMethods = AccessTools.GetDeclaredMethods(type); goto IL_0076; } catch (Exception e) { num++; Fail(type.Name, e); } continue; IL_0076: Dictionary<string, Hook> dictionary = new Dictionary<string, Hook>(); Hook value3; foreach (MethodInfo item in declaredMethods) { string key = type.Name + "." + item.Name; try { bool flag = item.IsDefined(typeof(HarmonyPrefix), inherit: false) || item.Name == "Prefix"; bool flag2 = item.IsDefined(typeof(HarmonyPostfix), inherit: false) || item.Name == "Postfix"; if (!flag && !flag2) { continue; } HarmonyMethod val2 = ((HarmonyAttribute)(((MemberInfo)item).GetCustomAttributes<HarmonyPatch>(inherit: false).FirstOrDefault()?)).info ?? val; Type type2 = val2?.declaringType ?? val?.declaringType; string text = val2?.methodName ?? val?.methodName; if (type2 == null || text == null) { throw new InvalidOperationException("no target method"); } key = type2.Name + "." + text; MethodType? val3 = val2?.methodType; bool flag3; if (val3.HasValue) { MethodType valueOrDefault = val3.GetValueOrDefault(); if ((int)valueOrDefault != 0) { flag3 = false; goto IL_01d8; } } flag3 = true; goto IL_01d8; IL_01d8: if (!flag3) { throw new NotSupportedException($"method type {val2.methodType}"); } MethodInfo original = AccessTools.Method(type2, text, val2?.argumentTypes, (Type[])null) ?? throw new MissingMethodException(type2.FullName, text); if (!dictionary.TryGetValue(key, out var value)) { value = (dictionary[key] = new Hook(original)); } if (flag) { value.Prefix = new HarmonyMethod(item); } if (flag2) { value.Postfix = new HarmonyMethod(item); } } catch (Exception ex) { if (!dictionary.TryGetValue(key, out var value2)) { value2 = (dictionary[key] = new Hook(null)); } value3 = value2; if (value3.Error == null) { Exception ex2 = (value3.Error = ex); } } } foreach (KeyValuePair<string, Hook> item2 in dictionary) { item2.Deconstruct(out var key2, out value3); string text2 = key2; Hook hook3 = value3; num++; if (hook3.Error != null || hook3.Original == null) { Fail(text2, hook3.Error ?? new MissingMethodException(text2)); continue; } try { harmony.Patch(hook3.Original, hook3.Prefix, hook3.Postfix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception e2) { Fail(text2, e2); try { harmony.Unpatch(hook3.Original, (HarmonyPatchType)0, harmony.Id); } catch (Exception) { } } } } Plugin.Log.LogInfo((object)$"Game hooks: {num - s_broken.Count} of {num} in place."); } public static void Start(string what, Action start) { try { start(); } catch (Exception e) { Fail(what, e); } } private static void Fail(string what, Exception e) { s_broken.Add(what); Plugin.Log.LogWarning((object)("Could not hook into " + what + " (has the game updated?): " + e.GetType().Name + ": " + e.Message + ". The rest of the mod works without it.")); } } internal sealed class Hotkeys : MonoBehaviour { private sealed class ParsedKey(Func<string> setting, Key fallback) { private string? _parsedName; private Key _key; private Key Current { get { //IL_006a: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) string text = setting(); if (text != _parsedName) { _parsedName = text; if (Enum.TryParse<Key>(text.Trim(), ignoreCase: true, out Key result) && (int)result != 0) { _key = result; } else { _key = fallback; Plugin.Log.LogWarning((object)$"Unknown key '{text}', using {fallback}."); } } return _key; } } public bool WasPressed(Keyboard keyboard) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return ((ButtonControl)keyboard[Current]).wasPressedThisFrame; } public bool IsHeld(Keyboard keyboard) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return ((ButtonControl)keyboard[Current]).isPressed; } } private const float MinTalkSeconds = 0.35f; private const float TalkDistance = 25f; private readonly ParsedKey _settings = new ParsedKey(() => Plugin.SettingsKey.Value, (Key)99); private readonly ParsedKey _ask = new ParsedKey(() => Plugin.AskKey.Value, (Key)34); private readonly ParsedKey _talk = new ParsedKey(() => Plugin.TalkKey.Value, (Key)39); private Guid _talkId; private MicRecorder? _recorder; private void Update() { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Invalid comparison between Unknown and I4 Keyboard current = Keyboard.current; if (current == null) { return; } if (_recorder != null) { if (!_talk.IsHeld(current) || _recorder.IsFull) { FinishRecording(); } return; } if (_settings.WasPressed(current)) { if (SettingsWindow.IsOpen) { SettingsWindow.CloseWindow(); } else if (!AnyOtherWindowBlocks()) { SettingsWindow.Toggle(); } return; } bool flag = _ask.WasPressed(current); bool flag2 = _talk.WasPressed(current); if ((!flag && !flag2) || AnyOtherWindowBlocks() || (int)Cursor.lockState != 1 || (flag && HandsScroll())) { return; } BingBongPlace bingBongPlace = BingBongPlace.OfLocalScout() ?? LyingNearby(); if (bingBongPlace == null) { if (Plugin.AiEnabled.Value) { Messages.Show(Lang.Get("msg.no_bingbong", ("m", 25))); } } else if (!Plugin.AiEnabled.Value) { (string, object)[] array = new(string, object)[3] { ("key", Plugin.SettingsKey.Value.ToUpperInvariant()), ("tab", Lang.Get("settings.tab_behaviour")), ("setting", Lang.Get("settings.enabled")) }; Player current2 = BingBongAI.Net.Brain.Current; Messages.Show((current2 != null && !current2.IsLocal) ? Lang.Get("msg.ai_off_lobby", array.Append(("who", BingBongAI.Net.Brain.NameOf(current2))).ToArray()) : Lang.Get("msg.ai_off", array)); } else if (!BingBongBrain.IsConfigured && !BingBongAI.Net.Brain.Remote) { Messages.Show(Lang.Get("msg.not_configured", ("key", Plugin.SettingsKey.Value.ToUpperInvariant()))); } else if (flag) { AskWindow.Open(bingBongPlace.Id); } else { StartRecording(bingBongPlace); } } private void OnDisable() { _recorder?.Dispose(); _recorder = null; } private BingBongPlace? TalkedBingBong() { return BingBongPlace.Find(_talkId); } private void StartRecording(BingBongPlace place) { string item = Plugin.SettingsKey.Value.ToUpperInvariant(); if (!BingBongAI.Net.Brain.Remote && !ListenService.Enabled) { Messages.Show(Lang.Get("msg.listen_off", ("key", item))); return; } if (!BingBongAI.Net.Brain.Remote && !ListenService.IsConfigured) { Messages.Show(Lang.Get("msg.listen_not_configured", ("key", item))); return; } try { _recorder = ListenService.StartRecording(); Plugin.Verbose("Listening on '" + ((_recorder.DeviceName.Length > 0) ? _recorder.DeviceName : "Windows default") + "'."); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not start the microphone: " + ex.Message)); Messages.Show(Lang.Get("msg.mic_failed", ("detail", ex.Message))); return; } _talkId = place.Id; BingBongSpeech.For(place).ShowListening(); } private async void FinishRecording() { MicRecorder recorder = _recorder; _recorder = null; BingBongSpeech speech = null; try { bool flag = recorder.Elapsed.TotalSeconds < 0.3499999940395355; short[] samples = recorder.Stop(); BingBongPlace bingBongPlace = TalkedBingBong(); if (bingBongPlace != null) { speech = BingBongSpeech.For(bingBongPlace); } if (flag) { if ((Object)(object)speech != (Object)null) { speech.StopThinking(); } Messages.Show(Lang.Get("msg.hold_to_talk", ("talk", Plugin.TalkKey.Value.ToUpperInvariant()))); return; } if (BingBongAI.Net.Brain.Remote) { if (bingBongPlace == null) { Messages.Show(Lang.Get("msg.listen_gone")); } else if (ListenService.IsSilence(samples)) { if ((Object)(object)speech != (Object)null) { speech.StopThinking(); } Messages.Show(Lang.Get("msg.not_heard")); } else { BrainNet.AskByVoice(bingBongPlace, samples, 16000); } return; } if ((Object)(object)speech != (Object)null) { speech.ShowThinking(); } string text = await ListenService.RecognizeAsync(samples); if (text == null) { if ((Object)(object)speech != (Object)null) { speech.StopThinking(); } Messages.Show(Lang.Get("msg.not_heard")); return; } Messages.Show(Lang.Get("msg.heard", ("text", text))); bingBongPlace = TalkedBingBong(); if (bingBongPlace == null) { if ((Object)(object)speech != (Object)null) { speech.StopThinking(); } Messages.Show(Lang.Get("msg.listen_gone")); } else { if (!BingBongBrain.Busy && (Object)(object)bingBongPlace.Instance != (Object)null && bingBongPlace.Spot == BingBongSpot.Hand) { AskPatch.Squish(bingBongPlace.Instance); } BingBongBrain.Ask(bingBongPlace, text); } } catch (ChatException ex) { Plugin.Log.LogWarning((object)$"Speech recognition failed ({ex.Kind}): {ex.Message}"); if ((Object)(object)speech != (Object)null) { speech.StopThinking(); } Messages.Show(BingBongBrain.ErrorText(ex, ListenService.Endpoint)); } catch (Exception ex2) { Plugin.Log.LogError((object)$"Spoken question failed: {ex2}"); if ((Object)(object)speech != (Object)null) { speech.StopThinking(); } Messages.Show(Lang.Get("msg.error.other", ("detail", ex2.GetType().Name))); } finally { recorder.Dispose(); } } private static bool HandsScroll() { Character localCharacter = Character.localCharacter; Item val = (((Object)(object)localCharacter != (Object)null && (Object)(object)localCharacter.data != (Object)null) ? localCharacter.data.currentItem : null); if ((Object)(object)val == (Object)null) { return false; } if (!((Object)(object)((Component)val).GetComponentInChildren<Action_GuidebookScroll>(true) != (Object)null) && !((Object)(object)((Component)val).GetComponentInChildren<Actions_Binoculars>(true) != (Object)null) && !((Object)(object)((Component)val).GetComponentInChildren<Action_ConstructableScoutCannonScroll>(true) != (Object)null)) { return (Object)(object)((Component)val).GetComponentInChildren<RopeSpool>(true) != (Object)null; } return true; } private static BingBongPlace? LyingNearby() { //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) Character localCharacter = Character.localCharacter; if ((Object)(object)localCharacter == (Object)null || (Object)(object)localCharacter.data == (Object)null || localCharacter.data.dead) { return null; } Vector3 me = localCharacter.Center; return (from p in BingBongPlace.All() where (Object)(object)p.Carrier == (Object)null && Vector3.Distance(p.Position, me) < 25f orderby Vector3.Distance(p.Position, me) select p).FirstOrDefault(); } public static Action_AskBingBong? HeldBingBong() { Character localCharacter = Character.localCharacter; if ((Object)(object)localCharacter == (Object)null || (Object)(object)localCharacter.data == (Object)null || localCharacter.data.dead) { return null; } Item currentItem = localCharacter.data.currentItem; Action_AskBingBong result = default(Action_AskBingBong); if (!((Object)(object)currentItem != (Object)null) || !((Component)currentItem).TryGetComponent<Action_AskBingBong>(ref result)) { return null; } return result; } private static bool AnyOtherWindowBlocks() { if (!AskWindow.IsOpen) { if ((Object)(object)GUIManager.instance != (Object)null) { return GUIManager.instance.windowBlockingInput; } return false; } return true; } } internal static class Lang { public const string Auto = "auto"; private const string Fallback = "en"; private static Dictionary<string, Dictionary<string, string>>? s_tables; public static IReadOnlyList<string> Available { get { List<string> list = Tables.Keys.ToList(); list.Sort((string a, string b) => (!(a == "en")) ? ((b == "en") ? 1 : string.CompareOrdinal(a, b)) : (-1)); return list; } } public static string Current { get { string text = Plugin.Language.Value.Trim().ToLowerInvariant(); if (text != "auto" && Tables.ContainsKey(text)) { return text; } string text2 = FromGame(); if (!Tables.ContainsKey(text2)) { return "en"; } return text2; } } public static bool IsAuto => Plugin.Language.Value.Trim().ToLowerInvariant() == "auto"; private static Dictionary<string, Dictionary<string, string>> Tables => s_tables ?? (s_tables = LoadTables()); public static string NativeName(string code) { if (!Tables.TryGetValue(code, out Dictionary<string, string> value) || !value.TryGetValue("_language", out var value2)) { return code; } return value2; } public static string Get(string key, params (string name, object value)[] args) { return Format(Lookup(key), args); } public static string Count(long n, string key) { string[] array = Get(key).Split('|'); int num; if (n >= 1000) { num = 2; } else { int num2; if (array.Length < 3) { num2 = ((n != 1) ? 1 : 0); } else { int num3; if (n % 10 == 1 && n % 100 != 11) { num3 = 0; } else { long num4 = n % 10; bool flag = num4 >= 2 && num4 <= 4; bool flag2 = flag; if (flag2) { num4 = n % 100; bool flag3 = ((num4 < 12 || num4 > 14) ? true : false); flag2 = flag3; } num3 = (flag2 ? 1 : 2); } num2 = num3; } num = num2; } int val = num; return Short(n) + " " + array[Math.Min(val, array.Length - 1)]; } public static string Short(long n) { if (n < 1000) { return n.ToString(CultureInfo.InvariantCulture); } bool flag = n >= 1000000; string item = ((double)n / (flag ? 1000000.0 : 1000.0)).ToString((n >= 100000 && !flag) ? "0" : "0.#", CultureInfo.InvariantCulture).Replace(".", Get("number.decimal_point")); return Get(flag ? "number.millions" : "number.thousands", ("n", item)); } public static string? Find(string key) { if (!TryLookup(Current, key, out string text) && !TryLookup("en", key, out text)) { return null; } return text; } private static string Lookup(string key) { return Find(key) ?? key; } private static bool TryLookup(string language, string key, out string text) { text = ""; if (Tables.TryGetValue(language, out Dictionary<string, string> value) && value.TryGetValue(key, out text)) { return !string.IsNullOrEmpty(text); } return false; } private static string Format(string text, (string name, object value)[] args) { for (int i = 0; i < args.Length; i++) { (string name, object value) tuple = args[i]; string item = tuple.name; object item2 = tuple.value; text = text.Replace("{" + item + "}", item2?.ToString() ?? ""); } return text; } private static string FromGame() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return CodeFor(LocalizedText.CURRENT_LANGUAGE); } internal static string CodeFor(Language language) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected I4, but got Unknown return (int)language switch { 0 => "en", 1 => "fr", 2 => "it", 3 => "de", 4 => "es", 5 => "es-419", 6 => "pt-br", 7 => "ru", 8 => "uk", 9 => "zh-hans", 10 => "zh-hant", 11 => "ja", 12 => "ko", 13 => "pl", 14 => "tr", _ => "en", }; } private static Dictionary<string, Dictionary<string, string>> LoadTables() { Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); Assembly executingAssembly = Assembly.GetExecutingAssembly(); string[] manifestResourceNames = executingAssembly.GetManifestResourceNames(); foreach (string text in manifestResourceNames) { if (!text.StartsWith("Lang.", StringComparison.Ordinal) || !text.EndsWith(".json", StringComparison.Ordinal)) { continue; } string code = text.Substring(5, text.Length - 10).ToLowerInvariant(); using Stream stream = executingAssembly.GetManifestResourceStream(text); using StreamReader streamReader = new StreamReader(stream); Merge(dictionary, code, streamReader.ReadToEnd(), text); } string path = Path.Combine(Path.GetDirectoryName(executingAssembly.Location) ?? "", "Lang"); if (Directory.Exists(path)) { string[] files = Directory.GetFiles(path, "*.json"); foreach (string text2 in files) { Merge(dictionary, Path.GetFileNameWithoutExtension(text2).ToLowerInvariant(), File.ReadAllText(text2), text2); } } Plugin.Log.LogInfo((object)("Languages: " + string.Join(", ", dictionary.Keys))); return dictionary; } private static void Merge(Dictionary<string, Dictionary<string, string>> tables, string code, string json, string source) { try { Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json) ?? new Dictionary<string, string>(); if (!tables.TryGetValue(code, out Dictionary<string, string> value)) { value = (tables[code] = new Dictionary<string, string>()); } foreach (KeyValuePair<string, string> item in dictionary) { value[item.Key] = item.Value; } } catch (Exception ex) { Plugin.Log.LogError((object)("Could not read translation " + source + ": " + ex.Message)); } } public static void CycleOverride() { List<string> list = new List<string> { "auto" }; list.AddRange(Available); string item = Plugin.Language.Value.Trim().ToLowerInvariant(); int num = list.IndexOf(item); Plugin.Language.Value = list[(num + 1) % list.Count]; } public static string MenuLanguageLabel() { string text = NativeName(Current); return Get("settings.language", ("lang", IsAuto ? Get("settings.language_auto", ("lang", text)) : text)); } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("CavyCrew.BingBongAI", "Bing Bong AI", "0.9.1")] public class Plugin : BaseUnityPlugin { public const string Id = "CavyCrew.BingBongAI"; internal static ManualLogSource Log { get; private set; } internal static ConfigEntry<bool> AiEnabled { get; private set; } internal static ConfigEntry<string> Provider { get; private set; } internal static ConfigEntry<string> BaseUrl { get; private set; } internal static ConfigEntry<string> Model { get; private set; } internal static ConfigEntry<float> Temperature { get; private set; } internal static ConfigEntry<int> MaxReplyTokens { get; private set; } internal static ConfigEntry<string> Personality { get; private set; } internal static ConfigEntry<string> PersonalityCustom { get; private set; } internal static ConfigEntry<string> ReplyLength { get; private set; } internal static ConfigEntry<int> TimeoutSeconds { get; private set; } internal static ConfigEntry<bool> NoThinking { get; private set; } internal static ConfigEntry<bool> SendNicknames { get; private set; } internal static ConfigEntry<int> MemoryPairs { get; private set; } internal static ConfigEntry<bool> RunSummary { get; private set; } internal static ConfigEntry<int> PastRuns { get; private set; } internal static ConfigEntry<bool> Reactions { get; private set; } internal static ConfigEntry<int> ReactionCooldownSeconds { get; private set; } internal static ConfigEntry<bool> GuineaPigs { get; private set; } internal static ConfigEntry<bool> GameEvents { get; private set; } internal static ConfigEntry<int> GameEventMinutes { get; private set; } internal static ConfigEntry<bool> Basketball { get; private set; } internal static ConfigEntry<bool> ShowScoreboard { get; private set; } internal static ConfigEntry<bool> RealDate { get; private set; } internal static ConfigEntry<int> CommentatorMinutes { get; private set; } internal static ConfigEntry<int> CommentatorRestMinutes { get; private set; } internal static ConfigEntry<int> PigRemarkMinutes { get; private set; } internal static ConfigEntry<string> VoiceProvider { get; private set; } internal static ConfigEntry<string> WindowsVoiceId { get; private set; } internal static ConfigEntry<string> OnlineVoice { get; private set; } internal static ConfigEntry<float> VoicePitch { get; private set; } internal static ConfigEntry<float> VoiceVolume { get; private set; } internal static ConfigEntry<float> VoiceSpeed { get; private set; } internal static ConfigEntry<string> OpenAiSpeechModel { get; private set; } internal static ConfigEntry<string> OpenAiVoice { get; private set; } internal static ConfigEntry<string> SpeechInstructions { get; private set; } internal static ConfigEntry<string> ElevenModel { get; private set; } internal static ConfigEntry<string> ElevenVoiceId { get; private set; } internal static ConfigEntry<string> ElevenVoiceName { get; private set; } internal static ConfigEntry<string> KieSpeechModel { get; private set; } internal static ConfigEntry<string> KieVoiceId { get; private set; } internal static ConfigEntry<string> KieGeminiVoice { get; private set; } internal static ConfigEntry<string> GoogleSpeechModel { get; private set; } internal static ConfigEntry<string> GoogleVoice { get; private set; } internal static ConfigEntry<string> FalSpeechModel { get; private set; } internal static ConfigEntry<string> FalGeminiVoice { get; private set; } internal static ConfigEntry<string> FalElevenVoice { get; private set; } internal static ConfigEntry<bool> ElevenShowPaid { get; private set; } internal static ConfigEntry<string> SpeechServerUrl { get; private set; } internal static ConfigEntry<string> SpeechServerModel { get; private set; } internal static ConfigEntry<string> SpeechServerVoice { get; private set; } internal static ConfigEntry<string> SpeechLocalUrl { get; private set; } internal static ConfigEntry<string> SpeechLocalModel { get; private set; } internal static ConfigEntry<string> SpeechLocalVoice { get; private set; } internal static ConfigEntry<string> ListenProvider { get; private set; } internal static ConfigEntry<string> ListenGroqModel { get; private set; } internal static ConfigEntry<string> ListenOpenAiModel { get; private set; } internal static ConfigEntry<string> ListenServerUrl { get; private set; } internal static ConfigEntry<string> ListenServerModel { get; private set; } internal static ConfigEntry<string> ListenLocalUrl { get; private set; } internal static ConfigEntry<string> ListenLocalModel { get; private set; } internal static ConfigEntry<string> SettingsKey { get; private set; } internal static ConfigEntry<string> AskKey { get; private set; } internal static ConfigEntry<string> TalkKey { get; private set; } internal static ConfigEntry<string> Language { get; private set; } internal static ConfigEntry<string> BingBongLanguage { get; private set; } internal static ConfigEntry<bool> ShareAi { get; private set; } internal static ConfigEntry<string> AddressMeAs { get; private set; } internal static ConfigEntry<string> CallMeBy { get; private set; } internal static ConfigEntry<string> MyName { get; private set; } internal static ConfigEntry<int> GuestMinSeconds { get; private set; } internal static ConfigEntry<int> GuestPerMinute { get; private set; } internal static ConfigEntry<bool> VerboseLogging { get; private set; } internal static ConfigEntry<bool> LogPrompts { get; private set; } public static string Name => "Bing Bong AI"; public static string Version => "0.9.1"; private void Awake() { //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Expected O, but got Unknown //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Expected O, but got Unknown //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Expected O, but got Unknown //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Expected O, but got Unknown //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Expected O, but got Unknown //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Expected O, but got Unknown //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_036c: Expected O, but got Unknown //IL_03f4: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Expected O, but got Unknown //IL_0426: Unknown result type (might be due to invalid IL or missing references) //IL_0430: Expected O, but got Unknown //IL_04cf: Unknown result type (might be due to invalid IL or missing references) //IL_04d9: Expected O, but got Unknown //IL_050c: Unknown result type (might be due to invalid IL or missing references) //IL_0516: Expected O, but got Unknown //IL_0549: Unknown result type (might be due to invalid IL or missing references) //IL_0553: Expected O, but got Unknown //IL_0aa7: Unknown result type (might be due to invalid IL or missing references) //IL_0ab1: Expected O, but got Unknown //IL_0ad9: Unknown result type (might be due to invalid IL or missing references) //IL_0ae3: Expected O, but got Unknown //IL_0b51: Unknown result type (might be due to invalid IL or missing references) //IL_0b5b: Expected O, but got Unknown //IL_0bcf: Unknown result type (might be due to invalid IL or missing references) //IL_0bd5: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; AiEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "Enabled", true, "Bing Bong answers through the AI. Off = the normal random voice lines."); Provider = ((BaseUnityPlugin)this).Config.Bind<string>("AI", "Provider", "deepseek", "Which service the settings window shows: deepseek, claude, gemini, gemma, glm, xai (Grok), openai, openrouter, groq (not Grok: open models), mistral, kie, fal, server (another online service), lmstudio, ollama or custom (another program on this PC)."); BaseUrl = ((BaseUnityPlugin)this).Config.Bind<string>("AI", "BaseUrl", "https://api.deepseek.com", "Address of the AI's API (usually ends in /v1). Used only for server (own server), custom and openrouter; the ready-made services always use their own address."); Model = ((BaseUnityPlugin)this).Config.Bind<string>("AI", "Model", "deepseek-flash", "Model name as the service calls it."); Temperature = ((BaseUnityPlugin)this).Config.Bind<float>("AI", "Temperature", 0.9f, new ConfigDescription("How playful and unpredictable the answers are.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1.5f), Array.Empty<object>())); MaxReplyTokens = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "MaxReplyTokens", 1000, new ConfigDescription("Upper limit of tokens per answer. Bing Bong is told to be brief; models that 'think' first need room for the thinking.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(100, 8000), Array.Empty<object>())); Personality = ((BaseUnityPlugin)this).Config.Bind<string>("AI", "Personality", "smart", "Bing Bong's character: smart (a clever, witty companion), naive (a cheerful little simpleton), snarky (teasing but kind), coward (scared of everything), grumpy (grumbles but cares), storyteller (legends and parables), seadog (an old sailor), teacher (speaks simply and explains words, for learning the speech language), expert (knows the game, with notes from its data) or custom (your own text below)."); PersonalityCustom = ((BaseUnityPlugin)this).Config.Bind<string>("AI", "PersonalityCustom", "", "Your own description of Bing Bong's character, used when Personality = custom."); ReplyLength = ((BaseUnityPlugin)this).Config.Bind<string>("AI", "ReplyLength", "normal", "How long his answers are: short (1-2 sentences), normal (1-3) or long (up to 5)."); TimeoutSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "TimeoutSeconds", 60, new ConfigDescription("How long to wait for an answer.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 300), Array.Empty<object>())); NoThinking = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "NoThinking", true, "Ask models that 'think' before answering to skip it or keep it short (each service has its own switch): answers come several times faster. Services that do not understand it are asked again without it."); MemoryPairs = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "MemoryPairs", 12, new ConfigDescription("How many recent question/answer pairs Bing Bong remembers word for word. Older ones are folded into a short memory of the whole run. More = longer word-for-word memory, but longer requests.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); RunSummary = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "RunSummary", true, "Fold the older conversation into a short memory of the whole run (one small extra request every few answers). Off = older pairs are simply forgotten."); PastRuns = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "PastRuns", 1, new ConfigDescription("How many earlier runs Bing Bong remembers (their short memories, kept in %APPDATA%\\BingBongAI). 0 = none.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20), Array.Empty<object>())); SendNicknames = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "SendNicknames", false, "Also send the scouts' nicknames to the AI service. Off = Bing Bong tells scouts apart by colour only."); Reactions = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "Reactions", true, "Bing Bong speaks up on his own when he is held over a fire, cooked, thrown hard, falls far or lands in water. Only the game of the scout who did it reacts."); ReactionCooldownSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "ReactionCooldownSeconds", 60, new ConfigDescription("Pause between two reactions of the same kind (fire, throws and falls, water); any two reactions are at least 20 s apart.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(15, 900), Array.Empty<object>())); GuineaPigs = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "GuineaPigs", true, "With our mod 'Guinea Pigs and Their Treats' installed: Bing Bong knows the pigs near him and now and then speaks about them (in hands, a pocket or a backpack). Without that mod this does nothing."); PigRemarkMinutes = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "PigRemarkMinutes", 10, new ConfigDescription("At most one remark about the guinea pigs per this many minutes.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 60), Array.Empty<object>())); GameEvents = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "GameEvents", true, "Bing Bong now and then speaks up about the game: a scout passes out, comes to, dies or is brought back, a campfire is lit, the scouts reach a new stage."); GameEventMinutes = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "GameEventMinutes", 4, new ConfigDescription("At most one remark about the game's events per this many minutes.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), Array.Empty<object>())); Basketball = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "BasketballCommentator", true, "When the scouts throw the basketball at a hoop, Bing Bong comments like a sports broadcast."); RealDate = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "RealDate", true, "Tell the AI today's real date and time (the brain's clock), so it knows what year it is."); ShowScoreboard = ((BaseUnityPlugin)this).Config.Bind<bool>("AI", "Scoreboard", true, "Show Bing Bong's holographic scoreboard next to the hoop during a basketball game (each player's own setting)."); CommentatorMinutes = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "CommentatorMinutes", 4, new ConfigDescription("After this many minutes of commenting Bing Bong takes a break.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 15), Array.Empty<object>())); CommentatorRestMinutes = ((BaseUnityPlugin)this).Config.Bind<int>("AI", "CommentatorRestMinutes", 3, new ConfigDescription("How long the commentator's break lasts, in minutes.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), Array.Empty<object>())); VoiceProvider = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "Provider", "windows", "Bing Bong's voice: windows (the voices built into Windows, no setup), openai (needs the OpenAI key), elevenlabs (needs an ElevenLabs key), kie (ElevenLabs and Gemini voices through kie.ai, needs a kie.ai key), fal (Gemini and ElevenLabs voices through fal.ai, needs a fal.ai key), google (Gemini voices from Google directly, needs the Gemini key), server (another online speech service with OpenAI's /audio/speech API), local (a speech server on this PC) or off (subtitles only)."); OnlineVoice = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "LastOnlineProvider", "openai", "The online voice service the settings window comes back to (openai, elevenlabs, kie, fal, google or server)."); WindowsVoiceId = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "WindowsVoice", "", "Windows voice per language, as language=registry path separated by ';' (picked in the settings window). A language without a choice gets the best installed voice for it, a male one if there is one."); VoicePitch = ((BaseUnityPlugin)this).Config.Bind<float>("Voice", "Pitch", 1.25f, new ConfigDescription("How high (and fast) he sounds: 1 = the voice as it is, 1.25 = a squeaky toy.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>())); VoiceVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Voice", "Volume", 1f, new ConfigDescription("Bing Bong's voice volume on top of the game's sound volume: 1 = 100%.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), Array.Empty<object>())); VoiceSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Voice", "Speed", 1f, new ConfigDescription("How fast Bing Bong speaks, 1 = normal. Every voice service applies what it can (ElevenLabs 0.7-1.2; Gemini gets it as a hint). The pitch already speeds him up a little.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>())); OpenAiSpeechModel = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "OpenAiModel", "gpt-4o-mini-tts", "OpenAI speech model."); OpenAiVoice = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "OpenAiVoice", "ash", "OpenAI voice name."); SpeechInstructions = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "OpenAiInstructions", "", "How OpenAI's voice should speak. Empty = a cheerful, slightly squeaky plush toy (in the mod's language)."); ElevenModel = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "ElevenLabsModel", "eleven_flash_v2_5", "ElevenLabs model: eleven_flash_v2_5 is the fastest, eleven_multilingual_v2 and eleven_v3 sound richer."); ElevenVoiceId = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "ElevenLabsVoice", "", "ElevenLabs voice id (picked in the settings window)."); ElevenVoiceName = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "ElevenLabsVoiceName", "", "Name of that voice, for the settings window."); KieSpeechModel = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "KieModel", "google/gemini-3-8-flash-tts", "kie.ai speech model: google/gemini-3-8-flash-tts, google/gemini-3-8-flash-lite-tts, google/gemini-3-1-flash-tts, elevenlabs/text-to-speech-turbo-2-5 or elevenlabs/text-to-speech-multilingual-v2."); KieVoiceId = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "KieVoice", "9yzdeviXkFddZ4Oz8Mok", "kie.ai ElevenLabs voice id (picked in the settings window)."); ElevenShowPaid = ((BaseUnityPlugin)this).Config.Bind<bool>("Voice", "ElevenShowLibraryVoices", false, "Also list ElevenLabs Voice Library voices, which only paid plans can use through the API."); KieGeminiVoice = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "KieGeminiVoice", "Puck", "kie.ai Gemini voice name (Puck, Fenrir, Zephyr...; picked in the settings window)."); GoogleSpeechModel = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "GoogleModel", "gemini-3.8-flash-lite-tts", "Google's Gemini speech model (Provider = google): gemini-3.8-flash-lite-tts (faster, cheaper) or gemini-3.8-flash-tts (more expressive)."); GoogleVoice = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "GoogleVoice", "Puck", "Google's Gemini voice name (Provider = google): Puck, Kore, Charon...; picked in the settings window."); FalSpeechModel = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "FalModel", "fal-ai/gemini-3.1-flash-tts", "fal.ai speech model (Provider = fal): fal-ai/gemini-3.8-flash-lite-tts, fal-ai/gemini-3.8-flash-tts, fal-ai/gemini-3.1-flash-tts, fal-ai/elevenlabs/tts/turbo-v2.5, fal-ai/elevenlabs/tts/multilingual-v2 or fal-ai/elevenlabs/tts/eleven-v3."); FalGeminiVoice = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "FalGeminiVoice", "Puck", "fal.ai Gemini voice name (Puck, Kore, Charon...; picked in the settings window)."); FalElevenVoice = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "FalElevenVoice", "Rachel", "fal.ai ElevenLabs voice name (Rachel, Aria, Roger...; picked in the settings window)."); SpeechServerUrl = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "OwnServerUrl", "", "Address of another online speech service with OpenAI's /audio/speech API (usually ends in /v1)."); SpeechServerModel = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "OwnServerModel", "tts-1", "Model name that service expects."); SpeechServerVoice = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "OwnServerVoice", "", "Voice name that service expects."); SpeechLocalUrl = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "LocalUrl", "http://localhost:8000/v1", "Address of a speech server on this PC with OpenAI's API: Piper through tools/PiperServer/piper_server.py (port 8000, Russian voices), speaches (port 8000), AllTalk (port 7851, XTTS speaks Russian)..."); SpeechLocalModel = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "LocalModel", "tts-1", "Model name the local speech server expects."); SpeechLocalVoice = ((BaseUnityPlugin)this).Config.Bind<string>("Voice", "LocalVoice", "", "Voice name the local speech server expects."); ListenProvider = ((BaseUnityPlugin)this).Config.Bind<string>("Listen", "Provider", "groq", "Speech recognition for spoken questions (hold the talk key while holding Bing Bong): groq, openai, server (another online service with OpenAI's /audio/transcriptions API), local (a Whisper server on this PC) or off (questions by text only)."); ListenGroqModel = ((BaseUnityPlugin)this).Config.Bind<string>("Listen", "GroqModel", "whisper-large-v3-turbo", "Groq's recognition model."); ListenOpenAiModel = ((BaseUnityPlugin)this).Config.Bind<string>("Listen", "OpenAiModel", "gpt-transcribe", "OpenAI's recognition model."); ListenServerUrl = ((BaseUnityPlugin)this).Config.Bind<string>("Listen", "OwnServerUrl", "", "Address of another online recognition service with OpenAI's /audio/transcriptions API (usually ends in /v1)."); ListenServerModel = ((BaseUnityPlugin)this).Config.Bind<string>("Listen", "OwnServerModel", "", "Model that service expects."); ListenLocalUrl = ((BaseUnityPlugin)this).Config.Bind<string>("Listen", "LocalUrl", "http://localhost:8080/v1", "Address of a Whisper server on this PC: whisper.cpp's whisper-server started with --inference-path /v1/audio/transcriptions (port 8080), or speaches (port 8000)."); ListenLocalModel = ((BaseUnityPlugin)this).Config.Bind<string>("Listen", "LocalModel", "", "Model the local server expects (whisper.cpp ignores it)."); SettingsKey = ((BaseUnityPlugin)this).Config.Bind<string>("Controls", "SettingsKey", "F6", "Opens the Bing Bong AI settings. Unity Input System key names, e.g. F6, F7, Numpad5."); AskKey = ((BaseUnityPlugin)this).Config.Bind<string>("Controls", "AskKey", "T", "While holding Bing Bong: opens the box to type a question."); TalkKey = ((BaseUnityPlugin)this).Config.Bind<string>("Controls", "TalkKey", "Y", "While holding Bing Bong: hold it and speak, let go to ask out loud (recognition is set up on the Microphone tab). Y is free in the game's default controls."); Language = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Language", "auto", "Language of the mod's texts and settings window: 'auto' follows the game; or a code such as ru, en."); BingBongLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("General", "BingBongLanguage", "auto", "The language Bing Bong speaks: 'auto' follows the game; or any of the game's languages (en, fr, it, de, es, es-419, pt-br, ru, uk, zh-hans, zh-hant, ja, ko, pl, tr), e.g. to practise one."); AddressMeAs = ((BaseUnityPlugin)this).Config.Bind<string>("General", "AddressMeAs", "any", "How Bing Bong speaks to and about you: he, she, or any (no gender). Teammates' games with the mod see it too, so the lobby's brain knows; it goes to the AI service with your nickname."); CallMeBy = ((BaseUnityPlugin)this).Config.Bind<string>("General", "CallMeBy", "nick", "How Bing Bong calls you, any of: name, nick, colour (comma-separated). More than one: mostly by name, sometimes by nickname, by colour only now and then as a joke. Empty: as the lobby's brain decides (its SendNicknames)."); MyName = ((BaseUnityPlugin)this).Config.Bind<string>("General", "MyName", "", "Your name for Bing Bong when CallMeBy has 'name' (up to 20 letters). Goes to the AI service and to teammates' games."); ShareAi = ((BaseUnityPlugin)this).Config.Bind<bool>("Coop", "ShareAi", true, "Teammates with this mod ask Bing Bong through your AI and everyone hears the answers (you are the lobby's 'brain'). Your keys never leave your computer. Off: only you use your AI."); GuestMinSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("Coop", "GuestMinSeconds", 4, new ConfigDescription("A teammate's next question is taken no sooner than this many seconds after their last.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 60), Array.Empty<object>())); GuestPerMinute = ((BaseUnityPlugin)this).Config.Bind<int>("Coop", "GuestPerMinute", 8, new ConfigDescription("At most this many questions a minute from each teammate.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), Array.Empty<object>())); VerboseLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Write extra diagnostic messages to the BepInEx log."); LogPrompts = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogPrompts", false, "Write every prompt and raw answer to the BepInEx log (never the key). For tuning Bing Bong's character."); SecretStore.LogWarning = delegate(string message) { Log.LogWarning((object)message); }; GameHooks.PatchAll(new Harmony("CavyCrew.BingBongAI")); GameHooks.Start("Reactions", BingBongAI.Brain.Reactions.Init); GameHooks.Start("PigsLink", PigsLink.Init); GameHooks.Start("BrainNet", BrainNet.Init); GameObject val = new GameObject("BingBongAI"); Object.DontDestroyOnLoad((Object)(object)val); ((Object)val).hideFlags = (HideFlags)61; val.AddComponent<Hotkeys>(); val.AddComponent<RunTracker>(); val.AddComponent<BingBongWatcher>(); val.AddComponent<PigWatcher>(); val.AddComponent<GameWatcher>(); val.AddComponent<BrainWatcher>(); val.AddComponent<MicWatch>(); val.AddComponent<SupportWatcher>(); Log.LogInfo((object)("Plugin " + Name + " " + Version + " is loaded! AI: " + (BingBongBrain.IsConfigured ? "configured" : "not configured yet") + ".")); } internal static void Verbose(string message) { if (VerboseLogging.Value) { Log.LogInfo((object)message); } } } } namespace BingBongAI.Voice { internal static class ElevenLabsClient { public const string DefaultBaseUrl = "https://api.elevenlabs.io"; public static readonly string[] KnownModels = new string[3] { "eleven_flash_v2_5", "eleven_multilingual_v2", "eleven_v3" }; public static ChatEndpoint Endpoint(string? key, string baseUrl = "https://api.elevenlabs.io") { return new ChatEndpoint(baseUrl, "", key, ChatProtocol.ElevenLabs); } public static async Task<VoiceAudio> SynthesizeAsync(ChatEndpoint endpoint, string voiceId, string modelId, string text, string? languageCode, TimeSpan timeout, CancellationToken cancel = default(CancellationToken), float speed = 1f) { if (string.IsNullOrWhiteSpace(voiceId)) { throw new ChatException(ChatErrorKind.BadRequest, "No ElevenLabs voice chosen."); } JObject val = new JObject { ["text"] = JToken.op_Implicit(text), ["model_id"] = JToken.op_Implicit(modelId) }; if (Math.Abs(speed - 1f) > 0.01f) { val["voice_settings"] = (JToken)new JObject { ["speed"] = JToken.op_Implicit(Math.Round(Math.Min(1.2f, Math.Max(0.7f, speed)), 2)) }; } if (!string.IsNullOrWhiteSpace(languageCode)) { val["language_code"] = JToken.op_Implicit(languageCode); } byte[] data = await ChatClient.PostForBytesAsync(endpoint, "v1/text-to-speech/" + Uri.EscapeDataString(voiceId.Trim()) + "?output_format=wav_22050", ((JToken)val).ToString((Formatting)0, Array.Empty<JsonConverter>()), timeout, cancel).ConfigureAwait(continueOnCapturedContext: false); try { return Wav.Parse(data); } catch (FormatException ex) { throw new ChatException(ChatErrorKind.BadResponse, "ElevenLabs did not send a WAV file: " + ex.Message, ex); } } public static async Task<List<VoiceInfo>> ListVoicesAsync(ChatEndpoint endpoint, CancellationToken cancel = default(CancellationToken)) { List<VoiceInfo> voices = new List<VoiceInfo>(); string text = null; for (int i = 0; i < 3; i++) { string path = "v2/voices?page_size=100" + ((text != null) ? ("&next_page_token=" + Uri.EscapeDataString(text)) : ""); JObject val = Parse(await ChatClient.GetStringAsync(endpoint, path, TimeSpan.FromSeconds(15.0), cancel).ConfigureAwait(continueOnCapturedContext: false)); JToken obj = val["voices"]; foreach (JToken item in (JArray)(((object)((obj is JArray) ? obj : null)) ?? ((object)new JArray()))) { string text2 = (string)item[(object)"voice_id"]; if (string.IsNullOrWhiteSpace(text2)) { continue; } JToken obj2 = item[(object)"labels"]; JObject val2 = (JObject)(object)((obj2 is JObject) ? obj2 : null); object obj3 = (string)((val2 != null) ? val2["language"] : null); if (obj3 == null) { JToken obj4 = item[(object)"verified_languages"]; JToken obj5 = ((obj4 is JArray) ? obj4 : null); object obj6; if (obj5 == null) { obj6 = null; } else { JToken? obj7 = ((IEnumerable<JToken>)obj5).FirstOrDefault(); obj6 = ((obj7 != null) ? obj7[(object)"language"] : null); } obj3 = ((string)(JToken)obj6) ?? ""; } string language = (string)obj3; voices.Add(new VoiceInfo(text2, ((string)item[(object)"name"]) ?? text2, language, ((string)((val2 != null) ? val2["gender"] : null)) ?? "", IsLibraryVoice(item))); } text = (((bool?)val["has_more"] == true) ? ((string)val["next_page_token"]) : null); if (text == null) { break; } } return voices.OrderBy((VoiceInfo v) => v.Library).ToList(); } private static bool IsLibraryVoice(JToken voice) { JToken obj = voice[(object)"sharing"]; JToken obj2 = ((obj is JObject) ? obj : null); string text = ((string)((obj2 != null) ? ((JObject)obj2)["status"] : null)) ?? ""; if (text.StartsWith("copied", StringComparison.OrdinalIgnoreCase)) { return true; } bool flag; switch (((string)voice[(object)"category"]) ?? "") { case "professional": case "famous": case "high_quality": flag = true; break; default: flag = false; break; } if (flag) { return (bool?)voice[(object)"is_owner"] != true; } return false; } public static async Task<List<string>> ListModelsAsync(ChatEndpoint endpoint, CancellationToken cancel = default(CancellationToken)) { string text = await ChatClient.GetStringAsync(endpoint, "v1/models", TimeSpan.FromSeconds(15.0), cancel).ConfigureAwait(continueOnCapturedContext: false); try { return (from m in (IEnumerable<JToken>)JArray.Parse(text) where (bool?)m[(object)"can_do_text_to_speech"] != false select (string)m[(object)"model_id"] into id where !string.IsNullOrWhiteSpace(id) select (id)).ToList(); } catch (JsonException ex) { JsonException inner = ex; throw new ChatException(ChatErrorKind.BadResponse, "The ElevenLabs model list is not JSON.", (Exception?)(object)inner); } } private static JObject Parse(string json) { //IL_000a: Expected O, but got Unknown try { return JObject.Parse(json); } catch (JsonException ex) { JsonException inner = ex; throw new ChatException(ChatErrorKind.BadResponse, "The ElevenLabs voice list is not JSON.", (Exception?)(object)inner); } } } internal static class FalSpeechClient { public const string DefaultBaseUrl = "https://fal.run"; public static readonly string[] Models = new string[6] { "fal-ai/gemini-3.8-flash-lite-tts", "fal-ai/gemini-3.8-flash-tts", "fal-ai/gemini-3.1-flash-tts", "fal-ai/elevenlabs/tts/turbo-v2.5", "fal-ai/elevenlabs/tts/multilingual-v2", "fal-ai/elevenlabs/tts/eleven-v3" }; public const string DefaultGeminiVoice = "Puck"; public const string DefaultElevenVoice = "Rachel"; public static readonly IReadOnlyList<(string Id, string Name, string Description)> ElevenVoices = new <>z__ReadOnlyArray<(string, string, string)>(new(string, string, string)[21] { ("Rachel", "Rachel", "Calm, female"), ("Aria", "Aria", "Expressive, female"), ("Sarah", "Sarah", "Soft, female"), ("Laura", "Laura", "Upbeat, female"), ("Alice", "Alice", "Confident, British female"), ("Matilda", "Matilda", "Friendly, female"), ("Jessica", "Jessica", "Expressive, young female"), ("Lily", "Lily", "Warm, British female"), ("Charlotte", "Charlotte", "Seductive, female"), ("River", "River", "Confident, neutral"), ("Roger", "Roger", "Confident, male"), ("Charlie", "Charlie", "Natural, Australian male"), ("George", "George", "Warm, British male"), ("Callum", "Callum", "Intense, male"), ("Liam", "Liam", "Articulate, young male"), ("Will", "Will", "Friendly, young male"), ("Eric", "Eric", "Friendly, male"), ("Chris", "Chris", "Casual, male"), ("Brian", "Brian", "Deep, male"), ("Daniel", "Daniel", "Authoritative, British male"), ("Bill", "Bill", "Trustworthy, older male") }); public static bool IsGemini(string model) { return model.IndexOf("gemini", StringComparison.OrdinalIgnoreCase) >= 0; } public static IReadOnlyList<(string Id, string Name, string Description)> VoicesFor(string model) { if (!IsGemini(model)) { return ElevenVoices; } return KieSpeechClient.GeminiVoices.Take(30).ToList(); } public static ChatEndpoint Endpoint(string? key, string baseUrl = "https://fal.run") { return new ChatEndpoint(baseUrl, "", key, ChatProtocol.OpenAiCompatible, Kie: false, Fal: true); } public static async Task<string> SpeakToUrlAsync(ChatEndpoint endpoint, string model, string voice, string text, TimeSpan timeout, CancellationToken cancel = default(CancellationToken), string? style = null, float speed = 1f) { model = model.Trim(); JObject val; if (IsGemini(model)) { val = new JObject { ["prompt"] = JToken.op_Implicit(text), ["voice"] = JToken.op_Implicit(string.IsNullOrWhiteSpace(voice) ? "Puck" : voice.Trim()) }; if (model.IndexOf("gemini-3.1", StringComparison.OrdinalIgnoreCase) >= 0) { val["output_format"] = JToken.op_Implicit("wav"); } if (!string.IsNullOrWhiteSpace(style)) { val["style_instructions"] = JToken.op_Implicit(style); } } else { val = new JObject { ["text"] = JToken.op_Implicit(text), ["voice"] = JToken.op_Implicit(string.IsNullOrWhiteSpace(voice) ? "Rachel" : voice.Trim()) }; if (model.IndexOf("eleven-v3", StringComparison.OrdinalIgnoreCase) < 0) { val["speed"] = JToken.op_Implicit(Math.Round(Math.Min(1.2f, Math.Max(0.7f, speed)), 2)); } } byte[] bytes = await ChatClient.PostForBytesAsync(endpoint, model, ((JToken)val).ToString((Formatting)0, Array.Empty<JsonConverter>()), timeout, cancel).ConfigureAwait(continueOnCapturedContext: false); JObject val2; try { val2 = JObject.Parse(Encoding.UTF8.GetString(bytes)); } catch (JsonException ex) { JsonException inner = ex; throw new ChatException(ChatErrorKind.BadResponse, "fal.ai: the answer is not JSON.", (Exception?)(object)inner); } JToken obj = val2["audio"]; string text2 = (string)((obj != null) ? obj[(object)"url"] : null); if (string.IsNullOrWhiteSpace(text2)) { throw new ChatException(ChatErrorKind.BadResponse, "fal.ai: no audio in the answer."); } return text2; } } internal static class GoogleSpeechClient { public const string DefaultBaseUrl = "https://generativelanguage.googleapis.com/v1beta"; public static readonly string[] Models = new string[3] { "gemini-3.8-flash-lite-tts", "gemini-3.8-flash-tts", "gemini-3.1-flash-tts-preview" }; private const int PcmRate = 24000; public static IReadOnlyList<(string Id, string Name, string Description)> Voices => KieSpeechClient.GeminiVoices; public static IReadOnlyList<(string Id, string Name, string Description)> VoicesFor(string model) { if (model.IndexOf("gemini-3.1", StringComparison.OrdinalIgnoreCase) < 0) { return Voices; } return Voices.Take(30).ToList(); } public static ChatEndpoint Endpoint(string? key, string baseUrl = "https://generativelanguage.googleapis.com/v1beta") { return new ChatEndpoint(baseUrl, "", key, ChatProtocol.Google); } public static async Task<VoiceAudio> SynthesizeAsync(ChatEndpoint endpoint, string model, string voice, string text, string? style, TimeSpan timeout, CancellationToken cancel = default(CancellationToken)) { JObject val = new JObject { ["type"] = JToken.op_Implicit("text"), ["text"] = JToken.op_Implicit(text) }; if (!string.IsNullOrWhiteSpace(style)) { JArray val2 = new JArray(); val2.Add((JToken)new JObject { ["type"] = JToken.op_Implicit("speech_metadata"), ["style"] = JToken.op_Implicit(style.Trim()) }); val["annotations"] = (JToken)val2; } JObject val3 = new JObject { ["model"] = JToken.op_Implicit(model) }; JArray val4 = new JArray(); JObject val5 = new JObject { ["type"] = JToken.op_Implicit("user_input") }; JArray val6 = new JArray(); val6.Add((JToken)(object)val); val5["content"] = (JToken)val6; val4.Add((JToken)val5); val3["input"] = (JToken)val4; val3["response_format"] = (JToken)new JObject { ["type"] = JToken.op_Implicit("audio"), ["mime_type"] = JToken.op_Implicit("audio/wav") }; JObject val7 = new JObject(); JArray val8 = new JArray(); val8.Add((JToken)new JObject { ["voice"] = JToken.op_Implicit(string.IsNullOrWhiteSpace(voice) ? "Puck" : voice.Trim()) }); val7["speech_config"] = (JToken)val8; val3["generation_config"] = (JToken)val7; JObject val9 = val3; byte[] answer; try { answer = await ChatClient.PostForBytesAsync(endpoint, "interactions", ((JToken)val9).ToString((Formatting)0, Array.Empty<JsonConverter>()), timeout, cancel).ConfigureAwait(continueOnCapturedContext: false); } catch (ChatException ex) when (ex.Kind == ChatErrorKind.BadRequest && (ex.Message.IndexOf("API key not valid", StringComparison.OrdinalIgnoreCase) >= 0 || ex.Message.IndexOf("API_KEY_INVALID", StringComparison.OrdinalIgnoreCase) >= 0)) { throw new ChatException(ChatErrorKind.Unauthorized, ex.Message, ex); } byte[] array = Convert.FromBase64String(AudioData(answer)); try { return (array.Length >= 12 && Encoding.ASCII.GetString(array, 0, 4) == "RIFF") ? Wav.Parse(array) : FromPcm(array); } catch (FormatException ex2) { throw new ChatException(ChatErrorKind.BadResponse, "Google did not send a WAV file: " + ex2.Message, ex2); } } private static string AudioData(byte[] answer) { //IL_0014: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) JObject val; try { val = JObject.Parse(Encoding.UTF8.GetString(answer)); } catch (JsonException ex) { JsonException inner = ex; throw new ChatException(ChatErrorKind.BadResponse, "Google's answer is not JSON.", (Exception?)(object)inner); } JToken obj = val["steps"]; string text = (from content in ((IEnumerable<JToken>)(((object)((obj is JArray) ? obj : null)) ?? ((object)new JArray()))).Where((JToken step) => (string)step[(object)"type"] == "model_output").SelectMany(delegate(JToken step) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) JToken obj2 = step[(object)"content"]; return (IEnumerable<JToken>)(((object)((obj2 is JArray) ? obj2 : null)) ?? ((object)new JArray())); }) where (string)content[(object)"type"] == "audio" select (string)content[(object)"data"]).LastOrDefault((string value) => !string.IsNullOrEmpty(value)); return text ?? throw new ChatException(ChatErrorKind.BadResponse, "Google's answer has no audio."); } private static VoiceAudio FromPcm(byte[] pcm) { float[] array = new float[pcm.Length / 2]; for (int i = 0; i < array.Length; i++) { array[i] = (float)BitConverter.ToInt16(pcm, i * 2) / 32768f; } return new VoiceAudio(array, 1, 24000); } } internal static class KieSpeechClient { public const string DefaultBaseUrl = "https://api.kie.ai"; public static readonly string[] Models = new string[5] { "elevenlabs/text-to-speech-turbo-2-5", "elevenlabs/text-to-speech-multilingual-v2", "google/gemini-3-8-flash-tts", "google/gemini-3-8-flash-lite-tts", "google/gemini-3-1-flash-tts" }; public const string DefaultGeminiVoice = "Puck"; public static readonly IReadOnlyList<(string Id, string Name, string Description)> GeminiVoices = new <>z__ReadOnlyArray<(string, string, string)>(new(string, string, string)[70] { ("Puck", "Puck", "Upbeat"), ("Fenrir", "Fenrir", "Excitable"), ("Zephyr", "Zephyr", "Bright"), ("Leda", "Leda", "Youthful"), ("Charon", "Charon", "Informative"), ("Kore", "Kore", "Firm"), ("Orus", "Orus", "Firm"), ("Aoede", "Aoede", "Breezy"), ("Callirrhoe", "Callirrhoe", "Easy-going"), ("Autonoe", "Autonoe", "Bright"), ("Enceladus", "Enceladus", "Breathy"), ("Iapetus", "Iapetus", "Clear"), ("Umbriel", "Umbriel", "Easy-going"), ("Algieba", "Algieba", "Smooth"), ("Despina", "Despina", "Smooth"), ("Erinome", "Erinome", "Clear"), ("Algenib", "Algenib", "Gravelly"), ("Rasalgethi", "Rasalgethi", "Informative"), ("Laomedeia", "Laomedeia", "Upbeat"), ("Achernar", "Achernar", "Soft"), ("Alnilam", "Alnilam", "Firm"), ("Schedar", "Schedar", "Even"), ("Gacrux", "Gacrux", "Mature"), ("Pulcherrima", "Pulcherrima", "Forward"), ("Achird", "Achird", "Friendly"), ("Zubenelgenubi", "Zubenelgenubi", "Casual"), ("Vindemiatrix", "Vindemiatrix", "Gentle"), ("Sadachbia", "Sadachbia", "Lively"), ("Sadaltager", "Sadaltager", "Knowledgeable"), ("Sulafat", "Sulafat", "Warm"), ("Bodi", "Bodi", "Tutor, 3.8"), ("Lumi", "Lumi", "Tutor, 3.8"), ("Sola", "Sola", "Tutor, 3.8"), ("Varo", "Varo", "Tutor, 3.8"), ("Koda", "Koda", "Commercial voiceover, 3.8"), ("Nika", "Nika", "Commercial voiceover, 3.8"), ("Tavi", "Tavi", "Commercial voiceover, 3.8"), ("Zeno", "Zeno", "Commercial voiceover, 3.8"), ("Kira", "Kira", "Instructional, 3.8"), ("Ludo", "Ludo", "Instructional, 3.8"), ("Mako", "Mako", "Instructional, 3.8"), ("Rina", "Rina", "Instructional, 3.8"), ("Brio", "Brio", "Podcast, 3.8"), ("Jori", "Jori", "Podcast, 3.8"), ("Rami", "Rami", "Podcast, 3.8"), ("Veda", "Veda", "Podcast, 3.8"), ("Enzo", "Enzo", "Storyteller, 3.8"), ("Riko", "Riko", "Storyteller, 3.8"), ("Sami", "Sami", "Storyteller, 3.8"), ("Zali", "Zali", "Storyteller, 3.8"), ("Gero", "Gero", "Digital assistant, 3.8"), ("Neno", "Neno", "Digital assistant, 3.8"), ("Olin", "Olin", "Digital assistant, 3.8"), ("Tari", "Tari", "Digital assistant, 3.8"), ("Daro", "Daro", "Call center, 3.8"), ("Fola", "Fola", "Call center, 3.8"), ("Hali", "Hali", "Call center, 3.8"), ("Milo", "Milo", "Call center, 3.8"), ("Arlo", "Arlo", "Concierge, 3.8"), ("Cleo", "Cleo", "Concierge, 3.8"), ("Finn", "Finn", "Concierge, 3.8"), ("Lora", "Lora", "Concierge, 3.8"), ("Enya", "Enya", "Tech support, 3.8"), ("Jett", "Jett", "Tech support, 3.8"), ("Knox", "Knox", "Tech support, 3.8"), ("Nyla", "Nyla", "Tech support, 3.8"), ("Cruz", "Cruz", "Professional, 3.8"), ("Elio", "Elio", "Professional, 3.8"), ("Tova", "Tova", "Professional, 3.8"), ("Zuri", "Zuri", "Professional, 3.8") }); private static bool s_skipLanguageCode; public static readonly IReadOnlyList<(string Id, string Name, string Description)> Voices = new <>z__ReadOnlyArray<(string, string, string)>(new(string, string, string)[64] { ("EkK5I93UQWFDigLMpZcX", "James", "Husky, Engaging and Bold"), ("Z3R5wn05IrDiVCyEkUrK", "Arabella", "Mysterious and Emotive"), ("NNl6r8mD7vthiJatiJt1", "Bradford", "Expressive"), ("YOq2y2Up4RgXP2HyXjE5", "Xavier", "Dominating, Metallic"), ("B8gJV1IhpuegLxdpXFOE", "Kuon", "Cheerful, Clear and Steady"), ("2zRM7PkgwBPiau2jvVXc", "Monika Sogam", "Deep and Natural"), ("1SM7GgM6IMuvQlz2BwM3", "Mark", "Casual, Relaxed and Light"), ("5l5f8iK3YPeGga21rQIX", "Adeline", "Feminine"), ("scOwDtmlUjD3prqpp97I", "Sam", "Support Agent"), ("NOpBlnGInO9m6vDvFkFC", "Spuds Oxley", "Wise"), ("BZgkqPqms7Kj9ulSkVzn", "Eve", "Authentic, Energetic"), ("DGzg6RaUqxGRTHSBjfgF", "Brock", "Commanding and Loud"), ("x70vRnQBMBu4FAYhjJbO", "Nathan", "Virtual Radio Host"), ("Sm1seazb4gs7RSlUVw7c", "Anika", "Animated, Friendly"), ("P1bg08DkjqiVEzOn76yG", "Viraj", "Rich and Soft"), ("qDuRKMlYmrm8trt5QyBn", "Taksh", "Calm, Serious and Smooth"), ("qXpMhyvQqiRxWQs4qSSB", "Horatius", "Energetic Character"), ("TX3LPaxmHKxFdv7VOQHJ", "Liam", "Energetic, Social Media"), ("N2lVS1w4EtoT3dr4eOWO", "Callum", "Husky Trickster"), ("FGY2WhTYpPnrIDTdsKH5", "Laura", "Enthusiast, Quirky"), ("kPzsL2i3teMYv0FxEYQ6", "Brittney", "Social Media Voice -"), ("UgBBYS2sOqTuMpoF3BR0", "Mark", "Natural Conversations"), ("hpp4J3VqNfWAUOO0d1Us", "Bella", "Professional, Bright"), ("nPczCjzI2devNBz1zQrb", "Brian", "Deep, Resonant"), ("uYXf8XasLslADfZ2MB4u", "Hope", "Bubbly, Gossipy and Girly"), ("gs0tAILXbY5DNrJrsM6F", "Jeff", "Classy, Resonating"), ("DTKMou8ccj1ZaWGBiotd", "Jamahal", "Young, Vibrant"), ("vBKc2FfBKJfcZNyEt1n6", "Finn", "Youthful, Eager"), ("DYkrAHD8iwork3YSUBbs", "Tom", "Conversations & Books"), ("56AoDkrOh6qfVPDXZ7Pt", "Cassidy", "Crisp, Direct and Clear"), ("eR40ATw9ArzDf9h3v7t7", "Addison 2.0", "Australian"), ("g6xIsTj2HwM6VR4iXFCw", "Jessica Anne Bogart", "Chatty"), ("lcMyyd2HUfFzxdCaC4Ta", "Lucy", "Fresh & Casual"), ("6aDn1KB0hjpdcocrUkmq", "Tiffany", "Natural and Welcoming"), ("Sq93GQT4X1lKDXsQcixO", "Felix", "Warm, Positive"), ("flHkNRp1BlvT73UL6gyz", "Jessica Anne Bogart", "Eloquent"), ("9yzdeviXkFddZ4Oz8Mok", "Lutz", "Chuckling, Giggly"), ("pPdl9cQBQq4p6mRkZy2Z", "Emma", "Adorable and Upbeat"), ("zYcjlYFOd3taleS0gkk3", "Edward", "Loud, Confident"), ("nzeAacJi50IvxcyDnMXa", "Marshal", "Friendly, Funny"), ("ruirxsoakN0GWmGNIo04", "John Morgan", "Gritty, Rugged"), ("TC0Zp7WVFzhA8zpTlRqV", "Aria", "Sultry Villain"), ("ljo9gAlSqKOvF6D8sOsX", "Viking Bjorn", "Epic Medieval"), ("8JVbfL6oEdmuxKn5DK2C", "Johnny Kid", "Serious and Calm"), ("iCrDUkL56s3C8sCRl7wb", "Hope", "Poetic, Romantic"), ("wJqPPQ618aTW29mptyoc", "Ana Rita", "Smooth, Expressive"), ("EiNlNiXeDU1pqqOPrYMO", "John Doe", "Deep"), ("4YYIPFl9wE5c4L2eu2Gb", "Burt Reynolds™", "Deep, Smooth"), ("6F5Zhi321D3Oq7v1oNT4", "Hank", "Deep and Engaging Narrator"), ("YXpFCvM1S3JbWEJhoskW", "Wyatt", "Wise Rustic Cowboy"), ("LG95yZDEHg6fCZdQjLqj", "Phil", "Explosive, Passionate"), ("CeNX9CMwmxDxUF5Q2Inm", "Johnny Dynamite", "Vintage Radio"), ("aD6riP1btT197c6dACmy", "Rachel M", "Pro British Radio"), ("mtrellq69YZsNwzUSyXh", "Rex Thunder", "Deep N Tough"), ("dHd5gvgSOzSfduK4CvEg", "Ed", "Late Night Announcer"), ("eVItLK1UvXctxuaRV2Oq", "Jean", "Alluring and Playful Femme"), ("esy0r39YPLQjOczyOib8", "Britney", "Calm and Calculative"), ("Tsns2HvNFKfGiNjllgqo", "Sven", "Emotional and Nice"), ("1U02n4nD6AdIZ9CjF053", "Viraj", "Smooth and Gentle"), ("AeRdCCKzvd23BpJoofzx", "Nathaniel", "Engaging, British"), ("LruHrtVF6PSyGItzMNHS", "Benjamin", "Deep, Warm, Calming"), ("1wGbFxmAM3Fgw63G1zZJ", "Allison", "Calm, Soothing"), ("hqfrgApggtO1785R4Fsn", "Theodore HQ", "Serene and Grounded"), ("MJ0RnG71ty4LH3dvNfSd", "Leon", "Soothing and Grounded") }); public static bool IsGemini(string model) { return model.Trim().StartsWith("google/", StringComparison.OrdinalIgnoreCase); } public static string GeminiSibling(string model) { if (model.IndexOf("gemini-3-8-flash-lite", StringComparison.OrdinalIgnoreCase) < 0) { return "google/gemini-3-8-flash-lite-tts"; } return "google/gemini-3-8-flash-tts"; } public static IReadOnlyList<(string Id, string Name, string Description)> VoicesFor(string model) { if (IsGemini(model)) { if (model.IndexOf("gemini-3-1", StringComparison.OrdinalIgnoreCase) < 0) { return GeminiVoices; } return GeminiVoices.Take(30).ToList(); } return Voices; } public static ChatEndpoint Endpoint(string? key, string baseUrl = "https://api.kie.ai") { return new ChatEndpoint(baseUrl, "", key, ChatProtocol.OpenAiCompatible, Kie: true); } public static async Task<string> SpeakToUrlAsync(ChatEndpoint endpoint, string model, string voice, string text, string? languageCode, TimeSpan timeout, CancellationToken cancel = default(CancellationToken), string? style = null, float speed = 1f, Action<string>? retrying = null) { model = model.Trim(); if (IsGemini(model)) { string[] models = new string[3] { model, model, GeminiSibling(model) }; DateTime started = DateTime.UtcNow; int attempt = 0; while (true) { try { return await RunTaskAsync(endpoint, GeminiBody(models[attempt], voice, text, style), timeout - (DateTime.UtcNow - started), cancel).ConfigureAwait(continueOnCapturedContext: false); } catch (ChatException ex) when (attempt + 1 < models.Length && ex.Kind == ChatErrorKind.BadResponse && ex.Message.StartsWith("kie.ai:", StringComparison.Ordinal) && timeout - (DateTime.UtcNow - started) > TimeSpan.FromSeconds(15.0)) { retrying?.Invoke(models[attempt + 1]); } attempt++; } } bool withLanguage = !s_skipLanguageCode && !string.IsNullOrWhiteSpace(languageCode) && model.IndexOf("turbo", StringComparison.OrdinalIgnoreCase) >= 0; try { return await RunTaskAsync(endpoint, ElevenLabsBody(model, voice, text, withLanguage ? languageCode : null, speed), timeout, cancel).ConfigureAwait(continueOnCapturedContext: false); } catch (ChatException ex2) when (withLanguage && ex2.Kind == ChatErrorKind.BadResponse && ex2.Message.StartsWith("kie.ai:", StringComparison.Ordinal)) { string result = await RunTaskAsync(endpoint, ElevenLabsBody(model, voice, text, null, speed), timeout, cancel).ConfigureAwait(continueOnCapturedContext: false); s_skipLanguageCode = true; return result; } } private static JObject ElevenLabsBody(string model, string voice, string text, string? languageCode, float speed = 1f) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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_0027: 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_0059: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00ac: 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_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown JObject val = new JObject { ["text"] = JToken.op_Implicit(text), ["voice"] = JToken.op_Implicit(voice), ["stability"] = JToken.op_Implicit(0.5), ["similarity_boost"] = JToken.op_Implicit(0.75), ["style"] = JToken.op_Implicit(0), ["speed"] = JToken.op_Implicit(Math.Round(Math.Min(1.2f, Math.Max(0.7f, speed)), 2)) }; if (languageCode != null) { val["language_code"] = JToken.op_Implicit(languageCode); } return new JObject { ["model"] = JToken.op_Implicit(model), ["input"] = (JToken)(object)val }; } private static JObject GeminiBody(string model, string voice, string text, string? style) { //IL_0013: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0053: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //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_0096: Expected O, but got Unknown //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: 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_00ff: 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_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown bool flag = model.IndexOf("gemini-3-1", StringComparison.OrdinalIgnoreCase) >= 0; JObject val = new JObject { ["speaker_id"] = JToken.op_Implicit("Speaker 1"), ["voice_name"] = JToken.op_Implicit(string.IsNullOrWhiteSpace(voice) ? "Puck" : voice.Trim()) }; JObject val2 = new JObject { ["speaker_id"] = JToken.op_Implicit("Speaker 1"), ["text"] = JToken.op_Implicit(text) }; JObject val3 = new JObject { ["temperature"] = JToken.op_Implicit(1) }; if (flag) { val["accent"] = JToken.op_Implicit("Neutral"); } if (!string.IsNullOrWhiteSpace(style)) { if (flag) { val3["sample_context"] = JToken.op_Implicit(style); } else { val2["style"] = JToken.op_Implicit(style); } } val3["speakers"] = (JToken)new JArray((object)val); val3["dialogue_turns"] = (JToken)new JArray((object)val2); return new JObject { ["model"] = JToken.op_Implicit(model), ["input"] = (JToken)(object)val3 }; } private static async Task<string> RunTaskAsync(ChatEndpoint endpoint, JObject body, TimeSpan timeout, CancellationToken cancel) { DateTime started = DateTime.UtcNow; JObject val = Parse(await ChatClient.PostForBytesAsync(endpoint, "api/v1/jobs/createTask", ((JToken)body).ToString((Formatting)0, Array.Empty<JsonConverter>()), timeout, cancel).ConfigureAwait(continueOnCapturedContext: false)); JToken obj = val["data"]; string taskId = (string)((obj != null) ? obj[(object)"taskId"] : null); if (string.IsNullOrWhiteSpace(taskId)) { throw new ChatException(ChatErrorKind.BadResponse, "kie.ai did not return a task id."); } TimeSpan delay = TimeSpan.FromMilliseconds(400.0); JToken val2; while (true) { await Task.Delay(delay, cancel).ConfigureAwait(continueOnCapturedContext: false); if (DateTime.UtcNow - started > timeout) { throw new ChatException(ChatErrorKind.Timeout, $"The kie.ai speech task took longer than {timeout.TotalSeconds:0} s."); } string s = await ChatClient.GetStringAsync(endpoint, "api/v1/jobs/recordInfo?taskId=" + Uri.EscapeDataString(taskId), TimeSpan.FromSeconds(15.0), cancel).ConfigureAwait(continueOnCapturedContext: false); val2 = Parse(Encoding.UTF8.GetBytes(s))["data"]; string text = (string)((val2 != null) ? val2[(object)"state"] : null); if (text == "success") { string text2 = ResultUrl((string)((val2 != null) ? val2[(object)"resultJson"] : null)); return text2 ?? throw new ChatException(ChatErrorKind.BadResponse, "The kie.ai speech task finished without a file."); } if (text == "fail") { break; } if (delay < TimeSpan.FromSeconds(1.5)) { delay += TimeSpan.FromMilliseconds(200.0); } } string text3 = ((string)((val2 != null) ? val2[(object)"failCode"] : null)) ?? ""; throw new ChatException(ChatErrorKind.BadResponse, "kie.ai: " + (((string)((val2 != null) ? val2[(object)"failMsg"] : null)) ?? "the speech task failed") + ((text3.Length > 0) ? (" (code " + text3 + ")") : "")); } private static string? ResultUrl(string? resultJson) { if (string.IsNullOrWhiteSpace(resultJson)) { return null; } try { JToken obj = JObject.Parse(resultJson)["resultUrls"]; return (string)((IEnumerable<JToken>)((obj is JArray) ? obj : null))?.FirstOrDefault(); } catch (JsonException) { return null; } } private static JObject Parse(byte[] body) { //IL_0014: Expected O, but got Unknown JObject val; try { val = JObject.Parse(Encoding.UTF8.GetString(body)); } catch (JsonException ex) { JsonException inner = ex; throw new ChatException(ChatErrorKind.BadResponse, "kie.ai's answer is not JSON.", (Exception?)(object)inner); } ChatClient.ThrowIfServiceError(val); return val; } } internal static class ListenService { public const string Groq = "groq"; public const string OpenAi = "openai"; public const string Server = "server"; public const string Local = "local"; public const string Off = "off"; public static readonly string[] Providers = new string[5] { "groq", "openai", "server", "local", "off" }; public static readonly string[] OnlineProviders = new string[3] { "groq", "openai", "server" }; public const string GroqUrl = "https://api.groq.com/openai/v1"; public const string OpenAiUrl = "https://api.openai.com/v1"; public const string ServerKey = "listen-server"; public const int MaxSeconds = 30; public static readonly string[] GroqModels = new string[2] { "whisper-large-v3-turbo", "whisper-large-v3" }; public static readonly string[] OpenAiModels = new string[2] { "gpt-transcribe", "gpt-4o-mini-transcribe" }; public static string Provider { get { string text = Plugin.ListenProvider.Value.Trim().ToLowerInvariant(); if (Array.IndexOf(Providers, text) < 0) { return "groq"; } return text; } } public static bool Enabled => Provider != "off"; public static ChatEndpoint Endpoint => Provider switch { "openai" => new ChatEndpoint("https://api.openai.com/v1", OrDefault(Plugin.ListenOpenAiModel.Value, OpenAiModels[0]), SecretStore.Get(KeyName("openai"))), "server" => new ChatEndpoint(Plugin.ListenServerUrl.Value.Trim(), Plugin.ListenServerModel.Value.Trim(), SecretStore.Get("listen-server")), "local" => new ChatEndpoint(Plugin.ListenLocalUrl.Value.Trim(), Plugin.ListenLocalModel.Value.Trim(), null), _ => new ChatEndpoint("https://api.groq.com/openai/v1", OrDefault(Plugin.ListenGroqModel.Value, GroqModels[0]), SecretStore.Get(KeyName("groq"))), }; public static bool IsConfigured { get { string provider = Provider; return provider switch { "off" => false, "server" => !string.IsNullOrWhiteSpace(Plugin.ListenServerUrl.Value), "local" => !string.IsNullOrWhiteSpace(Plugin.ListenLocalUrl.Value), _ => SecretStore.Has(KeyName(provider)), }; } } public static string? GameMicrophone { get { try { GameHandler instance = GameHandler.Instance; object obj; if (instance == null) { obj = null; } else { SettingsHandler settingsHandler = instance.SettingsHandler; obj = ((settingsHandler == null) ? null : settingsHandler.GetSetting<MicrophoneSetting>()?.Value.id); } string text = (string)obj; return string.IsNullOrWhiteSpace(text) ? null : text; } catch (Exception ex) { Plugin.Verbose("Could not read the game's microphone setting: " + ex.Message); return null; } } } public static bool IsOnline(string provider) { return Array.IndexOf(OnlineProviders, provider) >= 0; } public static string KeyName(string provider) { if (!(provider == "groq")) { if (provider == "openai") { return "openai"; } return "listen-server"; } return "groq"; } private static string OrDefault(string model, string fallback) { if (!string.IsNullOrWhiteSpace(model)) { return model.Trim(); } return fallback; } public static MicRecorder StartRecording() { return MicRecorder.Start(GameMicrophone, 30); } public static bool IsSilence(short[] samples) { float num = (float)samples.Length / 16000f; var (num2, num3) = MicRecorder.Loudness(samples); Plugin.Verbose($"Spoken question: {num:0.0} s, peak {num2:0.000}, level {num3:0.0000}."); if (!(num < 0.4f)) { return num2 < 0.01f; } return true; } public static async Task<string?> RecognizeAsync(short[] samples, CancellationToken cancel = default(CancellationToken)) { if (IsSilence(samples)) { return null; } ChatEndpoint endpoint = Endpoint; bool flag = SpeechLanguage.Current == Lang.Current; string text = await TranscriptionClient.TranscribeAsync(endpoint, Wav.Encode(samples, 16000), flag ? SpeechLanguage.Iso : null, flag ? Lang.Get("listen.prompt") : null, TimeSpan.FromSeconds(Math.Max(15, Plugin.TimeoutSeconds.Value)), cancel); Usage.Add(Usage.Listen(Provider), 0L, 0L, (double)samples.Length / 16000.0); Plugin.Verbose("Heard (" + endpoint.Model + "): " + text); return TranscriptionClient.IsPhantom(text) ? null : text; } } internal sealed class MicRecorder : IDisposable { private struct WaveHeader { public IntPtr lpData; public uint dwBufferLength; public uint dwBytesRecorded; public IntPtr dwUser; public uint dwFlags; public uint dwLoops; public IntPtr lpNext; public IntPtr reserved; } [StructLayout(LayoutKind.Sequential, Pack = 2)] private struct WaveFormat { public ushort wFormatTag; public ushort nChannels; public uint nSamplesPerSec; public uint nAvgBytesPerSec; public ushort nBlockAlign; public ushort wBitsPerSample; public ushort cbSize; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct WaveInCaps { public ushort wMid; public ushort wPid; public uint vDriverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szPname; public uint dwFormats; public ushort wChannels; public ushort wReserved1; } public const int SampleRate = 16000; private const uint WaveMapper = uint.MaxValue; private const uint WaveMapped = 4u; private const uint HeaderDone = 1u; private static readonly uint s_headerSize = (uint)Marshal.SizeOf<WaveHeader>(); private static readonly int s_flagsOffset = Marshal.OffsetOf<WaveHeader>("dwFlags").ToInt32(); private IntPtr _handle; private IntPtr _header; private IntPtr _data; private bool _prepared; private readonly int _bytes; private readonly DateTime _started; public string DeviceName { get; } public TimeSpan Elapsed => DateTime.UtcNow - _started; public bool IsFull { get { if (_header != IntPtr.Zero) { return (Marshal.ReadInt32(_header, s_flagsOffset) & 1) != 0; } return false; } } public static MicRecorder Start(string? preferredDevice, int maxSeconds) { if (waveInGetNumDevs() == 0) { throw new InvalidOperationException("Windows sees no microphone."); } string name; uint num = FindDevice(preferredDevice, out name); WaveFormat format = new WaveFormat { wFormatTag = 1, nChannels = 1, nSamplesPerSec = 16000u, nAvgBytesPerSec = 32000u, nBlockAlign = 2, wBitsPerSample = 16 }; Check(waveInOpen(out var handle, num, ref format, IntPtr.Zero, IntPtr.Zero, (num != uint.MaxValue) ? 4u : 0u), "open"); return new MicRecorder(handle, maxSeconds, name); } public static List<string> Devices() { List<string> list = new List<string>(); uint num = waveInGetNumDevs(); for (uint num2 = 0u; num2 < num; num2++) { if (waveInGetDevCaps((UIntPtr)num2, out var caps, (uint)Marshal.SizeOf<WaveInCaps>()) == 0) { list.Add(caps.szPname ?? ""); } } return list; } public static (float Peak, float Rms) Loudness(short[] samples) { if (samples.Length == 0) { return (Peak: 0f, Rms: 0f); } int num = 0; double num2 = 0.0; foreach (short num3 in samples) { int num4 = Math.Abs((int)num3); if (num4 > num) { num = num4; } num2 += (double)num3 * (double)num3; } return (Peak: (float)num / 32768f, Rms: (float)(Math.Sqrt(num2 / (double)samples.Length) / 32768.0)); } private MicRecorder(IntPtr handle, int maxSeconds, string deviceName) { _handle = handle; DeviceName = deviceName; _bytes = 32000 * Math.Max(1, maxSeconds); try { _data = Marshal.AllocHGlobal(_bytes); _header = Marshal.AllocHGlobal((int)s_headerSize); Marshal.StructureToPtr(new WaveHeader { lpData = _data, dwBufferLength = (uint)_bytes }, _header, fDeleteOld: false); Check(waveInPrepareHeader(_handle, _header, s_headerSize), "prepare"); _prepared = true; Check(waveInAddBuffer(_handle, _header, s_headerSize), "add buffer"); Check(waveInStart(_handle), "start"); _started = DateTime.UtcNow; } catch { Release(); throw; } } public short[] Stop() { if (_handle == IntPtr.Zero) { return Array.Empty<short>(); } waveInReset(_handle); int num = (int)Math.Min(Marshal.PtrToStructure<WaveHeader>(_header).dwBytesRecorded, (uint)_bytes); short[] array = new short[num / 2]; Marshal.Copy(_data, array, 0, array.Length); Release(); return array; } public void Dispose() { Release(); } private void Release() { if (_handle != IntPtr.Zero) { waveInReset(_handle); if (_prepared) { waveInUnprepareHeader(_handle, _header, s_headerSize); } waveInClose(_handle); _handle = IntPtr.Zero; } _prepared = false; if (_header != IntPtr.Zero) { Marshal.FreeHGlobal(_header); } if (_data != IntPtr.Zero) { Marshal.FreeHGlobal(_data); } _header = (_data = IntPtr.Zero); } private static uint FindDevice(string? preferred, out string name) { name = ""; if (string.IsNullOrWhiteSpace(preferred)) { return uint.MaxValue; } List<string> list = Devices(); for (int i = 0; i < list.Count; i++) { string text = list[i].Trim(); if (text.Length > 0 && (preferred.StartsWith(text, StringComparison.OrdinalIgnoreCase) || text.StartsWith(preferred.Trim(), StringComparison.OrdinalIgnoreCase))) { name = text; return (uint)i; } } return uint.MaxValue; } private static void Check(uint result, string step) { string text; switch (result) { case 0u: return; case 2u: text = "no such microphone"; break; case 4u: text = "the microphone is busy"; break; case 6u: text = "no driver for the microphone"; break; case 7u: text = "out of memory"; break; case 32u: text = "the microphone cannot record in 16 kHz mono"; break; default: text = "error " + result; break; } string text2 = text; throw new InvalidOperationException("Microphone " + step + ": " + text2 + "."); } [DllImport("winmm.dll")] private static extern uint waveInGetNumDevs(); [DllImport("winmm.dll", CharSet = CharSet.Unicode, EntryPoint = "waveInGetDevCapsW")] private static extern uint waveInGetDevCaps(UIntPtr deviceId, out WaveInCaps caps, uint size); [DllImport("winmm.dll")] private static extern uint waveInOpen(out IntPtr handle, uint deviceId, ref WaveFormat format, IntPtr callback, IntPtr instance, uint flags); [DllImport("winmm.dll")] private static extern uint waveInPrepareHeader(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveInUnprepareHeader(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveInAddBuffer(IntPtr handle, IntPtr header, uint size); [DllImport("winmm.dll")] private static extern uint waveInStart(IntPtr handle); [DllImport("winmm.dll")] private static extern uint waveInReset(IntPtr handle); [DllImport("winmm.dll")] private static extern uint waveInClose(IntPtr handle); } internal sealed class MicWatch : MonoBehaviour { private const float CheckSeconds = 5f; private float _next; private string _last = ""; private void Update() { if (Time.time < _next) { return; } _next = Time.time + 5f; try { string text = string.Join(" | ", Microphone.devices); string text2 = "game sees [" + text + "], uses '" + (ListenService.GameMicrophone ?? "(default)") + "'"; if (!(text2 == _last)) { _last = text2; Plugin.Log.LogInfo((object)("Microphones: " + text2 + "; Windows has [" + string.Join(" | ", MicRecorder.Devices()) + "].")); } } catch (Exception ex) { Plugin.Verbose("Could not list the microphones: " + ex.Message); } } } internal static class SpeechClient { public static async Task<VoiceAudio> SynthesizeAsync(ChatEndpoint endpoint, string voice, string text, string? instructions, TimeSpan timeout, CancellationToken cancel = default(CancellationToken), float speed = 1f) { JObject val = new JObject { ["model"] = JToken.op_Implicit(endpoint.Model), ["input"] = JToken.op_Implicit(text), ["voice"] = JToken.op_Implicit(voice), ["response_format"] = JToken.op_Implicit("wav") }; if (!string.IsNullOrWhiteSpace(instructions)) { val["instructions"] = JToken.op_Implicit(instructions); } if (Math.Abs(speed - 1f) > 0.01f) { val["speed"] = JToken.op_Implicit(Math.Round(speed, 2)); } byte[] data = await ChatClient.PostForBytesAsync(endpoint, "audio/speech", ((JToken)val).ToString((Formatting)0, Array.Empty<JsonConverter>()), timeout, cancel).ConfigureAwait(continueOnCapturedContext: false); try { return Wav.Parse(data); } catch (FormatException ex) { throw new ChatException(ChatErrorKind.BadResponse, "The speech server did not send a WAV file: " + ex.Message, ex); } } public static async Task<List<VoiceInfo>> ListVoicesAsync(ChatEndpoint endpoint, CancellationToken cancel = default(CancellationToken)) { string text = await ChatClient.GetStringAsync(endpoint, "audio/voices", TimeSpan.FromSeconds(10.0), cancel).ConfigureAwait(continueOnCapturedContext: false); JToken val; try { val = JToken.Parse(text); } catch (JsonException ex) { JsonException inner = ex; throw new ChatException(ChatErrorKind.BadResponse, "The voice list is not JSON.", (Exception?)(object)inner); } object obj = ((val is JArray) ? val : null); if (obj == null) { JToken obj2 = ((val is JObject) ? val : null); JToken obj3 = ((obj2 != null) ? ((JObject)obj2)["voices"] : null); obj = ((obj3 is JArray) ? obj3 : null); if (obj == null) { JToken obj4 = ((val is JObject) ? val : null); JToken obj5 = ((obj4 != null) ? ((JObject)obj4)["data"] : null); obj = ((object)((obj5 is JArray) ? obj5 : null)) ?? ((object)new JArray()); } } JArray val2 = (JArray)obj; List<VoiceInfo> list = new List<VoiceInfo>(); foreach (JToken item in val2) { string text2 = ((item is JValue) ? ((string)item) : (((string)item[(object)"id"]) ?? ((string)item[(object)"voice_id"]) ?? ((string)item[(object)"name"]))); if (!string.IsNullOrWhiteSpace(text2)) { JObject val3 = (JObject)(object)((item is JObject) ? item : null); string name = ((val3 != null) ? (((string)val3["name"]) ?? text2) : text2); JObject val4 = (JObject)(object)((item is JObject) ? item : null); string language = ((val4 != null) ? (((string)val4["language"]) ?? "") : ""); list.Add(new VoiceInfo(text2, name, language, "")); } } return list; } } internal static class TranscriptionClient { private static readonly HashSet<string> s_refused = new HashSet<string>(); private static readonly string[] s_phantoms = new string[10] { "субтитр", "dimatorzok", "продолжение следует", "подписывайтесь на канал", "спасибо за просмотр", "amara.org", "thanks for watching", "thank you for watching", "subtitles by", "please subscribe" }; public static async Task<string> TranscribeAsync(ChatEndpoint endpoint, byte[] wav, string? language, string? prompt, TimeSpan timeout, CancellationToken cancel = default(CancellationToken)) { if (endpoint.Model.StartsWith("gpt-transcribe", StringComparison.OrdinalIgnoreCase)) { language = null; } int attempt = 0; while (true) { bool sendLanguage = !string.IsNullOrWhiteSpace(language) && !Refused(endpoint, "language"); bool sendPrompt = !string.IsNullOrWhiteSpace(prompt) && !Refused(endpoint, "prompt"); MultipartFormDataContent form = new MultipartFormDataContent(); ByteArrayContent byteArrayContent = new ByteArrayContent(wav); byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("audio/wav"); Add(form, byteArrayContent, "file", "question.wav"); if (!string.IsNullOrWhiteSpace(endpoint.Model)) { Add(form, new StringContent(endpoint.Model), "model"); } Add(form, new StringContent("json"), "response_format"); if (sendLanguage) { Add(form, new StringContent(language), "language"); } if (sendPrompt) { Add(form, new StringContent(prompt), "prompt"); } try { return ReadText(await ChatClient.PostFormAsync(endpoint, "audio/transcriptio
plugins/BingBongHelper/BingBongHelper.exe
Decompiled 2 weeks 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.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Windows.Forms; using System.Windows.Forms.Layout; using Microsoft.CodeAnalysis; using Microsoft.Win32; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("BingBongHelper")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("BingBongHelper")] [assembly: AssemblyTitle("Bing Bong AI helpers")] [assembly: AssemblyVersion("0.1.0.0")] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } 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; } } } namespace BingBongHelper { internal static class Text { private static readonly Dictionary<string, Dictionary<string, string>> s_tables = new Dictionary<string, Dictionary<string, string>>(); private static string SystemLanguage { get { CultureInfo currentUICulture = CultureInfo.CurrentUICulture; if (currentUICulture.TwoLetterISOLanguageName == "ru") { return "ru"; } if (currentUICulture.TwoLetterISOLanguageName != "zh") { return "en"; } string name = currentUICulture.Name; if (!name.Contains("Hant") && !name.EndsWith("-TW") && !name.EndsWith("-HK") && !name.EndsWith("-MO")) { return "zh-hans"; } return "zh-hant"; } } public static string Language { get; private set; } = SystemLanguage; public static string FontName { get { string language = Language; if (!(language == "zh-hans")) { if (language == "zh-hant") { return "Microsoft JhengHei UI"; } return "Segoe UI"; } return "Microsoft YaHei UI"; } } public static void Use(string language) { bool flag; switch (language) { case "ru": case "en": case "zh-hans": case "zh-hant": flag = true; break; default: flag = false; break; } Language = (flag ? language : SystemLanguage); } public static string T(string russian, string english) { string language = Language; if (!(language == "ru")) { if (language == "en") { return english; } string value; return Table(Language).TryGetValue(english, out value) ? value : english; } return russian; } private static Dictionary<string, string> Table(string language) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (s_tables.TryGetValue(language, out Dictionary<string, string> value)) { return value; } value = new Dictionary<string, string>(StringComparer.Ordinal); try { using Stream stream = typeof(Text).Assembly.GetManifestResourceStream("Lang." + language + ".json"); if (stream != null) { using StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); value = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(streamReader.ReadToEnd()) ?? value; } } catch (Exception) { } s_tables[language] = value; return value; } } internal enum ServerState { Off, Starting, Running, External, Failed, Missing } internal abstract class LocalService { private readonly Func<string> _title; public string Name { get; } public string Title => _title(); public int Port { get; protected set; } public string LogPath { get; } public string Address => $"http://localhost:{Port}/v1"; public ServerState State { get; protected set; } public string Detail { get; protected set; } = ""; public abstract bool Owned { get; } public virtual bool StartsWithOthers => true; public double? LastSeconds { get; protected set; } public double? LastSpeechSeconds { get; protected set; } public DateTime? LastAt { get; protected set; } protected LocalService(string name, Func<string> title, int port, string logFile) { Name = name; _title = title; Port = port; LogPath = Path.Combine(Services.Logs, logFile); } public abstract void Start(); public abstract void Stop(); public abstract void Refresh(bool detailed, ISet<int> listening); public abstract (long Ram, long? Video) Memory(); protected static (long Ram, long? Video) MemoryOf(ICollection<int> ids) { long num = 0L; foreach (int id in ids) { try { using Process process = Process.GetProcessById(id); num += process.WorkingSet64; } catch (ArgumentException) { } } return (Ram: num, Video: (ids.Count > 0) ? GpuMemory.Dedicated(ids) : ((long?)null)); } } internal sealed class Launch { public ProcessStartInfo? Start { get; } public string Detail { get; } public int Port { get; } public Launch(ProcessStartInfo? start, string detail, int port) { Start = start; Detail = detail; Port = port; } } internal sealed class ProcessService : LocalService { private readonly Func<Launch> _prepare; private Process? _process; private JobObject? _job; private StreamWriter? _log; private bool _stopping; private string _lastLine = ""; private long _questionStarted; private double _questionSeconds; private static readonly Regex s_whisperStart = new Regex("processing '[^']*' \\(\\d+ samples, ([\\d.]+) sec\\)"); private static readonly Regex s_piperDone = new Regex(": \\d+ letters, ([\\d.]+) s of speech in ([\\d.]+) s"); public override bool Owned { get { if (_process != null) { return !_process.HasExited; } return false; } } public ProcessService(string name, Func<string> title, int port, string logFile, Func<Launch> prepare) : base(name, title, port, logFile) { _prepare = prepare; } public override void Start() { if (Owned || base.State == ServerState.External) { return; } Launch launch = _prepare(); base.Detail = launch.Detail; base.Port = launch.Port; ProcessStartInfo start = launch.Start; if (start == null) { base.State = ServerState.Missing; return; } start.UseShellExecute = false; start.CreateNoWindow = true; start.RedirectStandardOutput = true; start.RedirectStandardError = true; start.StandardOutputEncoding = Encoding.UTF8; start.StandardErrorEncoding = Encoding.UTF8; Directory.CreateDirectory(Path.GetDirectoryName(base.LogPath)); _log = new StreamWriter(base.LogPath, append: false, Encoding.UTF8) { AutoFlush = true }; _log.WriteLine($"[{DateTime.Now:HH:mm:ss}] {start.FileName} {start.Arguments}"); _stopping = false; _lastLine = ""; _process = new Process { StartInfo = start, EnableRaisingEvents = true }; _process.OutputDataReceived += delegate(object _, DataReceivedEventArgs e) { Write(e.Data); }; _process.ErrorDataReceived += delegate(object _, DataReceivedEventArgs e) { Write(e.Data); }; try { _process.Start(); } catch (Win32Exception ex) { Write(ex.Message); _process = null; base.State = ServerState.Missing; base.Detail = Text.T("не запускается: ", "does not start: ") + ex.Message; return; } _job = new JobObject(); _job.Add(_process); _process.BeginOutputReadLine(); _process.BeginErrorReadLine(); base.State = ServerState.Starting; } public override void Stop() { _stopping = true; try { _job?.Terminate(); if (Owned) { _process.WaitForExit(3000); } } catch (InvalidOperationException) { } _job?.Dispose(); _job = null; Write($"[{DateTime.Now:HH:mm:ss}] stopped"); _process = null; } public override void Refresh(bool detailed, ISet<int> ports) { if (base.State == ServerState.Missing && !Owned) { return; } bool flag = ports.Contains(base.Port); if (Owned) { base.State = ((!flag) ? ServerState.Starting : ServerState.Running); } else if (_process != null && !_stopping) { if (base.State != ServerState.Failed) { base.Detail = Explain(_lastLine); } base.State = ServerState.Failed; } else { base.State = (flag ? ServerState.External : ServerState.Off); } } private static string Explain(string line) { if (line.Contains("vc_redist")) { return Text.T("нужна библиотека Microsoft Visual C++ (x64): aka.ms/vs/17/release/vc_redist.x64.exe – установи и запусти снова", "it needs Microsoft Visual C++ (x64): aka.ms/vs/17/release/vc_redist.x64.exe; install it and start again"); } if (line.StartsWith("Cannot listen on", StringComparison.Ordinal) || line.Contains("10048")) { return Text.T("порт занят другой программой", "another program holds the port"); } if (line.Length <= 200) { return line; } return line.Substring(0, 200) + "…"; } public override (long Ram, long? Video) Memory() { return LocalService.MemoryOf(_job?.ProcessIds() ?? new List<int>()); } private void Write(string? line) { if (line == null) { return; } if (line.Trim().Length > 0 && !_stopping) { _lastLine = line.Trim(); } Measure(line); lock (this) { try { _log?.WriteLine(line); } catch (ObjectDisposedException) { } } } private void Measure(string line) { Match match = s_whisperStart.Match(line); if (match.Success) { _questionSeconds = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); _questionStarted = Stopwatch.GetTimestamp(); return; } if (_questionStarted != 0L && line.Contains("progress = 100%")) { base.LastSeconds = (double)(Stopwatch.GetTimestamp() - _questionStarted) / (double)Stopwatch.Frequency; base.LastSpeechSeconds = _questionSeconds; base.LastAt = DateTime.Now; _questionStarted = 0L; return; } Match match2 = s_piperDone.Match(line); if (match2.Success) { base.LastSpeechSeconds = double.Parse(match2.Groups[1].Value, CultureInfo.InvariantCulture); base.LastSeconds = double.Parse(match2.Groups[2].Value, CultureInfo.InvariantCulture); base.LastAt = DateTime.Now; } } } internal static class Ports { public static HashSet<int> Listening() { try { HashSet<int> hashSet = new HashSet<int>(); foreach (int item in from endpoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() select endpoint.Port) { hashSet.Add(item); } return hashSet; } catch (NetworkInformationException) { return new HashSet<int>(); } } } internal static class Services { private static readonly bool s_portable = File.Exists(Path.Combine(Root, "helper.ini")); public static string Root => AppDomain.CurrentDomain.BaseDirectory; public static string Data { get { if (!s_portable) { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BingBongAI", "helper"); } return Root; } } public static string SettingsPath => Path.Combine(Data, "helper.ini"); public static string Logs => Path.Combine(Data, "logs"); public static string VoiceExe => Path.Combine(Root, "BingBongVoice.exe"); public static string LocalWhisperServer => Path.Combine(Root, "whisper", "bin", "whisper-server.exe"); public static string LocalWhisperModels => Path.Combine(Root, "whisper", "models"); public static string LocalVoices => Path.Combine(Root, "piper", "voices"); public static string LocalPython => Path.Combine(Root, "piper", "venv", "Scripts", "python.exe"); public static string DefaultVoices => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BingBongAI", "voices"); public static string? OllamaPath { get { string text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Ollama", "ollama.exe"); if (!File.Exists(text)) { return null; } return text; } } public static List<(string Label, bool Complete)> PiperVoices(string folder) { if (!Directory.Exists(folder)) { return new List<(string, bool)>(); } return (from f in Directory.GetFiles(folder, "*.onnx") orderby f select f).Select(delegate(string file) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); string[] array = fileNameWithoutExtension.Split(new char[1] { '-' }); return ((array.Length == 3) ? (array[1] + " (" + array[0] + ", " + array[2] + ")") : fileNameWithoutExtension, File.Exists(file + ".json")); }).ToList(); } public static LocalService Whisper(HelperSettings settings) { return new ProcessService("whisper", () => Text.T("Распознавание речи (Whisper)", "Speech recognition (Whisper)"), 8080, "whisper.log", () => settings.CustomLaunch("whisper", 8080) ?? BuiltInWhisper(settings)); } public static LocalService Piper(HelperSettings settings) { return new ProcessService("piper", () => Text.T("Голос Бинг-Бонга (Piper)", "Bing Bong's voice (Piper)"), 8000, "piper.log", delegate { Launch launch = settings.CustomLaunch("piper", 8000); if (launch == null) { if (!(settings.VoiceEngine == "python")) { return BuiltInVoice(settings); } launch = PythonPiper(settings); } return launch; }); } public static LocalService? TextAi(HelperSettings settings) { return settings.LlmKind switch { "lmstudio" => new LmStudioService(settings), "ollama" => new ProcessService("ollama", () => Text.T("Текстовая нейросеть (Ollama)", "Text AI (Ollama)"), 11434, "ollama.log", Ollama), "custom" => new ProcessService("textai", () => Text.T("Текстовая нейросеть (своя программа)", "Text AI (own program)"), settings.Number("llm.port", 1234), "textai.log", () => settings.CustomLaunch("llm", 1234) ?? new Launch(null, Text.T("укажи программу в «Настройках»", "choose the program in Settings"), settings.Number("llm.port", 1234))), _ => null, }; } public static List<string> WhisperModels(string folder) { if (!Directory.Exists(folder)) { return new List<string>(); } return (from f in Directory.GetFiles(folder, "ggml-*.bin") orderby Path.GetFileName(f).Contains("large-v3-turbo") descending, f select f).ToList(); } private static Launch Missing(string what, int port) { return new Launch(null, what, port); } private static Launch BuiltInWhisper(HelperSettings settings) { string whisperServer = settings.WhisperServer; if (whisperServer.Length == 0) { return Missing(Text.T("укажи whisper-server.exe в «Настройках»", "choose whisper-server.exe in Settings"), 8080); } if (!File.Exists(whisperServer)) { return Missing(Text.T("не нашёл ", "not found: ") + whisperServer, 8080); } string whisperModelFile = settings.WhisperModelFile; if (whisperModelFile.Length == 0) { return Missing(Text.T("укажи модель (ggml-….bin) в «Настройках»", "choose a model (ggml-….bin) in Settings"), 8080); } if (!File.Exists(whisperModelFile)) { return Missing(Text.T("не нашёл модель ", "model not found: ") + whisperModelFile, 8080); } string directoryName = Path.GetDirectoryName(whisperServer); bool flag = settings.WhisperDevice != "cpu" && File.Exists(Path.Combine(directoryName, "cublas64_12.dll")); string arguments = "-m \"" + whisperModelFile + "\" --host 127.0.0.1 --port 8080 --inference-path /v1/audio/transcriptions -l auto -pp" + (flag ? "" : " -ng -t 12 -ac 768"); string text = Path.GetFileName(whisperModelFile).Replace("ggml-", "").Replace(".bin", ""); return new Launch(new ProcessStartInfo(whisperServer, arguments) { WorkingDirectory = directoryName }, (flag ? Text.T("видеокарта", "graphics card") : Text.T("процессор", "processor")) + " · " + text, 8080); } private static (string[] Voices, Launch? Missing) VoicesIn(string folder) { string[] array = (Directory.Exists(folder) ? (from f in Directory.GetFiles(folder, "*.onnx") where File.Exists(f + ".json") select f).ToArray() : Array.Empty<string>()); if (array.Length == 0) { return (Voices: Array.Empty<string>(), Missing: Missing(Text.T("в папке голосов пусто – добавь голос (в «Настройках»: «Голос»)", "the voices folder is empty: add a voice (Settings, Voice)"), 8000)); } return (Voices: array, Missing: null); } private static string VoiceNames(string[] onnx) { return Text.T("голоса: ", "voices: ") + string.Join(", ", onnx.Select((string f) => Path.GetFileNameWithoutExtension(f).Split(new char[1] { '-' }).ElementAtOrDefault(1) ?? Path.GetFileNameWithoutExtension(f))); } private static Launch BuiltInVoice(HelperSettings settings) { if (!File.Exists(VoiceExe)) { return Missing(Text.T("нет BingBongVoice.exe рядом с помощником – выбери в «Настройках» Piper через Python", "BingBongVoice.exe is not next to the helper: choose Piper through Python in Settings"), 8000); } string voicesFolder = settings.VoicesFolder; var (onnx, launch) = VoicesIn(voicesFolder); if (launch != null) { return launch; } return new Launch(new ProcessStartInfo(VoiceExe, "--voices \"" + voicesFolder.TrimEnd(new char[1] { '\\' }) + "\" --port 8000") { WorkingDirectory = Root }, VoiceNames(onnx), 8000); } private static Launch PythonPiper(HelperSettings settings) { string piperPython = settings.PiperPython; if (piperPython.Length == 0) { return Missing(Text.T("укажи python.exe (с piper-tts) в «Настройках»", "choose python.exe (with piper-tts) in Settings"), 8000); } if (!File.Exists(piperPython)) { return Missing(Text.T("не нашёл ", "not found: ") + piperPython, 8000); } string text = new string[3] { Path.Combine(Root, "piper_server.py"), Path.Combine(Root, "piper", "piper_server.py"), Path.GetFullPath(Path.Combine(Root, "..", "BingBongAI", "tools", "PiperServer", "piper_server.py")) }.FirstOrDefault(File.Exists); if (text == null) { return Missing(Text.T("нет piper_server.py рядом с помощником", "piper_server.py is not next to the helper"), 8000); } string voicesFolder = settings.VoicesFolder; var (onnx, launch) = VoicesIn(voicesFolder); if (launch != null) { return launch; } ProcessStartInfo processStartInfo = new ProcessStartInfo(piperPython, "-u \"" + text + "\" --voices \"" + voicesFolder.TrimEnd(new char[1] { '\\' }) + "\" --port 8000"); processStartInfo.WorkingDirectory = Path.GetDirectoryName(text); processStartInfo.EnvironmentVariables["PYTHONIOENCODING"] = "utf-8"; return new Launch(processStartInfo, "Python · " + VoiceNames(onnx), 8000); } private static Launch Ollama() { string ollamaPath = OllamaPath; if (ollamaPath == null) { return new Launch(null, Text.T("Ollama не установлен", "Ollama is not installed"), 11434); } ProcessStartInfo processStartInfo = new ProcessStartInfo(ollamaPath, "serve"); processStartInfo.EnvironmentVariables["OLLAMA_HOST"] = "127.0.0.1:11434"; return new Launch(processStartInfo, Text.T("модель загрузится с первым вопросом", "the model loads with the first question"), 11434); } } internal sealed class JobObject : IDisposable { private struct JOBOBJECT_BASIC_LIMIT_INFORMATION { public long PerProcessUserTimeLimit; public long PerJobUserTimeLimit; public uint LimitFlags; public UIntPtr MinimumWorkingSetSize; public UIntPtr MaximumWorkingSetSize; public uint ActiveProcessLimit; public UIntPtr Affinity; public uint PriorityClass; public uint SchedulingClass; } private struct IO_COUNTERS { public ulong ReadOperationCount; public ulong WriteOperationCount; public ulong OtherOperationCount; public ulong ReadTransferCount; public ulong WriteTransferCount; public ulong OtherTransferCount; } private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; public IO_COUNTERS IoInfo; public UIntPtr ProcessMemoryLimit; public UIntPtr JobMemoryLimit; public UIntPtr PeakProcessMemoryUsed; public UIntPtr PeakJobMemoryUsed; } private IntPtr _handle; public JobObject() { _handle = CreateJobObject(IntPtr.Zero, null); JOBOBJECT_EXTENDED_LIMIT_INFORMATION structure = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION { BasicLimitInformation = { LimitFlags = 8192u } }; int num = Marshal.SizeOf(structure); IntPtr intPtr = Marshal.AllocHGlobal(num); try { Marshal.StructureToPtr(structure, intPtr, fDeleteOld: false); SetInformationJobObject(_handle, 9, intPtr, (uint)num); } finally { Marshal.FreeHGlobal(intPtr); } } public void Add(Process process) { if (_handle != IntPtr.Zero) { AssignProcessToJobObject(_handle, process.Handle); } } public List<int> ProcessIds() { List<int> list = new List<int>(); if (_handle == IntPtr.Zero) { return list; } int num = 8 + 64 * IntPtr.Size; IntPtr intPtr = Marshal.AllocHGlobal(num); try { if (QueryInformationJobObject(_handle, 3, intPtr, (uint)num, IntPtr.Zero)) { int val = Marshal.ReadInt32(intPtr, 4); for (int i = 0; i < Math.Min(val, 64); i++) { list.Add((int)Marshal.ReadIntPtr(intPtr, 8 + i * IntPtr.Size).ToInt64()); } } } finally { Marshal.FreeHGlobal(intPtr); } return list; } public void Terminate() { if (_handle != IntPtr.Zero) { TerminateJobObject(_handle, 1u); } } public void Dispose() { if (_handle != IntPtr.Zero) { CloseHandle(_handle); } _handle = IntPtr.Zero; } [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CreateJobObject(IntPtr attributes, string? name); [DllImport("kernel32.dll")] private static extern bool SetInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint length); [DllImport("kernel32.dll")] private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); [DllImport("kernel32.dll")] private static extern bool TerminateJobObject(IntPtr job, uint exitCode); [DllImport("kernel32.dll")] private static extern bool QueryInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint length, IntPtr returnLength); [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle); } internal static class GpuMemory { private static bool? s_available; public static long? Dedicated(ICollection<int> processIds) { //IL_004d: 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_0095: Expected O, but got Unknown try { bool valueOrDefault = s_available == true; if (!s_available.HasValue) { valueOrDefault = PerformanceCounterCategory.Exists("GPU Process Memory"); s_available = valueOrDefault; } if (s_available != true) { return null; } InstanceDataCollection val = new PerformanceCounterCategory("GPU Process Memory").ReadCategory()["Dedicated Usage"]; if (val == null) { return null; } long num = 0L; foreach (InstanceData value in val.Values) { InstanceData val2 = value; string instanceName = val2.InstanceName; int num2 = instanceName.IndexOf('_', 4); if (instanceName.StartsWith("pid_", StringComparison.Ordinal) && num2 > 4 && int.TryParse(instanceName.Substring(4, num2 - 4), out var result) && processIds.Contains(result)) { num += val2.RawValue; } } return num; } catch (Exception ex) when (((ex is InvalidOperationException || ex is UnauthorizedAccessException || ex is Win32Exception) ? 1 : 0) != 0) { return null; } } } internal static class Program { [STAThread] private static int Main(string[] args) { //IL_0095: Unknown result type (might be due to invalid IL or missing references) HelperSettings helperSettings = new HelperSettings(Services.SettingsPath); Text.Use(helperSettings.Language); Theme.Use(helperSettings.Theme); if (args.Contains("--check")) { return Check(helperSettings); } if (args.Contains("--check-lms")) { return CheckLmStudio(helperSettings); } int num = Array.IndexOf(args, "--screenshot"); if (num >= 0 && num + 1 < args.Length) { return Screenshots(helperSettings, args[num + 1]); } bool createdNew; using (new Mutex(initiallyOwned: true, "BingBongAI.LocalHelper", out createdNew)) { if (!createdNew) { MessageBox.Show(Text.T("Помощник уже открыт: он в трее возле часов.", "The helper is already open: it is in the tray next to the clock."), "Bing Bong AI", (MessageBoxButtons)0, (MessageBoxIcon)64); return 0; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run((Form)(object)new HelperForm(helperSettings)); return 0; } } private static int Check(HelperSettings settings) { StringBuilder stringBuilder = new StringBuilder(); bool flag = true; LocalService[] array = new LocalService[2] { Services.Whisper(settings), Services.Piper(settings) }; Directory.CreateDirectory(Services.Logs); string path = Path.Combine(Services.Logs, "check-ready.txt"); File.Delete(path); Stopwatch stopwatch = Stopwatch.StartNew(); LocalService[] array2 = array; for (int i = 0; i < array2.Length; i++) { array2[i].Start(); } do { Thread.Sleep(250); HashSet<int> listening = Ports.Listening(); array2 = array; for (int i = 0; i < array2.Length; i++) { array2[i].Refresh(detailed: true, listening); } } while (array.Any((LocalService s) => s.State == ServerState.Starting) && stopwatch.Elapsed.TotalSeconds < 30.0); array2 = array; foreach (LocalService localService in array2) { flag &= localService.State == ServerState.Running; stringBuilder.AppendLine($"{localService.Name}: {localService.State} after {stopwatch.Elapsed.TotalSeconds:0.0} s ({localService.Detail})"); } File.WriteAllText(path, "ready"); Stopwatch stopwatch2 = Stopwatch.StartNew(); while (array.Any((LocalService s) => !s.LastSeconds.HasValue) && stopwatch2.Elapsed.TotalSeconds < 60.0) { Thread.Sleep(250); } array2 = array; foreach (LocalService localService2 in array2) { (long Ram, long? Video) tuple = localService2.Memory(); long item = tuple.Ram; long? item2 = tuple.Video; double? lastSeconds = localService2.LastSeconds; object obj; if (lastSeconds.HasValue) { double valueOrDefault = lastSeconds.GetValueOrDefault(); obj = $"last request {valueOrDefault:0.00} s for {localService2.LastSpeechSeconds:0.0} s of speech"; } else { obj = "no request came"; } string text = (string)obj; object[] obj2 = new object[4] { localService2.Name, item >> 20, null, null }; object obj3; if (item2.HasValue) { long valueOrDefault2 = item2.GetValueOrDefault(); obj3 = (valueOrDefault2 >> 20) + " MB"; } else { obj3 = "unknown"; } obj2[2] = obj3; obj2[3] = text; stringBuilder.AppendLine(string.Format("{0}: {1} MB RAM, {2} video memory; {3}", obj2)); } array2 = array; for (int i = 0; i < array2.Length; i++) { array2[i].Stop(); } Thread.Sleep(500); HashSet<int> listening2 = Ports.Listening(); array2 = array; foreach (LocalService localService3 in array2) { localService3.Refresh(detailed: false, listening2); bool flag2 = localService3.State == ServerState.Off; flag = flag && flag2; stringBuilder.AppendLine(string.Format("{0}: after Stop {1} {2}", localService3.Name, localService3.State, flag2 ? "ok" : "FAIL")); } File.Delete(path); File.WriteAllText(Path.Combine(Services.Logs, "check.txt"), stringBuilder.ToString()); return (!flag) ? 1 : 0; } private static int CheckLmStudio(HelperSettings settings) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("lms: " + (LmStudioCli.Path ?? "not found")); List<LmModel> list = LmStudioCli.ListModels(); stringBuilder.AppendLine("models: " + string.Join(" | ", list.Select((LmModel m) => m.Key + " = " + m.Label))); if (list.Count > 0) { stringBuilder.AppendLine($"estimate {list[0].Key} @ {settings.LlmContext}: {LmStudioCli.EstimateGpuGb(list[0].Key, settings.LlmContext, settings.LlmGpu)} GiB"); } stringBuilder.AppendLine("server start: " + LmStudioCli.Run("server start --port 1234", 60).Output.Trim()); LmStudioService lmStudioService = new LmStudioService(settings); lmStudioService.Refresh(detailed: true, Ports.Listening()); stringBuilder.AppendLine($"service: {lmStudioService.State} · {lmStudioService.Detail}"); Stopwatch stopwatch = Stopwatch.StartNew(); lmStudioService.Memory(); long elapsedMilliseconds = stopwatch.ElapsedMilliseconds; stopwatch.Restart(); (long Ram, long? Video) tuple = lmStudioService.Memory(); long item = tuple.Ram; long? item2 = tuple.Video; object[] obj = new object[4] { item >> 20, null, null, null }; object obj2; if (item2.HasValue) { long valueOrDefault = item2.GetValueOrDefault(); obj2 = (valueOrDefault >> 20) + " MB"; } else { obj2 = "unknown"; } obj[1] = obj2; obj[2] = elapsedMilliseconds; obj[3] = stopwatch.ElapsedMilliseconds; stringBuilder.AppendLine(string.Format("LM Studio memory: {0} MB RAM, {1} video (first {2} ms, then {3} ms)", obj)); stringBuilder.AppendLine("server stop: " + LmStudioCli.Run("server stop", 30).Output.Trim()); File.WriteAllText(Path.Combine(Services.Logs, "check-lms.txt"), stringBuilder.ToString()); return 0; } private static int Screenshots(HelperSettings settings, string folder) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown Directory.CreateDirectory(folder); Application.SetUnhandledExceptionMode((UnhandledExceptionMode)2); Application.ThreadException += delegate(object _, ThreadExceptionEventArgs e) { File.AppendAllText(Path.Combine(folder, "errors.txt"), e.Exception?.ToString() + Environment.NewLine); }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); WindowsFormsSynchronizationContext.AutoInstall = false; SynchronizationContext.SetSynchronizationContext((SynchronizationContext?)new WindowsFormsSynchronizationContext()); string[] array = new string[2] { "light", "dark" }; foreach (string text in array) { Theme.Use(text); HelperForm helperForm = new HelperForm(settings, autostart: false); ((Form)helperForm).StartPosition = (FormStartPosition)0; ((Form)helperForm).Location = new Point(-6000, -6000); ((Form)helperForm).ShowInTaskbar = false; HelperForm helperForm2 = helperForm; try { ((Control)helperForm2).Show(); Application.DoEvents(); Save((Form)(object)helperForm2, Path.Combine(folder, "main-" + text + ".png")); SettingsForm settingsForm = new SettingsForm(settings, ((Form)helperForm2).Icon); ((Form)settingsForm).StartPosition = (FormStartPosition)0; ((Form)settingsForm).Location = new Point(-6000, -6000); ((Form)settingsForm).ShowInTaskbar = false; SettingsForm settingsForm2 = settingsForm; try { ((Control)settingsForm2).Show(); Application.DoEvents(); Thread.Sleep(2500); Application.DoEvents(); for (int num2 = 0; num2 < settingsForm2.TabCount; num2++) { settingsForm2.ShowTab(num2); Application.DoEvents(); Save((Form)(object)settingsForm2, Path.Combine(folder, $"settings-{text}-{num2}.png")); } ((Form)settingsForm2).Close(); LogWindow logWindow = new LogWindow(new <>z__ReadOnlyArray<LocalService>(new LocalService[2] { Services.Whisper(settings), Services.Piper(settings) }), ((Form)helperForm2).Icon); ((Form)logWindow).StartPosition = (FormStartPosition)0; ((Form)logWindow).Location = new Point(-6000, -6000); ((Form)logWindow).ShowInTaskbar = false; LogWindow logWindow2 = logWindow; try { ((Control)logWindow2).Show(); Application.DoEvents(); Save((Form)(object)logWindow2, Path.Combine(folder, "logs-" + text + ".png")); ((Form)logWindow2).Close(); ((Form)helperForm2).Close(); } finally { ((IDisposable)(object)logWindow2)?.Dispose(); } } finally { ((IDisposable)(object)settingsForm2)?.Dispose(); } } finally { ((IDisposable)(object)helperForm2)?.Dispose(); } } return 0; static void Save(Form form, string path) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown Bitmap val = new Bitmap(((Control)form).Width, ((Control)form).Height); try { ((Control)form).DrawToBitmap(val, new Rectangle(0, 0, ((Control)form).Width, ((Control)form).Height)); ((Image)val).Save(path, ImageFormat.Png); } finally { ((IDisposable)val)?.Dispose(); } } } } internal sealed class HelperForm : Form { private readonly HelperSettings _settings; private readonly List<LocalService> _services = new List<LocalService>(); private readonly NotifyIcon _tray; private readonly Timer _timer; private readonly Icon _icon; private Label[] _dots = Array.Empty<Label>(); private Label[] _states = Array.Empty<Label>(); private Button[] _buttons = Array.Empty<Button>(); private (long Ram, long? Video)?[] _memory = Array.Empty<(long, long?)?>(); private int _ticks; private bool _refreshing; private bool _restartNote; private LogWindow? _logs; private readonly bool _autostart; public HelperForm(HelperSettings settings, bool autostart = true) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Expected O, but got Unknown _settings = settings; _autostart = autostart; _icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); ((Form)this).Icon = _icon; ((Control)this).Font = new Font(Text.FontName, 10f); ((Form)this).FormBorderStyle = (FormBorderStyle)1; ((Form)this).MaximizeBox = false; ((Form)this).StartPosition = (FormStartPosition)1; ((Control)this).AutoSize = true; ((Form)this).AutoSizeMode = (AutoSizeMode)0; ((Control)this).Padding = new Padding(14); _services.Add(Services.Whisper(settings)); _services.Add(Services.Piper(settings)); LocalService localService = Services.TextAi(settings); if (localService != null) { _services.Add(localService); } _tray = new NotifyIcon { Icon = _icon, Text = "Bing Bong AI", Visible = true }; _tray.DoubleClick += delegate { ShowFromTray(); }; BuildUi(); _timer = new Timer { Interval = 1000 }; _timer.Tick += delegate { RefreshAll(); }; ((Control)this).DoubleBuffered = true; _timer.Start(); } protected override void OnShown(EventArgs e) { ((Form)this).OnShown(e); if (_autostart && _settings.AutoStart) { foreach (LocalService item in _services.Where((LocalService s) => s.StartsWithOthers)) { item.Start(); } } RefreshAll(); } protected override void OnResize(EventArgs e) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 ((Form)this).OnResize(e); if ((int)((Form)this).WindowState == 1) { ((Control)this).Hide(); } } protected override void OnFormClosing(FormClosingEventArgs e) { _timer.Stop(); ((Control)this).Cursor = Cursors.WaitCursor; StopAll(); _tray.Visible = false; ((Component)(object)_tray).Dispose(); ((Form)this).OnFormClosing(e); } private void BuildUi() { //IL_003d: 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) //IL_0049: 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_0058: Expected O, but got Unknown //IL_0064: 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) //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_0087: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Expected O, but got Unknown //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Expected O, but got Unknown //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Expected O, but got Unknown //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0186: 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_0194: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Expected O, but got Unknown //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Expected O, but got Unknown //IL_01ed: Expected O, but got Unknown //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Expected O, but got Unknown //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Expected O, but got Unknown //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_03e6: Unknown result type (might be due to invalid IL or missing references) //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_0402: Unknown result type (might be due to invalid IL or missing references) //IL_0413: Unknown result type (might be due to invalid IL or missing references) //IL_0418: Unknown result type (might be due to invalid IL or missing references) //IL_0427: Expected O, but got Unknown //IL_048b: Unknown result type (might be due to invalid IL or missing references) //IL_0490: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) //IL_049f: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Expected O, but got Unknown //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_04c7: Expected O, but got Unknown //IL_0549: Unknown result type (might be due to invalid IL or missing references) //IL_0553: Expected O, but got Unknown ((Control)this).SuspendLayout(); ((Control)this).Controls.Clear(); ((Control)this).Text = "Bing Bong AI – " + Text.T("помощники на ПК", "local helpers"); TableLayoutPanel val = new TableLayoutPanel { AutoSize = true, ColumnCount = 1, Dock = (DockStyle)5 }; ((Control)this).Controls.Add((Control)(object)val); TableLayoutPanel val2 = new TableLayoutPanel { AutoSize = true, ColumnCount = 3, Margin = new Padding(0, 0, 0, 8) }; val2.ColumnStyles.Add(new ColumnStyle((SizeType)0)); val2.ColumnStyles.Add(new ColumnStyle((SizeType)1, 470f)); val2.ColumnStyles.Add(new ColumnStyle((SizeType)0)); ((ControlCollection)val.Controls).Add((Control)(object)val2); int count = _services.Count; _dots = (Label[])(object)new Label[count]; _states = (Label[])(object)new Label[count]; _buttons = (Button[])(object)new Button[count]; _memory = new(long, long?)?[count]; for (int i = 0; i < count; i++) { int index = i; _dots[i] = new Label { Text = "●", AutoSize = true, Font = new Font(Text.FontName, 18f), Margin = new Padding(0, 4, 6, 10), Tag = "keep" }; FlowLayoutPanel val3 = new FlowLayoutPanel { FlowDirection = (FlowDirection)1, AutoSize = true, WrapContents = false, Margin = new Padding(0, 6, 10, 10) }; ((Control)val3).Controls.Add((Control)new Label { Text = _services[i].Title, AutoSize = true, Font = new Font(Text.FontName, 11f, (FontStyle)1) }); _states[i] = new Label { AutoSize = true, MaximumSize = new Size(470, 0), Tag = "soft" }; ((Control)val3).Controls.Add((Control)(object)_states[i]); _buttons[i] = MakeButton("", 120, delegate { Toggle(index); }); ((Control)_buttons[i]).Margin = new Padding(0, 10, 0, 10); val2.Controls.Add((Control)(object)_dots[i], 0, i); val2.Controls.Add((Control)(object)val3, 1, i); val2.Controls.Add((Control)(object)_buttons[i], 2, i); } FlowLayoutPanel val4 = new FlowLayoutPanel { AutoSize = true, WrapContents = false, Margin = new Padding(0, 0, 0, 6) }; ((Control)val4).Controls.Add((Control)(object)MakeButton(Text.T("Запустить всё", "Start all"), 130, StartAll)); ((Control)val4).Controls.Add((Control)(object)MakeButton(Text.T("Остановить всё", "Stop all"), 140, StopAllInBackground)); ((Control)val4).Controls.Add((Control)(object)MakeButton(Text.T("Журналы", "Logs"), 105, OpenLogs)); ((Control)val4).Controls.Add((Control)(object)MakeButton(Text.T("Настройки", "Settings"), 115, OpenSettings)); ((Control)val4).Controls.Add((Control)(object)MakeButton(Text.T("Ярлык на рабочий стол", "Desktop shortcut"), 190, MakeShortcut)); ((ControlCollection)val.Controls).Add((Control)(object)val4); CheckBox autoStart = new CheckBox { Text = Text.T("Запускать всё сразу при открытии", "Start everything when opened"), AutoSize = true, Checked = _settings.AutoStart, Margin = new Padding(3, 4, 0, 6) }; autoStart.CheckedChanged += delegate { _settings.Set("autostart", autoStart.Checked); _settings.Save(); }; ((ControlCollection)val.Controls).Add((Control)(object)autoStart); string text = Text.T("Свернёшь окно – оно спрячется в трей возле часов. Закроешь – помощники, запущенные отсюда, выключатся.", "Minimise the window and it waits in the tray next to the clock. Close it and the helpers started here stop."); if (_restartNote) { text = text + "\n" + Text.T("Новые настройки программ применятся, когда помощник запустится заново («Остановить» → «Запустить»).", "New program settings apply when a helper starts again (Stop, then Start)."); } ((ControlCollection)val.Controls).Add((Control)new Label { Text = text, AutoSize = true, MaximumSize = new Size(700, 0), Tag = "soft" }); ContextMenuStrip val5 = new ContextMenuStrip(); ((ToolStrip)val5).Items.Add(Text.T("Открыть", "Open"), (Image)null, (EventHandler)delegate { ShowFromTray(); }); ((ToolStrip)val5).Items.Add(Text.T("Запустить всё", "Start all"), (Image)null, (EventHandler)delegate { StartAll(); }); ((ToolStrip)val5).Items.Add(Text.T("Остановить всё", "Stop all"), (Image)null, (EventHandler)delegate { StopAllInBackground(); }); ((ToolStrip)val5).Items.Add((ToolStripItem)new ToolStripSeparator()); ((ToolStrip)val5).Items.Add(Text.T("Выход", "Exit"), (Image)null, (EventHandler)delegate { ((Form)this).Close(); }); ((Component)(object)_tray.ContextMenuStrip)?.Dispose(); _tray.ContextMenuStrip = val5; Theme.Apply((Form)(object)this); ((Control)this).ResumeLayout(); _ticks = 0; RefreshAll(); } private Button MakeButton(string text, int width, Action click) { //IL_000d: 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_0019: 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_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown Button val = new Button { Text = text, AutoSize = true, AutoSizeMode = (AutoSizeMode)1, MinimumSize = new Size(width, 34), Padding = new Padding(6, 0, 6, 0), Margin = new Padding(0, 0, 8, 0) }; ((Control)val).Click += delegate { click(); }; return val; } private async void Toggle(int index) { LocalService localService = _services[index]; Button button = _buttons[index]; ((Control)button).Enabled = false; if (localService.Owned) { await Task.Run((Action)localService.Stop); } else { localService.Start(); } if (!((Control)button).IsDisposed) { ((Control)button).Enabled = true; } RefreshAll(); } private void StartAll() { foreach (LocalService service in _services) { service.Start(); } RefreshAll(); } private void StopAll() { foreach (LocalService item in _services.Where((LocalService s) => s.Owned)) { item.Stop(); } if (!((Control)this).IsDisposed) { RefreshAll(); } } private async void StopAllInBackground() { List<LocalService> running = _services.Where((LocalService s) => s.Owned).ToList(); await Task.Run(delegate { running.ForEach(delegate(LocalService s) { s.Stop(); }); }); RefreshAll(); } private async void RefreshAll() { if (_refreshing || ((Control)this).IsDisposed) { return; } _refreshing = true; LocalService[] services = _services.ToArray(); bool open = ((Control)this).Visible && (int)((Form)this).WindowState != 1; bool readMemory = open && _ticks++ % 3 == 0; (long, long?)?[] array = await Task.Run(delegate { HashSet<int> listening = Ports.Listening(); (long, long?)?[] array2 = new(long, long?)?[services.Length]; for (int i = 0; i < services.Length; i++) { services[i].Refresh(open, listening); if (readMemory && (services[i].Owned || (services[i].State == ServerState.External && services[i] is LmStudioService))) { array2[i] = services[i].Memory(); } } return array2; }); _refreshing = false; if (((Control)this).IsDisposed || _states.Length != services.Length || !services.SequenceEqual(_services)) { return; } for (int num = 0; num < services.Length; num++) { if (readMemory) { _memory[num] = array[num]; } if (!services[num].Owned && services[num].State != ServerState.External) { _memory[num] = null; } } ShowStates(); } private void ShowStates() { for (int i = 0; i < _services.Count; i++) { LocalService localService = _services[i]; var (color, text) = localService.State switch { ServerState.Running => (Color.FromArgb(46, 160, 67), Text.T("работает", "running") + ((localService.Detail.Length > 0) ? (" · " + localService.Detail) : "") + "\n" + Text.T("адрес в моде: ", "address in the mod: ") + localService.Address + MemoryLine(_memory[i]) + LastLine(localService)), ServerState.Starting => (Theme.Current.Accent, Text.T("запускается…", "starting…") + ((localService.Detail.Length > 0) ? (" " + localService.Detail) : "")), ServerState.External => (Color.FromArgb(60, 110, 200), Text.T("уже работает (запущен не отсюда)", "already running (started elsewhere)") + ((localService.Detail.Length > 0) ? (" · " + localService.Detail) : "") + "\n" + localService.Address + MemoryLine(_memory[i])), ServerState.Failed => (Color.FromArgb(190, 40, 30), Text.T("остановился с ошибкой – открой «Журналы»", "stopped with an error: see Logs") + ((localService.Detail.Length > 0) ? ("\n" + localService.Detail) : "")), ServerState.Missing => (Color.FromArgb(190, 40, 30), Text.T("не настроен: ", "not set up: ") + localService.Detail), _ => (Color.FromArgb(160, 150, 140), Text.T("выключен", "off")), }; if (((Control)_dots[i]).ForeColor != color) { ((Control)_dots[i]).ForeColor = color; } if (((Control)_states[i]).Text != text) { ((Control)_states[i]).Text = text; } string text2 = (localService.Owned ? Text.T("Остановить", "Stop") : Text.T("Запустить", "Start")); if (((Control)_buttons[i]).Text != text2) { ((Control)_buttons[i]).Text = text2; } if (localService.State == ServerState.External) { ((Control)_buttons[i]).Enabled = false; } else if (!((Control)_buttons[i]).Enabled && localService.State != ServerState.Starting) { ((Control)_buttons[i]).Enabled = true; } } string text3 = "Bing Bong AI: " + string.Join(" ", _services.Select((LocalService s) => ShortName(s) + " " + Mark(s))); _tray.Text = ((text3.Length > 63) ? text3.Substring(0, 63) : text3); static string Mark(LocalService s) { ServerState state = s.State; if ((uint)(state - 2) > 1u) { if (s.State != ServerState.Starting) { return "–"; } return "…"; } return "✓"; } } private static string ShortName(LocalService service) { string name = service.Name; if (!(name == "whisper")) { if (name == "piper") { return "Piper"; } return "LLM"; } return "Whisper"; } private static string MemoryLine((long Ram, long? Video)? memory) { if (!memory.HasValue) { return ""; } (long Ram, long? Video) value = memory.Value; long item = value.Ram; long? item2 = value.Video; string text = "\n" + Text.T("память: ОЗУ ", "memory: RAM ") + FormatSize(item); if (item2 > 0) { text = text + Text.T(" · видеопамять ", " · video memory ") + FormatSize(item2.Value); } return text; } private static string LastLine(LocalService service) { bool flag = !(service is ProcessService); if (!flag) { string name = service.Name; bool flag2 = ((name == "whisper" || name == "piper") ? true : false); flag = !flag2; } if (flag) { return ""; } double? lastSeconds = service.LastSeconds; if (lastSeconds.HasValue) { double valueOrDefault = lastSeconds.GetValueOrDefault(); DateTime? lastAt = service.LastAt; if (lastAt.HasValue) { DateTime valueOrDefault2 = lastAt.GetValueOrDefault(); string arg = ((service.Name == "whisper") ? Text.T("последний вопрос", "last question") : Text.T("последняя фраза", "last phrase")); lastSeconds = service.LastSpeechSeconds; object obj; if (lastSeconds.HasValue) { double valueOrDefault3 = lastSeconds.GetValueOrDefault(); obj = $"{valueOrDefault3:0.0} " + Text.T("с речи, ", "s of speech, "); } else { obj = ""; } string text = (string)obj; return $"\n{arg}: {valueOrDefault:0.00} " + Text.T("с", "s") + " (" + text + Text.T("в ", "at ") + $"{valueOrDefault2:HH:mm})"; } } return "\n" + Text.T("запросов ещё не было", "no requests yet"); } private static string FormatSize(long bytes) { if (bytes < 1073741824) { return $"{bytes >> 20} " + Text.T("МБ", "MB"); } return $"{(double)bytes / 1073741824.0:0.0} " + Text.T("ГБ", "GB"); } private void ShowFromTray() { ((Control)this).Show(); ((Form)this).WindowState = (FormWindowState)0; ((Form)this).Activate(); _ticks = 0; RefreshAll(); } private void OpenLogs() { if (_logs != null && !((Control)_logs).IsDisposed) { ((Form)_logs).Activate(); return; } _logs = new LogWindow(_services, _icon); ((Form)_logs).Show((IWin32Window)(object)this); } private void OpenSettings() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown SettingsForm settingsForm = new SettingsForm(_settings, _icon); try { if ((int)((Form)settingsForm).ShowDialog((IWin32Window)(object)this) == 1) { Text.Use(_settings.Language); ((Control)this).Font = new Font(Text.FontName, 10f); Theme.Use(_settings.Theme); _restartNote = _services.Any((LocalService s) => s.Owned); ReplaceTextAi(); if (_logs != null && !((Control)_logs).IsDisposed) { ((Form)_logs).Close(); } BuildUi(); } } finally { ((IDisposable)(object)settingsForm)?.Dispose(); } } private void ReplaceTextAi() { LocalService localService = _services.FirstOrDefault(delegate(LocalService s) { switch (s.Name) { case "lmstudio": case "ollama": case "textai": return true; default: return false; } }); if (localService == null || !localService.Owned) { if (localService != null) { _services.Remove(localService); } LocalService localService2 = Services.TextAi(_settings); if (localService2 != null) { _services.Add(localService2); } } } private void MakeShortcut() { //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Unknown result type (might be due to invalid IL or missing references) try { string text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Text.T("Бинг-Бонг помощники", "Bing Bong helpers") + ".lnk"); dynamic val = Activator.CreateInstance(Type.GetTypeFromProgID("WScript.Shell")); dynamic val2 = val.CreateShortcut(text); val2.TargetPath = Application.ExecutablePath; val2.WorkingDirectory = Services.Root; val2.IconLocation = Application.ExecutablePath + ",0"; val2.Description = "Bing Bong AI: Whisper + Piper"; val2.Save(); MessageBox.Show(Text.T("Ярлык «Бинг-Бонг помощники» на рабочем столе.", "The \"Bing Bong helpers\" shortcut is on the desktop."), "Bing Bong AI", (MessageBoxButtons)0, (MessageBoxIcon)64); } catch (Exception ex) { MessageBox.Show(Text.T("Не получилось создать ярлык: ", "Could not create the shortcut: ") + ex.Message, "Bing Bong AI", (MessageBoxButtons)0, (MessageBoxIcon)48); } } } internal sealed class HelperSettings { private readonly string _path; private readonly Dictionary<string, string> _values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public bool AutoStart => Flag("autostart", fallback: true); public string Theme => Get("theme", "system"); public string Language => Get("language", "system"); public string WhisperServer => Get("whisper.server", File.Exists(Services.LocalWhisperServer) ? Services.LocalWhisperServer : ""); public string WhisperModelFile { get { string text = Get("whisper.modelfile"); if (text.Length > 0) { return text; } List<string> list = Services.WhisperModels(Services.LocalWhisperModels); string text2 = Path.Combine(Services.LocalWhisperModels, Get("whisper.model")); string text3; if (!list.Contains(text2)) { text3 = list.FirstOrDefault(); if (text3 == null) { return ""; } } else { text3 = text2; } return text3; } } public string WhisperDevice => Get("whisper.device", "auto"); public string VoiceEngine => Get("piper.engine", (File.Exists(Services.VoiceExe) || !File.Exists(Services.LocalPython)) ? "builtin" : "python"); public string VoicesFolder => Get("piper.voices", Directory.Exists(Services.LocalVoices) ? Services.LocalVoices : Services.DefaultVoices); public string PiperPython => Get("piper.python", File.Exists(Services.LocalPython) ? Services.LocalPython : ""); public string LlmKind => Get("llm.kind", (LmStudioCli.Path != null) ? "lmstudio" : "off"); public string LlmModel => Get("llm.model"); public int LlmContext => Number("llm.context", 8192); public string LlmGpu => Get("llm.gpu", "auto"); public bool LlmAutoStart => Flag("llm.autostart", fallback: false); public HelperSettings(string path) { _path = path; try { if (!File.Exists(path)) { return; } string[] array = File.ReadAllLines(path); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0) { _values[text.Substring(0, num).Trim()] = text.Substring(num + 1).Trim(); } } } catch (IOException) { } } public string Get(string key, string fallback = "") { if (!_values.TryGetValue(key, out string value) || value.Length <= 0) { return fallback; } return value; } public bool Flag(string key, bool fallback) { if (!_values.TryGetValue(key, out string value) || value.Length <= 0) { return fallback; } return value == "1"; } public int Number(string key, int fallback) { if (!int.TryParse(Get(key), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return fallback; } return result; } public void Set(string key, string value) { _values[key] = value; } public void Set(string key, bool value) { _values[key] = (value ? "1" : "0"); } public void Save() { try { Directory.CreateDirectory(Path.GetDirectoryName(_path)); File.WriteAllLines(_path, from pair in _values.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> pair) => pair.Key, StringComparer.OrdinalIgnoreCase) select pair.Key + "=" + pair.Value); } catch (IOException) { } catch (UnauthorizedAccessException) { } } public Launch? CustomLaunch(string role, int defaultPort) { if (!Flag(role + ".custom", fallback: false)) { return null; } string text = Get(role + ".exe"); int port = Number(role + ".port", defaultPort); if (text.Length == 0 || !File.Exists(text)) { return new Launch(null, Text.T("своя программа не найдена: ", "own program not found: ") + ((text.Length > 0) ? text : "–"), port); } return new Launch(new ProcessStartInfo(text, Get(role + ".args")) { WorkingDirectory = (Path.GetDirectoryName(text) ?? "") }, Text.T("своя программа: ", "own program: ") + Path.GetFileName(text), port); } } internal sealed class LmModel { public string Key { get; } public string Label { get; } public LmModel(string key, string label) { Key = key; Label = label; } } internal static class LmStudioCli { private static readonly Regex s_ansi = new Regex("\\x1B\\[[0-9;]*[A-Za-z]"); public static string? Path { get { string text = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".lmstudio", "bin", "lms.exe"); if (File.Exists(text)) { return text; } return (from dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(new char[1] { ';' }) select System.IO.Path.Combine(dir.Trim(), "lms.exe")).FirstOrDefault(File.Exists); } } public static (int Code, string Output) Run(string arguments, int timeoutSeconds) { string path = Path; if (path == null) { return (Code: -1, Output: "LM Studio (lms.exe) is not installed."); } using Process process = Process.Start(new ProcessStartInfo(path, arguments) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8 }); StringBuilder output = new StringBuilder(); process.OutputDataReceived += delegate(object _, DataReceivedEventArgs e) { if (e.Data != null) { lock (output) { output.AppendLine(e.Data); } } }; process.ErrorDataReceived += delegate(object _, DataReceivedEventArgs e) { if (e.Data != null) { lock (output) { output.AppendLine(e.Data); } } }; process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (!process.WaitForExit(timeoutSeconds * 1000)) { try { process.Kill(); } catch (InvalidOperationException) { } return (Code: -2, Output: s_ansi.Replace(output.ToString(), "") + $"\n(lms {arguments}: no answer in {timeoutSeconds} s)"); } process.WaitForExit(); return (Code: process.ExitCode, Output: s_ansi.Replace(output.ToString(), "")); } public static List<LmModel> ListModels() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) (int Code, string Output) tuple = Run("ls --llm --json", 60); int item = tuple.Code; string item2 = tuple.Output; List<LmModel> list = new List<LmModel>(); if (item != 0) { return list; } int num = item2.IndexOf('['); if (num < 0) { return list; } try { foreach (Dictionary<string, object> item4 in new JavaScriptSerializer().Deserialize<ArrayList>(item2.Substring(num)).OfType<Dictionary<string, object>>()) { object value; string text = (item4.TryGetValue("modelKey", out value) ? ((value as string) ?? "") : ""); if (text.Length != 0) { object value2; List<string> list2 = new List<string> { (item4.TryGetValue("displayName", out value2) && value2 is string text2) ? text2 : text }; if (item4.TryGetValue("paramsString", out var value3) && value3 is string item3) { list2.Add(item3); } if (item4.TryGetValue("quantization", out var value4) && value4 is Dictionary<string, object> dictionary && dictionary.TryGetValue("name", out var value5)) { list2.Add(value5?.ToString() ?? ""); } if (item4.TryGetValue("sizeBytes", out var value6)) { list2.Add($"{Convert.ToDouble(value6, CultureInfo.InvariantCulture) / 1073741824.0:0.0} " + Text.T("ГБ", "GB")); } list.Add(new LmModel(text, string.Join(" · ", list2.Where((string part) => part.Length > 0)))); } } } catch (ArgumentException) { } return list; } public static double? EstimateGpuGb(string model, int context, string gpu) { Match match = Regex.Match(Run($"load \"{model}\" --estimate-only -y --context-length {context}" + ((gpu == "max") ? " --gpu max" : ""), 120).Output, "Estimated GPU Memory:\\s*([\\d.]+)\\s*GiB"); if (!match.Success) { return null; } return double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); } } internal sealed class LmStudioService : LocalService { private readonly HelperSettings _settings; private Task? _busy; private bool _startedHere; private string _failure = ""; private string _loaded = ""; private DateTime _nextQuery; private string? _loadingModel; private const int QueryLimitedInformation = 4096; public override bool Owned => _startedHere; public override bool StartsWithOthers => _settings.LlmAutoStart; public LmStudioService(HelperSettings settings) : base("lmstudio", () => Text.T("Текстовая нейросеть (LM Studio)", "Text AI (LM Studio)"), 1234, "lmstudio.log") { _settings = settings; } public override void Start() { if (_startedHere || base.State == ServerState.External || (_busy != null && !_busy.IsCompleted)) { return; } if (LmStudioCli.Path == null) { base.State = ServerState.Missing; base.Detail = Text.T("LM Studio не установлен (lmstudio.ai)", "LM Studio is not installed (lmstudio.ai)"); return; } _failure = ""; _startedHere = true; string model = _settings.LlmModel; int context = _settings.LlmContext; string gpu = _settings.LlmGpu; base.State = ServerState.Starting; Directory.CreateDirectory(Path.GetDirectoryName(base.LogPath)); File.WriteAllText(base.LogPath, $"[{DateTime.Now:HH:mm:ss}] LM Studio\n"); _busy = Task.Run(delegate { if (model.Length == 0) { model = LmStudioCli.ListModels().FirstOrDefault()?.Key ?? ""; } if (model.Length == 0) { _failure = Text.T("в LM Studio нет скачанных моделей", "LM Studio has no models downloaded"); } else { _loadingModel = model; Log(LmStudioCli.Run($"server start --port {base.Port}", 60).Output); var (num, text) = LmStudioCli.Run($"load \"{model}\" -y --context-length {context}" + ((gpu == "max") ? " --gpu max" : ""), 600); Log(text); if (num != 0) { _failure = (from line in text.Split(new char[1] { '\n' }) select line.Trim()).LastOrDefault((string line) => line.Length > 0) ?? "lms load failed"; } _nextQuery = DateTime.MinValue; } }); } public override void Stop() { if (_startedHere) { _startedHere = false; Log(LmStudioCli.Run("unload --all", 60).Output); Log(LmStudioCli.Run("server stop", 30).Output); _loaded = ""; _loadingModel = null; } } public override void Refresh(bool detailed, ISet<int> ports) { if (_busy != null && !_busy.IsCompleted) { base.State = ServerState.Starting; base.Detail = Text.T("загружает модель ", "loading the model ") + _loadingModel + "…"; } else if (_failure.Length > 0 && _startedHere) { base.State = ServerState.Failed; base.Detail = _failure; } else { if (base.State == ServerState.Missing && LmStudioCli.Path == null) { return; } if (!ports.Contains(base.Port)) { base.State = (_startedHere ? ServerState.Failed : ServerState.Off); base.Detail = (_startedHere ? Text.T("сервер LM Studio остановился", "LM Studio's server stopped") : ""); _loaded = ""; return; } if (detailed && DateTime.Now >= _nextQuery) { _nextQuery = DateTime.Now.AddSeconds(3.0); _loaded = LoadedModels(); } base.State = (_startedHere ? ServerState.Running : ServerState.External); base.Detail = ((_loaded.Length > 0) ? (Text.T("модель: ", "model: ") + _loaded) : Text.T("модель не загружена", "no model loaded")); } } public override (long Ram, long? Video) Memory() { string text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".lmstudio"); char directorySeparatorChar = Path.DirectorySeparatorChar; string value = text + directorySeparatorChar; List<int> list = new List<int>(); Process[] processes = Process.GetProcesses(); foreach (Process process in processes) { using (process) { if (process.ProcessName == "LM Studio") { goto IL_006e; } string? text2 = ImagePath(process.Id); if (text2 != null && text2.StartsWith(value, StringComparison.OrdinalIgnoreCase)) { goto IL_006e; } goto end_IL_003f; IL_006e: list.Add(process.Id); end_IL_003f:; } } return LocalService.MemoryOf(list); } private static string? ImagePath(int id) { IntPtr intPtr = OpenProcess(4096, inherit: false, id); if (intPtr == IntPtr.Zero) { return null; } try { StringBuilder stringBuilder = new StringBuilder(1024); int size = stringBuilder.Capacity; return QueryFullProcessImageName(intPtr, 0, stringBuilder, ref size) ? stringBuilder.ToString() : null; } finally { CloseHandle(intPtr); } } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr OpenProcess(int access, bool inherit, int id); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder path, ref int size); [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle); private string LoadedModels() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) try { using WebClient webClient = new WebClient { Encoding = Encoding.UTF8, Proxy = null }; string text = webClient.DownloadString($"http://127.0.0.1:{base.Port}/api/v0/models"); if (!new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(text).TryGetValue("data", out var value) || !(value is ArrayList source)) { return ""; } object value3; object value2; return string.Join(", ", from model in source.OfType<Dictionary<string, object>>() where model.TryGetValue("state", out value2) && value2 as string == "loaded" && (!model.TryGetValue("type", out value3) || value3 as string != "embeddings") select (!model.TryGetValue("id", out value2)) ? "" : ((value2 as string) ?? "")); } catch (Exception ex) when (((ex is WebException || ex is ArgumentException || ex is InvalidOperationException) ? 1 : 0) != 0) { return _loaded; } } private void Log(string text) { try { File.AppendAllText(base.LogPath, text.TrimEnd(Array.Empty<char>()) + "\n"); } catch (IOException) { } } } internal sealed class LogWindow : Form { private const int MaxLines = 400; private readonly ComboBox _which; private readonly TextBox _text; private readonly CheckBox _follow; private readonly Timer _timer; private readonly List<(string Title, string Path)> _logs; private long _shownLength = -1L; private string _shownPath = ""; private bool _reading; public LogWindow(IEnumerable<LocalService> services, Icon icon) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown //IL_00ae: 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_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Expected O, but got Unknown //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: 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_00ff: Expected O, but got Unknown //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Expected O, but got Unknown //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Expected O, but got Unknown //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Expected O, but got Unknown //IL_026e: Expected O, but got Unknown //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Expected O, but got Unknown _logs = services.Select((LocalService s) => (Title: s.Title, LogPath: s.LogPath)).ToList(); ((Control)this).Text = Text.T("Журналы помощников", "Helper logs"); ((Form)this).Icon = icon; ((Control)this).Font = new Font(Text.FontName, 10f); ((Form)this).Size = new Size(900, 560); ((Control)this).MinimumSize = new Size(560, 300); ((Form)this).StartPosition = (FormStartPosition)4; ((Control)this).Padding = new Padding(10); FlowLayoutPanel val = new FlowLayoutPanel { Dock = (DockStyle)1, AutoSize = true, WrapContents = false, Margin = new Padding(0, 0, 0, 6) }; _which = new ComboBox { DropDownStyle = (ComboBoxStyle)2, Width = 330 }; foreach (var log in _logs) { string item = log.Title; _which.Items.Add((object)item); } _which.SelectedIndexChanged += delegate { Reload(force: true); }; ((Control)val).Controls.Add((Control)(object)_which); _follow = new CheckBox { Text = Text.T("Прокручивать вниз", "Follow the end"), AutoSize = true, Checked = true, Margin = new Padding(12, 6, 0, 0) }; ((Control)val).Controls.Add((Control)(object)_follow); Button val2 = new Button { Text = Text.T("Открыть папку", "Open folder"), Width = 140, Height = 30, Margin = new Padding(12, 0, 0, 0) }; ((Control)val2).Click += delegate { Directory.CreateDirectory(Services.Logs); Process.Start("explorer.exe", "\"" + Services.Logs + "\""); }; ((Control)val).Controls.Add((Control)(object)val2); _text = new TextBox { Dock = (DockStyle)5, Multiline = true, ReadOnly = true, ScrollBars = (ScrollBars)3, WordWrap = false, Font = new Font("Consolas", 9.5f) }; ((Control)this).Controls.Add((Control)(object)_text); ((Control)this).Controls.Add((Control)(object)val); Theme.Apply((Form)(object)this); _timer = new Timer { Interval = 1000 }; _timer.Tick += delegate { Reload(force: false); }; if (_which.Items.Count > 0) { ((ListControl)_which).SelectedIndex = 0; } _timer.Start(); } protected override void OnFormClosed(FormClosedEventArgs e) { _timer.Stop(); ((Component)(object)_timer).Dispose(); ((Form)this).OnFormClosed(e); } private async void Reload(bool force) { if (_reading || ((ListControl)_which).SelectedIndex < 0) { return; } string path = _logs[((ListControl)_which).SelectedIndex].Path; bool same = !force && path == _shownPath; long shown = _shownLength; _reading = true; (long, string) obj = await Task.Run(delegate { long num = (File.Exists(path) ? new FileInfo(path).Length : 0); return (same && num == shown) ? (size: num, null) : (size: num, (num == 0L) ? Text.T("(журнал пуст: помощник ещё не запускался)", "(empty: the helper has not run yet)") : Tail(path)); }); long item = obj.Item1; string item2 = obj.Item2; _reading = false; if (!((Control)this).IsDisposed && item2 != null) { _shownPath = path; _shownLength = item; ((Control)_text).Text = item2; if (_follow.Checked) { ((TextBoxBase)_text).SelectionStart = ((TextBoxBase)_text).TextLength; ((TextBoxBase)_text).ScrollToCaret(); } } } private static string Tail(string path) { try { using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); if (fileStream.Length > 262144) { fileStream.Seek(-262144L, SeekOrigin.End); } using StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8); string[] array = streamReader.ReadToEnd().Replace("\r", "").Split(new char[1] { '\n' }); return string.Join(Environment.NewLine, array.Skip(Math.Max(0, array.Length - 400))); } catch (IOException ex) { return ex.Message; } } } internal sealed class SettingsForm : Form { private sealed class Item { public string Value { get; } public string Text { get; } public Item(string value, string text) { Value = value; Text = text; } public override string ToString() { return Text; } } private sealed class CustomProgram { private readonly CheckBox? _switch; private readonly TextBox _exe; private readonly TextBox _args; private readonly NumericUpDown _port; private readonly List<Control> _rows = new List<Control>(); private readonly string _role; public CustomProgram(SettingsForm form, string role, int defaultPort, bool withSwitch) { //IL_00aa: 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_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Expected O, but got Unknown //IL_00db: 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_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0105: 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_0115: Expected O, but got Unknown //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Expected O, but got Unknown //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Expected O, but got Unknown //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Expected O, but got Unknown //IL_003d: 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) //IL_0057: 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_007b: Expected O, but got Unknown CustomProgram customProgram = this; _role = role; HelperSettings settings = form._settings; if (withSwitch) { _switch = new CheckBox { Text = Text.T("Своя программа вместо встроенной", "Own program instead of the built-in one"), AutoSize = true, Checked = settings.Flag(role + ".custom", fallback: false) }; _switch.CheckedChanged += delegate { customProgram.Show(parentVisible: true); form.UpdateScroll(); }; form.Row("", (Control)(object)_switch); } _exe = new TextBox { Width = 320, Text = settings.Get(role + ".exe") }; Button val = new Button { Text = Text.T("Обзор…", "Browse…"), Width = 100, Height = 28, Margin = new Padding(6, 0, 0, 0) }; ((Control)val).Click += delegate { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Invalid comparison between Unknown and I4 OpenFileDialog val3 = new OpenFileDialog { Filter = Text.T("Программы", "Programs") + " (*.exe;*.bat;*.cmd)|*.exe;*.bat;*.cmd" }; try { if ((int)((CommonDialog)val3).ShowDialog((IWin32Window)(object)form) == 1) { ((Control)customProgram._exe).Text = ((FileDialog)val3).FileName; } } finally { ((IDisposable)val3)?.Dispose(); } }; FlowLayoutPanel val2 = new FlowLayoutPanel { AutoSize = true, WrapContents = false, Margin = new Padding(0) }; ((Control)val2).Controls.Add((Control)(object)_exe); ((Control)val2).Controls.Add((Control)(object)val); _rows.Add(form.Row(Text.T("Программа", "Program"), (Control)(object)val2)); _args = new TextBox { Width = 426, Text = settings.Get(role + ".args") }; _rows.Add(form.Row(Text.T("Аргументы", "Arguments"), (Control)(object)_args)); _port = new NumericUpDown { Minimum = 1m, Maximum = 65535m, Width = 100, Value = settings.Number(role + ".port", defaultPort) }; _rows.Add(form.Row(Text.T("Порт", "Port"), (Control)(object)_port)); _rows.Add((Control)(object)form.Note(Text.T("Программа должна отвечать на этом порту по API OpenAI (/v1/…). Её адрес впиши в мод.", "The program must answer on this port with OpenAI's API (/v1/…). Put its address into the mod."))); Show(parentVisible: true); } public void Show(bool parentVisible) { bool visible = parentVisible && (_switch == null || _switch.Checked); foreach (Control row in _rows) { SetRowVisible(row, visible); } } public void Save(HelperSettings settings) { if (_switch != null) { settings.Set(_role + ".custom", _switch.Checked); } else { settings.Set(_role + ".custom", value: true); } settings.Set(_role + ".exe", ((Control)_exe).Text.Trim()); settings.Set(_role + ".args", ((Control)_args).Text.Trim()); settings.Set(_role + ".port", ((int)_port.Value).ToString(CultureInfo.InvariantCulture)); } } private const int LabelWidth = 230; private const int FieldWidth = 430; private readonly HelperSettings _settings; private TableLayoutPanel _table; private readonly Panel _content; private readonly FlowLayoutPanel _tabs; private readonly List<(Button Tab, TableLayoutPanel Page)> _pages = new List<(Button, TableLayoutPanel)>(); private readonly ComboBox _theme; private readonly ComboBox _language; private readonly TextBox _whisperServer; private readonly ComboBox _whisperModel; private readonly ComboBox _whisperDevice; private readonly CustomProgram _whisperCustom; private readonly ComboBox _voiceEngine; private readonly TextBox _voicesFolder; private readonly TextBox _python; private readonly Label _pythonNote; private readonly CustomProgram _piperCustom; private readonly Label _voices; private readonly ComboBox _llmKind; private readonly ComboBox _llmModel; private readonly ComboBox _llmContext; private readonly ComboBox _llmGpu; private readonly Button _estimate; private readonly Label _estimateResult; private readonly CheckBox _llmAutoStart; private readonly Label _ollamaNote; private readonly CustomProgram _llmCustom; private readonly List<Control> _lmStudioRows = new List<Control>(); public int TabCount => _pages.Count; public SettingsForm(HelperSettings settings, Icon icon) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Expected O, but got Unknown //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009f: 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_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Expected O, but got Unknown //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Expected O, but got Unknown //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Expected O, but got Unknown //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Expected O, but got Unknown //IL_04b4: Unknown result type (might be due to invalid IL or missing references) //IL_04b9: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_04d6: Expected O, but got Unknown //IL_04f2: Unknown result type (might be due to invalid IL or missing references) //IL_04f7: Unknown result type (might be due to invalid IL or missing references) //IL_050c: Unknown result type (might be due to invalid IL or missing references) //IL_0513: Unknown result type (might be due to invalid IL or missing references) //IL_0522: Expected O, but got Unknown //IL_07bf: Unknown result type (might be due to invalid IL or missing references) //IL_07c4: Unknown result type (might be due to invalid IL or missing references) //IL_07d9: Unknown result type (might be due to invalid IL or missing references) //IL_07e4: Unknown result type (might be due to invalid IL or missing references) //IL_07f1: Expected O, but got Unknown //IL_0809: Unknown result type (might be due to invalid IL or missing references) //IL_080e: Unknown result type (might be due to invalid IL or missing references) //IL_0815: Unknown result type (might be due to invalid IL or missing references) //IL_0826: Unknown result type (might be due to invalid IL or missing references) //IL_0831: Unknown result type (might be due to invalid IL or missing references) //IL_0836: Unknown result type (might be due to invalid IL or missing references) //IL_0845: Expected O, but got Unknown //IL_0845: Unknown result type (might be due to invalid IL or missing references) //IL_084a: Unknown result type (might be due to invalid IL or missing references) //IL_0851: Unknown result type (might be due to invalid IL or missing references) //IL_0858: Unknown result type (might be due to invalid IL or missing references) //IL_085a: Unknown result type (might be due to invalid IL or missing references) //IL_0865: Expected O, but got Unknown //IL_0931: Unknown result type (might be due to invalid IL or missing references) //IL_0936: Unknown result type (might be due to invalid IL or missing references) //IL_094b: Unknown result type (might be due to invalid IL or missing references) //IL_0952: Unknown result type (might be due to invalid IL or missing references) //IL_0963: Expected O, but got Unknown //IL_098c: Unknown result type (might be due to invalid IL or missing references) //IL_0991: Unknown result type (might be due to invalid IL or missing references) //IL_09a6: Unknown result type (might be due to invalid IL or missing references) //IL_09ad: Unknown result type (might be due to invalid IL or missing references) //IL_09b4: Unknown result type (might be due to invalid IL or missing references) //IL_09c5: Unknown result type (might be due to invalid IL or missing references) //IL_09cc: Unknown result type (might be due to invalid IL or missing references) //IL_09d6: Unknown result type (might be due to invalid IL or missing references) //IL_09e3: Expected O, but got Unknown //IL_09e3: Unknown result type (might be due to invalid IL or missing references) //IL_09e8: Unknown result type (might be due to invalid IL or missing references) //IL_09ef: Unknown result type (might be due to invalid IL or missing references) //IL_09f6: Unknown result type (might be due to invalid IL or missing references) //IL_09fd: Unknown result type (might be due to invalid IL or missing references) //IL_0a00: Unknown result type (might be due to invalid IL or missing references) //IL_0a0c: Expected O, but got Unknown //IL_0a0c: Unknown result type (might be due to invalid IL or missing references) //IL_0a11: Unknown result type (might be due to invalid IL or missing references) //IL_0a26: Unknown result type (might be due to invalid IL or missing references) //IL_0a2e: Unknown result type (might be due to invalid IL or missing references) //IL_0a36: Unknown result type (might be due to invalid IL or missing references) //IL_0a3f: Expected O, but got Unknown //IL_0a3f: Unknown result type (might be due to invalid IL or missing references) //IL_0a44: Unknown result type (might be due to invalid IL or missing references) //IL_0a59: Unknown result type (might be due to invalid IL or missing references) //IL_0a64: Unknown result type (might be due to invalid IL or missing references) //IL_0a6e: Expected O, but got Unknown _settings = settings; ((Control)this).Text = Text.T("Настройки помощника", "Helper settings"); ((Form)this).Icon = icon; ((Control)this).Font = new Font(Text.FontName, 10f); ((Form)this).FormBorderStyle = (FormBorderStyle)3; ((Form)this).MaximizeBox = false; ((Form)this).MinimizeBox = false; ((Form)this).StartPosition = (FormStartPosition)4; ((Form)this).ClientSize = new Size(730, 590); ((Control)this).DoubleBuffered = true; ((Control)this).SuspendLayout(); _tabs = new FlowLayoutPanel { Dock = (DockStyle)1, AutoSize = true, WrapContents = false, Padding = new Padding(12, 12, 12, 2) }; _content = new Panel { Dock = (DockStyle)5, Padding = new Padding(14, 6, 14, 6) }; Page(Text.T("Вид", "Look")); _theme = Choice(Text.T("Тема", "Theme"), settings.Theme, ("system", Text.T("Как в Windows", "As in Windows")), ("light", Text.T("Светлая", "Light")), ("dark", Text.T("Тёмная", "Dark"))); _language = Choice(Text.T("Язык", "Language"), settings.Language, ("system", Text.T("Как в Windows", "As in Windows")), ("ru", "Русский"), ("en", "English"), ("zh-hans", "简体中文"), ("zh-hant", "繁體中文")); Page(Text.T("Распознавание", "Recognition")); _whisperServer = FileRow(Text.T("Программа", "Program"), settings.WhisperServer, "whisper-server.exe|whisper-server.exe|" + Text.T("Программы", "Programs") + " (*.exe)|*.exe");
plugins/BingBongHelper/BingBongVoice.exe
Decompiled 2 weeks agousing System; 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.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web.Script.Serialization; using Microsoft.CodeAnalysis; using Microsoft.ML.OnnxRuntime; using Microsoft.ML.OnnxRuntime.Tensors; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("BingBongVoice")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("BingBongVoice")] [assembly: AssemblyTitle("Bing Bong AI voice (Piper without Python)")] [assembly: AssemblyVersion("0.1.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; } } } namespace BingBongVoice { internal static class Espeak { private const int AudioOutputSynchronous = 2; private const int CharsAuto = 0; private const int PhonemesIpa = 2; private const int TypeClause = 262144; private const int TypeSentence = 524288; private const int Period = 524328; private const int Comma = 266260; private const int Question = 532520; private const int Exclamation = 536621; private const int Colon = 262174; private const int Semicolon = 266270; private static readonly object s_lock = new object(); private static bool s_ready; public static void Initialize() { lock (s_lock) { if (!s_ready) { string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; if (!Directory.Exists(Path.Combine(baseDirectory, "espeak-ng-data"))) { throw new InvalidOperationException("espeak-ng-data is missing next to " + Path.Combine(baseDirectory, "BingBongVoice.exe") + "."); } Environment.CurrentDirectory = baseDirectory; if (espeak_Initialize(2, 0, ".", 0) < 0) { throw new InvalidOperationException("espeak-ng did not start."); } s_ready = true; } } } public static List<(string Phonemes, string Terminator, bool EndOfSentence)> Clauses(string voice, string text) { List<(string, string, bool)> list = new List<(string, string, bool)>(); byte[] bytes = Encoding.UTF8.GetBytes(text + "\0"); IntPtr intPtr = Marshal.AllocHGlobal(bytes.Length); try { Marshal.Copy(bytes, 0, intPtr, bytes.Length); lock (s_lock) { if (espeak_SetVoiceByName(voice) != 0) { throw new InvalidOperationException("espeak-ng has no voice \"" + voice + "\"."); } IntPtr text2 = intPtr; while (text2 != IntPtr.Zero) { int terminator; IntPtr text3 = espeak_TextToPhonemesWithTerminator(ref text2, 0, 2, out terminator); terminator &= 0xFFFFF; string item = terminator switch { 524328 => ".", 532520 => "?", 536621 => "!", 266260 => ",", 262174 => ":", 266270 => ";", _ => "", }; list.Add((Utf8(text3), item, (terminator & 0x80000) == 524288)); } return list; } } finally { Marshal.FreeHGlobal(intPtr); } } private static string Utf8(IntPtr text) { if (text == IntPtr.Zero) { return ""; } int i; for (i = 0; Marshal.ReadByte(text, i) != 0; i++) { } byte[] array = new byte[i]; Marshal.Copy(text, array, 0, i); return Encoding.UTF8.GetString(array); } [DllImport("espeak-ng.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int espeak_Initialize(int output, int bufferLength, [MarshalAs(UnmanagedType.LPStr)] string path, int options); [DllImport("espeak-ng.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int espeak_SetVoiceByName([MarshalAs(UnmanagedType.LPStr)] string name); [DllImport("espeak-ng.dll", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr espeak_TextToPhonemesWithTerminator(ref IntPtr text, int textMode, int phonemeMode, out int terminator); } internal sealed class PiperVoice : IDisposable { private const string Pad = "_"; private const string Bos = "^"; private const string Eos = "$"; private static readonly Regex s_rawPhonemes = new Regex("(\\[\\[.*?\\]\\])"); private static readonly Regex s_languageFlags = new Regex("\\([^)]+\\)"); private readonly InferenceSession _session; private readonly Dictionary<string, long[]> _ids = new Dictionary<string, long[]>(StringComparer.Ordinal); private readonly HashSet<string> _clusters = new HashSet<string>(StringComparer.Ordinal); private readonly int _maxCluster; private readonly string _espeakVoice; private readonly string _phonemeType; private readonly int _speakers; private readonly long _defaultSpeaker; private readonly float _noiseScale; private readonly float _noiseW; public int SampleRate { get; } public float LengthScale { get; } public PiperVoice(string model) { //IL_0026: 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_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Expected O, but got Unknown //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Expected O, but got Unknown Dictionary<string, object> dictionary = (Dictionary<string, object>)new JavaScriptSerializer { MaxJsonLength = int.MaxValue }.DeserializeObject(File.ReadAllText(model + ".json", Encoding.UTF8)); SampleRate = Convert.ToInt32(Section(dictionary, "audio")["sample_rate"], CultureInfo.InvariantCulture); _espeakVoice = Convert.ToString(Section(dictionary, "espeak").TryGetValue("voice", out object value) ? value : "", CultureInfo.InvariantCulture) ?? ""; _phonemeType = ((dictionary.TryGetValue("phoneme_type", out var value2) && value2 != null) ? Convert.ToString(value2, CultureInfo.InvariantCulture) : "espeak"); _speakers = Convert.ToInt32(dictionary["num_speakers"], CultureInfo.InvariantCulture); _defaultSpeaker = ((dictionary.TryGetValue("default_speaker_id", out var value3) && value3 != null) ? Convert.ToInt64(value3, CultureInfo.InvariantCulture) : 0); Dictionary<string, object> section = Section(dictionary, "inference"); _noiseScale = Number(section, "noise_scale", 0.667f); LengthScale = Number(section, "length_scale", 1f); _noiseW = Number(section, "noise_w", 0.8f); foreach (KeyValuePair<string, object> item in Section(dictionary, "phoneme_id_map")) { _ids[item.Key] = ((object[])item.Value).Select((object id) => Convert.ToInt64(id, CultureInfo.InvariantCulture)).ToArray(); } if (dictionary.TryGetValue("vowel_clusters", out var value4) && value4 is object[] source) { foreach (object[] item2 in source.OfType<object[]>()) { _clusters.Add(string.Join("\u0001", item2.Select((object c) => Convert.ToString(c, CultureInfo.InvariantCulture)))); _maxCluster = Math.Max(_maxCluster, item2.Length); } } string phonemeType = _phonemeType; if ((!(phonemeType == "espeak") && !(phonemeType == "text")) || 1 == 0) { throw new NotSupportedException("This voice needs Piper's Python code (phoneme_type \"" + _phonemeType + "\")."); } _session = new InferenceSession(model, new SessionOptions()); } public byte[] Wav(string text, float? lengthScale) { List<short> list = new List<short>(); foreach (List<string> item in Phonemize(text)) { if (item.Count != 0) { list.AddRange(ToInt16(Audio(PhonemeIds(item), lengthScale ?? LengthScale))); } } if (list.Count == 0) { throw new InvalidOperationException("there is nothing to say in it"); } return WavFile(list, SampleRate); } public void Dispose() { _session.Dispose(); } internal List<List<string>> Phonemize(string text) { if (_phonemeType == "text") { return new List<List<string>>(1) { CodePoints(text.Normalize(NormalizationForm.FormD)) }; } List<List<string>> list = new List<List<string>>(); string[] array = s_rawPhonemes.Split(text); bool flag = false; for (int i = 0; i < array.Length; i++) { string text2 = array[i]; if (text2.StartsWith("[[", StringComparison.Ordinal)) { flag = true; if (list.Count == 0) { list.Add(new List<string>()); } if (i > 0 && array[i - 1].EndsWith(" ", StringComparison.Ordinal)) { list[list.Count - 1].Add(" "); } list[list.Count - 1].AddRange(CodePoints(text2.Substring(2, text2.Length - 4).Trim())); if (i < array.Length - 1 && array[i + 1].StartsWith(" ", StringComparison.Ordinal)) { list[list.Count - 1].Add(" "); } } else { List<List<string>> list2 = EspeakPhonemes(text2); if (flag && list2.Count > 0) { list[list.Count - 1].AddRange(list2[0]); list2.RemoveAt(0); } list.AddRange(list2); flag = false; } } if (list.Count > 0 && list[list.Count - 1].Count == 0) { list.RemoveAt(list.Count - 1); } return list; } private List<List<string>> EspeakPhonemes(string text) { List<List<string>> list = new List<List<string>>(); List<string> list2 = new List<string>(); foreach (var item4 in Espeak.Clauses(_espeakVoice, text)) { string item = item4.Phonemes; string item2 = item4.Terminator; bool item3 = item4.EndOfSentence; string text2 = s_languageFlags.Replace(item, "") + item2; bool flag; switch (item2) { case ",": case ":": case ";": flag = true; break; default: flag = false; break; } if (flag) { text2 += " "; } list2.AddRange(CodePoints(text2.Normalize(NormalizationForm.FormD))); if (item3) { list.Add(MergeClusters(list2)); list2 = new List<string>(); } } if (list2.Count > 0) { list.Add(MergeClusters(list2)); } return list; } private List<string> MergeClusters(List<string> phones) { if (_clusters.Count == 0) { return phones; } List<string> list = new List<string>(); int num = 0; while (num < phones.Count) { int num2 = 0; for (int num3 = Math.Min(_maxCluster, phones.Count - num); num3 > 1; num3--) { if (_clusters.Contains(string.Join("\u0001", phones.Skip(num).Take(num3)))) { num2 = num3; break; } } if (num2 > 0) { list.Add(string.Concat(phones.Skip(num).Take(num2))); num += num2; } else { list.Add(phones[num]); num++; } } return list; } internal long[] PhonemeIds(List<string> phonemes) { List<long> list = new List<long>(); list.AddRange(_ids["^"]); list.AddRange(_ids["_"]); foreach (string phoneme in phonemes) { if (!_ids.TryGetValue(phoneme, out long[] value)) { Console.WriteLine("Missing phoneme from id map: " + phoneme); continue; } list.AddRange(value); list.AddRange(_ids["_"]); } list.AddRange(_ids["$"]); return list.ToArray(); } private float[] Audio(long[] ids, float lengthScale) { List<NamedOnnxValue> list = new List<NamedOnnxValue>(); list.Add(NamedOnnxValue.CreateFromTensor<long>("input", (Tensor<long>)(object)new DenseTensor<long>((Memory<long>)ids, new ReadOnlySpan<int>(new int[2] { 1, ids.Length }), false))); Memory<long> memory = new long[1] { ids.Length }; object obj = global::<PrivateImplementationDetails>.67ABDD721024F0FF4E0B3F4C2FC13BC5BAD42D0B7851D456D88D203D15AAA450_A6; if (obj == null) { obj = new int[1] { 1 }; global::<PrivateImplementationDetails>.67ABDD721024F0FF4E0B3F4C2FC13BC5BAD42D0B7851D456D88D203D15AAA450_A6 = (int[])obj; } list.Add(NamedOnnxValue.CreateFromTensor<long>("input_lengths", (Tensor<long>)(object)new DenseTensor<long>(memory, new ReadOnlySpan<int>((int[]?)obj), false))); Memory<float> memory2 = new float[3] { _noiseScale, lengthScale, _noiseW }; object obj2 = global::<PrivateImplementationDetails>.9D9F290527A6BE626A8F5985B26E19B237B44872B03631811DF4416FC1713178_A6; if (obj2 == null) { obj2 = new int[1] { 3 }; global::<PrivateImplementationDetails>.9D9F290527A6BE626A8F5985B26E19B237B44872B03631811DF4416FC1713178_A6 = (int[])obj2; } list.Add(NamedOnnxValue.CreateFromTensor<float>("scales", (Tensor<float>)(object)new DenseTensor<float>(memory2, new ReadOnlySpan<int>((int[]?)obj2), false))); List<NamedOnnxValue> list2 = list; if (_speakers > 1) { Memory<long> memory3 = new long[1] { _defaultSpeaker }; object obj3 = global::<PrivateImplementationDetails>.67ABDD721024F0FF4E0B3F4C2FC13BC5BAD42D0B7851D456D88D203D15AAA450_A6; if (obj3 == null) { obj3 = new int[1] { 1 }; global::<PrivateImplementationDetails>.67ABDD721024F0FF4E0B3F4C2FC13BC5BAD42D0B7851D456D88D203D15AAA450_A6 = (int[])obj3; } list2.Add(NamedOnnxValue.CreateFromTensor<long>("sid", (Tensor<long>)(object)new DenseTensor<long>(memory3, new ReadOnlySpan<int>((int[]?)obj3), false))); } IDisposableReadOnlyCollection<DisposableNamedOnnxValue> val = _session.Run((IReadOnlyCollection<NamedOnnxValue>)list2); try { float[] array = ((NamedOnnxValue)((IEnumerable<DisposableNamedOnnxValue>)val).First()).AsEnumerable<float>().ToArray(); float num = 0f; float[] array2 = array; foreach (float value in array2) { num = Math.Max(num, Math.Abs(value)); } for (int j = 0; j < array.Length; j++) { array[j] = ((num < 1E-08f) ? 0f : Math.Max(-1f, Math.Min(1f, array[j] / num))); } return array; } finally { ((IDisposable)val)?.Dispose(); } } private static IEnumerable<short> ToInt16(float[] audio) { return audio.Select((float sample) => (short)Math.Max(-32767f, Math.Min(32767f, sample * 32767f))); } private static byte[] WavFile(List<short> samples, int sampleRate) { using MemoryStream memoryStream = new MemoryStream(44 + samples.Count * 2); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(Encoding.ASCII.GetBytes("RIFF")); binaryWriter.Write(36 + samples.Count * 2); binaryWriter.Write(Encoding.ASCII.GetBytes("WAVEfmt ")); binaryWriter.Write(16); binaryWriter.Write((short)1); binaryWriter.Write((short)1); binaryWriter.Write(sampleRate); binaryWriter.Write(sampleRate * 2); binaryWriter.Write((short)2); binaryWriter.Write((short)16); binaryWriter.Write(Encoding.ASCII.GetBytes("data")); binaryWriter.Write(samples.Count * 2); foreach (short sample in samples) { binaryWriter.Write(sample); } binaryWriter.Flush(); return memoryStream.ToArray(); } private static List<string> CodePoints(string text) { List<string> list = new List<string>(text.Length); for (int i = 0; i < text.Length; i++) { if (char.IsHighSurrogate(text[i]) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1])) { list.Add(text.Substring(i, 2)); i++; } else { list.Add(text[i].ToString()); } } return list; } private static Dictionary<string, object> Section(Dictionary<string, object> config, string name) { if (!config.TryGetValue(name, out object value) || !(value is Dictionary<string, object> result)) { return new Dictionary<string, object>(); } return result; } private static float Number(Dictionary<string, object> section, string name, float fallback) { if (!section.TryGetValue(name, out object value) || value == null) { return fallback; } return Convert.ToSingle(value, CultureInfo.InvariantCulture); } } internal sealed class Voices { private readonly string _folder; private readonly Dictionary<string, PiperVoice> _loaded = new Dictionary<string, PiperVoice>(StringComparer.Ordinal); public string Folder => _folder; public Voices(string folder) { _folder = folder; } public List<Dictionary<string, object>> Available() { //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); if (!Directory.Exists(_folder)) { return list; } foreach (string item in Directory.GetFiles(_folder, "*.onnx").OrderBy<string, string>((string f) => f, StringComparer.Ordinal)) { string path = item + ".json"; if (!File.Exists(path)) { continue; } string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(item); string value = fileNameWithoutExtension; string text = ""; try { Dictionary<string, object> obj = (Dictionary<string, object>)new JavaScriptSerializer { MaxJsonLength = int.MaxValue }.DeserializeObject(File.ReadAllText(path, Encoding.UTF8)); if (obj.TryGetValue("dataset", out var value2) && value2 is string { Length: >0 } text2) { value = text2; } if (obj.TryGetValue("language", out var value3) && value3 is Dictionary<string, object> dictionary && dictionary.TryGetValue("code", out var value4) && value4 is string text3) { text = text3; } } catch (Exception ex) when (((ex is IOException || ex is ArgumentException || ex is InvalidOperationException || ex is InvalidCastException) ? 1 : 0) != 0) { } list.Add(new Dictionary<string, object> { ["id"] = fileNameWithoutExtension, ["name"] = value, ["language"] = text.Replace("_", "-") }); } return list; } public (string Id, PiperVoice Voice) Get(string wanted) { List<string> list = (from v in Available() select (string)v["id"]).ToList(); if (list.Count == 0) { throw new KeyNotFoundException("No voices in " + _folder + " (each needs .onnx and .onnx.json)."); } string text = (list.Contains(wanted) ? wanted : list[0]); lock (_loaded) { if (!_loaded.TryGetValue(text, out PiperVoice value)) { value = (_loaded[text] = new PiperVoice(Path.Combine(_folder, text + ".onnx"))); } return (Id: text, Voice: value); } } } internal static class Program { private static Voices s_voices = null; private static readonly object s_speaking = new object(); private static readonly JavaScriptSerializer s_json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; private static int Main(string[] args) { StreamWriter obj = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)) { AutoFlush = true }; Console.SetOut(obj); Console.SetError(obj); Dictionary<string, string> dictionary = Options(args); if (!dictionary.TryGetValue("voices", out var value)) { Console.WriteLine("Piper voices with OpenAI's speech API, for Bing Bong AI."); Console.WriteLine("BingBongVoice.exe --voices <folder with *.onnx and *.onnx.json> [--port 8000] [--host 127.0.0.1]"); return 2; } string value2; string text = (dictionary.TryGetValue("host", out value2) ? value2 : "127.0.0.1"); string value3; int result; int num = ((dictionary.TryGetValue("port", out value3) && int.TryParse(value3, out result)) ? result : 8000); s_voices = new Voices(Path.GetFullPath(value)); List<Dictionary<string, object>> list = s_voices.Available(); if (list.Count == 0) { Console.WriteLine("No Piper voices in " + s_voices.Folder + ": put a .onnx file and its .onnx.json there."); return 1; } try { Espeak.Initialize(); s_voices.Get((string)list[0]["id"]); } catch (Exception ex) when (((ex is DllNotFoundException || ex is BadImageFormatException || ex is TypeInitializationException) ? 1 : 0) != 0) { Console.WriteLine("Could not load the voice engine: " + ex.GetBaseException().Message); Console.WriteLine("It needs the Microsoft Visual C++ Redistributable (x64): https://aka.ms/vs/17/release/vc_redist.x64.exe"); return 1; } catch (Exception ex2) { Console.WriteLine("Could not load the voice: " + ex2.Message); return 1; } TcpListener tcpListener; try { tcpListener = new TcpListener(IPAddress.Parse(text), num); tcpListener.Start(); } catch (Exception ex3) when (((ex3 is SocketException || ex3 is FormatException) ? 1 : 0) != 0) { Console.WriteLine($"Cannot listen on {text}:{num}: {ex3.Message}"); return 1; } Console.WriteLine($"Piper for Bing Bong AI: http://{text}:{num}/v1"); Console.WriteLine("Voices: " + string.Join(", ", list.Select((Dictionary<string, object> v) => string.Format("{0} ({1})", v["id"], v["language"])))); Console.WriteLine("Leave this window open while playing; close it (or Ctrl+C) to stop."); while (true) { TcpClient client = tcpListener.AcceptTcpClient(); ThreadPool.QueueUserWorkItem(delegate { Serve(client); }); } } private static Dictionary<string, string> Options(string[] args) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < args.Length; i++) { if (args[i].StartsWith("--", StringComparison.Ordinal)) { string text = args[i].Substring(2); int num = text.IndexOf('='); if (num >= 0) { dictionary[text.Substring(0, num)] = text.Substring(num + 1); } else if (i + 1 < args.Length) { dictionary[text] = args[++i]; } } } return dictionary; } private static void Serve(TcpClient client) { using (client) { try { client.ReceiveTimeout = 30000; NetworkStream stream = client.GetStream(); var (text, target, dictionary) = ReadHead(stream); if (text == null) { return; } byte[] body = Array.Empty<byte>(); if (dictionary.TryGetValue("content-length", out var value) && int.TryParse(value, out var result) && result > 0) { if (dictionary.TryGetValue("expect", out var value2) && value2.Equals("100-continue", StringComparison.OrdinalIgnoreCase)) { Write(stream, Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n")); } body = ReadExactly(stream, result); } (int Code, byte[] Content, string Type) tuple2 = Handle(text, target, body); int item = tuple2.Code; byte[] item2 = tuple2.Content; string item3 = tuple2.Type; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("HTTP/1.0 ").Append(item).Append(' ') .Append(Reason(item)) .Append("\r\n"); stringBuilder.Append("Content-Type: ").Append(item3).Append("\r\n"); stringBuilder.Append("Content-Length: ").Append(item2.Length).Append("\r\n"); stringBuilder.Append("Connection: close\r\n\r\n"); Write(stream, Encoding.ASCII.GetBytes(stringBuilder.ToString())); Write(stream, item2); } catch (Exception ex) when (((ex is IOException || ex is SocketException || ex is ObjectDisposedException) ? 1 : 0) != 0) { } } } private static (int Code, byte[] Content, string Type) Handle(string method, string target, byte[] body) { string text = target.Split(new char[1] { '?' })[0].TrimEnd(new char[1] { '/' }); string text2 = (text.StartsWith("/v1/", StringComparison.Ordinal) ? text.Substring(3) : text); if (method == "GET") { if (text2 == "/audio/voices") { return Json(200, new Dictionary<string, object> { ["voices"] = s_voices.Available() }); } if (text2 == "/models") { return Json(200, new Dictionary<string, object> { ["object"] = "list", ["data"] = new Dictionary<string, object>[1] { new Dictionary<string, object> { ["id"] = "piper", ["object"] = "model" } } }); } return Fail(404, "Not found: " + target); } if (method != "POST") { return Fail(501, "Unsupported method (" + method + ")"); } if (text2 != "/audio/speech") { return Fail(404, "Not found: " + target); } Dictionary<string, object> dictionary; try { string text3 = Encoding.UTF8.GetString(body); dictionary = (s_json.DeserializeObject((text3.Length > 0) ? text3 : "{}") as Dictionary<string, object>) ?? throw new ArgumentException(); } catch (ArgumentException) { return Fail(400, "The request body is not JSON."); } catch (InvalidOperationException) { return Fail(400, "The request body is not JSON."); } string text4 = Field(dictionary, "input").Trim(); if (text4.Length == 0) { return Fail(400, "'input' is empty."); } try { (string Id, PiperVoice Voice) tuple = s_voices.Get(Field(dictionary, "voice")); string item = tuple.Id; PiperVoice item2 = tuple.Voice; float val = ((dictionary.TryGetValue("speed", out var value) && value != null && Convert.ToSingle(value, CultureInfo.InvariantCulture) != 0f) ? Convert.ToSingle(value, CultureInfo.InvariantCulture) : 1f); val = Math.Min(4f, Math.Max(0.25f, val)); float? lengthScale = ((val == 1f) ? ((float?)null) : new float?(item2.LengthScale / val)); Stopwatch stopwatch = Stopwatch.StartNew(); byte[] array; lock (s_speaking) { array = item2.Wav(text4, lengthScale); } double num = (double)(array.Length - 44) / (2.0 * (double)item2.SampleRate); Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}: {1} letters, {2:0.0} s of speech in {3:0.00} s", item, text4.Length, num, stopwatch.Elapsed.TotalSeconds)); return (Code: 200, Content: array, Type: "audio/wav"); } catch (KeyNotFoundException ex3) { return Fail(500, ex3.Message); } catch (Exception ex4) { return Fail(500, "Piper could not say that: " + ex4.Message); } } private static string Field(Dictionary<string, object> request, string name) { if (!request.TryGetValue(name, out object value) || value == null) { return ""; } return Convert.ToString(value, CultureInfo.InvariantCulture) ?? ""; } private static (int, byte[], string) Json(int code, object value) { return (code, Encoding.UTF8.GetBytes(s_json.Serialize(value)), "application/json"); } private static (int, byte[], string) Fail(int code, string message) { Console.WriteLine($" error {code}: {message}"); return Json(code, new Dictionary<string, object> { ["error"] = new Dictionary<string, object> { ["message"] = message } }); } private static string Reason(int code) { return code switch { 200 => "OK", 400 => "Bad Request", 404 => "Not Found", 501 => "Not Implemented", _ => "Internal Server Error", }; } private static (string? Method, string Target, Dictionary<string, string> Headers) ReadHead(NetworkStream stream) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); List<byte> list = new List<byte>(); while (list.Count < 65536) { int num = stream.ReadByte(); if (num < 0) { return (Method: null, Target: "", Headers: dictionary); } list.Add((byte)num); int count = list.Count; if (count >= 4 && list[count - 4] == 13 && list[count - 3] == 10 && list[count - 2] == 13 && list[count - 1] == 10) { break; } } string[] array = Encoding.ASCII.GetString(list.ToArray()).Split(new string[1] { "\r\n" }, StringSplitOptions.None); string[] array2 = array[0].Split(new char[1] { ' ' }); if (array2.Length < 2) { return (Method: null, Target: "", Headers: dictionary); } foreach (string item in array.Skip(1)) { int num2 = item.IndexOf(':'); if (num2 > 0) { dictionary[item.Substring(0, num2).Trim()] = item.Substring(num2 + 1).Trim(); } } return (Method: array2[0].ToUpperInvariant(), Target: array2[1], Headers: dictionary); } private static byte[] ReadExactly(NetworkStream stream, int size) { byte[] array = new byte[size]; int num; for (int i = 0; i < size; i += num) { num = stream.Read(array, i, size - i); if (num <= 0) { throw new IOException("The connection closed before the whole request came."); } } return array; } private static void Write(NetworkStream stream, byte[] bytes) { stream.Write(bytes, 0, bytes.Length); } } }
plugins/BingBongHelper/Microsoft.ML.OnnxRuntime.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.ML.OnnxRuntime.CompileApi; using Microsoft.ML.OnnxRuntime.Tensors; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.ML.OnnxRuntime.Tests.Common, PublicKey=002400000480000094000000060200000024000052534131000400000100010059013e94e4bc70136ca4c35f33acd6b62974536b698f9c7a21cee18d805c7ad860ad9eebfdc47a96ba2f8d03f4cf1c36b9d30787e276c7b9833b5bf2a6eba7e919e6b90083078a352262aed1d842e5f70a3085cbcf4c56ae851b161137920961c23fcc246598d61d258ccc615c927b2441359eea666a99ce1c3c07dca18fb0e1")] [assembly: InternalsVisibleTo("Microsoft.ML.OnnxRuntime.Tests.NetCoreApp, PublicKey=002400000480000094000000060200000024000052534131000400000100010059013e94e4bc70136ca4c35f33acd6b62974536b698f9c7a21cee18d805c7ad860ad9eebfdc47a96ba2f8d03f4cf1c36b9d30787e276c7b9833b5bf2a6eba7e919e6b90083078a352262aed1d842e5f70a3085cbcf4c56ae851b161137920961c23fcc246598d61d258ccc615c927b2441359eea666a99ce1c3c07dca18fb0e1")] [assembly: InternalsVisibleTo("Microsoft.ML.OnnxRuntime.Tests.MAUI, PublicKey=002400000480000094000000060200000024000052534131000400000100010059013e94e4bc70136ca4c35f33acd6b62974536b698f9c7a21cee18d805c7ad860ad9eebfdc47a96ba2f8d03f4cf1c36b9d30787e276c7b9833b5bf2a6eba7e919e6b90083078a352262aed1d842e5f70a3085cbcf4c56ae851b161137920961c23fcc246598d61d258ccc615c927b2441359eea666a99ce1c3c07dca18fb0e1")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyConfiguration("RelWithDebInfo")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("This package contains ONNX Runtime for .Net platforms")] [assembly: AssemblyFileVersion("1.31.0.0")] [assembly: AssemblyInformationalVersion("1.31.0+402979ac1bef89dcd55add41eaa7277c407599eb")] [assembly: AssemblyProduct("Microsoft.ML.OnnxRuntime")] [assembly: AssemblyTitle("Microsoft.ML.OnnxRuntime C# Bindings")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/microsoft/onnxruntime")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.31.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } [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 Microsoft.ML.OnnxRuntime { [Flags] public enum OrtCompileApiFlags : uint { NONE = 0u, ERROR_IF_NO_NODES_COMPILED = 1u, ERROR_IF_OUTPUT_FILE_EXISTS = 2u } public class OrtModelCompilationOptions : IDisposable { public delegate void WriteEpContextDataDelegate(string name, OrtEpContextData data); public delegate void WriteBufferToDestinationDelegate(ReadOnlySpan<byte> buffer); public delegate OrtExternalInitializerInfo GetInitializerLocationDelegate(string initializerName, IReadOnlyOrtValue initializerValue, IReadOnlyExternalInitializerInfo originalInitializerLocation); private sealed class EpContextDataWriteConnector { private readonly WriteEpContextDataDelegate _writeDelegate; internal EpContextDataWriteConnector(WriteEpContextDataDelegate writeDelegate) { _writeDelegate = writeDelegate; } internal static IntPtr WriteEpContextDataDelegateWrapper(IntPtr state, IntPtr name, IntPtr buffer, UIntPtr bufferSize) { try { EpContextDataWriteConnector epContextDataWriteConnector = (EpContextDataWriteConnector)GCHandle.FromIntPtr(state).Target; string name2 = NativeOnnxValueHelper.StringFromNativeUtf8(name); OrtEpContextData ortEpContextData = new OrtEpContextData(buffer, bufferSize); try { epContextDataWriteConnector._writeDelegate(name2, ortEpContextData); } finally { ortEpContextData.Invalidate(); } return IntPtr.Zero; } catch (Exception ex) { string s = "The C# EPContext data write delegate threw an exception: " + ex.Message; return NativeMethods.OrtCreateStatus(1u, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(s)); } } } private sealed class EpContextDataWriteRegistration : IDisposable { private EpContextDataWriteConnector _connector; private Microsoft.ML.OnnxRuntime.CompileApi.NativeMethods.DOrtWriteNamedBufferDelegate _nativeDelegate; private GCHandle _connectorHandle; private int _referenceCount = 1; private int _ownerReleased; internal IntPtr FunctionPointer { get; } internal IntPtr State { get; } internal EpContextDataWriteRegistration(WriteEpContextDataDelegate writeDelegate) { _connector = new EpContextDataWriteConnector(writeDelegate); _nativeDelegate = EpContextDataWriteConnector.WriteEpContextDataDelegateWrapper; _connectorHandle = GCHandle.Alloc(_connector); try { FunctionPointer = Marshal.GetFunctionPointerForDelegate(_nativeDelegate); State = GCHandle.ToIntPtr(_connectorHandle); } catch { _connectorHandle.Free(); throw; } } internal void Release() { if (Interlocked.Decrement(ref _referenceCount) == 0) { if (_connectorHandle.IsAllocated) { _connectorHandle.Free(); } _connector = null; _nativeDelegate = null; } } public void Dispose() { if (Interlocked.Exchange(ref _ownerReleased, 1) == 0) { Release(); } GC.SuppressFinalize(this); } ~EpContextDataWriteRegistration() { if (Interlocked.Exchange(ref _ownerReleased, 1) == 0) { Release(); } } } private class WriteBufferToDestinationConnector { private readonly WriteBufferToDestinationDelegate _userDelegate; internal WriteBufferToDestinationConnector(WriteBufferToDestinationDelegate writeBufferDelegate) { _userDelegate = writeBufferDelegate; } public unsafe static IntPtr WriteBufferToDestinationDelegateWrapper(IntPtr state, IntPtr buffer, UIntPtr bufferNumBytes) { try { WriteBufferToDestinationConnector obj = (WriteBufferToDestinationConnector)GCHandle.FromIntPtr(state).Target; ReadOnlySpan<byte> buffer2 = new ReadOnlySpan<byte>(buffer.ToPointer(), checked((int)(uint)bufferNumBytes)); obj._userDelegate(buffer2); } catch (Exception ex) { string s = "The C# WriteBufferToDestination delegate threw an exception: " + ex.Message; return NativeMethods.OrtCreateStatus(1u, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(s)); } return IntPtr.Zero; } } private class GetInitializerLocationConnector { private readonly GetInitializerLocationDelegate _userDelegate; internal GetInitializerLocationConnector(GetInitializerLocationDelegate getInitializerLocationDelegate) { _userDelegate = getInitializerLocationDelegate; } public static IntPtr GetInitializerLocationDelegateWrapper(IntPtr state, IntPtr initializerName, IntPtr initializerValue, IntPtr originalInitializerLocation, out IntPtr newInitializerLocationOutput) { newInitializerLocationOutput = IntPtr.Zero; try { GetInitializerLocationConnector obj = (GetInitializerLocationConnector)GCHandle.FromIntPtr(state).Target; string initializerName2 = NativeOnnxValueHelper.StringFromNativeUtf8(initializerName); IReadOnlyOrtValue initializerValue2 = new OrtValue(initializerValue, owned: false); IReadOnlyExternalInitializerInfo originalInitializerLocation2 = null; if (originalInitializerLocation != IntPtr.Zero) { originalInitializerLocation2 = new OrtExternalInitializerInfo(originalInitializerLocation); } OrtExternalInitializerInfo ortExternalInitializerInfo = obj._userDelegate(initializerName2, initializerValue2, originalInitializerLocation2); if (ortExternalInitializerInfo != null) { byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(ortExternalInitializerInfo.GetFilePath()); IntPtr intPtr = NativeMethods.OrtCreateExternalInitializerInfo(platformSerializedString, ortExternalInitializerInfo.GetFileOffset(), (UIntPtr)(ulong)ortExternalInitializerInfo.GetByteSize(), out newInitializerLocationOutput); if (intPtr != IntPtr.Zero) { return intPtr; } } else { newInitializerLocationOutput = IntPtr.Zero; } } catch (Exception ex) { string s = "The C# GetInitializerLocation delegate threw an exception: " + ex.Message; return NativeMethods.OrtCreateStatus(1u, NativeOnnxValueHelper.StringToZeroTerminatedUtf8(s)); } return IntPtr.Zero; } } private class DelegateResources<Connector, Delegate> : IDisposable where Connector : class where Delegate : class { private Connector _connector; private Delegate _delegate; private GCHandle _connectorHandle; private GCHandle _delegateHandle; private bool _disposed; public DelegateResources(Connector connector, Delegate @delegate) { _connector = connector; _delegate = @delegate; _connectorHandle = GCHandle.Alloc(_connector); _delegateHandle = GCHandle.Alloc(_delegate); } internal IntPtr GetFunctionPointerForDelegate() { return Marshal.GetFunctionPointerForDelegate(_delegate); } internal IntPtr GetConnectorHandleAsPointer() { return GCHandle.ToIntPtr(_connectorHandle); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (_connectorHandle.IsAllocated) { _connectorHandle.Free(); _connector = null; } if (_delegateHandle.IsAllocated) { _delegateHandle.Free(); _delegate = null; } _disposed = true; } } ~DelegateResources() { Dispose(disposing: false); } } private IntPtr _handle; private bool _disposed; private SessionOptions.EpContextDataReadRegistration _epContextDataReadRegistration; private DelegateResources<WriteBufferToDestinationConnector, NativeMethods.DOrtWriteBufferToDestinationDelegate> _writeBufferToDestinationDelegateState; private readonly object _epContextDataWriteRegistrationLock = new object(); private EpContextDataWriteRegistration _epContextDataWriteRegistration; private int _activeCompileCount; private bool _epContextDataWriteRegistrationUpdatePending; private readonly List<EpContextDataWriteRegistration> _retiredEpContextDataWriteRegistrations = new List<EpContextDataWriteRegistration>(); private DelegateResources<GetInitializerLocationConnector, NativeMethods.DOrtGetInitializerLocationDelegate> _getInitializerLocationDelegateState; public OrtModelCompilationOptions(SessionOptions sessionOptions) { _epContextDataReadRegistration = sessionOptions.InvokeWithEpContextDataReadRegistration(delegate(IntPtr sessionOptionsHandle) { NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtCreateModelCompilationOptionsFromSessionOptions(OrtEnv.Instance().Handle, sessionOptionsHandle, out _handle)); }); } public void CompileModel() { lock (_epContextDataWriteRegistrationLock) { if (_activeCompileCount == 0) { ApplyPendingEpContextDataWriteRegistration(); } _activeCompileCount++; } try { NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtCompileModel(OrtEnv.Instance().Handle, _handle)); } finally { lock (_epContextDataWriteRegistrationLock) { if (--_activeCompileCount == 0) { ApplyPendingEpContextDataWriteRegistration(); } } GC.KeepAlive(this); } } public void SetInputModelPath(string path) { byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(path); NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetInputModelPath(_handle, platformSerializedString)); } public void SetInputModelFromBuffer(byte[] buffer) { NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetInputModelFromBuffer(_handle, buffer, (UIntPtr)(ulong)buffer.Length)); } public void SetOutputModelPath(string path) { byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(path); NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelPath(_handle, platformSerializedString)); } public void SetOutputModelExternalInitializersFile(string filePath, ulong threshold) { byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(filePath); NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelExternalInitializersFile(_handle, platformSerializedString, new UIntPtr(threshold))); } internal void SetOutputModelBuffer(OrtAllocator allocator, ref IntPtr outputModelBufferPtr, ref UIntPtr outputModelBufferSizePtr) { NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelBuffer(_handle, allocator.Pointer, ref outputModelBufferPtr, ref outputModelBufferSizePtr)); } public void SetEpContextEmbedMode(bool embed) { NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextEmbedMode(_handle, embed)); } public void SetFlags(OrtCompileApiFlags flags) { NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetFlags(_handle, (uint)flags)); } public void SetEpContextBinaryInformation(string outputDirectory, string modelName) { byte[] platformSerializedString = NativeOnnxValueHelper.GetPlatformSerializedString(outputDirectory); byte[] platformSerializedString2 = NativeOnnxValueHelper.GetPlatformSerializedString(modelName); NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextBinaryInformation(_handle, platformSerializedString, platformSerializedString2)); } public void SetGraphOptimizationLevel(GraphOptimizationLevel graphOptimizationLevel) { NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetGraphOptimizationLevel(_handle, graphOptimizationLevel)); } public void SetEpContextDataWriteDelegate(WriteEpContextDataDelegate writeDelegate) { if (writeDelegate == null) { throw new ArgumentNullException("writeDelegate"); } EpContextDataWriteRegistration epContextDataWriteRegistration = new EpContextDataWriteRegistration(writeDelegate); try { lock (_epContextDataWriteRegistrationLock) { if (_activeCompileCount > 0) { EpContextDataWriteRegistration epContextDataWriteRegistration2 = _epContextDataWriteRegistration; _epContextDataWriteRegistration = epContextDataWriteRegistration; RetireEpContextDataWriteRegistration(epContextDataWriteRegistration2); _epContextDataWriteRegistrationUpdatePending = true; } else { ApplyPendingEpContextDataWriteRegistration(); EpContextDataWriteRegistration epContextDataWriteRegistration3 = _epContextDataWriteRegistration; NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc(_handle, epContextDataWriteRegistration.FunctionPointer, epContextDataWriteRegistration.State)); _epContextDataWriteRegistration = epContextDataWriteRegistration; RetireEpContextDataWriteRegistration(epContextDataWriteRegistration3); } } } catch { epContextDataWriteRegistration.Dispose(); throw; } } public void ClearEpContextDataWriteDelegate() { lock (_epContextDataWriteRegistrationLock) { if (_activeCompileCount > 0) { EpContextDataWriteRegistration epContextDataWriteRegistration = _epContextDataWriteRegistration; _epContextDataWriteRegistration = null; RetireEpContextDataWriteRegistration(epContextDataWriteRegistration); _epContextDataWriteRegistrationUpdatePending = true; } else { ApplyPendingEpContextDataWriteRegistration(); EpContextDataWriteRegistration epContextDataWriteRegistration2 = _epContextDataWriteRegistration; NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc(_handle, IntPtr.Zero, IntPtr.Zero)); _epContextDataWriteRegistration = null; RetireEpContextDataWriteRegistration(epContextDataWriteRegistration2); } } } private void ApplyPendingEpContextDataWriteRegistration() { if (!_epContextDataWriteRegistrationUpdatePending) { return; } EpContextDataWriteRegistration epContextDataWriteRegistration = _epContextDataWriteRegistration; NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetEpContextDataWriteFunc(_handle, epContextDataWriteRegistration?.FunctionPointer ?? IntPtr.Zero, epContextDataWriteRegistration?.State ?? IntPtr.Zero)); _epContextDataWriteRegistrationUpdatePending = false; foreach (EpContextDataWriteRegistration retiredEpContextDataWriteRegistration in _retiredEpContextDataWriteRegistrations) { retiredEpContextDataWriteRegistration.Dispose(); } _retiredEpContextDataWriteRegistrations.Clear(); } private void RetireEpContextDataWriteRegistration(EpContextDataWriteRegistration registration) { if (registration != null) { if (_activeCompileCount > 0) { _retiredEpContextDataWriteRegistrations.Add(registration); } else { registration.Dispose(); } } } public void SetOutputModelWriteDelegate(WriteBufferToDestinationDelegate writeBufferDelegate) { _writeBufferToDestinationDelegateState?.Dispose(); _writeBufferToDestinationDelegateState = new DelegateResources<WriteBufferToDestinationConnector, NativeMethods.DOrtWriteBufferToDestinationDelegate>(new WriteBufferToDestinationConnector(writeBufferDelegate), WriteBufferToDestinationConnector.WriteBufferToDestinationDelegateWrapper); IntPtr functionPointerForDelegate = _writeBufferToDestinationDelegateState.GetFunctionPointerForDelegate(); NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelWriteFunc(_handle, functionPointerForDelegate, _writeBufferToDestinationDelegateState.GetConnectorHandleAsPointer())); } public void SetOutputModelGetInitializerLocationDelegate(GetInitializerLocationDelegate getInitializerLocationDelegate) { _getInitializerLocationDelegateState?.Dispose(); _getInitializerLocationDelegateState = new DelegateResources<GetInitializerLocationConnector, NativeMethods.DOrtGetInitializerLocationDelegate>(new GetInitializerLocationConnector(getInitializerLocationDelegate), GetInitializerLocationConnector.GetInitializerLocationDelegateWrapper); IntPtr functionPointerForDelegate = _getInitializerLocationDelegateState.GetFunctionPointerForDelegate(); NativeApiStatus.VerifySuccess(NativeMethods.CompileApi.OrtModelCompilationOptions_SetOutputModelGetInitializerLocationFunc(_handle, functionPointerForDelegate, _getInitializerLocationDelegateState.GetConnectorHandleAsPointer())); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_disposed) { return; } NativeMethods.CompileApi.OrtReleaseModelCompilationOptions(_handle); _handle = IntPtr.Zero; if (_epContextDataReadRegistration != null) { _epContextDataReadRegistration.Release(); _epContextDataReadRegistration = null; } lock (_epContextDataWriteRegistrationLock) { EpContextDataWriteRegistration epContextDataWriteRegistration = _epContextDataWriteRegistration; _epContextDataWriteRegistration = null; RetireEpContextDataWriteRegistration(epContextDataWriteRegistration); foreach (EpContextDataWriteRegistration retiredEpContextDataWriteRegistration in _retiredEpContextDataWriteRegistrations) { retiredEpContextDataWriteRegistration.Dispose(); } _retiredEpContextDataWriteRegistrations.Clear(); } if (disposing) { _writeBufferToDestinationDelegateState?.Dispose(); _getInitializerLocationDelegateState?.Dispose(); } _disposed = true; } ~OrtModelCompilationOptions() { Dispose(disposing: false); } } public interface IDisposableReadOnlyCollection<T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyList<T>, IDisposable { } internal class DisposableList<T> : List<T>, IDisposableReadOnlyCollection<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyList<T>, IDisposable where T : IDisposable { private bool _disposed; public DisposableList() { } public DisposableList(int count) : base(count) { } public DisposableList(IEnumerable<T> collection) : base(collection) { } protected virtual void Dispose(bool disposing) { if (_disposed || !disposing) { return; } for (int num = base.Count - 1; num >= 0; num--) { T val = base[num]; if (val != null) { val.Dispose(); } } Clear(); _disposed = true; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public class DisposableNamedOnnxValue : NamedOnnxValue, IDisposable { private IOrtValueOwner _ortValueHolder; private bool _disposed; public TensorElementType ElementType { get; } private DisposableNamedOnnxValue(string name, object value, TensorElementType elementType, IOrtValueOwner ortValueHolder) : base(name, value, OnnxValueType.ONNX_TYPE_TENSOR) { _ortValueHolder = ortValueHolder; ElementType = elementType; } private DisposableNamedOnnxValue(string name, object value, OnnxValueType onnxValueType, IOrtValueOwner ortValueHolder) : base(name, value, onnxValueType) { _ortValueHolder = ortValueHolder; ElementType = TensorElementType.DataTypeMax; } private DisposableNamedOnnxValue(string name, object value, MapHelper mapHelper, IOrtValueOwner ortValueHolder) : base(name, value, mapHelper) { _ortValueHolder = ortValueHolder; ElementType = TensorElementType.DataTypeMax; } internal override IntPtr InputToOrtValueHandle(NodeMetadata metadata, out IDisposable memoryHolder) { if (_ortValueHolder == null) { throw new InvalidOperationException("The instance of this class does not own an OrtValue"); } memoryHolder = null; return _ortValueHolder.Value.Handle; } internal override IntPtr OutputToOrtValueHandle(NodeMetadata metadata, out IDisposable memoryOwner) { return InputToOrtValueHandle(metadata, out memoryOwner); } internal static DisposableNamedOnnxValue CreateFromOrtValue(string name, ref OrtValue ortValue) { return CreateFromOrtValue(name, ref ortValue, OrtAllocator.DefaultInstance); } internal static DisposableNamedOnnxValue CreateFromOrtValue(string name, ref OrtValue ortValue, OrtAllocator allocator) { OnnxValueType onnxType = ortValue.OnnxType; return onnxType switch { OnnxValueType.ONNX_TYPE_TENSOR => FromNativeTensor(name, ref ortValue), OnnxValueType.ONNX_TYPE_SEQUENCE => FromNativeSequence(name, ref ortValue, allocator), OnnxValueType.ONNX_TYPE_MAP => FromNativeMap(name, ref ortValue, allocator), _ => throw new NotSupportedException($"OnnxValueType : {onnxType} is not supported"), }; } private static DisposableNamedOnnxValue FromNativeTensor(string name, ref OrtValue ortValue) { OrtTensorTypeAndShapeInfo tensorTypeAndShape = ortValue.GetTensorTypeAndShape(); switch (tensorTypeAndShape.ElementDataType) { case TensorElementType.Float: return FromNativeTensor<float>(name, ref ortValue); case TensorElementType.Double: return FromNativeTensor<double>(name, ref ortValue); case TensorElementType.Int16: return FromNativeTensor<short>(name, ref ortValue); case TensorElementType.UInt16: return FromNativeTensor<ushort>(name, ref ortValue); case TensorElementType.Int32: return FromNativeTensor<int>(name, ref ortValue); case TensorElementType.UInt32: return FromNativeTensor<uint>(name, ref ortValue); case TensorElementType.Int64: return FromNativeTensor<long>(name, ref ortValue); case TensorElementType.UInt64: return FromNativeTensor<ulong>(name, ref ortValue); case TensorElementType.UInt8: return FromNativeTensor<byte>(name, ref ortValue); case TensorElementType.Int8: return FromNativeTensor<sbyte>(name, ref ortValue); case TensorElementType.String: { int[] shape = Array.ConvertAll(tensorTypeAndShape.Shape, Convert.ToInt32); return FromNativeStringTensor(name, shape, ref ortValue); } case TensorElementType.Bool: return FromNativeTensor<bool>(name, ref ortValue); case TensorElementType.Float16: return FromNativeTensor<Float16>(name, ref ortValue); case TensorElementType.BFloat16: return FromNativeTensor<BFloat16>(name, ref ortValue); default: throw new NotSupportedException($"Tensor of element type: {tensorTypeAndShape.ElementDataType} is not supported"); } } private static DisposableNamedOnnxValue FromNativeStringTensor(string name, int[] shape, ref OrtValue ortValue) { DenseTensor<string> value = new DenseTensor<string>(ortValue.GetStringTensorAsArray(), shape); DisposableNamedOnnxValue result = new DisposableNamedOnnxValue(name, value, TensorElementType.String, ortValue); ortValue = null; return result; } private static DisposableNamedOnnxValue FromNativeTensor<T>(string name, ref OrtValue ortValue) { OrtValueTensor<T> ortValueTensor = new OrtValueTensor<T>(ref ortValue); try { DenseTensor<T> value = new DenseTensor<T>(ortValueTensor.Memory, ortValueTensor.Dimensions); return new DisposableNamedOnnxValue(name, value, ortValueTensor.ElementType, ortValueTensor); } catch (Exception) { ortValueTensor.Dispose(); throw; } } private static DisposableNamedOnnxValue FromNativeSequence(string name, ref OrtValue ortValueSequence, OrtAllocator allocator) { int valueCount = ortValueSequence.GetValueCount(); DisposableList<DisposableNamedOnnxValue> disposableList = new DisposableList<DisposableNamedOnnxValue>(valueCount); try { for (int i = 0; i < valueCount; i++) { OrtValue ortValue = ortValueSequence.GetValue(i, allocator); try { disposableList.Add(CreateFromOrtValue(string.Empty, ref ortValue, allocator)); } finally { ortValue?.Dispose(); } } NativeOrtValueCollectionOwner ortValueHolder = new NativeOrtValueCollectionOwner(ref ortValueSequence, disposableList); return new DisposableNamedOnnxValue(name, disposableList, OnnxValueType.ONNX_TYPE_SEQUENCE, ortValueHolder); } catch (Exception) { disposableList.Dispose(); throw; } } private static DisposableNamedOnnxValue FromNativeMap(string name, ref OrtValue ortValueMap, OrtAllocator allocator) { DisposableNamedOnnxValue result = null; Span<OrtValue> disposables = new OrtValue[2]; DisposableArray<OrtValue> disposableArray = new DisposableArray<OrtValue>(disposables); try { disposables[0] = ortValueMap.GetValue(0, allocator); disposables[1] = ortValueMap.GetValue(1, allocator); OrtTensorTypeAndShapeInfo tensorTypeAndShape = disposables[0].GetTensorTypeAndShape(); OrtTensorTypeAndShapeInfo tensorTypeAndShape2 = disposables[1].GetTensorTypeAndShape(); int[] keysShape = Array.ConvertAll(tensorTypeAndShape.Shape, Convert.ToInt32); int[] valsShape = Array.ConvertAll(tensorTypeAndShape2.Shape, Convert.ToInt32); result = tensorTypeAndShape.ElementDataType switch { TensorElementType.Int64 => tensorTypeAndShape2.ElementDataType switch { TensorElementType.Float => FromNativeMapElements<long, float>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), TensorElementType.Double => FromNativeMapElements<long, double>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), TensorElementType.Int64 => FromNativeMapElements<long, long>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), TensorElementType.String => FromNativeMapElements<long, string>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), _ => throw new NotSupportedException($"Map value type: {tensorTypeAndShape2.ElementDataType} is not supported"), }, TensorElementType.String => tensorTypeAndShape2.ElementDataType switch { TensorElementType.Float => FromNativeMapElements<string, float>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), TensorElementType.Double => FromNativeMapElements<string, double>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), TensorElementType.Int64 => FromNativeMapElements<string, long>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), TensorElementType.String => FromNativeMapElements<string, string>(name, ref ortValueMap, keysShape, ref disposables[0], valsShape, ref disposables[1]), _ => throw new NotSupportedException($"Map value type: {tensorTypeAndShape2.ElementDataType} is not supported"), }, _ => throw new NotSupportedException($"Map key type: {tensorTypeAndShape.ElementDataType} is not supported"), }; } finally { disposableArray.Dispose(); } return result; } private static DisposableNamedOnnxValue FromNativeMapElements<K, V>(string name, ref OrtValue ortValueMap, int[] keysShape, ref OrtValue ortValueTensorKeys, int[] valsShape, ref OrtValue ortValueTensorValues) { if (typeof(K) == typeof(string)) { DenseTensor<string> denseTensorKeys = new DenseTensor<string>(ortValueTensorKeys.GetStringTensorAsArray(), keysShape); if (typeof(V) == typeof(string)) { DenseTensor<string> denseTensorValues = new DenseTensor<string>(ortValueTensorValues.GetStringTensorAsArray(), valsShape); Dictionary<string, string> value = Enumerable.Range(0, (int)denseTensorKeys.Length).ToDictionary((int i) => denseTensorKeys[new int[1] { i }], (int i) => denseTensorValues[new int[1] { i }]); MapHelper mapHelper = new MapHelper(denseTensorKeys, denseTensorValues); DisposableNamedOnnxValue result = new DisposableNamedOnnxValue(name, value, mapHelper, ortValueMap); ortValueMap = null; return result; } OrtValueTensor<V> ortValueTensor = new OrtValueTensor<V>(ref ortValueTensorValues); try { DenseTensor<V> values = new DenseTensor<V>(ortValueTensor.Memory, ortValueTensor.Dimensions); return FromMapDenseTensors(name, ref ortValueMap, denseTensorKeys, values, ortValueTensor); } catch (Exception) { ortValueTensor.Dispose(); throw; } } DisposableList<IDisposable> disposableList = new DisposableList<IDisposable>(2); try { OrtValueTensor<K> ortValueTensor2 = new OrtValueTensor<K>(ref ortValueTensorKeys); disposableList.Add(ortValueTensor2); DenseTensor<K> keys = new DenseTensor<K>(ortValueTensor2.Memory, ortValueTensor2.Dimensions); if (typeof(V) == typeof(string)) { DenseTensor<string> values2 = new DenseTensor<string>(ortValueTensorValues.GetStringTensorAsArray(), valsShape); return FromMapDenseTensors(name, ref ortValueMap, keys, values2, disposableList); } OrtValueTensor<V> ortValueTensor3 = new OrtValueTensor<V>(ref ortValueTensorValues); disposableList.Add(ortValueTensor3); DenseTensor<V> values3 = new DenseTensor<V>(ortValueTensor3.Memory, ortValueTensor3.Dimensions); return FromMapDenseTensors(name, ref ortValueMap, keys, values3, disposableList); } catch (Exception) { disposableList.Dispose(); throw; } } private static DisposableNamedOnnxValue FromMapDenseTensors<K, V>(string name, ref OrtValue ortValueMap, DenseTensor<K> keys, DenseTensor<V> values, IDisposable disposables) { Dictionary<K, V> value = Enumerable.Range(0, (int)keys.Length).ToDictionary((int i) => keys[new int[1] { i }], (int i) => values[new int[1] { i }]); MapHelper mapHelper = new MapHelper(keys, values); NativeOrtValueCollectionOwner ortValueHolder = new NativeOrtValueCollectionOwner(ref ortValueMap, disposables); return new DisposableNamedOnnxValue(name, value, mapHelper, ortValueHolder); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing && _ortValueHolder != null) { _ortValueHolder.Dispose(); _ortValueHolder = null; } _disposed = true; } } public void Dispose() { Dispose(disposing: true); } } public sealed class OrtEpContextData { private IntPtr _pointer; private bool _isValid; public ulong Size { get; } internal OrtEpContextData(IntPtr pointer, UIntPtr size) { _pointer = pointer; Size = size.ToUInt64(); _isValid = true; } public ReadOnlySpan<byte> GetSpan() { ThrowIfInvalid(); if (Size > int.MaxValue) { throw new InvalidOperationException("EPContext data is too large for a single Span<byte>. Read it in chunks."); } return GetSpan(0uL, checked((int)Size)); } public unsafe ReadOnlySpan<byte> GetSpan(ulong offset, int length) { ThrowIfInvalid(); ValidateRange(offset, length); if (length == 0) { return ReadOnlySpan<byte>.Empty; } return new ReadOnlySpan<byte>(AddOffset(_pointer, offset).ToPointer(), length); } internal void Invalidate() { _isValid = false; _pointer = IntPtr.Zero; } internal static IntPtr AddOffset(IntPtr pointer, ulong offset) { if (UIntPtr.Size == 4) { ulong num = (uint)pointer.ToInt32(); if (offset > uint.MaxValue || num + offset > uint.MaxValue) { throw new ArgumentOutOfRangeException("offset"); } return new IntPtr((int)(num + offset)); } ulong num2 = (ulong)pointer.ToInt64(); if (offset > (ulong)(-1L - (long)num2)) { throw new ArgumentOutOfRangeException("offset"); } return new IntPtr((long)(num2 + offset)); } private void ThrowIfInvalid() { if (!_isValid) { throw new ObjectDisposedException("OrtEpContextData", "EPContext data is valid only during the write delegate invocation."); } } private void ValidateRange(ulong offset, int length) { if (length < 0 || offset > Size || (ulong)length > Size - offset) { throw new ArgumentOutOfRangeException("length"); } if (length != 0 && _pointer == IntPtr.Zero) { throw new InvalidOperationException("EPContext data has a null buffer for a non-empty range."); } } } public sealed class OrtEpContextDataBuffer : IDisposable { private OrtAllocator _allocator; private readonly ulong _maxDataSize; private IntPtr _pointer; private bool _disposed; public ulong Size { get; private set; } public bool IsAllocated { get; private set; } internal OrtEpContextDataBuffer(IntPtr allocator, ulong maxDataSize) { _allocator = new OrtAllocator(allocator, owned: false); _maxDataSize = maxDataSize; try { using OrtMemoryInfo memoryInfo = _allocator.Info; EnsureCpuAccessibleAllocator(memoryInfo); } catch { _allocator.Dispose(); throw; } } internal static void EnsureCpuAccessibleAllocator(OrtMemoryInfo memoryInfo) { if (memoryInfo.GetDeviceType() != OrtMemoryInfoDeviceType.CPU && memoryInfo.GetDeviceMemoryType() != OrtDeviceMemoryType.HOST_ACCESSIBLE) { throw new InvalidOperationException("EPContext read callbacks require a CPU or host-accessible allocator."); } } public Span<byte> Allocate(int size) { if (size < 0) { throw new ArgumentOutOfRangeException("size"); } Allocate((ulong)size); return GetSpan(); } public void Allocate(ulong size) { ThrowIfDisposed(); if (IsAllocated) { throw new InvalidOperationException("The EPContext data buffer has already been allocated."); } if (size > _maxDataSize) { throw new ArgumentOutOfRangeException("size", "EPContext data exceeds the configured maximum size."); } UIntPtr size2 = ToUIntPtr(size); IntPtr p = IntPtr.Zero; if (size != 0L) { NativeApiStatus.VerifySuccess(NativeMethods.OrtAllocatorAlloc(_allocator.Pointer, size2, out p)); if (p == IntPtr.Zero) { throw new InvalidOperationException("The ORT allocator returned a null pointer for a non-empty allocation."); } } _pointer = p; Size = size; IsAllocated = true; } public Span<byte> GetSpan() { if (Size > int.MaxValue) { throw new InvalidOperationException("EPContext data is too large for a single Span<byte>. Fill it in chunks."); } return GetSpan(0uL, checked((int)Size)); } public unsafe Span<byte> GetSpan(ulong offset, int length) { ThrowIfDisposed(); if (!IsAllocated) { throw new InvalidOperationException("Allocate must be called before accessing the EPContext data buffer."); } if (length < 0 || offset > Size || (ulong)length > Size - offset) { throw new ArgumentOutOfRangeException("length"); } if (length == 0) { return Span<byte>.Empty; } return new Span<byte>(OrtEpContextData.AddOffset(_pointer, offset).ToPointer(), length); } internal void Detach(out IntPtr pointer, out UIntPtr size) { ThrowIfDisposed(); if (!IsAllocated) { throw new InvalidOperationException("The EPContext data read delegate must allocate its output buffer."); } pointer = _pointer; size = ToUIntPtr(Size); _pointer = IntPtr.Zero; _disposed = true; _allocator.Dispose(); _allocator = null; } public void Dispose() { if (!_disposed) { if (_pointer != IntPtr.Zero) { _allocator.FreeMemory(_pointer); _pointer = IntPtr.Zero; } _allocator.Dispose(); _allocator = null; _disposed = true; GC.SuppressFinalize(this); } } private static UIntPtr ToUIntPtr(ulong value) { if (UIntPtr.Size == 4 && value > uint.MaxValue) { throw new ArgumentOutOfRangeException("value"); } return new UIntPtr(value); } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException("OrtEpContextDataBuffer"); } } } internal enum ErrorCode { Ok, Fail, InvalidArgument, NoSuchFile, NoModel, EngineError, RuntimeException, InvalidProtobuf, ModelLoaded, NotImplemented, InvalidGraph, ShapeInferenceNotRegistered, RequirementNotRegistered } public class OnnxRuntimeException : Exception { private static Dictionary<ErrorCode, string> errorCodeToString = new Dictionary<ErrorCode, string> { { ErrorCode.Ok, "Ok" }, { ErrorCode.Fail, "Fail" }, { ErrorCode.InvalidArgument, "InvalidArgument" }, { ErrorCode.NoSuchFile, "NoSuchFile" }, { ErrorCode.NoModel, "NoModel" }, { ErrorCode.EngineError, "EngineError" }, { ErrorCode.RuntimeException, "RuntimeException" }, { ErrorCode.InvalidProtobuf, "InvalidProtobuf" }, { ErrorCode.ModelLoaded, "ModelLoaded" }, { ErrorCode.NotImplemented, "NotImplemented" }, { ErrorCode.InvalidGraph, "InvalidGraph" }, { ErrorCode.ShapeInferenceNotRegistered, "ShapeInferenceNotRegistered" }, { ErrorCode.RequirementNotRegistered, "RequirementNotRegistered" } }; internal OnnxRuntimeException(ErrorCode errorCode, string message) : base("[ErrorCode:" + errorCodeToString[errorCode] + "] " + message) { } } public class FixedBufferOnnxValue : IDisposable { private bool _disposed; internal OrtValue Value { get; private set; } internal OnnxValueType OnnxValueType { get; private set; } internal TensorElementType ElementType { get; private set; } private FixedBufferOnnxValue(ref OrtValue ortValue, OnnxValueType onnxValueType, TensorElementType elementType) { Value = ortValue; ortValue = null; OnnxValueType = onnxValueType; ElementType = elementType; } public static FixedBufferOnnxValue CreateFromTensor<T>(Tensor<T> value) { TensorElementType elementType; OrtValue ortValue = OrtValue.CreateFromTensorObject(value, out elementType); return new FixedBufferOnnxValue(ref ortValue, OnnxValueType.ONNX_TYPE_TENSOR, elementType); } public static FixedBufferOnnxValue CreateFromMemory<T>(OrtMemoryInfo memoryInfo, Memory<T> memory, TensorElementType elementType, long[] shape, long bytesSize) where T : unmanaged { if (elementType == TensorElementType.String) { throw new ArgumentException("String data type is not supported"); } OrtValue ortValue = OrtValue.CreateTensorValueFromMemory(memoryInfo, memory, shape); try { return new FixedBufferOnnxValue(ref ortValue, OnnxValueType.ONNX_TYPE_TENSOR, elementType); } catch (Exception) { ortValue?.Dispose(); throw; } } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { Value.Dispose(); } _disposed = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public class InferenceSession : IDisposable { private delegate string NameExtractor<in TInput>(TInput input); private delegate IntPtr OrtValueHandleExtractor(NamedOnnxValue value, NodeMetadata metadata, out IDisposable memOwner); private delegate NodeMetadata MetadataLookup(string nodeName); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void OrtCallbackDelegate(IntPtr userData, IntPtr[] outputs, uint numOutputs, IntPtr status); private delegate void UserCallbackDelegate(IReadOnlyCollection<OrtValue> outputs, IntPtr status); private class CallbackHost : IDisposable { private GCHandle rawInputNamesHandle; private GCHandle rawInputValuesHandle; private GCHandle rawOutputNamesHandle; private GCHandle rawOutputValuesHandle; public InferenceSession session { get; } public RunOptions options { get; } public IReadOnlyCollection<string> inputNames { get; } public IReadOnlyCollection<OrtValue> inputValues { get; } public IReadOnlyCollection<string> outputNames { get; } public IReadOnlyCollection<OrtValue> outputValues { get; } public UserCallbackDelegate callback { get; } public IntPtr[] rawInputNames { get; } public IntPtr[] rawInputValues { get; } public IntPtr[] rawOutputNames { get; } public IntPtr[] rawOutputValues { get; } public IntPtr rawInputNamesPointer => GetPinnedPointer(rawInputNamesHandle); public IntPtr rawInputValuesPointer => GetPinnedPointer(rawInputValuesHandle); public IntPtr rawOutputNamesPointer => GetPinnedPointer(rawOutputNamesHandle); public IntPtr rawOutputValuesPointer => GetPinnedPointer(rawOutputValuesHandle); public CallbackHost(InferenceSession session, RunOptions options, IReadOnlyCollection<string> cbInputNames, IReadOnlyCollection<OrtValue> cbinputValues, IReadOnlyCollection<string> cbOutputNames, IReadOnlyCollection<OrtValue> cbOutputValues, UserCallbackDelegate userCallback) { this.session = session; this.options = options; inputNames = cbInputNames; inputValues = cbinputValues; outputNames = cbOutputNames; outputValues = cbOutputValues; callback = userCallback; rawInputNames = LookupUtf8Names(inputNames, (string n) => n, session.LookupInputMetadata); rawInputValues = inputValues.Select((OrtValue v) => v.Handle).ToArray(); rawOutputNames = LookupUtf8Names(outputNames, (string n) => n, session.LookupOutputMetadata); rawOutputValues = outputValues.Select((OrtValue v) => v.Handle).ToArray(); try { rawInputNamesHandle = PinArray(rawInputNames); rawInputValuesHandle = PinArray(rawInputValues); rawOutputNamesHandle = PinArray(rawOutputNames); rawOutputValuesHandle = PinArray(rawOutputValues); } catch { Dispose(); throw; } } public void Dispose() { FreeHandle(ref rawInputNamesHandle); FreeHandle(ref rawInputValuesHandle); FreeHandle(ref rawOutputNamesHandle); FreeHandle(ref rawOutputValuesHandle); } private static GCHandle PinArray(IntPtr[] array) { if (array.Length != 0) { return GCHandle.Alloc(array, GCHandleType.Pinned); } return default(GCHandle); } private static IntPtr GetPinnedPointer(GCHandle handle) { if (!handle.IsAllocated) { return IntPtr.Zero; } return handle.AddrOfPinnedObject(); } private static void FreeHandle(ref GCHandle handle) { if (handle.IsAllocated) { handle.Free(); } } } private IntPtr _nativeHandle; private Dictionary<string, NodeMetadata> _inputMetadata; private List<string> _inputNames; private Dictionary<string, NodeMetadata> _outputMetadata; private List<string> _outputNames; private Dictionary<string, NodeMetadata> _overridableInitializerMetadata; private List<IntPtr> _namesMemoryPtrs; private SessionOptions _builtInSessionOptions; private SessionOptions.EpContextDataReadRegistration _epContextDataReadRegistration; private RunOptions _builtInRunOptions; private ModelMetadata _modelMetadata; private bool _disposed; private ulong _profilingStartTimeNs; private static OrtCallbackDelegate ortCallback = OrtCallback; public IReadOnlyDictionary<string, NodeMetadata> InputMetadata => _inputMetadata; public IReadOnlyList<string> InputNames => _inputNames; public IReadOnlyDictionary<string, NodeMetadata> OutputMetadata => _outputMetadata; public IReadOnlyList<string> OutputNames => _outputNames; public IReadOnlyDictionary<string, NodeMetadata> OverridableInitializerMetadata => _overridableInitializerMetadata; public ModelMetadata ModelMetadata { get { if (_modelMetadata != null) { return _modelMetadata; } _modelMetadata = new ModelMetadata(this); return _modelMetadata; } } public ulong ProfilingStartTimeNs => _profilingStartTimeNs; internal IntPtr Handle => _nativeHandle; public InferenceSession(string modelPath) { _builtInSessionOptions = new SessionOptions(); Init(modelPath, _builtInSessionOptions); } public InferenceSession(string modelPath, PrePackedWeightsContainer prepackedWeightsContainer) { _builtInSessionOptions = new SessionOptions(); Init(modelPath, _builtInSessionOptions, prepackedWeightsContainer); } public InferenceSession(string modelPath, SessionOptions options) { Init(modelPath, options); } public InferenceSession(string modelPath, SessionOptions options, PrePackedWeightsContainer prepackedWeightsContainer) { Init(modelPath, options, prepackedWeightsContainer); } public InferenceSession(byte[] model) { _builtInSessionOptions = new SessionOptions(); Init(model, _builtInSessionOptions); } public InferenceSession(byte[] model, PrePackedWeightsContainer prepackedWeightsContainer) { _builtInSessionOptions = new SessionOptions(); Init(model, _builtInSessionOptions, prepackedWeightsContainer); } public InferenceSession(byte[] model, SessionOptions options) { Init(model, options); } public InferenceSession(byte[] model, SessionOptions options, PrePackedWeightsContainer prepackedWeightsContainer) { Init(model, options, prepackedWeightsContainer); } public IDisposableReadOnlyCollection<OrtMemoryInfo> GetMemoryInfosForInputs() { NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputCount(_nativeHandle, out var count)); if (count == UIntPtr.Zero) { return new DisposableList<OrtMemoryInfo>(); } IntPtr[] array = new IntPtr[(ulong)count]; NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetMemoryInfoForInputs(_nativeHandle, array, count)); return new DisposableList<OrtMemoryInfo>(array.Select((IntPtr ptr) => new OrtMemoryInfo(ptr, owned: false))); } public IDisposableReadOnlyCollection<OrtMemoryInfo> GetMemoryInfosForOutputs() { NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOutputCount(_nativeHandle, out var count)); if (count == UIntPtr.Zero) { return new DisposableList<OrtMemoryInfo>(); } IntPtr[] array = new IntPtr[(ulong)count]; NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetMemoryInfoForOutputs(_nativeHandle, array, count)); return new DisposableList<OrtMemoryInfo>(array.Select((IntPtr ptr) => new OrtMemoryInfo(ptr, owned: false))); } public IReadOnlyList<OrtEpDevice> GetEpDeviceForInputs() { NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputCount(_nativeHandle, out var count)); if (count == UIntPtr.Zero) { return Array.Empty<OrtEpDevice>(); } IntPtr[] array = new IntPtr[(ulong)count]; NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetEpDeviceForInputs(_nativeHandle, array, count)); return array.Select((IntPtr ptr) => (!(ptr == IntPtr.Zero)) ? new OrtEpDevice(ptr) : null).ToList().AsReadOnly(); } public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs) { return Run(inputs, _outputNames); } public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<string> outputNames) { return Run(inputs, outputNames, _builtInRunOptions); } public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<string> outputNames, RunOptions options) { IntPtr[] inputNames = LookupUtf8Names(inputs, (NamedOnnxValue v) => v.Name, LookupInputMetadata); IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata); DisposableArray<IDisposable> disposer; IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputs, LookupInputMetadata, ExtractOrtValueHandleForInput, out disposer); try { using DisposableOrtValueHandleArray disposableOrtValueHandleArray = RunImpl(options, inputNames, ortValuesHandles, outputNames2); return CreateDisposableResult(disposableOrtValueHandleArray.Span, outputNames); } finally { disposer.Dispose(); } } public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues) { return Run(inputNames, inputValues, _outputNames, _builtInRunOptions); } public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<string> outputNames) { return Run(inputNames, inputValues, outputNames, _builtInRunOptions); } public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<string> outputNames, RunOptions options) { if (inputNames.Count != inputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count)); } IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata); IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputValues, input: true); IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata); using DisposableOrtValueHandleArray disposableOrtValueHandleArray = RunImpl(options, inputNames2, ortValuesHandles, outputNames2); return CreateDisposableResult(disposableOrtValueHandleArray.Span, outputNames); } public void Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<FixedBufferOnnxValue> outputValues) { Run(inputNames, inputValues, outputNames, outputValues, _builtInRunOptions); } public void Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<FixedBufferOnnxValue> outputValues, RunOptions options) { if (inputNames.Count != inputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count)); } if (outputNames.Count != outputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "outputNames", outputNames.Count, "outputValues", outputValues.Count)); } IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata); IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputValues, input: true); IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata); IntPtr[] ortValuesHandles2 = GetOrtValuesHandles(outputValues, input: false); NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames2, ortValuesHandles, (UIntPtr)(ulong)inputNames.Count, outputNames2, (UIntPtr)(ulong)outputNames.Count, ortValuesHandles2)); } public void Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<NamedOnnxValue> outputs) { Run(inputs, outputs, _builtInRunOptions); } public void Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<NamedOnnxValue> outputs, RunOptions options) { IntPtr[] inputNames = LookupUtf8Names(inputs, (NamedOnnxValue i) => i.Name, LookupInputMetadata); IntPtr[] outputNames = LookupUtf8Names(outputs, (NamedOnnxValue o) => o.Name, LookupOutputMetadata); DisposableArray<IDisposable> disposer; IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputs, LookupInputMetadata, ExtractOrtValueHandleForInput, out disposer); try { DisposableArray<IDisposable> disposer2; IntPtr[] ortValuesHandles2 = GetOrtValuesHandles(outputs, LookupOutputMetadata, ExtractOrtValueHandleForOutput, out disposer2); try { NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames, ortValuesHandles, (UIntPtr)(ulong)inputs.Count, outputNames, (UIntPtr)(ulong)outputs.Count, ortValuesHandles2)); } finally { disposer2.Dispose(); } } finally { disposer.Dispose(); } } public void Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<FixedBufferOnnxValue> outputValues) { Run(inputs, outputNames, outputValues, _builtInRunOptions); } public void Run(IReadOnlyCollection<NamedOnnxValue> inputs, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<FixedBufferOnnxValue> outputValues, RunOptions options) { if (outputNames.Count != outputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "outputNames", outputNames.Count, "outputValues", outputValues.Count)); } IntPtr[] inputNames = LookupUtf8Names(inputs, (NamedOnnxValue i) => i.Name, LookupInputMetadata); IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata); IntPtr[] ortValuesHandles = GetOrtValuesHandles(outputValues, input: false); DisposableArray<IDisposable> disposer; IntPtr[] ortValuesHandles2 = GetOrtValuesHandles(inputs, LookupInputMetadata, ExtractOrtValueHandleForInput, out disposer); try { NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames, ortValuesHandles2, (UIntPtr)(ulong)inputs.Count, outputNames2, (UIntPtr)(ulong)outputNames.Count, ortValuesHandles)); } finally { disposer.Dispose(); } } public void Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<NamedOnnxValue> outputs) { Run(inputNames, inputValues, outputs, _builtInRunOptions); } public void Run(IReadOnlyCollection<string> inputNames, IReadOnlyCollection<FixedBufferOnnxValue> inputValues, IReadOnlyCollection<NamedOnnxValue> outputs, RunOptions options) { if (inputNames.Count != inputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count)); } IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata); IntPtr[] ortValuesHandles = GetOrtValuesHandles(inputValues, input: true); IntPtr[] outputNames = LookupUtf8Names(outputs, (NamedOnnxValue o) => o.Name, LookupOutputMetadata); DisposableArray<IDisposable> disposer; IntPtr[] ortValuesHandles2 = GetOrtValuesHandles(outputs, LookupOutputMetadata, ExtractOrtValueHandleForOutput, out disposer); try { NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames2, ortValuesHandles, (UIntPtr)(ulong)inputNames.Count, outputNames, (UIntPtr)(ulong)outputs.Count, ortValuesHandles2)); } finally { disposer.Dispose(); } } public IDisposableReadOnlyCollection<OrtValue> Run(RunOptions runOptions, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames) { if (inputNames.Count != inputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count)); } IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata); IntPtr[] inputValues2 = inputValues.Select((OrtValue v) => v.Handle).ToArray(); IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata); using DisposableOrtValueHandleArray disposableHandles = RunImpl(runOptions, inputNames2, inputValues2, outputNames2); return CreateDisposableResult(disposableHandles); } public IDisposableReadOnlyCollection<OrtValue> Run(RunOptions runOptions, IReadOnlyDictionary<string, OrtValue> inputs, IReadOnlyCollection<string> outputNames) { IntPtr[] array = new IntPtr[inputs.Count]; IntPtr[] array2 = new IntPtr[inputs.Count]; int num = 0; foreach (KeyValuePair<string, OrtValue> input in inputs) { array[num] = LookupInputMetadata(input.Key).ZeroTerminatedName; array2[num] = input.Value.Handle; num++; } IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata); using DisposableOrtValueHandleArray disposableHandles = RunImpl(runOptions, array, array2, outputNames2); return CreateDisposableResult(disposableHandles); } private static IDisposableReadOnlyCollection<OrtValue> CreateDisposableResult(DisposableOrtValueHandleArray disposableHandles) { DisposableList<OrtValue> disposableList = new DisposableList<OrtValue>(disposableHandles.Span.Length); try { for (int i = 0; i < disposableHandles.Span.Length; i++) { disposableList.Add(new OrtValue(disposableHandles.Span[i])); disposableHandles.Span[i] = IntPtr.Zero; } return disposableList; } catch (Exception) { disposableList.Dispose(); throw; } } public void Run(RunOptions runOptions, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<OrtValue> outputValues) { if (inputNames.Count != inputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count)); } if (outputNames.Count != outputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "outputNames", outputNames.Count, "outputValues", outputValues.Count)); } if (runOptions == null) { runOptions = _builtInRunOptions; } IntPtr[] inputNames2 = LookupUtf8Names(inputNames, (string n) => n, LookupInputMetadata); IntPtr[] inputValues2 = inputValues.Select((OrtValue v) => v.Handle).ToArray(); IntPtr[] outputNames2 = LookupUtf8Names(outputNames, (string n) => n, LookupOutputMetadata); IntPtr[] outputValues2 = outputValues.Select((OrtValue v) => v.Handle).ToArray(); NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, runOptions.Handle, inputNames2, inputValues2, (UIntPtr)(ulong)inputNames.Count, outputNames2, (UIntPtr)(ulong)outputNames.Count, outputValues2)); } public OrtIoBinding CreateIoBinding() { return new OrtIoBinding(this); } public void RunWithBinding(RunOptions runOptions, OrtIoBinding ioBinding) { NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle)); } public IDisposableReadOnlyCollection<OrtValue> RunWithBoundResults(RunOptions runOptions, OrtIoBinding ioBinding) { NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle)); return ioBinding.GetOutputValues(); } public IDisposableReadOnlyCollection<DisposableNamedOnnxValue> RunWithBindingAndNames(RunOptions runOptions, OrtIoBinding ioBinding, string[] names = null) { string[] array = names; if (array == null || names.Length == 0) { array = ioBinding.GetOutputNames(); } NativeApiStatus.VerifySuccess(NativeMethods.OrtRunWithBinding(Handle, runOptions.Handle, ioBinding.Handle)); OrtValue[] outputOrtValues = ioBinding.GetOutputOrtValues(); DisposableArray<OrtValue> disposableArray = new DisposableArray<OrtValue>(outputOrtValues); try { DisposableList<DisposableNamedOnnxValue> disposableList = new DisposableList<DisposableNamedOnnxValue>(outputOrtValues.Length); try { for (int i = 0; i < array.Length; i++) { disposableList.Add(DisposableNamedOnnxValue.CreateFromOrtValue(array[i], ref outputOrtValues[i])); } return disposableList; } catch (Exception) { disposableList.Dispose(); throw; } } finally { disposableArray.Dispose(); } } public string EndProfiling() { OrtAllocator defaultInstance = OrtAllocator.DefaultInstance; NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionEndProfiling(_nativeHandle, defaultInstance.Pointer, out var profile_file)); return NativeOnnxValueHelper.StringFromNativeUtf8(profile_file, defaultInstance); } private NodeMetadata LookupInputMetadata(string nodeName) { if (!_inputMetadata.TryGetValue(nodeName, out var value) && !_overridableInitializerMetadata.TryGetValue(nodeName, out value)) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Input name: '" + nodeName + "' is not in the metadata"); } return value; } private NodeMetadata LookupOutputMetadata(string nodeName) { if (!_outputMetadata.TryGetValue(nodeName, out var value)) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Output name: '" + nodeName + "' is not in the metadata"); } return value; } private static IntPtr ExtractOrtValueHandleForInput(NamedOnnxValue input, NodeMetadata metadata, out IDisposable memOwner) { return input.InputToOrtValueHandle(metadata, out memOwner); } private static IntPtr ExtractOrtValueHandleForOutput(NamedOnnxValue output, NodeMetadata metadata, out IDisposable memOwner) { return output.OutputToOrtValueHandle(metadata, out memOwner); } private static IntPtr[] LookupUtf8Names<T>(IReadOnlyCollection<T> values, NameExtractor<T> nameExtractor, MetadataLookup metaLookup) { IntPtr[] array = new IntPtr[values.Count]; for (int i = 0; i < values.Count; i++) { string nodeName = nameExtractor(values.ElementAt(i)); NodeMetadata nodeMetadata = metaLookup(nodeName); array[i] = nodeMetadata.ZeroTerminatedName; } return array; } private static IntPtr[] GetOrtValuesHandles(IReadOnlyCollection<NamedOnnxValue> values, MetadataLookup metaLookup, OrtValueHandleExtractor ortValueExtractor, out DisposableArray<IDisposable> disposer) { IDisposable[] array = new IDisposable[values.Count]; DisposableArray<IDisposable> disposableArray = new DisposableArray<IDisposable>(array); try { IntPtr[] array2 = new IntPtr[values.Count]; for (int i = 0; i < values.Count; i++) { NamedOnnxValue namedOnnxValue = values.ElementAt(i); NodeMetadata metadata = metaLookup(namedOnnxValue.Name); array2[i] = ortValueExtractor(namedOnnxValue, metadata, out var memOwner); if (memOwner != null) { array[i] = memOwner; } } disposer = disposableArray; return array2; } catch (Exception) { disposableArray.Dispose(); throw; } } private static IntPtr[] GetOrtValuesHandles(IReadOnlyCollection<FixedBufferOnnxValue> values, bool input) { IntPtr[] array = new IntPtr[values.Count]; for (int i = 0; i < values.Count; i++) { FixedBufferOnnxValue fixedBufferOnnxValue = values.ElementAt(i); if (!input && fixedBufferOnnxValue.ElementType == TensorElementType.String) { throw new NotSupportedException("Using string type FixedBufferOnnxValue in outputs is not supported."); } array[i] = fixedBufferOnnxValue.Value.Handle; } return array; } private DisposableOrtValueHandleArray RunImpl(RunOptions options, IntPtr[] inputNames, IntPtr[] inputValues, IntPtr[] outputNames) { IntPtr[] array = new IntPtr[outputNames.Length]; NativeApiStatus.VerifySuccess(NativeMethods.OrtRun(_nativeHandle, options.Handle, inputNames, inputValues, (UIntPtr)(ulong)inputNames.Length, outputNames, (UIntPtr)(ulong)outputNames.Length, array)); return new DisposableOrtValueHandleArray(array); } private static IDisposableReadOnlyCollection<DisposableNamedOnnxValue> CreateDisposableResult(Span<IntPtr> valueHandles, IReadOnlyCollection<string> outputNames) { DisposableList<DisposableNamedOnnxValue> disposableList = new DisposableList<DisposableNamedOnnxValue>(valueHandles.Length); try { for (int i = 0; i < valueHandles.Length; i++) { OrtValue ortValue = new OrtValue(valueHandles[i]); disposableList.Add(DisposableNamedOnnxValue.CreateFromOrtValue(outputNames.ElementAt(i), ref ortValue)); valueHandles[i] = IntPtr.Zero; } return disposableList; } catch (OnnxRuntimeException) { disposableList.Dispose(); throw; } } private static void OrtCallback(IntPtr userData, IntPtr[] outputs, uint numOutputs, IntPtr status) { GCHandle gCHandle = GCHandle.FromIntPtr(userData); CallbackHost callbackHost = (CallbackHost)gCHandle.Target; try { callbackHost.callback(callbackHost.outputValues, status); } finally { callbackHost.Dispose(); gCHandle.Free(); } } private unsafe void RunAsyncInternal(RunOptions options, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<OrtValue> outputValues, UserCallbackDelegate callback) { if (inputNames.Count != inputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "inputNames", inputNames.Count, "inputValues", inputValues.Count)); } if (outputNames.Count != outputValues.Count) { throw new ArgumentException(string.Format("Length of {0} ({1}) must match that of {2} ({3}).", "outputNames", outputNames.Count, "outputValues", outputValues.Count)); } CallbackHost callbackHost = new CallbackHost(this, options, inputNames, inputValues, outputNames, outputValues, callback); GCHandle value = default(GCHandle); try { value = GCHandle.Alloc(callbackHost, GCHandleType.Normal); NativeApiStatus.VerifySuccess(NativeMethods.OrtRunAsync(_nativeHandle, options?.Handle ?? ((IntPtr)(void*)null), callbackHost.rawInputNamesPointer, callbackHost.rawInputValuesPointer, (UIntPtr)(ulong)callbackHost.rawInputNames.Length, callbackHost.rawOutputNamesPointer, (UIntPtr)(ulong)callbackHost.rawOutputNames.Length, callbackHost.rawOutputValuesPointer, Marshal.GetFunctionPointerForDelegate(ortCallback), GCHandle.ToIntPtr(value))); } catch { callbackHost.Dispose(); if (value.IsAllocated) { value.Free(); } throw; } } public async Task<IReadOnlyCollection<OrtValue>> RunAsync(RunOptions options, IReadOnlyCollection<string> inputNames, IReadOnlyCollection<OrtValue> inputValues, IReadOnlyCollection<string> outputNames, IReadOnlyCollection<OrtValue> outputValues) { TaskCompletionSource<IReadOnlyCollection<OrtValue>> promise = new TaskCompletionSource<IReadOnlyCollection<OrtValue>>(); RunAsyncInternal(options, inputNames, inputValues, outputNames, outputValues, delegate(IReadOnlyCollection<OrtValue> outputs, IntPtr status) { try { NativeApiStatus.VerifySuccess(status); promise.SetResult(outputs); } catch (Exception exception) { promise.SetException(exception); } }); return await promise.Task; } private void Init(string modelPath, SessionOptions options, PrePackedWeightsContainer prepackedWeightsContainer = null) { IntPtr session = IntPtr.Zero; _epContextDataReadRegistration = options.InvokeWithEpContextDataReadRegistration(delegate(IntPtr optionsHandle) { IntPtr handle = OrtEnv.Instance().Handle; if (prepackedWeightsContainer == null) { NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSession(handle, NativeOnnxValueHelper.GetPlatformSerializedString(modelPath), optionsHandle, out session)); } else { NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSessionWithPrepackedWeightsContainer(handle, NativeOnnxValueHelper.GetPlatformSerializedString(modelPath), optionsHandle, prepackedWeightsContainer.Pointer, out session)); } }); InitWithSessionHandle(session); } private void Init(byte[] modelData, SessionOptions options, PrePackedWeightsContainer prepackedWeightsContainer = null) { IntPtr session = IntPtr.Zero; _epContextDataReadRegistration = options.InvokeWithEpContextDataReadRegistration(delegate(IntPtr optionsHandle) { IntPtr handle = OrtEnv.Instance().Handle; if (prepackedWeightsContainer == null) { NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSessionFromArray(handle, modelData, (UIntPtr)(ulong)modelData.Length, optionsHandle, out session)); } else { NativeApiStatus.VerifySuccess(NativeMethods.OrtCreateSessionFromArrayWithPrepackedWeightsContainer(handle, modelData, (UIntPtr)(ulong)modelData.Length, optionsHandle, prepackedWeightsContainer.Pointer, out session)); } }); InitWithSessionHandle(session); } private void ReleaseEpContextDataReadDelegate() { if (_epContextDataReadRegistration != null) { _epContextDataReadRegistration.Release(); _epContextDataReadRegistration = null; } } private void InitWithSessionHandle(IntPtr session) { _nativeHandle = session; try { NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputCount(_nativeHandle, out var count)); NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOutputCount(_nativeHandle, out var count2)); NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOverridableInitializerCount(_nativeHandle, out var count3)); int capacity = (int)((uint)count + (uint)count2 + (uint)count3); _namesMemoryPtrs = new List<IntPtr>(capacity); _inputMetadata = new Dictionary<string, NodeMetadata>((int)(uint)count); _inputNames = new List<string>((int)(uint)count); for (ulong num = 0uL; num < (ulong)count; num++) { NodeMetadata inputMetadata = GetInputMetadata(num); IntPtr utf; string inputName = GetInputName(num, out utf); _namesMemoryPtrs.Add(utf); inputMetadata.ZeroTerminatedName = utf; _inputNames.Add(inputName); _inputMetadata[inputName] = inputMetadata; } _outputMetadata = new Dictionary<string, NodeMetadata>((int)(uint)count2); _outputNames = new List<string>((int)(uint)count2); for (ulong num2 = 0uL; num2 < (ulong)count2; num2++) { NodeMetadata outputMetadata = GetOutputMetadata(num2); IntPtr utf2; string outputName = GetOutputName(num2, out utf2); _namesMemoryPtrs.Add(utf2); outputMetadata.ZeroTerminatedName = utf2; _outputNames.Add(outputName); _outputMetadata[outputName] = outputMetadata; } _overridableInitializerMetadata = new Dictionary<string, NodeMetadata>((int)(uint)count3); for (ulong num3 = 0uL; num3 < (ulong)count3; num3++) { NodeMetadata overridableInitializerMetadata = GetOverridableInitializerMetadata(num3); IntPtr utf3; string overridableInitializerName = GetOverridableInitializerName(num3, out utf3); _namesMemoryPtrs.Add(utf3); overridableInitializerMetadata.ZeroTerminatedName = utf3; _overridableInitializerMetadata[overridableInitializerName] = overridableInitializerMetadata; } NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetProfilingStartTimeNs(_nativeHandle, out var startTime)); _profilingStartTimeNs = (ulong)startTime; } catch (Exception) { DisposeImpl(disposing: true); throw; } _builtInRunOptions = new RunOptions(); } private string GetOutputName(ulong index, out IntPtr utf8) { OrtAllocator defaultInstance = OrtAllocator.DefaultInstance; NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOutputName(_nativeHandle, (UIntPtr)index, defaultInstance.Pointer, out var name)); NativeOnnxValueHelper.StringAndUtf8FromNative(defaultInstance, name, out var str, out utf8); return str; } private string GetInputName(ulong index, out IntPtr utf8) { OrtAllocator defaultInstance = OrtAllocator.DefaultInstance; NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputName(_nativeHandle, (UIntPtr)index, defaultInstance.Pointer, out var name)); NativeOnnxValueHelper.StringAndUtf8FromNative(defaultInstance, name, out var str, out utf8); return str; } private string GetOverridableInitializerName(ulong index, out IntPtr utf8) { OrtAllocator defaultInstance = OrtAllocator.DefaultInstance; NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOverridableInitializerName(_nativeHandle, (UIntPtr)index, defaultInstance.Pointer, out var name)); NativeOnnxValueHelper.StringAndUtf8FromNative(defaultInstance, name, out var str, out utf8); return str; } private NodeMetadata GetInputMetadata(ulong index) { NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetInputTypeInfo(_nativeHandle, (UIntPtr)index, out var typeInfo)); try { return GetMetadataFromTypeInfo(typeInfo); } finally { NativeMethods.OrtReleaseTypeInfo(typeInfo); } } private NodeMetadata GetOutputMetadata(ulong index) { NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOutputTypeInfo(_nativeHandle, (UIntPtr)index, out var typeInfo)); try { return GetMetadataFromTypeInfo(typeInfo); } finally { NativeMethods.OrtReleaseTypeInfo(typeInfo); } } private NodeMetadata GetOverridableInitializerMetadata(ulong index) { NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetOverridableInitializerTypeInfo(_nativeHandle, (UIntPtr)index, out var typeInfo)); try { return GetMetadataFromTypeInfo(typeInfo); } finally { NativeMethods.OrtReleaseTypeInfo(typeInfo); } } internal static NodeMetadata GetMetadataFromTypeInfo(IntPtr typeInfo) { NativeApiStatus.VerifySuccess(NativeMethods.OrtGetOnnxTypeFromTypeInfo(typeInfo, out var onnxtype)); OnnxValueType onnxValueType = (OnnxValueType)(int)onnxtype; switch (onnxValueType) { case OnnxValueType.ONNX_TYPE_TENSOR: case OnnxValueType.ONNX_TYPE_SPARSETENSOR: return GetTensorNodeMetadata(onnxValueType, typeInfo); case OnnxValueType.ONNX_TYPE_SEQUENCE: return GetSequenceMetadataFromTypeInfo(typeInfo); case OnnxValueType.ONNX_TYPE_MAP: return GetMapMetadataFromTypeInfo(typeInfo); case OnnxValueType.ONNX_TYPE_OPTIONAL: return GetOptionalMetadataFromTypeInfo(typeInfo); default: throw new OnnxRuntimeException(ErrorCode.NotImplemented, $"Value type: '{onnxValueType}' not supported in this code"); } } internal static NodeMetadata GetSequenceMetadataFromTypeInfo(IntPtr typeInfo) { NativeApiStatus.VerifySuccess(NativeMethods.OrtCastTypeInfoToSequenceTypeInfo(typeInfo, out var sequenceTypeInfo)); if (sequenceTypeInfo == IntPtr.Zero) { throw new OnnxRuntimeException(ErrorCode.Fail, "TypeInfo cast to SequenceTypeInfo failed. The object does not represent a sequence"); } NativeApiStatus.VerifySuccess(NativeMethods.OrtGetSequenceElementType(sequenceTypeInfo, out var elementTypeInfo)); try { return new NodeMetadata(new SequenceMetadata(GetMetadataFromTypeInfo(elementTypeInfo))); } finally { NativeMethods.OrtReleaseTypeInfo(elementTypeInfo); } } internal static NodeMetadata GetMapMetadataFromTypeInfo(IntPtr typeInfo) { NativeApiStatus.VerifySuccess(NativeMethods.OrtCastTypeInfoToMapTypeInfo(typeInfo, out var mapTypeInfo)); if (mapTypeInfo == IntPtr.Zero) { throw new OnnxRuntimeException(ErrorCode.Fail, "TypeInfo cast to MapTypeInfo failed. The object does not represent a map"); } NativeApiStatus.VerifySuccess(NativeMethods.OrtGetMapKeyType(mapTypeInfo, out var tensorElementType)); NativeApiStatus.VerifySuccess(NativeMethods.OrtGetMapValueType(mapTypeInfo, out var type_info)); try { NodeMetadata metadataFromTypeInfo = GetMetadataFromTypeInfo(type_info); return new NodeMetadata(new MapMetadata((TensorElementType)(int)tensorElementType, metadataFromTypeInfo)); } finally { NativeMethods.OrtReleaseTypeInfo(type_info); } } internal static NodeMetadata GetOptionalMetadataFromTypeInfo(IntPtr typeInfo) { NativeApiStatus.VerifySuccess(NativeMethods.OrtCastTypeInfoToOptionalTypeInfo(typeInfo, out var optionalTypeInfo)); if (optionalTypeInfo == IntPtr.Zero) { throw new OnnxRuntimeException(ErrorCode.Fail, "TypeInfo cast to OptionalTypeInfo failed. The object does not represent a optional value"); } NativeApiStatus.VerifySuccess(NativeMethods.OrtGetOptionalContainedTypeInfo(optionalTypeInfo, out var containedTypeInfo)); try { return new NodeMetadata(new OptionalMetadata(GetMetadataFromTypeInfo(containedTypeInfo))); } finally { NativeMethods.OrtReleaseTypeInfo(containedTypeInfo); } } internal static NodeMetadata GetTensorNodeMetadata(OnnxValueType valueType, IntPtr typeInfo) { NativeApiStatus.VerifySuccess(NativeMethods.OrtCastTypeInfoToTensorInfo(typeInfo, out var typeAndShapeInfo)); if (typeAndShapeInfo == IntPtr.Zero) { throw new OnnxRuntimeException(ErrorCode.Fail, "TypeInfo cast to TensorTypeInfo failed. The object does not represent a tensor"); } NativeApiStatus.VerifySuccess(NativeMethods.OrtGetTensorElementType(typeAndShapeInfo, out var output)); TensorElementType elementType = (TensorElementType)(int)output; NativeApiStatus.VerifySuccess(NativeMethods.OrtGetDimensionsCount(typeAndShapeInfo, out var output2)); long[] array = new long[(uint)output2]; NativeApiStatus.VerifySuccess(NativeMethods.OrtGetDimensions(typeAndShapeInfo, array, output2)); int[] array2 = new int[(uint)output2]; for (int i = 0; (long)i < (long)(ulong)output2; i++) { array2[i] = (int)array[i]; } IntPtr[] array3 = new IntPtr[(uint)output2]; NativeApiStatus.VerifySuccess(NativeMethods.OrtGetSymbolicDimensions(typeAndShapeInfo, array3, output2)); string[] array4 = new string[(uint)output2]; for (int j = 0; j < (int)(uint)output2; j++) { array4[j] = NativeOnnxValueHelper.StringFromNativeUtf8(array3[j]); } TensorTypeAndShape typeAndShape = new TensorTypeAndShape(elementType, array2, array4); return new NodeMetadata(valueType, typeAndShape); } ~InferenceSession() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { DisposeImpl(disposing); } } private void DisposeImpl(bool disposing) { if (disposing) { if (_namesMemoryPtrs != null) { foreach (IntPtr namesMemoryPtr in _namesMemoryPtrs) { Marshal.FreeHGlobal(namesMemoryPtr); } _namesMemoryPtrs = null; } if (_builtInSessionOptions != null) { _builtInSessionOptions.Dispose(); _builtInSessionOptions = null; } if (_builtInRunOptions != null) { _builtInRunOptions.Dispose(); _builtInRunOptions = null; } } if (_nativeHandle != IntPtr.Zero) { NativeMethods.OrtReleaseSession(_nativeHandle); _nativeHandle = IntPtr.Zero; } ReleaseEpContextDataReadDelegate(); _disposed = true; } } public class TensorTypeAndShape { public TensorElementType ElementDataType { get; } public int[] Dimensions { get; } public string[] SymbolicDimensions { get; } public TensorElementTypeInfo ElementTypeInfo { get; } internal TensorTypeAndShape(TensorElementType elementType, int[] dimensions, string[] symbolicDimensions) { ElementTypeInfo = TensorBase.GetElementTypeInfo(elementType); if (ElementTypeInfo == null) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Unregistered TensorElementType value of: " + elementType); } ElementDataType = elementType; Dimensions = dimensions; SymbolicDimensions = symbolicDimensions; } } public class SequenceMetadata { public NodeMetadata ElementMeta { get; } internal SequenceMetadata(NodeMetadata elementData) { ElementMeta = elementData; } } public class OptionalMetadata { public NodeMetadata ElementMeta { get; } internal OptionalMetadata(NodeMetadata elementData) { ElementMeta = elementData; } } public class MapMetadata { public TensorElementType KeyDataType { get; } public NodeMetadata ValueMetadata { get; } internal MapMetadata(TensorElementType keyDataType, NodeMetadata valueMetadata) { KeyDataType = keyDataType; ValueMetadata = valueMetadata; } } public class NodeMetadata { private readonly object _metadata; public OnnxValueType OnnxValueType { get; } internal IntPtr ZeroTerminatedName { get; set; } public int[] Dimensions { get { CheckTensor(); return (_metadata as TensorTypeAndShape).Dimensions; } } public string[] SymbolicDimensions { get { CheckTensor(); return (_metadata as TensorTypeAndShape).SymbolicDimensions; } } public Type ElementType { get { CheckTensor(); return (_metadata as TensorTypeAndShape).ElementTypeInfo.TensorType; } } public TensorElementType ElementDataType { get { CheckTensor(); return (_metadata as TensorTypeAndShape).ElementDataType; } } public bool IsString { get { CheckTensor(); return (_metadata as TensorTypeAndShape).ElementTypeInfo.IsString; } } public bool IsTensor { get { if (OnnxValueType != OnnxValueType.ONNX_TYPE_TENSOR) { return OnnxValueType == OnnxValueType.ONNX_TYPE_SPARSETENSOR; } return true; } } internal NodeMetadata(OnnxValueType onnxValueType, TensorTypeAndShape typeAndShape) { OnnxValueType = onnxValueType; CheckTensor(); _metadata = typeAndShape; } internal NodeMetadata(MapMetadata mapMetadata) { OnnxValueType = OnnxValueType.ONNX_TYPE_MAP; _metadata = mapMetadata; } internal NodeMetadata(SequenceMetadata sequenceMetadata) { OnnxValueType = OnnxValueType.ONNX_TYPE_SEQUENCE; _metadata = sequenceMetadata; } internal NodeMetadata(OptionalMetadata optMetadata) { OnnxValueType = OnnxValueType.ONNX_TYPE_OPTIONAL; _metadata = optMetadata; } private void CheckTensor() { if (!IsTensor) { throw new OnnxRuntimeException(ErrorCode.Fail, "OnnxValueType must either be a tensor or sparse tensor"); } } public MapMetadata AsMapMetadata() { if (OnnxValueType != OnnxValueType.ONNX_TYPE_MAP) { throw new OnnxRuntimeException(ErrorCode.Fail, "Instance does not contain Map metadata"); } return _metadata as MapMetadata; } public SequenceMetadata AsSequenceMetadata() { if (OnnxValueType != OnnxValueType.ONNX_TYPE_SEQUENCE) { throw new OnnxRuntimeException(ErrorCode.Fail, "Instance does not contain Sequence metadata"); } return _metadata as SequenceMetadata; } public OptionalMetadata AsOptionalMetadata() { if (OnnxValueType != OnnxValueType.ONNX_TYPE_OPTIONAL) { throw new OnnxRuntimeException(ErrorCode.Fail, "Instance does not contain Optional metadata"); } return _metadata as OptionalMetadata; } } public class ModelMetadata { private string _producerName; private string _graphName; private string _domain; private string _description; private string _graphDescription; private long _version; private Dictionary<string, string> _customMetadataMap = new Dictionary<string, string>(); public string ProducerName => _producerName; public string GraphName => _graphName; public string Domain => _domain; public string Description => _description; public string GraphDescription => _graphDescription; public long Version => _version; public Dictionary<string, string> CustomMetadataMap => _customMetadataMap; internal unsafe ModelMetadata(InferenceSession session) { OrtAllocator defaultInstance = OrtAllocator.DefaultInstance; NativeApiStatus.VerifySuccess(NativeMethods.OrtSessionGetModelMetadata(session.Handle, out var modelMetadata)); try { NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetProducerName(modelMetadata, defaultInstance.Pointer, out var value)); _producerName = NativeOnnxValueHelper.StringFromNativeUtf8(value, defaultInstance); NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetGraphName(modelMetadata, defaultInstance.Pointer, out var value2)); _graphName = NativeOnnxValueHelper.StringFromNativeUtf8(value2, defaultInstance); NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetDomain(modelMetadata, defaultInstance.Pointer, out var value3)); _domain = NativeOnnxValueHelper.StringFromNativeUtf8(value3, defaultInstance); NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetDescription(modelMetadata, defaultInstance.Pointer, out var value4)); _description = NativeOnnxValueHelper.StringFromNativeUtf8(value4, defaultInstance); NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetGraphDescription(modelMetadata, defaultInstance.Pointer, out var value5)); _graphDescription = NativeOnnxValueHelper.StringFromNativeUtf8(value5, defaultInstance); NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetVersion(modelMetadata, out _version)); NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataGetCustomMetadataMapKeys(modelMetadata, defaultInstance.Pointer, out var keys, out var numKeys)); try { Span<IntPtr> span = new Span<IntPtr>(keys.ToPointer(), (int)numKeys); using DisposableList<OrtMemoryAllocation> disposableList = new DisposableList<OrtMemoryAllocation>((int)numKeys); Span<IntPtr> span2 = span; for (int i = 0; i < span2.Length; i++) { IntPtr pointer = span2[i]; disposableList.Add(new OrtMemoryAllocation(defaultInstance, pointer, 0u)); } span2 = span; for (int i = 0; i < span2.Length; i++) { IntPtr intPtr = span2[i]; NativeApiStatus.VerifySuccess(NativeMethods.OrtModelMetadataLookupCustomMetadataMap(modelMetadata, defaultInstance.Pointer, intPtr, out var value6)); string value7 = NativeOnnxValueHelper.StringFromNativeUtf8(value6, defaultInstance); string key = NativeOnnxValueHelper.StringFromNativeUtf8(intPtr); _customMetadataMap[key] = value7; } } finally { defaultInstance.FreeMemory(keys); } } finally { NativeMethods.OrtReleaseModelMetadata(modelMetadata); } } } internal class ManagedTypeProjection { internal static OrtValue CreateProjection(NamedOnnxValue namedOnnxValue, NodeMetadata metadata) { NodeMetadata nodeMetadata = metadata; if (metadata.OnnxValueType == OnnxValueType.ONNX_TYPE_OPTIONAL) { nodeMetadata = metadata.AsOptionalMetadata().ElementMeta; } if (namedOnnxValue.ValueType != nodeMetadata.OnnxValueType) { throw new OnnxRuntimeException(ErrorCode.RuntimeException, $"NamedOnnxValue: {namedOnnxValue.Name} has value type: {namedOnnxValue.ValueType}" + $" expected: {nodeMetadata.OnnxValueType} after optional type adjustment"); } return namedOnnxValue.ValueType switch { OnnxValueType.ONNX_TYPE_TENSOR => CreateTensorProjection(namedOnnxValue, nodeMetadata), OnnxValueType.ONNX_TYPE_SEQUENCE => CreateSequenceProjection(namedOnnxValue, nodeMetadata), OnnxValueType.ONNX_TYPE_MAP => CreateMapProjection(namedOnnxValue, nodeMetadata), _ => throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "ManagedTypeProjection can only project tensors, sequences, maps and optional types"), }; } private static OrtValue CreateSequenceProjection(NamedOnnxValue namedOnnxValue, NodeMetadata metadata) { NodeMetadata elementMeta = metadata.AsSequenceMetadata().ElementMeta; OnnxValueType onnxValueType = elementMeta.OnnxValueType; IEnumerable<NamedOnnxValue> enumerable = namedOnnxValue.AsEnumerable<NamedOnnxValue>() ?? throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "NamedOnnxValue: " + namedOnnxValue.Name + " sequence does not contain NamedOnnxValue elements"); int count = 0; if (enumerable is ICollection<NamedOnnxValue> collection) { count = collection.Count; } DisposableList<OrtValue> compositeMembers = new DisposableList<OrtValue>(count); try { foreach (NamedOnnxValue item in enumerable) { if (onnxValueType != item.ValueType) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"NamedOnnxValue: {namedOnnxValue.Name} sequence element expected to be {onnxValueType}, received {item.ValueType}"); } compositeMembers.Add(CreateProjection(item, elementMeta)); } return OrtValue.CreateSequence(ref compositeMembers); } catch (Exception) { compositeMembers?.Dispose(); throw; } } private static OrtValue CreateMapProjection(NamedOnnxValue node, NodeMetadata elementMeta) { MapMetadata mapMetadata = elementMeta.AsMapMetadata(); NodeMetadata valueMetadata = mapMetadata.ValueMetadata; if (valueMetadata.OnnxValueType != OnnxValueType.ONNX_TYPE_TENSOR) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Node: " + node.Name + " onnxruntime only supports maps with primitive types values"); } Span<OrtValue> disposables = new OrtValue[2]; DisposableArray<OrtValue> disposableArray = new DisposableArray<OrtValue>(disposables); try { TensorBase dictionaryKeys = node.GetDictionaryKeys(); disposables[0] = OrtValue.CreateFromTensorObject(dictionaryKeys, out var elementType); if (elementType != mapMetadata.KeyDataType) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Map key data type supplied: {elementType} metadata expected: {mapMetadata.KeyDataType}"); } TensorBase dictionaryValues = node.GetDictionaryValues(); disposables[1] = OrtValue.CreateFromTensorObject(dictionaryValues, out var elementType2); if (elementType2 != valueMetadata.ElementDataType) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Map value data type supplied: {elementType2} metadata expected: {valueMetadata.ElementDataType}"); } return OrtValue.CreateMap(ref disposables[0], ref disposables[1]); } catch (Exception) { disposableArray.Dispose(); throw; } } private static OrtValue CreateTensorProjection(NamedOnnxValue node, NodeMetadata elementMeta) { if (!(node.Value is TensorBase)) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"NamedOnnxValue contains: {node.Value.GetType()}, expecting a Tensor<T>"); } TensorElementType elementType; OrtValue ortValue = OrtValue.CreateFromTensorObject(node.Value as TensorBase, out elementType); try { if (elementType != elementMeta.ElementDataType) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, $"Tensor element data type discovered: {elementType} metadata expected: {elementMeta.ElementDataType}"); } return ortValue; } catch (Exception) { ortValue.Dispose(); throw; } } } internal class MapHelper { internal TensorBase Keys { get; } internal TensorBase Values { get; } internal MapHelper(TensorBase keys, TensorBase values) { Keys = keys; Values = values; } } public class NamedOnnxValue { private object _value; private string _name; private MapHelper _mapHelper; public OnnxValueType ValueType { get; internal set; } public string Name { get { return _name; } set { _name = value; } } public object Value { get { return _value; } set { _value = value; } } [Obsolete("Use constructors with valueType or static factory methods")] protected NamedOnnxValue(string name, object value) { _name = name; _value = value; ValueType = OnnxValueType.ONNX_TYPE_UNKNOWN; } internal NamedOnnxValue(string name, object value, OnnxValueType valueType) { _name = name; _value = value; ValueType = valueType; if (valueType == OnnxValueType.ONNX_TYPE_MAP) { throw new OnnxRuntimeException(ErrorCode.InvalidArgument, "Use another __ctor for maps"); } } internal NamedOnnxValue(string name, object value, MapHelper helper) { _name = name; _value = value; ValueType = OnnxValueType.ONNX_TYPE_MAP; _mapHelper = helper; } public static NamedOnnxValue CreateFromTensor<T>(string name, Tensor<T> value) { return new NamedOnnxValue(name, value, OnnxValueType.ONNX_TYPE_TENSOR); } public static NamedOnnxValue CreateFromSequence<T>(string name, IEnumerable<T> value) { return new NamedOnnxValue(name, value, OnnxValueType.ONNX_TYPE_SEQUENCE); } public static NamedOnnxValue CreateFromMap<K, V>(string name, IDictionary<K, V> value) { return CreateFromMap(name, value.Keys, value.Values); } internal static NamedOnnxValue CreateFromMap<K, V>(string name, ICollection<K> keys, ICollection<V> values) { DenseTensor<K> keys2 = new DenseTensor<K>(keys.ToArray(), new int[1] { keys.Count }); DenseTensor<V> values2 = new DenseTensor<V>(values.ToArray(), new int[1] { values.Count }); return new NamedOnnxValue(name, values, new MapHelper(keys2, values2)); } public Tensor<T> AsTensor<T>() { return _value as Tensor<T>; } public IEnumerable<T> AsEnumerable<T>() { return _value as IEnumerable<T>; } public IDictionary<K, V> AsDictionary<K, V>() { return _value as IDictionary<K, V>; } internal virtual IntPtr InputToOrtValueHandle(NodeMetadata metadata, out IDisposable memoryOwner) { return ((OrtValue)(memoryOwner = ManagedTypeProjection.CreateProjection(this, metadata))).Handle; } internal virtual IntPtr OutputToOrtValueHandle(NodeMetadata metadata, out IDisposable memoryOwner) { if (metadata.OnnxValueType == OnnxValueType.ONNX_TYPE_TENSOR) { return ((OrtValue)(memoryOwner = ManagedTypeProjection.CreateProjection(this, metadata))).Handle; } if (metadata.OnnxValueType == OnnxValueType.ONNX_TYPE_OPTIONAL && metadata.AsOptionalMetadata().ElementMeta.OnnxValueType == OnnxValueType.ONNX_TYPE_TENSOR) { return ((OrtValue)(memoryOwner = ManagedTypeProjection.CreateProjection(this, metadata))).Handle; } throw new OnnxRuntimeException(ErrorCode.NotImplemented, $"Can not create output OrtValue for NamedOnnxValue '{metadata.OnnxValueType}' type." + " Only tensors can be pre-allocated for outputs Use Run() overloads that return DisposableNamedOnnxValue to get access to all Onnx value types that may be returned as output."); } internal TensorBase GetDictionaryKeys() { if (ValueType != OnnxValueType.ONNX_TYPE_MAP) { throw new OnnxRuntimeException(ErrorCode.Fail, "This NamedOnnxValue instance does not contain a dictionary"); } return _mapHelper.Keys; } internal TensorBase GetDictionaryValues() { if (ValueType != OnnxValueType.ONNX_TYPE_MAP) { throw new OnnxRuntimeException(ErrorCode.Fail, "This NamedOnnxValue instance does not contain a dictionary"); } return _mapHelper.Values; } } internal class NativeApiStatus { private static string GetErrorMessage(IntPtr status) { return NativeOnnxValueHelper.StringFromNativeUtf8(NativeMethods.OrtGetErrorMessage(status)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void VerifySuccess(IntPtr nativeStatus) { if (nativeStatus != IntPtr.Zero) { try { ErrorCode errorCode = NativeMethods.OrtGetErrorCode(nativeStatus); string errorMessage = GetErrorMessage(nativeStatus); throw new OnnxRuntimeException(errorCode, errorMessage); } finally { NativeMethods.OrtReleaseStatus(nativeStatus); } } } } [StructLayout(LayoutKind.Sequential)] public class OrtApiBase { public IntPtr GetApi; public IntPtr GetVersionString; } [StructLayout(LayoutKind.Sequential)] public class OrtApi { public IntPtr CreateStatus; public IntPtr GetErrorCode; public IntPtr GetErrorMessage; public IntPtr CreateEnv; public IntPtr CreateEnvWithCustomLogger; public IntPtr EnableTelemetryEvents; public IntPtr DisableTelemetryEvents; public IntPtr CreateSession; public IntPtr CreateSessionFromArray; public IntPtr Run; public IntPtr CreateSessionOptions; public IntPtr SetOptimizedModelFilePath; public IntPtr CloneSessionOptions; public IntPtr SetSessionExecutionMode; public IntPtr EnableProfiling; public IntPtr DisableProfiling; public IntPtr EnableMemPattern; public IntPtr DisableMemPattern; public IntPtr EnableCpuMemArena; public IntPtr DisableCpuMemArena; public IntPtr SetSessionLogId; public IntPtr SetSessionLogVerbosityLevel; public IntPtr SetSessionLogSeverityLevel; public IntPtr SetSessionGraphOptimizationLevel; public IntPtr SetIntraOpNumThreads; public IntPtr SetInterOpNumThreads; public IntPtr CreateCustomOpDomain; public IntPtr CustomOpDomain_Add; public IntPtr AddCustomOpDomain; public IntPtr RegisterCustomOpsLibrary; public IntPtr SessionGetInputCount; public IntPtr SessionGetOutputCount; public IntPtr SessionGetOverridableInitializerCount; public IntPtr SessionGetInputTypeInfo; public IntPtr SessionGetOutputTypeInfo; public IntPtr SessionGetOverridableInitializerTypeInfo; public IntPtr SessionGetInputName; public IntPtr SessionGetOutputName; public IntPtr SessionGetOverridableInitializerName; public IntPtr CreateRunOptions; public IntPtr RunOptionsSetRunLogVerbosityLevel; public IntPtr RunOptionsSetRunLogSeverityLevel; public IntPtr RunOptionsSetRunTag; public IntPtr RunOptionsGetRunLogVerbosityLevel; public IntPtr RunOptionsGetRunLogSeverityLevel; public IntPtr RunOptionsGetRunTag; public IntPtr RunOptionsSetTerminate; public IntPtr RunOptionsUnsetTerminate; public IntPtr CreateTensorAsOrtValue; public IntPtr CreateTensorWithDataAsOrtValue; public IntPtr IsTensor; public IntPtr GetTensorMutableData; public IntPtr FillStringTensor; public IntPtr GetStringTensorDataLength; public IntPtr GetStringTensorContent; public IntPtr CastTypeInfoToTensorInfo; public IntPtr GetOnnxTypeFromTypeInfo; public IntPtr CreateTensorTypeAndShapeInfo; public IntPtr SetTensorElementType; public IntPtr SetDimensions; public IntPtr GetTensorElementType; public IntPtr GetDimensionsCount; public IntPtr GetDimensions; public IntPtr GetSymbolicDimensions; public IntPtr GetTensorShapeElementCount; public IntPtr GetTensorTypeAndShape; public IntPtr GetTypeInfo; public IntPtr GetValueType; public IntPtr CreateMemoryInfo; public IntPtr CreateCpuMemoryInfo; public IntPtr CompareMemoryInfo; public IntPtr MemoryInfoGetName; public IntPtr MemoryInfoGetId; public IntPtr MemoryInfoGetMemType; public IntPtr MemoryInfoGetType; public IntPtr AllocatorAlloc; public IntPtr AllocatorFree; public IntPtr AllocatorGetInfo;
plugins/BingBongHelper/System.Buffers.dll
Decompiled 2 weeks agousing System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Buffers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Buffers")] [assembly: AssemblyDescription("System.Buffers")] [assembly: AssemblyDefaultAlias("System.Buffers")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.28619.01")] [assembly: AssemblyInformationalVersion("4.6.28619.01 @BuiltBy: dlab14-DDVSOWINAGE069 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/7601f4f6225089ffb291dc7d58293c7bbf5c5d4f")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.3.0")] [module: UnverifiableCode] namespace FxResources.System.Buffers { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(SR); internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Buffers { public abstract class ArrayPool<T> { private static ArrayPool<T> s_sharedInstance; public static ArrayPool<T> Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static ArrayPool<T> EnsureSharedCreated() { Interlocked.CompareExchange(ref s_sharedInstance, Create(), null); return s_sharedInstance; } public static ArrayPool<T> Create() { return new DefaultArrayPool<T>(); } public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket) { return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket); } public abstract T[] Rent(int minimumLength); public abstract void Return(T[] array, bool clearArray = false); } [EventSource(Name = "System.Buffers.ArrayPoolEventSource")] internal sealed class ArrayPoolEventSource : EventSource { internal enum BufferAllocatedReason { Pooled, OverMaximumSize, PoolExhausted } internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource(); [Event(1, Level = EventLevel.Verbose)] internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) { EventData* ptr = stackalloc EventData[4]; *ptr = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; WriteEventCore(1, 4, ptr); } [Event(2, Level = EventLevel.Informational)] internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason) { EventData* ptr = stackalloc EventData[5]; *ptr = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferId) }; ptr[1] = new EventData { Size = 4, DataPointer = (IntPtr)(&bufferSize) }; ptr[2] = new EventData { Size = 4, DataPointer = (IntPtr)(&poolId) }; ptr[3] = new EventData { Size = 4, DataPointer = (IntPtr)(&bucketId) }; ptr[4] = new EventData { Size = 4, DataPointer = (IntPtr)(&reason) }; WriteEventCore(2, 5, ptr); } [Event(3, Level = EventLevel.Verbose)] internal void BufferReturned(int bufferId, int bufferSize, int poolId) { WriteEvent(3, bufferId, bufferSize, poolId); } } internal sealed class DefaultArrayPool<T> : ArrayPool<T> { private sealed class Bucket { internal readonly int _bufferLength; private readonly T[][] _buffers; private readonly int _poolId; private SpinLock _lock; private int _index; internal int Id => GetHashCode(); internal Bucket(int bufferLength, int numberOfBuffers, int poolId) { _lock = new SpinLock(Debugger.IsAttached); _buffers = new T[numberOfBuffers][]; _bufferLength = bufferLength; _poolId = poolId; } internal T[] Rent() { T[][] buffers = _buffers; T[] array = null; bool lockTaken = false; bool flag = false; try { _lock.Enter(ref lockTaken); if (_index < buffers.Length) { array = buffers[_index]; buffers[_index++] = null; flag = array == null; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } if (flag) { array = new T[_bufferLength]; System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled); } } return array; } internal void Return(T[] array) { if (array.Length != _bufferLength) { throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array"); } bool lockTaken = false; try { _lock.Enter(ref lockTaken); if (_index != 0) { _buffers[--_index] = array; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } } } private const int DefaultMaxArrayLength = 1048576; private const int DefaultMaxNumberOfArraysPerBucket = 50; private static T[] s_emptyArray; private readonly Bucket[] _buckets; private int Id => GetHashCode(); internal DefaultArrayPool() : this(1048576, 50) { } internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket) { if (maxArrayLength <= 0) { throw new ArgumentOutOfRangeException("maxArrayLength"); } if (maxArraysPerBucket <= 0) { throw new ArgumentOutOfRangeException("maxArraysPerBucket"); } if (maxArrayLength > 1073741824) { maxArrayLength = 1073741824; } else if (maxArrayLength < 16) { maxArrayLength = 16; } int id = Id; int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength); Bucket[] array = new Bucket[num + 1]; for (int i = 0; i < array.Length; i++) { array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id); } _buckets = array; } public override T[] Rent(int minimumLength) { if (minimumLength < 0) { throw new ArgumentOutOfRangeException("minimumLength"); } if (minimumLength == 0) { return s_emptyArray ?? (s_emptyArray = new T[0]); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; T[] array = null; int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength); if (num < _buckets.Length) { int num2 = num; do { array = _buckets[num2].Rent(); if (array != null) { if (log.IsEnabled()) { log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id); } return array; } } while (++num2 < _buckets.Length && num2 != num + 2); array = new T[_buckets[num]._bufferLength]; } else { array = new T[minimumLength]; } if (log.IsEnabled()) { int hashCode = array.GetHashCode(); int bucketId = -1; log.BufferRented(hashCode, array.Length, Id, bucketId); log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); } return array; } public override void Return(T[] array, bool clearArray = false) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Length == 0) { return; } int num = System.Buffers.Utilities.SelectBucketIndex(array.Length); if (num < _buckets.Length) { if (clearArray) { Array.Clear(array, 0, array.Length); } _buckets[num].Return(array); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferReturned(array.GetHashCode(), array.Length, Id); } } } internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int SelectBucketIndex(int bufferSize) { uint num = (uint)(bufferSize - 1) >> 4; int num2 = 0; if (num > 65535) { num >>= 16; num2 = 16; } if (num > 255) { num >>= 8; num2 += 8; } if (num > 15) { num >>= 4; num2 += 4; } if (num > 3) { num >>= 2; num2 += 2; } if (num > 1) { num >>= 1; num2++; } return num2 + (int)num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetMaxSizeForBucket(int binIndex) { return 16 << binIndex; } } }
plugins/BingBongHelper/System.Memory.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Numerics; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Memory; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Memory")] [assembly: AssemblyDescription("System.Memory")] [assembly: AssemblyDefaultAlias("System.Memory")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.31308.01")] [assembly: AssemblyInformationalVersion("4.6.31308.01 @BuiltBy: cloudtest-841353dfc000000 @Branch: release/2.1-MSRC @SrcCode: https://github.com/dotnet/corefx/tree/32b491939fbd125f304031c35038b1e14b4e3958")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.1.2")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } } namespace FxResources.System.Memory { internal static class SR { } } namespace System { public readonly struct SequencePosition : IEquatable<SequencePosition> { private readonly object _object; private readonly int _integer; public SequencePosition(object @object, int integer) { _object = @object; _integer = integer; } [EditorBrowsable(EditorBrowsableState.Never)] public object GetObject() { return _object; } [EditorBrowsable(EditorBrowsableState.Never)] public int GetInteger() { return _integer; } public bool Equals(SequencePosition other) { if (_integer == other._integer) { return object.Equals(_object, other._object); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is SequencePosition other) { return Equals(other); } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return HashHelpers.Combine(_object?.GetHashCode() ?? 0, _integer); } } internal static class ThrowHelper { internal static void ThrowArgumentNullException(System.ExceptionArgument argument) { throw CreateArgumentNullException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentNullException(System.ExceptionArgument argument) { return new ArgumentNullException(argument.ToString()); } internal static void ThrowArrayTypeMismatchException() { throw CreateArrayTypeMismatchException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArrayTypeMismatchException() { return new ArrayTypeMismatchException(); } internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type) { throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type) { return new ArgumentException(System.SR.Format(System.SR.Argument_InvalidTypeWithPointersNotSupported, type)); } internal static void ThrowArgumentException_DestinationTooShort() { throw CreateArgumentException_DestinationTooShort(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_DestinationTooShort() { return new ArgumentException(System.SR.Argument_DestinationTooShort); } internal static void ThrowIndexOutOfRangeException() { throw CreateIndexOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateIndexOutOfRangeException() { return new IndexOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException() { throw CreateArgumentOutOfRangeException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException() { return new ArgumentOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument) { throw CreateArgumentOutOfRangeException(argument); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument) { return new ArgumentOutOfRangeException(argument.ToString()); } internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge() { throw CreateArgumentOutOfRangeException_PrecisionTooLarge(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge() { return new ArgumentOutOfRangeException("precision", System.SR.Format(System.SR.Argument_PrecisionTooLarge, (byte)99)); } internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit() { throw CreateArgumentOutOfRangeException_SymbolDoesNotFit(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit() { return new ArgumentOutOfRangeException("symbol", System.SR.Argument_BadFormatSpecifier); } internal static void ThrowInvalidOperationException() { throw CreateInvalidOperationException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException() { return new InvalidOperationException(); } internal static void ThrowInvalidOperationException_OutstandingReferences() { throw CreateInvalidOperationException_OutstandingReferences(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_OutstandingReferences() { return new InvalidOperationException(System.SR.OutstandingReferences); } internal static void ThrowInvalidOperationException_UnexpectedSegmentType() { throw CreateInvalidOperationException_UnexpectedSegmentType(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_UnexpectedSegmentType() { return new InvalidOperationException(System.SR.UnexpectedSegmentType); } internal static void ThrowInvalidOperationException_EndPositionNotReached() { throw CreateInvalidOperationException_EndPositionNotReached(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateInvalidOperationException_EndPositionNotReached() { return new InvalidOperationException(System.SR.EndPositionNotReached); } internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange() { throw CreateArgumentOutOfRangeException_PositionOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange() { return new ArgumentOutOfRangeException("position"); } internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange() { throw CreateArgumentOutOfRangeException_OffsetOutOfRange(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange() { return new ArgumentOutOfRangeException("offset"); } internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer() { throw CreateObjectDisposedException_ArrayMemoryPoolBuffer(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer() { return new ObjectDisposedException("ArrayMemoryPoolBuffer"); } internal static void ThrowFormatException_BadFormatSpecifier() { throw CreateFormatException_BadFormatSpecifier(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateFormatException_BadFormatSpecifier() { return new FormatException(System.SR.Argument_BadFormatSpecifier); } internal static void ThrowArgumentException_OverlapAlignmentMismatch() { throw CreateArgumentException_OverlapAlignmentMismatch(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateArgumentException_OverlapAlignmentMismatch() { return new ArgumentException(System.SR.Argument_OverlapAlignmentMismatch); } internal static void ThrowNotSupportedException() { throw CreateThrowNotSupportedException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static Exception CreateThrowNotSupportedException() { return new NotSupportedException(); } public static bool TryFormatThrowFormatException(out int bytesWritten) { bytesWritten = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static bool TryParseThrowFormatException<T>(out T value, out int bytesConsumed) { value = default(T); bytesConsumed = 0; ThrowFormatException_BadFormatSpecifier(); return false; } public static void ThrowArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment) { throw CreateArgumentValidationException(startSegment, startIndex, endSegment); } private static Exception CreateArgumentValidationException<T>(ReadOnlySequenceSegment<T> startSegment, int startIndex, ReadOnlySequenceSegment<T> endSegment) { if (startSegment == null) { return CreateArgumentNullException(System.ExceptionArgument.startSegment); } if (endSegment == null) { return CreateArgumentNullException(System.ExceptionArgument.endSegment); } if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment); } if ((uint)startSegment.Memory.Length < (uint)startIndex) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex); } public static void ThrowArgumentValidationException(Array array, int start) { throw CreateArgumentValidationException(array, start); } private static Exception CreateArgumentValidationException(Array array, int start) { if (array == null) { return CreateArgumentNullException(System.ExceptionArgument.array); } if ((uint)start > (uint)array.Length) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); } public static void ThrowStartOrEndArgumentValidationException(long start) { throw CreateStartOrEndArgumentValidationException(start); } private static Exception CreateStartOrEndArgumentValidationException(long start) { if (start < 0) { return CreateArgumentOutOfRangeException(System.ExceptionArgument.start); } return CreateArgumentOutOfRangeException(System.ExceptionArgument.length); } } internal enum ExceptionArgument { length, start, minimumBufferSize, elementIndex, comparable, comparer, destination, offset, startSegment, endSegment, startIndex, endIndex, array, culture, manager } internal static class DecimalDecCalc { private static uint D32DivMod1E9(uint hi32, ref uint lo32) { ulong num = ((ulong)hi32 << 32) | lo32; lo32 = (uint)(num / 1000000000); return (uint)(num % 1000000000); } internal static uint DecDivMod1E9(ref MutableDecimal value) { return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0u, ref value.High), ref value.Mid), ref value.Low); } internal static void DecAddInt32(ref MutableDecimal value, uint i) { if (D32AddCarry(ref value.Low, i) && D32AddCarry(ref value.Mid, 1u)) { D32AddCarry(ref value.High, 1u); } } private static bool D32AddCarry(ref uint value, uint i) { uint num = value; uint num2 = (value = num + i); if (num2 >= num) { return num2 < i; } return true; } internal static void DecMul10(ref MutableDecimal value) { MutableDecimal d = value; DecShiftLeft(ref value); DecShiftLeft(ref value); DecAdd(ref value, d); DecShiftLeft(ref value); } private static void DecShiftLeft(ref MutableDecimal value) { uint num = (((value.Low & 0x80000000u) != 0) ? 1u : 0u); uint num2 = (((value.Mid & 0x80000000u) != 0) ? 1u : 0u); value.Low <<= 1; value.Mid = (value.Mid << 1) | num; value.High = (value.High << 1) | num2; } private static void DecAdd(ref MutableDecimal value, MutableDecimal d) { if (D32AddCarry(ref value.Low, d.Low) && D32AddCarry(ref value.Mid, 1u)) { D32AddCarry(ref value.High, 1u); } if (D32AddCarry(ref value.Mid, d.Mid)) { D32AddCarry(ref value.High, 1u); } D32AddCarry(ref value.High, d.High); } } internal static class Number { private static class DoubleHelper { public unsafe static uint Exponent(double d) { return (*(uint*)((byte*)(&d) + 4) >> 20) & 0x7FFu; } public unsafe static ulong Mantissa(double d) { return *(uint*)(&d) | ((ulong)(uint)(*(int*)((byte*)(&d) + 4) & 0xFFFFF) << 32); } public unsafe static bool Sign(double d) { return *(uint*)((byte*)(&d) + 4) >> 31 != 0; } } internal const int DECIMAL_PRECISION = 29; private static readonly ulong[] s_rgval64Power10 = new ulong[30] { 11529215046068469760uL, 14411518807585587200uL, 18014398509481984000uL, 11258999068426240000uL, 14073748835532800000uL, 17592186044416000000uL, 10995116277760000000uL, 13743895347200000000uL, 17179869184000000000uL, 10737418240000000000uL, 13421772800000000000uL, 16777216000000000000uL, 10485760000000000000uL, 13107200000000000000uL, 16384000000000000000uL, 14757395258967641293uL, 11805916207174113035uL, 9444732965739290428uL, 15111572745182864686uL, 12089258196146291749uL, 9671406556917033399uL, 15474250491067253438uL, 12379400392853802751uL, 9903520314283042201uL, 15845632502852867522uL, 12676506002282294018uL, 10141204801825835215uL, 16225927682921336344uL, 12980742146337069075uL, 10384593717069655260uL }; private static readonly sbyte[] s_rgexp64Power10 = new sbyte[15] { 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37, 40, 44, 47, 50 }; private static readonly ulong[] s_rgval64Power10By16 = new ulong[42] { 10240000000000000000uL, 11368683772161602974uL, 12621774483536188886uL, 14012984643248170708uL, 15557538194652854266uL, 17272337110188889248uL, 9588073174409622172uL, 10644899600020376798uL, 11818212630765741798uL, 13120851772591970216uL, 14567071740625403792uL, 16172698447808779622uL, 17955302187076837696uL, 9967194951097567532uL, 11065809325636130658uL, 12285516299433008778uL, 13639663065038175358uL, 15143067982934716296uL, 16812182738118149112uL, 9332636185032188787uL, 10361307573072618722uL, 16615349947311448416uL, 14965776766268445891uL, 13479973333575319909uL, 12141680576410806707uL, 10936253623915059637uL, 9850501549098619819uL, 17745086042373215136uL, 15983352577617880260uL, 14396524142538228461uL, 12967236152753103031uL, 11679847981112819795uL, 10520271803096747049uL, 9475818434452569218uL, 17070116948172427008uL, 15375394465392026135uL, 13848924157002783096uL, 12474001934591998882uL, 11235582092889474480uL, 10120112665365530972uL, 18230774251475056952uL, 16420821625123739930uL }; private static readonly short[] s_rgexp64Power10By16 = new short[21] { 54, 107, 160, 213, 266, 319, 373, 426, 479, 532, 585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064, 1117 }; public static void RoundNumber(ref NumberBuffer number, int pos) { Span<byte> digits = number.Digits; int i; for (i = 0; i < pos && digits[i] != 0; i++) { } if (i == pos && digits[i] >= 53) { while (i > 0 && digits[i - 1] == 57) { i--; } if (i > 0) { digits[i - 1]++; } else { number.Scale++; digits[0] = 49; i = 1; } } else { while (i > 0 && digits[i - 1] == 48) { i--; } } if (i == 0) { number.Scale = 0; number.IsNegative = false; } digits[i] = 0; } internal static bool NumberBufferToDouble(ref NumberBuffer number, out double value) { double num = NumberToDouble(ref number); uint num2 = DoubleHelper.Exponent(num); ulong num3 = DoubleHelper.Mantissa(num); switch (num2) { case 2047u: value = 0.0; return false; case 0u: if (num3 == 0L) { num = 0.0; } break; } value = num; return true; } public unsafe static bool NumberBufferToDecimal(ref NumberBuffer number, ref decimal value) { MutableDecimal value2 = default(MutableDecimal); byte* ptr = number.UnsafeDigits; int num = number.Scale; if (*ptr == 0) { if (num > 0) { num = 0; } } else { if (num > 29) { return false; } while ((num > 0 || (*ptr != 0 && num > -28)) && (value2.High < 429496729 || (value2.High == 429496729 && (value2.Mid < 2576980377u || (value2.Mid == 2576980377u && (value2.Low < 2576980377u || (value2.Low == 2576980377u && *ptr <= 53))))))) { DecimalDecCalc.DecMul10(ref value2); if (*ptr != 0) { DecimalDecCalc.DecAddInt32(ref value2, (uint)(*(ptr++) - 48)); } num--; } if (*(ptr++) >= 53) { bool flag = true; if (*(ptr - 1) == 53 && *(ptr - 2) % 2 == 0) { int num2 = 20; while (*ptr == 48 && num2 != 0) { ptr++; num2--; } if (*ptr == 0 || num2 == 0) { flag = false; } } if (flag) { DecimalDecCalc.DecAddInt32(ref value2, 1u); if ((value2.High | value2.Mid | value2.Low) == 0) { value2.High = 429496729u; value2.Mid = 2576980377u; value2.Low = 2576980378u; num++; } } } } if (num > 0) { return false; } if (num <= -29) { value2.High = 0u; value2.Low = 0u; value2.Mid = 0u; value2.Scale = 28; } else { value2.Scale = -num; } value2.IsNegative = number.IsNegative; value = System.Runtime.CompilerServices.Unsafe.As<MutableDecimal, decimal>(ref value2); return true; } public static void DecimalToNumber(decimal value, ref NumberBuffer number) { ref MutableDecimal reference = ref System.Runtime.CompilerServices.Unsafe.As<decimal, MutableDecimal>(ref value); Span<byte> digits = number.Digits; number.IsNegative = reference.IsNegative; int num = 29; while ((reference.Mid != 0) | (reference.High != 0)) { uint num2 = DecimalDecCalc.DecDivMod1E9(ref reference); for (int i = 0; i < 9; i++) { digits[--num] = (byte)(num2 % 10 + 48); num2 /= 10; } } for (uint num3 = reference.Low; num3 != 0; num3 /= 10) { digits[--num] = (byte)(num3 % 10 + 48); } int num4 = 29 - num; number.Scale = num4 - reference.Scale; Span<byte> digits2 = number.Digits; int index = 0; while (--num4 >= 0) { digits2[index++] = digits[num++]; } digits2[index] = 0; } private static uint DigitsToInt(ReadOnlySpan<byte> digits, int count) { uint value; int bytesConsumed; bool flag = Utf8Parser.TryParse(digits.Slice(0, count), out value, out bytesConsumed, 'D'); return value; } private static ulong Mul32x32To64(uint a, uint b) { return (ulong)a * (ulong)b; } private static ulong Mul64Lossy(ulong a, ulong b, ref int pexp) { ulong num = Mul32x32To64((uint)(a >> 32), (uint)(b >> 32)) + (Mul32x32To64((uint)(a >> 32), (uint)b) >> 32) + (Mul32x32To64((uint)a, (uint)(b >> 32)) >> 32); if ((num & 0x8000000000000000uL) == 0L) { num <<= 1; pexp--; } return num; } private static int abs(int value) { if (value < 0) { return -value; } return value; } private unsafe static double NumberToDouble(ref NumberBuffer number) { ReadOnlySpan<byte> digits = number.Digits; int i = 0; int numDigits = number.NumDigits; int num = numDigits; for (; digits[i] == 48; i++) { num--; } if (num == 0) { return 0.0; } int num2 = Math.Min(num, 9); num -= num2; ulong num3 = DigitsToInt(digits, num2); if (num > 0) { num2 = Math.Min(num, 9); num -= num2; uint b = (uint)(s_rgval64Power10[num2 - 1] >> 64 - s_rgexp64Power10[num2 - 1]); num3 = Mul32x32To64((uint)num3, b) + DigitsToInt(digits.Slice(9), num2); } int num4 = number.Scale - (numDigits - num); int num5 = abs(num4); if (num5 >= 352) { ulong num6 = ((num4 > 0) ? 9218868437227405312uL : 0); if (number.IsNegative) { num6 |= 0x8000000000000000uL; } return *(double*)(&num6); } int pexp = 64; if ((num3 & 0xFFFFFFFF00000000uL) == 0L) { num3 <<= 32; pexp -= 32; } if ((num3 & 0xFFFF000000000000uL) == 0L) { num3 <<= 16; pexp -= 16; } if ((num3 & 0xFF00000000000000uL) == 0L) { num3 <<= 8; pexp -= 8; } if ((num3 & 0xF000000000000000uL) == 0L) { num3 <<= 4; pexp -= 4; } if ((num3 & 0xC000000000000000uL) == 0L) { num3 <<= 2; pexp -= 2; } if ((num3 & 0x8000000000000000uL) == 0L) { num3 <<= 1; pexp--; } int num7 = num5 & 0xF; if (num7 != 0) { int num8 = s_rgexp64Power10[num7 - 1]; pexp += ((num4 < 0) ? (-num8 + 1) : num8); ulong b2 = s_rgval64Power10[num7 + ((num4 < 0) ? 15 : 0) - 1]; num3 = Mul64Lossy(num3, b2, ref pexp); } num7 = num5 >> 4; if (num7 != 0) { int num9 = s_rgexp64Power10By16[num7 - 1]; pexp += ((num4 < 0) ? (-num9 + 1) : num9); ulong b3 = s_rgval64Power10By16[num7 + ((num4 < 0) ? 21 : 0) - 1]; num3 = Mul64Lossy(num3, b3, ref pexp); } if (((uint)(int)num3 & 0x400u) != 0) { ulong num10 = num3 + 1023 + (ulong)(((int)num3 >> 11) & 1); if (num10 < num3) { num10 = (num10 >> 1) | 0x8000000000000000uL; pexp++; } num3 = num10; } pexp += 1022; num3 = ((pexp <= 0) ? ((pexp == -52 && num3 >= 9223372036854775896uL) ? 1 : ((pexp > -52) ? (num3 >> -pexp + 11 + 1) : 0)) : ((pexp < 2047) ? ((ulong)((long)pexp << 52) + ((num3 >> 11) & 0xFFFFFFFFFFFFFL)) : 9218868437227405312uL)); if (number.IsNegative) { num3 |= 0x8000000000000000uL; } return *(double*)(&num3); } } internal ref struct NumberBuffer { public int Scale; public bool IsNegative; public const int BufferSize = 51; private byte _b0; private byte _b1; private byte _b2; private byte _b3; private byte _b4; private byte _b5; private byte _b6; private byte _b7; private byte _b8; private byte _b9; private byte _b10; private byte _b11; private byte _b12; private byte _b13; private byte _b14; private byte _b15; private byte _b16; private byte _b17; private byte _b18; private byte _b19; private byte _b20; private byte _b21; private byte _b22; private byte _b23; private byte _b24; private byte _b25; private byte _b26; private byte _b27; private byte _b28; private byte _b29; private byte _b30; private byte _b31; private byte _b32; private byte _b33; private byte _b34; private byte _b35; private byte _b36; private byte _b37; private byte _b38; private byte _b39; private byte _b40; private byte _b41; private byte _b42; private byte _b43; private byte _b44; private byte _b45; private byte _b46; private byte _b47; private byte _b48; private byte _b49; private byte _b50; public unsafe Span<byte> Digits => new Span<byte>(System.Runtime.CompilerServices.Unsafe.AsPointer<byte>(ref _b0), 51); public unsafe byte* UnsafeDigits => (byte*)System.Runtime.CompilerServices.Unsafe.AsPointer<byte>(ref _b0); public int NumDigits => Digits.IndexOf<byte>(0); [Conditional("DEBUG")] public void CheckConsistency() { } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); stringBuilder.Append('"'); Span<byte> digits = Digits; for (int i = 0; i < 51; i++) { byte b = digits[i]; if (b == 0) { break; } stringBuilder.Append((char)b); } stringBuilder.Append('"'); stringBuilder.Append(", Scale = " + Scale); stringBuilder.Append(", IsNegative = " + IsNegative); stringBuilder.Append(']'); return stringBuilder.ToString(); } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory<T> { private readonly object _object; private readonly int _index; private readonly int _length; private const int RemoveFlagsBitMask = int.MaxValue; public static Memory<T> Empty => default(Memory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Span<T> result; if (_index < 0) { result = ((MemoryManager<T>)_object).GetSpan(); return result.Slice(_index & 0x7FFFFFFF, _length); } if (typeof(T) == typeof(char) && _object is string text) { result = new Span<T>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new Span<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(Span<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) { this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[] array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = array.Length - start; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int length) { if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager<T> manager, int start, int length) { if (length < 0 || start < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = start | int.MinValue; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(object obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator Memory<T>(T[] array) { return new Memory<T>(array); } public static implicit operator Memory<T>(ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { return System.Runtime.CompilerServices.Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.Memory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { int length2 = _length; int num = length2 & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = System.Runtime.CompilerServices.Unsafe.Add<T>(System.Runtime.CompilerServices.Unsafe.AsPointer<T>(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer3, handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> readOnlyMemory) { return readOnlyMemory.Equals(this); } if (obj is Memory<T> other) { return Equals(other); } return false; } public bool Equals(Memory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } int hashCode = _object.GetHashCode(); int index = _index; int hashCode2 = index.GetHashCode(); index = _length; return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } internal sealed class MemoryDebugView<T> { private readonly ReadOnlyMemory<T> _memory; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _memory.ToArray(); public MemoryDebugView(Memory<T> memory) { _memory = memory; } public MemoryDebugView(ReadOnlyMemory<T> memory) { _memory = memory; } } public static class MemoryExtensions { internal static readonly IntPtr StringAdjustment = MeasureStringAdjustment(); public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span) { return span.TrimStart().TrimEnd(); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span) { int num = span.Length - 1; while (num >= 0 && char.IsWhiteSpace(span[num])) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, char trimChar) { return span.TrimStart(trimChar).TrimEnd(trimChar); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, char trimChar) { int i; for (i = 0; i < span.Length && span[i] == trimChar; i++) { } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, char trimChar) { int num = span.Length - 1; while (num >= 0 && span[num] == trimChar) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { return span.TrimStart(trimChars).TrimEnd(trimChars); } public static ReadOnlySpan<char> TrimStart(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimStart(); } int i; for (i = 0; i < span.Length; i++) { int num = 0; while (num < trimChars.Length) { if (span[i] != trimChars[num]) { num++; continue; } goto IL_003c; } break; IL_003c:; } return span.Slice(i); } public static ReadOnlySpan<char> TrimEnd(this ReadOnlySpan<char> span, ReadOnlySpan<char> trimChars) { if (trimChars.IsEmpty) { return span.TrimEnd(); } int num; for (num = span.Length - 1; num >= 0; num--) { int num2 = 0; while (num2 < trimChars.Length) { if (span[num] != trimChars[num2]) { num2++; continue; } goto IL_0044; } break; IL_0044:; } return span.Slice(0, num + 1); } public static bool IsWhiteSpace(this ReadOnlySpan<char> span) { for (int i = 0; i < span.Length; i++) { if (!char.IsWhiteSpace(span[i])) { return false; } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } public static int SequenceCompareTo<T>(this Span<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value), span.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, char>(ref value), span.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOf(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), value.Length); } return System.SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.IndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this Span<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, T value0, T value1, T value2) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value0), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value1), System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value2), span.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> values) where T : IEquatable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.LastIndexOfAny(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(values)), values.Length); } return System.SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IEquatable<T> { int length = span.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), (NUInt)length * size); } return false; } if (length == other.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SequenceCompareTo<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) where T : IComparable<T> { if (typeof(T) == typeof(byte)) { return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return System.SpanHelpers.SequenceCompareTo(ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref System.Runtime.CompilerServices.Unsafe.As<T, char>(ref MemoryMarshal.GetReference(other)), other.Length); } return System.SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length * size); } return false; } if (length <= span.Length) { return System.SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T> { int length = span.Length; int length2 = value.Length; if (default(T) != null && IsTypeComparableAsBytes<T>(out var size)) { if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2)), ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size); } return false; } if (length2 <= length) { return System.SpanHelpers.SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref MemoryMarshal.GetReference(span), length - length2), ref MemoryMarshal.GetReference(value), length2); } return false; } public static void Reverse<T>(this Span<T> span) { ref T reference = ref MemoryMarshal.GetReference(span); int num = 0; int num2 = span.Length - 1; while (num < num2) { T val = System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num); System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num) = System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num2); System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, num2) = val; num++; num2--; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array) { return new Span<T>(array); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array, int start, int length) { return new Span<T>(array, start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Span<T>(segment.Array, segment.Offset + start, segment.Count - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Span<T>(segment.Array, segment.Offset + start, length); } public static Memory<T> AsMemory<T>(this T[] array) { return new Memory<T>(array); } public static Memory<T> AsMemory<T>(this T[] array, int start) { return new Memory<T>(array, start); } public static Memory<T> AsMemory<T>(this T[] array, int start, int length) { return new Memory<T>(array, start, length); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment) { return new Memory<T>(segment.Array, segment.Offset, segment.Count); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new Memory<T>(segment.Array, segment.Offset + start, segment.Count - start); } public static Memory<T> AsMemory<T>(this ArraySegment<T> segment, int start, int length) { if ((uint)start > segment.Count) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } if ((uint)length > segment.Count - start) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.length); } return new Memory<T>(segment.Array, segment.Offset + start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] source, Span<T> destination) { new ReadOnlySpan<T>(source).CopyTo(destination); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo<T>(this T[] source, Memory<T> destination) { source.CopyTo(destination.Span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other) { return ((ReadOnlySpan<T>)span).Overlaps(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps<T>(this Span<T> span, ReadOnlySpan<T> other, out int elementOffset) { return ((ReadOnlySpan<T>)span).Overlaps(other, out elementOffset); } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other) { if (span.IsEmpty || other.IsEmpty) { return false; } IntPtr intPtr = System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (System.Runtime.CompilerServices.Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr >= (uint)(span.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>())) { return (uint)(int)intPtr > (uint)(-(other.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>())); } return true; } if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>())) { return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>())); } return true; } public static bool Overlaps<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other, out int elementOffset) { if (span.IsEmpty || other.IsEmpty) { elementOffset = 0; return false; } IntPtr intPtr = System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (System.Runtime.CompilerServices.Unsafe.SizeOf<IntPtr>() == 4) { if ((uint)(int)intPtr < (uint)(span.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()))) { if ((int)intPtr % System.Runtime.CompilerServices.Unsafe.SizeOf<T>() != 0) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)intPtr / System.Runtime.CompilerServices.Unsafe.SizeOf<T>(); return true; } elementOffset = 0; return false; } if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)System.Runtime.CompilerServices.Unsafe.SizeOf<T>()))) { if ((long)intPtr % System.Runtime.CompilerServices.Unsafe.SizeOf<T>() != 0L) { System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)((long)intPtr / System.Runtime.CompilerServices.Unsafe.SizeOf<T>()); return true; } elementOffset = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this Span<T> span, IComparable<T> comparable) { return span.BinarySearch<T, IComparable<T>>(comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this Span<T> span, TComparable comparable) where TComparable : IComparable<T> { return BinarySearch((ReadOnlySpan<T>)span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this Span<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { return ((ReadOnlySpan<T>)span).BinarySearch(value, comparer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T>(this ReadOnlySpan<T> span, IComparable<T> comparable) { return MemoryExtensions.BinarySearch<T, IComparable<T>>(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { return System.SpanHelpers.BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparer>(this ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : IComparer<T> { if (comparer == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparer); } System.SpanHelpers.ComparerComparable<T, TComparer> comparable = new System.SpanHelpers.ComparerComparable<T, TComparer>(value, comparer); return BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsTypeComparableAsBytes<T>(out NUInt size) { if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) { size = (NUInt)1; return true; } if (typeof(T) == typeof(char) || typeof(T) == typeof(short) || typeof(T) == typeof(ushort)) { size = (NUInt)2; return true; } if (typeof(T) == typeof(int) || typeof(T) == typeof(uint)) { size = (NUInt)4; return true; } if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong)) { size = (NUInt)8; return true; } size = default(NUInt); return false; } public static Span<T> AsSpan<T>(this T[] array, int start) { return Span<T>.Create(array, start); } public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { return span.IndexOf(value, comparisonType) >= 0; } public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.SequenceEqual(other); case StringComparison.OrdinalIgnoreCase: if (span.Length != other.Length) { return false; } return EqualsOrdinalIgnoreCase(span, other); default: return span.ToString().Equals(other.ToString(), comparisonType); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool EqualsOrdinalIgnoreCase(ReadOnlySpan<char> span, ReadOnlySpan<char> other) { if (other.Length == 0) { return true; } return CompareToOrdinalIgnoreCase(span, other) == 0; } public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { return comparisonType switch { StringComparison.Ordinal => span.SequenceCompareTo(other), StringComparison.OrdinalIgnoreCase => CompareToOrdinalIgnoreCase(span, other), _ => string.Compare(span.ToString(), other.ToString(), comparisonType), }; } private unsafe static int CompareToOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) { int num = Math.Min(strA.Length, strB.Length); int num2 = num; fixed (char* ptr = &MemoryMarshal.GetReference(strA)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(strB)) { char* ptr2 = ptr; char* ptr4 = ptr3; while (num != 0 && *ptr2 <= '\u007f' && *ptr4 <= '\u007f') { int num3 = *ptr2; int num4 = *ptr4; if (num3 == num4) { ptr2++; ptr4++; num--; continue; } if ((uint)(num3 - 97) <= 25u) { num3 -= 32; } if ((uint)(num4 - 97) <= 25u) { num4 -= 32; } if (num3 != num4) { return num3 - num4; } ptr2++; ptr4++; num--; } if (num == 0) { return strA.Length - strB.Length; } num2 -= num; return string.Compare(strA.Slice(num2).ToString(), strB.Slice(num2).ToString(), StringComparison.OrdinalIgnoreCase); } } } public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { if (comparisonType == StringComparison.Ordinal) { return span.IndexOf(value); } return span.ToString().IndexOf(value.ToString(), comparisonType); } public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); } if (destination.Length < source.Length) { return -1; } string text = source.ToString(); string text2 = text.ToLower(culture); AsSpan(text2).CopyTo(destination); return source.Length; } public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToLower(destination, CultureInfo.InvariantCulture); } public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture); } if (destination.Length < source.Length) { return -1; } string text = source.ToString(); string text2 = text.ToUpper(culture); AsSpan(text2).CopyTo(destination); return source.Length; } public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination) { return source.ToUpper(destination, CultureInfo.InvariantCulture); } public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.EndsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.EndsWith(value2, comparisonType); } } } public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.Ordinal: return span.StartsWith(value); case StringComparison.OrdinalIgnoreCase: if (value.Length <= span.Length) { return EqualsOrdinalIgnoreCase(span.Slice(0, value.Length), value); } return false; default: { string text = span.ToString(); string value2 = value.ToString(); return text.StartsWith(value2, comparisonType); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text) { if (text == null) { return default(ReadOnlySpan<char>); } return new ReadOnlySpan<char>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text), StringAdjustment, text.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text), StringAdjustment + start * 2, text.Length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlySpan<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlySpan<char>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text), StringAdjustment + start * 2, length); } public static ReadOnlyMemory<char> AsMemory(this string text) { if (text == null) { return default(ReadOnlyMemory<char>); } return new ReadOnlyMemory<char>(text, 0, text.Length); } public static ReadOnlyMemory<char> AsMemory(this string text, int start) { if (text == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, text.Length - start); } public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(ReadOnlyMemory<char>); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<char>(text, start, length); } private unsafe static IntPtr MeasureStringAdjustment() { string text = "a"; fixed (char* ptr = text) { return System.Runtime.CompilerServices.Unsafe.ByteOffset<char>(ref System.Runtime.CompilerServices.Unsafe.As<Pinnable<char>>((object)text).Data, ref System.Runtime.CompilerServices.Unsafe.AsRef<char>((void*)ptr)); } } } [DebuggerTypeProxy(typeof(System.MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct ReadOnlyMemory<T> { private readonly object _object; private readonly int _index; private readonly int _length; internal const int RemoveFlagsBitMask = int.MaxValue; public static ReadOnlyMemory<T> Empty => default(ReadOnlyMemory<T>); public int Length => _length & 0x7FFFFFFF; public bool IsEmpty => (_length & 0x7FFFFFFF) == 0; public ReadOnlySpan<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) { return ((MemoryManager<T>)_object).GetSpan().Slice(_index & 0x7FFFFFFF, _length); } ReadOnlySpan<T> result; if (typeof(T) == typeof(char) && _object is string text) { result = new ReadOnlySpan<T>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)text), MemoryExtensions.StringAdjustment, text.Length); return result.Slice(_index, _length); } if (_object != null) { return new ReadOnlySpan<T>((T[])_object, _index, _length & 0x7FFFFFFF); } result = default(ReadOnlySpan<T>); return result; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array) { if (array == null) { this = default(ReadOnlyMemory<T>); return; } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(ReadOnlyMemory<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlyMemory(object obj, int start, int length) { _object = obj; _index = start; _length = length; } public static implicit operator ReadOnlyMemory<T>(T[] array) { return new ReadOnlyMemory<T>(array); } public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) { return new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length & 0x7FFFFFFF); } return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length & 0x7FFFFFFF}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start) { int length = _length; int num = length & 0x7FFFFFFF; if ((uint)start > (uint)num) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory<T> Slice(int start, int length) { int length2 = _length; int num = _length & 0x7FFFFFFF; if ((uint)start > (uint)num || (uint)length > (uint)(num - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return new ReadOnlyMemory<T>(_object, _index + start, length | (length2 & int.MinValue)); } public void CopyTo(Memory<T> destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory<T> destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { if (_index < 0) { return ((MemoryManager<T>)_object).Pin(_index & 0x7FFFFFFF); } if (typeof(T) == typeof(char) && _object is string value) { GCHandle handle = GCHandle.Alloc(value, GCHandleType.Pinned); void* pointer = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer, handle); } if (_object is T[] array) { if (_length < 0) { void* pointer2 = System.Runtime.CompilerServices.Unsafe.Add<T>(System.Runtime.CompilerServices.Unsafe.AsPointer<T>(ref MemoryMarshal.GetReference<T>(array)), _index); return new MemoryHandle(pointer2); } GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer3 = System.Runtime.CompilerServices.Unsafe.Add<T>((void*)handle2.AddrOfPinnedObject(), _index); return new MemoryHandle(pointer3, handle2); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T> other) { return Equals(other); } if (obj is Memory<T> memory) { return Equals(memory); } return false; } public bool Equals(ReadOnlyMemory<T> other) { if (_object == other._object && _index == other._index) { return _length == other._length; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { if (_object == null) { return 0; } int hashCode = _object.GetHashCode(); int index = _index; int hashCode2 = index.GetHashCode(); index = _length; return CombineHashCodes(hashCode, hashCode2, index.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal object GetObjectStartLength(out int start, out int length) { start = _index; length = _length; return _object; } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct ReadOnlySpan<T> { public ref struct Enumerator { private readonly ReadOnlySpan<T> _span; private int _index; public ref readonly T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(ReadOnlySpan<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly Pinnable<T> _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>); public unsafe ref readonly T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable<T> Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { return !(left == right); } [Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator ReadOnlySpan<T>(T[] array) { return new ReadOnlySpan<T>(array); } public static implicit operator ReadOnlySpan<T>(ArraySegment<T> segment) { return new ReadOnlySpan<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array) { if (array == null) { this = default(ReadOnlySpan<T>); return; } _length = array.Length; _pinnable = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(ReadOnlySpan<T>); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe ReadOnlySpan(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(Pinnable<T> pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref readonly T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset); } return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>((void*)null); } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination.Length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { if (left._length == right._length) { return System.Runtime.CompilerServices.Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { if (_byteOffset == MemoryExtensions.StringAdjustment) { object obj = System.Runtime.CompilerServices.Unsafe.As<object>((object)_pinnable); if (obj is string text && _length == text.Length) { return text; } } fixed (char* value = &System.Runtime.CompilerServices.Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new ReadOnlySpan<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal unsafe ref T DangerousGetPinnableReference() { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset); } } [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [DebuggerTypeProxy(typeof(System.SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly ref struct Span<T> { public ref struct Enumerator { private readonly Span<T> _span; private int _index; public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span<T> span) { _span = span; _index = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int num = _index + 1; if (num < _span.Length) { _index = num; return true; } return false; } } private readonly Pinnable<T> _pinnable; private readonly IntPtr _byteOffset; private readonly int _length; public int Length => _length; public bool IsEmpty => _length == 0; public static Span<T> Empty => default(Span<T>); public unsafe ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)_length) { System.ThrowHelper.ThrowIndexOutOfRangeException(); } if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()), index); } return ref System.Runtime.CompilerServices.Unsafe.Add<T>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index); } } internal Pinnable<T> Pinnable => _pinnable; internal IntPtr ByteOffset => _byteOffset; public static bool operator !=(Span<T> left, Span<T> right) { return !(left == right); } [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(System.SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(System.SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator Span<T>(T[] array) { return new Span<T>(array); } public static implicit operator Span<T>(ArraySegment<T> segment) { return new Span<T>(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array) { if (array == null) { this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } _length = array.Length; _pinnable = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Span<T> Create(T[] array, int start) { if (array == null) { if (start != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } return default(Span<T>); } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); int length = array.Length - start; return new Span<T>(System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array), byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } this = default(Span<T>); return; } if (default(T) == null && array.GetType() != typeof(T[])) { System.ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array); _byteOffset = System.SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe Span(void* pointer, int length) { if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { System.ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length) { _length = length; _pinnable = pinnable; _byteOffset = byteOffset; } [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset); } return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>((void*)null); } public unsafe void Clear() { int length = _length; if (length == 0) { return; } UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>()); if ((System.Runtime.CompilerServices.Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0) { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; byte* ptr = (byte*)byteOffset.ToPointer(); System.SpanHelpers.ClearLessThanPointerSized(ptr, byteLength); } else { System.SpanHelpers.ClearLessThanPointerSized(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset)), byteLength); } } else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>()) { UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * System.Runtime.CompilerServices.Unsafe.SizeOf<T>() / sizeof(IntPtr)); System.SpanHelpers.ClearPointerSizedWithReferences(ref System.Runtime.CompilerServices.Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength); } else { System.SpanHelpers.ClearPointerSizedWithoutReferences(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength); } } public unsafe void Fill(T value) { int length = _length; if (length == 0) { return; } if (System.Runtime.CompilerServices.Unsafe.SizeOf<T>() == 1) { byte b = System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref value); if (_pinnable == null) { IntPtr byteOffset = _byteOffset; System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), b, (uint)length); } else { System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(ref System.Runtime.CompilerServices.Unsafe.As<T, byte>(ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset)), b, (uint)length); } return; } ref T reference = ref DangerousGetPinnableReference(); int i; for (i = 0; i < (length & -8); i += 8) { System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 1) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 2) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 3) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 4) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 5) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 6) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 7) = value; } if (i < (length & -4)) { System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 1) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 2) = value; System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i + 3) = value; i += 4; } for (; i < length; i++) { System.Runtime.CompilerServices.Unsafe.Add<T>(ref reference, i) = value; } } public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) { System.ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span<T> destination) { int length = _length; int length2 = destination._length; if (length == 0) { return true; } if ((uint)length > (uint)length2) { return false; } ref T src = ref DangerousGetPinnableReference(); System.SpanHelpers.CopyTo(ref destination.DangerousGetPinnableReference(), length2, ref src, length); return true; } public static bool operator ==(Span<T> left, Span<T> right) { if (left._length == right._length) { return System.Runtime.CompilerServices.Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference()); } return false; } public static implicit operator ReadOnlySpan<T>(Span<T> span) { return new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length); } public unsafe override string ToString() { if (typeof(T) == typeof(char)) { fixed (char* value = &System.Runtime.CompilerServices.Unsafe.As<T, char>(ref DangerousGetPinnableReference())) { return new string(value, 0, _length); } } return $"System.Span<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); int length = _length - start; return new Span<T>(_pinnable, byteOffset, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.start); } IntPtr byteOffset = _byteOffset.Add<T>(start); return new Span<T>(_pinnable, byteOffset, length); } public T[] ToArray() { if (_length == 0) { return System.SpanHelpers.PerTypeValues<T>.EmptyArray; } T[] array = new T[_length]; CopyTo(array); return array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal unsafe ref T DangerousGetPinnableReference() { if (_pinnable == null) { IntPtr byteOffset = _byteOffset; return ref System.Runtime.CompilerServices.Unsafe.AsRef<T>(byteOffset.ToPointer()); } return ref System.Runtime.CompilerServices.Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset); } } internal sealed class SpanDebugView<T> { private readonly T[] _array; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _array; public SpanDebugView(Span<T> span) { _array = span.ToArray(); } public SpanDebugView(ReadOnlySpan<T> span) { _array = span.ToArray(); } } internal static class SpanHelpers { internal struct ComparerComparable<T, TComparer> : IComparable<T> where TComparer : IComparer<T> { private readonly T _value; private readonly TComparer _comparer; public ComparerComparable(T value, TComparer comparer) { _value = value; _comparer = comparer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int CompareTo(T other) { return _comparer.Compare(_value, other); } } [StructLayout(LayoutKind.Sequential, Size = 64)] private struct Reg64 { } [StructLayout(LayoutKind.Sequential, Size = 32)] private struct Reg32 { } [StructLayout(LayoutKind.Sequential, Size = 16)] private struct Reg16 { } public static class PerTypeValues<T> { public static readonly bool IsReferenceOrContainsReferences = IsReferenceOrContainsReferencesCore(typeof(T)); public static readonly T[] EmptyArray = new T[0]; public static readonly IntPtr ArrayAdjustment = MeasureArrayAdjustment(); private static IntPtr MeasureArrayAdjustment() { T[] array = new T[1]; return System.Runtime.CompilerServices.Unsafe.ByteOffset<T>(ref System.Runtime.CompilerServices.Unsafe.As<Pinnable<T>>((object)array).Data, ref array[0]); } } private const ulong XorPowerOfTwoToHighByte = 283686952306184uL; private const ulong XorPowerOfTwoToHighChar = 4295098372uL; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch<T, TComparable>(this ReadOnlySpan<T> span, TComparable comparable) where TComparable : IComparable<T> { if (comparable == null) { System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.comparable); } return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable); } public static int BinarySearch<T, TComparable>(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable<T> { int num = 0; int num2 = length - 1; while (num <= num2) { int num3 = num2 + num >>> 1; int num4 = comparable.CompareTo(System.Runtime.CompilerServices.Unsafe.Add<T>(ref spanStart, num3)); if (num4 == 0) { return num3; } if (num4 > 0) { num = num3 + 1; } else { num2 = num3 - 1; } } return ~num; } public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref System.Runtime.CompilerServices.Unsafe.Add<byte>(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = IndexOf(ref System.Runtime.CompilerServices.Unsafe.Add<byte>(ref searchSpace, num2), value2, num3); if (num4 == -1) { break; } num2 += num4; if (SequenceEqual(ref System.Runtime.CompilerServices.Unsafe.Add<byte>(ref searchSpace, num2 + 1), ref second, num)) { return num2; } num2++; } return -1; } public static int IndexOfAny(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } int num = -1; for (int i = 0; i < valueLength; i++) { int num2 = IndexOf(ref searchSpace, System.Runtime.CompilerServices.Unsafe.Add<byte>(ref value, i), searchSpaceLength); if ((uint)num2 < (uint)num) { num = num2; searchSpaceLength = num2; if (num == 0) { break;
plugins/BingBongHelper/System.Numerics.Vectors.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Diagnostics; using System.Globalization; using System.Numerics; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Numerics.Vectors; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Numerics.Vectors")] [assembly: AssemblyDescription("System.Numerics.Vectors")] [assembly: AssemblyDefaultAlias("System.Numerics.Vectors")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.26515.06")] [assembly: AssemblyInformationalVersion("4.6.26515.06 @BuiltBy: dlab-DDVSOWINAGE059 @Branch: release/2.1 @SrcCode: https://github.com/dotnet/corefx/tree/30ab651fcb4354552bd4891619a0bdd81e0ebdbf")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.1.4.0")] [assembly: TypeForwardedTo(typeof(Matrix3x2))] [assembly: TypeForwardedTo(typeof(Matrix4x4))] [assembly: TypeForwardedTo(typeof(Plane))] [assembly: TypeForwardedTo(typeof(Quaternion))] [assembly: TypeForwardedTo(typeof(Vector2))] [assembly: TypeForwardedTo(typeof(Vector3))] [assembly: TypeForwardedTo(typeof(Vector4))] [module: UnverifiableCode] namespace FxResources.System.Numerics.Vectors { internal static class SR { } } namespace System { internal static class MathF { public const float PI = 3.1415927f; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) { return Math.Abs(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acos(float x) { return (float)Math.Acos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(float x) { return (float)Math.Cos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float IEEERemainder(float x, float y) { return (float)Math.IEEERemainder(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Pow(float x, float y) { return (float)Math.Pow(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(float x) { return (float)Math.Sin(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(float x) { return (float)Math.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tan(float x) { return (float)Math.Tan(x); } } internal static class SR { private static ResourceManager s_resourceManager; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static Type ResourceType { get; } = typeof(SR); internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException", null); internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination", null); internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef", null); internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported", null); internal static string Arg_InsufficientNumberOfElements => GetResourceString("Arg_InsufficientNumberOfElements", null); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, Inherited = false)] internal sealed class IntrinsicAttribute : Attribute { } } namespace System.Numerics { internal class ConstantHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte GetByteWithAllBitsSet() { byte result = 0; result = byte.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static sbyte GetSByteWithAllBitsSet() { sbyte result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort GetUInt16WithAllBitsSet() { ushort result = 0; result = ushort.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short GetInt16WithAllBitsSet() { short result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint GetUInt32WithAllBitsSet() { uint result = 0u; result = uint.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetInt32WithAllBitsSet() { int result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong GetUInt64WithAllBitsSet() { ulong result = 0uL; result = ulong.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long GetInt64WithAllBitsSet() { long result = 0L; result = -1L; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static float GetSingleWithAllBitsSet() { float result = 0f; *(int*)(&result) = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static double GetDoubleWithAllBitsSet() { double result = 0.0; *(long*)(&result) = -1L; return result; } } [StructLayout(LayoutKind.Explicit)] internal struct Register { [FieldOffset(0)] internal byte byte_0; [FieldOffset(1)] internal byte byte_1; [FieldOffset(2)] internal byte byte_2; [FieldOffset(3)] internal byte byte_3; [FieldOffset(4)] internal byte byte_4; [FieldOffset(5)] internal byte byte_5; [FieldOffset(6)] internal byte byte_6; [FieldOffset(7)] internal byte byte_7; [FieldOffset(8)] internal byte byte_8; [FieldOffset(9)] internal byte byte_9; [FieldOffset(10)] internal byte byte_10; [FieldOffset(11)] internal byte byte_11; [FieldOffset(12)] internal byte byte_12; [FieldOffset(13)] internal byte byte_13; [FieldOffset(14)] internal byte byte_14; [FieldOffset(15)] internal byte byte_15; [FieldOffset(0)] internal sbyte sbyte_0; [FieldOffset(1)] internal sbyte sbyte_1; [FieldOffset(2)] internal sbyte sbyte_2; [FieldOffset(3)] internal sbyte sbyte_3; [FieldOffset(4)] internal sbyte sbyte_4; [FieldOffset(5)] internal sbyte sbyte_5; [FieldOffset(6)] internal sbyte sbyte_6; [FieldOffset(7)] internal sbyte sbyte_7; [FieldOffset(8)] internal sbyte sbyte_8; [FieldOffset(9)] internal sbyte sbyte_9; [FieldOffset(10)] internal sbyte sbyte_10; [FieldOffset(11)] internal sbyte sbyte_11; [FieldOffset(12)] internal sbyte sbyte_12; [FieldOffset(13)] internal sbyte sbyte_13; [FieldOffset(14)] internal sbyte sbyte_14; [FieldOffset(15)] internal sbyte sbyte_15; [FieldOffset(0)] internal ushort uint16_0; [FieldOffset(2)] internal ushort uint16_1; [FieldOffset(4)] internal ushort uint16_2; [FieldOffset(6)] internal ushort uint16_3; [FieldOffset(8)] internal ushort uint16_4; [FieldOffset(10)] internal ushort uint16_5; [FieldOffset(12)] internal ushort uint16_6; [FieldOffset(14)] internal ushort uint16_7; [FieldOffset(0)] internal short int16_0; [FieldOffset(2)] internal short int16_1; [FieldOffset(4)] internal short int16_2; [FieldOffset(6)] internal short int16_3; [FieldOffset(8)] internal short int16_4; [FieldOffset(10)] internal short int16_5; [FieldOffset(12)] internal short int16_6; [FieldOffset(14)] internal short int16_7; [FieldOffset(0)] internal uint uint32_0; [FieldOffset(4)] internal uint uint32_1; [FieldOffset(8)] internal uint uint32_2; [FieldOffset(12)] internal uint uint32_3; [FieldOffset(0)] internal int int32_0; [FieldOffset(4)] internal int int32_1; [FieldOffset(8)] internal int int32_2; [FieldOffset(12)] internal int int32_3; [FieldOffset(0)] internal ulong uint64_0; [FieldOffset(8)] internal ulong uint64_1; [FieldOffset(0)] internal long int64_0; [FieldOffset(8)] internal long int64_1; [FieldOffset(0)] internal float single_0; [FieldOffset(4)] internal float single_1; [FieldOffset(8)] internal float single_2; [FieldOffset(12)] internal float single_3; [FieldOffset(0)] internal double double_0; [FieldOffset(8)] internal double double_1; } [System.Runtime.CompilerServices.Intrinsic] public struct Vector<T> : IEquatable<Vector<T>>, IFormattable where T : struct { private struct VectorSizeHelper { internal Vector<T> _placeholder; internal byte _byte; } private System.Numerics.Register register; private static readonly int s_count = InitializeCount(); private static readonly Vector<T> s_zero = default(Vector<T>); private static readonly Vector<T> s_one = new Vector<T>(GetOneValue()); private static readonly Vector<T> s_allOnes = new Vector<T>(GetAllBitsSetValue()); public static int Count { [System.Runtime.CompilerServices.Intrinsic] get { return s_count; } } public static Vector<T> Zero { [System.Runtime.CompilerServices.Intrinsic] get { return s_zero; } } public static Vector<T> One { [System.Runtime.CompilerServices.Intrinsic] get { return s_one; } } internal static Vector<T> AllOnes => s_allOnes; public unsafe T this[int index] { [System.Runtime.CompilerServices.Intrinsic] get { if (index >= Count || index < 0) { throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index)); } if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { return (T)(object)ptr[index]; } } if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { return (T)(object)ptr2[index]; } } if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { return (T)(object)ptr3[index]; } } if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { return (T)(object)ptr4[index]; } } if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { return (T)(object)ptr5[index]; } } if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { return (T)(object)ptr6[index]; } } if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { return (T)(object)ptr7[index]; } } if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { return (T)(object)ptr8[index]; } } if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { return (T)(object)ptr9[index]; } } if (typeof(T) == typeof(double)) { fixed (double* ptr10 = ®ister.double_0) { return (T)(object)ptr10[index]; } } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } } private unsafe static int InitializeCount() { VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper); byte* ptr = &vectorSizeHelper._placeholder.register.byte_0; byte* ptr2 = &vectorSizeHelper._byte; int num = (int)(ptr2 - ptr); int num2 = -1; if (typeof(T) == typeof(byte)) { num2 = 1; } else if (typeof(T) == typeof(sbyte)) { num2 = 1; } else if (typeof(T) == typeof(ushort)) { num2 = 2; } else if (typeof(T) == typeof(short)) { num2 = 2; } else if (typeof(T) == typeof(uint)) { num2 = 4; } else if (typeof(T) == typeof(int)) { num2 = 4; } else if (typeof(T) == typeof(ulong)) { num2 = 8; } else if (typeof(T) == typeof(long)) { num2 = 8; } else if (typeof(T) == typeof(float)) { num2 = 4; } else { if (!(typeof(T) == typeof(double))) { throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } num2 = 8; } return num / num2; } [System.Runtime.CompilerServices.Intrinsic] public unsafe Vector(T value) { this = default(Vector<T>); if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)value; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)value; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)value; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)value; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)value; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)value; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)value; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)value; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)value; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)value; } } } } else if (typeof(T) == typeof(byte)) { register.byte_0 = (byte)(object)value; register.byte_1 = (byte)(object)value; register.byte_2 = (byte)(object)value; register.byte_3 = (byte)(object)value; register.byte_4 = (byte)(object)value; register.byte_5 = (byte)(object)value; register.byte_6 = (byte)(object)value; register.byte_7 = (byte)(object)value; register.byte_8 = (byte)(object)value; register.byte_9 = (byte)(object)value; register.byte_10 = (byte)(object)value; register.byte_11 = (byte)(object)value; register.byte_12 = (byte)(object)value; register.byte_13 = (byte)(object)value; register.byte_14 = (byte)(object)value; register.byte_15 = (byte)(object)value; } else if (typeof(T) == typeof(sbyte)) { register.sbyte_0 = (sbyte)(object)value; register.sbyte_1 = (sbyte)(object)value; register.sbyte_2 = (sbyte)(object)value; register.sbyte_3 = (sbyte)(object)value; register.sbyte_4 = (sbyte)(object)value; register.sbyte_5 = (sbyte)(object)value; register.sbyte_6 = (sbyte)(object)value; register.sbyte_7 = (sbyte)(object)value; register.sbyte_8 = (sbyte)(object)value; register.sbyte_9 = (sbyte)(object)value; register.sbyte_10 = (sbyte)(object)value; register.sbyte_11 = (sbyte)(object)value; register.sbyte_12 = (sbyte)(object)value; register.sbyte_13 = (sbyte)(object)value; register.sbyte_14 = (sbyte)(object)value; register.sbyte_15 = (sbyte)(object)value; } else if (typeof(T) == typeof(ushort)) { register.uint16_0 = (ushort)(object)value; register.uint16_1 = (ushort)(object)value; register.uint16_2 = (ushort)(object)value; register.uint16_3 = (ushort)(object)value; register.uint16_4 = (ushort)(object)value; register.uint16_5 = (ushort)(object)value; register.uint16_6 = (ushort)(object)value; register.uint16_7 = (ushort)(object)value; } else if (typeof(T) == typeof(short)) { register.int16_0 = (short)(object)value; register.int16_1 = (short)(object)value; register.int16_2 = (short)(object)value; register.int16_3 = (short)(object)value; register.int16_4 = (short)(object)value; register.int16_5 = (short)(object)value; register.int16_6 = (short)(object)value; register.int16_7 = (short)(object)value; } else if (typeof(T) == typeof(uint)) { register.uint32_0 = (uint)(object)value; register.uint32_1 = (uint)(object)value; register.uint32_2 = (uint)(object)value; register.uint32_3 = (uint)(object)value; } else if (typeof(T) == typeof(int)) { register.int32_0 = (int)(object)value; register.int32_1 = (int)(object)value; register.int32_2 = (int)(object)value; register.int32_3 = (int)(object)value; } else if (typeof(T) == typeof(ulong)) { register.uint64_0 = (ulong)(object)value; register.uint64_1 = (ulong)(object)value; } else if (typeof(T) == typeof(long)) { register.int64_0 = (long)(object)value; register.int64_1 = (long)(object)value; } else if (typeof(T) == typeof(float)) { register.single_0 = (float)(object)value; register.single_1 = (float)(object)value; register.single_2 = (float)(object)value; register.single_3 = (float)(object)value; } else if (typeof(T) == typeof(double)) { register.double_0 = (double)(object)value; register.double_1 = (double)(object)value; } } [System.Runtime.CompilerServices.Intrinsic] public Vector(T[] values) : this(values, 0) { } public unsafe Vector(T[] values, int index) { this = default(Vector<T>); if (values == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (index < 0 || values.Length - index < Count) { throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_InsufficientNumberOfElements, Count, "values")); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)values[i + index]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)values[j + index]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)values[k + index]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)values[l + index]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)values[m + index]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)values[n + index]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)values[num + index]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)values[num2 + index]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)values[num3 + index]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)values[num4 + index]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = ®ister.byte_0) { *ptr11 = (byte)(object)values[index]; ptr11[1] = (byte)(object)values[1 + index]; ptr11[2] = (byte)(object)values[2 + index]; ptr11[3] = (byte)(object)values[3 + index]; ptr11[4] = (byte)(object)values[4 + index]; ptr11[5] = (byte)(object)values[5 + index]; ptr11[6] = (byte)(object)values[6 + index]; ptr11[7] = (byte)(object)values[7 + index]; ptr11[8] = (byte)(object)values[8 + index]; ptr11[9] = (byte)(object)values[9 + index]; ptr11[10] = (byte)(object)values[10 + index]; ptr11[11] = (byte)(object)values[11 + index]; ptr11[12] = (byte)(object)values[12 + index]; ptr11[13] = (byte)(object)values[13 + index]; ptr11[14] = (byte)(object)values[14 + index]; ptr11[15] = (byte)(object)values[15 + index]; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = ®ister.sbyte_0) { *ptr12 = (sbyte)(object)values[index]; ptr12[1] = (sbyte)(object)values[1 + index]; ptr12[2] = (sbyte)(object)values[2 + index]; ptr12[3] = (sbyte)(object)values[3 + index]; ptr12[4] = (sbyte)(object)values[4 + index]; ptr12[5] = (sbyte)(object)values[5 + index]; ptr12[6] = (sbyte)(object)values[6 + index]; ptr12[7] = (sbyte)(object)values[7 + index]; ptr12[8] = (sbyte)(object)values[8 + index]; ptr12[9] = (sbyte)(object)values[9 + index]; ptr12[10] = (sbyte)(object)values[10 + index]; ptr12[11] = (sbyte)(object)values[11 + index]; ptr12[12] = (sbyte)(object)values[12 + index]; ptr12[13] = (sbyte)(object)values[13 + index]; ptr12[14] = (sbyte)(object)values[14 + index]; ptr12[15] = (sbyte)(object)values[15 + index]; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = ®ister.uint16_0) { *ptr13 = (ushort)(object)values[index]; ptr13[1] = (ushort)(object)values[1 + index]; ptr13[2] = (ushort)(object)values[2 + index]; ptr13[3] = (ushort)(object)values[3 + index]; ptr13[4] = (ushort)(object)values[4 + index]; ptr13[5] = (ushort)(object)values[5 + index]; ptr13[6] = (ushort)(object)values[6 + index]; ptr13[7] = (ushort)(object)values[7 + index]; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = ®ister.int16_0) { *ptr14 = (short)(object)values[index]; ptr14[1] = (short)(object)values[1 + index]; ptr14[2] = (short)(object)values[2 + index]; ptr14[3] = (short)(object)values[3 + index]; ptr14[4] = (short)(object)values[4 + index]; ptr14[5] = (short)(object)values[5 + index]; ptr14[6] = (short)(object)values[6 + index]; ptr14[7] = (short)(object)values[7 + index]; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = ®ister.uint32_0) { *ptr15 = (uint)(object)values[index]; ptr15[1] = (uint)(object)values[1 + index]; ptr15[2] = (uint)(object)values[2 + index]; ptr15[3] = (uint)(object)values[3 + index]; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = ®ister.int32_0) { *ptr16 = (int)(object)values[index]; ptr16[1] = (int)(object)values[1 + index]; ptr16[2] = (int)(object)values[2 + index]; ptr16[3] = (int)(object)values[3 + index]; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = ®ister.uint64_0) { *ptr17 = (ulong)(object)values[index]; ptr17[1] = (ulong)(object)values[1 + index]; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = ®ister.int64_0) { *ptr18 = (long)(object)values[index]; ptr18[1] = (long)(object)values[1 + index]; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = ®ister.single_0) { *ptr19 = (float)(object)values[index]; ptr19[1] = (float)(object)values[1 + index]; ptr19[2] = (float)(object)values[2 + index]; ptr19[3] = (float)(object)values[3 + index]; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = ®ister.double_0) { *ptr20 = (double)(object)values[index]; ptr20[1] = (double)(object)values[1 + index]; } } } internal unsafe Vector(void* dataPointer) : this(dataPointer, 0) { } internal unsafe Vector(void* dataPointer, int offset) { this = default(Vector<T>); if (typeof(T) == typeof(byte)) { byte* ptr = (byte*)dataPointer; ptr += offset; fixed (byte* ptr2 = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr2[i] = ptr[i]; } } return; } if (typeof(T) == typeof(sbyte)) { sbyte* ptr3 = (sbyte*)dataPointer; ptr3 += offset; fixed (sbyte* ptr4 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr4[j] = ptr3[j]; } } return; } if (typeof(T) == typeof(ushort)) { ushort* ptr5 = (ushort*)dataPointer; ptr5 += offset; fixed (ushort* ptr6 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr6[k] = ptr5[k]; } } return; } if (typeof(T) == typeof(short)) { short* ptr7 = (short*)dataPointer; ptr7 += offset; fixed (short* ptr8 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr8[l] = ptr7[l]; } } return; } if (typeof(T) == typeof(uint)) { uint* ptr9 = (uint*)dataPointer; ptr9 += offset; fixed (uint* ptr10 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr10[m] = ptr9[m]; } } return; } if (typeof(T) == typeof(int)) { int* ptr11 = (int*)dataPointer; ptr11 += offset; fixed (int* ptr12 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr12[n] = ptr11[n]; } } return; } if (typeof(T) == typeof(ulong)) { ulong* ptr13 = (ulong*)dataPointer; ptr13 += offset; fixed (ulong* ptr14 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr14[num] = ptr13[num]; } } return; } if (typeof(T) == typeof(long)) { long* ptr15 = (long*)dataPointer; ptr15 += offset; fixed (long* ptr16 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr16[num2] = ptr15[num2]; } } return; } if (typeof(T) == typeof(float)) { float* ptr17 = (float*)dataPointer; ptr17 += offset; fixed (float* ptr18 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr18[num3] = ptr17[num3]; } } return; } if (typeof(T) == typeof(double)) { double* ptr19 = (double*)dataPointer; ptr19 += offset; fixed (double* ptr20 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr20[num4] = ptr19[num4]; } } return; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } private Vector(ref System.Numerics.Register existingRegister) { register = existingRegister; } [System.Runtime.CompilerServices.Intrinsic] public void CopyTo(T[] destination) { CopyTo(destination, 0); } [System.Runtime.CompilerServices.Intrinsic] public unsafe void CopyTo(T[] destination, int startIndex) { if (destination == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (startIndex < 0 || startIndex >= destination.Length) { throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex)); } if (destination.Length - startIndex < Count) { throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex)); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = (byte[])(object)destination) { for (int i = 0; i < Count; i++) { ptr[startIndex + i] = (byte)(object)this[i]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = (sbyte[])(object)destination) { for (int j = 0; j < Count; j++) { ptr2[startIndex + j] = (sbyte)(object)this[j]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = (ushort[])(object)destination) { for (int k = 0; k < Count; k++) { ptr3[startIndex + k] = (ushort)(object)this[k]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = (short[])(object)destination) { for (int l = 0; l < Count; l++) { ptr4[startIndex + l] = (short)(object)this[l]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = (uint[])(object)destination) { for (int m = 0; m < Count; m++) { ptr5[startIndex + m] = (uint)(object)this[m]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = (int[])(object)destination) { for (int n = 0; n < Count; n++) { ptr6[startIndex + n] = (int)(object)this[n]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = (ulong[])(object)destination) { for (int num = 0; num < Count; num++) { ptr7[startIndex + num] = (ulong)(object)this[num]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = (long[])(object)destination) { for (int num2 = 0; num2 < Count; num2++) { ptr8[startIndex + num2] = (long)(object)this[num2]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = (float[])(object)destination) { for (int num3 = 0; num3 < Count; num3++) { ptr9[startIndex + num3] = (float)(object)this[num3]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = (double[])(object)destination) { for (int num4 = 0; num4 < Count; num4++) { ptr10[startIndex + num4] = (double)(object)this[num4]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = (byte[])(object)destination) { ptr11[startIndex] = register.byte_0; ptr11[startIndex + 1] = register.byte_1; ptr11[startIndex + 2] = register.byte_2; ptr11[startIndex + 3] = register.byte_3; ptr11[startIndex + 4] = register.byte_4; ptr11[startIndex + 5] = register.byte_5; ptr11[startIndex + 6] = register.byte_6; ptr11[startIndex + 7] = register.byte_7; ptr11[startIndex + 8] = register.byte_8; ptr11[startIndex + 9] = register.byte_9; ptr11[startIndex + 10] = register.byte_10; ptr11[startIndex + 11] = register.byte_11; ptr11[startIndex + 12] = register.byte_12; ptr11[startIndex + 13] = register.byte_13; ptr11[startIndex + 14] = register.byte_14; ptr11[startIndex + 15] = register.byte_15; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = (sbyte[])(object)destination) { ptr12[startIndex] = register.sbyte_0; ptr12[startIndex + 1] = register.sbyte_1; ptr12[startIndex + 2] = register.sbyte_2; ptr12[startIndex + 3] = register.sbyte_3; ptr12[startIndex + 4] = register.sbyte_4; ptr12[startIndex + 5] = register.sbyte_5; ptr12[startIndex + 6] = register.sbyte_6; ptr12[startIndex + 7] = register.sbyte_7; ptr12[startIndex + 8] = register.sbyte_8; ptr12[startIndex + 9] = register.sbyte_9; ptr12[startIndex + 10] = register.sbyte_10; ptr12[startIndex + 11] = register.sbyte_11; ptr12[startIndex + 12] = register.sbyte_12; ptr12[startIndex + 13] = register.sbyte_13; ptr12[startIndex + 14] = register.sbyte_14; ptr12[startIndex + 15] = register.sbyte_15; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = (ushort[])(object)destination) { ptr13[startIndex] = register.uint16_0; ptr13[startIndex + 1] = register.uint16_1; ptr13[startIndex + 2] = register.uint16_2; ptr13[startIndex + 3] = register.uint16_3; ptr13[startIndex + 4] = register.uint16_4; ptr13[startIndex + 5] = register.uint16_5; ptr13[startIndex + 6] = register.uint16_6; ptr13[startIndex + 7] = register.uint16_7; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = (short[])(object)destination) { ptr14[startIndex] = register.int16_0; ptr14[startIndex + 1] = register.int16_1; ptr14[startIndex + 2] = register.int16_2; ptr14[startIndex + 3] = register.int16_3; ptr14[startIndex + 4] = register.int16_4; ptr14[startIndex + 5] = register.int16_5; ptr14[startIndex + 6] = register.int16_6; ptr14[startIndex + 7] = register.int16_7; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = (uint[])(object)destination) { ptr15[startIndex] = register.uint32_0; ptr15[startIndex + 1] = register.uint32_1; ptr15[startIndex + 2] = register.uint32_2; ptr15[startIndex + 3] = register.uint32_3; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = (int[])(object)destination) { ptr16[startIndex] = register.int32_0; ptr16[startIndex + 1] = register.int32_1; ptr16[startIndex + 2] = register.int32_2; ptr16[startIndex + 3] = register.int32_3; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = (ulong[])(object)destination) { ptr17[startIndex] = register.uint64_0; ptr17[startIndex + 1] = register.uint64_1; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = (long[])(object)destination) { ptr18[startIndex] = register.int64_0; ptr18[startIndex + 1] = register.int64_1; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = (float[])(object)destination) { ptr19[startIndex] = register.single_0; ptr19[startIndex + 1] = register.single_1; ptr19[startIndex + 2] = register.single_2; ptr19[startIndex + 3] = register.single_3; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = (double[])(object)destination) { ptr20[startIndex] = register.double_0; ptr20[startIndex + 1] = register.double_1; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector<T>)) { return false; } return Equals((Vector<T>)obj); } [System.Runtime.CompilerServices.Intrinsic] public bool Equals(Vector<T> other) { if (Vector.IsHardwareAccelerated) { for (int i = 0; i < Count; i++) { if (!ScalarEquals(this[i], other[i])) { return false; } } return true; } if (typeof(T) == typeof(byte)) { if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14) { return register.byte_15 == other.register.byte_15; } return false; } if (typeof(T) == typeof(sbyte)) { if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14) { return register.sbyte_15 == other.register.sbyte_15; } return false; } if (typeof(T) == typeof(ushort)) { if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6) { return register.uint16_7 == other.register.uint16_7; } return false; } if (typeof(T) == typeof(short)) { if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6) { return register.int16_7 == other.register.int16_7; } return false; } if (typeof(T) == typeof(uint)) { if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2) { return register.uint32_3 == other.register.uint32_3; } return false; } if (typeof(T) == typeof(int)) { if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2) { return register.int32_3 == other.register.int32_3; } return false; } if (typeof(T) == typeof(ulong)) { if (register.uint64_0 == other.register.uint64_0) { return register.uint64_1 == other.register.uint64_1; } return false; } if (typeof(T) == typeof(long)) { if (register.int64_0 == other.register.int64_0) { return register.int64_1 == other.register.int64_1; } return false; } if (typeof(T) == typeof(float)) { if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2) { return register.single_3 == other.register.single_3; } return false; } if (typeof(T) == typeof(double)) { if (register.double_0 == other.register.double_0) { return register.double_1 == other.register.double_1; } return false; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override int GetHashCode() { int num = 0; if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { for (int i = 0; i < Count; i++) { num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode()); } return num; } if (typeof(T) == typeof(sbyte)) { for (int j = 0; j < Count; j++) { num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode()); } return num; } if (typeof(T) == typeof(ushort)) { for (int k = 0; k < Count; k++) { num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode()); } return num; } if (typeof(T) == typeof(short)) { for (int l = 0; l < Count; l++) { num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode()); } return num; } if (typeof(T) == typeof(uint)) { for (int m = 0; m < Count; m++) { num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode()); } return num; } if (typeof(T) == typeof(int)) { for (int n = 0; n < Count; n++) { num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode()); } return num; } if (typeof(T) == typeof(ulong)) { for (int num2 = 0; num2 < Count; num2++) { num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode()); } return num; } if (typeof(T) == typeof(long)) { for (int num3 = 0; num3 < Count; num3++) { num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode()); } return num; } if (typeof(T) == typeof(float)) { for (int num4 = 0; num4 < Count; num4++) { num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode()); } return num; } if (typeof(T) == typeof(double)) { for (int num5 = 0; num5 < Count; num5++) { num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode()); } return num; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } if (typeof(T) == typeof(byte)) { num = HashHelpers.Combine(num, register.byte_0.GetHashCode()); num = HashHelpers.Combine(num, register.byte_1.GetHashCode()); num = HashHelpers.Combine(num, register.byte_2.GetHashCode()); num = HashHelpers.Combine(num, register.byte_3.GetHashCode()); num = HashHelpers.Combine(num, register.byte_4.GetHashCode()); num = HashHelpers.Combine(num, register.byte_5.GetHashCode()); num = HashHelpers.Combine(num, register.byte_6.GetHashCode()); num = HashHelpers.Combine(num, register.byte_7.GetHashCode()); num = HashHelpers.Combine(num, register.byte_8.GetHashCode()); num = HashHelpers.Combine(num, register.byte_9.GetHashCode()); num = HashHelpers.Combine(num, register.byte_10.GetHashCode()); num = HashHelpers.Combine(num, register.byte_11.GetHashCode()); num = HashHelpers.Combine(num, register.byte_12.GetHashCode()); num = HashHelpers.Combine(num, register.byte_13.GetHashCode()); num = HashHelpers.Combine(num, register.byte_14.GetHashCode()); return HashHelpers.Combine(num, register.byte_15.GetHashCode()); } if (typeof(T) == typeof(sbyte)) { num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode()); return HashHelpers.Combine(num, register.sbyte_15.GetHashCode()); } if (typeof(T) == typeof(ushort)) { num = HashHelpers.Combine(num, register.uint16_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_2.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_3.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_4.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_5.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_6.GetHashCode()); return HashHelpers.Combine(num, register.uint16_7.GetHashCode()); } if (typeof(T) == typeof(short)) { num = HashHelpers.Combine(num, register.int16_0.GetHashCode()); num = HashHelpers.Combine(num, register.int16_1.GetHashCode()); num = HashHelpers.Combine(num, register.int16_2.GetHashCode()); num = HashHelpers.Combine(num, register.int16_3.GetHashCode()); num = HashHelpers.Combine(num, register.int16_4.GetHashCode()); num = HashHelpers.Combine(num, register.int16_5.GetHashCode()); num = HashHelpers.Combine(num, register.int16_6.GetHashCode()); return HashHelpers.Combine(num, register.int16_7.GetHashCode()); } if (typeof(T) == typeof(uint)) { num = HashHelpers.Combine(num, register.uint32_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_2.GetHashCode()); return HashHelpers.Combine(num, register.uint32_3.GetHashCode()); } if (typeof(T) == typeof(int)) { num = HashHelpers.Combine(num, register.int32_0.GetHashCode()); num = HashHelpers.Combine(num, register.int32_1.GetHashCode()); num = HashHelpers.Combine(num, register.int32_2.GetHashCode()); return HashHelpers.Combine(num, register.int32_3.GetHashCode()); } if (typeof(T) == typeof(ulong)) { num = HashHelpers.Combine(num, register.uint64_0.GetHashCode()); return HashHelpers.Combine(num, register.uint64_1.GetHashCode()); } if (typeof(T) == typeof(long)) { num = HashHelpers.Combine(num, register.int64_0.GetHashCode()); return HashHelpers.Combine(num, register.int64_1.GetHashCode()); } if (typeof(T) == typeof(float)) { num = HashHelpers.Combine(num, register.single_0.GetHashCode()); num = HashHelpers.Combine(num, register.single_1.GetHashCode()); num = HashHelpers.Combine(num, register.single_2.GetHashCode()); return HashHelpers.Combine(num, register.single_3.GetHashCode()); } if (typeof(T) == typeof(double)) { num = HashHelpers.Combine(num, register.double_0.GetHashCode()); return HashHelpers.Combine(num, register.double_1.GetHashCode()); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } public string ToString(string format, IFormatProvider formatProvider) { StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); for (int i = 0; i < Count - 1; i++) { stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); } stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } public unsafe static Vector<T>operator +(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 + right.register.int32_0; result.register.int32_1 = left.register.int32_1 + right.register.int32_1; result.register.int32_2 = left.register.int32_2 + right.register.int32_2; result.register.int32_3 = left.register.int32_3 + right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 + right.register.int64_0; result.register.int64_1 = left.register.int64_1 + right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 + right.register.single_0; result.register.single_1 = left.register.single_1 + right.register.single_1; result.register.single_2 = left.register.single_2 + right.register.single_2; result.register.single_3 = left.register.single_3 + right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 + right.register.double_0; result.register.double_1 = left.register.double_1 + right.register.double_1; } return result; } public unsafe static Vector<T>operator -(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 - right.register.int32_0; result.register.int32_1 = left.register.int32_1 - right.register.int32_1; result.register.int32_2 = left.register.int32_2 - right.register.int32_2; result.register.int32_3 = left.register.int32_3 - right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 - right.register.int64_0; result.register.int64_1 = left.register.int64_1 - right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 - right.register.single_0; result.register.single_1 = left.register.single_1 - right.register.single_1; result.register.single_2 = left.register.single_2 - right.register.single_2; result.register.single_3 = left.register.single_3 - right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 - right.register.double_0; result.register.double_1 = left.register.double_1 - right.register.double_1; } return result; } public unsafe static Vector<T>operator *(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 * right.register.int32_0; result.register.int32_1 = left.register.int32_1 * right.register.int32_1; result.register.int32_2 = left.register.int32_2 * right.register.int32_2; result.register.int32_3 = left.register.int32_3 * right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 * right.register.int64_0; result.register.int64_1 = left.register.int64_1 * right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 * right.register.single_0; result.register.single_1 = left.register.single_1 * right.register.single_1; result.register.single_2 = left.register.single_2 * right.register.single_2; result.register.single_3 = left.register.single_3 * right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 * right.register.double_0; result.register.double_1 = left.register.double_1 * right.register.double_1; } return result; } public static Vector<T>operator *(Vector<T> value, T factor) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public static Vector<T>operator *(T factor, Vector<T> value) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public unsafe static Vector<T>operator /(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)(uint)Count]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)(uint)Count]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 / right.register.int32_0; result.register.int32_1 = left.register.int32_1 / right.register.int32_1; result.register.int32_2 = left.register.int32_2 / right.register.int32_2; result.register.int32_3 = left.register.int32_3 / right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 / right.register.int64_0; result.register.int64_1 = left.register.int64_1 / right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 / right.register.single_0; result.register.single_1 = left.register.single_1 / right.register.single_1; result.register.single_2 = left.register.single_2 / right.register.single_2; result.register.single_3 = left.register.single_3 / right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 / right.register.double_0; result.register.double_1 = left.register.double_1 / right.register.double_1; } return result; } public static Vector<T>operator -(Vector<T> value) { return Zero - value; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector<T>operator &(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] & ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 & right.register.int64_0; result.register.int64_1 = left.register.int64_1 & right.register.int64_1; } return result; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector<T>operator |(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] | ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 | right.register.int64_0; result.register.int64_1 = left.register.int64_1 | right.register.int64_1; } return result; } [System.Runtime.CompilerServices.Intrinsic] public unsafe static Vector<T>operator ^(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] ^ ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 ^ right.register.int64_0; result.register.int64_1 = left.register.int64_1 ^ right.register.int64_1; } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T>operator ~(Vector<T> value) { return s_allOnes ^ value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector<T> left, Vector<T> right) { return left.Equals(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector<T> left, Vector<T> right) { return !(left == right); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<byte>(Vector<T> value) { return new Vector<byte>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<sbyte>(Vector<T> value) { return new Vector<sbyte>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<ushort>(Vector<T> value) { return new Vector<ushort>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<short>(Vector<T> value) { return new Vector<short>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<uint>(Vector<T> value) { return new Vector<uint>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<int>(Vector<T> value) { return new Vector<int>(ref value.register); } [CLSCompliant(false)] [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<ulong>(Vector<T> value) { return new Vector<ulong>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<long>(Vector<T> value) { return new Vector<long>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<float>(Vector<T> value) { return new Vector<float>(ref value.register); } [System.Runtime.CompilerServices.Intrinsic] public static explicit operator Vector<double>(Vector<T> value) { return new Vector<double>(ref value.register); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Compile
plugins/BingBongHelper/System.Runtime.CompilerServices.Unsafe.dll
Decompiled 2 weeks agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyFileVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.0.0.0")] [assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: CLSCompliant(false)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("4.0.4.1")] namespace System.Runtime.CompilerServices { public static class Unsafe { [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T Read<T>(void* source) { return Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static T ReadUnaligned<T>(void* source) { return Unsafe.ReadUnaligned<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T ReadUnaligned<T>(ref byte source) { return Unsafe.ReadUnaligned<T>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Write<T>(void* destination, T value) { Unsafe.Write(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void WriteUnaligned<T>(void* destination, T value) { Unsafe.WriteUnaligned(destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void WriteUnaligned<T>(ref byte destination, T value) { Unsafe.WriteUnaligned(ref destination, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(void* destination, ref T source) { Unsafe.Write(destination, source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void Copy<T>(ref T destination, void* source) { destination = Unsafe.Read<T>(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* AsPointer<T>(ref T value) { return Unsafe.AsPointer(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static int SizeOf<T>() { return Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlock(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlock(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlock(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(destination, source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount) { // IL cpblk instruction Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlock(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlock(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { // IL initblk instruction Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static T As<T>(object o) where T : class { return (T)o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static ref T AsRef<T>(void* source) { return ref *(T*)source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AsRef<T>(in T source) { return ref source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref TTo As<TFrom, TTo>(ref TFrom source) { return ref Unsafe.As<TFrom, TTo>(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, int elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Add<T>(void* source, int elementOffset) { return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Add<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Add(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.AddByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, int elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public unsafe static void* Subtract<T>(void* source, int elementOffset) { return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T Subtract<T>(ref T source, IntPtr elementOffset) { return ref Unsafe.Subtract(ref source, elementOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset) { return ref Unsafe.SubtractByteOffset(ref source, byteOffset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static IntPtr ByteOffset<T>(ref T origin, ref T target) { return Unsafe.ByteOffset(target: ref target, origin: ref origin); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool AreSame<T>(ref T left, ref T right) { return Unsafe.AreSame(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) { return Unsafe.IsAddressGreaterThan(ref left, ref right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [System.Runtime.Versioning.NonVersionable] public static bool IsAddressLessThan<T>(ref T left, ref T right) { return Unsafe.IsAddressLessThan(ref left, ref right); } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.CompilerServices { internal sealed class IsReadOnlyAttribute : Attribute { } }