Decompiled source of TextureSwapper v1.1.7

Endec.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Microsoft.CodeAnalysis;
using io.wispforest.impl;
using io.wispforest.util;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Endec")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+f93a879a4766a4c6139dad1820e2a8337b613517")]
[assembly: AssemblyProduct("Endec")]
[assembly: AssemblyTitle("Endec")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 io.wispforest
{
	public interface Deserializer<out T> where T : class
	{
		SerializationContext setupContext(SerializationContext ctx)
		{
			return ctx;
		}

		byte readByte(SerializationContext ctx);

		short readShort(SerializationContext ctx);

		int readInt(SerializationContext ctx);

		long readLong(SerializationContext ctx);

		float readFloat(SerializationContext ctx);

		double readDouble(SerializationContext ctx);

		int readVarInt(SerializationContext ctx);

		long readVarLong(SerializationContext ctx);

		bool readBoolean(SerializationContext ctx);

		string readString(SerializationContext ctx);

		byte[] readBytes(SerializationContext ctx);

		V? readOptional<V>(SerializationContext ctx, Endec<V> endec);

		SequenceDeserializer<E> sequence<E>(SerializationContext ctx, Endec<E> elementEndec);

		MapDeserializer<V> map<V>(SerializationContext ctx, Endec<V> valueEndec);

		StructDeserializer structed();

		V tryRead<V>(Func<Deserializer<T>, V> reader);
	}
	public interface SequenceDeserializer<E> : IEnumerator<E>, IEnumerator, IDisposable, IEnumerable<E>, IEnumerable
	{
		object? IEnumerator.Current => Current;

		IEnumerator<E> IEnumerable<E>.GetEnumerator()
		{
			return this;
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this;
		}

		int estimatedSize();
	}
	public interface MapDeserializer<E> : IEnumerator<KeyValuePair<string, E>>, IEnumerator, IDisposable, IEnumerable<KeyValuePair<string, E>>, IEnumerable
	{
		object? IEnumerator.Current => Current;

		IEnumerator<KeyValuePair<string, E>> IEnumerable<KeyValuePair<string, E>>.GetEnumerator()
		{
			return this;
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this;
		}

		int estimatedSize();
	}
	public interface StructDeserializer
	{
		F? field<F>(string name, SerializationContext ctx, Endec<F> endec)
		{
			return field(name, ctx, endec, null);
		}

		F? field<F>(string name, SerializationContext ctx, Endec<F> endec, Func<F>? defaultValueFactory);
	}
	public interface SelfDescribedDeserializer<out T> : Deserializer<T> where T : class
	{
		void readAny<S>(SerializationContext ctx, Serializer<S> visitor) where S : class;
	}
	public delegate T IntFunction<T>(int size);
	public delegate void Encoder<T>(SerializationContext ctx, Serializer<dynamic> serializer, T value);
	public delegate T Decoder<T>(SerializationContext ctx, Deserializer<dynamic> deserializer);
	public delegate T DecoderWithError<T>(SerializationContext ctx, Deserializer<dynamic> deserializer, Exception exception);
	public abstract class Endec<T>
	{
		public abstract void encode<E>(SerializationContext ctx, Serializer<E> serializer, T value) where E : class;

		public abstract T decode<E>(SerializationContext ctx, Deserializer<E> deserializer) where E : class;

		public E encodeFully<E>(SerializationContext ctx, Func<Serializer<E>> serializerConstructor, T value) where E : class
		{
			Serializer<E> serializer = serializerConstructor();
			encode(serializer.setupContext(ctx), serializer, value);
			return serializer.result();
		}

		public E encodeFully<E>(Func<Serializer<E>> serializerConstructor, T value) where E : class
		{
			return encodeFully(SerializationContext.empty(), serializerConstructor, value);
		}

		public T decodeFully<E>(SerializationContext ctx, Func<E, Deserializer<E>> deserializerConstructor, E value) where E : class
		{
			Deserializer<E> deserializer = deserializerConstructor(value);
			return decode(deserializer.setupContext(ctx), deserializer);
		}

		public T decodeFully<E>(Func<E, Deserializer<E>> deserializerConstructor, E value) where E : class
		{
			return decodeFully(SerializationContext.empty(), deserializerConstructor, value);
		}

		public Endec<IList<T>> listOf()
		{
			return EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, IList<T> list)
			{
				using SequenceSerializer<T> sequenceSerializer = serializer.sequence(ctx, this, list.Count);
				foreach (T item in list)
				{
					sequenceSerializer.element(item);
				}
			}, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer)
			{
				SequenceDeserializer<T> sequenceDeserializer = deserializer.sequence(ctx, this);
				List<T> list2 = new List<T>(sequenceDeserializer.estimatedSize());
				foreach (T item2 in sequenceDeserializer)
				{
					list2.Add(item2);
				}
				return list2;
			});
		}

		public Endec<T[]> arrayOf()
		{
			return listOf().xmap((IList<T> list) => list.ToArray(), (T[] array) => new List<T>(array));
		}

		public Endec<IDictionary<string, T>> mapOf()
		{
			return mapOf(EndecUtils.DefaultDictionary<string, T>());
		}

		public Endec<M> mapOf<M>(IntFunction<M> mapConstructor) where M : IDictionary<string, T>
		{
			IntFunction<M> mapConstructor2 = mapConstructor;
			return EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, M map)
			{
				using MapSerializer<T> mapSerializer = serializer.map(ctx, this, map.Count);
				foreach (KeyValuePair<string, T> item in map)
				{
					mapSerializer.entry(item.Key, item.Value);
				}
			}, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer)
			{
				MapDeserializer<T> mapDeserializer = deserializer.map(ctx, this);
				M result = mapConstructor2(mapDeserializer.estimatedSize());
				foreach (KeyValuePair<string, T> item2 in mapDeserializer)
				{
					ref M reference = ref result;
					M val = default(M);
					if (val == null)
					{
						val = reference;
						reference = ref val;
					}
					reference[item2.Key] = item2.Value;
				}
				return result;
			});
		}

		public Endec<IDictionary<K, T>> mapOf<K>(Func<K, string> keyToString, Func<string, K> stringToKey)
		{
			return mapOf(EndecUtils.DefaultDictionary<K, T>(), keyToString, stringToKey);
		}

		public Endec<M> mapOf<K, M>(IntFunction<M> mapConstructor, Func<K, string> keyToString, Func<string, K> stringToKey) where M : IDictionary<K, T>
		{
			return EndecUtils.map(mapConstructor, keyToString, stringToKey, this);
		}

		public Endec<T?> optionalOf()
		{
			return EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, T value)
			{
				serializer.writeOptional(ctx, this, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readOptional(ctx, this));
		}

		public Endec<R> xmap<R>(Func<T, R> to, Func<R, T> from)
		{
			Func<R, T> from2 = from;
			Func<T, R> to2 = to;
			return EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, R value)
			{
				encode(ctx, serializer, from2(value));
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => to2(decode(ctx, deserializer)));
		}

		public Endec<R> xmapWithContext<R>(Func<SerializationContext, T, R> to, Func<SerializationContext, R, T> from)
		{
			Func<SerializationContext, R, T> from2 = from;
			Func<SerializationContext, T, R> to2 = to;
			return EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, R value)
			{
				encode(ctx, serializer, from2(ctx, value));
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => to2(ctx, decode(ctx, deserializer)));
		}

		public Endec<T> validate(Action<T> validator)
		{
			Action<T> validator2 = validator;
			return xmap(delegate(T t)
			{
				validator2(t);
				return t;
			}, delegate(T t)
			{
				validator2(t);
				return t;
			});
		}

		public Endec<T> catchErrors(DecoderWithError<T> decodeOnError)
		{
			DecoderWithError<T> decodeOnError2 = decodeOnError;
			return EndecUtils.of(encode, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer)
			{
				SerializationContext ctx2 = ctx;
				try
				{
					return deserializer.tryRead((Deserializer<dynamic> deserializer1) => decode(ctx2, deserializer1));
				}
				catch (Exception exception)
				{
					return decodeOnError2(ctx2, deserializer, exception);
				}
			});
		}

		public Endec<ISet<T>> setOf()
		{
			return listOf().xmap((IList<T> list) => new HashSet<T>(list), (ISet<T> set) => new List<T>(set));
		}

		public KeyedEndec<T> keyed(string key, T defaultValue)
		{
			return new KeyedEndec<T>(key, this, defaultValue);
		}

		public KeyedEndec<T> keyed(string key, Func<T> defaultValueFactory)
		{
			return new KeyedEndec<T>(key, this, defaultValueFactory);
		}

		public StructEndec<T> structOf(string name)
		{
			string name2 = name;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> _, StructSerializer instance, T value)
			{
				instance.field(name2, ctx, this, value);
			}, (SerializationContext ctx, Deserializer<dynamic> _, StructDeserializer instance) => instance.field(name2, ctx, this));
		}

		public StructField<S, T> fieldOf<S>(string name, Func<S, T> getter)
		{
			return new StructField<S, T>(name, this, getter);
		}

		public StructField<S, T> optionalFieldOf<S>(string name, Func<S, T?> getter)
		{
			return optionalFieldOf(name, getter, null);
		}

		public StructField<S, T> optionalFieldOf<S>(string name, Func<S, T?> getter, T? defaultValue)
		{
			return new StructField<S, T>(name, optionalOf(), getter, defaultValue);
		}

		public StructField<S, T> optionalFieldOf<S>(string name, Func<S, T?> getter, Func<T?> defaultValue)
		{
			if (defaultValue == null)
			{
				throw new NullReferenceException("Supplier was found to be null which is not permitted for optionalFieldOf");
			}
			return new StructField<S, T>(name, optionalOf(), getter, defaultValue);
		}
	}
	public sealed class EndecGetter
	{
		public static Endec<T> Endec<T>() where T : EndecGetter<T>
		{
			return EndecGetter<T>.Endec();
		}
	}
	public interface EndecGetter<T> where T : EndecGetter<T>
	{
		static Endec<T> Endec()
		{
			MethodInfo method = typeof(T).GetMethod("Endec", BindingFlags.Static | BindingFlags.Public);
			object obj = method.Invoke(null, null);
			if (!(obj is Endec<T> result))
			{
				throw new InvalidCastException("Unable to get Endec due to it being the incorrect type!");
			}
			return result;
		}
	}
	public class SerializationAttributes
	{
		public static readonly SerializationAttributeMarker HUMAN_READABLE = SerializationAttribute.marker("human_readable");
	}
	public abstract class SerializationAttribute
	{
		public readonly string name;

		protected SerializationAttribute(string name)
		{
			this.name = name;
		}

		public static SerializationAttributeMarker marker(string name)
		{
			return new SerializationAttributeMarker(name);
		}

		public static SerializationAttributeWithValue<T> withValue<T>(string name)
		{
			return new SerializationAttributeWithValue<T>(name);
		}
	}
	public sealed class SerializationAttributeMarker : SerializationAttribute, SerializationAttributeInstance
	{
		internal SerializationAttributeMarker(string name)
			: base(name)
		{
		}

		public SerializationAttribute attribute()
		{
			return this;
		}

		public object value()
		{
			return null;
		}
	}
	public sealed class SerializationAttributeWithValue<T> : SerializationAttribute
	{
		internal SerializationAttributeWithValue(string name)
			: base(name)
		{
		}

		public SerializationAttributeInstance instance(T value)
		{
			return new InstanceImpl(this, value);
		}
	}
	public interface SerializationAttributeInstance
	{
		SerializationAttribute attribute();

		object value();
	}
	internal class InstanceImpl : SerializationAttributeInstance
	{
		private readonly SerializationAttribute attribute;

		private readonly object value;

		internal InstanceImpl(SerializationAttribute attribute, object value)
		{
			this.attribute = attribute;
			this.value = value;
		}

		SerializationAttribute SerializationAttributeInstance.attribute()
		{
			return attribute;
		}

		object SerializationAttributeInstance.value()
		{
			return value;
		}
	}
	public class SerializationContext
	{
		private static readonly SerializationContext EMPTY = new SerializationContext(new Dictionary<SerializationAttribute, object>(), new HashSet<SerializationAttribute>());

		private readonly IDictionary<SerializationAttribute, object> attributeValues;

		private readonly ISet<SerializationAttribute> suppressedAttributes;

		private SerializationContext(IDictionary<SerializationAttribute, object> attributeValues, ISet<SerializationAttribute> suppressedAttributes)
		{
			this.attributeValues = attributeValues.ImmutableWrap();
			this.suppressedAttributes = suppressedAttributes.ImmutableWrap();
		}

		public static SerializationContext empty()
		{
			return EMPTY;
		}

		public static SerializationContext attributes(params SerializationAttributeInstance[] attributes)
		{
			if (attributes.Length == 0)
			{
				return EMPTY;
			}
			return new SerializationContext(unpackAttributes(attributes), new HashSet<SerializationAttribute>());
		}

		public static SerializationContext suppressed(params SerializationAttribute[] attributes)
		{
			if (attributes.Length == 0)
			{
				return EMPTY;
			}
			return new SerializationContext(new Dictionary<SerializationAttribute, object>(), new HashSet<SerializationAttribute>(attributes));
		}

		public SerializationContext withAttributes(params SerializationAttributeInstance[] attributes)
		{
			IDictionary<SerializationAttribute, object> dictionary = unpackAttributes(attributes);
			foreach (KeyValuePair<SerializationAttribute, object> attributeValue in attributeValues)
			{
				if (!dictionary.ContainsKey(attributeValue.Key))
				{
					dictionary.Add(attributeValue);
				}
			}
			return new SerializationContext(dictionary, suppressedAttributes);
		}

		public SerializationContext withoutAttributes(params SerializationAttribute[] attributes)
		{
			Dictionary<SerializationAttribute, object> dictionary = new Dictionary<SerializationAttribute, object>(attributeValues);
			foreach (SerializationAttribute key in attributes)
			{
				dictionary.Remove(key);
			}
			return new SerializationContext(dictionary, suppressedAttributes);
		}

		public SerializationContext withSuppressed(params SerializationAttribute[] attributes)
		{
			HashSet<SerializationAttribute> set = new HashSet<SerializationAttribute>(suppressedAttributes);
			set.AddAll(attributes);
			return new SerializationContext(attributeValues, set);
		}

		public SerializationContext withoutSuppressed(params SerializationAttribute[] attributes)
		{
			HashSet<SerializationAttribute> hashSet = new HashSet<SerializationAttribute>(suppressedAttributes);
			foreach (SerializationAttribute item in attributes)
			{
				hashSet.Remove(item);
			}
			return new SerializationContext(attributeValues, hashSet);
		}

		public SerializationContext and(SerializationContext other)
		{
			Dictionary<SerializationAttribute, object> dictionary = new Dictionary<SerializationAttribute, object>(attributeValues);
			dictionary.AddAll(other.attributeValues);
			HashSet<SerializationAttribute> set = new HashSet<SerializationAttribute>(suppressedAttributes);
			set.AddAll(other.suppressedAttributes);
			return new SerializationContext(dictionary, set);
		}

		public bool hasAttribute(SerializationAttribute attribute)
		{
			return attributeValues.ContainsKey(attribute) && !suppressedAttributes.Contains(attribute);
		}

		public A getAttributeValue<A>(SerializationAttributeWithValue<A> attribute)
		{
			return (A)attributeValues[attribute];
		}

		public A requireAttributeValue<A>(SerializationAttributeWithValue<A> attribute)
		{
			if (!hasAttribute(attribute))
			{
				throw new MissingAttributeValueException("Context did not provide a value for attribute '" + attribute.name + "'");
			}
			return getAttributeValue(attribute);
		}

		private static IDictionary<SerializationAttribute, object> unpackAttributes(params SerializationAttributeInstance[] attributes)
		{
			Dictionary<SerializationAttribute, object> dictionary = new Dictionary<SerializationAttribute, object>();
			foreach (SerializationAttributeInstance serializationAttributeInstance in attributes)
			{
				dictionary.Add(serializationAttributeInstance.attribute(), serializationAttributeInstance.value());
			}
			return dictionary;
		}
	}
	public interface Serializer<out T> where T : class
	{
		SerializationContext setupContext(SerializationContext ctx)
		{
			return ctx;
		}

		void writeByte(SerializationContext ctx, byte value);

		void writeShort(SerializationContext ctx, short value);

		void writeInt(SerializationContext ctx, int value);

		void writeLong(SerializationContext ctx, long value);

		void writeFloat(SerializationContext ctx, float value);

		void writeDouble(SerializationContext ctx, double value);

		void writeVarInt(SerializationContext ctx, int value);

		void writeVarLong(SerializationContext ctx, long value);

		void writeBoolean(SerializationContext ctx, bool value);

		void writeString(SerializationContext ctx, string value);

		void writeBytes(SerializationContext ctx, byte[] bytes);

		void writeOptional<V>(SerializationContext ctx, Endec<V> endec, V? optional);

		SequenceSerializer<E> sequence<E>(SerializationContext ctx, Endec<E> elementEndec, int size);

		MapSerializer<V> map<V>(SerializationContext ctx, Endec<V> valueEndec, int size);

		StructSerializer structed();

		T result();
	}
	public interface SequenceSerializer<E> : Endable, IDisposable
	{
		void element(E element);
	}
	public interface MapSerializer<V> : Endable, IDisposable
	{
		void entry(string key, V value);
	}
	public interface StructSerializer : Endable, IDisposable
	{
		StructSerializer field<F>(string name, SerializationContext ctx, Endec<F> endec, F value)
		{
			return field(name, ctx, endec, value, mayOmit: false);
		}

		StructSerializer field<F>(string name, SerializationContext ctx, Endec<F> endec, F value, bool mayOmit);
	}
	public interface SelfDescribedSerializer<T> : Serializer<T> where T : class
	{
	}
	public delegate void StructuredEncoder<T>(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, T value);
	public delegate T StructuredDecoder<T>(SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance);
	public delegate T StructuredDecoderWithError<T>(SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance, Exception exception);
	public abstract class StructEndec<T> : Endec<T>
	{
		public abstract void encodeStruct<E>(SerializationContext ctx, Serializer<E> serializer, StructSerializer instance, T value) where E : class;

		public abstract T decodeStruct<E>(SerializationContext ctx, Deserializer<E> deserializer, StructDeserializer instance) where E : class;

		public override void encode<E>(SerializationContext ctx, Serializer<E> serializer, T value)
		{
			using StructSerializer instance = serializer.structed();
			encodeStruct(ctx, serializer, instance, value);
		}

		public override T decode<E>(SerializationContext ctx, Deserializer<E> deserializer)
		{
			return decodeStruct(ctx, deserializer, deserializer.structed());
		}

		public StructField<S, T> flatFieldOf<S>(Func<S, T> getter)
		{
			return new FlatStructField<S, T>(this, getter);
		}

		public StructField<M, T> flatInheritedFieldOf<M>() where M : T
		{
			return new FlatStructField<M, T>(this, (M m) => (T)(object)m);
		}

		public new StructEndec<R> xmap<R>(Func<T, R> to, Func<R, T> from)
		{
			Func<R, T> from2 = from;
			Func<T, R> to2 = to;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, R value)
			{
				encodeStruct(ctx, serializer, instance, from2(value));
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => to2(decodeStruct(ctx, deserializer, instance)));
		}

		public new StructEndec<R> xmapWithContext<R>(Func<SerializationContext, T, R> to, Func<SerializationContext, R, T> from)
		{
			Func<SerializationContext, R, T> from2 = from;
			Func<SerializationContext, T, R> to2 = to;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, R value)
			{
				encodeStruct(ctx, serializer, instance, from2(ctx, value));
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => to2(ctx, decodeStruct(ctx, deserializer, instance)));
		}

		public StructEndec<T> structuredCatchErrors(StructuredDecoderWithError<T> decodeOnError)
		{
			StructuredDecoderWithError<T> decodeOnError2 = decodeOnError;
			return StructEndecUtils.of(encodeStruct, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance)
			{
				SerializationContext ctx2 = ctx;
				StructDeserializer instance2 = instance;
				try
				{
					return deserializer.tryRead((Deserializer<dynamic> deserializer1) => decodeStruct(ctx2, deserializer1, instance2));
				}
				catch (Exception exception)
				{
					return decodeOnError2(ctx2, deserializer, instance2, exception);
				}
			});
		}

		public new StructEndec<T> validate(Action<T> validator)
		{
			Action<T> validator2 = validator;
			return xmap(delegate(T t)
			{
				validator2(t);
				return t;
			}, delegate(T t)
			{
				validator2(t);
				return t;
			});
		}
	}
	public class StructEndecUtils
	{
		public static StructEndec<T> of<T>(StructuredEncoder<T> encoder, StructuredDecoder<T> decoder)
		{
			return new StructEndecImpl<T>(encoder, decoder);
		}

		private static StructEndec<T> recursive<T>(Func<StructEndec<T>, StructEndec<T>> builderFunc)
		{
			return new RecursiveStructEndec<T>(builderFunc);
		}

		public static AttributeStructEndecBuilder<T> ifAttr<T>(SerializationAttribute attribute, StructEndec<T> endec)
		{
			return new AttributeStructEndecBuilder<T>(endec, attribute);
		}
	}
}
namespace io.wispforest.util
{
	public interface Endable : IDisposable
	{
		void end();

		void IDisposable.Dispose()
		{
			end();
		}
	}
	public class EndecUtils
	{
		public static IntFunction<IDictionary<K, V>> DefaultDictionary<K, V>()
		{
			return (int i) => new Dictionary<K, V>(i);
		}

		public static Endec<T> of<T>(Encoder<T> encoder, Decoder<T> decoder)
		{
			return new EndecImpl<T>(encoder, decoder);
		}

		private static Endec<T> recursive<T>(Func<Endec<T>, Endec<T>> builderFunc)
		{
			return new RecursiveEndec<T>(builderFunc);
		}

		public static StructEndec<T> unit<T>(T instance)
		{
			T instance2 = instance;
			return unit(() => instance2);
		}

		public static StructEndec<T> unit<T>(Func<T> instanceGetter)
		{
			Func<T> instanceGetter2 = instanceGetter;
			return StructEndecUtils.of(delegate
			{
			}, (SerializationContext _, Deserializer<dynamic> _, StructDeserializer _) => instanceGetter2());
		}

		public static Endec<IDictionary<K, V>> map<K, V>(Endec<K> keyEndec, Endec<V> valueEndec)
		{
			return StructEndecBuilder.of(keyEndec.fieldOf("k", (KeyValuePair<K, V> s) => s.Key), valueEndec.fieldOf("v", (KeyValuePair<K, V> s) => s.Value), (K k, V v) => new KeyValuePair<K, V>(k, v)).listOf().xmap(delegate(IList<KeyValuePair<K, V>> entries)
			{
				Dictionary<K, V> dictionary = new Dictionary<K, V>(entries.Count);
				dictionary.AddAll(entries);
				return dictionary;
			}, (IDictionary<K, V> kvMap) => new List<KeyValuePair<K, V>>(kvMap));
		}

		public static Endec<IDictionary<K, V>> map<K, V>(Func<K, string> keyToString, Func<string, K> stringToKey, Endec<V> valueEndec)
		{
			return map(DefaultDictionary<K, V>(), keyToString, stringToKey, valueEndec);
		}

		public static Endec<M> map<K, V, M>(IntFunction<M> mapConstructor, Func<K, string> keyToString, Func<string, K> stringToKey, Endec<V> valueEndec) where M : IDictionary<K, V>
		{
			Endec<V> valueEndec2 = valueEndec;
			Func<K, string> keyToString2 = keyToString;
			IntFunction<M> mapConstructor2 = mapConstructor;
			Func<string, K> stringToKey2 = stringToKey;
			return of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, M map)
			{
				using MapSerializer<V> mapSerializer = serializer.map(ctx, valueEndec2, map.Count);
				foreach (KeyValuePair<K, V> item in map)
				{
					mapSerializer.entry(keyToString2(item.Key), item.Value);
				}
			}, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer)
			{
				MapDeserializer<V> mapDeserializer = deserializer.map(ctx, valueEndec2);
				M result = mapConstructor2(mapDeserializer.estimatedSize());
				foreach (KeyValuePair<string, V> item2 in mapDeserializer)
				{
					ref M reference = ref result;
					M val = default(M);
					if (val == null)
					{
						val = reference;
						reference = ref val;
					}
					reference[stringToKey2(item2.Key)] = item2.Value;
				}
				return result;
			});
		}

		public static Endec<E> forEnum<E>() where E : class, Enum
		{
			return forEnum((E arg) => Enum.GetName(typeof(E), arg));
		}

		public static Endec<E> forEnum<E>(Func<E, string?> nameLookup) where E : class, Enum
		{
			Func<E, string?> nameLookup2 = nameLookup;
			Array enumValues = Enum.GetValues(typeof(E));
			Dictionary<string, E?> serializedNames = new Dictionary<string, E>();
			Dictionary<E, int> entryToIndex = new Dictionary<E, int>();
			int num = 0;
			foreach (E item in enumValues)
			{
				serializedNames[nameLookup2(item)] = item;
				entryToIndex[item] = num;
				num++;
			}
			Type type = typeof(E);
			return ifAttr(SerializationAttributes.HUMAN_READABLE, Endecs.STRING.xmap(delegate(string name)
			{
				E val2 = serializedNames[name];
				if (val2 == null)
				{
					throw new Exception(type.Name + " constant with the name of [" + name + "] could not be located!");
				}
				return val2;
			}, delegate(E value)
			{
				string text = nameLookup2(value);
				if (text == null)
				{
					throw new Exception($"{type.Name} constant with the value of [{value}] could not be located!");
				}
				return text;
			})).orElse(Endecs.VAR_INT.xmap((int ordinal) => enumValues.GetValue(ordinal) as E, (E value) => entryToIndex[value]));
		}

		public static StructEndec<T> dispatchedStruct<T, K>(Func<K, StructEndec<T>> variantToEndec, Func<T, K> instanceToVariant, Endec<K> variantEndec)
		{
			return dispatchedStruct(variantToEndec, instanceToVariant, variantEndec, "type");
		}

		public static StructEndec<T> dispatchedStruct<T, K>(Func<K, StructEndec<T>> variantToEndec, Func<T, K> instanceToVariant, Endec<K> variantEndec, string variantKey)
		{
			Func<T, K> instanceToVariant2 = instanceToVariant;
			string variantKey2 = variantKey;
			Endec<K> variantEndec2 = variantEndec;
			Func<K, StructEndec<T>> variantToEndec2 = variantToEndec;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, T value)
			{
				K val = instanceToVariant2(value);
				instance.field(variantKey2, ctx, variantEndec2, val);
				variantToEndec2(val).encodeStruct(ctx, serializer, instance, value);
			}, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance)
			{
				K arg = instance.field(variantKey2, ctx, variantEndec2);
				return variantToEndec2(arg).decodeStruct(ctx, deserializer, instance);
			});
		}

		public static StructEndec<T> dispatched<T, K>(Func<K, Endec<T>> variantToEndec, Func<T, K> instanceToVariant, Endec<K> variantEndec)
		{
			Func<T, K> instanceToVariant2 = instanceToVariant;
			Endec<K> variantEndec2 = variantEndec;
			Func<K, Endec<T>> variantToEndec2 = variantToEndec;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> _, StructSerializer instance, T value)
			{
				K val = instanceToVariant2(value);
				instance.field("variant", ctx, variantEndec2, val);
				instance.field("instance", ctx, variantToEndec2(val), value);
			}, delegate(SerializationContext ctx, Deserializer<dynamic> _, StructDeserializer instance)
			{
				K arg = instance.field("variant", ctx, variantEndec2);
				return instance.field("instance", ctx, variantToEndec2(arg));
			});
		}

		public static StructEndec<T> dispatchedFlatable<T, K>(string variantKey, string instanceKey, Func<K, Endec<T>> variantToEndec, Func<T, K> instanceToVariant, Endec<K> variantEndec)
		{
			Func<T, K> instanceToVariant2 = instanceToVariant;
			Endec<K> variantEndec2 = variantEndec;
			Func<K, Endec<T>> variantToEndec2 = variantToEndec;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, T value)
			{
				K val = instanceToVariant2(value);
				instance.field("variant", ctx, variantEndec2, val);
				Endec<T> endec2 = variantToEndec2(val);
				if (endec2 is StructEndec<T> structEndec2)
				{
					structEndec2.encodeStruct(ctx, serializer, instance, value);
				}
				else
				{
					instance.field("instance", ctx, endec2, value);
				}
			}, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance)
			{
				K arg = instance.field("variant", ctx, variantEndec2);
				Endec<T> endec = variantToEndec2(arg);
				return (T)((endec is StructEndec<T> structEndec) ? ((object)structEndec.decodeStruct(ctx, deserializer, instance)) : ((object)instance.field("instance", ctx, endec)));
			});
		}

		public static AttributeEndecBuilder<T> ifAttr<T>(SerializationAttribute attribute, Endec<T> endec)
		{
			return new AttributeEndecBuilder<T>(endec, attribute);
		}
	}
	public static class DictionaryExtensions
	{
		public static IDictionary<TKey, TValue> ImmutableWrap<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
		{
			return new ReadOnlyDictionary<TKey, TValue>(dictionary);
		}

		public static void AddAll<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IDictionary<TKey, TValue> additional)
		{
			foreach (KeyValuePair<TKey, TValue> item in additional)
			{
				dictionary.Add(item);
			}
		}

		public static void AddAll<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IEnumerable<KeyValuePair<TKey, TValue>> additional)
		{
			foreach (KeyValuePair<TKey, TValue> item in additional)
			{
				dictionary.Add(item);
			}
		}
	}
	public static class SetExtensions
	{
		public static ISet<T> ImmutableWrap<T>(this ISet<T> set)
		{
			return new ReadOnlySet<T>(set);
		}

		public static void AddAll<T>(this ISet<T> set, IEnumerable<T> additional)
		{
			set.UnionWith(additional);
		}
	}
	public static class EnumerableExtensions
	{
		public static ISet<T> ImmutableSet<T>(this IEnumerable<T> set)
		{
			return new ReadOnlySet<T>(set);
		}
	}
	public interface MapCarrier
	{
		T getWithErrors<T>(SerializationContext ctx, KeyedEndec<T> key);

		T getWithErrors<T>(KeyedEndec<T> key)
		{
			return getWithErrors(SerializationContext.empty(), key);
		}

		void put<T>(SerializationContext ctx, KeyedEndec<T> key, T value);

		void put<T>(KeyedEndec<T> key, T value)
		{
			put(SerializationContext.empty(), key, value);
		}

		void delete<T>(KeyedEndec<T> key);

		bool has<T>(KeyedEndec<T> key);

		T get<T>(SerializationContext ctx, KeyedEndec<T> key)
		{
			try
			{
				return getWithErrors(ctx, key);
			}
			catch (Exception)
			{
				return key.defaultValue();
			}
		}

		T get<T>(KeyedEndec<T> key)
		{
			return get(SerializationContext.empty(), key);
		}

		void putIfNotNull<T>(KeyedEndec<T> key, T? value)
		{
			putIfNotNull(SerializationContext.empty(), key, value);
		}

		void putIfNotNull<T>(SerializationContext ctx, KeyedEndec<T> key, T? value)
		{
			if (value != null)
			{
				put(ctx, key, value);
			}
		}

		void copy<T>(KeyedEndec<T> key, MapCarrier other)
		{
			copy(SerializationContext.empty(), key, other);
		}

		void copy<T>(SerializationContext ctx, KeyedEndec<T> key, MapCarrier other)
		{
			other.put(ctx, key, get(ctx, key));
		}

		void copyIfPresent<T>(KeyedEndec<T> key, MapCarrier other)
		{
			copyIfPresent(SerializationContext.empty(), key, other);
		}

		void copyIfPresent<T>(SerializationContext ctx, KeyedEndec<T> key, MapCarrier other)
		{
			if (has(key))
			{
				copy(ctx, key, other);
			}
		}

		void mutate<T>(KeyedEndec<T> key, Func<T, T> mutator)
		{
			mutate(SerializationContext.empty(), key, mutator);
		}

		void mutate<T>(SerializationContext ctx, KeyedEndec<T> key, Func<T, T> mutator)
		{
			put(ctx, key, mutator(get(ctx, key)));
		}
	}
	public class ReadOnlySet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, IEnumerable
	{
		private readonly ISet<T> _set;

		public int Count => _set.Count;

		public bool IsReadOnly => true;

		public ReadOnlySet(ISet<T> set)
		{
			_set = set;
		}

		public ReadOnlySet(IEnumerable<T> enumerable)
		{
			_set = new HashSet<T>(enumerable);
		}

		public ReadOnlySet(params T[] entries)
		{
			_set = new HashSet<T>(entries);
		}

		public void Add(T item)
		{
			throw new NotSupportedException("Adding an item is not supported due to being read-only.");
		}

		public void ExceptWith(IEnumerable<T> other)
		{
			throw new NotSupportedException("Adding an item is not supported due to being read-only.");
		}

		public void IntersectWith(IEnumerable<T> other)
		{
			throw new NotSupportedException("Adding an item is not supported due to being read-only.");
		}

		public bool IsProperSubsetOf(IEnumerable<T> other)
		{
			return _set.IsProperSubsetOf(other);
		}

		public bool IsProperSupersetOf(IEnumerable<T> other)
		{
			return _set.IsProperSupersetOf(other);
		}

		public bool IsSubsetOf(IEnumerable<T> other)
		{
			return _set.IsSubsetOf(other);
		}

		public bool IsSupersetOf(IEnumerable<T> other)
		{
			return _set.IsSupersetOf(other);
		}

		public bool Overlaps(IEnumerable<T> other)
		{
			return _set.Overlaps(other);
		}

		public bool SetEquals(IEnumerable<T> other)
		{
			return _set.SetEquals(other);
		}

		public void SymmetricExceptWith(IEnumerable<T> other)
		{
			throw new NotSupportedException("Adding an item is not supported due to being read-only.");
		}

		public void UnionWith(IEnumerable<T> other)
		{
			throw new NotSupportedException("Adding an item is not supported due to being read-only.");
		}

		bool ISet<T>.Add(T item)
		{
			throw new NotSupportedException("Adding an item is not supported due to being read-only.");
		}

		public void Clear()
		{
			throw new NotSupportedException("Adding an item is not supported due to being read-only.");
		}

		public bool Contains(T item)
		{
			return _set.Contains(item);
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			_set.CopyTo(array, arrayIndex);
		}

		public bool Remove(T item)
		{
			throw new NotSupportedException("Adding an item is not supported due to being read-only.");
		}

		public IEnumerator<T> GetEnumerator()
		{
			return _set.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public abstract class RecursiveDeserializer<T> : Deserializer<T> where T : class
	{
		private readonly LinkedList<Func<T>> frames = new LinkedList<Func<T>>();

		private readonly T serialized;

		protected RecursiveDeserializer(T serialized)
		{
			this.serialized = serialized;
			frames.AddFirst(() => this.serialized);
		}

		protected T getValue()
		{
			return frames.First.Value();
		}

		protected V frame<V>(Func<T> nextValue, Func<V> action)
		{
			try
			{
				frames.AddFirst(nextValue);
				return action();
			}
			finally
			{
				frames.RemoveFirst();
			}
		}

		public V tryRead<V>(Func<Deserializer<T>, V> reader)
		{
			LinkedList<Func<T>> linkedList = new LinkedList<Func<T>>(frames);
			try
			{
				return reader(this);
			}
			catch (Exception ex)
			{
				frames.Clear();
				foreach (Func<T> item in linkedList)
				{
					frames.AddFirst(item);
				}
				throw ex;
			}
		}

		public abstract byte readByte(SerializationContext ctx);

		public abstract short readShort(SerializationContext ctx);

		public abstract int readInt(SerializationContext ctx);

		public abstract long readLong(SerializationContext ctx);

		public abstract float readFloat(SerializationContext ctx);

		public abstract double readDouble(SerializationContext ctx);

		public abstract int readVarInt(SerializationContext ctx);

		public abstract long readVarLong(SerializationContext ctx);

		public abstract bool readBoolean(SerializationContext ctx);

		public abstract string readString(SerializationContext ctx);

		public abstract byte[] readBytes(SerializationContext ctx);

		public abstract V? readOptional<V>(SerializationContext ctx, Endec<V> endec);

		public abstract SequenceDeserializer<E> sequence<E>(SerializationContext ctx, Endec<E> elementEndec);

		public abstract MapDeserializer<V> map<V>(SerializationContext ctx, Endec<V> valueEndec);

		public abstract StructDeserializer structed();
	}
	public abstract class RecursiveSerializer<T> : Serializer<T> where T : class
	{
		private readonly LinkedList<Action<T>> _frames = new LinkedList<Action<T>>();

		private T _result;

		protected RecursiveSerializer(T initialResult)
		{
			_result = initialResult;
			_frames.AddFirst(delegate(T t)
			{
				_result = t;
			});
		}

		protected void consume(T value)
		{
			_frames.First.Value(value);
		}

		protected void frame(FrameAction<T> action)
		{
			EncodedValue<T> encodedValue = new EncodedValue<T>();
			_frames.AddFirst(encodedValue.set);
			action(encodedValue);
			_frames.RemoveFirst();
		}

		public T result()
		{
			return _result;
		}

		public abstract void writeByte(SerializationContext ctx, byte value);

		public abstract void writeShort(SerializationContext ctx, short value);

		public abstract void writeInt(SerializationContext ctx, int value);

		public abstract void writeLong(SerializationContext ctx, long value);

		public abstract void writeFloat(SerializationContext ctx, float value);

		public abstract void writeDouble(SerializationContext ctx, double value);

		public abstract void writeVarInt(SerializationContext ctx, int value);

		public abstract void writeVarLong(SerializationContext ctx, long value);

		public abstract void writeBoolean(SerializationContext ctx, bool value);

		public abstract void writeString(SerializationContext ctx, string value);

		public abstract void writeBytes(SerializationContext ctx, byte[] bytes);

		public abstract void writeOptional<V>(SerializationContext ctx, Endec<V> endec, V? optional);

		public abstract SequenceSerializer<E> sequence<E>(SerializationContext ctx, Endec<E> elementEndec, int size);

		public abstract MapSerializer<V> map<V>(SerializationContext ctx, Endec<V> valueEndec, int size);

		public abstract StructSerializer structed();
	}
	public delegate void FrameAction<T>(EncodedValue<T> encoded);
	public class EncodedValue<T>
	{
		private T? _value = default(T);

		private bool _encoded = false;

		internal void set(T value)
		{
			_value = value;
			_encoded = true;
		}

		public T value()
		{
			return _value;
		}

		public bool wasEncoded()
		{
			return _encoded;
		}

		public T require(string name)
		{
			if (!_encoded)
			{
				throw new Exception("Endec for " + name + " serialized nothing");
			}
			return value();
		}
	}
	public class VarInts
	{
		public const int SEGMENT_BITS = 127;

		public const int CONTINUE_BIT = 128;

		public static int getSizeInBytesFromInt(int i)
		{
			for (int j = 1; j < 5; j++)
			{
				if ((i & (-1 << j * 7)) == 0)
				{
					return j;
				}
			}
			return 5;
		}

		public static int getSizeInBytesFromLong(long l)
		{
			for (int i = 1; i < 10; i++)
			{
				if ((l & (-1L << i * 7)) == 0)
				{
					return i;
				}
			}
			return 10;
		}

		public static int readInt(Func<byte> readByteSup)
		{
			int num = 0;
			int num2 = 0;
			while (true)
			{
				byte b = readByteSup();
				num |= (b & 0x7F) << num2;
				if ((b & 0x80) == 0)
				{
					break;
				}
				num2 += 7;
				if (num2 >= 32)
				{
					throw new Exception("VarInt is too big");
				}
			}
			return num;
		}

		public static void writeInt(int value, Action<byte> writeByteFunc)
		{
			while (((uint)value & 0xFFFFFF80u) != 0)
			{
				writeByteFunc((byte)(((uint)value & 0x7Fu) | 0x80u));
				value >>>= 7;
			}
			writeByteFunc((byte)value);
		}

		public static long readLong(Func<byte> readByteSup)
		{
			long num = 0L;
			int num2 = 0;
			while (true)
			{
				byte b = readByteSup();
				num |= (long)(b & 0x7F) << num2;
				if ((b & 0x80) == 0)
				{
					break;
				}
				num2 += 7;
				if (num2 >= 64)
				{
					throw new Exception("VarLong is too big");
				}
			}
			return num;
		}

		public static void writeLong(long value, Action<byte> writeByteFunc)
		{
			while ((value & -128) != 0)
			{
				writeByteFunc((byte)((value & 0x7F) | 0x80));
				value >>>= 7;
			}
			writeByteFunc((byte)value);
		}
	}
}
namespace io.wispforest.impl
{
	public class AttributeEndecBuilder<T>
	{
		private readonly List<(SerializationAttribute, Endec<T>)> _branches = new List<(SerializationAttribute, Endec<T>)>();

		public AttributeEndecBuilder(Endec<T> endec, SerializationAttribute attribute)
		{
			_branches.Add((attribute, endec));
		}

		public AttributeEndecBuilder<T> orElseIf(Endec<T> endec, SerializationAttribute attribute)
		{
			return orElseIf(attribute, endec);
		}

		public AttributeEndecBuilder<T> orElseIf(SerializationAttribute attribute, Endec<T> endec)
		{
			SerializationAttribute attribute2 = attribute;
			if (_branches.Exists(((SerializationAttribute, Endec<T>) tuple) => tuple.Item1.Equals(attribute2)))
			{
				throw new ArgumentException("Cannot have more than one branch for attribute " + attribute2.name);
			}
			_branches.Add((attribute2, endec));
			return this;
		}

		public Endec<T> orElse(Endec<T> endec)
		{
			Endec<T> endec2 = endec;
			return EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, T value)
			{
				Endec<T> endec4 = endec2;
				foreach (var branch in _branches)
				{
					if (ctx.hasAttribute(branch.Item1))
					{
						endec4 = branch.Item2;
						break;
					}
				}
				endec4.encode(ctx, serializer, value);
			}, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer)
			{
				Endec<T> endec3 = endec2;
				foreach (var branch2 in _branches)
				{
					if (ctx.hasAttribute(branch2.Item1))
					{
						endec3 = branch2.Item2;
						break;
					}
				}
				return endec3.decode(ctx, deserializer);
			});
		}
	}
	public class AttributeStructEndecBuilder<T>
	{
		private readonly List<(SerializationAttribute, StructEndec<T>)> branches = new List<(SerializationAttribute, StructEndec<T>)>();

		public AttributeStructEndecBuilder(StructEndec<T> endec, SerializationAttribute attribute)
		{
			branches.Add((attribute, endec));
		}

		public AttributeStructEndecBuilder<T> orElseIf(StructEndec<T> endec, SerializationAttribute attribute)
		{
			return orElseIf(attribute, endec);
		}

		public AttributeStructEndecBuilder<T> orElseIf(SerializationAttribute attribute, StructEndec<T> endec)
		{
			SerializationAttribute attribute2 = attribute;
			if (branches.Exists(((SerializationAttribute, StructEndec<T>) tuple) => tuple.Item1.Equals(attribute2)))
			{
				throw new ArgumentException("Cannot have more than one branch for attribute " + attribute2.name);
			}
			branches.Add((attribute2, endec));
			return this;
		}

		public StructEndec<T> orElse(StructEndec<T> endec)
		{
			StructEndec<T> endec2 = endec;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, T value)
			{
				StructEndec<T> structEndec2 = endec2;
				foreach (var branch in branches)
				{
					if (ctx.hasAttribute(branch.Item1))
					{
						structEndec2 = branch.Item2;
						break;
					}
				}
				structEndec2.encodeStruct(ctx, serializer, instance, value);
			}, delegate(SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance)
			{
				StructEndec<T> structEndec = endec2;
				foreach (var branch2 in branches)
				{
					if (ctx.hasAttribute(branch2.Item1))
					{
						structEndec = branch2.Item2;
						break;
					}
				}
				return structEndec.decodeStruct(ctx, deserializer, instance);
			});
		}
	}
	public class EndecImpl<T> : Endec<T>
	{
		private readonly Encoder<T> _encoder;

		private readonly Decoder<T> _decoder;

		public EndecImpl(Encoder<T> encoder, Decoder<T> decoder)
		{
			_encoder = encoder;
			_decoder = decoder;
		}

		public override void encode<E>(SerializationContext ctx, Serializer<E> serializer, T value)
		{
			_encoder(ctx, serializer, value);
		}

		public override T decode<E>(SerializationContext ctx, Deserializer<E> deserializer)
		{
			return _decoder(ctx, deserializer);
		}
	}
	public class Endecs
	{
		public static readonly StructEndec<object> VOID = EndecUtils.unit<object>(null);

		public static readonly Endec<bool> BOOLEAN = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, bool value)
		{
			serializer.writeBoolean(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readBoolean(ctx));

		public static readonly Endec<byte> BYTE = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, byte value)
		{
			serializer.writeByte(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readByte(ctx));

		public static readonly Endec<short> SHORT = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, short value)
		{
			serializer.writeShort(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readShort(ctx));

		public static readonly Endec<int> INT = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, int value)
		{
			serializer.writeInt(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readInt(ctx));

		public static readonly Endec<int> VAR_INT = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, int value)
		{
			serializer.writeVarInt(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readVarInt(ctx));

		public static readonly Endec<long> LONG = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, long value)
		{
			serializer.writeLong(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readLong(ctx));

		public static readonly Endec<long> VAR_LONG = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, long value)
		{
			serializer.writeVarLong(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readVarLong(ctx));

		public static readonly Endec<float> FLOAT = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, float value)
		{
			serializer.writeFloat(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readFloat(ctx));

		public static readonly Endec<double> DOUBLE = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, double value)
		{
			serializer.writeDouble(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readDouble(ctx));

		public static readonly Endec<string> STRING = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, string value)
		{
			serializer.writeString(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readString(ctx));

		public static readonly Endec<byte[]> BYTES = EndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, byte[] value)
		{
			serializer.writeBytes(ctx, value);
		}, (SerializationContext ctx, Deserializer<dynamic> deserializer) => deserializer.readBytes(ctx));

		public static readonly Endec<int[]> INT_ARRAY = INT.listOf().xmap((IList<int> list) => list.ToArray(), (int[] ints) => new List<int>(ints));

		public static readonly Endec<long[]> LONG_ARRAY = LONG.listOf().xmap((IList<long> list) => list.ToArray(), (long[] longs) => new List<long>(longs));

		public static readonly Endec<Guid> GUID = EndecUtils.ifAttr(SerializationAttributes.HUMAN_READABLE, STRING.xmap(Guid.Parse, (Guid guid) => guid.ToString())).orElse(BYTES.xmap((byte[] bytes) => new Guid(bytes), (Guid guid) => guid.ToByteArray()));

		public static Endec<V> vectorEndec<C, V>(string name, Endec<C> componentEndec, Func<C, C, V> constructor, Func<V, C> xGetter, Func<V, C> yGetter)
		{
			Func<C, C, V> constructor2 = constructor;
			Func<V, C> xGetter2 = xGetter;
			Func<V, C> yGetter2 = yGetter;
			return componentEndec.listOf().validate(validateSize<C>(name, 2)).xmap((IList<C> components) => constructor2(components[0], components[1]), (V vector) => new List<C>(2)
			{
				xGetter2(vector),
				yGetter2(vector)
			});
		}

		public static Endec<V> vectorEndec<C, V>(string name, Endec<C> componentEndec, Func<C, C, C, V> constructor, Func<V, C> xGetter, Func<V, C> yGetter, Func<V, C> zGetter)
		{
			Func<C, C, C, V> constructor2 = constructor;
			Func<V, C> xGetter2 = xGetter;
			Func<V, C> yGetter2 = yGetter;
			Func<V, C> zGetter2 = zGetter;
			return componentEndec.listOf().validate(validateSize<C>(name, 3)).xmap((IList<C> components) => constructor2(components[0], components[1], components[2]), (V vector) => new List<C>(3)
			{
				xGetter2(vector),
				yGetter2(vector),
				zGetter2(vector)
			});
		}

		public static Endec<V> vectorEndec<C, V>(string name, Endec<C> componentEndec, Func<C, C, C, C, V> constructor, Func<V, C> xGetter, Func<V, C> yGetter, Func<V, C> zGetter, Func<V, C> wGetter)
		{
			Func<C, C, C, C, V> constructor2 = constructor;
			Func<V, C> xGetter2 = xGetter;
			Func<V, C> yGetter2 = yGetter;
			Func<V, C> zGetter2 = zGetter;
			Func<V, C> wGetter2 = wGetter;
			return componentEndec.listOf().validate(validateSize<C>(name, 4)).xmap((IList<C> components) => constructor2(components[0], components[1], components[2], components[3]), (V vector) => new List<C>(4)
			{
				xGetter2(vector),
				yGetter2(vector),
				zGetter2(vector),
				wGetter2(vector)
			});
		}

		private static Action<IList<C>> validateSize<C>(string name, int requiredSize)
		{
			string name2 = name;
			return delegate(IList<C> collection)
			{
				if (collection.Count() != 4)
				{
					throw new ArgumentException(name2 + "collection must have " + requiredSize + " elements");
				}
			};
		}
	}
	public class KeyedEndec<F>
	{
		public string key { get; }

		public Endec<F> endec { get; }

		public Func<F> defaultValueFactory { get; }

		public KeyedEndec(string key, Endec<F> endec, Func<F> defaultValueFactory)
		{
			this.key = key;
			this.endec = endec;
			this.defaultValueFactory = defaultValueFactory;
		}

		public KeyedEndec(string key, Endec<F> endec, F defaultValue)
		{
			F defaultValue2 = defaultValue;
			this..ctor(key, endec, (Func<F>)(() => defaultValue2));
		}

		public F defaultValue()
		{
			return defaultValueFactory();
		}
	}
	public class MissingAttributeValueException : Exception
	{
		public MissingAttributeValueException(string message)
			: base(message)
		{
		}
	}
	public class RecursiveEndec<T> : Endec<T>
	{
		public readonly Endec<T> endec;

		public RecursiveEndec(Func<Endec<T>, Endec<T>> builder)
		{
			endec = builder(this);
		}

		public override void encode<E>(SerializationContext ctx, Serializer<E> serializer, T value)
		{
			endec.encode(ctx, serializer, value);
		}

		public override T decode<E>(SerializationContext ctx, Deserializer<E> deserializer)
		{
			return endec.decode(ctx, deserializer);
		}
	}
	public class RecursiveStructEndec<T> : StructEndec<T>
	{
		public readonly StructEndec<T> structEndec;

		public RecursiveStructEndec(Func<StructEndec<T>, StructEndec<T>> builder)
		{
			structEndec = builder(this);
		}

		public override void encodeStruct<E>(SerializationContext ctx, Serializer<E> serializer, StructSerializer instance, T value)
		{
			structEndec.encodeStruct(ctx, serializer, instance, value);
		}

		public override T decodeStruct<E>(SerializationContext ctx, Deserializer<E> deserializer, StructDeserializer instance)
		{
			return structEndec.decodeStruct(ctx, deserializer, instance);
		}
	}
	public class StructEndecBuilder
	{
		public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, in T17, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16, T17 arg17);

		public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, in T17, in T18, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16, T17 arg17, T18 arg18);

		public static StructEndec<S> of<S, F1>(StructField<S, F1> f1, Func<F1, S> constructor)
		{
			StructField<S, F1> f2 = f1;
			Func<F1, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f2.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f2.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2>(StructField<S, F1> f1, StructField<S, F2> f2, Func<F1, F2, S> constructor)
		{
			StructField<S, F1> f3 = f1;
			StructField<S, F2> f4 = f2;
			Func<F1, F2, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f3.encodeField(ctx, serializer, instance, value);
				f4.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f3.decodeField(ctx, deserializer, instance), f4.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, Func<F1, F2, F3, S> constructor)
		{
			StructField<S, F1> f4 = f1;
			StructField<S, F2> f5 = f2;
			StructField<S, F3> f6 = f3;
			Func<F1, F2, F3, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f4.encodeField(ctx, serializer, instance, value);
				f5.encodeField(ctx, serializer, instance, value);
				f6.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f4.decodeField(ctx, deserializer, instance), f5.decodeField(ctx, deserializer, instance), f6.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, Func<F1, F2, F3, F4, S> constructor)
		{
			StructField<S, F1> f5 = f1;
			StructField<S, F2> f6 = f2;
			StructField<S, F3> f7 = f3;
			StructField<S, F4> f8 = f4;
			Func<F1, F2, F3, F4, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f5.encodeField(ctx, serializer, instance, value);
				f6.encodeField(ctx, serializer, instance, value);
				f7.encodeField(ctx, serializer, instance, value);
				f8.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f5.decodeField(ctx, deserializer, instance), f6.decodeField(ctx, deserializer, instance), f7.decodeField(ctx, deserializer, instance), f8.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, Func<F1, F2, F3, F4, F5, S> constructor)
		{
			StructField<S, F1> f6 = f1;
			StructField<S, F2> f7 = f2;
			StructField<S, F3> f8 = f3;
			StructField<S, F4> f9 = f4;
			StructField<S, F5> f10 = f5;
			Func<F1, F2, F3, F4, F5, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f6.encodeField(ctx, serializer, instance, value);
				f7.encodeField(ctx, serializer, instance, value);
				f8.encodeField(ctx, serializer, instance, value);
				f9.encodeField(ctx, serializer, instance, value);
				f10.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f6.decodeField(ctx, deserializer, instance), f7.decodeField(ctx, deserializer, instance), f8.decodeField(ctx, deserializer, instance), f9.decodeField(ctx, deserializer, instance), f10.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, Func<F1, F2, F3, F4, F5, F6, S> constructor)
		{
			StructField<S, F1> f7 = f1;
			StructField<S, F2> f8 = f2;
			StructField<S, F3> f9 = f3;
			StructField<S, F4> f10 = f4;
			StructField<S, F5> f11 = f5;
			StructField<S, F6> f12 = f6;
			Func<F1, F2, F3, F4, F5, F6, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f7.encodeField(ctx, serializer, instance, value);
				f8.encodeField(ctx, serializer, instance, value);
				f9.encodeField(ctx, serializer, instance, value);
				f10.encodeField(ctx, serializer, instance, value);
				f11.encodeField(ctx, serializer, instance, value);
				f12.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f7.decodeField(ctx, deserializer, instance), f8.decodeField(ctx, deserializer, instance), f9.decodeField(ctx, deserializer, instance), f10.decodeField(ctx, deserializer, instance), f11.decodeField(ctx, deserializer, instance), f12.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, Func<F1, F2, F3, F4, F5, F6, F7, S> constructor)
		{
			StructField<S, F1> f8 = f1;
			StructField<S, F2> f9 = f2;
			StructField<S, F3> f10 = f3;
			StructField<S, F4> f11 = f4;
			StructField<S, F5> f12 = f5;
			StructField<S, F6> f13 = f6;
			StructField<S, F7> f14 = f7;
			Func<F1, F2, F3, F4, F5, F6, F7, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f8.encodeField(ctx, serializer, instance, value);
				f9.encodeField(ctx, serializer, instance, value);
				f10.encodeField(ctx, serializer, instance, value);
				f11.encodeField(ctx, serializer, instance, value);
				f12.encodeField(ctx, serializer, instance, value);
				f13.encodeField(ctx, serializer, instance, value);
				f14.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f8.decodeField(ctx, deserializer, instance), f9.decodeField(ctx, deserializer, instance), f10.decodeField(ctx, deserializer, instance), f11.decodeField(ctx, deserializer, instance), f12.decodeField(ctx, deserializer, instance), f13.decodeField(ctx, deserializer, instance), f14.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, Func<F1, F2, F3, F4, F5, F6, F7, F8, S> constructor)
		{
			StructField<S, F1> f9 = f1;
			StructField<S, F2> f10 = f2;
			StructField<S, F3> f11 = f3;
			StructField<S, F4> f12 = f4;
			StructField<S, F5> f13 = f5;
			StructField<S, F6> f14 = f6;
			StructField<S, F7> f15 = f7;
			StructField<S, F8> f16 = f8;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f9.encodeField(ctx, serializer, instance, value);
				f10.encodeField(ctx, serializer, instance, value);
				f11.encodeField(ctx, serializer, instance, value);
				f12.encodeField(ctx, serializer, instance, value);
				f13.encodeField(ctx, serializer, instance, value);
				f14.encodeField(ctx, serializer, instance, value);
				f15.encodeField(ctx, serializer, instance, value);
				f16.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f9.decodeField(ctx, deserializer, instance), f10.decodeField(ctx, deserializer, instance), f11.decodeField(ctx, deserializer, instance), f12.decodeField(ctx, deserializer, instance), f13.decodeField(ctx, deserializer, instance), f14.decodeField(ctx, deserializer, instance), f15.decodeField(ctx, deserializer, instance), f16.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, S> constructor)
		{
			StructField<S, F1> f10 = f1;
			StructField<S, F2> f11 = f2;
			StructField<S, F3> f12 = f3;
			StructField<S, F4> f13 = f4;
			StructField<S, F5> f14 = f5;
			StructField<S, F6> f15 = f6;
			StructField<S, F7> f16 = f7;
			StructField<S, F8> f17 = f8;
			StructField<S, F9> f18 = f9;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f10.encodeField(ctx, serializer, instance, value);
				f11.encodeField(ctx, serializer, instance, value);
				f12.encodeField(ctx, serializer, instance, value);
				f13.encodeField(ctx, serializer, instance, value);
				f14.encodeField(ctx, serializer, instance, value);
				f15.encodeField(ctx, serializer, instance, value);
				f16.encodeField(ctx, serializer, instance, value);
				f17.encodeField(ctx, serializer, instance, value);
				f18.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f10.decodeField(ctx, deserializer, instance), f11.decodeField(ctx, deserializer, instance), f12.decodeField(ctx, deserializer, instance), f13.decodeField(ctx, deserializer, instance), f14.decodeField(ctx, deserializer, instance), f15.decodeField(ctx, deserializer, instance), f16.decodeField(ctx, deserializer, instance), f17.decodeField(ctx, deserializer, instance), f18.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, S> constructor)
		{
			StructField<S, F1> f11 = f1;
			StructField<S, F2> f13 = f2;
			StructField<S, F3> f14 = f3;
			StructField<S, F4> f15 = f4;
			StructField<S, F5> f16 = f5;
			StructField<S, F6> f17 = f6;
			StructField<S, F7> f18 = f7;
			StructField<S, F8> f19 = f8;
			StructField<S, F9> f20 = f9;
			StructField<S, F10> f12 = f10;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f11.encodeField(ctx, serializer, instance, value);
				f13.encodeField(ctx, serializer, instance, value);
				f14.encodeField(ctx, serializer, instance, value);
				f15.encodeField(ctx, serializer, instance, value);
				f16.encodeField(ctx, serializer, instance, value);
				f17.encodeField(ctx, serializer, instance, value);
				f18.encodeField(ctx, serializer, instance, value);
				f19.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
				f12.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f11.decodeField(ctx, deserializer, instance), f13.decodeField(ctx, deserializer, instance), f14.decodeField(ctx, deserializer, instance), f15.decodeField(ctx, deserializer, instance), f16.decodeField(ctx, deserializer, instance), f17.decodeField(ctx, deserializer, instance), f18.decodeField(ctx, deserializer, instance), f19.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance), f12.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, StructField<S, F11> f11, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, S> constructor)
		{
			StructField<S, F1> f12 = f1;
			StructField<S, F2> f15 = f2;
			StructField<S, F3> f16 = f3;
			StructField<S, F4> f17 = f4;
			StructField<S, F5> f18 = f5;
			StructField<S, F6> f19 = f6;
			StructField<S, F7> f20 = f7;
			StructField<S, F8> f21 = f8;
			StructField<S, F9> f22 = f9;
			StructField<S, F10> f13 = f10;
			StructField<S, F11> f14 = f11;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f12.encodeField(ctx, serializer, instance, value);
				f15.encodeField(ctx, serializer, instance, value);
				f16.encodeField(ctx, serializer, instance, value);
				f17.encodeField(ctx, serializer, instance, value);
				f18.encodeField(ctx, serializer, instance, value);
				f19.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
				f21.encodeField(ctx, serializer, instance, value);
				f22.encodeField(ctx, serializer, instance, value);
				f13.encodeField(ctx, serializer, instance, value);
				f14.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f12.decodeField(ctx, deserializer, instance), f15.decodeField(ctx, deserializer, instance), f16.decodeField(ctx, deserializer, instance), f17.decodeField(ctx, deserializer, instance), f18.decodeField(ctx, deserializer, instance), f19.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance), f21.decodeField(ctx, deserializer, instance), f22.decodeField(ctx, deserializer, instance), f13.decodeField(ctx, deserializer, instance), f14.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, StructField<S, F11> f11, StructField<S, F12> f12, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, S> constructor)
		{
			StructField<S, F1> f13 = f1;
			StructField<S, F2> f17 = f2;
			StructField<S, F3> f18 = f3;
			StructField<S, F4> f19 = f4;
			StructField<S, F5> f20 = f5;
			StructField<S, F6> f21 = f6;
			StructField<S, F7> f22 = f7;
			StructField<S, F8> f23 = f8;
			StructField<S, F9> f24 = f9;
			StructField<S, F10> f14 = f10;
			StructField<S, F11> f15 = f11;
			StructField<S, F12> f16 = f12;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f13.encodeField(ctx, serializer, instance, value);
				f17.encodeField(ctx, serializer, instance, value);
				f18.encodeField(ctx, serializer, instance, value);
				f19.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
				f21.encodeField(ctx, serializer, instance, value);
				f22.encodeField(ctx, serializer, instance, value);
				f23.encodeField(ctx, serializer, instance, value);
				f24.encodeField(ctx, serializer, instance, value);
				f14.encodeField(ctx, serializer, instance, value);
				f15.encodeField(ctx, serializer, instance, value);
				f16.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f13.decodeField(ctx, deserializer, instance), f17.decodeField(ctx, deserializer, instance), f18.decodeField(ctx, deserializer, instance), f19.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance), f21.decodeField(ctx, deserializer, instance), f22.decodeField(ctx, deserializer, instance), f23.decodeField(ctx, deserializer, instance), f24.decodeField(ctx, deserializer, instance), f14.decodeField(ctx, deserializer, instance), f15.decodeField(ctx, deserializer, instance), f16.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, StructField<S, F11> f11, StructField<S, F12> f12, StructField<S, F13> f13, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, S> constructor)
		{
			StructField<S, F1> f14 = f1;
			StructField<S, F2> f19 = f2;
			StructField<S, F3> f20 = f3;
			StructField<S, F4> f21 = f4;
			StructField<S, F5> f22 = f5;
			StructField<S, F6> f23 = f6;
			StructField<S, F7> f24 = f7;
			StructField<S, F8> f25 = f8;
			StructField<S, F9> f26 = f9;
			StructField<S, F10> f15 = f10;
			StructField<S, F11> f16 = f11;
			StructField<S, F12> f17 = f12;
			StructField<S, F13> f18 = f13;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f14.encodeField(ctx, serializer, instance, value);
				f19.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
				f21.encodeField(ctx, serializer, instance, value);
				f22.encodeField(ctx, serializer, instance, value);
				f23.encodeField(ctx, serializer, instance, value);
				f24.encodeField(ctx, serializer, instance, value);
				f25.encodeField(ctx, serializer, instance, value);
				f26.encodeField(ctx, serializer, instance, value);
				f15.encodeField(ctx, serializer, instance, value);
				f16.encodeField(ctx, serializer, instance, value);
				f17.encodeField(ctx, serializer, instance, value);
				f18.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f14.decodeField(ctx, deserializer, instance), f19.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance), f21.decodeField(ctx, deserializer, instance), f22.decodeField(ctx, deserializer, instance), f23.decodeField(ctx, deserializer, instance), f24.decodeField(ctx, deserializer, instance), f25.decodeField(ctx, deserializer, instance), f26.decodeField(ctx, deserializer, instance), f15.decodeField(ctx, deserializer, instance), f16.decodeField(ctx, deserializer, instance), f17.decodeField(ctx, deserializer, instance), f18.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, StructField<S, F11> f11, StructField<S, F12> f12, StructField<S, F13> f13, StructField<S, F14> f14, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, S> constructor)
		{
			StructField<S, F1> f15 = f1;
			StructField<S, F2> f21 = f2;
			StructField<S, F3> f22 = f3;
			StructField<S, F4> f23 = f4;
			StructField<S, F5> f24 = f5;
			StructField<S, F6> f25 = f6;
			StructField<S, F7> f26 = f7;
			StructField<S, F8> f27 = f8;
			StructField<S, F9> f28 = f9;
			StructField<S, F10> f16 = f10;
			StructField<S, F11> f17 = f11;
			StructField<S, F12> f18 = f12;
			StructField<S, F13> f19 = f13;
			StructField<S, F14> f20 = f14;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f15.encodeField(ctx, serializer, instance, value);
				f21.encodeField(ctx, serializer, instance, value);
				f22.encodeField(ctx, serializer, instance, value);
				f23.encodeField(ctx, serializer, instance, value);
				f24.encodeField(ctx, serializer, instance, value);
				f25.encodeField(ctx, serializer, instance, value);
				f26.encodeField(ctx, serializer, instance, value);
				f27.encodeField(ctx, serializer, instance, value);
				f28.encodeField(ctx, serializer, instance, value);
				f16.encodeField(ctx, serializer, instance, value);
				f17.encodeField(ctx, serializer, instance, value);
				f18.encodeField(ctx, serializer, instance, value);
				f19.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f15.decodeField(ctx, deserializer, instance), f21.decodeField(ctx, deserializer, instance), f22.decodeField(ctx, deserializer, instance), f23.decodeField(ctx, deserializer, instance), f24.decodeField(ctx, deserializer, instance), f25.decodeField(ctx, deserializer, instance), f26.decodeField(ctx, deserializer, instance), f27.decodeField(ctx, deserializer, instance), f28.decodeField(ctx, deserializer, instance), f16.decodeField(ctx, deserializer, instance), f17.decodeField(ctx, deserializer, instance), f18.decodeField(ctx, deserializer, instance), f19.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, StructField<S, F11> f11, StructField<S, F12> f12, StructField<S, F13> f13, StructField<S, F14> f14, StructField<S, F15> f15, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, S> constructor)
		{
			StructField<S, F1> f16 = f1;
			StructField<S, F2> f23 = f2;
			StructField<S, F3> f24 = f3;
			StructField<S, F4> f25 = f4;
			StructField<S, F5> f26 = f5;
			StructField<S, F6> f27 = f6;
			StructField<S, F7> f28 = f7;
			StructField<S, F8> f29 = f8;
			StructField<S, F9> f30 = f9;
			StructField<S, F10> f17 = f10;
			StructField<S, F11> f18 = f11;
			StructField<S, F12> f19 = f12;
			StructField<S, F13> f20 = f13;
			StructField<S, F14> f21 = f14;
			StructField<S, F15> f22 = f15;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f16.encodeField(ctx, serializer, instance, value);
				f23.encodeField(ctx, serializer, instance, value);
				f24.encodeField(ctx, serializer, instance, value);
				f25.encodeField(ctx, serializer, instance, value);
				f26.encodeField(ctx, serializer, instance, value);
				f27.encodeField(ctx, serializer, instance, value);
				f28.encodeField(ctx, serializer, instance, value);
				f29.encodeField(ctx, serializer, instance, value);
				f30.encodeField(ctx, serializer, instance, value);
				f17.encodeField(ctx, serializer, instance, value);
				f18.encodeField(ctx, serializer, instance, value);
				f19.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
				f21.encodeField(ctx, serializer, instance, value);
				f22.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f16.decodeField(ctx, deserializer, instance), f23.decodeField(ctx, deserializer, instance), f24.decodeField(ctx, deserializer, instance), f25.decodeField(ctx, deserializer, instance), f26.decodeField(ctx, deserializer, instance), f27.decodeField(ctx, deserializer, instance), f28.decodeField(ctx, deserializer, instance), f29.decodeField(ctx, deserializer, instance), f30.decodeField(ctx, deserializer, instance), f17.decodeField(ctx, deserializer, instance), f18.decodeField(ctx, deserializer, instance), f19.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance), f21.decodeField(ctx, deserializer, instance), f22.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, StructField<S, F11> f11, StructField<S, F12> f12, StructField<S, F13> f13, StructField<S, F14> f14, StructField<S, F15> f15, StructField<S, F16> f16, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, S> constructor)
		{
			StructField<S, F1> f17 = f1;
			StructField<S, F2> f25 = f2;
			StructField<S, F3> f26 = f3;
			StructField<S, F4> f27 = f4;
			StructField<S, F5> f28 = f5;
			StructField<S, F6> f29 = f6;
			StructField<S, F7> f30 = f7;
			StructField<S, F8> f31 = f8;
			StructField<S, F9> f32 = f9;
			StructField<S, F10> f18 = f10;
			StructField<S, F11> f19 = f11;
			StructField<S, F12> f20 = f12;
			StructField<S, F13> f21 = f13;
			StructField<S, F14> f22 = f14;
			StructField<S, F15> f23 = f15;
			StructField<S, F16> f24 = f16;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f17.encodeField(ctx, serializer, instance, value);
				f25.encodeField(ctx, serializer, instance, value);
				f26.encodeField(ctx, serializer, instance, value);
				f27.encodeField(ctx, serializer, instance, value);
				f28.encodeField(ctx, serializer, instance, value);
				f29.encodeField(ctx, serializer, instance, value);
				f30.encodeField(ctx, serializer, instance, value);
				f31.encodeField(ctx, serializer, instance, value);
				f32.encodeField(ctx, serializer, instance, value);
				f18.encodeField(ctx, serializer, instance, value);
				f19.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
				f21.encodeField(ctx, serializer, instance, value);
				f22.encodeField(ctx, serializer, instance, value);
				f23.encodeField(ctx, serializer, instance, value);
				f24.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f17.decodeField(ctx, deserializer, instance), f25.decodeField(ctx, deserializer, instance), f26.decodeField(ctx, deserializer, instance), f27.decodeField(ctx, deserializer, instance), f28.decodeField(ctx, deserializer, instance), f29.decodeField(ctx, deserializer, instance), f30.decodeField(ctx, deserializer, instance), f31.decodeField(ctx, deserializer, instance), f32.decodeField(ctx, deserializer, instance), f18.decodeField(ctx, deserializer, instance), f19.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance), f21.decodeField(ctx, deserializer, instance), f22.decodeField(ctx, deserializer, instance), f23.decodeField(ctx, deserializer, instance), f24.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, StructField<S, F11> f11, StructField<S, F12> f12, StructField<S, F13> f13, StructField<S, F14> f14, StructField<S, F15> f15, StructField<S, F16> f16, StructField<S, F17> f17, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, S> constructor)
		{
			StructField<S, F1> f18 = f1;
			StructField<S, F2> f27 = f2;
			StructField<S, F3> f28 = f3;
			StructField<S, F4> f29 = f4;
			StructField<S, F5> f30 = f5;
			StructField<S, F6> f31 = f6;
			StructField<S, F7> f32 = f7;
			StructField<S, F8> f33 = f8;
			StructField<S, F9> f34 = f9;
			StructField<S, F10> f19 = f10;
			StructField<S, F11> f20 = f11;
			StructField<S, F12> f21 = f12;
			StructField<S, F13> f22 = f13;
			StructField<S, F14> f23 = f14;
			StructField<S, F15> f24 = f15;
			StructField<S, F16> f25 = f16;
			StructField<S, F17> f26 = f17;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f18.encodeField(ctx, serializer, instance, value);
				f27.encodeField(ctx, serializer, instance, value);
				f28.encodeField(ctx, serializer, instance, value);
				f29.encodeField(ctx, serializer, instance, value);
				f30.encodeField(ctx, serializer, instance, value);
				f31.encodeField(ctx, serializer, instance, value);
				f32.encodeField(ctx, serializer, instance, value);
				f33.encodeField(ctx, serializer, instance, value);
				f34.encodeField(ctx, serializer, instance, value);
				f19.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
				f21.encodeField(ctx, serializer, instance, value);
				f22.encodeField(ctx, serializer, instance, value);
				f23.encodeField(ctx, serializer, instance, value);
				f24.encodeField(ctx, serializer, instance, value);
				f25.encodeField(ctx, serializer, instance, value);
				f26.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f18.decodeField(ctx, deserializer, instance), f27.decodeField(ctx, deserializer, instance), f28.decodeField(ctx, deserializer, instance), f29.decodeField(ctx, deserializer, instance), f30.decodeField(ctx, deserializer, instance), f31.decodeField(ctx, deserializer, instance), f32.decodeField(ctx, deserializer, instance), f33.decodeField(ctx, deserializer, instance), f34.decodeField(ctx, deserializer, instance), f19.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance), f21.decodeField(ctx, deserializer, instance), f22.decodeField(ctx, deserializer, instance), f23.decodeField(ctx, deserializer, instance), f24.decodeField(ctx, deserializer, instance), f25.decodeField(ctx, deserializer, instance), f26.decodeField(ctx, deserializer, instance)));
		}

		public static StructEndec<S> of<S, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18>(StructField<S, F1> f1, StructField<S, F2> f2, StructField<S, F3> f3, StructField<S, F4> f4, StructField<S, F5> f5, StructField<S, F6> f6, StructField<S, F7> f7, StructField<S, F8> f8, StructField<S, F9> f9, StructField<S, F10> f10, StructField<S, F11> f11, StructField<S, F12> f12, StructField<S, F13> f13, StructField<S, F14> f14, StructField<S, F15> f15, StructField<S, F16> f16, StructField<S, F17> f17, StructField<S, F18> f18, Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, S> constructor)
		{
			StructField<S, F1> f19 = f1;
			StructField<S, F2> f29 = f2;
			StructField<S, F3> f30 = f3;
			StructField<S, F4> f31 = f4;
			StructField<S, F5> f32 = f5;
			StructField<S, F6> f33 = f6;
			StructField<S, F7> f34 = f7;
			StructField<S, F8> f35 = f8;
			StructField<S, F9> f36 = f9;
			StructField<S, F10> f20 = f10;
			StructField<S, F11> f21 = f11;
			StructField<S, F12> f22 = f12;
			StructField<S, F13> f23 = f13;
			StructField<S, F14> f24 = f14;
			StructField<S, F15> f25 = f15;
			StructField<S, F16> f26 = f16;
			StructField<S, F17> f27 = f17;
			StructField<S, F18> f28 = f18;
			Func<F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, S> constructor2 = constructor;
			return StructEndecUtils.of(delegate(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S value)
			{
				f19.encodeField(ctx, serializer, instance, value);
				f29.encodeField(ctx, serializer, instance, value);
				f30.encodeField(ctx, serializer, instance, value);
				f31.encodeField(ctx, serializer, instance, value);
				f32.encodeField(ctx, serializer, instance, value);
				f33.encodeField(ctx, serializer, instance, value);
				f34.encodeField(ctx, serializer, instance, value);
				f35.encodeField(ctx, serializer, instance, value);
				f36.encodeField(ctx, serializer, instance, value);
				f20.encodeField(ctx, serializer, instance, value);
				f21.encodeField(ctx, serializer, instance, value);
				f22.encodeField(ctx, serializer, instance, value);
				f23.encodeField(ctx, serializer, instance, value);
				f24.encodeField(ctx, serializer, instance, value);
				f25.encodeField(ctx, serializer, instance, value);
				f26.encodeField(ctx, serializer, instance, value);
				f27.encodeField(ctx, serializer, instance, value);
				f28.encodeField(ctx, serializer, instance, value);
			}, (SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance) => constructor2(f19.decodeField(ctx, deserializer, instance), f29.decodeField(ctx, deserializer, instance), f30.decodeField(ctx, deserializer, instance), f31.decodeField(ctx, deserializer, instance), f32.decodeField(ctx, deserializer, instance), f33.decodeField(ctx, deserializer, instance), f34.decodeField(ctx, deserializer, instance), f35.decodeField(ctx, deserializer, instance), f36.decodeField(ctx, deserializer, instance), f20.decodeField(ctx, deserializer, instance), f21.decodeField(ctx, deserializer, instance), f22.decodeField(ctx, deserializer, instance), f23.decodeField(ctx, deserializer, instance), f24.decodeField(ctx, deserializer, instance), f25.decodeField(ctx, deserializer, instance), f26.decodeField(ctx, deserializer, instance), f27.decodeField(ctx, deserializer, instance), f28.decodeField(ctx, deserializer, instance)));
		}
	}
	public class StructEndecImpl<T> : StructEndec<T>
	{
		private readonly StructuredEncoder<T> _encoder;

		private readonly StructuredDecoder<T> _decoder;

		public StructEndecImpl(StructuredEncoder<T> encoder, StructuredDecoder<T> decoder)
		{
			_encoder = encoder;
			_decoder = decoder;
		}

		public override void encodeStruct<E>(SerializationContext ctx, Serializer<E> serializer, StructSerializer instance, T value)
		{
			_encoder(ctx, serializer, instance, value);
		}

		public override T decodeStruct<E>(SerializationContext ctx, Deserializer<E> deserializer, StructDeserializer instance)
		{
			return _decoder(ctx, deserializer, instance);
		}
	}
	public class StructField<S, F>
	{
		protected readonly string _name;

		protected readonly Endec<F> _endec;

		protected readonly Func<S, F> _getter;

		protected readonly Func<F>? _defaultValueFactory;

		public StructField(string name, Endec<F> endec, Func<S, F> getter, Func<F> defaultValueFactory)
		{
			_name = name;
			_endec = endec;
			_getter = getter;
			_defaultValueFactory = defaultValueFactory;
		}

		public StructField(string name, Endec<F> endec, Func<S, F> getter, F? defaultValue)
		{
			F defaultValue2 = defaultValue;
			this..ctor(name, endec, getter, (Func<F>)(() => defaultValue2));
		}

		public StructField(string name, Endec<F> endec, Func<S, F> getter)
			: this(name, endec, getter, (Func<F>)null)
		{
		}

		public virtual void encodeField(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S obj)
		{
			try
			{
				instance.field(_name, ctx, _endec, _getter(obj), _defaultValueFactory != null);
			}
			catch (Exception cause)
			{
				throw new StructFieldException("Exception occurred when encoding a given StructField: [Field: " + _name + "]", cause);
			}
		}

		public virtual F decodeField(SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance)
		{
			try
			{
				return instance.field(_name, ctx, _endec, _defaultValueFactory);
			}
			catch (Exception cause)
			{
				throw new StructFieldException("Exception occurred when decoding a given StructField: [Field: " + _name + "]", cause);
			}
		}
	}
	public sealed class FlatStructField<S, F> : StructField<S, F>
	{
		public FlatStructField(StructEndec<F> endec, Func<S, F> getter)
			: base("", (Endec<F>)endec, getter, (Func<F>)null)
		{
		}

		public override void encodeField(SerializationContext ctx, Serializer<dynamic> serializer, StructSerializer instance, S obj)
		{
			(_endec as StructEndec<F>).encodeStruct(ctx, serializer, instance, _getter(obj));
		}

		public override F decodeField(SerializationContext ctx, Deserializer<dynamic> deserializer, StructDeserializer instance)
		{
			return (_endec as StructEndec<F>).decodeStruct(ctx, deserializer, instance);
		}
	}
	public class StructFieldException : Exception
	{
		public StructFieldException(string message, Exception cause)
			: base(message, cause)
		{
		}
	}
}
namespace io.wispforest.format.binary
{
	public class BinaryReaderDeserializer : Deserializer<BinaryReader>
	{
		public static Action<string> DEBUG_HOOK_1 = delegate
		{
		};

		protected readonly BinaryReader input;

		protected BinaryReaderDeserializer(BinaryReader input)
		{
			this.input = input;
		}

		public static BinaryReaderDeserializer of(BinaryReader input)
		{
			return new BinaryReaderDeserializer(input);
		}

		public byte readByte(SerializationContext ctx)
		{
			return input.ReadByte();
		}

		public short readShort(SerializationContext ctx)
		{
			return input.ReadInt16();
		}

		public int readInt(SerializationContext ctx)
		{
			return input.ReadInt32();
		}

		public long readLong(SerializationContext ctx)
		{
			return input.ReadInt64();
		}

		public float readFloat(SerializationContext ctx)
		{
			return input.ReadSingle();
		}

		public double readDouble(SerializationContext ctx)
		{
			return input.ReadDouble();
		}

		public int readVarInt(SerializationContext ctx)
		{
			SerializationContext ctx2 = ctx;
			return VarInts.readInt(() => readByte(ctx2));
		}

		public long readVarLong(SerializationContext ctx)
		{
			SerializationContext ctx2 = ctx;
			return VarInts.readLong(() => readByte(ctx2));
		}

		public bool readBoolean(SerializationContext ctx)
		{
			return input.ReadBoolean();
		}

		public string readString(SerializationContext ctx)
		{
			string @string = Encoding.UTF8.GetString(readBytes(ctx));
			DEBUG_HOOK_1(@string);
			return @string;
		}

		public byte[] readBytes(SerializationContext ctx)
		{
			return input.ReadBytes(readVarInt(ctx));
		}

		public V? readOptional<V>(SerializationContext ctx, Endec<V> endec)
		{
			return (V?)(readBoolean(ctx) ? ((object)endec.decode(ctx, this)) : ((object)default(V)));
		}

		public V tryRead<V>(Func<Deserializer<BinaryReader>, V> reader)
		{
			throw new Exception("As BinaryReader cannot be rewound, tryRead(...) cannot be supported");
		}

		public SequenceDeserializer<E> sequence<E>(SerializationContext ctx, Endec<E> elementEndec)
		{
			return new BinaryReaderSequenceDeserializer<E>(this, ctx, elementEndec, readVarInt(ctx));
		}

		public MapDeserializer<V> map<V>(SerializationContext ctx, Endec<V> valueEndec)
		{
			return new BinaryReaderMapDeserializer<V>(this, ctx, valueEndec, readVarInt(ctx));
		}

		public StructDeserializer structed()
		{
			return new BinaryReaderStructDeserializer(this);
		}
	}
	internal class BinaryReaderSequenceDeserializer<V> : SequenceDeserializer<V>, IEnumerator<V>, IEnumerator, IDisposable, IEnumerable<V>, IEnumerable
	{
		private readonly BinaryReaderDeserializer deserializer;

		private readonly SerializationContext ctx;

		private readonly Endec<V> valueEndec;

		private readonly int size;

		private int index = 0;

		public V Current => next();

		public BinaryReaderSequenceDeserializer(BinaryReaderDeserializer deserializer, SerializationContext ctx, Endec<V> valueEndec, int size)
		{
			this.deserializer = deserializer;
			this.ctx = ctx;
			this.valueEndec = valueEndec;
			this.size = size;
		}

		public int estimatedSize()
		{
			return size;
		}

		public bool MoveNext()
		{
			return index < size;
		}

		public V next()
		{
			index++;
			return valueEndec.decode(ctx, deserializer);
		}

		public void Dispose()
		{
		}

		public void Reset()
		{
			throw new Exception("As BinaryReader cannot be rewound, Reset(...) cannot be supported");
		}
	}
	internal class BinaryReaderStructDeserializer : StructDeserializer
	{
		private readonly BinaryReaderDeserializer deserializer;

		public BinaryReaderStructDeserializer(BinaryReaderDeserializer deserializer)
		{
			this.deserializer = deserializer;
		}

		public T? field<T>(string name, SerializationContext ctx, Endec<T> endec, Func<T>? defaultValueFactory)
		{
			return endec.decode(ctx, deserializer);
		}
	}
	internal class BinaryReaderMapDeserializer<V> : MapDeserializer<V>, IEnumerator<KeyValuePair<string, V>>, IEnumerator, IDisposable, IEnumerable<KeyValuePair<string, V>>, IEnumerable
	{
		private readonly BinaryReaderDeserializer deserializer;

		private readonly SerializationContext ctx;

		private readonly Endec<V> valueEndec;

		private readonly int size;

		private int index = 0;

		public KeyValuePair<string, V> Current => next();

		public BinaryReaderMapDeserializer(BinaryReaderDeserializer deserializer, SerializationContext ctx, Endec<V> valueEndec, int size)
		{
			this.deserializer = deserializer;
			this.ctx = ctx;
			this.valueEndec = valueEndec;
			this.size = size;
		}

		public int estimatedSize()
		{
			return size;
		}

		public bool MoveNext()
		{
			return index < size;
		}

		public KeyValuePair<string, V> next()
		{
			index++;
			return new KeyValuePair<string, V>(deserializer.readString(ctx), valueEndec.decode(ctx, deserializer));
		}

		public void Dispose()
		{
		}

		public void Reset()
		{
			throw new Exception("As BinaryReader cannot be rewound, Reset(...) cannot be supported");
		}
	}
	public class BinaryWriterSerializer : Serializer<BinaryWriter>
	{
		public static Action<string> DEBUG_HOOK_1 = delegate
		{
		};

		public static Action<long, long> DEBUG_HOOK_2 = delegate
		{
		};

		protected readonly BinaryWriter input;

		protected BinaryWriterSerializer(BinaryWriter input)
		{
			this.input = input;
		}

		public static BinaryWriterSerializer of(BinaryWriter input)
		{
			return new BinaryWriterSerializer(input);
		}

		public void writeByte(SerializationContext ctx, byte value)
		{
			input.Write(value);
		}

		public void writeShort(SerializationContext ctx, short value)
		{
			input.Write(value);
		}

		public void writeInt(SerializationContext ctx, int value)
		{
			input.Write(value);
		}

		public void writeLong(SerializationContext ctx, long value)
		{
			input.Write(value);
		}

		public void writeFloat(SerializationContext ctx, float value)
		{
			input.Write(value);
		}

		public void writeDouble(SerializationContext ctx, double value)
		{
			input.Write(value);
		}

		public void writeVarInt(SerializationContext ctx, int value)
		{
			SerializationContext ctx2 = ctx;
			VarInts.writeInt(value, delegate(byte b)
			{
				writeByte(ctx2, b);
			});
		}

		public void writeVarLong(SerializationContext ctx, long value)
		{
			SerializationContext ctx2 = ctx;
			VarInts.writeLong(value, delegate(byte b)
			{
				writeByte(ctx2, b);
			});
		}

		public void writeBoolean(SerializationContext ctx, bool value)
		{
			input.Write(value);
		}

		public void writeString(SerializationContext ctx, string value)
		{
			DEBUG_HOOK_1(value);
			long arg = -1L;
			if (input.BaseStream is MemoryStream memoryStream)
			{
				arg = memoryStream.Length;
			}
			writeBytes(ctx, Encoding.UTF8.GetBytes(value));
			long arg2 = -1L;
			if (input.BaseStream is MemoryStream memoryStream2)
			{
				arg2 = memoryStream2.Length;
			}
			DEBUG_HOOK_2(arg, arg2);
		}

		public void writeBytes(SerializationContext ctx, byte[] bytes)
		{
			writeVarInt(ctx, bytes.Length);
			input.Write(bytes);
		}

		public void writeOptional<V>(SerializationContext ctx, Endec<V> endec, V? optional)
		{
			if (optional == null)
			{
				writeBoolean(ctx, value: false);
				return;
			}
			writeBoolean(ctx, value: true);
			endec.encode(ctx, this, optional);
		}

		public BinaryWriter result()
		{
			return input;
		}

		public MapSerializer<V> map<V>(SerializationContext ctx, Endec<V> valueEndec, int size)
		{
			writeVarInt(ctx, size);
			return new BinaryWriterSequenceSerializer<V>(this, ctx, valueEndec);
		}

		public SequenceSerializer<E> sequence<E>(SerializationContext ctx, Endec<E> elementEndec, int size)
		{
			writeVarInt(ctx, size);
			return new BinaryWriterSequenceSerializer<E>(this, ctx, elementEndec);
		}

		public StructSerializer structed()
		{
			return new BinaryWriterStructSerializer(this);
		}
	}
	internal class BinaryWriterSequenceSerializer<V> : SequenceSerializer<V>, Endable, IDisposable, MapSerializer<V>
	{
		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private BinaryWriterSerializer <serializer>P;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private SerializationContext <ctx>P;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private Endec<V> <valueEndec>P;

		public BinaryWriterSequenceSerializer(BinaryWriterSerializer serializer, SerializationContext ctx, Endec<V> valueEndec)
		{
			<serializer>P = serializer;
			<ctx>P = ctx;
			<valueEndec>P = valueEndec;
			base..ct

Microsoft.CSharp.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading;
using FxResources.Microsoft.CSharp;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Semantics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
using Microsoft.CodeAnalysis;

[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyDefaultAlias("Microsoft.CSharp")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Microsoft.CSharp")]
[assembly: AssemblyFileVersion("4.700.19.56404")]
[assembly: AssemblyInformationalVersion("3.1.0+0f7f38c4fd323b26da10cce95f857f77f0f09b48")]
[assembly: AssemblyProduct("Microsoft® .NET Core")]
[assembly: AssemblyTitle("Microsoft.CSharp")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("4.0.5.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}
namespace FxResources.Microsoft.CSharp
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string InternalCompilerError => GetResourceString("InternalCompilerError");

		internal static string BindPropertyFailedMethodGroup => GetResourceString("BindPropertyFailedMethodGroup");

		internal static string BindPropertyFailedEvent => GetResourceString("BindPropertyFailedEvent");

		internal static string BindInvokeFailedNonDelegate => GetResourceString("BindInvokeFailedNonDelegate");

		internal static string NullReferenceOnMemberException => GetResourceString("NullReferenceOnMemberException");

		internal static string BindCallToConditionalMethod => GetResourceString("BindCallToConditionalMethod");

		internal static string BindToVoidMethodButExpectResult => GetResourceString("BindToVoidMethodButExpectResult");

		internal static string EmptyDynamicView => GetResourceString("EmptyDynamicView");

		internal static string GetValueonWriteOnlyProperty => GetResourceString("GetValueonWriteOnlyProperty");

		internal static string BadBinaryOps => GetResourceString("BadBinaryOps");

		internal static string BadIndexLHS => GetResourceString("BadIndexLHS");

		internal static string BadIndexCount => GetResourceString("BadIndexCount");

		internal static string BadUnaryOp => GetResourceString("BadUnaryOp");

		internal static string NoImplicitConv => GetResourceString("NoImplicitConv");

		internal static string NoExplicitConv => GetResourceString("NoExplicitConv");

		internal static string ConstOutOfRange => GetResourceString("ConstOutOfRange");

		internal static string AmbigBinaryOps => GetResourceString("AmbigBinaryOps");

		internal static string AmbigUnaryOp => GetResourceString("AmbigUnaryOp");

		internal static string ValueCantBeNull => GetResourceString("ValueCantBeNull");

		internal static string NoSuchMember => GetResourceString("NoSuchMember");

		internal static string ObjectRequired => GetResourceString("ObjectRequired");

		internal static string AmbigCall => GetResourceString("AmbigCall");

		internal static string BadAccess => GetResourceString("BadAccess");

		internal static string AssgLvalueExpected => GetResourceString("AssgLvalueExpected");

		internal static string NoConstructors => GetResourceString("NoConstructors");

		internal static string PropertyLacksGet => GetResourceString("PropertyLacksGet");

		internal static string ObjectProhibited => GetResourceString("ObjectProhibited");

		internal static string AssgReadonly => GetResourceString("AssgReadonly");

		internal static string AssgReadonlyStatic => GetResourceString("AssgReadonlyStatic");

		internal static string AssgReadonlyProp => GetResourceString("AssgReadonlyProp");

		internal static string UnsafeNeeded => GetResourceString("UnsafeNeeded");

		internal static string BadBoolOp => GetResourceString("BadBoolOp");

		internal static string MustHaveOpTF => GetResourceString("MustHaveOpTF");

		internal static string ConstOutOfRangeChecked => GetResourceString("ConstOutOfRangeChecked");

		internal static string AmbigMember => GetResourceString("AmbigMember");

		internal static string NoImplicitConvCast => GetResourceString("NoImplicitConvCast");

		internal static string InaccessibleGetter => GetResourceString("InaccessibleGetter");

		internal static string InaccessibleSetter => GetResourceString("InaccessibleSetter");

		internal static string BadArity => GetResourceString("BadArity");

		internal static string TypeArgsNotAllowed => GetResourceString("TypeArgsNotAllowed");

		internal static string HasNoTypeVars => GetResourceString("HasNoTypeVars");

		internal static string NewConstraintNotSatisfied => GetResourceString("NewConstraintNotSatisfied");

		internal static string GenericConstraintNotSatisfiedRefType => GetResourceString("GenericConstraintNotSatisfiedRefType");

		internal static string GenericConstraintNotSatisfiedNullableEnum => GetResourceString("GenericConstraintNotSatisfiedNullableEnum");

		internal static string GenericConstraintNotSatisfiedNullableInterface => GetResourceString("GenericConstraintNotSatisfiedNullableInterface");

		internal static string GenericConstraintNotSatisfiedValType => GetResourceString("GenericConstraintNotSatisfiedValType");

		internal static string CantInferMethTypeArgs => GetResourceString("CantInferMethTypeArgs");

		internal static string RefConstraintNotSatisfied => GetResourceString("RefConstraintNotSatisfied");

		internal static string ValConstraintNotSatisfied => GetResourceString("ValConstraintNotSatisfied");

		internal static string AmbigUDConv => GetResourceString("AmbigUDConv");

		internal static string BindToBogus => GetResourceString("BindToBogus");

		internal static string CantCallSpecialMethod => GetResourceString("CantCallSpecialMethod");

		internal static string ConvertToStaticClass => GetResourceString("ConvertToStaticClass");

		internal static string IncrementLvalueExpected => GetResourceString("IncrementLvalueExpected");

		internal static string BadArgCount => GetResourceString("BadArgCount");

		internal static string BadArgTypes => GetResourceString("BadArgTypes");

		internal static string BadProtectedAccess => GetResourceString("BadProtectedAccess");

		internal static string BindToBogusProp2 => GetResourceString("BindToBogusProp2");

		internal static string BindToBogusProp1 => GetResourceString("BindToBogusProp1");

		internal static string BadDelArgCount => GetResourceString("BadDelArgCount");

		internal static string BadDelArgTypes => GetResourceString("BadDelArgTypes");

		internal static string BadCtorArgCount => GetResourceString("BadCtorArgCount");

		internal static string NonInvocableMemberCalled => GetResourceString("NonInvocableMemberCalled");

		internal static string BadNamedArgument => GetResourceString("BadNamedArgument");

		internal static string BadNamedArgumentForDelegateInvoke => GetResourceString("BadNamedArgumentForDelegateInvoke");

		internal static string DuplicateNamedArgument => GetResourceString("DuplicateNamedArgument");

		internal static string NamedArgumentUsedInPositional => GetResourceString("NamedArgumentUsedInPositional");

		internal static string TypeArgumentRequiredForStaticCall => GetResourceString("TypeArgumentRequiredForStaticCall");

		internal static string DynamicArgumentNeedsValue => GetResourceString("DynamicArgumentNeedsValue");

		internal static string BadNonTrailingNamedArgument => GetResourceString("BadNonTrailingNamedArgument");

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool UsingResourceKeys()
		{
			return false;
		}

		internal static string GetResourceString(string resourceKey, string defaultString = null)
		{
			if (UsingResourceKeys())
			{
				return defaultString ?? resourceKey;
			}
			string text = null;
			try
			{
				text = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			if (defaultString != null && resourceKey.Equals(text))
			{
				return defaultString;
			}
			return text;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}
	}
}
namespace System.Numerics.Hashing
{
	internal static class HashHelpers
	{
		public static readonly int RandomSeed = new Random().Next(int.MinValue, int.MaxValue);

		public static int Combine(int h1, int h2)
		{
			uint num = (uint)(h1 << 5) | ((uint)h1 >> 27);
			return ((int)num + h1) ^ h2;
		}
	}
}
namespace Microsoft.CSharp.RuntimeBinder
{
	internal readonly struct ArgumentObject
	{
		internal readonly object Value;

		internal readonly CSharpArgumentInfo Info;

		internal readonly Type Type;

		public ArgumentObject(object value, CSharpArgumentInfo info, Type type)
		{
			Value = value;
			Info = info;
			Type = type;
		}
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	public static class Binder
	{
		public static CallSiteBinder BinaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0;
			bool flag = (flags & CSharpBinderFlags.BinaryOperationLogical) != 0;
			CSharpBinaryOperationFlags cSharpBinaryOperationFlags = CSharpBinaryOperationFlags.None;
			if (flag)
			{
				cSharpBinaryOperationFlags |= CSharpBinaryOperationFlags.LogicalOperation;
			}
			return new CSharpBinaryOperationBinder(operation, isChecked, cSharpBinaryOperationFlags, context, argumentInfo).TryGetExisting();
		}

		public static CallSiteBinder Convert(CSharpBinderFlags flags, Type type, Type context)
		{
			CSharpConversionKind conversionKind = (((flags & CSharpBinderFlags.ConvertExplicit) != 0) ? CSharpConversionKind.ExplicitConversion : (((flags & CSharpBinderFlags.ConvertArrayIndex) != 0) ? CSharpConversionKind.ArrayCreationConversion : CSharpConversionKind.ImplicitConversion));
			bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0;
			return new CSharpConvertBinder(type, conversionKind, isChecked, context).TryGetExisting();
		}

		public static CallSiteBinder GetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			return new CSharpGetIndexBinder(context, argumentInfo).TryGetExisting();
		}

		public static CallSiteBinder GetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			bool resultIndexed = (flags & CSharpBinderFlags.ResultIndexed) != 0;
			return new CSharpGetMemberBinder(name, resultIndexed, context, argumentInfo).TryGetExisting();
		}

		public static CallSiteBinder Invoke(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			bool flag = (flags & CSharpBinderFlags.ResultDiscarded) != 0;
			CSharpCallFlags cSharpCallFlags = CSharpCallFlags.None;
			if (flag)
			{
				cSharpCallFlags |= CSharpCallFlags.ResultDiscarded;
			}
			return new CSharpInvokeBinder(cSharpCallFlags, context, argumentInfo).TryGetExisting();
		}

		public static CallSiteBinder InvokeMember(CSharpBinderFlags flags, string name, IEnumerable<Type> typeArguments, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			bool flag = (flags & CSharpBinderFlags.InvokeSimpleName) != 0;
			bool flag2 = (flags & CSharpBinderFlags.InvokeSpecialName) != 0;
			bool flag3 = (flags & CSharpBinderFlags.ResultDiscarded) != 0;
			CSharpCallFlags cSharpCallFlags = CSharpCallFlags.None;
			if (flag)
			{
				cSharpCallFlags |= CSharpCallFlags.SimpleNameCall;
			}
			if (flag2)
			{
				cSharpCallFlags |= CSharpCallFlags.EventHookup;
			}
			if (flag3)
			{
				cSharpCallFlags |= CSharpCallFlags.ResultDiscarded;
			}
			return new CSharpInvokeMemberBinder(cSharpCallFlags, name, context, typeArguments, argumentInfo).TryGetExisting();
		}

		public static CallSiteBinder InvokeConstructor(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			return new CSharpInvokeConstructorBinder(CSharpCallFlags.None, context, argumentInfo).TryGetExisting();
		}

		public static CallSiteBinder IsEvent(CSharpBinderFlags flags, string name, Type context)
		{
			return new CSharpIsEventBinder(name, context).TryGetExisting();
		}

		public static CallSiteBinder SetIndex(CSharpBinderFlags flags, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			bool isCompoundAssignment = (flags & CSharpBinderFlags.ValueFromCompoundAssignment) != 0;
			bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0;
			return new CSharpSetIndexBinder(isCompoundAssignment, isChecked, context, argumentInfo).TryGetExisting();
		}

		public static CallSiteBinder SetMember(CSharpBinderFlags flags, string name, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			bool isCompoundAssignment = (flags & CSharpBinderFlags.ValueFromCompoundAssignment) != 0;
			bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0;
			return new CSharpSetMemberBinder(name, isCompoundAssignment, isChecked, context, argumentInfo).TryGetExisting();
		}

		public static CallSiteBinder UnaryOperation(CSharpBinderFlags flags, ExpressionType operation, Type context, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			bool isChecked = (flags & CSharpBinderFlags.CheckedContext) != 0;
			return new CSharpUnaryOperationBinder(operation, isChecked, context, argumentInfo).TryGetExisting();
		}
	}
	internal static class BinderEquivalence
	{
		internal class BinderEqualityComparer : IEqualityComparer<ICSharpBinder>
		{
			public bool Equals(ICSharpBinder x, ICSharpBinder y)
			{
				return x.IsEquivalentTo(y);
			}

			public int GetHashCode(ICSharpBinder obj)
			{
				return obj.GetGetBinderEquivalenceHash();
			}
		}

		private static int cachedBinderCount;

		private static readonly ConcurrentDictionary<ICSharpBinder, ICSharpBinder> binderEquivalenceCache = new ConcurrentDictionary<ICSharpBinder, ICSharpBinder>(2, 32, new BinderEqualityComparer());

		internal static T TryGetExisting<T>(this T binder) where T : ICSharpBinder
		{
			ICSharpBinder orAdd = binderEquivalenceCache.GetOrAdd(binder, binder);
			if (orAdd == (object)binder)
			{
				int num = Interlocked.Increment(ref cachedBinderCount);
				if ((uint)num > 4096u)
				{
					binderEquivalenceCache.Clear();
					cachedBinderCount = 0;
				}
			}
			return (T)orAdd;
		}
	}
	internal static class BinderHelper
	{
		private static MethodInfo s_DoubleIsNaN;

		private static MethodInfo s_SingleIsNaN;

		internal static DynamicMetaObject Bind(ICSharpBinder action, RuntimeBinder binder, DynamicMetaObject[] args, IEnumerable<CSharpArgumentInfo> arginfos, DynamicMetaObject onBindingError)
		{
			Expression[] array = new Expression[args.Length];
			BindingRestrictions bindingRestrictions = BindingRestrictions.Empty;
			ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder;
			ParameterExpression parameterExpression = null;
			IEnumerator<CSharpArgumentInfo> enumerator = (arginfos ?? Array.Empty<CSharpArgumentInfo>()).GetEnumerator();
			for (int i = 0; i < args.Length; i++)
			{
				DynamicMetaObject dynamicMetaObject = args[i];
				CSharpArgumentInfo cSharpArgumentInfo = (enumerator.MoveNext() ? enumerator.Current : null);
				if (i == 0 && IsIncrementOrDecrementActionOnLocal(action))
				{
					object value = dynamicMetaObject.Value;
					parameterExpression = (ParameterExpression)(array[0] = Expression.Variable((value != null) ? value.GetType() : typeof(object), "t0"));
				}
				else
				{
					array[i] = dynamicMetaObject.Expression;
				}
				BindingRestrictions restrictions = DeduceArgumentRestriction(i, callPayload, dynamicMetaObject, cSharpArgumentInfo);
				bindingRestrictions = bindingRestrictions.Merge(restrictions);
				if (cSharpArgumentInfo != null && cSharpArgumentInfo.LiteralConstant)
				{
					if (dynamicMetaObject.Value is double && double.IsNaN((double)dynamicMetaObject.Value))
					{
						MethodInfo method = s_DoubleIsNaN ?? (s_DoubleIsNaN = typeof(double).GetMethod("IsNaN"));
						Expression expression = Expression.Call(null, method, dynamicMetaObject.Expression);
						bindingRestrictions = bindingRestrictions.Merge(BindingRestrictions.GetExpressionRestriction(expression));
					}
					else if (dynamicMetaObject.Value is float && float.IsNaN((float)dynamicMetaObject.Value))
					{
						MethodInfo method2 = s_SingleIsNaN ?? (s_SingleIsNaN = typeof(float).GetMethod("IsNaN"));
						Expression expression2 = Expression.Call(null, method2, dynamicMetaObject.Expression);
						bindingRestrictions = bindingRestrictions.Merge(BindingRestrictions.GetExpressionRestriction(expression2));
					}
					else
					{
						Expression expression3 = Expression.Equal(dynamicMetaObject.Expression, Expression.Constant(dynamicMetaObject.Value, dynamicMetaObject.Expression.Type));
						restrictions = BindingRestrictions.GetExpressionRestriction(expression3);
						bindingRestrictions = bindingRestrictions.Merge(restrictions);
					}
				}
			}
			try
			{
				Expression expression4 = binder.Bind(action, array, args, out var deferredBinding);
				if (deferredBinding != null)
				{
					expression4 = ConvertResult(deferredBinding.Expression, action);
					bindingRestrictions = deferredBinding.Restrictions.Merge(bindingRestrictions);
					return new DynamicMetaObject(expression4, bindingRestrictions);
				}
				if (parameterExpression != null)
				{
					DynamicMetaObject dynamicMetaObject2 = args[0];
					expression4 = Expression.Block(new ParameterExpression[1] { parameterExpression }, Expression.Assign(parameterExpression, Expression.Convert(dynamicMetaObject2.Expression, dynamicMetaObject2.Value.GetType())), expression4, Expression.Assign(dynamicMetaObject2.Expression, Expression.Convert(parameterExpression, dynamicMetaObject2.Expression.Type)));
				}
				expression4 = ConvertResult(expression4, action);
				return new DynamicMetaObject(expression4, bindingRestrictions);
			}
			catch (RuntimeBinderException ex)
			{
				if (onBindingError != null)
				{
					return onBindingError;
				}
				return new DynamicMetaObject(Expression.Throw(Expression.New(typeof(RuntimeBinderException).GetConstructor(new Type[1] { typeof(string) }), Expression.Constant(ex.Message)), GetTypeForErrorMetaObject(action, args)), bindingRestrictions);
			}
		}

		public static void ValidateBindArgument(DynamicMetaObject argument, string paramName)
		{
			if (argument == null)
			{
				throw Error.ArgumentNull(paramName);
			}
			if (!argument.HasValue)
			{
				throw Error.DynamicArgumentNeedsValue(paramName);
			}
		}

		public static void ValidateBindArgument(DynamicMetaObject[] arguments, string paramName)
		{
			if (arguments != null)
			{
				for (int i = 0; i != arguments.Length; i++)
				{
					ValidateBindArgument(arguments[i], $"{paramName}[{i}]");
				}
			}
		}

		private static bool IsTypeOfStaticCall(int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload)
		{
			if (parameterIndex == 0 && callPayload != null)
			{
				return callPayload.StaticCall;
			}
			return false;
		}

		private static bool IsComObject(object obj)
		{
			if (obj != null)
			{
				return Marshal.IsComObject(obj);
			}
			return false;
		}

		private static bool IsTransparentProxy(object obj)
		{
			return false;
		}

		private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info)
		{
			return info != null && !info.UseCompileTimeType && (IsComObject(argument.Value) || IsTransparentProxy(argument.Value));
		}

		private static BindingRestrictions DeduceArgumentRestriction(int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload, DynamicMetaObject argument, CSharpArgumentInfo info)
		{
			if (argument.Value != null && !IsTypeOfStaticCall(parameterIndex, callPayload) && !IsDynamicallyTypedRuntimeProxy(argument, info))
			{
				return BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType);
			}
			return BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value);
		}

		private static Expression ConvertResult(Expression binding, ICSharpBinder action)
		{
			if (action is CSharpInvokeConstructorBinder)
			{
				return binding;
			}
			if (binding.Type == typeof(void))
			{
				if (action is ICSharpInvokeOrInvokeMemberBinder iCSharpInvokeOrInvokeMemberBinder && iCSharpInvokeOrInvokeMemberBinder.ResultDiscarded)
				{
					return Expression.Block(binding, Expression.Default(action.ReturnType));
				}
				throw Error.BindToVoidMethodButExpectResult();
			}
			if (binding.Type.IsValueType && !action.ReturnType.IsValueType)
			{
				return Expression.Convert(binding, action.ReturnType);
			}
			return binding;
		}

		private static Type GetTypeForErrorMetaObject(ICSharpBinder action, DynamicMetaObject[] args)
		{
			if (action is CSharpInvokeConstructorBinder)
			{
				return args[0].Value as Type;
			}
			return action.ReturnType;
		}

		private static bool IsIncrementOrDecrementActionOnLocal(ICSharpBinder action)
		{
			if (action is CSharpUnaryOperationBinder cSharpUnaryOperationBinder)
			{
				if (cSharpUnaryOperationBinder.Operation != ExpressionType.Increment)
				{
					return cSharpUnaryOperationBinder.Operation == ExpressionType.Decrement;
				}
				return true;
			}
			return false;
		}

		internal static T[] Cons<T>(T sourceHead, T[] sourceTail)
		{
			if (sourceTail == null || sourceTail.Length != 0)
			{
				T[] array = new T[sourceTail.Length + 1];
				array[0] = sourceHead;
				sourceTail.CopyTo(array, 1);
				return array;
			}
			return new T[1] { sourceHead };
		}

		internal static T[] Cons<T>(T sourceHead, T[] sourceMiddle, T sourceLast)
		{
			if (sourceMiddle == null || sourceMiddle.Length != 0)
			{
				T[] array = new T[sourceMiddle.Length + 2];
				array[0] = sourceHead;
				array[^1] = sourceLast;
				sourceMiddle.CopyTo(array, 1);
				return array;
			}
			return new T[2] { sourceHead, sourceLast };
		}

		internal static T[] ToArray<T>(IEnumerable<T> source)
		{
			if (source != null)
			{
				return source.ToArray();
			}
			return Array.Empty<T>();
		}

		internal static CallInfo CreateCallInfo(ref IEnumerable<CSharpArgumentInfo> argInfos, int discard)
		{
			int num = 0;
			List<string> list = new List<string>();
			CSharpArgumentInfo[] array = (CSharpArgumentInfo[])(argInfos = ToArray(argInfos));
			foreach (CSharpArgumentInfo cSharpArgumentInfo in array)
			{
				if (cSharpArgumentInfo.NamedArgument)
				{
					list.Add(cSharpArgumentInfo.Name);
				}
				num++;
			}
			return new CallInfo(num - discard, list);
		}

		internal static string GetCLROperatorName(this ExpressionType p)
		{
			return p switch
			{
				ExpressionType.Add => "op_Addition", 
				ExpressionType.Subtract => "op_Subtraction", 
				ExpressionType.Multiply => "op_Multiply", 
				ExpressionType.Divide => "op_Division", 
				ExpressionType.Modulo => "op_Modulus", 
				ExpressionType.LeftShift => "op_LeftShift", 
				ExpressionType.RightShift => "op_RightShift", 
				ExpressionType.LessThan => "op_LessThan", 
				ExpressionType.GreaterThan => "op_GreaterThan", 
				ExpressionType.LessThanOrEqual => "op_LessThanOrEqual", 
				ExpressionType.GreaterThanOrEqual => "op_GreaterThanOrEqual", 
				ExpressionType.Equal => "op_Equality", 
				ExpressionType.NotEqual => "op_Inequality", 
				ExpressionType.And => "op_BitwiseAnd", 
				ExpressionType.ExclusiveOr => "op_ExclusiveOr", 
				ExpressionType.Or => "op_BitwiseOr", 
				ExpressionType.AddAssign => "op_Addition", 
				ExpressionType.SubtractAssign => "op_Subtraction", 
				ExpressionType.MultiplyAssign => "op_Multiply", 
				ExpressionType.DivideAssign => "op_Division", 
				ExpressionType.ModuloAssign => "op_Modulus", 
				ExpressionType.AndAssign => "op_BitwiseAnd", 
				ExpressionType.ExclusiveOrAssign => "op_ExclusiveOr", 
				ExpressionType.OrAssign => "op_BitwiseOr", 
				ExpressionType.LeftShiftAssign => "op_LeftShift", 
				ExpressionType.RightShiftAssign => "op_RightShift", 
				ExpressionType.Negate => "op_UnaryNegation", 
				ExpressionType.UnaryPlus => "op_UnaryPlus", 
				ExpressionType.Not => "op_LogicalNot", 
				ExpressionType.OnesComplement => "op_OnesComplement", 
				ExpressionType.IsTrue => "op_True", 
				ExpressionType.IsFalse => "op_False", 
				ExpressionType.Increment => "op_Increment", 
				ExpressionType.Decrement => "op_Decrement", 
				_ => null, 
			};
		}

		internal static int AddArgHashes(int hash, Type[] typeArguments, CSharpArgumentInfo[] argInfos)
		{
			foreach (Type type in typeArguments)
			{
				hash = HashHelpers.Combine(hash, type.GetHashCode());
			}
			return AddArgHashes(hash, argInfos);
		}

		internal static int AddArgHashes(int hash, CSharpArgumentInfo[] argInfos)
		{
			foreach (CSharpArgumentInfo cSharpArgumentInfo in argInfos)
			{
				hash = HashHelpers.Combine(hash, (int)cSharpArgumentInfo.Flags);
				string name = cSharpArgumentInfo.Name;
				if (!string.IsNullOrEmpty(name))
				{
					hash = HashHelpers.Combine(hash, name.GetHashCode());
				}
			}
			return hash;
		}

		internal static bool CompareArgInfos(Type[] typeArgs, Type[] otherTypeArgs, CSharpArgumentInfo[] argInfos, CSharpArgumentInfo[] otherArgInfos)
		{
			for (int i = 0; i < typeArgs.Length; i++)
			{
				if (typeArgs[i] != otherTypeArgs[i])
				{
					return false;
				}
			}
			return CompareArgInfos(argInfos, otherArgInfos);
		}

		internal static bool CompareArgInfos(CSharpArgumentInfo[] argInfos, CSharpArgumentInfo[] otherArgInfos)
		{
			for (int i = 0; i < argInfos.Length; i++)
			{
				CSharpArgumentInfo cSharpArgumentInfo = argInfos[i];
				CSharpArgumentInfo cSharpArgumentInfo2 = otherArgInfos[i];
				if (cSharpArgumentInfo.Flags != cSharpArgumentInfo2.Flags || cSharpArgumentInfo.Name != cSharpArgumentInfo2.Name)
				{
					return false;
				}
			}
			return true;
		}
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	public sealed class CSharpArgumentInfo
	{
		internal static readonly CSharpArgumentInfo None = new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null);

		internal CSharpArgumentInfoFlags Flags { get; }

		internal string Name { get; }

		internal bool UseCompileTimeType => (Flags & CSharpArgumentInfoFlags.UseCompileTimeType) != 0;

		internal bool LiteralConstant => (Flags & CSharpArgumentInfoFlags.Constant) != 0;

		internal bool NamedArgument => (Flags & CSharpArgumentInfoFlags.NamedArgument) != 0;

		internal bool IsByRefOrOut => (Flags & (CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.IsOut)) != 0;

		internal bool IsOut => (Flags & CSharpArgumentInfoFlags.IsOut) != 0;

		internal bool IsStaticType => (Flags & CSharpArgumentInfoFlags.IsStaticType) != 0;

		private CSharpArgumentInfo(CSharpArgumentInfoFlags flags, string name)
		{
			Flags = flags;
			Name = name;
		}

		public static CSharpArgumentInfo Create(CSharpArgumentInfoFlags flags, string name)
		{
			return new CSharpArgumentInfo(flags, name);
		}
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[Flags]
	public enum CSharpArgumentInfoFlags
	{
		None = 0,
		UseCompileTimeType = 1,
		Constant = 2,
		NamedArgument = 4,
		IsRef = 8,
		IsOut = 0x10,
		IsStaticType = 0x20
	}
	internal sealed class CSharpBinaryOperationBinder : BinaryOperationBinder, ICSharpBinder
	{
		private readonly CSharpBinaryOperationFlags _binopFlags;

		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		[ExcludeFromCodeCoverage]
		public string Name => null;

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => false;

		internal bool IsLogicalOperation => (_binopFlags & CSharpBinaryOperationFlags.LogicalOperation) != 0;

		private bool IsChecked => _binder.IsChecked;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.BindBinaryOperation(this, arguments, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			string cLROperatorName = base.Operation.GetCLROperatorName();
			SymbolTable.PopulateSymbolTableWithName(cLROperatorName, null, arguments[0].Type);
			SymbolTable.PopulateSymbolTableWithName(cLROperatorName, null, arguments[1].Type);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpBinaryOperationBinder(ExpressionType operation, bool isChecked, CSharpBinaryOperationFlags binaryOperationFlags, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo)
			: base(operation)
		{
			_binopFlags = binaryOperationFlags;
			_callingContext = callingContext;
			_argumentInfo = BinderHelper.ToArray(argumentInfo);
			_binder = new RuntimeBinder(callingContext, isChecked);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = _callingContext?.GetHashCode() ?? 0;
			h = HashHelpers.Combine(h, (int)_binopFlags);
			if (IsChecked)
			{
				h = HashHelpers.Combine(h, 1);
			}
			h = HashHelpers.Combine(h, (int)base.Operation);
			return BinderHelper.AddArgHashes(h, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpBinaryOperationBinder cSharpBinaryOperationBinder))
			{
				return false;
			}
			if (_binopFlags != cSharpBinaryOperationBinder._binopFlags || base.Operation != cSharpBinaryOperationBinder.Operation || IsChecked != cSharpBinaryOperationBinder.IsChecked || _callingContext != cSharpBinaryOperationBinder._callingContext)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(_argumentInfo, cSharpBinaryOperationBinder._argumentInfo);
		}

		public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			BinderHelper.ValidateBindArgument(arg, "arg");
			return BinderHelper.Bind(this, _binder, new DynamicMetaObject[2] { target, arg }, _argumentInfo, errorSuggestion);
		}
	}
	[Flags]
	internal enum CSharpBinaryOperationFlags
	{
		None = 0,
		MemberAccess = 1,
		LogicalOperation = 2
	}
	[Flags]
	[EditorBrowsable(EditorBrowsableState.Never)]
	public enum CSharpBinderFlags
	{
		None = 0,
		CheckedContext = 1,
		InvokeSimpleName = 2,
		InvokeSpecialName = 4,
		BinaryOperationLogical = 8,
		ConvertExplicit = 0x10,
		ConvertArrayIndex = 0x20,
		ResultIndexed = 0x40,
		ValueFromCompoundAssignment = 0x80,
		ResultDiscarded = 0x100
	}
	[Flags]
	internal enum CSharpCallFlags
	{
		None = 0,
		SimpleNameCall = 1,
		EventHookup = 2,
		ResultDiscarded = 4
	}
	internal enum CSharpConversionKind
	{
		ImplicitConversion,
		ExplicitConversion,
		ArrayCreationConversion
	}
	internal sealed class CSharpConvertBinder : ConvertBinder, ICSharpBinder
	{
		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		[ExcludeFromCodeCoverage]
		public string Name => null;

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => false;

		private CSharpConversionKind ConversionKind { get; }

		private bool IsChecked => _binder.IsChecked;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			if (!base.Explicit)
			{
				return runtimeBinder.BindImplicitConversion(arguments, base.Type, locals, ConversionKind == CSharpConversionKind.ArrayCreationConversion);
			}
			return runtimeBinder.BindExplicitConversion(arguments, base.Type, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return CSharpArgumentInfo.None;
		}

		public CSharpConvertBinder(Type type, CSharpConversionKind conversionKind, bool isChecked, Type callingContext)
			: base(type, conversionKind == CSharpConversionKind.ExplicitConversion)
		{
			ConversionKind = conversionKind;
			_callingContext = callingContext;
			_binder = new RuntimeBinder(callingContext, isChecked);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = _callingContext?.GetHashCode() ?? 0;
			h = HashHelpers.Combine(h, (int)ConversionKind);
			if (IsChecked)
			{
				h = HashHelpers.Combine(h, 1);
			}
			return HashHelpers.Combine(h, base.Type.GetHashCode());
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpConvertBinder cSharpConvertBinder))
			{
				return false;
			}
			if (ConversionKind != cSharpConvertBinder.ConversionKind || IsChecked != cSharpConvertBinder.IsChecked || _callingContext != cSharpConvertBinder._callingContext || base.Type != cSharpConvertBinder.Type)
			{
				return false;
			}
			return true;
		}

		public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			return BinderHelper.Bind(this, _binder, new DynamicMetaObject[1] { target }, null, errorSuggestion);
		}
	}
	internal sealed class CSharpGetIndexBinder : GetIndexBinder, ICSharpBinder
	{
		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		public string Name => "$Item$";

		public BindingFlag BindingFlags => BindingFlag.BIND_RVALUEREQUIRED;

		public bool IsBinderThatCanHaveRefReceiver => true;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			Expr optionalIndexerArguments = runtimeBinder.CreateArgumentListEXPR(arguments, locals, 1, arguments.Length);
			return runtimeBinder.BindProperty(this, arguments[0], locals[0], optionalIndexerArguments);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			SymbolTable.PopulateSymbolTableWithName("$Item$", null, arguments[0].Type);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpGetIndexBinder(Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo)
			: base(BinderHelper.CreateCallInfo(ref argumentInfo, 1))
		{
			_argumentInfo = argumentInfo as CSharpArgumentInfo[];
			_callingContext = callingContext;
			_binder = new RuntimeBinder(callingContext);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int hash = _callingContext?.GetHashCode() ?? 0;
			return BinderHelper.AddArgHashes(hash, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpGetIndexBinder cSharpGetIndexBinder))
			{
				return false;
			}
			if (_callingContext != cSharpGetIndexBinder._callingContext || _argumentInfo.Length != cSharpGetIndexBinder._argumentInfo.Length)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(_argumentInfo, cSharpGetIndexBinder._argumentInfo);
		}

		public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			BinderHelper.ValidateBindArgument(indexes, "indexes");
			return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, indexes), _argumentInfo, errorSuggestion);
		}
	}
	internal sealed class CSharpGetMemberBinder : GetMemberBinder, IInvokeOnGetBinder, ICSharpBinder
	{
		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		public BindingFlag BindingFlags => BindingFlag.BIND_RVALUEREQUIRED;

		public bool IsBinderThatCanHaveRefReceiver => false;

		bool IInvokeOnGetBinder.InvokeOnGet => !ResultIndexed;

		private bool ResultIndexed { get; }

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.BindProperty(this, arguments[0], locals[0], null);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			SymbolTable.PopulateSymbolTableWithName(base.Name, null, arguments[0].Type);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpGetMemberBinder(string name, bool resultIndexed, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo)
			: base(name, ignoreCase: false)
		{
			ResultIndexed = resultIndexed;
			_argumentInfo = BinderHelper.ToArray(argumentInfo);
			_callingContext = callingContext;
			_binder = new RuntimeBinder(callingContext);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = _callingContext?.GetHashCode() ?? 0;
			if (ResultIndexed)
			{
				h = HashHelpers.Combine(h, 1);
			}
			h = HashHelpers.Combine(h, base.Name.GetHashCode());
			return BinderHelper.AddArgHashes(h, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpGetMemberBinder cSharpGetMemberBinder))
			{
				return false;
			}
			if (base.Name != cSharpGetMemberBinder.Name || ResultIndexed != cSharpGetMemberBinder.ResultIndexed || _callingContext != cSharpGetMemberBinder._callingContext || _argumentInfo.Length != cSharpGetMemberBinder._argumentInfo.Length)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(_argumentInfo, cSharpGetMemberBinder._argumentInfo);
		}

		public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			return BinderHelper.Bind(this, _binder, new DynamicMetaObject[1] { target }, _argumentInfo, errorSuggestion);
		}

		[SpecialName]
		string ICSharpBinder.get_Name()
		{
			return base.Name;
		}
	}
	internal sealed class CSharpInvokeBinder : InvokeBinder, ICSharpInvokeOrInvokeMemberBinder, ICSharpBinder
	{
		private readonly CSharpCallFlags _flags;

		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => true;

		bool ICSharpInvokeOrInvokeMemberBinder.StaticCall
		{
			get
			{
				if (_argumentInfo[0] != null)
				{
					return _argumentInfo[0].IsStaticType;
				}
				return false;
			}
		}

		string ICSharpBinder.Name => "Invoke";

		Type[] ICSharpInvokeOrInvokeMemberBinder.TypeArguments => Array.Empty<Type>();

		CSharpCallFlags ICSharpInvokeOrInvokeMemberBinder.Flags => _flags;

		bool ICSharpInvokeOrInvokeMemberBinder.ResultDiscarded => (_flags & CSharpCallFlags.ResultDiscarded) != 0;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.DispatchPayload(this, arguments, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			RuntimeBinder.PopulateSymbolTableWithPayloadInformation(this, callingType, arguments);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpInvokeBinder(CSharpCallFlags flags, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo)
			: base(BinderHelper.CreateCallInfo(ref argumentInfo, 1))
		{
			_flags = flags;
			_callingContext = callingContext;
			_argumentInfo = argumentInfo as CSharpArgumentInfo[];
			_binder = new RuntimeBinder(callingContext);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = _callingContext?.GetHashCode() ?? 0;
			h = HashHelpers.Combine(h, (int)_flags);
			return BinderHelper.AddArgHashes(h, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpInvokeBinder cSharpInvokeBinder))
			{
				return false;
			}
			if (_flags != cSharpInvokeBinder._flags || _callingContext != cSharpInvokeBinder._callingContext || _argumentInfo.Length != cSharpInvokeBinder._argumentInfo.Length)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(_argumentInfo, cSharpInvokeBinder._argumentInfo);
		}

		public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			BinderHelper.ValidateBindArgument(args, "args");
			return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, args), _argumentInfo, errorSuggestion);
		}
	}
	internal sealed class CSharpInvokeConstructorBinder : DynamicMetaObjectBinder, ICSharpInvokeOrInvokeMemberBinder, ICSharpBinder
	{
		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => true;

		public CSharpCallFlags Flags { get; }

		public bool StaticCall => true;

		public Type[] TypeArguments => Array.Empty<Type>();

		public string Name => ".ctor";

		bool ICSharpInvokeOrInvokeMemberBinder.ResultDiscarded => false;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.DispatchPayload(this, arguments, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			RuntimeBinder.PopulateSymbolTableWithPayloadInformation(this, callingType, arguments);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpInvokeConstructorBinder(CSharpCallFlags flags, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo)
		{
			Flags = flags;
			_callingContext = callingContext;
			_argumentInfo = BinderHelper.ToArray(argumentInfo);
			_binder = new RuntimeBinder(callingContext);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = _callingContext?.GetHashCode() ?? 0;
			h = HashHelpers.Combine(h, (int)Flags);
			h = HashHelpers.Combine(h, Name.GetHashCode());
			return BinderHelper.AddArgHashes(h, TypeArguments, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpInvokeConstructorBinder cSharpInvokeConstructorBinder))
			{
				return false;
			}
			if (Flags != cSharpInvokeConstructorBinder.Flags || _callingContext != cSharpInvokeConstructorBinder._callingContext || Name != cSharpInvokeConstructorBinder.Name || TypeArguments.Length != cSharpInvokeConstructorBinder.TypeArguments.Length || _argumentInfo.Length != cSharpInvokeConstructorBinder._argumentInfo.Length)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(TypeArguments, cSharpInvokeConstructorBinder.TypeArguments, _argumentInfo, cSharpInvokeConstructorBinder._argumentInfo);
		}

		public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			BinderHelper.ValidateBindArgument(args, "args");
			return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, args), _argumentInfo, null);
		}
	}
	internal sealed class CSharpInvokeMemberBinder : InvokeMemberBinder, ICSharpInvokeOrInvokeMemberBinder, ICSharpBinder
	{
		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => true;

		bool ICSharpInvokeOrInvokeMemberBinder.StaticCall => _argumentInfo[0]?.IsStaticType ?? false;

		public CSharpCallFlags Flags { get; }

		public Type CallingContext { get; }

		public Type[] TypeArguments { get; }

		bool ICSharpInvokeOrInvokeMemberBinder.ResultDiscarded => (Flags & CSharpCallFlags.ResultDiscarded) != 0;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.DispatchPayload(this, arguments, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			RuntimeBinder.PopulateSymbolTableWithPayloadInformation(this, callingType, arguments);
		}

		public CSharpArgumentInfo GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpArgumentInfo[] ArgumentInfoArray()
		{
			CSharpArgumentInfo[] array = new CSharpArgumentInfo[_argumentInfo.Length];
			_argumentInfo.CopyTo(array, 0);
			return array;
		}

		public CSharpInvokeMemberBinder(CSharpCallFlags flags, string name, Type callingContext, IEnumerable<Type> typeArguments, IEnumerable<CSharpArgumentInfo> argumentInfo)
			: base(name, ignoreCase: false, BinderHelper.CreateCallInfo(ref argumentInfo, 1))
		{
			Flags = flags;
			CallingContext = callingContext;
			TypeArguments = BinderHelper.ToArray(typeArguments);
			_argumentInfo = BinderHelper.ToArray(argumentInfo);
			_binder = new RuntimeBinder(callingContext);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = CallingContext?.GetHashCode() ?? 0;
			h = HashHelpers.Combine(h, (int)Flags);
			h = HashHelpers.Combine(h, base.Name.GetHashCode());
			return BinderHelper.AddArgHashes(h, TypeArguments, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpInvokeMemberBinder cSharpInvokeMemberBinder))
			{
				return false;
			}
			if (Flags != cSharpInvokeMemberBinder.Flags || CallingContext != cSharpInvokeMemberBinder.CallingContext || base.Name != cSharpInvokeMemberBinder.Name || TypeArguments.Length != cSharpInvokeMemberBinder.TypeArguments.Length || _argumentInfo.Length != cSharpInvokeMemberBinder._argumentInfo.Length)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(TypeArguments, cSharpInvokeMemberBinder.TypeArguments, _argumentInfo, cSharpInvokeMemberBinder._argumentInfo);
		}

		public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			BinderHelper.ValidateBindArgument(args, "args");
			return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, args), _argumentInfo, errorSuggestion);
		}

		public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
		{
			CSharpInvokeBinder cSharpInvokeBinder = new CSharpInvokeBinder(Flags, CallingContext, _argumentInfo).TryGetExisting();
			return cSharpInvokeBinder.Defer(target, args);
		}

		[SpecialName]
		string ICSharpBinder.get_Name()
		{
			return base.Name;
		}
	}
	internal sealed class CSharpIsEventBinder : DynamicMetaObjectBinder, ICSharpBinder
	{
		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => false;

		public string Name { get; }

		public override Type ReturnType => typeof(bool);

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.BindIsEvent(this, arguments, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			SymbolTable.PopulateSymbolTableWithName(Name, null, arguments[0].Info.IsStaticType ? (arguments[0].Value as Type) : arguments[0].Type);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return CSharpArgumentInfo.None;
		}

		public CSharpIsEventBinder(string name, Type callingContext)
		{
			Name = name;
			_callingContext = callingContext;
			_binder = new RuntimeBinder(callingContext);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = _callingContext?.GetHashCode() ?? 0;
			return HashHelpers.Combine(h, Name.GetHashCode());
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpIsEventBinder cSharpIsEventBinder))
			{
				return false;
			}
			if (_callingContext != cSharpIsEventBinder._callingContext || Name != cSharpIsEventBinder.Name)
			{
				return false;
			}
			return true;
		}

		public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			return BinderHelper.Bind(this, _binder, new DynamicMetaObject[1] { target }, null, null);
		}
	}
	internal sealed class CSharpSetIndexBinder : SetIndexBinder, ICSharpBinder
	{
		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		public string Name => "$Item$";

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => true;

		internal bool IsCompoundAssignment { get; }

		private bool IsChecked => _binder.IsChecked;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.BindAssignment(this, arguments, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			SymbolTable.PopulateSymbolTableWithName("$Item$", null, arguments[0].Type);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpSetIndexBinder(bool isCompoundAssignment, bool isChecked, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo)
			: base(BinderHelper.CreateCallInfo(ref argumentInfo, 2))
		{
			IsCompoundAssignment = isCompoundAssignment;
			_argumentInfo = argumentInfo as CSharpArgumentInfo[];
			_callingContext = callingContext;
			_binder = new RuntimeBinder(callingContext, isChecked);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int num = _callingContext?.GetHashCode() ?? 0;
			if (IsChecked)
			{
				num = HashHelpers.Combine(num, 1);
			}
			if (IsCompoundAssignment)
			{
				num = HashHelpers.Combine(num, 1);
			}
			return BinderHelper.AddArgHashes(num, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpSetIndexBinder cSharpSetIndexBinder))
			{
				return false;
			}
			if (_callingContext != cSharpSetIndexBinder._callingContext || IsChecked != cSharpSetIndexBinder.IsChecked || IsCompoundAssignment != cSharpSetIndexBinder.IsCompoundAssignment || _argumentInfo.Length != cSharpSetIndexBinder._argumentInfo.Length)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(_argumentInfo, cSharpSetIndexBinder._argumentInfo);
		}

		public override DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			BinderHelper.ValidateBindArgument(indexes, "indexes");
			BinderHelper.ValidateBindArgument(value, "value");
			return BinderHelper.Bind(this, _binder, BinderHelper.Cons(target, indexes, value), _argumentInfo, errorSuggestion);
		}
	}
	internal sealed class CSharpSetMemberBinder : SetMemberBinder, ICSharpBinder
	{
		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => false;

		internal bool IsCompoundAssignment { get; }

		private bool IsChecked => _binder.IsChecked;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.BindAssignment(this, arguments, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			SymbolTable.PopulateSymbolTableWithName(base.Name, null, arguments[0].Type);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpSetMemberBinder(string name, bool isCompoundAssignment, bool isChecked, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo)
			: base(name, ignoreCase: false)
		{
			IsCompoundAssignment = isCompoundAssignment;
			_argumentInfo = BinderHelper.ToArray(argumentInfo);
			_callingContext = callingContext;
			_binder = new RuntimeBinder(callingContext, isChecked);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = _callingContext?.GetHashCode() ?? 0;
			if (IsChecked)
			{
				h = HashHelpers.Combine(h, 1);
			}
			if (IsCompoundAssignment)
			{
				h = HashHelpers.Combine(h, 1);
			}
			h = HashHelpers.Combine(h, base.Name.GetHashCode());
			return BinderHelper.AddArgHashes(h, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpSetMemberBinder cSharpSetMemberBinder))
			{
				return false;
			}
			if (base.Name != cSharpSetMemberBinder.Name || _callingContext != cSharpSetMemberBinder._callingContext || IsChecked != cSharpSetMemberBinder.IsChecked || IsCompoundAssignment != cSharpSetMemberBinder.IsCompoundAssignment || _argumentInfo.Length != cSharpSetMemberBinder._argumentInfo.Length)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(_argumentInfo, cSharpSetMemberBinder._argumentInfo);
		}

		public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			BinderHelper.ValidateBindArgument(value, "value");
			return BinderHelper.Bind(this, _binder, new DynamicMetaObject[2] { target, value }, _argumentInfo, errorSuggestion);
		}

		[SpecialName]
		string ICSharpBinder.get_Name()
		{
			return base.Name;
		}
	}
	internal sealed class CSharpUnaryOperationBinder : UnaryOperationBinder, ICSharpBinder
	{
		private readonly CSharpArgumentInfo[] _argumentInfo;

		private readonly RuntimeBinder _binder;

		private readonly Type _callingContext;

		[ExcludeFromCodeCoverage]
		public string Name => null;

		public BindingFlag BindingFlags => (BindingFlag)0;

		public bool IsBinderThatCanHaveRefReceiver => false;

		private bool IsChecked => _binder.IsChecked;

		public Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return runtimeBinder.BindUnaryOperation(this, arguments, locals);
		}

		public void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments)
		{
			SymbolTable.PopulateSymbolTableWithName(base.Operation.GetCLROperatorName(), null, arguments[0].Type);
		}

		CSharpArgumentInfo ICSharpBinder.GetArgumentInfo(int index)
		{
			return _argumentInfo[index];
		}

		public CSharpUnaryOperationBinder(ExpressionType operation, bool isChecked, Type callingContext, IEnumerable<CSharpArgumentInfo> argumentInfo)
			: base(operation)
		{
			_argumentInfo = BinderHelper.ToArray(argumentInfo);
			_callingContext = callingContext;
			_binder = new RuntimeBinder(callingContext, isChecked);
		}

		public int GetGetBinderEquivalenceHash()
		{
			int h = _callingContext?.GetHashCode() ?? 0;
			h = HashHelpers.Combine(h, (int)base.Operation);
			if (IsChecked)
			{
				h = HashHelpers.Combine(h, 1);
			}
			return BinderHelper.AddArgHashes(h, _argumentInfo);
		}

		public bool IsEquivalentTo(ICSharpBinder other)
		{
			if (!(other is CSharpUnaryOperationBinder cSharpUnaryOperationBinder))
			{
				return false;
			}
			if (base.Operation != cSharpUnaryOperationBinder.Operation || IsChecked != cSharpUnaryOperationBinder.IsChecked || _callingContext != cSharpUnaryOperationBinder._callingContext)
			{
				return false;
			}
			return BinderHelper.CompareArgInfos(_argumentInfo, cSharpUnaryOperationBinder._argumentInfo);
		}

		public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
		{
			BinderHelper.ValidateBindArgument(target, "target");
			return BinderHelper.Bind(this, _binder, new DynamicMetaObject[1] { target }, _argumentInfo, errorSuggestion);
		}
	}
	[Serializable]
	[EditorBrowsable(EditorBrowsableState.Never)]
	internal sealed class DynamicBindingFailedException : Exception
	{
		public DynamicBindingFailedException()
		{
		}

		private DynamicBindingFailedException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	internal sealed class GetMemberValueBinder : GetMemberBinder
	{
		public GetMemberValueBinder(string name, bool ignoreCase)
			: base(name, ignoreCase)
		{
		}

		public override DynamicMetaObject FallbackGetMember(DynamicMetaObject self, DynamicMetaObject onBindingError)
		{
			if (onBindingError == null)
			{
				List<DynamicMetaObject> contributingObjects = new List<DynamicMetaObject> { self };
				return new DynamicMetaObject(Expression.Throw(Expression.Constant(new DynamicBindingFailedException(), typeof(Exception)), typeof(object)), BindingRestrictions.Combine(contributingObjects));
			}
			return onBindingError;
		}
	}
	internal sealed class DynamicMetaObjectProviderDebugView
	{
		[DebuggerDisplay("{value}", Name = "{name, nq}", Type = "{type, nq}")]
		internal class DynamicProperty
		{
			[DebuggerBrowsable(DebuggerBrowsableState.Never)]
			private readonly string name;

			[DebuggerBrowsable(DebuggerBrowsableState.Never)]
			private readonly object value;

			[DebuggerBrowsable(DebuggerBrowsableState.Never)]
			private readonly string type;

			public DynamicProperty(string name, object value)
			{
				this.name = name;
				this.value = value;
				type = ((value == null) ? "<null>" : value.GetType().ToString());
			}
		}

		[Serializable]
		internal class DynamicDebugViewEmptyException : Exception
		{
			public string Empty => System.SR.EmptyDynamicView;

			public DynamicDebugViewEmptyException()
			{
			}

			protected DynamicDebugViewEmptyException(SerializationInfo info, StreamingContext context)
				: base(info, context)
			{
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private IList<KeyValuePair<string, object>> results;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private object obj;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private static readonly ParameterExpression parameter = Expression.Parameter(typeof(object), "debug");

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		internal DynamicProperty[] Items
		{
			get
			{
				if (results == null || results.Count == 0)
				{
					results = QueryDynamicObject(obj);
					if (results == null || results.Count == 0)
					{
						throw new DynamicDebugViewEmptyException();
					}
				}
				DynamicProperty[] array = new DynamicProperty[results.Count];
				for (int i = 0; i < results.Count; i++)
				{
					array[i] = new DynamicProperty(results[i].Key, results[i].Value);
				}
				return array;
			}
		}

		public DynamicMetaObjectProviderDebugView(object arg)
		{
			obj = arg;
		}

		public static object TryEvalBinaryOperators<T1, T2>(T1 arg1, T2 arg2, CSharpArgumentInfoFlags arg1Flags, CSharpArgumentInfoFlags arg2Flags, ExpressionType opKind, Type accessibilityContext)
		{
			CSharpArgumentInfo cSharpArgumentInfo = CSharpArgumentInfo.Create(arg1Flags, null);
			CSharpArgumentInfo cSharpArgumentInfo2 = CSharpArgumentInfo.Create(arg2Flags, null);
			CSharpBinaryOperationBinder binder = new CSharpBinaryOperationBinder(opKind, isChecked: false, CSharpBinaryOperationFlags.None, accessibilityContext, new CSharpArgumentInfo[2] { cSharpArgumentInfo, cSharpArgumentInfo2 });
			CallSite<Func<CallSite, T1, T2, object>> callSite = CallSite<Func<CallSite, T1, T2, object>>.Create(binder);
			return callSite.Target(callSite, arg1, arg2);
		}

		public static object TryEvalUnaryOperators<T>(T obj, ExpressionType oper, Type accessibilityContext)
		{
			if (oper == ExpressionType.IsTrue || oper == ExpressionType.IsFalse)
			{
				CallSite<Func<CallSite, T, bool>> callSite = CallSite<Func<CallSite, T, bool>>.Create(new CSharpUnaryOperationBinder(oper, isChecked: false, accessibilityContext, new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
				return callSite.Target(callSite, obj);
			}
			CallSite<Func<CallSite, T, object>> callSite2 = CallSite<Func<CallSite, T, object>>.Create(new CSharpUnaryOperationBinder(oper, isChecked: false, accessibilityContext, new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));
			return callSite2.Target(callSite2, obj);
		}

		public static K TryEvalCast<T, K>(T obj, Type type, CSharpBinderFlags kind, Type accessibilityContext)
		{
			CallSite<Func<CallSite, T, K>> callSite = CallSite<Func<CallSite, T, K>>.Create(Binder.Convert(kind, type, accessibilityContext));
			return callSite.Target(callSite, obj);
		}

		private static void CreateDelegateSignatureAndArgumentInfos(object[] args, Type[] argTypes, CSharpArgumentInfoFlags[] argFlags, out Type[] delegateSignatureTypes, out CSharpArgumentInfo[] argInfos)
		{
			int num = args.Length;
			delegateSignatureTypes = new Type[num + 2];
			delegateSignatureTypes[0] = typeof(CallSite);
			argInfos = new CSharpArgumentInfo[num];
			for (int i = 0; i < num; i++)
			{
				if (argTypes[i] != null)
				{
					delegateSignatureTypes[i + 1] = argTypes[i];
				}
				else if (args[i] != null)
				{
					delegateSignatureTypes[i + 1] = args[i].GetType();
				}
				else
				{
					delegateSignatureTypes[i + 1] = typeof(object);
				}
				argInfos[i] = CSharpArgumentInfo.Create(argFlags[i], null);
			}
			delegateSignatureTypes[num + 1] = typeof(object);
		}

		private static object CreateDelegateAndInvoke(Type[] delegateSignatureTypes, CallSiteBinder binder, object[] args)
		{
			Type delegateType = Expression.GetDelegateType(delegateSignatureTypes);
			CallSite callSite = CallSite.Create(delegateType, binder);
			Delegate @delegate = (Delegate)callSite.GetType().GetField("Target").GetValue(callSite);
			object[] array = new object[args.Length + 1];
			array[0] = callSite;
			args.CopyTo(array, 1);
			return @delegate.DynamicInvoke(array);
		}

		public static object TryEvalMethodVarArgs(object[] methodArgs, Type[] argTypes, CSharpArgumentInfoFlags[] argFlags, string methodName, Type accessibilityContext, Type[] typeArguments)
		{
			Type[] delegateSignatureTypes = null;
			CSharpArgumentInfo[] argInfos = null;
			CreateDelegateSignatureAndArgumentInfos(methodArgs, argTypes, argFlags, out delegateSignatureTypes, out argInfos);
			return CreateDelegateAndInvoke(binder: (!string.IsNullOrEmpty(methodName)) ? ((CallSiteBinder)new CSharpInvokeMemberBinder(CSharpCallFlags.ResultDiscarded, methodName, accessibilityContext, typeArguments, argInfos)) : ((CallSiteBinder)new CSharpInvokeBinder(CSharpCallFlags.ResultDiscarded, accessibilityContext, argInfos)), delegateSignatureTypes: delegateSignatureTypes, args: methodArgs);
		}

		public static object TryGetMemberValue<T>(T obj, string propName, Type accessibilityContext, bool isResultIndexed)
		{
			CSharpGetMemberBinder binder = new CSharpGetMemberBinder(propName, isResultIndexed, accessibilityContext, new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
			CallSite<Func<CallSite, T, object>> callSite = CallSite<Func<CallSite, T, object>>.Create(binder);
			return callSite.Target(callSite, obj);
		}

		public static object TryGetMemberValueVarArgs(object[] propArgs, Type[] argTypes, CSharpArgumentInfoFlags[] argFlags, Type accessibilityContext)
		{
			Type[] delegateSignatureTypes = null;
			CSharpArgumentInfo[] argInfos = null;
			CreateDelegateSignatureAndArgumentInfos(propArgs, argTypes, argFlags, out delegateSignatureTypes, out argInfos);
			CallSiteBinder binder = new CSharpGetIndexBinder(accessibilityContext, argInfos);
			return CreateDelegateAndInvoke(delegateSignatureTypes, binder, propArgs);
		}

		public static object TrySetMemberValue<TObject, TValue>(TObject obj, string propName, TValue value, CSharpArgumentInfoFlags valueFlags, Type accessibilityContext)
		{
			CSharpArgumentInfo cSharpArgumentInfo = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
			CSharpArgumentInfo cSharpArgumentInfo2 = CSharpArgumentInfo.Create(valueFlags, null);
			CSharpSetMemberBinder binder = new CSharpSetMemberBinder(propName, isCompoundAssignment: false, isChecked: false, accessibilityContext, new CSharpArgumentInfo[2] { cSharpArgumentInfo, cSharpArgumentInfo2 });
			CallSite<Func<CallSite, TObject, TValue, object>> callSite = CallSite<Func<CallSite, TObject, TValue, object>>.Create(binder);
			return callSite.Target(callSite, obj, value);
		}

		public static object TrySetMemberValueVarArgs(object[] propArgs, Type[] argTypes, CSharpArgumentInfoFlags[] argFlags, Type accessibilityContext)
		{
			Type[] delegateSignatureTypes = null;
			CSharpArgumentInfo[] argInfos = null;
			CreateDelegateSignatureAndArgumentInfos(propArgs, argTypes, argFlags, out delegateSignatureTypes, out argInfos);
			CallSiteBinder binder = new CSharpSetIndexBinder(isCompoundAssignment: false, isChecked: false, accessibilityContext, argInfos);
			return CreateDelegateAndInvoke(delegateSignatureTypes, binder, propArgs);
		}

		internal static object TryGetMemberValue(object obj, string name, bool ignoreException)
		{
			bool ignoreCase = false;
			object obj2 = null;
			CallSite<Func<CallSite, object, object>> callSite = CallSite<Func<CallSite, object, object>>.Create(new GetMemberValueBinder(name, ignoreCase));
			try
			{
				return callSite.Target(callSite, obj);
			}
			catch (DynamicBindingFailedException ex)
			{
				if (ignoreException)
				{
					return null;
				}
				throw ex;
			}
			catch (MissingMemberException ex2)
			{
				if (ignoreException)
				{
					return System.SR.GetValueonWriteOnlyProperty;
				}
				throw ex2;
			}
		}

		private static IList<KeyValuePair<string, object>> QueryDynamicObject(object obj)
		{
			if (obj is IDynamicMetaObjectProvider dynamicMetaObjectProvider)
			{
				DynamicMetaObject metaObject = dynamicMetaObjectProvider.GetMetaObject(parameter);
				List<string> list = new List<string>(metaObject.GetDynamicMemberNames());
				list.Sort();
				if (list != null)
				{
					List<KeyValuePair<string, object>> list2 = new List<KeyValuePair<string, object>>();
					{
						foreach (string item in list)
						{
							object value;
							if ((value = TryGetMemberValue(obj, item, ignoreException: true)) != null)
							{
								list2.Add(new KeyValuePair<string, object>(item, value));
							}
						}
						return list2;
					}
				}
			}
			return new KeyValuePair<string, object>[0];
		}
	}
	internal static class Error
	{
		internal static Exception InternalCompilerError()
		{
			return new RuntimeBinderInternalCompilerException(System.SR.InternalCompilerError);
		}

		internal static Exception BindPropertyFailedMethodGroup(object p0)
		{
			return new RuntimeBinderException(System.SR.Format(System.SR.BindPropertyFailedMethodGroup, p0));
		}

		internal static Exception BindPropertyFailedEvent(object p0)
		{
			return new RuntimeBinderException(System.SR.Format(System.SR.BindPropertyFailedEvent, p0));
		}

		internal static Exception BindInvokeFailedNonDelegate()
		{
			return new RuntimeBinderException(System.SR.BindInvokeFailedNonDelegate);
		}

		internal static Exception BindStaticRequiresType(string paramName)
		{
			return new ArgumentException(System.SR.TypeArgumentRequiredForStaticCall, paramName);
		}

		internal static Exception NullReferenceOnMemberException()
		{
			return new RuntimeBinderException(System.SR.NullReferenceOnMemberException);
		}

		internal static Exception BindCallToConditionalMethod(object p0)
		{
			return new RuntimeBinderException(System.SR.Format(System.SR.BindCallToConditionalMethod, p0));
		}

		internal static Exception BindToVoidMethodButExpectResult()
		{
			return new RuntimeBinderException(System.SR.BindToVoidMethodButExpectResult);
		}

		internal static Exception ArgumentNull(string paramName)
		{
			return new ArgumentNullException(paramName);
		}

		internal static Exception DynamicArgumentNeedsValue(string paramName)
		{
			return new ArgumentException(System.SR.DynamicArgumentNeedsValue, paramName);
		}
	}
	internal sealed class ExpressionTreeCallRewriter : ExprVisitorBase
	{
		private sealed class ExpressionExpr : Expr
		{
			public readonly Expression Expression;

			public ExpressionExpr(Expression e)
				: base(ExpressionKind.NoOp)
			{
				Expression = e;
			}
		}

		private readonly Dictionary<ExprCall, Expression> _DictionaryOfParameters;

		private readonly Expression[] _ListOfParameters;

		private int _currentParameterIndex;

		private ExpressionTreeCallRewriter(Expression[] listOfParameters)
		{
			_DictionaryOfParameters = new Dictionary<ExprCall, Expression>();
			_ListOfParameters = listOfParameters;
		}

		public static Expression Rewrite(ExprBinOp binOp, Expression[] listOfParameters)
		{
			ExpressionTreeCallRewriter expressionTreeCallRewriter = new ExpressionTreeCallRewriter(listOfParameters);
			expressionTreeCallRewriter.Visit(binOp.OptionalLeftChild);
			ExprCall pExpr = (ExprCall)binOp.OptionalRightChild;
			ExpressionExpr expressionExpr = expressionTreeCallRewriter.Visit(pExpr) as ExpressionExpr;
			return expressionExpr.Expression;
		}

		protected override Expr VisitSAVE(ExprBinOp pExpr)
		{
			ExprCall key = (ExprCall)pExpr.OptionalLeftChild;
			Expression value = _ListOfParameters[_currentParameterIndex++];
			_DictionaryOfParameters.Add(key, value);
			return null;
		}

		protected override Expr VisitCALL(ExprCall pExpr)
		{
			if (pExpr.PredefinedMethod == PREDEFMETH.PM_COUNT)
			{
				return pExpr;
			}
			Expression e;
			switch (pExpr.PredefinedMethod)
			{
			case PREDEFMETH.PM_EXPRESSION_LAMBDA:
				return GenerateLambda(pExpr);
			case PREDEFMETH.PM_EXPRESSION_CALL:
				e = GenerateCall(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX:
			case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2:
				e = GenerateArrayIndex(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_CONVERT:
			case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED:
			case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED:
				e = GenerateConvert(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_PROPERTY:
				e = GenerateProperty(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_FIELD:
				e = GenerateField(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_INVOKE:
				e = GenerateInvoke(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_NEW:
				e = GenerateNew(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_ADD:
			case PREDEFMETH.PM_EXPRESSION_ADDCHECKED:
			case PREDEFMETH.PM_EXPRESSION_AND:
			case PREDEFMETH.PM_EXPRESSION_ANDALSO:
			case PREDEFMETH.PM_EXPRESSION_DIVIDE:
			case PREDEFMETH.PM_EXPRESSION_EQUAL:
			case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR:
			case PREDEFMETH.PM_EXPRESSION_GREATERTHAN:
			case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL:
			case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT:
			case PREDEFMETH.PM_EXPRESSION_LESSTHAN:
			case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL:
			case PREDEFMETH.PM_EXPRESSION_MODULO:
			case PREDEFMETH.PM_EXPRESSION_MULTIPLY:
			case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED:
			case PREDEFMETH.PM_EXPRESSION_NOTEQUAL:
			case PREDEFMETH.PM_EXPRESSION_OR:
			case PREDEFMETH.PM_EXPRESSION_ORELSE:
			case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT:
			case PREDEFMETH.PM_EXPRESSION_SUBTRACT:
			case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED:
				e = GenerateBinaryOperator(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED:
				e = GenerateUserDefinedBinaryOperator(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_NEGATE:
			case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED:
			case PREDEFMETH.PM_EXPRESSION_NOT:
				e = GenerateUnaryOperator(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED:
				e = GenerateUserDefinedUnaryOperator(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE:
				e = GenerateConstantType(pExpr);
				break;
			case PREDEFMETH.PM_EXPRESSION_ASSIGN:
				e = GenerateAssignment(pExpr);
				break;
			default:
				throw Error.InternalCompilerError();
			}
			return new ExpressionExpr(e);
		}

		protected override Expr VisitWRAP(ExprWrap pExpr)
		{
			return new ExpressionExpr(GetExpression(pExpr));
		}

		private Expr GenerateLambda(ExprCall pExpr)
		{
			return Visit(((ExprList)pExpr.OptionalArguments).OptionalElement);
		}

		private Expression GenerateCall(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			ExprMethodInfo exprMethodInfo;
			ExprArrayInit arrinit;
			if (exprList.OptionalNextListNode is ExprList exprList2)
			{
				exprMethodInfo = (ExprMethodInfo)exprList2.OptionalElement;
				arrinit = (ExprArrayInit)exprList2.OptionalNextListNode;
			}
			else
			{
				exprMethodInfo = (ExprMethodInfo)exprList.OptionalNextListNode;
				arrinit = null;
			}
			Expression instance = null;
			MethodInfo methodInfo = exprMethodInfo.MethodInfo;
			Expression[] argumentsFromArrayInit = GetArgumentsFromArrayInit(arrinit);
			if (methodInfo == null)
			{
				throw Error.InternalCompilerError();
			}
			if (!methodInfo.IsStatic)
			{
				instance = GetExpression(((ExprList)pExpr.OptionalArguments).OptionalElement);
			}
			return Expression.Call(instance, methodInfo, argumentsFromArrayInit);
		}

		private Expression GenerateArrayIndex(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			Expression expression = GetExpression(exprList.OptionalElement);
			Expression[] indexes = ((pExpr.PredefinedMethod != PREDEFMETH.PM_EXPRESSION_ARRAYINDEX) ? GetArgumentsFromArrayInit((ExprArrayInit)exprList.OptionalNextListNode) : new Expression[1] { GetExpression(exprList.OptionalNextListNode) });
			return Expression.ArrayAccess(expression, indexes);
		}

		private Expression GenerateConvert(ExprCall pExpr)
		{
			PREDEFMETH predefinedMethod = pExpr.PredefinedMethod;
			Expression expression;
			Type associatedSystemType;
			if (predefinedMethod == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED || predefinedMethod == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED)
			{
				ExprList exprList = (ExprList)pExpr.OptionalArguments;
				ExprList exprList2 = (ExprList)exprList.OptionalNextListNode;
				expression = GetExpression(exprList.OptionalElement);
				associatedSystemType = ((ExprTypeOf)exprList2.OptionalElement).SourceType.AssociatedSystemType;
				if (expression.Type.MakeByRefType() == associatedSystemType)
				{
					return expression;
				}
				MethodInfo methodInfo = ((ExprMethodInfo)exprList2.OptionalNextListNode).MethodInfo;
				if (predefinedMethod == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED)
				{
					return Expression.Convert(expression, associatedSystemType, methodInfo);
				}
				return Expression.ConvertChecked(expression, associatedSystemType, methodInfo);
			}
			ExprList exprList3 = (ExprList)pExpr.OptionalArguments;
			expression = GetExpression(exprList3.OptionalElement);
			associatedSystemType = ((ExprTypeOf)exprList3.OptionalNextListNode).SourceType.AssociatedSystemType;
			if (expression.Type.MakeByRefType() == associatedSystemType)
			{
				return expression;
			}
			if ((pExpr.Flags & EXPRFLAG.EXF_USERCALLABLE) != 0)
			{
				return Expression.Unbox(expression, associatedSystemType);
			}
			if (predefinedMethod == PREDEFMETH.PM_EXPRESSION_CONVERT)
			{
				return Expression.Convert(expression, associatedSystemType);
			}
			return Expression.ConvertChecked(expression, associatedSystemType);
		}

		private Expression GenerateProperty(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			Expr optionalElement = exprList.OptionalElement;
			Expr optionalNextListNode = exprList.OptionalNextListNode;
			ExprPropertyInfo exprPropertyInfo;
			ExprArrayInit exprArrayInit;
			if (optionalNextListNode is ExprList exprList2)
			{
				exprPropertyInfo = exprList2.OptionalElement as ExprPropertyInfo;
				exprArrayInit = exprList2.OptionalNextListNode as ExprArrayInit;
			}
			else
			{
				exprPropertyInfo = optionalNextListNode as ExprPropertyInfo;
				exprArrayInit = null;
			}
			PropertyInfo propertyInfo = exprPropertyInfo.PropertyInfo;
			if (propertyInfo == null)
			{
				throw Error.InternalCompilerError();
			}
			if (exprArrayInit == null)
			{
				return Expression.Property(GetExpression(optionalElement), propertyInfo);
			}
			return Expression.Property(GetExpression(optionalElement), propertyInfo, GetArgumentsFromArrayInit(exprArrayInit));
		}

		private Expression GenerateField(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			ExprFieldInfo exprFieldInfo = (ExprFieldInfo)exprList.OptionalNextListNode;
			Type type = exprFieldInfo.FieldType.AssociatedSystemType;
			FieldInfo fieldInfo = exprFieldInfo.Field.AssociatedFieldInfo;
			if (!type.IsGenericType && !type.IsNested)
			{
				type = fieldInfo.DeclaringType;
			}
			if (type.IsGenericType)
			{
				fieldInfo = type.GetField(fieldInfo.Name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			}
			return Expression.Field(GetExpression(exprList.OptionalElement), fieldInfo);
		}

		private Expression GenerateInvoke(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			return Expression.Invoke(GetExpression(exprList.OptionalElement), GetArgumentsFromArrayInit(exprList.OptionalNextListNode as ExprArrayInit));
		}

		private Expression GenerateNew(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			ConstructorInfo constructorInfo = ((ExprMethodInfo)exprList.OptionalElement).ConstructorInfo;
			Expression[] argumentsFromArrayInit = GetArgumentsFromArrayInit(exprList.OptionalNextListNode as ExprArrayInit);
			return Expression.New(constructorInfo, argumentsFromArrayInit);
		}

		private static Expression GenerateConstantType(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			return Expression.Constant(exprList.OptionalElement.Object, ((ExprTypeOf)exprList.OptionalNextListNode).SourceType.AssociatedSystemType);
		}

		private Expression GenerateAssignment(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			return Expression.Assign(GetExpression(exprList.OptionalElement), GetExpression(exprList.OptionalNextListNode));
		}

		private Expression GenerateBinaryOperator(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			Expression expression = GetExpression(exprList.OptionalElement);
			Expression expression2 = GetExpression(exprList.OptionalNextListNode);
			return pExpr.PredefinedMethod switch
			{
				PREDEFMETH.PM_EXPRESSION_ADD => Expression.Add(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_AND => Expression.And(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_DIVIDE => Expression.Divide(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_EQUAL => Expression.Equal(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR => Expression.ExclusiveOr(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_GREATERTHAN => Expression.GreaterThan(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL => Expression.GreaterThanOrEqual(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_LEFTSHIFT => Expression.LeftShift(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_LESSTHAN => Expression.LessThan(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL => Expression.LessThanOrEqual(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_MODULO => Expression.Modulo(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_MULTIPLY => Expression.Multiply(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_NOTEQUAL => Expression.NotEqual(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_OR => Expression.Or(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT => Expression.RightShift(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_SUBTRACT => Expression.Subtract(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_ORELSE => Expression.OrElse(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_ANDALSO => Expression.AndAlso(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_ADDCHECKED => Expression.AddChecked(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED => Expression.MultiplyChecked(expression, expression2), 
				PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED => Expression.SubtractChecked(expression, expression2), 
				_ => throw Error.InternalCompilerError(), 
			};
		}

		private Expression GenerateUserDefinedBinaryOperator(ExprCall pExpr)
		{
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			Expression expression = GetExpression(exprList.OptionalElement);
			Expression expression2 = GetExpression(((ExprList)exprList.OptionalNextListNode).OptionalElement);
			exprList = (ExprList)exprList.OptionalNextListNode;
			bool liftToNull = false;
			MethodInfo methodInfo;
			if (exprList.OptionalNextListNode is ExprList exprList2)
			{
				ExprConstant exprConstant = (ExprConstant)exprList2.OptionalElement;
				liftToNull = exprConstant.Val.Int32Val == 1;
				methodInfo = ((ExprMethodInfo)exprList2.OptionalNextListNode).MethodInfo;
			}
			else
			{
				methodInfo = ((ExprMethodInfo)exprList.OptionalNextListNode).MethodInfo;
			}
			return pExpr.PredefinedMethod switch
			{
				PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED => Expression.Add(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED => Expression.And(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED => Expression.Divide(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED => Expression.Equal(expression, expression2, liftToNull, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED => Expression.ExclusiveOr(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED => Expression.GreaterThan(expression, expression2, liftToNull, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED => Expression.GreaterThanOrEqual(expression, expression2, liftToNull, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED => Expression.LeftShift(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED => Expression.LessThan(expression, expression2, liftToNull, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED => Expression.LessThanOrEqual(expression, expression2, liftToNull, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED => Expression.Modulo(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED => Expression.Multiply(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED => Expression.NotEqual(expression, expression2, liftToNull, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED => Expression.Or(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED => Expression.RightShift(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED => Expression.Subtract(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED => Expression.OrElse(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED => Expression.AndAlso(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED => Expression.AddChecked(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED => Expression.MultiplyChecked(expression, expression2, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED => Expression.SubtractChecked(expression, expression2, methodInfo), 
				_ => throw Error.InternalCompilerError(), 
			};
		}

		private Expression GenerateUnaryOperator(ExprCall pExpr)
		{
			PREDEFMETH predefinedMethod = pExpr.PredefinedMethod;
			Expression expression = GetExpression(pExpr.OptionalArguments);
			return predefinedMethod switch
			{
				PREDEFMETH.PM_EXPRESSION_NOT => Expression.Not(expression), 
				PREDEFMETH.PM_EXPRESSION_NEGATE => Expression.Negate(expression), 
				PREDEFMETH.PM_EXPRESSION_NEGATECHECKED => Expression.NegateChecked(expression), 
				_ => throw Error.InternalCompilerError(), 
			};
		}

		private Expression GenerateUserDefinedUnaryOperator(ExprCall pExpr)
		{
			PREDEFMETH predefinedMethod = pExpr.PredefinedMethod;
			ExprList exprList = (ExprList)pExpr.OptionalArguments;
			Expression expression = GetExpression(exprList.OptionalElement);
			MethodInfo methodInfo = ((ExprMethodInfo)exprList.OptionalNextListNode).MethodInfo;
			return predefinedMethod switch
			{
				PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED => Expression.Not(expression, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED => Expression.Negate(expression, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED => Expression.UnaryPlus(expression, methodInfo), 
				PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED => Expression.NegateChecked(expression, methodInfo), 
				_ => throw Error.InternalCompilerError(), 
			};
		}

		private Expression GetExpression(Expr pExpr)
		{
			if (pExpr is ExprWrap exprWrap)
			{
				return _DictionaryOfParameters[(ExprCall)exprWrap.OptionalExpression];
			}
			if (pExpr is ExprConstant)
			{
				return null;
			}
			ExprCall exprCall = (ExprCall)pExpr;
			switch (exprCall.PredefinedMethod)
			{
			case PREDEFMETH.PM_EXPRESSION_CALL:
				return GenerateCall(exprCall);
			case PREDEFMETH.PM_EXPRESSION_CONVERT:
			case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED:
			case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED:
				return GenerateConvert(exprCall);
			case PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT:
			{
				ExprList exprList = (ExprList)exprCall.OptionalArguments;
				return Expression.NewArrayInit(((ExprTypeOf)exprList.OptionalElement).SourceType.AssociatedSystemType, GetArgumentsFromArrayInit((ExprArrayInit)exprList.OptionalNextListNode));
			}
			case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX:
			case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2:
				return GenerateArrayIndex(exprCall);
			case PREDEFMETH.PM_EXPRESSION_NEW:
				return GenerateNew(exprCall);
			case PREDEFMETH.PM_EXPRESSION_PROPERTY:
				return GenerateProperty(exprCall);
			case PREDEFMETH.PM_EXPRESSION_FIELD:
				return GenerateField(exprCall);
			case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE:
				return GenerateConstantType(exprCall);
			case PREDEFMETH.PM_EXPRESSION_ASSIGN:
				return GenerateAssignment(exprCall);
			case PREDEFMETH.PM_EXPRESSION_ADD:
			case PREDEFMETH.PM_EXPRESSION_ADDCHECKED:
			case PREDEFMETH.PM_EXPRESSION_AND:
			case PREDEFMETH.PM_EXPRESSION_ANDALSO:
			case PREDEFMETH.PM_EXPRESSION_DIVIDE:
			case PREDEFMETH.PM_EXPRESSION_EQUAL:
			case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR:
			case PREDEFMETH.PM_EXPRESSION_GREATERTHAN:
			case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL:
			case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT:
			case PREDEFMETH.PM_EXPRESSION_LESSTHAN:
			case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL:
			case PREDEFMETH.PM_EXPRESSION_MODULO:
			case PREDEFMETH.PM_EXPRESSION_MULTIPLY:
			case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED:
			case PREDEFMETH.PM_EXPRESSION_NOTEQUAL:
			case PREDEFMETH.PM_EXPRESSION_OR:
			case PREDEFMETH.PM_EXPRESSION_ORELSE:
			case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT:
			case PREDEFMETH.PM_EXPRESSION_SUBTRACT:
			case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED:
				return GenerateBinaryOperator(exprCall);
			case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED:
				return GenerateUserDefinedBinaryOperator(exprCall);
			case PREDEFMETH.PM_EXPRESSION_NEGATE:
			case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED:
			case PREDEFMETH.PM_EXPRESSION_NOT:
				return GenerateUnaryOperator(exprCall);
			case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED:
			case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED:
				return GenerateUserDefinedUnaryOperator(exprCall);
			default:
				throw Error.InternalCompilerError();
			}
		}

		private Expression[] GetArgumentsFromArrayInit(ExprArrayInit arrinit)
		{
			List<Expression> list = new List<Expression>();
			if (arrinit != null)
			{
				Expr expr = arrinit.OptionalArguments;
				while (expr != null)
				{
					Expr pExpr;
					if (expr is ExprList exprList)
					{
						pExpr = exprList.OptionalElement;
						expr = exprList.OptionalNextListNode;
					}
					else
					{
						pExpr = expr;
						expr = null;
					}
					list.Add(GetExpression(pExpr));
				}
			}
			return list.ToArray();
		}
	}
	internal interface ICSharpBinder
	{
		bool IsBinderThatCanHaveRefReceiver { get; }

		BindingFlag BindingFlags { get; }

		string Name { get; }

		Type ReturnType { get; }

		CSharpArgumentInfo GetArgumentInfo(int index);

		void PopulateSymbolTableWithName(Type callingType, ArgumentObject[] arguments);

		Expr DispatchPayload(RuntimeBinder runtimeBinder, ArgumentObject[] arguments, LocalVariableSymbol[] locals);

		int GetGetBinderEquivalenceHash();

		bool IsEquivalentTo(ICSharpBinder other);
	}
	internal interface ICSharpInvokeOrInvokeMemberBinder : ICSharpBinder
	{
		bool StaticCall { get; }

		bool ResultDiscarded { get; }

		CSharpCallFlags Flags { get; }

		Type[] TypeArguments { get; }
	}
	internal readonly struct RuntimeBinder
	{
		private static readonly object s_bindLock = new object();

		private readonly ExpressionBinder _binder;

		internal bool IsChecked => _binder.Context.Checked;

		public RuntimeBinder(Type contextType, bool isChecked = false)
		{
			AggregateSymbol context;
			if (contextType != null)
			{
				lock (s_bindLock)
				{
					context = ((AggregateType)SymbolTable.GetCTypeFromType(contextType)).OwningAggregate;
				}
			}
			else
			{
				context = null;
			}
			_binder = new ExpressionBinder(new BindingContext(context, isChecked));
		}

		public Expression Bind(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding)
		{
			lock (s_bindLock)
			{
				return BindCore(payload, parameters, args, out deferredBinding);
			}
		}

		private Expression BindCore(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding)
		{
			ArgumentObject[] array = CreateArgumentArray(payload, parameters, args);
			payload.PopulateSymbolTableWithName(array[0].Type, array);
			AddConversionsForArguments(array);
			Scope pScope = SymFactory.CreateScope();
			LocalVariableSymbol[] locals = PopulateLocalScope(payload, pScope, array, parameters);
			if (DeferBinding(payload, array, args, locals, out deferredBinding))
			{
				return null;
			}
			Expr pResult = payload.DispatchPayload(this, array, locals);
			return CreateExpressionTreeFromResult(parameters, pScope, pResult);
		}

		private bool DeferBinding(ICSharpBinder payload, ArgumentObject[] arguments, DynamicMetaObject[] args, LocalVariableSymbol[] locals, out DynamicMetaObject deferredBinding)
		{
			if (payload is CSharpInvokeMemberBinder cSharpInvokeMemberBinder)
			{
				Type[] typeArguments = cSharpInvokeMemberBinder.TypeArguments;
				int arity = ((typeArguments != null) ? typeArguments.Length : 0);
				MemberLookup mem = new MemberLookup();
				Expr callingObject = CreateCallingObjectForCall(cSharpInvokeMemberBinder, arguments, locals);
				SymWithType symWithType = SymbolTable.LookupMember(cSharpInvokeMemberBinder.Name, callingObject, _binder.Context.ContextForMemberLookup, arity, mem, (cSharpInvokeMemberBinder.Flags & CSharpCallFlags.EventHookup) != 0, requireInvocable: true);
				if (symWithType != null && symWithType.Sym.getKind() != SYMKIND.SK_MethodSymbol)
				{
					CSharpGetMemberBinder cSharpGetMemberBinder = new CSharpGetMemberBinder(cSharpInvokeMemberBinder.Name, resultIndexed: false, cSharpInvokeMemberBinder.CallingContext, new CSharpArgumentInfo[1] { cSharpInvokeMemberBinder.GetArgumentInfo(0) }).TryGetExisting();
					CSharpArgumentInfo[] array = cSharpInvokeMemberBinder.ArgumentInfoArray();
					array[0] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
					CSharpInvokeBinder cSharpInvokeBinder = new CSharpInvokeBinder(cSharpInvokeMemberBinder.Flags, cSharpInvokeMemberBinder.CallingContext, array).TryGetExisting();
					DynamicMetaObject[] array2 = new DynamicMetaObject[args.Length - 1];
					Array.Copy(args, 1, array2, 0, args.Length - 1);
					deferredBinding = cSharpInvokeBinder.Defer(cSharpGetMemberBinder.Defer(args[0]), array2);
					return true;
				}
			}
			deferredBinding = null;
			return false;
		}

		private static Expression CreateExpressionTreeFromResult(Expression[] parameters, Scope pScope, Expr pResult)
		{
			ExprBoundLambda expr = GenerateBoundLambda(pScope, pResult);
			ExprBinOp binOp = ExpressionTreeRewriter.Rewrite(expr);
			return ExpressionTreeCallRewriter.Rewrite(binOp, parameters);
		}

		private Type GetArgumentType(ICSharpBinder p, CSharpArgumentInfo argInfo, Expression param, DynamicMetaObject arg, int index)
		{
			Type type = (argInfo.UseCompileTimeType ? param.Type : arg.LimitType);
			if (argInfo.IsByRefOrOut)
			{
				if (index != 0 || !p.IsBinderThatCanHaveRefReceiver)
				{
					type = type.MakeByRefType();
				}
			}
			else if (!argInfo.UseCompileTimeType)
			{
				CType cTypeFromType = SymbolTable.GetCTypeFromType(type);
				CType bestAccessibleType = TypeManager.GetBestAccessibleType(_binder.Context.ContextForMemberLookup, cTypeFromType);
				type = bestAccessibleType.AssociatedSystemType;
			}
			return type;
		}

		private ArgumentObject[] CreateArgumentArray(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args)
		{
			ArgumentObject[] array = new ArgumentObject[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				CSharpArgumentInfo argumentInfo = payload.GetArgumentInfo(i);
				array[i] = new ArgumentObject(args[i].Value, argumentInfo, GetArgumentType(payload, argumentInfo, parameters[i], args[i], i));
			}
			return array;
		}

		internal static void PopulateSymbolTableWithPayloadInformation(ICSharpInvokeOrInvokeMemberBinder callOrInvoke, Type callingType, ArgumentObject[] arguments)
		{
			Type type;
			if (callOrInvoke.StaticCall)
			{
				type = arguments[0].Value as Type;
				if (type == null)
				{
					throw Error.BindStaticRequiresType(arguments[0].Info.Name);
				}
			}
			else
			{
				type = callingType;
			}
			SymbolTable.PopulateSymbolTableWithName(callOrInvoke.Name, callOrInvoke.TypeArguments, type);
			if (callOrInvoke.Name.StartsWith("set_", StringComparison.Ordinal) || callOrInvoke.Name.StartsWith("get_", StringComparison.Ordinal))
			{
				SymbolTable.PopulateSymbolTableWithName(callOrInvoke.Name.Substring(4), callOrInvoke.TypeArguments, type);
			}
		}

		private static void AddConversionsForArguments(ArgumentObject[] arguments)
		{
			for (int i = 0; i < arguments.Length; i++)
			{
				ArgumentObject argumentObject = arguments[i];
				SymbolTable.AddConversionsForType(argumentObject.Type);
			}
		}

		internal ExprWithArgs DispatchPayload(ICSharpInvokeOrInvokeMemberBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals)
		{
			return BindCall(payload, CreateCallingObjectForCall(payload, arguments, locals), arguments, locals);
		}

		private static LocalVariableSymbol[] PopulateLocalScope(ICSharpBinder payload, Scope pScope, ArgumentObject[] arguments, Expression[] parameterExpressions)
		{
			LocalVariableSymbol[] array = new LocalVariableSymbol[parameterExpressions.Length];
			for (int i = 0; i < parameterExpressions.Length; i++)
			{
				Expression expression = parameterExpressions[i];
				CType cType = SymbolTable.GetCTypeFromType(expression.Type);
				if ((i != 0 || !payload.IsBinderThatCanHaveRefReceiver) && expression is ParameterExpression parameterExpression && parameterExpression.IsByRef)
				{
					CSharpArgumentInfo info = arguments[i].Info;
					if (info.IsByRefOrOut)
					{
						cType = TypeManager.GetParameterModifier(cType, info.IsOut);
					}
				}
				LocalVariableSymbol localVariableSymbol = SymFactory.CreateLocalVar(NameManager.Add("p" + i), pScope, cType);
				array[i] = localVariableSymbol;
			}
			return array;
		}

		private static ExprBoundLambda GenerateBoundLambda(Scope pScope, Expr call)
		{
			AggregateType predefindType = SymbolLoader.GetPredefindType(PredefinedType.PT_FUNC);
			return ExprFactory.CreateAnonymousMethod(predefindType, pScope, call);
		}

		private Expr CreateLocal(Type type, bool isOut, LocalVariableSymbol local)
		{
			CType dest = ((!isOut) ? SymbolTable.GetCTypeFromType(type) : TypeManager.GetParameterModifier(SymbolTable.GetCTypeFromType(type.GetElementType()), isOut: true));
			ExprLocal expr = ExprFactory.CreateLocal(local);
			Expr expr2 = _binder.tryConvert(expr, dest) ?? _binder.mustCast(expr, dest);
			expr2.Flags |= EXPRFLAG.EXF_LVALUE;
			return expr2;
		}

		internal Expr CreateArgumentListEXPR(ArgumentObject[] arguments, LocalVariableSymbol[] locals, int startIndex, int endIndex)
		{
			Expr first = null;
			Expr last = null;
			if (arguments != null)
			{
				for (int i = startIndex; i < endIndex; i++)
				{
					ArgumentObject argument = arguments[i];
					Expr expr = CreateArgumentEXPR(argument, locals[i]);
					if (first == null)
					{
						first = expr;
						last = first;
					}
					else
					{
						ExprFactory.AppendItemToList(expr, ref first, ref last);
					}
				}
			}
			return first;
		}

		private Expr CreateArgumentEXPR(ArgumentObject argument, LocalVariableSymbol local)
		{
			Expr expr = (argument.Info.LiteralConstant ? ((argument.Value != null) ? ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), ConstVal.Get(argument.Value)) : ((!argument.Info.UseCompileTimeType) ? ExprFactory.CreateNull() : ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), default(ConstVal)))) : ((argument.Info.UseCompileTimeType || argument.Value != null) ? CreateLocal(argument.Type, argument.Info.IsOut, local) : ExprFactory.CreateNull()));
			if (argument.Info.NamedArgument)
			{
				expr = ExprFactory.CreateNamedArgumentSpecification(NameManager.Add(argument.Info.Name), expr);
			}
			if (!argument.Info.UseCompileTimeType && argument.Value != null)
			{
				expr.RuntimeObject = argument.Value;

TextureSwapper.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using ExitGames.Client.Photon.StructWrapping;
using FFMpegCore;
using FFMpegCore.Enums;
using HarmonyLib;
using ImageMagick;
using ImageMagick.Formats;
using Microsoft.CodeAnalysis;
using NAudio.Wave;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Photon.Pun;
using REPOLib.Modules;
using Sirenix.Utilities;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Video;
using io.wispforest.format.binary;
using io.wispforest.impl;
using io.wispforest.textureswapper.api;
using io.wispforest.textureswapper.api.components;
using io.wispforest.textureswapper.api.components.holders;
using io.wispforest.textureswapper.api.query;
using io.wispforest.textureswapper.api.query.impl;
using io.wispforest.textureswapper.endec.format.newtonsoft;
using io.wispforest.textureswapper.patches;
using io.wispforest.textureswapper.utils;
using io.wispforest.util;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyCompany("TextureSwapper")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.1.7.0")]
[assembly: AssemblyInformationalVersion("1.1.7+8772568bd44899b49007b0ca0d27c9fe69c9888b")]
[assembly: AssemblyProduct("Texture Swapper")]
[assembly: AssemblyTitle("TextureSwapper")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.7.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 io.wispforest.textureswapper
{
	public class ConfigAccess
	{
		private readonly ConfigEntry<bool> DEBUG_LOGGING;

		private readonly ConfigEntry<bool> CLIENT_SIDE_ONLY;

		private readonly ConfigEntry<string> PICTURE_TEXTURE_TARGETS;

		private readonly ConfigEntry<bool> RESTRICTED_QUERIES;

		private readonly ConfigEntry<bool> ONLY_FIRST_ANIMATION_FRAME;

		private readonly ConfigEntry<bool> ALLOW_TRANSCODING_VIDEOS;

		private readonly ConfigEntry<bool> PRIORITIZE_NEW_PICTURES;

		private readonly ConfigEntry<float> MIN_AUDIO_DISTANCE;

		private readonly ConfigEntry<float> MAX_AUDIO_DISTANCE;

		private readonly ConfigEntry<string> DIRECTORY_LOCATION;

		private readonly ConfigEntry<string> STATIC_WEB_MEDIA;

		private readonly ConfigEntry<string> BLACKLIST_TAGS;

		private readonly ConfigEntry<bool> ENABLE_GLOBAL_BLACKLIST;

		private readonly ConfigEntry<string> ALLOWED_TAGS;

		private readonly ConfigFile configFile;

		private static readonly string DEFAULT_TEXTURE_TARGETS = GeneralExtensions.Join<string>((IEnumerable<string>)new List<string>(new <>z__ReadOnlyArray<string>(new string[3] { "\"^(?=.*painting.*)((?!.*frame.*)).*$\"mi", "\"^(magazine\\d*) \\(Instance\\)$\"mi", "\"(magazine stack)\"mi" })), (Func<string, string>)null, ",");

		public List<string> pictureTextureTargets { get; private set; }

		public List<string> directoryLocations { get; private set; }

		public List<string> staticWebMedia { get; private set; }

		public List<string> blackListTags { get; private set; }

		public List<string> whiteListTags { get; private set; }

		public ConfigAccess(ConfigFile configFile)
		{
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Expected O, but got Unknown
			ConfigFile configFile2 = configFile;
			base..ctor();
			ConfigAccess configAccess = this;
			this.configFile = configFile2;
			configFile2.Section("Common").Bind(out CLIENT_SIDE_ONLY, "ClientSide", defaultValue: false, "Enables the ability to use a client based random value that pseudo syncs if the photos are the same on all clients").Bind(out DEBUG_LOGGING, "DebugLogging", defaultValue: false, "Enables some useful debug logging to check and or validate if things are going properly")
				.Bind(out PICTURE_TEXTURE_TARGETS, "TextureTargets", DEFAULT_TEXTURE_TARGETS, "All texture targets to replace with custom images, Seperated by commas (,) without any spaces")
				.Bind(out RESTRICTED_QUERIES, "RestrictiveQueries", defaultValue: true, "Will prevent restrict the queries allow to be safer with image content requested")
				.Bind(out BLACKLIST_TAGS, "DisallowedTags", "", "A list of tags that are disallowed from being shown, Seperated by commas (,) without any spaces")
				.Bind(out ENABLE_GLOBAL_BLACKLIST, "EnableGlobalBlacklist", defaultValue: false, "Enables the Global Blacklist for generally unsafe queries, disable at your own risk when allowing Restrictive Queries")
				.Bind(out ALLOWED_TAGS, "AllowedTags", "", "A list of tags that are allowed to be shown, Seperated by commas (,) without any spaces");
			configFile2.Section("SwapperSettings").Bind(out ONLY_FIRST_ANIMATION_FRAME, "OnlyFirstAnimationFrame", defaultValue: false, "Only uses the first frame of animation instead of all frames").Bind(out ALLOW_TRANSCODING_VIDEOS, "AllowTranscodingVideos", defaultValue: false, "Allows for the ability to transcode video if codec or format is not directly support by unity")
				.Bind(out PRIORITIZE_NEW_PICTURES, "PrioritizeNewPictures", defaultValue: true, "Attempts to place newer pictures first over already existing pictures")
				.Bind(out MIN_AUDIO_DISTANCE, "MinAudioDistance", 0.5f, "Minimum distance from the swapped asset in which audio will stay at maximum")
				.Bind(out MAX_AUDIO_DISTANCE, "MaxAudioDistance", 6.5f, "Maximum distance from the swapped asset in which audio can be heard");
			configFile2.Section("BuiltinQuerySettings").Bind(out DIRECTORY_LOCATION, "DirectoryLocations", "", "Location of all directories to be looked at for images, Seperated by commas (,) without any spaces").Bind(out STATIC_WEB_MEDIA, "StaticWebMedia", "", "Location of all photos to be downloaded, Seperated by commas (,) without any spaces");
			bool flag = debugLogging() && clientSideOnly();
			this.configFile.SaveOnConfigSet = !flag;
			if (flag)
			{
				ConfigEntry<bool> val = configFile2.Bind<bool>("Common", "ClientSideRefresh", false, new ConfigDescription("Useful feature to try and reload stuff after changes to config for Client Side only stuff", (AcceptableValueBase)null, Array.Empty<object>()));
				val.SettingChanged += delegate
				{
					//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)
					configFile2.Reload();
					Scene activeScene = SceneManager.GetActiveScene();
					GameObject[] rootGameObjects = ((Scene)(ref activeScene)).GetRootGameObjects();
					GameObject[] array = rootGameObjects;
					foreach (GameObject val2 in array)
					{
						if (((Object)val2).name.Equals("Level Generator"))
						{
							SwapperComponentSetupUtils.unswapScene(val2);
							ActiveSwapperHolder.getOrCreate().reset();
							SwapperComponentSetupUtils.commonSide(val2);
						}
					}
				};
			}
			configFile2.SettingChanged += delegate
			{
				configAccess.setupValues();
			};
			setupValues();
		}

		private void setupValues()
		{
			pictureTextureTargets = parseString(PICTURE_TEXTURE_TARGETS.Value);
			directoryLocations = parseString(DIRECTORY_LOCATION.Value);
			staticWebMedia = parseString(STATIC_WEB_MEDIA.Value);
			blackListTags = parseString(BLACKLIST_TAGS.Value);
			whiteListTags = parseString(ALLOWED_TAGS.Value);
		}

		public bool debugLogging()
		{
			return DEBUG_LOGGING.Value;
		}

		public bool clientSideOnly()
		{
			return CLIENT_SIDE_ONLY.Value;
		}

		public bool restrictiveQueries()
		{
			return RESTRICTED_QUERIES.Value;
		}

		public bool enableGlobalBlacklist()
		{
			return ENABLE_GLOBAL_BLACKLIST.Value;
		}

		public bool onlyFirstAnimationFrame()
		{
			return ONLY_FIRST_ANIMATION_FRAME.Value;
		}

		public bool allowTranscodingVideos()
		{
			return ALLOW_TRANSCODING_VIDEOS.Value;
		}

		public bool prioritizeNewPictures()
		{
			return PRIORITIZE_NEW_PICTURES.Value;
		}

		public float minAudioDistance()
		{
			return MIN_AUDIO_DISTANCE.Value;
		}

		public float maxAudioDistance()
		{
			return MAX_AUDIO_DISTANCE.Value;
		}

		private static List<string> parseString(string value)
		{
			return (from s in value.Split(',')
				where !Utility.IsNullOrWhiteSpace(s) && s.Length > 0
				select s).ToList();
		}
	}
	public class SectionBinder
	{
		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private ConfigFile <configFile>P;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string <section>P;

		public SectionBinder(ConfigFile configFile, string section)
		{
			<configFile>P = configFile;
			<section>P = section;
			base..ctor();
		}

		public SectionBinder Bind<T>(out ConfigEntry<T> field, string key, T defaultValue, ConfigDescription configDescription = null)
		{
			field = <configFile>P.Bind<T>(<section>P, key, defaultValue, configDescription);
			return this;
		}

		public SectionBinder Bind<T>(out ConfigEntry<T> field, string key, T defaultValue, string description)
		{
			field = <configFile>P.Bind<T>(<section>P, key, defaultValue, description);
			return this;
		}
	}
	public static class ConfigFileExtensions
	{
		public static SectionBinder Section(this ConfigFile file, string section)
		{
			return new SectionBinder(file, section);
		}
	}
	public class PhotonEndecAddon
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static SerializeMethod <>9__1_0;

			public static DeserializeMethod <>9__1_1;

			internal byte[] <init>b__1_0(object obj)
			{
				if (!(obj is ByteDataAccess byteDataAccess))
				{
					throw new Exception($"Object was found not to be a ByteDataHolder: [Type: {obj.GetType()}, Obj:{obj}]");
				}
				return byteDataAccess.getBytes();
			}

			internal object <init>b__1_1(byte[] bytes)
			{
				return new ByteDataHolder().setBytes(bytes);
			}
		}

		private static bool hasTypeBeenRegistered;

		internal static void init()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			if (hasTypeBeenRegistered)
			{
				return;
			}
			Type typeFromHandle = typeof(ByteDataAccess);
			object obj2 = <>c.<>9__1_0;
			if (obj2 == null)
			{
				SerializeMethod val = delegate(object obj)
				{
					if (!(obj is ByteDataAccess byteDataAccess))
					{
						throw new Exception($"Object was found not to be a ByteDataHolder: [Type: {obj.GetType()}, Obj:{obj}]");
					}
					return byteDataAccess.getBytes();
				};
				<>c.<>9__1_0 = val;
				obj2 = (object)val;
			}
			object obj3 = <>c.<>9__1_1;
			if (obj3 == null)
			{
				DeserializeMethod val2 = (byte[] bytes) => new ByteDataHolder().setBytes(bytes);
				<>c.<>9__1_1 = val2;
				obj3 = (object)val2;
			}
			if (PhotonPeer.RegisterType(typeFromHandle, (byte)201, (SerializeMethod)obj2, (DeserializeMethod)obj3))
			{
				Plugin.Logger.LogWarning((object)"Was able to add onto Photon Peer!");
			}
			else
			{
				Plugin.Logger.LogError((object)"Wasn't able to add onto Photon Peer, FUCKKKKKK!");
			}
			hasTypeBeenRegistered = true;
		}

		static PhotonEndecAddon()
		{
			hasTypeBeenRegistered = false;
			init();
		}
	}
	public static class PhotonStreamExtensions
	{
		static PhotonStreamExtensions()
		{
			PhotonEndecAddon.init();
		}

		public static PhotonStreamOperation handleObject<T>(this PhotonStream stream, Func<T> encodeGetter, Action<T> decodeHandler) where T : EndecGetter<T>
		{
			if (stream.IsWriting)
			{
				stream.addObject<T>(encodeGetter());
				return PhotonStreamOperation.ENCODE;
			}
			decodeHandler(stream.getObject<T>());
			return PhotonStreamOperation.DECODE;
		}

		public static PhotonStreamOperation handleObject<T>(this PhotonStream stream, ref T t) where T : EndecGetter<T>
		{
			if (stream.IsWriting)
			{
				stream.addObject<T>(t);
				return PhotonStreamOperation.ENCODE;
			}
			t = stream.getObject<T>();
			return PhotonStreamOperation.DECODE;
		}

		public static void addObject<T>(this PhotonStream stream, T data) where T : EndecGetter<T>
		{
			if (!stream.IsWriting)
			{
				throw new Exception("You can not write a object to a PhotonStream that is currently reading!");
			}
			stream.SendNext((object)new EndecedStructWrapper<T>(data));
		}

		public static T getObject<T>(this PhotonStream stream) where T : EndecGetter<T>
		{
			if (!stream.IsReading)
			{
				throw new Exception("You can not read an object from a PhotonStream that is currently writting!");
			}
			object obj = stream.PeekNext();
			if (obj is ByteDataHolder byteDataHolder)
			{
				stream.ReceiveNext();
				return ByteDataAccess.decodeFromBytes<T>(EndecGetter.Endec<T>(), byteDataHolder.getBytes());
			}
			throw new Exception($"Unable to use the current peeked object from a PhotonStream due to the type mismatch! [Type: {obj.GetType()}, Required Type: PhotonEndecHolder]");
		}

		public static void dumpPhotonStreamToLog(this PhotonStream stream, Action<Action<Action<string>>> logActionCallback)
		{
			Type type2 = ((object)stream).GetType();
			FieldInfo field = type2.GetField("currentItem", BindingFlags.Instance);
			List<object> list = new List<object>();
			int currentIndex = (field?.GetValue(stream) as int?).GetValueOrDefault(-1);
			list.AddRange(stream.ToArray());
			logActionCallback(delegate(Action<string> logAction)
			{
				logAction("Dumping the given PhotonStream Data: ");
			});
			for (int i = 0; i < list.Count; i++)
			{
				object obj = list[i];
				Type type = obj.GetType();
				logActionCallback(delegate(Action<string> logAction)
				{
					logAction(string.Format("    [{0}, {1}]: Type=({2}), Object:({3})", i, (currentIndex == i) ? "X" : "O", type.FullName, obj));
				});
			}
		}
	}
	public enum PhotonStreamOperation
	{
		ENCODE,
		DECODE
	}
	public class ByteDataHolder : ByteDataAccess
	{
		private byte[] bytes = new byte[0];

		public ByteDataAccess setBytes(byte[] bytes)
		{
			this.bytes = bytes;
			return this;
		}

		public byte[] getBytes()
		{
			return bytes;
		}

		public override bool Equals(object? obj)
		{
			if (this == obj)
			{
				return true;
			}
			if (this != null)
			{
				return getBytes().Equals(((ByteDataAccess)this).getBytes());
			}
			return false;
		}

		public override int GetHashCode()
		{
			return bytes.GetHashCode();
		}
	}
	public interface ByteDataAccess
	{
		byte[] getBytes();

		static byte[] encodeAsBytes<T>(Endec<T> endec, T data)
		{
			MemoryStream stream = new MemoryStream();
			((Endec<BinaryWriter>)(object)endec).encodeFully<BinaryWriter>((Func<Serializer<BinaryWriter>>)(() => (Serializer<BinaryWriter>)(object)BinaryWriterSerializer.of(new BinaryWriter(stream))), (BinaryWriter)data);
			return stream.GetBuffer();
		}

		static T decodeFromBytes<T>(Endec<T> endec, byte[] bytes)
		{
			return ((Endec<BinaryReader>)(object)endec).decodeFully<BinaryReader>((Func<BinaryReader, Deserializer<BinaryReader>>)((BinaryReader reader) => (Deserializer<BinaryReader>)(object)BinaryReaderDeserializer.of(reader)), new BinaryReader(new MemoryStream(bytes)));
		}
	}
	internal sealed class EndecedStructWrapper<T> : StructWrapper, ByteDataAccess where T : EndecGetter<T>
	{
		public readonly T data;

		public EndecedStructWrapper(T data)
			: base(typeof(ByteDataAccess), (WrappedType)0)
		{
			this.data = data;
		}

		public static EndecedStructWrapper<T> of<T>(object obj) where T : EndecGetter<T>
		{
			if (!(obj is T val) || 1 == 0)
			{
				throw new Exception($"Unable to create EndecedStructWrapper as the object is not the correct type! [Type: {typeof(object)}, Obj: {obj}]");
			}
			return new EndecedStructWrapper<T>(val);
		}

		public byte[] getBytes()
		{
			return ByteDataAccess.encodeAsBytes(EndecGetter.Endec<T>(), data);
		}

		public override bool Equals(object? obj)
		{
			if (this == obj)
			{
				return true;
			}
			if (obj is EndecedStructWrapper<T> endecedStructWrapper)
			{
				return ((object)data).Equals((object?)endecedStructWrapper.data);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return ((object)data).GetHashCode();
		}

		public override object Box()
		{
			return data;
		}

		public override void DisconnectFromPool()
		{
		}

		public override void Dispose()
		{
		}

		public override string ToString()
		{
			return ((object)StructWrapperUtility.Unwrap<T>((object)this)).ToString();
		}

		public override string ToString(bool writeTypeInfo)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return writeTypeInfo ? $"(EndecedStructWrapper<{base.wrappedType}>){((object)StructWrapperUtility.Unwrap<T>((object)this)).ToString()}" : ((object)this).ToString();
		}
	}
	[BepInPlugin("TextureSwapper", "Texture Swapper", "1.1.7")]
	public class Plugin : BaseUnityPlugin
	{
		public delegate void AdditionalQueryLookup(Action<Identifier, IList<MediaQuery>> addCallback);

		internal static readonly List<string> RAW_NAMES = new List<string>(4) { "texture_swapper_queries", "painting_swapper_images", "RandomPaintingSwap_Images", "CustomPaintings" };

		private static Plugin? _INSTANCE = null;

		private static ManualLogSource? _LOGGER = null;

		private static ConfigAccess? _CONFIG_ACCESS = null;

		private static Thread? _MAIN_THREAD = null;

		private readonly Harmony _harmony = new Harmony("TextureSwapper");

		internal static Plugin Instance => getOrThrow(_INSTANCE, "Texture Swapper _instance");

		internal static ManualLogSource Logger => getOrThrow<ManualLogSource>(_LOGGER, "Texture Swapper _logger");

		internal static ConfigAccess ConfigAccess => getOrThrow(_CONFIG_ACCESS, "Texture Swapper _config_access");

		internal static string TempStoragePath => Path.Combine(Application.temporaryCachePath, "painting_swapper");

		internal static string TempVideoStoragePath => Path.Combine(TempStoragePath, "videos");

		internal static string TempImageStoragePath => Path.Combine(TempStoragePath, "images");

		internal static string TempAudioStoragePath => Path.Combine(TempStoragePath, "audio");

		public static event AdditionalQueryLookup ADDITIONAL_QUERY_LOOKUP;

		private static T getOrThrow<T>(T? value, string fieldName)
		{
			if (value != null)
			{
				return value;
			}
			throw new NullReferenceException("Unable to get " + fieldName + " as it has not been initialized yet.");
		}

		public static void logIfDebugging(Action<ManualLogSource> logAction, Func<bool>? predicate = null)
		{
			if (ConfigAccess.debugLogging() && (predicate == null || predicate()))
			{
				logAction(Logger);
			}
		}

		public static void logIfDebugging(Func<string> message, Func<bool>? predicate = null)
		{
			if (ConfigAccess.debugLogging() && (predicate == null || predicate()))
			{
				Logger.LogInfo((object)message());
			}
		}

		public static bool isMainThread()
		{
			return Thread.CurrentThread == _MAIN_THREAD;
		}

		private void Awake()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			_INSTANCE = this;
			_CONFIG_ACCESS = new ConfigAccess(((BaseUnityPlugin)this).Config);
			_LOGGER = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Texture Swapper has begun setup...");
			logIfDebugging(delegate(ManualLogSource source)
			{
				source.LogError((object)("Using the following path to store files temporarily: " + TempStoragePath));
			});
			FileUtils.deleteOldFiles(TempStoragePath, 2);
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			GlobalFFOptions.Configure(new FFOptions
			{
				BinaryFolder = directoryName,
				LogLevel = (FFMpegLogLevel)8
			});
			MagickNET.SetNativeLibraryDirectory(directoryName);
			string environmentVariable = MagickNET.GetEnvironmentVariable("Path");
			if (environmentVariable != null && !environmentVariable.Contains("pluginFolder"))
			{
				MagickNET.SetEnvironmentVariable("Path", environmentVariable + ";" + directoryName);
			}
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			if (_MAIN_THREAD == null)
			{
				_MAIN_THREAD = Thread.CurrentThread;
			}
			MagickNET.Initialize();
			MediaIdentifiers.initErrorImages(directoryName);
			_harmony.PatchAll(Chainloader.PluginInfos.ContainsKey("REPOLib") ? typeof(RepoLibNetworkPrefabsPatch) : typeof(RunManagerPatch));
			PhotonEndecAddon.init();
			WrapperPrefabPool.onPrefabInstantiation += delegate(GameObject gameObject, string _, Vector3 _, Quaternion _)
			{
				SwapperComponentSetupUtils.commonSide(gameObject);
			};
			MediaQueryTypeRegistry.register<LocalMediaQueryType, LocalMediaQuery, LocalMediaQueryResult>(LocalMediaQueryType.INSTANCE);
			Logger.LogInfo((object)"Plugin Texture Swapper loaded Successfully!");
		}

		public void Start()
		{
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			Logger.LogInfo((object)"Plugin Texture Swapper starting!");
			Dictionary<Identifier, IList<MediaQuery>> typeToQueries = new Dictionary<Identifier, IList<MediaQuery>>();
			Plugin.ADDITIONAL_QUERY_LOOKUP?.Invoke(delegate(Identifier identifier, IList<MediaQuery> list)
			{
				LinqExtensions.AddRange<MediaQuery>(typeToQueries.computeIfAbsent(identifier, (Identifier _) => new List<MediaQuery>()), (IEnumerable<MediaQuery>)list);
			});
			List<string> directories = new List<string>();
			directories.Add(Path.Combine(directoryName, RAW_NAMES[0]));
			directories.AddRange(ConfigAccess.directoryLocations);
			directories.Add(Path.Combine(Paths.ConfigPath, "texture_swapper_queries"));
			CreateImagesDirectory(directories);
			string directoryName2 = Path.GetDirectoryName(directoryName);
			string[] directories2 = Directory.GetDirectories(directoryName2);
			foreach (string text in directories2)
			{
				foreach (string rAW_NAME in RAW_NAMES)
				{
					string item = Path.Combine(text, rAW_NAME);
					if (Directory.Exists(text))
					{
						directories.Add(item);
					}
				}
			}
			StructEndec<IList<MediaQuery>> queryList = ((Endec<MediaQuery>)(object)MediaQueryTypeRegistry.QUERY_DATA).listOf().structOf("query_entries");
			Task.Run(delegate
			{
				foreach (string item2 in directories)
				{
					try
					{
						typeToQueries.computeIfAbsent(LocalMediaQueryType.ID, (Identifier _) => new List<MediaQuery>()).Add(LocalMediaQuery.ofDirectory(item2));
					}
					catch (Exception arg)
					{
						Logger.LogError((object)$"Unable to query local directory: {arg}");
					}
					if (Directory.Exists(item2))
					{
						string[] files = Directory.GetFiles(item2, "*.json");
						string[] array = files;
						foreach (string text2 in array)
						{
							try
							{
								IList<MediaQuery> list2 = JsonUtils.parseFromFile<IList<MediaQuery>>(text2, (Endec<IList<MediaQuery>>)(object)queryList);
								if (list2 != null)
								{
									foreach (MediaQuery item3 in list2)
									{
										typeToQueries.computeIfAbsent(item3.getQueryTypeId(), (Identifier _) => new List<MediaQuery>()).Add(item3);
									}
								}
							}
							catch (Exception arg2)
							{
								Logger.LogError((object)$"Unable to parse the given file [{text2}] as MediaQueries: {arg2}");
							}
						}
					}
				}
				foreach (KeyValuePair<Identifier, IList<MediaQuery>> entry in typeToQueries)
				{
					MultiThreadHelper.run(new SemaphoreIdentifier(Identifier.of("texture_swapper", "types"), 1), delegate
					{
						foreach (MediaQuery item4 in entry.Value)
						{
							if (!MediaQueryTypeRegistry.attemptToHandleQuery(item4))
							{
								Logger.LogError((object)$"Unable to handle the given query: [Id: {entry.Key}]");
							}
						}
					});
				}
			});
			Logger.LogInfo((object)"Plugin Texture Swapper started Successfully!");
		}

		private void Update()
		{
			MediaSwapperStorage.handleToBeStoredHandlers();
			MainThreadHelper.handleActionsOnMainThread();
			ImageSequenceHolder.actIfPresent(delegate(ImageSequenceHolder holder)
			{
				holder.checkIfMaterialsLoaded();
			});
		}

		private void CreateImagesDirectory(List<string> directories)
		{
			foreach (string directory in directories)
			{
				try
				{
					if (!Directory.Exists(directory))
					{
						Directory.CreateDirectory(directory);
						logIfDebugging(delegate(ManualLogSource source)
						{
							source.LogInfo((object)("Folder " + directory + " created successfully!"));
						});
					}
					else
					{
						logIfDebugging(delegate(ManualLogSource source)
						{
							source.LogInfo((object)("Folder " + directory + " detected!)"));
						});
					}
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					Exception e = ex2;
					logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogError((object)("Unable to create directory [" + directory + "]:"));
						source.LogError((object)e);
					});
				}
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "TextureSwapper";

		public const string PLUGIN_NAME = "Texture Swapper";

		public const string PLUGIN_VERSION = "1.1.7";
	}
}
namespace io.wispforest.textureswapper.patches
{
	internal class RepoLibNetworkPrefabsPatch
	{
		[HarmonyPatch(typeof(NetworkPrefabs), "Initialize")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void AwakePatch()
		{
			WrapperPrefabPool.attemptToWrapPhotonPool();
		}
	}
	[HarmonyPatch(typeof(RunManager))]
	internal static class RunManagerPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void AwakePatch()
		{
			WrapperPrefabPool.attemptToWrapPhotonPool();
		}
	}
}
namespace io.wispforest.textureswapper.endec.format.newtonsoft
{
	public class JsonDeserializer : RecursiveDeserializer<JToken>, SelfDescribedDeserializer<JToken>, Deserializer<JToken>
	{
		private class JsonSequenceDeserializer<V> : SequenceDeserializer<V>, IEnumerator<V>, IEnumerator, IDisposable, IEnumerable<V>, IEnumerable
		{
			private readonly JsonDeserializer deserializer;

			private readonly SerializationContext ctx;

			private readonly Endec<V> valueEndec;

			private readonly IEnumerator<JToken> elements;

			private readonly int size;

			public V Current => next();

			public JsonSequenceDeserializer(JsonDeserializer deserializer, SerializationContext ctx, Endec<V> valueEndec, JArray elements)
			{
				this.deserializer = deserializer;
				this.ctx = ctx;
				this.valueEndec = valueEndec;
				this.elements = elements.GetEnumerator();
				size = ((JContainer)elements).Count;
			}

			public int estimatedSize()
			{
				return size;
			}

			public bool MoveNext()
			{
				return elements.MoveNext();
			}

			public V next()
			{
				JToken element = elements.Current;
				return ((RecursiveDeserializer<JToken>)(object)deserializer).frame<V>((Func<JToken>)(() => element), (Func<V>)(() => valueEndec.decode<JToken>(ctx, (Deserializer<JToken>)(object)deserializer)));
			}

			public void Reset()
			{
				elements.Reset();
			}

			public void Dispose()
			{
				elements.Dispose();
			}
		}

		private class JsonMapDeserializer<V> : MapDeserializer<V>, IEnumerator<KeyValuePair<string, V>>, IEnumerator, IDisposable, IEnumerable<KeyValuePair<string, V>>, IEnumerable
		{
			private readonly JsonDeserializer deserializer;

			private readonly SerializationContext ctx;

			private readonly Endec<V> valueEndec;

			private readonly IEnumerator<KeyValuePair<string, JToken>> entries;

			private readonly int size;

			public KeyValuePair<string, V> Current => next();

			public JsonMapDeserializer(JsonDeserializer deserializer, SerializationContext ctx, Endec<V> valueEndec, JObject entries)
			{
				this.deserializer = deserializer;
				this.ctx = ctx;
				this.valueEndec = valueEndec;
				this.entries = entries.GetEnumerator();
				size = ((JContainer)entries).Count;
			}

			public int estimatedSize()
			{
				return size;
			}

			public bool MoveNext()
			{
				return entries.MoveNext();
			}

			public KeyValuePair<string, V> next()
			{
				KeyValuePair<string, JToken> entry = entries.Current;
				return ((RecursiveDeserializer<JToken>)(object)deserializer).frame<KeyValuePair<string, V>>((Func<JToken>)(() => entry.Value), (Func<KeyValuePair<string, V>>)(() => new KeyValuePair<string, V>(entry.Key, valueEndec.decode<JToken>(ctx, (Deserializer<JToken>)(object)deserializer))));
			}

			public void Reset()
			{
				entries.Reset();
			}

			public void Dispose()
			{
				entries.Dispose();
			}
		}

		private class JsonStructDeserializer : StructDeserializer
		{
			private readonly JsonDeserializer deserializer;

			private readonly JObject obj;

			public JsonStructDeserializer(JsonDeserializer deserializer, JObject obj)
			{
				this.deserializer = deserializer;
				this.obj = obj;
			}

			public F? field<F>(string name, SerializationContext ctx, Endec<F> endec, Func<F>? defaultValueFactory)
			{
				Endec<F> endec2 = endec;
				SerializationContext ctx2 = ctx;
				JToken element = obj[name];
				if (element == null)
				{
					if (defaultValueFactory == null)
					{
						throw new Exception("Field '" + name + "' was missing from serialized data, but no default value was provided");
					}
					return defaultValueFactory();
				}
				try
				{
					return ((RecursiveDeserializer<JToken>)(object)deserializer).frame<F>((Func<JToken>)(() => element), (Func<F>)(() => ((Endec<JToken>)(object)endec2).decode<JToken>(ctx2, (Deserializer<JToken>)(object)deserializer)));
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					Exception e = ex2;
					Plugin.logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogError((object)e);
					});
					Plugin.logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogError((object)((object)obj).ToString());
					});
					throw e;
				}
			}
		}

		protected JsonDeserializer(JToken serialized)
			: base(serialized)
		{
		}

		public static JsonDeserializer of(JToken serialized)
		{
			return new JsonDeserializer(serialized);
		}

		public SerializationContext setupContext(SerializationContext ctx)
		{
			return ctx.withAttributes((SerializationAttributeInstance[])(object)new SerializationAttributeInstance[1] { (SerializationAttributeInstance)SerializationAttributes.HUMAN_READABLE });
		}

		public override byte readByte(SerializationContext ctx)
		{
			return readPrimitive((IConvertible convertible) => convertible.ToByte(CultureInfo.CurrentCulture));
		}

		public override short readShort(SerializationContext ctx)
		{
			return readPrimitive((IConvertible convertible) => convertible.ToInt16(CultureInfo.CurrentCulture));
		}

		public override int readInt(SerializationContext ctx)
		{
			return readPrimitive((IConvertible convertible) => convertible.ToInt32(CultureInfo.CurrentCulture));
		}

		public override long readLong(SerializationContext ctx)
		{
			return readPrimitive((IConvertible convertible) => convertible.ToInt64(CultureInfo.CurrentCulture));
		}

		public override float readFloat(SerializationContext ctx)
		{
			return readPrimitive((IConvertible convertible) => convertible.ToSingle(CultureInfo.CurrentCulture));
		}

		public override double readDouble(SerializationContext ctx)
		{
			return readPrimitive((IConvertible convertible) => convertible.ToDouble(CultureInfo.CurrentCulture));
		}

		public override int readVarInt(SerializationContext ctx)
		{
			return ((RecursiveDeserializer<JToken>)(object)this).readInt(ctx);
		}

		public override long readVarLong(SerializationContext ctx)
		{
			return ((RecursiveDeserializer<JToken>)(object)this).readLong(ctx);
		}

		public override bool readBoolean(SerializationContext ctx)
		{
			return readPrimitive((IConvertible convertible) => convertible.ToBoolean(CultureInfo.CurrentCulture));
		}

		public override string readString(SerializationContext ctx)
		{
			return readPrimitive((IConvertible convertible) => convertible.ToString(CultureInfo.CurrentCulture));
		}

		private T readPrimitive<T>(Func<IConvertible, T> func) where T : IConvertible
		{
			return readPrimitive(base.getValue(), func);
		}

		private T readPrimitive<T>(JToken token, Func<IConvertible, T> func) where T : IConvertible
		{
			JValue val = (JValue)(object)((token is JValue) ? token : null);
			if (val == null)
			{
				throw new Exception($"Unable to read JToken as it is not a JValue: {token}");
			}
			if (token == null)
			{
				throw new Exception($"Unable to read JToken as the given value is null and can not be converted to the needed type: {typeof(T)}");
			}
			if (!(val.Value is IConvertible arg))
			{
				throw new Exception($"Unable to read JValue as it is not a the correct type: [Type: {typeof(T)}, Obj Type: {val.Value}]");
			}
			return func(arg);
		}

		private T getValueSafe<T>() where T : JToken
		{
			JToken value = base.getValue();
			if (value == null)
			{
				throw new Exception("UHHHHHHHHHHHHHHHHHHHHHHHHH");
			}
			if (!(value is T))
			{
				throw new Exception($"FUCKLKDKDKDKDKDKDK: [Type: {((object)value).GetType()}");
			}
			return (T)(object)((value is T) ? value : null);
		}

		public override byte[] readBytes(SerializationContext ctx)
		{
			JArray valueSafe = getValueSafe<JArray>();
			byte[] array = new byte[((JContainer)valueSafe).Count];
			for (int i = 0; i < ((JContainer)valueSafe).Count; i++)
			{
				array[i] = readPrimitive(valueSafe[i], (IConvertible convertible) => convertible.ToByte(CultureInfo.CurrentCulture));
			}
			return array;
		}

		public override V? readOptional<V>(SerializationContext ctx, Endec<V> endec)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			JToken value = base.getValue();
			JTokenType type = value.Type;
			return (!((object)(JTokenType)(ref type)).Equals((object)(JTokenType)10)) ? ((Endec<JToken>)(object)endec).decode<JToken>(ctx, (Deserializer<JToken>)(object)this) : default(V);
		}

		public override SequenceDeserializer<E> sequence<E>(SerializationContext ctx, Endec<E> elementEndec)
		{
			return (SequenceDeserializer<E>)(object)new JsonSequenceDeserializer<E>(this, ctx, elementEndec, getValueSafe<JArray>());
		}

		public override MapDeserializer<V> map<V>(SerializationContext ctx, Endec<V> valueEndec)
		{
			return (MapDeserializer<V>)(object)new JsonMapDeserializer<V>(this, ctx, valueEndec, getValueSafe<JObject>());
		}

		public override StructDeserializer structed()
		{
			return (StructDeserializer)(object)new JsonStructDeserializer(this, getValueSafe<JObject>());
		}

		public void readAny<S>(SerializationContext ctx, Serializer<S> visitor) where S : class
		{
			decodeValue<S>(ctx, visitor, base.getValue());
		}

		private void decodeValue<S>(SerializationContext ctx, Serializer<S> visitor, JToken element) where S : class
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			bool flag = true;
			JTokenType type = element.Type;
			if (((object)(JTokenType)(ref type)).Equals((object)(JTokenType)10))
			{
				((Serializer<JToken>)(object)visitor).writeOptional<JToken>(ctx, (Endec<JToken>)(object)JsonEndec.INSTANCE, (JToken)null);
			}
			else
			{
				JValue val = (JValue)(object)((element is JValue) ? element : null);
				if (val != null)
				{
					if (val.Value is string text)
					{
						visitor.writeString(ctx, text);
					}
					else if (val.Value is bool flag2)
					{
						visitor.writeBoolean(ctx, flag2);
					}
					else if (val.Value is IConvertible convertible)
					{
						try
						{
							long num = convertible.ToInt64(CultureInfo.CurrentCulture);
							if ((byte)num == num)
							{
								visitor.writeByte(ctx, convertible.ToByte(CultureInfo.CurrentCulture));
							}
							else if ((short)num == num)
							{
								visitor.writeShort(ctx, convertible.ToInt16(CultureInfo.CurrentCulture));
							}
							else if ((int)num == num)
							{
								visitor.writeInt(ctx, convertible.ToInt32(CultureInfo.CurrentCulture));
							}
							else
							{
								visitor.writeLong(ctx, num);
							}
						}
						catch (Exception ex) when (ex is FormatException || ex is OverflowException)
						{
							double num2 = convertible.ToDouble(CultureInfo.CurrentCulture);
							if ((double)(float)num2 == num2)
							{
								visitor.writeFloat(ctx, convertible.ToSingle(CultureInfo.CurrentCulture));
							}
							else
							{
								visitor.writeDouble(ctx, num2);
							}
						}
					}
					else
					{
						flag = false;
					}
				}
				else
				{
					JArray val2 = (JArray)(object)((element is JArray) ? element : null);
					if (val2 != null)
					{
						SequenceSerializer<JToken> val3 = ((Serializer<JToken>)(object)visitor).sequence<JToken>(ctx, EndecUtils.of<JToken>((Encoder<JToken>)decodeValue<object>, (Decoder<JToken>)((SerializationContext _, Deserializer<dynamic> _) => null)), ((JContainer)val2).Count);
						try
						{
							foreach (JToken item in val2)
							{
								val3.element(item);
							}
						}
						finally
						{
							((IDisposable)val3)?.Dispose();
						}
					}
					else
					{
						JObject val4 = (JObject)(object)((element is JObject) ? element : null);
						if (val4 != null)
						{
							MapSerializer<JToken> val5 = ((Serializer<JToken>)(object)visitor).map<JToken>(ctx, EndecUtils.of<JToken>((Encoder<JToken>)decodeValue<object>, (Decoder<JToken>)((SerializationContext _, Deserializer<dynamic> _) => null)), ((JContainer)val4).Count);
							try
							{
								foreach (KeyValuePair<string, JToken> item2 in val4)
								{
									val5.entry(item2.Key, item2.Value);
								}
							}
							finally
							{
								((IDisposable)val5)?.Dispose();
							}
						}
						else
						{
							flag = false;
						}
					}
				}
			}
			if (!flag)
			{
				throw new Exception($"Non-standard, unrecognized JsonElement implementation cannot be decoded: {element}");
			}
		}
	}
	public class JsonEndec : Endec<JToken>
	{
		public static readonly JsonEndec INSTANCE = new JsonEndec();

		private JsonEndec()
		{
		}

		public override void encode<E>(SerializationContext ctx, Serializer<E> serializer, JToken value)
		{
			if (serializer is SelfDescribedSerializer<E>)
			{
				JsonDeserializer.of(value).readAny<E>(ctx, serializer);
			}
			else
			{
				serializer.writeString(ctx, JsonUtils.writeToString(value));
			}
		}

		public override JToken decode<E>(SerializationContext ctx, Deserializer<E> deserializer)
		{
			if (deserializer is SelfDescribedDeserializer<E> val)
			{
				JsonSerializer jsonSerializer = JsonSerializer.of();
				((SelfDescribedDeserializer<JToken>)(object)val).readAny<JToken>(ctx, (Serializer<JToken>)(object)jsonSerializer);
				return ((RecursiveSerializer<JToken>)(object)jsonSerializer).result();
			}
			return JsonUtils.readFromString(deserializer.readString(ctx));
		}
	}
	public class JsonSerializer : RecursiveSerializer<JToken>, SelfDescribedSerializer<JToken>, Serializer<JToken>
	{
		private class JsonStructSerializer : StructSerializer, Endable, IDisposable
		{
			private readonly JsonSerializer _serializer;

			private readonly JObject _result;

			public JsonStructSerializer(JsonSerializer serializer)
			{
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_007b: Expected O, but got Unknown
				_serializer = serializer;
				if (serializer.prefix != null)
				{
					JToken? prefix = serializer.prefix;
					JObject val = (JObject)(object)((prefix is JObject) ? prefix : null);
					if (val == null)
					{
						throw new Exception("Incompatible prefix of type used " + ((object)_serializer).GetType().Name + " for JSON map/struct");
					}
					_result = val;
					serializer.prefix = null;
				}
				else
				{
					_result = new JObject();
				}
			}

			public StructSerializer field<F>(string name, SerializationContext ctx, Endec<F> endec, F value, bool mayOmit)
			{
				Endec<F> endec2 = endec;
				SerializationContext ctx2 = ctx;
				F value2 = value;
				string name2 = name;
				((RecursiveSerializer<JToken>)(object)_serializer).frame((FrameAction<JToken>)delegate(EncodedValue<JToken> encoded)
				{
					//IL_0039: Unknown result type (might be due to invalid IL or missing references)
					//IL_003e: Unknown result type (might be due to invalid IL or missing references)
					((Endec<JToken>)(object)endec2).encode<JToken>(ctx2, (Serializer<JToken>)(object)_serializer, (JToken)value2);
					JToken val = encoded.require("struct field");
					if (mayOmit)
					{
						JTokenType type = val.Type;
						if (((object)(JTokenType)(ref type)).Equals((object)(JTokenType)10))
						{
							return;
						}
					}
					_result.Add(name2, val);
				});
				return (StructSerializer)(object)this;
			}

			public void end()
			{
				((RecursiveSerializer<JToken>)(object)_serializer).consume((JToken)(object)_result);
			}
		}

		private class JsonMapSerializer<V> : MapSerializer<V>, Endable, IDisposable
		{
			private readonly JsonSerializer _serializer;

			private readonly SerializationContext _ctx;

			private readonly Endec<V> _valueEndec;

			private readonly JObject _result;

			public JsonMapSerializer(JsonSerializer serializer, SerializationContext ctx, Endec<V> valueEndec)
			{
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Expected O, but got Unknown
				_serializer = serializer;
				_ctx = ctx;
				_valueEndec = valueEndec;
				if (serializer.prefix != null)
				{
					JToken? prefix = serializer.prefix;
					JObject val = (JObject)(object)((prefix is JObject) ? prefix : null);
					if (val == null)
					{
						throw new Exception("Incompatible prefix of type used " + ((object)_serializer).GetType().Name + " for JSON map/struct");
					}
					_result = val;
					serializer.prefix = null;
				}
				else
				{
					_result = new JObject();
				}
			}

			public void entry(string key, V value)
			{
				V value2 = value;
				string key2 = key;
				((RecursiveSerializer<JToken>)(object)_serializer).frame((FrameAction<JToken>)delegate(EncodedValue<JToken> encoded)
				{
					_valueEndec.encode<JToken>(_ctx, (Serializer<JToken>)(object)_serializer, value2);
					_result.Add(key2, encoded.require("map value"));
				});
			}

			public void end()
			{
				((RecursiveSerializer<JToken>)(object)_serializer).consume((JToken)(object)_result);
			}
		}

		private class JsonSequenceSerializer<V> : SequenceSerializer<V>, Endable, IDisposable
		{
			private readonly JsonSerializer _serializer;

			private readonly SerializationContext _ctx;

			private readonly Endec<V> _valueEndec;

			private readonly JArray _result;

			public JsonSequenceSerializer(JsonSerializer serializer, SerializationContext ctx, Endec<V> valueEndec, int size)
			{
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0086: Expected O, but got Unknown
				_serializer = serializer;
				_ctx = ctx;
				_valueEndec = valueEndec;
				if (serializer.prefix != null)
				{
					JToken? prefix = serializer.prefix;
					JArray val = (JArray)(object)((prefix is JArray) ? prefix : null);
					if (val == null)
					{
						throw new Exception("Incompatible prefix of type " + ((object)serializer.prefix).GetType().Name + " used for JSON sequence");
					}
					_result = val;
					serializer.prefix = null;
				}
				else
				{
					_result = new JArray();
				}
			}

			public void element(V element)
			{
				V element2 = element;
				((RecursiveSerializer<JToken>)(object)_serializer).frame((FrameAction<JToken>)delegate(EncodedValue<JToken> encoded)
				{
					_valueEndec.encode<JToken>(_ctx, (Serializer<JToken>)(object)_serializer, element2);
					_result.Add(encoded.require("sequence element"));
				});
			}

			public void end()
			{
				((RecursiveSerializer<JToken>)(object)_serializer).consume((JToken)(object)_result);
			}
		}

		internal JToken? prefix;

		protected JsonSerializer(JToken prefix)
			: base((JToken)null)
		{
			this.prefix = prefix;
		}

		public static JsonSerializer of()
		{
			return new JsonSerializer(null);
		}

		public SerializationContext setupContext(SerializationContext ctx)
		{
			return ctx.withAttributes((SerializationAttributeInstance[])(object)new SerializationAttributeInstance[1] { (SerializationAttributeInstance)SerializationAttributes.HUMAN_READABLE });
		}

		public override void writeByte(SerializationContext ctx, byte value)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			base.consume((JToken)new JValue((long)value));
		}

		public override void writeShort(SerializationContext ctx, short value)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			base.consume((JToken)new JValue((long)value));
		}

		public override void writeInt(SerializationContext ctx, int value)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			base.consume((JToken)new JValue((long)value));
		}

		public override void writeLong(SerializationContext ctx, long value)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			base.consume((JToken)new JValue(value));
		}

		public override void writeFloat(SerializationContext ctx, float value)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			base.consume((JToken)new JValue(value));
		}

		public override void writeDouble(SerializationContext ctx, double value)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			base.consume((JToken)new JValue(value));
		}

		public override void writeVarInt(SerializationContext ctx, int value)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			base.consume((JToken)new JValue((long)value));
		}

		public override void writeVarLong(SerializationContext ctx, long value)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			base.consume((JToken)new JValue(value));
		}

		public override void writeBoolean(SerializationContext ctx, bool value)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			base.consume((JToken)new JValue(value));
		}

		public override void writeString(SerializationContext ctx, string value)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			base.consume((JToken)new JValue(value));
		}

		public override void writeBytes(SerializationContext ctx, byte[] bytes)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			JArray val = new JArray();
			for (int i = 0; i < bytes.Length; i++)
			{
				val.Add((JToken)new JValue((long)bytes[i]));
			}
			base.consume((JToken)(object)val);
		}

		public override void writeOptional<V>(SerializationContext ctx, Endec<V> endec, V? optional)
		{
			if (optional == null)
			{
				base.consume((JToken)(object)JValue.CreateNull());
			}
			else
			{
				((Endec<JToken>)(object)endec).encode<JToken>(ctx, (Serializer<JToken>)(object)this, (JToken)optional);
			}
		}

		public override SequenceSerializer<E> sequence<E>(SerializationContext ctx, Endec<E> elementEndec, int size)
		{
			return (SequenceSerializer<E>)(object)new JsonSequenceSerializer<E>(this, ctx, elementEndec, size);
		}

		public override MapSerializer<V> map<V>(SerializationContext ctx, Endec<V> valueEndec, int size)
		{
			return (MapSerializer<V>)(object)new JsonMapSerializer<V>(this, ctx, valueEndec);
		}

		public override StructSerializer structed()
		{
			return (StructSerializer)(object)new JsonStructSerializer(this);
		}
	}
	public class JsonUtils
	{
		private static readonly List<string> ALLOWED_JSON_PATTERNS = new List<string>(2) { "*.json", "*.json5" };

		public static string writeToString(JToken value)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			StringWriter stringWriter = new StringWriter();
			value.WriteTo((JsonWriter)new JsonTextWriter((TextWriter)stringWriter), Array.Empty<JsonConverter>());
			return stringWriter.ToString();
		}

		public static JToken readFromString(string value)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			return JToken.ReadFrom((JsonReader)new JsonTextReader((TextReader)new StringReader(value)));
		}

		public static JToken readFromFile(string path)
		{
			return readFromString(File.ReadAllText(path));
		}

		public static JToken readFromStream(Stream value)
		{
			return readFromString(new StreamReader(value).ReadToEnd());
		}

		public static JToken readFromFileIfPresent(string path)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			if (!File.Exists(path))
			{
				return (JToken)new JObject();
			}
			return readFromString(File.ReadAllText(path));
		}

		public static T parseFromFile<T>(string path) where T : EndecGetter<T>
		{
			return parseFromFile<T>(path, EndecGetter.Endec<T>());
		}

		public static T? parseFromFile<T>(string path, Endec<T> endec)
		{
			if (!File.Exists(path))
			{
				return default(T);
			}
			JToken val = readFromFile(path);
			return ((Endec<JToken>)(object)endec).decodeFully<JToken>((Func<JToken, Deserializer<JToken>>)JsonDeserializer.of, val);
		}

		public static T parseFromStream<T>(Stream stream) where T : EndecGetter<T>
		{
			return parseFromStream<T>(stream, EndecGetter.Endec<T>());
		}

		public static T parseFromStream<T>(Stream stream, Endec<T> endec)
		{
			JToken val = readFromStream(stream);
			return ((Endec<JToken>)(object)endec).decodeFully<JToken>((Func<JToken, Deserializer<JToken>>)JsonDeserializer.of, val);
		}

		public static T parseFromString<T>(string str, Endec<T> endec)
		{
			JToken val = readFromString(str);
			return ((Endec<JToken>)(object)endec).decodeFully<JToken>((Func<JToken, Deserializer<JToken>>)JsonDeserializer.of, val);
		}

		public static Dictionary<string, T> parseFiles<T>(string directory, Func<string, string> keyMaker, Action<string, Exception> onError) where T : EndecGetter<T>
		{
			return parseFiles<T>(directory, EndecGetter.Endec<T>(), keyMaker, onError);
		}

		public static Dictionary<string, T> parseFiles<T>(string directory, Endec<T> endec, Func<string, string> keyMaker, Action<string, Exception> onError)
		{
			string directory2 = directory;
			List<string> list = ALLOWED_JSON_PATTERNS.SelectMany((string pattern) => Directory.GetFiles(directory2, pattern)).ToList();
			Dictionary<string, T> dictionary = new Dictionary<string, T>();
			foreach (string item in list)
			{
				if (item != null && File.Exists(item))
				{
					try
					{
						T value = parseFromFile<T>(item, endec);
						dictionary[keyMaker(item)] = value;
					}
					catch (Exception arg)
					{
						onError(item, arg);
					}
				}
			}
			return dictionary;
		}
	}
}
namespace io.wispforest.textureswapper.utils
{
	public class SwapperComponentSetupUtils
	{
		public static void unswapScene(GameObject rootObject)
		{
			if (!Plugin.ConfigAccess.clientSideOnly())
			{
				return;
			}
			foreach (GameObject item in unpackGameObject(rootObject))
			{
				item.GetComponent<SwapperHandlerHolder>()?.unswapAllTextures(item);
			}
		}

		public static void commonSide(GameObject rootObject)
		{
			try
			{
				foreach (GameObject obj in unpackGameObject(rootObject))
				{
					Action<MeshRenderer, int, Material, Action<Material>> onMatchEntry = delegate(MeshRenderer mesh, int i, Material material, Action<Material> setAction)
					{
						MeshRenderer mesh2 = mesh;
						Material material2 = material;
						Action<Material> setAction2 = setAction;
						if (Plugin.ConfigAccess.clientSideOnly())
						{
							fullClientSideSetup(obj, mesh2, i, material2, setAction2);
						}
						else
						{
							MediaIdentifierComponent orAddComponent = ComponentHolderProtocol.GetOrAddComponent<MediaIdentifierComponent>((Object)(object)obj);
							if (PhotonNetwork.LocalPlayer.IsMasterClient)
							{
								Identifier identifier = ActiveSwapperHolder.getOrCreate().actOrWaitWithHandler(delegate(MeshSwapper handler)
								{
									obj.setSwapperHolder(mesh2, i, material2, setAction2, handler);
								});
								if (identifier == null)
								{
									return;
								}
								if (orAddComponent != null)
								{
									orAddComponent.setId(identifier);
								}
								else
								{
									Plugin.logIfDebugging(delegate(ManualLogSource source)
									{
										source.LogWarning((object)"Unable to create or get the needed Painting Component for given obj");
									});
								}
							}
							PhotonView orAddComponent2 = ComponentHolderProtocol.GetOrAddComponent<PhotonView>((Object)(object)obj);
							Plugin.logIfDebugging(delegate(ManualLogSource source)
							{
								source.LogInfo((object)("Target Object preparing for Texture Component Replacment: " + ((Object)obj).name));
							});
							if ((Object)(object)orAddComponent2 == (Object)null)
							{
								Plugin.logIfDebugging(delegate(ManualLogSource source)
								{
									source.LogInfo((object)"Target Object was unable to have a Photon View\n");
								});
							}
							else
							{
								Plugin.logIfDebugging(delegate(ManualLogSource source)
								{
									source.LogInfo((object)"Target Object View will now track Painting Component!\n");
								});
								PhotonView photonView = PunExtensions.GetPhotonView(obj);
								(photonView.ObservedComponents ?? (photonView.ObservedComponents = new List<Component>())).Add((Component)(object)orAddComponent);
							}
						}
					};
					obj.tryToAdjustMaterial(onMatchEntry);
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)"An error has occured when adjusting painting material!");
				Plugin.Logger.LogError((object)ex);
			}
		}

		public static void fullClientSideSetup(GameObject obj, MeshRenderer mesh, int i, Material material, Action<Material> setAction)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj2 = obj;
			MeshRenderer mesh2 = mesh;
			Material material2 = material;
			Action<Material> setAction2 = setAction;
			Vector3 position = obj2.transform.position;
			int value = BitConverter.ToInt32(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes($"{position.x:R},{position.y:R},{position.z:R}")), 0);
			ActiveSwapperHolder.getOrCreate().actOrWaitWithHandler(delegate(MeshSwapper handler)
			{
				obj2.setSwapperHolder(mesh2, i, material2, setAction2, handler);
			}, value);
		}

		public static void clientPaintingDataChange(GameObject obj, FullMediaData fullData)
		{
			FullMediaData fullData2 = fullData;
			GameObject obj2 = obj;
			MediaSwapperStorage.loadIfNotFound(fullData2);
			Action<MeshRenderer, int, Material, Action<Material>> onMatchEntry = delegate(MeshRenderer mesh, int i, Material material, Action<Material> setAction)
			{
				MeshRenderer mesh2 = mesh;
				Material material2 = material;
				Action<Material> setAction2 = setAction;
				Identifier id = fullData2.id;
				if (MediaIdentifiers.ERROR.Equals(id) || !MediaSwapperStorage.hasMaterial(id))
				{
					Plugin.logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogInfo((object)$"Unable to Set Clients Material: {id}");
					});
				}
				MediaSwapperStorage.getOrActWithHandler(id, delegate(MeshSwapper handler)
				{
					if (isCensored(MediaSwapperStorage.getResult(id)))
					{
						handler = MediaSwapperStorage.getHandler<MeshSwapper>(MediaIdentifiers.CENSORED);
						Plugin.logIfDebugging(delegate(ManualLogSource source)
						{
							source.LogInfo((object)$"The given entry {id} has been censored due to being blacklisted!");
						});
					}
					obj2.gameObject.setSwapperHolder(mesh2, i, material2, setAction2, handler);
					Plugin.logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogInfo((object)$"Set Clients Material: {id}");
					});
				});
			};
			obj2.tryToAdjustMaterial(onMatchEntry);
		}

		public static bool isPictureGameObject(GameObject gameObject)
		{
			return searchMaterial(gameObject, (MeshRenderer _, int _, Material _, Action<Material> _) => true);
		}

		public static bool searchMaterial(GameObject gameObject, Func<MeshRenderer, int, Material, Action<Material>, bool> onMatchEntry)
		{
			List<Regex> source = Plugin.ConfigAccess.pictureTextureTargets.Select((string s) => RegexUtils.parseRegexWithFlags(s)).ToList();
			MeshRenderer[] components = gameObject.GetComponents<MeshRenderer>();
			foreach (MeshRenderer mesh in components)
			{
				Material[] sharedMaterials = ((Renderer)mesh).sharedMaterials;
				if (sharedMaterials == null)
				{
					continue;
				}
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					Material val = sharedMaterials[j];
					if (!((Object)(object)val != (Object)null))
					{
						continue;
					}
					string name = ((Object)val).name;
					if (source.Any((Regex regex) => regex.IsMatch(name)) || source.Any((Regex regex) => regex.IsMatch(((Object)((Component)mesh).gameObject).name)))
					{
						int targetIndex = j;
						Action<Material> arg = delegate(Material newMaterial)
						{
							sharedMaterials[targetIndex] = newMaterial;
							((Renderer)mesh).sharedMaterials = sharedMaterials;
						};
						if (onMatchEntry(mesh, targetIndex, val, arg))
						{
							return true;
						}
					}
				}
			}
			return false;
		}

		public static IEnumerable<GameObject> unpackGameObject(GameObject gameObject)
		{
			IEnumerable<GameObject> second = from child in gameObject.GetComponentsInChildren<Transform>()
				select ((Component)child).gameObject;
			return ((IEnumerable<GameObject>)(object)new GameObject[1] { gameObject }).Concat(second);
		}

		public static bool isCensored(MediaQueryResult queryResult)
		{
			if (Plugin.ConfigAccess.restrictiveQueries() && queryResult is RatedMediaResult ratedMediaResult && !ratedMediaResult.isSafe())
			{
				return true;
			}
			if (queryResult is TaggedMediaResult taggedMediaResult)
			{
				foreach (string blackListTag in Plugin.ConfigAccess.blackListTags)
				{
					if (taggedMediaResult.hasTag(blackListTag))
					{
						return true;
					}
				}
			}
			return false;
		}
	}
	public class Extensions
	{
	}
	public static class DictionaryExtensions
	{
		public static V computeIfAbsent<K, V>(this Dictionary<K, V> dict, K k, Func<K, V> func)
		{
			if (!dict.ContainsKey(k))
			{
				dict[k] = func(k);
			}
			return dict[k];
		}

		public static V? removeIfPresent<K, V>(this Dictionary<K, V> dict, K k) where V : class
		{
			V result = null;
			if (dict.ContainsKey(k))
			{
				result = dict[k];
				dict.Remove(k);
			}
			return result;
		}
	}
	public static class IListExtensions
	{
		public static IList<T> getSublistSafe<T>(this IList<T> list, int startInclusiveIndex, int endInclusiveIndex = -1)
		{
			IList<T> result;
			if (list.Count <= 0)
			{
				IList<T> list2 = new List<T>();
				result = list2;
			}
			else
			{
				result = list.getSublist(startInclusiveIndex, endInclusiveIndex);
			}
			return result;
		}

		public static IList<T> getSublist<T>(this IList<T> list, int startInclusiveIndex, int endInclusiveIndex = -1)
		{
			if (endInclusiveIndex <= -1)
			{
				endInclusiveIndex = list.Count - 1;
			}
			if (endInclusiveIndex >= list.Count)
			{
				throw new ArgumentOutOfRangeException($"End Index is out of bounds of the given list size: [Index: {endInclusiveIndex}, Size: {list.Count}");
			}
			if (startInclusiveIndex >= endInclusiveIndex)
			{
				throw new ArgumentOutOfRangeException($"Start Index is out of bounds of a Lists Rnage: [Start: {startInclusiveIndex}");
			}
			if (startInclusiveIndex < 0)
			{
				throw new ArgumentOutOfRangeException($"End Index is out of bounds of the given list size: [Index: {endInclusiveIndex}, Size: {list.Count}");
			}
			int num = endInclusiveIndex - startInclusiveIndex;
			List<T> list2 = new List<T>(num);
			for (int i = num; i < num; i++)
			{
				list2.Add(list[i]);
			}
			return list2;
		}
	}
	public static class PairedTupleExtensions
	{
		public static L? getLeftOrMapRight<L, R>(this (L?, R?) tuple, Func<R, L?> func)
		{
			var (val, val2) = tuple;
			if (val != null)
			{
				return val;
			}
			if (val2 == null)
			{
				throw new NullReferenceException("Unable to handle Either based tuple method due to the Left and Right values are both Null");
			}
			return func(val2);
		}
	}
	public static class EnumerableExtensions
	{
		public static IEnumerable<TSource> selectNonNull<TSource>(this IEnumerable<TSource?> source)
		{
			return from source1 in source
				where source1 != null
				select (source1);
		}
	}
	public class FileUtils
	{
		public static string? getParentDirectory(string path, int backTrackAmount = 1)
		{
			string path2 = path;
			for (int i = 0; i < backTrackAmount; i++)
			{
				path2 = Path.GetDirectoryName(path2);
			}
			return Path.GetFileName(path2);
		}

		public static void createFileFromBytes(byte[] data, string filePath)
		{
			string filePath2 = filePath;
			if (data.Length == 0 || string.IsNullOrEmpty(filePath2))
			{
				return;
			}
			try
			{
				string directoryName = Path.GetDirectoryName(filePath2);
				if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				File.WriteAllBytes(filePath2, data);
			}
			catch (Exception)
			{
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogError((object)("Unable to create file for the given path: " + filePath2));
				});
			}
		}

		public static async Task<byte[]?> loadDataFromFile(FileLookupHelper helper)
		{
			byte[] value = await loadDataFromFile(helper.getPrimaryPattern());
			if (value == null)
			{
				value = await loadDataFromFile(helper.getSecoundaryPattern());
			}
			return value;
		}

		public static async Task<byte[]?> loadDataFromFile((string directory, string filePattern) tuple)
		{
			return await loadDataFromFile(tuple.directory, tuple.filePattern);
		}

		public static async Task<byte[]?> loadDataFromFile(string directory, string filePattern)
		{
			string directory2 = directory;
			string filePattern2 = filePattern;
			if (!string.IsNullOrEmpty(directory2) && Directory.Exists(directory2) && !string.IsNullOrEmpty(filePattern2))
			{
				try
				{
					string[] files = Directory.GetFiles(directory2, filePattern2);
					if (files.Length != 0)
					{
						string filePath = files[0];
						return await File.ReadAllBytesAsync(filePath);
					}
				}
				catch (Exception ex2)
				{
					Exception ex3 = ex2;
					Exception ex = ex3;
					Plugin.logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogError((object)$"Unable to read file for the given path [{Path.Combine(directory2, filePattern2)}]: {ex}");
					});
				}
			}
			return null;
		}

		public static void deleteOldFiles(string folderPath, int daysOld)
		{
			string folderPath2 = folderPath;
			if (!Directory.Exists(folderPath2))
			{
				return;
			}
			string[] directories = Directory.GetDirectories(folderPath2);
			foreach (string folderPath3 in directories)
			{
				deleteOldFiles(folderPath3, daysOld);
			}
			try
			{
				DateTime dateTime = DateTime.Now.AddDays(-daysOld);
				string[] files = Directory.GetFiles(folderPath2);
				string[] array = files;
				foreach (string filePath in array)
				{
					FileInfo fileInfo = new FileInfo(filePath);
					if (fileInfo.LastAccessTime >= dateTime)
					{
						continue;
					}
					try
					{
						File.Delete(filePath);
						Plugin.logIfDebugging(delegate(ManualLogSource source)
						{
							source.LogError((object)("Deleted the given old cached file: " + filePath));
						});
					}
					catch (Exception ex2)
					{
						Exception ex3 = ex2;
						Exception deleteEx = ex3;
						Plugin.logIfDebugging(delegate(ManualLogSource source)
						{
							source.LogError((object)$"Unable to delete the given old cached file {filePath}: {deleteEx}");
						});
					}
				}
			}
			catch (Exception ex4)
			{
				Exception ex3 = ex4;
				Exception ex = ex3;
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogError((object)$"Unable to process the given temp directory for deletion {folderPath2}: {ex}");
				});
			}
		}
	}
	public class FileLookupHelper
	{
		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string <directory>P;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string <name>P;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string <filePattern>P;

		public FileLookupHelper(string directory, string name, string filePattern)
		{
			<directory>P = directory;
			<name>P = name;
			<filePattern>P = filePattern;
			base..ctor();
		}

		public (string directory, string filePattern) getPrimaryPattern()
		{
			return (<directory>P, <filePattern>P);
		}

		public (string directory, string filePattern) getSecoundaryPattern()
		{
			return (<directory>P, <name>P + ".*");
		}

		public string getFilePath()
		{
			return Path.Combine(<directory>P, <filePattern>P);
		}
	}
	public class HttpClientUtils
	{
		public static HttpClient createClient()
		{
			HttpClient httpClient = new HttpClient();
			httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("RepoTextureSwapper/1.0 (by Blodhgarm on github)");
			return httpClient;
		}

		public static async Task<string?> getContentTypeFromUrlAsync(string url)
		{
			string url2 = url;
			using HttpClient client = createClient();
			try
			{
				HttpResponseMessage response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url2));
				response.EnsureSuccessStatusCode();
				if (response.Content != null && response.Content.Headers != null)
				{
					HttpContent content = response.Content;
					object result;
					if (content == null)
					{
						result = null;
					}
					else
					{
						HttpContentHeaders headers = content.Headers;
						if (headers == null)
						{
							result = null;
						}
						else
						{
							MediaTypeHeaderValue? contentType = headers.ContentType;
							result = ((contentType != null) ? contentType.MediaType.Split("/")[1] : null);
						}
					}
					return (string?)result;
				}
			}
			catch (Exception ex2)
			{
				Exception ex3 = ex2;
				Exception ex = ex3;
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogError((object)$"Unable to get the content type from the URL [{url2}]: {ex}");
				});
			}
			return null;
		}

		public static string getFormatString(string url, int timeOutWindow = 30)
		{
			Task<string> contentTypeFromUrlAsync = getContentTypeFromUrlAsync(url);
			Task task = Task.Delay(timeOutWindow * 1000);
			bool flag = Task.WaitAny(contentTypeFromUrlAsync, task) == 0 && contentTypeFromUrlAsync.IsCompletedSuccessfully;
			string text = null;
			if (flag)
			{
				text = contentTypeFromUrlAsync.Result;
			}
			if (text != null)
			{
				return text;
			}
			return UriUtils.getFormatFromUri(url);
		}

		public static async void iteratePosts<T>(string type, int delayBetweenTask, HttpClient client, ConcurrentQueue<T> entries, Func<HttpClient, T, int, Task> taskCreator, Func<T, string> toURL)
		{
			Func<HttpClient, T, int, Task> taskCreator2 = taskCreator;
			HttpClient client2 = client;
			string type2 = type;
			try
			{
				ConcurrentQueue<Task> tasks = new ConcurrentQueue<Task>();
				while (true)
				{
					if (!entries.TryDequeue(out T entry))
					{
						break;
					}
					string url = toURL(entry);
					tasks.Enqueue(MultiThreadHelper.run(SemaphoreIdentifier.createFromMedia(url), delegate
					{
						taskCreator2(client2, entry, 0);
					}));
					Plugin.logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogInfo((object)("Task for Entry Decode has been created: " + url));
					});
					Thread.Sleep(delayBetweenTask);
				}
				await Task.WhenAll(tasks.ToArray()).ContinueWith(delegate
				{
					Plugin.logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogInfo((object)"Disposing of HTTP Client!");
					});
					client2.Dispose();
				});
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogInfo((object)("Created all " + type2 + " tasks for a given query!"));
				});
			}
			catch (Exception)
			{
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogInfo((object)("Exception when trying to handle " + type2 + " entries for a given query!"));
				});
			}
		}

		public static bool waitOrLog(Task task, int seconds, Func<string> logMsg)
		{
			if (task.Wait(seconds * 1000))
			{
				return false;
			}
			Plugin.Logger.LogError((object)logMsg());
			return true;
		}
	}
	public class Identifier
	{
		public static readonly Endec<Identifier> ENDEC = Endecs.STRING.xmap<Identifier>((Func<string, Identifier>)((string s) => of(s)), (Func<Identifier, string>)((Identifier identifier) => identifier.toStringFormat()));

		public readonly string Namespace;

		public readonly string Path;

		private Identifier(string ns, string path)
		{
			if (!IsValidNamespace(ns))
			{
				throw new ArgumentException("Identifier Namespace is not valid: " + ns);
			}
			if (!IsValidPath(path))
			{
				throw new ArgumentException("Identifier Path is not valid: " + path);
			}
			Namespace = ns;
			Path = path;
		}

		public static Identifier of(string Namespace, string Path)
		{
			return new Identifier(Namespace, Path);
		}

		public static Identifier of(string value)
		{
			if (!IsValidIdentifier(value))
			{
				throw new ArgumentException("Invalid identifier value: " + value);
			}
			string[] array = value.Split(":");
			return new Identifier(array[0], array[1]);
		}

		public static Identifier ofUri(string uri, string unknownHostType = "unknown")
		{
			string @namespace = UriUtils.sanitizeName(UriUtils.getDomain(uri)) ?? unknownHostType;
			string text = UriUtils.sanitizeName(System.IO.Path.GetFileNameWithoutExtension(uri));
			if (text == null)
			{
				throw new NullReferenceException("Unable to handle the given uri to an ID: " + uri);
			}
			return of(@namespace, text);
		}

		public string toStringFormat()
		{
			return Namespace + ":" + Path;
		}

		public override bool Equals(object? obj)
		{
			if (this == obj)
			{
				return true;
			}
			if (obj is Identifier identifier)
			{
				return identifier.Namespace == Namespace && identifier.Path == Path;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (Namespace, Path).GetHashCode();
		}

		public override string ToString()
		{
			return "Identifier(" + toStringFormat() + ")";
		}

		public static bool IsValidIdentifier(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				throw new NullReferenceException("A given string is null and cannot be converted to an Identifier");
			}
			string pattern = "^[^:\\s]+:[^:\\s]+$";
			return Regex.IsMatch(input, pattern);
		}

		public static bool IsValidNamespace(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				throw new NullReferenceException("A given string is null and is not a valid Namespace");
			}
			string pattern = "^[^:\\s]+$";
			return Regex.IsMatch(input, pattern);
		}

		public static bool IsValidPath(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				throw new NullReferenceException("A given string is null and is not a valid Path");
			}
			string pattern = "^[^:\\s]+$";
			return Regex.IsMatch(input, pattern);
		}
	}
	public class ImageUtils
	{
		private class CustomWriteDefines : IWriteDefines, IDefines
		{
			public IEnumerable<IDefine> Defines => new <>z__ReadOnlySingleElementList<IDefine>((IDefine)new MagickDefine("webm:codec", "libvpx"));

			public MagickFormat Format => (MagickFormat)256;
		}

		public static byte[] getInitialFrameOfAnimatedImage(byte[] bytes)
		{
			return convertAnimatedImageToSlices(bytes, onlySingleSlice: true).pngImageSlices[0];
		}

		public static PNGImageSequence convertAnimatedImageToSlices(byte[] bytes, bool onlySingleSlice = false, Identifier? id = null)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			Identifier id2 = id;
			MagickImageCollection val = new MagickImageCollection(bytes);
			try
			{
				val.Coalesce();
				List<byte[]> list = new List<byte[]>(val.Count);
				List<float> list2 = new List<float>();
				for (int i = 0; i < val.Count; i++)
				{
					IMagickImage<byte> val2 = val[i];
					using MemoryStream memoryStream = new MemoryStream();
					if (((IMagickImage)val2).HasAlpha)
					{
						((IMagickImage)val2).Alpha((AlphaOption)13);
					}
					((IMagickImage)val2).Write((Stream)memoryStream, (IWriteDefines)new JpegWriteDefines());
					memoryStream.Position = 0L;
					new ImageOptimizer
					{
						OptimalCompression = true
					}.Compress((Stream)memoryStream);
					memoryStream.Position = 0L;
					if (onlySingleSlice)
					{
						return new PNGImageSequence(new List<byte[]>(1) { memoryStream.ToArray() }, new List<float>(), 0f);
					}
					list.Add(memoryStream.ToArray());
					list2.Add((float)((IMagickImage)val2).AnimationDelay / 100f);
				}
				int sizeOfSequence = list.Select((byte[] pngBytes) => pngBytes.Length).Sum();
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogInfo((object)string.Format("Size of given computed image sequence [{0}] is: {1} mbs", id2?.ToString() ?? "unknown", (float)sizeOfSequence / 1000000f));
				});
				float maxAnimationTime = list2.Sum();
				return new PNGImageSequence(list, list2, maxAnimationTime);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public static byte[]? convertToWebm(Identifier id, byte[] inBytes)
		{
			if (inBytes.Length == 0)
			{
				throw new Exception("Fuck");
			}
			string text = Path.Combine(Plugin.TempVideoStoragePath, id.Namespace, id.Path);
			File.WriteAllBytes(text + ".gif", inBytes);
			Task<bool> task = FFMpegArguments.FromFileInput(new FileInfo(text + ".gif"), (Action<FFMpegArgumentOptions>)delegate(FFMpegArgumentOptions options)
			{
				options.ForceFormat("gif");
			}).OutputToFile(text + ".webm", true, (Action<FFMpegArgumentOptions>)delegate(FFMpegArgumentOptions options)
			{
				options.ForceFormat("webm").WithConstantRateFactor(10).ForcePixelFormat("yuv420p")
					.WithVideoBitrate(2200)
					.WithVideoCodec("libvpx")
					.WithAudioCodec("libvorbis");
			}).ProcessAsynchronously(true, (FFOptions)null);
			task.Wait();
			if (task.Result)
			{
				byte[] result = File.ReadAllBytes(text + ".webm");
				File.Delete(text + ".gif");
				File.Delete(text + ".webm");
				return result;
			}
			return null;
		}
	}
	public class PNGImageSequence
	{
		public List<byte[]> pngImageSlices { get; }

		public List<float> deltaBetweenFrames { get; }

		public float maxAnimationTime { get; }

		public PNGImageSequence(List<byte[]> pngImageSlices, List<float> deltaBetweenFrames, float maxAnimationTime)
		{
			this.pngImageSlices = pngImageSlices;
			this.deltaBetweenFrames = deltaBetweenFrames;
			this.maxAnimationTime = maxAnimationTime;
			base..ctor();
		}

		public List<Texture2D> getMaterials(Identifier id)
		{
			Identifier id2 = id;
			if (!Plugin.isMainThread())
			{
				throw new Exception($"Unable to get materials as its not on main thread! [ID: {id2}]");
			}
			return (from material in pngImageSlices.Select((byte[] bytes, int i) => MaterialUtils.loadTextureFromBytes(bytes, id2, $"_{i}"))
				where material != null
				select material).ToList();
		}

		public TextureSequence convertToMaterialSequence(Identifier id)
		{
			List<Texture2D> materials = getMaterials(id);
			return new TextureSequence(materials, deltaBetweenFrames, maxAnimationTime);
		}
	}
	public class TextureSequence
	{
		public List<Texture2D> imageSlices { get; }

		public List<float> deltaBetweenFrames { get; }

		public float maxAnimationTime { get; }

		public TextureSequence(List<Texture2D> imageSlices, List<float> deltaBetweenFrames, float maxAnimationTime)
		{
			this.imageSlices = imageSlices;
			this.deltaBetweenFrames = deltaBetweenFrames;
			this.maxAnimationTime = maxAnimationTime;
			base..ctor();
		}

		public void invalidateTextures()
		{
			foreach (Texture2D imageSlice in imageSlices)
			{
				MaterialUtils.invalidateTexture((Texture)(object)imageSlice);
			}
		}
	}
	public static class MainThreadHelper
	{
		private static readonly ConcurrentStack<Action> MAIN_THREAD_ACTIONS = new ConcurrentStack<Action>();

		internal static void handleActionsOnMainThread()
		{
			if (!Plugin.isMainThread() || MAIN_THREAD_ACTIONS.IsEmpty)
			{
				return;
			}
			int num = Math.Min(25, MAIN_THREAD_ACTIONS.Count);
			Action[] array = new Action[num];
			MAIN_THREAD_ACTIONS.TryPopRange(array, 0, num);
			Action[] array2 = array;
			foreach (Action action in array2)
			{
				try
				{
					action();
				}
				catch (Exception ex)
				{
					Exception ex2 = ex;
					Exception e = ex2;
					Plugin.logIfDebugging(delegate(ManualLogSource source)
					{
						source.LogError((object)"Unable handle a given enqueued action on the main thread due to it throwing an exception!");
						source.LogError((object)e);
					});
				}
			}
		}

		public static void runOnMainThread(Action action)
		{
			if (Plugin.isMainThread())
			{
				action();
			}
			else
			{
				MAIN_THREAD_ACTIONS.Push(action);
			}
		}
	}
	public class MaterialUtils
	{
		public static Texture2D? loadTextureFromBytes(byte[] fileData, Identifier id, string postFix = "")
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			Identifier id2 = id;
			string postFix2 = postFix;
			if (!Plugin.isMainThread())
			{
				throw new Exception($"Unable to load texture from bytes as it was being performed off thread! [Id: {id2}]");
			}
			Texture2D val = new Texture2D(2, 2);
			bool flag = false;
			if (fileData != null && fileData.Length != 0)
			{
				flag = ImageConversion.LoadImage(val, fileData);
			}
			if (flag)
			{
				val.Apply();
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogInfo((object)$"Texture created from image: {id2}{postFix2}");
				});
				return val;
			}
			Plugin.logIfDebugging(delegate(ManualLogSource source)
			{
				source.LogError((object)$"Unable to load the given image: {id2}{postFix2}");
			});
			return null;
		}

		public static Material? loadMaterialFromBytes(RawMediaData rawMediaData)
		{
			return loadMaterialFromBytes(rawMediaData.getBytes(), rawMediaData.id);
		}

		public static Material? loadMaterialFromBytes(byte[] fileData, Identifier id, string postFix = "")
		{
			if (!Plugin.isMainThread())
			{
				throw new Exception($"Unable to load texture from bytes as it was being performed off thread! [Id: {id}]");
			}
			Texture2D val = loadTextureFromBytes(fileData, id, postFix);
			return (val == null) ? null : createMaterial(val, id, postFix);
		}

		public static Material createMaterial(Texture2D? texture, Identifier id, string postFix = "")
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			Identifier id2 = id;
			string postFix2 = postFix;
			if (!Plugin.isMainThread())
			{
				throw new Exception($"Unable to load texture from bytes as it was being performed off thread! [Id: {id2}]");
			}
			Plugin.logIfDebugging(delegate(ManualLogSource source)
			{
				source.LogInfo((object)$"Image loaded and Material created: {id2}{postFix2}");
			});
			Material val = new Material(Shader.Find("Standard"));
			if (texture != null)
			{
				val.mainTexture = (Texture)(object)texture;
			}
			return val;
		}

		public static void invalidateMaterial(Material material)
		{
			if (!Plugin.isMainThread())
			{
				throw new Exception("Unable to load texture from bytes as it was being performed off thread!");
			}
			Texture mainTexture = material.mainTexture;
			invalidateTexture(mainTexture);
			if (!UnityObjectUtility.IsDestroyed((Object)(object)material))
			{
				Object.Destroy((Object)(object)material);
			}
		}

		public static void invalidateTexture(Texture texture)
		{
			if (!Plugin.isMainThread())
			{
				throw new Exception("Unable to load texture from bytes as it was being performed off thread!");
			}
			if (!UnityObjectUtility.IsDestroyed((Object)(object)texture))
			{
				Object.Destroy((Object)(object)texture);
			}
		}
	}
	public class MultiThreadHelper
	{
		public static readonly SemaphoreIdentifier DEFAULT_GROUP = new SemaphoreIdentifier(Identifier.of("texture_swapper", "default"), 1);

		public static readonly MultiThreadHelper INSTANCE = new MultiThreadHelper(1);

		private readonly Dictionary<SemaphoreIdentifier, SemaphoreSlim> ID_TO_SEMAPHORE = new Dictionary<SemaphoreIdentifier, SemaphoreSlim>();

		private static bool shouldPrintDebugInfo()
		{
			return false;
		}

		public MultiThreadHelper(int defaultMaxConcurrency)
		{
			ID_TO_SEMAPHORE[DEFAULT_GROUP] = new SemaphoreSlim(defaultMaxConcurrency, defaultMaxConcurrency);
		}

		public static Task run(Action action)
		{
			return run(DEFAULT_GROUP, action);
		}

		public static Task run(SemaphoreIdentifier id, Action action)
		{
			return INSTANCE.runAndExecuteAsync(id, action);
		}

		public Task runAndExecuteAsync(SemaphoreIdentifier id, Action action)
		{
			Action action2 = action;
			SemaphoreSlim semaphore = ID_TO_SEMAPHORE.computeIfAbsent(id, (SemaphoreIdentifier id1) => id1.createSemaphore());
			return Task.Run(async delegate
			{
				await executeAsync(semaphore, delegate
				{
					action2();
					return Task.CompletedTask;
				});
			});
		}

		public static async Task executeAsync(SemaphoreSlim semaphore, Func<Task> taskDelegate)
		{
			Plugin.logIfDebugging(delegate(ManualLogSource source)
			{
				source.LogInfo((object)"Going to check flag barrier");
			}, shouldPrintDebugInfo);
			await semaphore.WaitAsync();
			Plugin.logIfDebugging(delegate(ManualLogSource source)
			{
				source.LogInfo((object)"Starting Task");
			}, shouldPrintDebugInfo);
			try
			{
				await taskDelegate();
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogInfo((object)"Task Has been finished");
				}, shouldPrintDebugInfo);
			}
			finally
			{
				semaphore.Release();
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogInfo((object)"Permit has been released");
				}, shouldPrintDebugInfo);
			}
		}

		public static async Task<TResult> executeAsync<TResult>(SemaphoreSlim semaphore, Func<Task<TResult>> taskDelegate)
		{
			Plugin.logIfDebugging(delegate(ManualLogSource source)
			{
				source.LogInfo((object)"Going to check flag barrier");
			}, shouldPrintDebugInfo);
			await semaphore.WaitAsync();
			Plugin.logIfDebugging(delegate(ManualLogSource source)
			{
				source.LogInfo((object)"Starting Task");
			}, shouldPrintDebugInfo);
			try
			{
				return await taskDelegate();
			}
			finally
			{
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogInfo((object)"Task Has been finished");
				}, shouldPrintDebugInfo);
				semaphore.Release();
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogInfo((object)"Permit has been released");
				}, shouldPrintDebugInfo);
			}
		}
	}
	public class SemaphoreIdentifier
	{
		public readonly Identifier identifier;

		private readonly int initialCount;

		private readonly int maxCount;

		public SemaphoreIdentifier(Identifier identifier, int maxCount = 5, int initialCount = -1)
		{
			this.identifier = identifier;
			this.maxCount = maxCount;
			this.initialCount = ((initialCount == -1) ? maxCount : initialCount);
		}

		public SemaphoreSlim createSemaphore()
		{
			return new SemaphoreSlim(initialCount, maxCount);
		}

		public static SemaphoreIdentifier createFromMedia(string url)
		{
			Identifier identifier = Identifier.ofUri(url);
			return new SemaphoreIdentifier(Identifier.of("texture_swapper", identifier.Namespace), 4);
		}

		protected bool Equals(SemaphoreIdentifier other)
		{
			return identifier.Equals(other.identifier);
		}

		public override bool Equals(object? obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (this == obj)
			{
				return true;
			}
			if (obj.GetType() != GetType())
			{
				return false;
			}
			return Equals((SemaphoreIdentifier)obj);
		}

		public override int GetHashCode()
		{
			return identifier.GetHashCode();
		}
	}
	public class RegexUtils
	{
		public static Regex parseRegexWithFlags(string regexStringWithFlags)
		{
			Regex regex = new Regex("(\".*\")");
			Match match = regex.Match(regexStringWithFlags);
			if (!match.Success)
			{
				return new Regex(regexStringWithFlags);
			}
			string value = match.Value;
			string text = regexStringWithFlags.Replace(value, "");
			RegexOptions regexOptions = RegexOptions.None;
			if (text.Contains("i"))
			{
				regexOptions |= RegexOptions.IgnoreCase;
			}
			if (text.Contains("m"))
			{
				regexOptions |= RegexOptions.Multiline;
			}
			return new Regex(value.TrimStart('"').TrimEnd('"'), regexOptions);
		}
	}
	public class SwapperPluginInfo
	{
		public const string PLUGIN_GUID = "TextureSwapper";

		public const string PLUGIN_NAME = "Texture Swapper";

		public const string PLUGIN_VERSION = "1.1.7";
	}
	public class UriUtils
	{
		public static Uri? getURI(string url)
		{
			if (!string.IsNullOrEmpty(url))
			{
				try
				{
					return new Uri(url);
				}
				catch (UriFormatException)
				{
					if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
					{
						try
						{
							return new Uri("https://" + url);
						}
						catch (UriFormatException)
						{
						}
					}
				}
			}
			return null;
		}

		public static string? getDomain(string url)
		{
			return getURI(url)?.Host;
		}

		public static string getFormatFromUri(string url)
		{
			Uri? uRI = getURI(url);
			object obj;
			if ((object)uRI == null)
			{
				obj = null;
			}
			else
			{
				string pathAndQuery = uRI.PathAndQuery;
				if (pathAndQuery == null)
				{
					obj = null;
				}
				else
				{
					string[] array = pathAndQuery.Split("?");
					obj = ((array != null) ? array[0] : null);
				}
			}
			if (obj == null)
			{
				obj = url;
			}
			string path = (string)obj;
			return Path.GetExtension(path).Replace(".", "");
		}

		public static string? sanitizeName(string? hostname)
		{
			if (string.IsNullOrEmpty(hostname))
			{
				return null;
			}
			string text = Regex.Replace(hostname, "[^a-zA-Z0-9_\\-\\.]", "_");
			int num = 255;
			if (text.Length > num)
			{
				text = text.Substring(0, num);
			}
			string[] array = new string[22]
			{
				"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6",
				"COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7",
				"LPT8", "LPT9"
			};
			if (Array.IndexOf(array, text.ToUpper()) >= 0)
			{
				text = "_" + text;
			}
			return text;
		}
	}
}
namespace io.wispforest.textureswapper.api
{
	public static class MediaFormats
	{
		public static readonly Endec<MediaFormat> FORMAT_ENDEC;

		private static readonly Dictionary<string, MediaFormat> VALID_MEDIA_TYPES;

		private static readonly Dictionary<string, MagickFormat> ENUM_MAP;

		public static MediaType getType(string uri)
		{
			string formatFromUri = UriUtils.getFormatFromUri(uri);
			return getFormat(formatFromUri).getType();
		}

		public static MediaFormat getAFormat(params string[] names)
		{
			foreach (string name in names)
			{
				MediaFormat format = getFormat(name);
				if (!(format is UnimplementedMediaFormat))
				{
					return format;
				}
			}
			return new UnimplementedMediaFormat(names);
		}

		public static MediaFormat getFormatFromUrl(string url)
		{
			string locatedFormat = HttpClientUtils.getFormatString(url);
			Plugin.logIfDebugging(delegate(ManualLogSource source)
			{
				source.LogInfo((object)("URL format is: " + locatedFormat));
			});
			return getFormat(locatedFormat);
		}

		public static MediaFormat getFormat(string name)
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			if (ENUM_MAP.Count <= 0)
			{
				Type typeFromHandle = typeof(MagickFormat);
				Array values = Enum.GetValues(typeFromHandle);
				foreach (object item in values)
				{
					if (item != null && item is MagickFormat val)
					{
						ENUM_MAP[Enum.GetName(typeFromHandle, val).ToLower()] = val;
					}
				}
			}
			MagickFormat value;
			return ENUM_MAP.TryGetValue(name, out value) ? getFormat(value) : new UnimplementedMediaFormat(name);
		}

		public static MediaFormat getFormat(MagickFormat format)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			foreach (MediaFormat value in VALID_MEDIA_TYPES.Values)
			{
				if (value.getFormats().Contains(format))
				{
					return value;
				}
			}
			return new UnimplementedMediaFormat(format);
		}

		public static void registerFormat(MediaFormat format)
		{
			if (!VALID_MEDIA_TYPES.ContainsKey(format.name()))
			{
				VALID_MEDIA_TYPES[format.name()] = format;
			}
		}

		public static List<string> getValidMediaPatterns()
		{
			return VALID_MEDIA_TYPES.Values.SelectMany((MediaFormat type) => type.filePatterns()).ToList();
		}

		static MediaFormats()
		{
			FORMAT_ENDEC = Endecs.STRING.xmap<MediaFormat>((Func<string, MediaFormat>)((string s) => getFormat(s)), (Func<MediaFormat, string>)((MediaFormat type) => type.name()));
			VALID_MEDIA_TYPES = new Dictionary<string, MediaFormat>();
			ENUM_MAP = new Dictionary<string, MagickFormat>();
			registerFormat(PNG.INSTANCE);
			registerFormat(JPEG.INSTANCE);
			registerFormat(BMP.INSTANCE);
			registerFormat(TIFF.INSTANCE);
			registerFormat(PSD.INSTANCE);
			registerFormat(SVG.INSTANCE);
			registerFormat(WEBP.INSTANCE);
			registerFormat(GIF.INSTANCE);
			registerFormat(WEBM.INSTANCE);
			registerFormat(MP4.INSTANCE);
			registerFormat(MP3.INSTANCE);
		}
	}
	public class MP3 : MediaFormat
	{
		public static readonly MP3 INSTANCE = new MP3();

		public override string name()
		{
			return "mp3";
		}

		public override string primaryExtension()
		{
			return "mp3";
		}

		public override List<string> additionalExtensions()
		{
			return new List<string>();
		}

		public override MediaType getType()
		{
			return MediaType.AUDIO;
		}

		public override ISet<MagickFormat> getFormats()
		{
			return (ISet<MagickFormat>)new ReadOnlySet<MagickFormat>(Array.Empty<MagickFormat>());
		}

		public override SwapperImpl? decodeData(Identifier id, RawMediaData data)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			RawMediaData data2 = data;
			try
			{
				using MemoryStream memoryStream = new MemoryStream(data2.getBytes());
				Mp3FileReader val = new Mp3FileReader((Stream)memoryStream);
				try
				{
					WaveStream val2 = WaveFormatConversionStream.CreatePcmStream((WaveStream)(object)val);
					try
					{
						byte[] array = new byte[((Stream)(object)val2).Length];
						((Stream)(object)val2).Read(array, 0, (int)((Stream)(object)val2).Length);
						float[] array2 = new float[array.Length / 4];
						Buffer.BlockCopy(array, 0, array2, 0, array.Length);
						AudioClip val3 = AudioClip.Create(data2.id.Path, array2.Length / val2.WaveFormat.Channels, val2.WaveFormat.Channels, val2.WaveFormat.SampleRate, false);
						val3.SetData(array2, 0);
						return new AudioSwapper(id, val3);
					}
					finally
					{
						((IDisposable)val2)?.Dispose();
					}
				}
				finally
				{
					((IDisposable)val)?.Dispose();
				}
			}
			catch (Exception ex2)
			{
				Exception ex3 = ex2;
				Exception ex = ex3;
				Plugin.logIfDebugging(delegate(ManualLogSource source)
				{
					source.LogError((object)("MP3 threw a magic exception [" + data2.url + "]: " + ex.Message));
				});
				Debug.LogError((object)("Error creating AudioClip from MP3 bytes: " + ex.Message));
				return null;
			}
		}
	}
	public class PNG : MediaFormat
	{
		public static readonly PNG INSTANCE = new PNG();

		public override string name()
		{
			return "png";
		}

		public override string primaryExtension()
		{
			return "png";
		}

		public override List<string> additionalExtensions()
		{
			return new List<string>();
		}

		public override MediaType getType()
		{
			return MediaType.IMAGE;
		}

		public override ISet<MagickFormat> getFormats()
		{
			MagickFormat[] array = new MagickFormat[7];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			return (ISet<MagickFormat>)new ReadOnlySet<MagickFormat>((MagickFormat[])(object)array);
		}

		public override SwapperImpl? decodeData(Identifier id, RawMediaData data)
		{
			data.attemptToCacheFile();
			Material val = MaterialUtils.loadMaterialFromBytes(data);
			return (val != null) ? new MaterialSwapper(id, val) : null;
		}
	}
	public class WEBP : MediaFormat
	{
		public static readonly WEBP INSTANCE = new WEBP();

		public override string name()
		{
			return "webp";
		}

		public override string primaryExtension()
		{
			return "webp";
		}

		public override List<string> additionalExtensions()
		{
			return new List<string>();
		}

		public override MediaType getType()
		{
			return MediaType.IMAGE;
		}

		public override ISet<MagickFormat> getFormats()
		{
			return (ISet<MagickFormat>)new ReadOnlySet<MagickFormat>((MagickFormat[])(object)new MagickFormat[1] { (MagickFormat)260 });
		}

		public override SwapperImpl? decodeData(Identifier id, RawMediaData data)
		{
			RawMediaData data2 = data;
			Identifier id2 = id;
			MultiThreadHelper.run(MediaFormat.ENCODING_GROUP, delegate
			{
				bool hasCachedFile = data2.attemptToCacheFile(delegate(byte[] bytes)
				{
					//IL_0051: Expected O, but got Unknown
					//IL_0003: Unknown result type (might be due to invalid IL or missing references)
					//IL_0009: Expected O, but got Unknown
					try
					{
						MagickImage val2 = new MagickImage(bytes);
						try
						{
							val2.Format = (MagickFormat)185;
							using MemoryStream memoryStream = new MemoryStream();
							val2.Write((Stream)memoryStream);
							return memoryStream.ToArray();
						}
						finally
						{
							((IDisposable)val2)?.Dispose();
						}
					}
					catch (MagickException val3)
					{
						MagickException val4 = val3;
						MagickException ex = val4;
						Plugin.logIfDebugging(delegate(ManualLogSource source)
						{
							source.LogError((object)("WEBP threw a magic exception [" + data2.url + "]: " + ((Exception)(object)ex).Message));
						});
						return null;
					}
				});
				MainThreadHelper.runOnMainThread(delegate
				{
					SwapperImpl handler = null;
					if (hasCachedFile)
					{
						Material val = MaterialUtils.loadMaterialFromBytes(data2.getBytes(), id2);
						handler = ((val != null) ? new MaterialSwapper(id2, val) : null);
					}
					MediaSwapperStorage.storeHandler(id2, data2.mediaInfo, handler);
				});
			});
			return new DelayedMeshSwapper(id2, multiple: true);
		}
	}
	public class SVG : MediaFormat
	{
		public static readonly SVG INSTANCE = new SVG();

		public override string name()
		{
			return "svg";
		}

		public override string primaryExtension()
		{
			return "svg";
		}

		public override List<string> additionalExtensions()
		{
			return new List<string>();
		}

		public override MediaType getType()
		{
			return MediaType.IMAGE;
		}

		public override ISet<MagickFormat> getFormats()
		{
			return (ISet<MagickFormat>)new ReadOnlySet<MagickFormat>((MagickFormat[])(object)new MagickFormat[1] { (MagickFormat)235 });
		}

		public override SwapperImpl? decodeData(Identifier id, RawMediaData data)
		{
			RawMediaData data2 = data;
			Identifier id2 = id;
			MultiThreadHelper.run(MediaFormat.ENCODING_GROUP, delegate
			{
				bool hasCachedFile = data2.attemptToCacheFile(delegate(byte[] bytes)
				{
					//IL_0051: Expected O, but got Unknown
					//IL_0003: Unknown result type (might be due to invalid IL or missing references)
					//IL_0009: Expected O, but got Unknown
					try
					{
						MagickImage val2 = new MagickImage(bytes);
						try
						{
							val2.Format = (MagickFormat)185;
							using MemoryStream memoryStream = new MemoryStream();
							val2.Write((Stream)memoryStream);
							return memoryStream.ToArray();
						}
						finally
						{
							((IDisposable)val2)?.Dispose();
						}
					}
					catch (MagickException val3)
					{
						MagickException val4 = val3;
						MagickException ex = val4;
						Plugin.logIfDebugging(delegate(ManualLogSource source)
						{
							source.LogError((object)("SVG threw a magic exception [" + data2.url + "]: " + ((Exception)(object)ex).Message));
						});
						return null;
					}
				});
				MainThreadHelper.runOnMainThread(delegate
				{
					SwapperImpl handler = null;
					if (hasCachedFile)
					{
						Material val = MaterialUtils.loadMaterialFromBytes(data2.getBytes(), id2);
						handler = ((val != null) ? new MaterialSwapper(id2, val) : null);
					}
					MediaSwapperStorage.storeHandler(id2, data2.mediaInfo, handler);
				});
			});
			return new DelayedMeshSwapper(id2, multiple: true);
		}
	}
	public class BMP : MediaFormat
	{
		public static readonly BMP INSTANCE = new BMP();

		public override string name()
		{
			return "bmp";
		}

		public override string primaryExtension()
		{
			return "bmp";
		}

		public override List<string> additionalExtensions()
		{
			return new List<string>();
		}

		public override MediaType getType()
		{
			return MediaType.IMAGE;
		}

		public override ISet<MagickFormat> getFormats()
		{
			return (IS

FFMpegCore.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using FFMpegCore.Arguments;
using FFMpegCore.Builders.MetaData;
using FFMpegCore.Enums;
using FFMpegCore.Exceptions;
using FFMpegCore.Extend;
using FFMpegCore.Helpers;
using FFMpegCore.Pipes;
using Instances;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("FFMpegCore.Test")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Malte Rosenbjerg, Vlad Jerca, Max Bagryantsev")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A .NET Standard FFMpeg/FFProbe wrapper for easily integrating media analysis and conversion into your .NET applications")]
[assembly: AssemblyFileVersion("5.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+6f1a8d77d75646a344850744717cd170e0fe8cfc")]
[assembly: AssemblyProduct("FFMpegCore")]
[assembly: AssemblyTitle("FFMpegCore")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/rosenbjerg/FFMpegCore")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("5.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 FFMpegCore
{
	public static class FFMpeg
	{
		public static bool Snapshot(string input, string output, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null, int inputFileIndex = 0)
		{
			if (Path.GetExtension(output) != FileExtension.Png)
			{
				output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Png);
			}
			IMediaAnalysis source = FFProbe.Analyse(input);
			var (fFMpegArguments, addArguments) = SnapshotArgumentBuilder.BuildSnapshotArguments(input, source, size, captureTime, streamIndex, inputFileIndex);
			return fFMpegArguments.OutputToFile(output, overwrite: true, addArguments).ProcessSynchronously();
		}

		public static async Task<bool> SnapshotAsync(string input, string output, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null, int inputFileIndex = 0)
		{
			if (Path.GetExtension(output) != FileExtension.Png)
			{
				output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Png);
			}
			var (fFMpegArguments, addArguments) = SnapshotArgumentBuilder.BuildSnapshotArguments(input, await FFProbe.AnalyseAsync(input).ConfigureAwait(continueOnCapturedContext: false), size, captureTime, streamIndex, inputFileIndex);
			return await fFMpegArguments.OutputToFile(output, overwrite: true, addArguments).ProcessAsynchronously();
		}

		public static bool GifSnapshot(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null, int? streamIndex = null)
		{
			if (Path.GetExtension(output)?.ToLower() != FileExtension.Gif)
			{
				output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Gif);
			}
			IMediaAnalysis source = FFProbe.Analyse(input);
			var (fFMpegArguments, addArguments) = SnapshotArgumentBuilder.BuildGifSnapshotArguments(input, source, size, captureTime, duration, streamIndex);
			return fFMpegArguments.OutputToFile(output, overwrite: true, addArguments).ProcessSynchronously();
		}

		public static async Task<bool> GifSnapshotAsync(string input, string output, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null, int? streamIndex = null)
		{
			if (Path.GetExtension(output)?.ToLower() != FileExtension.Gif)
			{
				output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output) + FileExtension.Gif);
			}
			var (fFMpegArguments, addArguments) = SnapshotArgumentBuilder.BuildGifSnapshotArguments(input, await FFProbe.AnalyseAsync(input).ConfigureAwait(continueOnCapturedContext: false), size, captureTime, duration, streamIndex);
			return await fFMpegArguments.OutputToFile(output, overwrite: true, addArguments).ProcessAsynchronously();
		}

		public static bool JoinImageSequence(string output, double frameRate = 30.0, params string[] images)
		{
			string?[] array = images.Select(Path.GetExtension).Distinct().ToArray();
			if (array.Length != 1)
			{
				throw new ArgumentException("All images must have the same extension", "images");
			}
			string text = array[0].ToLowerInvariant();
			int? width = null;
			int? height = null;
			string text2 = Path.Combine(GlobalFFOptions.Current.TemporaryFilesFolder, Guid.NewGuid().ToString());
			Directory.CreateDirectory(text2);
			try
			{
				int num = 0;
				foreach (string obj in images)
				{
					IMediaAnalysis mediaAnalysis = FFProbe.Analyse(obj);
					FFMpegHelper.ConversionSizeExceptionCheck(mediaAnalysis.PrimaryVideoStream.Width, mediaAnalysis.PrimaryVideoStream.Height);
					int valueOrDefault = width.GetValueOrDefault();
					if (!width.HasValue)
					{
						valueOrDefault = mediaAnalysis.PrimaryVideoStream.Width;
						width = valueOrDefault;
					}
					valueOrDefault = height.GetValueOrDefault();
					if (!height.HasValue)
					{
						valueOrDefault = mediaAnalysis.PrimaryVideoStream.Height;
						height = valueOrDefault;
					}
					string destFileName = Path.Combine(text2, num++.ToString().PadLeft(9, '0') + text);
					File.Copy(obj, destFileName);
				}
				return FFMpegArguments.FromFileInput(Path.Combine(text2, "%09d" + text), verifyExists: false).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
				{
					options.ForcePixelFormat("yuv420p").Resize(width.Value, height.Value).WithFramerate(frameRate);
				}).ProcessSynchronously();
			}
			finally
			{
				Directory.Delete(text2, recursive: true);
			}
		}

		public static bool PosterWithAudio(string image, string audio, string output)
		{
			FFMpegHelper.ExtensionExceptionCheck(output, FileExtension.Mp4);
			IMediaAnalysis mediaAnalysis = FFProbe.Analyse(image);
			FFMpegHelper.ConversionSizeExceptionCheck(mediaAnalysis.PrimaryVideoStream.Width, mediaAnalysis.PrimaryVideoStream.Height);
			return FFMpegArguments.FromFileInput(image, verifyExists: false, delegate(FFMpegArgumentOptions options)
			{
				options.Loop(1).ForceFormat("image2");
			}).AddFileInput(audio).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
			{
				options.ForcePixelFormat("yuv420p").WithVideoCodec(VideoCodec.LibX264).WithConstantRateFactor(21)
					.WithAudioBitrate(AudioQuality.Normal)
					.UsingShortest();
			})
				.ProcessSynchronously();
		}

		public static bool Convert(string input, string output, ContainerFormat format, Speed speed = Speed.SuperFast, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithreaded = false)
		{
			FFMpegHelper.ExtensionExceptionCheck(output, format.Extension);
			IMediaAnalysis mediaAnalysis = FFProbe.Analyse(input);
			FFMpegHelper.ConversionSizeExceptionCheck(mediaAnalysis);
			double num = ((VideoSize.Original == size) ? 1.0 : ((double)mediaAnalysis.PrimaryVideoStream.Height / (double)size));
			Size outputSize = new Size((int)((double)mediaAnalysis.PrimaryVideoStream.Width / num), (int)((double)mediaAnalysis.PrimaryVideoStream.Height / num));
			if (outputSize.Width % 2 != 0)
			{
				outputSize.Width++;
			}
			return format.Name switch
			{
				"mp4" => FFMpegArguments.FromFileInput(input).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
				{
					options.UsingMultithreading(multithreaded).WithVideoCodec(VideoCodec.LibX264).WithVideoBitrate(2400)
						.WithVideoFilters(delegate(VideoFilterOptions filterOptions)
						{
							filterOptions.Scale(outputSize);
						})
						.WithSpeedPreset(speed)
						.WithAudioCodec(AudioCodec.Aac)
						.WithAudioBitrate(audioQuality);
				}).ProcessSynchronously(), 
				"ogv" => FFMpegArguments.FromFileInput(input).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
				{
					options.UsingMultithreading(multithreaded).WithVideoCodec(VideoCodec.LibTheora).WithVideoBitrate(2400)
						.WithVideoFilters(delegate(VideoFilterOptions filterOptions)
						{
							filterOptions.Scale(outputSize);
						})
						.WithSpeedPreset(speed)
						.WithAudioCodec(AudioCodec.LibVorbis)
						.WithAudioBitrate(audioQuality);
				}).ProcessSynchronously(), 
				"mpegts" => FFMpegArguments.FromFileInput(input).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
				{
					options.CopyChannel().WithBitStreamFilter(Channel.Video, Filter.H264_Mp4ToAnnexB).ForceFormat(VideoType.Ts);
				}).ProcessSynchronously(), 
				"webm" => FFMpegArguments.FromFileInput(input).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
				{
					options.UsingMultithreading(multithreaded).WithVideoCodec(VideoCodec.LibVpx).WithVideoBitrate(2400)
						.WithVideoFilters(delegate(VideoFilterOptions filterOptions)
						{
							filterOptions.Scale(outputSize);
						})
						.WithSpeedPreset(speed)
						.WithAudioCodec(AudioCodec.LibVorbis)
						.WithAudioBitrate(audioQuality);
				}).ProcessSynchronously(), 
				_ => throw new ArgumentOutOfRangeException("format"), 
			};
		}

		public static bool Join(string output, params string[] videos)
		{
			string[] array = videos.Select(delegate(string videoPath)
			{
				FFMpegHelper.ConversionSizeExceptionCheck(FFProbe.Analyse(videoPath));
				string text = Path.Combine(GlobalFFOptions.Current.TemporaryFilesFolder, Path.GetFileNameWithoutExtension(videoPath) + FileExtension.Ts);
				Directory.CreateDirectory(GlobalFFOptions.Current.TemporaryFilesFolder);
				Convert(videoPath, text, VideoType.Ts);
				return text;
			}).ToArray();
			try
			{
				return FFMpegArguments.FromConcatInput(array).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
				{
					options.CopyChannel().WithBitStreamFilter(Channel.Audio, Filter.Aac_AdtstoAsc);
				}).ProcessSynchronously();
			}
			finally
			{
				Cleanup(array);
			}
		}

		private static FFMpegArgumentProcessor BaseSubVideo(string input, string output, TimeSpan startTime, TimeSpan endTime)
		{
			if (Path.GetExtension(input) != Path.GetExtension(output))
			{
				output = Path.Combine(Path.GetDirectoryName(output), Path.GetFileNameWithoutExtension(output), Path.GetExtension(input));
			}
			return FFMpegArguments.FromFileInput(input, verifyExists: true, delegate(FFMpegArgumentOptions options)
			{
				options.Seek(startTime).EndSeek(endTime);
			}).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
			{
				options.CopyChannel();
			});
		}

		public static bool SubVideo(string input, string output, TimeSpan startTime, TimeSpan endTime)
		{
			return BaseSubVideo(input, output, startTime, endTime).ProcessSynchronously();
		}

		public static async Task<bool> SubVideoAsync(string input, string output, TimeSpan startTime, TimeSpan endTime)
		{
			return await BaseSubVideo(input, output, startTime, endTime).ProcessAsynchronously();
		}

		public static bool SaveM3U8Stream(Uri uri, string output)
		{
			FFMpegHelper.ExtensionExceptionCheck(output, FileExtension.Mp4);
			if (uri.Scheme != "http" && uri.Scheme != "https")
			{
				throw new ArgumentException("Uri: " + uri.AbsoluteUri + ", does not point to a valid http(s) stream.");
			}
			return FFMpegArguments.FromUrlInput(uri, delegate(FFMpegArgumentOptions options)
			{
				options.WithCopyCodec();
			}).OutputToFile(output).ProcessSynchronously();
		}

		public static bool Mute(string input, string output)
		{
			FFMpegHelper.ConversionSizeExceptionCheck(FFProbe.Analyse(input));
			return FFMpegArguments.FromFileInput(input).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
			{
				options.CopyChannel(Channel.Video).DisableChannel(Channel.Audio);
			}).ProcessSynchronously();
		}

		public static bool ExtractAudio(string input, string output)
		{
			FFMpegHelper.ExtensionExceptionCheck(output, FileExtension.Mp3);
			return FFMpegArguments.FromFileInput(input).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
			{
				options.DisableChannel(Channel.Video);
			}).ProcessSynchronously();
		}

		public static bool ReplaceAudio(string input, string inputAudio, string output, bool stopAtShortest = false)
		{
			FFMpegHelper.ConversionSizeExceptionCheck(FFProbe.Analyse(input));
			return FFMpegArguments.FromFileInput(input).AddFileInput(inputAudio).OutputToFile(output, overwrite: true, delegate(FFMpegArgumentOptions options)
			{
				options.CopyChannel().WithAudioCodec(AudioCodec.Aac).WithAudioBitrate(AudioQuality.Good)
					.UsingShortest(stopAtShortest);
			})
				.ProcessSynchronously();
		}

		internal static IReadOnlyList<PixelFormat> GetPixelFormatsInternal()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			FFMpegHelper.RootExceptionCheck();
			List<PixelFormat> list = new List<PixelFormat>();
			ProcessArguments val = new ProcessArguments(GlobalFFOptions.GetFFMpegBinaryPath(), "-pix_fmts");
			val.OutputDataReceived += delegate(object e, string data)
			{
				if (PixelFormat.TryParse(data, out PixelFormat fmt))
				{
					list.Add(fmt);
				}
			};
			IProcessResult val2 = ProcessArgumentsExtensions.StartAndWaitForExit(val);
			if (val2.ExitCode != 0)
			{
				throw new FFMpegException(FFMpegExceptionType.Process, string.Join("\r\n", val2.OutputData));
			}
			return list.AsReadOnly();
		}

		public static IReadOnlyList<PixelFormat> GetPixelFormats()
		{
			if (!GlobalFFOptions.Current.UseCache)
			{
				return GetPixelFormatsInternal();
			}
			return FFMpegCache.PixelFormats.Values.ToList().AsReadOnly();
		}

		public static bool TryGetPixelFormat(string name, out PixelFormat format)
		{
			string name2 = name;
			if (!GlobalFFOptions.Current.UseCache)
			{
				format = GetPixelFormatsInternal().FirstOrDefault((PixelFormat x) => x.Name == name2.ToLowerInvariant().Trim());
				return format != null;
			}
			return FFMpegCache.PixelFormats.TryGetValue(name2, out format);
		}

		public static PixelFormat GetPixelFormat(string name)
		{
			if (TryGetPixelFormat(name, out PixelFormat format))
			{
				return format;
			}
			throw new FFMpegException(FFMpegExceptionType.Operation, "Pixel format \"" + name + "\" not supported");
		}

		private static void ParsePartOfCodecs(Dictionary<string, Codec> codecs, string arguments, Func<string, Codec?> parser)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			Func<string, Codec?> parser2 = parser;
			Dictionary<string, Codec> codecs2 = codecs;
			FFMpegHelper.RootExceptionCheck();
			ProcessArguments val = new ProcessArguments(GlobalFFOptions.GetFFMpegBinaryPath(), arguments);
			val.OutputDataReceived += delegate(object e, string data)
			{
				Codec codec = parser2(data);
				if (codec != null)
				{
					if (codecs2.TryGetValue(codec.Name, out Codec value))
					{
						value.Merge(codec);
					}
					else
					{
						codecs2.Add(codec.Name, codec);
					}
				}
			};
			IProcessResult val2 = ProcessArgumentsExtensions.StartAndWaitForExit(val);
			if (val2.ExitCode != 0)
			{
				throw new FFMpegException(FFMpegExceptionType.Process, string.Join("\r\n", val2.OutputData));
			}
		}

		internal static Dictionary<string, Codec> GetCodecsInternal()
		{
			Dictionary<string, Codec> dictionary = new Dictionary<string, Codec>();
			ParsePartOfCodecs(dictionary, "-codecs", (string s) => Codec.TryParseFromCodecs(s, out Codec codec3) ? codec3 : null);
			ParsePartOfCodecs(dictionary, "-encoders", (string s) => Codec.TryParseFromEncodersDecoders(s, out Codec codec2, isEncoder: true) ? codec2 : null);
			ParsePartOfCodecs(dictionary, "-decoders", (string s) => Codec.TryParseFromEncodersDecoders(s, out Codec codec, isEncoder: false) ? codec : null);
			return dictionary;
		}

		public static IReadOnlyList<Codec> GetCodecs()
		{
			if (!GlobalFFOptions.Current.UseCache)
			{
				return GetCodecsInternal().Values.ToList().AsReadOnly();
			}
			return FFMpegCache.Codecs.Values.ToList().AsReadOnly();
		}

		public static IReadOnlyList<Codec> GetCodecs(CodecType type)
		{
			if (!GlobalFFOptions.Current.UseCache)
			{
				return GetCodecsInternal().Values.Where((Codec x) => x.Type == type).ToList().AsReadOnly();
			}
			return FFMpegCache.Codecs.Values.Where((Codec x) => x.Type == type).ToList().AsReadOnly();
		}

		public static IReadOnlyList<Codec> GetVideoCodecs()
		{
			return GetCodecs(CodecType.Video);
		}

		public static IReadOnlyList<Codec> GetAudioCodecs()
		{
			return GetCodecs(CodecType.Audio);
		}

		public static IReadOnlyList<Codec> GetSubtitleCodecs()
		{
			return GetCodecs(CodecType.Subtitle);
		}

		public static IReadOnlyList<Codec> GetDataCodecs()
		{
			return GetCodecs(CodecType.Data);
		}

		public static bool TryGetCodec(string name, out Codec codec)
		{
			string name2 = name;
			if (!GlobalFFOptions.Current.UseCache)
			{
				codec = GetCodecsInternal().Values.FirstOrDefault((Codec x) => x.Name == name2.ToLowerInvariant().Trim());
				return codec != null;
			}
			return FFMpegCache.Codecs.TryGetValue(name2, out codec);
		}

		public static Codec GetCodec(string name)
		{
			if (TryGetCodec(name, out Codec codec) && codec != null)
			{
				return codec;
			}
			throw new FFMpegException(FFMpegExceptionType.Operation, "Codec \"" + name + "\" not supported");
		}

		internal static IReadOnlyList<ContainerFormat> GetContainersFormatsInternal()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			FFMpegHelper.RootExceptionCheck();
			List<ContainerFormat> list = new List<ContainerFormat>();
			ProcessArguments val = new ProcessArguments(GlobalFFOptions.GetFFMpegBinaryPath(), "-formats");
			val.OutputDataReceived += delegate(object e, string data)
			{
				if (ContainerFormat.TryParse(data, out ContainerFormat fmt))
				{
					list.Add(fmt);
				}
			};
			IProcessResult val2 = ProcessArgumentsExtensions.StartAndWaitForExit(val);
			if (val2.ExitCode != 0)
			{
				throw new FFMpegException(FFMpegExceptionType.Process, string.Join("\r\n", val2.OutputData));
			}
			return list.AsReadOnly();
		}

		public static IReadOnlyList<ContainerFormat> GetContainerFormats()
		{
			if (!GlobalFFOptions.Current.UseCache)
			{
				return GetContainersFormatsInternal();
			}
			return FFMpegCache.ContainerFormats.Values.ToList().AsReadOnly();
		}

		public static bool TryGetContainerFormat(string name, out ContainerFormat fmt)
		{
			string name2 = name;
			if (!GlobalFFOptions.Current.UseCache)
			{
				fmt = GetContainersFormatsInternal().FirstOrDefault((ContainerFormat x) => x.Name == name2.ToLowerInvariant().Trim());
				return fmt != null;
			}
			return FFMpegCache.ContainerFormats.TryGetValue(name2, out fmt);
		}

		public static ContainerFormat GetContainerFormat(string name)
		{
			if (TryGetContainerFormat(name, out ContainerFormat fmt))
			{
				return fmt;
			}
			throw new FFMpegException(FFMpegExceptionType.Operation, "Container format \"" + name + "\" not supported");
		}

		private static void Cleanup(IEnumerable<string> pathList)
		{
			foreach (string path in pathList)
			{
				if (File.Exists(path))
				{
					File.Delete(path);
				}
			}
		}
	}
	public class FFMpegArgumentOptions : FFMpegArgumentsBase
	{
		internal FFMpegArgumentOptions()
		{
		}

		public FFMpegArgumentOptions WithAudioCodec(Codec audioCodec)
		{
			return WithArgument(new AudioCodecArgument(audioCodec));
		}

		public FFMpegArgumentOptions WithAudioCodec(string audioCodec)
		{
			return WithArgument(new AudioCodecArgument(audioCodec));
		}

		public FFMpegArgumentOptions WithAudioBitrate(AudioQuality audioQuality)
		{
			return WithArgument(new AudioBitrateArgument(audioQuality));
		}

		public FFMpegArgumentOptions WithAudioBitrate(int bitrate)
		{
			return WithArgument(new AudioBitrateArgument(bitrate));
		}

		public FFMpegArgumentOptions WithAudioSamplingRate(int samplingRate = 48000)
		{
			return WithArgument(new AudioSamplingRateArgument(samplingRate));
		}

		public FFMpegArgumentOptions WithVariableBitrate(int vbr)
		{
			return WithArgument(new VariableBitRateArgument(vbr));
		}

		public FFMpegArgumentOptions Resize(int width, int height)
		{
			return WithArgument(new SizeArgument(width, height));
		}

		public FFMpegArgumentOptions Resize(Size? size)
		{
			return WithArgument(new SizeArgument(size));
		}

		public FFMpegArgumentOptions Crop(Size? size, int left, int top)
		{
			return WithArgument(new CropArgument(size, top, left));
		}

		public FFMpegArgumentOptions Crop(int width, int height, int left, int top)
		{
			return WithArgument(new CropArgument(new Size(width, height), top, left));
		}

		public FFMpegArgumentOptions Crop(Size? size)
		{
			return WithArgument(new CropArgument(size, 0, 0));
		}

		public FFMpegArgumentOptions Crop(int width, int height)
		{
			return WithArgument(new CropArgument(new Size(width, height), 0, 0));
		}

		public FFMpegArgumentOptions WithBitStreamFilter(Channel channel, Filter filter)
		{
			return WithArgument(new BitStreamFilterArgument(channel, filter));
		}

		public FFMpegArgumentOptions WithConstantRateFactor(int crf)
		{
			return WithArgument(new ConstantRateFactorArgument(crf));
		}

		public FFMpegArgumentOptions CopyChannel(Channel channel = Channel.Both)
		{
			return WithArgument(new CopyArgument(channel));
		}

		public FFMpegArgumentOptions DisableChannel(Channel channel)
		{
			return WithArgument(new DisableChannelArgument(channel));
		}

		public FFMpegArgumentOptions WithDuration(TimeSpan? duration)
		{
			return WithArgument(new DurationArgument(duration));
		}

		public FFMpegArgumentOptions WithFastStart()
		{
			return WithArgument(new FaststartArgument());
		}

		public FFMpegArgumentOptions WithFrameOutputCount(int frames)
		{
			return WithArgument(new FrameOutputCountArgument(frames));
		}

		public FFMpegArgumentOptions WithHardwareAcceleration(HardwareAccelerationDevice hardwareAccelerationDevice = HardwareAccelerationDevice.Auto)
		{
			return WithArgument(new HardwareAccelerationArgument(hardwareAccelerationDevice));
		}

		public FFMpegArgumentOptions UsingShortest(bool shortest = true)
		{
			return WithArgument(new ShortestArgument(shortest));
		}

		public FFMpegArgumentOptions UsingMultithreading(bool multithread)
		{
			return WithArgument(new ThreadsArgument(multithread));
		}

		public FFMpegArgumentOptions UsingThreads(int threads)
		{
			return WithArgument(new ThreadsArgument(threads));
		}

		public FFMpegArgumentOptions WithVideoCodec(Codec videoCodec)
		{
			return WithArgument(new VideoCodecArgument(videoCodec));
		}

		public FFMpegArgumentOptions WithVideoCodec(string videoCodec)
		{
			return WithArgument(new VideoCodecArgument(videoCodec));
		}

		public FFMpegArgumentOptions WithVideoBitrate(int bitrate)
		{
			return WithArgument(new VideoBitrateArgument(bitrate));
		}

		public FFMpegArgumentOptions WithVideoFilters(Action<VideoFilterOptions> videoFilterOptions)
		{
			VideoFilterOptions videoFilterOptions2 = new VideoFilterOptions();
			videoFilterOptions(videoFilterOptions2);
			return WithArgument(new VideoFiltersArgument(videoFilterOptions2));
		}

		public FFMpegArgumentOptions WithAudioFilters(Action<AudioFilterOptions> audioFilterOptions)
		{
			AudioFilterOptions audioFilterOptions2 = new AudioFilterOptions();
			audioFilterOptions(audioFilterOptions2);
			return WithArgument(new AudioFiltersArgument(audioFilterOptions2));
		}

		public FFMpegArgumentOptions WithFramerate(double framerate)
		{
			return WithArgument(new FrameRateArgument(framerate));
		}

		public FFMpegArgumentOptions WithoutMetadata()
		{
			return WithArgument(new RemoveMetadataArgument());
		}

		public FFMpegArgumentOptions WithSpeedPreset(Speed speed)
		{
			return WithArgument(new SpeedPresetArgument(speed));
		}

		public FFMpegArgumentOptions WithStartNumber(int startNumber)
		{
			return WithArgument(new StartNumberArgument(startNumber));
		}

		public FFMpegArgumentOptions WithCustomArgument(string argument)
		{
			return WithArgument(new CustomArgument(argument));
		}

		public FFMpegArgumentOptions Seek(TimeSpan? seekTo)
		{
			return WithArgument(new SeekArgument(seekTo));
		}

		public FFMpegArgumentOptions EndSeek(TimeSpan? seekTo)
		{
			return WithArgument(new EndSeekArgument(seekTo));
		}

		public FFMpegArgumentOptions Loop(int times)
		{
			return WithArgument(new LoopArgument(times));
		}

		public FFMpegArgumentOptions OverwriteExisting()
		{
			return WithArgument(new OverwriteArgument());
		}

		public FFMpegArgumentOptions SelectStream(int streamIndex, int inputFileIndex = 0, Channel channel = Channel.All)
		{
			return WithArgument(new MapStreamArgument(streamIndex, inputFileIndex, channel));
		}

		public FFMpegArgumentOptions SelectStreams(IEnumerable<int> streamIndices, int inputFileIndex = 0, Channel channel = Channel.All)
		{
			return streamIndices.Aggregate(this, (FFMpegArgumentOptions options, int streamIndex) => options.SelectStream(streamIndex, inputFileIndex, channel));
		}

		public FFMpegArgumentOptions DeselectStream(int streamIndex, int inputFileIndex = 0, Channel channel = Channel.All)
		{
			return WithArgument(new MapStreamArgument(streamIndex, inputFileIndex, channel, negativeMap: true));
		}

		public FFMpegArgumentOptions DeselectStreams(IEnumerable<int> streamIndices, int inputFileIndex = 0, Channel channel = Channel.All)
		{
			return streamIndices.Aggregate(this, (FFMpegArgumentOptions options, int streamIndex) => options.DeselectStream(streamIndex, inputFileIndex, channel));
		}

		public FFMpegArgumentOptions ForceFormat(ContainerFormat format)
		{
			return WithArgument(new ForceFormatArgument(format));
		}

		public FFMpegArgumentOptions ForceFormat(string format)
		{
			return WithArgument(new ForceFormatArgument(format));
		}

		public FFMpegArgumentOptions ForcePixelFormat(string pixelFormat)
		{
			return WithArgument(new ForcePixelFormat(pixelFormat));
		}

		public FFMpegArgumentOptions ForcePixelFormat(PixelFormat pixelFormat)
		{
			return WithArgument(new ForcePixelFormat(pixelFormat));
		}

		public FFMpegArgumentOptions WithAudibleEncryptionKeys(string key, string iv)
		{
			return WithArgument(new AudibleEncryptionKeyArgument(key, iv));
		}

		public FFMpegArgumentOptions WithAudibleActivationBytes(string activationBytes)
		{
			return WithArgument(new AudibleEncryptionKeyArgument(activationBytes));
		}

		public FFMpegArgumentOptions WithTagVersion(int id3v2Version = 3)
		{
			return WithArgument(new ID3V2VersionArgument(id3v2Version));
		}

		public FFMpegArgumentOptions WithGifPaletteArgument(int streamIndex, Size? size, int fps = 12)
		{
			return WithArgument(new GifPaletteArgument(streamIndex, fps, size));
		}

		public FFMpegArgumentOptions WithCopyCodec()
		{
			return WithArgument(new CopyCodecArgument());
		}

		public FFMpegArgumentOptions WithArgument(IArgument argument)
		{
			Arguments.Add(argument);
			return this;
		}
	}
	public class FFMpegArgumentProcessor
	{
		private static readonly Regex ProgressRegex = new Regex("time=(\\d\\d:\\d\\d:\\d\\d.\\d\\d?)", RegexOptions.Compiled);

		private readonly List<Action<FFOptions>> _configurations;

		private readonly FFMpegArguments _ffMpegArguments;

		private Action<double>? _onPercentageProgress;

		private Action<TimeSpan>? _onTimeProgress;

		private Action<string>? _onOutput;

		private Action<string>? _onError;

		private TimeSpan? _totalTimespan;

		private FFMpegLogLevel? _logLevel;

		public string Arguments => _ffMpegArguments.Text;

		private event EventHandler<int> CancelEvent;

		internal FFMpegArgumentProcessor(FFMpegArguments ffMpegArguments)
		{
			_configurations = new List<Action<FFOptions>>();
			_ffMpegArguments = ffMpegArguments;
		}

		public FFMpegArgumentProcessor NotifyOnProgress(Action<double> onPercentageProgress, TimeSpan totalTimeSpan)
		{
			_totalTimespan = totalTimeSpan;
			_onPercentageProgress = onPercentageProgress;
			return this;
		}

		public FFMpegArgumentProcessor NotifyOnProgress(Action<TimeSpan> onTimeProgress)
		{
			_onTimeProgress = onTimeProgress;
			return this;
		}

		public FFMpegArgumentProcessor NotifyOnOutput(Action<string> onOutput)
		{
			_onOutput = onOutput;
			return this;
		}

		public FFMpegArgumentProcessor NotifyOnError(Action<string> onError)
		{
			_onError = onError;
			return this;
		}

		public FFMpegArgumentProcessor CancellableThrough(out Action cancel, int timeout = 0)
		{
			cancel = delegate
			{
				this.CancelEvent?.Invoke(this, timeout);
			};
			return this;
		}

		public FFMpegArgumentProcessor CancellableThrough(CancellationToken token, int timeout = 0)
		{
			token.Register(delegate
			{
				this.CancelEvent?.Invoke(this, timeout);
			});
			return this;
		}

		public FFMpegArgumentProcessor Configure(Action<FFOptions> configureOptions)
		{
			_configurations.Add(configureOptions);
			return this;
		}

		public FFMpegArgumentProcessor WithLogLevel(FFMpegLogLevel logLevel)
		{
			_logLevel = logLevel;
			return this;
		}

		public bool ProcessSynchronously(bool throwOnError = true, FFOptions? ffMpegOptions = null)
		{
			FFOptions configuredOptions = GetConfiguredOptions(ffMpegOptions);
			CancellationTokenSource cancellationTokenSource;
			ProcessArguments processArguments = PrepareProcessArguments(configuredOptions, out cancellationTokenSource);
			IProcessResult val = null;
			try
			{
				val = Process(processArguments, cancellationTokenSource).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().GetResult();
			}
			catch (OperationCanceledException)
			{
				if (throwOnError)
				{
					throw;
				}
			}
			return HandleCompletion(throwOnError, (val != null) ? val.ExitCode : (-1), ((val != null) ? val.ErrorData : null) ?? Array.Empty<string>());
		}

		public async Task<bool> ProcessAsynchronously(bool throwOnError = true, FFOptions? ffMpegOptions = null)
		{
			FFOptions configuredOptions = GetConfiguredOptions(ffMpegOptions);
			CancellationTokenSource cancellationTokenSource;
			ProcessArguments processArguments = PrepareProcessArguments(configuredOptions, out cancellationTokenSource);
			IProcessResult processResult = null;
			try
			{
				processResult = await Process(processArguments, cancellationTokenSource).ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (OperationCanceledException)
			{
				if (throwOnError)
				{
					throw;
				}
			}
			FFMpegArgumentProcessor fFMpegArgumentProcessor = this;
			IProcessResult obj = processResult;
			int exitCode = ((obj != null) ? obj.ExitCode : (-1));
			IProcessResult obj2 = processResult;
			return fFMpegArgumentProcessor.HandleCompletion(throwOnError, exitCode, ((obj2 != null) ? obj2.ErrorData : null) ?? Array.Empty<string>());
		}

		private async Task<IProcessResult> Process(ProcessArguments processArguments, CancellationTokenSource cancellationTokenSource)
		{
			CancellationTokenSource cancellationTokenSource2 = cancellationTokenSource;
			IProcessResult processResult = null;
			_ffMpegArguments.Pre();
			IProcessInstance instance = processArguments.Start();
			bool cancelled;
			try
			{
				cancelled = false;
				CancelEvent += OnCancelEvent;
				try
				{
					await Task.WhenAll(instance.WaitForExitAsync(default(CancellationToken)).ContinueWith(delegate(Task<IProcessResult> t)
					{
						processResult = t.Result;
						cancellationTokenSource2.Cancel();
						_ffMpegArguments.Post();
					}), _ffMpegArguments.During(cancellationTokenSource2.Token)).ConfigureAwait(continueOnCapturedContext: false);
					if (cancelled)
					{
						throw new OperationCanceledException("ffmpeg processing was cancelled");
					}
					return processResult;
				}
				finally
				{
					CancelEvent -= OnCancelEvent;
				}
			}
			finally
			{
				if (instance != null)
				{
					((IDisposable)instance).Dispose();
				}
			}
			void OnCancelEvent(object sender, int timeout)
			{
				cancelled = true;
				instance.SendInput("q");
				if (!cancellationTokenSource2.Token.WaitHandle.WaitOne(timeout, exitContext: true))
				{
					cancellationTokenSource2.Cancel();
					instance.Kill();
				}
			}
		}

		private bool HandleCompletion(bool throwOnError, int exitCode, IReadOnlyList<string> errorData)
		{
			if (throwOnError && exitCode != 0)
			{
				throw new FFMpegException(FFMpegExceptionType.Process, string.Format("ffmpeg exited with non-zero exit-code ({0} - {1})", exitCode, string.Join("\n", errorData)), null, string.Join("\n", errorData));
			}
			_onPercentageProgress?.Invoke(100.0);
			if (_totalTimespan.HasValue)
			{
				_onTimeProgress?.Invoke(_totalTimespan.Value);
			}
			return exitCode == 0;
		}

		internal FFOptions GetConfiguredOptions(FFOptions? ffOptions)
		{
			FFOptions fFOptions = ffOptions ?? GlobalFFOptions.Current.Clone();
			foreach (Action<FFOptions> configuration in _configurations)
			{
				configuration(fFOptions);
			}
			return fFOptions;
		}

		private ProcessArguments PrepareProcessArguments(FFOptions ffOptions, out CancellationTokenSource cancellationTokenSource)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			FFMpegHelper.RootExceptionCheck();
			FFMpegHelper.VerifyFFMpegExists(ffOptions);
			string text = _ffMpegArguments.Text;
			if (!_logLevel.HasValue)
			{
				_logLevel = ffOptions.LogLevel;
			}
			if (_logLevel.HasValue)
			{
				string text2 = _logLevel.ToString().ToLower();
				text = text + " -v " + text2;
			}
			ProcessArguments val = new ProcessArguments(new ProcessStartInfo
			{
				FileName = GlobalFFOptions.GetFFMpegBinaryPath(ffOptions),
				Arguments = text,
				StandardOutputEncoding = ffOptions.Encoding,
				StandardErrorEncoding = ffOptions.Encoding,
				WorkingDirectory = ffOptions.WorkingDirectory
			});
			cancellationTokenSource = new CancellationTokenSource();
			if (_onOutput != null)
			{
				val.OutputDataReceived += OutputData;
			}
			if (_onError != null || _onTimeProgress != null || (_onPercentageProgress != null && _totalTimespan.HasValue))
			{
				val.ErrorDataReceived += ErrorData;
			}
			return val;
		}

		private void ErrorData(object sender, string msg)
		{
			_onError?.Invoke(msg);
			Match match = ProgressRegex.Match(msg);
			if (match.Success)
			{
				TimeSpan obj = MediaAnalysisUtils.ParseDuration(match.Groups[1].Value);
				_onTimeProgress?.Invoke(obj);
				if (_onPercentageProgress != null && _totalTimespan.HasValue)
				{
					double obj2 = Math.Round(obj.TotalSeconds / _totalTimespan.Value.TotalSeconds * 100.0, 2);
					_onPercentageProgress(obj2);
				}
			}
		}

		private void OutputData(object sender, string msg)
		{
			_onOutput?.Invoke(msg);
		}
	}
	public sealed class FFMpegArguments : FFMpegArgumentsBase
	{
		private readonly FFMpegGlobalArguments _globalArguments = new FFMpegGlobalArguments();

		public string Text => GetText();

		private FFMpegArguments()
		{
		}

		private string GetText()
		{
			IArgument[] allArguments = _globalArguments.Arguments.Concat(Arguments).ToArray();
			return string.Join(" ", allArguments.Select((IArgument arg) => (!(arg is IDynamicArgument dynamicArgument)) ? arg.Text : dynamicArgument.GetText(allArguments)));
		}

		public static FFMpegArguments FromConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return new FFMpegArguments().WithInput(new ConcatArgument(filePaths), addArguments);
		}

		public static FFMpegArguments FromDemuxConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return new FFMpegArguments().WithInput(new DemuxConcatArgument(filePaths), addArguments);
		}

		public static FFMpegArguments FromFileInput(string filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return new FFMpegArguments().WithInput(new InputArgument(verifyExists, filePath), addArguments);
		}

		public static FFMpegArguments FromFileInput(IEnumerable<string> filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return new FFMpegArguments().WithInput(new MultiInputArgument(verifyExists, filePath), addArguments);
		}

		public static FFMpegArguments FromFileInput(FileInfo fileInfo, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return new FFMpegArguments().WithInput(new InputArgument(fileInfo.FullName, verifyExists: false), addArguments);
		}

		public static FFMpegArguments FromUrlInput(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return new FFMpegArguments().WithInput(new InputArgument(uri.AbsoluteUri, verifyExists: false), addArguments);
		}

		public static FFMpegArguments FromDeviceInput(string device, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return new FFMpegArguments().WithInput(new InputDeviceArgument(device), addArguments);
		}

		public static FFMpegArguments FromPipeInput(IPipeSource sourcePipe, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return new FFMpegArguments().WithInput(new InputPipeArgument(sourcePipe), addArguments);
		}

		public FFMpegArguments WithGlobalOptions(Action<FFMpegGlobalArguments> configureOptions)
		{
			configureOptions(_globalArguments);
			return this;
		}

		public FFMpegArguments AddConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new ConcatArgument(filePaths), addArguments);
		}

		public FFMpegArguments AddDemuxConcatInput(IEnumerable<string> filePaths, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new DemuxConcatArgument(filePaths), addArguments);
		}

		public FFMpegArguments AddFileInput(string filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new InputArgument(verifyExists, filePath), addArguments);
		}

		public FFMpegArguments AddFileInput(IEnumerable<string> filePath, bool verifyExists = true, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new MultiInputArgument(verifyExists, filePath), addArguments);
		}

		public FFMpegArguments AddFileInput(FileInfo fileInfo, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new InputArgument(fileInfo.FullName, verifyExists: false), addArguments);
		}

		public FFMpegArguments AddUrlInput(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new InputArgument(uri.AbsoluteUri, verifyExists: false), addArguments);
		}

		public FFMpegArguments AddDeviceInput(string device, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new InputDeviceArgument(device), addArguments);
		}

		public FFMpegArguments AddPipeInput(IPipeSource sourcePipe, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new InputPipeArgument(sourcePipe), addArguments);
		}

		public FFMpegArguments AddMetaData(string content, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new MetaDataArgument(content), addArguments);
		}

		public FFMpegArguments AddMetaData(IReadOnlyMetaData metaData, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new MetaDataArgument(MetaDataSerializer.Instance.Serialize(metaData)), addArguments);
		}

		public FFMpegArguments MapMetaData(int? inputIndex = null, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return WithInput(new MapMetadataArgument(inputIndex), addArguments);
		}

		private FFMpegArguments WithInput(IInputArgument inputArgument, Action<FFMpegArgumentOptions>? addArguments)
		{
			FFMpegArgumentOptions fFMpegArgumentOptions = new FFMpegArgumentOptions();
			addArguments?.Invoke(fFMpegArgumentOptions);
			Arguments.AddRange(fFMpegArgumentOptions.Arguments);
			Arguments.Add(inputArgument);
			return this;
		}

		public FFMpegArgumentProcessor OutputToFile(string file, bool overwrite = true, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return ToProcessor(new OutputArgument(file, overwrite), addArguments);
		}

		public FFMpegArgumentProcessor OutputToUrl(string uri, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return ToProcessor(new OutputUrlArgument(uri), addArguments);
		}

		public FFMpegArgumentProcessor OutputToUrl(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return ToProcessor(new OutputUrlArgument(uri.ToString()), addArguments);
		}

		public FFMpegArgumentProcessor OutputToPipe(IPipeSink reader, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return ToProcessor(new OutputPipeArgument(reader), addArguments);
		}

		private FFMpegArgumentProcessor ToProcessor(IOutputArgument argument, Action<FFMpegArgumentOptions>? addArguments)
		{
			FFMpegArgumentOptions fFMpegArgumentOptions = new FFMpegArgumentOptions();
			addArguments?.Invoke(fFMpegArgumentOptions);
			Arguments.AddRange(fFMpegArgumentOptions.Arguments);
			Arguments.Add(argument);
			return new FFMpegArgumentProcessor(this);
		}

		public FFMpegArgumentProcessor OutputToTee(Action<FFMpegMultiOutputOptions> addOutputs, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			FFMpegMultiOutputOptions fFMpegMultiOutputOptions = new FFMpegMultiOutputOptions();
			addOutputs(fFMpegMultiOutputOptions);
			return ToProcessor(new OutputTeeArgument(fFMpegMultiOutputOptions), addArguments);
		}

		public FFMpegArgumentProcessor MultiOutput(Action<FFMpegMultiOutputOptions> addOutputs)
		{
			FFMpegMultiOutputOptions fFMpegMultiOutputOptions = new FFMpegMultiOutputOptions();
			addOutputs(fFMpegMultiOutputOptions);
			Arguments.AddRange(fFMpegMultiOutputOptions.Arguments);
			return new FFMpegArgumentProcessor(this);
		}

		internal void Pre()
		{
			foreach (IInputOutputArgument item in Arguments.OfType<IInputOutputArgument>())
			{
				item.Pre();
			}
		}

		internal async Task During(CancellationToken cancellationToken = default(CancellationToken))
		{
			await Task.WhenAll(from io in Arguments.OfType<IInputOutputArgument>()
				select io.During(cancellationToken)).ConfigureAwait(continueOnCapturedContext: false);
		}

		internal void Post()
		{
			foreach (IInputOutputArgument item in Arguments.OfType<IInputOutputArgument>())
			{
				item.Post();
			}
		}
	}
	public abstract class FFMpegArgumentsBase
	{
		internal readonly List<IArgument> Arguments = new List<IArgument>();
	}
	internal static class FFMpegCache
	{
		private static readonly object _syncObject = new object();

		private static Dictionary<string, PixelFormat>? _pixelFormats;

		private static Dictionary<string, Codec>? _codecs;

		private static Dictionary<string, ContainerFormat>? _containers;

		public static IReadOnlyDictionary<string, PixelFormat> PixelFormats
		{
			get
			{
				if (_pixelFormats == null)
				{
					lock (_syncObject)
					{
						if (_pixelFormats == null)
						{
							_pixelFormats = FFMpeg.GetPixelFormatsInternal().ToDictionary((PixelFormat x) => x.Name);
						}
					}
				}
				return _pixelFormats;
			}
		}

		public static IReadOnlyDictionary<string, Codec> Codecs
		{
			get
			{
				if (_codecs == null)
				{
					lock (_syncObject)
					{
						if (_codecs == null)
						{
							_codecs = FFMpeg.GetCodecsInternal();
						}
					}
				}
				return _codecs;
			}
		}

		public static IReadOnlyDictionary<string, ContainerFormat> ContainerFormats
		{
			get
			{
				if (_containers == null)
				{
					lock (_syncObject)
					{
						if (_containers == null)
						{
							_containers = FFMpeg.GetContainersFormatsInternal().ToDictionary((ContainerFormat x) => x.Name);
						}
					}
				}
				return _containers;
			}
		}
	}
	public sealed class FFMpegGlobalArguments : FFMpegArgumentsBase
	{
		internal FFMpegGlobalArguments()
		{
		}

		public FFMpegGlobalArguments WithVerbosityLevel(VerbosityLevel verbosityLevel = VerbosityLevel.Error)
		{
			return WithOption(new VerbosityLevelArgument(verbosityLevel));
		}

		private FFMpegGlobalArguments WithOption(IArgument argument)
		{
			Arguments.Add(argument);
			return this;
		}
	}
	public class FFMpegMultiOutputOptions
	{
		internal readonly List<FFMpegArgumentOptions> Outputs = new List<FFMpegArgumentOptions>();

		public IEnumerable<IArgument> Arguments => Outputs.SelectMany((FFMpegArgumentOptions o) => o.Arguments);

		public FFMpegMultiOutputOptions OutputToFile(string file, bool overwrite = true, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return AddOutput(new OutputArgument(file, overwrite), addArguments);
		}

		public FFMpegMultiOutputOptions OutputToUrl(string uri, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return AddOutput(new OutputUrlArgument(uri), addArguments);
		}

		public FFMpegMultiOutputOptions OutputToUrl(Uri uri, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return AddOutput(new OutputUrlArgument(uri.ToString()), addArguments);
		}

		public FFMpegMultiOutputOptions OutputToPipe(IPipeSink reader, Action<FFMpegArgumentOptions>? addArguments = null)
		{
			return AddOutput(new OutputPipeArgument(reader), addArguments);
		}

		public FFMpegMultiOutputOptions AddOutput(IOutputArgument argument, Action<FFMpegArgumentOptions>? addArguments)
		{
			FFMpegArgumentOptions fFMpegArgumentOptions = new FFMpegArgumentOptions();
			addArguments?.Invoke(fFMpegArgumentOptions);
			fFMpegArgumentOptions.Arguments.Add(argument);
			Outputs.Add(fFMpegArgumentOptions);
			return this;
		}
	}
	public static class SnapshotArgumentBuilder
	{
		public static (FFMpegArguments, Action<FFMpegArgumentOptions> outputOptions) BuildSnapshotArguments(string input, IMediaAnalysis source, Size? size = null, TimeSpan? captureTime = null, int? streamIndex = null, int inputFileIndex = 0)
		{
			TimeSpan valueOrDefault = captureTime.GetValueOrDefault();
			if (!captureTime.HasValue)
			{
				valueOrDefault = TimeSpan.FromSeconds(source.Duration.TotalSeconds / 3.0);
				captureTime = valueOrDefault;
			}
			size = PrepareSnapshotSize(source, size);
			int valueOrDefault2 = streamIndex.GetValueOrDefault();
			if (!streamIndex.HasValue)
			{
				valueOrDefault2 = source.PrimaryVideoStream?.Index ?? source.VideoStreams.FirstOrDefault()?.Index ?? 0;
				streamIndex = valueOrDefault2;
			}
			return (FFMpegArguments.FromFileInput(input, verifyExists: false, delegate(FFMpegArgumentOptions options)
			{
				options.Seek(captureTime);
			}), delegate(FFMpegArgumentOptions options)
			{
				options.SelectStream(streamIndex.Value, inputFileIndex).WithVideoCodec(VideoCodec.Png).WithFrameOutputCount(1)
					.Resize(size);
			});
		}

		public static (FFMpegArguments, Action<FFMpegArgumentOptions> outputOptions) BuildGifSnapshotArguments(string input, IMediaAnalysis source, Size? size = null, TimeSpan? captureTime = null, TimeSpan? duration = null, int? streamIndex = null, int fps = 12)
		{
			Size defaultValue = new Size(480, -1);
			TimeSpan valueOrDefault = captureTime.GetValueOrDefault();
			if (!captureTime.HasValue)
			{
				valueOrDefault = TimeSpan.FromSeconds(source.Duration.TotalSeconds / 3.0);
				captureTime = valueOrDefault;
			}
			size = PrepareSnapshotSize(source, size).GetValueOrDefault(defaultValue);
			int valueOrDefault2 = streamIndex.GetValueOrDefault();
			if (!streamIndex.HasValue)
			{
				valueOrDefault2 = source.PrimaryVideoStream?.Index ?? source.VideoStreams.FirstOrDefault()?.Index ?? 0;
				streamIndex = valueOrDefault2;
			}
			return (FFMpegArguments.FromFileInput(input, verifyExists: false, delegate(FFMpegArgumentOptions options)
			{
				options.Seek(captureTime).WithDuration(duration);
			}), delegate(FFMpegArgumentOptions options)
			{
				options.WithGifPaletteArgument(streamIndex.Value, size, fps);
			});
		}

		private static Size? PrepareSnapshotSize(IMediaAnalysis source, Size? wantedSize)
		{
			if (!wantedSize.HasValue || (wantedSize.Value.Height <= 0 && wantedSize.Value.Width <= 0) || source.PrimaryVideoStream == null)
			{
				return null;
			}
			Size size = new Size(source.PrimaryVideoStream.Width, source.PrimaryVideoStream.Height);
			if (IsRotated(source.PrimaryVideoStream.Rotation))
			{
				size = new Size(source.PrimaryVideoStream.Height, source.PrimaryVideoStream.Width);
			}
			if (wantedSize.Value.Width != size.Width || wantedSize.Value.Height != size.Height)
			{
				if (wantedSize.Value.Width <= 0 && wantedSize.Value.Height > 0)
				{
					double num = (double)wantedSize.Value.Height / (double)size.Height;
					return new Size((int)((double)size.Width * num), (int)((double)size.Height * num));
				}
				if (wantedSize.Value.Height <= 0 && wantedSize.Value.Width > 0)
				{
					double num2 = (double)wantedSize.Value.Width / (double)size.Width;
					return new Size((int)((double)size.Width * num2), (int)((double)size.Height * num2));
				}
				return wantedSize;
			}
			return null;
		}

		private static bool IsRotated(int rotation)
		{
			int num = Math.Abs(rotation);
			if (num != 90)
			{
				return num == 180;
			}
			return true;
		}
	}
	public class FFOptions : ICloneable
	{
		public string WorkingDirectory { get; set; } = string.Empty;


		public string BinaryFolder { get; set; } = string.Empty;


		public string TemporaryFilesFolder { get; set; } = Path.GetTempPath();


		public string EncodingWebName { get; set; } = System.Text.Encoding.Default.WebName;


		[JsonIgnore]
		public Encoding Encoding
		{
			get
			{
				return System.Text.Encoding.GetEncoding(EncodingWebName);
			}
			set
			{
				EncodingWebName = value?.WebName ?? System.Text.Encoding.Default.WebName;
			}
		}

		public FFMpegLogLevel? LogLevel { get; set; }

		public Dictionary<string, string> ExtensionOverrides { get; set; } = new Dictionary<string, string> { { "mpegts", ".ts" } };


		public bool UseCache { get; set; } = true;


		object ICloneable.Clone()
		{
			return Clone();
		}

		public FFOptions Clone()
		{
			return (FFOptions)MemberwiseClone();
		}
	}
	public class AudioStream : MediaStream
	{
		public int Channels { get; set; }

		public string ChannelLayout { get; set; }

		public int SampleRateHz { get; set; }

		public string Profile { get; set; }
	}
	public static class FFProbe
	{
		public static IMediaAnalysis Analyse(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
		{
			ThrowIfInputFileDoesNotExist(filePath);
			IProcessResult obj = PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExit();
			ThrowIfExitCodeNotZero(obj);
			return ParseOutput(obj);
		}

		public static FFProbeFrames GetFrames(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
		{
			ThrowIfInputFileDoesNotExist(filePath);
			IProcessResult obj = PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExit();
			ThrowIfExitCodeNotZero(obj);
			return ParseFramesOutput(obj);
		}

		public static FFProbePackets GetPackets(string filePath, FFOptions? ffOptions = null, string? customArguments = null)
		{
			ThrowIfInputFileDoesNotExist(filePath);
			IProcessResult obj = PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExit();
			ThrowIfExitCodeNotZero(obj);
			return ParsePacketsOutput(obj);
		}

		public static IMediaAnalysis Analyse(Uri uri, FFOptions? ffOptions = null, string? customArguments = null)
		{
			IProcessResult obj = PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExit();
			ThrowIfExitCodeNotZero(obj);
			return ParseOutput(obj);
		}

		public static IMediaAnalysis Analyse(Stream stream, FFOptions? ffOptions = null, string? customArguments = null)
		{
			InputPipeArgument inputPipeArgument = new InputPipeArgument(new StreamPipeSource(stream));
			ProcessArguments processArguments = PrepareStreamAnalysisInstance(inputPipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
			inputPipeArgument.Pre();
			Task<IProcessResult> task = processArguments.StartAndWaitForExitAsync();
			try
			{
				inputPipeArgument.During().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter()
					.GetResult();
			}
			catch (IOException)
			{
			}
			finally
			{
				inputPipeArgument.Post();
			}
			IProcessResult result = task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().GetResult();
			ThrowIfExitCodeNotZero(result);
			return ParseOutput(result);
		}

		public static async Task<IMediaAnalysis> AnalyseAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default(CancellationToken), string? customArguments = null)
		{
			ThrowIfInputFileDoesNotExist(filePath);
			IProcessResult obj = await PrepareStreamAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			ThrowIfExitCodeNotZero(obj);
			return ParseOutput(obj);
		}

		public static FFProbeFrames GetFrames(Uri uri, FFOptions? ffOptions = null, string? customArguments = null)
		{
			IProcessResult obj = PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExit();
			ThrowIfExitCodeNotZero(obj);
			return ParseFramesOutput(obj);
		}

		public static async Task<FFProbeFrames> GetFramesAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default(CancellationToken), string? customArguments = null)
		{
			ThrowIfInputFileDoesNotExist(filePath);
			return ParseFramesOutput(await PrepareFrameAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
		}

		public static async Task<FFProbePackets> GetPacketsAsync(string filePath, FFOptions? ffOptions = null, CancellationToken cancellationToken = default(CancellationToken), string? customArguments = null)
		{
			ThrowIfInputFileDoesNotExist(filePath);
			return ParsePacketsOutput(await PreparePacketAnalysisInstance(filePath, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
		}

		public static async Task<IMediaAnalysis> AnalyseAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default(CancellationToken), string? customArguments = null)
		{
			IProcessResult obj = await PrepareStreamAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			ThrowIfExitCodeNotZero(obj);
			return ParseOutput(obj);
		}

		public static async Task<IMediaAnalysis> AnalyseAsync(Stream stream, FFOptions? ffOptions = null, CancellationToken cancellationToken = default(CancellationToken), string? customArguments = null)
		{
			StreamPipeSource writer = new StreamPipeSource(stream);
			InputPipeArgument pipeArgument = new InputPipeArgument(writer);
			ProcessArguments processArguments = PrepareStreamAnalysisInstance(pipeArgument.PipePath, ffOptions ?? GlobalFFOptions.Current, customArguments);
			pipeArgument.Pre();
			Task<IProcessResult> task = processArguments.StartAndWaitForExitAsync(cancellationToken);
			try
			{
				await pipeArgument.During(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (IOException)
			{
			}
			finally
			{
				pipeArgument.Post();
			}
			IProcessResult obj = await task.ConfigureAwait(continueOnCapturedContext: false);
			ThrowIfExitCodeNotZero(obj);
			pipeArgument.Post();
			return ParseOutput(obj);
		}

		public static async Task<FFProbeFrames> GetFramesAsync(Uri uri, FFOptions? ffOptions = null, CancellationToken cancellationToken = default(CancellationToken), string? customArguments = null)
		{
			return ParseFramesOutput(await PrepareFrameAnalysisInstance(uri.AbsoluteUri, ffOptions ?? GlobalFFOptions.Current, customArguments).StartAndWaitForExitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
		}

		private static IMediaAnalysis ParseOutput(IProcessResult instance)
		{
			FFProbeAnalysis? fFProbeAnalysis = JsonSerializer.Deserialize<FFProbeAnalysis>(string.Join(string.Empty, instance.OutputData), new JsonSerializerOptions
			{
				PropertyNameCaseInsensitive = true
			});
			if (fFProbeAnalysis?.Format == null)
			{
				throw new FormatNullException();
			}
			fFProbeAnalysis.ErrorData = instance.ErrorData;
			return new MediaAnalysis(fFProbeAnalysis);
		}

		private static FFProbeFrames ParseFramesOutput(IProcessResult instance)
		{
			return JsonSerializer.Deserialize<FFProbeFrames>(string.Join(string.Empty, instance.OutputData), new JsonSerializerOptions
			{
				PropertyNameCaseInsensitive = true,
				NumberHandling = (JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString)
			});
		}

		private static FFProbePackets ParsePacketsOutput(IProcessResult instance)
		{
			return JsonSerializer.Deserialize<FFProbePackets>(string.Join(string.Empty, instance.OutputData), new JsonSerializerOptions
			{
				PropertyNameCaseInsensitive = true,
				NumberHandling = (JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString)
			});
		}

		private static void ThrowIfInputFileDoesNotExist(string filePath)
		{
			if (!File.Exists(filePath))
			{
				throw new FFMpegException(FFMpegExceptionType.File, "No file found at '" + filePath + "'");
			}
		}

		private static void ThrowIfExitCodeNotZero(IProcessResult result)
		{
			if (result.ExitCode != 0)
			{
				string message = string.Format("ffprobe exited with non-zero exit-code ({0} - {1})", result.ExitCode, string.Join("\n", result.ErrorData));
				throw new FFMpegException(FFMpegExceptionType.Process, message, null, string.Join("\n", result.ErrorData));
			}
		}

		private static ProcessArguments PrepareStreamAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
		{
			return PrepareInstance("-loglevel error -print_format json -show_format -sexagesimal -show_streams -show_chapters \"" + filePath + "\"", ffOptions, customArguments);
		}

		private static ProcessArguments PrepareFrameAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
		{
			return PrepareInstance("-loglevel error -print_format json -show_frames -v quiet -sexagesimal \"" + filePath + "\"", ffOptions, customArguments);
		}

		private static ProcessArguments PreparePacketAnalysisInstance(string filePath, FFOptions ffOptions, string? customArguments)
		{
			return PrepareInstance("-loglevel error -print_format json -show_packets -v quiet -sexagesimal \"" + filePath + "\"", ffOptions, customArguments);
		}

		private static ProcessArguments PrepareInstance(string arguments, FFOptions ffOptions, string? customArguments)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			FFProbeHelper.RootExceptionCheck();
			FFProbeHelper.VerifyFFProbeExists(ffOptions);
			return new ProcessArguments(new ProcessStartInfo(GlobalFFOptions.GetFFProbeBinaryPath(ffOptions), arguments + " " + customArguments)
			{
				StandardOutputEncoding = ffOptions.Encoding,
				StandardErrorEncoding = ffOptions.Encoding,
				WorkingDirectory = ffOptions.WorkingDirectory
			});
		}
	}
	public class FFProbeAnalysis
	{
		[JsonPropertyName("streams")]
		public List<FFProbeStream> Streams { get; set; }

		[JsonPropertyName("format")]
		public Format Format { get; set; }

		[JsonPropertyName("chapters")]
		public List<Chapter> Chapters { get; set; }

		[JsonIgnore]
		public IReadOnlyList<string> ErrorData { get; set; } = new List<string>();

	}
	public class FFProbeStream : ITagsContainer, IDispositionContainer
	{
		[JsonPropertyName("index")]
		public int Index { get; set; }

		[JsonPropertyName("avg_frame_rate")]
		public string AvgFrameRate { get; set; }

		[JsonPropertyName("bits_per_raw_sample")]
		public string BitsPerRawSample { get; set; }

		[JsonPropertyName("bits_per_sample")]
		public int BitsPerSample { get; set; }

		[JsonPropertyName("bit_rate")]
		public string BitRate { get; set; }

		[JsonPropertyName("channels")]
		public int? Channels { get; set; }

		[JsonPropertyName("channel_layout")]
		public string ChannelLayout { get; set; }

		[JsonPropertyName("codec_type")]
		public string CodecType { get; set; }

		[JsonPropertyName("codec_name")]
		public string CodecName { get; set; }

		[JsonPropertyName("codec_long_name")]
		public string CodecLongName { get; set; }

		[JsonPropertyName("codec_tag")]
		public string CodecTag { get; set; }

		[JsonPropertyName("codec_tag_string")]
		public string CodecTagString { get; set; }

		[JsonPropertyName("display_aspect_ratio")]
		public string DisplayAspectRatio { get; set; }

		[JsonPropertyName("sample_aspect_ratio")]
		public string SampleAspectRatio { get; set; }

		[JsonPropertyName("start_time")]
		public string StartTime { get; set; }

		[JsonPropertyName("duration")]
		public string Duration { get; set; }

		[JsonPropertyName("profile")]
		public string Profile { get; set; }

		[JsonPropertyName("width")]
		public int? Width { get; set; }

		[JsonPropertyName("height")]
		public int? Height { get; set; }

		[JsonPropertyName("r_frame_rate")]
		public string FrameRate { get; set; }

		[JsonPropertyName("pix_fmt")]
		public string PixelFormat { get; set; }

		[JsonPropertyName("level")]
		public int Level { get; set; }

		[JsonPropertyName("sample_rate")]
		public string SampleRate { get; set; }

		[JsonPropertyName("disposition")]
		public Dictionary<string, int> Disposition { get; set; }

		[JsonPropertyName("tags")]
		public Dictionary<string, string>? Tags { get; set; }

		[JsonPropertyName("side_data_list")]
		public List<Dictionary<string, JsonValue>> SideData { get; set; }

		[JsonPropertyName("color_range")]
		public string ColorRange { get; set; }

		[JsonPropertyName("color_space")]
		public string ColorSpace { get; set; }

		[JsonPropertyName("color_transfer")]
		public string ColorTransfer { get; set; }

		[JsonPropertyName("color_primaries")]
		public string ColorPrimaries { get; set; }
	}
	public class Format : ITagsContainer
	{
		[JsonPropertyName("filename")]
		public string Filename { get; set; }

		[JsonPropertyName("nb_streams")]
		public int NbStreams { get; set; }

		[JsonPropertyName("nb_programs")]
		public int NbPrograms { get; set; }

		[JsonPropertyName("format_name")]
		public string FormatName { get; set; }

		[JsonPropertyName("format_long_name")]
		public string FormatLongName { get; set; }

		[JsonPropertyName("start_time")]
		public string StartTime { get; set; }

		[JsonPropertyName("duration")]
		public string Duration { get; set; }

		[JsonPropertyName("size")]
		public string Size { get; set; }

		[JsonPropertyName("bit_rate")]
		public string? BitRate { get; set; }

		[JsonPropertyName("probe_score")]
		public int ProbeScore { get; set; }

		[JsonPropertyName("tags")]
		public Dictionary<string, string>? Tags { get; set; }
	}
	public class Chapter : ITagsContainer
	{
		[JsonPropertyName("id")]
		public long Id { get; set; }

		[JsonPropertyName("time_base")]
		public string TimeBase { get; set; }

		[JsonPropertyName("start")]
		public long Start { get; set; }

		[JsonPropertyName("start_time")]
		public string StartTime { get; set; }

		[JsonPropertyName("end")]
		public long End { get; set; }

		[JsonPropertyName("end_time")]
		public string EndTime { get; set; }

		[JsonPropertyName("tags")]
		public Dictionary<string, string>? Tags { get; set; }
	}
	public interface IDispositionContainer
	{
		Dictionary<string, int> Disposition { get; set; }
	}
	public interface ITagsContainer
	{
		Dictionary<string, string>? Tags { get; set; }
	}
	public static class TagExtensions
	{
		private static string? TryGetTagValue(ITagsContainer tagsContainer, string key)
		{
			if (tagsContainer.Tags != null && tagsContainer.Tags.TryGetValue(key, out string value))
			{
				return value;
			}
			return null;
		}

		public static string? GetLanguage(this ITagsContainer tagsContainer)
		{
			return TryGetTagValue(tagsContainer, "language");
		}

		public static string? GetCreationTime(this ITagsContainer tagsContainer)
		{
			return TryGetTagValue(tagsContainer, "creation_time ");
		}

		public static string? GetRotate(this ITagsContainer tagsContainer)
		{
			return TryGetTagValue(tagsContainer, "rotate");
		}

		public static string? GetDuration(this ITagsContainer tagsContainer)
		{
			return TryGetTagValue(tagsContainer, "duration");
		}
	}
	public static class DispositionExtensions
	{
		private static int? TryGetDispositionValue(IDispositionContainer dispositionContainer, string key)
		{
			if (dispositionContainer.Disposition != null && dispositionContainer.Disposition.TryGetValue(key, out var value))
			{
				return value;
			}
			return null;
		}

		public static int? GetDefault(this IDispositionContainer tagsContainer)
		{
			return TryGetDispositionValue(tagsContainer, "default");
		}

		public static int? GetForced(this IDispositionContainer tagsContainer)
		{
			return TryGetDispositionValue(tagsContainer, "forced");
		}
	}
	public class FFProbeFrameAnalysis
	{
		[JsonPropertyName("media_type")]
		public string MediaType { get; set; }

		[JsonPropertyName("stream_index")]
		public int StreamIndex { get; set; }

		[JsonPropertyName("key_frame")]
		public int KeyFrame { get; set; }

		[JsonPropertyName("pkt_pts")]
		public long PacketPts { get; set; }

		[JsonPropertyName("pkt_pts_time")]
		public string PacketPtsTime { get; set; }

		[JsonPropertyName("pkt_dts")]
		public long PacketDts { get; set; }

		[JsonPropertyName("pkt_dts_time")]
		public string PacketDtsTime { get; set; }

		[JsonPropertyName("best_effort_timestamp")]
		public long BestEffortTimestamp { get; set; }

		[JsonPropertyName("best_effort_timestamp_time")]
		public string BestEffortTimestampTime { get; set; }

		[JsonPropertyName("pkt_duration")]
		public int PacketDuration { get; set; }

		[JsonPropertyName("pkt_duration_time")]
		public string PacketDurationTime { get; set; }

		[JsonPropertyName("pkt_pos")]
		public long PacketPos { get; set; }

		[JsonPropertyName("pkt_size")]
		public int PacketSize { get; set; }

		[JsonPropertyName("width")]
		public long Width { get; set; }

		[JsonPropertyName("height")]
		public long Height { get; set; }

		[JsonPropertyName("pix_fmt")]
		public string PixelFormat { get; set; }

		[JsonPropertyName("pict_type")]
		public string PictureType { get; set; }

		[JsonPropertyName("coded_picture_number")]
		public long CodedPictureNumber { get; set; }

		[JsonPropertyName("display_picture_number")]
		public long DisplayPictureNumber { get; set; }

		[JsonPropertyName("interlaced_frame")]
		public int InterlacedFrame { get; set; }

		[JsonPropertyName("top_field_first")]
		public int TopFieldFirst { get; set; }

		[JsonPropertyName("repeat_pict")]
		public int RepeatPicture { get; set; }

		[JsonPropertyName("chroma_location")]
		public string ChromaLocation { get; set; }
	}
	public class FFProbeFrames
	{
		[JsonPropertyName("frames")]
		public List<FFProbeFrameAnalysis> Frames { get; set; }
	}
	public interface IMediaAnalysis
	{
		TimeSpan Duration { get; }

		MediaFormat Format { get; }

		List<ChapterData> Chapters { get; }

		AudioStream? PrimaryAudioStream { get; }

		VideoStream? PrimaryVideoStream { get; }

		SubtitleStream? PrimarySubtitleStream { get; }

		List<VideoStream> VideoStreams { get; }

		List<AudioStream> AudioStreams { get; }

		List<SubtitleStream> SubtitleStreams { get; }

		IReadOnlyList<string> ErrorData { get; }
	}
	internal class MediaAnalysis : IMediaAnalysis
	{
		public TimeSpan Duration => new TimeSpan[3]
		{
			Format.Duration,
			PrimaryVideoStream?.Duration ?? TimeSpan.Zero,
			PrimaryAudioStream?.Duration ?? TimeSpan.Zero
		}.Max();

		public MediaFormat Format { get; }

		public List<ChapterData> Chapters { get; }

		public AudioStream? PrimaryAudioStream => AudioStreams.OrderBy((AudioStream stream) => stream.Index).FirstOrDefault();

		public VideoStream? PrimaryVideoStream => VideoStreams.OrderBy((VideoStream stream) => stream.Index).FirstOrDefault();

		public SubtitleStream? PrimarySubtitleStream => SubtitleStreams.OrderBy((SubtitleStream stream) => stream.Index).FirstOrDefault();

		public List<VideoStream> VideoStreams { get; }

		public List<AudioStream> AudioStreams { get; }

		public List<SubtitleStream> SubtitleStreams { get; }

		public IReadOnlyList<string> ErrorData { get; }

		internal MediaAnalysis(FFProbeAnalysis analysis)
		{
			Format = ParseFormat(analysis.Format);
			Chapters = analysis.Chapters.Select((Chapter c) => ParseChapter(c)).ToList();
			VideoStreams = analysis.Streams.Where((FFProbeStream stream) => stream.CodecType == "video").Select(ParseVideoStream).ToList();
			AudioStreams = analysis.Streams.Where((FFProbeStream stream) => stream.CodecType == "audio").Select(ParseAudioStream).ToList();
			SubtitleStreams = analysis.Streams.Where((FFProbeStream stream) => stream.CodecType == "subtitle").Select(ParseSubtitleStream).ToList();
			ErrorData = analysis.ErrorData;
		}

		private MediaFormat ParseFormat(Format analysisFormat)
		{
			return new MediaFormat
			{
				Duration = MediaAnalysisUtils.ParseDuration(analysisFormat.Duration),
				StartTime = MediaAnalysisUtils.ParseDuration(analysisFormat.StartTime),
				FormatName = analysisFormat.FormatName,
				FormatLongName = analysisFormat.FormatLongName,
				StreamCount = analysisFormat.NbStreams,
				ProbeScore = analysisFormat.ProbeScore,
				BitRate = long.Parse(analysisFormat.BitRate ?? "0"),
				Tags = analysisFormat.Tags.ToCaseInsensitive()
			};
		}

		private string GetValue(string tagName, Dictionary<string, string>? tags, string defaultValue)
		{
			if (tags != null)
			{
				if (!tags.TryGetValue(tagName, out string value))
				{
					return defaultValue;
				}
				return value;
			}
			return defaultValue;
		}

		private ChapterData ParseChapter(Chapter analysisChapter)
		{
			string value = GetValue("title", analysisChapter.Tags, "TitleValueNotSet");
			TimeSpan start = MediaAnalysisUtils.ParseDuration(analysisChapter.StartTime);
			TimeSpan end = MediaAnalysisUtils.ParseDuration(analysisChapter.EndTime);
			return new ChapterData(value, start, end);
		}

		private int? GetBitDepth(FFProbeStream stream)
		{
			int result;
			int num = (int.TryParse(stream.BitsPerRawSample, out result) ? result : stream.BitsPerSample);
			if (num != 0)
			{
				return num;
			}
			return null;
		}

		private VideoStream ParseVideoStream(FFProbeStream stream)
		{
			return new VideoStream
			{
				Index = stream.Index,
				AvgFrameRate = MediaAnalysisUtils.DivideRatio(MediaAnalysisUtils.ParseRatioDouble(stream.AvgFrameRate, '/')),
				BitRate = ((!string.IsNullOrEmpty(stream.BitRate)) ? MediaAnalysisUtils.ParseLongInvariant(stream.BitRate) : 0),
				BitsPerRawSample = ((!string.IsNullOrEmpty(stream.BitsPerRawSample)) ? MediaAnalysisUtils.ParseIntInvariant(stream.BitsPerRawSample) : 0),
				CodecName = stream.CodecName,
				CodecLongName = stream.CodecLongName,
				CodecTag = stream.CodecTag,
				CodecTagString = stream.CodecTagString,
				DisplayAspectRatio = MediaAnalysisUtils.ParseRatioInt(stream.DisplayAspectRatio, ':'),
				SampleAspectRatio = MediaAnalysisUtils.ParseRatioInt(stream.SampleAspectRatio, ':'),
				Duration = MediaAnalysisUtils.ParseDuration(stream.Duration),
				StartTime = MediaAnalysisUtils.ParseDuration(stream.StartTime),
				FrameRate = MediaAnalysisUtils.DivideRatio(MediaAnalysisUtils.ParseRatioDouble(stream.FrameRate, '/')),
				Height = stream.Height.GetValueOrDefault(),
				Width = stream.Width.GetValueOrDefault(),
				Profile = stream.Profile,
				PixelFormat = stream.PixelFormat,
				Level = stream.Level,
				ColorRange = stream.ColorRange,
				ColorSpace = stream.ColorSpace,
				ColorTransfer = stream.ColorTransfer,
				ColorPrimaries = stream.ColorPrimaries,
				Rotation = MediaAnalysisUtils.ParseRotation(stream),
				Language = stream.GetLanguage(),
				Disposition = MediaAnalysisUtils.FormatDisposition(stream.Disposition),
				Tags = stream.Tags.ToCaseInsensitive(),
				BitDepth = GetBitDepth(stream)
			};
		}

		private AudioStream ParseAudioStream(FFProbeStream stream)
		{
			return new AudioStream
			{
				Index = stream.Index,
				BitRate = ((!string.IsNullOrEmpty(stream.BitRate)) ? MediaAnalysisUtils.ParseLongInvariant(stream.BitRate) : 0),
				CodecName = stream.CodecName,
				CodecLongName = stream.CodecLongName,
				CodecTag = stream.CodecTag,
				CodecTagString = stream.CodecTagString,
				Channels = stream.Channels.GetValueOrDefault(),
				ChannelLayout = stream.ChannelLayout,
				Duration = MediaAnalysisUtils.ParseDuration(stream.Duration),
				StartTime = MediaAnalysisUtils.ParseDuration(stream.StartTime),
				SampleRateHz = ((!string.IsNullOrEmpty(stream.SampleRate)) ? MediaAnalysisUtils.ParseIntInvariant(stream.SampleRate) : 0),
				Profile = stream.Profile,
				Language = stream.GetLanguage(),
				Disposition = MediaAnalysisUtils.FormatDisposition(stream.Disposition),
				Tags = stream.Tags.ToCaseInsensitive(),
				BitDepth = GetBitDepth(stream)
			};
		}

		private SubtitleStream ParseSubtitleStream(FFProbeStream stream)
		{
			return new SubtitleStream
			{
				Index = stream.Index,
				BitRate = ((!string.IsNullOrEmpty(stream.BitRate)) ? MediaAnalysisUtils.ParseLongInvariant(stream.BitRate) : 0),
				CodecName = stream.CodecName,
				CodecLongName = stream.CodecLongName,
				Duration = MediaAnalysisUtils.ParseDuration(stream.Duration),
				StartTime = MediaAnalysisUtils.ParseDuration(stream.StartTime),
				Language = stream.GetLanguage(),
				Disposition = MediaAnalysisUtils.FormatDisposition(stream.Disposition),
				Tags = stream.Tags.ToCaseInsensitive()
			};
		}
	}
	public static class MediaAnalysisUtils
	{
		private static readonly Regex DurationRegex = new Regex("^(\\d+):(\\d{1,2}):(\\d{1,2})\\.(\\d{1,3})", RegexOptions.Compiled);

		internal static Dictionary<string, string> ToCaseInsensitive(this Dictionary<string, string>? dictionary)
		{
			return dictionary?.ToDictionary<KeyValuePair<string, string>, string, string>((KeyValuePair<string, string> tag) => tag.Key, (KeyValuePair<string, string> tag) => tag.Value, StringComparer.OrdinalIgnoreCase) ?? new Dictionary<string, string>();
		}

		public static double DivideRatio((double, double) ratio)
		{
			return ratio.Item1 / ratio.Item2;
		}

		public static (int, int) ParseRatioInt(string input, char separator)
		{
			if (string.IsNullOrEmpty(input))
			{
				return (0, 0);
			}
			string[] array = input.Split(new char[1] { separator });
			return (ParseIntInvariant(array[0]), ParseIntInvariant(array[1]));
		}

		public static (double, double) ParseRatioDouble(string input, char separator)
		{
			if (string.IsNullOrEmpty(input))
			{
				return (0.0, 0.0);
			}
			string[] array = input.Split(new char[1] { separator });
			return ((array.Length != 0) ? ParseDoubleInvariant(array[0]) : 0.0, (array.Length > 1) ? ParseDoubleInvariant(array[1]) : 0.0);
		}

		public static double ParseDoubleInvariant(string line)
		{
			return double.Parse(line, NumberStyles.Any, CultureInfo.InvariantCulture);
		}

		public static int ParseIntInvariant(string line)
		{
			return int.Parse(line, NumberStyles.Any, CultureInfo.InvariantCulture);
		}

		public static long ParseLongInvariant(string line)
		{
			return long.Parse(line, NumberStyles.Any, CultureInfo.InvariantCulture);
		}

		public static TimeSpan ParseDuration(string duration)
		{
			if (!string.IsNullOrEmpty(duration))
			{
				Match match = DurationRegex.Match(duration);
				if (match.Success)
				{
					string text = match.Groups[4].Value;
					if (text.Length < 3)
					{
						text = text.PadRight(3, '0');
					}
					int hours = int.Parse(match.Groups[1].Value);
					int minutes = int.Parse(match.Groups[2].Value);
					int seconds = int.Parse(match.Groups[3].Value);
					int milliseconds = int.Parse(text);
					return new TimeSpan(0, hours, minutes, seconds, milliseconds);
				}
				return TimeSpan.Zero;
			}
			return TimeSpan.Zero;
		}

		public static int ParseRotation(FFProbeStream fFProbeStream)
		{
			JsonValue value2;
			Dictionary<string, JsonValue>? obj = fFProbeStream.SideData?.Find((Dictionary<string, JsonValue> item) => item.TryGetValue("side_data_type", out value2) && value2.ToString() == "Display Matrix");
			if (obj != null && obj.TryGetValue("rotation", out JsonValue value))
			{
				return (int)float.Parse(value.ToString());
			}
			return (int)float.Parse(fFProbeStream.GetRotate() ?? "0");
		}

		public static Dictionary<string, bool>? FormatDisposition(Dictionary<string, int>? disposition)
		{
			if (disposition == null)
			{
				return null;
			}
			Dictionary<string, bool> dictionary = new Dictionary<string, bool>(disposition.Count, StringComparer.Ordinal);
			foreach (KeyValuePair<string, int> item in disposition)
			{
				dictionary.Add(item.Key, ToBool(item.Value));
			}
			return dictionary;
			static bool ToBool(int value)
			{
				return value switch
				{
					0 => false, 
					1 => true, 
					_ => throw new ArgumentOutOfRangeException("value", $"Not expected disposition state value: {value}"), 
				};
			}
		}
	}
	public class MediaFormat : ITagsContainer
	{
		public TimeSpan Duration { get; set; }

		public TimeSpan StartTime { get; set; }

		public string FormatName { get; set; }

		public string FormatLongName { get; set; }

		public int StreamCount { get; set; }

		public double ProbeScore { get; set; }

		public double BitRate { get; set; }

		public Dictionary<string, string>? Tags { get; set; }
	}
	public abstract class MediaStream : ITagsContainer
	{
		public int Index { get; set; }

		public string CodecName { get; set; }

		public string CodecLongName { get; set; }

		public string CodecTagString { get; set; }

		public string CodecTag { get; set; }

		public long BitRate { get; set; }

		public TimeSpan StartTime { get; set; }

		public TimeSpan Duration { get; set; }

		public string? Language { get; set; }

		public Dictionary<string, bool>? Disposition { get; set; }

		public Dictionary<string, string>? Tags { get; set; }

		public int? BitDepth { get; set; }

		public Codec GetCodecInfo()
		{
			return FFMpeg.GetCodec(CodecName);
		}
	}
	public class FFProbePacketAnalysis
	{
		[JsonPropertyName("codec_type")]
		public string CodecType { get; set; }

		[JsonPropertyName("stream_index")]
		public int StreamIndex { get; set; }

		[JsonPropertyName("pts")]
		public long Pts { get; set; }

		[JsonPropertyName("pts_time")]
		public string PtsTime { get; set; }

		[JsonPropertyName("dts")]
		public long Dts { get; set; }

		[JsonPropertyName("dts_time")]
		public string DtsTime { get; set; }

		[JsonPropertyName("duration")]
		public int Duration { get; set; }

		[JsonPropertyName("duration_time")]
		public string DurationTime { get; set; }

		[JsonPropertyName("size")]
		public int Size { get; set; }

		[JsonPropertyName("pos")]
		public long Pos { get; set; }

		[JsonPropertyName("flags")]
		public string Flags { get; set; }
	}
	public class FFProbePackets
	{
		[JsonPropertyName("packets")]
		public List<FFProbePacketAnalysis> Packets { get; set; }
	}
	public static class ProcessArgumentsExtensions
	{
		public static IProcessResult StartAndWaitForExit(this ProcessArguments processArguments)
		{
			IProcessInstance val = processArguments.Start();
			try
			{
				return val.WaitForExit();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public static async Task<IProcessResult> StartAndWaitForExitAsync(this ProcessArguments processArguments, CancellationToken cancellationToken = default(CancellationToken))
		{
			IProcessInstance instance = processArguments.Start();
			try
			{
				return await instance.WaitForExitAsync(cancellationToken);
			}
			finally
			{
				((IDisposable)instance)?.Dispose();
			}
		}
	}
	public class SubtitleStream : MediaStream
	{
	}
	public class VideoStream : MediaStream
	{
		public double AvgFrameRate { get; set; }

		public int BitsPerRawSample { get; set; }

		public (int Width, int Height) DisplayAspectRatio { get; set; }

		public (int Width, int Height) SampleAspectRatio { get; set; }

		public string Profile { get; set; }

		public int Width { get; set; }

		public int Height { get; set; }

		public double FrameRate { get; set; }

		public string PixelFormat { get; set; }

		public int Level { get; set; }

		public int Rotation { get; set; }

		public double AverageFrameRate { get; set; }

		public string ColorRange { get; set; }

		public string ColorSpace { get; set; }

		public string ColorTransfer { get; set; }

		public string ColorPrimaries { get; set; }

		public PixelFormat GetPixelFormatInfo()
		{
			return FFMpeg.GetPixelFormat(PixelFormat);
		}
	}
	public static class GlobalFFOptions
	{
		private const string ConfigFile = "ffmpeg.config.json";

		private static FFOptions? _current;

		public static FFOptions Current => _current ?? (_current = LoadFFOptions());

		public static void Configure(Action<FFOptions> optionsAction)
		{
			optionsAction(Current);
		}

		public static void Configure(FFOptions ffOptions)
		{
			_current = ffOptions ?? throw new ArgumentNullException("ffOptions");
		}

		public static string GetFFMpegBinaryPath(FFOptions? ffOptions = null)
		{
			return GetFFBinaryPath("FFMpeg", ffOptions ?? Current);
		}

		public static string GetFFProbeBinaryPath(FFOptions? ffOptions = null)
		{
			return GetFFBinaryPath("FFProbe", ffOptions ?? Current);
		}

		private static string GetFFBinaryPath(string name, FFOptions ffOptions)
		{
			string text = name.ToLowerInvariant();
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				text += ".exe";
			}
			string path = (Environment.Is64BitProcess ? "x64" : "x86");
			foreach (string item in new List<string>
			{
				Path.Combine(ffOptions.BinaryFolder, path),
				ffOptions.BinaryFolder
			})
			{
				string text2 = Path.Combine(item, text);
				if (File.Exists(text2))
				{
					return text2;
				}
			}
			return text;
		}

		private static FFOptions LoadFFOptions()
		{
			if (!File.Exists("ffmpeg.config.json"))
			{
				return new FFOptions();
			}
			return JsonSerializer.Deserialize<FFOptions>(File.ReadAllText("ffmpeg.config.json"));
		}
	}
}
namespace FFMpegCore.Helpers
{
	public static class FFMpegHelper
	{
		private static bool _ffmpegVerified;

		public static void ConversionSizeExceptionCheck(IMediaAnalysis info)
		{
			ConversionSizeExceptionCheck(info.PrimaryVideoStream.Width, info.PrimaryVideoStream.Height);
		}

		public static void ConversionSizeExceptionCheck(int width, int height)
		{
			if (height % 2 != 0 || width % 2 != 0)
			{
				throw new ArgumentException("FFMpeg yuv420p encoding requires the width and height to be a multiple of 2!");
			}
		}

		public static void ExtensionExceptionCheck(string filename, string extension)
		{
			if (!extension.Equals(Path.GetExtension(filename), StringComparison.OrdinalIgnoreCase))
			{
				throw new FFMpegException(FFMpegExceptionType.File, "Invalid output file. File extension should be '" + extension + "' required.");
			}
		}

		public static void RootExceptionCheck()
		{
			if (GlobalFFOptions.Current.BinaryFolder == null)
			{
				throw new FFOptionsException("FFMpeg root is not configured in app config. Missing key 'BinaryFolder'.");
			}
		}

		public static void VerifyFFMpegExists(FFOptions ffMpegOptions)
		{
			if (!_ffmpegVerified)
			{
				_ffmpegVerified = Instance.Finish(GlobalFFOptions.GetFFMpegBinaryPath(ffMpegOptions), "-version", (EventHandler<string>)null, (EventHandler<string>)null).ExitCode == 0;
				if (!_ffmpegVerified)
				{
					throw new FFMpegException(FFMpegExceptionType.Operation, "ffmpeg was not found on your system");
				}
			}
		}
	}
	public static class FFProbeHelper
	{
		private static bool _ffprobeVerified;

		public static void RootExceptionCheck()
		{
			if (GlobalFFOptions.Current.BinaryFolder == null)
			{
				throw new FFOptionsException("FFProbe root is not configured in app config. Missing key 'BinaryFolder'.");
			}
		}

		public static void VerifyFFProbeExists(FFOptions ffMpegOptions)
		{
			if (!_ffprobeVerified)
			{
				_ffprobeVerified = Instance.Finish(GlobalFFOptions.GetFFProbeBinaryPath(ffMpegOptions), "-version", (EventHandler<string>)null, (EventHandler<string>)null).ExitCode == 0;
				if (!_ffprobeVerified)
				{
					throw new FFProbeException("ffprobe was not found on your system");
				}
			}
		}
	}
}
namespace FFMpegCore.Pipes
{
	public interface IAudioSample
	{
		void Serialize(Stream stream);

		Task SerializeAsync(Stream stream, CancellationToken token);
	}
	public interface IPipeSink
	{
		Task ReadAsync(Stream inputStream, CancellationToken cancellationToken);

		string GetFormat();
	}
	public interface IPipeSource
	{
		string GetStreamArguments();

		Task WriteAsync(Stream outputStream, CancellationToken cancellationToken);
	}
	public interface IVideoFrame
	{
		int Width { get; }

		int Height { get; }

		string Format { get; }

		void Serialize(Stream pipe);

		Task SerializeAsync(Stream pipe, CancellationToken token);
	}
	internal static class PipeHelpers
	{
		public static string GetUnqiuePipeName()
		{
			return "FFMpegCore_" + Guid.NewGuid().ToString("N").Substring(0, 5);
		}

		public static string GetPipePath(string pipeName)
		{
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				return "\\\\.\\pipe\\" + pipeName;
			}
			return "unix:" + Path.Combine(Path.GetTempPath(), "CoreFxPipe_" + pipeName);
		}
	}
	public class RawAudioPipeSource : IPipeSource
	{
		private readonly IEnumerator<IAudioSample> _sampleEnumerator;

		public string Format { get; set; } = "s16le";


		public uint SampleRate { get; set; } = 8000u;


		public uint Channels { get; set; } = 1u;


		public RawAudioPipeSource(IEnumerator<IAudioSample> sampleEnumerator)
		{
			_sampleEnumerator = sampleEnumerator;
		}

		public RawAudioPipeSource(IEnumerable<IAudioSample> sampleEnumerator)
			: this(sampleEnumerator.GetEnumerator())
		{
		}

		public string GetStreamArguments()
		{
			return $"-f {Format} -ar {SampleRate} -ac {Channels}";
		}

		public async Task WriteAsync(Stream outputStream, CancellationToken cancellationToken)
		{
			if (_sampleEnumerator.MoveNext() && _sampleEnumerator.Current != null)
			{
				await _sampleEnumerator.Current.SerializeAsync(outputStream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			while (_sampleEnumerator.MoveNext())
			{
				await _sampleEnumerator.Current.SerializeAsync(outputStream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
		}
	}
	public class RawVideoPipeSource : IPipeSource
	{
		private bool _formatInitialized;

		private readonly IEnumerator<IVideoFrame> _framesEnumerator;

		public string StreamFormat { get; private set; }

		public int Width { get; private set; }

		public int Height { get; private set; }

		public double FrameRate { get; set; } = 25.0;


		public RawVideoPipeSource(IEnumerable<IVideoFrame> framesEnumerator)
		{
			_framesEnumerator = framesEnumerator.GetEnumerator();
		}

		public string GetStreamArguments()
		{
			if (!_formatInitialized)
			{
				if (_framesEnumerator.Current == null && !_framesEnumerator.MoveNext())
				{
					throw new InvalidOperationException("Enumerator is empty, unable to get frame");
				}
				StreamFormat = _framesEnumerator.Current.Format;
				Width = _framesEnumerator.Current.Width;
				Height = _framesEnumerator.Current.Height;
				_formatInitialized = true;
			}
			return $"-f rawvideo -r {FrameRate.ToString(CultureInfo.InvariantCulture)} -pix_fmt {StreamFormat} -s {Width}x{Height}";
		}

		public async Task WriteAsync(Stream outputStream, CancellationToken cancellationToken)
		{
			if (_framesEnumerator.Current != null)
			{
				CheckFrameAndThrow(_framesEnumerator.Current);
				await _framesEnumerator.Current.SerializeAsync(outputStream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			while (_framesEnumerator.MoveNext())
			{
				CheckFrameAndThrow(_framesEnumerator.Current);
				await _framesEnumerator.Current.SerializeAsync(outputStream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
		}

		private void CheckFrameAndThrow(IVideoFrame frame)
		{
			if (frame.Width != Width || frame.Height != Height || frame.Format != StreamFormat)
			{
				throw new FFMpegStreamFormatException(FFMpegExceptionType.Operation, "Video frame is not the same format as created raw video stream\r\n" + $"Frame format: {frame.Width}x{frame.Height} pix_fmt: {frame.Format}\r\n" + $"Stream format: {Width}x{Height} pix_fmt: {StreamFormat}");
			}
		}
	}
	public class StreamPipeSink : IPipeSink
	{
		public Func<Stream, CancellationToken, Task> Writer { get; }

		public int BlockSize { get; set; } = 4096;


		public string Format { get; set; } = string.Empty;


		public StreamPipeSink(Func<Stream, CancellationToken, Task> writer)
		{
			Writer = writer;
		}

		public StreamPipeSink(Stream destination)
		{
			Stream destination2 = destination;
			base..ctor();
			StreamPipeSink streamPipeSink = this;
			Writer = (Stream inputStream, CancellationToken cancellationToken) => inputStream.CopyToAsync(destination2, streamPipeSink.BlockSize, cancellationToken);
		}

		public async Task ReadAsync(Stream inputStream, CancellationToken cancellationToken)
		{
			await Writer(inputStream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public string GetFormat()
		{
			return Format;
		}
	}
	public class StreamPipeSource : IPipeSource
	{
		public Stream Source { get; }

		public int BlockSize { get; } = 4096;


		public string StreamFormat { get; } = string.Empty;


		public StreamPipeSource(Stream source)
		{
			Source = source;
		}

		public string GetStreamArguments()
		{
			return StreamFormat;
		}

		public Task WriteAsync(Stream outputStream, CancellationToken cancellationToken)
		{
			return Source.CopyToAsync(outputStream, BlockSize, cancellationToken);
		}
	}
}
namespace FFMpegCore.Exceptions
{
	public enum FFMpegExceptionType
	{
		Conversion,
		File,
		Operation,
		Process
	}
	public class FFMpegException : Exception
	{
		public FFMpegExceptionType Type { get; }

		public string FFMpegErrorOutput { get; }

		public FFMpegException(FFMpegExceptionType type, string message, Exception? innerException = null, string ffMpegErrorOutput = "")
			: base(message, innerException)
		{
			FFMpegErrorOutput = ffMpegErrorOutput;
			Type = type;
		}

		public FFMpegException(FFMpegExceptionType type, string message, string ffMpegErrorOutput = "")
			: base(message)
		{
			FFMpegErrorOutput = ffMpegErrorOutput;
			Type = type;
		}

		public FFMpegException(FFMpegExceptionType type, string message)
			: base(message)
		{
			FFMpegErrorOutput = string.Empty;
			Type = type;
		}
	}
	public class FFOptionsException : Exception
	{
		public FFOptionsException(string message, Exception? innerException = null)
			: base(message, innerException)
		{
		}
	}
	public class FFMpegArgumentException : Exception
	{
		public FFMpegArgumentException(string? message = null, Exception? innerException = null)
			: base(message, innerException)
		{
		}
	}
	public class FFMpegStreamFormatException : FFMpegException
	{
		public FFMpegStreamFormatException(FFMpegExceptionType type, string message, Exception? innerException = null)
			: base(type, message, innerException)
		{
		}
	}
	public class FFProbeException : Exception
	{
		public FFProbeException(string message, Exception? inner = null)
			: base(message, inner)
		{
		}
	}
	public class FFProbeProcessException : FFProbeException
	{
		public IReadOnlyCollection<string> ProcessErrors { get; }

		public FFProbeProcessException(string message, IReadOnlyCollection<string> processErrors, Exception? inner = null)
			: base(message, inner)
		{
			ProcessErrors = processErrors;
		}
	}
	public class FormatNullException : FFProbeException
	{
		public FormatNullException()
			: base("Format not specified")
		{
		}
	}
}
namespace FFMpegCore.Enums
{
	public enum AudioQuality
	{
		Ultra = 384,
		VeryHigh = 256,
		Good = 192,
		Normal = 128,
		BelowNormal = 96,
		Low = 64
	}
	public enum FeatureStatus
	{
		Unknown,
		NotSupported,
		Supported
	}
	public class Codec
	{
		public class FeatureLevel
		{
			public bool IsExperimental { get; internal set; }

			public FeatureStatus SupportsFrameLevelMultithreading { get; internal set; }

			public FeatureStatus SupportsSliceLevelMultithreading { get; internal set; }

			public FeatureStatus SupportsDrawHorizBand { get; internal set; }

			public FeatureStatus SupportsDirectRendering { get; internal set; }

			internal void Merge(FeatureLevel other)
			{
				IsExperimental |= other.IsExperimental;
				SupportsFrameLevelMultithreading = (FeatureStatus)Math.Max((int)SupportsFrameLevelMultithreading, (int)other.SupportsFrameLevelMultithreading);
				SupportsSliceLevelMultithreading = (FeatureStatus)Math.Max((int)SupportsSliceLevelMultithreading, (int)other.SupportsSliceLevelMultithreading);
				SupportsDrawHorizBand = (FeatureStatus)Math.Max((int)SupportsDrawHorizBand, (int)other.SupportsDrawHorizBand);
				SupportsDirectRendering = (FeatureStatus)Math.Max((int)SupportsDirectRendering, (int)other.SupportsDirectRendering);
			}
		}

		private static readonly Regex _codecsFormatRegex = new Regex("([D\\.])([E\\.])([VASD\\.])([I\\.])([L\\.])([S\\.])\\s+([a-z0-9_-]+)\\s+(.+)");

		private static readonly Regex _decodersEncodersFormatRegex = new Regex("([VASD\\.])([F\\.])([S\\.])([X\\.])([B\\.])([D\\.])\\s+([a-z0-9_-]+)\\s+(.+)");

		public string Name { get; private set; }

		public CodecType Type { get; private set; }

		public bool DecodingSupported { get; private set; }

		public bool EncodingSupported { get; private set; }

		public bool IsIntraFrameOnly { get; private set; }

		public bool IsLossy { get; private set; }

		public bool IsLossless { get; private set; }

		public string Description { get; private set; }

		public FeatureLevel EncoderFeatureLevel { get; private set; }

		public FeatureLevel DecoderFeatureLevel { get; private set; }

		internal Codec(string name, CodecType type)
		{
			EncoderFeatureLevel = new FeatureLevel();
			DecoderFeatureLevel = new FeatureLevel();
			Name = name;
			Type = type;
		}

		internal static bool TryParseFromCodecs(string line, out Codec codec)
		{
			Match match = _codecsFormatRegex.Match(line);
			if (!match.Success)
			{
				codec = null;
				return false;
			}
			string value = match.Groups[7].Value;
			CodecType codecType = match.Groups[3].Value switch
			{
				"V" => CodecType.Video, 
				"A" => CodecType.Audio, 
				"D" => CodecType.Data, 
				"S" => CodecType.Subtitle, 
				_ => CodecType.Unknown, 
			};
			if (codecType == CodecType.Unknown)
			{
				codec = null;
				return false;
			}
			codec = new Codec(value, codecType);
			codec.DecodingSupported = match.Groups[1].Value != ".";
			codec.EncodingSupported = match.Groups[2].Value != ".";
			codec.IsIntraFrameOnly = match.Groups[4].Value != ".";
			codec.IsLossy = match.Groups[5].Value != ".";
			codec.IsLossless = match.Groups[6].Value != ".";
			codec.Description = match.Groups[8].Value;
			return true;
		}

		internal static bool TryParseFromEncodersDecoders(string line, out Codec codec, bool isEncoder)
		{
			Match match = _decodersEncodersFormatRegex.Match(line);
			if (!match.Success)
			{
				codec = null;
				return false;
			}
			string value = match.Groups[7].Value;
			CodecType codecType = match.Groups[1].Value switch
			{
				"V" => CodecType.Video, 
				"A" => CodecType.Audio, 
				"D" => CodecType.Data, 
				"S" => CodecType.Subtitle, 
				_ => CodecType.Unknown, 
			};
			if (codecType == CodecType.Unknown)
			{
				codec = null;
				return false;
			}
			codec = new Codec(value, codecType);
			FeatureLevel obj = (isEncoder ? codec.EncoderFeatureLevel : codec.DecoderFeatureLevel);
			codec.DecodingSupported = !isEncoder;
			codec.EncodingSupported = isEncoder;
			obj.SupportsFrameLevelMultithreading = ((!(match.Groups[2].Value != ".")) ? FeatureStatus.NotSupported : FeatureStatus.Supported);
			obj.SupportsSliceLevelMultithreading = ((!(match.Groups[3].Value != ".")) ? FeatureStatus.NotSupported : FeatureStatus.Supported);
			obj.IsExperimental = match.Groups[4].Value != ".";
			obj.SupportsDrawHorizBand = ((!(match.Groups[5].Value != ".")) ? FeatureStatus.NotSupported : FeatureStatus.Supported);
			obj.SupportsDirectRendering = ((!(match.Groups[6].Value != ".")) ? FeatureStatus.NotSupported : FeatureStatus.Supported);
			codec.Description = match.Groups[8].Value;
			return true;
		}

		internal void Merge(Codec other)
		{
			if (Name != other.Name)
			{
				throw new FFMpegException(FFMpegExceptionType.Operation, "different codecs enable to merge");
			}
			Type |= other.Type;
			DecodingSupported |= other.DecodingSupported;
			EncodingSupported |= other.EncodingSupported;
			IsIntraFrameOnly |= other.IsIntraFrameOnly;
			IsLossy |= other.IsLossy;
			IsLossless |= other.IsLossless;
			EncoderFeatureLevel.Merge(other.EncoderFeatureLevel);
			DecoderFeatureLevel.Merge(other.DecoderFeatureLevel);
			if (Description != other.Description)
			{
				Description = Description + "\r\n" + other.Description;
			}
		}
	}
	public class ContainerFormat
	{
		private static readonly Regex FormatRegex = new Regex("([D ])([E ])\\s+([a-z0-9_]+)\\s+(.+)");

		public string Name { get; private set; }

		public bool DemuxingSupported { get; private set; }

		public bool MuxingSupported { get; private set; }

		public string Description { get; private set; }

		public string Extension
		{
			get
			{
				if (GlobalFFOptions.Current.ExtensionOverrides.ContainsKey(Name))
				{
					return GlobalFFOptions.Current.ExtensionOverrides[Name];
				}
				return "." + Name;
			}
		}

		internal ContainerFormat(string name)
		{
			Name = name;
		}

		internal static bool TryParse(string line, out ContainerFormat fmt)
		{
			Match match = FormatRegex.Match(line);
			if (!match.Success)
			{
				fmt = null;
				return false;
			}
			fmt = new ContainerFormat(match.Groups[3].Value)
			{
				DemuxingSupported = (match.Groups[1].Value != " "),
				MuxingSupported = (match.Groups[2].Value != " "),
				Description = match.Groups[4].Value
			};
			return true;
		}
	}
	public enum CodecType
	{
		Unknown = 0,
		Video = 2,
		Audio = 4,
		Subtitle = 8,
		Data = 0x10
	}
	public static class VideoCodec
	{
		public static Codec LibX264 => FFMpeg.GetCodec("libx264");

		public static Codec LibX265 => FFMpeg.GetCodec("libx265");

		public static Codec LibVpx => FFMpeg.GetCodec("libvpx");

		public static Codec LibTheora => FFMpeg.GetCodec("libtheora");

		public static Codec Png => FFMpeg.GetCodec("png");

		public static Codec MpegTs => FFMpeg.GetCodec("mpegts");

		public static Codec LibaomAv1 => FFMpeg.GetCodec("libaom-av1");
	}
	public static class AudioCodec
	{
		public static Codec Aac => FFMpeg.GetCodec("aac");

		public static Codec LibVorbis => FFMpeg.GetCodec("libvorbis");

		public static Codec LibFdk_Aac => FFMpeg.GetCodec("libfdk_aac");

		public static Codec Ac3 => FFMpeg.GetCodec("ac3");

		public static Codec Eac3 => FFMpeg.GetCodec("eac3");

		public static Codec LibMp3Lame => FFMpeg.GetCodec("libmp3lame");

		public static Codec Copy => new Codec("copy", CodecType.Audio);
	}
	public static class VideoType
	{
		public static ContainerFormat MpegTs => FFMpeg.GetContainerFormat("mpegts");

		public static ContainerFormat Ts => FFMpeg.GetContainerFormat("mpegts");

		public static ContainerFormat Mp4 => FFMpeg.GetContainerFormat("mp4");

		public s

Instances.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Instances.Exceptions;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Malte Rosenbjerg")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Rosenbjerg Softworks")]
[assembly: AssemblyDescription("A .NET Standard Process wrapper with an elegant API, for both asyncronous and syncronous use, providing both Events and support for Tasks with cancellation support")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+cd0a6c6f638b9e2f6025c6f61780511bf9c2f2c2")]
[assembly: AssemblyProduct("Instances")]
[assembly: AssemblyTitle("Instances")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/rosenbjerg/Instances")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace Instances
{
	public static class Instance
	{
		public static IProcessInstance Start(string path, string arguments = "", EventHandler<string>? outputHandler = null, EventHandler<string>? errorHandler = null)
		{
			return Start(new ProcessStartInfo
			{
				FileName = path,
				Arguments = arguments
			}, outputHandler, errorHandler);
		}

		public static IProcessInstance Start(ProcessStartInfo startInfo, EventHandler<string>? outputHandler, EventHandler<string>? errorHandler)
		{
			ProcessArguments processArguments = new ProcessArguments(startInfo);
			if (outputHandler != null)
			{
				processArguments.OutputDataReceived += outputHandler;
			}
			if (errorHandler != null)
			{
				processArguments.ErrorDataReceived += errorHandler;
			}
			return processArguments.Start();
		}

		public static IProcessResult Finish(string path, string arguments = "", EventHandler<string>? outputHandler = null, EventHandler<string>? errorHandler = null)
		{
			return Finish(new ProcessStartInfo
			{
				FileName = path,
				Arguments = arguments
			}, outputHandler, errorHandler);
		}

		public static IProcessResult Finish(ProcessStartInfo startInfo, EventHandler<string>? outputHandler = null, EventHandler<string>? errorHandler = null)
		{
			using IProcessInstance processInstance = Start(startInfo, outputHandler, errorHandler);
			return processInstance.WaitForExit();
		}

		public static Task<IProcessResult> FinishAsync(string path, string arguments = "", CancellationToken cancellationToken = default(CancellationToken), EventHandler<string>? outputHandler = null, EventHandler<string>? errorHandler = null)
		{
			return FinishAsync(new ProcessStartInfo
			{
				FileName = path,
				Arguments = arguments
			}, cancellationToken, outputHandler, errorHandler);
		}

		public static async Task<IProcessResult> FinishAsync(ProcessStartInfo startInfo, CancellationToken cancellationToken = default(CancellationToken), EventHandler<string>? outputHandler = null, EventHandler<string>? errorHandler = null)
		{
			using IProcessInstance instance = Start(startInfo, outputHandler, errorHandler);
			return await instance.WaitForExitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}
	}
	public interface IProcessInstance : IDisposable
	{
		IReadOnlyCollection<string> OutputData { get; }

		IReadOnlyCollection<string> ErrorData { get; }

		event EventHandler<IProcessResult>? Exited;

		event EventHandler<string>? OutputDataReceived;

		event EventHandler<string>? ErrorDataReceived;

		Task SendInputAsync(string input);

		void SendInput(string input);

		Task<IProcessResult> WaitForExitAsync(CancellationToken cancellationToken = default(CancellationToken));

		IProcessResult WaitForExit();

		IProcessResult Kill();
	}
	public interface IProcessResult
	{
		int ExitCode { get; }

		IReadOnlyList<string> OutputData { get; }

		IReadOnlyList<string> ErrorData { get; }
	}
	public class ProcessArguments
	{
		private readonly ProcessStartInfo _processStartInfo;

		public bool IgnoreEmptyLines { get; set; }

		public int DataBufferCapacity { get; set; } = int.MaxValue;


		public event EventHandler<IProcessResult>? Exited;

		public event EventHandler<string>? OutputDataReceived;

		public event EventHandler<string>? ErrorDataReceived;

		public ProcessArguments(string path, string arguments)
			: this(new ProcessStartInfo
			{
				FileName = path,
				Arguments = arguments
			})
		{
		}

		public ProcessArguments(ProcessStartInfo processStartInfo)
		{
			_processStartInfo = processStartInfo;
		}

		public IProcessInstance Start()
		{
			_processStartInfo.CreateNoWindow = true;
			_processStartInfo.UseShellExecute = false;
			_processStartInfo.RedirectStandardOutput = true;
			_processStartInfo.RedirectStandardInput = true;
			_processStartInfo.RedirectStandardError = true;
			Process process = new Process
			{
				StartInfo = _processStartInfo,
				EnableRaisingEvents = true
			};
			ProcessInstance processInstance = new ProcessInstance(process, IgnoreEmptyLines, DataBufferCapacity);
			processInstance.Exited += this.Exited;
			processInstance.OutputDataReceived += this.OutputDataReceived;
			processInstance.ErrorDataReceived += this.ErrorDataReceived;
			try
			{
				process.Start();
				process.BeginOutputReadLine();
				process.BeginErrorReadLine();
				return processInstance;
			}
			catch (Win32Exception ex) when (ex.Message.Contains("The system cannot find the file specified") || ex.Message.Contains("No such file or directory"))
			{
				throw new InstanceFileNotFoundException(_processStartInfo.FileName, ex);
			}
		}
	}
	public static class ProcessArgumentsExtensions
	{
		public static IProcessResult StartAndWaitForExit(this ProcessArguments processArguments)
		{
			using IProcessInstance processInstance = processArguments.Start();
			return processInstance.WaitForExit();
		}

		public static async Task<IProcessResult> StartAndWaitForExitAsync(this ProcessArguments processArguments, CancellationToken cancellationToken = default(CancellationToken))
		{
			using IProcessInstance instance = processArguments.Start();
			return await instance.WaitForExitAsync(cancellationToken);
		}
	}
	public class ProcessInstance : IProcessInstance, IDisposable
	{
		private readonly bool _ignoreEmptyLines;

		private readonly int _dataBufferCapacity;

		private readonly Process _process;

		private readonly TaskCompletionSource<bool> _mainTask = new TaskCompletionSource<bool>();

		private readonly TaskCompletionSource<bool> _stdoutTask = new TaskCompletionSource<bool>();

		private readonly TaskCompletionSource<bool> _stderrTask = new TaskCompletionSource<bool>();

		private readonly Queue<string> _outputData = new Queue<string>();

		private readonly Queue<string> _errorData = new Queue<string>();

		public IReadOnlyCollection<string> OutputData => _outputData.ToList().AsReadOnly();

		public IReadOnlyCollection<string> ErrorData => _errorData.ToList().AsReadOnly();

		public event EventHandler<IProcessResult>? Exited;

		public event EventHandler<string>? OutputDataReceived;

		public event EventHandler<string>? ErrorDataReceived;

		internal ProcessInstance(Process process, bool ignoreEmptyLines, int dataBufferCapacity)
		{
			process.OutputDataReceived += ReceiveOutput;
			process.ErrorDataReceived += ReceiveError;
			process.Exited += ReceiveExit;
			_process = process;
			_ignoreEmptyLines = ignoreEmptyLines;
			_dataBufferCapacity = dataBufferCapacity;
		}

		public async Task SendInputAsync(string input)
		{
			ThrowIfProcessExited();
			await _process.StandardInput.WriteAsync(input).ConfigureAwait(continueOnCapturedContext: false);
			await _process.StandardInput.FlushAsync().ConfigureAwait(continueOnCapturedContext: false);
		}

		public void SendInput(string input)
		{
			ThrowIfProcessExited();
			_process.StandardInput.Write(input);
			_process.StandardInput.Flush();
		}

		public IProcessResult Kill()
		{
			try
			{
				_process.Kill();
				return GetResult();
			}
			catch (InvalidOperationException innerException)
			{
				throw new InstanceProcessAlreadyExitedException(innerException);
			}
		}

		public async Task<IProcessResult> WaitForExitAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (cancellationToken != default(CancellationToken))
			{
				cancellationToken.Register(delegate
				{
					if (!_process.HasExited)
					{
						_process.Kill();
					}
				});
			}
			await _mainTask.Task.ConfigureAwait(continueOnCapturedContext: false);
			return GetResult();
		}

		public IProcessResult WaitForExit()
		{
			try
			{
				_process.WaitForExit();
				return GetResult();
			}
			catch (SystemException innerException)
			{
				throw new InstanceProcessAlreadyExitedException(innerException);
			}
		}

		public void Dispose()
		{
			_process.Dispose();
		}

		private void ReceiveExit(object sender, EventArgs e)
		{
			object sender2 = sender;
			Task.WhenAll<bool>(_stdoutTask.Task, _stderrTask.Task).ContinueWith(delegate
			{
				this.Exited?.Invoke(sender2, GetResult());
				return _mainTask.TrySetResult(result: true);
			});
		}

		private void ReceiveOutput(object _, DataReceivedEventArgs e)
		{
			AddData(_outputData, e.Data, this.OutputDataReceived, _stdoutTask);
		}

		private void ReceiveError(object _, DataReceivedEventArgs e)
		{
			AddData(_errorData, e.Data, this.ErrorDataReceived, _stderrTask);
		}

		private void AddData(Queue<string> dataList, string? data, EventHandler<string>? eventHandler, TaskCompletionSource<bool> taskCompletionSource)
		{
			if (data == null)
			{
				taskCompletionSource.TrySetResult(result: true);
			}
			else if (!_ignoreEmptyLines || !(data == string.Empty))
			{
				dataList.Enqueue(data);
				for (int i = 0; i < dataList.Count - _dataBufferCapacity; i++)
				{
					dataList.Dequeue();
				}
				eventHandler?.Invoke(this, data);
			}
		}

		private IProcessResult GetResult()
		{
			return new ProcessResult(_process.HasExited ? _process.ExitCode : (-100), _outputData.ToArray(), _errorData.ToArray());
		}

		private void ThrowIfProcessExited()
		{
			if (_process.HasExited)
			{
				throw new InstanceProcessAlreadyExitedException();
			}
		}
	}
	public class ProcessResult : IProcessResult
	{
		public int ExitCode { get; }

		public IReadOnlyList<string> OutputData { get; }

		public IReadOnlyList<string> ErrorData { get; }

		internal ProcessResult(int exitCode, IReadOnlyList<string> outputData, IReadOnlyList<string> errorData)
		{
			OutputData = outputData;
			ErrorData = errorData;
			ExitCode = exitCode;
		}
	}
}
namespace Instances.Exceptions
{
	public class InstanceException : Exception
	{
		public InstanceException(string msg, Exception innerException)
			: base(msg, innerException)
		{
		}
	}
	public class InstanceFileNotFoundException : InstanceException
	{
		public InstanceFileNotFoundException(string fileName, Exception innerException)
			: base("File not found: " + fileName, innerException)
		{
		}
	}
	public class InstanceProcessAlreadyExitedException : Exception
	{
		public InstanceProcessAlreadyExitedException()
			: base("The process instance has already exited")
		{
		}

		public InstanceProcessAlreadyExitedException(Exception innerException)
			: base("The process instance has already exited", innerException)
		{
		}
	}
}

Microsoft.Bcl.AsyncInterfaces.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Bcl.AsyncInterfaces")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides the IAsyncEnumerable<T> and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.")]
[assembly: AssemblyFileVersion("9.0.225.6610")]
[assembly: AssemblyInformationalVersion("9.0.2+80aa709f5d919c6814726788dc6dabe23e79e672")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.2")]
[assembly: TypeForwardedTo(typeof(IAsyncEnumerable<>))]
[assembly: TypeForwardedTo(typeof(IAsyncEnumerator<>))]
[assembly: TypeForwardedTo(typeof(IAsyncDisposable))]
[assembly: TypeForwardedTo(typeof(AsyncIteratorMethodBuilder))]
[assembly: TypeForwardedTo(typeof(AsyncIteratorStateMachineAttribute))]
[assembly: TypeForwardedTo(typeof(ConfiguredAsyncDisposable))]
[assembly: TypeForwardedTo(typeof(ConfiguredCancelableAsyncEnumerable<>))]
[assembly: TypeForwardedTo(typeof(EnumeratorCancellationAttribute))]
[assembly: TypeForwardedTo(typeof(ManualResetValueTaskSourceCore<>))]
[assembly: TypeForwardedTo(typeof(TaskAsyncEnumerableExtensions))]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}

System.Buffers.dll

Decompiled 3 months ago
using 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.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.All)]
	internal class __BlockReflectionAttribute : Attribute
	{
	}
}
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;
		}
	}
}

System.IO.Pipelines.dll

Decompiled 3 months ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using FxResources.System.IO.Pipelines;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.IO.Pipelines.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.IO.Pipelines")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Single producer single consumer byte buffer management.\r\n\r\nCommonly Used Types:\r\nSystem.IO.Pipelines.Pipe\r\nSystem.IO.Pipelines.PipeWriter\r\nSystem.IO.Pipelines.PipeReader")]
[assembly: AssemblyFileVersion("9.0.225.6610")]
[assembly: AssemblyInformationalVersion("9.0.2+80aa709f5d919c6814726788dc6dabe23e79e672")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.IO.Pipelines")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(true)]
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]
	[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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 FxResources.System.IO.Pipelines
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string AdvanceToInvalidCursor => GetResourceString("AdvanceToInvalidCursor");

		internal static string ArgumentOutOfRange_NeedPosNum => GetResourceString("ArgumentOutOfRange_NeedPosNum");

		internal static string ConcurrentOperationsNotSupported => GetResourceString("ConcurrentOperationsNotSupported");

		internal static string FlushCanceledOnPipeWriter => GetResourceString("FlushCanceledOnPipeWriter");

		internal static string GetResultBeforeCompleted => GetResourceString("GetResultBeforeCompleted");

		internal static string InvalidExaminedOrConsumedPosition => GetResourceString("InvalidExaminedOrConsumedPosition");

		internal static string InvalidExaminedPosition => GetResourceString("InvalidExaminedPosition");

		internal static string InvalidZeroByteRead => GetResourceString("InvalidZeroByteRead");

		internal static string ObjectDisposed_StreamClosed => GetResourceString("ObjectDisposed_StreamClosed");

		internal static string NoReadingOperationToComplete => GetResourceString("NoReadingOperationToComplete");

		internal static string NotSupported_UnreadableStream => GetResourceString("NotSupported_UnreadableStream");

		internal static string NotSupported_UnwritableStream => GetResourceString("NotSupported_UnwritableStream");

		internal static string ReadCanceledOnPipeReader => GetResourceString("ReadCanceledOnPipeReader");

		internal static string ReaderAndWriterHasToBeCompleted => GetResourceString("ReaderAndWriterHasToBeCompleted");

		internal static string ReadingAfterCompleted => GetResourceString("ReadingAfterCompleted");

		internal static string ReadingIsInProgress => GetResourceString("ReadingIsInProgress");

		internal static string WritingAfterCompleted => GetResourceString("WritingAfterCompleted");

		internal static string UnflushedBytesNotSupported => GetResourceString("UnflushedBytesNotSupported");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		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);
		}

		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(IFormatProvider? provider, string resourceFormat, object? p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string? EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type? StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Threading
{
	internal static class CancellationTokenExtensions
	{
		internal static CancellationTokenRegistration UnsafeRegister(this CancellationToken cancellationToken, Action<object> callback, object state)
		{
			return cancellationToken.Register(callback, state);
		}
	}
}
namespace System.Threading.Tasks
{
	internal static class TaskToAsyncResult
	{
		private sealed class TaskAsyncResult : IAsyncResult
		{
			internal readonly Task _task;

			private readonly AsyncCallback _callback;

			public object AsyncState { get; }

			public bool CompletedSynchronously { get; }

			public bool IsCompleted => _task.IsCompleted;

			public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle;

			internal TaskAsyncResult(Task task, object state, AsyncCallback callback)
			{
				_task = task;
				AsyncState = state;
				if (task.IsCompleted)
				{
					CompletedSynchronously = true;
					callback?.Invoke(this);
				}
				else if (callback != null)
				{
					_callback = callback;
					_task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().OnCompleted(delegate
					{
						_callback(this);
					});
				}
			}
		}

		public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? state)
		{
			if (task == null)
			{
				throw new ArgumentNullException("task");
			}
			return new TaskAsyncResult(task, state, callback);
		}

		public static void End(IAsyncResult asyncResult)
		{
			Unwrap(asyncResult).GetAwaiter().GetResult();
		}

		public static TResult End<TResult>(IAsyncResult asyncResult)
		{
			return Unwrap<TResult>(asyncResult).GetAwaiter().GetResult();
		}

		public static Task Unwrap(IAsyncResult asyncResult)
		{
			if (asyncResult == null)
			{
				throw new ArgumentNullException("asyncResult");
			}
			return (asyncResult as TaskAsyncResult)?._task ?? throw new ArgumentException(null, "asyncResult");
		}

		public static Task<TResult> Unwrap<TResult>(IAsyncResult asyncResult)
		{
			if (asyncResult == null)
			{
				throw new ArgumentNullException("asyncResult");
			}
			return ((asyncResult as TaskAsyncResult)?._task as Task<TResult>) ?? throw new ArgumentException(null, "asyncResult");
		}
	}
}
namespace System.IO
{
	internal static class StreamHelpers
	{
		public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize)
		{
			if (destination == null)
			{
				throw new ArgumentNullException("destination");
			}
			if (bufferSize <= 0)
			{
				throw new ArgumentOutOfRangeException("bufferSize", bufferSize, System.SR.ArgumentOutOfRange_NeedPosNum);
			}
			bool canRead = source.CanRead;
			if (!canRead && !source.CanWrite)
			{
				throw new ObjectDisposedException(null, System.SR.ObjectDisposed_StreamClosed);
			}
			bool canWrite = destination.CanWrite;
			if (!canWrite && !destination.CanRead)
			{
				throw new ObjectDisposedException("destination", System.SR.ObjectDisposed_StreamClosed);
			}
			if (!canRead)
			{
				throw new NotSupportedException(System.SR.NotSupported_UnreadableStream);
			}
			if (!canWrite)
			{
				throw new NotSupportedException(System.SR.NotSupported_UnwritableStream);
			}
		}
	}
}
namespace System.IO.Pipelines
{
	internal sealed class BufferSegment : ReadOnlySequenceSegment<byte>
	{
		private IMemoryOwner<byte> _memoryOwner;

		private byte[] _array;

		private BufferSegment _next;

		private int _end;

		public int End
		{
			get
			{
				return _end;
			}
			set
			{
				_end = value;
				base.Memory = AvailableMemory.Slice(0, value);
			}
		}

		public BufferSegment? NextSegment
		{
			get
			{
				return _next;
			}
			set
			{
				base.Next = value;
				_next = value;
			}
		}

		internal object? MemoryOwner => ((object)_memoryOwner) ?? ((object)_array);

		public Memory<byte> AvailableMemory { get; private set; }

		public int Length => End;

		public int WritableBytes
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return AvailableMemory.Length - End;
			}
		}

		public void SetOwnedMemory(IMemoryOwner<byte> memoryOwner)
		{
			_memoryOwner = memoryOwner;
			AvailableMemory = memoryOwner.Memory;
		}

		public void SetOwnedMemory(byte[] arrayPoolBuffer)
		{
			_array = arrayPoolBuffer;
			AvailableMemory = arrayPoolBuffer;
		}

		public void Reset()
		{
			ResetMemory();
			base.Next = null;
			base.RunningIndex = 0L;
			_next = null;
		}

		public void ResetMemory()
		{
			IMemoryOwner<byte> memoryOwner = _memoryOwner;
			if (memoryOwner != null)
			{
				_memoryOwner = null;
				memoryOwner.Dispose();
			}
			else
			{
				ArrayPool<byte>.Shared.Return(_array);
				_array = null;
			}
			base.Memory = default(ReadOnlyMemory<byte>);
			_end = 0;
			AvailableMemory = default(Memory<byte>);
		}

		public void SetNext(BufferSegment segment)
		{
			NextSegment = segment;
			segment = this;
			while (segment.Next != null)
			{
				segment.NextSegment.RunningIndex = segment.RunningIndex + segment.Length;
				segment = segment.NextSegment;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static long GetLength(BufferSegment startSegment, int startIndex, BufferSegment endSegment, int endIndex)
		{
			return endSegment.RunningIndex + (uint)endIndex - (startSegment.RunningIndex + (uint)startIndex);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static long GetLength(long startPosition, BufferSegment endSegment, int endIndex)
		{
			return endSegment.RunningIndex + (uint)endIndex - startPosition;
		}
	}
	internal readonly struct CompletionData
	{
		public Action<object?> Completion { get; }

		public object? CompletionState { get; }

		public ExecutionContext? ExecutionContext { get; }

		public SynchronizationContext? SynchronizationContext { get; }

		public CompletionData(Action<object?> completion, object? completionState, ExecutionContext? executionContext, SynchronizationContext? synchronizationContext)
		{
			Completion = completion;
			CompletionState = completionState;
			ExecutionContext = executionContext;
			SynchronizationContext = synchronizationContext;
		}
	}
	public struct FlushResult
	{
		internal ResultFlags _resultFlags;

		public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0;

		public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0;

		public FlushResult(bool isCanceled, bool isCompleted)
		{
			_resultFlags = ResultFlags.None;
			if (isCanceled)
			{
				_resultFlags |= ResultFlags.Canceled;
			}
			if (isCompleted)
			{
				_resultFlags |= ResultFlags.Completed;
			}
		}
	}
	internal sealed class InlineScheduler : PipeScheduler
	{
		public override void Schedule(Action<object?> action, object? state)
		{
			action(state);
		}

		internal override void UnsafeSchedule(Action<object?> action, object? state)
		{
			action(state);
		}
	}
	public interface IDuplexPipe
	{
		PipeReader Input { get; }

		PipeWriter Output { get; }
	}
	internal struct BufferSegmentStack
	{
		private readonly struct SegmentAsValueType
		{
			private readonly BufferSegment _value;

			private SegmentAsValueType(BufferSegment value)
			{
				_value = value;
			}

			public static implicit operator SegmentAsValueType(BufferSegment s)
			{
				return new SegmentAsValueType(s);
			}

			public static implicit operator BufferSegment(SegmentAsValueType s)
			{
				return s._value;
			}
		}

		private SegmentAsValueType[] _array;

		private int _size;

		public int Count => _size;

		public BufferSegmentStack(int size)
		{
			_array = new SegmentAsValueType[size];
			_size = 0;
		}

		public bool TryPop([NotNullWhen(true)] out BufferSegment? result)
		{
			int num = _size - 1;
			SegmentAsValueType[] array = _array;
			if ((uint)num >= (uint)array.Length)
			{
				result = null;
				return false;
			}
			_size = num;
			result = array[num];
			array[num] = default(SegmentAsValueType);
			return true;
		}

		public void Push(BufferSegment item)
		{
			int size = _size;
			SegmentAsValueType[] array = _array;
			if ((uint)size < (uint)array.Length)
			{
				array[size] = item;
				_size = size + 1;
			}
			else
			{
				PushWithResize(item);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void PushWithResize(BufferSegment item)
		{
			Array.Resize(ref _array, 2 * _array.Length);
			_array[_size] = item;
			_size++;
		}
	}
	public sealed class Pipe
	{
		private sealed class DefaultPipeReader : PipeReader, IValueTaskSource<ReadResult>
		{
			private readonly Pipe _pipe;

			public DefaultPipeReader(Pipe pipe)
			{
				_pipe = pipe;
			}

			public override bool TryRead(out ReadResult result)
			{
				return _pipe.TryRead(out result);
			}

			public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.ReadAsync(cancellationToken);
			}

			protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumBytes, CancellationToken cancellationToken)
			{
				return _pipe.ReadAtLeastAsync(minimumBytes, cancellationToken);
			}

			public override void AdvanceTo(SequencePosition consumed)
			{
				_pipe.AdvanceReader(in consumed);
			}

			public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
			{
				_pipe.AdvanceReader(in consumed, in examined);
			}

			public override void CancelPendingRead()
			{
				_pipe.CancelPendingRead();
			}

			public override void Complete(Exception exception = null)
			{
				_pipe.CompleteReader(exception);
			}

			public override void OnWriterCompleted(Action<Exception, object> callback, object state)
			{
				_pipe.OnWriterCompleted(callback, state);
			}

			public ValueTaskSourceStatus GetStatus(short token)
			{
				return _pipe.GetReadAsyncStatus();
			}

			public ReadResult GetResult(short token)
			{
				return _pipe.GetReadAsyncResult();
			}

			public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				_pipe.OnReadAsyncCompleted(continuation, state, flags);
			}
		}

		private sealed class DefaultPipeWriter : PipeWriter, IValueTaskSource<FlushResult>
		{
			private readonly Pipe _pipe;

			public override bool CanGetUnflushedBytes => true;

			public override long UnflushedBytes => _pipe.GetUnflushedBytes();

			public DefaultPipeWriter(Pipe pipe)
			{
				_pipe = pipe;
			}

			public override void Complete(Exception exception = null)
			{
				_pipe.CompleteWriter(exception);
			}

			public override void CancelPendingFlush()
			{
				_pipe.CancelPendingFlush();
			}

			public override void OnReaderCompleted(Action<Exception, object> callback, object state)
			{
				_pipe.OnReaderCompleted(callback, state);
			}

			public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.FlushAsync(cancellationToken);
			}

			public override void Advance(int bytes)
			{
				_pipe.Advance(bytes);
			}

			public override Memory<byte> GetMemory(int sizeHint = 0)
			{
				return _pipe.GetMemory(sizeHint);
			}

			public override Span<byte> GetSpan(int sizeHint = 0)
			{
				return _pipe.GetSpan(sizeHint);
			}

			public ValueTaskSourceStatus GetStatus(short token)
			{
				return _pipe.GetFlushAsyncStatus();
			}

			public FlushResult GetResult(short token)
			{
				return _pipe.GetFlushAsyncResult();
			}

			public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				_pipe.OnFlushAsyncCompleted(continuation, state, flags);
			}

			public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.WriteAsync(source, cancellationToken);
			}
		}

		private static readonly Action<object> s_signalReaderAwaitable = delegate(object state)
		{
			((Pipe)state).ReaderCancellationRequested();
		};

		private static readonly Action<object> s_signalWriterAwaitable = delegate(object state)
		{
			((Pipe)state).WriterCancellationRequested();
		};

		private static readonly Action<object> s_invokeCompletionCallbacks = delegate(object state)
		{
			((PipeCompletionCallbacks)state).Execute();
		};

		private static readonly ContextCallback s_executionContextRawCallback = ExecuteWithoutExecutionContext;

		private static readonly SendOrPostCallback s_syncContextExecutionContextCallback = ExecuteWithExecutionContext;

		private static readonly SendOrPostCallback s_syncContextExecuteWithoutExecutionContextCallback = ExecuteWithoutExecutionContext;

		private static readonly Action<object> s_scheduleWithExecutionContextCallback = ExecuteWithExecutionContext;

		private BufferSegmentStack _bufferSegmentPool;

		private readonly DefaultPipeReader _reader;

		private readonly DefaultPipeWriter _writer;

		private readonly PipeOptions _options;

		private readonly object _sync = new object();

		private long _unconsumedBytes;

		private long _unflushedBytes;

		private PipeAwaitable _readerAwaitable;

		private PipeAwaitable _writerAwaitable;

		private PipeCompletion _writerCompletion;

		private PipeCompletion _readerCompletion;

		private long _lastExaminedIndex = -1L;

		private BufferSegment _readHead;

		private int _readHeadIndex;

		private bool _disposed;

		private BufferSegment _readTail;

		private int _readTailIndex;

		private int _minimumReadBytes;

		private BufferSegment _writingHead;

		private Memory<byte> _writingHeadMemory;

		private int _writingHeadBytesBuffered;

		private PipeOperationState _operationState;

		private bool UseSynchronizationContext => _options.UseSynchronizationContext;

		private int MinimumSegmentSize => _options.MinimumSegmentSize;

		private long PauseWriterThreshold => _options.PauseWriterThreshold;

		private long ResumeWriterThreshold => _options.ResumeWriterThreshold;

		private PipeScheduler ReaderScheduler => _options.ReaderScheduler;

		private PipeScheduler WriterScheduler => _options.WriterScheduler;

		private object SyncObj => _sync;

		internal long Length => _unconsumedBytes;

		public PipeReader Reader => _reader;

		public PipeWriter Writer => _writer;

		public Pipe()
			: this(PipeOptions.Default)
		{
		}

		public Pipe(PipeOptions options)
		{
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			_bufferSegmentPool = new BufferSegmentStack(options.InitialSegmentPoolSize);
			_operationState = default(PipeOperationState);
			_readerCompletion = default(PipeCompletion);
			_writerCompletion = default(PipeCompletion);
			_options = options;
			_readerAwaitable = new PipeAwaitable(completed: false, UseSynchronizationContext);
			_writerAwaitable = new PipeAwaitable(completed: true, UseSynchronizationContext);
			_reader = new DefaultPipeReader(this);
			_writer = new DefaultPipeWriter(this);
		}

		private void ResetState()
		{
			_readerCompletion.Reset();
			_writerCompletion.Reset();
			_readerAwaitable = new PipeAwaitable(completed: false, UseSynchronizationContext);
			_writerAwaitable = new PipeAwaitable(completed: true, UseSynchronizationContext);
			_readTailIndex = 0;
			_readHeadIndex = 0;
			_lastExaminedIndex = -1L;
			_unflushedBytes = 0L;
			_unconsumedBytes = 0L;
		}

		internal Memory<byte> GetMemory(int sizeHint)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateWriteHeadIfNeeded(sizeHint);
			return _writingHeadMemory;
		}

		internal Span<byte> GetSpan(int sizeHint)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateWriteHeadIfNeeded(sizeHint);
			return _writingHeadMemory.Span;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AllocateWriteHeadIfNeeded(int sizeHint)
		{
			if (!_operationState.IsWritingActive || _writingHeadMemory.Length == 0 || _writingHeadMemory.Length < sizeHint)
			{
				AllocateWriteHeadSynchronized(sizeHint);
			}
		}

		private void AllocateWriteHeadSynchronized(int sizeHint)
		{
			lock (SyncObj)
			{
				_operationState.BeginWrite();
				if (_writingHead == null)
				{
					BufferSegment readTail = AllocateSegment(sizeHint);
					_writingHead = (_readHead = (_readTail = readTail));
					_lastExaminedIndex = 0L;
					return;
				}
				int length = _writingHeadMemory.Length;
				if (length == 0 || length < sizeHint)
				{
					if (_writingHeadBytesBuffered > 0)
					{
						_writingHead.End += _writingHeadBytesBuffered;
						_writingHeadBytesBuffered = 0;
					}
					if (_writingHead.Length == 0)
					{
						_writingHead.ResetMemory();
						RentMemory(_writingHead, sizeHint);
					}
					else
					{
						BufferSegment bufferSegment = AllocateSegment(sizeHint);
						_writingHead.SetNext(bufferSegment);
						_writingHead = bufferSegment;
					}
				}
			}
		}

		private BufferSegment AllocateSegment(int sizeHint)
		{
			BufferSegment bufferSegment = CreateSegmentUnsynchronized();
			RentMemory(bufferSegment, sizeHint);
			return bufferSegment;
		}

		private void RentMemory(BufferSegment segment, int sizeHint)
		{
			MemoryPool<byte> memoryPool = null;
			int num = -1;
			if (!_options.IsDefaultSharedMemoryPool)
			{
				memoryPool = _options.Pool;
				num = memoryPool.MaxBufferSize;
			}
			if (sizeHint <= num)
			{
				segment.SetOwnedMemory(memoryPool.Rent(GetSegmentSize(sizeHint, num)));
			}
			else
			{
				int segmentSize = GetSegmentSize(sizeHint);
				segment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize));
			}
			_writingHeadMemory = segment.AvailableMemory;
		}

		private int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue)
		{
			sizeHint = Math.Max(MinimumSegmentSize, sizeHint);
			return Math.Min(maxBufferSize, sizeHint);
		}

		private BufferSegment CreateSegmentUnsynchronized()
		{
			if (_bufferSegmentPool.TryPop(out BufferSegment result))
			{
				return result;
			}
			return new BufferSegment();
		}

		private void ReturnSegmentUnsynchronized(BufferSegment segment)
		{
			if (_bufferSegmentPool.Count < _options.MaxSegmentPoolSize)
			{
				_bufferSegmentPool.Push(segment);
			}
		}

		internal bool CommitUnsynchronized()
		{
			_operationState.EndWrite();
			if (_unflushedBytes == 0L)
			{
				return false;
			}
			_writingHead.End += _writingHeadBytesBuffered;
			_readTail = _writingHead;
			_readTailIndex = _writingHead.End;
			long unconsumedBytes = _unconsumedBytes;
			_unconsumedBytes += _unflushedBytes;
			bool result = true;
			if (_unconsumedBytes < _minimumReadBytes)
			{
				result = false;
			}
			else if (PauseWriterThreshold > 0 && unconsumedBytes < PauseWriterThreshold && _unconsumedBytes >= PauseWriterThreshold && !_readerCompletion.IsCompleted)
			{
				_writerAwaitable.SetUncompleted();
			}
			_unflushedBytes = 0L;
			_writingHeadBytesBuffered = 0;
			return result;
		}

		internal void Advance(int bytes)
		{
			lock (SyncObj)
			{
				if ((uint)bytes > (uint)_writingHeadMemory.Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes);
				}
				if (!_readerCompletion.IsCompleted)
				{
					AdvanceCore(bytes);
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AdvanceCore(int bytesWritten)
		{
			_unflushedBytes += bytesWritten;
			_writingHeadBytesBuffered += bytesWritten;
			_writingHeadMemory = _writingHeadMemory.Slice(bytesWritten);
		}

		internal ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken)
		{
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken));
			}
			CompletionData completionData;
			ValueTask<FlushResult> result;
			lock (SyncObj)
			{
				PrepareFlushUnsynchronized(out completionData, out result, cancellationToken);
			}
			TrySchedule(ReaderScheduler, in completionData);
			return result;
		}

		private void PrepareFlushUnsynchronized(out CompletionData completionData, out ValueTask<FlushResult> result, CancellationToken cancellationToken)
		{
			bool num = CommitUnsynchronized();
			_writerAwaitable.BeginOperation(cancellationToken, s_signalWriterAwaitable, this);
			if (_writerAwaitable.IsCompleted)
			{
				FlushResult result2 = default(FlushResult);
				GetFlushResult(ref result2);
				result = new ValueTask<FlushResult>(result2);
			}
			else
			{
				result = new ValueTask<FlushResult>(_writer, 0);
			}
			if (num)
			{
				_readerAwaitable.Complete(out completionData);
			}
			else
			{
				completionData = default(CompletionData);
			}
		}

		internal void CompleteWriter(Exception? exception)
		{
			PipeCompletionCallbacks pipeCompletionCallbacks;
			CompletionData completionData;
			bool isCompleted;
			lock (SyncObj)
			{
				CommitUnsynchronized();
				pipeCompletionCallbacks = _writerCompletion.TryComplete(exception);
				_readerAwaitable.Complete(out completionData);
				isCompleted = _readerCompletion.IsCompleted;
			}
			if (isCompleted)
			{
				CompletePipe();
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(ReaderScheduler, pipeCompletionCallbacks);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal void AdvanceReader(in SequencePosition consumed)
		{
			AdvanceReader(in consumed, in consumed);
		}

		internal void AdvanceReader(in SequencePosition consumed, in SequencePosition examined)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			AdvanceReader((BufferSegment)consumed.GetObject(), consumed.GetInteger(), (BufferSegment)examined.GetObject(), examined.GetInteger());
		}

		private void AdvanceReader(BufferSegment consumedSegment, int consumedIndex, BufferSegment examinedSegment, int examinedIndex)
		{
			if (consumedSegment != null && examinedSegment != null && BufferSegment.GetLength(consumedSegment, consumedIndex, examinedSegment, examinedIndex) < 0)
			{
				ThrowHelper.ThrowInvalidOperationException_InvalidExaminedOrConsumedPosition();
			}
			BufferSegment bufferSegment = null;
			BufferSegment returnEnd = null;
			CompletionData completionData = default(CompletionData);
			lock (SyncObj)
			{
				bool flag = false;
				if (examinedSegment == _readTail)
				{
					flag = examinedIndex == _readTailIndex;
				}
				if (examinedSegment != null && _lastExaminedIndex >= 0)
				{
					long length = BufferSegment.GetLength(_lastExaminedIndex, examinedSegment, examinedIndex);
					long unconsumedBytes = _unconsumedBytes;
					if (length < 0)
					{
						ThrowHelper.ThrowInvalidOperationException_InvalidExaminedPosition();
					}
					_unconsumedBytes -= length;
					_lastExaminedIndex = examinedSegment.RunningIndex + examinedIndex;
					if (unconsumedBytes >= ResumeWriterThreshold && _unconsumedBytes < ResumeWriterThreshold)
					{
						_writerAwaitable.Complete(out completionData);
					}
				}
				if (consumedSegment != null)
				{
					if (_readHead == null)
					{
						ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor();
						return;
					}
					bufferSegment = _readHead;
					returnEnd = consumedSegment;
					if (consumedIndex == returnEnd.Length)
					{
						if (_writingHead != returnEnd)
						{
							MoveReturnEndToNextBlock();
						}
						else if (_writingHeadBytesBuffered == 0 && !_operationState.IsWritingActive)
						{
							_writingHead = null;
							_writingHeadMemory = default(Memory<byte>);
							MoveReturnEndToNextBlock();
						}
						else
						{
							_readHead = consumedSegment;
							_readHeadIndex = consumedIndex;
						}
					}
					else
					{
						_readHead = consumedSegment;
						_readHeadIndex = consumedIndex;
					}
				}
				if (flag && !_writerCompletion.IsCompleted)
				{
					_readerAwaitable.SetUncompleted();
				}
				while (bufferSegment != null && bufferSegment != returnEnd)
				{
					BufferSegment? nextSegment = bufferSegment.NextSegment;
					bufferSegment.Reset();
					ReturnSegmentUnsynchronized(bufferSegment);
					bufferSegment = nextSegment;
				}
				_operationState.EndRead();
			}
			TrySchedule(WriterScheduler, in completionData);
			void MoveReturnEndToNextBlock()
			{
				BufferSegment nextSegment2 = returnEnd.NextSegment;
				if (_readTail == returnEnd)
				{
					_readTail = nextSegment2;
					_readTailIndex = 0;
				}
				_readHead = nextSegment2;
				_readHeadIndex = 0;
				returnEnd = nextSegment2;
			}
		}

		internal void CompleteReader(Exception? exception)
		{
			PipeCompletionCallbacks pipeCompletionCallbacks;
			CompletionData completionData;
			bool isCompleted;
			lock (SyncObj)
			{
				if (_operationState.IsReadingActive)
				{
					_operationState.EndRead();
				}
				pipeCompletionCallbacks = _readerCompletion.TryComplete(exception);
				_writerAwaitable.Complete(out completionData);
				isCompleted = _writerCompletion.IsCompleted;
			}
			if (isCompleted)
			{
				CompletePipe();
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(WriterScheduler, pipeCompletionCallbacks);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		internal void OnWriterCompleted(Action<Exception?, object?> callback, object? state)
		{
			if (callback == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback);
			}
			PipeCompletionCallbacks pipeCompletionCallbacks;
			lock (SyncObj)
			{
				pipeCompletionCallbacks = _writerCompletion.AddCallback(callback, state);
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(ReaderScheduler, pipeCompletionCallbacks);
			}
		}

		internal void CancelPendingRead()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_readerAwaitable.Cancel(out completionData);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal void CancelPendingFlush()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_writerAwaitable.Cancel(out completionData);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		internal void OnReaderCompleted(Action<Exception?, object?> callback, object? state)
		{
			if (callback == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback);
			}
			PipeCompletionCallbacks pipeCompletionCallbacks;
			lock (SyncObj)
			{
				pipeCompletionCallbacks = _readerCompletion.AddCallback(callback, state);
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(WriterScheduler, pipeCompletionCallbacks);
			}
		}

		internal ValueTask<ReadResult> ReadAtLeastAsync(int minimumBytes, CancellationToken token)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			if (token.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(token));
			}
			CompletionData completionData = default(CompletionData);
			ValueTask<ReadResult> result2;
			lock (SyncObj)
			{
				_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				if (_readerAwaitable.IsCompleted)
				{
					GetReadResult(out var result);
					if (_unconsumedBytes >= minimumBytes || result.IsCanceled || result.IsCompleted)
					{
						return new ValueTask<ReadResult>(result);
					}
					_readerAwaitable.SetUncompleted();
					_operationState.EndRead();
					_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				}
				if (!_writerAwaitable.IsCompleted)
				{
					_writerAwaitable.Complete(out completionData);
				}
				_minimumReadBytes = minimumBytes;
				result2 = new ValueTask<ReadResult>(_reader, 0);
			}
			TrySchedule(WriterScheduler, in completionData);
			return result2;
		}

		internal ValueTask<ReadResult> ReadAsync(CancellationToken token)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			if (token.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(token));
			}
			lock (SyncObj)
			{
				_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				if (_readerAwaitable.IsCompleted)
				{
					GetReadResult(out var result);
					return new ValueTask<ReadResult>(result);
				}
				return new ValueTask<ReadResult>(_reader, 0);
			}
		}

		internal bool TryRead(out ReadResult result)
		{
			lock (SyncObj)
			{
				if (_readerCompletion.IsCompleted)
				{
					ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
				}
				if (_unconsumedBytes > 0 || _readerAwaitable.IsCompleted)
				{
					GetReadResult(out result);
					return true;
				}
				if (_readerAwaitable.IsRunning)
				{
					ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
				}
				_operationState.BeginReadTentative();
				result = default(ReadResult);
				return false;
			}
		}

		private static void ScheduleCallbacks(PipeScheduler scheduler, PipeCompletionCallbacks completionCallbacks)
		{
			scheduler.UnsafeSchedule(s_invokeCompletionCallbacks, completionCallbacks);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static void TrySchedule(PipeScheduler scheduler, in CompletionData completionData)
		{
			Action<object> completion = completionData.Completion;
			if (completion != null)
			{
				if (completionData.SynchronizationContext == null && completionData.ExecutionContext == null)
				{
					scheduler.UnsafeSchedule(completion, completionData.CompletionState);
				}
				else
				{
					ScheduleWithContext(scheduler, in completionData);
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void ScheduleWithContext(PipeScheduler scheduler, in CompletionData completionData)
		{
			if (completionData.SynchronizationContext == null)
			{
				scheduler.UnsafeSchedule(s_scheduleWithExecutionContextCallback, completionData);
			}
			else if (completionData.ExecutionContext == null)
			{
				completionData.SynchronizationContext.Post(s_syncContextExecuteWithoutExecutionContextCallback, completionData);
			}
			else
			{
				completionData.SynchronizationContext.Post(s_syncContextExecutionContextCallback, completionData);
			}
		}

		private static void ExecuteWithoutExecutionContext(object state)
		{
			CompletionData completionData = (CompletionData)state;
			completionData.Completion(completionData.CompletionState);
		}

		private static void ExecuteWithExecutionContext(object state)
		{
			ExecutionContext.Run(((CompletionData)state).ExecutionContext, s_executionContextRawCallback, state);
		}

		private void CompletePipe()
		{
			lock (SyncObj)
			{
				if (!_disposed)
				{
					_disposed = true;
					BufferSegment bufferSegment = _readHead ?? _readTail;
					while (bufferSegment != null)
					{
						BufferSegment bufferSegment2 = bufferSegment;
						bufferSegment = bufferSegment.NextSegment;
						bufferSegment2.Reset();
					}
					_writingHead = null;
					_writingHeadMemory = default(Memory<byte>);
					_readHead = null;
					_readTail = null;
					_lastExaminedIndex = -1L;
				}
			}
		}

		internal ValueTaskSourceStatus GetReadAsyncStatus()
		{
			if (_readerAwaitable.IsCompleted)
			{
				if (_writerCompletion.IsFaulted)
				{
					return ValueTaskSourceStatus.Faulted;
				}
				return ValueTaskSourceStatus.Succeeded;
			}
			return ValueTaskSourceStatus.Pending;
		}

		internal void OnReadAsyncCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags)
		{
			CompletionData completionData;
			bool doubleCompletion;
			lock (SyncObj)
			{
				_readerAwaitable.OnCompleted(continuation, state, flags, out completionData, out doubleCompletion);
			}
			if (doubleCompletion)
			{
				Writer.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation());
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal ReadResult GetReadAsyncResult()
		{
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			CancellationToken cancellationToken = default(CancellationToken);
			ReadResult result;
			try
			{
				lock (SyncObj)
				{
					if (!_readerAwaitable.IsCompleted)
					{
						ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted();
					}
					cancellationTokenRegistration = _readerAwaitable.ReleaseCancellationTokenRegistration(out cancellationToken);
					GetReadResult(out result);
				}
			}
			finally
			{
				cancellationTokenRegistration.Dispose();
			}
			if (result.IsCanceled)
			{
				cancellationToken.ThrowIfCancellationRequested();
			}
			return result;
		}

		private void GetReadResult(out ReadResult result)
		{
			bool isCompleted = _writerCompletion.IsCompletedOrThrow();
			bool flag = _readerAwaitable.ObserveCancellation();
			BufferSegment readHead = _readHead;
			if (readHead != null)
			{
				ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(readHead, _readHeadIndex, _readTail, _readTailIndex);
				result = new ReadResult(buffer, flag, isCompleted);
			}
			else
			{
				result = new ReadResult(default(ReadOnlySequence<byte>), flag, isCompleted);
			}
			if (flag)
			{
				_operationState.BeginReadTentative();
			}
			else
			{
				_operationState.BeginRead();
			}
			_minimumReadBytes = 0;
		}

		internal ValueTaskSourceStatus GetFlushAsyncStatus()
		{
			if (_writerAwaitable.IsCompleted)
			{
				if (_readerCompletion.IsFaulted)
				{
					return ValueTaskSourceStatus.Faulted;
				}
				return ValueTaskSourceStatus.Succeeded;
			}
			return ValueTaskSourceStatus.Pending;
		}

		internal FlushResult GetFlushAsyncResult()
		{
			FlushResult result = default(FlushResult);
			CancellationToken cancellationToken = default(CancellationToken);
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			try
			{
				lock (SyncObj)
				{
					if (!_writerAwaitable.IsCompleted)
					{
						ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted();
					}
					GetFlushResult(ref result);
					cancellationTokenRegistration = _writerAwaitable.ReleaseCancellationTokenRegistration(out cancellationToken);
					return result;
				}
			}
			finally
			{
				cancellationTokenRegistration.Dispose();
				cancellationToken.ThrowIfCancellationRequested();
			}
		}

		internal long GetUnflushedBytes()
		{
			return _unflushedBytes;
		}

		private void GetFlushResult(ref FlushResult result)
		{
			if (_writerAwaitable.ObserveCancellation())
			{
				result._resultFlags |= ResultFlags.Canceled;
			}
			if (_readerCompletion.IsCompletedOrThrow())
			{
				result._resultFlags |= ResultFlags.Completed;
			}
		}

		internal ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (_readerCompletion.IsCompletedOrThrow())
			{
				return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: true));
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken));
			}
			CompletionData completionData;
			ValueTask<FlushResult> result;
			lock (SyncObj)
			{
				AllocateWriteHeadIfNeeded(0);
				if (source.Length <= _writingHeadMemory.Length)
				{
					source.CopyTo(_writingHeadMemory);
					AdvanceCore(source.Length);
				}
				else
				{
					WriteMultiSegment(source.Span);
				}
				PrepareFlushUnsynchronized(out completionData, out result, cancellationToken);
			}
			TrySchedule(ReaderScheduler, in completionData);
			return result;
		}

		private void WriteMultiSegment(ReadOnlySpan<byte> source)
		{
			Span<byte> span = _writingHeadMemory.Span;
			while (true)
			{
				int num = Math.Min(span.Length, source.Length);
				source.Slice(0, num).CopyTo(span);
				source = source.Slice(num);
				AdvanceCore(num);
				if (source.Length != 0)
				{
					_writingHead.End += _writingHeadBytesBuffered;
					_writingHeadBytesBuffered = 0;
					BufferSegment bufferSegment = AllocateSegment(0);
					_writingHead.SetNext(bufferSegment);
					_writingHead = bufferSegment;
					span = _writingHeadMemory.Span;
					continue;
				}
				break;
			}
		}

		internal void OnFlushAsyncCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags)
		{
			CompletionData completionData;
			bool doubleCompletion;
			lock (SyncObj)
			{
				_writerAwaitable.OnCompleted(continuation, state, flags, out completionData, out doubleCompletion);
			}
			if (doubleCompletion)
			{
				Reader.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation());
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		private void ReaderCancellationRequested()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_readerAwaitable.CancellationTokenFired(out completionData);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		private void WriterCancellationRequested()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_writerAwaitable.CancellationTokenFired(out completionData);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		public void Reset()
		{
			lock (SyncObj)
			{
				if (!_disposed)
				{
					ThrowHelper.ThrowInvalidOperationException_ResetIncompleteReaderWriter();
				}
				_disposed = false;
				ResetState();
			}
		}
	}
	[DebuggerDisplay("CanceledState = {_awaitableState}, IsCompleted = {IsCompleted}")]
	internal struct PipeAwaitable
	{
		[Flags]
		private enum AwaitableState
		{
			None = 0,
			Completed = 1,
			Running = 2,
			Canceled = 4,
			UseSynchronizationContext = 8
		}

		private sealed class SchedulingContext
		{
			public SynchronizationContext SynchronizationContext { get; set; }

			public ExecutionContext ExecutionContext { get; set; }
		}

		private AwaitableState _awaitableState;

		private Action<object> _completion;

		private object _completionState;

		private SchedulingContext _schedulingContext;

		private CancellationTokenRegistration _cancellationTokenRegistration;

		private CancellationToken _cancellationToken;

		private CancellationToken CancellationToken => _cancellationToken;

		public bool IsCompleted => (_awaitableState & (AwaitableState.Completed | AwaitableState.Canceled)) != 0;

		public bool IsRunning => (_awaitableState & AwaitableState.Running) != 0;

		public PipeAwaitable(bool completed, bool useSynchronizationContext)
		{
			_awaitableState = (completed ? AwaitableState.Completed : AwaitableState.None) | (useSynchronizationContext ? AwaitableState.UseSynchronizationContext : AwaitableState.None);
			_completion = null;
			_completionState = null;
			_cancellationTokenRegistration = default(CancellationTokenRegistration);
			_schedulingContext = null;
			_cancellationToken = CancellationToken.None;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginOperation(CancellationToken cancellationToken, Action<object?> callback, object? state)
		{
			if (cancellationToken.CanBeCanceled && !IsCompleted)
			{
				_cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, callback, state);
				if (_cancellationTokenRegistration == default(CancellationTokenRegistration))
				{
					cancellationToken.ThrowIfCancellationRequested();
				}
				_cancellationToken = cancellationToken;
			}
			_awaitableState |= AwaitableState.Running;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Complete(out CompletionData completionData)
		{
			ExtractCompletion(out completionData);
			_awaitableState |= AwaitableState.Completed;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void ExtractCompletion(out CompletionData completionData)
		{
			Action<object> completion = _completion;
			object completionState = _completionState;
			SchedulingContext schedulingContext = _schedulingContext;
			ExecutionContext executionContext = schedulingContext?.ExecutionContext;
			SynchronizationContext synchronizationContext = schedulingContext?.SynchronizationContext;
			_completion = null;
			_completionState = null;
			_schedulingContext = null;
			completionData = ((completion != null) ? new CompletionData(completion, completionState, executionContext, synchronizationContext) : default(CompletionData));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void SetUncompleted()
		{
			_awaitableState &= ~AwaitableState.Completed;
		}

		public void OnCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags, out CompletionData completionData, out bool doubleCompletion)
		{
			completionData = default(CompletionData);
			doubleCompletion = _completion != null;
			if (IsCompleted | doubleCompletion)
			{
				completionData = new CompletionData(continuation, state, _schedulingContext?.ExecutionContext, _schedulingContext?.SynchronizationContext);
				return;
			}
			_completion = continuation;
			_completionState = state;
			if ((_awaitableState & AwaitableState.UseSynchronizationContext) != 0 && (flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
			{
				SynchronizationContext current = SynchronizationContext.Current;
				if (current != null && current.GetType() != typeof(SynchronizationContext))
				{
					if (_schedulingContext == null)
					{
						_schedulingContext = new SchedulingContext();
					}
					_schedulingContext.SynchronizationContext = current;
				}
			}
			if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)
			{
				if (_schedulingContext == null)
				{
					_schedulingContext = new SchedulingContext();
				}
				_schedulingContext.ExecutionContext = ExecutionContext.Capture();
			}
		}

		public void Cancel(out CompletionData completionData)
		{
			ExtractCompletion(out completionData);
			_awaitableState |= AwaitableState.Canceled;
		}

		public void CancellationTokenFired(out CompletionData completionData)
		{
			if (CancellationToken.IsCancellationRequested)
			{
				Cancel(out completionData);
			}
			else
			{
				completionData = default(CompletionData);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool ObserveCancellation()
		{
			bool result = (_awaitableState & AwaitableState.Canceled) == AwaitableState.Canceled;
			_awaitableState &= ~(AwaitableState.Running | AwaitableState.Canceled);
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public CancellationTokenRegistration ReleaseCancellationTokenRegistration(out CancellationToken cancellationToken)
		{
			cancellationToken = CancellationToken;
			CancellationTokenRegistration cancellationTokenRegistration = _cancellationTokenRegistration;
			_cancellationToken = default(CancellationToken);
			_cancellationTokenRegistration = default(CancellationTokenRegistration);
			return cancellationTokenRegistration;
		}
	}
	[DebuggerDisplay("IsCompleted = {IsCompleted}")]
	internal struct PipeCompletion
	{
		private static readonly object s_completedSuccessfully = new object();

		private object _state;

		private List<PipeCompletionCallback> _callbacks;

		public bool IsCompleted => _state != null;

		public bool IsFaulted => _state is ExceptionDispatchInfo;

		public PipeCompletionCallbacks? TryComplete(Exception? exception = null)
		{
			if (_state == null)
			{
				if (exception != null)
				{
					_state = ExceptionDispatchInfo.Capture(exception);
				}
				else
				{
					_state = s_completedSuccessfully;
				}
			}
			return GetCallbacks();
		}

		public PipeCompletionCallbacks? AddCallback(Action<Exception?, object?> callback, object? state)
		{
			if (_callbacks == null)
			{
				_callbacks = new List<PipeCompletionCallback>();
			}
			_callbacks.Add(new PipeCompletionCallback(callback, state));
			if (IsCompleted)
			{
				return GetCallbacks();
			}
			return null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool IsCompletedOrThrow()
		{
			if (!IsCompleted)
			{
				return false;
			}
			if (_state is ExceptionDispatchInfo exceptionDispatchInfo)
			{
				exceptionDispatchInfo.Throw();
			}
			return true;
		}

		private PipeCompletionCallbacks GetCallbacks()
		{
			List<PipeCompletionCallback> callbacks = _callbacks;
			if (callbacks == null)
			{
				return null;
			}
			_callbacks = null;
			return new PipeCompletionCallbacks(callbacks, _state as ExceptionDispatchInfo);
		}

		public void Reset()
		{
			_state = null;
		}

		public override string ToString()
		{
			return string.Format("{0}: {1}", "IsCompleted", IsCompleted);
		}
	}
	internal readonly struct PipeCompletionCallback
	{
		public readonly Action<Exception?, object?> Callback;

		public readonly object? State;

		public PipeCompletionCallback(Action<Exception?, object?> callback, object? state)
		{
			Callback = callback;
			State = state;
		}
	}
	internal sealed class PipeCompletionCallbacks
	{
		private readonly List<PipeCompletionCallback> _callbacks;

		private readonly Exception _exception;

		public PipeCompletionCallbacks(List<PipeCompletionCallback> callbacks, ExceptionDispatchInfo? edi)
		{
			_callbacks = callbacks;
			_exception = edi?.SourceException;
		}

		public void Execute()
		{
			int count = _callbacks.Count;
			if (count != 0)
			{
				List<Exception> exceptions = null;
				for (int i = 0; i < count; i++)
				{
					PipeCompletionCallback callback = _callbacks[i];
					Execute(callback, ref exceptions);
				}
				if (exceptions != null)
				{
					throw new AggregateException(exceptions);
				}
			}
		}

		private void Execute(PipeCompletionCallback callback, ref List<Exception> exceptions)
		{
			try
			{
				callback.Callback(_exception, callback.State);
			}
			catch (Exception item)
			{
				if (exceptions == null)
				{
					exceptions = new List<Exception>();
				}
				exceptions.Add(item);
			}
		}
	}
	public class PipeOptions
	{
		private const int DefaultMinimumSegmentSize = 4096;

		public static PipeOptions Default { get; } = new PipeOptions(null, null, null, -1L, -1L);


		public bool UseSynchronizationContext { get; }

		public long PauseWriterThreshold { get; }

		public long ResumeWriterThreshold { get; }

		public int MinimumSegmentSize { get; }

		public PipeScheduler WriterScheduler { get; }

		public PipeScheduler ReaderScheduler { get; }

		public MemoryPool<byte> Pool { get; }

		internal bool IsDefaultSharedMemoryPool { get; }

		internal int InitialSegmentPoolSize { get; }

		internal int MaxSegmentPoolSize { get; }

		public PipeOptions(MemoryPool<byte>? pool = null, PipeScheduler? readerScheduler = null, PipeScheduler? writerScheduler = null, long pauseWriterThreshold = -1L, long resumeWriterThreshold = -1L, int minimumSegmentSize = -1, bool useSynchronizationContext = true)
		{
			MinimumSegmentSize = ((minimumSegmentSize == -1) ? 4096 : minimumSegmentSize);
			InitialSegmentPoolSize = 4;
			MaxSegmentPoolSize = 256;
			if (pauseWriterThreshold == -1)
			{
				pauseWriterThreshold = 65536L;
			}
			else if (pauseWriterThreshold < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.pauseWriterThreshold);
			}
			switch (resumeWriterThreshold)
			{
			case -1L:
				resumeWriterThreshold = 32768L;
				break;
			case 0L:
				resumeWriterThreshold = 1L;
				break;
			}
			if (resumeWriterThreshold < 0 || (pauseWriterThreshold > 0 && resumeWriterThreshold > pauseWriterThreshold))
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.resumeWriterThreshold);
			}
			Pool = pool ?? MemoryPool<byte>.Shared;
			IsDefaultSharedMemoryPool = Pool == MemoryPool<byte>.Shared;
			ReaderScheduler = readerScheduler ?? PipeScheduler.ThreadPool;
			WriterScheduler = writerScheduler ?? PipeScheduler.ThreadPool;
			PauseWriterThreshold = pauseWriterThreshold;
			ResumeWriterThreshold = resumeWriterThreshold;
			UseSynchronizationContext = useSynchronizationContext;
		}
	}
	public abstract class PipeReader
	{
		private PipeReaderStream _stream;

		public abstract bool TryRead(out ReadResult result);

		public abstract ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken));

		public ValueTask<ReadResult> ReadAtLeastAsync(int minimumSize, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (minimumSize < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.minimumSize);
			}
			return ReadAtLeastAsyncCore(minimumSize, cancellationToken);
		}

		protected virtual async ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken)
		{
			ReadResult result;
			while (true)
			{
				result = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				ReadOnlySequence<byte> buffer = result.Buffer;
				if (buffer.Length >= minimumSize || result.IsCompleted || result.IsCanceled)
				{
					break;
				}
				AdvanceTo(buffer.Start, buffer.End);
			}
			return result;
		}

		public abstract void AdvanceTo(SequencePosition consumed);

		public abstract void AdvanceTo(SequencePosition consumed, SequencePosition examined);

		public virtual Stream AsStream(bool leaveOpen = false)
		{
			if (_stream == null)
			{
				_stream = new PipeReaderStream(this, leaveOpen);
			}
			else if (leaveOpen)
			{
				_stream.LeaveOpen = leaveOpen;
			}
			return _stream;
		}

		public abstract void CancelPendingRead();

		public abstract void Complete(Exception? exception = null);

		public virtual ValueTask CompleteAsync(Exception? exception = null)
		{
			try
			{
				Complete(exception);
				return default(ValueTask);
			}
			catch (Exception exception2)
			{
				return new ValueTask(Task.FromException(exception2));
			}
		}

		[Obsolete("OnWriterCompleted has been deprecated and may not be invoked on all implementations of PipeReader.")]
		public virtual void OnWriterCompleted(Action<Exception?, object?> callback, object? state)
		{
		}

		public static PipeReader Create(Stream stream, StreamPipeReaderOptions? readerOptions = null)
		{
			return new StreamPipeReader(stream, readerOptions ?? StreamPipeReaderOptions.s_default);
		}

		public static PipeReader Create(ReadOnlySequence<byte> sequence)
		{
			return new SequencePipeReader(sequence);
		}

		public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return CopyToAsyncCore(destination, (PipeWriter destination, ReadOnlyMemory<byte> memory, CancellationToken cancellationToken) => destination.WriteAsync(memory, cancellationToken), cancellationToken);
		}

		public virtual Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return CopyToAsyncCore(destination, delegate(Stream destination, ReadOnlyMemory<byte> memory, CancellationToken cancellationToken)
			{
				ValueTask writeTask2 = StreamExtensions.WriteAsync(destination, memory, cancellationToken);
				if (writeTask2.IsCompletedSuccessfully)
				{
					writeTask2.GetAwaiter().GetResult();
					return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: false));
				}
				return Awaited(writeTask2);
			}, cancellationToken);
			static async ValueTask<FlushResult> Awaited(ValueTask writeTask)
			{
				await writeTask.ConfigureAwait(continueOnCapturedContext: false);
				return new FlushResult(isCanceled: false, isCompleted: false);
			}
		}

		private async Task CopyToAsyncCore<TStream>(TStream destination, Func<TStream, ReadOnlyMemory<byte>, CancellationToken, ValueTask<FlushResult>> writeAsync, CancellationToken cancellationToken)
		{
			while (true)
			{
				ReadResult result = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				ReadOnlySequence<byte> buffer = result.Buffer;
				SequencePosition position = buffer.Start;
				SequencePosition consumed = position;
				try
				{
					if (result.IsCanceled)
					{
						ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
					}
					ReadOnlyMemory<byte> memory;
					while (buffer.TryGet(ref position, out memory))
					{
						if (memory.IsEmpty)
						{
							consumed = position;
							continue;
						}
						FlushResult flushResult = await writeAsync(destination, memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						if (flushResult.IsCanceled)
						{
							ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
						}
						consumed = position;
						if (!flushResult.IsCompleted)
						{
							continue;
						}
						return;
					}
					consumed = buffer.End;
					if (result.IsCompleted)
					{
						break;
					}
				}
				finally
				{
					AdvanceTo(consumed);
				}
			}
		}
	}
	[DebuggerDisplay("State = {_state}")]
	internal struct PipeOperationState
	{
		[Flags]
		internal enum State : byte
		{
			Reading = 1,
			ReadingTentative = 2,
			Writing = 4
		}

		private State _state;

		public bool IsWritingActive => (_state & State.Writing) == State.Writing;

		public bool IsReadingActive => (_state & State.Reading) == State.Reading;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginRead()
		{
			if ((_state & State.Reading) == State.Reading)
			{
				ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
			}
			_state |= State.Reading;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginReadTentative()
		{
			if ((_state & State.Reading) == State.Reading)
			{
				ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
			}
			_state |= State.ReadingTentative;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void EndRead()
		{
			if ((_state & State.Reading) != State.Reading && (_state & State.ReadingTentative) != State.ReadingTentative)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadToComplete();
			}
			_state &= ~(State.Reading | State.ReadingTentative);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginWrite()
		{
			_state |= State.Writing;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void EndWrite()
		{
			_state &= ~State.Writing;
		}
	}
	internal sealed class PipeReaderStream : Stream
	{
		private readonly PipeReader _pipeReader;

		public override bool CanRead => true;

		public override bool CanSeek => false;

		public override bool CanWrite => false;

		public override long Length
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public override long Position
		{
			get
			{
				throw new NotSupportedException();
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		internal bool LeaveOpen { get; set; }

		public PipeReaderStream(PipeReader pipeReader, bool leaveOpen)
		{
			_pipeReader = pipeReader;
			LeaveOpen = leaveOpen;
		}

		protected override void Dispose(bool disposing)
		{
			if (!LeaveOpen)
			{
				_pipeReader.Complete();
			}
			base.Dispose(disposing);
		}

		public override void Flush()
		{
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return ReadInternal(new Span<byte>(buffer, offset, count));
		}

		public override int ReadByte()
		{
			Span<byte> buffer = stackalloc byte[1];
			if (ReadInternal(buffer) != 0)
			{
				return buffer[0];
			}
			return -1;
		}

		private int ReadInternal(Span<byte> buffer)
		{
			ValueTask<ReadResult> valueTask = _pipeReader.ReadAsync();
			ReadResult result = (valueTask.IsCompletedSuccessfully ? valueTask.Result : valueTask.AsTask().GetAwaiter().GetResult());
			return HandleReadResult(result, buffer);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		public sealed override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
		{
			return TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count, default(CancellationToken)), callback, state);
		}

		public sealed override int EndRead(IAsyncResult asyncResult)
		{
			return TaskToAsyncResult.End<int>(asyncResult);
		}

		public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return ReadAsyncInternal(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
		}

		private async ValueTask<int> ReadAsyncInternal(Memory<byte> buffer, CancellationToken cancellationToken)
		{
			return HandleReadResult(await _pipeReader.ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false), buffer.Span);
		}

		private int HandleReadResult(ReadResult result, Span<byte> buffer)
		{
			if (result.IsCanceled)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			ReadOnlySequence<byte> buffer2 = result.Buffer;
			long length = buffer2.Length;
			SequencePosition consumed = buffer2.Start;
			try
			{
				if (length != 0L)
				{
					int num = (int)Math.Min(length, buffer.Length);
					ReadOnlySequence<byte> source = ((num == length) ? buffer2 : buffer2.Slice(0, num));
					consumed = source.End;
					source.CopyTo(buffer);
					return num;
				}
				if (result.IsCompleted)
				{
					return 0;
				}
			}
			finally
			{
				_pipeReader.AdvanceTo(consumed);
			}
			ThrowHelper.ThrowInvalidOperationException_InvalidZeroByteRead();
			return 0;
		}

		public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
		{
			StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
			return _pipeReader.CopyToAsync(destination, cancellationToken);
		}
	}
	public abstract class PipeScheduler
	{
		private static readonly ThreadPoolScheduler s_threadPoolScheduler = new ThreadPoolScheduler();

		private static readonly InlineScheduler s_inlineScheduler = new InlineScheduler();

		public static PipeScheduler ThreadPool => s_threadPoolScheduler;

		public static PipeScheduler Inline => s_inlineScheduler;

		public abstract void Schedule(Action<object?> action, object? state);

		internal virtual void UnsafeSchedule(Action<object?> action, object? state)
		{
			Schedule(action, state);
		}
	}
	public abstract class PipeWriter : IBufferWriter<byte>
	{
		private PipeWriterStream _stream;

		public virtual bool CanGetUnflushedBytes => false;

		public virtual long UnflushedBytes
		{
			get
			{
				throw ThrowHelper.CreateNotSupportedException_UnflushedBytes();
			}
		}

		public abstract void Complete(Exception? exception = null);

		public virtual ValueTask CompleteAsync(Exception? exception = null)
		{
			try
			{
				Complete(exception);
				return default(ValueTask);
			}
			catch (Exception exception2)
			{
				return new ValueTask(Task.FromException(exception2));
			}
		}

		public abstract void CancelPendingFlush();

		[Obsolete("OnReaderCompleted has been deprecated and may not be invoked on all implementations of PipeWriter.")]
		public virtual void OnReaderCompleted(Action<Exception?, object?> callback, object? state)
		{
		}

		public abstract ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken));

		public abstract void Advance(int bytes);

		public abstract Memory<byte> GetMemory(int sizeHint = 0);

		public abstract Span<byte> GetSpan(int sizeHint = 0);

		public virtual Stream AsStream(bool leaveOpen = false)
		{
			if (_stream == null)
			{
				_stream = new PipeWriterStream(this, leaveOpen);
			}
			else if (leaveOpen)
			{
				_stream.LeaveOpen = leaveOpen;
			}
			return _stream;
		}

		public static PipeWriter Create(Stream stream, StreamPipeWriterOptions? writerOptions = null)
		{
			return new StreamPipeWriter(stream, writerOptions ?? StreamPipeWriterOptions.s_default);
		}

		public virtual ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
		{
			this.Write(source.Span);
			return FlushAsync(cancellationToken);
		}

		protected internal virtual async Task CopyFromAsync(Stream source, CancellationToken cancellationToken = default(CancellationToken))
		{
			FlushResult flushResult;
			do
			{
				Memory<byte> memory = GetMemory();
				int num = await StreamExtensions.ReadAsync(source, memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				if (num != 0)
				{
					Advance(num);
					flushResult = await FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					if (flushResult.IsCanceled)
					{
						ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
					}
					continue;
				}
				break;
			}
			while (!flushResult.IsCompleted);
		}
	}
	internal sealed class PipeWriterStream : Stream
	{
		private readonly PipeWriter _pipeWriter;

		internal bool LeaveOpen { get; set; }

		public override bool CanRead => false;

		public override bool CanSeek => false;

		public override bool CanWrite => true;

		public override long Length
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public override long Position
		{
			get
			{
				throw new NotSupportedException();
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public PipeWriterStream(PipeWriter pipeWriter, bool leaveOpen)
		{
			_pipeWriter = pipeWriter;
			LeaveOpen = leaveOpen;
		}

		protected override void Dispose(bool disposing)
		{
			if (!LeaveOpen)
			{
				_pipeWriter.Complete();
			}
		}

		public override void Flush()
		{
			FlushAsync().GetAwaiter().GetResult();
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public sealed override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
		{
			return TaskToAsyncResult.Begin(WriteAsync(buffer, offset, count, default(CancellationToken)), callback, state);
		}

		public sealed override void EndWrite(IAsyncResult asyncResult)
		{
			TaskToAsyncResult.End(asyncResult);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
		}

		public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return GetFlushResultAsTask(_pipeWriter.WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken));
		}

		public override Task FlushAsync(CancellationToken cancellationToken)
		{
			return GetFlushResultAsTask(_pipeWriter.FlushAsync(cancellationToken));
		}

		private static Task GetFlushResultAsTask(ValueTask<FlushResult> valueTask)
		{
			if (valueTask.IsCompletedSuccessfully)
			{
				if (valueTask.Result.IsCanceled)
				{
					ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
				}
				return Task.CompletedTask;
			}
			return AwaitTask(valueTask);
			static async Task AwaitTask(ValueTask<FlushResult> valueTask)
			{
				if ((await valueTask.ConfigureAwait(continueOnCapturedContext: false)).IsCanceled)
				{
					ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
				}
			}
		}
	}
	public readonly struct ReadResult
	{
		internal readonly ReadOnlySequence<byte> _resultBuffer;

		internal readonly ResultFlags _resultFlags;

		public ReadOnlySequence<byte> Buffer => _resultBuffer;

		public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0;

		public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0;

		public ReadResult(ReadOnlySequence<byte> buffer, bool isCanceled, bool isCompleted)
		{
			_resultBuffer = buffer;
			_resultFlags = ResultFlags.None;
			if (isCompleted)
			{
				_resultFlags |= ResultFlags.Completed;
			}
			if (isCanceled)
			{
				_resultFlags |= ResultFlags.Canceled;
			}
		}
	}
	[Flags]
	internal enum ResultFlags : byte
	{
		None = 0,
		Canceled = 1,
		Completed = 2
	}
	internal sealed class SequencePipeReader : PipeReader
	{
		private ReadOnlySequence<byte> _sequence;

		private bool _isReaderCompleted;

		private int _cancelNext;

		public SequencePipeReader(ReadOnlySequence<byte> sequence)
		{
			_sequence = sequence;
		}

		public override void AdvanceTo(SequencePosition consumed)
		{
			AdvanceTo(consumed, consumed);
		}

		public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
		{
			ThrowIfCompleted();
			if (consumed.Equals(_sequence.End))
			{
				_sequence = ReadOnlySequence<byte>.Empty;
			}
			else
			{
				_sequence = _sequence.Slice(consumed);
			}
		}

		public override void CancelPendingRead()
		{
			Interlocked.Exchange(ref _cancelNext, 1);
		}

		public override void Complete(Exception? exception = null)
		{
			if (!_isReaderCompleted)
			{
				_isReaderCompleted = true;
				_sequence = ReadOnlySequence<byte>.Empty;
			}
		}

		public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TryRead(out var result))
			{
				return new ValueTask<ReadResult>(result);
			}
			result = new ReadResult(ReadOnlySequence<byte>.Empty, isCanceled: false, isCompleted: true);
			return new ValueTask<ReadResult>(result);
		}

		public override bool TryRead(out ReadResult result)
		{
			ThrowIfCompleted();
			bool flag = Interlocked.Exchange(ref _cancelNext, 0) == 1;
			if (flag || _sequence.Length > 0)
			{
				result = new ReadResult(_sequence, flag, isCompleted: true);
				return true;
			}
			result = default(ReadResult);
			return false;
		}

		private void ThrowIfCompleted()
		{
			if (_isReaderCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
		}
	}
	public static class StreamPipeExtensions
	{
		public static Task CopyToAsync(this Stream source, PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
			}
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return destination.CopyFromAsync(source, cancellationToken);
		}
	}
	internal sealed class StreamPipeReader : PipeReader
	{
		internal const int InitialSegmentPoolSize = 4;

		internal const int MaxSegmentPoolSize = 256;

		private CancellationTokenSource _internalTokenSource;

		private bool _isReaderCompleted;

		private bool _isStreamCompleted;

		private BufferSegment _readHead;

		private int _readIndex;

		private BufferSegment _readTail;

		private long _bufferedBytes;

		private bool _examinedEverything;

		private readonly object _lock = new object();

		private BufferSegmentStack _bufferSegmentPool;

		private readonly StreamPipeReaderOptions _options;

		private bool LeaveOpen => _options.LeaveOpen;

		private bool UseZeroByteReads => _options.UseZeroByteReads;

		private int BufferSize => _options.BufferSize;

		private int MaxBufferSize => _options.MaxBufferSize;

		private int MinimumReadThreshold => _options.MinimumReadSize;

		private MemoryPool<byte> Pool => _options.Pool;

		public Stream InnerStream { get; }

		private CancellationTokenSource InternalTokenSource
		{
			get
			{
				lock (_lock)
				{
					return _internalTokenSource ?? (_internalTokenSource = new CancellationTokenSource());
				}
			}
		}

		public StreamPipeReader(Stream readingStream, StreamPipeReaderOptions options)
		{
			if (readingStream == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.readingStream);
			}
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			InnerStream = readingStream;
			_options = options;
			_bufferSegmentPool = new BufferSegmentStack(4);
		}

		public override void AdvanceTo(SequencePosition consumed)
		{
			AdvanceTo(consumed, consumed);
		}

		public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
		{
			ThrowIfCompleted();
			AdvanceTo((BufferSegment)consumed.GetObject(), consumed.GetInteger(), (BufferSegment)examined.GetObject(), examined.GetInteger());
		}

		private void AdvanceTo(BufferSegment consumedSegment, int consumedIndex, BufferSegment examinedSegment, int examinedIndex)
		{
			if (consumedSegment != null && examinedSegment != null)
			{
				if (_readHead == null)
				{
					ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor();
				}
				BufferSegment bufferSegment = _readHead;
				BufferSegment bufferSegment2 = consumedSegment;
				long length = BufferSegment.GetLength(bufferSegment, _readIndex, consumedSegment, consumedIndex);
				_bufferedBytes -= length;
				_examinedEverything = false;
				if (examinedSegment == _readTail)
				{
					_examinedEverything = examinedIndex == _readTail.End;
				}
				if (_bufferedBytes == 0L)
				{
					bufferSegment2 = null;
					_readHead = null;
					_readTail = null;
					_readIndex = 0;
				}
				else if (consumedIndex == bufferSegment2.Length)
				{
					BufferSegment bufferSegment3 = (_readHead = bufferSegment2.NextSegment);
					_readIndex = 0;
					bufferSegment2 = bufferSegment3;
				}
				else
				{
					_readHead = consumedSegment;
					_readIndex = consumedIndex;
				}
				while (bufferSegment != bufferSegment2)
				{
					BufferSegment? nextSegment = bufferSegment.NextSegment;
					ReturnSegmentUnsynchronized(bufferSegment);
					bufferSegment = nextSegment;
				}
			}
		}

		public override void CancelPendingRead()
		{
			InternalTokenSource.Cancel();
		}

		public override void Complete(Exception? exception = null)
		{
			if (CompleteAndGetNeedsDispose())
			{
				InnerStream.Dispose();
			}
		}

		private bool CompleteAndGetNeedsDispose()
		{
			if (_isReaderCompleted)
			{
				return false;
			}
			_isReaderCompleted = true;
			BufferSegment bufferSegment = _readHead;
			while (bufferSegment != null)
			{
				BufferSegment bufferSegment2 = bufferSegment;
				bufferSegment = bufferSegment.NextSegment;
				bufferSegment2.Reset();
			}
			return !LeaveOpen;
		}

		public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return ReadInternalAsync(null, cancellationToken);
		}

		protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken)
		{
			return ReadInternalAsync(minimumSize, cancellationToken);
		}

		private ValueTask<ReadResult> ReadInternalAsync(int? minimumSize, CancellationToken cancellationToken)
		{
			ThrowIfCompleted();
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(cancellationToken));
			}
			CancellationTokenSource internalTokenSource = InternalTokenSource;
			if (TryReadInternal(internalTokenSource, out var result) && (!minimumSize.HasValue || result.Buffer.Length >= minimumSize || result.IsCompleted || result.IsCanceled))
			{
				return new ValueTask<ReadResult>(result);
			}
			if (_isStreamCompleted)
			{
				return new ValueTask<ReadResult>(new ReadResult(default(ReadOnlySequence<byte>), isCanceled: false, isCompleted: true));
			}
			return Core(this, minimumSize, internalTokenSource, cancellationToken);
			static async ValueTask<ReadResult> Core(StreamPipeReader reader, int? minimumSize, CancellationTokenSource tokenSource, CancellationToken cancellationToken)
			{
				CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
				if (cancellationToken.CanBeCanceled)
				{
					cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
					{
						((StreamPipeReader)state).Cancel();
					}, reader);
				}
				using (cancellationTokenRegistration)
				{
					bool isCanceled = false;
					try
					{
						if (reader.UseZeroByteReads && reader._bufferedBytes == 0L)
						{
							await StreamExtensions.ReadAsync(reader.InnerStream, Memory<byte>.Empty, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
						}
						do
						{
							reader.AllocateReadTail(minimumSize);
							Memory<byte> buffer = reader._readTail.AvailableMemory.Slice(reader._readTail.End);
							int num = await StreamExtensions.ReadAsync(reader.InnerStream, buffer, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							reader._readTail.End += num;
							reader._bufferedBytes += num;
							if (num == 0)
							{
								reader._isStreamCompleted = true;
								break;
							}
						}
						while (minimumSize.HasValue && reader._bufferedBytes < minimumSize);
					}
					catch (OperationCanceledException ex)
					{
						reader.ClearCancellationToken();
						if (cancellationToken.IsCancellationRequested)
						{
							throw new OperationCanceledException(ex.Message, ex, cancellationToken);
						}
						if (!tokenSource.IsCancellationRequested)
						{
							throw;
						}
						isCanceled = true;
					}
					return new ReadResult(reader.GetCurrentReadOnlySequence(), isCanceled, reader._isStreamCompleted);
				}
			}
		}

		public override async Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			ThrowIfCompleted();
			CancellationTokenSource tokenSource = InternalTokenSource;
			if (tokenSource.IsCancellationRequested)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
				{
					((StreamPipeReader)state).Cancel();
				}, this);
			}
			using (cancellationTokenRegistration)
			{
				_ = 1;
				try
				{
					BufferSegment segment = _readHead;
					int start = _readIndex;
					try
					{
						while (segment != null)
						{
							FlushResult flushResult = await destination.WriteAsync(segment.Memory.Slice(start), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							if (flushResult.IsCanceled)
							{
								ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
							}
							segment = segment.NextSegment;
							start = 0;
							if (flushResult.IsCompleted)
							{
								return;
							}
						}
					}
					finally
					{
						if (segment != null)
						{
							AdvanceTo(segment, segment.End, segment, segment.End);
						}
					}
					if (_isStreamCompleted)
					{
						return;
					}
					await InnerStream.CopyToAsync(destination, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException)
				{
					ClearCancellationToken();
					throw;
				}
			}
		}

		public override async Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			ThrowIfCompleted();
			CancellationTokenSource tokenSource = InternalTokenSource;
			if (tokenSource.IsCancellationRequested)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
				{
					((StreamPipeReader)state).Cancel();
				}, this);
			}
			using (cancellationTokenRegistration)
			{
				_ = 1;
				try
				{
					BufferSegment segment = _readHead;
					int start = _readIndex;
					try
					{
						while (segment != null)
						{
							await StreamExtensions.WriteAsync(destination, segment.Memory.Slice(start), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							segment = segment.NextSegment;
							start = 0;
						}
					}
					finally
					{
						if (segment != null)
						{
							AdvanceTo(segment, segment.End, segment, segment.End);
						}
					}
					if (_isStreamCompleted)
					{
						return;
					}
					await StreamExtensions.CopyToAsync(InnerStream, destination, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException)
				{
					ClearCancellationToken();
					throw;
				}
			}
		}

		private void ClearCancellationToken()
		{
			lock (_lock)
			{
				_internalTokenSource = null;
			}
		}

		private void ThrowIfCompleted()
		{
			if (_isReaderCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
		}

		public override bool TryRead(out ReadResult result)
		{
			ThrowIfCompleted();
			return TryReadInternal(InternalTokenSource, out result);
		}

		private bool TryReadInternal(CancellationTokenSource source, out ReadResult result)
		{
			bool isCancellationRequested = source.IsCancellationRequested;
			if (isCancellationRequested || (_bufferedBytes > 0 && (!_examinedEverything || _isStreamCompleted)))
			{
				if (isCancellationRequested)
				{
					ClearCancellationToken();
				}
				ReadOnlySequence<byte> currentReadOnlySequence = GetCurrentReadOnlySequence();
				result = new ReadResult(currentReadOnlySequence, isCancellationRequested, _isStreamCompleted);
				return true;
			}
			result = default(ReadResult);
			return false;
		}

		private ReadOnlySequence<byte> GetCurrentReadOnlySequence()
		{
			if (_readHead != null)
			{
				return new ReadOnlySequence<byte>(_readHead, _readIndex, _readTail, _readTail.End);
			}
			return default(ReadOnlySequence<byte>);
		}

		private void AllocateReadTail(int? minimumSize = null)
		{
			if (_readHead == null)
			{
				_readHead = AllocateSegment(minimumSize);
				_readTail = _readHead;
			}
			else if (_readTail.WritableBytes < MinimumReadThreshold)
			{
				BufferSegment bufferSegment = AllocateSegment(minimumSize);
				_readTail.SetNext(bufferSegment);
				_readTail = bufferSegment;
			}
		}

		private BufferSegment AllocateSegment(int? minimumSize = null)
		{
			BufferSegment bufferSegment = CreateSegmentUnsynchronized();
			int num = minimumSize ?? BufferSize;
			int num2 = ((!_options.IsDefaultSharedMemoryPool) ? _options.Pool.MaxBufferSize : (-1));
			if (num <= num2)
			{
				int segmentSize = GetSegmentSize(num, num2);
				bufferSegment.SetOwnedMemory(_options.Pool.Rent(segmentSize));
			}
			else
			{
				int segmentSize2 = GetSegmentSize(num, MaxBufferSize);
				bufferSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize2));
			}
			return bufferSegment;
		}

		private int GetSegmentSize(int sizeHint, int maxBufferSize)
		{
			sizeHint = Math.Max(BufferSize, sizeHint);
			return Math.Min(maxBufferSize, sizeHint);
		}

		private BufferSegment CreateSegmentUnsynchronized()
		{
			if (_bufferSegmentPool.TryPop(out BufferSegment result))
			{
				return result;
			}
			return new BufferSegment();
		}

		private void ReturnSegmentUnsynchronized(BufferSegment segment)
		{
			segment.Reset();
			if (_bufferSegmentPool.Count < 256)
			{
				_bufferSegmentPool.Push(segment);
			}
		}

		private void Cancel()
		{
			InternalTokenSource.Cancel();
		}
	}
	public class StreamPipeReaderOptions
	{
		private const int DefaultBufferSize = 4096;

		internal const int DefaultMaxBufferSize = 2097152;

		private const int DefaultMinimumReadSize = 1024;

		internal static readonly StreamPipeReaderOptions s_default = new StreamPipeReaderOptions();

		public int BufferSize { get; }

		internal int MaxBufferSize { get; } = 2097152;


		public int MinimumReadSize { get; }

		public MemoryPool<byte> Pool { get; }

		public bool LeaveOpen { get; }

		public bool UseZeroByteReads { get; }

		internal bool IsDefaultSharedMemoryPool { get; }

		public StreamPipeReaderOptions(MemoryPool<byte>? pool, int bufferSize, int minimumReadSize, bool leaveOpen)
			: this(pool, bufferSize, minimumReadSize, leaveOpen, useZeroByteReads: false)
		{
		}

		public StreamPipeReaderOptions(MemoryPool<byte>? pool = null, int bufferSize = -1, int minimumReadSize = -1, bool leaveOpen = false, bool useZeroByteReads = false)
		{
			Pool = pool ?? MemoryPool<byte>.Shared;
			IsDefaultSharedMemoryPool = Pool == MemoryPool<byte>.Shared;
			int num;
			if (bufferSize != -1)
			{
				if (bufferSize <= 0)
				{
					throw new ArgumentOutOfRangeException("bufferSize");
				}
				num = bufferSize;
			}
			else
			{
				num = 4096;
			}
			BufferSize = num;
			int num2;
			if (minimumReadSize != -1)
			{
				if (minimumReadSize <= 0)
				{
					throw new ArgumentOutOfRangeException("minimumReadSize");
				}
				num2 = minimumReadSize;
			}
			else
			{
				num2 = 1024;
			}
			MinimumReadSize = num2;
			LeaveOpen = leaveOpen;
			UseZeroByteReads = useZeroByteReads;
		}
	}
	internal sealed class StreamPipeWriter : PipeWriter
	{
		internal const int InitialSegmentPoolSize = 4;

		internal const int MaxSegmentPoolSize = 256;

		private readonly int _minimumBufferSize;

		private BufferSegment _head;

		private BufferSegment _tail;

		private Memory<byte> _tailMemory;

		private int _tailBytesBuffered;

		private int _bytesBuffered;

		private readonly MemoryPool<byte> _pool;

		private readonly int _maxPooledBufferSize;

		private CancellationTokenSource _internalTokenSource;

		private bool _isCompleted;

		private readonly object _lockObject = new object();

		private BufferSegmentStack _bufferSegmentPool;

		private readonly bool _leaveOpen;

		private CancellationTokenSource InternalTokenSource
		{
			get
			{
				lock (_lockObject)
				{
					return _internalTokenSource ?? (_internalTokenSource = new CancellationTokenSource());
				}
			}
		}

		public Stream InnerStream { get; }

		public override bool CanGetUnflushedBytes => true;

		public override long UnflushedBytes => _bytesBuffered;

		public StreamPipeWriter(Stream writingStream, StreamPipeWriterOptions options)
		{
			if (writingStream == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.writingStream);
			}
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			InnerStream = writingStream;
			_minimumBufferSize = options.MinimumBufferSize;
			_pool = ((options.Pool == MemoryPool<byte>.Shared) ? null : options.Pool);
			_maxPooledBufferSize = _pool?.MaxBufferSize ?? (-1);
			_bufferSegmentPool = new BufferSegmentStack(4);
			_leaveOpen = options.LeaveOpen;
		}

		public override void Advance(int bytes)
		{
			if ((uint)bytes > (uint)_tailMemory.Length)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes);
			}
			_tailBytesBuffered += bytes;
			_bytesBuffered += bytes;
			_tailMemory = _tailMemory.Slice(bytes);
		}

		public override Memory<byte> GetMemory(int sizeHint = 0)
		{
			if (_isCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateMemory(sizeHint);
			return _tailMemory;
		}

		public override Span<byte> GetSpan(int sizeHint = 0)
		{
			if (_isCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateMemory(sizeHint);
			return _tailMemory.Span;
		}

		private void AllocateMemory(int sizeHint)
		{
			if (_head == null)
			{
				BufferSegment tail = AllocateSegment(sizeHint);
				_head = (_tail = tail);
				_tailBytesBuffered = 0;
				return;
			}
			int length = _tailMemory.Length;
			if (length == 0 || length < sizeHint)
			{
				if (_tailBytesBuffered > 0)
				{
					_tail.End += _tailBytesBuffered;
					_tailBytesBuffered = 0;
				}
				BufferSegment bufferSegment = AllocateSegment(sizeHint);
				_tail.SetNext(bufferSegment);
				_tail = bufferSegment;
			}
		}

		private BufferSegment AllocateSegment(int sizeHint)
		{
			BufferSegment bufferSegment = CreateSegmentUnsynchronized();
			int maxPooledBufferSize = _maxPooledBufferSize;
			if (sizeHint <= maxPooledBufferSize)
			{
				bufferSegment.SetOwnedMemory(_pool.Rent(GetSegmentSize(sizeHint, maxPooledBufferSize)));
			}
			else
			{
				int segmentSize = GetSegmentSize(sizeHint);
				bufferSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize));
			}
			_tailMemory = bufferSegment.AvailableMemory;
			return bufferSegment;
		}

		private int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue)
		{
			sizeHint = Math.Max(_minimumBufferSize, sizeHint);
			return Math.Min(maxBufferSize, sizeHint);
		}

		private BufferSegment CreateSegmentUnsynchronized()
		{
			if (_bufferSegmentPool.TryPop(out BufferSegment result))
			{
				return result;
			}
			return new BufferSegment();
		}

		private void ReturnSegmentUnsynchronized(BufferSegment segment)
		{
			segment.Reset();
			if (_bufferSegmentPool.Count < 256)
			{
				_bufferSegmentPool.Push(segment);
			}
		}

		public override void CancelPendingFlush()
		{
			Cancel();
		}

		public override void Complete(Exception? exception = null)
		{
			if (_isCompleted)
			{
				return;
			}
			_isCompleted = true;
			try
			{
				FlushInternal(exception == null);
			}
			finally
			{
				_internalTokenSource?.Dispose();
				if (!_leaveOpen)
				{
					InnerStream.Dispose();
				}
			}
		}

		public override async ValueTask CompleteAsync(Exception? exception = null)
		{
			if (_isCompleted)
			{
				return;
			}
			_isCompleted = true;
			try
			{
				await FlushAsyncInternal(exception == null, Memory<byte>.Empty).ConfigureAwait(continueOnCapturedContext: false);
			}
			finally
			{
				_internalTokenSource?.Dispose();
				if (!_leaveOpen)
				{
					InnerStream.Dispose();
				}
			}
		}

		public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (_bytesBuffered == 0)
			{
				return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: false));
			}
			return FlushAsyncInternal(writeToStream: true, Memory<byte>.Empty, cancellationToken);
		}

		public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return FlushAsyncInternal(writeToStream: true, source, cancellationToken);
		}

		private void Cancel()
		{
			InternalTokenSource.Cancel();
		}

		private async ValueTask<FlushResult> FlushAsyncInternal(bool writeToStream, ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default(CancellationToken))
		{
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
				{
					((StreamPipeWriter)state).Cancel();
				}, this);
			}
			if (_tailBytesBuffered > 0)
			{
				_tail.End += _tailBytesBuffered;
				_tailBytesBuffered = 0;
			}
			using (cancellationTokenRegistration)
			{
				CancellationToken localToken = InternalTokenSource.Token;
				try
				{
					BufferSegment segment = _head;
					while (segment != null)
					{
						BufferSegment returnSegment = segment;
						segment = segment.NextSegment;
						if (returnSegment.Length > 0 && writeToStream)
						{
							await StreamExtensions.WriteAsync(InnerStream, returnSegment.Memory, localToken).ConfigureAwait(continueOnCapturedContext: false);
						}
						ReturnSegmentUnsynchronized(returnSegment);
						_head = segment;
					}
					if (writeToStream)
					{
						if (data.Length > 0)
						{
							await StreamExtensions.WriteAsync(InnerStream, data, localToken).ConfigureAwait(continueOnCapturedContext: false);
						}
						if (_bytesBuffered > 0 || data.Length > 0)
						{
							await InnerStream.FlushAsync(localToken).ConfigureAwait(continueOnCapturedContext: false);
						}
					}
					_head = null;
					_tail = null;
					_tailMemory =

System.Memory.dll

Decompiled 3 months ago
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 source = 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)) && (source.High < 429496729 || (source.High == 429496729 && (source.Mid < 2576980377u || (source.Mid == 2576980377u && (source.Low < 2576980377u || (source.Low == 2576980377u && *ptr <= 53)))))))
				{
					DecimalDecCalc.DecMul10(ref source);
					if (*ptr != 0)
					{
						DecimalDecCalc.DecAddInt32(ref source, (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 source, 1u);
						if ((source.High | source.Mid | source.Low) == 0)
						{
							source.High = 429496729u;
							source.Mid = 2576980377u;
							source.Low = 2576980378u;
							num++;
						}
					}
				}
			}
			if (num > 0)
			{
				return false;
			}
			if (num <= -29)
			{
				source.High = 0u;
				source.Low = 0u;
				source.Mid = 0u;
				source.Scale = 28;
			}
			else
			{
				source.Scale = -num;
			}
			source.IsNegative = number.IsNegative;
			value = Unsafe.As<MutableDecimal, decimal>(ref source);
			return true;
		}

		public static void DecimalToNumber(decimal value, ref NumberBuffer number)
		{
			ref MutableDecimal reference = ref 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>(Unsafe.AsPointer(ref _b0), 51);

		public unsafe byte* UnsafeDigits => (byte*)Unsafe.AsPointer(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>(Unsafe.As<Pinnable<T>>(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 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 = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer, handle);
			}
			if (_object is T[] array)
			{
				if (_length < 0)
				{
					void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index);
					return new MemoryHandle(pointer2);
				}
				GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned);
				void* pointer3 = 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.IndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value), span.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.LastIndexOf(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), Unsafe.As<T, byte>(ref value0), Unsafe.As<T, byte>(ref value1), 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(other)), other.Length);
			}
			if (typeof(T) == typeof(char))
			{
				return System.SpanHelpers.SequenceCompareTo(ref Unsafe.As<T, char>(ref MemoryMarshal.GetReference(span)), span.Length, ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref 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 Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), ref 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 Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size);
				}
				return false;
			}
			if (length2 <= length)
			{
				return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(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 Unsafe.As<T, byte>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), length - length2)), ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(value)), (NUInt)length2 * size);
				}
				return false;
			}
			if (length2 <= length)
			{
				return System.SpanHelpers.SequenceEqual(ref Unsafe.Add(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 = Unsafe.Add(ref reference, num);
				Unsafe.Add(ref reference, num) = Unsafe.Add(ref reference, num2);
				Unsafe.Add(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 = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other));
			if (Unsafe.SizeOf<IntPtr>() == 4)
			{
				if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf<T>()))
				{
					return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>()));
				}
				return true;
			}
			if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()))
			{
				return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)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 = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other));
			if (Unsafe.SizeOf<IntPtr>() == 4)
			{
				if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf<T>()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf<T>())))
				{
					if ((int)intPtr % Unsafe.SizeOf<T>() != 0)
					{
						System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch();
					}
					elementOffset = (int)intPtr / Unsafe.SizeOf<T>();
					return true;
				}
				elementOffset = 0;
				return false;
			}
			if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf<T>()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf<T>())))
			{
				if ((long)intPtr % Unsafe.SizeOf<T>() != 0L)
				{
					System.ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch();
				}
				elementOffset = (int)((long)intPtr / 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>(Unsafe.As<Pinnable<char>>(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>(Unsafe.As<Pinnable<char>>(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>(Unsafe.As<Pinnable<char>>(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* source = text)
			{
				return Unsafe.ByteOffset(ref Unsafe.As<Pinnable<char>>(text).Data, ref Unsafe.AsRef<char>(source));
			}
		}
	}
	[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>(Unsafe.As<Pinnable<T>>(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 = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
				return new MemoryHandle(pointer, handle);
			}
			if (_object is T[] array)
			{
				if (_length < 0)
				{
					void* pointer2 = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetReference<T>(array)), _index);
					return new MemoryHandle(pointer2);
				}
				GCHandle handle2 = GCHandle.Alloc(array, GCHandleType.Pinned);
				void* pointer3 = 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 Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index);
				}
				return ref Unsafe.Add(ref Unsafe.AddByteOffset(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 = Unsafe.As<Pinnable<T>>(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 = Unsafe.As<Pinnable<T>>(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 Unsafe.AsRef<T>(byteOffset.ToPointer());
				}
				return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
			}
			return ref Unsafe.AsRef<T>(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 Unsafe.AreSame(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
			}
			return false;
		}

		public unsafe override string ToString()
		{
			if (typeof(T) == typeof(char))
			{
				if (_byteOffset == MemoryExtensions.StringAdjustment)
				{
					object obj = Unsafe.As<object>(_pinnable);
					if (obj is string text && _length == text.Length)
					{
						return text;
					}
				}
				fixed (char* value = &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 Unsafe.AsRef<T>(byteOffset.ToPointer());
			}
			return ref Unsafe.AddByteOffset(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 Unsafe.Add(ref Unsafe.AsRef<T>(byteOffset.ToPointer()), index);
				}
				return ref Unsafe.Add(ref Unsafe.AddByteOffset(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 = Unsafe.As<Pinnable<T>>(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>(Unsafe.As<Pinnable<T>>(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 = Unsafe.As<Pinnable<T>>(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 Unsafe.AsRef<T>(byteOffset.ToPointer());
				}
				return ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset);
			}
			return ref Unsafe.AsRef<T>(null);
		}

		public unsafe void Clear()
		{
			int length = _length;
			if (length == 0)
			{
				return;
			}
			UIntPtr byteLength = (UIntPtr)(ulong)((uint)length * Unsafe.SizeOf<T>());
			if ((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 Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), byteLength);
				}
			}
			else if (System.SpanHelpers.IsReferenceOrContainsReferences<T>())
			{
				UIntPtr pointerSizeLength = (UIntPtr)(ulong)(length * Unsafe.SizeOf<T>() / sizeof(IntPtr));
				System.SpanHelpers.ClearPointerSizedWithReferences(ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference()), pointerSizeLength);
			}
			else
			{
				System.SpanHelpers.ClearPointerSizedWithoutReferences(ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference()), byteLength);
			}
		}

		public unsafe void Fill(T value)
		{
			int length = _length;
			if (length == 0)
			{
				return;
			}
			if (Unsafe.SizeOf<T>() == 1)
			{
				byte value2 = Unsafe.As<T, byte>(ref value);
				if (_pinnable == null)
				{
					IntPtr byteOffset = _byteOffset;
					Unsafe.InitBlockUnaligned(byteOffset.ToPointer(), value2, (uint)length);
				}
				else
				{
					Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset(ref _pinnable.Data, _byteOffset)), value2, (uint)length);
				}
				return;
			}
			ref T source = ref DangerousGetPinnableReference();
			int i;
			for (i = 0; i < (length & -8); i += 8)
			{
				Unsafe.Add(ref source, i) = value;
				Unsafe.Add(ref source, i + 1) = value;
				Unsafe.Add(ref source, i + 2) = value;
				Unsafe.Add(ref source, i + 3) = value;
				Unsafe.Add(ref source, i + 4) = value;
				Unsafe.Add(ref source, i + 5) = value;
				Unsafe.Add(ref source, i + 6) = value;
				Unsafe.Add(ref source, i + 7) = value;
			}
			if (i < (length & -4))
			{
				Unsafe.Add(ref source, i) = value;
				Unsafe.Add(ref source, i + 1) = value;
				Unsafe.Add(ref source, i + 2) = value;
				Unsafe.Add(ref source, i + 3) = value;
				i += 4;
			}
			for (; i < length; i++)
			{
				Unsafe.Add(ref source, 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 Unsafe.AreSame(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 = &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 Unsafe.AsRef<T>(byteOffset.ToPointer());
			}
			return ref Unsafe.AddByteOffset(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 Unsafe.ByteOffset(ref Unsafe.As<Pinnable<T>>(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(Unsafe.Add(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 Unsafe.Add(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 Unsafe.Add(ref searchSpace, num2), value2, num3);
				if (num4 == -1)
				{
					break;
				}
				num2 += num4;
				if (SequenceEqual(ref Unsafe.Add(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, Unsafe.Add(ref value, i), searchSpaceLength);
				if ((uint)num2 < (uint)num)
				{
					num = num2;
					searchSpaceLength = num2;
					if (num == 0)
					{
						break;
					}
				}
			}
			return num;
		}

		public static int LastIndexOfAny(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 = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength);
				if (num2 > num)
				{
					num = num2;
				}
			}
			return num;
		}

		public unsafe static int IndexOf(ref byte searchSpace, byte value, int length)
		{
			IntPtr intPtr = (IntPtr)0;
			IntPtr intPtr2 = (IntPtr)length;
			if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
			{
				int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
				intPtr2 = (IntPtr)((Vector<byte>.Count - num) & (Vector<byte>.Count - 1));
			}
			while (true)
			{
				if ((nuint)(void*)intPtr2 >= (nuint)8u)
				{
					intPtr2 -= 8;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0242;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_024a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_0258;
					}
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4))
						{
							if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5))
							{
								if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6))
								{
									if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7))
									{
										break;
									}
									intPtr += 8;
									continue;
								}
								return (int)(void*)(intPtr + 6);
							}
							return (int)(void*)(intPtr + 5);
						}
						return (int)(void*)(intPtr + 4);
					}
					goto IL_0266;
				}
				if ((nuint)(void*)intPtr2 >= (nuint)4u)
				{
					intPtr2 -= 4;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0242;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_024a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_0258;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						goto IL_0266;
					}
					intPtr += 4;
				}
				while ((void*)intPtr2 != null)
				{
					intPtr2 -= 1;
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						intPtr += 1;
						continue;
					}
					goto IL_0242;
				}
				if (Vector.IsHardwareAccelerated && (int)(void*)intPtr < length)
				{
					intPtr2 = (IntPtr)((length - (int)(void*)intPtr) & ~(Vector<byte>.Count - 1));
					Vector<byte> vector = GetVector(value);
					for (; (void*)intPtr2 > (void*)intPtr; intPtr += Vector<byte>.Count)
					{
						Vector<byte> vector2 = Vector.Equals(vector, Unsafe.ReadUnaligned<Vector<byte>>(ref Unsafe.AddByteOffset(ref searchSpace, intPtr)));
						if (!Vector<byte>.Zero.Equals(vector2))
						{
							return (int)(void*)intPtr + LocateFirstFoundByte(vector2);
						}
					}
					if ((int)(void*)intPtr < length)
					{
						intPtr2 = (IntPtr)(length - (int)(void*)intPtr);
						continue;
					}
				}
				return -1;
				IL_0266:
				return (int)(void*)(intPtr + 3);
				IL_0242:
				return (int)(void*)intPtr;
				IL_0258:
				return (int)(void*)(intPtr + 2);
				IL_024a:
				return (int)(void*)(intPtr + 1);
			}
			return (int)(void*)(intPtr + 7);
		}

		public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
		{
			if (valueLength == 0)
			{
				return 0;
			}
			byte value2 = value;
			ref byte second = ref Unsafe.Add(ref value, 1);
			int num = valueLength - 1;
			int num2 = 0;
			while (true)
			{
				int num3 = searchSpaceLength - num2 - num;
				if (num3 <= 0)
				{
					break;
				}
				int num4 = LastIndexOf(ref searchSpace, value2, num3);
				if (num4 == -1)
				{
					break;
				}
				if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num))
				{
					return num4;
				}
				num2 += num3 - num4;
			}
			return -1;
		}

		public unsafe static int LastIndexOf(ref byte searchSpace, byte value, int length)
		{
			IntPtr intPtr = (IntPtr)length;
			IntPtr intPtr2 = (IntPtr)length;
			if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
			{
				int num = (int)Unsafe.AsPointer(ref searchSpace) & (Vector<byte>.Count - 1);
				intPtr2 = (IntPtr)(((length & (Vector<byte>.Count - 1)) + num) & (Vector<byte>.Count - 1));
			}
			while (true)
			{
				if ((nuint)(void*)intPtr2 >= (nuint)8u)
				{
					intPtr2 -= 8;
					intPtr -= 8;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 7))
					{
						break;
					}
					if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 6))
					{
						if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 5))
						{
							if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 4))
							{
								if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
								{
									if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
									{
										if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
										{
											if (value != Unsafe.AddByteOffset(ref searchSpace, intPtr))
											{
												continue;
											}
											goto IL_0254;
										}
										goto IL_025c;
									}
									goto IL_026a;
								}
								goto IL_0278;
							}
							return (int)(void*)(intPtr + 4);
						}
						return (int)(void*)(intPtr + 5);
					}
					return (int)(void*)(intPtr + 6);
				}
				if ((nuint)(void*)intPtr2 >= (nuint)4u)
				{
					intPtr2 -= 4;
					intPtr -= 4;
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 3))
					{
						goto IL_0278;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 2))
					{
						goto IL_026a;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr + 1))
					{
						goto IL_025c;
					}
					if (value == Unsafe.AddByteOffset(ref searchSpace, intPtr))
					{
						goto IL_0254;
					}
				}
				while ((void*)intPtr2 != null)
				{
					intPtr2 -= 1;
					intPtr -= 1;
					if (val

System.Numerics.Vectors.dll

Decompiled 3 months ago
using System;
using System.Diagnostics;
using System.Globalization;
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.25519.03")]
[assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.1.3.0")]
[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 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 const string s_resourcesName = "FxResources.System.Numerics.Vectors.SR";

		private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType));

		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 Type ResourceType => typeof(SR);

		[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.All)]
	internal class __BlockReflectionAttribute : 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;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)]
	internal class JitIntrinsicAttribute : Attribute
	{
	}
	[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;
	}
	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> zero = new Vector<T>(GetZeroValue());

		private static readonly Vector<T> one = new Vector<T>(GetOneValue());

		private static readonly Vector<T> allOnes = new Vector<T>(GetAllBitsSetValue());

		[JitIntrinsic]
		public static int Count => s_count;

		[JitIntrinsic]
		public static Vector<T> Zero => zero;

		[JitIntrinsic]
		public static Vector<T> One => one;

		internal static Vector<T> AllOnes => allOnes;

		[JitIntrinsic]
		public unsafe T this[int index]
		{
			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 = &register.byte_0)
					{
						return (T)(object)ptr[index];
					}
				}
				if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						return (T)(object)ptr2[index];
					}
				}
				if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						return (T)(object)ptr3[index];
					}
				}
				if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						return (T)(object)ptr4[index];
					}
				}
				if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						return (T)(object)ptr5[index];
					}
				}
				if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						return (T)(object)ptr6[index];
					}
				}
				if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						return (T)(object)ptr7[index];
					}
				}
				if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						return (T)(object)ptr8[index];
					}
				}
				if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						return (T)(object)ptr9[index];
					}
				}
				if (typeof(T) == typeof(double))
				{
					fixed (double* ptr10 = &register.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;
		}

		[JitIntrinsic]
		public unsafe Vector(T value)
		{
			this = default(Vector<T>);
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.byte_0)
					{
						for (int i = 0; i < Count; i++)
						{
							ptr[i] = (byte)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(sbyte))
				{
					fixed (sbyte* ptr2 = &register.sbyte_0)
					{
						for (int j = 0; j < Count; j++)
						{
							ptr2[j] = (sbyte)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(ushort))
				{
					fixed (ushort* ptr3 = &register.uint16_0)
					{
						for (int k = 0; k < Count; k++)
						{
							ptr3[k] = (ushort)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(short))
				{
					fixed (short* ptr4 = &register.int16_0)
					{
						for (int l = 0; l < Count; l++)
						{
							ptr4[l] = (short)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(uint))
				{
					fixed (uint* ptr5 = &register.uint32_0)
					{
						for (int m = 0; m < Count; m++)
						{
							ptr5[m] = (uint)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(int))
				{
					fixed (int* ptr6 = &register.int32_0)
					{
						for (int n = 0; n < Count; n++)
						{
							ptr6[n] = (int)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(ulong))
				{
					fixed (ulong* ptr7 = &register.uint64_0)
					{
						for (int num = 0; num < Count; num++)
						{
							ptr7[num] = (ulong)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(long))
				{
					fixed (long* ptr8 = &register.int64_0)
					{
						for (int num2 = 0; num2 < Count; num2++)
						{
							ptr8[num2] = (long)(object)value;
						}
					}
				}
				else if (typeof(T) == typeof(float))
				{
					fixed (float* ptr9 = &register.single_0)
					{
						for (int num3 = 0; num3 < Count; num3++)
						{
							ptr9[num3] = (float)(object)value;
						}
					}
				}
				else
				{
					if (!(typeof(T) == typeof(double)))
					{
						return;
					}
					fixed (double* ptr10 = &register.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;
			}
		}

		[JitIntrinsic]
		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();
			}
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					fixed (byte* ptr = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.uint64_0)
				{
					*ptr17 = (ulong)(object)values[index];
					ptr17[1] = (ulong)(object)values[1 + index];
				}
			}
			else if (typeof(T) == typeof(long))
			{
				fixed (long* ptr18 = &register.int64_0)
				{
					*ptr18 = (long)(object)values[index];
					ptr18[1] = (long)(object)values[1 + index];
				}
			}
			else if (typeof(T) == typeof(float))
			{
				fixed (float* ptr19 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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 = &register.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;
		}

		[JitIntrinsic]
		public void CopyTo(T[] destination)
		{
			CopyTo(destination, 0);
		}

		[JitIntrinsic]
		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);
		}

		[JitIntrinsic]
		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)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					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)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					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)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					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)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					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)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					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)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					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)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					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)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					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;
		}

		[JitIntrinsic]
		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;
		}

		[JitIntrinsic]
		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;
		}

		[JitIntrinsic]
		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 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);
		}

		[JitIntrinsic]
		public static explicit operator Vector<byte>(Vector<T> value)
		{
			return new Vector<byte>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<sbyte>(Vector<T> value)
		{
			return new Vector<sbyte>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<ushort>(Vector<T> value)
		{
			return new Vector<ushort>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<short>(Vector<T> value)
		{
			return new Vector<short>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<uint>(Vector<T> value)
		{
			return new Vector<uint>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<int>(Vector<T> value)
		{
			return new Vector<int>(ref value.register);
		}

		[CLSCompliant(false)]
		[JitIntrinsic]
		public static explicit operator Vector<ulong>(Vector<T> value)
		{
			return new Vector<ulong>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<long>(Vector<T> value)
		{
			return new Vector<long>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<float>(Vector<T> value)
		{
			return new Vector<float>(ref value.register);
		}

		[JitIntrinsic]
		public static explicit operator Vector<double>(Vector<T> value)
		{
			return new Vector<double>(ref value.register);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[JitIntrinsic]
		internal unsafe static Vector<T> Equals(Vector<T> left, Vector<T> right)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (typeof(T) == typeof(byte))
				{
					byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int i = 0; i < Count; i++)
					{
						ptr[i] = (byte)(ScalarEquals(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0);
					}
					return new Vector<T>(ptr);
				}
				if (typeof(T) == typeof(sbyte))
				{
					sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)];
					for (int j = 0; j < Count; j++)
					{
						ptr2[j] = (sbyte)(ScalarEquals(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0);
					}
					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)(ScalarEquals(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0);
					}
					return new Vector<T>(ptr3);
				}
				if (typeof(T) == typeof(short))
				{
					short* ptr4 

System.Runtime.CompilerServices.Unsafe.dll

Decompiled 3 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyFileVersion("6.0.21.52210")]
[assembly: AssemblyInformationalVersion("6.0.0")]
[assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyVersion("6.0.0.0")]
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 void SkipInit<T>(out T 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 Unbox<T>(object box) where T : struct
		{
			return ref (T)box;
		}

		[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)]
		public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint 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)]
		public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint 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)]
		public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint 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)]
		public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint 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);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.AsPointer(ref source) == null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T NullRef<T>()
		{
			return ref *(T*)null;
		}
	}
}
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
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] A_0)
		{
			TransformFlags = A_0;
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}

System.Text.Encodings.Web.dll

Decompiled 3 months ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading;
using FxResources.System.Text.Encodings.Web;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Text.Encodings.Web")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides types for encoding and escaping strings for use in JavaScript, HyperText Markup Language (HTML), and uniform resource locators (URL).\r\n\r\nCommonly Used Types:\r\nSystem.Text.Encodings.Web.HtmlEncoder\r\nSystem.Text.Encodings.Web.UrlEncoder\r\nSystem.Text.Encodings.Web.JavaScriptEncoder")]
[assembly: AssemblyFileVersion("9.0.225.6610")]
[assembly: AssemblyInformationalVersion("9.0.2+80aa709f5d919c6814726788dc6dabe23e79e672")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Text.Encodings.Web")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 FxResources.System.Text.Encodings.Web
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				ToCharsBuffer(bytes[i], chars, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(chars, bytes, out charsProcessed);
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < bytes.Length)
			{
				num3 = FromChar(chars[num + 1]);
				num4 = FromChar(chars[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				bytes[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string TextEncoderDoesNotImplementMaxOutputCharsPerInputChar => GetResourceString("TextEncoderDoesNotImplementMaxOutputCharsPerInputChar");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		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);
		}

		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(IFormatProvider provider, string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Numerics
{
	internal static class BitOperations
	{
		private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32]
		{
			0, 9, 1, 10, 13, 21, 2, 29, 11, 14,
			16, 18, 22, 25, 3, 30, 8, 12, 20, 28,
			15, 17, 24, 7, 19, 27, 23, 6, 26, 5,
			4, 31
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int Log2(uint value)
		{
			return Log2SoftwareFallback(value | 1u);
		}

		private static int Log2SoftwareFallback(uint value)
		{
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (nint)(value * 130329821 >> 27));
		}
	}
}
namespace System.Text
{
	internal static class UnicodeDebug
	{
		[Conditional("DEBUG")]
		internal static void AssertIsBmpCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsBmpCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsHighSurrogateCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsHighSurrogateCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsLowSurrogateCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsLowSurrogateCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsValidCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidScalar(uint scalarValue)
		{
			System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue)
		{
			if (System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue))
			{
				System.Text.UnicodeUtility.IsBmpCodePoint(scalarValue);
			}
		}

		private static string ToHexString(uint codePoint)
		{
			return FormattableString.Invariant($"U+{codePoint:X4}");
		}
	}
	internal static class UnicodeUtility
	{
		public const uint ReplacementChar = 65533u;

		public static int GetPlane(uint codePoint)
		{
			return (int)(codePoint >> 16);
		}

		public static uint GetScalarFromUtf16SurrogatePair(uint highSurrogateCodePoint, uint lowSurrogateCodePoint)
		{
			return (highSurrogateCodePoint << 10) + lowSurrogateCodePoint - 56613888;
		}

		public static int GetUtf16SequenceLength(uint value)
		{
			value -= 65536;
			value += 33554432;
			value >>= 24;
			return (int)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void GetUtf16SurrogatesFromSupplementaryPlaneScalar(uint value, out char highSurrogateCodePoint, out char lowSurrogateCodePoint)
		{
			highSurrogateCodePoint = (char)(value + 56557568 >> 10);
			lowSurrogateCodePoint = (char)((value & 0x3FF) + 56320);
		}

		public static int GetUtf8SequenceLength(uint value)
		{
			int num = (int)(value - 2048) >> 31;
			value ^= 0xF800u;
			value -= 63616;
			value += 67108864;
			value >>= 24;
			return (int)value + num * 2;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsAsciiCodePoint(uint value)
		{
			return value <= 127;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsBmpCodePoint(uint value)
		{
			return value <= 65535;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHighSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 55296u, 56319u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound)
		{
			return value - lowerBound <= upperBound - lowerBound;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsLowSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 56320u, 57343u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 55296u, 57343u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsValidCodePoint(uint codePoint)
		{
			return codePoint <= 1114111;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsValidUnicodeScalar(uint value)
		{
			return ((value - 1114112) ^ 0xD800) >= 4293855232u;
		}
	}
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public unsafe void Append(char* value, int length)
		{
			if (_pos > _chars.Length - length)
			{
				Grow(length);
			}
			Span<char> span = _chars.Slice(_pos, length);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = *(value++);
			}
			_pos += length;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
	internal readonly struct Rune : IEquatable<Rune>
	{
		private const int MaxUtf16CharsPerRune = 2;

		private const char HighSurrogateStart = '\ud800';

		private const char LowSurrogateStart = '\udc00';

		private const int HighSurrogateRange = 1023;

		private readonly uint _value;

		public bool IsAscii => System.Text.UnicodeUtility.IsAsciiCodePoint(_value);

		public bool IsBmp => System.Text.UnicodeUtility.IsBmpCodePoint(_value);

		public static Rune ReplacementChar => UnsafeCreate(65533u);

		public int Utf16SequenceLength => System.Text.UnicodeUtility.GetUtf16SequenceLength(_value);

		public int Value => (int)_value;

		public Rune(uint value)
		{
			if (!System.Text.UnicodeUtility.IsValidUnicodeScalar(value))
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
			}
			_value = value;
		}

		public Rune(int value)
			: this((uint)value)
		{
		}

		private Rune(uint scalarValue, bool _)
		{
			_value = scalarValue;
		}

		public static bool operator ==(Rune left, Rune right)
		{
			return left._value == right._value;
		}

		public static bool operator !=(Rune left, Rune right)
		{
			return left._value != right._value;
		}

		public static bool IsControl(Rune value)
		{
			return ((value._value + 1) & 0xFFFFFF7Fu) <= 32;
		}

		public static OperationStatus DecodeFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed)
		{
			if (!source.IsEmpty)
			{
				char c = source[0];
				if (TryCreate(c, out result))
				{
					charsConsumed = 1;
					return OperationStatus.Done;
				}
				if (1u < (uint)source.Length)
				{
					char lowSurrogate = source[1];
					if (TryCreate(c, lowSurrogate, out result))
					{
						charsConsumed = 2;
						return OperationStatus.Done;
					}
				}
				else if (char.IsHighSurrogate(c))
				{
					goto IL_004c;
				}
				charsConsumed = 1;
				result = ReplacementChar;
				return OperationStatus.InvalidData;
			}
			goto IL_004c;
			IL_004c:
			charsConsumed = source.Length;
			result = ReplacementChar;
			return OperationStatus.NeedMoreData;
		}

		public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> source, out Rune result, out int bytesConsumed)
		{
			int num = 0;
			uint num2;
			if ((uint)num < (uint)source.Length)
			{
				num2 = source[num];
				if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2))
				{
					goto IL_0021;
				}
				if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 194u, 244u))
				{
					num2 = num2 - 194 << 6;
					num++;
					if ((uint)num >= (uint)source.Length)
					{
						goto IL_0163;
					}
					int num3 = (sbyte)source[num];
					if (num3 < -64)
					{
						num2 += (uint)num3;
						num2 += 128;
						num2 += 128;
						if (num2 < 2048)
						{
							goto IL_0021;
						}
						if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 3072u, 3087u))
						{
							num++;
							if ((uint)num >= (uint)source.Length)
							{
								goto IL_0163;
							}
							num3 = (sbyte)source[num];
							if (num3 < -64)
							{
								num2 <<= 6;
								num2 += (uint)num3;
								num2 += 128;
								num2 -= 131072;
								if (num2 > 65535)
								{
									num++;
									if ((uint)num >= (uint)source.Length)
									{
										goto IL_0163;
									}
									num3 = (sbyte)source[num];
									if (num3 >= -64)
									{
										goto IL_0153;
									}
									num2 <<= 6;
									num2 += (uint)num3;
									num2 += 128;
									num2 -= 4194304;
								}
								goto IL_0021;
							}
						}
					}
				}
				else
				{
					num = 1;
				}
				goto IL_0153;
			}
			goto IL_0163;
			IL_0021:
			bytesConsumed = num + 1;
			result = UnsafeCreate(num2);
			return OperationStatus.Done;
			IL_0153:
			bytesConsumed = num;
			result = ReplacementChar;
			return OperationStatus.InvalidData;
			IL_0163:
			bytesConsumed = num;
			result = ReplacementChar;
			return OperationStatus.NeedMoreData;
		}

		public override bool Equals([NotNullWhen(true)] object obj)
		{
			if (obj is Rune other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(Rune other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			return Value;
		}

		public static bool TryCreate(char ch, out Rune result)
		{
			if (!System.Text.UnicodeUtility.IsSurrogateCodePoint(ch))
			{
				result = UnsafeCreate(ch);
				return true;
			}
			result = default(Rune);
			return false;
		}

		public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result)
		{
			uint num = (uint)(highSurrogate - 55296);
			uint num2 = (uint)(lowSurrogate - 56320);
			if ((num | num2) <= 1023)
			{
				result = UnsafeCreate((uint)((int)(num << 10) + (lowSurrogate - 56320) + 65536));
				return true;
			}
			result = default(Rune);
			return false;
		}

		public bool TryEncodeToUtf16(Span<char> destination, out int charsWritten)
		{
			if (destination.Length >= 1)
			{
				if (IsBmp)
				{
					destination[0] = (char)_value;
					charsWritten = 1;
					return true;
				}
				if (destination.Length >= 2)
				{
					System.Text.UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out destination[0], out destination[1]);
					charsWritten = 2;
					return true;
				}
			}
			charsWritten = 0;
			return false;
		}

		public bool TryEncodeToUtf8(Span<byte> destination, out int bytesWritten)
		{
			if (destination.Length >= 1)
			{
				if (IsAscii)
				{
					destination[0] = (byte)_value;
					bytesWritten = 1;
					return true;
				}
				if (destination.Length >= 2)
				{
					if (_value <= 2047)
					{
						destination[0] = (byte)(_value + 12288 >> 6);
						destination[1] = (byte)((_value & 0x3F) + 128);
						bytesWritten = 2;
						return true;
					}
					if (destination.Length >= 3)
					{
						if (_value <= 65535)
						{
							destination[0] = (byte)(_value + 917504 >> 12);
							destination[1] = (byte)(((_value & 0xFC0) >> 6) + 128);
							destination[2] = (byte)((_value & 0x3F) + 128);
							bytesWritten = 3;
							return true;
						}
						if (destination.Length >= 4)
						{
							destination[0] = (byte)(_value + 62914560 >> 18);
							destination[1] = (byte)(((_value & 0x3F000) >> 12) + 128);
							destination[2] = (byte)(((_value & 0xFC0) >> 6) + 128);
							destination[3] = (byte)((_value & 0x3F) + 128);
							bytesWritten = 4;
							return true;
						}
					}
				}
			}
			bytesWritten = 0;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static Rune UnsafeCreate(uint scalarValue)
		{
			return new Rune(scalarValue, _: false);
		}
	}
}
namespace System.Text.Unicode
{
	internal static class UnicodeHelpers
	{
		internal const int UNICODE_LAST_CODEPOINT = 1114111;

		private static ReadOnlySpan<byte> DefinedCharsBitmapSpan => new byte[8192]
		{
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 127, 0, 0, 0, 0,
			254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 252, 240, 215, 255, 255, 251, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 254, 255, 255, 255,
			127, 254, 255, 255, 255, 255, 255, 231, 254, 255,
			255, 255, 255, 255, 255, 0, 255, 255, 255, 135,
			31, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 191, 255, 255, 255, 255,
			255, 255, 255, 231, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 3, 0, 255, 255,
			255, 255, 255, 255, 255, 231, 255, 255, 255, 255,
			255, 63, 255, 127, 255, 255, 255, 79, 255, 7,
			255, 255, 255, 127, 3, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 239, 159, 249, 255, 255, 253,
			197, 243, 159, 121, 128, 176, 207, 255, 255, 127,
			238, 135, 249, 255, 255, 253, 109, 211, 135, 57,
			2, 94, 192, 255, 127, 0, 238, 191, 251, 255,
			255, 253, 237, 243, 191, 59, 1, 0, 207, 255,
			3, 254, 238, 159, 249, 255, 255, 253, 237, 243,
			159, 57, 224, 176, 207, 255, 255, 0, 236, 199,
			61, 214, 24, 199, 255, 195, 199, 61, 129, 0,
			192, 255, 255, 7, 255, 223, 253, 255, 255, 253,
			255, 243, 223, 61, 96, 39, 207, 255, 128, 255,
			255, 223, 253, 255, 255, 253, 239, 243, 223, 61,
			96, 96, 207, 255, 14, 0, 255, 223, 253, 255,
			255, 255, 255, 255, 223, 253, 240, 255, 207, 255,
			255, 255, 238, 255, 127, 252, 255, 255, 251, 47,
			127, 132, 95, 255, 192, 255, 28, 0, 254, 255,
			255, 255, 255, 255, 255, 135, 255, 255, 255, 15,
			0, 0, 0, 0, 214, 247, 255, 255, 175, 255,
			255, 63, 95, 127, 255, 243, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 254,
			255, 255, 255, 31, 254, 255, 255, 255, 255, 254,
			255, 255, 255, 223, 255, 223, 255, 7, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 191, 32, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 61, 127, 61, 255, 255,
			255, 255, 255, 61, 255, 255, 255, 255, 61, 127,
			61, 255, 127, 255, 255, 255, 255, 255, 255, 255,
			61, 255, 255, 255, 255, 255, 255, 255, 255, 231,
			255, 255, 255, 31, 255, 255, 255, 3, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 63, 63,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			254, 255, 255, 31, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 1, 255, 255, 63, 128,
			255, 255, 127, 0, 255, 255, 15, 0, 255, 223,
			13, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 255, 3, 255, 3, 255, 255,
			255, 3, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 1, 255, 255, 255, 255, 255, 7,
			255, 255, 255, 255, 255, 255, 255, 255, 63, 0,
			255, 255, 255, 127, 255, 15, 255, 15, 241, 255,
			255, 255, 255, 63, 31, 0, 255, 255, 255, 255,
			255, 15, 255, 255, 255, 3, 255, 199, 255, 255,
			255, 255, 255, 255, 255, 207, 255, 255, 255, 255,
			255, 255, 255, 127, 255, 255, 255, 159, 255, 3,
			255, 3, 255, 63, 255, 255, 255, 127, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 31, 255, 255, 255, 255, 255, 127,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 15, 240, 255, 255, 255, 255,
			255, 255, 255, 248, 255, 227, 255, 255, 255, 255,
			255, 255, 255, 1, 255, 255, 255, 255, 255, 231,
			255, 0, 255, 255, 255, 255, 255, 7, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 63, 63, 255, 255, 255, 255,
			63, 63, 255, 170, 255, 255, 255, 63, 255, 255,
			255, 255, 255, 255, 223, 255, 223, 255, 207, 239,
			255, 255, 220, 127, 0, 248, 255, 255, 255, 124,
			255, 255, 255, 255, 255, 127, 223, 255, 243, 255,
			255, 127, 255, 31, 255, 255, 255, 255, 1, 0,
			255, 255, 255, 255, 1, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 15, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 127, 0, 0, 0,
			255, 7, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			207, 255, 255, 255, 191, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 15, 254,
			255, 255, 255, 255, 191, 32, 255, 255, 255, 255,
			255, 255, 255, 128, 1, 128, 255, 255, 127, 0,
			127, 127, 127, 127, 127, 127, 127, 127, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 0, 0, 0, 0, 255, 255,
			255, 251, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 15, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			63, 0, 0, 0, 255, 15, 254, 255, 255, 255,
			255, 255, 255, 255, 254, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 127, 254, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 224, 255,
			255, 255, 255, 255, 254, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 127, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 15, 0, 255, 255,
			255, 255, 255, 127, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 31, 255, 255, 255, 255,
			255, 255, 127, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 15, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 7,
			235, 3, 0, 0, 252, 255, 255, 255, 255, 255,
			255, 31, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			63, 192, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 15, 128,
			255, 255, 255, 31, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 191, 255, 195, 255, 255, 255, 127,
			255, 255, 255, 255, 255, 255, 127, 0, 255, 63,
			255, 243, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 7, 0, 0, 248, 255, 255,
			127, 0, 126, 126, 126, 0, 127, 127, 255, 255,
			255, 255, 255, 255, 255, 15, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 63, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			15, 0, 255, 255, 127, 248, 255, 255, 255, 255,
			255, 15, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 3, 0, 0,
			0, 0, 127, 0, 248, 224, 255, 255, 127, 95,
			219, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 7, 0, 248, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 252, 255, 255, 255, 255, 255,
			255, 128, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 3, 255, 255, 255, 255, 255, 255, 247, 255,
			127, 15, 223, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 31,
			254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 127, 252, 252, 252, 28, 127, 127,
			0, 62
		};

		internal static ReadOnlySpan<byte> GetDefinedBmpCodePointsBitmapLittleEndian()
		{
			return DefinedCharsBitmapSpan;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static void GetUtf16SurrogatePairFromAstralScalarValue(uint scalar, out char highSurrogate, out char lowSurrogate)
		{
			highSurrogate = (char)(scalar + 56557568 >> 10);
			lowSurrogate = (char)((scalar & 0x3FF) + 56320);
		}

		internal static int GetUtf8RepresentationForScalarValue(uint scalar)
		{
			if (scalar <= 127)
			{
				return (byte)scalar;
			}
			if (scalar <= 2047)
			{
				byte b = (byte)(0xC0u | (scalar >> 6));
				return ((byte)(0x80 | (scalar & 0x3F)) << 8) | b;
			}
			if (scalar <= 65535)
			{
				byte b2 = (byte)(0xE0u | (scalar >> 12));
				byte b3 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu));
				return ((((byte)(0x80 | (scalar & 0x3F)) << 8) | b3) << 8) | b2;
			}
			byte b4 = (byte)(0xF0u | (scalar >> 18));
			byte b5 = (byte)(0x80u | ((scalar >> 12) & 0x3Fu));
			byte b6 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu));
			return ((((((byte)(0x80 | (scalar & 0x3F)) << 8) | b6) << 8) | b5) << 8) | b4;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static bool IsSupplementaryCodePoint(int scalar)
		{
			return (scalar & -65536) != 0;
		}
	}
	public sealed class UnicodeRange
	{
		public int FirstCodePoint { get; }

		public int Length { get; }

		public UnicodeRange(int firstCodePoint, int length)
		{
			if (firstCodePoint < 0 || firstCodePoint > 65535)
			{
				throw new ArgumentOutOfRangeException("firstCodePoint");
			}
			if (length < 0 || (long)firstCodePoint + (long)length > 65536)
			{
				throw new ArgumentOutOfRangeException("length");
			}
			FirstCodePoint = firstCodePoint;
			Length = length;
		}

		public static UnicodeRange Create(char firstCharacter, char lastCharacter)
		{
			if (lastCharacter < firstCharacter)
			{
				throw new ArgumentOutOfRangeException("lastCharacter");
			}
			return new UnicodeRange(firstCharacter, 1 + (lastCharacter - firstCharacter));
		}
	}
	public static class UnicodeRanges
	{
		private static UnicodeRange _none;

		private static UnicodeRange _all;

		private static UnicodeRange _u0000;

		private static UnicodeRange _u0080;

		private static UnicodeRange _u0100;

		private static UnicodeRange _u0180;

		private static UnicodeRange _u0250;

		private static UnicodeRange _u02B0;

		private static UnicodeRange _u0300;

		private static UnicodeRange _u0370;

		private static UnicodeRange _u0400;

		private static UnicodeRange _u0500;

		private static UnicodeRange _u0530;

		private static UnicodeRange _u0590;

		private static UnicodeRange _u0600;

		private static UnicodeRange _u0700;

		private static UnicodeRange _u0750;

		private static UnicodeRange _u0780;

		private static UnicodeRange _u07C0;

		private static UnicodeRange _u0800;

		private static UnicodeRange _u0840;

		private static UnicodeRange _u0860;

		private static UnicodeRange _u0870;

		private static UnicodeRange _u08A0;

		private static UnicodeRange _u0900;

		private static UnicodeRange _u0980;

		private static UnicodeRange _u0A00;

		private static UnicodeRange _u0A80;

		private static UnicodeRange _u0B00;

		private static UnicodeRange _u0B80;

		private static UnicodeRange _u0C00;

		private static UnicodeRange _u0C80;

		private static UnicodeRange _u0D00;

		private static UnicodeRange _u0D80;

		private static UnicodeRange _u0E00;

		private static UnicodeRange _u0E80;

		private static UnicodeRange _u0F00;

		private static UnicodeRange _u1000;

		private static UnicodeRange _u10A0;

		private static UnicodeRange _u1100;

		private static UnicodeRange _u1200;

		private static UnicodeRange _u1380;

		private static UnicodeRange _u13A0;

		private static UnicodeRange _u1400;

		private static UnicodeRange _u1680;

		private static UnicodeRange _u16A0;

		private static UnicodeRange _u1700;

		private static UnicodeRange _u1720;

		private static UnicodeRange _u1740;

		private static UnicodeRange _u1760;

		private static UnicodeRange _u1780;

		private static UnicodeRange _u1800;

		private static UnicodeRange _u18B0;

		private static UnicodeRange _u1900;

		private static UnicodeRange _u1950;

		private static UnicodeRange _u1980;

		private static UnicodeRange _u19E0;

		private static UnicodeRange _u1A00;

		private static UnicodeRange _u1A20;

		private static UnicodeRange _u1AB0;

		private static UnicodeRange _u1B00;

		private static UnicodeRange _u1B80;

		private static UnicodeRange _u1BC0;

		private static UnicodeRange _u1C00;

		private static UnicodeRange _u1C50;

		private static UnicodeRange _u1C80;

		private static UnicodeRange _u1C90;

		private static UnicodeRange _u1CC0;

		private static UnicodeRange _u1CD0;

		private static UnicodeRange _u1D00;

		private static UnicodeRange _u1D80;

		private static UnicodeRange _u1DC0;

		private static UnicodeRange _u1E00;

		private static UnicodeRange _u1F00;

		private static UnicodeRange _u2000;

		private static UnicodeRange _u2070;

		private static UnicodeRange _u20A0;

		private static UnicodeRange _u20D0;

		private static UnicodeRange _u2100;

		private static UnicodeRange _u2150;

		private static UnicodeRange _u2190;

		private static UnicodeRange _u2200;

		private static UnicodeRange _u2300;

		private static UnicodeRange _u2400;

		private static UnicodeRange _u2440;

		private static UnicodeRange _u2460;

		private static UnicodeRange _u2500;

		private static UnicodeRange _u2580;

		private static UnicodeRange _u25A0;

		private static UnicodeRange _u2600;

		private static UnicodeRange _u2700;

		private static UnicodeRange _u27C0;

		private static UnicodeRange _u27F0;

		private static UnicodeRange _u2800;

		private static UnicodeRange _u2900;

		private static UnicodeRange _u2980;

		private static UnicodeRange _u2A00;

		private static UnicodeRange _u2B00;

		private static UnicodeRange _u2C00;

		private static UnicodeRange _u2C60;

		private static UnicodeRange _u2C80;

		private static UnicodeRange _u2D00;

		private static UnicodeRange _u2D30;

		private static UnicodeRange _u2D80;

		private static UnicodeRange _u2DE0;

		private static UnicodeRange _u2E00;

		private static UnicodeRange _u2E80;

		private static UnicodeRange _u2F00;

		private static UnicodeRange _u2FF0;

		private static UnicodeRange _u3000;

		private static UnicodeRange _u3040;

		private static UnicodeRange _u30A0;

		private static UnicodeRange _u3100;

		private static UnicodeRange _u3130;

		private static UnicodeRange _u3190;

		private static UnicodeRange _u31A0;

		private static UnicodeRange _u31C0;

		private static UnicodeRange _u31F0;

		private static UnicodeRange _u3200;

		private static UnicodeRange _u3300;

		private static UnicodeRange _u3400;

		private static UnicodeRange _u4DC0;

		private static UnicodeRange _u4E00;

		private static UnicodeRange _uA000;

		private static UnicodeRange _uA490;

		private static UnicodeRange _uA4D0;

		private static UnicodeRange _uA500;

		private static UnicodeRange _uA640;

		private static UnicodeRange _uA6A0;

		private static UnicodeRange _uA700;

		private static UnicodeRange _uA720;

		private static UnicodeRange _uA800;

		private static UnicodeRange _uA830;

		private static UnicodeRange _uA840;

		private static UnicodeRange _uA880;

		private static UnicodeRange _uA8E0;

		private static UnicodeRange _uA900;

		private static UnicodeRange _uA930;

		private static UnicodeRange _uA960;

		private static UnicodeRange _uA980;

		private static UnicodeRange _uA9E0;

		private static UnicodeRange _uAA00;

		private static UnicodeRange _uAA60;

		private static UnicodeRange _uAA80;

		private static UnicodeRange _uAAE0;

		private static UnicodeRange _uAB00;

		private static UnicodeRange _uAB30;

		private static UnicodeRange _uAB70;

		private static UnicodeRange _uABC0;

		private static UnicodeRange _uAC00;

		private static UnicodeRange _uD7B0;

		private static UnicodeRange _uF900;

		private static UnicodeRange _uFB00;

		private static UnicodeRange _uFB50;

		private static UnicodeRange _uFE00;

		private static UnicodeRange _uFE10;

		private static UnicodeRange _uFE20;

		private static UnicodeRange _uFE30;

		private static UnicodeRange _uFE50;

		private static UnicodeRange _uFE70;

		private static UnicodeRange _uFF00;

		private static UnicodeRange _uFFF0;

		public static UnicodeRange None => _none ?? CreateEmptyRange(ref _none);

		public static UnicodeRange All => _all ?? CreateRange(ref _all, '\0', '\uffff');

		public static UnicodeRange BasicLatin => _u0000 ?? CreateRange(ref _u0000, '\0', '\u007f');

		public static UnicodeRange Latin1Supplement => _u0080 ?? CreateRange(ref _u0080, '\u0080', 'ÿ');

		public static UnicodeRange LatinExtendedA => _u0100 ?? CreateRange(ref _u0100, 'Ā', 'ſ');

		public static UnicodeRange LatinExtendedB => _u0180 ?? CreateRange(ref _u0180, 'ƀ', 'ɏ');

		public static UnicodeRange IpaExtensions => _u0250 ?? CreateRange(ref _u0250, 'ɐ', 'ʯ');

		public static UnicodeRange SpacingModifierLetters => _u02B0 ?? CreateRange(ref _u02B0, 'ʰ', '\u02ff');

		public static UnicodeRange CombiningDiacriticalMarks => _u0300 ?? CreateRange(ref _u0300, '\u0300', '\u036f');

		public static UnicodeRange GreekandCoptic => _u0370 ?? CreateRange(ref _u0370, 'Ͱ', 'Ͽ');

		public static UnicodeRange Cyrillic => _u0400 ?? CreateRange(ref _u0400, 'Ѐ', 'ӿ');

		public static UnicodeRange CyrillicSupplement => _u0500 ?? CreateRange(ref _u0500, 'Ԁ', 'ԯ');

		public static UnicodeRange Armenian => _u0530 ?? CreateRange(ref _u0530, '\u0530', '֏');

		public static UnicodeRange Hebrew => _u0590 ?? CreateRange(ref _u0590, '\u0590', '\u05ff');

		public static UnicodeRange Arabic => _u0600 ?? CreateRange(ref _u0600, '\u0600', 'ۿ');

		public static UnicodeRange Syriac => _u0700 ?? CreateRange(ref _u0700, '܀', 'ݏ');

		public static UnicodeRange ArabicSupplement => _u0750 ?? CreateRange(ref _u0750, 'ݐ', 'ݿ');

		public static UnicodeRange Thaana => _u0780 ?? CreateRange(ref _u0780, 'ހ', '\u07bf');

		public static UnicodeRange NKo => _u07C0 ?? CreateRange(ref _u07C0, '߀', '߿');

		public static UnicodeRange Samaritan => _u0800 ?? CreateRange(ref _u0800, 'ࠀ', '\u083f');

		public static UnicodeRange Mandaic => _u0840 ?? CreateRange(ref _u0840, 'ࡀ', '\u085f');

		public static UnicodeRange SyriacSupplement => _u0860 ?? CreateRange(ref _u0860, 'ࡠ', '\u086f');

		public static UnicodeRange ArabicExtendedB => _u0870 ?? CreateRange(ref _u0870, '\u0870', '\u089f');

		public static UnicodeRange ArabicExtendedA => _u08A0 ?? CreateRange(ref _u08A0, 'ࢠ', '\u08ff');

		public static UnicodeRange Devanagari => _u0900 ?? CreateRange(ref _u0900, '\u0900', 'ॿ');

		public static UnicodeRange Bengali => _u0980 ?? CreateRange(ref _u0980, 'ঀ', '\u09ff');

		public static UnicodeRange Gurmukhi => _u0A00 ?? CreateRange(ref _u0A00, '\u0a00', '\u0a7f');

		public static UnicodeRange Gujarati => _u0A80 ?? CreateRange(ref _u0A80, '\u0a80', '\u0aff');

		public static UnicodeRange Oriya => _u0B00 ?? CreateRange(ref _u0B00, '\u0b00', '\u0b7f');

		public static UnicodeRange Tamil => _u0B80 ?? CreateRange(ref _u0B80, '\u0b80', '\u0bff');

		public static UnicodeRange Telugu => _u0C00 ?? CreateRange(ref _u0C00, '\u0c00', '౿');

		public static UnicodeRange Kannada => _u0C80 ?? CreateRange(ref _u0C80, 'ಀ', '\u0cff');

		public static UnicodeRange Malayalam => _u0D00 ?? CreateRange(ref _u0D00, '\u0d00', 'ൿ');

		public static UnicodeRange Sinhala => _u0D80 ?? CreateRange(ref _u0D80, '\u0d80', '\u0dff');

		public static UnicodeRange Thai => _u0E00 ?? CreateRange(ref _u0E00, '\u0e00', '\u0e7f');

		public static UnicodeRange Lao => _u0E80 ?? CreateRange(ref _u0E80, '\u0e80', '\u0eff');

		public static UnicodeRange Tibetan => _u0F00 ?? CreateRange(ref _u0F00, 'ༀ', '\u0fff');

		public static UnicodeRange Myanmar => _u1000 ?? CreateRange(ref _u1000, 'က', '႟');

		public static UnicodeRange Georgian => _u10A0 ?? CreateRange(ref _u10A0, 'Ⴀ', 'ჿ');

		public static UnicodeRange HangulJamo => _u1100 ?? CreateRange(ref _u1100, 'ᄀ', 'ᇿ');

		public static UnicodeRange Ethiopic => _u1200 ?? CreateRange(ref _u1200, 'ሀ', '\u137f');

		public static UnicodeRange EthiopicSupplement => _u1380 ?? CreateRange(ref _u1380, 'ᎀ', '\u139f');

		public static UnicodeRange Cherokee => _u13A0 ?? CreateRange(ref _u13A0, 'Ꭰ', '\u13ff');

		public static UnicodeRange UnifiedCanadianAboriginalSyllabics => _u1400 ?? CreateRange(ref _u1400, '᐀', 'ᙿ');

		public static UnicodeRange Ogham => _u1680 ?? CreateRange(ref _u1680, '\u1680', '\u169f');

		public static UnicodeRange Runic => _u16A0 ?? CreateRange(ref _u16A0, 'ᚠ', '\u16ff');

		public static UnicodeRange Tagalog => _u1700 ?? CreateRange(ref _u1700, 'ᜀ', '\u171f');

		public static UnicodeRange Hanunoo => _u1720 ?? CreateRange(ref _u1720, 'ᜠ', '\u173f');

		public static UnicodeRange Buhid => _u1740 ?? CreateRange(ref _u1740, 'ᝀ', '\u175f');

		public static UnicodeRange Tagbanwa => _u1760 ?? CreateRange(ref _u1760, 'ᝠ', '\u177f');

		public static UnicodeRange Khmer => _u1780 ?? CreateRange(ref _u1780, 'ក', '\u17ff');

		public static UnicodeRange Mongolian => _u1800 ?? CreateRange(ref _u1800, '᠀', '\u18af');

		public static UnicodeRange UnifiedCanadianAboriginalSyllabicsExtended => _u18B0 ?? CreateRange(ref _u18B0, 'ᢰ', '\u18ff');

		public static UnicodeRange Limbu => _u1900 ?? CreateRange(ref _u1900, 'ᤀ', '᥏');

		public static UnicodeRange TaiLe => _u1950 ?? CreateRange(ref _u1950, 'ᥐ', '\u197f');

		public static UnicodeRange NewTaiLue => _u1980 ?? CreateRange(ref _u1980, 'ᦀ', '᧟');

		public static UnicodeRange KhmerSymbols => _u19E0 ?? CreateRange(ref _u19E0, '᧠', '᧿');

		public static UnicodeRange Buginese => _u1A00 ?? CreateRange(ref _u1A00, 'ᨀ', '᨟');

		public static UnicodeRange TaiTham => _u1A20 ?? CreateRange(ref _u1A20, 'ᨠ', '\u1aaf');

		public static UnicodeRange CombiningDiacriticalMarksExtended => _u1AB0 ?? CreateRange(ref _u1AB0, '\u1ab0', '\u1aff');

		public static UnicodeRange Balinese => _u1B00 ?? CreateRange(ref _u1B00, '\u1b00', '\u1b7f');

		public static UnicodeRange Sundanese => _u1B80 ?? CreateRange(ref _u1B80, '\u1b80', 'ᮿ');

		public static UnicodeRange Batak => _u1BC0 ?? CreateRange(ref _u1BC0, 'ᯀ', '᯿');

		public static UnicodeRange Lepcha => _u1C00 ?? CreateRange(ref _u1C00, 'ᰀ', 'ᱏ');

		public static UnicodeRange OlChiki => _u1C50 ?? CreateRange(ref _u1C50, '᱐', '᱿');

		public static UnicodeRange CyrillicExtendedC => _u1C80 ?? CreateRange(ref _u1C80, 'ᲀ', '\u1c8f');

		public static UnicodeRange GeorgianExtended => _u1C90 ?? CreateRange(ref _u1C90, 'Ა', 'Ჿ');

		public static UnicodeRange SundaneseSupplement => _u1CC0 ?? CreateRange(ref _u1CC0, '᳀', '\u1ccf');

		public static UnicodeRange VedicExtensions => _u1CD0 ?? CreateRange(ref _u1CD0, '\u1cd0', '\u1cff');

		public static UnicodeRange PhoneticExtensions => _u1D00 ?? CreateRange(ref _u1D00, 'ᴀ', 'ᵿ');

		public static UnicodeRange PhoneticExtensionsSupplement => _u1D80 ?? CreateRange(ref _u1D80, 'ᶀ', 'ᶿ');

		public static UnicodeRange CombiningDiacriticalMarksSupplement => _u1DC0 ?? CreateRange(ref _u1DC0, '\u1dc0', '\u1dff');

		public static UnicodeRange LatinExtendedAdditional => _u1E00 ?? CreateRange(ref _u1E00, 'Ḁ', 'ỿ');

		public static UnicodeRange GreekExtended => _u1F00 ?? CreateRange(ref _u1F00, 'ἀ', '\u1fff');

		public static UnicodeRange GeneralPunctuation => _u2000 ?? CreateRange(ref _u2000, '\u2000', '\u206f');

		public static UnicodeRange SuperscriptsandSubscripts => _u2070 ?? CreateRange(ref _u2070, '⁰', '\u209f');

		public static UnicodeRange CurrencySymbols => _u20A0 ?? CreateRange(ref _u20A0, '₠', '\u20cf');

		public static UnicodeRange CombiningDiacriticalMarksforSymbols => _u20D0 ?? CreateRange(ref _u20D0, '\u20d0', '\u20ff');

		public static UnicodeRange LetterlikeSymbols => _u2100 ?? CreateRange(ref _u2100, '℀', '⅏');

		public static UnicodeRange NumberForms => _u2150 ?? CreateRange(ref _u2150, '⅐', '\u218f');

		public static UnicodeRange Arrows => _u2190 ?? CreateRange(ref _u2190, '←', '⇿');

		public static UnicodeRange MathematicalOperators => _u2200 ?? CreateRange(ref _u2200, '∀', '⋿');

		public static UnicodeRange MiscellaneousTechnical => _u2300 ?? CreateRange(ref _u2300, '⌀', '⏿');

		public static UnicodeRange ControlPictures => _u2400 ?? CreateRange(ref _u2400, '␀', '\u243f');

		public static UnicodeRange OpticalCharacterRecognition => _u2440 ?? CreateRange(ref _u2440, '⑀', '\u245f');

		public static UnicodeRange EnclosedAlphanumerics => _u2460 ?? CreateRange(ref _u2460, '①', '⓿');

		public static UnicodeRange BoxDrawing => _u2500 ?? CreateRange(ref _u2500, '─', '╿');

		public static UnicodeRange BlockElements => _u2580 ?? CreateRange(ref _u2580, '▀', '▟');

		public static UnicodeRange GeometricShapes => _u25A0 ?? CreateRange(ref _u25A0, '■', '◿');

		public static UnicodeRange MiscellaneousSymbols => _u2600 ?? CreateRange(ref _u2600, '☀', '⛿');

		public static UnicodeRange Dingbats => _u2700 ?? CreateRange(ref _u2700, '✀', '➿');

		public static UnicodeRange MiscellaneousMathematicalSymbolsA => _u27C0 ?? CreateRange(ref _u27C0, '⟀', '⟯');

		public static UnicodeRange SupplementalArrowsA => _u27F0 ?? CreateRange(ref _u27F0, '⟰', '⟿');

		public static UnicodeRange BraillePatterns => _u2800 ?? CreateRange(ref _u2800, '⠀', '⣿');

		public static UnicodeRange SupplementalArrowsB => _u2900 ?? CreateRange(ref _u2900, '⤀', '⥿');

		public static UnicodeRange MiscellaneousMathematicalSymbolsB => _u2980 ?? CreateRange(ref _u2980, '⦀', '⧿');

		public static UnicodeRange SupplementalMathematicalOperators => _u2A00 ?? CreateRange(ref _u2A00, '⨀', '⫿');

		public static UnicodeRange MiscellaneousSymbolsandArrows => _u2B00 ?? CreateRange(ref _u2B00, '⬀', '⯿');

		public static UnicodeRange Glagolitic => _u2C00 ?? CreateRange(ref _u2C00, 'Ⰰ', '\u2c5f');

		public static UnicodeRange LatinExtendedC => _u2C60 ?? CreateRange(ref _u2C60, 'Ⱡ', 'Ɀ');

		public static UnicodeRange Coptic => _u2C80 ?? CreateRange(ref _u2C80, 'Ⲁ', '⳿');

		public static UnicodeRange GeorgianSupplement => _u2D00 ?? CreateRange(ref _u2D00, 'ⴀ', '\u2d2f');

		public static UnicodeRange Tifinagh => _u2D30 ?? CreateRange(ref _u2D30, 'ⴰ', '\u2d7f');

		public static UnicodeRange EthiopicExtended => _u2D80 ?? CreateRange(ref _u2D80, 'ⶀ', '\u2ddf');

		public static UnicodeRange CyrillicExtendedA => _u2DE0 ?? CreateRange(ref _u2DE0, '\u2de0', '\u2dff');

		public static UnicodeRange SupplementalPunctuation => _u2E00 ?? CreateRange(ref _u2E00, '⸀', '\u2e7f');

		public static UnicodeRange CjkRadicalsSupplement => _u2E80 ?? CreateRange(ref _u2E80, '⺀', '\u2eff');

		public static UnicodeRange KangxiRadicals => _u2F00 ?? CreateRange(ref _u2F00, '⼀', '\u2fdf');

		public static UnicodeRange IdeographicDescriptionCharacters => _u2FF0 ?? CreateRange(ref _u2FF0, '⿰', '\u2fff');

		public static UnicodeRange CjkSymbolsandPunctuation => _u3000 ?? CreateRange(ref _u3000, '\u3000', '〿');

		public static UnicodeRange Hiragana => _u3040 ?? CreateRange(ref _u3040, '\u3040', 'ゟ');

		public static UnicodeRange Katakana => _u30A0 ?? CreateRange(ref _u30A0, '゠', 'ヿ');

		public static UnicodeRange Bopomofo => _u3100 ?? CreateRange(ref _u3100, '\u3100', 'ㄯ');

		public static UnicodeRange HangulCompatibilityJamo => _u3130 ?? CreateRange(ref _u3130, '\u3130', '\u318f');

		public static UnicodeRange Kanbun => _u3190 ?? CreateRange(ref _u3190, '㆐', '㆟');

		public static UnicodeRange BopomofoExtended => _u31A0 ?? CreateRange(ref _u31A0, 'ㆠ', 'ㆿ');

		public static UnicodeRange CjkStrokes => _u31C0 ?? CreateRange(ref _u31C0, '㇀', '\u31ef');

		public static UnicodeRange KatakanaPhoneticExtensions => _u31F0 ?? CreateRange(ref _u31F0, 'ㇰ', 'ㇿ');

		public static UnicodeRange EnclosedCjkLettersandMonths => _u3200 ?? CreateRange(ref _u3200, '㈀', '㋿');

		public static UnicodeRange CjkCompatibility => _u3300 ?? CreateRange(ref _u3300, '㌀', '㏿');

		public static UnicodeRange CjkUnifiedIdeographsExtensionA => _u3400 ?? CreateRange(ref _u3400, '㐀', '䶿');

		public static UnicodeRange YijingHexagramSymbols => _u4DC0 ?? CreateRange(ref _u4DC0, '䷀', '䷿');

		public static UnicodeRange CjkUnifiedIdeographs => _u4E00 ?? CreateRange(ref _u4E00, '一', '\u9fff');

		public static UnicodeRange YiSyllables => _uA000 ?? CreateRange(ref _uA000, 'ꀀ', '\ua48f');

		public static UnicodeRange YiRadicals => _uA490 ?? CreateRange(ref _uA490, '꒐', '\ua4cf');

		public static UnicodeRange Lisu => _uA4D0 ?? CreateRange(ref _uA4D0, 'ꓐ', '꓿');

		public static UnicodeRange Vai => _uA500 ?? CreateRange(ref _uA500, 'ꔀ', '\ua63f');

		public static UnicodeRange CyrillicExtendedB => _uA640 ?? CreateRange(ref _uA640, 'Ꙁ', '\ua69f');

		public static UnicodeRange Bamum => _uA6A0 ?? CreateRange(ref _uA6A0, 'ꚠ', '\ua6ff');

		public static UnicodeRange ModifierToneLetters => _uA700 ?? CreateRange(ref _uA700, '\ua700', 'ꜟ');

		public static UnicodeRange LatinExtendedD => _uA720 ?? CreateRange(ref _uA720, '\ua720', 'ꟿ');

		public static UnicodeRange SylotiNagri => _uA800 ?? CreateRange(ref _uA800, 'ꠀ', '\ua82f');

		public static UnicodeRange CommonIndicNumberForms => _uA830 ?? CreateRange(ref _uA830, '꠰', '\ua83f');

		public static UnicodeRange Phagspa => _uA840 ?? CreateRange(ref _uA840, 'ꡀ', '\ua87f');

		public static UnicodeRange Saurashtra => _uA880 ?? CreateRange(ref _uA880, '\ua880', '\ua8df');

		public static UnicodeRange DevanagariExtended => _uA8E0 ?? CreateRange(ref _uA8E0, '\ua8e0', '\ua8ff');

		public static UnicodeRange KayahLi => _uA900 ?? CreateRange(ref _uA900, '꤀', '꤯');

		public static UnicodeRange Rejang => _uA930 ?? CreateRange(ref _uA930, 'ꤰ', '꥟');

		public static UnicodeRange HangulJamoExtendedA => _uA960 ?? CreateRange(ref _uA960, 'ꥠ', '\ua97f');

		public static UnicodeRange Javanese => _uA980 ?? CreateRange(ref _uA980, '\ua980', '꧟');

		public static UnicodeRange MyanmarExtendedB => _uA9E0 ?? CreateRange(ref _uA9E0, 'ꧠ', '\ua9ff');

		public static UnicodeRange Cham => _uAA00 ?? CreateRange(ref _uAA00, 'ꨀ', '꩟');

		public static UnicodeRange MyanmarExtendedA => _uAA60 ?? CreateRange(ref _uAA60, 'ꩠ', 'ꩿ');

		public static UnicodeRange TaiViet => _uAA80 ?? CreateRange(ref _uAA80, 'ꪀ', '꫟');

		public static UnicodeRange MeeteiMayekExtensions => _uAAE0 ?? CreateRange(ref _uAAE0, 'ꫠ', '\uaaff');

		public static UnicodeRange EthiopicExtendedA => _uAB00 ?? CreateRange(ref _uAB00, '\uab00', '\uab2f');

		public static UnicodeRange LatinExtendedE => _uAB30 ?? CreateRange(ref _uAB30, 'ꬰ', '\uab6f');

		public static UnicodeRange CherokeeSupplement => _uAB70 ?? CreateRange(ref _uAB70, 'ꭰ', 'ꮿ');

		public static UnicodeRange MeeteiMayek => _uABC0 ?? CreateRange(ref _uABC0, 'ꯀ', '\uabff');

		public static UnicodeRange HangulSyllables => _uAC00 ?? CreateRange(ref _uAC00, '가', '\ud7af');

		public static UnicodeRange HangulJamoExtendedB => _uD7B0 ?? CreateRange(ref _uD7B0, 'ힰ', '\ud7ff');

		public static UnicodeRange CjkCompatibilityIdeographs => _uF900 ?? CreateRange(ref _uF900, '豈', '\ufaff');

		public static UnicodeRange AlphabeticPresentationForms => _uFB00 ?? CreateRange(ref _uFB00, 'ff', 'ﭏ');

		public static UnicodeRange ArabicPresentationFormsA => _uFB50 ?? CreateRange(ref _uFB50, 'ﭐ', '\ufdff');

		public static UnicodeRange VariationSelectors => _uFE00 ?? CreateRange(ref _uFE00, '\ufe00', '\ufe0f');

		public static UnicodeRange VerticalForms => _uFE10 ?? CreateRange(ref _uFE10, '︐', '\ufe1f');

		public static UnicodeRange CombiningHalfMarks => _uFE20 ?? CreateRange(ref _uFE20, '\ufe20', '\ufe2f');

		public static UnicodeRange CjkCompatibilityForms => _uFE30 ?? CreateRange(ref _uFE30, '︰', '\ufe4f');

		public static UnicodeRange SmallFormVariants => _uFE50 ?? CreateRange(ref _uFE50, '﹐', '\ufe6f');

		public static UnicodeRange ArabicPresentationFormsB => _uFE70 ?? CreateRange(ref _uFE70, 'ﹰ', '\ufeff');

		public static UnicodeRange HalfwidthandFullwidthForms => _uFF00 ?? CreateRange(ref _uFF00, '\uff00', '\uffef');

		public static UnicodeRange Specials => _uFFF0 ?? CreateRange(ref _uFFF0, '\ufff0', '\uffff');

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static UnicodeRange CreateEmptyRange([NotNull] ref UnicodeRange range)
		{
			Volatile.Write(ref range, new UnicodeRange(0, 0));
			return range;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static UnicodeRange CreateRange([NotNull] ref UnicodeRange range, char first, char last)
		{
			Volatile.Write(ref range, UnicodeRange.Create(first, last));
			return range;
		}
	}
}
namespace System.Text.Encodings.Web
{
	internal struct AsciiByteMap
	{
		private const int BufferSize = 128;

		private unsafe fixed byte Buffer[128];

		internal unsafe void InsertAsciiChar(char key, byte value)
		{
			if (key < '\u0080')
			{
				Buffer[(uint)key] = value;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal unsafe readonly bool TryLookup(Rune key, out byte value)
		{
			if (key.IsAscii)
			{
				byte b = Buffer[(uint)key.Value];
				if (b != 0)
				{
					value = b;
					return true;
				}
			}
			value = 0;
			return false;
		}
	}
	internal struct AllowedBmpCodePointsBitmap
	{
		private const int BitmapLengthInDWords = 2048;

		private unsafe fixed uint Bitmap[2048];

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void AllowChar(char value)
		{
			_GetIndexAndOffset(value, out UIntPtr index, out int offset);
			ref uint reference = ref Bitmap[(ulong)index];
			reference |= (uint)(1 << offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void ForbidChar(char value)
		{
			_GetIndexAndOffset(value, out UIntPtr index, out int offset);
			ref uint reference = ref Bitmap[(ulong)index];
			reference &= (uint)(~(1 << offset));
		}

		public void ForbidHtmlCharacters()
		{
			ForbidChar('<');
			ForbidChar('>');
			ForbidChar('&');
			ForbidChar('\'');
			ForbidChar('"');
			ForbidChar('+');
		}

		public unsafe void ForbidUndefinedCharacters()
		{
			fixed (uint* pointer = Bitmap)
			{
				ReadOnlySpan<byte> definedBmpCodePointsBitmapLittleEndian = UnicodeHelpers.GetDefinedBmpCodePointsBitmapLittleEndian();
				Span<uint> span = new Span<uint>(pointer, 2048);
				for (int i = 0; i < span.Length; i++)
				{
					span[i] &= BinaryPrimitives.ReadUInt32LittleEndian(definedBmpCodePointsBitmapLittleEndian.Slice(i * 4));
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe readonly bool IsCharAllowed(char value)
		{
			_GetIndexAndOffset(

System.Text.Json.dll

Decompiled 3 months ago
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Pipelines;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Reflection;
using System.Text.Json.Schema;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using FxResources.System.Text.Json;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Text.Json")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nThe System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")]
[assembly: AssemblyFileVersion("9.0.225.6610")]
[assembly: AssemblyInformationalVersion("9.0.2+80aa709f5d919c6814726788dc6dabe23e79e672")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Text.Json")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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 RequiresLocationAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 FxResources.System.Text.Json
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				ToCharsBuffer(bytes[i], chars, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(chars, bytes, out charsProcessed);
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < bytes.Length)
			{
				num3 = FromChar(chars[num + 1]);
				num4 = FromChar(chars[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				bytes[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class Obsoletions
	{
		internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}";

		internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.";

		internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001";

		internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used.";

		internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002";

		internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime.";

		internal const string CodeAccessSecurityDiagId = "SYSLIB0003";

		internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported.";

		internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004";

		internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported.";

		internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005";

		internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadAbortDiagId = "SYSLIB0006";

		internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported.";

		internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007";

		internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException.";

		internal const string CreatePdbGeneratorDiagId = "SYSLIB0008";

		internal const string AuthenticationManagerMessage = "AuthenticationManager is not supported. Methods will no-op or throw PlatformNotSupportedException.";

		internal const string AuthenticationManagerDiagId = "SYSLIB0009";

		internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException.";

		internal const string RemotingApisDiagId = "SYSLIB0010";

		internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.";

		internal const string BinaryFormatterDiagId = "SYSLIB0011";

		internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead.";

		internal const string CodeBaseDiagId = "SYSLIB0012";

		internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead.";

		internal const string EscapeUriStringDiagId = "SYSLIB0013";

		internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.";

		internal const string WebRequestDiagId = "SYSLIB0014";

		internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+.";

		internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015";

		internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations.";

		internal const string GetContextInfoDiagId = "SYSLIB0016";

		internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException.";

		internal const string StrongNameKeyPairDiagId = "SYSLIB0017";

		internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException.";

		internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018";

		internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException.";

		internal const string RuntimeEnvironmentDiagId = "SYSLIB0019";

		internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull.";

		internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020";

		internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead.";

		internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021";

		internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead.";

		internal const string RijndaelDiagId = "SYSLIB0022";

		internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.";

		internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023";

		internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception.";

		internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024";

		internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+.";

		internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025";

		internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use X509CertificateLoader to create a new certificate.";

		internal const string X509CertificateImmutableDiagId = "SYSLIB0026";

		internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey.";

		internal const string PublicKeyPropertyDiagId = "SYSLIB0027";

		internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.";

		internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028";

		internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported.";

		internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029";

		internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter.";

		internal const string UseManagedSha1DiagId = "SYSLIB0030";

		internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1.";

		internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031";

		internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored.";

		internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032";

		internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead.";

		internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033";

		internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead.";

		internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034";

		internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner.";

		internal const string SignerInfoCounterSigDiagId = "SYSLIB0035";

		internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.";

		internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036";

		internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported.";

		internal const string AssemblyNameMembersDiagId = "SYSLIB0037";

		internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information.";

		internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038";

		internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults.";

		internal const string TlsVersion10and11DiagId = "SYSLIB0039";

		internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code.";

		internal const string EncryptionPolicyDiagId = "SYSLIB0040";

		internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations.";

		internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041";

		internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys.";

		internal const string EccXmlExportImportDiagId = "SYSLIB0042";

		internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead.";

		internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043";

		internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.";

		internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044";

		internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead.";

		internal const string CryptoStringFactoryDiagId = "SYSLIB0045";

		internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code.";

		internal const string ControlledExecutionRunDiagId = "SYSLIB0046";

		internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution.";

		internal const string XmlSecureResolverDiagId = "SYSLIB0047";

		internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead.";

		internal const string RsaEncryptDecryptDiagId = "SYSLIB0048";

		internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties.";

		internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049";

		internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used.";

		internal const string LegacyFormatterDiagId = "SYSLIB0050";

		internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code.";

		internal const string LegacyFormatterImplDiagId = "SYSLIB0051";

		internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported.";

		internal const string RegexExtensibilityDiagId = "SYSLIB0052";

		internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size.";

		internal const string AesGcmTagConstructorDiagId = "SYSLIB0053";

		internal const string ThreadVolatileReadWriteMessage = "Thread.VolatileRead and Thread.VolatileWrite are obsolete. Use Volatile.Read or Volatile.Write respectively instead.";

		internal const string ThreadVolatileReadWriteDiagId = "SYSLIB0054";

		internal const string ArmIntrinsicPerformsUnsignedOperationMessage = "The underlying hardware instruction does not perform a signed saturate narrowing operation, and it always returns an unsigned result. Use the unsigned overload instead.";

		internal const string ArmIntrinsicPerformsUnsignedOperationDiagId = "SYSLIB0055";

		internal const string LoadFromHashAlgorithmMessage = "LoadFrom with a custom AssemblyHashAlgorithm is obsolete. Use overloads without an AssemblyHashAlgorithm.";

		internal const string LoadFromHashAlgorithmDiagId = "SYSLIB0056";

		internal const string X509CtorCertDataObsoleteMessage = "Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates.";

		internal const string X509CtorCertDataObsoleteDiagId = "SYSLIB0057";
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge");

		internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss");

		internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16");

		internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16");

		internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose");

		internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty");

		internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8");

		internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64");

		internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16");

		internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16");

		internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8");

		internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray");

		internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty");

		internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose");

		internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject");

		internal static string DepthTooLarge => GetResourceString("DepthTooLarge");

		internal static string DestinationTooShort => GetResourceString("DestinationTooShort");

		internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid");

		internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound");

		internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound");

		internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson");

		internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound");

		internal static string ExpectedFalse => GetResourceString("ExpectedFalse");

		internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens");

		internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken");

		internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound");

		internal static string ExpectedNull => GetResourceString("ExpectedNull");

		internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound");

		internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound");

		internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound");

		internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound");

		internal static string ExpectedTrue => GetResourceString("ExpectedTrue");

		internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound");

		internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan");

		internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter");

		internal static string InvalidCast => GetResourceString("InvalidCast");

		internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString");

		internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString");

		internal static string UnsupportedEnumIdentifier => GetResourceString("UnsupportedEnumIdentifier");

		internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive");

		internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString");

		internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments");

		internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType");

		internal static string JsonElementDeepEqualsInsufficientExecutionStack => GetResourceString("JsonElementDeepEqualsInsufficientExecutionStack");

		internal static string JsonNumberExponentTooLarge => GetResourceString("JsonNumberExponentTooLarge");

		internal static string DefaultTypeInfoResolverImmutable => GetResourceString("DefaultTypeInfoResolverImmutable");

		internal static string TypeInfoResolverChainImmutable => GetResourceString("TypeInfoResolverChainImmutable");

		internal static string TypeInfoImmutable => GetResourceString("TypeInfoImmutable");

		internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive");

		internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid");

		internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray");

		internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty");

		internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge");

		internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge");

		internal static string FormatDecimal => GetResourceString("FormatDecimal");

		internal static string FormatDouble => GetResourceString("FormatDouble");

		internal static string FormatInt32 => GetResourceString("FormatInt32");

		internal static string FormatInt64 => GetResourceString("FormatInt64");

		internal static string FormatSingle => GetResourceString("FormatSingle");

		internal static string FormatUInt32 => GetResourceString("FormatUInt32");

		internal static string FormatUInt64 => GetResourceString("FormatUInt64");

		internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal");

		internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign");

		internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData");

		internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported");

		internal static string ValueTooLarge => GetResourceString("ValueTooLarge");

		internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd");

		internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue");

		internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType");

		internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize");

		internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar");

		internal static string InvalidComparison => GetResourceString("InvalidComparison");

		internal static string UnsupportedFormat => GetResourceString("UnsupportedFormat");

		internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment");

		internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd");

		internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd");

		internal static string SerializerOptionsReadOnly => GetResourceString("SerializerOptionsReadOnly");

		internal static string SerializerOptions_InvalidChainedResolver => GetResourceString("SerializerOptions_InvalidChainedResolver");

		internal static string StreamNotWritable => GetResourceString("StreamNotWritable");

		internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter");

		internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict");

		internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull");

		internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid");

		internal static string PropertyTypeNotNullable => GetResourceString("PropertyTypeNotNullable");

		internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute");

		internal static string ExtensionDataConflictsWithUnmappedMemberHandling => GetResourceString("ExtensionDataConflictsWithUnmappedMemberHandling");

		internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType");

		internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization");

		internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment");

		internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment");

		internal static string CannotSkip => GetResourceString("CannotSkip");

		internal static string NotEnoughData => GetResourceString("NotEnoughData");

		internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator");

		internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments");

		internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor");

		internal static string DeserializeInterfaceOrAbstractType => GetResourceString("DeserializeInterfaceOrAbstractType");

		internal static string DeserializationMustSpecifyTypeDiscriminator => GetResourceString("DeserializationMustSpecifyTypeDiscriminator");

		internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible");

		internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid");

		internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead");

		internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible");

		internal static string ResolverTypeNotCompatible => GetResourceString("ResolverTypeNotCompatible");

		internal static string ResolverTypeInfoOptionsNotCompatible => GetResourceString("ResolverTypeInfoOptionsNotCompatible");

		internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite");

		internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull");

		internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute");

		internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize");

		internal static string FormatByte => GetResourceString("FormatByte");

		internal static string FormatInt16 => GetResourceString("FormatInt16");

		internal static string FormatSByte => GetResourceString("FormatSByte");

		internal static string FormatUInt16 => GetResourceString("FormatUInt16");

		internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected");

		internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber");

		internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable");

		internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound");

		internal static string MetadataIdCannotBeCombinedWithRef => GetResourceString("MetadataIdCannotBeCombinedWithRef");

		internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType");

		internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues");

		internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed");

		internal static string MetadataInvalidPropertyInArrayMetadata => GetResourceString("MetadataInvalidPropertyInArrayMetadata");

		internal static string MetadataStandaloneValuesProperty => GetResourceString("MetadataStandaloneValuesProperty");

		internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties");

		internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound");

		internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString");

		internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign");

		internal static string MetadataUnexpectedProperty => GetResourceString("MetadataUnexpectedProperty");

		internal static string UnmappedJsonProperty => GetResourceString("UnmappedJsonProperty");

		internal static string DuplicateMetadataProperty => GetResourceString("DuplicateMetadataProperty");

		internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter");

		internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding");

		internal static string ObjectWithParameterizedCtorRefMetadataNotSupported => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotSupported");

		internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull");

		internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType");

		internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam");

		internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded");

		internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType");

		internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported");

		internal static string JsonIncludeOnInaccessibleProperty => GetResourceString("JsonIncludeOnInaccessibleProperty");

		internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember");

		internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection");

		internal static string ConstructorContainsNullParameterNames => GetResourceString("ConstructorContainsNullParameterNames");

		internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified");

		internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid");

		internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported");

		internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid");

		internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid");

		internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes");

		internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType");

		internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue");

		internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull");

		internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory");

		internal static string SerializerConverterFactoryInvalidArgument => GetResourceString("SerializerConverterFactoryInvalidArgument");

		internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType");

		internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray");

		internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent");

		internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected");

		internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert");

		internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement");

		internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed");

		internal static string NodeWrongType => GetResourceString("NodeWrongType");

		internal static string NodeParentWrongType => GetResourceString("NodeParentWrongType");

		internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey");

		internal static string SerializerContextOptionsReadOnly => GetResourceString("SerializerContextOptionsReadOnly");

		internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid");

		internal static string NoMetadataForType => GetResourceString("NoMetadataForType");

		internal static string AmbiguousMetadataForType => GetResourceString("AmbiguousMetadataForType");

		internal static string CollectionIsReadOnly => GetResourceString("CollectionIsReadOnly");

		internal static string ArrayIndexNegative => GetResourceString("ArrayIndexNegative");

		internal static string ArrayTooSmall => GetResourceString("ArrayTooSmall");

		internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty");

		internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties");

		internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual");

		internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember");

		internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported");

		internal static string Polymorphism_BaseConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_BaseConverterDoesNotSupportMetadata");

		internal static string Polymorphism_DerivedConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_DerivedConverterDoesNotSupportMetadata");

		internal static string Polymorphism_TypeDoesNotSupportPolymorphism => GetResourceString("Polymorphism_TypeDoesNotSupportPolymorphism");

		internal static string Polymorphism_DerivedTypeIsNotSupported => GetResourceString("Polymorphism_DerivedTypeIsNotSupported");

		internal static string Polymorphism_DerivedTypeIsAlreadySpecified => GetResourceString("Polymorphism_DerivedTypeIsAlreadySpecified");

		internal static string Polymorphism_TypeDicriminatorIdIsAlreadySpecified => GetResourceString("Polymorphism_TypeDicriminatorIdIsAlreadySpecified");

		internal static string Polymorphism_InvalidCustomTypeDiscriminatorPropertyName => GetResourceString("Polymorphism_InvalidCustomTypeDiscriminatorPropertyName");

		internal static string Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes => GetResourceString("Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes");

		internal static string Polymorphism_UnrecognizedTypeDiscriminator => GetResourceString("Polymorphism_UnrecognizedTypeDiscriminator");

		internal static string Polymorphism_RuntimeTypeNotSupported => GetResourceString("Polymorphism_RuntimeTypeNotSupported");

		internal static string Polymorphism_RuntimeTypeDiamondAmbiguity => GetResourceString("Polymorphism_RuntimeTypeDiamondAmbiguity");

		internal static string InvalidJsonTypeInfoOperationForKind => GetResourceString("InvalidJsonTypeInfoOperationForKind");

		internal static string OnDeserializingCallbacksNotSupported => GetResourceString("OnDeserializingCallbacksNotSupported");

		internal static string CreateObjectConverterNotCompatible => GetResourceString("CreateObjectConverterNotCompatible");

		internal static string JsonPropertyInfoBoundToDifferentParent => GetResourceString("JsonPropertyInfoBoundToDifferentParent");

		internal static string JsonSerializerOptionsNoTypeInfoResolverSpecified => GetResourceString("JsonSerializerOptionsNoTypeInfoResolverSpecified");

		internal static string JsonSerializerIsReflectionDisabled => GetResourceString("JsonSerializerIsReflectionDisabled");

		internal static string JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo => GetResourceString("JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo");

		internal static string JsonPropertyRequiredAndNotDeserializable => GetResourceString("JsonPropertyRequiredAndNotDeserializable");

		internal static string JsonPropertyRequiredAndExtensionData => GetResourceString("JsonPropertyRequiredAndExtensionData");

		internal static string JsonRequiredPropertiesMissing => GetResourceString("JsonRequiredPropertiesMissing");

		internal static string ObjectCreationHandlingPopulateNotSupportedByConverter => GetResourceString("ObjectCreationHandlingPopulateNotSupportedByConverter");

		internal static string ObjectCreationHandlingPropertyMustHaveAGetter => GetResourceString("ObjectCreationHandlingPropertyMustHaveAGetter");

		internal static string ObjectCreationHandlingPropertyValueTypeMustHaveASetter => GetResourceString("ObjectCreationHandlingPropertyValueTypeMustHaveASetter");

		internal static string ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization => GetResourceString("ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization");

		internal static string ObjectCreationHandlingPropertyCannotAllowReadOnlyMember => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReadOnlyMember");

		internal static string ObjectCreationHandlingPropertyCannotAllowReferenceHandling => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReferenceHandling");

		internal static string ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors => GetResourceString("ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors");

		internal static string FormatInt128 => GetResourceString("FormatInt128");

		internal static string FormatUInt128 => GetResourceString("FormatUInt128");

		internal static string FormatHalf => GetResourceString("FormatHalf");

		internal static string InvalidIndentCharacter => GetResourceString("InvalidIndentCharacter");

		internal static string InvalidIndentSize => GetResourceString("InvalidIndentSize");

		internal static string PipeWriterCanceled => GetResourceString("PipeWriterCanceled");

		internal static string PipeWriter_DoesNotImplementUnflushedBytes => GetResourceString("PipeWriter_DoesNotImplementUnflushedBytes");

		internal static string InvalidNewLine => GetResourceString("InvalidNewLine");

		internal static string PropertyGetterDisallowNull => GetResourceString("PropertyGetterDisallowNull");

		internal static string PropertySetterDisallowNull => GetResourceString("PropertySetterDisallowNull");

		internal static string ConstructorParameterDisallowNull => GetResourceString("ConstructorParameterDisallowNull");

		internal static string JsonSchemaExporter_ReferenceHandlerPreserve_NotSupported => GetResourceString("JsonSchemaExporter_ReferenceHandlerPreserve_NotSupported");

		internal static string JsonSchemaExporter_DepthTooLarge => GetResourceString("JsonSchemaExporter_DepthTooLarge");

		internal static string Arg_WrongType => GetResourceString("Arg_WrongType");

		internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall");

		internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported");

		internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound");

		internal static string Argument_IncompatibleArrayType => GetResourceString("Argument_IncompatibleArrayType");

		internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey");

		internal static string Argument_AddingDuplicate => GetResourceString("Argument_AddingDuplicate");

		internal static string InvalidOperation_ConcurrentOperationsNotSupported => GetResourceString("InvalidOperation_ConcurrentOperationsNotSupported");

		internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion");

		internal static string ArgumentOutOfRange_Generic_MustBeNonNegative => GetResourceString("ArgumentOutOfRange_Generic_MustBeNonNegative");

		internal static string ArgumentOutOfRange_Generic_MustBeGreaterOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeGreaterOrEqual");

		internal static string ArgumentOutOfRange_Generic_MustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeLessOrEqual");

		internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		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);
		}

		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(IFormatProvider provider, string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	internal sealed class ObsoleteAttribute : Attribute
	{
		public string Message { get; }

		public bool IsError { get; }

		public string DiagnosticId { get; set; }

		public string UrlFormat { get; set; }

		public ObsoleteAttribute()
		{
		}

		public ObsoleteAttribute(string message)
		{
			Message = message;
		}

		public ObsoleteAttribute(string message, bool error)
		{
			Message = message;
			IsError = error;
		}
	}
}
namespace System.Reflection
{
	internal sealed class NullabilityInfo
	{
		public Type Type { get; }

		public NullabilityState ReadState { get; internal set; }

		public NullabilityState WriteState { get; internal set; }

		public NullabilityInfo ElementType { get; }

		public NullabilityInfo[] GenericTypeArguments { get; }

		internal NullabilityInfo(Type type, NullabilityState readState, NullabilityState writeState, NullabilityInfo elementType, NullabilityInfo[] typeArguments)
		{
			Type = type;
			ReadState = readState;
			WriteState = writeState;
			ElementType = elementType;
			GenericTypeArguments = typeArguments;
		}
	}
	internal enum NullabilityState
	{
		Unknown,
		NotNull,
		Nullable
	}
	internal sealed class NullabilityInfoContext
	{
		[Flags]
		private enum NotAnnotatedStatus
		{
			None = 0,
			Private = 1,
			Internal = 2
		}

		private readonly struct NullableAttributeStateParser
		{
			private static readonly object UnknownByte = (byte)0;

			private readonly object _nullableAttributeArgument;

			public static NullableAttributeStateParser Unknown => new NullableAttributeStateParser(UnknownByte);

			public NullableAttributeStateParser(object nullableAttributeArgument)
			{
				_nullableAttributeArgument = nullableAttributeArgument;
			}

			public bool ParseNullableState(int index, ref NullabilityState state)
			{
				object nullableAttributeArgument = _nullableAttributeArgument;
				if (!(nullableAttributeArgument is byte b))
				{
					if (nullableAttributeArgument is ReadOnlyCollection<CustomAttributeTypedArgument> readOnlyCollection)
					{
						ReadOnlyCollection<CustomAttributeTypedArgument> readOnlyCollection2 = readOnlyCollection;
						if (index < readOnlyCollection2.Count && readOnlyCollection2[index].Value is byte b2)
						{
							state = TranslateByte(b2);
							return true;
						}
					}
					return false;
				}
				byte b3 = b;
				state = TranslateByte(b3);
				return true;
			}
		}

		private const string CompilerServicesNameSpace = "System.Runtime.CompilerServices";

		private readonly Dictionary<Module, NotAnnotatedStatus> _publicOnlyModules = new Dictionary<Module, NotAnnotatedStatus>();

		private readonly Dictionary<MemberInfo, NullabilityState> _context = new Dictionary<MemberInfo, NullabilityState>();

		private NullabilityState? GetNullableContext(MemberInfo memberInfo)
		{
			while (memberInfo != null)
			{
				if (_context.TryGetValue(memberInfo, out var value))
				{
					return value;
				}
				foreach (CustomAttributeData customAttributesDatum in memberInfo.GetCustomAttributesData())
				{
					if (customAttributesDatum.AttributeType.Name == "NullableContextAttribute" && customAttributesDatum.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttributesDatum.ConstructorArguments.Count == 1)
					{
						value = TranslateByte(customAttributesDatum.ConstructorArguments[0].Value);
						_context.Add(memberInfo, value);
						return value;
					}
				}
				memberInfo = memberInfo.DeclaringType;
			}
			return null;
		}

		public NullabilityInfo Create(ParameterInfo parameterInfo)
		{
			NetstandardHelpers.ThrowIfNull(parameterInfo, "parameterInfo");
			IList<CustomAttributeData> customAttributesData = parameterInfo.GetCustomAttributesData();
			NullableAttributeStateParser parser = ((parameterInfo.Member is MethodBase method && IsPrivateOrInternalMethodAndAnnotationDisabled(method)) ? NullableAttributeStateParser.Unknown : CreateParser(customAttributesData));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(parameterInfo.Member, parameterInfo.ParameterType, parser);
			if (nullabilityInfo.ReadState != 0)
			{
				CheckParameterMetadataType(parameterInfo, nullabilityInfo);
			}
			CheckNullabilityAttributes(nullabilityInfo, customAttributesData);
			return nullabilityInfo;
		}

		private void CheckParameterMetadataType(ParameterInfo parameter, NullabilityInfo nullability)
		{
			MemberInfo member = parameter.Member;
			MemberInfo metaMember;
			ParameterInfo parameterInfo;
			if (!(member is ConstructorInfo member2))
			{
				if (!(member is MethodInfo method))
				{
					return;
				}
				MethodInfo methodMetadataDefinition = GetMethodMetadataDefinition(method);
				metaMember = methodMetadataDefinition;
				parameterInfo = (string.IsNullOrEmpty(parameter.Name) ? methodMetadataDefinition.ReturnParameter : GetMetaParameter(methodMetadataDefinition, parameter));
			}
			else
			{
				parameterInfo = GetMetaParameter((MethodBase)(metaMember = (ConstructorInfo)GetMemberMetadataDefinition(member2)), parameter);
			}
			if (parameterInfo != null)
			{
				CheckGenericParameters(nullability, metaMember, parameterInfo.ParameterType, parameter.Member.ReflectedType);
			}
		}

		private static ParameterInfo GetMetaParameter(MethodBase metaMethod, ParameterInfo parameter)
		{
			ReadOnlySpan<ParameterInfo> parametersAsSpan = metaMethod.GetParametersAsSpan();
			for (int i = 0; i < parametersAsSpan.Length; i++)
			{
				if (parameter.Position == i && parameter.Name == parametersAsSpan[i].Name)
				{
					return parametersAsSpan[i];
				}
			}
			return null;
		}

		private static MethodInfo GetMethodMetadataDefinition(MethodInfo method)
		{
			if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
			{
				method = method.GetGenericMethodDefinition();
			}
			return (MethodInfo)GetMemberMetadataDefinition(method);
		}

		private static void CheckNullabilityAttributes(NullabilityInfo nullability, IList<CustomAttributeData> attributes)
		{
			NullabilityState nullabilityState = NullabilityState.Unknown;
			NullabilityState nullabilityState2 = NullabilityState.Unknown;
			foreach (CustomAttributeData attribute in attributes)
			{
				if (attribute.AttributeType.Namespace == "System.Diagnostics.CodeAnalysis")
				{
					if (attribute.AttributeType.Name == "NotNullAttribute")
					{
						nullabilityState = NullabilityState.NotNull;
					}
					else if ((attribute.AttributeType.Name == "MaybeNullAttribute" || attribute.AttributeType.Name == "MaybeNullWhenAttribute") && nullabilityState == NullabilityState.Unknown && !IsValueTypeOrValueTypeByRef(nullability.Type))
					{
						nullabilityState = NullabilityState.Nullable;
					}
					else if (attribute.AttributeType.Name == "DisallowNullAttribute")
					{
						nullabilityState2 = NullabilityState.NotNull;
					}
					else if (attribute.AttributeType.Name == "AllowNullAttribute" && nullabilityState2 == NullabilityState.Unknown && !IsValueTypeOrValueTypeByRef(nullability.Type))
					{
						nullabilityState2 = NullabilityState.Nullable;
					}
				}
			}
			if (nullabilityState != 0)
			{
				nullability.ReadState = nullabilityState;
			}
			if (nullabilityState2 != 0)
			{
				nullability.WriteState = nullabilityState2;
			}
		}

		public NullabilityInfo Create(PropertyInfo propertyInfo)
		{
			NetstandardHelpers.ThrowIfNull(propertyInfo, "propertyInfo");
			MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true);
			MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
			NullableAttributeStateParser parser = (((getMethod == null || IsPrivateOrInternalMethodAndAnnotationDisabled(getMethod)) && (setMethod == null || IsPrivateOrInternalMethodAndAnnotationDisabled(setMethod))) ? NullableAttributeStateParser.Unknown : CreateParser(propertyInfo.GetCustomAttributesData()));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(propertyInfo, propertyInfo.PropertyType, parser);
			if (getMethod != null)
			{
				CheckNullabilityAttributes(nullabilityInfo, getMethod.ReturnParameter.GetCustomAttributesData());
			}
			else
			{
				nullabilityInfo.ReadState = NullabilityState.Unknown;
			}
			if (setMethod != null)
			{
				ReadOnlySpan<ParameterInfo> parametersAsSpan = setMethod.GetParametersAsSpan();
				ParameterInfo parameterInfo = parametersAsSpan[parametersAsSpan.Length - 1];
				CheckNullabilityAttributes(nullabilityInfo, parameterInfo.GetCustomAttributesData());
			}
			else
			{
				nullabilityInfo.WriteState = NullabilityState.Unknown;
			}
			return nullabilityInfo;
		}

		private bool IsPrivateOrInternalMethodAndAnnotationDisabled(MethodBase method)
		{
			if ((method.IsPrivate || method.IsFamilyAndAssembly || method.IsAssembly) && IsPublicOnly(method.IsPrivate, method.IsFamilyAndAssembly, method.IsAssembly, method.Module))
			{
				return true;
			}
			return false;
		}

		public NullabilityInfo Create(EventInfo eventInfo)
		{
			NetstandardHelpers.ThrowIfNull(eventInfo, "eventInfo");
			return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType, CreateParser(eventInfo.GetCustomAttributesData()));
		}

		public NullabilityInfo Create(FieldInfo fieldInfo)
		{
			NetstandardHelpers.ThrowIfNull(fieldInfo, "fieldInfo");
			IList<CustomAttributeData> customAttributesData = fieldInfo.GetCustomAttributesData();
			NullableAttributeStateParser parser = (IsPrivateOrInternalFieldAndAnnotationDisabled(fieldInfo) ? NullableAttributeStateParser.Unknown : CreateParser(customAttributesData));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(fieldInfo, fieldInfo.FieldType, parser);
			CheckNullabilityAttributes(nullabilityInfo, customAttributesData);
			return nullabilityInfo;
		}

		private bool IsPrivateOrInternalFieldAndAnnotationDisabled(FieldInfo fieldInfo)
		{
			if ((fieldInfo.IsPrivate || fieldInfo.IsFamilyAndAssembly || fieldInfo.IsAssembly) && IsPublicOnly(fieldInfo.IsPrivate, fieldInfo.IsFamilyAndAssembly, fieldInfo.IsAssembly, fieldInfo.Module))
			{
				return true;
			}
			return false;
		}

		private bool IsPublicOnly(bool isPrivate, bool isFamilyAndAssembly, bool isAssembly, Module module)
		{
			if (!_publicOnlyModules.TryGetValue(module, out var value))
			{
				value = PopulateAnnotationInfo(module.GetCustomAttributesData());
				_publicOnlyModules.Add(module, value);
			}
			if (value == NotAnnotatedStatus.None)
			{
				return false;
			}
			if (((isPrivate || isFamilyAndAssembly) && value.HasFlag(NotAnnotatedStatus.Private)) || (isAssembly && value.HasFlag(NotAnnotatedStatus.Internal)))
			{
				return true;
			}
			return false;
		}

		private static NotAnnotatedStatus PopulateAnnotationInfo(IList<CustomAttributeData> customAttributes)
		{
			bool flag = default(bool);
			foreach (CustomAttributeData customAttribute in customAttributes)
			{
				if (customAttribute.AttributeType.Name == "NullablePublicOnlyAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1)
				{
					object value = customAttribute.ConstructorArguments[0].Value;
					int num;
					if (value is bool)
					{
						flag = (bool)value;
						num = 1;
					}
					else
					{
						num = 0;
					}
					if (((uint)num & (flag ? 1u : 0u)) != 0)
					{
						return NotAnnotatedStatus.Private | NotAnnotatedStatus.Internal;
					}
					return NotAnnotatedStatus.Private;
				}
			}
			return NotAnnotatedStatus.None;
		}

		private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser)
		{
			int index = 0;
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(memberInfo, type, parser, ref index);
			if (nullabilityInfo.ReadState != 0)
			{
				TryLoadGenericMetaTypeNullability(memberInfo, nullabilityInfo);
			}
			return nullabilityInfo;
		}

		private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser, ref int index)
		{
			NullabilityState state = NullabilityState.Unknown;
			NullabilityInfo elementType = null;
			NullabilityInfo[] array = Array.Empty<NullabilityInfo>();
			Type type2 = type;
			if (type2.IsByRef || type2.IsPointer)
			{
				type2 = type2.GetElementType();
			}
			if (type2.IsValueType)
			{
				Type underlyingType = Nullable.GetUnderlyingType(type2);
				if ((object)underlyingType != null)
				{
					type2 = underlyingType;
					state = NullabilityState.Nullable;
				}
				else
				{
					state = NullabilityState.NotNull;
				}
				if (type2.IsGenericType)
				{
					index++;
				}
			}
			else
			{
				if (!parser.ParseNullableState(index++, ref state))
				{
					NullabilityState? nullableContext = GetNullableContext(memberInfo);
					if (nullableContext.HasValue)
					{
						NullabilityState valueOrDefault = nullableContext.GetValueOrDefault();
						state = valueOrDefault;
					}
				}
				if (type2.IsArray)
				{
					elementType = GetNullabilityInfo(memberInfo, type2.GetElementType(), parser, ref index);
				}
			}
			if (type2.IsGenericType)
			{
				Type[] genericArguments = type2.GetGenericArguments();
				array = new NullabilityInfo[genericArguments.Length];
				for (int i = 0; i < genericArguments.Length; i++)
				{
					array[i] = GetNullabilityInfo(memberInfo, genericArguments[i], parser, ref index);
				}
			}
			return new NullabilityInfo(type, state, state, elementType, array);
		}

		private static NullableAttributeStateParser CreateParser(IList<CustomAttributeData> customAttributes)
		{
			foreach (CustomAttributeData customAttribute in customAttributes)
			{
				if (customAttribute.AttributeType.Name == "NullableAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1)
				{
					return new NullableAttributeStateParser(customAttribute.ConstructorArguments[0].Value);
				}
			}
			return new NullableAttributeStateParser(null);
		}

		private void TryLoadGenericMetaTypeNullability(MemberInfo memberInfo, NullabilityInfo nullability)
		{
			MemberInfo memberMetadataDefinition = GetMemberMetadataDefinition(memberInfo);
			Type type = null;
			if (memberMetadataDefinition is FieldInfo fieldInfo)
			{
				type = fieldInfo.FieldType;
			}
			else if (memberMetadataDefinition is PropertyInfo property)
			{
				type = GetPropertyMetaType(property);
			}
			if (type != null)
			{
				CheckGenericParameters(nullability, memberMetadataDefinition, type, memberInfo.ReflectedType);
			}
		}

		private static MemberInfo GetMemberMetadataDefinition(MemberInfo member)
		{
			Type declaringType = member.DeclaringType;
			if (declaringType != null && declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
			{
				return NetstandardHelpers.GetMemberWithSameMetadataDefinitionAs(declaringType.GetGenericTypeDefinition(), member);
			}
			return member;
		}

		private static Type GetPropertyMetaType(PropertyInfo property)
		{
			MethodInfo getMethod = property.GetGetMethod(nonPublic: true);
			if ((object)getMethod != null)
			{
				return getMethod.ReturnType;
			}
			return property.GetSetMethod(nonPublic: true).GetParametersAsSpan()[0].ParameterType;
		}

		private void CheckGenericParameters(NullabilityInfo nullability, MemberInfo metaMember, Type metaType, Type reflectedType)
		{
			if (metaType.IsGenericParameter)
			{
				if (nullability.ReadState == NullabilityState.NotNull)
				{
					TryUpdateGenericParameterNullability(nullability, metaType, reflectedType);
				}
			}
			else
			{
				if (!metaType.ContainsGenericParameters)
				{
					return;
				}
				if (nullability.GenericTypeArguments.Length != 0)
				{
					Type[] genericArguments = metaType.GetGenericArguments();
					for (int i = 0; i < genericArguments.Length; i++)
					{
						CheckGenericParameters(nullability.GenericTypeArguments[i], metaMember, genericArguments[i], reflectedType);
					}
					return;
				}
				NullabilityInfo elementType = nullability.ElementType;
				if (elementType != null && metaType.IsArray)
				{
					CheckGenericParameters(elementType, metaMember, metaType.GetElementType(), reflectedType);
				}
				else if (metaType.IsByRef)
				{
					CheckGenericParameters(nullability, metaMember, metaType.GetElementType(), reflectedType);
				}
			}
		}

		private bool TryUpdateGenericParameterNullability(NullabilityInfo nullability, Type genericParameter, Type reflectedType)
		{
			if ((object)reflectedType != null && !genericParameter.IsGenericMethodParameter() && TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, reflectedType, reflectedType))
			{
				return true;
			}
			if (IsValueTypeOrValueTypeByRef(nullability.Type))
			{
				return true;
			}
			NullabilityState state = NullabilityState.Unknown;
			if (CreateParser(genericParameter.GetCustomAttributesData()).ParseNullableState(0, ref state))
			{
				nullability.ReadState = state;
				nullability.WriteState = state;
				return true;
			}
			NullabilityState? nullableContext = GetNullableContext(genericParameter);
			if (nullableContext.HasValue)
			{
				NullabilityState writeState = (nullability.ReadState = nullableContext.GetValueOrDefault());
				nullability.WriteState = writeState;
				return true;
			}
			return false;
		}

		private bool TryUpdateGenericTypeParameterNullabilityFromReflectedType(NullabilityInfo nullability, Type genericParameter, Type context, Type reflectedType)
		{
			Type type2 = ((context.IsGenericType && !context.IsGenericTypeDefinition) ? context.GetGenericTypeDefinition() : context);
			if (genericParameter.DeclaringType == type2)
			{
				return false;
			}
			Type baseType = type2.BaseType;
			if ((object)baseType == null)
			{
				return false;
			}
			if (!baseType.IsGenericType || (baseType.IsGenericTypeDefinition ? baseType : baseType.GetGenericTypeDefinition()) != genericParameter.DeclaringType)
			{
				return TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, baseType, reflectedType);
			}
			Type[] genericArguments = baseType.GetGenericArguments();
			Type type3 = genericArguments[genericParameter.GenericParameterPosition];
			if (type3.IsGenericParameter)
			{
				return TryUpdateGenericParameterNullability(nullability, type3, reflectedType);
			}
			NullableAttributeStateParser parser = CreateParser(type2.GetCustomAttributesData());
			int index = 1;
			for (int i = 0; i < genericParameter.GenericParameterPosition; i++)
			{
				index += CountNullabilityStates(genericArguments[i]);
			}
			return TryPopulateNullabilityInfo(nullability, parser, ref index);
			static int CountNullabilityStates(Type type)
			{
				Type type4 = Nullable.GetUnderlyingType(type) ?? type;
				if (type4.IsGenericType)
				{
					int num = 1;
					Type[] genericArguments2 = type4.GetGenericArguments();
					foreach (Type type5 in genericArguments2)
					{
						num += CountNullabilityStates(type5);
					}
					return num;
				}
				if (type4.HasElementType)
				{
					return (type4.IsArray ? 1 : 0) + CountNullabilityStates(type4.GetElementType());
				}
				return (!type.IsValueType) ? 1 : 0;
			}
		}

		private static bool TryPopulateNullabilityInfo(NullabilityInfo nullability, NullableAttributeStateParser parser, ref int index)
		{
			bool flag = IsValueTypeOrValueTypeByRef(nullability.Type);
			if (!flag)
			{
				NullabilityState state = NullabilityState.Unknown;
				if (!parser.ParseNullableState(index, ref state))
				{
					return false;
				}
				nullability.ReadState = state;
				nullability.WriteState = state;
			}
			if (!flag || (Nullable.GetUnderlyingType(nullability.Type) ?? nullability.Type).IsGenericType)
			{
				index++;
			}
			if (nullability.GenericTypeArguments.Length != 0)
			{
				NullabilityInfo[] genericTypeArguments = nullability.GenericTypeArguments;
				for (int i = 0; i < genericTypeArguments.Length; i++)
				{
					TryPopulateNullabilityInfo(genericTypeArguments[i], parser, ref index);
				}
			}
			else
			{
				NullabilityInfo elementType = nullability.ElementType;
				if (elementType != null)
				{
					TryPopulateNullabilityInfo(elementType, parser, ref index);
				}
			}
			return true;
		}

		private static NullabilityState TranslateByte(object value)
		{
			if (!(value is byte b))
			{
				return NullabilityState.Unknown;
			}
			return TranslateByte(b);
		}

		private static NullabilityState TranslateByte(byte b)
		{
			return b switch
			{
				1 => NullabilityState.NotNull, 
				2 => NullabilityState.Nullable, 
				_ => NullabilityState.Unknown, 
			};
		}

		private static bool IsValueTypeOrValueTypeByRef(Type type)
		{
			if (!type.IsValueType)
			{
				if (type.IsByRef || type.IsPointer)
				{
					return type.GetElementType().IsValueType;
				}
				return false;
			}
			return true;
		}
	}
	internal static class NetstandardHelpers
	{
		public static void ThrowIfNull(object argument, string paramName)
		{
			if (argument == null)
			{
				Throw(paramName);
			}
			static void Throw(string paramName)
			{
				throw new ArgumentNullException(paramName);
			}
		}

		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This is finding the MemberInfo with the same MetadataToken as specified MemberInfo. If the specified MemberInfo exists and wasn't trimmed, then the current Type's MemberInfo couldn't have been trimmed.")]
		public static MemberInfo GetMemberWithSameMetadataDefinitionAs(this Type type, MemberInfo member)
		{
			ThrowIfNull(member, "member");
			MemberInfo[] members = type.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MemberInfo memberInfo in members)
			{
				if (HasSameMetadataDefinitionAs(memberInfo, member))
				{
					return memberInfo;
				}
			}
			throw new MissingMemberException(type.FullName, member.Name);
		}

		private static bool HasSameMetadataDefinitionAs(this MemberInfo info, MemberInfo other)
		{
			if (info.MetadataToken != other.MetadataToken)
			{
				return false;
			}
			if (!info.Module.Equals(other.Module))
			{
				return false;
			}
			return true;
		}

		public static bool IsGenericMethodParameter(this Type type)
		{
			if (type.IsGenericParameter)
			{
				return (object)type.DeclaringMethod != null;
			}
			return false;
		}

		public static ReadOnlySpan<ParameterInfo> GetParametersAsSpan(this MethodBase metaMethod)
		{
			return metaMethod.GetParameters();
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class DynamicDependencyAttribute : Attribute
	{
		public string MemberSignature { get; }

		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public Type Type { get; }

		public string TypeName { get; }

		public string AssemblyName { get; }

		public string Condition { get; set; }

		public DynamicDependencyAttribute(string memberSignature)
		{
			MemberSignature = memberSignature;
		}

		public DynamicDependencyAttribute(string memberSignature, Type type)
		{
			MemberSignature = memberSignature;
			Type = type;
		}

		public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName)
		{
			MemberSignature = memberSignature;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type)
		{
			MemberTypes = memberTypes;
			Type = type;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName)
		{
			MemberTypes = memberTypes;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string Scope { get; set; }

		public string Target { get; set; }

		public string MessageId { get; set; }

		public string Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class StringSyntaxAttribute : Attribute
	{
		public const string CompositeFormat = "CompositeFormat";

		public const string DateOnlyFormat = "DateOnlyFormat";

		public const string DateTimeFormat = "DateTimeFormat";

		public const string EnumFormat = "EnumFormat";

		public const string GuidFormat = "GuidFormat";

		public const string Json = "Json";

		public const string NumericFormat = "NumericFormat";

		public const string Regex = "Regex";

		public const string TimeOnlyFormat = "TimeOnlyFormat";

		public const string TimeSpanFormat = "TimeSpanFormat";

		public const string Uri = "Uri";

		public const string Xml = "Xml";

		public string Syntax { get; }

		public object[] Arguments { get; }

		public StringSyntaxAttribute(string syntax)
		{
			Syntax = syntax;
			Arguments = Array.Empty<object>();
		}

		public StringSyntaxAttribute(string syntax, params object[] arguments)
		{
			Syntax = syntax;
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Collections
{
	internal static class HashHelpers
	{
		public const uint HashCollisionThreshold = 100u;

		public const int MaxPrimeArrayLength = 2147483587;

		public const int HashPrime = 101;

		internal static ReadOnlySpan<int> Primes
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6;
				if (obj == null)
				{
					obj = new int[72]
					{
						3, 7, 11, 17, 23, 29, 37, 47, 59, 71,
						89, 107, 131, 163, 197, 239, 293, 353, 431, 521,
						631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371,
						4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023,
						25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363,
						156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403,
						968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559,
						5999471, 7199369
					};
					global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6 = (int[])obj;
				}
				return new ReadOnlySpan<int>((int[]?)obj);
			}
		}

		public static bool IsPrime(int candidate)
		{
			if (((uint)candidate & (true ? 1u : 0u)) != 0)
			{
				int num = (int)Math.Sqrt(candidate);
				for (int i = 3; i <= num; i += 2)
				{
					if (candidate % i == 0)
					{
						return false;
					}
				}
				return true;
			}
			return candidate == 2;
		}

		public static int GetPrime(int min)
		{
			if (min < 0)
			{
				throw new ArgumentException(System.SR.Arg_HTCapacityOverflow);
			}
			ReadOnlySpan<int> primes = Primes;
			for (int i = 0; i < primes.Length; i++)
			{
				int num = primes[i];
				if (num >= min)
				{
					return num;
				}
			}
			for (int j = min | 1; j < int.MaxValue; j += 2)
			{
				if (IsPrime(j) && (j - 1) % 101 != 0)
				{
					return j;
				}
			}
			return min;
		}

		public static int ExpandPrime(int oldSize)
		{
			int num = 2 * oldSize;
			if ((uint)num > 2147483587u && 2147483587 > oldSize)
			{
				return 2147483587;
			}
			return GetPrime(num);
		}

		public static ulong GetFastModMultiplier(uint divisor)
		{
			return ulong.MaxValue / (ulong)divisor + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint FastMod(uint value, uint divisor, ulong multiplier)
		{
			return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32);
		}
	}
	internal static class ThrowHelper
	{
		[DoesNotReturn]
		internal static void ThrowKeyNotFound<TKey>(TKey key)
		{
			throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key));
		}

		[DoesNotReturn]
		internal static void ThrowDuplicateKey<TKey>(TKey key)
		{
			throw new ArgumentException(System.SR.Format(System.SR.Argument_AddingDuplicate, key), "key");
		}

		[DoesNotReturn]
		internal static void ThrowConcurrentOperation()
		{
			throw new InvalidOperationException(System.SR.InvalidOperation_ConcurrentOperationsNotSupported);
		}

		[DoesNotReturn]
		internal static void ThrowIndexArgumentOutOfRange()
		{
			throw new ArgumentOutOfRangeException("index");
		}

		[DoesNotReturn]
		internal static void ThrowVersionCheckFailed()
		{
			throw new InvalidOperationException(System.SR.InvalidOperation_EnumFailedVersion);
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowNull(paramName);
			}
		}

		public static void ThrowIfNegative(int value, [CallerArgumentExpression("value")] string paramName = null)
		{
			if (value < 0)
			{
				ThrowNegative(value, paramName);
			}
		}

		public static void ThrowIfGreaterThan<T>(T value, T other, [CallerArgumentExpression("value")] string paramName = null) where T : IComparable<T>
		{
			if (value.CompareTo(other) > 0)
			{
				ThrowGreater(value, other, paramName);
			}
		}

		public static void ThrowIfLessThan<T>(T value, T other, [CallerArgumentExpression("value")] string paramName = null) where T : IComparable<T>
		{
			if (value.CompareTo(other) < 0)
			{
				ThrowLess(value, other, paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowNull(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[DoesNotReturn]
		private static void ThrowNegative(int value, string paramName)
		{
			throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeNonNegative, paramName, value));
		}

		[DoesNotReturn]
		private static void ThrowGreater<T>(T value, T other, string paramName)
		{
			throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeLessOrEqual, paramName, value, other));
		}

		[DoesNotReturn]
		private static void ThrowLess<T>(T value, T other, string paramName)
		{
			throw new ArgumentOutOfRangeException(paramName, value, System.SR.Format(System.SR.ArgumentOutOfRange_Generic_MustBeGreaterOrEqual, paramName, value, other));
		}
	}
}
namespace System.Collections.ObjectModel
{
	internal static class CollectionHelpers
	{
		internal static void ValidateCopyToArguments(int sourceCount, Array array, int index)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (array.Rank != 1)
			{
				throw new ArgumentException(System.SR.Arg_RankMultiDimNotSupported, "array");
			}
			if (array.GetLowerBound(0) != 0)
			{
				throw new ArgumentException(System.SR.Arg_NonZeroLowerBound, "array");
			}
			if (index < 0 || index > array.Length)
			{
				throw new ArgumentOutOfRangeException("index");
			}
			if (array.Length - index < sourceCount)
			{
				throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall);
			}
		}

		internal static void CopyTo<T>(ICollection<T> collection, Array array, int index)
		{
			ValidateCopyToArguments(collection.Count, array, index);
			if (collection is ICollection collection2)
			{
				collection2.CopyTo(array, index);
				return;
			}
			if (array is T[] array2)
			{
				collection.CopyTo(array2, index);
				return;
			}
			if (!(array is object[] array3))
			{
				throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array");
			}
			try
			{
				foreach (T item in collection)
				{
					array3[index++] = item;
				}
			}
			catch (ArrayTypeMismatchException)
			{
				throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array");
			}
		}
	}
}
namespace System.Collections.Generic
{
	internal sealed class ReferenceEqualityComparer : IEqualityComparer<object>, IEqualityComparer
	{
		public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer();


		private ReferenceEqualityComparer()
		{
		}

		public new bool Equals(object x, object y)
		{
			return x == y;
		}

		public int GetHashCode(object obj)
		{
			return RuntimeHelpers.GetHashCode(obj);
		}
	}
	[DebuggerDisplay("{Value}", Name = "[{Key}]")]
	internal readonly struct DebugViewDictionaryItem<TKey, TValue>
	{
		[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
		public TKey Key { get; }

		[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
		public TValue Value { get; }

		public DebugViewDictionaryItem(TKey key, TValue value)
		{
			Key = key;
			Value = value;
		}

		public DebugViewDictionaryItem(KeyValuePair<TKey, TValue> keyValue)
		{
			Key = keyValue.Key;
			Value = keyValue.Value;
		}
	}
	internal sealed class ICollectionDebugView<T>
	{
		private readonly ICollection<T> _collection;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items
		{
			get
			{
				T[] array = new T[_collection.Count];
				_collection.CopyTo(array, 0);
				return array;
			}
		}

		public ICollectionDebugView(ICollection<T> collection)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			_collection = collection;
		}
	}
	internal sealed class IDictionaryDebugView<TKey, TValue>
	{
		private readonly IDictionary<TKey, TValue> _dict;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public DebugViewDictionaryItem<TKey, TValue>[] Items
		{
			get
			{
				KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[_dict.Count];
				_dict.CopyTo(array, 0);
				DebugViewDictionaryItem<TKey, TValue>[] array2 = new DebugViewDictionaryItem<TKey, TValue>[array.Length];
				for (int i = 0; i < array2.Length; i++)
				{
					array2[i] = new DebugViewDictionaryItem<TKey, TValue>(array[i]);
				}
				return array2;
			}
		}

		public IDictionaryDebugView(IDictionary<TKey, TValue> dictionary)
		{
			_dict = dictionary ?? throw new ArgumentNullException("dictionary");
		}
	}
	internal sealed class DictionaryKeyCollectionDebugView<TKey, TValue>
	{
		private readonly ICollection<TKey> _collection;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public TKey[] Items
		{
			get
			{
				TKey[] array = new TKey[_collection.Count];
				_collection.CopyTo(array, 0);
				return array;
			}
		}

		public DictionaryKeyCollectionDebugView(ICollection<TKey> collection)
		{
			_collection = collection ?? throw new ArgumentNullException("collection");
		}
	}
	internal sealed class DictionaryValueCollectionDebugView<TKey, TValue>
	{
		private readonly ICollection<TValue> _collection;

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public TValue[] Items
		{
			get
			{
				TValue[] array = new TValue[_collection.Count];
				_collection.CopyTo(array, 0);
				return array;
			}
		}

		public DictionaryValueCollectionDebugView(ICollection<TValue> collection)
		{
			_collection = collection ?? throw new ArgumentNullException("collection");
		}
	}
	internal static class EnumerableHelpers
	{
		internal static void Reset<T>(ref T enumerator) where T : IEnumerator
		{
			enumerator.Reset();
		}

		internal static IEnumerator<T> GetEmptyEnumerator<T>()
		{
			return ((IEnumerable<T>)Array.Empty<T>()).GetEnumerator();
		}

		internal static T[] ToArray<T>(IEnumerable<T> source, out int length)
		{
			if (source is ICollection<T> collection)
			{
				int count = collection.Count;
				if (count != 0)
				{
					T[] array = new T[count];
					collection.CopyTo(array, 0);
					length = count;
					return array;
				}
			}
			else
			{
				using IEnumerator<T> enumerator = source.GetEnumerator();
				if (enumerator.MoveNext())
				{
					T[] array2 = new T[4]
					{
						enumerator.Current,
						default(T),
						default(T),
						default(T)
					};
					int num = 1;
					while (enumerator.MoveNext())
					{
						if (num == array2.Length)
						{
							int num2 = num << 1;
							if ((uint)num2 > 2147483591u)
							{
								num2 = ((2147483591 <= num) ? (num + 1) : 2147483591);
							}
							Array.Resize(ref array2, num2);
						}
						array2[num++] = enumerator.Current;
					}
					length = num;
					return array2;
				}
			}
			length = 0;
			return Array.Empty<T>();
		}
	}
	[DebuggerTypeProxy(typeof(System.Collections.Generic.IDictionaryDebugView<, >))]
	[DebuggerDisplay("Count = {Count}")]
	internal sealed class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IList<KeyValuePair<TKey, TValue>>, IReadOnlyList<KeyValuePair<TKey, TValue>>, IList
	{
		private struct Entry
		{
			public int Next;

			public uint HashCode;

			public TKey Key;

			public TValue Value;
		}

		[StructLayout(LayoutKind.Auto)]
		public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IEnumerator, IDisposable, IDictionaryEnumerator
		{
			private readonly OrderedDictionary<TKey, TValue> _dictionary;

			private readonly int _version;

			private readonly bool _useDictionaryEntry;

			private int _index;

			public KeyValuePair<TKey, TValue> Current { get; private set; }

			readonly object IEnumerator.Current
			{
				get
				{
					if (!_useDictionaryEntry)
					{
						return Current;
					}
					return new DictionaryEntry(Current.Key, Current.Value);
				}
			}

			readonly DictionaryEntry IDictionaryEnumerator.Entry => new DictionaryEntry(Current.Key, Current.Value);

			readonly object IDictionaryEnumerator.Key => Current.Key;

			readonly object IDictionaryEnumerator.Value => Current.Value;

			internal Enumerator(OrderedDictionary<TKey, TValue> dictionary, bool useDictionaryEntry)
			{
				_index = 0;
				_dictionary = dictionary;
				_version = _dictionary._version;
				_useDictionaryEntry = useDictionaryEntry;
			}

			public bool MoveNext()
			{
				OrderedDictionary<TKey, TValue> dictionary = _dictionary;
				if (_version != dictionary._version)
				{
					ThrowHelper.ThrowVersionCheckFailed();
				}
				if (_index < dictionary._count)
				{
					ref Entry reference = ref dictionary._entries[_index];
					Current = new KeyValuePair<TKey, TValue>(reference.Key, reference.Value);
					_index++;
					return true;
				}
				Current = default(KeyValuePair<TKey, TValue>);
				return false;
			}

			void IEnumerator.Reset()
			{
				if (_version != _dictionary._version)
				{
					ThrowHelper.ThrowVersionCheckFailed();
				}
				_index = 0;
				Current = default(KeyValuePair<TKey, TValue>);
			}

			readonly void IDisposable.Dispose()
			{
			}
		}

		[DebuggerTypeProxy(typeof(System.Collections.Generic.ICollectionDebugView<>))]
		[DebuggerDisplay("Count = {Count}")]
		public sealed class KeyCollection : IList<TKey>, ICollection<TKey>, IEnumerable<TKey>, IEnumerable, IReadOnlyList<TKey>, IReadOnlyCollection<TKey>, IList, ICollection
		{
			public struct Enumerator : IEnumerator<TKey>, IEnumerator, IDisposable
			{
				private OrderedDictionary<TKey, TValue>.Enumerator _enumerator;

				public TKey Current => _enumerator.Current.Key;

				object IEnumerator.Current => Current;

				internal Enumerator(OrderedDictionary<TKey, TValue> dictionary)
				{
					_enumerator = dictionary.GetEnumerator();
				}

				public bool MoveNext()
				{
					return _enumerator.MoveNext();
				}

				void IEnumerator.Reset()
				{
					System.Collections.Generic.EnumerableHelpers.Reset(ref _enumerator);
				}

				readonly void IDisposable.Dispose()
				{
				}
			}

			private readonly OrderedDictionary<TKey, TValue> _dictionary;

			public int Count => _dictionary.Count;

			bool ICollection<TKey>.IsReadOnly => true;

			bool IList.IsReadOnly => true;

			bool IList.IsFixedSize => false;

			bool ICollection.IsSynchronized => false;

			object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;

			TKey IList<TKey>.this[int index]
			{
				get
				{
					return _dictionary.GetAt(index).Key;
				}
				set
				{
					throw new NotSupportedException();
				}
			}

			object IList.this[int index]
			{
				get
				{
					return _dictionary.GetAt(index).Key;
				}
				set
				{
					throw new NotSupportedException();
				}
			}

			TKey IReadOnlyList<TKey>.this[int index] => _dictionary.GetAt(index).Key;

			internal KeyCollection(OrderedDictionary<TKey, TValue> dictionary)
			{
				_dictionary = dictionary;
			}

			public bool Contains(TKey key)
			{
				return _dictionary.ContainsKey(key);
			}

			bool IList.Contains(object value)
			{
				if (value is TKey key)
				{
					return Contains(key);
				}
				return false;
			}

			public void CopyTo(TKey[] array, int arrayIndex)
			{
				ThrowHelper.ThrowIfNull(array, "array");
				ThrowHelper.ThrowIfNegative(arrayIndex, "arrayIndex");
				OrderedDictionary<TKey, TValue> dictionary = _dictionary;
				int count = dictionary._count;
				if (array.Length - arrayIndex < count)
				{
					throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall, "array");
				}
				Entry[] entries = dictionary._entries;
				for (int i = 0; i < count; i++)
				{
					array[arrayIndex++] = entries[i].Key;
				}
			}

			void ICollection.CopyTo(Array array, int index)
			{
				ThrowHelper.ThrowIfNull(array, "array");
				if (array.Rank != 1)
				{
					throw new ArgumentException(System.SR.Arg_RankMultiDimNotSupported, "array");
				}
				if (array.GetLowerBound(0) != 0)
				{
					throw new ArgumentException(System.SR.Arg_NonZeroLowerBound, "array");
				}
				ThrowHelper.ThrowIfNegative(index, "index");
				if (array.Length - index < _dictionary.Count)
				{
					throw new ArgumentException(System.SR.Arg_ArrayPlusOffTooSmall);
				}
				if (array is TKey[] array2)
				{
					CopyTo(array2, index);
					return;
				}
				try
				{
					if (!(array is object[] array3))
					{
						throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array");
					}
					using Enumerator enumerator = GetEnumerator();
					while (enumerator.MoveNext())
					{
						TKey current = enumerator.Current;
						array3[index++] = current;
					}
				}
				catch (ArrayTypeMismatchException)
				{
					throw new ArgumentException(System.SR.Argument_IncompatibleArrayType, "array");
				}
			}

			public Enumerator GetEnumerator()
			{
				return new Enumerator(_dictionary);
			}

			IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
			{
				if (Count != 0)
				{
					return GetEnumerator();
				}
				return System.Collections.Generic.EnumerableHelpers.GetEmptyEnumerator<TKey>();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<TKey>)this).GetEnumerator();
			}

			int IList<TKey>.IndexOf(TKey item)
			{
				return _dictionary.IndexOf(item);
			}

			void ICollection<TKey>.Add(TKey item)
			{
				throw new NotSupportedException();
			}

			void ICollection<TKey>.Clear()
			{
				throw new NotSupportedException();
			}

			void IList<TKey>.Insert(int index, TKey item)
			{
				throw new NotSupp

System.Threading.Tasks.Extensions.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Threading.Tasks.Extensions")]
[assembly: AssemblyDescription("System.Threading.Tasks.Extensions")]
[assembly: AssemblyDefaultAlias("System.Threading.Tasks.Extensions")]
[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: AssemblyVersion("4.2.0.1")]
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
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		internal static void ThrowArgumentNullException(System.ExceptionArgument argument)
		{
			throw GetArgumentNullException(argument);
		}

		internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			throw GetArgumentOutOfRangeException(argument);
		}

		private static ArgumentNullException GetArgumentNullException(System.ExceptionArgument argument)
		{
			return new ArgumentNullException(GetArgumentName(argument));
		}

		private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			return new ArgumentOutOfRangeException(GetArgumentName(argument));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static string GetArgumentName(System.ExceptionArgument argument)
		{
			return argument.ToString();
		}
	}
	internal enum ExceptionArgument
	{
		task,
		source,
		state
	}
}
namespace System.Threading.Tasks
{
	[StructLayout(LayoutKind.Auto)]
	[AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))]
	public readonly struct ValueTask : IEquatable<ValueTask>
	{
		private sealed class ValueTaskSourceAsTask : TaskCompletionSource<bool>
		{
			private static readonly Action<object> s_completionAction = delegate(object state)
			{
				IValueTaskSource source;
				if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state);
					return;
				}
				valueTaskSourceAsTask._source = null;
				ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token);
				try
				{
					source.GetResult(valueTaskSourceAsTask._token);
					valueTaskSourceAsTask.TrySetResult(result: false);
				}
				catch (Exception exception)
				{
					if (status == ValueTaskSourceStatus.Canceled)
					{
						valueTaskSourceAsTask.TrySetCanceled();
					}
					else
					{
						valueTaskSourceAsTask.TrySetException(exception);
					}
				}
			};

			private IValueTaskSource _source;

			private readonly short _token;

			public ValueTaskSourceAsTask(IValueTaskSource source, short token)
			{
				_token = token;
				_source = source;
				source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None);
			}
		}

		private static readonly Task s_canceledTask = Task.Delay(-1, new CancellationToken(canceled: true));

		internal readonly object _obj;

		internal readonly short _token;

		internal readonly bool _continueOnCapturedContext;

		internal static Task CompletedTask { get; } = Task.Delay(0);


		public bool IsCompleted
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return true;
				}
				if (obj is Task task)
				{
					return task.IsCompleted;
				}
				return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending;
			}
		}

		public bool IsCompletedSuccessfully
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return true;
				}
				if (obj is Task task)
				{
					return task.Status == TaskStatus.RanToCompletion;
				}
				return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded;
			}
		}

		public bool IsFaulted
		{
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return false;
				}
				if (obj is Task task)
				{
					return task.IsFaulted;
				}
				return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted;
			}
		}

		public bool IsCanceled
		{
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return false;
				}
				if (obj is Task task)
				{
					return task.IsCanceled;
				}
				return Unsafe.As<IValueTaskSource>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(Task task)
		{
			if (task == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task);
			}
			_obj = task;
			_continueOnCapturedContext = true;
			_token = 0;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(IValueTaskSource source, short token)
		{
			if (source == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source);
			}
			_obj = source;
			_token = token;
			_continueOnCapturedContext = true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private ValueTask(object obj, short token, bool continueOnCapturedContext)
		{
			_obj = obj;
			_token = token;
			_continueOnCapturedContext = continueOnCapturedContext;
		}

		public override int GetHashCode()
		{
			return _obj?.GetHashCode() ?? 0;
		}

		public override bool Equals(object obj)
		{
			if (obj is ValueTask)
			{
				return Equals((ValueTask)obj);
			}
			return false;
		}

		public bool Equals(ValueTask other)
		{
			if (_obj == other._obj)
			{
				return _token == other._token;
			}
			return false;
		}

		public static bool operator ==(ValueTask left, ValueTask right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ValueTask left, ValueTask right)
		{
			return !left.Equals(right);
		}

		public Task AsTask()
		{
			object obj = _obj;
			object obj2;
			if (obj != null)
			{
				obj2 = obj as Task;
				if (obj2 == null)
				{
					return GetTaskForValueTaskSource(Unsafe.As<IValueTaskSource>(obj));
				}
			}
			else
			{
				obj2 = CompletedTask;
			}
			return (Task)obj2;
		}

		public ValueTask Preserve()
		{
			if (_obj != null)
			{
				return new ValueTask(AsTask());
			}
			return this;
		}

		private Task GetTaskForValueTaskSource(IValueTaskSource t)
		{
			ValueTaskSourceStatus status = t.GetStatus(_token);
			if (status != 0)
			{
				try
				{
					t.GetResult(_token);
					return CompletedTask;
				}
				catch (Exception exception)
				{
					if (status == ValueTaskSourceStatus.Canceled)
					{
						return s_canceledTask;
					}
					TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
					taskCompletionSource.TrySetException(exception);
					return taskCompletionSource.Task;
				}
			}
			ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token);
			return valueTaskSourceAsTask.Task;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[StackTraceHidden]
		internal void ThrowIfCompletedUnsuccessfully()
		{
			object obj = _obj;
			if (obj != null)
			{
				if (obj is Task task)
				{
					task.GetAwaiter().GetResult();
				}
				else
				{
					Unsafe.As<IValueTaskSource>(obj).GetResult(_token);
				}
			}
		}

		public ValueTaskAwaiter GetAwaiter()
		{
			return new ValueTaskAwaiter(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext)
		{
			return new ConfiguredValueTaskAwaitable(new ValueTask(_obj, _token, continueOnCapturedContext));
		}
	}
	[StructLayout(LayoutKind.Auto)]
	[AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))]
	public readonly struct ValueTask<TResult> : IEquatable<ValueTask<TResult>>
	{
		private sealed class ValueTaskSourceAsTask : TaskCompletionSource<TResult>
		{
			private static readonly Action<object> s_completionAction = delegate(object state)
			{
				IValueTaskSource<TResult> source;
				if (!(state is ValueTaskSourceAsTask valueTaskSourceAsTask) || (source = valueTaskSourceAsTask._source) == null)
				{
					System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state);
					return;
				}
				valueTaskSourceAsTask._source = null;
				ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token);
				try
				{
					valueTaskSourceAsTask.TrySetResult(source.GetResult(valueTaskSourceAsTask._token));
				}
				catch (Exception exception)
				{
					if (status == ValueTaskSourceStatus.Canceled)
					{
						valueTaskSourceAsTask.TrySetCanceled();
					}
					else
					{
						valueTaskSourceAsTask.TrySetException(exception);
					}
				}
			};

			private IValueTaskSource<TResult> _source;

			private readonly short _token;

			public ValueTaskSourceAsTask(IValueTaskSource<TResult> source, short token)
			{
				_source = source;
				_token = token;
				source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None);
			}
		}

		private static Task<TResult> s_canceledTask;

		internal readonly object _obj;

		internal readonly TResult _result;

		internal readonly short _token;

		internal readonly bool _continueOnCapturedContext;

		public bool IsCompleted
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return true;
				}
				if (obj is Task<TResult> task)
				{
					return task.IsCompleted;
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) != ValueTaskSourceStatus.Pending;
			}
		}

		public bool IsCompletedSuccessfully
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return true;
				}
				if (obj is Task<TResult> task)
				{
					return task.Status == TaskStatus.RanToCompletion;
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded;
			}
		}

		public bool IsFaulted
		{
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return false;
				}
				if (obj is Task<TResult> task)
				{
					return task.IsFaulted;
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted;
			}
		}

		public bool IsCanceled
		{
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return false;
				}
				if (obj is Task<TResult> task)
				{
					return task.IsCanceled;
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled;
			}
		}

		public TResult Result
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object obj = _obj;
				if (obj == null)
				{
					return _result;
				}
				if (obj is Task<TResult> task)
				{
					return task.GetAwaiter().GetResult();
				}
				return Unsafe.As<IValueTaskSource<TResult>>(obj).GetResult(_token);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(TResult result)
		{
			_result = result;
			_obj = null;
			_continueOnCapturedContext = true;
			_token = 0;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(Task<TResult> task)
		{
			if (task == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.task);
			}
			_obj = task;
			_result = default(TResult);
			_continueOnCapturedContext = true;
			_token = 0;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTask(IValueTaskSource<TResult> source, short token)
		{
			if (source == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.source);
			}
			_obj = source;
			_token = token;
			_result = default(TResult);
			_continueOnCapturedContext = true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private ValueTask(object obj, TResult result, short token, bool continueOnCapturedContext)
		{
			_obj = obj;
			_result = result;
			_token = token;
			_continueOnCapturedContext = continueOnCapturedContext;
		}

		public override int GetHashCode()
		{
			if (_obj == null)
			{
				if (_result == null)
				{
					return 0;
				}
				return _result.GetHashCode();
			}
			return _obj.GetHashCode();
		}

		public override bool Equals(object obj)
		{
			if (obj is ValueTask<TResult>)
			{
				return Equals((ValueTask<TResult>)obj);
			}
			return false;
		}

		public bool Equals(ValueTask<TResult> other)
		{
			if (_obj == null && other._obj == null)
			{
				return EqualityComparer<TResult>.Default.Equals(_result, other._result);
			}
			if (_obj == other._obj)
			{
				return _token == other._token;
			}
			return false;
		}

		public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right)
		{
			return !left.Equals(right);
		}

		public Task<TResult> AsTask()
		{
			object obj = _obj;
			if (obj == null)
			{
				return Task.FromResult(_result);
			}
			if (obj is Task<TResult> result)
			{
				return result;
			}
			return GetTaskForValueTaskSource(Unsafe.As<IValueTaskSource<TResult>>(obj));
		}

		public ValueTask<TResult> Preserve()
		{
			if (_obj != null)
			{
				return new ValueTask<TResult>(AsTask());
			}
			return this;
		}

		private Task<TResult> GetTaskForValueTaskSource(IValueTaskSource<TResult> t)
		{
			ValueTaskSourceStatus status = t.GetStatus(_token);
			if (status != 0)
			{
				try
				{
					return Task.FromResult(t.GetResult(_token));
				}
				catch (Exception exception)
				{
					if (status == ValueTaskSourceStatus.Canceled)
					{
						Task<TResult> task = s_canceledTask;
						if (task == null)
						{
							TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>();
							taskCompletionSource.TrySetCanceled();
							task = (s_canceledTask = taskCompletionSource.Task);
						}
						return task;
					}
					TaskCompletionSource<TResult> taskCompletionSource2 = new TaskCompletionSource<TResult>();
					taskCompletionSource2.TrySetException(exception);
					return taskCompletionSource2.Task;
				}
			}
			ValueTaskSourceAsTask valueTaskSourceAsTask = new ValueTaskSourceAsTask(t, _token);
			return valueTaskSourceAsTask.Task;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ValueTaskAwaiter<TResult> GetAwaiter()
		{
			return new ValueTaskAwaiter<TResult>(this);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext)
		{
			return new ConfiguredValueTaskAwaitable<TResult>(new ValueTask<TResult>(_obj, _result, _token, continueOnCapturedContext));
		}

		public override string ToString()
		{
			if (IsCompletedSuccessfully)
			{
				TResult result = Result;
				if (result != null)
				{
					return result.ToString();
				}
			}
			return string.Empty;
		}
	}
}
namespace System.Threading.Tasks.Sources
{
	[Flags]
	public enum ValueTaskSourceOnCompletedFlags
	{
		None = 0,
		UseSchedulingContext = 1,
		FlowExecutionContext = 2
	}
	public enum ValueTaskSourceStatus
	{
		Pending,
		Succeeded,
		Faulted,
		Canceled
	}
	public interface IValueTaskSource
	{
		ValueTaskSourceStatus GetStatus(short token);

		void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags);

		void GetResult(short token);
	}
	public interface IValueTaskSource<out TResult>
	{
		ValueTaskSourceStatus GetStatus(short token);

		void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags);

		TResult GetResult(short token);
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)]
	public sealed class AsyncMethodBuilderAttribute : Attribute
	{
		public Type BuilderType { get; }

		public AsyncMethodBuilderAttribute(Type builderType)
		{
			BuilderType = builderType;
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public struct AsyncValueTaskMethodBuilder
	{
		private AsyncTaskMethodBuilder _methodBuilder;

		private bool _haveResult;

		private bool _useBuilder;

		public ValueTask Task
		{
			get
			{
				if (_haveResult)
				{
					return default(ValueTask);
				}
				_useBuilder = true;
				return new ValueTask(_methodBuilder.Task);
			}
		}

		public static AsyncValueTaskMethodBuilder Create()
		{
			return default(AsyncValueTaskMethodBuilder);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
		{
			_methodBuilder.Start(ref stateMachine);
		}

		public void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			_methodBuilder.SetStateMachine(stateMachine);
		}

		public void SetResult()
		{
			if (_useBuilder)
			{
				_methodBuilder.SetResult();
			}
			else
			{
				_haveResult = true;
			}
		}

		public void SetException(Exception exception)
		{
			_methodBuilder.SetException(exception);
		}

		public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_useBuilder = true;
			_methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine);
		}

		[SecuritySafeCritical]
		public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_useBuilder = true;
			_methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public struct AsyncValueTaskMethodBuilder<TResult>
	{
		private AsyncTaskMethodBuilder<TResult> _methodBuilder;

		private TResult _result;

		private bool _haveResult;

		private bool _useBuilder;

		public ValueTask<TResult> Task
		{
			get
			{
				if (_haveResult)
				{
					return new ValueTask<TResult>(_result);
				}
				_useBuilder = true;
				return new ValueTask<TResult>(_methodBuilder.Task);
			}
		}

		public static AsyncValueTaskMethodBuilder<TResult> Create()
		{
			return default(AsyncValueTaskMethodBuilder<TResult>);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
		{
			_methodBuilder.Start(ref stateMachine);
		}

		public void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			_methodBuilder.SetStateMachine(stateMachine);
		}

		public void SetResult(TResult result)
		{
			if (_useBuilder)
			{
				_methodBuilder.SetResult(result);
				return;
			}
			_result = result;
			_haveResult = true;
		}

		public void SetException(Exception exception)
		{
			_methodBuilder.SetException(exception);
		}

		public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_useBuilder = true;
			_methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine);
		}

		[SecuritySafeCritical]
		public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_useBuilder = true;
			_methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly struct ConfiguredValueTaskAwaitable
	{
		[StructLayout(LayoutKind.Auto)]
		public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion
		{
			private readonly ValueTask _value;

			public bool IsCompleted
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return _value.IsCompleted;
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal ConfiguredValueTaskAwaiter(ValueTask value)
			{
				_value = value;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			[StackTraceHidden]
			public void GetResult()
			{
				_value.ThrowIfCompletedUnsuccessfully();
			}

			public void OnCompleted(Action continuation)
			{
				object obj = _value._obj;
				if (obj is Task task)
				{
					task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
				}
				else if (obj != null)
				{
					Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None));
				}
				else
				{
					ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
				}
			}

			public void UnsafeOnCompleted(Action continuation)
			{
				object obj = _value._obj;
				if (obj is Task task)
				{
					task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
				}
				else if (obj != null)
				{
					Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
				}
				else
				{
					ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
				}
			}
		}

		private readonly ValueTask _value;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ConfiguredValueTaskAwaitable(ValueTask value)
		{
			_value = value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ConfiguredValueTaskAwaiter GetAwaiter()
		{
			return new ConfiguredValueTaskAwaiter(_value);
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly struct ConfiguredValueTaskAwaitable<TResult>
	{
		[StructLayout(LayoutKind.Auto)]
		public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion
		{
			private readonly ValueTask<TResult> _value;

			public bool IsCompleted
			{
				[MethodImpl(MethodImplOptions.AggressiveInlining)]
				get
				{
					return _value.IsCompleted;
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			internal ConfiguredValueTaskAwaiter(ValueTask<TResult> value)
			{
				_value = value;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			[StackTraceHidden]
			public TResult GetResult()
			{
				return _value.Result;
			}

			public void OnCompleted(Action continuation)
			{
				object obj = _value._obj;
				if (obj is Task<TResult> task)
				{
					task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
				}
				else if (obj != null)
				{
					Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None));
				}
				else
				{
					ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
				}
			}

			public void UnsafeOnCompleted(Action continuation)
			{
				object obj = _value._obj;
				if (obj is Task<TResult> task)
				{
					task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
				}
				else if (obj != null)
				{
					Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None);
				}
				else
				{
					ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
				}
			}
		}

		private readonly ValueTask<TResult> _value;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ConfiguredValueTaskAwaitable(ValueTask<TResult> value)
		{
			_value = value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public ConfiguredValueTaskAwaiter GetAwaiter()
		{
			return new ConfiguredValueTaskAwaiter(_value);
		}
	}
	public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion
	{
		internal static readonly Action<object> s_invokeActionDelegate = delegate(object state)
		{
			if (!(state is Action action))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.state);
			}
			else
			{
				action();
			}
		};

		private readonly ValueTask _value;

		public bool IsCompleted
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return _value.IsCompleted;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ValueTaskAwaiter(ValueTask value)
		{
			_value = value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[StackTraceHidden]
		public void GetResult()
		{
			_value.ThrowIfCompletedUnsuccessfully();
		}

		public void OnCompleted(Action continuation)
		{
			object obj = _value._obj;
			if (obj is Task task)
			{
				task.GetAwaiter().OnCompleted(continuation);
			}
			else if (obj != null)
			{
				Unsafe.As<IValueTaskSource>(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext);
			}
			else
			{
				ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation);
			}
		}

		public void UnsafeOnCompleted(Action continuation)
		{
			object obj = _value._obj;
			if (obj is Task task)
			{
				task.GetAwaiter().UnsafeOnCompleted(continuation);
			}
			else if (obj != null)
			{
				Unsafe.As<IValueTaskSource>(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext);
			}
			else
			{
				ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation);
			}
		}
	}
	public readonly struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion, INotifyCompletion
	{
		private readonly ValueTask<TResult> _value;

		public bool IsCompleted
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return _value.IsCompleted;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ValueTaskAwaiter(ValueTask<TResult> value)
		{
			_value = value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[StackTraceHidden]
		public TResult GetResult()
		{
			return _value.Result;
		}

		public void OnCompleted(Action continuation)
		{
			object obj = _value._obj;
			if (obj is Task<TResult> task)
			{
				task.GetAwaiter().OnCompleted(continuation);
			}
			else if (obj != null)
			{
				Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext);
			}
			else
			{
				ValueTask.CompletedTask.GetAwaiter().OnCompleted(continuation);
			}
		}

		public void UnsafeOnCompleted(Action continuation)
		{
			object obj = _value._obj;
			if (obj is Task<TResult> task)
			{
				task.GetAwaiter().UnsafeOnCompleted(continuation);
			}
			else if (obj != null)
			{
				Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext);
			}
			else
			{
				ValueTask.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation);
			}
		}
	}
	[AttributeUsage(AttributeTargets.All)]
	internal class __BlockReflectionAttribute : Attribute
	{
	}
}
namespace System.Diagnostics
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class StackTraceHiddenAttribute : Attribute
	{
	}
}

Magick.NET-Q8-x64.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
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 ImageMagick.Configuration;
using ImageMagick.Drawing;
using ImageMagick.ImageOptimizers;
using ImageMagick.SourceGenerator;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MagickVersion]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: AssemblyTrademark("ImageMagick 7.1.1.44")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Dirk Lemstra")]
[assembly: AssemblyConfiguration("ReleaseQ8")]
[assembly: AssemblyCopyright("Copyright 2013-2025 Dirk Lemstra")]
[assembly: AssemblyFileVersion("14.5.0")]
[assembly: AssemblyInformationalVersion("14.5.0+0e6c26312fcd82ede604119187c3e1be1612e9c7")]
[assembly: AssemblyProduct("Magick.NET-Q8-x64")]
[assembly: AssemblyTitle("Magick.NET Q8 x64 netstandard20")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("14.5.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
}
namespace ImageMagick
{
	internal static class HexColor
	{
		public static bool TryParse(string value, out List<byte> channels)
		{
			channels = new List<byte>();
			if (value.Length < 13)
			{
				return TryParseQ8(value, channels);
			}
			return TryParseQ16(value, channels);
		}

		private static bool TryParseQ8(string value, List<byte> channels)
		{
			int num;
			if (value.Length == 4 || value.Length == 5)
			{
				num = 1;
			}
			else
			{
				if (value.Length != 3 && value.Length != 7 && value.Length != 9)
				{
					return false;
				}
				num = 2;
			}
			for (int i = 1; i < value.Length; i += num)
			{
				if (!TryParseHex(value, i, num, out var channel))
				{
					return false;
				}
				channels.Add(Quantum.Convert((byte)channel));
			}
			return true;
		}

		private static bool TryParseQ16(string value, List<byte> channels)
		{
			if (value.Length != 13 && value.Length != 17)
			{
				return false;
			}
			for (int i = 1; i < value.Length; i += 4)
			{
				if (!TryParseHex(value, i, 4, out var channel))
				{
					return false;
				}
				channels.Add(Quantum.Convert(channel));
			}
			return true;
		}

		private static bool TryParseHex(string color, int offset, int length, out ushort channel)
		{
			channel = 0;
			ushort num = 1;
			int num2 = length - 1;
			while (num2 >= 0)
			{
				char c = color[offset + num2];
				if (c >= '0' && c <= '9')
				{
					channel += (ushort)(num * (c - 48));
				}
				else if (c >= 'a' && c <= 'f')
				{
					channel += (ushort)(num * (c - 97 + 10));
				}
				else
				{
					if (c < 'A' || c > 'F')
					{
						return false;
					}
					channel += (ushort)(num * (c - 65 + 10));
				}
				num2--;
				num *= 16;
			}
			if (length == 1)
			{
				channel += (byte)(channel * 16);
			}
			return true;
		}
	}
	public sealed class MagickColor : IMagickColor<byte>, IEquatable<IMagickColor<byte>?>, IComparable<IMagickColor<byte>?>
	{
		[NativeInterop(QuantumType = true, ManagedToNative = true)]
		private sealed class NativeMagickColor : NativeInstance
		{
			protected override string TypeName => "MagickColor";

			public static NativeMagickColor Create()
			{
				IntPtr intPtr = NativeMethods.MagickColor_Create();
				if (intPtr == IntPtr.Zero)
				{
					throw new InvalidOperationException();
				}
				return new NativeMagickColor(intPtr);
			}

			public nuint Count_Get()
			{
				return NativeMethods.MagickColor_Count_Get(base.Instance);
			}

			public byte Red_Get()
			{
				return NativeMethods.MagickColor_Red_Get(base.Instance);
			}

			public void Red_Set(byte value)
			{
				NativeMethods.MagickColor_Red_Set(base.Instance, value);
			}

			public byte Green_Get()
			{
				return NativeMethods.MagickColor_Green_Get(base.Instance);
			}

			public void Green_Set(byte value)
			{
				NativeMethods.MagickColor_Green_Set(base.Instance, value);
			}

			public byte Blue_Get()
			{
				return NativeMethods.MagickColor_Blue_Get(base.Instance);
			}

			public void Blue_Set(byte value)
			{
				NativeMethods.MagickColor_Blue_Set(base.Instance, value);
			}

			public byte Alpha_Get()
			{
				return NativeMethods.MagickColor_Alpha_Get(base.Instance);
			}

			public void Alpha_Set(byte value)
			{
				NativeMethods.MagickColor_Alpha_Set(base.Instance, value);
			}

			public byte Black_Get()
			{
				return NativeMethods.MagickColor_Black_Get(base.Instance);
			}

			public void Black_Set(byte value)
			{
				NativeMethods.MagickColor_Black_Set(base.Instance, value);
			}

			public bool IsCMYK_Get()
			{
				return NativeMethods.MagickColor_IsCMYK_Get(base.Instance);
			}

			public void IsCMYK_Set(bool value)
			{
				NativeMethods.MagickColor_IsCMYK_Set(base.Instance, value);
			}

			public bool FuzzyEquals(IMagickColor<byte>? other, byte fuzz)
			{
				using INativeInstance nativeInstance = CreateInstance(other);
				return NativeMethods.MagickColor_FuzzyEquals(base.Instance, nativeInstance.Instance, fuzz);
			}

			public bool Initialize(string? value)
			{
				using UTF8Marshaler uTF8Marshaler = UTF8Marshaler.CreateInstance(value);
				return NativeMethods.MagickColor_Initialize(base.Instance, uTF8Marshaler.Instance);
			}

			static NativeMagickColor()
			{
				Environment.Initialize();
			}

			public NativeMagickColor(IntPtr instance)
			{
				base.Instance = instance;
			}

			protected override void Dispose(IntPtr instance)
			{
				NativeMethods.MagickColor_Dispose(instance);
			}
		}

		private static class NativeMethods
		{
			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickColor_Dispose(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickColor_Create();

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern nuint MagickColor_Count_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern byte MagickColor_Red_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickColor_Red_Set(IntPtr instance, byte value);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern byte MagickColor_Green_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickColor_Green_Set(IntPtr instance, byte value);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern byte MagickColor_Blue_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickColor_Blue_Set(IntPtr instance, byte value);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern byte MagickColor_Alpha_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickColor_Alpha_Set(IntPtr instance, byte value);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern byte MagickColor_Black_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickColor_Black_Set(IntPtr instance, byte value);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickColor_IsCMYK_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickColor_IsCMYK_Set(IntPtr instance, bool value);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickColor_FuzzyEquals(IntPtr instance, IntPtr other, byte fuzz);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickColor_Initialize(IntPtr instance, IntPtr value);
		}

		public byte A { get; set; }

		public byte B { get; set; }

		public byte G { get; set; }

		public bool IsCmyk { get; private set; }

		public byte K { get; set; }

		public byte R { get; set; }

		public MagickColor()
		{
		}

		public MagickColor(IMagickColor<byte> color)
		{
			Throw.IfNull(color, "color");
			R = color.R;
			G = color.G;
			B = color.B;
			A = color.A;
			K = color.K;
			IsCmyk = color.IsCmyk;
		}

		public MagickColor(byte red, byte green, byte blue)
		{
			Initialize(red, green, blue, Quantum.Max);
		}

		public MagickColor(byte red, byte green, byte blue, byte alpha)
		{
			Initialize(red, green, blue, alpha);
		}

		public MagickColor(byte cyan, byte magenta, byte yellow, byte black, byte alpha)
		{
			Initialize(cyan, magenta, yellow, alpha);
			K = black;
			IsCmyk = true;
		}

		public MagickColor(string color)
		{
			Throw.IfNullOrEmpty(color, "color");
			if (color.Equals("transparent", StringComparison.OrdinalIgnoreCase))
			{
				Initialize(Quantum.Max, Quantum.Max, Quantum.Max, 0);
				return;
			}
			if (color[0] == '#')
			{
				ParseHexColor(color);
				return;
			}
			using NativeMagickColor nativeMagickColor = NativeMagickColor.Create();
			Throw.IfFalse(nativeMagickColor.Initialize(color), "color", "Invalid color specified");
			Initialize(nativeMagickColor);
		}

		private MagickColor(NativeMagickColor nativeInstance)
		{
			Initialize(nativeInstance);
		}

		public static bool operator ==(MagickColor? left, MagickColor? right)
		{
			return object.Equals(left, right);
		}

		public static bool operator !=(MagickColor? left, MagickColor? right)
		{
			return !object.Equals(left, right);
		}

		public static bool operator >(MagickColor? left, MagickColor? right)
		{
			if ((object)left == null)
			{
				return (object)right == null;
			}
			return left.CompareTo((IMagickColor<byte>?)(object)right) == 1;
		}

		public static bool operator <(MagickColor? left, MagickColor? right)
		{
			if ((object)left == null)
			{
				return (object)right != null;
			}
			return left.CompareTo((IMagickColor<byte>?)(object)right) == -1;
		}

		public static bool operator >=(MagickColor? left, MagickColor? right)
		{
			if ((object)left == null)
			{
				return (object)right == null;
			}
			return left.CompareTo((IMagickColor<byte>?)(object)right) >= 0;
		}

		public static bool operator <=(MagickColor? left, MagickColor? right)
		{
			if ((object)left == null)
			{
				return (object)right != null;
			}
			return left.CompareTo((IMagickColor<byte>?)(object)right) <= 0;
		}

		public static MagickColor?operator *(MagickColor? color, Percentage percentage)
		{
			if ((object)color == null)
			{
				return null;
			}
			byte b = Quantum.Convert(((Percentage)(ref percentage)).Multiply((double)(int)color.R));
			byte b2 = Quantum.Convert(((Percentage)(ref percentage)).Multiply((double)(int)color.G));
			byte b3 = Quantum.Convert(((Percentage)(ref percentage)).Multiply((double)(int)color.B));
			if (!color.IsCmyk)
			{
				return new MagickColor(b, b2, b3, color.A);
			}
			byte black = Quantum.Convert(((Percentage)(ref percentage)).Multiply((double)(int)color.K));
			return new MagickColor(b, b2, b3, black, color.A);
		}

		public static MagickColor FromRgb(byte red, byte green, byte blue)
		{
			MagickColor magickColor = new MagickColor();
			magickColor.SetFromBytes(red, green, blue, byte.MaxValue);
			return magickColor;
		}

		public static MagickColor FromRgba(byte red, byte green, byte blue, byte alpha)
		{
			MagickColor magickColor = new MagickColor();
			magickColor.SetFromBytes(red, green, blue, alpha);
			return magickColor;
		}

		public int CompareTo(IMagickColor<byte>? other)
		{
			if (other == null)
			{
				return 1;
			}
			if (R < other.R)
			{
				return -1;
			}
			if (R > other.R)
			{
				return 1;
			}
			if (G < other.G)
			{
				return -1;
			}
			if (G > other.G)
			{
				return 1;
			}
			if (B < other.B)
			{
				return -1;
			}
			if (B > other.B)
			{
				return 1;
			}
			if (K < other.K)
			{
				return -1;
			}
			if (K > other.K)
			{
				return 1;
			}
			if (A < other.A)
			{
				return -1;
			}
			if (A > other.A)
			{
				return 1;
			}
			return 0;
		}

		public override bool Equals(object? obj)
		{
			return Equals(obj as IMagickColor<byte>);
		}

		public bool Equals(IMagickColor<byte>? other)
		{
			if (other == null)
			{
				return false;
			}
			if (this == other)
			{
				return true;
			}
			if (IsCmyk == other.IsCmyk && A == other.A && B == other.B && G == other.G && R == other.R)
			{
				return K == other.K;
			}
			return false;
		}

		public bool FuzzyEquals(IMagickColor<byte> other, Percentage fuzz)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (other == null)
			{
				return false;
			}
			if (this == other)
			{
				return true;
			}
			using NativeMagickColor nativeMagickColor = CreateNativeInstance((IMagickColor<byte>)(object)this);
			return nativeMagickColor.FuzzyEquals(other, PercentageHelper.ToQuantumType("fuzz", fuzz));
		}

		public override int GetHashCode()
		{
			return IsCmyk.GetHashCode() ^ A.GetHashCode() ^ B.GetHashCode() ^ G.GetHashCode() ^ K.GetHashCode() ^ R.GetHashCode();
		}

		public void SetFromBytes(byte red, byte green, byte blue, byte alpha)
		{
			R = Quantum.Convert(red);
			G = Quantum.Convert(green);
			B = Quantum.Convert(blue);
			A = Quantum.Convert(alpha);
			K = 0;
			IsCmyk = false;
		}

		public byte[] ToByteArray()
		{
			if (!IsCmyk)
			{
				return new byte[4]
				{
					Quantum.ScaleToByte(R),
					Quantum.ScaleToByte(G),
					Quantum.ScaleToByte(B),
					Quantum.ScaleToByte(A)
				};
			}
			return new byte[5]
			{
				Quantum.ScaleToByte(R),
				Quantum.ScaleToByte(G),
				Quantum.ScaleToByte(B),
				Quantum.ScaleToByte(K),
				Quantum.ScaleToByte(A)
			};
		}

		public string ToHexString()
		{
			if (IsCmyk)
			{
				throw new NotSupportedException("This method only works for non cmyk colors.");
			}
			byte b = Quantum.ScaleToByte(R);
			byte b2 = Quantum.ScaleToByte(G);
			byte b3 = Quantum.ScaleToByte(B);
			if (A == Quantum.Max)
			{
				return string.Format(CultureInfo.InvariantCulture, "#{0:X2}{1:X2}{2:X2}", b, b2, b3);
			}
			byte b4 = Quantum.ScaleToByte(A);
			return string.Format(CultureInfo.InvariantCulture, "#{0:X2}{1:X2}{2:X2}{3:X2}", b, b2, b3, b4);
		}

		public string ToShortString()
		{
			if (A != Quantum.Max)
			{
				return ToString();
			}
			if (IsCmyk)
			{
				byte b = Quantum.ScaleToByte(R);
				byte b2 = Quantum.ScaleToByte(G);
				byte b3 = Quantum.ScaleToByte(B);
				byte b4 = Quantum.ScaleToByte(K);
				return string.Format(CultureInfo.InvariantCulture, "cmyk({0},{1},{2},{3})", b, b2, b3, b4);
			}
			return string.Format(CultureInfo.InvariantCulture, "#{0:X2}{1:X2}{2:X2}", R, G, B);
		}

		public override string ToString()
		{
			if (IsCmyk)
			{
				byte b = Quantum.ScaleToByte(R);
				byte b2 = Quantum.ScaleToByte(G);
				byte b3 = Quantum.ScaleToByte(B);
				byte b4 = Quantum.ScaleToByte(K);
				return string.Format(CultureInfo.InvariantCulture, "cmyka({0},{1},{2},{3},{4:0.0###})", b, b2, b3, b4, (double)(int)A / (double)(int)Quantum.Max);
			}
			return string.Format(CultureInfo.InvariantCulture, "#{0:X2}{1:X2}{2:X2}{3:X2}", R, G, B, A);
		}

		internal static IMagickColor<byte>? Clone(IMagickColor<byte>? value)
		{
			if (value == null)
			{
				return value;
			}
			return (IMagickColor<byte>?)(object)new MagickColor
			{
				R = value.R,
				G = value.G,
				B = value.B,
				A = value.A,
				K = value.K,
				IsCmyk = value.IsCmyk
			};
		}

		private void Initialize(byte red, byte green, byte blue, byte alpha)
		{
			R = red;
			G = green;
			B = blue;
			A = alpha;
			K = 0;
			IsCmyk = false;
		}

		private void ParseHexColor(string color)
		{
			if (!HexColor.TryParse(color, out List<byte> channels))
			{
				throw new ArgumentException("Invalid hex value.", "color");
			}
			if (channels.Count == 1)
			{
				Initialize(channels[0], channels[0], channels[0], Quantum.Max);
			}
			else if (channels.Count == 3)
			{
				Initialize(channels[0], channels[1], channels[2], Quantum.Max);
			}
			else
			{
				Initialize(channels[0], channels[1], channels[2], channels[3]);
			}
		}

		internal static MagickColor? CreateInstance(IntPtr instance)
		{
			if (instance == IntPtr.Zero)
			{
				return null;
			}
			using NativeMagickColor nativeInstance = new NativeMagickColor(instance);
			return new MagickColor(nativeInstance);
		}

		internal static MagickColor? CreateInstance(IntPtr instance, out uint count)
		{
			count = 0u;
			if (instance == IntPtr.Zero)
			{
				return null;
			}
			using NativeMagickColor nativeMagickColor = new NativeMagickColor(instance);
			count = (uint)nativeMagickColor.Count_Get();
			return new MagickColor(nativeMagickColor);
		}

		private static NativeMagickColor CreateNativeInstance(IMagickColor<byte> instance)
		{
			NativeMagickColor nativeMagickColor = NativeMagickColor.Create();
			nativeMagickColor.Red_Set(instance.R);
			nativeMagickColor.Green_Set(instance.G);
			nativeMagickColor.Blue_Set(instance.B);
			nativeMagickColor.Alpha_Set(instance.A);
			nativeMagickColor.Black_Set(instance.K);
			nativeMagickColor.IsCMYK_Set(instance.IsCmyk);
			return nativeMagickColor;
		}

		private void Initialize(NativeMagickColor instance)
		{
			R = instance.Red_Get();
			G = instance.Green_Get();
			B = instance.Blue_Get();
			A = instance.Alpha_Get();
			K = instance.Black_Get();
			IsCmyk = instance.IsCMYK_Get();
		}

		internal static INativeInstance CreateInstance(IMagickColor<byte>? instance)
		{
			if (instance == null)
			{
				return NativeInstance.Zero;
			}
			return CreateNativeInstance(instance);
		}
	}
	internal static class MagickColorCollection
	{
		[NativeInterop]
		private static class NativeMagickColorCollection
		{
			public static void DisposeList(IntPtr list)
			{
				NativeMethods.MagickColorCollection_DisposeList(list);
			}

			public static IntPtr GetInstance(IntPtr list, nuint index)
			{
				return NativeMethods.MagickColorCollection_GetInstance(list, index);
			}

			static NativeMagickColorCollection()
			{
				Environment.Initialize();
			}
		}

		private static class NativeMethods
		{
			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickColorCollection_DisposeList(IntPtr list);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickColorCollection_GetInstance(IntPtr list, nuint index);
		}

		public static void DisposeList(IntPtr list)
		{
			if (list != IntPtr.Zero)
			{
				NativeMagickColorCollection.DisposeList(list);
			}
		}

		public static IReadOnlyDictionary<IMagickColor<byte>, uint> ToDictionary(IntPtr list, uint length)
		{
			Dictionary<IMagickColor<byte>, uint> dictionary = new Dictionary<IMagickColor<byte>, uint>((int)length);
			if (list == IntPtr.Zero)
			{
				return dictionary;
			}
			for (uint num = 0u; num < length; num++)
			{
				uint count;
				MagickColor magickColor = MagickColor.CreateInstance(NativeMagickColorCollection.GetInstance(list, num), out count);
				if ((object)magickColor != null)
				{
					dictionary.Add(magickColor, count);
				}
			}
			return dictionary;
		}
	}
	public class MagickColors : IMagickColors<byte>
	{
		public static MagickColor None => MagickColor.FromRgba(0, 0, 0, 0);

		public static MagickColor Transparent => MagickColor.FromRgba(0, 0, 0, 0);

		public static MagickColor AliceBlue => MagickColor.FromRgba(240, 248, byte.MaxValue, byte.MaxValue);

		public static MagickColor AntiqueWhite => MagickColor.FromRgba(250, 235, 215, byte.MaxValue);

		public static MagickColor Aqua => MagickColor.FromRgba(0, byte.MaxValue, byte.MaxValue, byte.MaxValue);

		public static MagickColor Aquamarine => MagickColor.FromRgba(127, byte.MaxValue, 212, byte.MaxValue);

		public static MagickColor Azure => MagickColor.FromRgba(240, byte.MaxValue, byte.MaxValue, byte.MaxValue);

		public static MagickColor Beige => MagickColor.FromRgba(245, 245, 220, byte.MaxValue);

		public static MagickColor Bisque => MagickColor.FromRgba(byte.MaxValue, 228, 196, byte.MaxValue);

		public static MagickColor Black => MagickColor.FromRgba(0, 0, 0, byte.MaxValue);

		public static MagickColor BlanchedAlmond => MagickColor.FromRgba(byte.MaxValue, 235, 205, byte.MaxValue);

		public static MagickColor Blue => MagickColor.FromRgba(0, 0, byte.MaxValue, byte.MaxValue);

		public static MagickColor BlueViolet => MagickColor.FromRgba(138, 43, 226, byte.MaxValue);

		public static MagickColor Brown => MagickColor.FromRgba(165, 42, 42, byte.MaxValue);

		public static MagickColor BurlyWood => MagickColor.FromRgba(222, 184, 135, byte.MaxValue);

		public static MagickColor CadetBlue => MagickColor.FromRgba(95, 158, 160, byte.MaxValue);

		public static MagickColor Chartreuse => MagickColor.FromRgba(127, byte.MaxValue, 0, byte.MaxValue);

		public static MagickColor Chocolate => MagickColor.FromRgba(210, 105, 30, byte.MaxValue);

		public static MagickColor Coral => MagickColor.FromRgba(byte.MaxValue, 127, 80, byte.MaxValue);

		public static MagickColor CornflowerBlue => MagickColor.FromRgba(100, 149, 237, byte.MaxValue);

		public static MagickColor Cornsilk => MagickColor.FromRgba(byte.MaxValue, 248, 220, byte.MaxValue);

		public static MagickColor Crimson => MagickColor.FromRgba(220, 20, 60, byte.MaxValue);

		public static MagickColor Cyan => MagickColor.FromRgba(0, byte.MaxValue, byte.MaxValue, byte.MaxValue);

		public static MagickColor DarkBlue => MagickColor.FromRgba(0, 0, 139, byte.MaxValue);

		public static MagickColor DarkCyan => MagickColor.FromRgba(0, 139, 139, byte.MaxValue);

		public static MagickColor DarkGoldenrod => MagickColor.FromRgba(184, 134, 11, byte.MaxValue);

		public static MagickColor DarkGray => MagickColor.FromRgba(169, 169, 169, byte.MaxValue);

		public static MagickColor DarkGreen => MagickColor.FromRgba(0, 100, 0, byte.MaxValue);

		public static MagickColor DarkKhaki => MagickColor.FromRgba(189, 183, 107, byte.MaxValue);

		public static MagickColor DarkMagenta => MagickColor.FromRgba(139, 0, 139, byte.MaxValue);

		public static MagickColor DarkOliveGreen => MagickColor.FromRgba(85, 107, 47, byte.MaxValue);

		public static MagickColor DarkOrange => MagickColor.FromRgba(byte.MaxValue, 140, 0, byte.MaxValue);

		public static MagickColor DarkOrchid => MagickColor.FromRgba(153, 50, 204, byte.MaxValue);

		public static MagickColor DarkRed => MagickColor.FromRgba(139, 0, 0, byte.MaxValue);

		public static MagickColor DarkSalmon => MagickColor.FromRgba(233, 150, 122, byte.MaxValue);

		public static MagickColor DarkSeaGreen => MagickColor.FromRgba(143, 188, 139, byte.MaxValue);

		public static MagickColor DarkSlateBlue => MagickColor.FromRgba(72, 61, 139, byte.MaxValue);

		public static MagickColor DarkSlateGray => MagickColor.FromRgba(47, 79, 79, byte.MaxValue);

		public static MagickColor DarkTurquoise => MagickColor.FromRgba(0, 206, 209, byte.MaxValue);

		public static MagickColor DarkViolet => MagickColor.FromRgba(148, 0, 211, byte.MaxValue);

		public static MagickColor DeepPink => MagickColor.FromRgba(byte.MaxValue, 20, 147, byte.MaxValue);

		public static MagickColor DeepSkyBlue => MagickColor.FromRgba(0, 191, byte.MaxValue, byte.MaxValue);

		public static MagickColor DimGray => MagickColor.FromRgba(105, 105, 105, byte.MaxValue);

		public static MagickColor DodgerBlue => MagickColor.FromRgba(30, 144, byte.MaxValue, byte.MaxValue);

		public static MagickColor Firebrick => MagickColor.FromRgba(178, 34, 34, byte.MaxValue);

		public static MagickColor FloralWhite => MagickColor.FromRgba(byte.MaxValue, 250, 240, byte.MaxValue);

		public static MagickColor ForestGreen => MagickColor.FromRgba(34, 139, 34, byte.MaxValue);

		public static MagickColor Fuchsia => MagickColor.FromRgba(byte.MaxValue, 0, byte.MaxValue, byte.MaxValue);

		public static MagickColor Gainsboro => MagickColor.FromRgba(220, 220, 220, byte.MaxValue);

		public static MagickColor GhostWhite => MagickColor.FromRgba(248, 248, byte.MaxValue, byte.MaxValue);

		public static MagickColor Gold => MagickColor.FromRgba(byte.MaxValue, 215, 0, byte.MaxValue);

		public static MagickColor Goldenrod => MagickColor.FromRgba(218, 165, 32, byte.MaxValue);

		public static MagickColor Gray => MagickColor.FromRgba(128, 128, 128, byte.MaxValue);

		public static MagickColor Green => MagickColor.FromRgba(0, 128, 0, byte.MaxValue);

		public static MagickColor GreenYellow => MagickColor.FromRgba(173, byte.MaxValue, 47, byte.MaxValue);

		public static MagickColor Honeydew => MagickColor.FromRgba(240, byte.MaxValue, 240, byte.MaxValue);

		public static MagickColor HotPink => MagickColor.FromRgba(byte.MaxValue, 105, 180, byte.MaxValue);

		public static MagickColor IndianRed => MagickColor.FromRgba(205, 92, 92, byte.MaxValue);

		public static MagickColor Indigo => MagickColor.FromRgba(75, 0, 130, byte.MaxValue);

		public static MagickColor Ivory => MagickColor.FromRgba(byte.MaxValue, byte.MaxValue, 240, byte.MaxValue);

		public static MagickColor Khaki => MagickColor.FromRgba(240, 230, 140, byte.MaxValue);

		public static MagickColor Lavender => MagickColor.FromRgba(230, 230, 250, byte.MaxValue);

		public static MagickColor LavenderBlush => MagickColor.FromRgba(byte.MaxValue, 240, 245, byte.MaxValue);

		public static MagickColor LawnGreen => MagickColor.FromRgba(124, 252, 0, byte.MaxValue);

		public static MagickColor LemonChiffon => MagickColor.FromRgba(byte.MaxValue, 250, 205, byte.MaxValue);

		public static MagickColor LightBlue => MagickColor.FromRgba(173, 216, 230, byte.MaxValue);

		public static MagickColor LightCoral => MagickColor.FromRgba(240, 128, 128, byte.MaxValue);

		public static MagickColor LightCyan => MagickColor.FromRgba(224, byte.MaxValue, byte.MaxValue, byte.MaxValue);

		public static MagickColor LightGoldenrodYellow => MagickColor.FromRgba(250, 250, 210, byte.MaxValue);

		public static MagickColor LightGreen => MagickColor.FromRgba(144, 238, 144, byte.MaxValue);

		public static MagickColor LightGray => MagickColor.FromRgba(211, 211, 211, byte.MaxValue);

		public static MagickColor LightPink => MagickColor.FromRgba(byte.MaxValue, 182, 193, byte.MaxValue);

		public static MagickColor LightSalmon => MagickColor.FromRgba(byte.MaxValue, 160, 122, byte.MaxValue);

		public static MagickColor LightSeaGreen => MagickColor.FromRgba(32, 178, 170, byte.MaxValue);

		public static MagickColor LightSkyBlue => MagickColor.FromRgba(135, 206, 250, byte.MaxValue);

		public static MagickColor LightSlateGray => MagickColor.FromRgba(119, 136, 153, byte.MaxValue);

		public static MagickColor LightSteelBlue => MagickColor.FromRgba(176, 196, 222, byte.MaxValue);

		public static MagickColor LightYellow => MagickColor.FromRgba(byte.MaxValue, byte.MaxValue, 224, byte.MaxValue);

		public static MagickColor Lime => MagickColor.FromRgba(0, byte.MaxValue, 0, byte.MaxValue);

		public static MagickColor LimeGreen => MagickColor.FromRgba(50, 205, 50, byte.MaxValue);

		public static MagickColor Linen => MagickColor.FromRgba(250, 240, 230, byte.MaxValue);

		public static MagickColor Magenta => MagickColor.FromRgba(byte.MaxValue, 0, byte.MaxValue, byte.MaxValue);

		public static MagickColor Maroon => MagickColor.FromRgba(128, 0, 0, byte.MaxValue);

		public static MagickColor MediumAquamarine => MagickColor.FromRgba(102, 205, 170, byte.MaxValue);

		public static MagickColor MediumBlue => MagickColor.FromRgba(0, 0, 205, byte.MaxValue);

		public static MagickColor MediumOrchid => MagickColor.FromRgba(186, 85, 211, byte.MaxValue);

		public static MagickColor MediumPurple => MagickColor.FromRgba(147, 112, 219, byte.MaxValue);

		public static MagickColor MediumSeaGreen => MagickColor.FromRgba(60, 179, 113, byte.MaxValue);

		public static MagickColor MediumSlateBlue => MagickColor.FromRgba(123, 104, 238, byte.MaxValue);

		public static MagickColor MediumSpringGreen => MagickColor.FromRgba(0, 250, 154, byte.MaxValue);

		public static MagickColor MediumTurquoise => MagickColor.FromRgba(72, 209, 204, byte.MaxValue);

		public static MagickColor MediumVioletRed => MagickColor.FromRgba(199, 21, 133, byte.MaxValue);

		public static MagickColor MidnightBlue => MagickColor.FromRgba(25, 25, 112, byte.MaxValue);

		public static MagickColor MintCream => MagickColor.FromRgba(245, byte.MaxValue, 250, byte.MaxValue);

		public static MagickColor MistyRose => MagickColor.FromRgba(byte.MaxValue, 228, 225, byte.MaxValue);

		public static MagickColor Moccasin => MagickColor.FromRgba(byte.MaxValue, 228, 181, byte.MaxValue);

		public static MagickColor NavajoWhite => MagickColor.FromRgba(byte.MaxValue, 222, 173, byte.MaxValue);

		public static MagickColor Navy => MagickColor.FromRgba(0, 0, 128, byte.MaxValue);

		public static MagickColor OldLace => MagickColor.FromRgba(253, 245, 230, byte.MaxValue);

		public static MagickColor Olive => MagickColor.FromRgba(128, 128, 0, byte.MaxValue);

		public static MagickColor OliveDrab => MagickColor.FromRgba(107, 142, 35, byte.MaxValue);

		public static MagickColor Orange => MagickColor.FromRgba(byte.MaxValue, 165, 0, byte.MaxValue);

		public static MagickColor OrangeRed => MagickColor.FromRgba(byte.MaxValue, 69, 0, byte.MaxValue);

		public static MagickColor Orchid => MagickColor.FromRgba(218, 112, 214, byte.MaxValue);

		public static MagickColor PaleGoldenrod => MagickColor.FromRgba(238, 232, 170, byte.MaxValue);

		public static MagickColor PaleGreen => MagickColor.FromRgba(152, 251, 152, byte.MaxValue);

		public static MagickColor PaleTurquoise => MagickColor.FromRgba(175, 238, 238, byte.MaxValue);

		public static MagickColor PaleVioletRed => MagickColor.FromRgba(219, 112, 147, byte.MaxValue);

		public static MagickColor PapayaWhip => MagickColor.FromRgba(byte.MaxValue, 239, 213, byte.MaxValue);

		public static MagickColor PeachPuff => MagickColor.FromRgba(byte.MaxValue, 218, 185, byte.MaxValue);

		public static MagickColor Peru => MagickColor.FromRgba(205, 133, 63, byte.MaxValue);

		public static MagickColor Pink => MagickColor.FromRgba(byte.MaxValue, 192, 203, byte.MaxValue);

		public static MagickColor Plum => MagickColor.FromRgba(221, 160, 221, byte.MaxValue);

		public static MagickColor PowderBlue => MagickColor.FromRgba(176, 224, 230, byte.MaxValue);

		public static MagickColor Purple => MagickColor.FromRgba(128, 0, 128, byte.MaxValue);

		public static MagickColor RebeccaPurple => MagickColor.FromRgba(102, 51, 153, byte.MaxValue);

		public static MagickColor Red => MagickColor.FromRgba(byte.MaxValue, 0, 0, byte.MaxValue);

		public static MagickColor RosyBrown => MagickColor.FromRgba(188, 143, 143, byte.MaxValue);

		public static MagickColor RoyalBlue => MagickColor.FromRgba(65, 105, 225, byte.MaxValue);

		public static MagickColor SaddleBrown => MagickColor.FromRgba(139, 69, 19, byte.MaxValue);

		public static MagickColor Salmon => MagickColor.FromRgba(250, 128, 114, byte.MaxValue);

		public static MagickColor SandyBrown => MagickColor.FromRgba(244, 164, 96, byte.MaxValue);

		public static MagickColor SeaGreen => MagickColor.FromRgba(46, 139, 87, byte.MaxValue);

		public static MagickColor SeaShell => MagickColor.FromRgba(byte.MaxValue, 245, 238, byte.MaxValue);

		public static MagickColor Sienna => MagickColor.FromRgba(160, 82, 45, byte.MaxValue);

		public static MagickColor Silver => MagickColor.FromRgba(192, 192, 192, byte.MaxValue);

		public static MagickColor SkyBlue => MagickColor.FromRgba(135, 206, 235, byte.MaxValue);

		public static MagickColor SlateBlue => MagickColor.FromRgba(106, 90, 205, byte.MaxValue);

		public static MagickColor SlateGray => MagickColor.FromRgba(112, 128, 144, byte.MaxValue);

		public static MagickColor Snow => MagickColor.FromRgba(byte.MaxValue, 250, 250, byte.MaxValue);

		public static MagickColor SpringGreen => MagickColor.FromRgba(0, byte.MaxValue, 127, byte.MaxValue);

		public static MagickColor SteelBlue => MagickColor.FromRgba(70, 130, 180, byte.MaxValue);

		public static MagickColor Tan => MagickColor.FromRgba(210, 180, 140, byte.MaxValue);

		public static MagickColor Teal => MagickColor.FromRgba(0, 128, 128, byte.MaxValue);

		public static MagickColor Thistle => MagickColor.FromRgba(216, 191, 216, byte.MaxValue);

		public static MagickColor Tomato => MagickColor.FromRgba(byte.MaxValue, 99, 71, byte.MaxValue);

		public static MagickColor Turquoise => MagickColor.FromRgba(64, 224, 208, byte.MaxValue);

		public static MagickColor Violet => MagickColor.FromRgba(238, 130, 238, byte.MaxValue);

		public static MagickColor Wheat => MagickColor.FromRgba(245, 222, 179, byte.MaxValue);

		public static MagickColor White => MagickColor.FromRgba(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);

		public static MagickColor WhiteSmoke => MagickColor.FromRgba(245, 245, 245, byte.MaxValue);

		public static MagickColor Yellow => MagickColor.FromRgba(byte.MaxValue, byte.MaxValue, 0, byte.MaxValue);

		public static MagickColor YellowGreen => MagickColor.FromRgba(154, 205, 50, byte.MaxValue);

		IMagickColor<byte> IMagickColors<byte>.None => (IMagickColor<byte>)(object)None;

		IMagickColor<byte> IMagickColors<byte>.Transparent => (IMagickColor<byte>)(object)Transparent;

		IMagickColor<byte> IMagickColors<byte>.AliceBlue => (IMagickColor<byte>)(object)AliceBlue;

		IMagickColor<byte> IMagickColors<byte>.AntiqueWhite => (IMagickColor<byte>)(object)AntiqueWhite;

		IMagickColor<byte> IMagickColors<byte>.Aqua => (IMagickColor<byte>)(object)Aqua;

		IMagickColor<byte> IMagickColors<byte>.Aquamarine => (IMagickColor<byte>)(object)Aquamarine;

		IMagickColor<byte> IMagickColors<byte>.Azure => (IMagickColor<byte>)(object)Azure;

		IMagickColor<byte> IMagickColors<byte>.Beige => (IMagickColor<byte>)(object)Beige;

		IMagickColor<byte> IMagickColors<byte>.Bisque => (IMagickColor<byte>)(object)Bisque;

		IMagickColor<byte> IMagickColors<byte>.Black => (IMagickColor<byte>)(object)Black;

		IMagickColor<byte> IMagickColors<byte>.BlanchedAlmond => (IMagickColor<byte>)(object)BlanchedAlmond;

		IMagickColor<byte> IMagickColors<byte>.Blue => (IMagickColor<byte>)(object)Blue;

		IMagickColor<byte> IMagickColors<byte>.BlueViolet => (IMagickColor<byte>)(object)BlueViolet;

		IMagickColor<byte> IMagickColors<byte>.Brown => (IMagickColor<byte>)(object)Brown;

		IMagickColor<byte> IMagickColors<byte>.BurlyWood => (IMagickColor<byte>)(object)BurlyWood;

		IMagickColor<byte> IMagickColors<byte>.CadetBlue => (IMagickColor<byte>)(object)CadetBlue;

		IMagickColor<byte> IMagickColors<byte>.Chartreuse => (IMagickColor<byte>)(object)Chartreuse;

		IMagickColor<byte> IMagickColors<byte>.Chocolate => (IMagickColor<byte>)(object)Chocolate;

		IMagickColor<byte> IMagickColors<byte>.Coral => (IMagickColor<byte>)(object)Coral;

		IMagickColor<byte> IMagickColors<byte>.CornflowerBlue => (IMagickColor<byte>)(object)CornflowerBlue;

		IMagickColor<byte> IMagickColors<byte>.Cornsilk => (IMagickColor<byte>)(object)Cornsilk;

		IMagickColor<byte> IMagickColors<byte>.Crimson => (IMagickColor<byte>)(object)Crimson;

		IMagickColor<byte> IMagickColors<byte>.Cyan => (IMagickColor<byte>)(object)Cyan;

		IMagickColor<byte> IMagickColors<byte>.DarkBlue => (IMagickColor<byte>)(object)DarkBlue;

		IMagickColor<byte> IMagickColors<byte>.DarkCyan => (IMagickColor<byte>)(object)DarkCyan;

		IMagickColor<byte> IMagickColors<byte>.DarkGoldenrod => (IMagickColor<byte>)(object)DarkGoldenrod;

		IMagickColor<byte> IMagickColors<byte>.DarkGray => (IMagickColor<byte>)(object)DarkGray;

		IMagickColor<byte> IMagickColors<byte>.DarkGreen => (IMagickColor<byte>)(object)DarkGreen;

		IMagickColor<byte> IMagickColors<byte>.DarkKhaki => (IMagickColor<byte>)(object)DarkKhaki;

		IMagickColor<byte> IMagickColors<byte>.DarkMagenta => (IMagickColor<byte>)(object)DarkMagenta;

		IMagickColor<byte> IMagickColors<byte>.DarkOliveGreen => (IMagickColor<byte>)(object)DarkOliveGreen;

		IMagickColor<byte> IMagickColors<byte>.DarkOrange => (IMagickColor<byte>)(object)DarkOrange;

		IMagickColor<byte> IMagickColors<byte>.DarkOrchid => (IMagickColor<byte>)(object)DarkOrchid;

		IMagickColor<byte> IMagickColors<byte>.DarkRed => (IMagickColor<byte>)(object)DarkRed;

		IMagickColor<byte> IMagickColors<byte>.DarkSalmon => (IMagickColor<byte>)(object)DarkSalmon;

		IMagickColor<byte> IMagickColors<byte>.DarkSeaGreen => (IMagickColor<byte>)(object)DarkSeaGreen;

		IMagickColor<byte> IMagickColors<byte>.DarkSlateBlue => (IMagickColor<byte>)(object)DarkSlateBlue;

		IMagickColor<byte> IMagickColors<byte>.DarkSlateGray => (IMagickColor<byte>)(object)DarkSlateGray;

		IMagickColor<byte> IMagickColors<byte>.DarkTurquoise => (IMagickColor<byte>)(object)DarkTurquoise;

		IMagickColor<byte> IMagickColors<byte>.DarkViolet => (IMagickColor<byte>)(object)DarkViolet;

		IMagickColor<byte> IMagickColors<byte>.DeepPink => (IMagickColor<byte>)(object)DeepPink;

		IMagickColor<byte> IMagickColors<byte>.DeepSkyBlue => (IMagickColor<byte>)(object)DeepSkyBlue;

		IMagickColor<byte> IMagickColors<byte>.DimGray => (IMagickColor<byte>)(object)DimGray;

		IMagickColor<byte> IMagickColors<byte>.DodgerBlue => (IMagickColor<byte>)(object)DodgerBlue;

		IMagickColor<byte> IMagickColors<byte>.Firebrick => (IMagickColor<byte>)(object)Firebrick;

		IMagickColor<byte> IMagickColors<byte>.FloralWhite => (IMagickColor<byte>)(object)FloralWhite;

		IMagickColor<byte> IMagickColors<byte>.ForestGreen => (IMagickColor<byte>)(object)ForestGreen;

		IMagickColor<byte> IMagickColors<byte>.Fuchsia => (IMagickColor<byte>)(object)Fuchsia;

		IMagickColor<byte> IMagickColors<byte>.Gainsboro => (IMagickColor<byte>)(object)Gainsboro;

		IMagickColor<byte> IMagickColors<byte>.GhostWhite => (IMagickColor<byte>)(object)GhostWhite;

		IMagickColor<byte> IMagickColors<byte>.Gold => (IMagickColor<byte>)(object)Gold;

		IMagickColor<byte> IMagickColors<byte>.Goldenrod => (IMagickColor<byte>)(object)Goldenrod;

		IMagickColor<byte> IMagickColors<byte>.Gray => (IMagickColor<byte>)(object)Gray;

		IMagickColor<byte> IMagickColors<byte>.Green => (IMagickColor<byte>)(object)Green;

		IMagickColor<byte> IMagickColors<byte>.GreenYellow => (IMagickColor<byte>)(object)GreenYellow;

		IMagickColor<byte> IMagickColors<byte>.Honeydew => (IMagickColor<byte>)(object)Honeydew;

		IMagickColor<byte> IMagickColors<byte>.HotPink => (IMagickColor<byte>)(object)HotPink;

		IMagickColor<byte> IMagickColors<byte>.IndianRed => (IMagickColor<byte>)(object)IndianRed;

		IMagickColor<byte> IMagickColors<byte>.Indigo => (IMagickColor<byte>)(object)Indigo;

		IMagickColor<byte> IMagickColors<byte>.Ivory => (IMagickColor<byte>)(object)Ivory;

		IMagickColor<byte> IMagickColors<byte>.Khaki => (IMagickColor<byte>)(object)Khaki;

		IMagickColor<byte> IMagickColors<byte>.Lavender => (IMagickColor<byte>)(object)Lavender;

		IMagickColor<byte> IMagickColors<byte>.LavenderBlush => (IMagickColor<byte>)(object)LavenderBlush;

		IMagickColor<byte> IMagickColors<byte>.LawnGreen => (IMagickColor<byte>)(object)LawnGreen;

		IMagickColor<byte> IMagickColors<byte>.LemonChiffon => (IMagickColor<byte>)(object)LemonChiffon;

		IMagickColor<byte> IMagickColors<byte>.LightBlue => (IMagickColor<byte>)(object)LightBlue;

		IMagickColor<byte> IMagickColors<byte>.LightCoral => (IMagickColor<byte>)(object)LightCoral;

		IMagickColor<byte> IMagickColors<byte>.LightCyan => (IMagickColor<byte>)(object)LightCyan;

		IMagickColor<byte> IMagickColors<byte>.LightGoldenrodYellow => (IMagickColor<byte>)(object)LightGoldenrodYellow;

		IMagickColor<byte> IMagickColors<byte>.LightGreen => (IMagickColor<byte>)(object)LightGreen;

		IMagickColor<byte> IMagickColors<byte>.LightGray => (IMagickColor<byte>)(object)LightGray;

		IMagickColor<byte> IMagickColors<byte>.LightPink => (IMagickColor<byte>)(object)LightPink;

		IMagickColor<byte> IMagickColors<byte>.LightSalmon => (IMagickColor<byte>)(object)LightSalmon;

		IMagickColor<byte> IMagickColors<byte>.LightSeaGreen => (IMagickColor<byte>)(object)LightSeaGreen;

		IMagickColor<byte> IMagickColors<byte>.LightSkyBlue => (IMagickColor<byte>)(object)LightSkyBlue;

		IMagickColor<byte> IMagickColors<byte>.LightSlateGray => (IMagickColor<byte>)(object)LightSlateGray;

		IMagickColor<byte> IMagickColors<byte>.LightSteelBlue => (IMagickColor<byte>)(object)LightSteelBlue;

		IMagickColor<byte> IMagickColors<byte>.LightYellow => (IMagickColor<byte>)(object)LightYellow;

		IMagickColor<byte> IMagickColors<byte>.Lime => (IMagickColor<byte>)(object)Lime;

		IMagickColor<byte> IMagickColors<byte>.LimeGreen => (IMagickColor<byte>)(object)LimeGreen;

		IMagickColor<byte> IMagickColors<byte>.Linen => (IMagickColor<byte>)(object)Linen;

		IMagickColor<byte> IMagickColors<byte>.Magenta => (IMagickColor<byte>)(object)Magenta;

		IMagickColor<byte> IMagickColors<byte>.Maroon => (IMagickColor<byte>)(object)Maroon;

		IMagickColor<byte> IMagickColors<byte>.MediumAquamarine => (IMagickColor<byte>)(object)MediumAquamarine;

		IMagickColor<byte> IMagickColors<byte>.MediumBlue => (IMagickColor<byte>)(object)MediumBlue;

		IMagickColor<byte> IMagickColors<byte>.MediumOrchid => (IMagickColor<byte>)(object)MediumOrchid;

		IMagickColor<byte> IMagickColors<byte>.MediumPurple => (IMagickColor<byte>)(object)MediumPurple;

		IMagickColor<byte> IMagickColors<byte>.MediumSeaGreen => (IMagickColor<byte>)(object)MediumSeaGreen;

		IMagickColor<byte> IMagickColors<byte>.MediumSlateBlue => (IMagickColor<byte>)(object)MediumSlateBlue;

		IMagickColor<byte> IMagickColors<byte>.MediumSpringGreen => (IMagickColor<byte>)(object)MediumSpringGreen;

		IMagickColor<byte> IMagickColors<byte>.MediumTurquoise => (IMagickColor<byte>)(object)MediumTurquoise;

		IMagickColor<byte> IMagickColors<byte>.MediumVioletRed => (IMagickColor<byte>)(object)MediumVioletRed;

		IMagickColor<byte> IMagickColors<byte>.MidnightBlue => (IMagickColor<byte>)(object)MidnightBlue;

		IMagickColor<byte> IMagickColors<byte>.MintCream => (IMagickColor<byte>)(object)MintCream;

		IMagickColor<byte> IMagickColors<byte>.MistyRose => (IMagickColor<byte>)(object)MistyRose;

		IMagickColor<byte> IMagickColors<byte>.Moccasin => (IMagickColor<byte>)(object)Moccasin;

		IMagickColor<byte> IMagickColors<byte>.NavajoWhite => (IMagickColor<byte>)(object)NavajoWhite;

		IMagickColor<byte> IMagickColors<byte>.Navy => (IMagickColor<byte>)(object)Navy;

		IMagickColor<byte> IMagickColors<byte>.OldLace => (IMagickColor<byte>)(object)OldLace;

		IMagickColor<byte> IMagickColors<byte>.Olive => (IMagickColor<byte>)(object)Olive;

		IMagickColor<byte> IMagickColors<byte>.OliveDrab => (IMagickColor<byte>)(object)OliveDrab;

		IMagickColor<byte> IMagickColors<byte>.Orange => (IMagickColor<byte>)(object)Orange;

		IMagickColor<byte> IMagickColors<byte>.OrangeRed => (IMagickColor<byte>)(object)OrangeRed;

		IMagickColor<byte> IMagickColors<byte>.Orchid => (IMagickColor<byte>)(object)Orchid;

		IMagickColor<byte> IMagickColors<byte>.PaleGoldenrod => (IMagickColor<byte>)(object)PaleGoldenrod;

		IMagickColor<byte> IMagickColors<byte>.PaleGreen => (IMagickColor<byte>)(object)PaleGreen;

		IMagickColor<byte> IMagickColors<byte>.PaleTurquoise => (IMagickColor<byte>)(object)PaleTurquoise;

		IMagickColor<byte> IMagickColors<byte>.PaleVioletRed => (IMagickColor<byte>)(object)PaleVioletRed;

		IMagickColor<byte> IMagickColors<byte>.PapayaWhip => (IMagickColor<byte>)(object)PapayaWhip;

		IMagickColor<byte> IMagickColors<byte>.PeachPuff => (IMagickColor<byte>)(object)PeachPuff;

		IMagickColor<byte> IMagickColors<byte>.Peru => (IMagickColor<byte>)(object)Peru;

		IMagickColor<byte> IMagickColors<byte>.Pink => (IMagickColor<byte>)(object)Pink;

		IMagickColor<byte> IMagickColors<byte>.Plum => (IMagickColor<byte>)(object)Plum;

		IMagickColor<byte> IMagickColors<byte>.PowderBlue => (IMagickColor<byte>)(object)PowderBlue;

		IMagickColor<byte> IMagickColors<byte>.Purple => (IMagickColor<byte>)(object)Purple;

		IMagickColor<byte> IMagickColors<byte>.RebeccaPurple => (IMagickColor<byte>)(object)RebeccaPurple;

		IMagickColor<byte> IMagickColors<byte>.Red => (IMagickColor<byte>)(object)Red;

		IMagickColor<byte> IMagickColors<byte>.RosyBrown => (IMagickColor<byte>)(object)RosyBrown;

		IMagickColor<byte> IMagickColors<byte>.RoyalBlue => (IMagickColor<byte>)(object)RoyalBlue;

		IMagickColor<byte> IMagickColors<byte>.SaddleBrown => (IMagickColor<byte>)(object)SaddleBrown;

		IMagickColor<byte> IMagickColors<byte>.Salmon => (IMagickColor<byte>)(object)Salmon;

		IMagickColor<byte> IMagickColors<byte>.SandyBrown => (IMagickColor<byte>)(object)SandyBrown;

		IMagickColor<byte> IMagickColors<byte>.SeaGreen => (IMagickColor<byte>)(object)SeaGreen;

		IMagickColor<byte> IMagickColors<byte>.SeaShell => (IMagickColor<byte>)(object)SeaShell;

		IMagickColor<byte> IMagickColors<byte>.Sienna => (IMagickColor<byte>)(object)Sienna;

		IMagickColor<byte> IMagickColors<byte>.Silver => (IMagickColor<byte>)(object)Silver;

		IMagickColor<byte> IMagickColors<byte>.SkyBlue => (IMagickColor<byte>)(object)SkyBlue;

		IMagickColor<byte> IMagickColors<byte>.SlateBlue => (IMagickColor<byte>)(object)SlateBlue;

		IMagickColor<byte> IMagickColors<byte>.SlateGray => (IMagickColor<byte>)(object)SlateGray;

		IMagickColor<byte> IMagickColors<byte>.Snow => (IMagickColor<byte>)(object)Snow;

		IMagickColor<byte> IMagickColors<byte>.SpringGreen => (IMagickColor<byte>)(object)SpringGreen;

		IMagickColor<byte> IMagickColors<byte>.SteelBlue => (IMagickColor<byte>)(object)SteelBlue;

		IMagickColor<byte> IMagickColors<byte>.Tan => (IMagickColor<byte>)(object)Tan;

		IMagickColor<byte> IMagickColors<byte>.Teal => (IMagickColor<byte>)(object)Teal;

		IMagickColor<byte> IMagickColors<byte>.Thistle => (IMagickColor<byte>)(object)Thistle;

		IMagickColor<byte> IMagickColors<byte>.Tomato => (IMagickColor<byte>)(object)Tomato;

		IMagickColor<byte> IMagickColors<byte>.Turquoise => (IMagickColor<byte>)(object)Turquoise;

		IMagickColor<byte> IMagickColors<byte>.Violet => (IMagickColor<byte>)(object)Violet;

		IMagickColor<byte> IMagickColors<byte>.Wheat => (IMagickColor<byte>)(object)Wheat;

		IMagickColor<byte> IMagickColors<byte>.White => (IMagickColor<byte>)(object)White;

		IMagickColor<byte> IMagickColors<byte>.WhiteSmoke => (IMagickColor<byte>)(object)WhiteSmoke;

		IMagickColor<byte> IMagickColors<byte>.Yellow => (IMagickColor<byte>)(object)Yellow;

		IMagickColor<byte> IMagickColors<byte>.YellowGreen => (IMagickColor<byte>)(object)YellowGreen;
	}
	public sealed class MagickDefine : IDefine
	{
		public MagickFormat Format { get; }

		public string Name { get; }

		public string Value { get; }

		public MagickDefine(string name, string value)
			: this((MagickFormat)0, name, value)
		{
		}

		public MagickDefine(string name, Enum value)
			: this((MagickFormat)0, name, value)
		{
		}

		public MagickDefine(MagickFormat format, string name, bool value)
			: this(format, name, value ? "true" : "false")
		{
		}//IL_0001: Unknown result type (might be due to invalid IL or missing references)


		public MagickDefine(MagickFormat format, string name, double value)
			: this(format, name, value.ToString(CultureInfo.InvariantCulture))
		{
		}//IL_0001: Unknown result type (might be due to invalid IL or missing references)


		public MagickDefine(MagickFormat format, string name, Enum value)
			: this(format, name, EnumHelper.GetName(value).ToLowerInvariant())
		{
		}//IL_0001: Unknown result type (might be due to invalid IL or missing references)


		public MagickDefine(MagickFormat format, string name, int value)
			: this(format, name, value.ToString(CultureInfo.InvariantCulture))
		{
		}//IL_0001: Unknown result type (might be due to invalid IL or missing references)


		public MagickDefine(MagickFormat format, string name, IMagickGeometry value)
			: this(format, name, (value != null) ? value.ToString() : null)
		{
		}//IL_0001: Unknown result type (might be due to invalid IL or missing references)


		public MagickDefine(MagickFormat format, string name, long value)
			: this(format, name, value.ToString(CultureInfo.InvariantCulture))
		{
		}//IL_0001: Unknown result type (might be due to invalid IL or missing references)


		public MagickDefine(MagickFormat format, string name, string value)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			Throw.IfNullOrEmpty(name, "name");
			Throw.IfNullOrEmpty(value, "value");
			Format = format;
			Name = name;
			Value = value;
		}

		public static MagickDefine? Create<T>(MagickFormat format, string name, IEnumerable<T>? value)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (value == null)
			{
				return null;
			}
			List<string> list = new List<string>();
			foreach (T item in value)
			{
				if (item != null)
				{
					string text = item.ToString();
					if (text != null)
					{
						list.Add(text);
					}
				}
			}
			if (list.Count == 0)
			{
				return null;
			}
			return new MagickDefine(format, name, string.Join(",", list.ToArray()));
		}
	}
	internal enum GeometryFlags
	{
		NoValue = 0,
		PercentValue = 0x1000,
		IgnoreAspectRatio = 0x2000,
		Less = 0x4000,
		Greater = 0x8000,
		FillArea = 0x10000,
		LimitPixels = 0x20000,
		AspectRatio = 0x100000
	}
	internal enum LayerMethod
	{
		Undefined,
		Coalesce,
		CompareAny,
		CompareClear,
		CompareOverlay,
		Dispose,
		Optimize,
		OptimizeImage,
		OptimizePlus,
		OptimizeTrans,
		RemoveDups,
		RemoveZero,
		Composite,
		Merge,
		Flatten,
		Mosaic,
		Trimbounds
	}
	internal sealed class ArtifactEventArgs : EventArgs
	{
		public string Key { get; }

		public string? Value { get; }

		internal ArtifactEventArgs(string key, string? value)
		{
			Key = key;
			Value = value;
		}
	}
	internal enum ExceptionSeverity
	{
		Undefined = 0,
		Warning = 300,
		ResourceLimitWarning = 300,
		TypeWarning = 305,
		OptionWarning = 310,
		DelegateWarning = 315,
		MissingDelegateWarning = 320,
		CorruptImageWarning = 325,
		FileOpenWarning = 330,
		BlobWarning = 335,
		StreamWarning = 340,
		CacheWarning = 345,
		CoderWarning = 350,
		FilterWarning = 352,
		ModuleWarning = 355,
		DrawWarning = 360,
		ImageWarning = 365,
		WandWarning = 370,
		RandomWarning = 375,
		XServerWarning = 380,
		MonitorWarning = 385,
		RegistryWarning = 390,
		ConfigureWarning = 395,
		PolicyWarning = 399,
		Error = 400,
		ResourceLimitError = 400,
		TypeError = 405,
		OptionError = 410,
		DelegateError = 415,
		MissingDelegateError = 420,
		CorruptImageError = 425,
		FileOpenError = 430,
		BlobError = 435,
		StreamError = 440,
		CacheError = 445,
		CoderError = 450,
		FilterError = 452,
		ModuleError = 455,
		DrawError = 460,
		ImageError = 465,
		WandError = 470,
		RandomError = 475,
		XServerError = 480,
		MonitorError = 485,
		RegistryError = 490,
		ConfigureError = 495,
		PolicyError = 499
	}
	internal static class MagickExceptionHelper
	{
		[NativeInterop]
		private static class NativeMagickExceptionHelper
		{
			public static string? Description(IntPtr exception)
			{
				return UTF8Marshaler.CreateNullableInstance(NativeMethods.MagickExceptionHelper_Description(exception));
			}

			public static void Dispose(IntPtr exception)
			{
				NativeMethods.MagickExceptionHelper_Dispose(exception);
			}

			public static string? Message(IntPtr exception)
			{
				return UTF8Marshaler.CreateNullableInstance(NativeMethods.MagickExceptionHelper_Message(exception));
			}

			public static IntPtr Related(IntPtr exception, nuint index)
			{
				return NativeMethods.MagickExceptionHelper_Related(exception, index);
			}

			public static nuint RelatedCount(IntPtr exception)
			{
				return NativeMethods.MagickExceptionHelper_RelatedCount(exception);
			}

			public static ExceptionSeverity Severity(IntPtr exception)
			{
				return (ExceptionSeverity)(int)NativeMethods.MagickExceptionHelper_Severity(exception);
			}

			static NativeMagickExceptionHelper()
			{
				Environment.Initialize();
			}
		}

		private static class NativeMethods
		{
			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickExceptionHelper_Description(IntPtr exception);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickExceptionHelper_Dispose(IntPtr exception);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickExceptionHelper_Message(IntPtr exception);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickExceptionHelper_Related(IntPtr exception, nuint index);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern nuint MagickExceptionHelper_RelatedCount(IntPtr exception);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickExceptionHelper_Severity(IntPtr exception);
		}

		public static MagickException? Check(IntPtr exception)
		{
			MagickException val = Create(exception);
			if (val == null)
			{
				return null;
			}
			if (val is MagickErrorException)
			{
				throw val;
			}
			return val;
		}

		public static MagickException? Create(IntPtr exception)
		{
			if (exception == IntPtr.Zero)
			{
				return null;
			}
			MagickException result = CreateException(exception);
			NativeMagickExceptionHelper.Dispose(exception);
			return result;
		}

		public static MagickException CreateException(IntPtr exception)
		{
			ExceptionSeverity severity = NativeMagickExceptionHelper.Severity(exception);
			string text = NativeMagickExceptionHelper.Message(exception);
			string text2 = NativeMagickExceptionHelper.Description(exception);
			if (!string.IsNullOrEmpty(text2))
			{
				text = text + " (" + text2 + ")";
			}
			if (text == null || text.Length == 0)
			{
				text = string.Empty;
			}
			MagickException val = Create(severity, text);
			List<MagickException> list = CreateRelatedExceptions(exception);
			if (list != null)
			{
				val.SetRelatedException(list);
			}
			return val;
		}

		private static List<MagickException>? CreateRelatedExceptions(IntPtr exception)
		{
			nuint num = NativeMagickExceptionHelper.RelatedCount(exception);
			if (num == 0)
			{
				return null;
			}
			List<MagickException> list = new List<MagickException>((int)num);
			for (uint num2 = 0u; num2 < num; num2++)
			{
				IntPtr exception2 = NativeMagickExceptionHelper.Related(exception, num2);
				list.Add(CreateException(exception2));
			}
			return list;
		}

		private static MagickException Create(ExceptionSeverity severity, string message)
		{
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Expected O, but got Unknown
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: Expected O, but got Unknown
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Expected O, but got Unknown
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Expected O, but got Unknown
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Expected O, but got Unknown
			//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Expected O, but got Unknown
			//IL_030c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Expected O, but got Unknown
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Expected O, but got Unknown
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Expected O, but got Unknown
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Expected O, but got Unknown
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Expected O, but got Unknown
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Expected O, but got Unknown
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Expected O, but got Unknown
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Expected O, but got Unknown
			//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Expected O, but got Unknown
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Expected O, but got Unknown
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Expected O, but got Unknown
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Expected O, but got Unknown
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Expected O, but got Unknown
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Expected O, but got Unknown
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Expected O, but got Unknown
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Expected O, but got Unknown
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Expected O, but got Unknown
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Expected O, but got Unknown
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Expected O, but got Unknown
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Expected O, but got Unknown
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Expected O, but got Unknown
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Expected O, but got Unknown
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Expected O, but got Unknown
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02be: Expected O, but got Unknown
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Expected O, but got Unknown
			//IL_029c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Expected O, but got Unknown
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Expected O, but got Unknown
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Expected O, but got Unknown
			switch (severity)
			{
			case ExceptionSeverity.BlobWarning:
				return (MagickException)new MagickBlobWarningException(message);
			case ExceptionSeverity.CacheWarning:
				return (MagickException)new MagickCacheWarningException(message);
			case ExceptionSeverity.CoderWarning:
				return (MagickException)new MagickCoderWarningException(message);
			case ExceptionSeverity.ConfigureWarning:
				return (MagickException)new MagickConfigureWarningException(message);
			case ExceptionSeverity.CorruptImageWarning:
				return (MagickException)new MagickCorruptImageWarningException(message);
			case ExceptionSeverity.DelegateWarning:
				return (MagickException)new MagickDelegateWarningException(message);
			case ExceptionSeverity.DrawWarning:
				return (MagickException)new MagickDrawWarningException(message);
			case ExceptionSeverity.FileOpenWarning:
				return (MagickException)new MagickFileOpenWarningException(message);
			case ExceptionSeverity.ImageWarning:
				return (MagickException)new MagickImageWarningException(message);
			case ExceptionSeverity.MissingDelegateWarning:
				return (MagickException)new MagickMissingDelegateWarningException(message);
			case ExceptionSeverity.ModuleWarning:
				return (MagickException)new MagickModuleWarningException(message);
			case ExceptionSeverity.OptionWarning:
				return (MagickException)new MagickOptionWarningException(message);
			case ExceptionSeverity.PolicyWarning:
				return (MagickException)new MagickPolicyWarningException(message);
			case ExceptionSeverity.RegistryWarning:
				return (MagickException)new MagickRegistryWarningException(message);
			case ExceptionSeverity.Warning:
				return (MagickException)new MagickResourceLimitWarningException(message);
			case ExceptionSeverity.StreamWarning:
				return (MagickException)new MagickStreamWarningException(message);
			case ExceptionSeverity.TypeWarning:
				return (MagickException)new MagickTypeWarningException(message);
			case ExceptionSeverity.BlobError:
				return (MagickException)new MagickBlobErrorException(message);
			case ExceptionSeverity.CacheError:
				return (MagickException)new MagickCacheErrorException(message);
			case ExceptionSeverity.CoderError:
				return (MagickException)new MagickCoderErrorException(message);
			case ExceptionSeverity.ConfigureError:
				return (MagickException)new MagickConfigureErrorException(message);
			case ExceptionSeverity.CorruptImageError:
				return (MagickException)new MagickCorruptImageErrorException(message);
			case ExceptionSeverity.DelegateError:
				return (MagickException)new MagickDelegateErrorException(message);
			case ExceptionSeverity.DrawError:
				return (MagickException)new MagickDrawErrorException(message);
			case ExceptionSeverity.FileOpenError:
				return (MagickException)new MagickFileOpenErrorException(message);
			case ExceptionSeverity.ImageError:
				return (MagickException)new MagickImageErrorException(message);
			case ExceptionSeverity.MissingDelegateError:
				return (MagickException)new MagickMissingDelegateErrorException(message);
			case ExceptionSeverity.ModuleError:
				return (MagickException)new MagickModuleErrorException(message);
			case ExceptionSeverity.OptionError:
				return (MagickException)new MagickOptionErrorException(message);
			case ExceptionSeverity.PolicyError:
				return (MagickException)new MagickPolicyErrorException(message);
			case ExceptionSeverity.RegistryError:
				return (MagickException)new MagickRegistryErrorException(message);
			case ExceptionSeverity.Error:
				return (MagickException)new MagickResourceLimitErrorException(message);
			case ExceptionSeverity.StreamError:
				return (MagickException)new MagickStreamErrorException(message);
			case ExceptionSeverity.TypeError:
				return (MagickException)new MagickTypeErrorException(message);
			default:
				if (severity >= ExceptionSeverity.Error)
				{
					return (MagickException)new MagickErrorException(message);
				}
				return (MagickException)new MagickWarningException(message);
			}
		}
	}
	public static class DensityExtensions
	{
		public static IMagickGeometry? ToGeometry(this Density self, double width, double height)
		{
			if (self == null)
			{
				return null;
			}
			uint width2 = (uint)(width * self.X);
			uint height2 = (uint)(height * self.Y);
			return (IMagickGeometry?)(object)new MagickGeometry(width2, height2);
		}
	}
	internal static class ByteConverter
	{
		public static byte[]? ToArray(IntPtr nativeData, int length)
		{
			if (nativeData == IntPtr.Zero)
			{
				return null;
			}
			byte[] array = new byte[length];
			Marshal.Copy(nativeData, array, 0, length);
			return array;
		}
	}
	internal static class QuantumConverter
	{
		public unsafe static byte[]? ToArray(IntPtr nativeData, uint length)
		{
			if (nativeData == IntPtr.Zero)
			{
				return null;
			}
			byte[] array = new byte[length];
			byte* source = (byte*)(void*)nativeData;
			fixed (byte* destination = array)
			{
				NativeMemory.Copy(source, destination, length);
			}
			return array;
		}
	}
	internal static class ShortConverter
	{
		public unsafe static ushort[]? ToArray(IntPtr nativeData, int length)
		{
			if (nativeData == IntPtr.Zero)
			{
				return null;
			}
			ushort[] array = new ushort[length];
			ushort* ptr = (ushort*)(void*)nativeData;
			for (int i = 0; i < length; i++)
			{
				array[i] = *(ptr++);
			}
			return array;
		}
	}
	internal sealed class ByteArrayWrapper
	{
		private byte[] _bytes = new byte[8192];

		private int _offset;

		private int _length;

		public byte[] GetBytes()
		{
			ResizeBytes(_length);
			return _bytes;
		}

		public unsafe long Read(IntPtr data, UIntPtr count, IntPtr user_data)
		{
			if (data == IntPtr.Zero)
			{
				return 0L;
			}
			int num = (int)(uint)count;
			if (num == 0)
			{
				return 0L;
			}
			int num2 = Math.Min(num, _length - _offset);
			if (num2 != 0)
			{
				byte* destination = (byte*)data.ToPointer();
				fixed (byte* ptr = _bytes)
				{
					NativeMemory.Copy(ptr + _offset, destination, num2);
				}
				_offset += num2;
			}
			return num2;
		}

		public long Seek(long offset, IntPtr whence, IntPtr user_data)
		{
			int num = (int)((SeekOrigin)(int)whence switch
			{
				SeekOrigin.Begin => offset, 
				SeekOrigin.Current => _offset + offset, 
				SeekOrigin.End => _length - offset, 
				_ => -1L, 
			});
			if (_offset == num)
			{
				return _offset;
			}
			if (num < 0)
			{
				return -1L;
			}
			_offset = num;
			return _offset;
		}

		public long Tell(IntPtr user_data)
		{
			return _offset;
		}

		public unsafe long Write(IntPtr data, UIntPtr count, IntPtr user_data)
		{
			if (data == IntPtr.Zero)
			{
				return 0L;
			}
			int num = (int)(uint)count;
			if (num == 0)
			{
				return 0L;
			}
			int num2 = _offset + num;
			EnsureLength(num2);
			byte* source = (byte*)data.ToPointer();
			fixed (byte* ptr = _bytes)
			{
				NativeMemory.Copy(source, ptr + _offset, num);
			}
			_offset = num2;
			return num;
		}

		private void EnsureLength(int length)
		{
			if (length >= _length)
			{
				_length = length;
				if (_length >= _bytes.Length)
				{
					int length2 = Math.Max(_bytes.Length * 2, _length);
					ResizeBytes(length2);
				}
			}
		}

		private void ResizeBytes(int length)
		{
			Array.Resize(ref _bytes, length);
		}
	}
	internal static class Environment
	{
		[NativeInterop]
		private static class NativeEnvironment
		{
			public static void Initialize()
			{
				NativeMethods.Environment_Initialize();
			}

			[Cleanup]
			public static string? GetEnv(string name)
			{
				using UTF8Marshaler uTF8Marshaler = UTF8Marshaler.CreateInstance(name);
				return UTF8Marshaler.CreateInstanceAndRelinquish(NativeMethods.Environment_GetEnv(uTF8Marshaler.Instance));
			}

			public static void SetEnv(string name, string value)
			{
				using UTF8Marshaler uTF8Marshaler = UTF8Marshaler.CreateInstance(name);
				using UTF8Marshaler uTF8Marshaler2 = UTF8Marshaler.CreateInstance(value);
				NativeMethods.Environment_SetEnv(uTF8Marshaler.Instance, uTF8Marshaler2.Instance);
			}
		}

		private static class NativeMethods
		{
			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void Environment_Initialize();

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr Environment_GetEnv(IntPtr name);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void Environment_SetEnv(IntPtr name, IntPtr value);
		}

		private static readonly object _lock = new object();

		private static bool _initialized;

		public static void Initialize()
		{
			if (_initialized)
			{
				return;
			}
			lock (_lock)
			{
				if (!_initialized)
				{
					NativeEnvironment.Initialize();
					_initialized = true;
				}
			}
		}

		public static string? GetEnv(string name)
		{
			return NativeEnvironment.GetEnv(name);
		}

		public static void SetEnv(string name, string value)
		{
			NativeEnvironment.SetEnv(name, value);
		}
	}
	internal static class MagickMemory
	{
		[NativeInterop]
		private static class NativeMagickMemory
		{
			public static void Relinquish(IntPtr value)
			{
				NativeMethods.MagickMemory_Relinquish(value);
			}

			static NativeMagickMemory()
			{
				Environment.Initialize();
			}
		}

		private static class NativeMethods
		{
			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickMemory_Relinquish(IntPtr value);
		}

		public static void Relinquish(IntPtr value)
		{
			NativeMagickMemory.Relinquish(value);
		}
	}
	internal static class NativeMemory
	{
		public unsafe static void Copy(byte* source, byte* destination, long length)
		{
			Buffer.MemoryCopy(source, destination, length, length);
		}
	}
	internal static class PercentageHelper
	{
		public static Percentage FromQuantum(double value)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Percentage(value / (double)(int)Quantum.Max * 100.0);
		}

		public static double ToQuantum(string paramName, Percentage percentage)
		{
			double num = ((Percentage)(ref percentage)).ToDouble();
			Throw.IfNegative(num, paramName);
			return (double)(int)Quantum.Max * (num / 100.0);
		}

		public static byte ToQuantumType(string paramName, Percentage percentage)
		{
			double num = ((Percentage)(ref percentage)).ToDouble();
			Throw.IfNegative(num, paramName);
			return (byte)((double)(int)Quantum.Max * (num / 100.0));
		}
	}
	internal static class Runtime
	{
		public static bool Is64Bit { get; }

		public static Architecture Architecture { get; }

		public static bool IsWindows { get; }

		static Runtime()
		{
			Architecture = GetArchitecture();
			Architecture architecture = Architecture;
			bool flag = ((architecture == Architecture.X64 || architecture == Architecture.Arm64) ? true : false);
			Is64Bit = flag;
			IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
		}

		private static Architecture GetArchitecture()
		{
			Architecture processArchitecture = RuntimeInformation.ProcessArchitecture;
			if ((uint)processArchitecture <= 1u || processArchitecture == Architecture.Arm64)
			{
				return processArchitecture;
			}
			throw new NotSupportedException(string.Format("{0} is an unsupported architecture, only {1}, {2} and {3} are supported.", processArchitecture, "X64", "Arm64", "X86"));
		}
	}
	internal sealed class StreamWrapper : IDisposable
	{
		private const int BufferSize = 8192;

		private readonly byte[] _buffer;

		private unsafe readonly byte* _bufferStart;

		private readonly long _streamStart;

		private readonly GCHandle _handle;

		private Stream _stream;

		private unsafe StreamWrapper(Stream stream)
		{
			_stream = stream;
			_buffer = new byte[8192];
			_handle = GCHandle.Alloc(_buffer, GCHandleType.Pinned);
			_bufferStart = (byte*)_handle.AddrOfPinnedObject().ToPointer();
			try
			{
				_streamStart = _stream.Position;
			}
			catch
			{
				_streamStart = 0L;
			}
		}

		public static StreamWrapper CreateForReading(Stream stream)
		{
			Throw.IfFalse(stream.CanRead, "stream", "The stream should be readable.");
			return new StreamWrapper(stream);
		}

		public static StreamWrapper CreateForWriting(Stream stream)
		{
			Throw.IfFalse(stream.CanWrite, "stream", "The stream should be writable.");
			return new StreamWrapper(stream);
		}

		public void Dispose()
		{
			_handle.Free();
		}

		public unsafe long Read(IntPtr data, UIntPtr count, IntPtr user_data)
		{
			long num = (long)(ulong)count;
			if (num == 0L)
			{
				return 0L;
			}
			if (data == IntPtr.Zero)
			{
				return 0L;
			}
			byte* destination = (byte*)data.ToPointer();
			long num2 = 0L;
			while (num > 0)
			{
				long num3 = Math.Min(num, 8192L);
				try
				{
					num3 = _stream.Read(_buffer, 0, (int)num3);
				}
				catch
				{
					return -1L;
				}
				if (num3 == 0L)
				{
					break;
				}
				num2 += num3;
				destination = ReadBuffer(destination, num3);
				num -= num3;
			}
			return num2;
		}

		public long Seek(long offset, IntPtr whence, IntPtr user_data)
		{
			try
			{
				return (SeekOrigin)(int)whence switch
				{
					SeekOrigin.Begin => _stream.Seek(_streamStart + offset, SeekOrigin.Begin) - _streamStart, 
					SeekOrigin.Current => _stream.Seek(offset, SeekOrigin.Current) - _streamStart, 
					SeekOrigin.End => _stream.Seek(offset, SeekOrigin.End) - _streamStart, 
					_ => -1L, 
				};
			}
			catch
			{
				return -1L;
			}
		}

		public long Tell(IntPtr user_data)
		{
			try
			{
				return _stream.Position - _streamStart;
			}
			catch
			{
				return -1L;
			}
		}

		public unsafe long Write(IntPtr data, UIntPtr count, IntPtr user_data)
		{
			long num = (long)(ulong)count;
			if (num == 0L)
			{
				return 0L;
			}
			if (data == IntPtr.Zero)
			{
				return 0L;
			}
			byte* source = (byte*)data.ToPointer();
			while (num > 0)
			{
				long num2 = Math.Min(num, 8192L);
				source = FillBuffer(source, num2);
				try
				{
					_stream.Write(_buffer, 0, (int)num2);
				}
				catch
				{
					return -1L;
				}
				num -= num2;
			}
			return (long)(ulong)count;
		}

		private unsafe byte* FillBuffer(byte* source, long length)
		{
			NativeMemory.Copy(source, _bufferStart, length);
			return source + length;
		}

		private unsafe byte* ReadBuffer(byte* destination, long length)
		{
			NativeMemory.Copy(_bufferStart, destination, length);
			return destination + length;
		}
	}
	internal sealed class TemporaryDefines : IDisposable
	{
		private readonly INativeMagickImage _image;

		private readonly List<string> _names = new List<string>();

		public TemporaryDefines(IMagickImage image)
		{
			_image = MagickImage.GetNativeImage(image);
		}

		public TemporaryDefines(INativeMagickImage image)
		{
			_image = image;
		}

		public void Dispose()
		{
			foreach (string name in _names)
			{
				_image.RemoveArtifact(name);
			}
		}

		public void SetArtifact(string name, string? value)
		{
			if (value != null && value.Length >= 1)
			{
				_names.Add(name);
				_image.SetArtifact(name, value);
			}
		}

		public void SetArtifact(string name, bool flag)
		{
			_names.Add(name);
			_image.SetArtifact(name, flag ? "true" : "false");
		}

		public void SetArtifact<TValue>(string name, TValue? value)
		{
			if (value != null)
			{
				_names.Add(name);
				string text = ((!((object)value is IConvertible convertible)) ? value.ToString() : convertible.ToString(CultureInfo.InvariantCulture));
				if (text != null)
				{
					_image.SetArtifact(name, text);
				}
			}
		}
	}
	internal sealed class TemporaryFile : IDisposable
	{
		private readonly FileInfo _tempFile;

		public long Length
		{
			get
			{
				_tempFile.Refresh();
				return _tempFile.Length;
			}
		}

		public string FullName => _tempFile.FullName;

		public TemporaryFile()
		{
			_tempFile = new FileInfo(Path.Combine(MagickNET.TemporaryDirectory, Guid.NewGuid().ToString()));
		}

		public void CopyTo(TemporaryFile temporaryFile)
		{
			CopyTo(temporaryFile._tempFile);
		}

		public void CopyTo(FileInfo file)
		{
			_tempFile.CopyTo(file.FullName, overwrite: true);
			file.Refresh();
		}

		public void Dispose()
		{
			if (_tempFile.Exists)
			{
				_tempFile.Delete();
			}
		}
	}
	internal sealed class TemporaryImageAttacher : IDisposable
	{
		private readonly List<IMagickImage<byte>> _images;

		public TemporaryImageAttacher(List<IMagickImage<byte>> images)
		{
			if (images.Count == 0)
			{
				throw new InvalidOperationException("Operation requires at least one image.");
			}
			_images = images;
			AttachImages();
		}

		public void Dispose()
		{
			DetachImages();
		}

		private void AttachImages()
		{
			for (int i = 0; i < _images.Count - 1; i++)
			{
				if (_images[i] is MagickImage magickImage)
				{
					magickImage.SetNext((IMagickImage?)(object)_images[i + 1]);
				}
			}
		}

		private void DetachImages()
		{
			for (int i = 0; i < _images.Count - 1; i++)
			{
				if (_images[i] is MagickImage magickImage)
				{
					magickImage.SetNext(null);
				}
			}
		}
	}
	internal sealed class TemporaryMagickFormat : IDisposable
	{
		private sealed class MagickFormatInfo
		{
			private readonly IMagickImage<byte> _image;

			private readonly MagickFormat _originalImageFormat;

			private readonly MagickFormat _originalSettingsFormat;

			public MagickFormatInfo(IMagickImage<byte> image)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: 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_0025: Unknown result type (might be due to invalid IL or missing references)
				_image = image;
				_originalImageFormat = ((IMagickImage)image).Format;
				_originalSettingsFormat = image.Settings.Format;
			}

			public void RestoreOriginalFormat()
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				((IMagickImage)_image).Format = _originalImageFormat;
				_image.Settings.Format = _originalSettingsFormat;
			}
		}

		private readonly List<MagickFormatInfo> _formatInfos = new List<MagickFormatInfo>();

		public TemporaryMagickFormat(MagickImage image, MagickFormat format)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			AddImage((IMagickImage<byte>)(object)image, format);
		}

		public TemporaryMagickFormat(MagickImageCollection images, MagickFormat format)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			foreach (IMagickImage<byte> image in images)
			{
				AddImage(image, format);
			}
		}

		public void Dispose()
		{
			foreach (MagickFormatInfo formatInfo in _formatInfos)
			{
				formatInfo.RestoreOriginalFormat();
			}
		}

		private void AddImage(IMagickImage<byte> image, MagickFormat format)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			_formatInfos.Add(new MagickFormatInfo(image));
			((IMagickImage)image).Format = format;
		}
	}
	internal sealed class UTF8Marshaler : INativeInstance, IDisposable
	{
		public IntPtr Instance { get; private set; }

		private UTF8Marshaler(string? value)
		{
			if (value == null)
			{
				Instance = IntPtr.Zero;
				return;
			}
			byte[] bytes = Encoding.UTF8.GetBytes(value);
			Instance = Marshal.AllocHGlobal(bytes.Length + 1);
			Marshal.Copy(bytes, 0, Instance, bytes.Length);
			Marshal.WriteByte(Instance + bytes.Length, 0);
		}

		public void Dispose()
		{
			if (!(Instance == IntPtr.Zero))
			{
				Marshal.FreeHGlobal(Instance);
				Instance = IntPtr.Zero;
			}
		}

		internal static UTF8Marshaler CreateInstance(string? value)
		{
			return new UTF8Marshaler(value);
		}

		internal static string CreateInstance(IntPtr nativeData)
		{
			return CreateNullableInstance(nativeData) ?? throw new InvalidOperationException("The string value should never be null.");
		}

		internal unsafe static string? CreateNullableInstance(IntPtr nativeData)
		{
			if (nativeData == IntPtr.Zero)
			{
				return null;
			}
			byte* ptr = (byte*)(void*)nativeData;
			int num = 0;
			byte* ptr2 = ptr;
			while (*(ptr2++) != 0)
			{
				num++;
			}
			if (num == 0)
			{
				return string.Empty;
			}
			return Encoding.UTF8.GetString(ptr, num);
		}

		internal static string? CreateInstanceAndRelinquish(IntPtr nativeData)
		{
			string? result = CreateNullableInstance(nativeData);
			MagickMemory.Relinquish(nativeData);
			return result;
		}
	}
	public sealed class ImageOptimizer
	{
		private readonly Collection<IImageOptimizer> _optimizers = CreateImageOptimizers();

		public bool IgnoreUnsupportedFormats { get; set; }

		public bool OptimalCompression { get; set; }

		public bool Compress(FileInfo file)
		{
			Throw.IfNull(file, "file");
			return DoCompress(file);
		}

		public bool Compress(string fileName)
		{
			string fileName2 = FileHelper.CheckForBaseDirectory(fileName);
			return DoCompress(new FileInfo(fileName2));
		}

		public bool Compress(Stream stream)
		{
			ImageOptimizerHelper.CheckStream(stream);
			IImageOptimizer optimizer = GetOptimizer(stream);
			if (optimizer == null)
			{
				return false;
			}
			optimizer.OptimalCompression = OptimalCompression;
			return optimizer.Compress(stream);
		}

		public bool IsSupported(FileInfo file)
		{
			return IsSupported(ImageOptimizerHelper.GetFormatInformation(file));
		}

		public bool IsSupported(IMagickFormatInfo? formatInfo)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (formatInfo == null)
			{
				return false;
			}
			foreach (IImageOptimizer optimizer in _optimizers)
			{
				if (optimizer.Format.Format == formatInfo.ModuleFormat)
				{
					return true;
				}
			}
			return false;
		}

		public bool IsSupported(string fileName)
		{
			return IsSupported(ImageOptimizerHelper.GetFormatInformation(fileName));
		}

		public bool IsSupported(Stream stream)
		{
			Throw.IfNull(stream, "stream");
			if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek)
			{
				return false;
			}
			return IsSupported(ImageOptimizerHelper.GetFormatInformation(stream));
		}

		public bool LosslessCompress(FileInfo file)
		{
			Throw.IfNull(file, "file");
			return DoLosslessCompress(file);
		}

		public bool LosslessCompress(string fileName)
		{
			string fileName2 = FileHelper.CheckForBaseDirectory(fileName);
			return DoLosslessCompress(new FileInfo(fileName2));
		}

		public bool LosslessCompress(Stream stream)
		{
			ImageOptimizerHelper.CheckStream(stream);
			IImageOptimizer optimizer = GetOptimizer(stream);
			if (optimizer == null)
			{
				return false;
			}
			optimizer.OptimalCompression = OptimalCompression;
			return optimizer.LosslessCompress(stream);
		}

		private static Collection<IImageOptimizer> CreateImageOptimizers()
		{
			return new Collection<IImageOptimizer>
			{
				(IImageOptimizer)(object)new JpegOptimizer(),
				(IImageOptimizer)(object)new PngOptimizer(),
				(IImageOptimizer)(object)new IcoOptimizer(),
				(IImageOptimizer)(object)new GifOptimizer()
			};
		}

		private bool DoLosslessCompress(FileInfo file)
		{
			IImageOptimizer optimizer = GetOptimizer(file);
			if (optimizer == null)
			{
				return false;
			}
			optimizer.OptimalCompression = OptimalCompression;
			return optimizer.LosslessCompress(file);
		}

		private bool DoCompress(FileInfo file)
		{
			IImageOptimizer optimizer = GetOptimizer(file);
			if (optimizer == null)
			{
				return false;
			}
			optimizer.OptimalCompression = OptimalCompression;
			return optimizer.Compress(file);
		}

		private IImageOptimizer? GetOptimizer(FileInfo file)
		{
			IMagickFormatInfo formatInformation = ImageOptimizerHelper.GetFormatInformation(file);
			return GetOptimizer(formatInformation);
		}

		private IImageOptimizer? GetOptimizer(Stream stream)
		{
			IMagickFormatInfo formatInformation = ImageOptimizerHelper.GetFormatInformation(stream);
			return GetOptimizer(formatInformation);
		}

		private IImageOptimizer? GetOptimizer(IMagickFormatInfo? info)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			if (info == null)
			{
				return null;
			}
			foreach (IImageOptimizer optimizer in _optimizers)
			{
				if (optimizer.Format.ModuleFormat == info.ModuleFormat)
				{
					return optimizer;
				}
			}
			if (IgnoreUnsupportedFormats)
			{
				return null;
			}
			string text = string.Join(", ", _optimizers.Select(delegate(IImageOptimizer imageOptizimer)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				MagickFormat moduleFormat = imageOptizimer.Format.ModuleFormat;
				return ((object)(MagickFormat)(ref moduleFormat)).ToString();
			}));
			throw new MagickCorruptImageErrorException("Invalid format, supported formats are: " + text);
		}
	}
	internal static class ImageOptimizerHelper
	{
		public static void CheckFormat(IMagickImage<byte> image, MagickFormat expectedFormat)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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_0028: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			IMagickFormatInfo? obj = MagickFormatInfo.Create(((IMagickImage)image).Format);
			MagickFormat? val = ((obj != null) ? new MagickFormat?(obj.ModuleFormat) : null);
			if (val != (MagickFormat?)expectedFormat)
			{
				throw new MagickCorruptImageErrorException("Invalid image format: " + val.ToString());
			}
		}

		public static void CheckStream(Stream stream)
		{
			Throw.IfNullOrEmpty(stream, "stream");
			Throw.IfFalse(stream.CanRead, "stream", "The stream should be readable.");
			Throw.IfFalse(stream.CanWrite, "stream", "The stream should be writeable.");
			Throw.IfFalse(stream.CanSeek, "stream", "The stream should be seekable.");
		}

		public static IMagickFormatInfo? GetFormatInformation(FileInfo file)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			IMagickFormatInfo val = MagickFormatInfo.Create(file);
			if (val != null)
			{
				return val;
			}
			try
			{
				return MagickFormatInfo.Create(new MagickImageInfo(file).Format);
			}
			catch
			{
				try
				{
					using FileStream stream = file.OpenRead();
					return GetFormatInformationFromHeader(stream);
				}
				catch
				{
					return null;
				}
			}
		}

		public static IMagickFormatInfo? GetFormatInformation(string fileName)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			IMagickFormatInfo val = MagickFormatInfo.Create(fileName);
			if (val != null)
			{
				return val;
			}
			try
			{
				return MagickFormatInfo.Create(new MagickImageInfo(fileName).Format);
			}
			catch
			{
				try
				{
					using FileStream stream = File.OpenRead(fileName);
					return GetFormatInformationFromHeader(stream);
				}
				catch
				{
					return null;
				}
			}
		}

		public static IMagickFormatInfo? GetFormatInformation(Stream stream)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			long position = stream.Position;
			try
			{
				return MagickFormatInfo.Create(new MagickImageInfo(stream).Format);
			}
			catch
			{
				stream.Position = position;
				return GetFormatInformationFromHeader(stream);
			}
			finally
			{
				stream.Position = position;
			}
		}

		private static IMagickFormatInfo? GetFormatInformationFromHeader(Stream stream)
		{
			byte[] array = new byte[4];
			stream.Read(array, 0, array.Length);
			if (array[0] == 0 && array[1] == 0 && array[2] == 1 && array[3] == 0)
			{
				return MagickFormatInfo.Create((MagickFormat)98);
			}
			return null;
		}
	}
	public sealed class MagickFormatInfo : IMagickFormatInfo, IEquatable<IMagickFormatInfo?>
	{
		[NativeInterop]
		private class NativeMagickFormatInfo : ConstNativeInstance
		{
			protected override string TypeName => "MagickFormatInfo";

			[Throws]
			[Cleanup(Name = "DisposeList", Arguments = "length")]
			public static IntPtr CreateList(out nuint length)
			{
				IntPtr exception = IntPtr.Zero;
				IntPtr intPtr = NativeMethods.MagickFormatInfo_CreateList(out length, out exception);
				MagickException val = MagickExceptionHelper.Create(exception);
				if (val is MagickErrorException)
				{
					if (intPtr != IntPtr.Zero)
					{
						DisposeList(intPtr, length);
					}
					throw val;
				}
				return intPtr;
			}

			public static void DisposeList(IntPtr instance, nuint length)
			{
				NativeMethods.MagickFormatInfo_DisposeList(instance, length);
			}

			[Throws]
			public static MagickFormatInfo? GetInfo(IntPtr list, nuint index)
			{
				IntPtr exception = IntPtr.Zero;
				IntPtr instance = NativeMethods.MagickFormatInfo_GetInfo(list, index, out exception);
				MagickExceptionHelper.Check(exception);
				return CreateInstance(instance);
			}

			[Throws]
			public static MagickFormatInfo? GetInfoByName(string name)
			{
				IntPtr exception = IntPtr.Zero;
				using UTF8Marshaler uTF8Marshaler = UTF8Marshaler.CreateInstance(name);
				IntPtr instance = NativeMethods.MagickFormatInfo_GetInfoByName(uTF8Marshaler.Instance, out exception);
				MagickExceptionHelper.Check(exception);
				return CreateInstance(instance);
			}

			[Throws]
			public unsafe static MagickFormatInfo? GetInfoWithBlob(byte[] data, nuint length)
			{
				IntPtr exception = IntPtr.Zero;
				fixed (byte* data2 = data)
				{
					IntPtr instance = NativeMethods.MagickFormatInfo_GetInfoWithBlob(data2, length, out exception);
					MagickExceptionHelper.Check(exception);
					return CreateInstance(instance);
				}
			}

			public static bool Unregister(string name)
			{
				using UTF8Marshaler uTF8Marshaler = UTF8Marshaler.CreateInstance(name);
				return NativeMethods.MagickFormatInfo_Unregister(uTF8Marshaler.Instance);
			}

			public string Description_Get()
			{
				return UTF8Marshaler.CreateInstance(NativeMethods.MagickFormatInfo_Description_Get(base.Instance));
			}

			public bool CanReadMultithreaded_Get()
			{
				return NativeMethods.MagickFormatInfo_CanReadMultithreaded_Get(base.Instance);
			}

			public bool CanWriteMultithreaded_Get()
			{
				return NativeMethods.MagickFormatInfo_CanWriteMultithreaded_Get(base.Instance);
			}

			public string Format_Get()
			{
				return UTF8Marshaler.CreateInstance(NativeMethods.MagickFormatInfo_Format_Get(base.Instance));
			}

			public bool SupportsMultipleFrames_Get()
			{
				return NativeMethods.MagickFormatInfo_SupportsMultipleFrames_Get(base.Instance);
			}

			public bool SupportsReading_Get()
			{
				return NativeMethods.MagickFormatInfo_SupportsReading_Get(base.Instance);
			}

			public bool SupportsWriting_Get()
			{
				return NativeMethods.MagickFormatInfo_SupportsWriting_Get(base.Instance);
			}

			public string? MimeType_Get()
			{
				return UTF8Marshaler.CreateNullableInstance(NativeMethods.MagickFormatInfo_MimeType_Get(base.Instance));
			}

			public string Module_Get()
			{
				return UTF8Marshaler.CreateInstance(NativeMethods.MagickFormatInfo_Module_Get(base.Instance));
			}

			static NativeMagickFormatInfo()
			{
				Environment.Initialize();
			}

			public NativeMagickFormatInfo(IntPtr instance)
			{
				base.Instance = instance;
			}
		}

		private static class NativeMethods
		{
			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickFormatInfo_CreateList(out nuint length, out IntPtr exception);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern void MagickFormatInfo_DisposeList(IntPtr instance, nuint length);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickFormatInfo_GetInfo(IntPtr list, nuint index, out IntPtr exception);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickFormatInfo_GetInfoByName(IntPtr name, out IntPtr exception);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public unsafe static extern IntPtr MagickFormatInfo_GetInfoWithBlob(byte* data, nuint length, out IntPtr exception);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickFormatInfo_Unregister(IntPtr name);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickFormatInfo_Description_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickFormatInfo_CanReadMultithreaded_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickFormatInfo_CanWriteMultithreaded_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickFormatInfo_Format_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickFormatInfo_SupportsMultipleFrames_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickFormatInfo_SupportsReading_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern bool MagickFormatInfo_SupportsWriting_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickFormatInfo_MimeType_Get(IntPtr instance);

			[DllImport("Magick.Native-Q8-x64.dll", CallingConvention = CallingConvention.Cdecl)]
			public static extern IntPtr MagickFormatInfo_Module_Get(IntPtr instance);
		}

		private static readonly Dictionary<MagickFormat, IMagickFormatInfo> _all = LoadFormats();

		public bool CanReadMultithreaded { get; }

		public bool CanWriteMultithreaded { get; }

		public string? Description { get; }

		public MagickFormat Format { get; }

		public string? MimeType { get; }

		public MagickFormat ModuleFormat { get; }

		public bool SupportsMultipleFrames { get; }

		public bool SupportsReading { get; }

		public bool SupportsWriting { get; }

		internal static IReadOnlyCollection<IMagickFormatInfo> All => _all.Values;

		private MagickFormatInfo(NativeMagickFormatInfo instance)
		{
			//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_0072: 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)
			Format = GetFormat(instance.Format_Get());
			Description = instance.Description_Get();
			CanReadMultithreaded = instance.CanReadMultithreaded_Get();
			CanWriteMultithreaded = instance.CanWriteMultithreaded_Get();
			SupportsMultipleFrames = instance.SupportsMultipleFrames_Get();
			SupportsReading = instance.SupportsReading_Get();
			SupportsWriting = instance.SupportsWriting_Get();
			MimeType = instance.MimeType_Get();
			ModuleFormat = GetFormat(instance.Module_Get());
		}

		public static IMagickFormatInfo? Create(FileInfo file)
		{
			//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_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)
			Throw.IfNull(file, "file");
			MagickFormat val = EnumHelper.ParseMagickFormatFromExtension(file);
			if ((int)val == 0)
			{
				return null;
			}
			return Create(val);
		}

		public static IMagickFormatInfo? Create(MagickFormat format)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (!_all.ContainsKey(format))
			{
				return null;
			}
			return _all[format];
		}

		public static IMagickFormatInfo? Create(byte[] data)
		{
			Throw.IfNullOrEmpty(data, "data");
			return (IMagickFormatInfo?)(object)NativeMagickFormatInfo.GetInfoWithBlob(data, (uint)data.Length);
		}

		public static IMagickFormatInfo? Create(string fileName)
		{
			return Create(new FileInfo(FileHelper.CheckForBaseDirectory(fileName)));
		}

		public override bool Equals(object? obj)
		{
			return Equals((IMagickFormatInfo?)((obj is IMagickFormatInfo) ? obj : null));
		}

		public bool Equals(IMagickFormatInfo? other)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (other == null)
			{
				return false;
			}
			if (this == other)
			{
				return true;
			}
			return Format == other.Format;
		}

		public override int GetHashCode()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			MagickFormat moduleFormat = ModuleFormat;
			return ((object)(MagickFormat)(ref moduleFormat)).GetHashCode();
		}

		public override string ToString()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return string.Format(CultureInfo.InvariantCulture, "{0}: {1} ({2}R{3}W{4}M)", Format, Description, SupportsReading ? "+" : "-", SupportsWriting ? "+" : "-", SupportsMultipleFrames ? "+" : "-");
		}

		public bool Unregister()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return NativeMagickFormatInfo.Unregiste

Magick.NET.Core.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
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 System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using ImageMagick.Configuration;
using ImageMagick.Drawing;
using ImageMagick.SourceGenerator;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Dirk Lemstra")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2013-2025 Dirk Lemstra")]
[assembly: AssemblyFileVersion("14.5.0")]
[assembly: AssemblyInformationalVersion("14.5.0+0e6c26312fcd82ede604119187c3e1be1612e9c7")]
[assembly: AssemblyProduct("Magick.NET.Core")]
[assembly: AssemblyTitle("Magick.NET.Core")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("14.5.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
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]
	[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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
}
namespace ImageMagick
{
	public interface IMagickColors<TQuantumType> where TQuantumType : struct, IConvertible
	{
		IMagickColor<TQuantumType> None { get; }

		IMagickColor<TQuantumType> Transparent { get; }

		IMagickColor<TQuantumType> AliceBlue { get; }

		IMagickColor<TQuantumType> AntiqueWhite { get; }

		IMagickColor<TQuantumType> Aqua { get; }

		IMagickColor<TQuantumType> Aquamarine { get; }

		IMagickColor<TQuantumType> Azure { get; }

		IMagickColor<TQuantumType> Beige { get; }

		IMagickColor<TQuantumType> Bisque { get; }

		IMagickColor<TQuantumType> Black { get; }

		IMagickColor<TQuantumType> BlanchedAlmond { get; }

		IMagickColor<TQuantumType> Blue { get; }

		IMagickColor<TQuantumType> BlueViolet { get; }

		IMagickColor<TQuantumType> Brown { get; }

		IMagickColor<TQuantumType> BurlyWood { get; }

		IMagickColor<TQuantumType> CadetBlue { get; }

		IMagickColor<TQuantumType> Chartreuse { get; }

		IMagickColor<TQuantumType> Chocolate { get; }

		IMagickColor<TQuantumType> Coral { get; }

		IMagickColor<TQuantumType> CornflowerBlue { get; }

		IMagickColor<TQuantumType> Cornsilk { get; }

		IMagickColor<TQuantumType> Crimson { get; }

		IMagickColor<TQuantumType> Cyan { get; }

		IMagickColor<TQuantumType> DarkBlue { get; }

		IMagickColor<TQuantumType> DarkCyan { get; }

		IMagickColor<TQuantumType> DarkGoldenrod { get; }

		IMagickColor<TQuantumType> DarkGray { get; }

		IMagickColor<TQuantumType> DarkGreen { get; }

		IMagickColor<TQuantumType> DarkKhaki { get; }

		IMagickColor<TQuantumType> DarkMagenta { get; }

		IMagickColor<TQuantumType> DarkOliveGreen { get; }

		IMagickColor<TQuantumType> DarkOrange { get; }

		IMagickColor<TQuantumType> DarkOrchid { get; }

		IMagickColor<TQuantumType> DarkRed { get; }

		IMagickColor<TQuantumType> DarkSalmon { get; }

		IMagickColor<TQuantumType> DarkSeaGreen { get; }

		IMagickColor<TQuantumType> DarkSlateBlue { get; }

		IMagickColor<TQuantumType> DarkSlateGray { get; }

		IMagickColor<TQuantumType> DarkTurquoise { get; }

		IMagickColor<TQuantumType> DarkViolet { get; }

		IMagickColor<TQuantumType> DeepPink { get; }

		IMagickColor<TQuantumType> DeepSkyBlue { get; }

		IMagickColor<TQuantumType> DimGray { get; }

		IMagickColor<TQuantumType> DodgerBlue { get; }

		IMagickColor<TQuantumType> Firebrick { get; }

		IMagickColor<TQuantumType> FloralWhite { get; }

		IMagickColor<TQuantumType> ForestGreen { get; }

		IMagickColor<TQuantumType> Fuchsia { get; }

		IMagickColor<TQuantumType> Gainsboro { get; }

		IMagickColor<TQuantumType> GhostWhite { get; }

		IMagickColor<TQuantumType> Gold { get; }

		IMagickColor<TQuantumType> Goldenrod { get; }

		IMagickColor<TQuantumType> Gray { get; }

		IMagickColor<TQuantumType> Green { get; }

		IMagickColor<TQuantumType> GreenYellow { get; }

		IMagickColor<TQuantumType> Honeydew { get; }

		IMagickColor<TQuantumType> HotPink { get; }

		IMagickColor<TQuantumType> IndianRed { get; }

		IMagickColor<TQuantumType> Indigo { get; }

		IMagickColor<TQuantumType> Ivory { get; }

		IMagickColor<TQuantumType> Khaki { get; }

		IMagickColor<TQuantumType> Lavender { get; }

		IMagickColor<TQuantumType> LavenderBlush { get; }

		IMagickColor<TQuantumType> LawnGreen { get; }

		IMagickColor<TQuantumType> LemonChiffon { get; }

		IMagickColor<TQuantumType> LightBlue { get; }

		IMagickColor<TQuantumType> LightCoral { get; }

		IMagickColor<TQuantumType> LightCyan { get; }

		IMagickColor<TQuantumType> LightGoldenrodYellow { get; }

		IMagickColor<TQuantumType> LightGreen { get; }

		IMagickColor<TQuantumType> LightGray { get; }

		IMagickColor<TQuantumType> LightPink { get; }

		IMagickColor<TQuantumType> LightSalmon { get; }

		IMagickColor<TQuantumType> LightSeaGreen { get; }

		IMagickColor<TQuantumType> LightSkyBlue { get; }

		IMagickColor<TQuantumType> LightSlateGray { get; }

		IMagickColor<TQuantumType> LightSteelBlue { get; }

		IMagickColor<TQuantumType> LightYellow { get; }

		IMagickColor<TQuantumType> Lime { get; }

		IMagickColor<TQuantumType> LimeGreen { get; }

		IMagickColor<TQuantumType> Linen { get; }

		IMagickColor<TQuantumType> Magenta { get; }

		IMagickColor<TQuantumType> Maroon { get; }

		IMagickColor<TQuantumType> MediumAquamarine { get; }

		IMagickColor<TQuantumType> MediumBlue { get; }

		IMagickColor<TQuantumType> MediumOrchid { get; }

		IMagickColor<TQuantumType> MediumPurple { get; }

		IMagickColor<TQuantumType> MediumSeaGreen { get; }

		IMagickColor<TQuantumType> MediumSlateBlue { get; }

		IMagickColor<TQuantumType> MediumSpringGreen { get; }

		IMagickColor<TQuantumType> MediumTurquoise { get; }

		IMagickColor<TQuantumType> MediumVioletRed { get; }

		IMagickColor<TQuantumType> MidnightBlue { get; }

		IMagickColor<TQuantumType> MintCream { get; }

		IMagickColor<TQuantumType> MistyRose { get; }

		IMagickColor<TQuantumType> Moccasin { get; }

		IMagickColor<TQuantumType> NavajoWhite { get; }

		IMagickColor<TQuantumType> Navy { get; }

		IMagickColor<TQuantumType> OldLace { get; }

		IMagickColor<TQuantumType> Olive { get; }

		IMagickColor<TQuantumType> OliveDrab { get; }

		IMagickColor<TQuantumType> Orange { get; }

		IMagickColor<TQuantumType> OrangeRed { get; }

		IMagickColor<TQuantumType> Orchid { get; }

		IMagickColor<TQuantumType> PaleGoldenrod { get; }

		IMagickColor<TQuantumType> PaleGreen { get; }

		IMagickColor<TQuantumType> PaleTurquoise { get; }

		IMagickColor<TQuantumType> PaleVioletRed { get; }

		IMagickColor<TQuantumType> PapayaWhip { get; }

		IMagickColor<TQuantumType> PeachPuff { get; }

		IMagickColor<TQuantumType> Peru { get; }

		IMagickColor<TQuantumType> Pink { get; }

		IMagickColor<TQuantumType> Plum { get; }

		IMagickColor<TQuantumType> PowderBlue { get; }

		IMagickColor<TQuantumType> Purple { get; }

		IMagickColor<TQuantumType> RebeccaPurple { get; }

		IMagickColor<TQuantumType> Red { get; }

		IMagickColor<TQuantumType> RosyBrown { get; }

		IMagickColor<TQuantumType> RoyalBlue { get; }

		IMagickColor<TQuantumType> SaddleBrown { get; }

		IMagickColor<TQuantumType> Salmon { get; }

		IMagickColor<TQuantumType> SandyBrown { get; }

		IMagickColor<TQuantumType> SeaGreen { get; }

		IMagickColor<TQuantumType> SeaShell { get; }

		IMagickColor<TQuantumType> Sienna { get; }

		IMagickColor<TQuantumType> Silver { get; }

		IMagickColor<TQuantumType> SkyBlue { get; }

		IMagickColor<TQuantumType> SlateBlue { get; }

		IMagickColor<TQuantumType> SlateGray { get; }

		IMagickColor<TQuantumType> Snow { get; }

		IMagickColor<TQuantumType> SpringGreen { get; }

		IMagickColor<TQuantumType> SteelBlue { get; }

		IMagickColor<TQuantumType> Tan { get; }

		IMagickColor<TQuantumType> Teal { get; }

		IMagickColor<TQuantumType> Thistle { get; }

		IMagickColor<TQuantumType> Tomato { get; }

		IMagickColor<TQuantumType> Turquoise { get; }

		IMagickColor<TQuantumType> Violet { get; }

		IMagickColor<TQuantumType> Wheat { get; }

		IMagickColor<TQuantumType> White { get; }

		IMagickColor<TQuantumType> WhiteSmoke { get; }

		IMagickColor<TQuantumType> Yellow { get; }

		IMagickColor<TQuantumType> YellowGreen { get; }
	}
	public interface IMagickColor<TQuantumType> : IEquatable<IMagickColor<TQuantumType>?>, IComparable<IMagickColor<TQuantumType>?> where TQuantumType : struct, IConvertible
	{
		TQuantumType A { get; set; }

		TQuantumType B { get; set; }

		TQuantumType G { get; set; }

		bool IsCmyk { get; }

		TQuantumType K { get; set; }

		TQuantumType R { get; set; }

		bool FuzzyEquals(IMagickColor<TQuantumType> other, Percentage fuzz);

		void SetFromBytes(byte red, byte green, byte blue, byte alpha);

		byte[] ToByteArray();

		string ToHexString();

		string ToShortString();

		new string ToString();
	}
	public interface IDefine
	{
		MagickFormat Format { get; }

		string Name { get; }

		string Value { get; }
	}
	public interface IDefines
	{
		IEnumerable<IDefine> Defines { get; }
	}
	public interface IReadDefines : IDefines
	{
		MagickFormat Format { get; }
	}
	public interface IWriteDefines : IDefines
	{
		MagickFormat Format { get; }
	}
	public enum AlphaOption
	{
		Undefined,
		Activate,
		Associate,
		Background,
		Copy,
		Deactivate,
		Discrete,
		Disassociate,
		Extract,
		Off,
		On,
		Opaque,
		Remove,
		Set,
		Shape,
		Transparent,
		OffIfOpaque
	}
	public enum AutoThresholdMethod
	{
		Undefined,
		Kapur,
		OTSU,
		Triangle
	}
	[Flags]
	public enum Channels : ulong
	{
		Undefined = 0uL,
		Red = 1uL,
		Gray = 1uL,
		Cyan = 1uL,
		Green = 2uL,
		Magenta = 2uL,
		Blue = 4uL,
		Yellow = 4uL,
		Black = 8uL,
		Alpha = 0x10uL,
		Opacity = 0x10uL,
		Index = 0x20uL,
		Composite = 0x1FuL,
		TrueAlpha = 0x100uL,
		RGB = 7uL,
		RGBA = 0x17uL,
		CMYK = 0xFuL,
		CMYKA = 0x1FuL,
		Meta0 = 0x400uL,
		Meta1 = 0x800uL,
		Meta2 = 0x1000uL,
		Meta3 = 0x2000uL,
		Meta4 = 0x4000uL,
		Meta5 = 0x8000uL,
		Meta6 = 0x10000uL,
		Meta7 = 0x20000uL,
		Meta8 = 0x40000uL,
		Meta9 = 0x80000uL,
		Meta10 = 0x100000uL,
		Meta11 = 0x200000uL,
		Meta12 = 0x400000uL,
		Meta13 = 0x800000uL,
		Meta14 = 0x1000000uL,
		Meta15 = 0x2000000uL,
		Meta16 = 0x4000000uL,
		Meta17 = 0x8000000uL,
		Meta18 = 0x10000000uL,
		Meta19 = 0x20000000uL,
		Meta20 = 0x40000000uL,
		Meta21 = 0x80000000uL,
		Meta22 = 0x100000000uL,
		Meta23 = 0x200000000uL,
		Meta24 = 0x400000000uL,
		Meta25 = 0x800000000uL,
		Meta26 = 0x1000000000uL,
		Meta27 = 0x2000000000uL,
		Meta28 = 0x4000000000uL,
		Meta29 = 0x8000000000uL,
		Meta30 = 0x10000000000uL,
		Meta31 = 0x20000000000uL,
		Meta32 = 0x40000000000uL,
		Meta33 = 0x80000000000uL,
		Meta34 = 0x100000000000uL,
		Meta35 = 0x200000000000uL,
		Meta36 = 0x400000000000uL,
		Meta37 = 0x800000000000uL,
		Meta38 = 0x1000000000000uL,
		Meta39 = 0x2000000000000uL,
		Meta40 = 0x4000000000000uL,
		Meta41 = 0x8000000000000uL,
		Meta42 = 0x10000000000000uL,
		Meta43 = 0x20000000000000uL,
		Meta44 = 0x40000000000000uL,
		Meta45 = 0x80000000000000uL,
		Meta46 = 0x100000000000000uL,
		Meta47 = 0x200000000000000uL,
		Meta48 = 0x400000000000000uL,
		Meta49 = 0x800000000000000uL,
		Meta50 = 0x1000000000000000uL,
		Meta51 = 0x2000000000000000uL,
		Meta52 = 0x4000000000000000uL,
		All = 0x7FFFFFFFFFFFFFFFuL
	}
	public enum ClassType
	{
		Undefined,
		Direct,
		Pseudo
	}
	public enum ClipPathUnit
	{
		Undefined,
		UserSpace,
		UserSpaceOnUse,
		ObjectBoundingBox
	}
	public enum ColorSpace
	{
		Undefined,
		CMY,
		CMYK,
		Gray,
		HCL,
		HCLp,
		HSB,
		HSI,
		HSL,
		HSV,
		HWB,
		Lab,
		LCH,
		LCHab,
		LCHuv,
		Log,
		LMS,
		Luv,
		OHTA,
		Rec601YCbCr,
		Rec709YCbCr,
		RGB,
		scRGB,
		sRGB,
		Transparent,
		XyY,
		XYZ,
		YCbCr,
		YCC,
		YDbDr,
		YIQ,
		YPbPr,
		YUV,
		LinearGray,
		Jzazbz,
		DisplayP3,
		Adobe98,
		ProPhoto,
		Oklab,
		Oklch,
		CAT02LMSC
	}
	public enum ColorTransformMode
	{
		HighRes,
		Quantum
	}
	public enum ColorType
	{
		Undefined,
		Bilevel,
		Grayscale,
		GrayscaleAlpha,
		Palette,
		PaletteAlpha,
		TrueColor,
		TrueColorAlpha,
		ColorSeparation,
		ColorSeparationAlpha,
		Optimize,
		PaletteBilevelAlpha
	}
	public enum ComplexOperator
	{
		Undefined,
		Add,
		Conjugate,
		Divide,
		MagnitudePhase,
		Multiply,
		RealImaginary,
		Subtract
	}
	public enum CompositeOperator
	{
		Undefined,
		Alpha,
		Atop,
		Blend,
		Blur,
		Bumpmap,
		ChangeMask,
		Clear,
		ColorBurn,
		ColorDodge,
		Colorize,
		CopyBlack,
		CopyBlue,
		Copy,
		CopyCyan,
		CopyGreen,
		CopyMagenta,
		CopyAlpha,
		CopyRed,
		CopyYellow,
		Darken,
		DarkenIntensity,
		Difference,
		Displace,
		Dissolve,
		Distort,
		DivideDst,
		DivideSrc,
		DstAtop,
		Dst,
		DstIn,
		DstOut,
		DstOver,
		Exclusion,
		HardLight,
		HardMix,
		Hue,
		In,
		Intensity,
		Lighten,
		LightenIntensity,
		LinearBurn,
		LinearDodge,
		LinearLight,
		Luminize,
		Mathematics,
		MinusDst,
		MinusSrc,
		Modulate,
		ModulusAdd,
		ModulusSubtract,
		Multiply,
		No,
		Out,
		Over,
		Overlay,
		PegtopLight,
		PinLight,
		Plus,
		Replace,
		Saturate,
		Screen,
		SoftLight,
		SrcAtop,
		Src,
		SrcIn,
		SrcOut,
		SrcOver,
		Threshold,
		VividLight,
		Xor,
		Stereo,
		Freeze,
		Interpolate,
		Negate,
		Reflect,
		SoftBurn,
		SoftDodge,
		Stamp,
		RMSE,
		SaliencyBlend,
		SeamlessBlend
	}
	public enum CompressionMethod
	{
		Undefined,
		B44A,
		B44,
		BZip,
		DXT1,
		DXT3,
		DXT5,
		Fax,
		Group4,
		JBIG1,
		JBIG2,
		JPEG2000,
		JPEG,
		LosslessJPEG,
		LZMA,
		LZW,
		NoCompression,
		Piz,
		Pxr24,
		RLE,
		Zip,
		ZipS,
		Zstd,
		WebP,
		DWAA,
		DWAB,
		BC7,
		BC5,
		LERC
	}
	public enum DensityUnit
	{
		Undefined,
		PixelsPerInch,
		PixelsPerCentimeter
	}
	public enum DistortMethod
	{
		Undefined,
		Affine,
		AffineProjection,
		ScaleRotateTranslate,
		Perspective,
		PerspectiveProjection,
		BilinearForward,
		BilinearReverse,
		Polynomial,
		Arc,
		Polar,
		DePolar,
		Cylinder2Plane,
		Plane2Cylinder,
		Barrel,
		BarrelInverse,
		Shepards,
		Resize,
		Sentinel,
		RigidAffine
	}
	public enum DitherMethod
	{
		Undefined,
		No,
		Riemersma,
		FloydSteinberg
	}
	public enum Endian
	{
		Undefined,
		LSB,
		MSB
	}
	public enum ErrorMetric
	{
		Undefined,
		Absolute,
		Fuzz,
		MeanAbsolute,
		MeanErrorPerPixel,
		MeanSquared,
		NormalizedCrossCorrelation,
		PeakAbsolute,
		PeakSignalToNoiseRatio,
		PerceptualHash,
		RootMeanSquared,
		StructuralSimilarity,
		StructuralDissimilarity
	}
	public enum EvaluateFunction
	{
		Undefined,
		Arcsin,
		Arctan,
		Polynomial,
		Sinusoid
	}
	public enum EvaluateOperator
	{
		Undefined,
		Abs,
		Add,
		AddModulus,
		And,
		Cosine,
		Divide,
		Exponential,
		GaussianNoise,
		ImpulseNoise,
		LaplacianNoise,
		LeftShift,
		Log,
		Max,
		Mean,
		Median,
		Min,
		MultiplicativeNoise,
		Multiply,
		Or,
		PoissonNoise,
		Pow,
		RightShift,
		RootMeanSquare,
		Set,
		Sine,
		Subtract,
		Sum,
		ThresholdBlack,
		Threshold,
		ThresholdWhite,
		UniformNoise,
		Xor,
		InverseLog
	}
	public enum FillRule
	{
		Undefined,
		EvenOdd,
		Nonzero
	}
	public enum FilterType
	{
		Undefined,
		Point,
		Box,
		Triangle,
		Hermite,
		Hann,
		Hamming,
		Blackman,
		Gaussian,
		Quadratic,
		Cubic,
		Catrom,
		Mitchell,
		Jinc,
		Sinc,
		SincFast,
		Kaiser,
		Welch,
		Parzen,
		Bohman,
		Bartlett,
		Lagrange,
		Lanczos,
		LanczosSharp,
		Lanczos2,
		Lanczos2Sharp,
		Robidoux,
		RobidouxSharp,
		Cosine,
		Spline,
		LanczosRadius,
		CubicSpline,
		MagicKernelSharp2013,
		MagicKernelSharp2021
	}
	public enum FontStretch
	{
		Undefined,
		Normal,
		UltraCondensed,
		ExtraCondensed,
		Condensed,
		SemiCondensed,
		SemiExpanded,
		Expanded,
		ExtraExpanded,
		UltraExpanded,
		Any
	}
	public enum FontStyleType
	{
		Undefined,
		Normal,
		Italic,
		Oblique,
		Any,
		Bold
	}
	public enum FontWeight
	{
		Undefined = 0,
		Thin = 100,
		ExtraLight = 200,
		UltraLight = 200,
		Light = 300,
		Normal = 400,
		Regular = 400,
		Medium = 500,
		DemiBold = 600,
		SemiBold = 600,
		Bold = 700,
		ExtraBold = 800,
		UltraBold = 800,
		Heavy = 900,
		Black = 900
	}
	public enum GifDisposeMethod
	{
		Undefined,
		None,
		Background,
		Previous
	}
	public enum Gravity
	{
		Undefined = 0,
		Forget = 0,
		Northwest = 1,
		North = 2,
		Northeast = 3,
		West = 4,
		Center = 5,
		East = 6,
		Southwest = 7,
		South = 8,
		Southeast = 9
	}
	public enum Interlace
	{
		Undefined,
		NoInterlace,
		Line,
		Plane,
		Partition,
		Gif,
		Jpeg,
		Png
	}
	public enum Kernel
	{
		Undefined,
		Unity,
		Gaussian,
		DoG,
		LoG,
		Blur,
		Comet,
		Binomial,
		Laplacian,
		Sobel,
		FreiChen,
		Roberts,
		Prewitt,
		Compass,
		Kirsch,
		Diamond,
		Square,
		Rectangle,
		Octagon,
		Disk,
		Plus,
		Cross,
		Ring,
		Peaks,
		Edges,
		Corners,
		Diagonals,
		LineEnds,
		LineJunctions,
		Ridges,
		ConvexHull,
		ThinSE,
		Skeleton,
		Chebyshev,
		Manhattan,
		Octagonal,
		Euclidean,
		UserDefined
	}
	public enum LineCap
	{
		Undefined,
		Butt,
		Round,
		Square
	}
	public enum LineJoin
	{
		Undefined,
		Miter,
		Round,
		Bevel
	}
	[Flags]
	public enum LogEventTypes
	{
		None = 0,
		Accelerate = 1,
		Annotate = 2,
		Blob = 4,
		Cache = 8,
		Coder = 0x10,
		Configure = 0x20,
		Deprecate = 0x40,
		Draw = 0x80,
		Exception = 0x100,
		Image = 0x200,
		Locale = 0x400,
		Module = 0x800,
		Pixel = 0x1000,
		Policy = 0x2000,
		Resource = 0x4000,
		Trace = 0x8000,
		Transform = 0x10000,
		User = 0x20000,
		Wand = 0x40000,
		Detailed = 0x7FFF7FFF,
		All = int.MaxValue
	}
	public enum MagickFormat
	{
		Unknown,
		ThreeFr,
		ThreeG2,
		ThreeGp,
		A,
		Aai,
		Ai,
		APng,
		Art,
		Arw,
		Ashlar,
		Avi,
		Avif,
		Avs,
		B,
		Bayer,
		Bayera,
		Bgr,
		Bgra,
		Bgro,
		Bmp,
		Bmp2,
		Bmp3,
		Brf,
		C,
		Cal,
		Cals,
		Canvas,
		Caption,
		Cin,
		Cip,
		Clip,
		Clipboard,
		Cmyk,
		Cmyka,
		Cr2,
		Cr3,
		Crw,
		Cube,
		Cur,
		Cut,
		Data,
		Dcm,
		Dcr,
		Dcraw,
		Dcx,
		Dds,
		Dfont,
		Dib,
		Dng,
		Dpx,
		Dxt1,
		Dxt5,
		Emf,
		Epdf,
		Epi,
		Eps,
		Eps2,
		Eps3,
		Epsf,
		Epsi,
		Ept,
		Ept2,
		Ept3,
		Erf,
		Exr,
		Farbfeld,
		Fax,
		Ff,
		Fff,
		File,
		Fits,
		Fl32,
		Flv,
		Fractal,
		Ftp,
		Fts,
		Ftxt,
		G,
		G3,
		G4,
		Gif,
		Gif87,
		Gradient,
		Gray,
		Graya,
		Group4,
		Hald,
		Hdr,
		Heic,
		Heif,
		Histogram,
		Hrz,
		Htm,
		Html,
		Http,
		Https,
		Icb,
		Ico,
		Icon,
		Iiq,
		Info,
		Inline,
		Ipl,
		Isobrl,
		Isobrl6,
		J2c,
		J2k,
		Jng,
		Jnx,
		Jp2,
		Jpc,
		Jpe,
		Jpeg,
		Jpg,
		Jpm,
		Jps,
		Jpt,
		Json,
		Jxl,
		K,
		K25,
		Kdc,
		Label,
		M,
		M2v,
		M4v,
		Mac,
		Map,
		Mask,
		Mat,
		Matte,
		Mdc,
		Mef,
		Miff,
		Mkv,
		Mng,
		Mono,
		Mos,
		Mov,
		Mp4,
		Mpc,
		Mpeg,
		Mpg,
		Mpo,
		Mrw,
		Msl,
		Msvg,
		Mtv,
		Mvg,
		Nef,
		Nrw,
		Null,
		O,
		Ora,
		Orf,
		Otb,
		Otf,
		Pal,
		Palm,
		Pam,
		Pango,
		Pattern,
		Pbm,
		Pcd,
		Pcds,
		Pcl,
		Pct,
		Pcx,
		Pdb,
		Pdf,
		Pdfa,
		Pef,
		Pes,
		Pfa,
		Pfb,
		Pfm,
		Pgx,
		Pgm,
		Phm,
		Picon,
		Pict,
		Pix,
		Pjpeg,
		Plasma,
		Png,
		Png00,
		Png24,
		Png32,
		Png48,
		Png64,
		Png8,
		Pnm,
		Pocketmod,
		Ppm,
		Ps,
		Ps2,
		Ps3,
		Psb,
		Psd,
		Ptif,
		Pwp,
		Qoi,
		R,
		RadialGradient,
		Raf,
		Ras,
		Raw,
		Rgb,
		Rgb565,
		Rgba,
		Rgbo,
		Rgf,
		Rla,
		Rle,
		Rmf,
		Rsvg,
		Rw2,
		Rwl,
		Scr,
		Screenshot,
		Sct,
		Sfw,
		Sgi,
		Shtml,
		Six,
		Sixel,
		SparseColor,
		Sr2,
		Srf,
		Srw,
		Stegano,
		Sti,
		StrImg,
		Sun,
		Svg,
		Svgz,
		Text,
		Tga,
		Thumbnail,
		Tif,
		Tiff,
		Tiff64,
		Tile,
		Tim,
		Tm2,
		Ttc,
		Ttf,
		Txt,
		Ubrl,
		Ubrl6,
		Uil,
		Uyvy,
		Vda,
		Vicar,
		Vid,
		WebM,
		Viff,
		Vips,
		Vst,
		WebP,
		Wbmp,
		Wmf,
		Wmv,
		Wpg,
		X3f,
		Xbm,
		Xc,
		Xcf,
		Xpm,
		Xps,
		Xv,
		Y,
		Yaml,
		Ycbcr,
		Ycbcra,
		Yuv,
		Avci
	}
	public enum MorphologyMethod
	{
		Undefined,
		Convolve,
		Correlate,
		Erode,
		Dilate,
		ErodeIntensity,
		DilateIntensity,
		IterativeDistance,
		Open,
		Close,
		OpenIntensity,
		CloseIntensity,
		Smooth,
		EdgeIn,
		EdgeOut,
		Edge,
		TopHat,
		BottomHat,
		HitAndMiss,
		Thinning,
		Thicken,
		Distance,
		Voronoi
	}
	public enum NoiseType
	{
		Undefined,
		Uniform,
		Gaussian,
		MultiplicativeGaussian,
		Impulse,
		Laplacian,
		Poisson,
		Random
	}
	public enum OpenCLDeviceType
	{
		Undefined,
		Cpu,
		Gpu
	}
	public enum OrientationType
	{
		Undefined,
		TopLeft,
		TopRight,
		BottomRight,
		BottomLeft,
		LeftTop,
		RightTop,
		RightBottom,
		LeftBottom
	}
	public enum PaintMethod
	{
		Undefined,
		Point,
		Replace,
		Floodfill,
		FillToBorder,
		Reset
	}
	public enum PixelChannel
	{
		Red = 0,
		Cyan = 0,
		Gray = 0,
		Green = 1,
		Magenta = 1,
		Blue = 2,
		Yellow = 2,
		Black = 3,
		Alpha = 4,
		Index = 5,
		Meta0 = 10,
		Meta1 = 11,
		Meta2 = 12,
		Meta3 = 13,
		Meta4 = 14,
		Meta5 = 15,
		Meta6 = 16,
		Meta7 = 17,
		Meta8 = 18,
		Meta9 = 19,
		Meta10 = 20,
		Meta11 = 21,
		Meta12 = 22,
		Meta13 = 23,
		Meta14 = 24,
		Meta15 = 25,
		Meta16 = 26,
		Meta17 = 27,
		Meta18 = 28,
		Meta19 = 29,
		Meta20 = 30,
		Meta21 = 31,
		Meta22 = 32,
		Meta23 = 33,
		Meta24 = 34,
		Meta25 = 35,
		Meta26 = 36,
		Meta27 = 37,
		Meta28 = 38,
		Meta29 = 39,
		Meta30 = 40,
		Meta31 = 41,
		Meta32 = 42,
		Meta33 = 43,
		Meta34 = 44,
		Meta35 = 45,
		Meta36 = 46,
		Meta37 = 47,
		Meta38 = 48,
		Meta39 = 49,
		Meta40 = 50,
		Meta41 = 51,
		Meta42 = 52,
		Meta43 = 53,
		Meta44 = 54,
		Meta45 = 55,
		Meta46 = 56,
		Meta47 = 57,
		Meta48 = 58,
		Meta49 = 59,
		Meta50 = 60,
		Meta51 = 61,
		Meta52 = 62,
		Composite = 64
	}
	public enum PixelIntensityMethod
	{
		Undefined,
		Average,
		Brightness,
		Lightness,
		MS,
		Rec601Luma,
		Rec601Luminance,
		Rec709Luma,
		Rec709Luminance,
		RMS
	}
	public enum PixelInterpolateMethod
	{
		Undefined,
		Average,
		Average9,
		Average16,
		Background,
		Bilinear,
		Blend,
		Catrom,
		Integer,
		Mesh,
		Nearest,
		Spline
	}
	public enum PixelMapping
	{
		ABGR,
		ARGB,
		CMYK,
		CMYKA,
		BGR,
		BGRA,
		RGB,
		RGBA
	}
	public enum RenderingIntent
	{
		Undefined,
		Saturation,
		Perceptual,
		Absolute,
		Relative
	}
	public enum SparseColorMethod
	{
		Undefined = 0,
		Barycentric = 1,
		Bilinear = 7,
		Polynomial = 8,
		Shepards = 16,
		Voronoi = 18,
		Inverse = 19,
		Manhattan = 20
	}
	public enum StatisticType
	{
		Undefined,
		Gradient,
		Maximum,
		Mean,
		Median,
		Minimum,
		Mode,
		Nonpeak,
		RootMeanSquare,
		StandardDeviation
	}
	public enum StorageType
	{
		Undefined,
		Char,
		Double,
		Float,
		Int32,
		Int64,
		Quantum,
		Short
	}
	public enum TextAlignment
	{
		Undefined,
		Left,
		Center,
		Right
	}
	public enum TextDecoration
	{
		Undefined,
		None,
		Underline,
		Overline,
		LineThrough
	}
	public enum TextDirection
	{
		Undefined,
		RightToLeft,
		LeftToRight
	}
	public enum VirtualPixelMethod
	{
		Undefined,
		Background,
		Dither,
		Edge,
		Mirror,
		Random,
		Tile,
		Transparent,
		Mask,
		Black,
		Gray,
		White,
		HorizontalTile,
		VerticalTile,
		HorizontalTileEdge,
		VerticalTileEdge,
		CheckerTile
	}
	public sealed class LogEventArgs : EventArgs
	{
		public LogEventTypes EventType { get; }

		public string Message { get; }

		public LogEventArgs(LogEventTypes eventType, string message)
		{
			EventType = eventType;
			Message = message;
			base..ctor();
		}
	}
	public sealed class ProgressEventArgs : EventArgs
	{
		public string? Origin { get; }

		public Percentage Progress { get; }

		public bool Cancel { get; set; }

		public ProgressEventArgs(string? origin, int offset, int extent)
		{
			Origin = origin;
			Progress = new Percentage((double)(offset + 1) / (double)extent * 100.0);
			base..ctor();
		}
	}
	public sealed class WarningEventArgs : EventArgs
	{
		public string Message => Exception.Message;

		public MagickWarningException Exception { get; }

		public WarningEventArgs(MagickWarningException exception)
		{
			Exception = exception;
			base..ctor();
		}
	}
	public sealed class MagickBlobErrorException : MagickErrorException
	{
		public MagickBlobErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickCacheErrorException : MagickErrorException
	{
		public MagickCacheErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickCoderErrorException : MagickErrorException
	{
		public MagickCoderErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickConfigureErrorException : MagickErrorException
	{
		public MagickConfigureErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickCorruptImageErrorException : MagickErrorException
	{
		public MagickCorruptImageErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickDelegateErrorException : MagickErrorException
	{
		public MagickDelegateErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickDrawErrorException : MagickErrorException
	{
		public MagickDrawErrorException(string message)
			: base(message)
		{
		}
	}
	public class MagickErrorException : MagickException
	{
		public MagickErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickFileOpenErrorException : MagickErrorException
	{
		public MagickFileOpenErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickImageErrorException : MagickErrorException
	{
		public MagickImageErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickMissingDelegateErrorException : MagickErrorException
	{
		public MagickMissingDelegateErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickModuleErrorException : MagickErrorException
	{
		public MagickModuleErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickOptionErrorException : MagickErrorException
	{
		public MagickOptionErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickPolicyErrorException : MagickErrorException
	{
		public MagickPolicyErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickRegistryErrorException : MagickErrorException
	{
		public MagickRegistryErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickResourceLimitErrorException : MagickErrorException
	{
		public MagickResourceLimitErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickStreamErrorException : MagickErrorException
	{
		public MagickStreamErrorException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickTypeErrorException : MagickErrorException
	{
		public MagickTypeErrorException(string message)
			: base(message)
		{
		}
	}
	public abstract class MagickException : Exception
	{
		private List<MagickException>? _relatedExceptions;

		public IReadOnlyList<MagickException> RelatedExceptions
		{
			get
			{
				if (_relatedExceptions == null)
				{
					return new MagickException[0];
				}
				return _relatedExceptions;
			}
		}

		public MagickException(string message)
			: base(message)
		{
		}

		public void SetRelatedException(List<MagickException> relatedExceptions)
		{
			_relatedExceptions = relatedExceptions;
		}
	}
	public sealed class MagickBlobWarningException : MagickWarningException
	{
		public MagickBlobWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickCacheWarningException : MagickWarningException
	{
		public MagickCacheWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickCoderWarningException : MagickWarningException
	{
		public MagickCoderWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickConfigureWarningException : MagickWarningException
	{
		public MagickConfigureWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickCorruptImageWarningException : MagickWarningException
	{
		public MagickCorruptImageWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickDelegateWarningException : MagickWarningException
	{
		public MagickDelegateWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickDrawWarningException : MagickWarningException
	{
		public MagickDrawWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickFileOpenWarningException : MagickWarningException
	{
		public MagickFileOpenWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickImageWarningException : MagickWarningException
	{
		public MagickImageWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickMissingDelegateWarningException : MagickWarningException
	{
		public MagickMissingDelegateWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickModuleWarningException : MagickWarningException
	{
		public MagickModuleWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickOptionWarningException : MagickWarningException
	{
		public MagickOptionWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickPolicyWarningException : MagickErrorException
	{
		public MagickPolicyWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickRegistryWarningException : MagickWarningException
	{
		public MagickRegistryWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickResourceLimitWarningException : MagickWarningException
	{
		public MagickResourceLimitWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickStreamWarningException : MagickWarningException
	{
		public MagickStreamWarningException(string message)
			: base(message)
		{
		}
	}
	public sealed class MagickTypeWarningException : MagickWarningException
	{
		public MagickTypeWarningException(string message)
			: base(message)
		{
		}
	}
	public class MagickWarningException : MagickException
	{
		public MagickWarningException(string message)
			: base(message)
		{
		}
	}
	internal static class ByteConverter
	{
		public static int ToUInt(byte[] data, ref int offset)
		{
			if (offset + 4 > data.Length)
			{
				return 0;
			}
			int num = (int)(((data[offset++] << 24) | (data[offset++] << 16) | (data[offset++] << 8) | data[offset++]) & 0xFFFFFFFFu);
			if (num >= 0)
			{
				return num;
			}
			return 0;
		}

		public static short ToShort(byte[] data, ref int offset)
		{
			if (offset + 2 > data.Length)
			{
				return 0;
			}
			return (short)((short)((short)(data[offset++] << 8) | data[offset++]) & 0xFFFF);
		}

		public static byte[] FromShortReversed(short value)
		{
			byte[] bytes = BitConverter.GetBytes(value);
			Array.Reverse((Array)bytes);
			return bytes;
		}

		public static byte[] FromUnsignedIntegerReversed(uint value)
		{
			byte[] bytes = BitConverter.GetBytes(value);
			Array.Reverse((Array)bytes);
			return bytes;
		}
	}
	internal static class MemoryStreamExtensions
	{
		public static void WriteBytes(this MemoryStream stream, byte[] bytes)
		{
			stream.Write(bytes, 0, bytes.Length);
		}
	}
	internal static class XmlHelper
	{
		public static XmlDocument CreateDocument()
		{
			return new XmlDocument
			{
				XmlResolver = null
			};
		}

		public static XmlElement CreateElement(XmlNode node, string name)
		{
			XmlElement xmlElement = ((node.GetType() == typeof(XmlDocument)) ? ((XmlDocument)node) : node.OwnerDocument).CreateElement(name);
			node.AppendChild(xmlElement);
			return xmlElement;
		}

		public static XmlReaderSettings CreateReaderSettings()
		{
			return new XmlReaderSettings
			{
				DtdProcessing = DtdProcessing.Ignore,
				XmlResolver = null
			};
		}

		public static void SetAttribute<TType>(XmlElement element, string name, TType value)
		{
			XmlAttribute xmlAttribute = ((!element.HasAttribute(name)) ? element.Attributes.Append(element.OwnerDocument.CreateAttribute(name)) : element.Attributes[name]);
			if (typeof(TType) == typeof(string))
			{
				xmlAttribute.Value = (string)(object)value;
			}
			else
			{
				xmlAttribute.Value = (string)Convert.ChangeType(value, typeof(string), CultureInfo.InvariantCulture);
			}
		}
	}
	public interface IMagickFormatInfo : IEquatable<IMagickFormatInfo?>
	{
		bool CanReadMultithreaded { get; }

		bool CanWriteMultithreaded { get; }

		string? Description { get; }

		MagickFormat Format { get; }

		string? MimeType { get; }

		MagickFormat ModuleFormat { get; }

		bool SupportsMultipleFrames { get; }

		bool SupportsReading { get; }

		bool SupportsWriting { get; }

		new string ToString();

		bool Unregister();
	}
	public interface IMagickImage : IMagickImageCreateOperations, IDisposable
	{
		uint AnimationDelay { get; set; }

		uint AnimationIterations { get; set; }

		int AnimationTicksPerSecond { get; set; }

		IEnumerable<string> ArtifactNames { get; }

		IEnumerable<string> AttributeNames { get; }

		uint BaseHeight { get; }

		uint BaseWidth { get; }

		bool BlackPointCompensation { get; set; }

		IMagickGeometry? BoundingBox { get; }

		uint ChannelCount { get; }

		IEnumerable<PixelChannel> Channels { get; }

		IChromaticityInfo Chromaticity { get; set; }

		ClassType ClassType { get; set; }

		Percentage ColorFuzz { get; set; }

		int ColormapSize { get; set; }

		ColorSpace ColorSpace { get; set; }

		ColorType ColorType { get; set; }

		string? Comment { get; set; }

		CompositeOperator Compose { get; set; }

		CompressionMethod Compression { get; }

		Density Density { get; set; }

		uint Depth { get; set; }

		Endian Endian { get; set; }

		string? FileName { get; }

		FilterType FilterType { get; set; }

		MagickFormat Format { get; set; }

		double Gamma { get; }

		GifDisposeMethod GifDisposeMethod { get; set; }

		bool HasAlpha { get; set; }

		uint Height { get; }

		Interlace Interlace { get; }

		PixelInterpolateMethod Interpolate { get; set; }

		bool IsOpaque { get; }

		string? Label { get; set; }

		uint MetaChannelCount { get; set; }

		OrientationType Orientation { get; set; }

		IMagickGeometry Page { get; set; }

		IEnumerable<string> ProfileNames { get; }

		uint Quality { get; set; }

		RenderingIntent RenderingIntent { get; set; }

		string Signature { get; }

		uint TotalColors { get; }

		VirtualPixelMethod VirtualPixelMethod { get; set; }

		uint Width { get; }

		event EventHandler<ProgressEventArgs> Progress;

		event EventHandler<WarningEventArgs> Warning;

		void Alpha(AlphaOption value);

		void Annotate(string text, IMagickGeometry boundingArea);

		void Annotate(string text, IMagickGeometry boundingArea, Gravity gravity);

		void Annotate(string text, IMagickGeometry boundingArea, Gravity gravity, double angle);

		void Annotate(string text, Gravity gravity);

		void AutoGamma();

		void AutoGamma(Channels channels);

		void AutoLevel();

		void AutoLevel(Channels channels);

		void AutoThreshold(AutoThresholdMethod method);

		void BlackThreshold(Percentage threshold);

		void BlackThreshold(Percentage threshold, Channels channels);

		void BrightnessContrast(Percentage brightness, Percentage contrast);

		void BrightnessContrast(Percentage brightness, Percentage contrast, Channels channels);

		void Clahe(Percentage xTiles, Percentage yTiles, uint numberBins, double clipLimit);

		void Clahe(uint xTiles, uint yTiles, uint numberBins, double clipLimit);

		void Clamp();

		void Clamp(Channels channels);

		void Clip();

		void Clip(string pathName);

		void ClipOutside();

		void ClipOutside(string pathName);

		void Clut(IMagickImage image);

		void Clut(IMagickImage image, Channels channels);

		void Clut(IMagickImage image, PixelInterpolateMethod method);

		void Clut(IMagickImage image, PixelInterpolateMethod method, Channels channels);

		void ColorDecisionList(string fileName);

		IMagickErrorInfo Compare(IMagickImage image);

		double Compare(IMagickImage image, ErrorMetric metric);

		double Compare(IMagickImage image, ErrorMetric metric, Channels channels);

		void Composite(IMagickImage image);

		void Composite(IMagickImage image, Channels channels);

		void Composite(IMagickImage image, CompositeOperator compose);

		void Composite(IMagickImage image, CompositeOperator compose, Channels channels);

		void Composite(IMagickImage image, CompositeOperator compose, string? args);

		void Composite(IMagickImage image, CompositeOperator compose, string? args, Channels channels);

		void Composite(IMagickImage image, int x, int y);

		void Composite(IMagickImage image, int x, int y, Channels channels);

		void Composite(IMagickImage image, int x, int y, CompositeOperator compose);

		void Composite(IMagickImage image, int x, int y, CompositeOperator compose, Channels channels);

		void Composite(IMagickImage image, int x, int y, CompositeOperator compose, string? args);

		void Composite(IMagickImage image, int x, int y, CompositeOperator compose, string? args, Channels channels);

		void Composite(IMagickImage image, Gravity gravity);

		void Composite(IMagickImage image, Gravity gravity, Channels channels);

		void Composite(IMagickImage image, Gravity gravity, CompositeOperator compose);

		void Composite(IMagickImage image, Gravity gravity, CompositeOperator compose, Channels channels);

		void Composite(IMagickImage image, Gravity gravity, CompositeOperator compose, string? args);

		void Composite(IMagickImage image, Gravity gravity, CompositeOperator compose, string? args, Channels channels);

		void Composite(IMagickImage image, Gravity gravity, int x, int y);

		void Composite(IMagickImage image, Gravity gravity, int x, int y, Channels channels);

		void Composite(IMagickImage image, Gravity gravity, int x, int y, CompositeOperator compose);

		void Composite(IMagickImage image, Gravity gravity, int x, int y, CompositeOperator compose, Channels channels);

		void Composite(IMagickImage image, Gravity gravity, int x, int y, CompositeOperator compose, string? args);

		void Composite(IMagickImage image, Gravity gravity, int x, int y, CompositeOperator compose, string? args, Channels channels);

		void Contrast();

		void ContrastStretch(Percentage blackPoint);

		void ContrastStretch(Percentage blackPoint, Percentage whitePoint);

		void ContrastStretch(Percentage blackPoint, Percentage whitePoint, Channels channels);

		IEnumerable<PointD> ConvexHull();

		void CopyPixels(IMagickImage source);

		void CopyPixels(IMagickImage source, Channels channels);

		void CopyPixels(IMagickImage source, IMagickGeometry geometry);

		void CopyPixels(IMagickImage source, IMagickGeometry geometry, Channels channels);

		void CopyPixels(IMagickImage source, IMagickGeometry geometry, int x, int y);

		void CopyPixels(IMagickImage source, IMagickGeometry geometry, int x, int y, Channels channels);

		void CycleColormap(int amount);

		void Decipher(string passphrase);

		uint DetermineBitDepth();

		uint DetermineBitDepth(Channels channels);

		ColorType DetermineColorType();

		void Draw(params IDrawable[] drawables);

		void Draw(IEnumerable<IDrawable> drawables);

		void Encipher(string passphrase);

		void Equalize();

		void Equalize(Channels channels);

		void Evaluate(Channels channels, EvaluateFunction evaluateFunction, params double[] arguments);

		void Evaluate(Channels channels, EvaluateOperator evaluateOperator, double value);

		void Evaluate(Channels channels, EvaluateOperator evaluateOperator, Percentage percentage);

		void Evaluate(Channels channels, IMagickGeometry geometry, EvaluateOperator evaluateOperator, double value);

		void Evaluate(Channels channels, IMagickGeometry geometry, EvaluateOperator evaluateOperator, Percentage percentage);

		ITypeMetric? FontTypeMetrics(string text);

		ITypeMetric? FontTypeMetrics(string text, bool ignoreNewlines);

		string? FormatExpression(string expression);

		void Fx(string expression);

		void Fx(string expression, Channels channels);

		void GammaCorrect(double gamma);

		void GammaCorrect(double gamma, Channels channels);

		IEightBimProfile? Get8BimProfile();

		string? GetArtifact(string name);

		string? GetAttribute(string name);

		string? GetClippingPath();

		string? GetClippingPath(string pathName);

		IColorProfile? GetColorProfile();

		IExifProfile? GetExifProfile();

		IIptcProfile? GetIptcProfile();

		IImageProfile? GetProfile(string name);

		IXmpProfile? GetXmpProfile();

		void Grayscale();

		void Grayscale(PixelIntensityMethod method);

		void HaldClut(IMagickImage image);

		void HaldClut(IMagickImage image, Channels channels);

		bool HasProfile(string name);

		void ImportPixels(byte[] data, IPixelImportSettings settings);

		void ImportPixels(byte[] data, uint offset, IPixelImportSettings settings);

		void InverseContrast();

		void InverseLevel(Percentage blackPointPercentage, Percentage whitePointPercentage);

		void InverseLevel(Percentage blackPointPercentage, Percentage whitePointPercentage, Channels channels);

		void InverseLevel(Percentage blackPointPercentage, Percentage whitePointPercentage, double gamma);

		void InverseLevel(Percentage blackPointPercentage, Percentage whitePointPercentage, double gamma, Channels channels);

		void InverseSigmoidalContrast(double contrast);

		void InverseSigmoidalContrast(double contrast, double midpoint);

		void InverseSigmoidalContrast(double contrast, double midpoint, Channels channels);

		void InverseSigmoidalContrast(double contrast, Percentage midpointPercentage);

		void Kmeans(IKmeansSettings settings);

		void Level(Percentage blackPointPercentage, Percentage whitePointPercentage);

		void Level(Percentage blackPointPercentage, Percentage whitePointPercentage, Channels channels);

		void Level(Percentage blackPointPercentage, Percentage whitePointPercentage, double gamma);

		void Level(Percentage blackPointPercentage, Percentage whitePointPercentage, double gamma, Channels channels);

		void LinearStretch(Percentage blackPoint, Percentage whitePoint);

		void LocalContrast(double radius, Percentage strength);

		void LocalContrast(double radius, Percentage strength, Channels channels);

		void Lower(uint size);

		void MedianFilter();

		void MedianFilter(uint radius);

		IEnumerable<PointD> MinimumBoundingBox();

		void Modulate(Percentage brightness);

		void Modulate(Percentage brightness, Percentage saturation);

		void Modulate(Percentage brightness, Percentage saturation, Percentage hue);

		IMoments Moments();

		void Negate();

		void Negate(Channels channels);

		void NegateGrayscale();

		void NegateGrayscale(Channels channels);

		void Normalize();

		void OrderedDither(string thresholdMap);

		void OrderedDither(string thresholdMap, Channels channels);

		void Perceptible(double epsilon);

		void Perceptible(double epsilon, Channels channels);

		IPerceptualHash? PerceptualHash();

		IPerceptualHash? PerceptualHash(params ColorSpace[] colorSpaces);

		void Ping(byte[] data);

		void Ping(byte[] data, uint offset, uint count);

		void Ping(FileInfo file);

		void Ping(Stream stream);

		void Ping(string fileName);

		void Polaroid(string caption, double angle, PixelInterpolateMethod method);

		void Posterize(int levels);

		void Posterize(int levels, Channels channels);

		void Posterize(int levels, DitherMethod method);

		void Posterize(int levels, DitherMethod method, Channels channels);

		void PreserveColorType();

		IMagickErrorInfo? Quantize(IQuantizeSettings settings);

		void Raise(int size);

		void RandomThreshold(Percentage percentageLow, Percentage percentageHigh);

		void RandomThreshold(Percentage percentageLow, Percentage percentageHigh, Channels channels);

		void RangeThreshold(Percentage percentageLowBlack, Percentage percentageLowWhite, Percentage percentageHighWhite, Percentage percentageHighBlack);

		void Read(byte[] data);

		void Read(byte[] data, uint offset, uint count);

		void Read(byte[] data, uint offset, uint count, MagickFormat format);

		void Read(byte[] data, MagickFormat format);

		void Read(FileInfo file);

		void Read(FileInfo file, uint width, uint height);

		void Read(FileInfo file, MagickFormat format);

		void Read(Stream stream);

		void Read(Stream stream, MagickFormat format);

		void Read(string fileName);

		void Read(string fileName, uint width, uint height);

		void Read(string fileName, MagickFormat format);

		Task ReadAsync(FileInfo file);

		Task ReadAsync(FileInfo file, CancellationToken cancellationToken);

		Task ReadAsync(FileInfo file, MagickFormat format);

		Task ReadAsync(FileInfo file, MagickFormat format, CancellationToken cancellationToken);

		Task ReadAsync(Stream stream);

		Task ReadAsync(Stream stream, CancellationToken cancellationToken);

		Task ReadAsync(Stream stream, MagickFormat format);

		Task ReadAsync(Stream stream, MagickFormat format, CancellationToken cancellationToken);

		Task ReadAsync(string fileName);

		Task ReadAsync(string fileName, CancellationToken cancellationToken);

		Task ReadAsync(string fileName, MagickFormat format);

		Task ReadAsync(string fileName, MagickFormat format, CancellationToken cancellationToken);

		void ReduceNoise();

		void ReduceNoise(uint order);

		void RegionMask(IMagickGeometry region);

		IMagickErrorInfo Remap(IMagickImage image);

		IMagickErrorInfo Remap(IMagickImage image, IQuantizeSettings settings);

		void RemoveArtifact(string name);

		void RemoveAttribute(string name);

		void RemoveRegionMask();

		void RemoveProfile(IImageProfile profile);

		void RemoveProfile(string name);

		void RemoveReadMask();

		void RemoveWriteMask();

		void ResetPage();

		void Segment();

		void Segment(ColorSpace quantizeColorSpace, double clusterThreshold, double smoothingThreshold);

		void SetArtifact(string name, string value);

		void SetArtifact(string name, bool flag);

		void SetAttenuate(double attenuate);

		void SetAttribute(string name, string value);

		void SetAttribute(string name, bool flag);

		void SetBitDepth(uint value);

		void SetBitDepth(uint value, Channels channels);

		void SetClippingPath(string value);

		void SetClippingPath(string value, string pathName);

		void SetCompression(CompressionMethod compression);

		void SetProfile(IImageProfile profile);

		void SetProfile(IColorProfile profile);

		void SetProfile(IColorProfile profile, ColorTransformMode mode);

		void SetReadMask(IMagickImage image);

		void SetWriteMask(IMagickImage image);

		void SigmoidalContrast(double contrast);

		void SigmoidalContrast(double contrast, double midpoint);

		void SigmoidalContrast(double contrast, double midpoint, Channels channels);

		void SigmoidalContrast(double contrast, Percentage midpointPercentage);

		void Solarize();

		void Solarize(double factor);

		void SortPixels();

		void Solarize(Percentage factorPercentage);

		IStatistics Statistics();

		IStatistics Statistics(Channels channels);

		void Strip();

		void Texture(IMagickImage image);

		void Threshold(Percentage percentage);

		void Threshold(Percentage percentage, Channels channels);

		void Tile(IMagickImage image, CompositeOperator compose);

		void Tile(IMagickImage image, CompositeOperator compose, string? args);

		string ToBase64();

		string ToBase64(MagickFormat format);

		string ToBase64(IWriteDefines defines);

		byte[] ToByteArray();

		byte[] ToByteArray(IWriteDefines defines);

		byte[] ToByteArray(MagickFormat format);

		bool TransformColorSpace(IColorProfile target);

		bool TransformColorSpace(IColorProfile target, ColorTransformMode mode);

		bool TransformColorSpace(IColorProfile source, IColorProfile target);

		bool TransformColorSpace(IColorProfile source, IColorProfile target, ColorTransformMode mode);

		void Trim();

		void Trim(params Gravity[] edges);

		void Trim(Percentage percentBackground);

		void WhiteBalance();

		void WhiteBalance(Percentage vibrance);

		void WhiteThreshold(Percentage threshold);

		void WhiteThreshold(Percentage threshold, Channels channels);

		void Write(FileInfo file);

		void Write(FileInfo file, IWriteDefines defines);

		void Write(FileInfo file, MagickFormat format);

		void Write(Stream stream);

		void Write(Stream stream, IWriteDefines defines);

		void Write(Stream stream, MagickFormat format);

		void Write(string fileName);

		void Write(string fileName, IWriteDefines defines);

		void Write(string fileName, MagickFormat format);

		Task WriteAsync(FileInfo file);

		Task WriteAsync(FileInfo file, CancellationToken cancellationToken);

		Task WriteAsync(FileInfo file, IWriteDefines defines);

		Task WriteAsync(FileInfo file, IWriteDefines defines, CancellationToken cancellationToken);

		Task WriteAsync(FileInfo file, MagickFormat format);

		Task WriteAsync(FileInfo file, MagickFormat format, CancellationToken cancellationToken);

		Task WriteAsync(Stream stream);

		Task WriteAsync(Stream stream, CancellationToken cancellationToken);

		Task WriteAsync(Stream stream, IWriteDefines defines);

		Task WriteAsync(Stream stream, IWriteDefines defines, CancellationToken cancellationToken);

		Task WriteAsync(Stream stream, MagickFormat format);

		Task WriteAsync(Stream stream, MagickFormat format, CancellationToken cancellationToken);

		Task WriteAsync(string fileName);

		Task WriteAsync(string fileName, CancellationToken cancellationToken);

		Task WriteAsync(string fileName, IWriteDefines defines);

		Task WriteAsync(string fileName, IWriteDefines defines, CancellationToken cancellationToken);

		Task WriteAsync(string fileName, MagickFormat format);

		Task WriteAsync(string fileName, MagickFormat format, CancellationToken cancellationToken);
	}
	public interface IMagickImageCloneMutator<TQuantumType> : IMagickImageCreateOperations<TQuantumType>, IMagickImageCreateOperations where TQuantumType : struct, IConvertible
	{
	}
	public interface IMagickImageCollection : IDisposable
	{
		event EventHandler<WarningEventArgs> Warning;

		void Add(string fileName);

		void AddRange(byte[] data);

		void AddRange(string fileName);

		void AddRange(Stream stream);

		void Coalesce();

		void Complex(IComplexSettings complexSettings);

		void Deconstruct();

		void Insert(int index, string fileName);

		void Morph(uint frames);

		void Optimize();

		void OptimizePlus();

		void OptimizeTransparency();

		void Ping(byte[] data);

		void Ping(byte[] data, uint offset, uint count);

		void Ping(FileInfo file);

		void Ping(Stream stream);

		void Ping(string fileName);

		IMagickErrorInfo? Quantize();

		IMagickErrorInfo? Quantize(IQuantizeSettings settings);

		void Read(byte[] data);

		void Read(byte[] data, uint offset, uint count);

		void Read(byte[] data, uint offset, uint count, MagickFormat format);

		void Read(byte[] data, MagickFormat format);

		void Read(FileInfo file);

		void Read(FileInfo file, MagickFormat format);

		void Read(Stream stream);

		void Read(Stream stream, MagickFormat format);

		void Read(string fileName);

		void Read(string fileName, MagickFormat format);

		Task ReadAsync(FileInfo file);

		Task ReadAsync(FileInfo file, CancellationToken cancellationToken);

		Task ReadAsync(FileInfo file, MagickFormat format);

		Task ReadAsync(FileInfo file, MagickFormat format, CancellationToken cancellationToken);

		Task ReadAsync(Stream stream);

		Task ReadAsync(Stream stream, CancellationToken cancellationToken);

		Task ReadAsync(Stream stream, MagickFormat format);

		Task ReadAsync(Stream stream, MagickFormat format, CancellationToken cancellationToken);

		Task ReadAsync(string fileName);

		Task ReadAsync(string fileName, CancellationToken cancellationToken);

		Task ReadAsync(string fileName, MagickFormat format);

		Task ReadAsync(string fileName, MagickFormat format, CancellationToken cancellationToken);

		void Remap(IMagickImage image);

		void Remap(IMagickImage image, IQuantizeSettings settings);

		void ResetPage();

		void Reverse();

		byte[] ToByteArray();

		byte[] ToByteArray(IWriteDefines defines);

		byte[] ToByteArray(MagickFormat format);

		string ToBase64();

		string ToBase64(MagickFormat format);

		string ToBase64(IWriteDefines defines);

		void TrimBounds();

		void Write(FileInfo file);

		void Write(FileInfo file, IWriteDefines defines);

		void Write(FileInfo file, MagickFormat format);

		void Write(Stream stream);

		void Write(Stream stream, IWriteDefines defines);

		void Write(Stream stream, MagickFormat format);

		void Write(string fileName);

		void Write(string fileName, IWriteDefines defines);

		void Write(string fileName, MagickFormat format);

		Task WriteAsync(FileInfo file);

		Task WriteAsync(FileInfo file, CancellationToken cancellationToken);

		Task WriteAsync(FileInfo file, IWriteDefines defines);

		Task WriteAsync(FileInfo file, IWriteDefines defines, CancellationToken cancellationToken);

		Task WriteAsync(FileInfo file, MagickFormat format);

		Task WriteAsync(FileInfo file, MagickFormat format, CancellationToken cancellationToken);

		Task WriteAsync(Stream stream);

		Task WriteAsync(Stream stream, CancellationToken cancellationToken);

		Task WriteAsync(Stream stream, IWriteDefines defines);

		Task WriteAsync(Stream stream, IWriteDefines defines, CancellationToken cancellationToken);

		Task WriteAsync(Stream stream, MagickFormat format);

		Task WriteAsync(Stream stream, MagickFormat format, CancellationToken cancellationToken);

		Task WriteAsync(string fileName);

		Task WriteAsync(string fileName, CancellationToken cancellationToken);

		Task WriteAsync(string fileName, IWriteDefines defines);

		Task WriteAsync(string fileName, IWriteDefines defines, CancellationToken cancellationToken);

		Task WriteAsync(string fileName, MagickFormat format);

		Task WriteAsync(string fileName, MagickFormat format, CancellationToken cancellationToken);
	}
	public interface IMagickImageCollection<TQuantumType> : IMagickImageCollection, IDisposable, IList<IMagickImage<TQuantumType>>, ICollection<IMagickImage<TQuantumType>>, IEnumerable<IMagickImage<TQuantumType>>, IEnumerable where TQuantumType : struct, IConvertible
	{
		void AddRange(byte[] data, IMagickReadSettings<TQuantumType>? readSettings);

		void AddRange(IEnumerable<IMagickImage<TQuantumType>> images);

		void AddRange(string fileName, IMagickReadSettings<TQuantumType>? readSettings);

		void AddRange(Stream stream, IMagickReadSettings<TQuantumType>? readSettings);

		IMagickImage<TQuantumType> AppendHorizontally();

		IMagickImage<TQuantumType> AppendVertically();

		IMagickImageCollection<TQuantumType> Clone();

		IMagickImage<TQuantumType> Combine();

		IMagickImage<TQuantumType> Combine(ColorSpace colorSpace);

		IMagickImage<TQuantumType> Evaluate(EvaluateOperator evaluateOperator);

		IMagickImage<TQuantumType> Flatten();

		IMagickImage<TQuantumType> Flatten(IMagickColor<TQuantumType> backgroundColor);

		IMagickImage<TQuantumType> Fx(string expression);

		IMagickImage<TQuantumType> Fx(string expression, Channels channels);

		IMagickImage<TQuantumType> Merge();

		IMagickImage<TQuantumType> Montage(IMontageSettings<TQuantumType> settings);

		IMagickImage<TQuantumType> Mosaic();

		void Ping(byte[] data, uint offset, uint count, IMagickReadSettings<TQuantumType>? readSettings);

		void Ping(byte[] data, IMagickReadSettings<TQuantumType>? readSettings);

		void Ping(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings);

		void Ping(Stream stream, IMagickReadSettings<TQuantumType>? readSettings);

		void Ping(string fileName, IMagickReadSettings<TQuantumType>? readSettings);

		IMagickImage<TQuantumType> Polynomial(double[] terms);

		void Read(byte[] data, uint offset, uint count, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(byte[] data, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(Stream stream, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(string fileName, IMagickReadSettings<TQuantumType>? readSettings);

		Task ReadAsync(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings);

		Task ReadAsync(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings, CancellationToken cancellationToken);

		Task ReadAsync(Stream stream, IMagickReadSettings<TQuantumType>? readSettings);

		Task ReadAsync(Stream stream, IMagickReadSettings<TQuantumType>? readSettings, CancellationToken cancellationToken);

		Task ReadAsync(string fileName, IMagickReadSettings<TQuantumType>? readSettings);

		Task ReadAsync(string fileName, IMagickReadSettings<TQuantumType>? readSettings, CancellationToken cancellationToken);

		IMagickImage<TQuantumType> SmushHorizontal(uint offset);

		IMagickImage<TQuantumType> SmushVertical(uint offset);
	}
	public interface IMagickImageCreateOperations
	{
		void AdaptiveBlur();

		void AdaptiveBlur(double radius);

		void AdaptiveBlur(double radius, double sigma);

		void AdaptiveResize(uint width, uint height);

		void AdaptiveResize(IMagickGeometry geometry);

		void AdaptiveSharpen();

		void AdaptiveSharpen(Channels channels);

		void AdaptiveSharpen(double radius, double sigma);

		void AdaptiveSharpen(double radius, double sigma, Channels channels);

		void AdaptiveThreshold(uint width, uint height);

		void AdaptiveThreshold(uint width, uint height, Channels channels);

		void AdaptiveThreshold(uint width, uint height, double bias);

		void AdaptiveThreshold(uint width, uint height, double bias, Channels channels);

		void AdaptiveThreshold(uint width, uint height, Percentage biasPercentage);

		void AdaptiveThreshold(uint width, uint height, Percentage biasPercentage, Channels channels);

		void AddNoise(NoiseType noiseType);

		void AddNoise(NoiseType noiseType, Channels channels);

		void AddNoise(NoiseType noiseType, double attenuate);

		void AddNoise(NoiseType noiseType, double attenuate, Channels channels);

		void AffineTransform(IDrawableAffine affineMatrix);

		void AutoOrient();

		void BilateralBlur(uint width, uint height);

		void BilateralBlur(uint width, uint height, double intensitySigma, double spatialSigma);

		void BlueShift();

		void BlueShift(double factor);

		void Blur();

		void Blur(Channels channels);

		void Blur(double radius, double sigma);

		void Blur(double radius, double sigma, Channels channels);

		void Border(uint size);

		void Border(uint width, uint height);

		void Border(Percentage percentage);

		void CannyEdge();

		void CannyEdge(double radius, double sigma, Percentage lower, Percentage upper);

		void Charcoal();

		void Charcoal(double radius, double sigma);

		void Chop(IMagickGeometry geometry);

		void ChopHorizontal(int offset, uint width);

		void ChopVertical(int offset, uint height);

		void ColorMatrix(IMagickColorMatrix matrix);

		void Convolve(IConvolveMatrix matrix);

		void Crop(uint width, uint height);

		void Crop(uint width, uint height, Gravity gravity);

		void Crop(IMagickGeometry geometry);

		void Crop(IMagickGeometry geometry, Gravity gravity);

		double Deskew(Percentage threshold);

		double DeskewAndCrop(Percentage threshold);

		void Despeckle();

		void Distort(DistortMethod method, params double[] arguments);

		void Distort(IDistortSettings settings, params double[] arguments);

		void Edge(double radius);

		void Emboss();

		void Emboss(double radius, double sigma);

		void Enhance();

		void Extent(uint width, uint height);

		void Extent(int x, int y, uint width, uint height);

		void Extent(uint width, uint height, Gravity gravity);

		void Extent(IMagickGeometry geometry);

		void Extent(IMagickGeometry geometry, Gravity gravity);

		void Flip();

		void Flop();

		void Frame();

		void Frame(IMagickGeometry geometry);

		void Frame(uint width, uint height);

		void Frame(uint width, uint height, int innerBevel, int outerBevel);

		void GaussianBlur(double radius);

		void GaussianBlur(double radius, Channels channels);

		void GaussianBlur(double radius, double sigma);

		void GaussianBlur(double radius, double sigma, Channels channels);

		void HoughLine();

		void HoughLine(uint width, uint height, uint threshold);

		void Implode(double amount, PixelInterpolateMethod method);

		void InterpolativeResize(uint width, uint height, PixelInterpolateMethod method);

		void InterpolativeResize(IMagickGeometry geometry, PixelInterpolateMethod method);

		void InterpolativeResize(Percentage percentage, PixelInterpolateMethod method);

		void InterpolativeResize(Percentage percentageWidth, Percentage percentageHeight, PixelInterpolateMethod method);

		void Kuwahara();

		void Kuwahara(double radius, double sigma);

		void LiquidRescale(uint width, uint height);

		void LiquidRescale(uint width, uint height, double deltaX, double rigidity);

		void LiquidRescale(IMagickGeometry geometry);

		void LiquidRescale(Percentage percentage);

		void LiquidRescale(Percentage percentageWidth, Percentage percentageHeight);

		void LiquidRescale(Percentage percentageWidth, Percentage percentageHeight, double deltaX, double rigidity);

		void Magnify();

		void MeanShift(uint size);

		void MeanShift(uint size, Percentage colorDistance);

		void MeanShift(uint width, uint height);

		void MeanShift(uint width, uint height, Percentage colorDistance);

		void Minify();

		void Morphology(IMorphologySettings settings);

		void MotionBlur(double radius, double sigma, double angle);

		void OilPaint();

		void OilPaint(double radius, double sigma);

		void Resample(double resolutionX, double resolutionY);

		void Resample(PointD density);

		void Resize(uint width, uint height);

		void Resize(IMagickGeometry geometry);

		void Resize(Percentage percentage);

		void Resize(Percentage percentageWidth, Percentage percentageHeight);

		void Roll(int x, int y);

		void Rotate(double degrees);

		void RotationalBlur(double angle);

		void RotationalBlur(double angle, Channels channels);

		void Sample(uint width, uint height);

		void Sample(IMagickGeometry geometry);

		void Sample(Percentage percentage);

		void Sample(Percentage percentageWidth, Percentage percentageHeight);

		void Scale(uint width, uint height);

		void Scale(IMagickGeometry geometry);

		void Scale(Percentage percentage);

		void Scale(Percentage percentageWidth, Percentage percentageHeight);

		void SelectiveBlur(double radius, double sigma, double threshold);

		void SelectiveBlur(double radius, double sigma, double threshold, Channels channels);

		void SelectiveBlur(double radius, double sigma, Percentage thresholdPercentage);

		void SelectiveBlur(double radius, double sigma, Percentage thresholdPercentage, Channels channels);

		void SepiaTone();

		void SepiaTone(Percentage threshold);

		void Shade();

		void Shade(double azimuth, double elevation);

		void Shade(double azimuth, double elevation, Channels channels);

		void ShadeGrayscale();

		void ShadeGrayscale(double azimuth, double elevation);

		void ShadeGrayscale(double azimuth, double elevation, Channels channels);

		void Shadow();

		void Shadow(int x, int y, double sigma, Percentage alpha);

		void Sharpen();

		void Sharpen(Channels channels);

		void Sharpen(double radius, double sigma);

		void Sharpen(double radius, double sigma, Channels channels);

		void Shave(uint size);

		void Shave(uint leftRight, uint topBottom);

		void Shear(double xAngle, double yAngle);

		void Sketch();

		void Sketch(double radius, double sigma, double angle);

		void Splice(IMagickGeometry geometry);

		void Spread();

		void Spread(double radius);

		void Spread(PixelInterpolateMethod method, double radius);

		void Statistic(StatisticType type, uint width, uint height);

		void Stegano(IMagickImage watermark);

		void Stereo(IMagickImage rightImage);

		void Swirl(double degrees);

		void Swirl(PixelInterpolateMethod method, double degrees);

		void Thumbnail(uint width, uint height);

		void Thumbnail(IMagickGeometry geometry);

		void Thumbnail(Percentage percentage);

		void Thumbnail(Percentage percentageWidth, Percentage percentageHeight);

		void Transpose();

		void Transverse();

		void UnsharpMask(double radius, double sigma);

		void UnsharpMask(double radius, double sigma, Channels channels);

		void UnsharpMask(double radius, double sigma, double amount, double threshold);

		void UnsharpMask(double radius, double sigma, double amount, double threshold, Channels channels);

		void Vignette();

		void Vignette(double radius, double sigma, int x, int y);

		void Wave();

		void Wave(PixelInterpolateMethod method, double amplitude, double length);

		void WaveletDenoise(Percentage thresholdPercentage);

		void WaveletDenoise(Percentage thresholdPercentage, double softness);
	}
	public interface IMagickImageCreateOperations<TQuantumType> : IMagickImageCreateOperations where TQuantumType : struct, IConvertible
	{
		void Colorize(IMagickColor<TQuantumType> color, Percentage alpha);

		void Colorize(IMagickColor<TQuantumType> color, Percentage alphaRed, Percentage alphaGreen, Percentage alphaBlue);

		void Extent(uint width, uint height, IMagickColor<TQuantumType> backgroundColor);

		void Extent(uint width, uint height, Gravity gravity, IMagickColor<TQuantumType> backgroundColor);

		void Extent(IMagickGeometry geometry, IMagickColor<TQuantumType> backgroundColor);

		void Extent(IMagickGeometry geometry, Gravity gravity, IMagickColor<TQuantumType> backgroundColor);

		void Shadow(IMagickColor<TQuantumType> color);

		void Shadow(int x, int y, double sigma, Percentage alpha, IMagickColor<TQuantumType> color);

		void SparseColor(SparseColorMethod method, IEnumerable<ISparseColorArg<TQuantumType>> args);

		void SparseColor(SparseColorMethod method, params ISparseColorArg<TQuantumType>[] args);

		void SparseColor(Channels channels, SparseColorMethod method, IEnumerable<ISparseColorArg<TQuantumType>> args);

		void SparseColor(Channels channels, SparseColorMethod method, params ISparseColorArg<TQuantumType>[] args);

		void Tint(IMagickGeometry opacity, IMagickColor<TQuantumType> color);

		void WaveletDenoise(TQuantumType threshold);

		void WaveletDenoise(TQuantumType threshold, double softness);
	}
	public interface IMagickImageInfo
	{
		ColorSpace ColorSpace { get; }

		CompressionMethod Compression { get; }

		Density? Density { get; }

		string? FileName { get; }

		MagickFormat Format { get; }

		uint Height { get; }

		Interlace Interlace { get; }

		OrientationType Orientation { get; }

		uint Quality { get; }

		uint Width { get; }

		void Read(byte[] data);

		void Read(byte[] data, uint offset, uint count);

		void Read(FileInfo file);

		void Read(Stream stream);

		void Read(string fileName);
	}
	public interface IMagickImageInfo<TQuantumType> : IMagickImageInfo where TQuantumType : struct, IConvertible
	{
		void Read(byte[] data, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(byte[] data, uint offset, uint count, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(Stream stream, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(string fileName, IMagickReadSettings<TQuantumType>? readSettings);
	}
	public interface IMagickImage<TQuantumType> : IMagickImageCreateOperations<TQuantumType>, IMagickImageCreateOperations, IMagickImage, IDisposable, IComparable<IMagickImage<TQuantumType>?> where TQuantumType : struct, IConvertible
	{
		IMagickColor<TQuantumType>? BackgroundColor { get; set; }

		IMagickColor<TQuantumType>? BorderColor { get; set; }

		IMagickColor<TQuantumType>? MatteColor { get; set; }

		IMagickSettings<TQuantumType> Settings { get; }

		IMagickImage<TQuantumType> Clone();

		IMagickImage<TQuantumType> CloneAndMutate(Action<IMagickImageCloneMutator<TQuantumType>> action);

		[Obsolete("This method will be removed in the next major release, use CloneArea instead.")]
		IMagickImage<TQuantumType> Clone(IMagickGeometry geometry);

		[Obsolete("This method will be removed in the next major release, use CloneArea instead.")]
		IMagickImage<TQuantumType> Clone(uint width, uint height);

		[Obsolete("This method will be removed in the next major release, use CloneArea instead.")]
		IMagickImage<TQuantumType> Clone(int x, int y, uint width, uint height);

		IMagickImage<TQuantumType> CloneArea(IMagickGeometry geometry);

		IMagickImage<TQuantumType> CloneArea(uint width, uint height);

		IMagickImage<TQuantumType> CloneArea(int x, int y, uint width, uint height);

		void ColorAlpha(IMagickColor<TQuantumType> color);

		void ColorThreshold(IMagickColor<TQuantumType> startColor, IMagickColor<TQuantumType> stopColor);

		IMagickImage<TQuantumType> Compare(IMagickImage image, ErrorMetric metric, out double distortion);

		IMagickImage<TQuantumType> Compare(IMagickImage image, ErrorMetric metric, Channels channels, out double distortion);

		IMagickImage<TQuantumType> Compare(IMagickImage image, ICompareSettings<TQuantumType> settings, out double distortion);

		IMagickImage<TQuantumType> Compare(IMagickImage image, ICompareSettings<TQuantumType> settings, Channels channels, out double distortion);

		IReadOnlyList<IConnectedComponent<TQuantumType>> ConnectedComponents(uint connectivity);

		IReadOnlyList<IConnectedComponent<TQuantumType>> ConnectedComponents(IConnectedComponentsSettings settings);

		IReadOnlyList<IMagickImage<TQuantumType>> CropToTiles(uint width, uint height);

		IReadOnlyList<IMagickImage<TQuantumType>> CropToTiles(IMagickGeometry geometry);

		void Draw(IDrawables<TQuantumType> drawables);

		void FloodFill(TQuantumType alpha, int x, int y);

		void FloodFill(IMagickColor<TQuantumType> color, int x, int y);

		void FloodFill(IMagickColor<TQuantumType> color, int x, int y, IMagickColor<TQuantumType> target);

		void FloodFill(IMagickImage<TQuantumType> image, int x, int y);

		void FloodFill(IMagickImage<TQuantumType> image, int x, int y, IMagickColor<TQuantumType> target);

		IMagickColor<TQuantumType>? GetColormapColor(int index);

		IPixelCollection<TQuantumType> GetPixels();

		IUnsafePixelCollection<TQuantumType> GetPixelsUnsafe();

		IMagickImage<TQuantumType>? GetReadMask();

		IMagickImage<TQuantumType>? GetWriteMask();

		IReadOnlyDictionary<IMagickColor<TQuantumType>, uint> Histogram();

		void ImportPixels(TQuantumType[] data, IPixelImportSettings settings);

		void ImportPixels(TQuantumType[] data, uint offset, IPixelImportSettings settings);

		IMagickImage<TQuantumType>? Integral();

		void InverseFloodFill(TQuantumType alpha, int x, int y);

		void InverseFloodFill(IMagickColor<TQuantumType> color, int x, int y);

		void InverseFloodFill(IMagickColor<TQuantumType> color, int x, int y, IMagickColor<TQuantumType> target);

		void InverseFloodFill(IMagickImage<TQuantumType> image, int x, int y);

		void InverseFloodFill(IMagickImage<TQuantumType> image, int x, int y, IMagickColor<TQuantumType> target);

		void InverseLevel(TQuantumType blackPoint, TQuantumType whitePoint);

		void InverseLevel(TQuantumType blackPoint, TQuantumType whitePoint, Channels channels);

		void InverseLevel(TQuantumType blackPoint, TQuantumType whitePoint, double gamma);

		void InverseLevel(TQuantumType blackPoint, TQuantumType whitePoint, double gamma, Channels channels);

		void InverseLevelColors(IMagickColor<TQuantumType> blackColor, IMagickColor<TQuantumType> whiteColor);

		void InverseLevelColors(IMagickColor<TQuantumType> blackColor, IMagickColor<TQuantumType> whiteColor, Channels channels);

		void InverseOpaque(IMagickColor<TQuantumType> target, IMagickColor<TQuantumType> fill);

		void InverseTransparent(IMagickColor<TQuantumType> color);

		void InverseTransparentChroma(IMagickColor<TQuantumType> colorLow, IMagickColor<TQuantumType> colorHigh);

		void Level(TQuantumType blackPoint, TQuantumType whitePoint);

		void Level(TQuantumType blackPoint, TQuantumType whitePoint, Channels channels);

		void Level(TQuantumType blackPoint, TQuantumType whitePoint, double gamma);

		void Level(TQuantumType blackPoint, TQuantumType whitePoint, double gamma, Channels channels);

		void LevelColors(IMagickColor<TQuantumType> blackColor, IMagickColor<TQuantumType> whiteColor);

		void LevelColors(IMagickColor<TQuantumType> blackColor, IMagickColor<TQuantumType> whiteColor, Channels channels);

		void Opaque(IMagickColor<TQuantumType> target, IMagickColor<TQuantumType> fill);

		void Ping(byte[] data, uint offset, uint count, IMagickReadSettings<TQuantumType>? readSettings);

		void Ping(byte[] data, IMagickReadSettings<TQuantumType>? readSettings);

		void Ping(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings);

		void Ping(Stream stream, IMagickReadSettings<TQuantumType>? readSettings);

		void Ping(string fileName, IMagickReadSettings<TQuantumType>? readSettings);

		void RandomThreshold(TQuantumType low, TQuantumType high);

		void RandomThreshold(TQuantumType low, TQuantumType high, Channels channels);

		void RangeThreshold(TQuantumType lowBlack, TQuantumType lowWhite, TQuantumType highWhite, TQuantumType highBlack);

		void Read(byte[] data, uint offset, uint count, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(byte[] data, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(IMagickColor<TQuantumType> color, uint width, uint height);

		void Read(Stream stream, IMagickReadSettings<TQuantumType>? readSettings);

		void Read(string fileName, IMagickReadSettings<TQuantumType>? readSettings);

		Task ReadAsync(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings);

		Task ReadAsync(FileInfo file, IMagickReadSettings<TQuantumType>? readSettings, CancellationToken cancellationToken);

		Task ReadAsync(Stream stream, IMagickReadSettings<TQuantumType>? readSettings);

		Task ReadAsync(Stream stream, IMagickReadSettings<TQuantumType>? readSettings, CancellationToken cancellationToken);

		Task ReadAsync(string fileName, IMagickReadSettings<TQuantumType>? readSettings);

		Task ReadAsync(string fileName, IMagickReadSettings<TQuantumType>? readSettings, CancellationToken cancellationToken);

		void ReadPixels(byte[] data, IPixelReadSettings<TQuantumType> settings);

		void ReadPixels(byte[] data, uint offset, uint count, IPixelReadSettings<TQuantumType> settings);

		void ReadPixels(TQuantumType[] data, IPixelReadSettings<TQuantumType> settings);

		void ReadPixels(TQuantumType[] data, uint offset, uint count, IPixelReadSettings<TQuantumType> settings);

		void ReadPixels(FileInfo file, IPixelReadSettings<TQuantumType> settings);

		void ReadPixels(Stream stream, IPixelReadSettings<TQuantumType> settings);

		void ReadPixels(string fileName, IPixelReadSettings<TQuantumType> settings);

		Task ReadPixelsAsync(FileInfo file, IPixelReadSettings<TQuantumType> settings);

		Task ReadPixelsAsync(FileInfo file, IPixelReadSettings<TQuantumType> settings, CancellationToken cancellationToken);

		Task ReadPixelsAsync(Stream stream, IPixelReadSettings<TQuantumType> settings);

		Task ReadPixelsAsync(Stream stream, IPixelReadSettings<TQuantumType> settings, CancellationToken cancellationToken);

		Task ReadPixelsAsync(string fileName, IPixelReadSettings<TQuantumType> settings);

		Task ReadPixelsAsync(string fileName, IPixelReadSettings<TQuantumType> settings, CancellationToken cancellationToken);

		IMagickErrorInfo Remap(IEnumerable<IMagickColor<TQuantumType>> colors);

		IMagickErrorInfo Remap(IEnumerable<IMagickColor<TQuantumType>> colors, IQuantizeSettings settings);

		IReadOnlyList<IMagickImage<TQuantumType>> Separate();

		IReadOnlyList<IMagickImage<TQuantumType>> Separate(Channels channels);

		void SetColormapColor(int index, IMagickColor<TQuantumType> color);

		IMagickSearchResult<TQuantumType>? SubImageSearch(IMagickImage<TQuantumType> image);

		IMagickSearchResult<TQuantumType>? SubImageSearch(IMagickImage<TQuantumType> image, ErrorMetric metric);

		IMagickSearchResult<TQuantumType>? SubImageSearch(IMagickImage<TQuantumType> image, ErrorMetric metric, double similarityThreshold);

		void Transparent(IMagickColor<TQuantumType> color);

		void TransparentChroma(IMagickColor<TQuantumType> colorLow, IMagickColor<TQuantumType> colorHigh);

		IMagickImage<TQuantumType>? UniqueColors();
	}
	public interface IMagickNET
	{
		string Delegates { get; }

		string Features { get; }

		IReadOnlyList<string> FontFamilies { get; }

		IReadOnlyList<string> FontNames { get; }

		string ImageMagickVersion { get; }

		IReadOnlyCollection<IMagickFormatInfo> SupportedFormats { get; }

		string Version { get; }

		event EventHandler<LogEventArgs> Log;

		string? GetEnvironmentVariable(string name);

		void Initialize();

		void Initialize(string path);

		string Initialize(IConfigurationFiles configFiles);

		void Initialize(IConfigurationFiles configFiles, string path);

		void ResetRandomSeed();

		void SetDefaultFontFile(FileInfo file);

		void SetDefaultFontFile(string fileName);

		void SetEnvironmentVariable(string name, string value);

		void SetFontConfigDirectory(string path);

		void SetGhostscriptDirectory(string path);

		void SetGhostscriptFontDirectory(string path);

		void SetLogEvents(LogEventTypes events);

		void SetNativeLibraryDirectory(string path);

		void SetTempDirectory(string path);

		void SetRandomSeed(ulong seed);
	}
	public interface IQuantum
	{
		uint Depth { get; }
	}
	public interface IQuantum<TQuantumType> : IQuantum where TQuantumType : struct, IConvertible
	{
		TQuantumType Max { get; }
	}
	public interface IResourceLimits
	{
		ulong Area { get; set; }

		ulong Disk { get; set; }

		ulong Height { get; set; }

		ulong ListLength { get; set; }

		ulong MaxMemoryRequest { get; set; }

		ulong MaxProfileSize { get; set; }

		ulong Memory { get; set; }

		ulong Thread { get; set; }

		ulong Throttle { get; set; }

		ulong Time { get; set; }

		ulong Width { get; set; }

		void LimitMemory(Percentage percentage);
	}
	public interface IConvolveMatrix : IDoubleMatrix
	{
	}
	public interface IDoubleMatrix
	{
		uint Order { get; }

		double this[int x, int y] { get; set; }

		double GetValue(int x, int y);

		void SetColumn(int x, params double[] values);

		void SetRow(int y, params double[] values);

		void SetValue(int x, int y, double value);

		double[] ToArray();
	}
	public interface IMagickColorMatrix : IDoubleMatrix
	{
	}
	public interface IOpenCL
	{
		bool IsEnabled { get; set; }

		IReadOnlyList<IOpenCLDevice> Devices { get; }

		void SetCacheDirectory(string path);
	}
	public interface IOpenCLDevice
	{
		double BenchmarkScore { get; }

		OpenCLDeviceType DeviceType { get; }

		bool IsEnabled { get; set; }

		IReadOnlyList<IOpenCLKernelProfileRecord> KernelProfileRecords { get; }

		string Name { get; }

		bool ProfileKernels { get; set; }

		string Version { get; }
	}
	public interface IOpenCLKernelProfileRecord
	{
		ulong Count { get; }

		ulong MaximumDuration { get; }

		ulong MinimumDuration { get; }

		string Name { get; }

		ulong TotalDuration { get; }
	}
	public interface IPixelCollection<TQuantumType> : IEnumerable<IPixel<TQuantumType>>, IEnumerable, IDisposable where TQuantumType : struct, IConvertible
	{
		uint Channels { get; }

		IPixel<TQuantumType>? this[int x, int y] { get; }

		TQuantumType[]? GetArea(int x, int y, uint width, uint height);

		TQuantumType[]? GetArea(IMagickGeometry geometry);

		uint? GetChannelIndex(PixelChannel channel);

		IPixel<TQuantumType> GetPixel(int x, int y);

		TQuantumType[]? GetValue(int x, int y);

		TQuantumType[]? GetValues();

		void SetArea(int x, int y, uint width, uint height, TQuantumType[] values);

		void SetArea(IMagickGeometry geometry, TQuantumType[] values);

		void SetByteArea(int x, int y, uint width, uint height, byte[] values);

		void SetByteArea(IMagickGeometry geometry, byte[] values);

		void SetBytePixels(byte[] values);

		void SetDoubleArea(int x, int y, uint width, uint height, double[] values);

		void SetDoubleArea(IMagickGeometry geometry, double[] values);

		void SetDoublePixels(double[] values);

		void SetIntArea(int x, int y, uint width, uint height, int[] values);

		void SetIntArea(IMagickGeometry geometry, int[] values);

		void SetIntPixels(int[] values);

		void SetPixel(IPixel<TQuantumType> pixel);

		void SetPixel(IEnumerable<IPixel<TQuantumType>> pixels);

		void SetPixel(int x, int y, TQuantumType[] value);

		void SetPixels(TQuantumType[] values);

		TQuantumType[]? ToArray();

		byte[]? ToByteArray(int x, int y, uint width, uint height, string mapping);

		byte[]? ToByteArray(int x, int y, uint width, uint height, PixelMapping mapping);

		byte[]? ToByteArray(IMagickGeometry geometry, string mapping);

		byte[]? ToByteArray(IMagickGeometry geometry, PixelMapping mapping);

		byte[]? ToByteArray(string mapping);

		byte[]? ToByteArray(PixelMapping mapping);

		ushort[]? ToShortArray(int x, int y, uint width, uint height, string mapping);

		ushort[]? ToShortArray(int x, int y, uint width, uint height, PixelMapping mapping);

		ushort[]? ToShortArray(IMagickGeometry geometry, string mapping);

		ushort[]? ToShortArray(IMagickGeometry geometry, PixelMapping mapping);

		ushort[]? ToShortArray(string mapping);

		ushort[]? ToShortArray(PixelMapping mapping);
	}
	public interface IPixel<TQuantumType> : IEquatable<IPixel<TQuantumType>?>, IEquatable<IMagickColor<TQuantumType>?> where TQuantumType : struct, IConvertible
	{
		uint Channels { get; }

		int X { get; }

		int Y { get; }

		TQuantumType this[uint channel] { get; set; }

		TQuantumType GetChannel(uint channel);

		void SetChannel(uint channel, TQuantumType value);

		void SetValues(TQuantumType[] values);

		TQuantumType[] ToArray();

		IMagickColor<TQuantumType>? ToColor();
	}
	public interface IUnsafePixelCollection<TQuantumType> : IPixelCollection<TQuantumType>, IEnumerable<IPixel<TQuantumType>>, IEnumerable, IDisposable where TQuantumType : struct, IConvertible
	{
		IntPtr GetAreaPointer(int x, int y, uint width, uint height);

		IntPtr GetAreaPointer(IMagickGeometry geometry);
	}
	public sealed class ClipPath : IClipPath
	{
		public string Name { get; }

		public IXPathNavigable Path { get; }

		internal ClipPath(string name, IXPathNavigable path)
		{
			Name = name;
			Path = path;
		}
	}
	internal sealed class ClipPathReader
	{
		private readonly uint _height;

		private readonly uint _width;

		private readonly PointD[] _first = new PointD[3];

		private readonly PointD[] _last = new PointD[3];

		private readonly StringBuilder _path = new StringBuilder();

		private int _index;

		private bool _inSubpath;

		private int _knotCount;

		private ClipPathReader(uint width, uint height)
		{
			_width = width;
			_height = height;
			_index = 0;
		}

		public static string Read(uint width, uint height, byte[] data)
		{
			return new ClipPathReader(width, height).Read(data);
		}

		private string Read(byte[] data)
		{
			while (_index < data.Length)
			{
				switch (ByteConverter.ToShort(data, ref _index))
				{
				case 0:
				case 3:
					SetKnotCount(data);
					break;
				case 1:
				case 2:
				case 4:
				case 5:
					AddPath(data);
					break;
				default:
					_index += 24;
					break;
				}
			}
			return _path.ToString();
		}

		private void AddPath(byte[] data)
		{
			if (_knotCount == 0)
			{
				_index += 24;
				return;
			}
			PointD[] array = CreatePoint(data);
			if (!_inSubpath)
			{
				_path.AppendFormat(CultureInfo.InvariantCulture, "M {0:0.###} {1:0.###}\n", array[1].X, array[1].Y);
				for (int i = 0; i < 3; i++)
				{
					_first[i] = array[i];
					_last[i] = array[i];
				}
			}
			else
			{
				if (_last[1].X == _last[2].X && _last[1].Y == _last[2].Y && array[0].X == array[1].X && array[0].Y == array[1].Y)
				{
					_path.AppendFormat(CultureInfo.InvariantCulture, "L {0:0.###} {1:0.###}\n", array[1].X, array[1].Y);
				}
				else
				{
					_path.AppendFormat(CultureInfo.InvariantCulture, "C {0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###}\n", _last[2].X, _last[2].Y, array[0].X, array[0].Y, array[1].X, array[1].Y);
				}
				for (int j = 0; j < 3; j++)
				{
					_last[j] = array[j];
				}
			}
			_inSubpath = true;
			_knotCount--;
			if (_knotCount == 0)
			{
				ClosePath();
				_inSubpath = false;
			}
		}

		private void ClosePath()
		{
			if (_last[1].X == _last[2].X && _last[1].Y == _last[2].Y && _first[0].X == _first[1].X && _first[0].Y == _first[1].Y)
			{
				_path.AppendFormat(CultureInfo.InvariantCulture, "L {0:0.###} {1:0.###} Z\n", _first[1].X, _first[1].Y);
				return;
			}
			_path.AppendFormat(CultureInfo.InvariantCulture, "C {0:0.###} {1:0.###} {2:0.###} {3:0.###} {4:0.###} {5:0.###} Z\n", _last[2].X, _last[2].Y, _first[0].X, _first[0].Y, _first[1].X, _first[1].Y);
		}

		private PointD[] CreatePoint(byte[] data)
		{
			PointD[] array = new PointD[3];
			for (int i = 0; i < 3; i++)
			{
				uint num = (uint)ByteConverter.ToUInt(data, ref _index);
				int num2 = (int)num;
				if (num > int.MaxValue)
				{
					num2 = (int)num - -1 - 1;
				}
				uint num3 = (uint)ByteConverter.ToUInt(data, ref _index);
				int num4 = (int)num3;
				if (num3 > int.MaxValue)
				{
					num4 = (int)num3 - -1 - 1;
				}
				array[i] = new PointD((double)num4 * (double)_width / 4096.0 / 4096.0, (double)num2 * (double)_height / 4096.0 / 4096.0);
			}
			return array;
		}

		private void SetKnotCount(byte[] data)
		{
			if (_knotCount != 0)
			{
				_index += 24;
				return;
			}
			_knotCount = ByteConverter.ToShort(data, ref _index);
			_index += 22;
		}
	}
	public sealed class EightBimProfile : ImageProfile, IEightBimProfile, IImageProfile, IEquatable<IImageProfile?>
	{
		private static readonly short ExifProfileId = 1058;

		private static readonly short IptcProfileId = 1028;

		private static readonly short XmpProfileId = 1060;

		private readonly uint _height;

		private readonly uint _width;

		private Collection<IEightBimValue>? _values;

		public IReadOnlyList<IClipPath> ClipPaths
		{
			get
			{
				Initialize();
				List<IClipPath> list = new List<IClipPath>(_values.Count);
				foreach (IEightBimValue value in _values)
				{
					ClipPath clipPath = CreateClipPath(value);
					if (clipPath != null)
					{
						list.Add(clipPath);
					}
				}
				return list;
			}
		}

		public IReadOnlyList<IEightBimValue> Values
		{
			get
			{
				Initialize();
				return _values;
			}
		}

		public EightBimProfile(byte[] data)
			: base("8bim", data)
		{
		}

		public EightBimProfile(string fileName)
			: base("8bim", fileName)
		{
		}

		public EightBimProfile(Stream stream)
			: base("8bim", stream)
		{
		}

		public EightBimProfile(IMagickImage image, byte[] data)
			: base("8bim", data)
		{
			Throw.IfNull(image, "image");
			_width = image.Width;
			_height = image.Height;
		}

		public IExifProfile? GetExifProfile()
		{
			Initialize();
			IEightBimValue eightBimValue = FindValue(ExifProfileId);
			if (eightBimValue == null)
			{
				return null;
			}
			return new ExifProfile(eightBimValue.ToByteArray());
		}

		public IIptcProfile? GetIptcProfile()
		{
			Initialize();
			IEightBimValue eightBimValue = FindValue(IptcProfileId);
			if (eightBimValue == null)
			{
				return null;
			}
			return new IptcProfile(eightBimValue.ToByteArray());
		}

		public IXmpProfile? GetXmpProfile()
		{
			Initialize();
			IEightBimValue eightBimValue = FindValue(XmpProfileId);
			if (eightBimValue == null)
			{
				return null;
			}
			return new XmpProfile(eightBimValue.ToByteArray());
		}

		public void SetExifProfile(IExifProfile? profile)
		{
			Initialize();
			IEightBimValue eightBimValue = FindValue(ExifProfileId);
			if (eightBimValue != null)
			{
				_values.Remove(eightBimValue);
			}
			SetData(null);
			if (profile != null)
			{
				byte[] array = profile.ToByteArray();
				if (array != null)
				{
					_values.Add(new EightBimValue(ExifProfileId, null, array));
				}
			}
		}

		public void SetIptcProfile(IIptcProfile? profile)
		{
			Initialize();
			IEightBimValue eightBimValue = FindValue(IptcProfileId);
			if (eightBimValue != null)
			{
				_values.Remove(eightBimValue);
			}
			SetData(null);
			if (profile != null)
			{
				byte[] array = profile.ToByteArray();
				if (array != null)
				{
					_values.Add(new EightBimValue(IptcProfileId, null, array));
				}
			}
		}

		public void SetXmpProfile(IXmpProfile? profile)
		{
			Initialize();
			IEightBimValue eightBimValue = FindValue(XmpProfileId);
			if (eightBimValue != null)
			{
				_values.Remove(eightBimValue);
			}
			SetData(null);
			if (profile != null)
			{
				byte[] array = profile.ToByteArray();
				if (array != null)
				{
					_values.Add(new EightBimValue(XmpProfileId, null, array));
				}
			}
		}

		protected override void UpdateData()
		{
			byte[] data = GetData();
			if (data == null && _values != null)
			{
				data = EightBimWriter.Write(_values);
				SetData(data);
			}
		}

		private ClipPath? CreateClipPath(IEightBimValue value)
		{
			if (value.Name == null)
			{
				return null;
			}
			string clipPath = GetClipPath(value.ToByteArray());
			if (string.IsNullOrEmpty(clipPath))
			{
				return null;
			}
			XmlDocument xmlDocument = XmlHelper.CreateDocument();
			xmlDocument.CreateXmlDeclaration("1.0", "iso-8859-1", null);
			XmlElement xmlElement = XmlHelper.CreateElement(xmlDocument, "svg");
			XmlHelper.SetAttribute(xmlElement, "width", _width);
			XmlHelper.SetAttribute(xmlElement, "height", _height);
			XmlElement element = XmlHelper.CreateElement(XmlHelper.CreateElement(xmlElement, "g"), "path");
			XmlHelper.SetAttribute(element, "fill", "#00000000");
			XmlHelper.SetAttribute(element, "stroke", "#00000000");
			XmlHelper.SetAttribute(element, "stroke-width", "0");
			XmlHelper.SetAttribute(element, "stroke-antialiasing", "false");
			XmlHelper.SetAttribute(element, "d", clipPath);
			return new ClipPath(value.Name, xmlDocument.CreateNavigator());
		}

		private IEightBimValue? FindValue(int id)
		{
			return _values?.Where((IEightBimValue value) => value.Id == id).FirstOrDefault();
		}

		private string? GetClipPath(byte[] data)
		{
			if (_width == 0 || _height == 0)
			{
				return null;
			}
			return ClipPathReader.Read(_width, _height, data);
		}

		[MemberNotNull("_values")]
		private void Initialize()
		{
			if (_values == null)
			{
				_values = EightBimReader.Read(GetData());
			}
		}
	}
	internal sealed class EightBimReader
	{
		private readonly byte[] _data;

		private readonly Collection<IEightBimValue> _values = new Collection<IEightBimValue>();

		public EightBimReader(byte[] data)
		{
			_data = data;
		}

		public static Collection<IEightBimValue> Read(byte[]? data)
		{
			if (data == null || data.Length == 0)
			{
				return new Collection<IEightBimValue>();
			}
			EightBimReader eightBimReader = new EightBimReader(data);
			eightBimReader.Read();
			return eightBimReader._values;
		}

		private void Read()
		{
			int offset = 0;
			while (offset < _data.Length)
			{
				if (_data[offset++] != 56 || _data[offset++] != 66 || _data[offset++] != 73 || _data[offset++] != 77)
				{
					continue;
				}
				if (offset + 7 > _data.Length)
				{
					break;
				}
				short num = ByteConverter.ToShort(_data, ref offset);
				string name = null;
				int num2 = _data[offset++];
				if (num2 != 0)
				{
					if (num > 1999 && num < 2998 && offset + num2 < _data.Length)
					{
						name = Encoding.ASCII.GetString(_data, offset, num2);
					}
					offset += num2;
				}
				if (((uint)(num2 + 1) & (true ? 1u : 0u)) != 0)
				{
					offset++;
				}
				num2 = ByteConverter.ToUInt(_data, ref offset);
				if (offset + num2 > _data.Length || num2 < 0)
				{
					break;
				}
				if (num2 != 0)
				{
					byte[] array = new byte[num2];
					Array.Copy(_data, offset, array, 0, num2);
					_values.Add(new EightBimValue(num, name, array));
				}
				offset += num2;
				if (((uint)num2 & (true ? 1u : 0u)) != 0)
				{
					offset++;
				}
			}
		}
	}
	public sealed class EightBimValue : IEightBimValue, IEquatable<IEightBimValue?>
	{
		private readonly byte[] _data;

		public short Id { get; }

		public string? Name { get; }

		internal EightBimValue(short id, string? name, byte[] data)
		{
			Id = id;
			Name = name;
			_data = data;
		}

		public override bool Equals(object? obj)
		{
			return Equals(obj as IEightBimValue);
		}

		public bool Equals(IEightBimValue? other)
		{
			if (other == null)
			{
				return false;
			}
			if (this == other)
			{
				return true;
			}
			if (Id != other.Id)
			{
				return false;
			}
			byte[] array = other.ToByteArray();
			if (_data.Length != array.Length)
			{
				return false;
			}
			for (int i = 0; i < _data.Length; i++)
			{
				if (_data[i] != array[i])
				{
					return false;
				}
			}
			return true;
		}

		public override int GetHashCode()
		{
			return _data.GetHashCode() ^ Id.GetHashCode();
		}

		public byte[] ToByteArray()
		{
			byte[] array = new byte[_data.Length];
			Array.Copy(_data, 0, array, 0, _data.Length);
			return array;
		}

		public override string ToString()
		{
			return ToString(Encoding.UTF8);
		}

		public string ToString(Encoding encoding)
		{
			Throw.IfNull(encoding, "encoding");
			return encoding.GetString(_data);
		}
	}
	internal sealed class EightBimWriter
	{
		public static byte[] Write(Collection<IEightBimValue> values)
		{
			if (values.Count == 0)
			{
				return Array.Empty<byte>();
			}
			using MemoryStream memoryStream = new MemoryStream();
			foreach (IEightBimValue value in values)
			{
				memoryStream.WriteByte(56);
				memoryStream.WriteByte(66);
				memoryStream.WriteByte(73);
				memoryStream.WriteByte(77);
				memoryStream.WriteBytes(ByteConverter.FromShortReversed(value.Id));
				int num = 0;
				byte[] array = null;
				if (value.Id > 1999 && value.Id < 2998 && value.Name != null && value.Name.Length < 255)
				{
					array = Encoding.ASCII.GetBytes(value.Name);
					num = array.Length;
				}
				memoryStream.WriteByte((byte)num);
				if (array != null)
				{
					memoryStream.WriteBytes(array);
				}
				if (((uint)(num + 1) & (true ? 1u : 0u)) != 0)
				{
					memoryStream.WriteByte(0);
				}
				array = value.ToByteArray();
				memoryStream.WriteBytes(ByteConverter.FromUnsignedIntegerReversed((uint)array.Length));
				if (array.Length != 0)
				{
					memoryStream.WriteBytes(array);
				}
				if (((uint)array.Length & (true ? 1u : 0u)) != 0)
				{
					memoryStream.WriteByte(0);
				}
			}
			return memoryStream.ToArray();
		}
	}
	public interface IClipPath
	{
		string Name { get; }

		IXPathNavigable Path { get; }
	}
	public interface IEightBimProfile : IImageProfile, IEquatable<IImageProfile?>
	{
		IReadOnlyList<IClipPath> ClipPaths { get; }

		IReadOnlyList<IEightBimValue> Values { get; }

		IExifProfile? GetExifProfile();

		IIptcProfile? GetIptcProfile();

		IXmpProfile? GetXmpProfile();

		void SetExifProfile(IExifProfile? profile);

		void SetIptcProfile(IIptcProfile? profile);

		void SetXmpProfile(IXmpProfile? profile);
	}
	public interface IEightBimValue : IEquatable<IEightBimValue?>
	{
		short Id { get; }

		string? Name { get; }

		byte[] ToByteArray();

		string ToString(Encoding encoding);
	}
	public sealed class ColorProfile : ImageProfile, IColorProfile, IImageProfile, IEquatable<IImageProfile?>
	{
		private static readonly object _syncRoot = new object();

		private static readonly Dictionary<string, ColorProfile> _profiles = new Dictionary<string, ColorProfile>();

		private ColorProfileData? _data;

		public static ColorProfile AdobeRGB1998 => Load("ImageMagick.Resources.ColorProfiles.RGB", "AdobeRGB1998.icc");

		public static ColorProfile AppleRGB => Load("ImageMagick.Resources.ColorProfiles.RGB", "AppleRGB.icc");

		public static ColorProfile CoatedFOGRA39 => Load("ImageMagick.Resources.ColorProfiles.CMYK", "CoatedFOGRA39.icc");

		public static ColorProfile ColorMatchRGB => Load("ImageMagick.Resources.ColorProfiles.RGB", "ColorMatchRGB.icc");

		public static ColorProfile SRGB => Load("ImageMagick.Resources.ColorProfiles.RGB", "SRGB.icm");

		public static ColorProfile USWebCoatedSWOP => Load("ImageMagick.Resources.ColorProfiles.CMYK", "USWebCoatedSWOP.icc");

		public ColorSpace ColorSpace
		{
			get
			{
				Initialize();
				return _data.ColorSpace;
			}
		}

		public string? Copyright
		{
			get
			{
				Initialize();
				return _data.Copyright;
			}
		}

		public string? Description
		{
			get
			{
				Initialize();
				return _data.Description;
			}
		}

		public string? Manufacturer
		{
			get
			{
				Initialize();
				return _data.Manufacturer;
			}
		}

		public string? Model
		{
			get
			{
				Initialize();
				return _data.Model;
			}
		}

		public ColorProfile(byte[] data)
			: base("icc", data)
		{
		}

		public ColorProfile(Stream stream)
			: base("icc", stream)
		{
		}

		public ColorProfile(string fileName)
			: base("icc", fileName)
		{
		}

		[Obsolete("This constructor will be removed in the next major release (only 'icc' will be used in the future).")]
		public ColorProfile(string name, byte[] data)
			: base(name, data)
		{
		}

		private static ColorProfile Load(string resourcePath, string resourceName)
		{
			if (!_profiles.ContainsKey(resourceName))
			{
				lock (_syncRoot)
				{
					if (!_profiles.ContainsKey(resourceName))
					{
						using Stream stream = TypeHelper.GetManifestResourceStream(typeof(ColorProfile), resourcePath, resourceName);
						_profiles[resourceName] = new ColorProfile(stream);
					}
				}
			}
			return _profiles[resourceName];
		}

		[MemberNotNull("_data")]
		private void Initialize()
		{
			_data = ColorProfileReader.Read(GetData());
		}
	}
	internal sealed class ColorProfileData
	{
		public ColorSpace ColorSpace { get; set; }

		public string? Copyright { get; set; }

		public string? Description { get; set; }

		public string? Manufacturer { get; set; }

		public string? Model { get; set; }
	}
	internal sealed class ColorProfileReader
	{
		private readonly ColorProfileData _data = new ColorProfileData();

		private readonly EndianReader _reader;

		private ColorProfileReader(byte[] data)
		{
			_reader = new EndianReader(data);
		}

		public static ColorProfileData Read(byte[]? data)
		{
			if (data == null)
			{
				return new ColorProfileData();
			}
			ColorProfileReader colorProfileReader = new ColorProfileReader(data);
			colorProfileReader.ReadColorSpace();
			colorProfileReader.ReadTagTable();
			return colorProfileReader._data;
		}

		private static ColorSpace DetermineColorSpace(string colorSpace)
		{
			return colorSpace switch
			{
				"CMY" => ColorSpace.CMY, 
				"CMYK" => ColorSpace.CMYK, 
				"GRAY" => ColorSpace.Gray, 
				"HSL" => ColorSpace.HSL, 
				"HSV" => ColorSpace.HSV, 
				"Lab" => ColorSpace.Lab, 
				"Luv" => ColorSpace.YUV, 
				"RGB" => ColorSpace.sRGB, 
				"XYZ" => ColorSpace.XYZ, 
				"YCbr" => ColorSpace.YCbCr, 
				_ => throw new NotSupportedException(colorSpace), 
			};
		}

		private void ReadColorSpace()
		{
			_reader.Seek(16u);
			string text = _reader.ReadString(4u);
			if (text != null)
			{
				_data.ColorSpace = DetermineColorSpace(text.TrimEnd(Array.Empty<char>()));
			}
		}

		private void ReadTagTable()
		{
			if (!_reader.Seek(128u))
			{
				return;
			}
			uint? num = _reader.ReadLong();
			for (int i = 0; i < num; i++)
			{
				switch (_reader.ReadLong())
				{
				case 1668313716u:
					_data.Copyright = ReadTag();
					break;
				case 1684370275u:
					_data.Description = ReadTag();
					break;
				case 1684893284u:
					_data.Manufacturer = ReadTag();
					break;
				case 1684890724u:
					_data.Model = ReadTag();
					break;
				default:
					_reader.Skip(8u);
					break;
				}
			}
		}

		private 

NAudio.dll

Decompiled 3 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using NAudio.Wave.SampleProviders;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Mark Heath & Contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2021")]
[assembly: AssemblyDescription("NAudio, an audio library for .NET")]
[assembly: AssemblyFileVersion("2.0.1.0")]
[assembly: AssemblyInformationalVersion("2.0.1")]
[assembly: AssemblyProduct("NAudio")]
[assembly: AssemblyTitle("NAudio")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.1.0")]
[module: UnverifiableCode]
namespace NAudio.Wave;

public class AudioFileReader : WaveStream, ISampleProvider
{
	private WaveStream readerStream;

	private readonly SampleChannel sampleChannel;

	private readonly int destBytesPerSample;

	private readonly int sourceBytesPerSample;

	private readonly long length;

	private readonly object lockObject;

	public string FileName { get; }

	public override WaveFormat WaveFormat => sampleChannel.WaveFormat;

	public override long Length => length;

	public override long Position
	{
		get
		{
			return SourceToDest(((Stream)(object)readerStream).Position);
		}
		set
		{
			lock (lockObject)
			{
				((Stream)(object)readerStream).Position = DestToSource(value);
			}
		}
	}

	public float Volume
	{
		get
		{
			return sampleChannel.Volume;
		}
		set
		{
			sampleChannel.Volume = value;
		}
	}

	public AudioFileReader(string fileName)
	{
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Expected O, but got Unknown
		lockObject = new object();
		FileName = fileName;
		CreateReaderStream(fileName);
		sourceBytesPerSample = readerStream.WaveFormat.BitsPerSample / 8 * readerStream.WaveFormat.Channels;
		sampleChannel = new SampleChannel((IWaveProvider)(object)readerStream, false);
		destBytesPerSample = 4 * sampleChannel.WaveFormat.Channels;
		length = SourceToDest(((Stream)(object)readerStream).Length);
	}

	private void CreateReaderStream(string fileName)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Invalid comparison between Unknown and I4
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Invalid comparison between Unknown and I4
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Expected O, but got Unknown
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Expected O, but got Unknown
		if (fileName.EndsWith(".wav", StringComparison.OrdinalIgnoreCase))
		{
			readerStream = (WaveStream)new WaveFileReader(fileName);
			if ((int)readerStream.WaveFormat.Encoding != 1 && (int)readerStream.WaveFormat.Encoding != 3)
			{
				readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
				readerStream = (WaveStream)new BlockAlignReductionStream(readerStream);
			}
		}
		else if (fileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase))
		{
			readerStream = (WaveStream)(object)new Mp3FileReader(fileName);
		}
		else if (fileName.EndsWith(".aiff", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith(".aif", StringComparison.OrdinalIgnoreCase))
		{
			readerStream = (WaveStream)new AiffFileReader(fileName);
		}
		else
		{
			readerStream = (WaveStream)new MediaFoundationReader(fileName);
		}
	}

	public override int Read(byte[] buffer, int offset, int count)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		WaveBuffer val = new WaveBuffer(buffer);
		int count2 = count / 4;
		return Read(val.FloatBuffer, offset / 4, count2) * 4;
	}

	public int Read(float[] buffer, int offset, int count)
	{
		lock (lockObject)
		{
			return sampleChannel.Read(buffer, offset, count);
		}
	}

	private long SourceToDest(long sourceBytes)
	{
		return destBytesPerSample * (sourceBytes / sourceBytesPerSample);
	}

	private long DestToSource(long destBytes)
	{
		return sourceBytesPerSample * (destBytes / destBytesPerSample);
	}

	protected override void Dispose(bool disposing)
	{
		if (disposing && readerStream != null)
		{
			((Stream)(object)readerStream).Dispose();
			readerStream = null;
		}
		((Stream)this).Dispose(disposing);
	}
}
public class Mp3FileReader : Mp3FileReaderBase
{
	public Mp3FileReader(string mp3FileName)
		: base((Stream)File.OpenRead(mp3FileName), new FrameDecompressorBuilder(CreateAcmFrameDecompressor), true)
	{
	}//IL_000e: Unknown result type (might be due to invalid IL or missing references)
	//IL_0019: Expected O, but got Unknown


	public Mp3FileReader(Stream inputStream)
		: base(inputStream, new FrameDecompressorBuilder(CreateAcmFrameDecompressor), false)
	{
	}//IL_0009: Unknown result type (might be due to invalid IL or missing references)
	//IL_0014: Expected O, but got Unknown


	public static IMp3FrameDecompressor CreateAcmFrameDecompressor(WaveFormat mp3Format)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return (IMp3FrameDecompressor)new AcmMp3FrameDecompressor(mp3Format);
	}
}

NAudio.Asio.dll

Decompiled 3 months ago
using System;
using System.Diagnostics;
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 Microsoft.Win32;
using NAudio.Wave.Asio;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Mark Heath")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2021")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyProduct("NAudio.Asio")]
[assembly: AssemblyTitle("NAudio.Asio")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.0.0")]
[module: UnverifiableCode]
namespace NAudio.Wave
{
	public class AsioAudioAvailableEventArgs : EventArgs
	{
		public IntPtr[] InputBuffers { get; private set; }

		public IntPtr[] OutputBuffers { get; private set; }

		public bool WrittenToOutputBuffers { get; set; }

		public int SamplesPerBuffer { get; private set; }

		public AsioSampleType AsioSampleType { get; private set; }

		public AsioAudioAvailableEventArgs(IntPtr[] inputBuffers, IntPtr[] outputBuffers, int samplesPerBuffer, AsioSampleType asioSampleType)
		{
			InputBuffers = inputBuffers;
			OutputBuffers = outputBuffers;
			SamplesPerBuffer = samplesPerBuffer;
			AsioSampleType = asioSampleType;
		}

		public unsafe int GetAsInterleavedSamples(float[] samples)
		{
			int num = InputBuffers.Length;
			if (samples.Length < SamplesPerBuffer * num)
			{
				throw new ArgumentException("Buffer not big enough");
			}
			int num2 = 0;
			if (AsioSampleType == AsioSampleType.Int32LSB)
			{
				for (int i = 0; i < SamplesPerBuffer; i++)
				{
					for (int j = 0; j < num; j++)
					{
						samples[num2++] = (float)(*(int*)((byte*)(void*)InputBuffers[j] + (nint)i * (nint)4)) / 2.1474836E+09f;
					}
				}
			}
			else if (AsioSampleType == AsioSampleType.Int16LSB)
			{
				for (int k = 0; k < SamplesPerBuffer; k++)
				{
					for (int l = 0; l < num; l++)
					{
						samples[num2++] = (float)(*(short*)((byte*)(void*)InputBuffers[l] + (nint)k * (nint)2)) / 32767f;
					}
				}
			}
			else if (AsioSampleType == AsioSampleType.Int24LSB)
			{
				for (int m = 0; m < SamplesPerBuffer; m++)
				{
					for (int n = 0; n < num; n++)
					{
						byte* ptr = (byte*)(void*)InputBuffers[n] + m * 3;
						int num3 = *ptr | (ptr[1] << 8) | ((sbyte)ptr[2] << 16);
						samples[num2++] = (float)num3 / 8388608f;
					}
				}
			}
			else
			{
				if (AsioSampleType != AsioSampleType.Float32LSB)
				{
					throw new NotImplementedException($"ASIO Sample Type {AsioSampleType} not supported");
				}
				for (int num4 = 0; num4 < SamplesPerBuffer; num4++)
				{
					for (int num5 = 0; num5 < num; num5++)
					{
						samples[num2++] = *(float*)((byte*)(void*)InputBuffers[num5] + (nint)num4 * (nint)4);
					}
				}
			}
			return SamplesPerBuffer * num;
		}

		[Obsolete("Better performance if you use the overload that takes an array, and reuse the same one")]
		public float[] GetAsInterleavedSamples()
		{
			int num = InputBuffers.Length;
			float[] array = new float[SamplesPerBuffer * num];
			GetAsInterleavedSamples(array);
			return array;
		}
	}
	public class AsioOut : IWavePlayer, IDisposable
	{
		private AsioDriverExt driver;

		private IWaveProvider sourceStream;

		private PlaybackState playbackState;

		private int nbSamples;

		private byte[] waveBuffer;

		private AsioSampleConvertor.SampleConvertor convertor;

		private string driverName;

		private readonly SynchronizationContext syncContext;

		private bool isInitialized;

		public int PlaybackLatency
		{
			get
			{
				driver.Driver.GetLatencies(out var _, out var outputLatency);
				return outputLatency;
			}
		}

		public bool AutoStop { get; set; }

		public bool HasReachedEnd { get; private set; }

		public PlaybackState PlaybackState => playbackState;

		public string DriverName => driverName;

		public int NumberOfOutputChannels { get; private set; }

		public int NumberOfInputChannels { get; private set; }

		public int DriverInputChannelCount => driver.Capabilities.NbInputChannels;

		public int DriverOutputChannelCount => driver.Capabilities.NbOutputChannels;

		public int FramesPerBuffer
		{
			get
			{
				if (!isInitialized)
				{
					throw new Exception("Not initialized yet. Call this after calling Init");
				}
				return nbSamples;
			}
		}

		public int ChannelOffset { get; set; }

		public int InputChannelOffset { get; set; }

		[Obsolete("this function will be removed in a future NAudio as ASIO does not support setting the volume on the device")]
		public float Volume
		{
			get
			{
				return 1f;
			}
			set
			{
				if (value != 1f)
				{
					throw new InvalidOperationException("AsioOut does not support setting the device volume");
				}
			}
		}

		public event EventHandler<StoppedEventArgs> PlaybackStopped;

		public event EventHandler<AsioAudioAvailableEventArgs> AudioAvailable;

		public event EventHandler DriverResetRequest;

		public AsioOut()
			: this(0)
		{
		}

		public AsioOut(string driverName)
		{
			syncContext = SynchronizationContext.Current;
			InitFromName(driverName);
		}

		public AsioOut(int driverIndex)
		{
			syncContext = SynchronizationContext.Current;
			string[] driverNames = GetDriverNames();
			if (driverNames.Length == 0)
			{
				throw new ArgumentException("There is no ASIO Driver installed on your system");
			}
			if (driverIndex < 0 || driverIndex > driverNames.Length)
			{
				throw new ArgumentException($"Invalid device number. Must be in the range [0,{driverNames.Length}]");
			}
			InitFromName(driverNames[driverIndex]);
		}

		~AsioOut()
		{
			Dispose();
		}

		public void Dispose()
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (driver != null)
			{
				if ((int)playbackState != 0)
				{
					driver.Stop();
				}
				driver.ResetRequestCallback = null;
				driver.ReleaseDriver();
				driver = null;
			}
		}

		public static string[] GetDriverNames()
		{
			return AsioDriver.GetAsioDriverNames();
		}

		public static bool isSupported()
		{
			return GetDriverNames().Length != 0;
		}

		public bool IsSampleRateSupported(int sampleRate)
		{
			return driver.IsSampleRateSupported(sampleRate);
		}

		private void InitFromName(string driverName)
		{
			this.driverName = driverName;
			AsioDriver asioDriverByName = AsioDriver.GetAsioDriverByName(driverName);
			driver = new AsioDriverExt(asioDriverByName);
			driver.ResetRequestCallback = OnDriverResetRequest;
			ChannelOffset = 0;
		}

		private void OnDriverResetRequest()
		{
			this.DriverResetRequest?.Invoke(this, EventArgs.Empty);
		}

		public void ShowControlPanel()
		{
			driver.ShowControlPanel();
		}

		public void Play()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState != 1)
			{
				playbackState = (PlaybackState)1;
				HasReachedEnd = false;
				driver.Start();
			}
		}

		public void Stop()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			playbackState = (PlaybackState)0;
			driver.Stop();
			HasReachedEnd = false;
			RaisePlaybackStopped(null);
		}

		public void Pause()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			playbackState = (PlaybackState)2;
			driver.Stop();
		}

		public void Init(IWaveProvider waveProvider)
		{
			InitRecordAndPlayback(waveProvider, 0, -1);
		}

		public void InitRecordAndPlayback(IWaveProvider waveProvider, int recordChannels, int recordOnlySampleRate)
		{
			if (isInitialized)
			{
				throw new InvalidOperationException("Already initialised this instance of AsioOut - dispose and create a new one");
			}
			isInitialized = true;
			int num = ((waveProvider != null) ? waveProvider.WaveFormat.SampleRate : recordOnlySampleRate);
			if (waveProvider != null)
			{
				sourceStream = waveProvider;
				NumberOfOutputChannels = waveProvider.WaveFormat.Channels;
				convertor = AsioSampleConvertor.SelectSampleConvertor(waveProvider.WaveFormat, driver.Capabilities.OutputChannelInfos[0].type);
			}
			else
			{
				NumberOfOutputChannels = 0;
			}
			if (!driver.IsSampleRateSupported(num))
			{
				throw new ArgumentException("SampleRate is not supported");
			}
			if (driver.Capabilities.SampleRate != (double)num)
			{
				driver.SetSampleRate(num);
			}
			driver.FillBufferCallback = driver_BufferUpdate;
			NumberOfInputChannels = recordChannels;
			nbSamples = driver.CreateBuffers(NumberOfOutputChannels, NumberOfInputChannels, useMaxBufferSize: false);
			driver.SetChannelOffset(ChannelOffset, InputChannelOffset);
			if (waveProvider != null)
			{
				waveBuffer = new byte[nbSamples * NumberOfOutputChannels * waveProvider.WaveFormat.BitsPerSample / 8];
			}
		}

		private unsafe void driver_BufferUpdate(IntPtr[] inputChannels, IntPtr[] outputChannels)
		{
			if (NumberOfInputChannels > 0)
			{
				EventHandler<AsioAudioAvailableEventArgs> audioAvailable = this.AudioAvailable;
				if (audioAvailable != null)
				{
					AsioAudioAvailableEventArgs asioAudioAvailableEventArgs = new AsioAudioAvailableEventArgs(inputChannels, outputChannels, nbSamples, driver.Capabilities.InputChannelInfos[0].type);
					audioAvailable(this, asioAudioAvailableEventArgs);
					if (asioAudioAvailableEventArgs.WrittenToOutputBuffers)
					{
						return;
					}
				}
			}
			if (NumberOfOutputChannels <= 0)
			{
				return;
			}
			int num = sourceStream.Read(waveBuffer, 0, waveBuffer.Length);
			if (num < waveBuffer.Length)
			{
				Array.Clear(waveBuffer, num, waveBuffer.Length - num);
			}
			fixed (byte* ptr = &waveBuffer[0])
			{
				void* value = ptr;
				convertor(new IntPtr(value), outputChannels, NumberOfOutputChannels, nbSamples);
			}
			if (num == 0)
			{
				if (AutoStop)
				{
					Stop();
				}
				HasReachedEnd = true;
			}
		}

		private void RaisePlaybackStopped(Exception e)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			EventHandler<StoppedEventArgs> handler = this.PlaybackStopped;
			if (handler == null)
			{
				return;
			}
			if (syncContext == null)
			{
				handler(this, new StoppedEventArgs(e));
				return;
			}
			syncContext.Post(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				handler(this, new StoppedEventArgs(e));
			}, null);
		}

		public string AsioInputChannelName(int channel)
		{
			if (channel <= DriverInputChannelCount)
			{
				return driver.Capabilities.InputChannelInfos[channel].name;
			}
			return "";
		}

		public string AsioOutputChannelName(int channel)
		{
			if (channel <= DriverOutputChannelCount)
			{
				return driver.Capabilities.OutputChannelInfos[channel].name;
			}
			return "";
		}
	}
}
namespace NAudio.Wave.Asio
{
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	public struct Asio64Bit
	{
		public uint hi;

		public uint lo;
	}
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	public struct AsioCallbacks
	{
		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public delegate void AsioBufferSwitchCallBack(int doubleBufferIndex, bool directProcess);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public delegate void AsioSampleRateDidChangeCallBack(double sRate);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public delegate int AsioAsioMessageCallBack(AsioMessageSelector selector, int value, IntPtr message, IntPtr opt);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public delegate IntPtr AsioBufferSwitchTimeInfoCallBack(IntPtr asioTimeParam, int doubleBufferIndex, bool directProcess);

		public AsioBufferSwitchCallBack pbufferSwitch;

		public AsioSampleRateDidChangeCallBack psampleRateDidChange;

		public AsioAsioMessageCallBack pasioMessage;

		public AsioBufferSwitchTimeInfoCallBack pbufferSwitchTimeInfo;
	}
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	public struct AsioChannelInfo
	{
		public int channel;

		public bool isInput;

		public bool isActive;

		public int channelGroup;

		[MarshalAs(UnmanagedType.U4)]
		public AsioSampleType type;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		public string name;
	}
	public class AsioDriver
	{
		[StructLayout(LayoutKind.Sequential, Pack = 2)]
		private class AsioDriverVTable
		{
			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate int ASIOInit(IntPtr _pUnknown, IntPtr sysHandle);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate void ASIOgetDriverName(IntPtr _pUnknown, StringBuilder name);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate int ASIOgetDriverVersion(IntPtr _pUnknown);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate void ASIOgetErrorMessage(IntPtr _pUnknown, StringBuilder errorMessage);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOstart(IntPtr _pUnknown);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOstop(IntPtr _pUnknown);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOgetChannels(IntPtr _pUnknown, out int numInputChannels, out int numOutputChannels);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOgetLatencies(IntPtr _pUnknown, out int inputLatency, out int outputLatency);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOgetBufferSize(IntPtr _pUnknown, out int minSize, out int maxSize, out int preferredSize, out int granularity);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOcanSampleRate(IntPtr _pUnknown, double sampleRate);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOgetSampleRate(IntPtr _pUnknown, out double sampleRate);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOsetSampleRate(IntPtr _pUnknown, double sampleRate);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOgetClockSources(IntPtr _pUnknown, out long clocks, int numSources);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOsetClockSource(IntPtr _pUnknown, int reference);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOgetSamplePosition(IntPtr _pUnknown, out long samplePos, ref Asio64Bit timeStamp);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOgetChannelInfo(IntPtr _pUnknown, ref AsioChannelInfo info);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOcreateBuffers(IntPtr _pUnknown, IntPtr bufferInfos, int numChannels, int bufferSize, IntPtr callbacks);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOdisposeBuffers(IntPtr _pUnknown);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOcontrolPanel(IntPtr _pUnknown);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOfuture(IntPtr _pUnknown, int selector, IntPtr opt);

			[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
			public delegate AsioError ASIOoutputReady(IntPtr _pUnknown);

			public ASIOInit init;

			public ASIOgetDriverName getDriverName;

			public ASIOgetDriverVersion getDriverVersion;

			public ASIOgetErrorMessage getErrorMessage;

			public ASIOstart start;

			public ASIOstop stop;

			public ASIOgetChannels getChannels;

			public ASIOgetLatencies getLatencies;

			public ASIOgetBufferSize getBufferSize;

			public ASIOcanSampleRate canSampleRate;

			public ASIOgetSampleRate getSampleRate;

			public ASIOsetSampleRate setSampleRate;

			public ASIOgetClockSources getClockSources;

			public ASIOsetClockSource setClockSource;

			public ASIOgetSamplePosition getSamplePosition;

			public ASIOgetChannelInfo getChannelInfo;

			public ASIOcreateBuffers createBuffers;

			public ASIOdisposeBuffers disposeBuffers;

			public ASIOcontrolPanel controlPanel;

			public ASIOfuture future;

			public ASIOoutputReady outputReady;
		}

		private IntPtr pAsioComObject;

		private IntPtr pinnedcallbacks;

		private AsioDriverVTable asioDriverVTable;

		private AsioDriver()
		{
		}

		public static string[] GetAsioDriverNames()
		{
			RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\ASIO");
			string[] result = new string[0];
			if (registryKey != null)
			{
				result = registryKey.GetSubKeyNames();
				registryKey.Close();
			}
			return result;
		}

		public static AsioDriver GetAsioDriverByName(string name)
		{
			return GetAsioDriverByGuid(new Guid((Registry.LocalMachine.OpenSubKey("SOFTWARE\\ASIO\\" + name) ?? throw new ArgumentException("Driver Name " + name + " doesn't exist")).GetValue("CLSID").ToString()));
		}

		public static AsioDriver GetAsioDriverByGuid(Guid guid)
		{
			AsioDriver asioDriver = new AsioDriver();
			asioDriver.InitFromGuid(guid);
			return asioDriver;
		}

		public bool Init(IntPtr sysHandle)
		{
			return asioDriverVTable.init(pAsioComObject, sysHandle) == 1;
		}

		public string GetDriverName()
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			asioDriverVTable.getDriverName(pAsioComObject, stringBuilder);
			return stringBuilder.ToString();
		}

		public int GetDriverVersion()
		{
			return asioDriverVTable.getDriverVersion(pAsioComObject);
		}

		public string GetErrorMessage()
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			asioDriverVTable.getErrorMessage(pAsioComObject, stringBuilder);
			return stringBuilder.ToString();
		}

		public void Start()
		{
			HandleException(asioDriverVTable.start(pAsioComObject), "start");
		}

		public AsioError Stop()
		{
			return asioDriverVTable.stop(pAsioComObject);
		}

		public void GetChannels(out int numInputChannels, out int numOutputChannels)
		{
			HandleException(asioDriverVTable.getChannels(pAsioComObject, out numInputChannels, out numOutputChannels), "getChannels");
		}

		public AsioError GetLatencies(out int inputLatency, out int outputLatency)
		{
			return asioDriverVTable.getLatencies(pAsioComObject, out inputLatency, out outputLatency);
		}

		public void GetBufferSize(out int minSize, out int maxSize, out int preferredSize, out int granularity)
		{
			HandleException(asioDriverVTable.getBufferSize(pAsioComObject, out minSize, out maxSize, out preferredSize, out granularity), "getBufferSize");
		}

		public bool CanSampleRate(double sampleRate)
		{
			AsioError asioError = asioDriverVTable.canSampleRate(pAsioComObject, sampleRate);
			switch (asioError)
			{
			case AsioError.ASE_NoClock:
				return false;
			case AsioError.ASE_OK:
				return true;
			default:
				HandleException(asioError, "canSampleRate");
				return false;
			}
		}

		public double GetSampleRate()
		{
			HandleException(asioDriverVTable.getSampleRate(pAsioComObject, out var sampleRate), "getSampleRate");
			return sampleRate;
		}

		public void SetSampleRate(double sampleRate)
		{
			HandleException(asioDriverVTable.setSampleRate(pAsioComObject, sampleRate), "setSampleRate");
		}

		public void GetClockSources(out long clocks, int numSources)
		{
			HandleException(asioDriverVTable.getClockSources(pAsioComObject, out clocks, numSources), "getClockSources");
		}

		public void SetClockSource(int reference)
		{
			HandleException(asioDriverVTable.setClockSource(pAsioComObject, reference), "setClockSources");
		}

		public void GetSamplePosition(out long samplePos, ref Asio64Bit timeStamp)
		{
			HandleException(asioDriverVTable.getSamplePosition(pAsioComObject, out samplePos, ref timeStamp), "getSamplePosition");
		}

		public AsioChannelInfo GetChannelInfo(int channelNumber, bool trueForInputInfo)
		{
			AsioChannelInfo asioChannelInfo = default(AsioChannelInfo);
			asioChannelInfo.channel = channelNumber;
			asioChannelInfo.isInput = trueForInputInfo;
			AsioChannelInfo info = asioChannelInfo;
			HandleException(asioDriverVTable.getChannelInfo(pAsioComObject, ref info), "getChannelInfo");
			return info;
		}

		public void CreateBuffers(IntPtr bufferInfos, int numChannels, int bufferSize, ref AsioCallbacks callbacks)
		{
			pinnedcallbacks = Marshal.AllocHGlobal(Marshal.SizeOf(callbacks));
			Marshal.StructureToPtr(callbacks, pinnedcallbacks, fDeleteOld: false);
			HandleException(asioDriverVTable.createBuffers(pAsioComObject, bufferInfos, numChannels, bufferSize, pinnedcallbacks), "createBuffers");
		}

		public AsioError DisposeBuffers()
		{
			AsioError result = asioDriverVTable.disposeBuffers(pAsioComObject);
			Marshal.FreeHGlobal(pinnedcallbacks);
			return result;
		}

		public void ControlPanel()
		{
			HandleException(asioDriverVTable.controlPanel(pAsioComObject), "controlPanel");
		}

		public void Future(int selector, IntPtr opt)
		{
			HandleException(asioDriverVTable.future(pAsioComObject, selector, opt), "future");
		}

		public AsioError OutputReady()
		{
			return asioDriverVTable.outputReady(pAsioComObject);
		}

		public void ReleaseComAsioDriver()
		{
			Marshal.Release(pAsioComObject);
		}

		private void HandleException(AsioError error, string methodName)
		{
			if (error != 0 && error != AsioError.ASE_SUCCESS)
			{
				throw new AsioException("Error code [" + AsioException.getErrorName(error) + "] while calling ASIO method <" + methodName + ">, " + GetErrorMessage())
				{
					Error = error
				};
			}
		}

		private void InitFromGuid(Guid asioGuid)
		{
			int num = CoCreateInstance(ref asioGuid, IntPtr.Zero, 1u, ref asioGuid, out pAsioComObject);
			if (num != 0)
			{
				throw new COMException("Unable to instantiate ASIO. Check if STAThread is set", num);
			}
			IntPtr ptr = Marshal.ReadIntPtr(pAsioComObject);
			asioDriverVTable = new AsioDriverVTable();
			FieldInfo[] fields = typeof(AsioDriverVTable).GetFields();
			for (int i = 0; i < fields.Length; i++)
			{
				FieldInfo fieldInfo = fields[i];
				object delegateForFunctionPointer = Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(ptr, (i + 3) * IntPtr.Size), fieldInfo.FieldType);
				fieldInfo.SetValue(asioDriverVTable, delegateForFunctionPointer);
			}
		}

		[DllImport("ole32.Dll")]
		private static extern int CoCreateInstance(ref Guid clsid, IntPtr inner, uint context, ref Guid uuid, out IntPtr rReturnedComObject);
	}
	public class AsioDriverCapability
	{
		public string DriverName;

		public int NbInputChannels;

		public int NbOutputChannels;

		public int InputLatency;

		public int OutputLatency;

		public int BufferMinSize;

		public int BufferMaxSize;

		public int BufferPreferredSize;

		public int BufferGranularity;

		public double SampleRate;

		public AsioChannelInfo[] InputChannelInfos;

		public AsioChannelInfo[] OutputChannelInfos;
	}
	public delegate void AsioFillBufferCallback(IntPtr[] inputChannels, IntPtr[] outputChannels);
	public class AsioDriverExt
	{
		private readonly AsioDriver driver;

		private AsioCallbacks callbacks;

		private AsioDriverCapability capability;

		private AsioBufferInfo[] bufferInfos;

		private bool isOutputReadySupported;

		private IntPtr[] currentOutputBuffers;

		private IntPtr[] currentInputBuffers;

		private int numberOfOutputChannels;

		private int numberOfInputChannels;

		private AsioFillBufferCallback fillBufferCallback;

		private int bufferSize;

		private int outputChannelOffset;

		private int inputChannelOffset;

		public Action ResetRequestCallback;

		public AsioDriver Driver => driver;

		public AsioFillBufferCallback FillBufferCallback
		{
			get
			{
				return fillBufferCallback;
			}
			set
			{
				fillBufferCallback = value;
			}
		}

		public AsioDriverCapability Capabilities => capability;

		public AsioDriverExt(AsioDriver driver)
		{
			this.driver = driver;
			if (!driver.Init(IntPtr.Zero))
			{
				throw new InvalidOperationException(driver.GetErrorMessage());
			}
			callbacks = default(AsioCallbacks);
			callbacks.pasioMessage = AsioMessageCallBack;
			callbacks.pbufferSwitch = BufferSwitchCallBack;
			callbacks.pbufferSwitchTimeInfo = BufferSwitchTimeInfoCallBack;
			callbacks.psampleRateDidChange = SampleRateDidChangeCallBack;
			BuildCapabilities();
		}

		public void SetChannelOffset(int outputChannelOffset, int inputChannelOffset)
		{
			if (outputChannelOffset + numberOfOutputChannels <= Capabilities.NbOutputChannels)
			{
				this.outputChannelOffset = outputChannelOffset;
				if (inputChannelOffset + numberOfInputChannels <= Capabilities.NbInputChannels)
				{
					this.inputChannelOffset = inputChannelOffset;
					return;
				}
				throw new ArgumentException("Invalid channel offset");
			}
			throw new ArgumentException("Invalid channel offset");
		}

		public void Start()
		{
			driver.Start();
		}

		public void Stop()
		{
			driver.Stop();
		}

		public void ShowControlPanel()
		{
			driver.ControlPanel();
		}

		public void ReleaseDriver()
		{
			try
			{
				driver.DisposeBuffers();
			}
			catch (Exception ex)
			{
				Console.Out.WriteLine(ex.ToString());
			}
			driver.ReleaseComAsioDriver();
		}

		public bool IsSampleRateSupported(double sampleRate)
		{
			return driver.CanSampleRate(sampleRate);
		}

		public void SetSampleRate(double sampleRate)
		{
			driver.SetSampleRate(sampleRate);
			BuildCapabilities();
		}

		public unsafe int CreateBuffers(int numberOfOutputChannels, int numberOfInputChannels, bool useMaxBufferSize)
		{
			if (numberOfOutputChannels < 0 || numberOfOutputChannels > capability.NbOutputChannels)
			{
				throw new ArgumentException($"Invalid number of channels {numberOfOutputChannels}, must be in the range [0,{capability.NbOutputChannels}]");
			}
			if (numberOfInputChannels < 0 || numberOfInputChannels > capability.NbInputChannels)
			{
				throw new ArgumentException("numberOfInputChannels", $"Invalid number of input channels {numberOfInputChannels}, must be in the range [0,{capability.NbInputChannels}]");
			}
			this.numberOfOutputChannels = numberOfOutputChannels;
			this.numberOfInputChannels = numberOfInputChannels;
			int num = capability.NbInputChannels + capability.NbOutputChannels;
			bufferInfos = new AsioBufferInfo[num];
			currentOutputBuffers = new IntPtr[numberOfOutputChannels];
			currentInputBuffers = new IntPtr[numberOfInputChannels];
			int num2 = 0;
			int num3 = 0;
			while (num3 < capability.NbInputChannels)
			{
				bufferInfos[num2].isInput = true;
				bufferInfos[num2].channelNum = num3;
				bufferInfos[num2].pBuffer0 = IntPtr.Zero;
				bufferInfos[num2].pBuffer1 = IntPtr.Zero;
				num3++;
				num2++;
			}
			int num4 = 0;
			while (num4 < capability.NbOutputChannels)
			{
				bufferInfos[num2].isInput = false;
				bufferInfos[num2].channelNum = num4;
				bufferInfos[num2].pBuffer0 = IntPtr.Zero;
				bufferInfos[num2].pBuffer1 = IntPtr.Zero;
				num4++;
				num2++;
			}
			if (useMaxBufferSize)
			{
				bufferSize = capability.BufferMaxSize;
			}
			else
			{
				bufferSize = capability.BufferPreferredSize;
			}
			fixed (AsioBufferInfo* value = &bufferInfos[0])
			{
				IntPtr intPtr = new IntPtr(value);
				driver.CreateBuffers(intPtr, num, bufferSize, ref callbacks);
			}
			isOutputReadySupported = driver.OutputReady() == AsioError.ASE_OK;
			return bufferSize;
		}

		private void BuildCapabilities()
		{
			capability = new AsioDriverCapability();
			capability.DriverName = driver.GetDriverName();
			driver.GetChannels(out capability.NbInputChannels, out capability.NbOutputChannels);
			capability.InputChannelInfos = new AsioChannelInfo[capability.NbInputChannels];
			capability.OutputChannelInfos = new AsioChannelInfo[capability.NbOutputChannels];
			for (int i = 0; i < capability.NbInputChannels; i++)
			{
				capability.InputChannelInfos[i] = driver.GetChannelInfo(i, trueForInputInfo: true);
			}
			for (int j = 0; j < capability.NbOutputChannels; j++)
			{
				capability.OutputChannelInfos[j] = driver.GetChannelInfo(j, trueForInputInfo: false);
			}
			capability.SampleRate = driver.GetSampleRate();
			AsioError latencies = driver.GetLatencies(out capability.InputLatency, out capability.OutputLatency);
			if (latencies != 0 && latencies != AsioError.ASE_NotPresent)
			{
				throw new AsioException("ASIOgetLatencies")
				{
					Error = latencies
				};
			}
			driver.GetBufferSize(out capability.BufferMinSize, out capability.BufferMaxSize, out capability.BufferPreferredSize, out capability.BufferGranularity);
		}

		private void BufferSwitchCallBack(int doubleBufferIndex, bool directProcess)
		{
			for (int i = 0; i < numberOfInputChannels; i++)
			{
				currentInputBuffers[i] = bufferInfos[i + inputChannelOffset].Buffer(doubleBufferIndex);
			}
			for (int j = 0; j < numberOfOutputChannels; j++)
			{
				currentOutputBuffers[j] = bufferInfos[j + outputChannelOffset + capability.NbInputChannels].Buffer(doubleBufferIndex);
			}
			fillBufferCallback?.Invoke(currentInputBuffers, currentOutputBuffers);
			if (isOutputReadySupported)
			{
				driver.OutputReady();
			}
		}

		private void SampleRateDidChangeCallBack(double sRate)
		{
			capability.SampleRate = sRate;
		}

		private int AsioMessageCallBack(AsioMessageSelector selector, int value, IntPtr message, IntPtr opt)
		{
			switch (selector)
			{
			case AsioMessageSelector.kAsioSelectorSupported:
				switch ((AsioMessageSelector)Enum.ToObject(typeof(AsioMessageSelector), value))
				{
				case AsioMessageSelector.kAsioEngineVersion:
					return 1;
				case AsioMessageSelector.kAsioResetRequest:
					ResetRequestCallback?.Invoke();
					return 0;
				case AsioMessageSelector.kAsioBufferSizeChange:
					return 0;
				case AsioMessageSelector.kAsioResyncRequest:
					return 0;
				case AsioMessageSelector.kAsioLatenciesChanged:
					return 0;
				case AsioMessageSelector.kAsioSupportsTimeInfo:
					return 0;
				case AsioMessageSelector.kAsioSupportsTimeCode:
					return 0;
				}
				break;
			case AsioMessageSelector.kAsioEngineVersion:
				return 2;
			case AsioMessageSelector.kAsioResetRequest:
				ResetRequestCallback?.Invoke();
				return 1;
			case AsioMessageSelector.kAsioBufferSizeChange:
				return 0;
			case AsioMessageSelector.kAsioResyncRequest:
				return 0;
			case AsioMessageSelector.kAsioLatenciesChanged:
				return 0;
			case AsioMessageSelector.kAsioSupportsTimeInfo:
				return 0;
			case AsioMessageSelector.kAsioSupportsTimeCode:
				return 0;
			}
			return 0;
		}

		private IntPtr BufferSwitchTimeInfoCallBack(IntPtr asioTimeParam, int doubleBufferIndex, bool directProcess)
		{
			return IntPtr.Zero;
		}
	}
	public enum AsioError
	{
		ASE_OK = 0,
		ASE_SUCCESS = 1061701536,
		ASE_NotPresent = -1000,
		ASE_HWMalfunction = -999,
		ASE_InvalidParameter = -998,
		ASE_InvalidMode = -997,
		ASE_SPNotAdvancing = -996,
		ASE_NoClock = -995,
		ASE_NoMemory = -994
	}
	public enum AsioMessageSelector
	{
		kAsioSelectorSupported = 1,
		kAsioEngineVersion,
		kAsioResetRequest,
		kAsioBufferSizeChange,
		kAsioResyncRequest,
		kAsioLatenciesChanged,
		kAsioSupportsTimeInfo,
		kAsioSupportsTimeCode,
		kAsioMMCCommand,
		kAsioSupportsInputMonitor,
		kAsioSupportsInputGain,
		kAsioSupportsInputMeter,
		kAsioSupportsOutputGain,
		kAsioSupportsOutputMeter,
		kAsioOverload
	}
	internal class AsioSampleConvertor
	{
		public delegate void SampleConvertor(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples);

		public static SampleConvertor SelectSampleConvertor(WaveFormat waveFormat, AsioSampleType asioType)
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Invalid comparison between Unknown and I4
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Invalid comparison between Unknown and I4
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Invalid comparison between Unknown and I4
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Invalid comparison between Unknown and I4
			SampleConvertor result = null;
			bool flag = waveFormat.Channels == 2;
			switch (asioType)
			{
			case AsioSampleType.Int32LSB:
				switch (waveFormat.BitsPerSample)
				{
				case 16:
					result = (flag ? new SampleConvertor(ConvertorShortToInt2Channels) : new SampleConvertor(ConvertorShortToIntGeneric));
					break;
				case 32:
					result = (((int)waveFormat.Encoding != 3) ? (flag ? new SampleConvertor(ConvertorIntToInt2Channels) : new SampleConvertor(ConvertorIntToIntGeneric)) : (flag ? new SampleConvertor(ConvertorFloatToInt2Channels) : new SampleConvertor(ConvertorFloatToIntGeneric)));
					break;
				}
				break;
			case AsioSampleType.Int16LSB:
				switch (waveFormat.BitsPerSample)
				{
				case 16:
					result = (flag ? new SampleConvertor(ConvertorShortToShort2Channels) : new SampleConvertor(ConvertorShortToShortGeneric));
					break;
				case 32:
					result = (((int)waveFormat.Encoding != 3) ? (flag ? new SampleConvertor(ConvertorIntToShort2Channels) : new SampleConvertor(ConvertorIntToShortGeneric)) : (flag ? new SampleConvertor(ConvertorFloatToShort2Channels) : new SampleConvertor(ConvertorFloatToShortGeneric)));
					break;
				}
				break;
			case AsioSampleType.Int24LSB:
				switch (waveFormat.BitsPerSample)
				{
				case 16:
					throw new ArgumentException("Not a supported conversion");
				case 32:
					if ((int)waveFormat.Encoding == 3)
					{
						result = ConverterFloatTo24LSBGeneric;
						break;
					}
					throw new ArgumentException("Not a supported conversion");
				}
				break;
			case AsioSampleType.Float32LSB:
				switch (waveFormat.BitsPerSample)
				{
				case 16:
					throw new ArgumentException("Not a supported conversion");
				case 32:
					result = (((int)waveFormat.Encoding != 3) ? new SampleConvertor(ConvertorIntToFloatGeneric) : new SampleConvertor(ConverterFloatToFloatGeneric));
					break;
				}
				break;
			default:
				throw new ArgumentException($"ASIO Buffer Type {Enum.GetName(typeof(AsioSampleType), asioType)} is not yet supported.");
			}
			return result;
		}

		public unsafe static void ConvertorShortToInt2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			short* ptr = (short*)(void*)inputInterleavedBuffer;
			short* ptr2 = (short*)(void*)asioOutputBuffers[0];
			short* ptr3 = (short*)(void*)asioOutputBuffers[1];
			ptr2++;
			ptr3++;
			for (int i = 0; i < nbSamples; i++)
			{
				*ptr2 = *ptr;
				*ptr3 = ptr[1];
				ptr += 2;
				ptr2 += 2;
				ptr3 += 2;
			}
		}

		public unsafe static void ConvertorShortToIntGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			short* ptr = (short*)(void*)inputInterleavedBuffer;
			short*[] array = new short*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (short*)(void*)asioOutputBuffers[i];
				int num = i;
				short* ptr2 = array[num];
				array[num] = ptr2 + 1;
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					*array[k] = *(ptr++);
					short*[] array2 = array;
					int num = k;
					array2[num] += 2;
				}
			}
		}

		public unsafe static void ConvertorFloatToInt2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			float* ptr = (float*)(void*)inputInterleavedBuffer;
			int* ptr2 = (int*)(void*)asioOutputBuffers[0];
			int* ptr3 = (int*)(void*)asioOutputBuffers[1];
			for (int i = 0; i < nbSamples; i++)
			{
				*(ptr2++) = clampToInt(*ptr);
				*(ptr3++) = clampToInt(ptr[1]);
				ptr += 2;
			}
		}

		public unsafe static void ConvertorFloatToIntGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			float* ptr = (float*)(void*)inputInterleavedBuffer;
			int*[] array = new int*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (int*)(void*)asioOutputBuffers[i];
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					int num = k;
					int* ptr2 = array[num];
					array[num] = ptr2 + 1;
					*ptr2 = clampToInt(*(ptr++));
				}
			}
		}

		public unsafe static void ConvertorIntToInt2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			int* ptr = (int*)(void*)inputInterleavedBuffer;
			int* ptr2 = (int*)(void*)asioOutputBuffers[0];
			int* ptr3 = (int*)(void*)asioOutputBuffers[1];
			for (int i = 0; i < nbSamples; i++)
			{
				*(ptr2++) = *ptr;
				*(ptr3++) = ptr[1];
				ptr += 2;
			}
		}

		public unsafe static void ConvertorIntToIntGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			int* ptr = (int*)(void*)inputInterleavedBuffer;
			int*[] array = new int*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (int*)(void*)asioOutputBuffers[i];
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					int num = k;
					int* ptr2 = array[num];
					array[num] = ptr2 + 1;
					*ptr2 = *(ptr++);
				}
			}
		}

		public unsafe static void ConvertorIntToShort2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			int* ptr = (int*)(void*)inputInterleavedBuffer;
			short* ptr2 = (short*)(void*)asioOutputBuffers[0];
			short* ptr3 = (short*)(void*)asioOutputBuffers[1];
			for (int i = 0; i < nbSamples; i++)
			{
				*(ptr2++) = (short)(*ptr / 65536);
				*(ptr3++) = (short)(ptr[1] / 65536);
				ptr += 2;
			}
		}

		public unsafe static void ConvertorIntToShortGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			int* ptr = (int*)(void*)inputInterleavedBuffer;
			int*[] array = new int*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (int*)(void*)asioOutputBuffers[i];
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					int num = k;
					int* ptr2 = array[num];
					array[num] = ptr2 + 1;
					*ptr2 = (short)(*(ptr++) / 65536);
				}
			}
		}

		public unsafe static void ConvertorIntToFloatGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			int* ptr = (int*)(void*)inputInterleavedBuffer;
			float*[] array = new float*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (float*)(void*)asioOutputBuffers[i];
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					int num = k;
					float* ptr2 = array[num];
					array[num] = ptr2 + 1;
					*ptr2 = *(ptr++) / int.MinValue;
				}
			}
		}

		public unsafe static void ConvertorShortToShort2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			short* ptr = (short*)(void*)inputInterleavedBuffer;
			short* ptr2 = (short*)(void*)asioOutputBuffers[0];
			short* ptr3 = (short*)(void*)asioOutputBuffers[1];
			for (int i = 0; i < nbSamples; i++)
			{
				*(ptr2++) = *ptr;
				*(ptr3++) = ptr[1];
				ptr += 2;
			}
		}

		public unsafe static void ConvertorShortToShortGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			short* ptr = (short*)(void*)inputInterleavedBuffer;
			short*[] array = new short*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (short*)(void*)asioOutputBuffers[i];
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					int num = k;
					short* ptr2 = array[num];
					array[num] = ptr2 + 1;
					*ptr2 = *(ptr++);
				}
			}
		}

		public unsafe static void ConvertorFloatToShort2Channels(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			float* ptr = (float*)(void*)inputInterleavedBuffer;
			short* ptr2 = (short*)(void*)asioOutputBuffers[0];
			short* ptr3 = (short*)(void*)asioOutputBuffers[1];
			for (int i = 0; i < nbSamples; i++)
			{
				*(ptr2++) = clampToShort(*ptr);
				*(ptr3++) = clampToShort(ptr[1]);
				ptr += 2;
			}
		}

		public unsafe static void ConvertorFloatToShortGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			float* ptr = (float*)(void*)inputInterleavedBuffer;
			short*[] array = new short*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (short*)(void*)asioOutputBuffers[i];
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					int num = k;
					short* ptr2 = array[num];
					array[num] = ptr2 + 1;
					*ptr2 = clampToShort(*(ptr++));
				}
			}
		}

		public unsafe static void ConverterFloatTo24LSBGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			float* ptr = (float*)(void*)inputInterleavedBuffer;
			byte*[] array = new byte*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (byte*)(void*)asioOutputBuffers[i];
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					int num = clampTo24Bit(*(ptr++));
					int num2 = k;
					*(array[num2]++) = (byte)num;
					num2 = k;
					*(array[num2]++) = (byte)(num >> 8);
					num2 = k;
					*(array[num2]++) = (byte)(num >> 16);
				}
			}
		}

		public unsafe static void ConverterFloatToFloatGeneric(IntPtr inputInterleavedBuffer, IntPtr[] asioOutputBuffers, int nbChannels, int nbSamples)
		{
			float* ptr = (float*)(void*)inputInterleavedBuffer;
			float*[] array = new float*[nbChannels];
			for (int i = 0; i < nbChannels; i++)
			{
				array[i] = (float*)(void*)asioOutputBuffers[i];
			}
			for (int j = 0; j < nbSamples; j++)
			{
				for (int k = 0; k < nbChannels; k++)
				{
					int num = k;
					float* ptr2 = array[num];
					array[num] = ptr2 + 1;
					*ptr2 = *(ptr++);
				}
			}
		}

		private static int clampTo24Bit(double sampleValue)
		{
			sampleValue = ((sampleValue < -1.0) ? (-1.0) : ((sampleValue > 1.0) ? 1.0 : sampleValue));
			return (int)(sampleValue * 8388607.0);
		}

		private static int clampToInt(double sampleValue)
		{
			sampleValue = ((sampleValue < -1.0) ? (-1.0) : ((sampleValue > 1.0) ? 1.0 : sampleValue));
			return (int)(sampleValue * 2147483647.0);
		}

		private static short clampToShort(double sampleValue)
		{
			sampleValue = ((sampleValue < -1.0) ? (-1.0) : ((sampleValue > 1.0) ? 1.0 : sampleValue));
			return (short)(sampleValue * 32767.0);
		}
	}
	public enum AsioSampleType
	{
		Int16MSB = 0,
		Int24MSB = 1,
		Int32MSB = 2,
		Float32MSB = 3,
		Float64MSB = 4,
		Int32MSB16 = 8,
		Int32MSB18 = 9,
		Int32MSB20 = 10,
		Int32MSB24 = 11,
		Int16LSB = 16,
		Int24LSB = 17,
		Int32LSB = 18,
		Float32LSB = 19,
		Float64LSB = 20,
		Int32LSB16 = 24,
		Int32LSB18 = 25,
		Int32LSB20 = 26,
		Int32LSB24 = 27,
		DSDInt8LSB1 = 32,
		DSDInt8MSB1 = 33,
		DSDInt8NER8 = 40
	}
	internal class AsioException : Exception
	{
		private AsioError error;

		public AsioError Error
		{
			get
			{
				return error;
			}
			set
			{
				error = value;
				Data["ASIOError"] = error;
			}
		}

		public AsioException()
		{
		}

		public AsioException(string message)
			: base(message)
		{
		}

		public AsioException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public static string getErrorName(AsioError error)
		{
			return Enum.GetName(typeof(AsioError), error);
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	internal struct AsioBufferInfo
	{
		public bool isInput;

		public int channelNum;

		public IntPtr pBuffer0;

		public IntPtr pBuffer1;

		public IntPtr Buffer(int bufferIndex)
		{
			if (bufferIndex != 0)
			{
				return pBuffer1;
			}
			return pBuffer0;
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	internal struct AsioTimeCode
	{
		public double speed;

		public Asio64Bit timeCodeSamples;

		public AsioTimeCodeFlags flags;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
		public string future;
	}
	[Flags]
	internal enum AsioTimeCodeFlags
	{
		kTcValid = 1,
		kTcRunning = 2,
		kTcReverse = 4,
		kTcOnspeed = 8,
		kTcStill = 0x10,
		kTcSpeedValid = 0x100
	}
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	internal struct AsioTimeInfo
	{
		public double speed;

		public Asio64Bit systemTime;

		public Asio64Bit samplePosition;

		public double sampleRate;

		public AsioTimeInfoFlags flags;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]
		public string reserved;
	}
	[Flags]
	internal enum AsioTimeInfoFlags
	{
		kSystemTimeValid = 1,
		kSamplePositionValid = 2,
		kSampleRateValid = 4,
		kSpeedValid = 8,
		kSampleRateChanged = 0x10,
		kClockSourceChanged = 0x20
	}
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	internal struct AsioTime
	{
		public int reserved1;

		public int reserved2;

		public int reserved3;

		public int reserved4;

		public AsioTimeInfo timeInfo;

		public AsioTimeCode timeCode;
	}
}

NAudio.Core.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using NAudio.Dmo;
using NAudio.Dsp;
using NAudio.FileFormats.Wav;
using NAudio.Utils;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Mark Heath")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2021")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyProduct("NAudio.Core")]
[assembly: AssemblyTitle("NAudio.Core")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.0.0")]
[module: UnverifiableCode]
namespace NAudio
{
	public enum Manufacturers
	{
		Microsoft = 1,
		Creative = 2,
		Mediavision = 3,
		Fujitsu = 4,
		Artisoft = 20,
		TurtleBeach = 21,
		Ibm = 22,
		Vocaltec = 23,
		Roland = 24,
		DspSolutions = 25,
		Nec = 26,
		Ati = 27,
		Wanglabs = 28,
		Tandy = 29,
		Voyetra = 30,
		Antex = 31,
		IclPS = 32,
		Intel = 33,
		Gravis = 34,
		Val = 35,
		Interactive = 36,
		Yamaha = 37,
		Everex = 38,
		Echo = 39,
		Sierra = 40,
		Cat = 41,
		Apps = 42,
		DspGroup = 43,
		Melabs = 44,
		ComputerFriends = 45,
		Ess = 46,
		Audiofile = 47,
		Motorola = 48,
		Canopus = 49,
		Epson = 50,
		Truevision = 51,
		Aztech = 52,
		Videologic = 53,
		Scalacs = 54,
		Korg = 55,
		Apt = 56,
		Ics = 57,
		Iteratedsys = 58,
		Metheus = 59,
		Logitech = 60,
		Winnov = 61,
		Ncr = 62,
		Exan = 63,
		Ast = 64,
		Willowpond = 65,
		Sonicfoundry = 66,
		Vitec = 67,
		Moscom = 68,
		Siliconsoft = 69,
		Supermac = 73,
		Audiopt = 74,
		Speechcomp = 76,
		Ahead = 77,
		Dolby = 78,
		Oki = 79,
		Auravision = 80,
		Olivetti = 81,
		Iomagic = 82,
		Matsushita = 83,
		Controlres = 84,
		Xebec = 85,
		Newmedia = 86,
		Nms = 87,
		Lyrrus = 88,
		Compusic = 89,
		Opti = 90,
		Adlacc = 91,
		Compaq = 92,
		Dialogic = 93,
		Insoft = 94,
		Mptus = 95,
		Weitek = 96,
		LernoutAndHauspie = 97,
		Qciar = 98,
		Apple = 99,
		Digital = 100,
		Motu = 101,
		Workbit = 102,
		Ositech = 103,
		Miro = 104,
		Cirruslogic = 105,
		Isolution = 106,
		Horizons = 107,
		Concepts = 108,
		Vtg = 109,
		Radius = 110,
		Rockwell = 111,
		Xyz = 112,
		Opcode = 113,
		Voxware = 114,
		NorthernTelecom = 115,
		Apicom = 116,
		Grande = 117,
		Addx = 118,
		Wildcat = 119,
		Rhetorex = 120,
		Brooktree = 121,
		Ensoniq = 125,
		Fast = 126,
		Nvidia = 127,
		Oksori = 128,
		Diacoustics = 129,
		Gulbransen = 130,
		KayElemetrics = 131,
		Crystal = 132,
		SplashStudios = 133,
		Quarterdeck = 134,
		Tdk = 135,
		DigitalAudioLabs = 136,
		Seersys = 137,
		Picturetel = 138,
		AttMicroelectronics = 139,
		Osprey = 140,
		Mediatrix = 141,
		Soundesigns = 142,
		Aldigital = 143,
		SpectrumSignalProcessing = 144,
		Ecs = 145,
		Amd = 146,
		Coredynamics = 147,
		Canam = 148,
		Softsound = 149,
		Norris = 150,
		Ddd = 151,
		Euphonics = 152,
		Precept = 153,
		CrystalNet = 154,
		Chromatic = 155,
		Voiceinfo = 156,
		Viennasys = 157,
		Connectix = 158,
		Gadgetlabs = 159,
		Frontier = 160,
		Viona = 161,
		Casio = 162,
		Diamondmm = 163,
		S3 = 164,
		FraunhoferIis = 172
	}
	public class MmException : Exception
	{
		private MmResult result;

		private string function;

		public MmResult Result => result;

		public MmException(MmResult result, string function)
			: base(ErrorMessage(result, function))
		{
			this.result = result;
			this.function = function;
		}

		private static string ErrorMessage(MmResult result, string function)
		{
			return $"{result} calling {function}";
		}

		public static void Try(MmResult result, string function)
		{
			if (result != 0)
			{
				throw new MmException(result, function);
			}
		}
	}
	public enum MmResult
	{
		NoError = 0,
		UnspecifiedError = 1,
		BadDeviceId = 2,
		NotEnabled = 3,
		AlreadyAllocated = 4,
		InvalidHandle = 5,
		NoDriver = 6,
		MemoryAllocationError = 7,
		NotSupported = 8,
		BadErrorNumber = 9,
		InvalidFlag = 10,
		InvalidParameter = 11,
		HandleBusy = 12,
		InvalidAlias = 13,
		BadRegistryDatabase = 14,
		RegistryKeyNotFound = 15,
		RegistryReadError = 16,
		RegistryWriteError = 17,
		RegistryDeleteError = 18,
		RegistryValueNotFound = 19,
		NoDriverCallback = 20,
		MoreData = 21,
		WaveBadFormat = 32,
		WaveStillPlaying = 33,
		WaveHeaderUnprepared = 34,
		WaveSync = 35,
		AcmNotPossible = 512,
		AcmBusy = 513,
		AcmHeaderUnprepared = 514,
		AcmCancelled = 515,
		MixerInvalidLine = 1024,
		MixerInvalidControl = 1025,
		MixerInvalidValue = 1026
	}
}
namespace NAudio.CoreAudioApi
{
	public enum CaptureState
	{
		Stopped,
		Starting,
		Capturing,
		Stopping
	}
}
namespace NAudio.Dmo
{
	public class AudioMediaSubtypes
	{
		public static readonly Guid MEDIASUBTYPE_PCM = new Guid("00000001-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_PCMAudioObsolete = new Guid("e436eb8a-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_MPEG1Packet = new Guid("e436eb80-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_MPEG1Payload = new Guid("e436eb81-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_MPEG2_AUDIO = new Guid("e06d802b-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid MEDIASUBTYPE_DVD_LPCM_AUDIO = new Guid("e06d8032-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid MEDIASUBTYPE_DRM_Audio = new Guid("00000009-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_IEEE_FLOAT = new Guid("00000003-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_DOLBY_AC3 = new Guid("e06d802c-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid MEDIASUBTYPE_DOLBY_AC3_SPDIF = new Guid("00000092-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_RAW_SPORT = new Guid("00000240-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_SPDIF_TAG_241h = new Guid("00000241-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_I420 = new Guid("30323449-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_IYUV = new Guid("56555949-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_RGB1 = new Guid("e436eb78-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB24 = new Guid("e436eb7d-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB32 = new Guid("e436eb7e-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB4 = new Guid("e436eb79-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB555 = new Guid("e436eb7c-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB565 = new Guid("e436eb7b-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB8 = new Guid("e436eb7a-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_UYVY = new Guid("59565955-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_VIDEOIMAGE = new Guid("1d4a45f2-e5f6-4b44-8388-f0ae5c0e0c37");

		public static readonly Guid MEDIASUBTYPE_YUY2 = new Guid("32595559-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_YV12 = new Guid("31313259-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_YVU9 = new Guid("39555659-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_YVYU = new Guid("55595659-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMFORMAT_MPEG2Video = new Guid("e06d80e3-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid WMFORMAT_Script = new Guid("5C8510F2-DEBE-4ca7-BBA5-F07A104F8DFF");

		public static readonly Guid WMFORMAT_VideoInfo = new Guid("05589f80-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid WMFORMAT_WaveFormatEx = new Guid("05589f81-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid WMFORMAT_WebStream = new Guid("da1e6b13-8359-4050-b398-388e965bf00c");

		public static readonly Guid WMMEDIASUBTYPE_ACELPnet = new Guid("00000130-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_Base = new Guid("00000000-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_DRM = new Guid("00000009-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MP3 = new Guid("00000055-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MP43 = new Guid("3334504D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MP4S = new Guid("5334504D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_M4S2 = new Guid("3253344D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_P422 = new Guid("32323450-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MPEG2_VIDEO = new Guid("e06d8026-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid WMMEDIASUBTYPE_MSS1 = new Guid("3153534D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MSS2 = new Guid("3253534D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_PCM = new Guid("00000001-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WebStream = new Guid("776257d4-c627-41cb-8f81-7ac7ff1c40cc");

		public static readonly Guid WMMEDIASUBTYPE_WMAudio_Lossless = new Guid("00000163-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMAudioV2 = new Guid("00000161-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMAudioV7 = new Guid("00000161-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMAudioV8 = new Guid("00000161-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMAudioV9 = new Guid("00000162-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMSP1 = new Guid("0000000A-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMV1 = new Guid("31564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMV2 = new Guid("32564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMV3 = new Guid("33564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMVA = new Guid("41564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMVP = new Guid("50564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WVP2 = new Guid("32505657-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIATYPE_Audio = new Guid("73647561-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIATYPE_FileTransfer = new Guid("D9E47579-930E-4427-ADFC-AD80F290E470");

		public static readonly Guid WMMEDIATYPE_Image = new Guid("34A50FD8-8AA5-4386-81FE-A0EFE0488E31");

		public static readonly Guid WMMEDIATYPE_Script = new Guid("73636d64-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIATYPE_Text = new Guid("9BBA1EA7-5AB2-4829-BA57-0940209BCF3E");

		public static readonly Guid WMMEDIATYPE_Video = new Guid("73646976-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMSCRIPTTYPE_TwoStrings = new Guid("82f38a70-c29f-11d1-97ad-00a0c95ea850");

		public static readonly Guid MEDIASUBTYPE_WAVE = new Guid("e436eb8b-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_AU = new Guid("e436eb8c-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_AIFF = new Guid("e436eb8d-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid[] AudioSubTypes = new Guid[13]
		{
			MEDIASUBTYPE_PCM, MEDIASUBTYPE_PCMAudioObsolete, MEDIASUBTYPE_MPEG1Packet, MEDIASUBTYPE_MPEG1Payload, MEDIASUBTYPE_MPEG2_AUDIO, MEDIASUBTYPE_DVD_LPCM_AUDIO, MEDIASUBTYPE_DRM_Audio, MEDIASUBTYPE_IEEE_FLOAT, MEDIASUBTYPE_DOLBY_AC3, MEDIASUBTYPE_DOLBY_AC3_SPDIF,
			MEDIASUBTYPE_RAW_SPORT, MEDIASUBTYPE_SPDIF_TAG_241h, WMMEDIASUBTYPE_MP3
		};

		public static readonly string[] AudioSubTypeNames = new string[13]
		{
			"PCM", "PCM Obsolete", "MPEG1Packet", "MPEG1Payload", "MPEG2_AUDIO", "DVD_LPCM_AUDIO", "DRM_Audio", "IEEE_FLOAT", "DOLBY_AC3", "DOLBY_AC3_SPDIF",
			"RAW_SPORT", "SPDIF_TAG_241h", "MP3"
		};

		public static string GetAudioSubtypeName(Guid subType)
		{
			for (int i = 0; i < AudioSubTypes.Length; i++)
			{
				if (subType == AudioSubTypes[i])
				{
					return AudioSubTypeNames[i];
				}
			}
			return subType.ToString();
		}
	}
}
namespace NAudio.Utils
{
	public static class BufferHelpers
	{
		public static byte[] Ensure(byte[] buffer, int bytesRequired)
		{
			if (buffer == null || buffer.Length < bytesRequired)
			{
				buffer = new byte[bytesRequired];
			}
			return buffer;
		}

		public static float[] Ensure(float[] buffer, int samplesRequired)
		{
			if (buffer == null || buffer.Length < samplesRequired)
			{
				buffer = new float[samplesRequired];
			}
			return buffer;
		}
	}
	public static class ByteArrayExtensions
	{
		public static bool IsEntirelyNull(byte[] buffer)
		{
			for (int i = 0; i < buffer.Length; i++)
			{
				if (buffer[i] != 0)
				{
					return false;
				}
			}
			return true;
		}

		public static string DescribeAsHex(byte[] buffer, string separator, int bytesPerLine)
		{
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			foreach (byte b in buffer)
			{
				stringBuilder.AppendFormat("{0:X2}{1}", b, separator);
				if (++num % bytesPerLine == 0)
				{
					stringBuilder.Append("\r\n");
				}
			}
			stringBuilder.Append("\r\n");
			return stringBuilder.ToString();
		}

		public static string DecodeAsString(byte[] buffer, int offset, int length, Encoding encoding)
		{
			for (int i = 0; i < length; i++)
			{
				if (buffer[offset + i] == 0)
				{
					length = i;
				}
			}
			return encoding.GetString(buffer, offset, length);
		}

		public static byte[] Concat(params byte[][] byteArrays)
		{
			int num = 0;
			byte[][] array = byteArrays;
			foreach (byte[] array2 in array)
			{
				num += array2.Length;
			}
			if (num <= 0)
			{
				return new byte[0];
			}
			byte[] array3 = new byte[num];
			int num2 = 0;
			array = byteArrays;
			foreach (byte[] array4 in array)
			{
				Array.Copy(array4, 0, array3, num2, array4.Length);
				num2 += array4.Length;
			}
			return array3;
		}
	}
	public class ByteEncoding : Encoding
	{
		public static readonly ByteEncoding Instance = new ByteEncoding();

		private ByteEncoding()
		{
		}

		public override int GetByteCount(char[] chars, int index, int count)
		{
			return count;
		}

		public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			for (int i = 0; i < charCount; i++)
			{
				bytes[byteIndex + i] = (byte)chars[charIndex + i];
			}
			return charCount;
		}

		public override int GetCharCount(byte[] bytes, int index, int count)
		{
			for (int i = 0; i < count; i++)
			{
				if (bytes[index + i] == 0)
				{
					return i;
				}
			}
			return count;
		}

		public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
		{
			for (int i = 0; i < byteCount; i++)
			{
				byte b = bytes[byteIndex + i];
				if (b == 0)
				{
					return i;
				}
				chars[charIndex + i] = (char)b;
			}
			return byteCount;
		}

		public override int GetMaxCharCount(int byteCount)
		{
			return byteCount;
		}

		public override int GetMaxByteCount(int charCount)
		{
			return charCount;
		}
	}
	public class ChunkIdentifier
	{
		public static int ChunkIdentifierToInt32(string s)
		{
			if (s.Length != 4)
			{
				throw new ArgumentException("Must be a four character string");
			}
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			if (bytes.Length != 4)
			{
				throw new ArgumentException("Must encode to exactly four bytes");
			}
			return BitConverter.ToInt32(bytes, 0);
		}
	}
	public class CircularBuffer
	{
		private readonly byte[] buffer;

		private readonly object lockObject;

		private int writePosition;

		private int readPosition;

		private int byteCount;

		public int MaxLength => buffer.Length;

		public int Count
		{
			get
			{
				lock (lockObject)
				{
					return byteCount;
				}
			}
		}

		public CircularBuffer(int size)
		{
			buffer = new byte[size];
			lockObject = new object();
		}

		public int Write(byte[] data, int offset, int count)
		{
			lock (lockObject)
			{
				int num = 0;
				if (count > buffer.Length - byteCount)
				{
					count = buffer.Length - byteCount;
				}
				int num2 = Math.Min(buffer.Length - writePosition, count);
				Array.Copy(data, offset, buffer, writePosition, num2);
				writePosition += num2;
				writePosition %= buffer.Length;
				num += num2;
				if (num < count)
				{
					Array.Copy(data, offset + num, buffer, writePosition, count - num);
					writePosition += count - num;
					num = count;
				}
				byteCount += num;
				return num;
			}
		}

		public int Read(byte[] data, int offset, int count)
		{
			lock (lockObject)
			{
				if (count > byteCount)
				{
					count = byteCount;
				}
				int num = 0;
				int num2 = Math.Min(buffer.Length - readPosition, count);
				Array.Copy(buffer, readPosition, data, offset, num2);
				num += num2;
				readPosition += num2;
				readPosition %= buffer.Length;
				if (num < count)
				{
					Array.Copy(buffer, readPosition, data, offset + num, count - num);
					readPosition += count - num;
					num = count;
				}
				byteCount -= num;
				return num;
			}
		}

		public void Reset()
		{
			lock (lockObject)
			{
				ResetInner();
			}
		}

		private void ResetInner()
		{
			byteCount = 0;
			readPosition = 0;
			writePosition = 0;
		}

		public void Advance(int count)
		{
			lock (lockObject)
			{
				if (count >= byteCount)
				{
					ResetInner();
					return;
				}
				byteCount -= count;
				readPosition += count;
				readPosition %= MaxLength;
			}
		}
	}
	public class Decibels
	{
		private const double LOG_2_DB = 8.685889638065037;

		private const double DB_2_LOG = 0.11512925464970228;

		public static double LinearToDecibels(double lin)
		{
			return Math.Log(lin) * 8.685889638065037;
		}

		public static double DecibelsToLinear(double dB)
		{
			return Math.Exp(dB * 0.11512925464970228);
		}
	}
	[AttributeUsage(AttributeTargets.Field)]
	public class FieldDescriptionAttribute : Attribute
	{
		public string Description { get; }

		public FieldDescriptionAttribute(string description)
		{
			Description = description;
		}

		public override string ToString()
		{
			return Description;
		}
	}
	public static class FieldDescriptionHelper
	{
		public static string Describe(Type t, Guid guid)
		{
			FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (!fieldInfo.IsPublic || !fieldInfo.IsStatic || !(fieldInfo.FieldType == typeof(Guid)) || !((Guid)fieldInfo.GetValue(null) == guid))
				{
					continue;
				}
				object[] customAttributes = fieldInfo.GetCustomAttributes(inherit: false);
				for (int j = 0; j < customAttributes.Length; j++)
				{
					if (customAttributes[j] is FieldDescriptionAttribute fieldDescriptionAttribute)
					{
						return fieldDescriptionAttribute.Description;
					}
				}
				return fieldInfo.Name;
			}
			return guid.ToString();
		}
	}
	public static class HResult
	{
		public const int S_OK = 0;

		public const int S_FALSE = 1;

		public const int E_INVALIDARG = -2147483645;

		private const int FACILITY_AAF = 18;

		private const int FACILITY_ACS = 20;

		private const int FACILITY_BACKGROUNDCOPY = 32;

		private const int FACILITY_CERT = 11;

		private const int FACILITY_COMPLUS = 17;

		private const int FACILITY_CONFIGURATION = 33;

		private const int FACILITY_CONTROL = 10;

		private const int FACILITY_DISPATCH = 2;

		private const int FACILITY_DPLAY = 21;

		private const int FACILITY_HTTP = 25;

		private const int FACILITY_INTERNET = 12;

		private const int FACILITY_ITF = 4;

		private const int FACILITY_MEDIASERVER = 13;

		private const int FACILITY_MSMQ = 14;

		private const int FACILITY_NULL = 0;

		private const int FACILITY_RPC = 1;

		private const int FACILITY_SCARD = 16;

		private const int FACILITY_SECURITY = 9;

		private const int FACILITY_SETUPAPI = 15;

		private const int FACILITY_SSPI = 9;

		private const int FACILITY_STORAGE = 3;

		private const int FACILITY_SXS = 23;

		private const int FACILITY_UMI = 22;

		private const int FACILITY_URT = 19;

		private const int FACILITY_WIN32 = 7;

		private const int FACILITY_WINDOWS = 8;

		private const int FACILITY_WINDOWS_CE = 24;

		public static int MAKE_HRESULT(int sev, int fac, int code)
		{
			return (sev << 31) | (fac << 16) | code;
		}

		public static int GetHResult(this COMException exception)
		{
			return exception.ErrorCode;
		}
	}
	public static class IEEE
	{
		private static double UnsignedToFloat(ulong u)
		{
			return (double)(long)(u - int.MaxValue - 1) + 2147483648.0;
		}

		private static double ldexp(double x, int exp)
		{
			return x * Math.Pow(2.0, exp);
		}

		private static double frexp(double x, out int exp)
		{
			exp = (int)Math.Floor(Math.Log(x) / Math.Log(2.0)) + 1;
			return 1.0 - (Math.Pow(2.0, exp) - x) / Math.Pow(2.0, exp);
		}

		private static ulong FloatToUnsigned(double f)
		{
			return (ulong)((long)(f - 2147483648.0) + int.MaxValue + 1);
		}

		public static byte[] ConvertToIeeeExtended(double num)
		{
			int num2;
			if (num < 0.0)
			{
				num2 = 32768;
				num *= -1.0;
			}
			else
			{
				num2 = 0;
			}
			ulong num4;
			ulong num5;
			int num3;
			if (num == 0.0)
			{
				num3 = 0;
				num4 = 0uL;
				num5 = 0uL;
			}
			else
			{
				double num6 = frexp(num, out num3);
				if (num3 > 16384 || !(num6 < 1.0))
				{
					num3 = num2 | 0x7FFF;
					num4 = 0uL;
					num5 = 0uL;
				}
				else
				{
					num3 += 16382;
					if (num3 < 0)
					{
						num6 = ldexp(num6, num3);
						num3 = 0;
					}
					num3 |= num2;
					num6 = ldexp(num6, 32);
					double num7 = Math.Floor(num6);
					num4 = FloatToUnsigned(num7);
					num6 = ldexp(num6 - num7, 32);
					num7 = Math.Floor(num6);
					num5 = FloatToUnsigned(num7);
				}
			}
			return new byte[10]
			{
				(byte)(num3 >> 8),
				(byte)num3,
				(byte)(num4 >> 24),
				(byte)(num4 >> 16),
				(byte)(num4 >> 8),
				(byte)num4,
				(byte)(num5 >> 24),
				(byte)(num5 >> 16),
				(byte)(num5 >> 8),
				(byte)num5
			};
		}

		public static double ConvertFromIeeeExtended(byte[] bytes)
		{
			if (bytes.Length != 10)
			{
				throw new Exception("Incorrect length for IEEE extended.");
			}
			int num = ((bytes[0] & 0x7F) << 8) | bytes[1];
			uint num2 = (uint)((bytes[2] << 24) | (bytes[3] << 16) | (bytes[4] << 8) | bytes[5]);
			uint num3 = (uint)((bytes[6] << 24) | (bytes[7] << 16) | (bytes[8] << 8) | bytes[9]);
			double num4;
			if (num == 0 && num2 == 0 && num3 == 0)
			{
				num4 = 0.0;
			}
			else if (num == 32767)
			{
				num4 = double.NaN;
			}
			else
			{
				num -= 16383;
				num4 = ldexp(UnsignedToFloat(num2), num -= 31);
				num4 += ldexp(UnsignedToFloat(num3), num -= 32);
			}
			if ((bytes[0] & 0x80) == 128)
			{
				return 0.0 - num4;
			}
			return num4;
		}
	}
	public class IgnoreDisposeStream : Stream
	{
		public Stream SourceStream { get; private set; }

		public bool IgnoreDispose { get; set; }

		public override bool CanRead => SourceStream.CanRead;

		public override bool CanSeek => SourceStream.CanSeek;

		public override bool CanWrite => SourceStream.CanWrite;

		public override long Length => SourceStream.Length;

		public override long Position
		{
			get
			{
				return SourceStream.Position;
			}
			set
			{
				SourceStream.Position = value;
			}
		}

		public IgnoreDisposeStream(Stream sourceStream)
		{
			SourceStream = sourceStream;
			IgnoreDispose = true;
		}

		public override void Flush()
		{
			SourceStream.Flush();
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			return SourceStream.Read(buffer, offset, count);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			return SourceStream.Seek(offset, origin);
		}

		public override void SetLength(long value)
		{
			SourceStream.SetLength(value);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			SourceStream.Write(buffer, offset, count);
		}

		protected override void Dispose(bool disposing)
		{
			if (!IgnoreDispose)
			{
				SourceStream.Dispose();
				SourceStream = null;
			}
		}
	}
	public static class NativeMethods
	{
		[DllImport("kernel32.dll")]
		public static extern IntPtr LoadLibrary(string dllToLoad);

		[DllImport("kernel32.dll")]
		public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

		[DllImport("kernel32.dll")]
		public static extern bool FreeLibrary(IntPtr hModule);
	}
	public static class WavePositionExtensions
	{
		public static TimeSpan GetPositionTimeSpan(this IWavePosition @this)
		{
			return TimeSpan.FromMilliseconds((double)(@this.GetPosition() / (@this.OutputWaveFormat.Channels * @this.OutputWaveFormat.BitsPerSample / 8)) * 1000.0 / (double)@this.OutputWaveFormat.SampleRate);
		}
	}
}
namespace NAudio.FileFormats.Wav
{
	public class WaveFileChunkReader
	{
		private WaveFormat waveFormat;

		private long dataChunkPosition;

		private long dataChunkLength;

		private List<RiffChunk> riffChunks;

		private readonly bool strictMode;

		private bool isRf64;

		private readonly bool storeAllChunks;

		private long riffSize;

		public WaveFormat WaveFormat => waveFormat;

		public long DataChunkPosition => dataChunkPosition;

		public long DataChunkLength => dataChunkLength;

		public List<RiffChunk> RiffChunks => riffChunks;

		public WaveFileChunkReader()
		{
			storeAllChunks = true;
			strictMode = false;
		}

		public void ReadWaveHeader(Stream stream)
		{
			dataChunkPosition = -1L;
			waveFormat = null;
			riffChunks = new List<RiffChunk>();
			dataChunkLength = 0L;
			BinaryReader binaryReader = new BinaryReader(stream);
			ReadRiffHeader(binaryReader);
			riffSize = binaryReader.ReadUInt32();
			if (binaryReader.ReadInt32() != ChunkIdentifier.ChunkIdentifierToInt32("WAVE"))
			{
				throw new FormatException("Not a WAVE file - no WAVE header");
			}
			if (isRf64)
			{
				ReadDs64Chunk(binaryReader);
			}
			int num = ChunkIdentifier.ChunkIdentifierToInt32("data");
			int num2 = ChunkIdentifier.ChunkIdentifierToInt32("fmt ");
			long num3 = Math.Min(riffSize + 8, stream.Length);
			while (stream.Position <= num3 - 8)
			{
				int num4 = binaryReader.ReadInt32();
				uint num5 = binaryReader.ReadUInt32();
				if (num4 == num)
				{
					dataChunkPosition = stream.Position;
					if (!isRf64)
					{
						dataChunkLength = num5;
					}
					stream.Position += num5;
				}
				else if (num4 == num2)
				{
					if (num5 > int.MaxValue)
					{
						throw new InvalidDataException($"Format chunk length must be between 0 and {int.MaxValue}.");
					}
					waveFormat = WaveFormat.FromFormatChunk(binaryReader, (int)num5);
				}
				else
				{
					if (num5 > stream.Length - stream.Position)
					{
						if (!strictMode)
						{
						}
						break;
					}
					if (storeAllChunks)
					{
						if (num5 > int.MaxValue)
						{
							throw new InvalidDataException($"RiffChunk chunk length must be between 0 and {int.MaxValue}.");
						}
						riffChunks.Add(GetRiffChunk(stream, num4, (int)num5));
					}
					stream.Position += num5;
				}
				if (num5 % 2 != 0 && binaryReader.PeekChar() == 0)
				{
					stream.Position++;
				}
			}
			if (waveFormat == null)
			{
				throw new FormatException("Invalid WAV file - No fmt chunk found");
			}
			if (dataChunkPosition == -1)
			{
				throw new FormatException("Invalid WAV file - No data chunk found");
			}
		}

		private void ReadDs64Chunk(BinaryReader reader)
		{
			int num = ChunkIdentifier.ChunkIdentifierToInt32("ds64");
			if (reader.ReadInt32() != num)
			{
				throw new FormatException("Invalid RF64 WAV file - No ds64 chunk found");
			}
			int num2 = reader.ReadInt32();
			riffSize = reader.ReadInt64();
			dataChunkLength = reader.ReadInt64();
			reader.ReadInt64();
			reader.ReadBytes(num2 - 24);
		}

		private static RiffChunk GetRiffChunk(Stream stream, int chunkIdentifier, int chunkLength)
		{
			return new RiffChunk(chunkIdentifier, chunkLength, stream.Position);
		}

		private void ReadRiffHeader(BinaryReader br)
		{
			int num = br.ReadInt32();
			if (num == ChunkIdentifier.ChunkIdentifierToInt32("RF64"))
			{
				isRf64 = true;
			}
			else if (num != ChunkIdentifier.ChunkIdentifierToInt32("RIFF"))
			{
				throw new FormatException("Not a WAVE file - no RIFF header");
			}
		}
	}
}
namespace NAudio.SoundFont
{
	public class Generator
	{
		public GeneratorEnum GeneratorType { get; set; }

		public ushort UInt16Amount { get; set; }

		public short Int16Amount
		{
			get
			{
				return (short)UInt16Amount;
			}
			set
			{
				UInt16Amount = (ushort)value;
			}
		}

		public byte LowByteAmount
		{
			get
			{
				return (byte)(UInt16Amount & 0xFFu);
			}
			set
			{
				UInt16Amount &= 65280;
				UInt16Amount += value;
			}
		}

		public byte HighByteAmount
		{
			get
			{
				return (byte)((UInt16Amount & 0xFF00) >> 8);
			}
			set
			{
				UInt16Amount &= 255;
				UInt16Amount += (ushort)(value << 8);
			}
		}

		public Instrument Instrument { get; set; }

		public SampleHeader SampleHeader { get; set; }

		public override string ToString()
		{
			if (GeneratorType == GeneratorEnum.Instrument)
			{
				return "Generator Instrument " + Instrument.Name;
			}
			if (GeneratorType == GeneratorEnum.SampleID)
			{
				return $"Generator SampleID {SampleHeader}";
			}
			return $"Generator {GeneratorType} {UInt16Amount}";
		}
	}
	internal class GeneratorBuilder : StructureBuilder<Generator>
	{
		public override int Length => 4;

		public Generator[] Generators => data.ToArray();

		public override Generator Read(BinaryReader br)
		{
			Generator generator = new Generator();
			generator.GeneratorType = (GeneratorEnum)br.ReadUInt16();
			generator.UInt16Amount = br.ReadUInt16();
			data.Add(generator);
			return generator;
		}

		public override void Write(BinaryWriter bw, Generator o)
		{
		}

		public void Load(Instrument[] instruments)
		{
			Generator[] generators = Generators;
			foreach (Generator generator in generators)
			{
				if (generator.GeneratorType == GeneratorEnum.Instrument)
				{
					generator.Instrument = instruments[generator.UInt16Amount];
				}
			}
		}

		public void Load(SampleHeader[] sampleHeaders)
		{
			Generator[] generators = Generators;
			foreach (Generator generator in generators)
			{
				if (generator.GeneratorType == GeneratorEnum.SampleID)
				{
					generator.SampleHeader = sampleHeaders[generator.UInt16Amount];
				}
			}
		}
	}
	public enum GeneratorEnum
	{
		StartAddressOffset,
		EndAddressOffset,
		StartLoopAddressOffset,
		EndLoopAddressOffset,
		StartAddressCoarseOffset,
		ModulationLFOToPitch,
		VibratoLFOToPitch,
		ModulationEnvelopeToPitch,
		InitialFilterCutoffFrequency,
		InitialFilterQ,
		ModulationLFOToFilterCutoffFrequency,
		ModulationEnvelopeToFilterCutoffFrequency,
		EndAddressCoarseOffset,
		ModulationLFOToVolume,
		Unused1,
		ChorusEffectsSend,
		ReverbEffectsSend,
		Pan,
		Unused2,
		Unused3,
		Unused4,
		DelayModulationLFO,
		FrequencyModulationLFO,
		DelayVibratoLFO,
		FrequencyVibratoLFO,
		DelayModulationEnvelope,
		AttackModulationEnvelope,
		HoldModulationEnvelope,
		DecayModulationEnvelope,
		SustainModulationEnvelope,
		ReleaseModulationEnvelope,
		KeyNumberToModulationEnvelopeHold,
		KeyNumberToModulationEnvelopeDecay,
		DelayVolumeEnvelope,
		AttackVolumeEnvelope,
		HoldVolumeEnvelope,
		DecayVolumeEnvelope,
		SustainVolumeEnvelope,
		ReleaseVolumeEnvelope,
		KeyNumberToVolumeEnvelopeHold,
		KeyNumberToVolumeEnvelopeDecay,
		Instrument,
		Reserved1,
		KeyRange,
		VelocityRange,
		StartLoopAddressCoarseOffset,
		KeyNumber,
		Velocity,
		InitialAttenuation,
		Reserved2,
		EndLoopAddressCoarseOffset,
		CoarseTune,
		FineTune,
		SampleID,
		SampleModes,
		Reserved3,
		ScaleTuning,
		ExclusiveClass,
		OverridingRootKey,
		Unused5,
		UnusedEnd
	}
	public class InfoChunk
	{
		public SFVersion SoundFontVersion { get; }

		public string WaveTableSoundEngine { get; set; }

		public string BankName { get; set; }

		public string DataROM { get; set; }

		public string CreationDate { get; set; }

		public string Author { get; set; }

		public string TargetProduct { get; set; }

		public string Copyright { get; set; }

		public string Comments { get; set; }

		public string Tools { get; set; }

		public SFVersion ROMVersion { get; set; }

		internal InfoChunk(RiffChunk chunk)
		{
			bool flag = false;
			bool flag2 = false;
			if (chunk.ReadChunkID() != "INFO")
			{
				throw new InvalidDataException("Not an INFO chunk");
			}
			RiffChunk nextSubChunk;
			while ((nextSubChunk = chunk.GetNextSubChunk()) != null)
			{
				switch (nextSubChunk.ChunkID)
				{
				case "ifil":
					flag = true;
					SoundFontVersion = nextSubChunk.GetDataAsStructure(new SFVersionBuilder());
					break;
				case "isng":
					WaveTableSoundEngine = nextSubChunk.GetDataAsString();
					break;
				case "INAM":
					flag2 = true;
					BankName = nextSubChunk.GetDataAsString();
					break;
				case "irom":
					DataROM = nextSubChunk.GetDataAsString();
					break;
				case "iver":
					ROMVersion = nextSubChunk.GetDataAsStructure(new SFVersionBuilder());
					break;
				case "ICRD":
					CreationDate = nextSubChunk.GetDataAsString();
					break;
				case "IENG":
					Author = nextSubChunk.GetDataAsString();
					break;
				case "IPRD":
					TargetProduct = nextSubChunk.GetDataAsString();
					break;
				case "ICOP":
					Copyright = nextSubChunk.GetDataAsString();
					break;
				case "ICMT":
					Comments = nextSubChunk.GetDataAsString();
					break;
				case "ISFT":
					Tools = nextSubChunk.GetDataAsString();
					break;
				default:
					throw new InvalidDataException("Unknown chunk type " + nextSubChunk.ChunkID);
				}
			}
			if (!flag)
			{
				throw new InvalidDataException("Missing SoundFont version information");
			}
			if (!flag2)
			{
				throw new InvalidDataException("Missing SoundFont name information");
			}
		}

		public override string ToString()
		{
			return string.Format("Bank Name: {0}\r\nAuthor: {1}\r\nCopyright: {2}\r\nCreation Date: {3}\r\nTools: {4}\r\nComments: {5}\r\nSound Engine: {6}\r\nSoundFont Version: {7}\r\nTarget Product: {8}\r\nData ROM: {9}\r\nROM Version: {10}", BankName, Author, Copyright, CreationDate, Tools, "TODO-fix comments", WaveTableSoundEngine, SoundFontVersion, TargetProduct, DataROM, ROMVersion);
		}
	}
	public class Instrument
	{
		internal ushort startInstrumentZoneIndex;

		internal ushort endInstrumentZoneIndex;

		public string Name { get; set; }

		public Zone[] Zones { get; set; }

		public override string ToString()
		{
			return Name;
		}
	}
	internal class InstrumentBuilder : StructureBuilder<Instrument>
	{
		private Instrument lastInstrument;

		public override int Length => 22;

		public Instrument[] Instruments => data.ToArray();

		public override Instrument Read(BinaryReader br)
		{
			Instrument instrument = new Instrument();
			string text = Encoding.UTF8.GetString(br.ReadBytes(20), 0, 20);
			if (text.IndexOf('\0') >= 0)
			{
				text = text.Substring(0, text.IndexOf('\0'));
			}
			instrument.Name = text;
			instrument.startInstrumentZoneIndex = br.ReadUInt16();
			if (lastInstrument != null)
			{
				lastInstrument.endInstrumentZoneIndex = (ushort)(instrument.startInstrumentZoneIndex - 1);
			}
			data.Add(instrument);
			lastInstrument = instrument;
			return instrument;
		}

		public override void Write(BinaryWriter bw, Instrument instrument)
		{
		}

		public void LoadZones(Zone[] zones)
		{
			for (int i = 0; i < data.Count - 1; i++)
			{
				Instrument instrument = data[i];
				instrument.Zones = new Zone[instrument.endInstrumentZoneIndex - instrument.startInstrumentZoneIndex + 1];
				Array.Copy(zones, instrument.startInstrumentZoneIndex, instrument.Zones, 0, instrument.Zones.Length);
			}
			data.RemoveAt(data.Count - 1);
		}
	}
	public enum TransformEnum
	{
		Linear
	}
	public class Modulator
	{
		public ModulatorType SourceModulationData { get; set; }

		public GeneratorEnum DestinationGenerator { get; set; }

		public short Amount { get; set; }

		public ModulatorType SourceModulationAmount { get; set; }

		public TransformEnum SourceTransform { get; set; }

		public override string ToString()
		{
			return $"Modulator {SourceModulationData} {DestinationGenerator} {Amount} {SourceModulationAmount} {SourceTransform}";
		}
	}
	internal class ModulatorBuilder : StructureBuilder<Modulator>
	{
		public override int Length => 10;

		public Modulator[] Modulators => data.ToArray();

		public override Modulator Read(BinaryReader br)
		{
			Modulator modulator = new Modulator();
			modulator.SourceModulationData = new ModulatorType(br.ReadUInt16());
			modulator.DestinationGenerator = (GeneratorEnum)br.ReadUInt16();
			modulator.Amount = br.ReadInt16();
			modulator.SourceModulationAmount = new ModulatorType(br.ReadUInt16());
			modulator.SourceTransform = (TransformEnum)br.ReadUInt16();
			data.Add(modulator);
			return modulator;
		}

		public override void Write(BinaryWriter bw, Modulator o)
		{
		}
	}
	public enum ControllerSourceEnum
	{
		NoController = 0,
		NoteOnVelocity = 2,
		NoteOnKeyNumber = 3,
		PolyPressure = 10,
		ChannelPressure = 13,
		PitchWheel = 14,
		PitchWheelSensitivity = 16
	}
	public enum SourceTypeEnum
	{
		Linear,
		Concave,
		Convex,
		Switch
	}
	public class ModulatorType
	{
		private bool polarity;

		private bool direction;

		private bool midiContinuousController;

		private ControllerSourceEnum controllerSource;

		private SourceTypeEnum sourceType;

		private ushort midiContinuousControllerNumber;

		internal ModulatorType(ushort raw)
		{
			polarity = (raw & 0x200) == 512;
			direction = (raw & 0x100) == 256;
			midiContinuousController = (raw & 0x80) == 128;
			sourceType = (SourceTypeEnum)((raw & 0xFC00) >> 10);
			controllerSource = (ControllerSourceEnum)(raw & 0x7F);
			midiContinuousControllerNumber = (ushort)(raw & 0x7Fu);
		}

		public override string ToString()
		{
			if (midiContinuousController)
			{
				return $"{sourceType} CC{midiContinuousControllerNumber}";
			}
			return $"{sourceType} {controllerSource}";
		}
	}
	public class Preset
	{
		internal ushort startPresetZoneIndex;

		internal ushort endPresetZoneIndex;

		internal uint library;

		internal uint genre;

		internal uint morphology;

		public string Name { get; set; }

		public ushort PatchNumber { get; set; }

		public ushort Bank { get; set; }

		public Zone[] Zones { get; set; }

		public override string ToString()
		{
			return $"{Bank}-{PatchNumber} {Name}";
		}
	}
	internal class PresetBuilder : StructureBuilder<Preset>
	{
		private Preset lastPreset;

		public override int Length => 38;

		public Preset[] Presets => data.ToArray();

		public override Preset Read(BinaryReader br)
		{
			Preset preset = new Preset();
			string text = Encoding.UTF8.GetString(br.ReadBytes(20), 0, 20);
			if (text.IndexOf('\0') >= 0)
			{
				text = text.Substring(0, text.IndexOf('\0'));
			}
			preset.Name = text;
			preset.PatchNumber = br.ReadUInt16();
			preset.Bank = br.ReadUInt16();
			preset.startPresetZoneIndex = br.ReadUInt16();
			preset.library = br.ReadUInt32();
			preset.genre = br.ReadUInt32();
			preset.morphology = br.ReadUInt32();
			if (lastPreset != null)
			{
				lastPreset.endPresetZoneIndex = (ushort)(preset.startPresetZoneIndex - 1);
			}
			data.Add(preset);
			lastPreset = preset;
			return preset;
		}

		public override void Write(BinaryWriter bw, Preset preset)
		{
		}

		public void LoadZones(Zone[] presetZones)
		{
			for (int i = 0; i < data.Count - 1; i++)
			{
				Preset preset = data[i];
				preset.Zones = new Zone[preset.endPresetZoneIndex - preset.startPresetZoneIndex + 1];
				Array.Copy(presetZones, preset.startPresetZoneIndex, preset.Zones, 0, preset.Zones.Length);
			}
			data.RemoveAt(data.Count - 1);
		}
	}
	public class PresetsChunk
	{
		private PresetBuilder presetHeaders = new PresetBuilder();

		private ZoneBuilder presetZones = new ZoneBuilder();

		private ModulatorBuilder presetZoneModulators = new ModulatorBuilder();

		private GeneratorBuilder presetZoneGenerators = new GeneratorBuilder();

		private InstrumentBuilder instruments = new InstrumentBuilder();

		private ZoneBuilder instrumentZones = new ZoneBuilder();

		private ModulatorBuilder instrumentZoneModulators = new ModulatorBuilder();

		private GeneratorBuilder instrumentZoneGenerators = new GeneratorBuilder();

		private SampleHeaderBuilder sampleHeaders = new SampleHeaderBuilder();

		public Preset[] Presets => presetHeaders.Presets;

		public Instrument[] Instruments => instruments.Instruments;

		public SampleHeader[] SampleHeaders => sampleHeaders.SampleHeaders;

		internal PresetsChunk(RiffChunk chunk)
		{
			string text = chunk.ReadChunkID();
			if (text != "pdta")
			{
				throw new InvalidDataException($"Not a presets data chunk ({text})");
			}
			RiffChunk nextSubChunk;
			while ((nextSubChunk = chunk.GetNextSubChunk()) != null)
			{
				switch (nextSubChunk.ChunkID)
				{
				case "PHDR":
				case "phdr":
					nextSubChunk.GetDataAsStructureArray(presetHeaders);
					break;
				case "PBAG":
				case "pbag":
					nextSubChunk.GetDataAsStructureArray(presetZones);
					break;
				case "PMOD":
				case "pmod":
					nextSubChunk.GetDataAsStructureArray(presetZoneModulators);
					break;
				case "PGEN":
				case "pgen":
					nextSubChunk.GetDataAsStructureArray(presetZoneGenerators);
					break;
				case "INST":
				case "inst":
					nextSubChunk.GetDataAsStructureArray(instruments);
					break;
				case "IBAG":
				case "ibag":
					nextSubChunk.GetDataAsStructureArray(instrumentZones);
					break;
				case "IMOD":
				case "imod":
					nextSubChunk.GetDataAsStructureArray(instrumentZoneModulators);
					break;
				case "IGEN":
				case "igen":
					nextSubChunk.GetDataAsStructureArray(instrumentZoneGenerators);
					break;
				case "SHDR":
				case "shdr":
					nextSubChunk.GetDataAsStructureArray(sampleHeaders);
					break;
				default:
					throw new InvalidDataException($"Unknown chunk type {nextSubChunk.ChunkID}");
				}
			}
			instrumentZoneGenerators.Load(sampleHeaders.SampleHeaders);
			instrumentZones.Load(instrumentZoneModulators.Modulators, instrumentZoneGenerators.Generators);
			instruments.LoadZones(instrumentZones.Zones);
			presetZoneGenerators.Load(instruments.Instruments);
			presetZones.Load(presetZoneModulators.Modulators, presetZoneGenerators.Generators);
			presetHeaders.LoadZones(presetZones.Zones);
			sampleHeaders.RemoveEOS();
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Preset Headers:\r\n");
			Preset[] presets = presetHeaders.Presets;
			foreach (Preset arg in presets)
			{
				stringBuilder.AppendFormat("{0}\r\n", arg);
			}
			stringBuilder.Append("Instruments:\r\n");
			Instrument[] array = instruments.Instruments;
			foreach (Instrument arg2 in array)
			{
				stringBuilder.AppendFormat("{0}\r\n", arg2);
			}
			return stringBuilder.ToString();
		}
	}
	internal class RiffChunk
	{
		private string chunkID;

		private BinaryReader riffFile;

		public string ChunkID
		{
			get
			{
				return chunkID;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("ChunkID may not be null");
				}
				if (value.Length != 4)
				{
					throw new ArgumentException("ChunkID must be four characters");
				}
				chunkID = value;
			}
		}

		public uint ChunkSize { get; private set; }

		public long DataOffset { get; private set; }

		public static RiffChunk GetTopLevelChunk(BinaryReader file)
		{
			RiffChunk riffChunk = new RiffChunk(file);
			riffChunk.ReadChunk();
			return riffChunk;
		}

		private RiffChunk(BinaryReader file)
		{
			riffFile = file;
			chunkID = "????";
			ChunkSize = 0u;
			DataOffset = 0L;
		}

		public string ReadChunkID()
		{
			byte[] array = riffFile.ReadBytes(4);
			if (array.Length != 4)
			{
				throw new InvalidDataException("Couldn't read Chunk ID");
			}
			return ByteEncoding.Instance.GetString(array, 0, array.Length);
		}

		private void ReadChunk()
		{
			chunkID = ReadChunkID();
			ChunkSize = riffFile.ReadUInt32();
			DataOffset = riffFile.BaseStream.Position;
		}

		public RiffChunk GetNextSubChunk()
		{
			if (riffFile.BaseStream.Position + 8 < DataOffset + ChunkSize)
			{
				RiffChunk riffChunk = new RiffChunk(riffFile);
				riffChunk.ReadChunk();
				return riffChunk;
			}
			return null;
		}

		public byte[] GetData()
		{
			riffFile.BaseStream.Position = DataOffset;
			byte[] array = riffFile.ReadBytes((int)ChunkSize);
			if (array.Length != ChunkSize)
			{
				throw new InvalidDataException($"Couldn't read chunk's data Chunk: {this}, read {array.Length} bytes");
			}
			return array;
		}

		public string GetDataAsString()
		{
			byte[] data = GetData();
			if (data == null)
			{
				return null;
			}
			return ByteEncoding.Instance.GetString(data, 0, data.Length);
		}

		public T GetDataAsStructure<T>(StructureBuilder<T> s)
		{
			riffFile.BaseStream.Position = DataOffset;
			if (s.Length != ChunkSize)
			{
				throw new InvalidDataException($"Chunk size is: {ChunkSize} so can't read structure of: {s.Length}");
			}
			return s.Read(riffFile);
		}

		public T[] GetDataAsStructureArray<T>(StructureBuilder<T> s)
		{
			riffFile.BaseStream.Position = DataOffset;
			if (ChunkSize % s.Length != 0L)
			{
				throw new InvalidDataException($"Chunk size is: {ChunkSize} not a multiple of structure size: {s.Length}");
			}
			int num = (int)(ChunkSize / s.Length);
			T[] array = new T[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = s.Read(riffFile);
			}
			return array;
		}

		public override string ToString()
		{
			return $"RiffChunk ID: {ChunkID} Size: {ChunkSize} Data Offset: {DataOffset}";
		}
	}
	internal class SampleDataChunk
	{
		public byte[] SampleData { get; private set; }

		public SampleDataChunk(RiffChunk chunk)
		{
			string text = chunk.ReadChunkID();
			if (text != "sdta")
			{
				throw new InvalidDataException("Not a sample data chunk (" + text + ")");
			}
			SampleData = chunk.GetData();
		}
	}
	public class SampleHeader
	{
		public string SampleName;

		public uint Start;

		public uint End;

		public uint StartLoop;

		public uint EndLoop;

		public uint SampleRate;

		public byte OriginalPitch;

		public sbyte PitchCorrection;

		public ushort SampleLink;

		public SFSampleLink SFSampleLink;

		public override string ToString()
		{
			return SampleName;
		}
	}
	internal class SampleHeaderBuilder : StructureBuilder<SampleHeader>
	{
		public override int Length => 46;

		public SampleHeader[] SampleHeaders => data.ToArray();

		public override SampleHeader Read(BinaryReader br)
		{
			SampleHeader sampleHeader = new SampleHeader();
			byte[] array = br.ReadBytes(20);
			sampleHeader.SampleName = ByteEncoding.Instance.GetString(array, 0, array.Length);
			sampleHeader.Start = br.ReadUInt32();
			sampleHeader.End = br.ReadUInt32();
			sampleHeader.StartLoop = br.ReadUInt32();
			sampleHeader.EndLoop = br.ReadUInt32();
			sampleHeader.SampleRate = br.ReadUInt32();
			sampleHeader.OriginalPitch = br.ReadByte();
			sampleHeader.PitchCorrection = br.ReadSByte();
			sampleHeader.SampleLink = br.ReadUInt16();
			sampleHeader.SFSampleLink = (SFSampleLink)br.ReadUInt16();
			data.Add(sampleHeader);
			return sampleHeader;
		}

		public override void Write(BinaryWriter bw, SampleHeader sampleHeader)
		{
		}

		internal void RemoveEOS()
		{
			data.RemoveAt(data.Count - 1);
		}
	}
	public enum SampleMode
	{
		NoLoop,
		LoopContinuously,
		ReservedNoLoop,
		LoopAndContinue
	}
	public enum SFSampleLink : ushort
	{
		MonoSample = 1,
		RightSample = 2,
		LeftSample = 4,
		LinkedSample = 8,
		RomMonoSample = 32769,
		RomRightSample = 32770,
		RomLeftSample = 32772,
		RomLinkedSample = 32776
	}
	public class SFVersion
	{
		public short Major { get; set; }

		public short Minor { get; set; }
	}
	internal class SFVersionBuilder : StructureBuilder<SFVersion>
	{
		public override int Length => 4;

		public override SFVersion Read(BinaryReader br)
		{
			SFVersion sFVersion = new SFVersion();
			sFVersion.Major = br.ReadInt16();
			sFVersion.Minor = br.ReadInt16();
			data.Add(sFVersion);
			return sFVersion;
		}

		public override void Write(BinaryWriter bw, SFVersion v)
		{
			bw.Write(v.Major);
			bw.Write(v.Minor);
		}
	}
	public class SoundFont
	{
		private InfoChunk info;

		private PresetsChunk presetsChunk;

		private SampleDataChunk sampleData;

		public InfoChunk FileInfo => info;

		public Preset[] Presets => presetsChunk.Presets;

		public Instrument[] Instruments => presetsChunk.Instruments;

		public SampleHeader[] SampleHeaders => presetsChunk.SampleHeaders;

		public byte[] SampleData => sampleData.SampleData;

		public SoundFont(string fileName)
			: this(new FileStream(fileName, FileMode.Open, FileAccess.Read))
		{
		}

		public SoundFont(Stream sfFile)
		{
			using (sfFile)
			{
				RiffChunk topLevelChunk = RiffChunk.GetTopLevelChunk(new BinaryReader(sfFile));
				if (topLevelChunk.ChunkID == "RIFF")
				{
					string text = topLevelChunk.ReadChunkID();
					if (text != "sfbk")
					{
						throw new InvalidDataException($"Not a SoundFont ({text})");
					}
					RiffChunk nextSubChunk = topLevelChunk.GetNextSubChunk();
					if (nextSubChunk.ChunkID == "LIST")
					{
						info = new InfoChunk(nextSubChunk);
						RiffChunk nextSubChunk2 = topLevelChunk.GetNextSubChunk();
						sampleData = new SampleDataChunk(nextSubChunk2);
						nextSubChunk2 = topLevelChunk.GetNextSubChunk();
						presetsChunk = new PresetsChunk(nextSubChunk2);
						return;
					}
					throw new InvalidDataException($"Not info list found ({nextSubChunk.ChunkID})");
				}
				throw new InvalidDataException("Not a RIFF file");
			}
		}

		public override string ToString()
		{
			return $"Info Chunk:\r\n{info}\r\nPresets Chunk:\r\n{presetsChunk}";
		}
	}
	internal abstract class StructureBuilder<T>
	{
		protected List<T> data;

		public abstract int Length { get; }

		public T[] Data => data.ToArray();

		public StructureBuilder()
		{
			Reset();
		}

		public abstract T Read(BinaryReader br);

		public abstract void Write(BinaryWriter bw, T o);

		public void Reset()
		{
			data = new List<T>();
		}
	}
	public class Zone
	{
		internal ushort generatorIndex;

		internal ushort modulatorIndex;

		internal ushort generatorCount;

		internal ushort modulatorCount;

		public Modulator[] Modulators { get; set; }

		public Generator[] Generators { get; set; }

		public override string ToString()
		{
			return $"Zone {generatorCount} Gens:{generatorIndex} {modulatorCount} Mods:{modulatorIndex}";
		}
	}
	internal class ZoneBuilder : StructureBuilder<Zone>
	{
		private Zone lastZone;

		public Zone[] Zones => data.ToArray();

		public override int Length => 4;

		public override Zone Read(BinaryReader br)
		{
			Zone zone = new Zone();
			zone.generatorIndex = br.ReadUInt16();
			zone.modulatorIndex = br.ReadUInt16();
			if (lastZone != null)
			{
				lastZone.generatorCount = (ushort)(zone.generatorIndex - lastZone.generatorIndex);
				lastZone.modulatorCount = (ushort)(zone.modulatorIndex - lastZone.modulatorIndex);
			}
			data.Add(zone);
			lastZone = zone;
			return zone;
		}

		public override void Write(BinaryWriter bw, Zone zone)
		{
		}

		public void Load(Modulator[] modulators, Generator[] generators)
		{
			for (int i = 0; i < data.Count - 1; i++)
			{
				Zone zone = data[i];
				zone.Generators = new Generator[zone.generatorCount];
				Array.Copy(generators, zone.generatorIndex, zone.Generators, 0, zone.generatorCount);
				zone.Modulators = new Modulator[zone.modulatorCount];
				Array.Copy(modulators, zone.modulatorIndex, zone.Modulators, 0, zone.modulatorCount);
			}
			data.RemoveAt(data.Count - 1);
		}
	}
}
namespace NAudio.Wave
{
	public enum ChannelMode
	{
		Stereo,
		JointStereo,
		DualChannel,
		Mono
	}
	public class Id3v2Tag
	{
		private long tagStartPosition;

		private long tagEndPosition;

		private byte[] rawData;

		public byte[] RawData => rawData;

		public static Id3v2Tag ReadTag(Stream input)
		{
			try
			{
				return new Id3v2Tag(input);
			}
			catch (FormatException)
			{
				return null;
			}
		}

		public static Id3v2Tag Create(IEnumerable<KeyValuePair<string, string>> tags)
		{
			return ReadTag(CreateId3v2TagStream(tags));
		}

		private static byte[] FrameSizeToBytes(int n)
		{
			byte[] bytes = BitConverter.GetBytes(n);
			Array.Reverse((Array)bytes);
			return bytes;
		}

		private static byte[] CreateId3v2Frame(string key, string value)
		{
			if (string.IsNullOrEmpty(key))
			{
				throw new ArgumentNullException("key");
			}
			if (string.IsNullOrEmpty(value))
			{
				throw new ArgumentNullException("value");
			}
			if (key.Length != 4)
			{
				throw new ArgumentOutOfRangeException("key", "key " + key + " must be 4 characters long");
			}
			byte[] array = new byte[2] { 255, 254 };
			byte[] array2 = new byte[3];
			byte[] array3 = new byte[2];
			byte[] array4 = ((!(key == "COMM")) ? ByteArrayExtensions.Concat(new byte[1] { 1 }, array, Encoding.Unicode.GetBytes(value)) : ByteArrayExtensions.Concat(new byte[1] { 1 }, array2, array3, array, Encoding.Unicode.GetBytes(value)));
			return ByteArrayExtensions.Concat(Encoding.UTF8.GetBytes(key), FrameSizeToBytes(array4.Length), new byte[2], array4);
		}

		private static byte[] GetId3TagHeaderSize(int size)
		{
			byte[] array = new byte[4];
			for (int num = array.Length - 1; num >= 0; num--)
			{
				array[num] = (byte)(size % 128);
				size /= 128;
			}
			return array;
		}

		private static byte[] CreateId3v2TagHeader(IEnumerable<byte[]> frames)
		{
			int num = 0;
			foreach (byte[] frame in frames)
			{
				num += frame.Length;
			}
			return ByteArrayExtensions.Concat(Encoding.UTF8.GetBytes("ID3"), new byte[2] { 3, 0 }, new byte[1], GetId3TagHeaderSize(num));
		}

		private static Stream CreateId3v2TagStream(IEnumerable<KeyValuePair<string, string>> tags)
		{
			List<byte[]> list = new List<byte[]>();
			foreach (KeyValuePair<string, string> tag in tags)
			{
				list.Add(CreateId3v2Frame(tag.Key, tag.Value));
			}
			byte[] array = CreateId3v2TagHeader(list);
			MemoryStream memoryStream = new MemoryStream();
			memoryStream.Write(array, 0, array.Length);
			foreach (byte[] item in list)
			{
				memoryStream.Write(item, 0, item.Length);
			}
			memoryStream.Position = 0L;
			return memoryStream;
		}

		private Id3v2Tag(Stream input)
		{
			tagStartPosition = input.Position;
			BinaryReader binaryReader = new BinaryReader(input);
			byte[] array = binaryReader.ReadBytes(10);
			if (array.Length >= 3 && array[0] == 73 && array[1] == 68 && array[2] == 51)
			{
				if ((array[5] & 0x40) == 64)
				{
					byte[] array2 = binaryReader.ReadBytes(4);
					_ = array2[0] * 2097152 + array2[1] * 16384 + array2[2] * 128;
					_ = array2[3];
				}
				int num = array[6] * 2097152;
				num += array[7] * 16384;
				num += array[8] * 128;
				num += array[9];
				binaryReader.ReadBytes(num);
				if ((array[5] & 0x10) == 16)
				{
					binaryReader.ReadBytes(10);
				}
				tagEndPosition = input.Position;
				input.Position = tagStartPosition;
				rawData = binaryReader.ReadBytes((int)(tagEndPosition - tagStartPosition));
				return;
			}
			input.Position = tagStartPosition;
			throw new FormatException("Not an ID3v2 tag");
		}
	}
	public interface IMp3FrameDecompressor : IDisposable
	{
		WaveFormat OutputFormat { get; }

		int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset);

		void Reset();
	}
	public class Mp3Frame
	{
		private static readonly int[,,] bitRates = new int[2, 3, 15]
		{
			{
				{
					0, 32, 64, 96, 128, 160, 192, 224, 256, 288,
					320, 352, 384, 416, 448
				},
				{
					0, 32, 48, 56, 64, 80, 96, 112, 128, 160,
					192, 224, 256, 320, 384
				},
				{
					0, 32, 40, 48, 56, 64, 80, 96, 112, 128,
					160, 192, 224, 256, 320
				}
			},
			{
				{
					0, 32, 48, 56, 64, 80, 96, 112, 128, 144,
					160, 176, 192, 224, 256
				},
				{
					0, 8, 16, 24, 32, 40, 48, 56, 64, 80,
					96, 112, 128, 144, 160
				},
				{
					0, 8, 16, 24, 32, 40, 48, 56, 64, 80,
					96, 112, 128, 144, 160
				}
			}
		};

		private static readonly int[,] samplesPerFrame = new int[2, 3]
		{
			{ 384, 1152, 1152 },
			{ 384, 1152, 576 }
		};

		private static readonly int[] sampleRatesVersion1 = new int[3] { 44100, 48000, 32000 };

		private static readonly int[] sampleRatesVersion2 = new int[3] { 22050, 24000, 16000 };

		private static readonly int[] sampleRatesVersion25 = new int[3] { 11025, 12000, 8000 };

		private const int MaxFrameLength = 16384;

		public int SampleRate { get; private set; }

		public int FrameLength { get; private set; }

		public int BitRate { get; private set; }

		public byte[] RawData { get; private set; }

		public MpegVersion MpegVersion { get; private set; }

		public MpegLayer MpegLayer { get; private set; }

		public ChannelMode ChannelMode { get; private set; }

		public int SampleCount { get; private set; }

		public int ChannelExtension { get; private set; }

		public int BitRateIndex { get; private set; }

		public bool Copyright { get; private set; }

		public bool CrcPresent { get; private set; }

		public long FileOffset { get; private set; }

		public static Mp3Frame LoadFromStream(Stream input)
		{
			return LoadFromStream(input, readData: true);
		}

		public static Mp3Frame LoadFromStream(Stream input, bool readData)
		{
			Mp3Frame mp3Frame = new Mp3Frame();
			mp3Frame.FileOffset = input.Position;
			byte[] array = new byte[4];
			if (input.Read(array, 0, array.Length) < array.Length)
			{
				return null;
			}
			while (!IsValidHeader(array, mp3Frame))
			{
				array[0] = array[1];
				array[1] = array[2];
				array[2] = array[3];
				if (input.Read(array, 3, 1) < 1)
				{
					return null;
				}
				mp3Frame.FileOffset++;
			}
			int num = mp3Frame.FrameLength - 4;
			if (readData)
			{
				mp3Frame.RawData = new byte[mp3Frame.FrameLength];
				Array.Copy(array, mp3Frame.RawData, 4);
				if (input.Read(mp3Frame.RawData, 4, num) < num)
				{
					throw new EndOfStreamException("Unexpected end of stream before frame complete");
				}
			}
			else
			{
				input.Position += num;
			}
			return mp3Frame;
		}

		private Mp3Frame()
		{
		}

		private static bool IsValidHeader(byte[] headerBytes, Mp3Frame frame)
		{
			if (headerBytes[0] == byte.MaxValue && (headerBytes[1] & 0xE0) == 224)
			{
				frame.MpegVersion = (MpegVersion)((headerBytes[1] & 0x18) >> 3);
				if (frame.MpegVersion == MpegVersion.Reserved)
				{
					return false;
				}
				frame.MpegLayer = (MpegLayer)((headerBytes[1] & 6) >> 1);
				if (frame.MpegLayer == MpegLayer.Reserved)
				{
					return false;
				}
				int num = ((frame.MpegLayer != MpegLayer.Layer1) ? ((frame.MpegLayer == MpegLayer.Layer2) ? 1 : 2) : 0);
				frame.CrcPresent = (headerBytes[1] & 1) == 0;
				frame.BitRateIndex = (headerBytes[2] & 0xF0) >> 4;
				if (frame.BitRateIndex == 15)
				{
					return false;
				}
				int num2 = ((frame.MpegVersion != MpegVersion.Version1) ? 1 : 0);
				frame.BitRate = bitRates[num2, num, frame.BitRateIndex] * 1000;
				if (frame.BitRate == 0)
				{
					return false;
				}
				int num3 = (headerBytes[2] & 0xC) >> 2;
				if (num3 == 3)
				{
					return false;
				}
				if (frame.MpegVersion == MpegVersion.Version1)
				{
					frame.SampleRate = sampleRatesVersion1[num3];
				}
				else if (frame.MpegVersion == MpegVersion.Version2)
				{
					frame.SampleRate = sampleRatesVersion2[num3];
				}
				else
				{
					frame.SampleRate = sampleRatesVersion25[num3];
				}
				bool flag = (headerBytes[2] & 2) == 2;
				_ = headerBytes[2];
				frame.ChannelMode = (ChannelMode)((headerBytes[3] & 0xC0) >> 6);
				frame.ChannelExtension = (headerBytes[3] & 0x30) >> 4;
				if (frame.ChannelExtension != 0 && frame.ChannelMode != ChannelMode.JointStereo)
				{
					return false;
				}
				frame.Copyright = (headerBytes[3] & 8) == 8;
				_ = headerBytes[3];
				_ = headerBytes[3];
				int num4 = (flag ? 1 : 0);
				frame.SampleCount = samplesPerFrame[num2, num];
				int num5 = frame.SampleCount / 8;
				if (frame.MpegLayer == MpegLayer.Layer1)
				{
					frame.FrameLength = (num5 * frame.BitRate / frame.SampleRate + num4) * 4;
				}
				else
				{
					frame.FrameLength = num5 * frame.BitRate / frame.SampleRate + num4;
				}
				if (frame.FrameLength > 16384)
				{
					return false;
				}
				return true;
			}
			return false;
		}
	}
	public enum MpegLayer
	{
		Reserved,
		Layer3,
		Layer2,
		Layer1
	}
	public enum MpegVersion
	{
		Version25,
		Reserved,
		Version2,
		Version1
	}
	public class XingHeader
	{
		[Flags]
		private enum XingHeaderOptions
		{
			Frames = 1,
			Bytes = 2,
			Toc = 4,
			VbrScale = 8
		}

		private static int[] sr_table = new int[4] { 44100, 48000, 32000, 99999 };

		private int vbrScale = -1;

		private int startOffset;

		private int endOffset;

		private int tocOffset = -1;

		private int framesOffset = -1;

		private int bytesOffset = -1;

		private Mp3Frame frame;

		public int Frames
		{
			get
			{
				if (framesOffset == -1)
				{
					return -1;
				}
				return ReadBigEndian(frame.RawData, framesOffset);
			}
			set
			{
				if (framesOffset == -1)
				{
					throw new InvalidOperationException("Frames flag is not set");
				}
				WriteBigEndian(frame.RawData, framesOffset, value);
			}
		}

		public int Bytes
		{
			get
			{
				if (bytesOffset == -1)
				{
					return -1;
				}
				return ReadBigEndian(frame.RawData, bytesOffset);
			}
			set
			{
				if (framesOffset == -1)
				{
					throw new InvalidOperationException("Bytes flag is not set");
				}
				WriteBigEndian(frame.RawData, bytesOffset, value);
			}
		}

		public int VbrScale => vbrScale;

		public Mp3Frame Mp3Frame => frame;

		private static int ReadBigEndian(byte[] buffer, int offset)
		{
			return (((((buffer[offset] << 8) | buffer[offset + 1]) << 8) | buffer[offset + 2]) << 8) | buffer[offset + 3];
		}

		private void WriteBigEndian(byte[] buffer, int offset, int value)
		{
			byte[] bytes = BitConverter.GetBytes(value);
			for (int i = 0; i < 4; i++)
			{
				buffer[offset + 3 - i] = bytes[i];
			}
		}

		public static XingHeader LoadXingHeader(Mp3Frame frame)
		{
			XingHeader xingHeader = new XingHeader();
			xingHeader.frame = frame;
			int num = 0;
			if (frame.MpegVersion == MpegVersion.Version1)
			{
				num = ((frame.ChannelMode == ChannelMode.Mono) ? 21 : 36);
			}
			else
			{
				if (frame.MpegVersion != MpegVersion.Version2)
				{
					return null;
				}
				num = ((frame.ChannelMode == ChannelMode.Mono) ? 13 : 21);
			}
			if (frame.RawData[num] == 88 && frame.RawData[num + 1] == 105 && frame.RawData[num + 2] == 110 && frame.RawData[num + 3] == 103)
			{
				xingHeader.startOffset = num;
				num += 4;
			}
			else
			{
				if (frame.RawData[num] != 73 || frame.RawData[num + 1] != 110 || frame.RawData[num + 2] != 102 || frame.RawData[num + 3] != 111)
				{
					return null;
				}
				xingHeader.startOffset = num;
				num += 4;
			}
			int num2 = ReadBigEndian(frame.RawData, num);
			num += 4;
			if (((uint)num2 & (true ? 1u : 0u)) != 0)
			{
				xingHeader.framesOffset = num;
				num += 4;
			}
			if (((uint)num2 & 2u) != 0)
			{
				xingHeader.bytesOffset = num;
				num += 4;
			}
			if (((uint)num2 & 4u) != 0)
			{
				xingHeader.tocOffset = num;
				num += 100;
			}
			if (((uint)num2 & 8u) != 0)
			{
				xingHeader.vbrScale = ReadBigEndian(frame.RawData, num);
				num += 4;
			}
			xingHeader.endOffset = num;
			return xingHeader;
		}

		private XingHeader()
		{
		}
	}
	public static class WaveExtensionMethods
	{
		public static ISampleProvider ToSampleProvider(this IWaveProvider waveProvider)
		{
			return SampleProviderConverters.ConvertWaveProviderIntoSampleProvider(waveProvider);
		}

		public static void Init(this IWavePlayer wavePlayer, ISampleProvider sampleProvider, bool convertTo16Bit = false)
		{
			IWaveProvider waveProvider2;
			if (!convertTo16Bit)
			{
				IWaveProvider waveProvider = new SampleToWaveProvider(sampleProvider);
				waveProvider2 = waveProvider;
			}
			else
			{
				IWaveProvider waveProvider = new SampleToWaveProvider16(sampleProvider);
				waveProvider2 = waveProvider;
			}
			IWaveProvider waveProvider3 = waveProvider2;
			wavePlayer.Init(waveProvider3);
		}

		public static WaveFormat AsStandardWaveFormat(this WaveFormat waveFormat)
		{
			if (!(waveFormat is WaveFormatExtensible waveFormatExtensible))
			{
				return waveFormat;
			}
			return waveFormatExtensible.ToStandardWaveFormat();
		}

		public static IWaveProvider ToWaveProvider(this ISampleProvider sampleProvider)
		{
			return new SampleToWaveProvider(sampleProvider);
		}

		public static IWaveProvider ToWaveProvider16(this ISampleProvider sampleProvider)
		{
			return new SampleToWaveProvider16(sampleProvider);
		}

		public static ISampleProvider FollowedBy(this ISampleProvider sampleProvider, ISampleProvider next)
		{
			return new ConcatenatingSampleProvider(new ISampleProvider[2] { sampleProvider, next });
		}

		public static ISampleProvider FollowedBy(this ISampleProvider sampleProvider, TimeSpan silenceDuration, ISampleProvider next)
		{
			OffsetSampleProvider offsetSampleProvider = new OffsetSampleProvider(sampleProvider)
			{
				LeadOut = silenceDuration
			};
			return new ConcatenatingSampleProvider(new ISampleProvider[2] { offsetSampleProvider, next });
		}

		public static ISampleProvider Skip(this ISampleProvider sampleProvider, TimeSpan skipDuration)
		{
			return new OffsetSampleProvider(sampleProvider)
			{
				SkipOver = skipDuration
			};
		}

		public static ISampleProvider Take(this ISampleProvider sampleProvider, TimeSpan takeDuration)
		{
			return new OffsetSampleProvider(sampleProvider)
			{
				Take = takeDuration
			};
		}

		public static ISampleProvider ToMono(this ISampleProvider sourceProvider, float leftVol = 0.5f, float rightVol = 0.5f)
		{
			if (sourceProvider.WaveFormat.Channels == 1)
			{
				return sourceProvider;
			}
			return new StereoToMonoSampleProvider(sourceProvider)
			{
				LeftVolume = leftVol,
				RightVolume = rightVol
			};
		}

		public static ISampleProvider ToStereo(this ISampleProvider sourceProvider, float leftVol = 1f, float rightVol = 1f)
		{
			if (sourceProvider.WaveFormat.Channels == 2)
			{
				return sourceProvider;
			}
			return new MonoToStereoSampleProvider(sourceProvider)
			{
				LeftVolume = leftVol,
				RightVolume = rightVol
			};
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class AdpcmWaveFormat : WaveFormat
	{
		private short samplesPerBlock;

		private short numCoeff;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)]
		private short[] coefficients;

		public int SamplesPerBlock => samplesPerBlock;

		public int NumCoefficients => numCoeff;

		public short[] Coefficients => coefficients;

		private AdpcmWaveFormat()
			: this(8000, 1)
		{
		}

		public AdpcmWaveFormat(int sampleRate, int channels)
			: base(sampleRate, 0, channels)
		{
			waveFormatTag = WaveFormatEncoding.Adpcm;
			extraSize = 32;
			switch (base.sampleRate)
			{
			case 8000:
			case 11025:
				blockAlign = 256;
				break;
			case 22050:
				blockAlign = 512;
				break;
			default:
				blockAlign = 1024;
				break;
			}
			bitsPerSample = 4;
			samplesPerBlock = (short)((blockAlign - 7 * channels) * 8 / (bitsPerSample * channels) + 2);
			averageBytesPerSecond = base.SampleRate * blockAlign / samplesPerBlock;
			numCoeff = 7;
			coefficients = new short[14]
			{
				256, 0, 512, -256, 0, 0, 192, 64, 240, 0,
				460, -208, 392, -232
			};
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			writer.Write(samplesPerBlock);
			writer.Write(numCoeff);
			short[] array = coefficients;
			foreach (short value in array)
			{
				writer.Write(value);
			}
		}

		public override string ToString()
		{
			return $"Microsoft ADPCM {base.SampleRate} Hz {channels} channels {bitsPerSample} bits per sample {samplesPerBlock} samples per block";
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class Gsm610WaveFormat : WaveFormat
	{
		private readonly short samplesPerBlock;

		public short SamplesPerBlock => samplesPerBlock;

		public Gsm610WaveFormat()
		{
			waveFormatTag = WaveFormatEncoding.Gsm610;
			channels = 1;
			averageBytesPerSecond = 1625;
			bitsPerSample = 0;
			blockAlign = 65;
			sampleRate = 8000;
			extraSize = 2;
			samplesPerBlock = 320;
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			writer.Write(samplesPerBlock);
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class ImaAdpcmWaveFormat : WaveFormat
	{
		private short samplesPerBlock;

		private ImaAdpcmWaveFormat()
		{
		}

		public ImaAdpcmWaveFormat(int sampleRate, int channels, int bitsPerSample)
		{
			waveFormatTag = WaveFormatEncoding.DviAdpcm;
			base.sampleRate = sampleRate;
			base.channels = (short)channels;
			base.bitsPerSample = (short)bitsPerSample;
			extraSize = 2;
			blockAlign = 0;
			averageBytesPerSecond = 0;
			samplesPerBlock = 0;
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class Mp3WaveFormat : WaveFormat
	{
		public Mp3WaveFormatId id;

		public Mp3WaveFormatFlags flags;

		public ushort blockSize;

		public ushort framesPerBlock;

		public ushort codecDelay;

		private const short Mp3WaveFormatExtraBytes = 12;

		public Mp3WaveFormat(int sampleRate, int channels, int blockSize, int bitRate)
		{
			waveFormatTag = WaveFormatEncoding.MpegLayer3;
			base.channels = (short)channels;
			averageBytesPerSecond = bitRate / 8;
			bitsPerSample = 0;
			blockAlign = 1;
			base.sampleRate = sampleRate;
			extraSize = 12;
			id = Mp3WaveFormatId.Mpeg;
			flags = Mp3WaveFormatFlags.PaddingIso;
			this.blockSize = (ushort)blockSize;
			framesPerBlock = 1;
			codecDelay = 0;
		}
	}
	[Flags]
	public enum Mp3WaveFormatFlags
	{
		PaddingIso = 0,
		PaddingOn = 1,
		PaddingOff = 2
	}
	public enum Mp3WaveFormatId : ushort
	{
		Unknown,
		Mpeg,
		ConstantFrameSize
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	internal class OggWaveFormat : WaveFormat
	{
		public uint dwVorbisACMVersion;

		public uint dwLibVorbisVersion;
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class TrueSpeechWaveFormat : WaveFormat
	{
		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
		private short[] unknown;

		public TrueSpeechWaveFormat()
		{
			waveFormatTag = WaveFormatEncoding.DspGroupTrueSpeech;
			channels = 1;
			averageBytesPerSecond = 1067;
			bitsPerSample = 1;
			blockAlign = 32;
			sampleRate = 8000;
			extraSize = 32;
			unknown = new short[16];
			unknown[0] = 1;
			unknown[1] = 240;
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			short[] array = unknown;
			foreach (short value in array)
			{
				writer.Write(value);
			}
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class WaveFormat
	{
		protected WaveFormatEncoding waveFormatTag;

		protected short channels;

		protected int sampleRate;

		protected int averageBytesPerSecond;

		protected short blockAlign;

		protected short bitsPerSample;

		protected short extraSize;

		public WaveFormatEncoding Encoding => waveFormatTag;

		public int Channels => channels;

		public int SampleRate => sampleRate;

		public int AverageBytesPerSecond => averageBytesPerSecond;

		public virtual int BlockAlign => blockAlign;

		public int BitsPerSample => bitsPerSample;

		public int ExtraSize => extraSize;

		public WaveFormat()
			: this(44100, 16, 2)
		{
		}

		public WaveFormat(int sampleRate, int channels)
			: this(sampleRate, 16, channels)
		{
		}

		public int ConvertLatencyToByteSize(int milliseconds)
		{
			int num = (int)((double)AverageBytesPerSecond / 1000.0 * (double)milliseconds);
			if (num % BlockAlign != 0)
			{
				num = num + BlockAlign - num % BlockAlign;
			}
			return num;
		}

		public static WaveFormat CreateCustomFormat(WaveFormatEncoding tag, int sampleRate, int channels, int averageBytesPerSecond, int blockAlign, int bitsPerSample)
		{
			return new WaveFormat
			{
				waveFormatTag = tag,
				channels = (short)channels,
				sampleRate = sampleRate,
				averageBytesPerSecond = averageBytesPerSecond,
				blockAlign = (short)blockAlign,
				bitsPerSample = (short)bitsPerSample,
				extraSize = 0
			};
		}

		public static WaveFormat CreateALawFormat(int sampleRate, int channels)
		{
			return CreateCustomFormat(WaveFormatEncoding.ALaw, sampleRate, channels, sampleRate * channels, channels, 8);
		}

		public static WaveFormat CreateMuLawFormat(int sampleRate, int channels)
		{
			return CreateCustomFormat(WaveFormatEncoding.MuLaw, sampleRate, channels, sampleRate * channels, channels, 8);
		}

		public WaveFormat(int rate, int bits, int channels)
		{
			if (channels < 1)
			{
				throw new ArgumentOutOfRangeException("channels", "Channels must be 1 or greater");
			}
			waveFormatTag = WaveFormatEncoding.Pcm;
			this.channels = (short)channels;
			sampleRate = rate;
			bitsPerSample = (short)bits;
			extraSize = 0;
			blockAlign = (short)(channels * (bits / 8));
			averageBytesPerSecond = sampleRate * blockAlign;
		}

		public static WaveFormat CreateIeeeFloatWaveFormat(int sampleRate, int channels)
		{
			WaveFormat waveFormat = new WaveFormat();
			waveFormat.waveFormatTag = WaveFormatEncoding.IeeeFloat;
			waveFormat.channels = (short)channels;
			waveFormat.bitsPerSample = 32;
			waveFormat.sampleRate = sampleRate;
			waveFormat.blockAlign = (short)(4 * channels);
			waveFormat.averageBytesPerSecond = sampleRate * waveFormat.blockAlign;
			waveFormat.extraSize = 0;
			return waveFormat;
		}

		public static WaveFormat MarshalFromPtr(IntPtr pointer)
		{
			WaveFormat waveFormat = Marshal.PtrToStructure<WaveFormat>(pointer);
			switch (waveFormat.Encoding)
			{
			case WaveFormatEncoding.Pcm:
				waveFormat.extraSize = 0;
				break;
			case WaveFormatEncoding.Extensible:
				waveFormat = Marshal.PtrToStructure<WaveFormatExtensible>(pointer);
				break;
			case WaveFormatEncoding.Adpcm:
				waveFormat = Marshal.PtrToStructure<AdpcmWaveFormat>(pointer);
				break;
			case WaveFormatEncoding.Gsm610:
				waveFormat = Marshal.PtrToStructure<Gsm610WaveFormat>(pointer);
				break;
			default:
				if (waveFormat.ExtraSize > 0)
				{
					waveFormat = Marshal.PtrToStructure<WaveFormatExtraData>(pointer);
				}
				break;
			}
			return waveFormat;
		}

		public static IntPtr MarshalToPtr(WaveFormat format)
		{
			IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(format));
			Marshal.StructureToPtr(format, intPtr, fDeleteOld: false);
			return intPtr;
		}

		public static WaveFormat FromFormatChunk(BinaryReader br, int formatChunkLength)
		{
			WaveFormatExtraData waveFormatExtraData = new WaveFormatExtraData();
			waveFormatExtraData.ReadWaveFormat(br, formatChunkLength);
			waveFormatExtraData.ReadExtraData(br);
			return waveFormatExtraData;
		}

		private void ReadWaveFormat(BinaryReader br, int formatChunkLength)
		{
			if (formatChunkLength < 16)
			{
				throw new InvalidDataException("Invalid WaveFormat Structure");
			}
			waveFormatTag = (WaveFormatEncoding)br.ReadUInt16();
			channels = br.ReadInt16();
			sampleRate = br.ReadInt32();
			averageBytesPerSecond = br.ReadInt32();
			blockAlign = br.ReadInt16();
			bitsPerSample = br.ReadInt16();
			if (formatChunkLength > 16)
			{
				extraSize = br.ReadInt16();
				if (extraSize != formatChunkLength - 18)
				{
					extraSize = (short)(formatChunkLength - 18);
				}
			}
		}

		public WaveFormat(BinaryReader br)
		{
			int formatChunkLength = br.ReadInt32();
			ReadWaveFormat(br, formatChunkLength);
		}

		public override string ToString()
		{
			WaveFormatEncoding waveFormatEncoding = waveFormatTag;
			if (waveFormatEncoding == WaveFormatEncoding.Pcm || waveFormatEncoding == WaveFormatEncoding.Extensible)
			{
				return $"{bitsPerSample} bit PCM: {sampleRate / 1000}kHz {channels} channels";
			}
			return waveFormatTag.ToString();
		}

		public override bool Equals(object obj)
		{
			if (obj is WaveFormat waveFormat)
			{
				if (waveFormatTag == waveFormat.waveFormatTag && channels == waveFormat.channels && sampleRate == waveFormat.sampleRate && averageBytesPerSecond == waveFormat.averageBytesPerSecond && blockAlign == waveFormat.blockAlign)
				{
					return bitsPerSample == waveFormat.bitsPerSample;
				}
				return false;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (int)waveFormatTag ^ (int)channels ^ sampleRate ^ averageBytesPerSecond ^ blockAlign ^ bitsPerSample;
		}

		public virtual void Serialize(BinaryWriter writer)
		{
			writer.Write(18 + extraSize);
			writer.Write((short)Encoding);
			writer.Write((short)Channels);
			writer.Write(SampleRate);
			writer.Write(AverageBytesPerSecond);
			writer.Write((short)BlockAlign);
			writer.Write((short)BitsPerSample);
			writer.Write(extraSize);
		}
	}
	public sealed class WaveFormatCustomMarshaler : ICustomMarshaler
	{
		private static WaveFormatCustomMarshaler marshaler;

		public static ICustomMarshaler GetInstance(string cookie)
		{
			if (marshaler == null)
			{
				marshaler = new WaveFormatCustomMarshaler();
			}
			return marshaler;
		}

		public void CleanUpManagedData(object ManagedObj)
		{
		}

		public void CleanUpNativeData(IntPtr pNativeData)
		{
			Marshal.FreeHGlobal(pNativeData);
		}

		public int GetNativeDataSize()
		{
			throw new NotImplementedException();
		}

		public IntPtr MarshalManagedToNative(object ManagedObj)
		{
			return WaveFormat.MarshalToPtr((WaveFormat)ManagedObj);
		}

		public object MarshalNativeToManaged(IntPtr pNativeData)
		{
			return WaveFormat.MarshalFromPtr(pNativeData);
		}
	}
	public enum WaveFormatEncoding : ushort
	{
		Unknown = 0,
		Pcm = 1,
		Adpcm = 2,
		IeeeFloat = 3,
		Vselp = 4,
		IbmCvsd = 5,
		ALaw = 6,
		MuLaw = 7,
		Dts = 8,
		Drm = 9,
		WmaVoice9 = 10,
		OkiAdpcm = 16,
		DviAdpcm = 17,
		ImaAdpcm = 17,
		MediaspaceAdpcm = 18,
		SierraAdpcm = 19,
		G723Adpcm = 20,
		DigiStd = 21,
		DigiFix = 22,
		DialogicOkiAdpcm = 23,
		MediaVisionAdpcm = 24,
		CUCodec = 25,
		YamahaAdpcm = 32,
		SonarC = 33,
		DspGroupTrueSpeech = 34,
		EchoSpeechCorporation1 = 35,
		AudioFileAf36 = 36,
		Aptx = 37,
		AudioFileAf10 = 38,
		Prosody1612 = 39,
		Lrc = 40,
		DolbyAc2 = 48,
		Gsm610 = 49,
		MsnAudio = 50,
		AntexAdpcme = 51,
		ControlResVqlpc = 52,
		DigiReal = 53,
		DigiAdpcm = 54,
		ControlResCr10 = 55,
		WAVE_FORMAT_NMS_VBXADPCM = 56,
		WAVE_FORMAT_CS_IMAADPCM = 57,
		WAVE_FORMAT_ECHOSC3 = 58,
		WAVE_FORMAT_ROCKWELL_ADPCM = 59,
		WAVE_FORMAT_ROCKWELL_DIGITALK = 60,
		WAVE_FORMAT_XEBEC = 61,
		WAVE_FORMAT_G721_ADPCM = 64,
		WAVE_FORMAT_G728_CELP = 65,
		WAVE_FORMAT_MSG723 = 66,
		Mpeg = 80,
		WAVE_FORMAT_RT24 = 82,
		WAVE_FORMAT_PAC = 83,
		MpegLayer3 = 85,
		WAVE_FORMAT_LUCENT_G723 = 89,
		WAVE_FORMAT_CIRRUS = 96,
		WAVE_FORMAT_ESPCM = 97,
		WAVE_FORMAT_VOXWARE = 98,
		WAVE_FORMAT_CANOPUS_ATRAC = 99,
		WAVE_FORMAT_G726_ADPCM = 100,
		WAVE_FORMAT_G722_ADPCM = 101,
		WAVE_FORMAT_DSAT_DISPLAY = 103,
		WAVE_FORMAT_VOXWARE_BYTE_ALIGNED = 105,
		WAVE_FORMAT_VOXWARE_AC8 = 112,
		WAVE_FORMAT_VOXWARE_AC10 = 113,
		WAVE_FORMAT_VOXWARE_AC16 = 114,
		WAVE_FORMAT_VOXWARE_AC20 = 115,
		WAVE_FORMAT_VOXWARE_RT24 = 116,
		WAVE_FORMAT_VOXWARE_RT29 = 117,
		WAVE_FORMAT_VOXWARE_RT29HW = 118,
		WAVE_FORMAT_VOXWARE_VR12 = 119,
		WAVE_FORMAT_VOXWARE_VR18 = 120,
		WAVE_FORMAT_VOXWARE_TQ40 = 121,
		WAVE_FORMAT_SOFTSOUND = 128,
		WAVE_FORMAT_VOXWARE_TQ60 = 129,
		WAVE_FORMAT_MSRT24 = 130,
		WAVE_FORMAT_G729A = 131,
		WAVE_FORMAT_MVI_MVI2 = 132,
		WAVE_FORMAT_DF_G726 = 133,
		WAVE_FORMAT_DF_GSM610 = 134,
		WAVE_FORMAT_ISIAUDIO = 136,
		WAVE_FORMAT_ONLIVE = 137,
		WAVE_FORMAT_SBC24 = 145,
		WAVE_FORMAT_DOLBY_AC3_SPDIF = 146,
		WAVE_FORMAT_MEDIASONIC_G723 = 147,
		WAVE_FORMAT_PROSODY_8KBPS = 148,
		WAVE_FORMAT_ZYXEL_ADPCM = 151,
		WAVE_FORMAT_PHILIPS_LPCBB = 152,
		WAVE_FORMAT_PACKED = 153,
		WAVE_FORMAT_MALDEN_PHONYTALK = 160,
		Gsm = 161,
		G729 = 162,
		G723 = 163,
		Acelp = 164,
		RawAac = 255,
		WAVE_FORMAT_RHETOREX_ADPCM = 256,
		WAVE_FORMAT_IRAT = 257,
		WAVE_FORMAT_VIVO_G723 = 273,
		WAVE_FORMAT_VIVO_SIREN = 274,
		WAVE_FORMAT_DIGITAL_G723 = 291,
		WAVE_FORMAT_SANYO_LD_ADPCM = 293,
		WAVE_FORMAT_SIPROLAB_ACEPLNET = 304,
		WAVE_FORMAT_SIPROLAB_ACELP4800 = 305,
		WAVE_FORMAT_SIPROLAB_ACELP8V3 = 306,
		WAVE_FORMAT_SIPROLAB_G729 = 307,
		WAVE_FORMAT_SIPROLAB_G729A = 308,
		WAVE_FORMAT_SIPROLAB_KELVIN = 309,
		WAVE_FORMAT_G726ADPCM = 320,
		WAVE_FORMAT_QUALCOMM_PUREVOICE = 336,
		WAVE_FORMAT_QUALCOMM_HALFRATE = 337,
		WAVE_FORMAT_TUBGSM = 341,
		WAVE_FORMAT_MSAUDIO1 = 352,
		WindowsMediaAudio = 353,
		WindowsMediaAudioProfessional = 354,
		WindowsMediaAudioLosseless = 355,
		WindowsMediaAudioSpdif = 356,
		WAVE_FORMAT_UNISYS_NAP_ADPCM = 368,
		WAVE_FORMAT_UNISYS_NAP_ULAW = 369,
		WAVE_FORMAT_UNISYS_NAP_ALAW = 370,
		WAVE_FORMAT_UNISYS_NAP_16K = 371,
		WAVE_FORMAT_CREATIVE_ADPCM = 512,
		WAVE_FORMAT_CREATIVE_FASTSPEECH8 = 514,
		WAVE_FORMAT_CREATIVE_FASTSPEECH10 = 515,
		WAVE_FORMAT_UHER_ADPCM = 528,
		WAVE_FORMAT_QUARTERDECK = 544,
		WAVE_FORMAT_ILINK_VC = 560,
		WAVE_FORMAT_RAW_SPORT = 576,
		WAVE_FORMAT_ESST_AC3 = 577,
		WAVE_FORMAT_IPI_HSX = 592,
		WAVE_FORMAT_IPI_RPELP = 593,
		WAVE_FORMAT_CS2 = 608,
		WAVE_FORMAT_SONY_SCX = 624,
		WAVE_FORMAT_FM_TOWNS_SND = 768,
		WAVE_FORMAT_BTV_DIGITAL = 1024,
		WAVE_FORMAT_QDESIGN_MUSIC = 1104,
		WAVE_FORMAT_VME_VMPCM = 1664,
		WAVE_FORMAT_TPC = 1665,
		WAVE_FORMAT_OLIGSM = 4096,
		WAVE_FORMAT_OLIADPCM = 4097,
		WAVE_FORMAT_OLICELP = 4098,
		WAVE_FORMAT_OLISBC = 4099,
		WAVE_FORMAT_OLIOPR = 4100,
		WAVE_FORMAT_LH_CODEC = 4352,
		WAVE_FORMAT_NORRIS = 5120,
		WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS = 5376,
		MPEG_ADTS_AAC = 5632,
		MPEG_RAW_AAC = 5633,
		MPEG_LOAS = 5634,
		NOKIA_MPEG_ADTS_AAC = 5640,
		NOKIA_MPEG_RAW_AAC = 5641,
		VODAFONE_MPEG_ADTS_AAC = 5642,
		VODAFONE_MPEG_RAW_AAC = 5643,
		MPEG_HEAAC = 5648,
		WAVE_FORMAT_DVM = 8192,
		Vorbis1 = 26447,
		Vorbis2 = 26448,
		Vorbis3 = 26449,
		Vorbis1P = 26479,
		Vorbis2P = 26480,
		Vorbis3P = 26481,
		Extensible = 65534,
		WAVE_FORMAT_DEVELOPMENT = ushort.MaxValue
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class WaveFormatExtensible : WaveFormat
	{
		private short wValidBitsPerSample;

		private int dwChannelMask;

		private Guid subFormat;

		public Guid SubFormat => subFormat;

		private WaveFormatExtensible()
		{
		}

		public WaveFormatExtensible(int rate, int bits, int channels)
			: base(rate, bits, channels)
		{
			waveFormatTag = WaveFormatEncoding.Extensible;
			extraSize = 22;
			wValidBitsPerSample = (short)bits;
			for (int i = 0; i < channels; i++)
			{
				dwChannelMask |= 1 << i;
			}
			if (bits == 32)
			{
				subFormat = AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT;
			}
			else
			{
				subFormat = AudioMediaSubtypes.MEDIASUBTYPE_PCM;
			}
		}

		public WaveFormat ToStandardWaveFormat()
		{
			if (subFormat == AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT && bitsPerSample == 32)
			{
				return WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels);
			}
			if (subFormat == AudioMediaSubtypes.MEDIASUBTYPE_PCM)
			{
				return new WaveFormat(sampleRate, bitsPerSample, channels);
			}
			return this;
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			writer.Write(wValidBitsPerSample);
			writer.Write(dwChannelMask);
			byte[] array = subFormat.ToByteArray();
			writer.Write(array, 0, array.Length);
		}

		public override string ToString()
		{
			return $"{base.ToString()} wBitsPerSample:{wValidBitsPerSample} dwChannelMask:{dwChannelMask} subFormat:{subFormat} extraSize:{extraSize}";
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class WaveFormatExtraData : WaveFormat
	{
		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
		private byte[] extraData = new byte[100];

		public byte[] ExtraData => extraData;

		internal WaveFormatExtraData()
		{
		}

		public WaveFormatExtraData(BinaryReader reader)
			: base(reader)
		{
			ReadExtraData(reader);
		}

		internal void ReadExtraData(BinaryReader reader)
		{
			if (extraSize > 0)
			{
				reader.Read(extraData, 0, extraSize);
			}
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			if (extraSize > 0)
			{
				writer.Write(extraData, 0, extraSize);
			}
		}
	}
	public interface IWaveIn : IDisposable
	{
		WaveFormat WaveFormat { get; set; }

		event EventHandler<WaveInEventArgs> DataAvailable;

		event EventHandler<StoppedEventArgs> RecordingStopped;

		void StartRecording();

		void StopRecording();
	}
	public class WaveInEventArgs : EventArgs
	{
		private byte[] buffer;

		private int bytes;

		public byte[] Buffer => buffer;

		public int BytesRecorded => bytes;

		public WaveInEventArgs(byte[] buffer, int bytes)
		{
			this.buffer = buffer;
			this.bytes = bytes;
		}
	}
	public class AiffFileWriter : Stream
	{
		private Stream outStream;

		private BinaryWriter writer;

		private long dataSizePos;

		private long commSampleCountPos;

		private int dataChunkSize = 8;

		private WaveFormat format;

		private string filename;

		private byte[] value24 = new byte[3];

		public string Filename => filename;

		public override long Length => dataChunkSize;

		public WaveFormat WaveFormat => format;

		public override bool CanRead => false;

		public override bool CanWrite => true;

		public override bool CanSeek => false;

		public override long Position
		{
			get
			{
				return dataChunkSize;
			}
			set
			{
				throw new InvalidOperationException("Repositioning an AiffFileWriter is not supported");
			}
		}

		public static void CreateAiffFile(string filename, WaveStream sourceProvider)
		{
			using AiffFileWriter aiffFileWriter = new AiffFileWriter(filename, sourceProvider.WaveFormat);
			byte[] array = new byte[16384];
			while (sourceProvider.Position < sourceProvider.Length)
			{
				int count = Math.Min((int)(sourceProvider.Length - sourceProvider.Position), array.Length);
				int num = sourceProvider.Read(array, 0, count);
				if (num == 0)
				{
					break;
				}
				aiffFileWriter.Write(array, 0, num);
			}
		}

		public AiffFileWriter(Stream outStream, WaveFormat format)
		{
			this.outStream = outStream;
			this.format = format;
			writer = new BinaryWriter(outStream, Encoding.UTF8);
			writer.Write(Encoding.UTF8.GetBytes("FORM"));
			writer.Write(0);
			writer.Write(Encoding.UTF8.GetBytes("AIFF"));
			CreateCommChunk();
			WriteSsndChunkHeader();
		}

		public AiffFileWriter(string filename, WaveFormat format)
			: this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), format)
		{
			this.filename = filename;
		}

		private void WriteSsndChunkHeader()
		{
			writer.Write(Encoding.UTF8.GetBytes("SSND"));
			dataSizePos = outStream.Position;
			writer.Write(0);
			writer.Write(0);
			writer.Write(SwapEndian(format.BlockAlign));
		}

		private byte[] SwapEndian(short n)
		{
			return new byte[2]
			{
				(byte)(n >> 8),
				(byte)((uint)n & 0xFFu)
			};
		}

		private byte[] SwapEndian(int n)
		{
			return new byte[4]
			{
				(byte)((uint)(n >> 24) & 0xFFu),
				(byte)((uint)(n >> 16) & 0xFFu),
				(byte)((uint)(n >> 8) & 0xFFu),
				(byte)((uint)n & 0xFFu)
			};
		}

		private void CreateCommChunk()
		{
			writer.Write(Encoding.UTF8.GetBytes("COMM"));
			writer.Write(SwapEndian(18));
			writer.Write(SwapEndian((short)format.Channels));
			commSampleCountPos = outStream.Position;
			writer.Write(0);
			writer.Write(SwapEndian((short)format.BitsPerSample));
			writer.Write(IEEE.ConvertToIeeeExtended(format.SampleRate));
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			throw new InvalidOperationException("Cannot read from an AiffFileWriter");
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new InvalidOperationException("Cannot seek within an AiffFileWriter");
		}

		public override void SetLength(long value)
		{
			throw new InvalidOperationException("Cannot set length of an AiffFileWriter");
		}

		public override void Write(byte[] data, int offset, int count)
		{
			byte[] array = new byte[data.Length];
			int num = format.BitsPerSample / 8;
			for (int i = 0; i < data.Length; i++)
			{
				int num2 = (int)Math.Floor((double)i / (double)num) * num + (num - i % num - 1);
				array[i] = data[num2];
			}
			outStream.Write(array, offset, count);
			dataChunkSize += count;
		}

		public void WriteSample(float sample)
		{
			if (WaveFormat.BitsPerSample == 16)
			{
				writer.Write(SwapEndian((short)(32767f * sample)));
				dataChunkSize += 2;
			}
			else if (WaveFormat.BitsPerSample == 24)
			{
				byte[] bytes = BitConverter.GetBytes((int)(2.1474836E+09f * sample));
				value24[2] = bytes[1];
				value24[1] = bytes[2];
				value24[0] = bytes[3];
				writer.Write(value24);
				dataChunkSize += 3;
			}
			else
			{
				if (WaveFormat.BitsPerSample != 32 || WaveFormat.Encoding != WaveFormatEncoding.Extensible)
				{
					throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported");
				}
				writer.Write(SwapEndian(65535 * (int)sample));
				dataChunkSize += 4;
			}
		}

		public void WriteSamples(float[] samples, int offset, int count)
		{
			for (int i = 0; i < count; i++)
			{
				WriteSample(samples[offset + i]);
			}
		}

		public void WriteSamples(short[] samples, int offset, int count)
		{
			if (WaveFormat.BitsPerSample == 16)
			{
				for (int i = 0; i < count; i++)
				{
					writer.Write(SwapEndian(samples[i + offset]));
				}
				dataChunkSize += count * 2;
			}
			else if (WaveFormat.BitsPerSample == 24)
			{
				for (int j = 0; j < count; j++)
				{
					byte[] bytes = BitConverter.GetBytes(65535 * samples[j + offset]);
					value24[2] = bytes[1];
					value24[1] = bytes[2];
					value24[0] = bytes[3];
					writer.Write(value24);
				}
				dataChunkSize += count * 3;
			}
			else
			{
				if (WaveFormat.BitsPerSample != 32 || WaveFormat.Encoding != WaveFormatEncoding.Extensible)
				{
					throw new InvalidOperationException("Only 16, 24 or 32 bit PCM audio data supported");
				}
				for (int k = 0; k < count; k++)
				{
					writer.Write(SwapEndian(65535 * samples[k + offset]));
				}
				dataChunkSize += count * 4;
			}
		}

		public override void Flush()
		{
			writer.Flush();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && outStream != null)
			{
				try
				{
					UpdateHeader(writer);
				}
				finally
				{
					outStream.Dispose();
					outStream = null;
				}
			}
		}

		protected virtual void UpdateHeader(BinaryWriter writer)
		{
			Flush();
			writer.Seek(4, SeekOrigin.Begin);
			writer.Write(SwapEndian((int)(outStream.Length - 8)));
			UpdateCommChunk(writer);
			UpdateSsndChunk(writer);
		}

		private void UpdateCommChunk(BinaryWriter writer)
		{
			writer.Seek((int)commSampleCountPos, SeekOrigin.Begin);
			writer.Write(SwapEndian(dataChunkSize * 8 / format.BitsPerSample / format.Channels));
		}

		private void UpdateSsndChunk(BinaryWriter writer)
		{
			writer.Seek((int)dataSizePos, SeekOrigin.Begin);
			writer.Write(SwapEndian(dataChunkSize));
		}

		~AiffFileWriter()
		{
			Dispose(disposing: false);
		}
	}
	public class BextChunkInfo
	{
		public string Description { get; set; }

		public string Originator { get; set; }

		public string OriginatorReference { get; set; }

		public DateTime OriginationDateTime { get; set; }

		public string OriginationDate => OriginationDateTime.ToString("yyyy-MM-dd");

		public string OriginationTime => OriginationDateTime.ToString("HH:mm:ss");

		public long TimeReference { get; set; }

		public ushort Version => 1;

		public string UniqueMaterialIdentifier { get; set; }

		public byte[] Reserved { get; }

		public string CodingHistory { get; set; }

		public BextChunkInfo()
		{
			Reserved = new byte[190];
		}
	}
	public class BwfWriter : IDisposable
	{
		private readonly WaveFormat format;

		private readonly BinaryWriter writer;

		private readonly long dataChunkSizePosition;

		private long dataLength;

		private bool isDisposed;

		public BwfWriter(string filename, WaveFormat format, BextChunkInfo bextChunkInfo)
		{
			this.format = format;
			writer = new BinaryWriter(File.OpenWrite(filename));
			writer.Write(Encoding.UTF8.GetBytes("RIFF"));
			writer.Write(0);
			writer.Write(Encoding.UTF8.GetBytes("WAVE"));
			writer.Write(Encoding.UTF8.GetBytes("JUNK"));
			writer.Write(28);
			writer.Write(0L);
			writer.Write(0L);
			writer.Write(0L);
			writer.Write(0);
			writer.Write(Encoding.UTF8.GetBytes("bext"));
			byte[] bytes = Encoding.ASCII.GetBytes(bextChunkInfo.CodingHistory ?? "");
			int num = 602 + bytes.Length;
			if (num % 2 != 0)
			{
				num++;
			}
			writer.Write(num);
			_ = writer.BaseStream.Position;
			writer.Write(GetAsBytes(bextChunkInfo.Description, 256));
			writer.Write(GetAsBytes(bextChunkInfo.Originator, 32));
			writer.Write(GetAsBytes(bextChunkInfo.OriginatorReference, 32));
			writer.Write(GetAsBytes(bextChunkInfo.OriginationDate, 10));
			writer.Write(GetAsBytes(bextChunkInfo.OriginationTime, 8));
			writer.Write(bextChunkInfo.TimeReference);
			writer.Write(bextChunkInfo.Version);
			writer.Write(GetAsBytes(bextChunkInfo.UniqueMaterialIdentifier, 64));
			writer.Write(bextChunkInfo.Reserved);
			writer.Write(bytes);
			if (bytes.Length % 2 != 0)
			{
				writer.Write((byte)0);
			}
			writer.Write(Encoding.UTF8.GetBytes("fmt "));
			format.Serialize(writer);
			writer.Write(Encoding.UTF8.GetBytes("data"));
			dataChunkSizePosition = writer.BaseStream.Position;
			writer.Write(-1);
		}

		public void Write(byte[] buffer, int offset, int count)
		{
			if (isDisposed)
			{
				throw new ObjectDisposedException("This BWF Writer already disposed");
			}
			writer.Write(buffer, offset, count);
			dataLength += count;
		}

		public void Flush()
		{
			if (isDisposed)
			{
				throw new ObjectDisposedException("This BWF Writer already disposed");
			}
			writer.Flush();
			FixUpChunkSizes(restorePosition: true);
		}

		private void FixUpChunkSizes(bool restorePosition)
		{
			long position = writer.BaseStream.Position;
			bool num = dataLength > int.MaxValue;
			long num2 = writer.BaseStream.Length - 8;
			if (num)
			{
				int num3 = format.BitsPerSample / 8 * format.Channels;
				writer.BaseStream.Position = 0L;
				writer.Write(Encoding.UTF8.GetBytes("RF64"));
				writer.Write(-1);
				writer.BaseStream.Position += 4L;
				writer.Write(Encoding.UTF8.GetBytes("ds64"));
				writer.BaseStream.Position += 4L;
				writer.Write(num2);
				writer.Write(dataLength);
				writer.Write(dataLength / num3);
			}
			else
			{
				writer.BaseStream.Position = 4L;
				writer.Write((uint)num2);
				writer.BaseStream.Position = dataChunkSizePosition;
				writer.Write((uint)dataLength);
			}
			if (restorePosition)
			{
				writer.BaseStream.Position = position;
			}
		}

		public void Dispose()
		{
			if (!isDisposed)
			{
				FixUpChunkSizes(restorePosition: false);
				writer.Dispose();
				isDisposed = true;
			}
		}

		private static byte[] GetAsBytes(string message, int byteSize)
		{
			byte[] array = new byte[byteSize];
			byte[] bytes = Encoding.ASCII.GetBytes(message ?? "");
			Array.Copy(bytes, array, Math.Min(bytes.Length, byteSize));
			return array;
		}
	}
	public class CueWaveFileWriter : WaveFileWriter
	{
		private CueList cues;

		public CueWaveFileWriter(string fileName, WaveFormat waveFormat)
			: base(fileName, waveFormat)
		{
		}

		public void AddCue(int position, string label)
		{
			if (cues == null)
			{
				cues = new CueList();
			}
			cues.Add(new Cue(position, label));
		}

		private void WriteCues(BinaryWriter w)
		{
			if (cues != null)
			{
				int count = cues.GetRiffChunks().Length;
				w.Seek(0, SeekOrigin.End);
				if (w.BaseStream.Length % 2 == 1)
				{
					w.Write((byte)0);
				}
				w.Write(cues.GetRiffChunks(), 0, count);
				w.Seek(4, SeekOrigin.Begin);
				w.Write((int)(w.BaseStream.Length - 8));
			}
		}

		protected override void UpdateHeader(BinaryWriter writer)
		{
			base.UpdateHeader(writer);
			WriteCues(writer);
		}
	}
	public class DirectSoundOut : IWavePlayer, IDisposable
	{
		[StructLayout(LayoutKind.Sequential, Pack = 2)]
		internal class BufferDescription
		{
			public int dwSize;

			[MarshalAs(UnmanagedType.U4)]
			public DirectSoundBufferCaps dwFlags;

			public uint dwBufferBytes;

			public int dwReserved;

			public IntPtr lpwfxFormat;

			public Guid guidAlgo;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 2)]
		internal class BufferCaps
		{
			public int dwSize;

			public int dwFlags;

			public int dwBufferBytes;

			public int dwUnlockTransferRate;

			public int dwPlayCpuOverhead;
		}

		internal enum DirectSoundCooperativeLevel : uint
		{
			DSSCL_NORMAL = 1u,
			DSSCL_PRIORITY,
			DSSCL_EXCLUSIVE,
			DSSCL_WRITEPRIMARY
		}

		[Flags]
		internal enum DirectSoundPlayFlags : uint
		{
			DSBPLAY_LOOPING = 1u,
			DSBPLAY_LOCHARDWARE = 2u,
			DSBPLAY_LOCSOFTWARE = 4u,
			DSBPLAY_TERMINATEBY_TIME = 8u,
			DSBPLAY_TERMINATEBY_DISTANCE = 0x10u,
			DSBPLAY_TERMINATEBY_PRIORITY = 0x20u
		}

		internal enum DirectSoundBufferLockFlag : uint
		{
			None,
			FromWriteCursor,
			EntireBuffer
		}

		[Flags]
		internal enum DirectSoundBufferStatus : uint
		{
			DSBSTATUS_PLAYING = 1u,
			DSBSTATUS_BUFFERLOST = 2u,
			DSBSTATUS_LOOPING = 4u,
			DSBSTATUS_LOCHARDWARE = 8u,
			DSBSTATUS_LOCSOFTWARE = 0x10u,
			DSBSTATUS_TERMINATED = 0x20u
		}

		[Flags]
		internal enum DirectSoundBufferCaps : uint
		{
			DSBCAPS_PRIMARYBUFFER = 1u,
			DSBCAPS_STATIC = 2u,
			DSBCAPS_LOCHARDWARE = 4u,
			DSBCAPS_LOCSOFTWARE = 8u,
			DSBCAPS_CTRL3D = 0x10u,
			DSBCAPS_CTRLFREQUENCY = 0x20u,
			DSBCAPS_CTRLPAN = 0x40u,
			DSBCAPS_CTRLVOLUME = 0x80u,
			DSBCAPS_CTRLPOSITIONNOTIFY = 0x100u,
			DSBCAPS_CTRLFX = 0x200u,
			DSBCAPS_STICKYFOCUS = 0x4000u,
			DSBCAPS_GLOBALFOCUS = 0x8000u,
			DSBCAPS_GETCURRENTPOSITION2 = 0x10000u,
			DSBCAPS_MUTE3DATMAXDISTANCE = 0x20000u,
			DSBCAPS_LOCDEFER = 0x40000u
		}

		internal struct DirectSoundBufferPositionNotify
		{
			public uint dwOffset;

			public IntPtr hEventNotify;
		}

		[ComImport]
		[Guid("279AFA83-4981-11CE-A521-0020AF0BE560")]
		[SuppressUnmanagedCodeSecurity]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		internal interface IDirectSound
		{
			void CreateSoundBuffer([In] BufferDescription desc, [MarshalAs(UnmanagedType.Interface)] out object dsDSoundBuffer, IntPtr pUnkOuter);

			void GetCaps(IntPtr caps);

			void DuplicateSoundBuffer([In][MarshalAs(UnmanagedType.Interface)] IDirectSoundBuffer bufferOriginal, [In][MarshalAs(UnmanagedType.Interface)] IDirectSoundBuffer bufferDuplicate);

			void SetCooperativeLevel(IntPtr HWND, [In][MarshalAs(UnmanagedType.U4)] DirectSoundCooperativeLevel dwLevel);

			void Compact();

			void GetSpeakerConfig(IntPtr pdwSpeakerConfig);

			void SetSpeakerConfig(uint pdwSpeakerConfig);

			void Initialize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guid);
		}

		[ComImport]
		[Guid("279AFA85-4981-11CE-A521-0020AF0BE560")]
		[SuppressUnmanagedCodeSecurity]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		internal interface IDirectSoundBuffer
		{
			void GetCaps([MarshalAs(UnmanagedType.LPStruct)] BufferCaps pBufferCaps);

			void GetCurrentPosition(out uint currentPlayCursor, out uint currentWriteCursor);

			void GetFormat();

			[return: MarshalAs(UnmanagedType.I4)]
			int GetVolume();

			void GetPan(out uint pan);

			[return: MarshalAs(UnmanagedType.I4)]
			int GetFrequency();

			[return: MarshalAs(UnmanagedType.U4)]
			DirectSoundBufferStatus GetStatus();

			void Initialize([In][MarshalAs(UnmanagedType.Interface)] IDirectSound directSound, [In] BufferDescription desc);

			void Lock(int dwOffset, uint dwBytes, out IntPtr audioPtr1, out int audioBytes1, out IntPtr audioPtr2, out int audioBytes2, [MarshalAs(UnmanagedType.U4)] DirectSoundBufferLockFlag dwFlags);

			void Play(uint dwReserved1, uint dwPriority, [In][MarshalAs(UnmanagedType.U4)] DirectSoundPlayFlags dwFlags);

			void SetCurrentPosition(uint dwNewPosition);

			void SetFormat([In] WaveFormat pcfxFormat);

			void SetVolume(int volume);

			void SetPan(uint pan);

			void SetFrequency(uint frequency);

			void Stop();

			void Unlock(IntPtr pvAudioPtr1, int dwAudioBytes1, IntPtr pvAudioPtr2, int dwAudioBytes2);

			void Restore();
		}

		[ComImport]
		[Guid("b0210783-89cd-11d0-af08-00a0c925cd16")]
		[SuppressUnmanagedCodeSecurity]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		internal interface IDirectSoundNotify
		{
			void SetNotificationPositions(uint dwPositionNotifies, [In][MarshalAs(UnmanagedType.LPArray)] DirectSoundBufferPositionNotify[] pcPositionNotifies);
		}

		private delegate bool DSEnumCallback(IntPtr lpGuid, IntPtr lpcstrDescription, IntPtr lpcstrModule, IntPtr lpContext);

		private PlaybackState playbackState;

		private WaveFormat waveFormat;

		private int samplesTotalSize;

		private int samplesFrameSize;

		private int nextSamplesWriteIndex;

		private int desiredLatency;

		private Guid device;

		private byte[] samples;

		private IWaveProvider waveStream;

		private IDirectSound directSound;

		private IDirectSoundBuffer primarySoundBuffer;

		private IDirectSoundBuffer secondaryBuffer;

		private EventWaitHandle frameEventWaitHandle1;

		private EventWa

NAudio.Midi.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using NAudio.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Mark Heath")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2021")]
[assembly: AssemblyFileVersion("2.0.1.0")]
[assembly: AssemblyInformationalVersion("2.0.1")]
[assembly: AssemblyProduct("NAudio.Midi")]
[assembly: AssemblyTitle("NAudio.Midi")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: AssemblyVersion("2.0.1.0")]
namespace NAudio.Midi
{
	public class ChannelAfterTouchEvent : MidiEvent
	{
		private byte afterTouchPressure;

		public int AfterTouchPressure
		{
			get
			{
				return afterTouchPressure;
			}
			set
			{
				if (value < 0 || value > 127)
				{
					throw new ArgumentOutOfRangeException("value", "After touch pressure must be in the range 0-127");
				}
				afterTouchPressure = (byte)value;
			}
		}

		public ChannelAfterTouchEvent(BinaryReader br)
		{
			afterTouchPressure = br.ReadByte();
			if ((afterTouchPressure & 0x80u) != 0)
			{
				throw new FormatException("Invalid afterTouchPressure");
			}
		}

		public ChannelAfterTouchEvent(long absoluteTime, int channel, int afterTouchPressure)
			: base(absoluteTime, channel, MidiCommandCode.ChannelAfterTouch)
		{
			AfterTouchPressure = afterTouchPressure;
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write(afterTouchPressure);
		}

		public override int GetAsShortMessage()
		{
			return base.GetAsShortMessage() + (afterTouchPressure << 8);
		}

		public override string ToString()
		{
			return $"{base.ToString()} {afterTouchPressure}";
		}
	}
	public class ControlChangeEvent : MidiEvent
	{
		private MidiController controller;

		private byte controllerValue;

		public MidiController Controller
		{
			get
			{
				return controller;
			}
			set
			{
				if ((int)value < 0 || (int)value > 127)
				{
					throw new ArgumentOutOfRangeException("value", "Controller number must be in the range 0-127");
				}
				controller = value;
			}
		}

		public int ControllerValue
		{
			get
			{
				return controllerValue;
			}
			set
			{
				if (value < 0 || value > 127)
				{
					throw new ArgumentOutOfRangeException("value", "Controller Value must be in the range 0-127");
				}
				controllerValue = (byte)value;
			}
		}

		public ControlChangeEvent(BinaryReader br)
		{
			byte b = br.ReadByte();
			controllerValue = br.ReadByte();
			if ((b & 0x80u) != 0)
			{
				throw new InvalidDataException("Invalid controller");
			}
			controller = (MidiController)b;
			if ((controllerValue & 0x80u) != 0)
			{
				throw new InvalidDataException($"Invalid controllerValue {controllerValue} for controller {controller}, Pos 0x{br.BaseStream.Position:X}");
			}
		}

		public ControlChangeEvent(long absoluteTime, int channel, MidiController controller, int controllerValue)
			: base(absoluteTime, channel, MidiCommandCode.ControlChange)
		{
			Controller = controller;
			ControllerValue = controllerValue;
		}

		public override string ToString()
		{
			return $"{base.ToString()} Controller {controller} Value {controllerValue}";
		}

		public override int GetAsShortMessage()
		{
			byte b = (byte)controller;
			return base.GetAsShortMessage() + (b << 8) + (controllerValue << 16);
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write((byte)controller);
			writer.Write(controllerValue);
		}
	}
	public class KeySignatureEvent : MetaEvent
	{
		private readonly byte sharpsFlats;

		private readonly byte majorMinor;

		public int SharpsFlats => (sbyte)sharpsFlats;

		public int MajorMinor => majorMinor;

		public KeySignatureEvent(BinaryReader br, int length)
		{
			if (length != 2)
			{
				throw new FormatException("Invalid key signature length");
			}
			sharpsFlats = br.ReadByte();
			majorMinor = br.ReadByte();
		}

		public KeySignatureEvent(int sharpsFlats, int majorMinor, long absoluteTime)
			: base(MetaEventType.KeySignature, 2, absoluteTime)
		{
			this.sharpsFlats = (byte)sharpsFlats;
			this.majorMinor = (byte)majorMinor;
		}

		public override MidiEvent Clone()
		{
			return (KeySignatureEvent)MemberwiseClone();
		}

		public override string ToString()
		{
			return $"{base.ToString()} {SharpsFlats} {majorMinor}";
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write(sharpsFlats);
			writer.Write(majorMinor);
		}
	}
	public class MetaEvent : MidiEvent
	{
		private MetaEventType metaEvent;

		internal int metaDataLength;

		public MetaEventType MetaEventType => metaEvent;

		protected MetaEvent()
		{
		}

		public MetaEvent(MetaEventType metaEventType, int metaDataLength, long absoluteTime)
			: base(absoluteTime, 1, MidiCommandCode.MetaEvent)
		{
			metaEvent = metaEventType;
			this.metaDataLength = metaDataLength;
		}

		public override MidiEvent Clone()
		{
			return new MetaEvent(metaEvent, metaDataLength, base.AbsoluteTime);
		}

		public static MetaEvent ReadMetaEvent(BinaryReader br)
		{
			MetaEventType metaEventType = (MetaEventType)br.ReadByte();
			int num = MidiEvent.ReadVarInt(br);
			MetaEvent metaEvent = new MetaEvent();
			if (metaEventType <= MetaEventType.SetTempo)
			{
				if (metaEventType <= MetaEventType.DeviceName)
				{
					if (metaEventType != 0)
					{
						if (metaEventType - 1 > MetaEventType.ProgramName)
						{
							goto IL_00a6;
						}
						metaEvent = new TextEvent(br, num);
					}
					else
					{
						metaEvent = new TrackSequenceNumberEvent(br, num);
					}
				}
				else if (metaEventType != MetaEventType.EndTrack)
				{
					if (metaEventType != MetaEventType.SetTempo)
					{
						goto IL_00a6;
					}
					metaEvent = new TempoEvent(br, num);
				}
				else if (num != 0)
				{
					throw new FormatException("End track length");
				}
			}
			else if (metaEventType <= MetaEventType.TimeSignature)
			{
				if (metaEventType != MetaEventType.SmpteOffset)
				{
					if (metaEventType != MetaEventType.TimeSignature)
					{
						goto IL_00a6;
					}
					metaEvent = new TimeSignatureEvent(br, num);
				}
				else
				{
					metaEvent = new SmpteOffsetEvent(br, num);
				}
			}
			else if (metaEventType != MetaEventType.KeySignature)
			{
				if (metaEventType != MetaEventType.SequencerSpecific)
				{
					goto IL_00a6;
				}
				metaEvent = new SequencerSpecificEvent(br, num);
			}
			else
			{
				metaEvent = new KeySignatureEvent(br, num);
			}
			metaEvent.metaEvent = metaEventType;
			metaEvent.metaDataLength = num;
			return metaEvent;
			IL_00a6:
			byte[] array = br.ReadBytes(num);
			if (array.Length != num)
			{
				throw new FormatException("Failed to read metaevent's data fully");
			}
			return new RawMetaEvent(metaEventType, 0L, array);
		}

		public override string ToString()
		{
			return $"{base.AbsoluteTime} {metaEvent}";
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write((byte)metaEvent);
			MidiEvent.WriteVarInt(writer, metaDataLength);
		}
	}
	public enum MetaEventType : byte
	{
		TrackSequenceNumber = 0,
		TextEvent = 1,
		Copyright = 2,
		SequenceTrackName = 3,
		TrackInstrumentName = 4,
		Lyric = 5,
		Marker = 6,
		CuePoint = 7,
		ProgramName = 8,
		DeviceName = 9,
		MidiChannel = 32,
		MidiPort = 33,
		EndTrack = 47,
		SetTempo = 81,
		SmpteOffset = 84,
		TimeSignature = 88,
		KeySignature = 89,
		SequencerSpecific = 127
	}
	public enum MidiCommandCode : byte
	{
		NoteOff = 128,
		NoteOn = 144,
		KeyAfterTouch = 160,
		ControlChange = 176,
		PatchChange = 192,
		ChannelAfterTouch = 208,
		PitchWheelChange = 224,
		Sysex = 240,
		Eox = 247,
		TimingClock = 248,
		StartSequence = 250,
		ContinueSequence = 251,
		StopSequence = 252,
		AutoSensing = 254,
		MetaEvent = byte.MaxValue
	}
	public enum MidiController : byte
	{
		BankSelect = 0,
		Modulation = 1,
		BreathController = 2,
		FootController = 4,
		MainVolume = 7,
		Pan = 10,
		Expression = 11,
		BankSelectLsb = 32,
		Sustain = 64,
		Portamento = 65,
		Sostenuto = 66,
		SoftPedal = 67,
		LegatoFootswitch = 68,
		ResetAllControllers = 121,
		AllNotesOff = 123
	}
	public class MidiEvent : ICloneable
	{
		private MidiCommandCode commandCode;

		private int channel;

		private int deltaTime;

		private long absoluteTime;

		public virtual int Channel
		{
			get
			{
				return channel;
			}
			set
			{
				if (value < 1 || value > 16)
				{
					throw new ArgumentOutOfRangeException("value", value, $"Channel must be 1-16 (Got {value})");
				}
				channel = value;
			}
		}

		public int DeltaTime => deltaTime;

		public long AbsoluteTime
		{
			get
			{
				return absoluteTime;
			}
			set
			{
				absoluteTime = value;
			}
		}

		public MidiCommandCode CommandCode => commandCode;

		public static MidiEvent FromRawMessage(int rawMessage)
		{
			long num = 0L;
			int num2 = rawMessage & 0xFF;
			int num3 = (rawMessage >> 8) & 0xFF;
			int num4 = (rawMessage >> 16) & 0xFF;
			int num5 = 1;
			MidiCommandCode midiCommandCode;
			if ((num2 & 0xF0) == 240)
			{
				midiCommandCode = (MidiCommandCode)num2;
			}
			else
			{
				midiCommandCode = (MidiCommandCode)((uint)num2 & 0xF0u);
				num5 = (num2 & 0xF) + 1;
			}
			switch (midiCommandCode)
			{
			case MidiCommandCode.NoteOff:
			case MidiCommandCode.NoteOn:
			case MidiCommandCode.KeyAfterTouch:
				if (num4 > 0 && midiCommandCode == MidiCommandCode.NoteOn)
				{
					return new NoteOnEvent(num, num5, num3, num4, 0);
				}
				return new NoteEvent(num, num5, midiCommandCode, num3, num4);
			case MidiCommandCode.ControlChange:
				return new ControlChangeEvent(num, num5, (MidiController)num3, num4);
			case MidiCommandCode.PatchChange:
				return new PatchChangeEvent(num, num5, num3);
			case MidiCommandCode.ChannelAfterTouch:
				return new ChannelAfterTouchEvent(num, num5, num3);
			case MidiCommandCode.PitchWheelChange:
				return new PitchWheelChangeEvent(num, num5, num3 + (num4 << 7));
			case MidiCommandCode.TimingClock:
			case MidiCommandCode.StartSequence:
			case MidiCommandCode.ContinueSequence:
			case MidiCommandCode.StopSequence:
			case MidiCommandCode.AutoSensing:
				return new MidiEvent(num, num5, midiCommandCode);
			default:
				throw new FormatException($"Unsupported MIDI Command Code for Raw Message {midiCommandCode}");
			}
		}

		public static MidiEvent ReadNextEvent(BinaryReader br, MidiEvent previous)
		{
			int num = ReadVarInt(br);
			int num2 = 1;
			byte b = br.ReadByte();
			MidiCommandCode midiCommandCode;
			if ((b & 0x80) == 0)
			{
				midiCommandCode = previous.CommandCode;
				num2 = previous.Channel;
				br.BaseStream.Position--;
			}
			else if ((b & 0xF0) == 240)
			{
				midiCommandCode = (MidiCommandCode)b;
			}
			else
			{
				midiCommandCode = (MidiCommandCode)(b & 0xF0u);
				num2 = (b & 0xF) + 1;
			}
			MidiEvent midiEvent;
			switch (midiCommandCode)
			{
			case MidiCommandCode.NoteOn:
				midiEvent = new NoteOnEvent(br);
				break;
			case MidiCommandCode.NoteOff:
			case MidiCommandCode.KeyAfterTouch:
				midiEvent = new NoteEvent(br);
				break;
			case MidiCommandCode.ControlChange:
				midiEvent = new ControlChangeEvent(br);
				break;
			case MidiCommandCode.PatchChange:
				midiEvent = new PatchChangeEvent(br);
				break;
			case MidiCommandCode.ChannelAfterTouch:
				midiEvent = new ChannelAfterTouchEvent(br);
				break;
			case MidiCommandCode.PitchWheelChange:
				midiEvent = new PitchWheelChangeEvent(br);
				break;
			case MidiCommandCode.TimingClock:
			case MidiCommandCode.StartSequence:
			case MidiCommandCode.ContinueSequence:
			case MidiCommandCode.StopSequence:
				midiEvent = new MidiEvent();
				break;
			case MidiCommandCode.Sysex:
				midiEvent = SysexEvent.ReadSysexEvent(br);
				break;
			case MidiCommandCode.MetaEvent:
				midiEvent = MetaEvent.ReadMetaEvent(br);
				break;
			default:
				throw new FormatException($"Unsupported MIDI Command Code {(byte)midiCommandCode:X2}");
			}
			midiEvent.channel = num2;
			midiEvent.deltaTime = num;
			midiEvent.commandCode = midiCommandCode;
			return midiEvent;
		}

		public virtual int GetAsShortMessage()
		{
			return channel - 1 + (int)commandCode;
		}

		protected MidiEvent()
		{
		}

		public MidiEvent(long absoluteTime, int channel, MidiCommandCode commandCode)
		{
			this.absoluteTime = absoluteTime;
			Channel = channel;
			this.commandCode = commandCode;
		}

		public virtual MidiEvent Clone()
		{
			return (MidiEvent)MemberwiseClone();
		}

		object ICloneable.Clone()
		{
			return Clone();
		}

		public static bool IsNoteOff(MidiEvent midiEvent)
		{
			if (midiEvent != null)
			{
				if (midiEvent.CommandCode == MidiCommandCode.NoteOn)
				{
					return ((NoteEvent)midiEvent).Velocity == 0;
				}
				return midiEvent.CommandCode == MidiCommandCode.NoteOff;
			}
			return false;
		}

		public static bool IsNoteOn(MidiEvent midiEvent)
		{
			if (midiEvent != null && midiEvent.CommandCode == MidiCommandCode.NoteOn)
			{
				return ((NoteEvent)midiEvent).Velocity > 0;
			}
			return false;
		}

		public static bool IsEndTrack(MidiEvent midiEvent)
		{
			if (midiEvent != null && midiEvent is MetaEvent metaEvent)
			{
				return metaEvent.MetaEventType == MetaEventType.EndTrack;
			}
			return false;
		}

		public override string ToString()
		{
			if ((int)commandCode >= 240)
			{
				return $"{absoluteTime} {commandCode}";
			}
			return $"{absoluteTime} {commandCode} Ch: {channel}";
		}

		public static int ReadVarInt(BinaryReader br)
		{
			int num = 0;
			for (int i = 0; i < 4; i++)
			{
				byte b = br.ReadByte();
				num <<= 7;
				num += b & 0x7F;
				if ((b & 0x80) == 0)
				{
					return num;
				}
			}
			throw new FormatException("Invalid Var Int");
		}

		public static void WriteVarInt(BinaryWriter writer, int value)
		{
			if (value < 0)
			{
				throw new ArgumentOutOfRangeException("value", value, "Cannot write a negative Var Int");
			}
			if (value > 268435455)
			{
				throw new ArgumentOutOfRangeException("value", value, "Maximum allowed Var Int is 0x0FFFFFFF");
			}
			int num = 0;
			byte[] array = new byte[4];
			do
			{
				array[num++] = (byte)((uint)value & 0x7Fu);
				value >>= 7;
			}
			while (value > 0);
			while (num > 0)
			{
				num--;
				if (num > 0)
				{
					writer.Write((byte)(array[num] | 0x80u));
				}
				else
				{
					writer.Write(array[num]);
				}
			}
		}

		public virtual void Export(ref long absoluteTime, BinaryWriter writer)
		{
			if (this.absoluteTime < absoluteTime)
			{
				throw new FormatException("Can't export unsorted MIDI events");
			}
			WriteVarInt(writer, (int)(this.absoluteTime - absoluteTime));
			absoluteTime = this.absoluteTime;
			int num = (int)commandCode;
			if (commandCode != MidiCommandCode.MetaEvent)
			{
				num += channel - 1;
			}
			writer.Write((byte)num);
		}
	}
	public class MidiEventCollection : IEnumerable<IList<MidiEvent>>, IEnumerable
	{
		private int midiFileType;

		private readonly List<IList<MidiEvent>> trackEvents;

		public int Tracks => trackEvents.Count;

		public long StartAbsoluteTime { get; set; }

		public int DeltaTicksPerQuarterNote { get; }

		public IList<MidiEvent> this[int trackNumber] => trackEvents[trackNumber];

		public int MidiFileType
		{
			get
			{
				return midiFileType;
			}
			set
			{
				if (midiFileType != value)
				{
					midiFileType = value;
					if (value == 0)
					{
						FlattenToOneTrack();
					}
					else
					{
						ExplodeToManyTracks();
					}
				}
			}
		}

		public MidiEventCollection(int midiFileType, int deltaTicksPerQuarterNote)
		{
			this.midiFileType = midiFileType;
			DeltaTicksPerQuarterNote = deltaTicksPerQuarterNote;
			StartAbsoluteTime = 0L;
			trackEvents = new List<IList<MidiEvent>>();
		}

		public IList<MidiEvent> GetTrackEvents(int trackNumber)
		{
			return trackEvents[trackNumber];
		}

		public IList<MidiEvent> AddTrack()
		{
			return AddTrack(null);
		}

		public IList<MidiEvent> AddTrack(IList<MidiEvent> initialEvents)
		{
			List<MidiEvent> list = new List<MidiEvent>();
			if (initialEvents != null)
			{
				list.AddRange(initialEvents);
			}
			trackEvents.Add(list);
			return list;
		}

		public void RemoveTrack(int track)
		{
			trackEvents.RemoveAt(track);
		}

		public void Clear()
		{
			trackEvents.Clear();
		}

		public void AddEvent(MidiEvent midiEvent, int originalTrack)
		{
			if (midiFileType == 0)
			{
				EnsureTracks(1);
				trackEvents[0].Add(midiEvent);
			}
			else if (originalTrack == 0)
			{
				switch (midiEvent.CommandCode)
				{
				case MidiCommandCode.NoteOff:
				case MidiCommandCode.NoteOn:
				case MidiCommandCode.KeyAfterTouch:
				case MidiCommandCode.ControlChange:
				case MidiCommandCode.PatchChange:
				case MidiCommandCode.ChannelAfterTouch:
				case MidiCommandCode.PitchWheelChange:
					EnsureTracks(midiEvent.Channel + 1);
					trackEvents[midiEvent.Channel].Add(midiEvent);
					break;
				default:
					EnsureTracks(1);
					trackEvents[0].Add(midiEvent);
					break;
				}
			}
			else
			{
				EnsureTracks(originalTrack + 1);
				trackEvents[originalTrack].Add(midiEvent);
			}
		}

		private void EnsureTracks(int count)
		{
			for (int i = trackEvents.Count; i < count; i++)
			{
				trackEvents.Add(new List<MidiEvent>());
			}
		}

		private void ExplodeToManyTracks()
		{
			IList<MidiEvent> list = trackEvents[0];
			Clear();
			foreach (MidiEvent item in list)
			{
				AddEvent(item, 0);
			}
			PrepareForExport();
		}

		private void FlattenToOneTrack()
		{
			bool flag = false;
			for (int i = 1; i < trackEvents.Count; i++)
			{
				foreach (MidiEvent item in trackEvents[i])
				{
					if (!MidiEvent.IsEndTrack(item))
					{
						trackEvents[0].Add(item);
						flag = true;
					}
				}
			}
			for (int num = trackEvents.Count - 1; num > 0; num--)
			{
				RemoveTrack(num);
			}
			if (flag)
			{
				PrepareForExport();
			}
		}

		public void PrepareForExport()
		{
			MidiEventComparer comparer = new MidiEventComparer();
			foreach (IList<MidiEvent> trackEvent in trackEvents)
			{
				MergeSort.Sort(trackEvent, comparer);
				int num = 0;
				while (num < trackEvent.Count - 1)
				{
					if (MidiEvent.IsEndTrack(trackEvent[num]))
					{
						trackEvent.RemoveAt(num);
					}
					else
					{
						num++;
					}
				}
			}
			int num2 = 0;
			while (num2 < trackEvents.Count)
			{
				IList<MidiEvent> list = trackEvents[num2];
				if (list.Count == 0)
				{
					RemoveTrack(num2);
					continue;
				}
				if (list.Count == 1 && MidiEvent.IsEndTrack(list[0]))
				{
					RemoveTrack(num2);
					continue;
				}
				if (!MidiEvent.IsEndTrack(list[list.Count - 1]))
				{
					list.Add(new MetaEvent(MetaEventType.EndTrack, 0, list[list.Count - 1].AbsoluteTime));
				}
				num2++;
			}
		}

		public IEnumerator<IList<MidiEvent>> GetEnumerator()
		{
			return trackEvents.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return trackEvents.GetEnumerator();
		}
	}
	public class MidiEventComparer : IComparer<MidiEvent>
	{
		public int Compare(MidiEvent x, MidiEvent y)
		{
			long num = x.AbsoluteTime;
			long num2 = y.AbsoluteTime;
			if (num == num2)
			{
				MetaEvent metaEvent = x as MetaEvent;
				MetaEvent metaEvent2 = y as MetaEvent;
				if (metaEvent != null)
				{
					num = ((metaEvent.MetaEventType != MetaEventType.EndTrack) ? long.MinValue : long.MaxValue);
				}
				if (metaEvent2 != null)
				{
					num2 = ((metaEvent2.MetaEventType != MetaEventType.EndTrack) ? long.MinValue : long.MaxValue);
				}
			}
			return num.CompareTo(num2);
		}
	}
	public class MidiFile
	{
		private readonly MidiEventCollection events;

		private readonly ushort fileFormat;

		private readonly ushort deltaTicksPerQuarterNote;

		private readonly bool strictChecking;

		public int FileFormat => fileFormat;

		public MidiEventCollection Events => events;

		public int Tracks => events.Tracks;

		public int DeltaTicksPerQuarterNote => deltaTicksPerQuarterNote;

		public MidiFile(string filename)
			: this(filename, strictChecking: true)
		{
		}

		public MidiFile(string filename, bool strictChecking)
			: this(File.OpenRead(filename), strictChecking, ownInputStream: true)
		{
		}

		public MidiFile(Stream inputStream, bool strictChecking)
			: this(inputStream, strictChecking, ownInputStream: false)
		{
		}

		private MidiFile(Stream inputStream, bool strictChecking, bool ownInputStream)
		{
			this.strictChecking = strictChecking;
			BinaryReader binaryReader = new BinaryReader(inputStream);
			try
			{
				if (Encoding.UTF8.GetString(binaryReader.ReadBytes(4)) != "MThd")
				{
					throw new FormatException("Not a MIDI file - header chunk missing");
				}
				uint num = SwapUInt32(binaryReader.ReadUInt32());
				if (num != 6)
				{
					throw new FormatException("Unexpected header chunk length");
				}
				fileFormat = SwapUInt16(binaryReader.ReadUInt16());
				int num2 = SwapUInt16(binaryReader.ReadUInt16());
				deltaTicksPerQuarterNote = SwapUInt16(binaryReader.ReadUInt16());
				events = new MidiEventCollection((fileFormat != 0) ? 1 : 0, deltaTicksPerQuarterNote);
				for (int i = 0; i < num2; i++)
				{
					events.AddTrack();
				}
				long num3 = 0L;
				for (int j = 0; j < num2; j++)
				{
					if (fileFormat == 1)
					{
						num3 = 0L;
					}
					if (Encoding.UTF8.GetString(binaryReader.ReadBytes(4)) != "MTrk")
					{
						throw new FormatException("Invalid chunk header");
					}
					num = SwapUInt32(binaryReader.ReadUInt32());
					long position = binaryReader.BaseStream.Position;
					MidiEvent midiEvent = null;
					List<NoteOnEvent> list = new List<NoteOnEvent>();
					while (binaryReader.BaseStream.Position < position + num)
					{
						try
						{
							midiEvent = MidiEvent.ReadNextEvent(binaryReader, midiEvent);
						}
						catch (InvalidDataException)
						{
							if (strictChecking)
							{
								throw;
							}
							continue;
						}
						catch (FormatException)
						{
							if (strictChecking)
							{
								throw;
							}
							continue;
						}
						num3 = (midiEvent.AbsoluteTime = num3 + midiEvent.DeltaTime);
						events[j].Add(midiEvent);
						if (midiEvent.CommandCode == MidiCommandCode.NoteOn)
						{
							NoteEvent noteEvent = (NoteEvent)midiEvent;
							if (noteEvent.Velocity > 0)
							{
								list.Add((NoteOnEvent)noteEvent);
							}
							else
							{
								FindNoteOn(noteEvent, list);
							}
						}
						else if (midiEvent.CommandCode == MidiCommandCode.NoteOff)
						{
							FindNoteOn((NoteEvent)midiEvent, list);
						}
						else if (midiEvent.CommandCode == MidiCommandCode.MetaEvent && ((MetaEvent)midiEvent).MetaEventType == MetaEventType.EndTrack && strictChecking && binaryReader.BaseStream.Position < position + num)
						{
							throw new FormatException($"End Track event was not the last MIDI event on track {j}");
						}
					}
					if (list.Count > 0 && strictChecking)
					{
						throw new FormatException($"Note ons without note offs {list.Count} (file format {fileFormat})");
					}
					if (binaryReader.BaseStream.Position != position + num)
					{
						throw new FormatException($"Read too far {num}+{position}!={binaryReader.BaseStream.Position}");
					}
				}
			}
			finally
			{
				if (ownInputStream)
				{
					binaryReader.Dispose();
				}
			}
		}

		private void FindNoteOn(NoteEvent offEvent, List<NoteOnEvent> outstandingNoteOns)
		{
			bool flag = false;
			foreach (NoteOnEvent outstandingNoteOn in outstandingNoteOns)
			{
				if (outstandingNoteOn.Channel == offEvent.Channel && outstandingNoteOn.NoteNumber == offEvent.NoteNumber)
				{
					outstandingNoteOn.OffEvent = offEvent;
					outstandingNoteOns.Remove(outstandingNoteOn);
					flag = true;
					break;
				}
			}
			if (!flag && strictChecking)
			{
				throw new FormatException($"Got an off without an on {offEvent}");
			}
		}

		private static uint SwapUInt32(uint i)
		{
			return ((i & 0xFF000000u) >> 24) | ((i & 0xFF0000) >> 8) | ((i & 0xFF00) << 8) | ((i & 0xFF) << 24);
		}

		private static ushort SwapUInt16(ushort i)
		{
			return (ushort)(((i & 0xFF00) >> 8) | ((i & 0xFF) << 8));
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendFormat("Format {0}, Tracks {1}, Delta Ticks Per Quarter Note {2}\r\n", fileFormat, Tracks, deltaTicksPerQuarterNote);
			for (int i = 0; i < Tracks; i++)
			{
				foreach (MidiEvent item in events[i])
				{
					stringBuilder.AppendFormat("{0}\r\n", item);
				}
			}
			return stringBuilder.ToString();
		}

		public static void Export(string filename, MidiEventCollection events)
		{
			if (events.MidiFileType == 0 && events.Tracks > 1)
			{
				throw new ArgumentException("Can't export more than one track to a type 0 file");
			}
			using BinaryWriter binaryWriter = new BinaryWriter(File.Create(filename));
			binaryWriter.Write(Encoding.UTF8.GetBytes("MThd"));
			binaryWriter.Write(SwapUInt32(6u));
			binaryWriter.Write(SwapUInt16((ushort)events.MidiFileType));
			binaryWriter.Write(SwapUInt16((ushort)events.Tracks));
			binaryWriter.Write(SwapUInt16((ushort)events.DeltaTicksPerQuarterNote));
			for (int i = 0; i < events.Tracks; i++)
			{
				IList<MidiEvent> list = events[i];
				binaryWriter.Write(Encoding.UTF8.GetBytes("MTrk"));
				long position = binaryWriter.BaseStream.Position;
				binaryWriter.Write(SwapUInt32(0u));
				long absoluteTime = events.StartAbsoluteTime;
				MergeSort.Sort(list, new MidiEventComparer());
				_ = list.Count;
				_ = 0;
				foreach (MidiEvent item in list)
				{
					item.Export(ref absoluteTime, binaryWriter);
				}
				uint num = (uint)((int)(binaryWriter.BaseStream.Position - position) - 4);
				binaryWriter.BaseStream.Position = position;
				binaryWriter.Write(SwapUInt32(num));
				binaryWriter.BaseStream.Position += num;
			}
		}
	}
	public class MidiIn : IDisposable
	{
		private IntPtr hMidiIn = IntPtr.Zero;

		private bool disposed;

		private MidiInterop.MidiInCallback callback;

		private IntPtr[] SysexBufferHeaders = new IntPtr[0];

		public static int NumberOfDevices => MidiInterop.midiInGetNumDevs();

		public event EventHandler<MidiInMessageEventArgs> MessageReceived;

		public event EventHandler<MidiInMessageEventArgs> ErrorReceived;

		public event EventHandler<MidiInSysexMessageEventArgs> SysexMessageReceived;

		public MidiIn(int deviceNo)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			callback = Callback;
			MmException.Try(MidiInterop.midiInOpen(out hMidiIn, (IntPtr)deviceNo, callback, IntPtr.Zero, 196608), "midiInOpen");
		}

		public void Close()
		{
			Dispose();
		}

		public void Dispose()
		{
			GC.KeepAlive(callback);
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		public void Start()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			MmException.Try(MidiInterop.midiInStart(hMidiIn), "midiInStart");
		}

		public void Stop()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			MmException.Try(MidiInterop.midiInStop(hMidiIn), "midiInStop");
		}

		public void Reset()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			MmException.Try(MidiInterop.midiInReset(hMidiIn), "midiInReset");
		}

		public void CreateSysexBuffers(int bufferSize, int numberOfBuffers)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			SysexBufferHeaders = new IntPtr[numberOfBuffers];
			int cb = Marshal.SizeOf(typeof(MidiInterop.MIDIHDR));
			for (int i = 0; i < numberOfBuffers; i++)
			{
				MidiInterop.MIDIHDR structure = default(MidiInterop.MIDIHDR);
				structure.dwBufferLength = bufferSize;
				structure.dwBytesRecorded = 0;
				structure.lpData = Marshal.AllocHGlobal(bufferSize);
				structure.dwFlags = 0;
				IntPtr intPtr = Marshal.AllocHGlobal(cb);
				Marshal.StructureToPtr(structure, intPtr, fDeleteOld: false);
				MmException.Try(MidiInterop.midiInPrepareHeader(hMidiIn, intPtr, Marshal.SizeOf(typeof(MidiInterop.MIDIHDR))), "midiInPrepareHeader");
				MmException.Try(MidiInterop.midiInAddBuffer(hMidiIn, intPtr, Marshal.SizeOf(typeof(MidiInterop.MIDIHDR))), "midiInAddBuffer");
				SysexBufferHeaders[i] = intPtr;
			}
		}

		private void Callback(IntPtr midiInHandle, MidiInterop.MidiInMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2)
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			switch (message)
			{
			case MidiInterop.MidiInMessage.Data:
				if (this.MessageReceived != null)
				{
					this.MessageReceived(this, new MidiInMessageEventArgs(messageParameter1.ToInt32(), messageParameter2.ToInt32()));
				}
				break;
			case MidiInterop.MidiInMessage.Error:
				if (this.ErrorReceived != null)
				{
					this.ErrorReceived(this, new MidiInMessageEventArgs(messageParameter1.ToInt32(), messageParameter2.ToInt32()));
				}
				break;
			case MidiInterop.MidiInMessage.LongData:
				if (this.SysexMessageReceived != null)
				{
					MidiInterop.MIDIHDR mIDIHDR = (MidiInterop.MIDIHDR)Marshal.PtrToStructure(messageParameter1, typeof(MidiInterop.MIDIHDR));
					byte[] array = new byte[mIDIHDR.dwBytesRecorded];
					Marshal.Copy(mIDIHDR.lpData, array, 0, mIDIHDR.dwBytesRecorded);
					this.SysexMessageReceived(this, new MidiInSysexMessageEventArgs(array, messageParameter2.ToInt32()));
					MidiInterop.midiInAddBuffer(hMidiIn, messageParameter1, Marshal.SizeOf(typeof(MidiInterop.MIDIHDR)));
				}
				break;
			case MidiInterop.MidiInMessage.Open:
			case MidiInterop.MidiInMessage.Close:
			case MidiInterop.MidiInMessage.LongError:
			case (MidiInterop.MidiInMessage)967:
			case (MidiInterop.MidiInMessage)968:
			case (MidiInterop.MidiInMessage)969:
			case (MidiInterop.MidiInMessage)970:
			case (MidiInterop.MidiInMessage)971:
			case MidiInterop.MidiInMessage.MoreData:
				break;
			}
		}

		public static MidiInCapabilities DeviceInfo(int midiInDeviceNumber)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			MidiInCapabilities capabilities = default(MidiInCapabilities);
			int size = Marshal.SizeOf(capabilities);
			MmException.Try(MidiInterop.midiInGetDevCaps((IntPtr)midiInDeviceNumber, out capabilities, size), "midiInGetDevCaps");
			return capabilities;
		}

		protected virtual void Dispose(bool disposing)
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			if (!disposed)
			{
				if (SysexBufferHeaders.Length != 0)
				{
					MmException.Try(MidiInterop.midiInReset(hMidiIn), "midiInReset");
					IntPtr[] sysexBufferHeaders = SysexBufferHeaders;
					foreach (IntPtr intPtr in sysexBufferHeaders)
					{
						MidiInterop.MIDIHDR obj = (MidiInterop.MIDIHDR)Marshal.PtrToStructure(intPtr, typeof(MidiInterop.MIDIHDR));
						MmException.Try(MidiInterop.midiInUnprepareHeader(hMidiIn, intPtr, Marshal.SizeOf(typeof(MidiInterop.MIDIHDR))), "midiInPrepareHeader");
						Marshal.FreeHGlobal(obj.lpData);
						Marshal.FreeHGlobal(intPtr);
					}
					SysexBufferHeaders = new IntPtr[0];
				}
				MidiInterop.midiInClose(hMidiIn);
			}
			disposed = true;
		}

		~MidiIn()
		{
			Dispose(disposing: false);
		}
	}
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
	public struct MidiInCapabilities
	{
		private ushort manufacturerId;

		private ushort productId;

		private uint driverVersion;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		private string productName;

		private int support;

		private const int MaxProductNameLength = 32;

		public Manufacturers Manufacturer => (Manufacturers)manufacturerId;

		public int ProductId => productId;

		public string ProductName => productName;
	}
	public class MidiInMessageEventArgs : EventArgs
	{
		public int RawMessage { get; private set; }

		public MidiEvent MidiEvent { get; private set; }

		public int Timestamp { get; private set; }

		public MidiInMessageEventArgs(int message, int timestamp)
		{
			RawMessage = message;
			Timestamp = timestamp;
			try
			{
				MidiEvent = MidiEvent.FromRawMessage(message);
			}
			catch (Exception)
			{
			}
		}
	}
	public class MidiInSysexMessageEventArgs : EventArgs
	{
		public byte[] SysexBytes { get; private set; }

		public int Timestamp { get; private set; }

		public MidiInSysexMessageEventArgs(byte[] sysexBytes, int timestamp)
		{
			SysexBytes = sysexBytes;
			Timestamp = timestamp;
		}
	}
	internal class MidiInterop
	{
		public enum MidiInMessage
		{
			Open = 961,
			Close = 962,
			Data = 963,
			LongData = 964,
			Error = 965,
			LongError = 966,
			MoreData = 972
		}

		public enum MidiOutMessage
		{
			Open = 967,
			Close,
			Done
		}

		public delegate void MidiInCallback(IntPtr midiInHandle, MidiInMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2);

		public delegate void MidiOutCallback(IntPtr midiInHandle, MidiOutMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2);

		public struct MMTIME
		{
			public int wType;

			public int u;
		}

		public struct MIDIEVENT
		{
			public int dwDeltaTime;

			public int dwStreamID;

			public int dwEvent;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
			public int dwParms;
		}

		public struct MIDIHDR
		{
			public IntPtr lpData;

			public int dwBufferLength;

			public int dwBytesRecorded;

			public IntPtr dwUser;

			public int dwFlags;

			public IntPtr lpNext;

			public IntPtr reserved;

			public int dwOffset;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
			public IntPtr[] dwReserved;
		}

		public struct MIDIPROPTEMPO
		{
			public int cbStruct;

			public int dwTempo;
		}

		public const int CALLBACK_FUNCTION = 196608;

		public const int CALLBACK_NULL = 0;

		[DllImport("winmm.dll")]
		public static extern MmResult midiConnect(IntPtr hMidiIn, IntPtr hMidiOut, IntPtr pReserved);

		[DllImport("winmm.dll")]
		public static extern MmResult midiDisconnect(IntPtr hMidiIn, IntPtr hMidiOut, IntPtr pReserved);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInAddBuffer(IntPtr hMidiIn, IntPtr lpMidiInHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInClose(IntPtr hMidiIn);

		[DllImport("winmm.dll", CharSet = CharSet.Auto)]
		public static extern MmResult midiInGetDevCaps(IntPtr deviceId, out MidiInCapabilities capabilities, int size);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInGetErrorText(int err, string lpText, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInGetID(IntPtr hMidiIn, out int lpuDeviceId);

		[DllImport("winmm.dll")]
		public static extern int midiInGetNumDevs();

		[DllImport("winmm.dll")]
		public static extern MmResult midiInMessage(IntPtr hMidiIn, int msg, IntPtr dw1, IntPtr dw2);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInOpen(out IntPtr hMidiIn, IntPtr uDeviceID, MidiInCallback callback, IntPtr dwInstance, int dwFlags);

		[DllImport("winmm.dll", EntryPoint = "midiInOpen")]
		public static extern MmResult midiInOpenWindow(out IntPtr hMidiIn, IntPtr uDeviceID, IntPtr callbackWindowHandle, IntPtr dwInstance, int dwFlags);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInPrepareHeader(IntPtr hMidiIn, IntPtr lpMidiInHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInReset(IntPtr hMidiIn);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInStart(IntPtr hMidiIn);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInStop(IntPtr hMidiIn);

		[DllImport("winmm.dll")]
		public static extern MmResult midiInUnprepareHeader(IntPtr hMidiIn, IntPtr lpMidiInHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutCacheDrumPatches(IntPtr hMidiOut, int uPatch, IntPtr lpKeyArray, int uFlags);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutCachePatches(IntPtr hMidiOut, int uBank, IntPtr lpPatchArray, int uFlags);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutClose(IntPtr hMidiOut);

		[DllImport("winmm.dll", CharSet = CharSet.Auto)]
		public static extern MmResult midiOutGetDevCaps(IntPtr deviceNumber, out MidiOutCapabilities caps, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutGetErrorText(IntPtr err, string lpText, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutGetID(IntPtr hMidiOut, out int lpuDeviceID);

		[DllImport("winmm.dll")]
		public static extern int midiOutGetNumDevs();

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutGetVolume(IntPtr uDeviceID, ref int lpdwVolume);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutLongMsg(IntPtr hMidiOut, ref MIDIHDR lpMidiOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutMessage(IntPtr hMidiOut, int msg, IntPtr dw1, IntPtr dw2);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutOpen(out IntPtr lphMidiOut, IntPtr uDeviceID, MidiOutCallback dwCallback, IntPtr dwInstance, int dwFlags);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutPrepareHeader(IntPtr hMidiOut, ref MIDIHDR lpMidiOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutReset(IntPtr hMidiOut);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutSetVolume(IntPtr hMidiOut, int dwVolume);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutShortMsg(IntPtr hMidiOut, int dwMsg);

		[DllImport("winmm.dll")]
		public static extern MmResult midiOutUnprepareHeader(IntPtr hMidiOut, ref MIDIHDR lpMidiOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult midiStreamClose(IntPtr hMidiStream);

		[DllImport("winmm.dll")]
		public static extern MmResult midiStreamOpen(out IntPtr hMidiStream, IntPtr puDeviceID, int cMidi, IntPtr dwCallback, IntPtr dwInstance, int fdwOpen);

		[DllImport("winmm.dll")]
		public static extern MmResult midiStreamOut(IntPtr hMidiStream, ref MIDIHDR pmh, int cbmh);

		[DllImport("winmm.dll")]
		public static extern MmResult midiStreamPause(IntPtr hMidiStream);

		[DllImport("winmm.dll")]
		public static extern MmResult midiStreamPosition(IntPtr hMidiStream, ref MMTIME lpmmt, int cbmmt);

		[DllImport("winmm.dll")]
		public static extern MmResult midiStreamProperty(IntPtr hMidiStream, IntPtr lppropdata, int dwProperty);

		[DllImport("winmm.dll")]
		public static extern MmResult midiStreamRestart(IntPtr hMidiStream);

		[DllImport("winmm.dll")]
		public static extern MmResult midiStreamStop(IntPtr hMidiStream);
	}
	public class MidiMessage
	{
		private int rawData;

		public int RawData => rawData;

		public MidiMessage(int status, int data1, int data2)
		{
			rawData = status + (data1 << 8) + (data2 << 16);
		}

		public MidiMessage(int rawData)
		{
			this.rawData = rawData;
		}

		public static MidiMessage StartNote(int note, int volume, int channel)
		{
			ValidateNoteParameters(note, volume, channel);
			return new MidiMessage(144 + channel - 1, note, volume);
		}

		private static void ValidateNoteParameters(int note, int volume, int channel)
		{
			ValidateChannel(channel);
			if (note < 0 || note > 127)
			{
				throw new ArgumentOutOfRangeException("note", "Note number must be in the range 0-127");
			}
			if (volume < 0 || volume > 127)
			{
				throw new ArgumentOutOfRangeException("volume", "Velocity must be in the range 0-127");
			}
		}

		private static void ValidateChannel(int channel)
		{
			if (channel < 1 || channel > 16)
			{
				throw new ArgumentOutOfRangeException("channel", channel, $"Channel must be 1-16 (Got {channel})");
			}
		}

		public static MidiMessage StopNote(int note, int volume, int channel)
		{
			ValidateNoteParameters(note, volume, channel);
			return new MidiMessage(128 + channel - 1, note, volume);
		}

		public static MidiMessage ChangePatch(int patch, int channel)
		{
			ValidateChannel(channel);
			return new MidiMessage(192 + channel - 1, patch, 0);
		}

		public static MidiMessage ChangeControl(int controller, int value, int channel)
		{
			ValidateChannel(channel);
			return new MidiMessage(176 + channel - 1, controller, value);
		}
	}
	public class MidiOut : IDisposable
	{
		private IntPtr hMidiOut = IntPtr.Zero;

		private bool disposed;

		private MidiInterop.MidiOutCallback callback;

		public static int NumberOfDevices => MidiInterop.midiOutGetNumDevs();

		public int Volume
		{
			get
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				int lpdwVolume = 0;
				MmException.Try(MidiInterop.midiOutGetVolume(hMidiOut, ref lpdwVolume), "midiOutGetVolume");
				return lpdwVolume;
			}
			set
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				MmException.Try(MidiInterop.midiOutSetVolume(hMidiOut, value), "midiOutSetVolume");
			}
		}

		public static MidiOutCapabilities DeviceInfo(int midiOutDeviceNumber)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			MidiOutCapabilities caps = default(MidiOutCapabilities);
			int uSize = Marshal.SizeOf(caps);
			MmException.Try(MidiInterop.midiOutGetDevCaps((IntPtr)midiOutDeviceNumber, out caps, uSize), "midiOutGetDevCaps");
			return caps;
		}

		public MidiOut(int deviceNo)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			callback = Callback;
			MmException.Try(MidiInterop.midiOutOpen(out hMidiOut, (IntPtr)deviceNo, callback, IntPtr.Zero, 196608), "midiOutOpen");
		}

		public void Close()
		{
			Dispose();
		}

		public void Dispose()
		{
			GC.KeepAlive(callback);
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		public void Reset()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			MmException.Try(MidiInterop.midiOutReset(hMidiOut), "midiOutReset");
		}

		public void SendDriverMessage(int message, int param1, int param2)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			MmException.Try(MidiInterop.midiOutMessage(hMidiOut, message, (IntPtr)param1, (IntPtr)param2), "midiOutMessage");
		}

		public void Send(int message)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			MmException.Try(MidiInterop.midiOutShortMsg(hMidiOut, message), "midiOutShortMsg");
		}

		protected virtual void Dispose(bool disposing)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (!disposed)
			{
				MidiInterop.midiOutClose(hMidiOut);
			}
			disposed = true;
		}

		private void Callback(IntPtr midiInHandle, MidiInterop.MidiOutMessage message, IntPtr userData, IntPtr messageParameter1, IntPtr messageParameter2)
		{
		}

		public void SendBuffer(byte[] byteBuffer)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			MidiInterop.MIDIHDR lpMidiOutHdr = default(MidiInterop.MIDIHDR);
			lpMidiOutHdr.lpData = Marshal.AllocHGlobal(byteBuffer.Length);
			Marshal.Copy(byteBuffer, 0, lpMidiOutHdr.lpData, byteBuffer.Length);
			lpMidiOutHdr.dwBufferLength = byteBuffer.Length;
			lpMidiOutHdr.dwBytesRecorded = byteBuffer.Length;
			int uSize = Marshal.SizeOf(lpMidiOutHdr);
			MidiInterop.midiOutPrepareHeader(hMidiOut, ref lpMidiOutHdr, uSize);
			if ((int)MidiInterop.midiOutLongMsg(hMidiOut, ref lpMidiOutHdr, uSize) != 0)
			{
				MidiInterop.midiOutUnprepareHeader(hMidiOut, ref lpMidiOutHdr, uSize);
			}
			Marshal.FreeHGlobal(lpMidiOutHdr.lpData);
		}

		~MidiOut()
		{
			Dispose(disposing: false);
		}
	}
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
	public struct MidiOutCapabilities
	{
		[Flags]
		private enum MidiOutCapabilityFlags
		{
			Volume = 1,
			LeftRightVolume = 2,
			PatchCaching = 4,
			Stream = 8
		}

		private short manufacturerId;

		private short productId;

		private int driverVersion;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		private string productName;

		private short wTechnology;

		private short wVoices;

		private short wNotes;

		private ushort wChannelMask;

		private MidiOutCapabilityFlags dwSupport;

		private const int MaxProductNameLength = 32;

		public Manufacturers Manufacturer => (Manufacturers)manufacturerId;

		public short ProductId => productId;

		public string ProductName => productName;

		public int Voices => wVoices;

		public int Notes => wNotes;

		public bool SupportsAllChannels => wChannelMask == ushort.MaxValue;

		public bool SupportsPatchCaching => (dwSupport & MidiOutCapabilityFlags.PatchCaching) != 0;

		public bool SupportsSeparateLeftAndRightVolume => (dwSupport & MidiOutCapabilityFlags.LeftRightVolume) != 0;

		public bool SupportsMidiStreamOut => (dwSupport & MidiOutCapabilityFlags.Stream) != 0;

		public bool SupportsVolumeControl => (dwSupport & MidiOutCapabilityFlags.Volume) != 0;

		public MidiOutTechnology Technology => (MidiOutTechnology)wTechnology;

		public bool SupportsChannel(int channel)
		{
			return (wChannelMask & (1 << channel - 1)) > 0;
		}
	}
	public enum MidiOutTechnology
	{
		MidiPort = 1,
		Synth,
		SquareWaveSynth,
		FMSynth,
		MidiMapper,
		WaveTableSynth,
		SoftwareSynth
	}
	public class NoteEvent : MidiEvent
	{
		private int noteNumber;

		private int velocity;

		private static readonly string[] NoteNames = new string[12]
		{
			"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A",
			"A#", "B"
		};

		public virtual int NoteNumber
		{
			get
			{
				return noteNumber;
			}
			set
			{
				if (value < 0 || value > 127)
				{
					throw new ArgumentOutOfRangeException("value", "Note number must be in the range 0-127");
				}
				noteNumber = value;
			}
		}

		public int Velocity
		{
			get
			{
				return velocity;
			}
			set
			{
				if (value < 0 || value > 127)
				{
					throw new ArgumentOutOfRangeException("value", "Velocity must be in the range 0-127");
				}
				velocity = value;
			}
		}

		public string NoteName
		{
			get
			{
				if (Channel == 16 || Channel == 10)
				{
					return noteNumber switch
					{
						35 => "Acoustic Bass Drum", 
						36 => "Bass Drum 1", 
						37 => "Side Stick", 
						38 => "Acoustic Snare", 
						39 => "Hand Clap", 
						40 => "Electric Snare", 
						41 => "Low Floor Tom", 
						42 => "Closed Hi-Hat", 
						43 => "High Floor Tom", 
						44 => "Pedal Hi-Hat", 
						45 => "Low Tom", 
						46 => "Open Hi-Hat", 
						47 => "Low-Mid Tom", 
						48 => "Hi-Mid Tom", 
						49 => "Crash Cymbal 1", 
						50 => "High Tom", 
						51 => "Ride Cymbal 1", 
						52 => "Chinese Cymbal", 
						53 => "Ride Bell", 
						54 => "Tambourine", 
						55 => "Splash Cymbal", 
						56 => "Cowbell", 
						57 => "Crash Cymbal 2", 
						58 => "Vibraslap", 
						59 => "Ride Cymbal 2", 
						60 => "Hi Bongo", 
						61 => "Low Bongo", 
						62 => "Mute Hi Conga", 
						63 => "Open Hi Conga", 
						64 => "Low Conga", 
						65 => "High Timbale", 
						66 => "Low Timbale", 
						67 => "High Agogo", 
						68 => "Low Agogo", 
						69 => "Cabasa", 
						70 => "Maracas", 
						71 => "Short Whistle", 
						72 => "Long Whistle", 
						73 => "Short Guiro", 
						74 => "Long Guiro", 
						75 => "Claves", 
						76 => "Hi Wood Block", 
						77 => "Low Wood Block", 
						78 => "Mute Cuica", 
						79 => "Open Cuica", 
						80 => "Mute Triangle", 
						81 => "Open Triangle", 
						_ => $"Drum {noteNumber}", 
					};
				}
				int num = noteNumber / 12;
				return $"{NoteNames[noteNumber % 12]}{num}";
			}
		}

		public NoteEvent(BinaryReader br)
		{
			NoteNumber = br.ReadByte();
			velocity = br.ReadByte();
			if (velocity > 127)
			{
				velocity = 127;
			}
		}

		public NoteEvent(long absoluteTime, int channel, MidiCommandCode commandCode, int noteNumber, int velocity)
			: base(absoluteTime, channel, commandCode)
		{
			NoteNumber = noteNumber;
			Velocity = velocity;
		}

		public override int GetAsShortMessage()
		{
			return base.GetAsShortMessage() + (noteNumber << 8) + (velocity << 16);
		}

		public override string ToString()
		{
			return $"{base.ToString()} {NoteName} Vel:{Velocity}";
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write((byte)noteNumber);
			writer.Write((byte)velocity);
		}
	}
	public class NoteOnEvent : NoteEvent
	{
		private NoteEvent offEvent;

		public NoteEvent OffEvent
		{
			get
			{
				return offEvent;
			}
			set
			{
				if (!MidiEvent.IsNoteOff(value))
				{
					throw new ArgumentException("OffEvent must be a valid MIDI note off event");
				}
				if (value.NoteNumber != NoteNumber)
				{
					throw new ArgumentException("Note Off Event must be for the same note number");
				}
				if (value.Channel != Channel)
				{
					throw new ArgumentException("Note Off Event must be for the same channel");
				}
				offEvent = value;
			}
		}

		public override int NoteNumber
		{
			get
			{
				return base.NoteNumber;
			}
			set
			{
				base.NoteNumber = value;
				if (OffEvent != null)
				{
					OffEvent.NoteNumber = NoteNumber;
				}
			}
		}

		public override int Channel
		{
			get
			{
				return base.Channel;
			}
			set
			{
				base.Channel = value;
				if (OffEvent != null)
				{
					OffEvent.Channel = Channel;
				}
			}
		}

		public int NoteLength
		{
			get
			{
				return (int)(offEvent.AbsoluteTime - base.AbsoluteTime);
			}
			set
			{
				if (value < 0)
				{
					throw new ArgumentException("NoteLength must be 0 or greater");
				}
				offEvent.AbsoluteTime = base.AbsoluteTime + value;
			}
		}

		public NoteOnEvent(BinaryReader br)
			: base(br)
		{
		}

		public NoteOnEvent(long absoluteTime, int channel, int noteNumber, int velocity, int duration)
			: base(absoluteTime, channel, MidiCommandCode.NoteOn, noteNumber, velocity)
		{
			OffEvent = new NoteEvent(absoluteTime, channel, MidiCommandCode.NoteOff, noteNumber, 0);
			NoteLength = duration;
		}

		public override MidiEvent Clone()
		{
			return new NoteOnEvent(base.AbsoluteTime, Channel, NoteNumber, base.Velocity, NoteLength);
		}

		public override string ToString()
		{
			if (base.Velocity == 0 && OffEvent == null)
			{
				return $"{base.ToString()} (Note Off)";
			}
			return string.Format("{0} Len: {1}", base.ToString(), (OffEvent == null) ? "?" : NoteLength.ToString());
		}
	}
	public class PatchChangeEvent : MidiEvent
	{
		private byte patch;

		private static readonly string[] patchNames = new string[128]
		{
			"Acoustic Grand", "Bright Acoustic", "Electric Grand", "Honky-Tonk", "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clav", "Celesta", "Glockenspiel",
			"Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ", "Percussive Organ", "Rock Organ", "Church Organ",
			"Reed Organ", "Accoridan", "Harmonica", "Tango Accordian", "Acoustic Guitar(nylon)", "Acoustic Guitar(steel)", "Electric Guitar(jazz)", "Electric Guitar(clean)", "Electric Guitar(muted)", "Overdriven Guitar",
			"Distortion Guitar", "Guitar Harmonics", "Acoustic Bass", "Electric Bass(finger)", "Electric Bass(pick)", "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2",
			"Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Strings", "Timpani", "String Ensemble 1", "String Ensemble 2",
			"SynthStrings 1", "SynthStrings 2", "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba", "Muted Trumpet",
			"French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn",
			"Bassoon", "Clarinet", "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Skakuhachi", "Whistle", "Ocarina",
			"Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)", "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)", "Pad 2 (warm)",
			"Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)", "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)",
			"FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)", "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bagpipe",
			"Fiddle", "Shanai", "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
			"Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter", "Applause", "Gunshot"
		};

		public int Patch
		{
			get
			{
				return patch;
			}
			set
			{
				if (value < 0 || value > 127)
				{
					throw new ArgumentOutOfRangeException("value", "Patch number must be in the range 0-127");
				}
				patch = (byte)value;
			}
		}

		public static string GetPatchName(int patchNumber)
		{
			return patchNames[patchNumber];
		}

		public PatchChangeEvent(BinaryReader br)
		{
			patch = br.ReadByte();
			if ((patch & 0x80u) != 0)
			{
				throw new FormatException("Invalid patch");
			}
		}

		public PatchChangeEvent(long absoluteTime, int channel, int patchNumber)
			: base(absoluteTime, channel, MidiCommandCode.PatchChange)
		{
			Patch = patchNumber;
		}

		public override string ToString()
		{
			return $"{base.ToString()} {GetPatchName(patch)}";
		}

		public override int GetAsShortMessage()
		{
			return base.GetAsShortMessage() + (patch << 8);
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write(patch);
		}
	}
	public class PitchWheelChangeEvent : MidiEvent
	{
		private int pitch;

		public int Pitch
		{
			get
			{
				return pitch;
			}
			set
			{
				if (value < 0 || value >= 16384)
				{
					throw new ArgumentOutOfRangeException("value", "Pitch value must be in the range 0 - 0x3FFF");
				}
				pitch = value;
			}
		}

		public PitchWheelChangeEvent(BinaryReader br)
		{
			byte b = br.ReadByte();
			byte b2 = br.ReadByte();
			if ((b & 0x80u) != 0)
			{
				throw new FormatException("Invalid pitchwheelchange byte 1");
			}
			if ((b2 & 0x80u) != 0)
			{
				throw new FormatException("Invalid pitchwheelchange byte 2");
			}
			pitch = b + (b2 << 7);
		}

		public PitchWheelChangeEvent(long absoluteTime, int channel, int pitchWheel)
			: base(absoluteTime, channel, MidiCommandCode.PitchWheelChange)
		{
			Pitch = pitchWheel;
		}

		public override string ToString()
		{
			return $"{base.ToString()} Pitch {pitch} ({pitch - 8192})";
		}

		public override int GetAsShortMessage()
		{
			return base.GetAsShortMessage() + ((pitch & 0x7F) << 8) + (((pitch >> 7) & 0x7F) << 16);
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write((byte)((uint)pitch & 0x7Fu));
			writer.Write((byte)((uint)(pitch >> 7) & 0x7Fu));
		}
	}
	public class RawMetaEvent : MetaEvent
	{
		public byte[] Data { get; set; }

		public RawMetaEvent(MetaEventType metaEventType, long absoluteTime, byte[] data)
			: base(metaEventType, (data != null) ? data.Length : 0, absoluteTime)
		{
			Data = data;
		}

		public override MidiEvent Clone()
		{
			return new RawMetaEvent(base.MetaEventType, base.AbsoluteTime, (byte[])Data?.Clone());
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder().Append(base.ToString());
			byte[] data = Data;
			foreach (byte b in data)
			{
				stringBuilder.AppendFormat(" {0:X2}", b);
			}
			return stringBuilder.ToString();
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			if (Data != null)
			{
				writer.Write(Data, 0, Data.Length);
			}
		}
	}
	public class SequencerSpecificEvent : MetaEvent
	{
		private byte[] data;

		public byte[] Data
		{
			get
			{
				return data;
			}
			set
			{
				data = value;
				metaDataLength = data.Length;
			}
		}

		public SequencerSpecificEvent(BinaryReader br, int length)
		{
			data = br.ReadBytes(length);
		}

		public SequencerSpecificEvent(byte[] data, long absoluteTime)
			: base(MetaEventType.SequencerSpecific, data.Length, absoluteTime)
		{
			this.data = data;
		}

		public override MidiEvent Clone()
		{
			return new SequencerSpecificEvent((byte[])data.Clone(), base.AbsoluteTime);
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(base.ToString());
			stringBuilder.Append(" ");
			byte[] array = data;
			foreach (byte b in array)
			{
				stringBuilder.AppendFormat("{0:X2} ", b);
			}
			stringBuilder.Length--;
			return stringBuilder.ToString();
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write(data);
		}
	}
	public class SmpteOffsetEvent : MetaEvent
	{
		private readonly byte hours;

		private readonly byte minutes;

		private readonly byte seconds;

		private readonly byte frames;

		private readonly byte subFrames;

		public int Hours => hours;

		public int Minutes => minutes;

		public int Seconds => seconds;

		public int Frames => frames;

		public int SubFrames => subFrames;

		public SmpteOffsetEvent(byte hours, byte minutes, byte seconds, byte frames, byte subFrames)
		{
			this.hours = hours;
			this.minutes = minutes;
			this.seconds = seconds;
			this.frames = frames;
			this.subFrames = subFrames;
		}

		public SmpteOffsetEvent(BinaryReader br, int length)
		{
			if (length != 5)
			{
				throw new FormatException($"Invalid SMPTE Offset length: Got {length}, expected 5");
			}
			hours = br.ReadByte();
			minutes = br.ReadByte();
			seconds = br.ReadByte();
			frames = br.ReadByte();
			subFrames = br.ReadByte();
		}

		public override MidiEvent Clone()
		{
			return (SmpteOffsetEvent)MemberwiseClone();
		}

		public override string ToString()
		{
			return $"{base.ToString()} {hours}:{minutes}:{seconds}:{frames}:{subFrames}";
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write(hours);
			writer.Write(minutes);
			writer.Write(seconds);
			writer.Write(frames);
			writer.Write(subFrames);
		}
	}
	public class SysexEvent : MidiEvent
	{
		private byte[] data;

		public static SysexEvent ReadSysexEvent(BinaryReader br)
		{
			SysexEvent sysexEvent = new SysexEvent();
			List<byte> list = new List<byte>();
			bool flag = true;
			while (flag)
			{
				byte b = br.ReadByte();
				if (b == 247)
				{
					flag = false;
				}
				else
				{
					list.Add(b);
				}
			}
			sysexEvent.data = list.ToArray();
			return sysexEvent;
		}

		public override MidiEvent Clone()
		{
			return new SysexEvent
			{
				data = (byte[])data?.Clone()
			};
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			byte[] array = data;
			foreach (byte b in array)
			{
				stringBuilder.AppendFormat("{0:X2} ", b);
			}
			return $"{base.AbsoluteTime} Sysex: {data.Length} bytes\r\n{stringBuilder.ToString()}";
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write(data, 0, data.Length);
			writer.Write((byte)247);
		}
	}
	public class TempoEvent : MetaEvent
	{
		private int microsecondsPerQuarterNote;

		public int MicrosecondsPerQuarterNote
		{
			get
			{
				return microsecondsPerQuarterNote;
			}
			set
			{
				microsecondsPerQuarterNote = value;
			}
		}

		public double Tempo
		{
			get
			{
				return 60000000.0 / (double)microsecondsPerQuarterNote;
			}
			set
			{
				microsecondsPerQuarterNote = (int)(60000000.0 / value);
			}
		}

		public TempoEvent(BinaryReader br, int length)
		{
			if (length != 3)
			{
				throw new FormatException("Invalid tempo length");
			}
			microsecondsPerQuarterNote = (br.ReadByte() << 16) + (br.ReadByte() << 8) + br.ReadByte();
		}

		public TempoEvent(int microsecondsPerQuarterNote, long absoluteTime)
			: base(MetaEventType.SetTempo, 3, absoluteTime)
		{
			this.microsecondsPerQuarterNote = microsecondsPerQuarterNote;
		}

		public override MidiEvent Clone()
		{
			return (TempoEvent)MemberwiseClone();
		}

		public override string ToString()
		{
			return string.Format("{0} {2}bpm ({1})", base.ToString(), microsecondsPerQuarterNote, 60000000 / microsecondsPerQuarterNote);
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write((byte)((uint)(microsecondsPerQuarterNote >> 16) & 0xFFu));
			writer.Write((byte)((uint)(microsecondsPerQuarterNote >> 8) & 0xFFu));
			writer.Write((byte)((uint)microsecondsPerQuarterNote & 0xFFu));
		}
	}
	public class TextEvent : MetaEvent
	{
		private byte[] data;

		public string Text
		{
			get
			{
				return ((Encoding)(object)ByteEncoding.Instance).GetString(data);
			}
			set
			{
				Encoding instance = (Encoding)(object)ByteEncoding.Instance;
				data = instance.GetBytes(value);
				metaDataLength = data.Length;
			}
		}

		public byte[] Data
		{
			get
			{
				return data;
			}
			set
			{
				data = value;
				metaDataLength = data.Length;
			}
		}

		public TextEvent(BinaryReader br, int length)
		{
			data = br.ReadBytes(length);
		}

		public TextEvent(string text, MetaEventType metaEventType, long absoluteTime)
			: base(metaEventType, text.Length, absoluteTime)
		{
			Text = text;
		}

		public override MidiEvent Clone()
		{
			return (TextEvent)MemberwiseClone();
		}

		public override string ToString()
		{
			return $"{base.ToString()} {Text}";
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write(data);
		}
	}
	public class TimeSignatureEvent : MetaEvent
	{
		private byte numerator;

		private byte denominator;

		private byte ticksInMetronomeClick;

		private byte no32ndNotesInQuarterNote;

		public int Numerator => numerator;

		public int Denominator => denominator;

		public int TicksInMetronomeClick => ticksInMetronomeClick;

		public int No32ndNotesInQuarterNote => no32ndNotesInQuarterNote;

		public string TimeSignature
		{
			get
			{
				string arg = $"Unknown ({denominator})";
				switch (denominator)
				{
				case 1:
					arg = "2";
					break;
				case 2:
					arg = "4";
					break;
				case 3:
					arg = "8";
					break;
				case 4:
					arg = "16";
					break;
				case 5:
					arg = "32";
					break;
				}
				return $"{numerator}/{arg}";
			}
		}

		public TimeSignatureEvent(BinaryReader br, int length)
		{
			if (length != 4)
			{
				throw new FormatException($"Invalid time signature length: Got {length}, expected 4");
			}
			numerator = br.ReadByte();
			denominator = br.ReadByte();
			ticksInMetronomeClick = br.ReadByte();
			no32ndNotesInQuarterNote = br.ReadByte();
		}

		public TimeSignatureEvent(long absoluteTime, int numerator, int denominator, int ticksInMetronomeClick, int no32ndNotesInQuarterNote)
			: base(MetaEventType.TimeSignature, 4, absoluteTime)
		{
			this.numerator = (byte)numerator;
			this.denominator = (byte)denominator;
			this.ticksInMetronomeClick = (byte)ticksInMetronomeClick;
			this.no32ndNotesInQuarterNote = (byte)no32ndNotesInQuarterNote;
		}

		public override MidiEvent Clone()
		{
			return (TimeSignatureEvent)MemberwiseClone();
		}

		public override string ToString()
		{
			return $"{base.ToString()} {TimeSignature} TicksInClick:{ticksInMetronomeClick} 32ndsInQuarterNote:{no32ndNotesInQuarterNote}";
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write(numerator);
			writer.Write(denominator);
			writer.Write(ticksInMetronomeClick);
			writer.Write(no32ndNotesInQuarterNote);
		}
	}
	public class TrackSequenceNumberEvent : MetaEvent
	{
		private ushort sequenceNumber;

		public TrackSequenceNumberEvent(ushort sequenceNumber)
		{
			this.sequenceNumber = sequenceNumber;
		}

		public TrackSequenceNumberEvent(BinaryReader br, int length)
		{
			if (length != 2)
			{
				throw new FormatException("Invalid sequence number length");
			}
			sequenceNumber = (ushort)((br.ReadByte() << 8) + br.ReadByte());
		}

		public override MidiEvent Clone()
		{
			return (TrackSequenceNumberEvent)MemberwiseClone();
		}

		public override string ToString()
		{
			return $"{base.ToString()} {sequenceNumber}";
		}

		public override void Export(ref long absoluteTime, BinaryWriter writer)
		{
			base.Export(ref absoluteTime, writer);
			writer.Write((byte)((uint)(sequenceNumber >> 8) & 0xFFu));
			writer.Write((byte)(sequenceNumber & 0xFFu));
		}
	}
}
namespace NAudio.Utils
{
	internal class MergeSort
	{
		private static void Sort<T>(IList<T> list, int lowIndex, int highIndex, IComparer<T> comparer)
		{
			if (lowIndex >= highIndex)
			{
				return;
			}
			int num = (lowIndex + highIndex) / 2;
			Sort(list, lowIndex, num, comparer);
			Sort(list, num + 1, highIndex, comparer);
			int num2 = num;
			int num3 = num + 1;
			while (lowIndex <= num2 && num3 <= highIndex)
			{
				if (comparer.Compare(list[lowIndex], list[num3]) <= 0)
				{
					lowIndex++;
					continue;
				}
				T value = list[num3];
				for (int num4 = num3 - 1; num4 >= lowIndex; num4--)
				{
					list[num4 + 1] = list[num4];
				}
				list[lowIndex] = value;
				lowIndex++;
				num2++;
				num3++;
			}
		}

		public static void Sort<T>(IList<T> list) where T : IComparable<T>
		{
			Sort(list, 0, list.Count - 1, Comparer<T>.Default);
		}

		public static void Sort<T>(IList<T> list, IComparer<T> comparer)
		{
			Sort(list, 0, list.Count - 1, comparer);
		}
	}
}

NAudio.Wasapi.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Threading;
using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
using NAudio.Dmo;
using NAudio.Dmo.Effect;
using NAudio.MediaFoundation;
using NAudio.Utils;
using NAudio.Wave;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Mark Heath")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2021")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
[assembly: AssemblyProduct("NAudio.Wasapi")]
[assembly: AssemblyTitle("NAudio.Wasapi")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: AssemblyVersion("2.0.0.0")]
namespace NAudio.MediaFoundation
{
	public static class AudioSubtypes
	{
		[FieldDescription("AAC")]
		public static readonly Guid MFAudioFormat_AAC = new Guid("00001610-0000-0010-8000-00aa00389b71");

		[FieldDescription("ADTS")]
		public static readonly Guid MFAudioFormat_ADTS = new Guid("00001600-0000-0010-8000-00aa00389b71");

		[FieldDescription("Dolby AC3 SPDIF")]
		public static readonly Guid MFAudioFormat_Dolby_AC3_SPDIF = new Guid("00000092-0000-0010-8000-00aa00389b71");

		[FieldDescription("DRM")]
		public static readonly Guid MFAudioFormat_DRM = new Guid("00000009-0000-0010-8000-00aa00389b71");

		[FieldDescription("DTS")]
		public static readonly Guid MFAudioFormat_DTS = new Guid("00000008-0000-0010-8000-00aa00389b71");

		[FieldDescription("IEEE floating-point")]
		public static readonly Guid MFAudioFormat_Float = new Guid("00000003-0000-0010-8000-00aa00389b71");

		[FieldDescription("MP3")]
		public static readonly Guid MFAudioFormat_MP3 = new Guid("00000055-0000-0010-8000-00aa00389b71");

		[FieldDescription("MPEG")]
		public static readonly Guid MFAudioFormat_MPEG = new Guid("00000050-0000-0010-8000-00aa00389b71");

		[FieldDescription("WMA 9 Voice codec")]
		public static readonly Guid MFAudioFormat_MSP1 = new Guid("0000000a-0000-0010-8000-00aa00389b71");

		[FieldDescription("PCM")]
		public static readonly Guid MFAudioFormat_PCM = new Guid("00000001-0000-0010-8000-00aa00389b71");

		[FieldDescription("WMA SPDIF")]
		public static readonly Guid MFAudioFormat_WMASPDIF = new Guid("00000164-0000-0010-8000-00aa00389b71");

		[FieldDescription("WMAudio Lossless")]
		public static readonly Guid MFAudioFormat_WMAudio_Lossless = new Guid("00000163-0000-0010-8000-00aa00389b71");

		[FieldDescription("Windows Media Audio")]
		public static readonly Guid MFAudioFormat_WMAudioV8 = new Guid("00000161-0000-0010-8000-00aa00389b71");

		[FieldDescription("Windows Media Audio Professional")]
		public static readonly Guid MFAudioFormat_WMAudioV9 = new Guid("00000162-0000-0010-8000-00aa00389b71");

		[FieldDescription("Dolby AC3")]
		public static readonly Guid MFAudioFormat_Dolby_AC3 = new Guid("e06d802c-db46-11cf-b4d1-00805f6cbbea");

		[FieldDescription("MPEG-4 and AAC Audio Types")]
		public static readonly Guid MEDIASUBTYPE_RAW_AAC1 = new Guid("000000ff-0000-0010-8000-00aa00389b71");

		[FieldDescription("Dolby Audio Types")]
		public static readonly Guid MEDIASUBTYPE_DVM = new Guid("00002000-0000-0010-8000-00aa00389b71");

		[FieldDescription("Dolby Audio Types")]
		public static readonly Guid MEDIASUBTYPE_DOLBY_DDPLUS = new Guid("a7fb87af-2d02-42fb-a4d4-05cd93843bdd");

		[FieldDescription("μ-law")]
		public static readonly Guid KSDATAFORMAT_SUBTYPE_MULAW = new Guid("00000007-0000-0010-8000-00aa00389b71");

		[FieldDescription("ADPCM")]
		public static readonly Guid KSDATAFORMAT_SUBTYPE_ADPCM = new Guid("00000002-0000-0010-8000-00aa00389b71");

		[FieldDescription("Dolby Digital Plus for HDMI")]
		public static readonly Guid KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS = new Guid("0000000a-0cea-0010-8000-00aa00389b71");

		[FieldDescription("MSAudio1")]
		public static readonly Guid MEDIASUBTYPE_MSAUDIO1 = new Guid("00000160-0000-0010-8000-00aa00389b71");

		[FieldDescription("IMA ADPCM")]
		public static readonly Guid ImaAdpcm = new Guid("00000011-0000-0010-8000-00aa00389b71");

		[FieldDescription("WMSP2")]
		public static readonly Guid WMMEDIASUBTYPE_WMSP2 = new Guid("0000000b-0000-0010-8000-00aa00389b71");
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("7FEE9E9A-4A89-47a6-899C-B6A53A70FB67")]
	public interface IMFActivate : IMFAttributes
	{
		new void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue);

		new void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType);

		new void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		new void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		new void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue);

		new void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue);

		new void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue);

		new void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue);

		new void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength);

		new void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength);

		new void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength);

		new void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize);

		new void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize);

		new void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize);

		new void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);

		new void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value);

		new void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey);

		new void DeleteAllItems();

		new void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue);

		new void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue);

		new void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue);

		new void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue);

		new void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue);

		new void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize);

		new void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown);

		new void LockStore();

		new void UnlockStore();

		new void GetCount(out int pcItems);

		new void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue);

		new void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest);

		void ActivateObject([In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv);

		void ShutdownObject();

		void DetachObject();
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("2CD2D921-C447-44A7-A13C-4ADABFC247E3")]
	public interface IMFAttributes
	{
		void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue);

		void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType);

		void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue);

		void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue);

		void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue);

		void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue);

		void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength);

		void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength);

		void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength);

		void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize);

		void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize);

		void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize);

		void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);

		void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr Value);

		void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey);

		void DeleteAllItems();

		void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue);

		void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue);

		void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue);

		void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue);

		void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue);

		void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize);

		void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown);

		void LockStore();

		void UnlockStore();

		void GetCount(out int pcItems);

		void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue);

		void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest);
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("ad4c1b00-4bf7-422f-9175-756693d9130d")]
	public interface IMFByteStream
	{
		void GetCapabilities(ref int pdwCapabiities);

		void GetLength(ref long pqwLength);

		void SetLength(long qwLength);

		void GetCurrentPosition(ref long pqwPosition);

		void SetCurrentPosition(long qwPosition);

		void IsEndOfStream([MarshalAs(UnmanagedType.Bool)] ref bool pfEndOfStream);

		void Read(IntPtr pb, int cb, ref int pcbRead);

		void BeginRead(IntPtr pb, int cb, IntPtr pCallback, IntPtr punkState);

		void EndRead(IntPtr pResult, ref int pcbRead);

		void Write(IntPtr pb, int cb, ref int pcbWritten);

		void BeginWrite(IntPtr pb, int cb, IntPtr pCallback, IntPtr punkState);

		void EndWrite(IntPtr pResult, ref int pcbWritten);

		void Seek(int SeekOrigin, long llSeekOffset, int dwSeekFlags, ref long pqwCurrentPosition);

		void Flush();

		void Close();
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("5BC8A76B-869A-46A3-9B03-FA218A66AEBE")]
	public interface IMFCollection
	{
		void GetElementCount(out int pcElements);

		void GetElement([In] int dwElementIndex, [MarshalAs(UnmanagedType.IUnknown)] out object ppUnkElement);

		void AddElement([In][MarshalAs(UnmanagedType.IUnknown)] object pUnkElement);

		void RemoveElement([In] int dwElementIndex, [MarshalAs(UnmanagedType.IUnknown)] out object ppUnkElement);

		void InsertElementAt([In] int dwIndex, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown);

		void RemoveAllElements();
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("045FA593-8799-42b8-BC8D-8968C6453507")]
	public interface IMFMediaBuffer
	{
		void Lock(out IntPtr ppbBuffer, out int pcbMaxLength, out int pcbCurrentLength);

		void Unlock();

		void GetCurrentLength(out int pcbCurrentLength);

		void SetCurrentLength(int cbCurrentLength);

		void GetMaxLength(out int pcbMaxLength);
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("DF598932-F10C-4E39-BBA2-C308F101DAA3")]
	public interface IMFMediaEvent : IMFAttributes
	{
		new void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue);

		new void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType);

		new void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		new void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		new void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue);

		new void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue);

		new void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue);

		new void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue);

		new void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength);

		new void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength);

		new void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength);

		new void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize);

		new void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize);

		new void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize);

		new void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);

		new void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value);

		new void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey);

		new void DeleteAllItems();

		new void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue);

		new void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue);

		new void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue);

		new void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue);

		new void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue);

		new void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize);

		new void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown);

		new void LockStore();

		new void UnlockStore();

		new void GetCount(out int pcItems);

		new void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue);

		new void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest);

		void GetType(out MediaEventType pmet);

		void GetExtendedType(out Guid pguidExtendedType);

		void GetStatus([MarshalAs(UnmanagedType.Error)] out int phrStatus);

		void GetValue([Out] IntPtr pvValue);
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("44AE0FA8-EA31-4109-8D2E-4CAE4997C555")]
	public interface IMFMediaType : IMFAttributes
	{
		new void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue);

		new void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType);

		new void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		new void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		new void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue);

		new void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue);

		new void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue);

		new void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue);

		new void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength);

		new void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength);

		new void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength);

		new void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize);

		new void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize);

		new void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize);

		new void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);

		new void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value);

		new void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey);

		new void DeleteAllItems();

		new void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue);

		new void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue);

		new void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue);

		new void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue);

		new void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue);

		new void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize);

		new void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown);

		new void LockStore();

		new void UnlockStore();

		new void GetCount(out int pcItems);

		new void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue);

		new void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest);

		void GetMajorType(out Guid pguidMajorType);

		void IsCompressedFormat([MarshalAs(UnmanagedType.Bool)] out bool pfCompressed);

		[PreserveSig]
		int IsEqual([In][MarshalAs(UnmanagedType.Interface)] IMFMediaType pIMediaType, ref int pdwFlags);

		void GetRepresentation([In] Guid guidRepresentation, ref IntPtr ppvRepresentation);

		void FreeRepresentation([In] Guid guidRepresentation, [In] IntPtr pvRepresentation);
	}
	[ComImport]
	[Guid("E7FE2E12-661C-40DA-92F9-4F002AB67627")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IMFReadWriteClassFactory
	{
		void CreateInstanceFromURL([In][MarshalAs(UnmanagedType.LPStruct)] Guid clsid, [In][MarshalAs(UnmanagedType.LPWStr)] string pwszURL, [In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pAttributes, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject);

		void CreateInstanceFromObject([In][MarshalAs(UnmanagedType.LPStruct)] Guid clsid, [In][MarshalAs(UnmanagedType.IUnknown)] object punkObject, [In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pAttributes, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject);
	}
	[ComImport]
	[Guid("48e2ed0f-98c2-4a37-bed5-166312ddd83f")]
	public class MFReadWriteClassFactory
	{
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("c40a00f2-b93a-4d80-ae8c-5a1c634f58e4")]
	public interface IMFSample : IMFAttributes
	{
		new void GetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][Out] IntPtr pValue);

		new void GetItemType([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pType);

		new void CompareItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		new void Compare([MarshalAs(UnmanagedType.Interface)] IMFAttributes pTheirs, int matchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);

		new void GetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int punValue);

		new void GetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out long punValue);

		new void GetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out double pfValue);

		new void GetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out Guid pguidValue);

		new void GetStringLength([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcchLength);

		new void GetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszValue, int cchBufSize, out int pcchLength);

		new void GetAllocatedString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out int pcchLength);

		new void GetBlobSize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out int pcbBlobSize);

		new void GetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] pBuf, int cbBufSize, out int pcbBlobSize);

		new void GetAllocatedBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, out IntPtr ip, out int pcbSize);

		new void GetUnknown([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);

		new void SetItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, IntPtr value);

		new void DeleteItem([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey);

		new void DeleteAllItems();

		new void SetUINT32([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, int unValue);

		new void SetUINT64([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, long unValue);

		new void SetDouble([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, double fValue);

		new void SetGUID([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidValue);

		new void SetString([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPWStr)] string wszValue);

		new void SetBlob([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pBuf, int cbBufSize);

		new void SetUnknown([MarshalAs(UnmanagedType.LPStruct)] Guid guidKey, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnknown);

		new void LockStore();

		new void UnlockStore();

		new void GetCount(out int pcItems);

		new void GetItemByIndex(int unIndex, out Guid pGuidKey, [In][Out] IntPtr pValue);

		new void CopyAllItems([In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pDest);

		void GetSampleFlags(out int pdwSampleFlags);

		void SetSampleFlags(int dwSampleFlags);

		void GetSampleTime(out long phnsSampletime);

		void SetSampleTime(long hnsSampleTime);

		void GetSampleDuration(out long phnsSampleDuration);

		void SetSampleDuration(long hnsSampleDuration);

		void GetBufferCount(out int pdwBufferCount);

		void GetBufferByIndex(int dwIndex, out IMFMediaBuffer ppBuffer);

		void ConvertToContiguousBuffer(out IMFMediaBuffer ppBuffer);

		void AddBuffer(IMFMediaBuffer pBuffer);

		void RemoveBufferByIndex(int dwIndex);

		void RemoveAllBuffers();

		void GetTotalLength(out int pcbTotalLength);

		void CopyToBuffer(IMFMediaBuffer pBuffer);
	}
	[ComImport]
	[Guid("3137f1cd-fe5e-4805-a5d8-fb477448cb3d")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IMFSinkWriter
	{
		void AddStream([In][MarshalAs(UnmanagedType.Interface)] IMFMediaType pTargetMediaType, out int pdwStreamIndex);

		void SetInputMediaType([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.Interface)] IMFMediaType pInputMediaType, [In][MarshalAs(UnmanagedType.Interface)] IMFAttributes pEncodingParameters);

		void BeginWriting();

		void WriteSample([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.Interface)] IMFSample pSample);

		void SendStreamTick([In] int dwStreamIndex, [In] long llTimestamp);

		void PlaceMarker([In] int dwStreamIndex, [In] IntPtr pvContext);

		void NotifyEndOfSegment([In] int dwStreamIndex);

		void Flush([In] int dwStreamIndex);

		void DoFinalize();

		void GetServiceForStream([In] int dwStreamIndex, [In] ref Guid guidService, [In] ref Guid riid, out IntPtr ppvObject);

		void GetStatistics([In] int dwStreamIndex, [In][Out] MF_SINK_WRITER_STATISTICS pStats);
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("70ae66f2-c809-4e4f-8915-bdcb406b7993")]
	public interface IMFSourceReader
	{
		void GetStreamSelection([In] int dwStreamIndex, [MarshalAs(UnmanagedType.Bool)] out bool pSelected);

		void SetStreamSelection([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.Bool)] bool pSelected);

		void GetNativeMediaType([In] int dwStreamIndex, [In] int dwMediaTypeIndex, out IMFMediaType ppMediaType);

		void GetCurrentMediaType([In] int dwStreamIndex, out IMFMediaType ppMediaType);

		void SetCurrentMediaType([In] int dwStreamIndex, IntPtr pdwReserved, [In] IMFMediaType pMediaType);

		void SetCurrentPosition([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidTimeFormat, [In] IntPtr varPosition);

		void ReadSample([In] int dwStreamIndex, [In] int dwControlFlags, out int pdwActualStreamIndex, out MF_SOURCE_READER_FLAG pdwStreamFlags, out ulong pllTimestamp, out IMFSample ppSample);

		void Flush([In] int dwStreamIndex);

		void GetServiceForStream([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidService, [In][MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IntPtr ppvObject);

		[PreserveSig]
		int GetPresentationAttribute([In] int dwStreamIndex, [In][MarshalAs(UnmanagedType.LPStruct)] Guid guidAttribute, [Out] IntPtr pvarAttribute);
	}
	[Flags]
	public enum MF_SOURCE_READER_FLAG
	{
		None = 0,
		MF_SOURCE_READERF_ERROR = 1,
		MF_SOURCE_READERF_ENDOFSTREAM = 2,
		MF_SOURCE_READERF_NEWSTREAM = 4,
		MF_SOURCE_READERF_NATIVEMEDIATYPECHANGED = 0x10,
		MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED = 0x20,
		MF_SOURCE_READERF_STREAMTICK = 0x100,
		MF_SOURCE_READERF_ALLEFFECTSREMOVED = 0x200
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("bf94c121-5b05-4e6f-8000-ba598961414d")]
	public interface IMFTransform
	{
		void GetStreamLimits(out int pdwInputMinimum, out int pdwInputMaximum, out int pdwOutputMinimum, out int pdwOutputMaximum);

		void GetStreamCount(out int pcInputStreams, out int pcOutputStreams);

		void GetStreamIds([In] int dwInputIdArraySize, [In][Out] IntPtr pdwInputIDs, [In] int dwOutputIdArraySize, [In][Out] IntPtr pdwOutputIDs);

		void GetInputStreamInfo([In] int dwInputStreamId, out MFT_INPUT_STREAM_INFO pStreamInfo);

		void GetOutputStreamInfo([In] int dwOutputStreamId, out MFT_OUTPUT_STREAM_INFO pStreamInfo);

		void GetAttributes(out IMFAttributes pAttributes);

		void GetInputStreamAttributes([In] int dwInputStreamId, out IMFAttributes pAttributes);

		void GetOutputStreamAttributes([In] int dwOutputStreamId, out IMFAttributes pAttributes);

		void DeleteInputStream([In] int dwOutputStreamId);

		void AddInputStreams([In] int cStreams, [In] IntPtr adwStreamIDs);

		void GetInputAvailableType([In] int dwInputStreamId, [In] int dwTypeIndex, out IMFMediaType ppType);

		void GetOutputAvailableType([In] int dwOutputStreamId, [In] int dwTypeIndex, out IMFMediaType ppType);

		void SetInputType([In] int dwInputStreamId, [In] IMFMediaType pType, [In] _MFT_SET_TYPE_FLAGS dwFlags);

		void SetOutputType([In] int dwOutputStreamId, [In] IMFMediaType pType, [In] _MFT_SET_TYPE_FLAGS dwFlags);

		void GetInputCurrentType([In] int dwInputStreamId, out IMFMediaType ppType);

		void GetOutputCurrentType([In] int dwOutputStreamId, out IMFMediaType ppType);

		void GetInputStatus([In] int dwInputStreamId, out _MFT_INPUT_STATUS_FLAGS pdwFlags);

		void GetOutputStatus([In] int dwInputStreamId, out _MFT_OUTPUT_STATUS_FLAGS pdwFlags);

		void SetOutputBounds([In] long hnsLowerBound, [In] long hnsUpperBound);

		void ProcessEvent([In] int dwInputStreamId, [In] IMFMediaEvent pEvent);

		void ProcessMessage([In] MFT_MESSAGE_TYPE eMessage, [In] IntPtr ulParam);

		void ProcessInput([In] int dwInputStreamId, [In] IMFSample pSample, int dwFlags);

		[PreserveSig]
		int ProcessOutput([In] _MFT_PROCESS_OUTPUT_FLAGS dwFlags, [In] int cOutputBufferCount, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] MFT_OUTPUT_DATA_BUFFER[] pOutputSamples, out _MFT_PROCESS_OUTPUT_STATUS pdwStatus);
	}
	public enum MediaEventType
	{
		MEUnknown = 0,
		MEError = 1,
		MEExtendedType = 2,
		MENonFatalError = 3,
		MESessionUnknown = 100,
		MESessionTopologySet = 101,
		MESessionTopologiesCleared = 102,
		MESessionStarted = 103,
		MESessionPaused = 104,
		MESessionStopped = 105,
		MESessionClosed = 106,
		MESessionEnded = 107,
		MESessionRateChanged = 108,
		MESessionScrubSampleComplete = 109,
		MESessionCapabilitiesChanged = 110,
		MESessionTopologyStatus = 111,
		MESessionNotifyPresentationTime = 112,
		MENewPresentation = 113,
		MELicenseAcquisitionStart = 114,
		MELicenseAcquisitionCompleted = 115,
		MEIndividualizationStart = 116,
		MEIndividualizationCompleted = 117,
		MEEnablerProgress = 118,
		MEEnablerCompleted = 119,
		MEPolicyError = 120,
		MEPolicyReport = 121,
		MEBufferingStarted = 122,
		MEBufferingStopped = 123,
		MEConnectStart = 124,
		MEConnectEnd = 125,
		MEReconnectStart = 126,
		MEReconnectEnd = 127,
		MERendererEvent = 128,
		MESessionStreamSinkFormatChanged = 129,
		MESourceUnknown = 200,
		MESourceStarted = 201,
		MEStreamStarted = 202,
		MESourceSeeked = 203,
		MEStreamSeeked = 204,
		MENewStream = 205,
		MEUpdatedStream = 206,
		MESourceStopped = 207,
		MEStreamStopped = 208,
		MESourcePaused = 209,
		MEStreamPaused = 210,
		MEEndOfPresentation = 211,
		MEEndOfStream = 212,
		MEMediaSample = 213,
		MEStreamTick = 214,
		MEStreamThinMode = 215,
		MEStreamFormatChanged = 216,
		MESourceRateChanged = 217,
		MEEndOfPresentationSegment = 218,
		MESourceCharacteristicsChanged = 219,
		MESourceRateChangeRequested = 220,
		MESourceMetadataChanged = 221,
		MESequencerSourceTopologyUpdated = 222,
		MESinkUnknown = 300,
		MEStreamSinkStarted = 301,
		MEStreamSinkStopped = 302,
		MEStreamSinkPaused = 303,
		MEStreamSinkRateChanged = 304,
		MEStreamSinkRequestSample = 305,
		MEStreamSinkMarker = 306,
		MEStreamSinkPrerolled = 307,
		MEStreamSinkScrubSampleComplete = 308,
		MEStreamSinkFormatChanged = 309,
		MEStreamSinkDeviceChanged = 310,
		MEQualityNotify = 311,
		MESinkInvalidated = 312,
		MEAudioSessionNameChanged = 313,
		MEAudioSessionVolumeChanged = 314,
		MEAudioSessionDeviceRemoved = 315,
		MEAudioSessionServerShutdown = 316,
		MEAudioSessionGroupingParamChanged = 317,
		MEAudioSessionIconChanged = 318,
		MEAudioSessionFormatChanged = 319,
		MEAudioSessionDisconnected = 320,
		MEAudioSessionExclusiveModeOverride = 321,
		METrustUnknown = 400,
		MEPolicyChanged = 401,
		MEContentProtectionMessage = 402,
		MEPolicySet = 403,
		MEWMDRMLicenseBackupCompleted = 500,
		MEWMDRMLicenseBackupProgress = 501,
		MEWMDRMLicenseRestoreCompleted = 502,
		MEWMDRMLicenseRestoreProgress = 503,
		MEWMDRMLicenseAcquisitionCompleted = 506,
		MEWMDRMIndividualizationCompleted = 508,
		MEWMDRMIndividualizationProgress = 513,
		MEWMDRMProximityCompleted = 514,
		MEWMDRMLicenseStoreCleaned = 515,
		MEWMDRMRevocationDownloadCompleted = 516,
		METransformUnknown = 600,
		METransformNeedInput = 601,
		METransformHaveOutput = 602,
		METransformDrainComplete = 603,
		METransformMarker = 604
	}
	public static class MediaFoundationAttributes
	{
		public static readonly Guid MF_TRANSFORM_ASYNC = new Guid("f81a699a-649a-497d-8c73-29f8fed6ad7a");

		public static readonly Guid MF_TRANSFORM_ASYNC_UNLOCK = new Guid("e5666d6b-3422-4eb6-a421-da7db1f8e207");

		[FieldDescription("Transform Flags")]
		public static readonly Guid MF_TRANSFORM_FLAGS_Attribute = new Guid("9359bb7e-6275-46c4-a025-1c01e45f1a86");

		[FieldDescription("Transform Category")]
		public static readonly Guid MF_TRANSFORM_CATEGORY_Attribute = new Guid("ceabba49-506d-4757-a6ff-66c184987e4e");

		[FieldDescription("Class identifier")]
		public static readonly Guid MFT_TRANSFORM_CLSID_Attribute = new Guid("6821c42b-65a4-4e82-99bc-9a88205ecd0c");

		[FieldDescription("Input Types")]
		public static readonly Guid MFT_INPUT_TYPES_Attributes = new Guid("4276c9b1-759d-4bf3-9cd0-0d723d138f96");

		[FieldDescription("Output Types")]
		public static readonly Guid MFT_OUTPUT_TYPES_Attributes = new Guid("8eae8cf3-a44f-4306-ba5c-bf5dda242818");

		public static readonly Guid MFT_ENUM_HARDWARE_URL_Attribute = new Guid("2fb866ac-b078-4942-ab6c-003d05cda674");

		[FieldDescription("Name")]
		public static readonly Guid MFT_FRIENDLY_NAME_Attribute = new Guid("314ffbae-5b41-4c95-9c19-4e7d586face3");

		public static readonly Guid MFT_CONNECTED_STREAM_ATTRIBUTE = new Guid("71eeb820-a59f-4de2-bcec-38db1dd611a4");

		public static readonly Guid MFT_CONNECTED_TO_HW_STREAM = new Guid("34e6e728-06d6-4491-a553-4795650db912");

		[FieldDescription("Preferred Output Format")]
		public static readonly Guid MFT_PREFERRED_OUTPUTTYPE_Attribute = new Guid("7e700499-396a-49ee-b1b4-f628021e8c9d");

		public static readonly Guid MFT_PROCESS_LOCAL_Attribute = new Guid("543186e4-4649-4e65-b588-4aa352aff379");

		public static readonly Guid MFT_PREFERRED_ENCODER_PROFILE = new Guid("53004909-1ef5-46d7-a18e-5a75f8b5905f");

		public static readonly Guid MFT_HW_TIMESTAMP_WITH_QPC_Attribute = new Guid("8d030fb8-cc43-4258-a22e-9210bef89be4");

		public static readonly Guid MFT_FIELDOFUSE_UNLOCK_Attribute = new Guid("8ec2e9fd-9148-410d-831e-702439461a8e");

		public static readonly Guid MFT_CODEC_MERIT_Attribute = new Guid("88a7cb15-7b07-4a34-9128-e64c6703c4d3");

		public static readonly Guid MFT_ENUM_TRANSCODE_ONLY_ATTRIBUTE = new Guid("111ea8cd-b62a-4bdb-89f6-67ffcdc2458b");

		[FieldDescription("PMP Host Context")]
		public static readonly Guid MF_PD_PMPHOST_CONTEXT = new Guid("6c990d31-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("App Context")]
		public static readonly Guid MF_PD_APP_CONTEXT = new Guid("6c990d32-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Duration")]
		public static readonly Guid MF_PD_DURATION = new Guid("6c990d33-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Total File Size")]
		public static readonly Guid MF_PD_TOTAL_FILE_SIZE = new Guid("6c990d34-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Audio encoding bitrate")]
		public static readonly Guid MF_PD_AUDIO_ENCODING_BITRATE = new Guid("6c990d35-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Video Encoding Bitrate")]
		public static readonly Guid MF_PD_VIDEO_ENCODING_BITRATE = new Guid("6c990d36-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("MIME Type")]
		public static readonly Guid MF_PD_MIME_TYPE = new Guid("6c990d37-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Last Modified Time")]
		public static readonly Guid MF_PD_LAST_MODIFIED_TIME = new Guid("6c990d38-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Element ID")]
		public static readonly Guid MF_PD_PLAYBACK_ELEMENT_ID = new Guid("6c990d39-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Preferred Language")]
		public static readonly Guid MF_PD_PREFERRED_LANGUAGE = new Guid("6c990d3a-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Playback boundary time")]
		public static readonly Guid MF_PD_PLAYBACK_BOUNDARY_TIME = new Guid("6c990d3b-bb8e-477a-8598-0d5d96fcd88a");

		[FieldDescription("Audio is variable bitrate")]
		public static readonly Guid MF_PD_AUDIO_ISVARIABLEBITRATE = new Guid("33026ee0-e387-4582-ae0a-34a2ad3baa18");

		[FieldDescription("Major Media Type")]
		public static readonly Guid MF_MT_MAJOR_TYPE = new Guid("48eba18e-f8c9-4687-bf11-0a74c9f96a8f");

		[FieldDescription("Media Subtype")]
		public static readonly Guid MF_MT_SUBTYPE = new Guid("f7e34c9a-42e8-4714-b74b-cb29d72c35e5");

		[FieldDescription("Audio block alignment")]
		public static readonly Guid MF_MT_AUDIO_BLOCK_ALIGNMENT = new Guid("322de230-9eeb-43bd-ab7a-ff412251541d");

		[FieldDescription("Audio average bytes per second")]
		public static readonly Guid MF_MT_AUDIO_AVG_BYTES_PER_SECOND = new Guid("1aab75c8-cfef-451c-ab95-ac034b8e1731");

		[FieldDescription("Audio number of channels")]
		public static readonly Guid MF_MT_AUDIO_NUM_CHANNELS = new Guid("37e48bf5-645e-4c5b-89de-ada9e29b696a");

		[FieldDescription("Audio samples per second")]
		public static readonly Guid MF_MT_AUDIO_SAMPLES_PER_SECOND = new Guid("5faeeae7-0290-4c31-9e8a-c534f68d9dba");

		[FieldDescription("Audio bits per sample")]
		public static readonly Guid MF_MT_AUDIO_BITS_PER_SAMPLE = new Guid("f2deb57f-40fa-4764-aa33-ed4f2d1ff669");

		[FieldDescription("Enable Hardware Transforms")]
		public static readonly Guid MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS = new Guid("a634a91c-822b-41b9-a494-4de4643612b0");

		[FieldDescription("User data")]
		public static readonly Guid MF_MT_USER_DATA = new Guid("b6bc765f-4c3b-40a4-bd51-2535b66fe09d");

		[FieldDescription("All samples independent")]
		public static readonly Guid MF_MT_ALL_SAMPLES_INDEPENDENT = new Guid("c9173739-5e56-461c-b713-46fb995cb95f");

		[FieldDescription("Fixed size samples")]
		public static readonly Guid MF_MT_FIXED_SIZE_SAMPLES = new Guid("b8ebefaf-b718-4e04-b0a9-116775e3321b");

		[FieldDescription("DirectShow Format Guid")]
		public static readonly Guid MF_MT_AM_FORMAT_TYPE = new Guid("73d1072d-1870-4174-a063-29ff4ff6c11e");

		[FieldDescription("Preferred legacy format structure")]
		public static readonly Guid MF_MT_AUDIO_PREFER_WAVEFORMATEX = new Guid("a901aaba-e037-458a-bdf6-545be2074042");

		[FieldDescription("Is Compressed")]
		public static readonly Guid MF_MT_COMPRESSED = new Guid("3afd0cee-18f2-4ba5-a110-8bea502e1f92");

		[FieldDescription("Average bitrate")]
		public static readonly Guid MF_MT_AVG_BITRATE = new Guid("20332624-fb0d-4d9e-bd0d-cbf6786c102e");

		[FieldDescription("AAC payload type")]
		public static readonly Guid MF_MT_AAC_PAYLOAD_TYPE = new Guid("bfbabe79-7434-4d1c-94f0-72a3b9e17188");

		[FieldDescription("AAC Audio Profile Level Indication")]
		public static readonly Guid MF_MT_AAC_AUDIO_PROFILE_LEVEL_INDICATION = new Guid("7632f0e6-9538-4d61-acda-ea29c8c14456");
	}
	public static class MediaFoundationErrors
	{
		public const int MF_E_PLATFORM_NOT_INITIALIZED = -1072875856;

		public const int MF_E_BUFFERTOOSMALL = -1072875855;

		public const int MF_E_INVALIDREQUEST = -1072875854;

		public const int MF_E_INVALIDSTREAMNUMBER = -1072875853;

		public const int MF_E_INVALIDMEDIATYPE = -1072875852;

		public const int MF_E_NOTACCEPTING = -1072875851;

		public const int MF_E_NOT_INITIALIZED = -1072875850;

		public const int MF_E_UNSUPPORTED_REPRESENTATION = -1072875849;

		public const int MF_E_NO_MORE_TYPES = -1072875847;

		public const int MF_E_UNSUPPORTED_SERVICE = -1072875846;

		public const int MF_E_UNEXPECTED = -1072875845;

		public const int MF_E_INVALIDNAME = -1072875844;

		public const int MF_E_INVALIDTYPE = -1072875843;

		public const int MF_E_INVALID_FILE_FORMAT = -1072875842;

		public const int MF_E_INVALIDINDEX = -1072875841;

		public const int MF_E_INVALID_TIMESTAMP = -1072875840;

		public const int MF_E_UNSUPPORTED_SCHEME = -1072875837;

		public const int MF_E_UNSUPPORTED_BYTESTREAM_TYPE = -1072875836;

		public const int MF_E_UNSUPPORTED_TIME_FORMAT = -1072875835;

		public const int MF_E_NO_SAMPLE_TIMESTAMP = -1072875832;

		public const int MF_E_NO_SAMPLE_DURATION = -1072875831;

		public const int MF_E_INVALID_STREAM_DATA = -1072875829;

		public const int MF_E_RT_UNAVAILABLE = -1072875825;

		public const int MF_E_UNSUPPORTED_RATE = -1072875824;

		public const int MF_E_THINNING_UNSUPPORTED = -1072875823;

		public const int MF_E_REVERSE_UNSUPPORTED = -1072875822;

		public const int MF_E_UNSUPPORTED_RATE_TRANSITION = -1072875821;

		public const int MF_E_RATE_CHANGE_PREEMPTED = -1072875820;

		public const int MF_E_NOT_FOUND = -1072875819;

		public const int MF_E_NOT_AVAILABLE = -1072875818;

		public const int MF_E_NO_CLOCK = -1072875817;

		public const int MF_S_MULTIPLE_BEGIN = 866008;

		public const int MF_E_MULTIPLE_BEGIN = -1072875815;

		public const int MF_E_MULTIPLE_SUBSCRIBERS = -1072875814;

		public const int MF_E_TIMER_ORPHANED = -1072875813;

		public const int MF_E_STATE_TRANSITION_PENDING = -1072875812;

		public const int MF_E_UNSUPPORTED_STATE_TRANSITION = -1072875811;

		public const int MF_E_UNRECOVERABLE_ERROR_OCCURRED = -1072875810;

		public const int MF_E_SAMPLE_HAS_TOO_MANY_BUFFERS = -1072875809;

		public const int MF_E_SAMPLE_NOT_WRITABLE = -1072875808;

		public const int MF_E_INVALID_KEY = -1072875806;

		public const int MF_E_BAD_STARTUP_VERSION = -1072875805;

		public const int MF_E_UNSUPPORTED_CAPTION = -1072875804;

		public const int MF_E_INVALID_POSITION = -1072875803;

		public const int MF_E_ATTRIBUTENOTFOUND = -1072875802;

		public const int MF_E_PROPERTY_TYPE_NOT_ALLOWED = -1072875801;

		public const int MF_E_PROPERTY_TYPE_NOT_SUPPORTED = -1072875800;

		public const int MF_E_PROPERTY_EMPTY = -1072875799;

		public const int MF_E_PROPERTY_NOT_EMPTY = -1072875798;

		public const int MF_E_PROPERTY_VECTOR_NOT_ALLOWED = -1072875797;

		public const int MF_E_PROPERTY_VECTOR_REQUIRED = -1072875796;

		public const int MF_E_OPERATION_CANCELLED = -1072875795;

		public const int MF_E_BYTESTREAM_NOT_SEEKABLE = -1072875794;

		public const int MF_E_DISABLED_IN_SAFEMODE = -1072875793;

		public const int MF_E_CANNOT_PARSE_BYTESTREAM = -1072875792;

		public const int MF_E_SOURCERESOLVER_MUTUALLY_EXCLUSIVE_FLAGS = -1072875791;

		public const int MF_E_MEDIAPROC_WRONGSTATE = -1072875790;

		public const int MF_E_RT_THROUGHPUT_NOT_AVAILABLE = -1072875789;

		public const int MF_E_RT_TOO_MANY_CLASSES = -1072875788;

		public const int MF_E_RT_WOULDBLOCK = -1072875787;

		public const int MF_E_NO_BITPUMP = -1072875786;

		public const int MF_E_RT_OUTOFMEMORY = -1072875785;

		public const int MF_E_RT_WORKQUEUE_CLASS_NOT_SPECIFIED = -1072875784;

		public const int MF_E_INSUFFICIENT_BUFFER = -1072860816;

		public const int MF_E_CANNOT_CREATE_SINK = -1072875782;

		public const int MF_E_BYTESTREAM_UNKNOWN_LENGTH = -1072875781;

		public const int MF_E_SESSION_PAUSEWHILESTOPPED = -1072875780;

		public const int MF_S_ACTIVATE_REPLACED = 866045;

		public const int MF_E_FORMAT_CHANGE_NOT_SUPPORTED = -1072875778;

		public const int MF_E_INVALID_WORKQUEUE = -1072875777;

		public const int MF_E_DRM_UNSUPPORTED = -1072875776;

		public const int MF_E_UNAUTHORIZED = -1072875775;

		public const int MF_E_OUT_OF_RANGE = -1072875774;

		public const int MF_E_INVALID_CODEC_MERIT = -1072875773;

		public const int MF_E_HW_MFT_FAILED_START_STREAMING = -1072875772;

		public const int MF_S_ASF_PARSEINPROGRESS = 1074608792;

		public const int MF_E_ASF_PARSINGINCOMPLETE = -1072874856;

		public const int MF_E_ASF_MISSINGDATA = -1072874855;

		public const int MF_E_ASF_INVALIDDATA = -1072874854;

		public const int MF_E_ASF_OPAQUEPACKET = -1072874853;

		public const int MF_E_ASF_NOINDEX = -1072874852;

		public const int MF_E_ASF_OUTOFRANGE = -1072874851;

		public const int MF_E_ASF_INDEXNOTLOADED = -1072874850;

		public const int MF_E_ASF_TOO_MANY_PAYLOADS = -1072874849;

		public const int MF_E_ASF_UNSUPPORTED_STREAM_TYPE = -1072874848;

		public const int MF_E_ASF_DROPPED_PACKET = -1072874847;

		public const int MF_E_NO_EVENTS_AVAILABLE = -1072873856;

		public const int MF_E_INVALID_STATE_TRANSITION = -1072873854;

		public const int MF_E_END_OF_STREAM = -1072873852;

		public const int MF_E_SHUTDOWN = -1072873851;

		public const int MF_E_MP3_NOTFOUND = -1072873850;

		public const int MF_E_MP3_OUTOFDATA = -1072873849;

		public const int MF_E_MP3_NOTMP3 = -1072873848;

		public const int MF_E_MP3_NOTSUPPORTED = -1072873847;

		public const int MF_E_NO_DURATION = -1072873846;

		public const int MF_E_INVALID_FORMAT = -1072873844;

		public const int MF_E_PROPERTY_NOT_FOUND = -1072873843;

		public const int MF_E_PROPERTY_READ_ONLY = -1072873842;

		public const int MF_E_PROPERTY_NOT_ALLOWED = -1072873841;

		public const int MF_E_MEDIA_SOURCE_NOT_STARTED = -1072873839;

		public const int MF_E_UNSUPPORTED_FORMAT = -1072873832;

		public const int MF_E_MP3_BAD_CRC = -1072873831;

		public const int MF_E_NOT_PROTECTED = -1072873830;

		public const int MF_E_MEDIA_SOURCE_WRONGSTATE = -1072873829;

		public const int MF_E_MEDIA_SOURCE_NO_STREAMS_SELECTED = -1072873828;

		public const int MF_E_CANNOT_FIND_KEYFRAME_SAMPLE = -1072873827;

		public const int MF_E_NETWORK_RESOURCE_FAILURE = -1072872856;

		public const int MF_E_NET_WRITE = -1072872855;

		public const int MF_E_NET_READ = -1072872854;

		public const int MF_E_NET_REQUIRE_NETWORK = -1072872853;

		public const int MF_E_NET_REQUIRE_ASYNC = -1072872852;

		public const int MF_E_NET_BWLEVEL_NOT_SUPPORTED = -1072872851;

		public const int MF_E_NET_STREAMGROUPS_NOT_SUPPORTED = -1072872850;

		public const int MF_E_NET_MANUALSS_NOT_SUPPORTED = -1072872849;

		public const int MF_E_NET_INVALID_PRESENTATION_DESCRIPTOR = -1072872848;

		public const int MF_E_NET_CACHESTREAM_NOT_FOUND = -1072872847;

		public const int MF_I_MANUAL_PROXY = 1074610802;

		public const int MF_E_NET_REQUIRE_INPUT = -1072872844;

		public const int MF_E_NET_REDIRECT = -1072872843;

		public const int MF_E_NET_REDIRECT_TO_PROXY = -1072872842;

		public const int MF_E_NET_TOO_MANY_REDIRECTS = -1072872841;

		public const int MF_E_NET_TIMEOUT = -1072872840;

		public const int MF_E_NET_CLIENT_CLOSE = -1072872839;

		public const int MF_E_NET_BAD_CONTROL_DATA = -1072872838;

		public const int MF_E_NET_INCOMPATIBLE_SERVER = -1072872837;

		public const int MF_E_NET_UNSAFE_URL = -1072872836;

		public const int MF_E_NET_CACHE_NO_DATA = -1072872835;

		public const int MF_E_NET_EOL = -1072872834;

		public const int MF_E_NET_BAD_REQUEST = -1072872833;

		public const int MF_E_NET_INTERNAL_SERVER_ERROR = -1072872832;

		public const int MF_E_NET_SESSION_NOT_FOUND = -1072872831;

		public const int MF_E_NET_NOCONNECTION = -1072872830;

		public const int MF_E_NET_CONNECTION_FAILURE = -1072872829;

		public const int MF_E_NET_INCOMPATIBLE_PUSHSERVER = -1072872828;

		public const int MF_E_NET_SERVER_ACCESSDENIED = -1072872827;

		public const int MF_E_NET_PROXY_ACCESSDENIED = -1072872826;

		public const int MF_E_NET_CANNOTCONNECT = -1072872825;

		public const int MF_E_NET_INVALID_PUSH_TEMPLATE = -1072872824;

		public const int MF_E_NET_INVALID_PUSH_PUBLISHING_POINT = -1072872823;

		public const int MF_E_NET_BUSY = -1072872822;

		public const int MF_E_NET_RESOURCE_GONE = -1072872821;

		public const int MF_E_NET_ERROR_FROM_PROXY = -1072872820;

		public const int MF_E_NET_PROXY_TIMEOUT = -1072872819;

		public const int MF_E_NET_SERVER_UNAVAILABLE = -1072872818;

		public const int MF_E_NET_TOO_MUCH_DATA = -1072872817;

		public const int MF_E_NET_SESSION_INVALID = -1072872816;

		public const int MF_E_OFFLINE_MODE = -1072872815;

		public const int MF_E_NET_UDP_BLOCKED = -1072872814;

		public const int MF_E_NET_UNSUPPORTED_CONFIGURATION = -1072872813;

		public const int MF_E_NET_PROTOCOL_DISABLED = -1072872812;

		public const int MF_E_ALREADY_INITIALIZED = -1072871856;

		public const int MF_E_BANDWIDTH_OVERRUN = -1072871855;

		public const int MF_E_LATE_SAMPLE = -1072871854;

		public const int MF_E_FLUSH_NEEDED = -1072871853;

		public const int MF_E_INVALID_PROFILE = -1072871852;

		public const int MF_E_INDEX_NOT_COMMITTED = -1072871851;

		public const int MF_E_NO_INDEX = -1072871850;

		public const int MF_E_CANNOT_INDEX_IN_PLACE = -1072871849;

		public const int MF_E_MISSING_ASF_LEAKYBUCKET = -1072871848;

		public const int MF_E_INVALID_ASF_STREAMID = -1072871847;

		public const int MF_E_STREAMSINK_REMOVED = -1072870856;

		public const int MF_E_STREAMSINKS_OUT_OF_SYNC = -1072870854;

		public const int MF_E_STREAMSINKS_FIXED = -1072870853;

		public const int MF_E_STREAMSINK_EXISTS = -1072870852;

		public const int MF_E_SAMPLEALLOCATOR_CANCELED = -1072870851;

		public const int MF_E_SAMPLEALLOCATOR_EMPTY = -1072870850;

		public const int MF_E_SINK_ALREADYSTOPPED = -1072870849;

		public const int MF_E_ASF_FILESINK_BITRATE_UNKNOWN = -1072870848;

		public const int MF_E_SINK_NO_STREAMS = -1072870847;

		public const int MF_S_SINK_NOT_FINALIZED = 870978;

		public const int MF_E_METADATA_TOO_LONG = -1072870845;

		public const int MF_E_SINK_NO_SAMPLES_PROCESSED = -1072870844;

		public const int MF_E_VIDEO_REN_NO_PROCAMP_HW = -1072869856;

		public const int MF_E_VIDEO_REN_NO_DEINTERLACE_HW = -1072869855;

		public const int MF_E_VIDEO_REN_COPYPROT_FAILED = -1072869854;

		public const int MF_E_VIDEO_REN_SURFACE_NOT_SHARED = -1072869853;

		public const int MF_E_VIDEO_DEVICE_LOCKED = -1072869852;

		public const int MF_E_NEW_VIDEO_DEVICE = -1072869851;

		public const int MF_E_NO_VIDEO_SAMPLE_AVAILABLE = -1072869850;

		public const int MF_E_NO_AUDIO_PLAYBACK_DEVICE = -1072869756;

		public const int MF_E_AUDIO_PLAYBACK_DEVICE_IN_USE = -1072869755;

		public const int MF_E_AUDIO_PLAYBACK_DEVICE_INVALIDATED = -1072869754;

		public const int MF_E_AUDIO_SERVICE_NOT_RUNNING = -1072869753;

		public const int MF_E_TOPO_INVALID_OPTIONAL_NODE = -1072868850;

		public const int MF_E_TOPO_CANNOT_FIND_DECRYPTOR = -1072868847;

		public const int MF_E_TOPO_CODEC_NOT_FOUND = -1072868846;

		public const int MF_E_TOPO_CANNOT_CONNECT = -1072868845;

		public const int MF_E_TOPO_UNSUPPORTED = -1072868844;

		public const int MF_E_TOPO_INVALID_TIME_ATTRIBUTES = -1072868843;

		public const int MF_E_TOPO_LOOPS_IN_TOPOLOGY = -1072868842;

		public const int MF_E_TOPO_MISSING_PRESENTATION_DESCRIPTOR = -1072868841;

		public const int MF_E_TOPO_MISSING_STREAM_DESCRIPTOR = -1072868840;

		public const int MF_E_TOPO_STREAM_DESCRIPTOR_NOT_SELECTED = -1072868839;

		public const int MF_E_TOPO_MISSING_SOURCE = -1072868838;

		public const int MF_E_TOPO_SINK_ACTIVATES_UNSUPPORTED = -1072868837;

		public const int MF_E_SEQUENCER_UNKNOWN_SEGMENT_ID = -1072864852;

		public const int MF_S_SEQUENCER_CONTEXT_CANCELED = 876973;

		public const int MF_E_NO_SOURCE_IN_CACHE = -1072864850;

		public const int MF_S_SEQUENCER_SEGMENT_AT_END_OF_STREAM = 876975;

		public const int MF_E_TRANSFORM_TYPE_NOT_SET = -1072861856;

		public const int MF_E_TRANSFORM_STREAM_CHANGE = -1072861855;

		public const int MF_E_TRANSFORM_INPUT_REMAINING = -1072861854;

		public const int MF_E_TRANSFORM_PROFILE_MISSING = -1072861853;

		public const int MF_E_TRANSFORM_PROFILE_INVALID_OR_CORRUPT = -1072861852;

		public const int MF_E_TRANSFORM_PROFILE_TRUNCATED = -1072861851;

		public const int MF_E_TRANSFORM_PROPERTY_PID_NOT_RECOGNIZED = -1072861850;

		public const int MF_E_TRANSFORM_PROPERTY_VARIANT_TYPE_WRONG = -1072861849;

		public const int MF_E_TRANSFORM_PROPERTY_NOT_WRITEABLE = -1072861848;

		public const int MF_E_TRANSFORM_PROPERTY_ARRAY_VALUE_WRONG_NUM_DIM = -1072861847;

		public const int MF_E_TRANSFORM_PROPERTY_VALUE_SIZE_WRONG = -1072861846;

		public const int MF_E_TRANSFORM_PROPERTY_VALUE_OUT_OF_RANGE = -1072861845;

		public const int MF_E_TRANSFORM_PROPERTY_VALUE_INCOMPATIBLE = -1072861844;

		public const int MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_OUTPUT_MEDIATYPE = -1072861843;

		public const int MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_INPUT_MEDIATYPE = -1072861842;

		public const int MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_MEDIATYPE_COMBINATION = -1072861841;

		public const int MF_E_TRANSFORM_CONFLICTS_WITH_OTHER_CURRENTLY_ENABLED_FEATURES = -1072861840;

		public const int MF_E_TRANSFORM_NEED_MORE_INPUT = -1072861838;

		public const int MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_SPKR_CONFIG = -1072861837;

		public const int MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING = -1072861836;

		public const int MF_S_TRANSFORM_DO_NOT_PROPAGATE_EVENT = 879989;

		public const int MF_E_UNSUPPORTED_D3D_TYPE = -1072861834;

		public const int MF_E_TRANSFORM_ASYNC_LOCKED = -1072861833;

		public const int MF_E_TRANSFORM_CANNOT_INITIALIZE_ACM_DRIVER = -1072861832;

		public const int MF_E_LICENSE_INCORRECT_RIGHTS = -1072860856;

		public const int MF_E_LICENSE_OUTOFDATE = -1072860855;

		public const int MF_E_LICENSE_REQUIRED = -1072860854;

		public const int MF_E_DRM_HARDWARE_INCONSISTENT = -1072860853;

		public const int MF_E_NO_CONTENT_PROTECTION_MANAGER = -1072860852;

		public const int MF_E_LICENSE_RESTORE_NO_RIGHTS = -1072860851;

		public const int MF_E_BACKUP_RESTRICTED_LICENSE = -1072860850;

		public const int MF_E_LICENSE_RESTORE_NEEDS_INDIVIDUALIZATION = -1072860849;

		public const int MF_S_PROTECTION_NOT_REQUIRED = 880976;

		public const int MF_E_COMPONENT_REVOKED = -1072860847;

		public const int MF_E_TRUST_DISABLED = -1072860846;

		public const int MF_E_WMDRMOTA_NO_ACTION = -1072860845;

		public const int MF_E_WMDRMOTA_ACTION_ALREADY_SET = -1072860844;

		public const int MF_E_WMDRMOTA_DRM_HEADER_NOT_AVAILABLE = -1072860843;

		public const int MF_E_WMDRMOTA_DRM_ENCRYPTION_SCHEME_NOT_SUPPORTED = -1072860842;

		public const int MF_E_WMDRMOTA_ACTION_MISMATCH = -1072860841;

		public const int MF_E_WMDRMOTA_INVALID_POLICY = -1072860840;

		public const int MF_E_POLICY_UNSUPPORTED = -1072860839;

		public const int MF_E_OPL_NOT_SUPPORTED = -1072860838;

		public const int MF_E_TOPOLOGY_VERIFICATION_FAILED = -1072860837;

		public const int MF_E_SIGNATURE_VERIFICATION_FAILED = -1072860836;

		public const int MF_E_DEBUGGING_NOT_ALLOWED = -1072860835;

		public const int MF_E_CODE_EXPIRED = -1072860834;

		public const int MF_E_GRL_VERSION_TOO_LOW = -1072860833;

		public const int MF_E_GRL_RENEWAL_NOT_FOUND = -1072860832;

		public const int MF_E_GRL_EXTENSIBLE_ENTRY_NOT_FOUND = -1072860831;

		public const int MF_E_KERNEL_UNTRUSTED = -1072860830;

		public const int MF_E_PEAUTH_UNTRUSTED = -1072860829;

		public const int MF_E_NON_PE_PROCESS = -1072860827;

		public const int MF_E_REBOOT_REQUIRED = -1072860825;

		public const int MF_S_WAIT_FOR_POLICY_SET = 881000;

		public const int MF_S_VIDEO_DISABLED_WITH_UNKNOWN_SOFTWARE_OUTPUT = 881001;

		public const int MF_E_GRL_INVALID_FORMAT = -1072860822;

		public const int MF_E_GRL_UNRECOGNIZED_FORMAT = -1072860821;

		public const int MF_E_ALL_PROCESS_RESTART_REQUIRED = -1072860820;

		public const int MF_E_PROCESS_RESTART_REQUIRED = -1072860819;

		public const int MF_E_USERMODE_UNTRUSTED = -1072860818;

		public const int MF_E_PEAUTH_SESSION_NOT_STARTED = -1072860817;

		public const int MF_E_PEAUTH_PUBLICKEY_REVOKED = -1072860815;

		public const int MF_E_GRL_ABSENT = -1072860814;

		public const int MF_S_PE_TRUSTED = 881011;

		public const int MF_E_PE_UNTRUSTED = -1072860812;

		public const int MF_E_PEAUTH_NOT_STARTED = -1072860811;

		public const int MF_E_INCOMPATIBLE_SAMPLE_PROTECTION = -1072860810;

		public const int MF_E_PE_SESSIONS_MAXED = -1072860809;

		public const int MF_E_HIGH_SECURITY_LEVEL_CONTENT_NOT_ALLOWED = -1072860808;

		public const int MF_E_TEST_SIGNED_COMPONENTS_NOT_ALLOWED = -1072860807;

		public const int MF_E_ITA_UNSUPPORTED_ACTION = -1072860806;

		public const int MF_E_ITA_ERROR_PARSING_SAP_PARAMETERS = -1072860805;

		public const int MF_E_POLICY_MGR_ACTION_OUTOFBOUNDS = -1072860804;

		public const int MF_E_BAD_OPL_STRUCTURE_FORMAT = -1072860803;

		public const int MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_PROTECTION_GUID = -1072860802;

		public const int MF_E_NO_PMP_HOST = -1072860801;

		public const int MF_E_ITA_OPL_DATA_NOT_INITIALIZED = -1072860800;

		public const int MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_OUTPUT = -1072860799;

		public const int MF_E_ITA_UNRECOGNIZED_DIGITAL_VIDEO_OUTPUT = -1072860798;

		public const int MF_E_CLOCK_INVALID_CONTINUITY_KEY = -1072849856;

		public const int MF_E_CLOCK_NO_TIME_SOURCE = -1072849855;

		public const int MF_E_CLOCK_STATE_ALREADY_SET = -1072849854;

		public const int MF_E_CLOCK_NOT_SIMPLE = -1072849853;

		public const int MF_S_CLOCK_STOPPED = 891972;

		public const int MF_E_NO_MORE_DROP_MODES = -1072848856;

		public const int MF_E_NO_MORE_QUALITY_LEVELS = -1072848855;

		public const int MF_E_DROPTIME_NOT_SUPPORTED = -1072848854;

		public const int MF_E_QUALITYKNOB_WAIT_LONGER = -1072848853;

		public const int MF_E_QM_INVALIDSTATE = -1072848852;

		public const int MF_E_TRANSCODE_NO_CONTAINERTYPE = -1072847856;

		public const int MF_E_TRANSCODE_PROFILE_NO_MATCHING_STREAMS = -1072847855;

		public const int MF_E_TRANSCODE_NO_MATCHING_ENCODER = -1072847854;

		public const int MF_E_ALLOCATOR_NOT_INITIALIZED = -1072846856;

		public const int MF_E_ALLOCATOR_NOT_COMMITED = -1072846855;

		public const int MF_E_ALLOCATOR_ALREADY_COMMITED = -1072846854;

		public const int MF_E_STREAM_ERROR = -1072846853;

		public const int MF_E_INVALID_STREAM_STATE = -1072846852;

		public const int MF_E_HW_STREAM_NOT_CONNECTED = -1072846851;
	}
	public static class MediaFoundationApi
	{
		private static bool initialized;

		public static void Startup()
		{
			if (!initialized)
			{
				int num = 2;
				OperatingSystem oSVersion = Environment.OSVersion;
				if (oSVersion.Version.Major == 6 && oSVersion.Version.Minor == 0)
				{
					num = 1;
				}
				MediaFoundationInterop.MFStartup((num << 16) | 0x70);
				initialized = true;
			}
		}

		public static IEnumerable<IMFActivate> EnumerateTransforms(Guid category)
		{
			MediaFoundationInterop.MFTEnumEx(category, _MFT_ENUM_FLAG.MFT_ENUM_FLAG_ALL, null, null, out var interfacesPointer, out var pcMFTActivate);
			IMFActivate[] array = new IMFActivate[pcMFTActivate];
			for (int i = 0; i < pcMFTActivate; i++)
			{
				IntPtr pUnk = Marshal.ReadIntPtr(new IntPtr(interfacesPointer.ToInt64() + i * Marshal.SizeOf(interfacesPointer)));
				array[i] = (IMFActivate)Marshal.GetObjectForIUnknown(pUnk);
			}
			IMFActivate[] array2 = array;
			for (int j = 0; j < array2.Length; j++)
			{
				yield return array2[j];
			}
			Marshal.FreeCoTaskMem(interfacesPointer);
		}

		public static void Shutdown()
		{
			if (initialized)
			{
				MediaFoundationInterop.MFShutdown();
				initialized = false;
			}
		}

		public static IMFMediaType CreateMediaType()
		{
			MediaFoundationInterop.MFCreateMediaType(out var ppMFType);
			return ppMFType;
		}

		public static IMFMediaType CreateMediaTypeFromWaveFormat(WaveFormat waveFormat)
		{
			IMFMediaType iMFMediaType = CreateMediaType();
			try
			{
				MediaFoundationInterop.MFInitMediaTypeFromWaveFormatEx(iMFMediaType, waveFormat, Marshal.SizeOf<WaveFormat>(waveFormat));
				return iMFMediaType;
			}
			catch (Exception)
			{
				Marshal.ReleaseComObject(iMFMediaType);
				throw;
			}
		}

		public static IMFMediaBuffer CreateMemoryBuffer(int bufferSize)
		{
			MediaFoundationInterop.MFCreateMemoryBuffer(bufferSize, out var ppBuffer);
			return ppBuffer;
		}

		public static IMFSample CreateSample()
		{
			MediaFoundationInterop.MFCreateSample(out var ppIMFSample);
			return ppIMFSample;
		}

		public static IMFAttributes CreateAttributes(int initialSize)
		{
			MediaFoundationInterop.MFCreateAttributes(out var ppMFAttributes, initialSize);
			return ppMFAttributes;
		}

		public static IMFByteStream CreateByteStream(object stream)
		{
			if (stream is IStream)
			{
				MediaFoundationInterop.MFCreateMFByteStreamOnStream(stream as IStream, out var ppByteStream);
				return ppByteStream;
			}
			throw new ArgumentException("Stream must be IStream in desktop apps");
		}

		public static IMFSourceReader CreateSourceReaderFromByteStream(IMFByteStream byteStream)
		{
			MediaFoundationInterop.MFCreateSourceReaderFromByteStream(byteStream, null, out var ppSourceReader);
			return ppSourceReader;
		}
	}
	public static class MediaFoundationInterop
	{
		public const int MF_SOURCE_READER_ALL_STREAMS = -2;

		public const int MF_SOURCE_READER_FIRST_AUDIO_STREAM = -3;

		public const int MF_SOURCE_READER_FIRST_VIDEO_STREAM = -4;

		public const int MF_SOURCE_READER_MEDIASOURCE = -1;

		public const int MF_SDK_VERSION = 2;

		public const int MF_API_VERSION = 112;

		public const int MF_VERSION = 131184;

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void MFStartup(int version, int dwFlags = 0);

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void MFShutdown();

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		internal static extern void MFCreateMediaType(out IMFMediaType ppMFType);

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		internal static extern void MFInitMediaTypeFromWaveFormatEx([In] IMFMediaType pMFType, [In] WaveFormat pWaveFormat, [In] int cbBufSize);

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		internal static extern void MFCreateWaveFormatExFromMFMediaType(IMFMediaType pMFType, ref IntPtr ppWF, ref int pcbSize, int flags = 0);

		[DllImport("mfreadwrite.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void MFCreateSourceReaderFromURL([In][MarshalAs(UnmanagedType.LPWStr)] string pwszURL, [In] IMFAttributes pAttributes, [MarshalAs(UnmanagedType.Interface)] out IMFSourceReader ppSourceReader);

		[DllImport("mfreadwrite.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void MFCreateSourceReaderFromByteStream([In] IMFByteStream pByteStream, [In] IMFAttributes pAttributes, [MarshalAs(UnmanagedType.Interface)] out IMFSourceReader ppSourceReader);

		[DllImport("mfreadwrite.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void MFCreateSinkWriterFromURL([In][MarshalAs(UnmanagedType.LPWStr)] string pwszOutputURL, [In] IMFByteStream pByteStream, [In] IMFAttributes pAttributes, out IMFSinkWriter ppSinkWriter);

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void MFCreateMFByteStreamOnStream([In] IStream punkStream, out IMFByteStream ppByteStream);

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void MFTEnumEx([In] Guid guidCategory, [In] _MFT_ENUM_FLAG flags, [In] MFT_REGISTER_TYPE_INFO pInputType, [In] MFT_REGISTER_TYPE_INFO pOutputType, out IntPtr pppMFTActivate, out int pcMFTActivate);

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		internal static extern void MFCreateSample(out IMFSample ppIMFSample);

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		internal static extern void MFCreateMemoryBuffer(int cbMaxLength, out IMFMediaBuffer ppBuffer);

		[DllImport("mfplat.dll", ExactSpelling = true, PreserveSig = false)]
		internal static extern void MFCreateAttributes([MarshalAs(UnmanagedType.Interface)] out IMFAttributes ppMFAttributes, [In] int cInitialSize);

		[DllImport("mf.dll", ExactSpelling = true, PreserveSig = false)]
		public static extern void MFTranscodeGetAudioOutputAvailableTypes([In][MarshalAs(UnmanagedType.LPStruct)] Guid guidSubType, [In] _MFT_ENUM_FLAG dwMFTFlags, [In] IMFAttributes pCodecConfig, [MarshalAs(UnmanagedType.Interface)] out IMFCollection ppAvailableTypes);
	}
	public abstract class MediaFoundationTransform : IWaveProvider, IDisposable
	{
		protected readonly IWaveProvider sourceProvider;

		protected readonly WaveFormat outputWaveFormat;

		private readonly byte[] sourceBuffer;

		private byte[] outputBuffer;

		private int outputBufferOffset;

		private int outputBufferCount;

		private IMFTransform transform;

		private bool disposed;

		private long inputPosition;

		private long outputPosition;

		private bool initializedForStreaming;

		public WaveFormat WaveFormat => outputWaveFormat;

		public MediaFoundationTransform(IWaveProvider sourceProvider, WaveFormat outputFormat)
		{
			outputWaveFormat = outputFormat;
			this.sourceProvider = sourceProvider;
			sourceBuffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond];
			outputBuffer = new byte[outputWaveFormat.AverageBytesPerSecond + outputWaveFormat.BlockAlign];
		}

		private void InitializeTransformForStreaming()
		{
			transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_COMMAND_FLUSH, IntPtr.Zero);
			transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, IntPtr.Zero);
			transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_NOTIFY_START_OF_STREAM, IntPtr.Zero);
			initializedForStreaming = true;
		}

		protected abstract IMFTransform CreateTransform();

		protected virtual void Dispose(bool disposing)
		{
			if (transform != null)
			{
				Marshal.ReleaseComObject(transform);
			}
		}

		public void Dispose()
		{
			if (!disposed)
			{
				disposed = true;
				Dispose(disposing: true);
				GC.SuppressFinalize(this);
			}
		}

		~MediaFoundationTransform()
		{
			Dispose(disposing: false);
		}

		public int Read(byte[] buffer, int offset, int count)
		{
			if (transform == null)
			{
				transform = CreateTransform();
				InitializeTransformForStreaming();
			}
			int i = 0;
			if (outputBufferCount > 0)
			{
				i += ReadFromOutputBuffer(buffer, offset, count - i);
			}
			for (; i < count; i += ReadFromOutputBuffer(buffer, offset + i, count - i))
			{
				IMFSample iMFSample = ReadFromSource();
				if (iMFSample == null)
				{
					EndStreamAndDrain();
					i += ReadFromOutputBuffer(buffer, offset + i, count - i);
					ClearOutputBuffer();
					break;
				}
				if (!initializedForStreaming)
				{
					InitializeTransformForStreaming();
				}
				transform.ProcessInput(0, iMFSample, 0);
				Marshal.ReleaseComObject(iMFSample);
				ReadFromTransform();
			}
			return i;
		}

		private void EndStreamAndDrain()
		{
			transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_NOTIFY_END_OF_STREAM, IntPtr.Zero);
			transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_COMMAND_DRAIN, IntPtr.Zero);
			int num;
			do
			{
				num = ReadFromTransform();
			}
			while (num > 0);
			inputPosition = 0L;
			outputPosition = 0L;
			transform.ProcessMessage(MFT_MESSAGE_TYPE.MFT_MESSAGE_NOTIFY_END_STREAMING, IntPtr.Zero);
			initializedForStreaming = false;
		}

		private void ClearOutputBuffer()
		{
			outputBufferCount = 0;
			outputBufferOffset = 0;
		}

		private int ReadFromTransform()
		{
			MFT_OUTPUT_DATA_BUFFER[] array = new MFT_OUTPUT_DATA_BUFFER[1];
			IMFSample iMFSample = MediaFoundationApi.CreateSample();
			IMFMediaBuffer iMFMediaBuffer = MediaFoundationApi.CreateMemoryBuffer(outputBuffer.Length);
			iMFSample.AddBuffer(iMFMediaBuffer);
			iMFSample.SetSampleTime(outputPosition);
			array[0].pSample = iMFSample;
			_MFT_PROCESS_OUTPUT_STATUS pdwStatus;
			int num = transform.ProcessOutput(_MFT_PROCESS_OUTPUT_FLAGS.None, 1, array, out pdwStatus);
			switch (num)
			{
			case -1072861838:
				Marshal.ReleaseComObject(iMFMediaBuffer);
				Marshal.ReleaseComObject(iMFSample);
				return 0;
			default:
				Marshal.ThrowExceptionForHR(num);
				break;
			case 0:
				break;
			}
			array[0].pSample.ConvertToContiguousBuffer(out var ppBuffer);
			ppBuffer.Lock(out var ppbBuffer, out var _, out var pcbCurrentLength);
			outputBuffer = BufferHelpers.Ensure(outputBuffer, pcbCurrentLength);
			Marshal.Copy(ppbBuffer, outputBuffer, 0, pcbCurrentLength);
			outputBufferOffset = 0;
			outputBufferCount = pcbCurrentLength;
			ppBuffer.Unlock();
			outputPosition += BytesToNsPosition(outputBufferCount, WaveFormat);
			Marshal.ReleaseComObject(iMFMediaBuffer);
			iMFSample.RemoveAllBuffers();
			Marshal.ReleaseComObject(iMFSample);
			Marshal.ReleaseComObject(ppBuffer);
			return pcbCurrentLength;
		}

		private static long BytesToNsPosition(int bytes, WaveFormat waveFormat)
		{
			return 10000000L * (long)bytes / waveFormat.AverageBytesPerSecond;
		}

		private IMFSample ReadFromSource()
		{
			int num = sourceProvider.Read(sourceBuffer, 0, sourceBuffer.Length);
			if (num == 0)
			{
				return null;
			}
			IMFMediaBuffer iMFMediaBuffer = MediaFoundationApi.CreateMemoryBuffer(num);
			iMFMediaBuffer.Lock(out var ppbBuffer, out var _, out var _);
			Marshal.Copy(sourceBuffer, 0, ppbBuffer, num);
			iMFMediaBuffer.Unlock();
			iMFMediaBuffer.SetCurrentLength(num);
			IMFSample iMFSample = MediaFoundationApi.CreateSample();
			iMFSample.AddBuffer(iMFMediaBuffer);
			iMFSample.SetSampleTime(inputPosition);
			long num2 = BytesToNsPosition(num, sourceProvider.WaveFormat);
			iMFSample.SetSampleDuration(num2);
			inputPosition += num2;
			Marshal.ReleaseComObject(iMFMediaBuffer);
			return iMFSample;
		}

		private int ReadFromOutputBuffer(byte[] buffer, int offset, int needed)
		{
			int num = Math.Min(needed, outputBufferCount);
			Array.Copy(outputBuffer, outputBufferOffset, buffer, offset, num);
			outputBufferOffset += num;
			outputBufferCount -= num;
			if (outputBufferCount == 0)
			{
				outputBufferOffset = 0;
			}
			return num;
		}

		public void Reposition()
		{
			if (initializedForStreaming)
			{
				EndStreamAndDrain();
				ClearOutputBuffer();
				InitializeTransformForStreaming();
			}
		}
	}
	public static class MediaFoundationTransformCategories
	{
		[FieldDescription("Video Decoder")]
		public static readonly Guid VideoDecoder = new Guid("{d6c02d4b-6833-45b4-971a-05a4b04bab91}");

		[FieldDescription("Video Encoder")]
		public static readonly Guid VideoEncoder = new Guid("{f79eac7d-e545-4387-bdee-d647d7bde42a}");

		[FieldDescription("Video Effect")]
		public static readonly Guid VideoEffect = new Guid("{12e17c21-532c-4a6e-8a1c-40825a736397}");

		[FieldDescription("Multiplexer")]
		public static readonly Guid Multiplexer = new Guid("{059c561e-05ae-4b61-b69d-55b61ee54a7b}");

		[FieldDescription("Demultiplexer")]
		public static readonly Guid Demultiplexer = new Guid("{a8700a7a-939b-44c5-99d7-76226b23b3f1}");

		[FieldDescription("Audio Decoder")]
		public static readonly Guid AudioDecoder = new Guid("{9ea73fb4-ef7a-4559-8d5d-719d8f0426c7}");

		[FieldDescription("Audio Encoder")]
		public static readonly Guid AudioEncoder = new Guid("{91c64bd0-f91e-4d8c-9276-db248279d975}");

		[FieldDescription("Audio Effect")]
		public static readonly Guid AudioEffect = new Guid("{11064c48-3648-4ed0-932e-05ce8ac811b7}");

		[FieldDescription("Video Processor")]
		public static readonly Guid VideoProcessor = new Guid("{302EA3FC-AA5F-47f9-9F7A-C2188BB16302}");

		[FieldDescription("Other")]
		public static readonly Guid Other = new Guid("{90175d57-b7ea-4901-aeb3-933a8747756f}");
	}
	public class MediaType
	{
		private readonly IMFMediaType mediaType;

		public int SampleRate
		{
			get
			{
				return GetUInt32(MediaFoundationAttributes.MF_MT_AUDIO_SAMPLES_PER_SECOND);
			}
			set
			{
				mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_SAMPLES_PER_SECOND, value);
			}
		}

		public int ChannelCount
		{
			get
			{
				return GetUInt32(MediaFoundationAttributes.MF_MT_AUDIO_NUM_CHANNELS);
			}
			set
			{
				mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_NUM_CHANNELS, value);
			}
		}

		public int BitsPerSample
		{
			get
			{
				return GetUInt32(MediaFoundationAttributes.MF_MT_AUDIO_BITS_PER_SAMPLE);
			}
			set
			{
				mediaType.SetUINT32(MediaFoundationAttributes.MF_MT_AUDIO_BITS_PER_SAMPLE, value);
			}
		}

		public int AverageBytesPerSecond => GetUInt32(MediaFoundationAttributes.MF_MT_AUDIO_AVG_BYTES_PER_SECOND);

		public Guid SubType
		{
			get
			{
				return GetGuid(MediaFoundationAttributes.MF_MT_SUBTYPE);
			}
			set
			{
				mediaType.SetGUID(MediaFoundationAttributes.MF_MT_SUBTYPE, value);
			}
		}

		public Guid MajorType
		{
			get
			{
				return GetGuid(MediaFoundationAttributes.MF_MT_MAJOR_TYPE);
			}
			set
			{
				mediaType.SetGUID(MediaFoundationAttributes.MF_MT_MAJOR_TYPE, value);
			}
		}

		public IMFMediaType MediaFoundationObject => mediaType;

		public MediaType(IMFMediaType mediaType)
		{
			this.mediaType = mediaType;
		}

		public MediaType()
		{
			mediaType = MediaFoundationApi.CreateMediaType();
		}

		public MediaType(WaveFormat waveFormat)
		{
			mediaType = MediaFoundationApi.CreateMediaTypeFromWaveFormat(waveFormat);
		}

		private int GetUInt32(Guid key)
		{
			mediaType.GetUINT32(key, out var punValue);
			return punValue;
		}

		private Guid GetGuid(Guid key)
		{
			mediaType.GetGUID(key, out var pguidValue);
			return pguidValue;
		}

		public int TryGetUInt32(Guid key, int defaultValue = -1)
		{
			int punValue = defaultValue;
			try
			{
				mediaType.GetUINT32(key, out punValue);
			}
			catch (COMException ex)
			{
				if (HResult.GetHResult(ex) != -1072875802)
				{
					if (HResult.GetHResult(ex) == -1072875843)
					{
						throw new ArgumentException("Not a UINT32 parameter");
					}
					throw;
				}
			}
			return punValue;
		}
	}
	public static class MediaTypes
	{
		public static readonly Guid MFMediaType_Default = new Guid("81A412E6-8103-4B06-857F-1862781024AC");

		[FieldDescription("Audio")]
		public static readonly Guid MFMediaType_Audio = new Guid("73647561-0000-0010-8000-00aa00389b71");

		[FieldDescription("Video")]
		public static readonly Guid MFMediaType_Video = new Guid("73646976-0000-0010-8000-00aa00389b71");

		[FieldDescription("Protected Media")]
		public static readonly Guid MFMediaType_Protected = new Guid("7b4b6fe6-9d04-4494-be14-7e0bd076c8e4");

		[FieldDescription("SAMI captions")]
		public static readonly Guid MFMediaType_SAMI = new Guid("e69669a0-3dcd-40cb-9e2e-3708387c0616");

		[FieldDescription("Script stream")]
		public static readonly Guid MFMediaType_Script = new Guid("72178c22-e45b-11d5-bc2a-00b0d0f3f4ab");

		[FieldDescription("Still image stream")]
		public static readonly Guid MFMediaType_Image = new Guid("72178c23-e45b-11d5-bc2a-00b0d0f3f4ab");

		[FieldDescription("HTML stream")]
		public static readonly Guid MFMediaType_HTML = new Guid("72178c24-e45b-11d5-bc2a-00b0d0f3f4ab");

		[FieldDescription("Binary stream")]
		public static readonly Guid MFMediaType_Binary = new Guid("72178c25-e45b-11d5-bc2a-00b0d0f3f4ab");

		[FieldDescription("File transfer")]
		public static readonly Guid MFMediaType_FileTransfer = new Guid("72178c26-e45b-11d5-bc2a-00b0d0f3f4ab");
	}
	public struct MFT_INPUT_STREAM_INFO
	{
		public long hnsMaxLatency;

		public _MFT_INPUT_STREAM_INFO_FLAGS dwFlags;

		public int cbSize;

		public int cbMaxLookahead;

		public int cbAlignment;
	}
	public enum MFT_MESSAGE_TYPE
	{
		MFT_MESSAGE_COMMAND_FLUSH = 0,
		MFT_MESSAGE_COMMAND_DRAIN = 1,
		MFT_MESSAGE_SET_D3D_MANAGER = 2,
		MFT_MESSAGE_DROP_SAMPLES = 3,
		MFT_MESSAGE_COMMAND_TICK = 4,
		MFT_MESSAGE_NOTIFY_BEGIN_STREAMING = 268435456,
		MFT_MESSAGE_NOTIFY_END_STREAMING = 268435457,
		MFT_MESSAGE_NOTIFY_END_OF_STREAM = 268435458,
		MFT_MESSAGE_NOTIFY_START_OF_STREAM = 268435459,
		MFT_MESSAGE_COMMAND_MARKER = 536870912
	}
	public struct MFT_OUTPUT_DATA_BUFFER
	{
		public int dwStreamID;

		public IMFSample pSample;

		public _MFT_OUTPUT_DATA_BUFFER_FLAGS dwStatus;

		public IMFCollection pEvents;
	}
	public struct MFT_OUTPUT_STREAM_INFO
	{
		public _MFT_OUTPUT_STREAM_INFO_FLAGS dwFlags;

		public int cbSize;

		public int cbAlignment;
	}
	[StructLayout(LayoutKind.Sequential)]
	public class MFT_REGISTER_TYPE_INFO
	{
		public Guid guidMajorType;

		public Guid guidSubtype;
	}
	[StructLayout(LayoutKind.Sequential)]
	public class MF_SINK_WRITER_STATISTICS
	{
		public int cb;

		public long llLastTimestampReceived;

		public long llLastTimestampEncoded;

		public long llLastTimestampProcessed;

		public long llLastStreamTickReceived;

		public long llLastSinkSampleRequest;

		public long qwNumSamplesReceived;

		public long qwNumSamplesEncoded;

		public long qwNumSamplesProcessed;

		public long qwNumStreamTicksReceived;

		public int dwByteCountQueued;

		public long qwByteCountProcessed;

		public int dwNumOutstandingSinkSampleRequests;

		public int dwAverageSampleRateReceived;

		public int dwAverageSampleRateEncoded;

		public int dwAverageSampleRateProcessed;
	}
	[Flags]
	public enum _MFT_ENUM_FLAG
	{
		None = 0,
		MFT_ENUM_FLAG_SYNCMFT = 1,
		MFT_ENUM_FLAG_ASYNCMFT = 2,
		MFT_ENUM_FLAG_HARDWARE = 4,
		MFT_ENUM_FLAG_FIELDOFUSE = 8,
		MFT_ENUM_FLAG_LOCALMFT = 0x10,
		MFT_ENUM_FLAG_TRANSCODE_ONLY = 0x20,
		MFT_ENUM_FLAG_SORTANDFILTER = 0x40,
		MFT_ENUM_FLAG_ALL = 0x3F
	}
	[Flags]
	public enum _MFT_INPUT_STATUS_FLAGS
	{
		None = 0,
		MFT_INPUT_STATUS_ACCEPT_DATA = 1
	}
	[Flags]
	public enum _MFT_INPUT_STREAM_INFO_FLAGS
	{
		None = 0,
		MFT_INPUT_STREAM_WHOLE_SAMPLES = 1,
		MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER = 2,
		MFT_INPUT_STREAM_FIXED_SAMPLE_SIZE = 4,
		MFT_INPUT_STREAM_HOLDS_BUFFERS = 8,
		MFT_INPUT_STREAM_DOES_NOT_ADDREF = 0x100,
		MFT_INPUT_STREAM_REMOVABLE = 0x200,
		MFT_INPUT_STREAM_OPTIONAL = 0x400,
		MFT_INPUT_STREAM_PROCESSES_IN_PLACE = 0x800
	}
	[Flags]
	public enum _MFT_OUTPUT_DATA_BUFFER_FLAGS
	{
		None = 0,
		MFT_OUTPUT_DATA_BUFFER_INCOMPLETE = 0x1000000,
		MFT_OUTPUT_DATA_BUFFER_FORMAT_CHANGE = 0x100,
		MFT_OUTPUT_DATA_BUFFER_STREAM_END = 0x200,
		MFT_OUTPUT_DATA_BUFFER_NO_SAMPLE = 0x300
	}
	[Flags]
	public enum _MFT_OUTPUT_STATUS_FLAGS
	{
		None = 0,
		MFT_OUTPUT_STATUS_SAMPLE_READY = 1
	}
	[Flags]
	public enum _MFT_OUTPUT_STREAM_INFO_FLAGS
	{
		None = 0,
		MFT_OUTPUT_STREAM_WHOLE_SAMPLES = 1,
		MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER = 2,
		MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE = 4,
		MFT_OUTPUT_STREAM_DISCARDABLE = 8,
		MFT_OUTPUT_STREAM_OPTIONAL = 0x10,
		MFT_OUTPUT_STREAM_PROVIDES_SAMPLES = 0x100,
		MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES = 0x200,
		MFT_OUTPUT_STREAM_LAZY_READ = 0x400,
		MFT_OUTPUT_STREAM_REMOVABLE = 0x800
	}
	[Flags]
	public enum _MFT_PROCESS_OUTPUT_FLAGS
	{
		None = 0,
		MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER = 1,
		MFT_PROCESS_OUTPUT_REGENERATE_LAST_OUTPUT = 2
	}
	[Flags]
	public enum _MFT_PROCESS_OUTPUT_STATUS
	{
		None = 0,
		MFT_PROCESS_OUTPUT_STATUS_NEW_STREAMS = 0x100
	}
	[Flags]
	public enum _MFT_SET_TYPE_FLAGS
	{
		None = 0,
		MFT_SET_TYPE_TEST_ONLY = 1
	}
}
namespace NAudio.Dmo
{
	public class DmoDescriptor
	{
		public string Name { get; private set; }

		public Guid Clsid { get; private set; }

		public DmoDescriptor(string name, Guid clsid)
		{
			Name = name;
			Clsid = clsid;
		}
	}
	public class DmoEnumerator
	{
		public static IEnumerable<DmoDescriptor> GetAudioEffectNames()
		{
			return GetDmos(DmoGuids.DMOCATEGORY_AUDIO_EFFECT);
		}

		public static IEnumerable<DmoDescriptor> GetAudioEncoderNames()
		{
			return GetDmos(DmoGuids.DMOCATEGORY_AUDIO_ENCODER);
		}

		public static IEnumerable<DmoDescriptor> GetAudioDecoderNames()
		{
			return GetDmos(DmoGuids.DMOCATEGORY_AUDIO_DECODER);
		}

		private static IEnumerable<DmoDescriptor> GetDmos(Guid category)
		{
			Marshal.ThrowExceptionForHR(DmoInterop.DMOEnum(ref category, DmoEnumFlags.None, 0, null, 0, null, out var enumDmo));
			int itemsFetched;
			do
			{
				enumDmo.Next(1, out var clsid, out var name, out itemsFetched);
				if (itemsFetched == 1)
				{
					string name2 = Marshal.PtrToStringUni(name);
					Marshal.FreeCoTaskMem(name);
					yield return new DmoDescriptor(name2, clsid);
				}
			}
			while (itemsFetched > 0);
		}
	}
	[Flags]
	internal enum DmoEnumFlags
	{
		None = 0,
		DMO_ENUMF_INCLUDE_KEYED = 1
	}
	internal static class DmoGuids
	{
		public static readonly Guid DMOCATEGORY_AUDIO_DECODER = new Guid("57f2db8b-e6bb-4513-9d43-dcd2a6593125");

		public static readonly Guid DMOCATEGORY_AUDIO_ENCODER = new Guid("33D9A761-90C8-11d0-BD43-00A0C911CE86");

		public static readonly Guid DMOCATEGORY_VIDEO_DECODER = new Guid("4a69b442-28be-4991-969c-b500adf5d8a8");

		public static readonly Guid DMOCATEGORY_VIDEO_ENCODER = new Guid("33D9A760-90C8-11d0-BD43-00A0C911CE86");

		public static readonly Guid DMOCATEGORY_AUDIO_EFFECT = new Guid("f3602b3f-0592-48df-a4cd-674721e7ebeb");

		public static readonly Guid DMOCATEGORY_VIDEO_EFFECT = new Guid("d990ee14-776c-4723-be46-3da2f56f10b9");

		public static readonly Guid DMOCATEGORY_AUDIO_CAPTURE_EFFECT = new Guid("f665aaba-3e09-4920-aa5f-219811148f09");
	}
	internal static class DmoMediaTypeGuids
	{
		public static readonly Guid FORMAT_None = new Guid("0F6417D6-C318-11D0-A43F-00A0C9223196");

		public static readonly Guid FORMAT_VideoInfo = new Guid("05589f80-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid FORMAT_VideoInfo2 = new Guid("F72A76A0-EB0A-11d0-ACE4-0000C0CC16BA");

		public static readonly Guid FORMAT_WaveFormatEx = new Guid("05589f81-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid FORMAT_MPEGVideo = new Guid("05589f82-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid FORMAT_MPEGStreams = new Guid("05589f83-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid FORMAT_DvInfo = new Guid("05589f84-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid FORMAT_525WSS = new Guid("C7ECF04D-4582-4869-9ABB-BFB523B62EDF");
	}
	internal enum DmoHResults
	{
		DMO_E_INVALIDSTREAMINDEX = -2147220991,
		DMO_E_INVALIDTYPE,
		DMO_E_TYPE_NOT_SET,
		DMO_E_NOTACCEPTING,
		DMO_E_TYPE_NOT_ACCEPTED,
		DMO_E_NO_MORE_ITEMS
	}
	[Flags]
	public enum DmoInPlaceProcessFlags
	{
		Normal = 0,
		Zero = 1
	}
	public enum DmoInPlaceProcessReturn
	{
		Normal,
		HasEffectTail
	}
	[Flags]
	public enum DmoInputDataBufferFlags
	{
		None = 0,
		SyncPoint = 1,
		Time = 2,
		TimeLength = 4
	}
	[Flags]
	internal enum DmoInputStatusFlags
	{
		None = 0,
		DMO_INPUT_STATUSF_ACCEPT_DATA = 1
	}
	internal static class DmoInterop
	{
		[DllImport("msdmo.dll")]
		public static extern int DMOEnum([In] ref Guid guidCategory, DmoEnumFlags flags, int inTypes, [In] DmoPartialMediaType[] inTypesArray, int outTypes, [In] DmoPartialMediaType[] outTypesArray, out IEnumDmo enumDmo);

		[DllImport("msdmo.dll")]
		public static extern int MoFreeMediaType([In] ref DmoMediaType mediaType);

		[DllImport("msdmo.dll")]
		public static extern int MoInitMediaType([In][Out] ref DmoMediaType mediaType, int formatBlockBytes);

		[DllImport("msdmo.dll")]
		public static extern int DMOGetName([In] ref Guid clsidDMO, [Out] StringBuilder name);
	}
	public struct DmoMediaType
	{
		private Guid majortype;

		private Guid subtype;

		private bool bFixedSizeSamples;

		private bool bTemporalCompression;

		private int lSampleSize;

		private Guid formattype;

		private IntPtr pUnk;

		private int cbFormat;

		private IntPtr pbFormat;

		public Guid MajorType => majortype;

		public string MajorTypeName => MediaTypes.GetMediaTypeName(majortype);

		public Guid SubType => subtype;

		public string SubTypeName
		{
			get
			{
				if (majortype == MediaTypes.MEDIATYPE_Audio)
				{
					return AudioMediaSubtypes.GetAudioSubtypeName(subtype);
				}
				return subtype.ToString();
			}
		}

		public bool FixedSizeSamples => bFixedSizeSamples;

		public int SampleSize => lSampleSize;

		public Guid FormatType => formattype;

		public string FormatTypeName
		{
			get
			{
				if (formattype == DmoMediaTypeGuids.FORMAT_None)
				{
					return "None";
				}
				if (formattype == Guid.Empty)
				{
					return "Null";
				}
				if (formattype == DmoMediaTypeGuids.FORMAT_WaveFormatEx)
				{
					return "WaveFormatEx";
				}
				return FormatType.ToString();
			}
		}

		public WaveFormat GetWaveFormat()
		{
			if (formattype == DmoMediaTypeGuids.FORMAT_WaveFormatEx)
			{
				return WaveFormat.MarshalFromPtr(pbFormat);
			}
			throw new InvalidOperationException("Not a WaveFormat type");
		}

		public void SetWaveFormat(WaveFormat waveFormat)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Invalid comparison between Unknown and I4
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			majortype = MediaTypes.MEDIATYPE_Audio;
			WaveFormatExtensible val = (WaveFormatExtensible)(object)((waveFormat is WaveFormatExtensible) ? waveFormat : null);
			if (val != null)
			{
				subtype = val.SubFormat;
			}
			else
			{
				WaveFormatEncoding encoding = waveFormat.Encoding;
				if ((int)encoding != 1)
				{
					if ((int)encoding != 3)
					{
						if ((int)encoding != 85)
						{
							throw new ArgumentException($"Not a supported encoding {waveFormat.Encoding}");
						}
						subtype = AudioMediaSubtypes.WMMEDIASUBTYPE_MP3;
					}
					else
					{
						subtype = AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT;
					}
				}
				else
				{
					subtype = AudioMediaSubtypes.MEDIASUBTYPE_PCM;
				}
			}
			bFixedSizeSamples = SubType == AudioMediaSubtypes.MEDIASUBTYPE_PCM || SubType == AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT;
			formattype = DmoMediaTypeGuids.FORMAT_WaveFormatEx;
			if (cbFormat < Marshal.SizeOf<WaveFormat>(waveFormat))
			{
				throw new InvalidOperationException("Not enough memory assigned for a WaveFormat structure");
			}
			Marshal.StructureToPtr<WaveFormat>(waveFormat, pbFormat, fDeleteOld: false);
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 8)]
	public struct DmoOutputDataBuffer : IDisposable
	{
		[MarshalAs(UnmanagedType.Interface)]
		private IMediaBuffer pBuffer;

		private DmoOutputDataBufferFlags dwStatus;

		private long rtTimestamp;

		private long referenceTimeDuration;

		public IMediaBuffer MediaBuffer
		{
			get
			{
				return pBuffer;
			}
			internal set
			{
				pBuffer = value;
			}
		}

		public int Length => ((MediaBuffer)pBuffer).Length;

		public DmoOutputDataBufferFlags StatusFlags
		{
			get
			{
				return dwStatus;
			}
			internal set
			{
				dwStatus = value;
			}
		}

		public long Timestamp
		{
			get
			{
				return rtTimestamp;
			}
			internal set
			{
				rtTimestamp = value;
			}
		}

		public long Duration
		{
			get
			{
				return referenceTimeDuration;
			}
			internal set
			{
				referenceTimeDuration = value;
			}
		}

		public bool MoreDataAvailable => (StatusFlags & DmoOutputDataBufferFlags.Incomplete) == DmoOutputDataBufferFlags.Incomplete;

		public DmoOutputDataBuffer(int maxBufferSize)
		{
			pBuffer = new MediaBuffer(maxBufferSize);
			dwStatus = DmoOutputDataBufferFlags.None;
			rtTimestamp = 0L;
			referenceTimeDuration = 0L;
		}

		public void Dispose()
		{
			if (pBuffer != null)
			{
				((MediaBuffer)pBuffer).Dispose();
				pBuffer = null;
				GC.SuppressFinalize(this);
			}
		}

		public void RetrieveData(byte[] data, int offset)
		{
			((MediaBuffer)pBuffer).RetrieveData(data, offset);
		}
	}
	[Flags]
	public enum DmoOutputDataBufferFlags
	{
		None = 0,
		SyncPoint = 1,
		Time = 2,
		TimeLength = 4,
		Incomplete = 0x1000000
	}
	internal struct DmoPartialMediaType
	{
		private Guid type;

		private Guid subtype;

		public Guid Type
		{
			get
			{
				return type;
			}
			internal set
			{
				type = value;
			}
		}

		public Guid Subtype
		{
			get
			{
				return subtype;
			}
			internal set
			{
				subtype = value;
			}
		}
	}
	[Flags]
	public enum DmoProcessOutputFlags
	{
		None = 0,
		DiscardWhenNoBuffer = 1
	}
	[Flags]
	internal enum DmoSetTypeFlags
	{
		None = 0,
		DMO_SET_TYPEF_TEST_ONLY = 1,
		DMO_SET_TYPEF_CLEAR = 2
	}
	[Guid("2c3cd98a-2bfa-4a53-9c27-5249ba64ba0f")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface IEnumDmo
	{
		int Next(int itemsToFetch, out Guid clsid, out IntPtr name, out int itemsFetched);

		int Skip(int itemsToSkip);

		int Reset();

		int Clone(out IEnumDmo enumPointer);
	}
	[ComImport]
	[SuppressUnmanagedCodeSecurity]
	[Guid("59eff8b9-938c-4a26-82f2-95cb84cdc837")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IMediaBuffer
	{
		[PreserveSig]
		int SetLength(int length);

		[PreserveSig]
		int GetMaxLength(out int maxLength);

		[PreserveSig]
		int GetBufferAndLength(IntPtr bufferPointerPointer, IntPtr validDataLengthPointer);
	}
	[ComImport]
	[SuppressUnmanagedCodeSecurity]
	[Guid("d8ad0f58-5494-4102-97c5-ec798e59bcf4")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface IMediaObject
	{
		[PreserveSig]
		int GetStreamCount(out int inputStreams, out int outputStreams);

		[PreserveSig]
		int GetInputStreamInfo(int inputStreamIndex, out InputStreamInfoFlags flags);

		[PreserveSig]
		int GetOutputStreamInfo(int outputStreamIndex, out OutputStreamInfoFlags flags);

		[PreserveSig]
		int GetInputType(int inputStreamIndex, int typeIndex, out DmoMediaType mediaType);

		[PreserveSig]
		int GetOutputType(int outputStreamIndex, int typeIndex, out DmoMediaType mediaType);

		[PreserveSig]
		int SetInputType(int inputStreamIndex, [In] ref DmoMediaType mediaType, DmoSetTypeFlags flags);

		[PreserveSig]
		int SetOutputType(int outputStreamIndex, [In] ref DmoMediaType mediaType, DmoSetTypeFlags flags);

		[PreserveSig]
		int GetInputCurrentType(int inputStreamIndex, out DmoMediaType mediaType);

		[PreserveSig]
		int GetOutputCurrentType(int outputStreamIndex, out DmoMediaType mediaType);

		[PreserveSig]
		int GetInputSizeInfo(int inputStreamIndex, out int size, out int maxLookahead, out int alignment);

		[PreserveSig]
		int GetOutputSizeInfo(int outputStreamIndex, out int size, out int alignment);

		[PreserveSig]
		int GetInputMaxLatency(int inputStreamIndex, out long referenceTimeMaxLatency);

		[PreserveSig]
		int SetInputMaxLatency(int inputStreamIndex, long referenceTimeMaxLatency);

		[PreserveSig]
		int Flush();

		[PreserveSig]
		int Discontinuity(int inputStreamIndex);

		[PreserveSig]
		int AllocateStreamingResources();

		[PreserveSig]
		int FreeStreamingResources();

		[PreserveSig]
		int GetInputStatus(int inputStreamIndex, out DmoInputStatusFlags flags);

		[PreserveSig]
		int ProcessInput(int inputStreamIndex, [In] IMediaBuffer mediaBuffer, DmoInputDataBufferFlags flags, long referenceTimeTimestamp, long referenceTimeDuration);

		[PreserveSig]
		int ProcessOutput(DmoProcessOutputFlags flags, int outputBufferCount, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] DmoOutputDataBuffer[] outputBuffers, out int statusReserved);

		[PreserveSig]
		int Lock(bool acquireLock);
	}
	[ComImport]
	[SuppressUnmanagedCodeSecurity]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("651B9AD0-0FC7-4AA9-9538-D89931010741")]
	internal interface IMediaObjectInPlace
	{
		[PreserveSig]
		int Process([In] int size, [In] IntPtr data, [In] long refTimeStart, [In] DmoInPlaceProcessFlags dwFlags);

		[PreserveSig]
		int Clone([MarshalAs(UnmanagedType.Interface)] out IMediaObjectInPlace mediaObjectInPlace);

		[PreserveSig]
		int GetLatency(out long latencyTime);
	}
	[ComImport]
	[SuppressUnmanagedCodeSecurity]
	[Guid("6d6cbb60-a223-44aa-842f-a2f06750be6d")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface IMediaParamInfo
	{
		[PreserveSig]
		int GetParamCount(out int paramCount);

		[PreserveSig]
		int GetParamInfo(int paramIndex, ref MediaParamInfo paramInfo);

		[PreserveSig]
		int GetParamText(int paramIndex, out IntPtr paramText);

		[PreserveSig]
		int GetNumTimeFormats(out int numTimeFormats);

		[PreserveSig]
		int GetSupportedTimeFormat(int formatIndex, out Guid guidTimeFormat);

		[PreserveSig]
		int GetCurrentTimeFormat(out Guid guidTimeFormat, out int mediaTimeData);
	}
	[Flags]
	internal enum InputStreamInfoFlags
	{
		None = 0,
		DMO_INPUT_STREAMF_WHOLE_SAMPLES = 1,
		DMO_INPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER = 2,
		DMO_INPUT_STREAMF_FIXED_SAMPLE_SIZE = 4,
		DMO_INPUT_STREAMF_HOLDS_BUFFERS = 8
	}
	[Guid("E7E9984F-F09F-4da4-903F-6E2E0EFE56B5")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface IWMResamplerProps
	{
		int SetHalfFilterLength(int outputQuality);

		int SetUserChannelMtx([In] float[] channelConversionMatrix);
	}
	public class MediaBuffer : IMediaBuffer, IDisposable
	{
		private IntPtr buffer;

		private int length;

		private readonly int maxLength;

		public int Length
		{
			get
			{
				return length;
			}
			set
			{
				if (length > maxLength)
				{
					throw new ArgumentException("Cannot be greater than maximum buffer size");
				}
				length = value;
			}
		}

		public MediaBuffer(int maxLength)
		{
			buffer = Marshal.AllocCoTaskMem(maxLength);
			this.maxLength = maxLength;
		}

		public void Dispose()
		{
			if (buffer != IntPtr.Zero)
			{
				Marshal.FreeCoTaskMem(buffer);
				buffer = IntPtr.Zero;
				GC.SuppressFinalize(this);
			}
		}

		~MediaBuffer()
		{
			Dispose();
		}

		int IMediaBuffer.SetLength(int length)
		{
			if (length > maxLength)
			{
				return -2147483645;
			}
			this.length = length;
			return 0;
		}

		int IMediaBuffer.GetMaxLength(out int maxLength)
		{
			maxLength = this.maxLength;
			return 0;
		}

		int IMediaBuffer.GetBufferAndLength(IntPtr bufferPointerPointer, IntPtr validDataLengthPointer)
		{
			if (bufferPointerPointer != IntPtr.Zero)
			{
				Marshal.WriteIntPtr(bufferPointerPointer, buffer);
			}
			if (validDataLengthPointer != IntPtr.Zero)
			{
				Marshal.WriteInt32(validDataLengthPointer, length);
			}
			return 0;
		}

		public void LoadData(byte[] data, int bytes)
		{
			Length = bytes;
			Marshal.Copy(data, 0, buffer, bytes);
		}

		public void RetrieveData(byte[] data, int offset)
		{
			Marshal.Copy(buffer, data, offset, Length);
		}
	}
	public class MediaObject : IDisposable
	{
		private IMediaObject mediaObject;

		private readonly int inputStreams;

		private readonly int outputStreams;

		public int InputStreamCount => inputStreams;

		public int OutputStreamCount => outputStreams;

		internal MediaObject(IMediaObject mediaObject)
		{
			this.mediaObject = mediaObject;
			mediaObject.GetStreamCount(out inputStreams, out outputStreams);
		}

		public DmoMediaType? GetInputType(int inputStream, int inputTypeIndex)
		{
			try
			{
				if (mediaObject.GetInputType(inputStream, inputTypeIndex, out var mediaType) == 0)
				{
					DmoInterop.MoFreeMediaType(ref mediaType);
					return mediaType;
				}
			}
			catch (COMException ex)
			{
				if (HResult.GetHResult(ex) != -2147220986)
				{
					throw;
				}
			}
			return null;
		}

		public DmoMediaType? GetOutputType(int outputStream, int outputTypeIndex)
		{
			try
			{
				if (mediaObject.GetOutputType(outputStream, outputTypeIndex, out var mediaType) == 0)
				{
					DmoInterop.MoFreeMediaType(ref mediaType);
					return mediaType;
				}
			}
			catch (COMException ex)
			{
				if (HResult.GetHResult(ex) != -2147220986)
				{
					throw;
				}
			}
			return null;
		}

		public DmoMediaType GetOutputCurrentType(int outputStreamIndex)
		{
			DmoMediaType mediaType;
			int outputCurrentType = mediaObject.GetOutputCurrentType(outputStreamIndex, out mediaType);
			switch (outputCurrentType)
			{
			case 0:
				DmoInterop.MoFreeMediaType(ref mediaType);
				return mediaType;
			case -2147220989:
				throw new InvalidOperationException("Media type was not set.");
			default:
				throw Marshal.GetExceptionForHR(outputCurrentType);
			}
		}

		public IEnumerable<DmoMediaType> GetInputTypes(int inputStreamIndex)
		{
			int typeIndex = 0;
			while (true)
			{
				DmoMediaType? inputType;
				DmoMediaType? dmoMediaType = (inputType = GetInputType(inputStreamIndex, typeIndex));
				if (dmoMediaType.HasValue)
				{
					yield return inputType.Value;
					typeIndex++;
					continue;
				}
				break;
			}
		}

		public IEnumerable<DmoMediaType> GetOutputTypes(int outputStreamIndex)
		{
			int typeIndex = 0;
			while (true)
			{
				DmoMediaType? outputType;
				DmoMediaType? dmoMediaType = (outputType = GetOutputType(outputStreamIndex, typeIndex));
				if (dmoMediaType.HasValue)
				{
					yield return outputType.Value;
					typeIndex++;
					continue;
				}
				break;
			}
		}

		public bool SupportsInputType(int inputStreamIndex, DmoMediaType mediaType)
		{
			return SetInputType(inputStreamIndex, mediaType, DmoSetTypeFlags.DMO_SET_TYPEF_TEST_ONLY);
		}

		private bool SetInputType(int inputStreamIndex, DmoMediaType mediaType, DmoSetTypeFlags flags)
		{
			switch (mediaObject.SetInputType(inputStreamIndex, ref mediaType, flags))
			{
			case -2147220991:
				throw new ArgumentException("Invalid stream index");
			default:
				_ = -2147220987;
				return false;
			case 0:
				return true;
			}
		}

		public void SetInputType(int inputStreamIndex, DmoMediaType mediaType)
		{
			if (!SetInputType(inputStreamIndex, mediaType, DmoSetTypeFlags.None))
			{
				throw new ArgumentException("Media Type not supported");
			}
		}

		public void SetInputWaveFormat(int inputStreamIndex, WaveFormat waveFormat)
		{
			DmoMediaType mediaType = CreateDmoMediaTypeForWaveFormat(waveFormat);
			bool num = SetInputType(inputStreamIndex, mediaType, DmoSetTypeFlags.None);
			DmoInterop.MoFreeMediaType(ref mediaType);
			if (!num)
			{
				throw new ArgumentException("Media Type not supported");
			}
		}

		public bool SupportsInputWaveFormat(int inputStreamIndex, WaveFormat waveFormat)
		{
			DmoMediaType mediaType = CreateDmoMediaTypeForWaveFormat(waveFormat);
			bool result = SetInputType(inputStreamIndex, mediaType, DmoSetTypeFlags.DMO_SET_TYPEF_TEST_ONLY);
			DmoInterop.MoFreeMediaType(ref mediaType);
			return result;
		}

		private DmoMediaType CreateDmoMediaTypeForWaveFormat(WaveFormat waveFormat)
		{
			DmoMediaType mediaType = default(DmoMediaType);
			int formatBlockBytes = Marshal.SizeOf<WaveFormat>(waveFormat);
			DmoInterop.MoInitMediaType(ref mediaType, formatBlockBytes);
			mediaType.SetWaveFormat(waveFormat);
			return mediaType;
		}

		public bool SupportsOutputType(int outputStreamIndex, DmoMediaType mediaType)
		{
			return SetOutputType(outputStreamIndex, mediaType, DmoSetTypeFlags.DMO_SET_TYPEF_TEST_ONLY);
		}

		public bool SupportsOutputWaveFormat(int outputStreamIndex, WaveFormat waveFormat)
		{
			DmoMediaType mediaType = CreateDmoMediaTypeForWaveFormat(waveFormat);
			bool result = SetOutputType(outputStreamIndex, mediaType, DmoSetTypeFlags.DMO_SET_TYPEF_TEST_ONLY);
			DmoInterop.MoFreeMediaType(ref mediaType);
			return result;
		}

		private bool SetOutputType(int outputStreamIndex, DmoMediaType mediaType, DmoSetTypeFlags flags)
		{
			int num = mediaObject.SetOutputType(outputStreamIndex, ref mediaType, flags);
			return num switch
			{
				-2147220987 => false, 
				0 => true, 
				_ => throw Marshal.GetExceptionForHR(num), 
			};
		}

		public void SetOutputType(int outputStreamIndex, DmoMediaType mediaType)
		{
			if (!SetOutputType(outputStreamIndex, mediaType, DmoSetTypeFlags.None))
			{
				throw new ArgumentException("Media Type not supported");
			}
		}

		public void SetOutputWaveFormat(int outputStreamIndex, WaveFormat waveFormat)
		{
			DmoMediaType mediaType = CreateDmoMediaTypeForWaveFormat(waveFormat);
			bool num = SetOutputType(outputStreamIndex, mediaType, DmoSetTypeFlags.None);
			DmoInterop.MoFreeMediaType(ref mediaType);
			if (!num)
			{
				throw new ArgumentException("Media Type not supported");
			}
		}

		public MediaObjectSizeInfo GetInputSizeInfo(int inputStreamIndex)
		{
			Marshal.ThrowExceptionForHR(mediaObject.GetInputSizeInfo(inputStreamIndex, out var size, out var maxLookahead, out var alignment));
			return new MediaObjectSizeInfo(size, maxLookahead, alignment);
		}

		public MediaObjectSizeInfo GetOutputSizeInfo(int outputStreamIndex)
		{
			Marshal.ThrowExceptionForHR(mediaObject.GetOutputSizeInfo(outputStreamIndex, out var size, out var alignment));
			return new MediaObjectSizeInfo(size, 0, alignment);
		}

		public void ProcessInput(int inputStreamIndex, IMediaBuffer mediaBuffer, DmoInputDataBufferFlags flags, long timestamp, long duration)
		{
			Marshal.ThrowExceptionForHR(mediaObject.ProcessInput(inputStreamIndex, mediaBuffer, flags, timestamp, duration));
		}

		public void ProcessOutput(DmoProcessOutputFlags flags, int outputBufferCount, DmoOutputDataBuffer[] outputBuffers)
		{
			Marshal.ThrowExceptionForHR(mediaObject.ProcessOutput(flags, outputBufferCount, outputBuffers

NAudio.WinForms.dll

Decompiled 3 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Windows.Forms;
using NAudio.Mixer;
using NAudio.Wave;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Mark Heath")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2021")]
[assembly: AssemblyFileVersion("2.0.1.0")]
[assembly: AssemblyInformationalVersion("2.0.1")]
[assembly: AssemblyProduct("NAudio.WinForms")]
[assembly: AssemblyTitle("NAudio.WinForms")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: AssemblyVersion("2.0.1.0")]
namespace NAudio.Wave
{
	public class WaveCallbackInfo
	{
		private WaveWindow waveOutWindow;

		private WaveWindowNative waveOutWindowNative;

		public WaveCallbackStrategy Strategy { get; private set; }

		public IntPtr Handle { get; private set; }

		public static WaveCallbackInfo FunctionCallback()
		{
			return new WaveCallbackInfo((WaveCallbackStrategy)0, IntPtr.Zero);
		}

		public static WaveCallbackInfo NewWindow()
		{
			return new WaveCallbackInfo((WaveCallbackStrategy)1, IntPtr.Zero);
		}

		public static WaveCallbackInfo ExistingWindow(IntPtr handle)
		{
			if (handle == IntPtr.Zero)
			{
				throw new ArgumentException("Handle cannot be zero");
			}
			return new WaveCallbackInfo((WaveCallbackStrategy)2, handle);
		}

		private WaveCallbackInfo(WaveCallbackStrategy strategy, IntPtr handle)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Strategy = strategy;
			Handle = handle;
		}

		internal void Connect(WaveCallback callback)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			if ((int)Strategy == 1)
			{
				waveOutWindow = new WaveWindow(callback);
				((Control)waveOutWindow).CreateControl();
				Handle = ((Control)waveOutWindow).Handle;
			}
			else if ((int)Strategy == 2)
			{
				waveOutWindowNative = new WaveWindowNative(callback);
				((NativeWindow)waveOutWindowNative).AssignHandle(Handle);
			}
		}

		internal MmResult WaveOutOpen(out IntPtr waveOutHandle, int deviceNumber, WaveFormat waveFormat, WaveCallback callback)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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)
			if ((int)Strategy == 0)
			{
				return WaveInterop.waveOutOpen(ref waveOutHandle, (IntPtr)deviceNumber, waveFormat, callback, IntPtr.Zero, (WaveInOutOpenFlags)196608);
			}
			return WaveInterop.waveOutOpenWindow(ref waveOutHandle, (IntPtr)deviceNumber, waveFormat, Handle, IntPtr.Zero, (WaveInOutOpenFlags)65536);
		}

		internal MmResult WaveInOpen(out IntPtr waveInHandle, int deviceNumber, WaveFormat waveFormat, WaveCallback callback)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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)
			if ((int)Strategy == 0)
			{
				return WaveInterop.waveInOpen(ref waveInHandle, (IntPtr)deviceNumber, waveFormat, callback, IntPtr.Zero, (WaveInOutOpenFlags)196608);
			}
			return WaveInterop.waveInOpenWindow(ref waveInHandle, (IntPtr)deviceNumber, waveFormat, Handle, IntPtr.Zero, (WaveInOutOpenFlags)65536);
		}

		internal void Disconnect()
		{
			if (waveOutWindow != null)
			{
				((Form)waveOutWindow).Close();
				waveOutWindow = null;
			}
			if (waveOutWindowNative != null)
			{
				((NativeWindow)waveOutWindowNative).ReleaseHandle();
				waveOutWindowNative = null;
			}
		}
	}
	public class WaveIn : IWaveIn, IDisposable
	{
		private IntPtr waveInHandle;

		private volatile bool recording;

		private WaveInBuffer[] buffers;

		private readonly WaveCallback callback;

		private WaveCallbackInfo callbackInfo;

		private readonly SynchronizationContext syncContext;

		private int lastReturnedBufferIndex;

		public static int DeviceCount => WaveInterop.waveInGetNumDevs();

		public int BufferMilliseconds { get; set; }

		public int NumberOfBuffers { get; set; }

		public int DeviceNumber { get; set; }

		public WaveFormat WaveFormat { get; set; }

		public event EventHandler<WaveInEventArgs> DataAvailable;

		public event EventHandler<StoppedEventArgs> RecordingStopped;

		public WaveIn()
			: this(WaveCallbackInfo.NewWindow())
		{
		}

		public WaveIn(IntPtr windowHandle)
			: this(WaveCallbackInfo.ExistingWindow(windowHandle))
		{
		}

		public WaveIn(WaveCallbackInfo callbackInfo)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			syncContext = SynchronizationContext.Current;
			if (((int)callbackInfo.Strategy == 1 || (int)callbackInfo.Strategy == 2) && syncContext == null)
			{
				throw new InvalidOperationException("Use WaveInEvent to record on a background thread");
			}
			DeviceNumber = 0;
			WaveFormat = new WaveFormat(8000, 16, 1);
			BufferMilliseconds = 100;
			NumberOfBuffers = 3;
			callback = new WaveCallback(Callback);
			this.callbackInfo = callbackInfo;
			callbackInfo.Connect(callback);
		}

		public static WaveInCapabilities GetCapabilities(int devNumber)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			WaveInCapabilities val = default(WaveInCapabilities);
			int num = Marshal.SizeOf<WaveInCapabilities>(val);
			MmException.Try(WaveInterop.waveInGetDevCaps((IntPtr)devNumber, ref val, num), "waveInGetDevCaps");
			return val;
		}

		private void CreateBuffers()
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			int num = BufferMilliseconds * WaveFormat.AverageBytesPerSecond / 1000;
			if (num % WaveFormat.BlockAlign != 0)
			{
				num -= num % WaveFormat.BlockAlign;
			}
			buffers = (WaveInBuffer[])(object)new WaveInBuffer[NumberOfBuffers];
			for (int i = 0; i < buffers.Length; i++)
			{
				buffers[i] = new WaveInBuffer(waveInHandle, num);
			}
		}

		private void Callback(IntPtr waveInHandle, WaveMessage message, IntPtr userData, WaveHeader waveHeader, IntPtr reserved)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if ((int)message != 960 || !recording)
			{
				return;
			}
			WaveInBuffer val = (WaveInBuffer)((GCHandle)waveHeader.userData).Target;
			if (val != null)
			{
				lastReturnedBufferIndex = Array.IndexOf(buffers, val);
				RaiseDataAvailable(val);
				try
				{
					val.Reuse();
				}
				catch (Exception e)
				{
					recording = false;
					RaiseRecordingStopped(e);
				}
			}
		}

		private void RaiseDataAvailable(WaveInBuffer buffer)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			this.DataAvailable?.Invoke(this, new WaveInEventArgs(buffer.Data, buffer.BytesRecorded));
		}

		private void RaiseRecordingStopped(Exception e)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			EventHandler<StoppedEventArgs> handler = this.RecordingStopped;
			if (handler == null)
			{
				return;
			}
			if (syncContext == null)
			{
				handler(this, new StoppedEventArgs(e));
				return;
			}
			syncContext.Post(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				handler(this, new StoppedEventArgs(e));
			}, null);
		}

		private void OpenWaveInDevice()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			CloseWaveInDevice();
			MmException.Try(callbackInfo.WaveInOpen(out waveInHandle, DeviceNumber, WaveFormat, callback), "waveInOpen");
			CreateBuffers();
		}

		public void StartRecording()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (recording)
			{
				throw new InvalidOperationException("Already recording");
			}
			OpenWaveInDevice();
			EnqueueBuffers();
			MmException.Try(WaveInterop.waveInStart(waveInHandle), "waveInStart");
			recording = true;
		}

		private void EnqueueBuffers()
		{
			WaveInBuffer[] array = buffers;
			foreach (WaveInBuffer val in array)
			{
				if (!val.InQueue)
				{
					val.Reuse();
				}
			}
		}

		public void StopRecording()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (!recording)
			{
				return;
			}
			recording = false;
			MmException.Try(WaveInterop.waveInStop(waveInHandle), "waveInStop");
			for (int i = 0; i < buffers.Length; i++)
			{
				int num = (i + lastReturnedBufferIndex + 1) % buffers.Length;
				WaveInBuffer val = buffers[num];
				if (val.Done)
				{
					RaiseDataAvailable(val);
				}
			}
			RaiseRecordingStopped(null);
		}

		public long GetPosition()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_0041: Unknown result type (might be due to invalid IL or missing references)
			MmTime val = default(MmTime);
			val.wType = 4u;
			MmException.Try(WaveInterop.waveInGetPosition(waveInHandle, ref val, Marshal.SizeOf<MmTime>(val)), "waveInGetPosition");
			if (val.wType != 4)
			{
				throw new Exception($"waveInGetPosition: wType -> Expected {4}, Received {val.wType}");
			}
			return val.cb;
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (recording)
				{
					StopRecording();
				}
				CloseWaveInDevice();
				if (callbackInfo != null)
				{
					callbackInfo.Disconnect();
					callbackInfo = null;
				}
			}
		}

		private void CloseWaveInDevice()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if (waveInHandle == IntPtr.Zero)
			{
				return;
			}
			WaveInterop.waveInReset(waveInHandle);
			if (buffers != null)
			{
				for (int i = 0; i < buffers.Length; i++)
				{
					buffers[i].Dispose();
				}
				buffers = null;
			}
			WaveInterop.waveInClose(waveInHandle);
			waveInHandle = IntPtr.Zero;
		}

		public MixerLine GetMixerLine()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			if (waveInHandle != IntPtr.Zero)
			{
				return new MixerLine(waveInHandle, 0, (MixerFlags)(-1610612736));
			}
			return new MixerLine((IntPtr)DeviceNumber, 0, (MixerFlags)536870912);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	public class WaveOut : IWavePlayer, IDisposable, IWavePosition
	{
		private IntPtr hWaveOut;

		private WaveOutBuffer[] buffers;

		private IWaveProvider waveStream;

		private volatile PlaybackState playbackState;

		private readonly WaveCallback callback;

		private readonly WaveCallbackInfo callbackInfo;

		private readonly object waveOutLock;

		private int queuedBuffers;

		private readonly SynchronizationContext syncContext;

		public static int DeviceCount => WaveInterop.waveOutGetNumDevs();

		public int DesiredLatency { get; set; }

		public int NumberOfBuffers { get; set; }

		public int DeviceNumber { get; set; } = -1;


		public WaveFormat OutputWaveFormat => waveStream.WaveFormat;

		public PlaybackState PlaybackState => playbackState;

		public float Volume
		{
			get
			{
				return WaveOutUtils.GetWaveOutVolume(hWaveOut, waveOutLock);
			}
			set
			{
				WaveOutUtils.SetWaveOutVolume(value, hWaveOut, waveOutLock);
			}
		}

		public event EventHandler<StoppedEventArgs> PlaybackStopped;

		public static WaveOutCapabilities GetCapabilities(int devNumber)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			WaveOutCapabilities val = default(WaveOutCapabilities);
			int num = Marshal.SizeOf<WaveOutCapabilities>(val);
			MmException.Try(WaveInterop.waveOutGetDevCaps((IntPtr)devNumber, ref val, num), "waveOutGetDevCaps");
			return val;
		}

		public WaveOut()
			: this((SynchronizationContext.Current == null) ? WaveCallbackInfo.FunctionCallback() : WaveCallbackInfo.NewWindow())
		{
		}

		public WaveOut(IntPtr windowHandle)
			: this(WaveCallbackInfo.ExistingWindow(windowHandle))
		{
		}

		public WaveOut(WaveCallbackInfo callbackInfo)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			syncContext = SynchronizationContext.Current;
			DesiredLatency = 300;
			NumberOfBuffers = 2;
			callback = new WaveCallback(Callback);
			waveOutLock = new object();
			this.callbackInfo = callbackInfo;
			callbackInfo.Connect(callback);
		}

		public void Init(IWaveProvider waveProvider)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			waveStream = waveProvider;
			int num = waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1) / NumberOfBuffers);
			MmResult val;
			lock (waveOutLock)
			{
				val = callbackInfo.WaveOutOpen(out hWaveOut, DeviceNumber, waveStream.WaveFormat, callback);
			}
			MmException.Try(val, "waveOutOpen");
			buffers = (WaveOutBuffer[])(object)new WaveOutBuffer[NumberOfBuffers];
			playbackState = (PlaybackState)0;
			for (int i = 0; i < NumberOfBuffers; i++)
			{
				buffers[i] = new WaveOutBuffer(hWaveOut, num, waveStream, waveOutLock);
			}
		}

		public void Play()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState == 0)
			{
				playbackState = (PlaybackState)1;
				EnqueueBuffers();
			}
			else if ((int)playbackState == 2)
			{
				EnqueueBuffers();
				Resume();
				playbackState = (PlaybackState)1;
			}
		}

		private void EnqueueBuffers()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < NumberOfBuffers; i++)
			{
				if (!buffers[i].InQueue)
				{
					if (!buffers[i].OnDone())
					{
						playbackState = (PlaybackState)0;
						break;
					}
					Interlocked.Increment(ref queuedBuffers);
				}
			}
		}

		public void Pause()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_000d: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState == 1)
			{
				playbackState = (PlaybackState)2;
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutPause(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutPause");
				}
			}
		}

		public void Resume()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState == 2)
			{
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutRestart(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutRestart");
				}
				playbackState = (PlaybackState)1;
			}
		}

		public void Stop()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState != 0)
			{
				playbackState = (PlaybackState)0;
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutReset(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutReset");
				}
				if ((int)callbackInfo.Strategy == 0)
				{
					RaisePlaybackStoppedEvent(null);
				}
			}
		}

		public long GetPosition()
		{
			return WaveOutUtils.GetPositionBytes(hWaveOut, waveOutLock);
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected void Dispose(bool disposing)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			Stop();
			if (disposing && buffers != null)
			{
				for (int i = 0; i < buffers.Length; i++)
				{
					if (buffers[i] != null)
					{
						buffers[i].Dispose();
					}
				}
				buffers = null;
			}
			lock (waveOutLock)
			{
				WaveInterop.waveOutClose(hWaveOut);
			}
			if (disposing)
			{
				callbackInfo.Disconnect();
			}
		}

		~WaveOut()
		{
			Dispose(disposing: false);
		}

		private void Callback(IntPtr hWaveOut, WaveMessage uMsg, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Invalid comparison between Unknown and I4
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if ((int)uMsg != 957)
			{
				return;
			}
			WaveOutBuffer val = (WaveOutBuffer)((GCHandle)wavhdr.userData).Target;
			Interlocked.Decrement(ref queuedBuffers);
			Exception e = null;
			if ((int)PlaybackState == 1)
			{
				lock (waveOutLock)
				{
					try
					{
						if (val.OnDone())
						{
							Interlocked.Increment(ref queuedBuffers);
						}
					}
					catch (Exception ex)
					{
						e = ex;
					}
				}
			}
			if (queuedBuffers == 0 && ((int)callbackInfo.Strategy != 0 || (int)playbackState != 0))
			{
				playbackState = (PlaybackState)0;
				RaisePlaybackStoppedEvent(e);
			}
		}

		private void RaisePlaybackStoppedEvent(Exception e)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			EventHandler<StoppedEventArgs> handler = this.PlaybackStopped;
			if (handler == null)
			{
				return;
			}
			if (syncContext == null)
			{
				handler(this, new StoppedEventArgs(e));
				return;
			}
			syncContext.Post(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				handler(this, new StoppedEventArgs(e));
			}, null);
		}
	}
	internal class WaveWindowNative : NativeWindow
	{
		private WaveCallback waveCallback;

		public WaveWindowNative(WaveCallback waveCallback)
		{
			this.waveCallback = waveCallback;
		}

		protected override void WndProc(ref Message m)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected I4, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			WaveMessage val = (WaveMessage)((Message)(ref m)).Msg;
			switch (val - 955)
			{
			case 2:
			case 5:
			{
				IntPtr wParam = ((Message)(ref m)).WParam;
				WaveHeader val2 = new WaveHeader();
				Marshal.PtrToStructure<WaveHeader>(((Message)(ref m)).LParam, val2);
				waveCallback.Invoke(wParam, val, IntPtr.Zero, val2, IntPtr.Zero);
				break;
			}
			case 0:
			case 1:
			case 3:
			case 4:
				waveCallback.Invoke(((Message)(ref m)).WParam, val, IntPtr.Zero, (WaveHeader)null, IntPtr.Zero);
				break;
			default:
				((NativeWindow)this).WndProc(ref m);
				break;
			}
		}
	}
	internal class WaveWindow : Form
	{
		private WaveCallback waveCallback;

		public WaveWindow(WaveCallback waveCallback)
		{
			this.waveCallback = waveCallback;
		}

		protected override void WndProc(ref Message m)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected I4, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			WaveMessage val = (WaveMessage)((Message)(ref m)).Msg;
			switch (val - 955)
			{
			case 2:
			case 5:
			{
				IntPtr wParam = ((Message)(ref m)).WParam;
				WaveHeader val2 = new WaveHeader();
				Marshal.PtrToStructure<WaveHeader>(((Message)(ref m)).LParam, val2);
				waveCallback.Invoke(wParam, val, IntPtr.Zero, val2, IntPtr.Zero);
				break;
			}
			case 0:
			case 1:
			case 3:
			case 4:
				waveCallback.Invoke(((Message)(ref m)).WParam, val, IntPtr.Zero, (WaveHeader)null, IntPtr.Zero);
				break;
			default:
				((Form)this).WndProc(ref m);
				break;
			}
		}
	}
}
namespace NAudio.Utils
{
	public class ProgressLog : UserControl
	{
		private delegate void LogMessageDelegate(Color color, string message);

		private delegate void ClearLogDelegate();

		private IContainer components;

		private RichTextBox richTextBoxLog;

		public string Text => ((Control)richTextBoxLog).Text;

		public ProgressLog()
		{
			InitializeComponent();
		}

		public void LogMessage(Color color, string message)
		{
			if (((Control)richTextBoxLog).InvokeRequired)
			{
				((Control)this).Invoke((Delegate)new LogMessageDelegate(LogMessage), new object[2] { color, message });
			}
			else
			{
				((TextBoxBase)richTextBoxLog).SelectionStart = ((TextBoxBase)richTextBoxLog).TextLength;
				richTextBoxLog.SelectionColor = color;
				((TextBoxBase)richTextBoxLog).AppendText(message);
				((TextBoxBase)richTextBoxLog).AppendText(Environment.NewLine);
			}
		}

		public void ClearLog()
		{
			if (((Control)richTextBoxLog).InvokeRequired)
			{
				((Control)this).Invoke((Delegate)new ClearLogDelegate(ClearLog), new object[0]);
			}
			else
			{
				((TextBoxBase)richTextBoxLog).Clear();
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((ContainerControl)this).Dispose(disposing);
		}

		private void InitializeComponent()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			richTextBoxLog = new RichTextBox();
			((Control)this).SuspendLayout();
			((TextBoxBase)richTextBoxLog).BorderStyle = (BorderStyle)0;
			((Control)richTextBoxLog).Dock = (DockStyle)5;
			((Control)richTextBoxLog).Location = new Point(1, 1);
			((Control)richTextBoxLog).Name = "richTextBoxLog";
			((TextBoxBase)richTextBoxLog).ReadOnly = true;
			((Control)richTextBoxLog).Size = new Size(311, 129);
			((Control)richTextBoxLog).TabIndex = 0;
			((Control)richTextBoxLog).Text = "";
			((ContainerControl)this).AutoScaleDimensions = new SizeF(6f, 13f);
			((ContainerControl)this).AutoScaleMode = (AutoScaleMode)1;
			((Control)this).BackColor = SystemColors.ControlDarkDark;
			((Control)this).Controls.Add((Control)(object)richTextBoxLog);
			((Control)this).Name = "ProgressLog";
			((Control)this).Padding = new Padding(1);
			((Control)this).Size = new Size(313, 131);
			((Control)this).ResumeLayout(false);
		}
	}
}
namespace NAudio.WinForms.Gui
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Fader
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					resourceMan = new ResourceManager("NAudio.WinForms.Gui.Fader", typeof(Fader).Assembly);
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal Fader()
		{
		}
	}
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class PanSlider
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					resourceMan = new ResourceManager("NAudio.WinForms.Gui.PanSlider", typeof(PanSlider).Assembly);
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal PanSlider()
		{
		}
	}
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class VolumeSlider
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					resourceMan = new ResourceManager("NAudio.WinForms.Gui.VolumeSlider", typeof(VolumeSlider).Assembly);
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal VolumeSlider()
		{
		}
	}
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class WaveViewer
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					resourceMan = new ResourceManager("NAudio.WinForms.Gui.WaveViewer", typeof(WaveViewer).Assembly);
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal WaveViewer()
		{
		}
	}
}
namespace NAudio.Gui
{
	public class Fader : Control
	{
		private int minimum;

		private int maximum;

		private float percent;

		private Orientation orientation;

		private Container components;

		private readonly int SliderHeight = 30;

		private readonly int SliderWidth = 15;

		private Rectangle sliderRectangle;

		private bool dragging;

		private int dragY;

		public int Minimum
		{
			get
			{
				return minimum;
			}
			set
			{
				minimum = value;
			}
		}

		public int Maximum
		{
			get
			{
				return maximum;
			}
			set
			{
				maximum = value;
			}
		}

		public int Value
		{
			get
			{
				return (int)(percent * (float)(maximum - minimum)) + minimum;
			}
			set
			{
				percent = (float)(value - minimum) / (float)(maximum - minimum);
			}
		}

		public Orientation Orientation
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return orientation;
			}
			set
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				orientation = value;
			}
		}

		public Fader()
		{
			InitializeComponent();
			((Control)this).SetStyle((ControlStyles)73730, true);
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((Control)this).Dispose(disposing);
		}

		private void DrawSlider(Graphics g)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			Brush val = (Brush)new SolidBrush(Color.White);
			Pen val2 = new Pen(Color.Black);
			sliderRectangle.X = (((Control)this).Width - SliderWidth) / 2;
			sliderRectangle.Width = SliderWidth;
			sliderRectangle.Y = (int)((float)(((Control)this).Height - SliderHeight) * percent);
			sliderRectangle.Height = SliderHeight;
			g.FillRectangle(val, sliderRectangle);
			g.DrawLine(val2, sliderRectangle.Left, sliderRectangle.Top + sliderRectangle.Height / 2, sliderRectangle.Right, sliderRectangle.Top + sliderRectangle.Height / 2);
			val.Dispose();
			val2.Dispose();
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			Graphics graphics = e.Graphics;
			if ((int)Orientation == 1)
			{
				Brush val = (Brush)new SolidBrush(Color.Black);
				graphics.FillRectangle(val, ((Control)this).Width / 2, SliderHeight / 2, 2, ((Control)this).Height - SliderHeight);
				val.Dispose();
				DrawSlider(graphics);
			}
			((Control)this).OnPaint(e);
		}

		protected override void OnMouseDown(MouseEventArgs e)
		{
			if (sliderRectangle.Contains(e.X, e.Y))
			{
				dragging = true;
				dragY = e.Y - sliderRectangle.Y;
			}
			((Control)this).OnMouseDown(e);
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			if (dragging)
			{
				int num = e.Y - dragY;
				if (num < 0)
				{
					percent = 0f;
				}
				else if (num > ((Control)this).Height - SliderHeight)
				{
					percent = 1f;
				}
				else
				{
					percent = (float)num / (float)(((Control)this).Height - SliderHeight);
				}
				((Control)this).Invalidate();
			}
			((Control)this).OnMouseMove(e);
		}

		protected override void OnMouseUp(MouseEventArgs e)
		{
			dragging = false;
			((Control)this).OnMouseUp(e);
		}

		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
		}
	}
	public class PanSlider : UserControl
	{
		private Container components;

		private float pan;

		public float Pan
		{
			get
			{
				return pan;
			}
			set
			{
				if (value < -1f)
				{
					value = -1f;
				}
				if (value > 1f)
				{
					value = 1f;
				}
				if (value != pan)
				{
					pan = value;
					if (this.PanChanged != null)
					{
						this.PanChanged(this, EventArgs.Empty);
					}
					((Control)this).Invalidate();
				}
			}
		}

		public event EventHandler PanChanged;

		public PanSlider()
		{
			InitializeComponent();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((ContainerControl)this).Dispose(disposing);
		}

		private void InitializeComponent()
		{
			((Control)this).Name = "PanSlider";
			((Control)this).Size = new Size(104, 16);
		}

		protected override void OnPaint(PaintEventArgs pe)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			StringFormat val = new StringFormat();
			val.LineAlignment = (StringAlignment)1;
			val.Alignment = (StringAlignment)1;
			string text;
			if ((double)pan == 0.0)
			{
				pe.Graphics.FillRectangle(Brushes.Orange, ((Control)this).Width / 2 - 1, 1, 3, ((Control)this).Height - 2);
				text = "C";
			}
			else if (pan > 0f)
			{
				pe.Graphics.FillRectangle(Brushes.Orange, ((Control)this).Width / 2, 1, (int)((float)(((Control)this).Width / 2) * pan), ((Control)this).Height - 2);
				text = $"{pan * 100f:F0}%R";
			}
			else
			{
				pe.Graphics.FillRectangle(Brushes.Orange, (int)((float)(((Control)this).Width / 2) * (pan + 1f)), 1, (int)((float)(((Control)this).Width / 2) * (0f - pan)), ((Control)this).Height - 2);
				text = $"{pan * -100f:F0}%L";
			}
			pe.Graphics.DrawRectangle(Pens.Black, 0, 0, ((Control)this).Width - 1, ((Control)this).Height - 1);
			pe.Graphics.DrawString(text, ((Control)this).Font, Brushes.Black, (RectangleF)((Control)this).ClientRectangle, val);
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			if ((int)e.Button == 1048576)
			{
				SetPanFromMouse(e.X);
			}
			((Control)this).OnMouseMove(e);
		}

		protected override void OnMouseDown(MouseEventArgs e)
		{
			SetPanFromMouse(e.X);
			((UserControl)this).OnMouseDown(e);
		}

		private void SetPanFromMouse(int x)
		{
			Pan = (float)x / (float)((Control)this).Width * 2f - 1f;
		}
	}
	public class Pot : UserControl
	{
		private double minimum;

		private double maximum = 1.0;

		private double value = 0.5;

		private int beginDragY;

		private double beginDragValue;

		private bool dragging;

		private IContainer components;

		public double Minimum
		{
			get
			{
				return minimum;
			}
			set
			{
				if (value >= maximum)
				{
					throw new ArgumentOutOfRangeException("Minimum must be less than maximum");
				}
				minimum = value;
				if (Value < minimum)
				{
					Value = minimum;
				}
			}
		}

		public double Maximum
		{
			get
			{
				return maximum;
			}
			set
			{
				if (value <= minimum)
				{
					throw new ArgumentOutOfRangeException("Maximum must be greater than minimum");
				}
				maximum = value;
				if (Value > maximum)
				{
					Value = maximum;
				}
			}
		}

		public double Value
		{
			get
			{
				return value;
			}
			set
			{
				SetValue(value, raiseEvents: false);
			}
		}

		public event EventHandler ValueChanged;

		public Pot()
		{
			((Control)this).SetStyle((ControlStyles)73730, true);
			InitializeComponent();
		}

		private void SetValue(double newValue, bool raiseEvents)
		{
			if (value != newValue)
			{
				value = newValue;
				if (raiseEvents && this.ValueChanged != null)
				{
					this.ValueChanged(this, EventArgs.Empty);
				}
				((Control)this).Invalidate();
			}
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			int num = Math.Min(((Control)this).Width - 4, ((Control)this).Height - 4);
			Pen val = new Pen(((Control)this).ForeColor, 3f);
			val.LineJoin = (LineJoin)2;
			GraphicsState val2 = e.Graphics.Save();
			e.Graphics.TranslateTransform((float)(((Control)this).Width / 2), (float)(((Control)this).Height / 2));
			e.Graphics.SmoothingMode = (SmoothingMode)4;
			e.Graphics.DrawArc(val, new Rectangle(num / -2, num / -2, num, num), 135f, 270f);
			double num2 = (value - minimum) / (maximum - minimum);
			double num3 = 135.0 + num2 * 270.0;
			double num4 = (double)num / 2.0 * Math.Cos(Math.PI * num3 / 180.0);
			double num5 = (double)num / 2.0 * Math.Sin(Math.PI * num3 / 180.0);
			e.Graphics.DrawLine(val, 0f, 0f, (float)num4, (float)num5);
			e.Graphics.Restore(val2);
			((Control)this).OnPaint(e);
		}

		protected override void OnMouseDown(MouseEventArgs e)
		{
			dragging = true;
			beginDragY = e.Y;
			beginDragValue = value;
			((UserControl)this).OnMouseDown(e);
		}

		protected override void OnMouseUp(MouseEventArgs e)
		{
			dragging = false;
			((Control)this).OnMouseUp(e);
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			if (dragging)
			{
				int num = beginDragY - e.Y;
				double num2 = (maximum - minimum) * ((double)num / 150.0);
				double num3 = beginDragValue + num2;
				if (num3 < minimum)
				{
					num3 = minimum;
				}
				if (num3 > maximum)
				{
					num3 = maximum;
				}
				SetValue(num3, raiseEvents: true);
			}
			((Control)this).OnMouseMove(e);
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((ContainerControl)this).Dispose(disposing);
		}

		private void InitializeComponent()
		{
			((Control)this).SuspendLayout();
			((ContainerControl)this).AutoScaleDimensions = new SizeF(6f, 13f);
			((ContainerControl)this).AutoScaleMode = (AutoScaleMode)1;
			((Control)this).Name = "Pot";
			((Control)this).Size = new Size(32, 32);
			((Control)this).ResumeLayout(false);
		}
	}
	public class VolumeMeter : Control
	{
		private Brush foregroundBrush;

		private float amplitude;

		private IContainer components;

		[DefaultValue(-3.0)]
		public float Amplitude
		{
			get
			{
				return amplitude;
			}
			set
			{
				amplitude = value;
				((Control)this).Invalidate();
			}
		}

		[DefaultValue(-60.0)]
		public float MinDb { get; set; }

		[DefaultValue(18.0)]
		public float MaxDb { get; set; }

		[DefaultValue(/*Could not decode attribute arguments.*/)]
		public Orientation Orientation { get; set; }

		public VolumeMeter()
		{
			((Control)this).SetStyle((ControlStyles)139266, true);
			MinDb = -60f;
			MaxDb = 18f;
			Amplitude = 0f;
			Orientation = (Orientation)1;
			InitializeComponent();
			((Control)this).OnForeColorChanged(EventArgs.Empty);
		}

		protected override void OnForeColorChanged(EventArgs e)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			foregroundBrush = (Brush)new SolidBrush(((Control)this).ForeColor);
			((Control)this).OnForeColorChanged(e);
		}

		protected override void OnPaint(PaintEventArgs pe)
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			pe.Graphics.DrawRectangle(Pens.Black, 0, 0, ((Control)this).Width - 1, ((Control)this).Height - 1);
			double num = 20.0 * Math.Log10(Amplitude);
			if (num < (double)MinDb)
			{
				num = MinDb;
			}
			if (num > (double)MaxDb)
			{
				num = MaxDb;
			}
			double num2 = (num - (double)MinDb) / (double)(MaxDb - MinDb);
			int num3 = ((Control)this).Width - 2;
			int num4 = ((Control)this).Height - 2;
			if ((int)Orientation == 0)
			{
				num3 = (int)((double)num3 * num2);
				pe.Graphics.FillRectangle(foregroundBrush, 1, 1, num3, num4);
			}
			else
			{
				num4 = (int)((double)num4 * num2);
				pe.Graphics.FillRectangle(foregroundBrush, 1, ((Control)this).Height - 1 - num4, num3, num4);
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((Control)this).Dispose(disposing);
		}

		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
		}
	}
	public class VolumeSlider : UserControl
	{
		private Container components;

		private float volume = 1f;

		private float MinDb = -48f;

		[DefaultValue(1f)]
		public float Volume
		{
			get
			{
				return volume;
			}
			set
			{
				if (value < 0f)
				{
					value = 0f;
				}
				if (value > 1f)
				{
					value = 1f;
				}
				if (volume != value)
				{
					volume = value;
					if (this.VolumeChanged != null)
					{
						this.VolumeChanged(this, EventArgs.Empty);
					}
					((Control)this).Invalidate();
				}
			}
		}

		public event EventHandler VolumeChanged;

		public VolumeSlider()
		{
			InitializeComponent();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((ContainerControl)this).Dispose(disposing);
		}

		private void InitializeComponent()
		{
			((Control)this).Name = "VolumeSlider";
			((Control)this).Size = new Size(96, 16);
		}

		protected override void OnPaint(PaintEventArgs pe)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			StringFormat val = new StringFormat();
			val.LineAlignment = (StringAlignment)1;
			val.Alignment = (StringAlignment)1;
			pe.Graphics.DrawRectangle(Pens.Black, 0, 0, ((Control)this).Width - 1, ((Control)this).Height - 1);
			float num = 20f * (float)Math.Log10(Volume);
			float num2 = 1f - num / MinDb;
			pe.Graphics.FillRectangle(Brushes.LightGreen, 1, 1, (int)((float)(((Control)this).Width - 2) * num2), ((Control)this).Height - 2);
			string text = $"{num:F2} dB";
			pe.Graphics.DrawString(text, ((Control)this).Font, Brushes.Black, (RectangleF)((Control)this).ClientRectangle, val);
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			if ((int)e.Button == 1048576)
			{
				SetVolumeFromMouse(e.X);
			}
			((Control)this).OnMouseMove(e);
		}

		protected override void OnMouseDown(MouseEventArgs e)
		{
			SetVolumeFromMouse(e.X);
			((UserControl)this).OnMouseDown(e);
		}

		private void SetVolumeFromMouse(int x)
		{
			float num = (1f - (float)x / (float)((Control)this).Width) * MinDb;
			if (x <= 0)
			{
				Volume = 0f;
			}
			else
			{
				Volume = (float)Math.Pow(10.0, num / 20f);
			}
		}
	}
	public class WaveformPainter : Control
	{
		private Pen foregroundPen;

		private List<float> samples = new List<float>(1000);

		private int maxSamples;

		private int insertPos;

		private IContainer components;

		public WaveformPainter()
		{
			((Control)this).SetStyle((ControlStyles)139266, true);
			InitializeComponent();
			((Control)this).OnForeColorChanged(EventArgs.Empty);
			((Control)this).OnResize(EventArgs.Empty);
		}

		protected override void OnResize(EventArgs e)
		{
			maxSamples = ((Control)this).Width;
			((Control)this).OnResize(e);
		}

		protected override void OnForeColorChanged(EventArgs e)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			foregroundPen = new Pen(((Control)this).ForeColor);
			((Control)this).OnForeColorChanged(e);
		}

		public void AddMax(float maxSample)
		{
			if (maxSamples != 0)
			{
				if (samples.Count <= maxSamples)
				{
					samples.Add(maxSample);
				}
				else if (insertPos < maxSamples)
				{
					samples[insertPos] = maxSample;
				}
				insertPos++;
				insertPos %= maxSamples;
				((Control)this).Invalidate();
			}
		}

		protected override void OnPaint(PaintEventArgs pe)
		{
			((Control)this).OnPaint(pe);
			for (int i = 0; i < ((Control)this).Width; i++)
			{
				float num = (float)((Control)this).Height * GetSample(i - ((Control)this).Width + insertPos);
				float num2 = ((float)((Control)this).Height - num) / 2f;
				pe.Graphics.DrawLine(foregroundPen, (float)i, num2, (float)i, num2 + num);
			}
		}

		private float GetSample(int index)
		{
			if (index < 0)
			{
				index += maxSamples;
			}
			if ((index >= 0) & (index < samples.Count))
			{
				return samples[index];
			}
			return 0f;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((Control)this).Dispose(disposing);
		}

		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
		}
	}
	public class WaveViewer : UserControl
	{
		private Container components;

		private WaveStream waveStream;

		private int samplesPerPixel = 128;

		private long startPosition;

		private int bytesPerSample;

		public WaveStream WaveStream
		{
			get
			{
				return waveStream;
			}
			set
			{
				waveStream = value;
				if (waveStream != null)
				{
					bytesPerSample = waveStream.WaveFormat.BitsPerSample / 8 * waveStream.WaveFormat.Channels;
				}
				((Control)this).Invalidate();
			}
		}

		public int SamplesPerPixel
		{
			get
			{
				return samplesPerPixel;
			}
			set
			{
				samplesPerPixel = value;
				((Control)this).Invalidate();
			}
		}

		public long StartPosition
		{
			get
			{
				return startPosition;
			}
			set
			{
				startPosition = value;
			}
		}

		public WaveViewer()
		{
			InitializeComponent();
			((Control)this).DoubleBuffered = true;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((ContainerControl)this).Dispose(disposing);
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			if (waveStream != null)
			{
				((Stream)(object)waveStream).Position = 0L;
				byte[] array = new byte[samplesPerPixel * bytesPerSample];
				((Stream)(object)waveStream).Position = startPosition + e.ClipRectangle.Left * bytesPerSample * samplesPerPixel;
				for (float num = e.ClipRectangle.X; num < (float)e.ClipRectangle.Right; num += 1f)
				{
					short num2 = 0;
					short num3 = 0;
					int num4 = ((Stream)(object)waveStream).Read(array, 0, samplesPerPixel * bytesPerSample);
					if (num4 == 0)
					{
						break;
					}
					for (int i = 0; i < num4; i += 2)
					{
						short num5 = BitConverter.ToInt16(array, i);
						if (num5 < num2)
						{
							num2 = num5;
						}
						if (num5 > num3)
						{
							num3 = num5;
						}
					}
					float num6 = ((float)num2 - -32768f) / 65535f;
					float num7 = ((float)num3 - -32768f) / 65535f;
					e.Graphics.DrawLine(Pens.Black, num, (float)((Control)this).Height * num6, num, (float)((Control)this).Height * num7);
				}
			}
			((Control)this).OnPaint(e);
		}

		private void InitializeComponent()
		{
			components = new Container();
		}
	}
}

NAudio.WinMM.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using Microsoft.Win32;
using NAudio.CoreAudioApi;
using NAudio.Mixer;
using NAudio.Utils;
using NAudio.Wave.Compression;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("NAudio.WinMM")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2021")]
[assembly: AssemblyFileVersion("2.0.1.0")]
[assembly: AssemblyInformationalVersion("2.0.1")]
[assembly: AssemblyProduct("NAudio.WinMM")]
[assembly: AssemblyTitle("NAudio.WinMM")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: AssemblyVersion("2.0.1.0")]
namespace NAudio.Mixer
{
	public class BooleanMixerControl : MixerControl
	{
		private MixerInterop.MIXERCONTROLDETAILS_BOOLEAN boolDetails;

		public bool Value
		{
			get
			{
				GetControlDetails();
				return boolDetails.fValue == 1;
			}
			set
			{
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				boolDetails.fValue = (value ? 1 : 0);
				mixerControlDetails.paDetails = Marshal.AllocHGlobal(Marshal.SizeOf(boolDetails));
				Marshal.StructureToPtr(boolDetails, mixerControlDetails.paDetails, fDeleteOld: false);
				MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails");
				Marshal.FreeHGlobal(mixerControlDetails.paDetails);
			}
		}

		internal BooleanMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
			boolDetails = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_BOOLEAN>(pDetails);
		}
	}
	public class CustomMixerControl : MixerControl
	{
		internal CustomMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
		}
	}
	public class ListTextMixerControl : MixerControl
	{
		internal ListTextMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
		}
	}
	public class Mixer
	{
		private MixerInterop.MIXERCAPS caps;

		private IntPtr mixerHandle;

		private MixerFlags mixerHandleType;

		public static int NumberOfDevices => MixerInterop.mixerGetNumDevs();

		public int DestinationCount => (int)caps.cDestinations;

		public string Name => caps.szPname;

		public Manufacturers Manufacturer => (Manufacturers)caps.wMid;

		public int ProductID => caps.wPid;

		public IEnumerable<MixerLine> Destinations
		{
			get
			{
				for (int destination = 0; destination < DestinationCount; destination++)
				{
					yield return GetDestination(destination);
				}
			}
		}

		public static IEnumerable<Mixer> Mixers
		{
			get
			{
				for (int device = 0; device < NumberOfDevices; device++)
				{
					yield return new Mixer(device);
				}
			}
		}

		public Mixer(int mixerIndex)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (mixerIndex < 0 || mixerIndex >= NumberOfDevices)
			{
				throw new ArgumentOutOfRangeException("mixerID");
			}
			caps = default(MixerInterop.MIXERCAPS);
			MmException.Try(MixerInterop.mixerGetDevCaps((IntPtr)mixerIndex, ref caps, Marshal.SizeOf(caps)), "mixerGetDevCaps");
			mixerHandle = (IntPtr)mixerIndex;
			mixerHandleType = MixerFlags.Mixer;
		}

		public MixerLine GetDestination(int destinationIndex)
		{
			if (destinationIndex < 0 || destinationIndex >= DestinationCount)
			{
				throw new ArgumentOutOfRangeException("destinationIndex");
			}
			return new MixerLine(mixerHandle, destinationIndex, mixerHandleType);
		}
	}
	public abstract class MixerControl
	{
		internal MixerInterop.MIXERCONTROL mixerControl;

		internal MixerInterop.MIXERCONTROLDETAILS mixerControlDetails;

		protected IntPtr mixerHandle;

		protected int nChannels;

		protected MixerFlags mixerHandleType;

		public string Name => mixerControl.szName;

		public MixerControlType ControlType => mixerControl.dwControlType;

		public bool IsBoolean => IsControlBoolean(mixerControl.dwControlType);

		public bool IsListText => IsControlListText(mixerControl.dwControlType);

		public bool IsSigned => IsControlSigned(mixerControl.dwControlType);

		public bool IsUnsigned => IsControlUnsigned(mixerControl.dwControlType);

		public bool IsCustom => IsControlCustom(mixerControl.dwControlType);

		public static IList<MixerControl> GetMixerControls(IntPtr mixerHandle, MixerLine mixerLine, MixerFlags mixerHandleType)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			List<MixerControl> list = new List<MixerControl>();
			if (mixerLine.ControlsCount > 0)
			{
				int num = Marshal.SizeOf<MixerInterop.MIXERCONTROL>();
				MixerInterop.MIXERLINECONTROLS mixerLineControls = default(MixerInterop.MIXERLINECONTROLS);
				IntPtr intPtr = Marshal.AllocHGlobal(num * mixerLine.ControlsCount);
				mixerLineControls.cbStruct = Marshal.SizeOf(mixerLineControls);
				mixerLineControls.dwLineID = mixerLine.LineId;
				mixerLineControls.cControls = mixerLine.ControlsCount;
				mixerLineControls.pamxctrl = intPtr;
				mixerLineControls.cbmxctrl = Marshal.SizeOf<MixerInterop.MIXERCONTROL>();
				try
				{
					MmResult val = MixerInterop.mixerGetLineControls(mixerHandle, ref mixerLineControls, MixerFlags.Mixer | mixerHandleType);
					if ((int)val != 0)
					{
						throw new MmException(val, "mixerGetLineControls");
					}
					for (int i = 0; i < mixerLineControls.cControls; i++)
					{
						MixerInterop.MIXERCONTROL mIXERCONTROL = Marshal.PtrToStructure<MixerInterop.MIXERCONTROL>((IntPtr)(intPtr.ToInt64() + num * i));
						MixerControl item = GetMixerControl(mixerHandle, mixerLine.LineId, mIXERCONTROL.dwControlID, mixerLine.Channels, mixerHandleType);
						list.Add(item);
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
				}
			}
			return list;
		}

		public static MixerControl GetMixerControl(IntPtr mixerHandle, int nLineId, int controlId, int nChannels, MixerFlags mixerFlags)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			MixerInterop.MIXERLINECONTROLS mixerLineControls = default(MixerInterop.MIXERLINECONTROLS);
			MixerInterop.MIXERCONTROL structure = default(MixerInterop.MIXERCONTROL);
			IntPtr intPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(structure));
			mixerLineControls.cbStruct = Marshal.SizeOf(mixerLineControls);
			mixerLineControls.cControls = 1;
			mixerLineControls.dwControlID = controlId;
			mixerLineControls.cbmxctrl = Marshal.SizeOf(structure);
			mixerLineControls.pamxctrl = intPtr;
			mixerLineControls.dwLineID = nLineId;
			MmResult val = MixerInterop.mixerGetLineControls(mixerHandle, ref mixerLineControls, MixerFlags.ListText | mixerFlags);
			if ((int)val != 0)
			{
				Marshal.FreeCoTaskMem(intPtr);
				throw new MmException(val, "mixerGetLineControls");
			}
			structure = Marshal.PtrToStructure<MixerInterop.MIXERCONTROL>(mixerLineControls.pamxctrl);
			Marshal.FreeCoTaskMem(intPtr);
			if (IsControlBoolean(structure.dwControlType))
			{
				return new BooleanMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			if (IsControlSigned(structure.dwControlType))
			{
				return new SignedMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			if (IsControlUnsigned(structure.dwControlType))
			{
				return new UnsignedMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			if (IsControlListText(structure.dwControlType))
			{
				return new ListTextMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			if (IsControlCustom(structure.dwControlType))
			{
				return new CustomMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			throw new InvalidOperationException($"Unknown mixer control type {structure.dwControlType}");
		}

		protected void GetControlDetails()
		{
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			mixerControlDetails.cbStruct = Marshal.SizeOf(mixerControlDetails);
			mixerControlDetails.dwControlID = mixerControl.dwControlID;
			if (IsCustom)
			{
				mixerControlDetails.cChannels = 0;
			}
			else if ((mixerControl.fdwControl & (true ? 1u : 0u)) != 0)
			{
				mixerControlDetails.cChannels = 1;
			}
			else
			{
				mixerControlDetails.cChannels = nChannels;
			}
			if ((mixerControl.fdwControl & 2u) != 0)
			{
				mixerControlDetails.hwndOwner = (IntPtr)mixerControl.cMultipleItems;
			}
			else if (IsCustom)
			{
				mixerControlDetails.hwndOwner = IntPtr.Zero;
			}
			else
			{
				mixerControlDetails.hwndOwner = IntPtr.Zero;
			}
			if (IsBoolean)
			{
				mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_BOOLEAN>();
			}
			else if (IsListText)
			{
				mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_LISTTEXT>();
			}
			else if (IsSigned)
			{
				mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_SIGNED>();
			}
			else if (IsUnsigned)
			{
				mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_UNSIGNED>();
			}
			else
			{
				mixerControlDetails.cbDetails = mixerControl.Metrics.customData;
			}
			int num = mixerControlDetails.cbDetails * mixerControlDetails.cChannels;
			if ((mixerControl.fdwControl & 2u) != 0)
			{
				num *= (int)mixerControl.cMultipleItems;
			}
			IntPtr intPtr = Marshal.AllocCoTaskMem(num);
			mixerControlDetails.paDetails = intPtr;
			MmResult val = MixerInterop.mixerGetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType);
			if ((int)val == 0)
			{
				GetDetails(mixerControlDetails.paDetails);
			}
			Marshal.FreeCoTaskMem(intPtr);
			if ((int)val != 0)
			{
				throw new MmException(val, "mixerGetControlDetails");
			}
		}

		protected abstract void GetDetails(IntPtr pDetails);

		private static bool IsControlBoolean(MixerControlType controlType)
		{
			switch (controlType)
			{
			case MixerControlType.BooleanMeter:
			case MixerControlType.Boolean:
			case MixerControlType.OnOff:
			case MixerControlType.Mute:
			case MixerControlType.Mono:
			case MixerControlType.Loudness:
			case MixerControlType.StereoEnhance:
			case MixerControlType.Button:
			case MixerControlType.SingleSelect:
			case MixerControlType.Mux:
			case MixerControlType.MultipleSelect:
			case MixerControlType.Mixer:
				return true;
			default:
				return false;
			}
		}

		private static bool IsControlListText(MixerControlType controlType)
		{
			if (controlType == MixerControlType.Equalizer || (uint)(controlType - 1879113728) <= 1u || (uint)(controlType - 1895890944) <= 1u)
			{
				return true;
			}
			return false;
		}

		private static bool IsControlSigned(MixerControlType controlType)
		{
			switch (controlType)
			{
			case MixerControlType.SignedMeter:
			case MixerControlType.PeakMeter:
			case MixerControlType.Signed:
			case MixerControlType.Decibels:
			case MixerControlType.Slider:
			case MixerControlType.Pan:
			case MixerControlType.QSoundPan:
				return true;
			default:
				return false;
			}
		}

		private static bool IsControlUnsigned(MixerControlType controlType)
		{
			switch (controlType)
			{
			case MixerControlType.UnsignedMeter:
			case MixerControlType.Unsigned:
			case MixerControlType.Percent:
			case MixerControlType.Fader:
			case MixerControlType.Volume:
			case MixerControlType.Bass:
			case MixerControlType.Treble:
			case MixerControlType.Equalizer:
			case MixerControlType.MicroTime:
			case MixerControlType.MilliTime:
				return true;
			default:
				return false;
			}
		}

		private static bool IsControlCustom(MixerControlType controlType)
		{
			return controlType == MixerControlType.Custom;
		}

		public override string ToString()
		{
			return $"{Name} {ControlType}";
		}
	}
	[Flags]
	internal enum MixerControlClass
	{
		Custom = 0,
		Meter = 0x10000000,
		Switch = 0x20000000,
		Number = 0x30000000,
		Slider = 0x40000000,
		Fader = 0x50000000,
		Time = 0x60000000,
		List = 0x70000000,
		Mask = 0x70000000
	}
	[Flags]
	internal enum MixerControlSubclass
	{
		SwitchBoolean = 0,
		SwitchButton = 0x1000000,
		MeterPolled = 0,
		TimeMicrosecs = 0,
		TimeMillisecs = 0x1000000,
		ListSingle = 0,
		ListMultiple = 0x1000000,
		Mask = 0xF000000
	}
	[Flags]
	internal enum MixerControlUnits
	{
		Custom = 0,
		Boolean = 0x10000,
		Signed = 0x20000,
		Unsigned = 0x30000,
		Decibels = 0x40000,
		Percent = 0x50000,
		Mask = 0xFF0000
	}
	public enum MixerControlType
	{
		Custom = 0,
		BooleanMeter = 268500992,
		SignedMeter = 268566528,
		PeakMeter = 268566529,
		UnsignedMeter = 268632064,
		Boolean = 536936448,
		OnOff = 536936449,
		Mute = 536936450,
		Mono = 536936451,
		Loudness = 536936452,
		StereoEnhance = 536936453,
		Button = 553713664,
		Decibels = 805568512,
		Signed = 805437440,
		Unsigned = 805502976,
		Percent = 805634048,
		Slider = 1073872896,
		Pan = 1073872897,
		QSoundPan = 1073872898,
		Fader = 1342373888,
		Volume = 1342373889,
		Bass = 1342373890,
		Treble = 1342373891,
		Equalizer = 1342373892,
		SingleSelect = 1879113728,
		Mux = 1879113729,
		MultipleSelect = 1895890944,
		Mixer = 1895890945,
		MicroTime = 1610809344,
		MilliTime = 1627586560
	}
	[Flags]
	public enum MixerFlags
	{
		Handle = int.MinValue,
		Mixer = 0,
		MixerHandle = int.MinValue,
		WaveOut = 0x10000000,
		WaveOutHandle = -1879048192,
		WaveIn = 0x20000000,
		WaveInHandle = -1610612736,
		MidiOut = 0x30000000,
		MidiOutHandle = -1342177280,
		MidiIn = 0x40000000,
		MidiInHandle = -1073741824,
		Aux = 0x50000000,
		Value = 0,
		ListText = 1,
		QueryMask = 0xF,
		All = 0,
		OneById = 1,
		OneByType = 2,
		GetLineInfoOfDestination = 0,
		GetLineInfoOfSource = 1,
		GetLineInfoOfLineId = 2,
		GetLineInfoOfComponentType = 3,
		GetLineInfoOfTargetType = 4,
		GetLineInfoOfQueryMask = 0xF
	}
	internal class MixerInterop
	{
		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
		public struct MIXERCONTROLDETAILS
		{
			public int cbStruct;

			public int dwControlID;

			public int cChannels;

			public IntPtr hwndOwner;

			public int cbDetails;

			public IntPtr paDetails;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERCAPS
		{
			public ushort wMid;

			public ushort wPid;

			public uint vDriverVersion;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
			public string szPname;

			public uint fdwSupport;

			public uint cDestinations;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERLINECONTROLS
		{
			public int cbStruct;

			public int dwLineID;

			public int dwControlID;

			public int cControls;

			public int cbmxctrl;

			public IntPtr pamxctrl;
		}

		[Flags]
		public enum MIXERLINE_LINEF
		{
			MIXERLINE_LINEF_ACTIVE = 1,
			MIXERLINE_LINEF_DISCONNECTED = 0x8000,
			MIXERLINE_LINEF_SOURCE = int.MinValue
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERLINE
		{
			public int cbStruct;

			public int dwDestination;

			public int dwSource;

			public int dwLineID;

			public MIXERLINE_LINEF fdwLine;

			public IntPtr dwUser;

			public MixerLineComponentType dwComponentType;

			public int cChannels;

			public int cConnections;

			public int cControls;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
			public string szShortName;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
			public string szName;

			public uint dwType;

			public uint dwDeviceID;

			public ushort wMid;

			public ushort wPid;

			public uint vDriverVersion;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
			public string szPname;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct Bounds
		{
			public int minimum;

			public int maximum;

			public int reserved2;

			public int reserved3;

			public int reserved4;

			public int reserved5;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct Metrics
		{
			public int step;

			public int customData;

			public int reserved2;

			public int reserved3;

			public int reserved4;

			public int reserved5;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERCONTROL
		{
			public uint cbStruct;

			public int dwControlID;

			public MixerControlType dwControlType;

			public uint fdwControl;

			public uint cMultipleItems;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
			public string szShortName;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
			public string szName;

			public Bounds Bounds;

			public Metrics Metrics;
		}

		public struct MIXERCONTROLDETAILS_BOOLEAN
		{
			public int fValue;
		}

		public struct MIXERCONTROLDETAILS_SIGNED
		{
			public int lValue;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERCONTROLDETAILS_LISTTEXT
		{
			public uint dwParam1;

			public uint dwParam2;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
			public string szName;
		}

		public struct MIXERCONTROLDETAILS_UNSIGNED
		{
			public uint dwValue;
		}

		public const uint MIXERCONTROL_CONTROLF_UNIFORM = 1u;

		public const uint MIXERCONTROL_CONTROLF_MULTIPLE = 2u;

		public const uint MIXERCONTROL_CONTROLF_DISABLED = 2147483648u;

		public const int MAXPNAMELEN = 32;

		public const int MIXER_SHORT_NAME_CHARS = 16;

		public const int MIXER_LONG_NAME_CHARS = 64;

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern int mixerGetNumDevs();

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerOpen(out IntPtr hMixer, int uMxId, IntPtr dwCallback, IntPtr dwInstance, MixerFlags dwOpenFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerClose(IntPtr hMixer);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetControlDetails(IntPtr hMixer, ref MIXERCONTROLDETAILS mixerControlDetails, MixerFlags dwDetailsFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetDevCaps(IntPtr nMixerID, ref MIXERCAPS mixerCaps, int mixerCapsSize);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetID(IntPtr hMixer, out int mixerID, MixerFlags dwMixerIDFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetLineControls(IntPtr hMixer, ref MIXERLINECONTROLS mixerLineControls, MixerFlags dwControlFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetLineInfo(IntPtr hMixer, ref MIXERLINE mixerLine, MixerFlags dwInfoFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerMessage(IntPtr hMixer, uint nMessage, IntPtr dwParam1, IntPtr dwParam2);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerSetControlDetails(IntPtr hMixer, ref MIXERCONTROLDETAILS mixerControlDetails, MixerFlags dwDetailsFlags);
	}
	public class MixerLine
	{
		private MixerInterop.MIXERLINE mixerLine;

		private IntPtr mixerHandle;

		private MixerFlags mixerHandleType;

		public string Name => mixerLine.szName;

		public string ShortName => mixerLine.szShortName;

		public int LineId => mixerLine.dwLineID;

		public MixerLineComponentType ComponentType => mixerLine.dwComponentType;

		public string TypeDescription => mixerLine.dwComponentType switch
		{
			MixerLineComponentType.DestinationUndefined => "Undefined Destination", 
			MixerLineComponentType.DestinationDigital => "Digital Destination", 
			MixerLineComponentType.DestinationLine => "Line Level Destination", 
			MixerLineComponentType.DestinationMonitor => "Monitor Destination", 
			MixerLineComponentType.DestinationSpeakers => "Speakers Destination", 
			MixerLineComponentType.DestinationHeadphones => "Headphones Destination", 
			MixerLineComponentType.DestinationTelephone => "Telephone Destination", 
			MixerLineComponentType.DestinationWaveIn => "Wave Input Destination", 
			MixerLineComponentType.DestinationVoiceIn => "Voice Recognition Destination", 
			MixerLineComponentType.SourceUndefined => "Undefined Source", 
			MixerLineComponentType.SourceDigital => "Digital Source", 
			MixerLineComponentType.SourceLine => "Line Level Source", 
			MixerLineComponentType.SourceMicrophone => "Microphone Source", 
			MixerLineComponentType.SourceSynthesizer => "Synthesizer Source", 
			MixerLineComponentType.SourceCompactDisc => "Compact Disk Source", 
			MixerLineComponentType.SourceTelephone => "Telephone Source", 
			MixerLineComponentType.SourcePcSpeaker => "PC Speaker Source", 
			MixerLineComponentType.SourceWaveOut => "Wave Out Source", 
			MixerLineComponentType.SourceAuxiliary => "Auxiliary Source", 
			MixerLineComponentType.SourceAnalog => "Analog Source", 
			_ => "Invalid Component Type", 
		};

		public int Channels => mixerLine.cChannels;

		public int SourceCount => mixerLine.cConnections;

		public int ControlsCount => mixerLine.cControls;

		public bool IsActive => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_ACTIVE) != 0;

		public bool IsDisconnected => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_DISCONNECTED) != 0;

		public bool IsSource => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_SOURCE) != 0;

		public IEnumerable<MixerControl> Controls => MixerControl.GetMixerControls(mixerHandle, this, mixerHandleType);

		public IEnumerable<MixerLine> Sources
		{
			get
			{
				for (int source = 0; source < SourceCount; source++)
				{
					yield return GetSource(source);
				}
			}
		}

		public string TargetName => mixerLine.szPname;

		public MixerLine(IntPtr mixerHandle, int destinationIndex, MixerFlags mixerHandleType)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			this.mixerHandle = mixerHandle;
			this.mixerHandleType = mixerHandleType;
			mixerLine = default(MixerInterop.MIXERLINE);
			mixerLine.cbStruct = Marshal.SizeOf(mixerLine);
			mixerLine.dwDestination = destinationIndex;
			MmException.Try(MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.Mixer), "mixerGetLineInfo");
		}

		public MixerLine(IntPtr mixerHandle, int destinationIndex, int sourceIndex, MixerFlags mixerHandleType)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			this.mixerHandle = mixerHandle;
			this.mixerHandleType = mixerHandleType;
			mixerLine = default(MixerInterop.MIXERLINE);
			mixerLine.cbStruct = Marshal.SizeOf(mixerLine);
			mixerLine.dwDestination = destinationIndex;
			mixerLine.dwSource = sourceIndex;
			MmException.Try(MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.ListText), "mixerGetLineInfo");
		}

		public static int GetMixerIdForWaveIn(int waveInDevice)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			int mixerID = -1;
			MmException.Try(MixerInterop.mixerGetID((IntPtr)waveInDevice, out mixerID, MixerFlags.WaveIn), "mixerGetID");
			return mixerID;
		}

		public MixerLine GetSource(int sourceIndex)
		{
			if (sourceIndex < 0 || sourceIndex >= SourceCount)
			{
				throw new ArgumentOutOfRangeException("sourceIndex");
			}
			return new MixerLine(mixerHandle, mixerLine.dwDestination, sourceIndex, mixerHandleType);
		}

		public override string ToString()
		{
			return $"{Name} {TypeDescription} ({ControlsCount} controls, ID={mixerLine.dwLineID})";
		}
	}
	public enum MixerLineComponentType
	{
		DestinationUndefined = 0,
		DestinationDigital = 1,
		DestinationLine = 2,
		DestinationMonitor = 3,
		DestinationSpeakers = 4,
		DestinationHeadphones = 5,
		DestinationTelephone = 6,
		DestinationWaveIn = 7,
		DestinationVoiceIn = 8,
		SourceUndefined = 4096,
		SourceDigital = 4097,
		SourceLine = 4098,
		SourceMicrophone = 4099,
		SourceSynthesizer = 4100,
		SourceCompactDisc = 4101,
		SourceTelephone = 4102,
		SourcePcSpeaker = 4103,
		SourceWaveOut = 4104,
		SourceAuxiliary = 4105,
		SourceAnalog = 4106
	}
	public class SignedMixerControl : MixerControl
	{
		private MixerInterop.MIXERCONTROLDETAILS_SIGNED signedDetails;

		public int Value
		{
			get
			{
				GetControlDetails();
				return signedDetails.lValue;
			}
			set
			{
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				signedDetails.lValue = value;
				mixerControlDetails.paDetails = Marshal.AllocHGlobal(Marshal.SizeOf(signedDetails));
				Marshal.StructureToPtr(signedDetails, mixerControlDetails.paDetails, fDeleteOld: false);
				MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails");
				Marshal.FreeHGlobal(mixerControlDetails.paDetails);
			}
		}

		public int MinValue => mixerControl.Bounds.minimum;

		public int MaxValue => mixerControl.Bounds.maximum;

		public double Percent
		{
			get
			{
				return 100.0 * (double)(Value - MinValue) / (double)(MaxValue - MinValue);
			}
			set
			{
				Value = (int)((double)MinValue + value / 100.0 * (double)(MaxValue - MinValue));
			}
		}

		internal SignedMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
			signedDetails = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_SIGNED>(mixerControlDetails.paDetails);
		}

		public override string ToString()
		{
			return $"{base.ToString()} {Percent}%";
		}
	}
	public class UnsignedMixerControl : MixerControl
	{
		private MixerInterop.MIXERCONTROLDETAILS_UNSIGNED[] unsignedDetails;

		public uint Value
		{
			get
			{
				GetControlDetails();
				return unsignedDetails[0].dwValue;
			}
			set
			{
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				int num = Marshal.SizeOf(unsignedDetails[0]);
				mixerControlDetails.paDetails = Marshal.AllocHGlobal(num * nChannels);
				for (int i = 0; i < nChannels; i++)
				{
					unsignedDetails[i].dwValue = value;
					long num2 = mixerControlDetails.paDetails.ToInt64() + num * i;
					Marshal.StructureToPtr(unsignedDetails[i], (IntPtr)num2, fDeleteOld: false);
				}
				MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails");
				Marshal.FreeHGlobal(mixerControlDetails.paDetails);
			}
		}

		public uint MinValue => (uint)mixerControl.Bounds.minimum;

		public uint MaxValue => (uint)mixerControl.Bounds.maximum;

		public double Percent
		{
			get
			{
				return 100.0 * (double)(Value - MinValue) / (double)(MaxValue - MinValue);
			}
			set
			{
				Value = (uint)((double)MinValue + value / 100.0 * (double)(MaxValue - MinValue));
			}
		}

		internal UnsignedMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
			unsignedDetails = new MixerInterop.MIXERCONTROLDETAILS_UNSIGNED[nChannels];
			for (int i = 0; i < nChannels; i++)
			{
				unsignedDetails[i] = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_UNSIGNED>(mixerControlDetails.paDetails);
			}
		}

		public override string ToString()
		{
			return $"{base.ToString()} {Percent}%";
		}
	}
}
namespace NAudio.Wave
{
	internal enum AcmMetrics
	{
		CountDrivers = 1,
		CountCodecs = 2,
		CountConverters = 3,
		CountFilters = 4,
		CountDisabled = 5,
		CountHardware = 6,
		CountLocalDrivers = 20,
		CountLocalCodecs = 21,
		CountLocalConverters = 22,
		CountLocalFilters = 23,
		CountLocalDisabled = 24,
		HardwareWaveInput = 30,
		HardwareWaveOutput = 31,
		MaxSizeFormat = 50,
		MaxSizeFilter = 51,
		DriverSupport = 100,
		DriverPriority = 101
	}
	[Flags]
	internal enum AcmStreamConvertFlags
	{
		BlockAlign = 4,
		Start = 0x10,
		End = 0x20
	}
	[StructLayout(LayoutKind.Explicit)]
	public struct MmTime
	{
		public const int TIME_MS = 1;

		public const int TIME_SAMPLES = 2;

		public const int TIME_BYTES = 4;

		[FieldOffset(0)]
		public uint wType;

		[FieldOffset(4)]
		public uint ms;

		[FieldOffset(4)]
		public uint sample;

		[FieldOffset(4)]
		public uint cb;

		[FieldOffset(4)]
		public uint ticks;

		[FieldOffset(4)]
		public byte smpteHour;

		[FieldOffset(5)]
		public byte smpteMin;

		[FieldOffset(6)]
		public byte smpteSec;

		[FieldOffset(7)]
		public byte smpteFrame;

		[FieldOffset(8)]
		public byte smpteFps;

		[FieldOffset(9)]
		public byte smpteDummy;

		[FieldOffset(10)]
		public byte smptePad0;

		[FieldOffset(11)]
		public byte smptePad1;

		[FieldOffset(4)]
		public uint midiSongPtrPos;
	}
	public enum WaveCallbackStrategy
	{
		FunctionCallback,
		NewWindow,
		ExistingWindow,
		Event
	}
	[StructLayout(LayoutKind.Sequential)]
	public sealed class WaveHeader
	{
		public IntPtr dataBuffer;

		public int bufferLength;

		public int bytesRecorded;

		public IntPtr userData;

		public WaveHeaderFlags flags;

		public int loops;

		public IntPtr next;

		public IntPtr reserved;
	}
	[Flags]
	public enum WaveHeaderFlags
	{
		BeginLoop = 4,
		Done = 1,
		EndLoop = 8,
		InQueue = 0x10,
		Prepared = 2
	}
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
	public struct WaveInCapabilities
	{
		private short manufacturerId;

		private short productId;

		private int driverVersion;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		private string productName;

		private SupportedWaveFormat supportedFormats;

		private short channels;

		private short reserved;

		private Guid manufacturerGuid;

		private Guid productGuid;

		private Guid nameGuid;

		private const int MaxProductNameLength = 32;

		public int Channels => channels;

		public string ProductName => productName;

		public Guid NameGuid => nameGuid;

		public Guid ProductGuid => productGuid;

		public Guid ManufacturerGuid => manufacturerGuid;

		public bool SupportsWaveFormat(SupportedWaveFormat waveFormat)
		{
			return (supportedFormats & waveFormat) == waveFormat;
		}
	}
	public static class WaveCapabilitiesHelpers
	{
		public static readonly Guid MicrosoftDefaultManufacturerId = new Guid("d5a47fa8-6d98-11d1-a21a-00a0c9223196");

		public static readonly Guid DefaultWaveOutGuid = new Guid("E36DC310-6D9A-11D1-A21A-00A0C9223196");

		public static readonly Guid DefaultWaveInGuid = new Guid("E36DC311-6D9A-11D1-A21A-00A0C9223196");

		public static string GetNameFromGuid(Guid guid)
		{
			string result = null;
			using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\MediaCategories"))
			{
				using RegistryKey registryKey2 = registryKey.OpenSubKey(guid.ToString("B"));
				if (registryKey2 != null)
				{
					result = registryKey2.GetValue("Name") as string;
				}
			}
			return result;
		}
	}
	public class WaveInterop
	{
		[Flags]
		public enum WaveInOutOpenFlags
		{
			CallbackNull = 0,
			CallbackFunction = 0x30000,
			CallbackEvent = 0x50000,
			CallbackWindow = 0x10000,
			CallbackThread = 0x20000
		}

		public enum WaveMessage
		{
			WaveInOpen = 958,
			WaveInClose = 959,
			WaveInData = 960,
			WaveOutClose = 956,
			WaveOutDone = 957,
			WaveOutOpen = 955
		}

		public delegate void WaveCallback(IntPtr hWaveOut, WaveMessage message, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved);

		[DllImport("winmm.dll")]
		public static extern int mmioStringToFOURCC([MarshalAs(UnmanagedType.LPStr)] string s, int flags);

		[DllImport("winmm.dll")]
		public static extern int waveOutGetNumDevs();

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutPrepareHeader(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutUnprepareHeader(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutWrite(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutOpen(out IntPtr hWaveOut, IntPtr uDeviceID, WaveFormat lpFormat, WaveCallback dwCallback, IntPtr dwInstance, WaveInOutOpenFlags dwFlags);

		[DllImport("winmm.dll", EntryPoint = "waveOutOpen")]
		public static extern MmResult waveOutOpenWindow(out IntPtr hWaveOut, IntPtr uDeviceID, WaveFormat lpFormat, IntPtr callbackWindowHandle, IntPtr dwInstance, WaveInOutOpenFlags dwFlags);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutReset(IntPtr hWaveOut);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutClose(IntPtr hWaveOut);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutPause(IntPtr hWaveOut);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutRestart(IntPtr hWaveOut);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutGetPosition(IntPtr hWaveOut, ref MmTime mmTime, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutSetVolume(IntPtr hWaveOut, int dwVolume);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutGetVolume(IntPtr hWaveOut, out int dwVolume);

		[DllImport("winmm.dll", CharSet = CharSet.Auto)]
		public static extern MmResult waveOutGetDevCaps(IntPtr deviceID, out WaveOutCapabilities waveOutCaps, int waveOutCapsSize);

		[DllImport("winmm.dll")]
		public static extern int waveInGetNumDevs();

		[DllImport("winmm.dll", CharSet = CharSet.Auto)]
		public static extern MmResult waveInGetDevCaps(IntPtr deviceID, out WaveInCapabilities waveInCaps, int waveInCapsSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInAddBuffer(IntPtr hWaveIn, WaveHeader pwh, int cbwh);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInClose(IntPtr hWaveIn);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInOpen(out IntPtr hWaveIn, IntPtr uDeviceID, WaveFormat lpFormat, WaveCallback dwCallback, IntPtr dwInstance, WaveInOutOpenFlags dwFlags);

		[DllImport("winmm.dll", EntryPoint = "waveInOpen")]
		public static extern MmResult waveInOpenWindow(out IntPtr hWaveIn, IntPtr uDeviceID, WaveFormat lpFormat, IntPtr callbackWindowHandle, IntPtr dwInstance, WaveInOutOpenFlags dwFlags);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInPrepareHeader(IntPtr hWaveIn, WaveHeader lpWaveInHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInUnprepareHeader(IntPtr hWaveIn, WaveHeader lpWaveInHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInReset(IntPtr hWaveIn);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInStart(IntPtr hWaveIn);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInStop(IntPtr hWaveIn);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInGetPosition(IntPtr hWaveIn, out MmTime mmTime, int uSize);
	}
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
	public struct WaveOutCapabilities
	{
		private short manufacturerId;

		private short productId;

		private int driverVersion;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		private string productName;

		private SupportedWaveFormat supportedFormats;

		private short channels;

		private short reserved;

		private WaveOutSupport support;

		private Guid manufacturerGuid;

		private Guid productGuid;

		private Guid nameGuid;

		private const int MaxProductNameLength = 32;

		public int Channels => channels;

		public bool SupportsPlaybackRateControl => (support & WaveOutSupport.PlaybackRate) == WaveOutSupport.PlaybackRate;

		public string ProductName => productName;

		public Guid NameGuid => nameGuid;

		public Guid ProductGuid => productGuid;

		public Guid ManufacturerGuid => manufacturerGuid;

		public bool SupportsWaveFormat(SupportedWaveFormat waveFormat)
		{
			return (supportedFormats & waveFormat) == waveFormat;
		}
	}
	[Flags]
	public enum SupportedWaveFormat
	{
		WAVE_FORMAT_1M08 = 1,
		WAVE_FORMAT_1S08 = 2,
		WAVE_FORMAT_1M16 = 4,
		WAVE_FORMAT_1S16 = 8,
		WAVE_FORMAT_2M08 = 0x10,
		WAVE_FORMAT_2S08 = 0x20,
		WAVE_FORMAT_2M16 = 0x40,
		WAVE_FORMAT_2S16 = 0x80,
		WAVE_FORMAT_4M08 = 0x100,
		WAVE_FORMAT_4S08 = 0x200,
		WAVE_FORMAT_4M16 = 0x400,
		WAVE_FORMAT_4S16 = 0x800,
		WAVE_FORMAT_44M08 = 0x100,
		WAVE_FORMAT_44S08 = 0x200,
		WAVE_FORMAT_44M16 = 0x400,
		WAVE_FORMAT_44S16 = 0x800,
		WAVE_FORMAT_48M08 = 0x1000,
		WAVE_FORMAT_48S08 = 0x2000,
		WAVE_FORMAT_48M16 = 0x4000,
		WAVE_FORMAT_48S16 = 0x8000,
		WAVE_FORMAT_96M08 = 0x10000,
		WAVE_FORMAT_96S08 = 0x20000,
		WAVE_FORMAT_96M16 = 0x40000,
		WAVE_FORMAT_96S16 = 0x80000
	}
	[Flags]
	internal enum WaveOutSupport
	{
		Pitch = 1,
		PlaybackRate = 2,
		Volume = 4,
		LRVolume = 8,
		Sync = 0x10,
		SampleAccurate = 0x20
	}
	public class AcmMp3FrameDecompressor : IMp3FrameDecompressor, IDisposable
	{
		private readonly AcmStream conversionStream;

		private readonly WaveFormat pcmFormat;

		private bool disposed;

		public WaveFormat OutputFormat => pcmFormat;

		public AcmMp3FrameDecompressor(WaveFormat sourceFormat)
		{
			pcmFormat = AcmStream.SuggestPcmFormat(sourceFormat);
			try
			{
				conversionStream = new AcmStream(sourceFormat, pcmFormat);
			}
			catch (Exception)
			{
				disposed = true;
				GC.SuppressFinalize(this);
				throw;
			}
		}

		public int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset)
		{
			if (frame == null)
			{
				throw new ArgumentNullException("frame", "You must provide a non-null Mp3Frame to decompress");
			}
			Array.Copy(frame.RawData, conversionStream.SourceBuffer, frame.FrameLength);
			int sourceBytesConverted;
			int num = conversionStream.Convert(frame.FrameLength, out sourceBytesConverted);
			if (sourceBytesConverted != frame.FrameLength)
			{
				throw new InvalidOperationException($"Couldn't convert the whole MP3 frame (converted {sourceBytesConverted}/{frame.FrameLength})");
			}
			Array.Copy(conversionStream.DestBuffer, 0, dest, destOffset, num);
			return num;
		}

		public void Reset()
		{
			conversionStream.Reposition();
		}

		public void Dispose()
		{
			if (!disposed)
			{
				disposed = true;
				if (conversionStream != null)
				{
					conversionStream.Dispose();
				}
				GC.SuppressFinalize(this);
			}
		}

		~AcmMp3FrameDecompressor()
		{
			Dispose();
		}
	}
	public class WaveFormatConversionProvider : IWaveProvider, IDisposable
	{
		private readonly AcmStream conversionStream;

		private readonly IWaveProvider sourceProvider;

		private readonly int preferredSourceReadSize;

		private int leftoverDestBytes;

		private int leftoverDestOffset;

		private int leftoverSourceBytes;

		private bool isDisposed;

		public WaveFormat WaveFormat { get; }

		public WaveFormatConversionProvider(WaveFormat targetFormat, IWaveProvider sourceProvider)
		{
			this.sourceProvider = sourceProvider;
			WaveFormat = targetFormat;
			conversionStream = new AcmStream(sourceProvider.WaveFormat, targetFormat);
			preferredSourceReadSize = Math.Min(sourceProvider.WaveFormat.AverageBytesPerSecond, conversionStream.SourceBuffer.Length);
			preferredSourceReadSize -= preferredSourceReadSize % sourceProvider.WaveFormat.BlockAlign;
		}

		public void Reposition()
		{
			leftoverDestBytes = 0;
			leftoverDestOffset = 0;
			leftoverSourceBytes = 0;
			conversionStream.Reposition();
		}

		public int Read(byte[] buffer, int offset, int count)
		{
			int i = 0;
			if (count % WaveFormat.BlockAlign != 0)
			{
				count -= count % WaveFormat.BlockAlign;
			}
			int num5;
			for (; i < count; i += num5)
			{
				int num = Math.Min(count - i, leftoverDestBytes);
				if (num > 0)
				{
					Array.Copy(conversionStream.DestBuffer, leftoverDestOffset, buffer, offset + i, num);
					leftoverDestOffset += num;
					leftoverDestBytes -= num;
					i += num;
				}
				if (i >= count)
				{
					break;
				}
				int num2 = Math.Min(preferredSourceReadSize, conversionStream.SourceBuffer.Length - leftoverSourceBytes);
				int num3 = sourceProvider.Read(conversionStream.SourceBuffer, leftoverSourceBytes, num2) + leftoverSourceBytes;
				if (num3 == 0)
				{
					break;
				}
				int sourceBytesConverted;
				int num4 = conversionStream.Convert(num3, out sourceBytesConverted);
				if (sourceBytesConverted == 0)
				{
					break;
				}
				leftoverSourceBytes = num3 - sourceBytesConverted;
				if (leftoverSourceBytes > 0)
				{
					Buffer.BlockCopy(conversionStream.SourceBuffer, sourceBytesConverted, conversionStream.SourceBuffer, 0, leftoverSourceBytes);
				}
				if (num4 <= 0)
				{
					break;
				}
				int val = count - i;
				num5 = Math.Min(num4, val);
				if (num5 < num4)
				{
					leftoverDestBytes = num4 - num5;
					leftoverDestOffset = num5;
				}
				Array.Copy(conversionStream.DestBuffer, 0, buffer, i + offset, num5);
			}
			return i;
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!isDisposed)
			{
				isDisposed = true;
				conversionStream?.Dispose();
			}
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		~WaveFormatConversionProvider()
		{
			Dispose(disposing: false);
		}
	}
	public class WaveFormatConversionStream : WaveStream
	{
		private readonly WaveFormatConversionProvider conversionProvider;

		private readonly WaveFormat targetFormat;

		private readonly long length;

		private long position;

		private readonly WaveStream sourceStream;

		private bool isDisposed;

		public override long Position
		{
			get
			{
				return position;
			}
			set
			{
				value -= value % ((WaveStream)this).BlockAlign;
				long num = EstimateDestToSource(value);
				((Stream)(object)sourceStream).Position = num;
				position = EstimateSourceToDest(((Stream)(object)sourceStream).Position);
				conversionProvider.Reposition();
			}
		}

		public override long Length => length;

		public override WaveFormat WaveFormat => targetFormat;

		public WaveFormatConversionStream(WaveFormat targetFormat, WaveStream sourceStream)
		{
			this.sourceStream = sourceStream;
			this.targetFormat = targetFormat;
			conversionProvider = new WaveFormatConversionProvider(targetFormat, (IWaveProvider)(object)sourceStream);
			length = EstimateSourceToDest((int)((Stream)(object)sourceStream).Length);
			position = 0L;
		}

		public static WaveStream CreatePcmStream(WaveStream sourceStream)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			if ((int)sourceStream.WaveFormat.Encoding == 1)
			{
				return sourceStream;
			}
			WaveFormat val = AcmStream.SuggestPcmFormat(sourceStream.WaveFormat);
			if (val.SampleRate < 8000)
			{
				if ((int)sourceStream.WaveFormat.Encoding != 163)
				{
					throw new InvalidOperationException("Invalid suggested output format, please explicitly provide a target format");
				}
				val = new WaveFormat(8000, 16, 1);
			}
			return (WaveStream)(object)new WaveFormatConversionStream(val, sourceStream);
		}

		[Obsolete("can be unreliable, use of this method not encouraged")]
		public int SourceToDest(int source)
		{
			return (int)EstimateSourceToDest(source);
		}

		private long EstimateSourceToDest(long source)
		{
			long num = source * targetFormat.AverageBytesPerSecond / sourceStream.WaveFormat.AverageBytesPerSecond;
			return num - num % targetFormat.BlockAlign;
		}

		private long EstimateDestToSource(long dest)
		{
			long num = dest * sourceStream.WaveFormat.AverageBytesPerSecond / targetFormat.AverageBytesPerSecond;
			return (int)(num - num % sourceStream.WaveFormat.BlockAlign);
		}

		[Obsolete("can be unreliable, use of this method not encouraged")]
		public int DestToSource(int dest)
		{
			return (int)EstimateDestToSource(dest);
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			int num = conversionProvider.Read(buffer, offset, count);
			position += num;
			return num;
		}

		protected override void Dispose(bool disposing)
		{
			if (!isDisposed)
			{
				isDisposed = true;
				if (disposing)
				{
					((Stream)(object)sourceStream).Dispose();
					conversionProvider.Dispose();
				}
			}
			((Stream)this).Dispose(disposing);
		}
	}
	public class WaveInBuffer : IDisposable
	{
		private readonly WaveHeader header;

		private readonly int bufferSize;

		private readonly byte[] buffer;

		private GCHandle hBuffer;

		private IntPtr waveInHandle;

		private GCHandle hHeader;

		private GCHandle hThis;

		public byte[] Data => buffer;

		public bool Done => (header.flags & WaveHeaderFlags.Done) == WaveHeaderFlags.Done;

		public bool InQueue => (header.flags & WaveHeaderFlags.InQueue) == WaveHeaderFlags.InQueue;

		public int BytesRecorded => header.bytesRecorded;

		public int BufferSize => bufferSize;

		public WaveInBuffer(IntPtr waveInHandle, int bufferSize)
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			this.bufferSize = bufferSize;
			buffer = new byte[bufferSize];
			hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
			this.waveInHandle = waveInHandle;
			header = new WaveHeader();
			hHeader = GCHandle.Alloc(header, GCHandleType.Pinned);
			header.dataBuffer = hBuffer.AddrOfPinnedObject();
			header.bufferLength = bufferSize;
			header.loops = 1;
			hThis = GCHandle.Alloc(this);
			header.userData = (IntPtr)hThis;
			MmException.Try(WaveInterop.waveInPrepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveInPrepareHeader");
		}

		public void Reuse()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			MmException.Try(WaveInterop.waveInUnprepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveUnprepareHeader");
			MmException.Try(WaveInterop.waveInPrepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveInPrepareHeader");
			MmException.Try(WaveInterop.waveInAddBuffer(waveInHandle, header, Marshal.SizeOf(header)), "waveInAddBuffer");
		}

		~WaveInBuffer()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected void Dispose(bool disposing)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (waveInHandle != IntPtr.Zero)
			{
				WaveInterop.waveInUnprepareHeader(waveInHandle, header, Marshal.SizeOf(header));
				waveInHandle = IntPtr.Zero;
			}
			if (hHeader.IsAllocated)
			{
				hHeader.Free();
			}
			if (hBuffer.IsAllocated)
			{
				hBuffer.Free();
			}
			if (hThis.IsAllocated)
			{
				hThis.Free();
			}
		}
	}
	public class WaveInEvent : IWaveIn, IDisposable
	{
		private readonly AutoResetEvent callbackEvent;

		private readonly SynchronizationContext syncContext;

		private IntPtr waveInHandle;

		private volatile CaptureState captureState;

		private WaveInBuffer[] buffers;

		public static int DeviceCount => WaveInterop.waveInGetNumDevs();

		public int BufferMilliseconds { get; set; }

		public int NumberOfBuffers { get; set; }

		public int DeviceNumber { get; set; }

		public WaveFormat WaveFormat { get; set; }

		public event EventHandler<WaveInEventArgs> DataAvailable;

		public event EventHandler<StoppedEventArgs> RecordingStopped;

		public WaveInEvent()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			callbackEvent = new AutoResetEvent(initialState: false);
			syncContext = SynchronizationContext.Current;
			DeviceNumber = 0;
			WaveFormat = new WaveFormat(8000, 16, 1);
			BufferMilliseconds = 100;
			NumberOfBuffers = 3;
			captureState = (CaptureState)0;
		}

		public static WaveInCapabilities GetCapabilities(int devNumber)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			WaveInCapabilities waveInCaps = default(WaveInCapabilities);
			int waveInCapsSize = Marshal.SizeOf(waveInCaps);
			MmException.Try(WaveInterop.waveInGetDevCaps((IntPtr)devNumber, out waveInCaps, waveInCapsSize), "waveInGetDevCaps");
			return waveInCaps;
		}

		private void CreateBuffers()
		{
			int num = BufferMilliseconds * WaveFormat.AverageBytesPerSecond / 1000;
			if (num % WaveFormat.BlockAlign != 0)
			{
				num -= num % WaveFormat.BlockAlign;
			}
			buffers = new WaveInBuffer[NumberOfBuffers];
			for (int i = 0; i < buffers.Length; i++)
			{
				buffers[i] = new WaveInBuffer(waveInHandle, num);
			}
		}

		private void OpenWaveInDevice()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			CloseWaveInDevice();
			MmException.Try(WaveInterop.waveInOpenWindow(out waveInHandle, (IntPtr)DeviceNumber, WaveFormat, callbackEvent.SafeWaitHandle.DangerousGetHandle(), IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackEvent), "waveInOpen");
			CreateBuffers();
		}

		public void StartRecording()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if ((int)captureState != 0)
			{
				throw new InvalidOperationException("Already recording");
			}
			OpenWaveInDevice();
			MmException.Try(WaveInterop.waveInStart(waveInHandle), "waveInStart");
			captureState = (CaptureState)1;
			ThreadPool.QueueUserWorkItem(delegate
			{
				RecordThread();
			}, null);
		}

		private void RecordThread()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Exception e = null;
			try
			{
				DoRecording();
			}
			catch (Exception ex)
			{
				e = ex;
			}
			finally
			{
				captureState = (CaptureState)0;
				RaiseRecordingStoppedEvent(e);
			}
		}

		private void DoRecording()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Invalid comparison between Unknown and I4
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Invalid comparison between Unknown and I4
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			captureState = (CaptureState)2;
			WaveInBuffer[] array = buffers;
			foreach (WaveInBuffer waveInBuffer in array)
			{
				if (!waveInBuffer.InQueue)
				{
					waveInBuffer.Reuse();
				}
			}
			while ((int)captureState == 2)
			{
				if (!callbackEvent.WaitOne())
				{
					continue;
				}
				array = buffers;
				foreach (WaveInBuffer waveInBuffer2 in array)
				{
					if (waveInBuffer2.Done)
					{
						if (waveInBuffer2.BytesRecorded > 0)
						{
							this.DataAvailable?.Invoke(this, new WaveInEventArgs(waveInBuffer2.Data, waveInBuffer2.BytesRecorded));
						}
						if ((int)captureState == 2)
						{
							waveInBuffer2.Reuse();
						}
					}
				}
			}
		}

		private void RaiseRecordingStoppedEvent(Exception e)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			EventHandler<StoppedEventArgs> handler = this.RecordingStopped;
			if (handler == null)
			{
				return;
			}
			if (syncContext == null)
			{
				handler(this, new StoppedEventArgs(e));
				return;
			}
			syncContext.Post(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				handler(this, new StoppedEventArgs(e));
			}, null);
		}

		public void StopRecording()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if ((int)captureState != 0)
			{
				captureState = (CaptureState)3;
				MmException.Try(WaveInterop.waveInStop(waveInHandle), "waveInStop");
				MmException.Try(WaveInterop.waveInReset(waveInHandle), "waveInReset");
				callbackEvent.Set();
			}
		}

		public long GetPosition()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			MmTime mmTime = default(MmTime);
			mmTime.wType = 4u;
			MmException.Try(WaveInterop.waveInGetPosition(waveInHandle, out mmTime, Marshal.SizeOf(mmTime)), "waveInGetPosition");
			if (mmTime.wType != 4)
			{
				throw new Exception($"waveInGetPosition: wType -> Expected {4}, Received {mmTime.wType}");
			}
			return mmTime.cb;
		}

		protected virtual void Dispose(bool disposing)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (disposing)
			{
				if ((int)captureState != 0)
				{
					StopRecording();
				}
				CloseWaveInDevice();
			}
		}

		private void CloseWaveInDevice()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			WaveInterop.waveInReset(waveInHandle);
			if (buffers != null)
			{
				for (int i = 0; i < buffers.Length; i++)
				{
					buffers[i].Dispose();
				}
				buffers = null;
			}
			WaveInterop.waveInClose(waveInHandle);
			waveInHandle = IntPtr.Zero;
		}

		public MixerLine GetMixerLine()
		{
			if (waveInHandle != IntPtr.Zero)
			{
				return new MixerLine(waveInHandle, 0, MixerFlags.WaveInHandle);
			}
			return new MixerLine((IntPtr)DeviceNumber, 0, MixerFlags.WaveIn);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	public class WaveOutBuffer : IDisposable
	{
		private readonly WaveHeader header;

		private readonly int bufferSize;

		private readonly byte[] buffer;

		private readonly IWaveProvider waveStream;

		private readonly object waveOutLock;

		private GCHandle hBuffer;

		private IntPtr hWaveOut;

		private GCHandle hHeader;

		private GCHandle hThis;

		public bool InQueue => (header.flags & WaveHeaderFlags.InQueue) == WaveHeaderFlags.InQueue;

		public int BufferSize => bufferSize;

		public WaveOutBuffer(IntPtr hWaveOut, int bufferSize, IWaveProvider bufferFillStream, object waveOutLock)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			this.bufferSize = bufferSize;
			buffer = new byte[bufferSize];
			hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
			this.hWaveOut = hWaveOut;
			waveStream = bufferFillStream;
			this.waveOutLock = waveOutLock;
			header = new WaveHeader();
			hHeader = GCHandle.Alloc(header, GCHandleType.Pinned);
			header.dataBuffer = hBuffer.AddrOfPinnedObject();
			header.bufferLength = bufferSize;
			header.loops = 1;
			hThis = GCHandle.Alloc(this);
			header.userData = (IntPtr)hThis;
			lock (waveOutLock)
			{
				MmException.Try(WaveInterop.waveOutPrepareHeader(hWaveOut, header, Marshal.SizeOf(header)), "waveOutPrepareHeader");
			}
		}

		~WaveOutBuffer()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected void Dispose(bool disposing)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			if (hHeader.IsAllocated)
			{
				hHeader.Free();
			}
			if (hBuffer.IsAllocated)
			{
				hBuffer.Free();
			}
			if (hThis.IsAllocated)
			{
				hThis.Free();
			}
			if (hWaveOut != IntPtr.Zero)
			{
				lock (waveOutLock)
				{
					WaveInterop.waveOutUnprepareHeader(hWaveOut, header, Marshal.SizeOf(header));
				}
				hWaveOut = IntPtr.Zero;
			}
		}

		public bool OnDone()
		{
			int num;
			lock (waveStream)
			{
				num = waveStream.Read(buffer, 0, buffer.Length);
			}
			if (num == 0)
			{
				return false;
			}
			for (int i = num; i < buffer.Length; i++)
			{
				buffer[i] = 0;
			}
			WriteToWaveOut();
			return true;
		}

		private void WriteToWaveOut()
		{
			//IL_0028: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			MmResult val;
			lock (waveOutLock)
			{
				val = WaveInterop.waveOutWrite(hWaveOut, header, Marshal.SizeOf(header));
			}
			if ((int)val != 0)
			{
				throw new MmException(val, "waveOutWrite");
			}
			GC.KeepAlive(this);
		}
	}
	public class WaveOutEvent : IWavePlayer, IDisposable, IWavePosition
	{
		private readonly object waveOutLock;

		private readonly SynchronizationContext syncContext;

		private IntPtr hWaveOut;

		private WaveOutBuffer[] buffers;

		private IWaveProvider waveStream;

		private volatile PlaybackState playbackState;

		private AutoResetEvent callbackEvent;

		public int DesiredLatency { get; set; }

		public int NumberOfBuffers { get; set; }

		public int DeviceNumber { get; set; } = -1;


		public WaveFormat OutputWaveFormat => waveStream.WaveFormat;

		public PlaybackState PlaybackState => playbackState;

		public float Volume
		{
			get
			{
				return WaveOutUtils.GetWaveOutVolume(hWaveOut, waveOutLock);
			}
			set
			{
				WaveOutUtils.SetWaveOutVolume(value, hWaveOut, waveOutLock);
			}
		}

		public event EventHandler<StoppedEventArgs> PlaybackStopped;

		public WaveOutEvent()
		{
			syncContext = SynchronizationContext.Current;
			if (syncContext != null && (syncContext.GetType().Name == "LegacyAspNetSynchronizationContext" || syncContext.GetType().Name == "AspNetSynchronizationContext"))
			{
				syncContext = null;
			}
			DesiredLatency = 300;
			NumberOfBuffers = 2;
			waveOutLock = new object();
		}

		public void Init(IWaveProvider waveProvider)
		{
			//IL_0001: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState != 0)
			{
				throw new InvalidOperationException("Can't re-initialize during playback");
			}
			if (hWaveOut != IntPtr.Zero)
			{
				DisposeBuffers();
				CloseWaveOut();
			}
			callbackEvent = new AutoResetEvent(initialState: false);
			waveStream = waveProvider;
			int bufferSize = waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1) / NumberOfBuffers);
			MmResult val;
			lock (waveOutLock)
			{
				val = WaveInterop.waveOutOpenWindow(out hWaveOut, (IntPtr)DeviceNumber, waveStream.WaveFormat, callbackEvent.SafeWaitHandle.DangerousGetHandle(), IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackEvent);
			}
			MmException.Try(val, "waveOutOpen");
			buffers = new WaveOutBuffer[NumberOfBuffers];
			playbackState = (PlaybackState)0;
			for (int i = 0; i < NumberOfBuffers; i++)
			{
				buffers[i] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock);
			}
		}

		public void Play()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Invalid comparison between Unknown and I4
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (buffers == null || waveStream == null)
			{
				throw new InvalidOperationException("Must call Init first");
			}
			if ((int)playbackState == 0)
			{
				playbackState = (PlaybackState)1;
				callbackEvent.Set();
				ThreadPool.QueueUserWorkItem(delegate
				{
					PlaybackThread();
				}, null);
			}
			else if ((int)playbackState == 2)
			{
				Resume();
				callbackEvent.Set();
			}
		}

		private void PlaybackThread()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Exception e = null;
			try
			{
				DoPlayback();
			}
			catch (Exception ex)
			{
				e = ex;
			}
			finally
			{
				playbackState = (PlaybackState)0;
				RaisePlaybackStoppedEvent(e);
			}
		}

		private void DoPlayback()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			while ((int)playbackState != 0)
			{
				if (!callbackEvent.WaitOne(DesiredLatency))
				{
					_ = playbackState;
					_ = 1;
				}
				if ((int)playbackState != 1)
				{
					continue;
				}
				int num = 0;
				WaveOutBuffer[] array = buffers;
				foreach (WaveOutBuffer waveOutBuffer in array)
				{
					if (waveOutBuffer.InQueue || waveOutBuffer.OnDone())
					{
						num++;
					}
				}
				if (num == 0)
				{
					playbackState = (PlaybackState)0;
					callbackEvent.Set();
				}
			}
		}

		public void Pause()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_000d: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState == 1)
			{
				playbackState = (PlaybackState)2;
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutPause(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutPause");
				}
			}
		}

		private void Resume()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState == 2)
			{
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutRestart(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutRestart");
				}
				playbackState = (PlaybackState)1;
			}
		}

		public void Stop()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState != 0)
			{
				playbackState = (PlaybackState)0;
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutReset(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutReset");
				}
				callbackEvent.Set();
			}
		}

		public long GetPosition()
		{
			return WaveOutUtils.GetPositionBytes(hWaveOut, waveOutLock);
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected void Dispose(bool disposing)
		{
			Stop();
			if (disposing)
			{
				DisposeBuffers();
			}
			CloseWaveOut();
		}

		private void CloseWaveOut()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if (callbackEvent != null)
			{
				callbackEvent.Close();
				callbackEvent = null;
			}
			lock (waveOutLock)
			{
				if (hWaveOut != IntPtr.Zero)
				{
					WaveInterop.waveOutClose(hWaveOut);
					hWaveOut = IntPtr.Zero;
				}
			}
		}

		private void DisposeBuffers()
		{
			if (buffers != null)
			{
				WaveOutBuffer[] array = buffers;
				for (int i = 0; i < array.Length; i++)
				{
					array[i].Dispose();
				}
				buffers = null;
			}
		}

		~WaveOutEvent()
		{
			Dispose(disposing: false);
		}

		private void RaisePlaybackStoppedEvent(Exception e)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			EventHandler<StoppedEventArgs> handler = this.PlaybackStopped;
			if (handler == null)
			{
				return;
			}
			if (syncContext == null)
			{
				handler(this, new StoppedEventArgs(e));
				return;
			}
			syncContext.Post(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				handler(this, new StoppedEventArgs(e));
			}, null);
		}
	}
	public static class WaveOutUtils
	{
		public static float GetWaveOutVolume(IntPtr hWaveOut, object lockObject)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			MmResult val;
			int dwVolume;
			lock (lockObject)
			{
				val = WaveInterop.waveOutGetVolume(hWaveOut, out dwVolume);
			}
			MmException.Try(val, "waveOutGetVolume");
			return (float)(dwVolume & 0xFFFF) / 65535f;
		}

		public static void SetWaveOutVolume(float value, IntPtr hWaveOut, object lockObject)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			if (value < 0f)
			{
				throw new ArgumentOutOfRangeException("value", "Volume must be between 0.0 and 1.0");
			}
			if (value > 1f)
			{
				throw new ArgumentOutOfRangeException("value", "Volume must be between 0.0 and 1.0");
			}
			int dwVolume = (int)(value * 65535f) + ((int)(value * 65535f) << 16);
			MmResult val;
			lock (lockObject)
			{
				val = WaveInterop.waveOutSetVolume(hWaveOut, dwVolume);
			}
			MmException.Try(val, "waveOutSetVolume");
		}

		public static long GetPositionBytes(IntPtr hWaveOut, object lockObject)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			lock (lockObject)
			{
				MmTime mmTime = default(MmTime);
				mmTime.wType = 4u;
				MmException.Try(WaveInterop.waveOutGetPosition(hWaveOut, ref mmTime, Marshal.SizeOf(mmTime)), "waveOutGetPosition");
				if (mmTime.wType != 4)
				{
					throw new Exception($"waveOutGetPosition: wType -> Expected {4}, Received {mmTime.wType}");
				}
				return mmTime.cb;
			}
		}
	}
}
namespace NAudio.Wave.Compression
{
	public class AcmDriver : IDisposable
	{
		private static List<AcmDriver> drivers;

		private AcmDriverDetails details;

		private IntPtr driverId;

		private IntPtr driverHandle;

		private List<AcmFormatTag> formatTags;

		private List<AcmFormat> tempFormatsList;

		private IntPtr localDllHandle;

		public int MaxFormatSize
		{
			get
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				MmException.Try(AcmInterop.acmMetrics(driverHandle, AcmMetrics.MaxSizeFormat, out var output), "acmMetrics");
				return output;
			}
		}

		public string ShortName => details.shortName;

		public string LongName => details.longName;

		public IntPtr DriverId => driverId;

		public IEnumerable<AcmFormatTag> FormatTags
		{
			get
			{
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				if (formatTags == null)
				{
					if (driverHandle == IntPtr.Zero)
					{
						throw new InvalidOperationException("Driver must be opened first");
					}
					formatTags = new List<AcmFormatTag>();
					AcmFormatTagDetails formatTagDetails = default(AcmFormatTagDetails);
					formatTagDetails.structureSize = Marshal.SizeOf(formatTagDetails);
					MmException.Try(AcmInterop.acmFormatTagEnum(driverHandle, ref formatTagDetails, AcmFormatTagEnumCallback, IntPtr.Zero, 0), "acmFormatTagEnum");
				}
				return formatTags;
			}
		}

		public static bool IsCodecInstalled(string shortName)
		{
			foreach (AcmDriver item in EnumerateAcmDrivers())
			{
				if (item.ShortName == shortName)
				{
					return true;
				}
			}
			return false;
		}

		public static AcmDriver AddLocalDriver(string driverFile)
		{
			//IL_0050: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			IntPtr intPtr = NativeMethods.LoadLibrary(driverFile);
			if (intPtr == IntPtr.Zero)
			{
				throw new ArgumentException("Failed to load driver file");
			}
			IntPtr procAddress = NativeMethods.GetProcAddress(intPtr, "DriverProc");
			if (procAddress == IntPtr.Zero)
			{
				NativeMethods.FreeLibrary(intPtr);
				throw new ArgumentException("Failed to discover DriverProc");
			}
			IntPtr hAcmDriver;
			MmResult val = AcmInterop.acmDriverAdd(out hAcmDriver, intPtr, procAddress, 0, AcmDriverAddFlags.Function);
			if ((int)val != 0)
			{
				NativeMethods.FreeLibrary(intPtr);
				throw new MmException(val, "acmDriverAdd");
			}
			AcmDriver acmDriver = new AcmDriver(hAcmDriver);
			if (string.IsNullOrEmpty(acmDriver.details.longName))
			{
				acmDriver.details.longName = "Local driver: " + Path.GetFileName(driverFile);
				acmDriver.localDllHandle = intPtr;
			}
			return acmDriver;
		}

		public static void RemoveLocalDriver(AcmDriver localDriver)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (localDriver.localDllHandle == IntPtr.Zero)
			{
				throw new ArgumentException("Please pass in the AcmDriver returned by the AddLocalDriver method");
			}
			MmResult val = AcmInterop.acmDriverRemove(localDriver.driverId, 0);
			NativeMethods.FreeLibrary(localDriver.localDllHandle);
			MmException.Try(val, "acmDriverRemove");
		}

		public static bool ShowFormatChooseDialog(IntPtr ownerWindowHandle, string windowTitle, AcmFormatEnumFlags enumFlags, WaveFormat enumFormat, out WaveFormat selectedFormat, out string selectedFormatDescription, out string selectedFormatTagDescription)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Invalid comparison between Unknown and I4
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Invalid comparison between Unknown and I4
			//IL_00ec: 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_00f5: Unknown result type (might be due to invalid IL or missing references)
			AcmFormatChoose formatChoose = default(AcmFormatChoose);
			formatChoose.structureSize = Marshal.SizeOf(formatChoose);
			formatChoose.styleFlags = AcmFormatChooseStyleFlags.None;
			formatChoose.ownerWindowHandle = ownerWindowHandle;
			int num = 200;
			formatChoose.selectedWaveFormatPointer = Marshal.AllocHGlobal(num);
			formatChoose.selectedWaveFormatByteSize = num;
			formatChoose.title = windowTitle;
			formatChoose.name = null;
			formatChoose.formatEnumFlags = enumFlags;
			formatChoose.waveFormatEnumPointer = IntPtr.Zero;
			if (enumFormat != null)
			{
				IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf<WaveFormat>(enumFormat));
				Marshal.StructureToPtr<WaveFormat>(enumFormat, intPtr, fDeleteOld: false);
				formatChoose.waveFormatEnumPointer = intPtr;
			}
			formatChoose.instanceHandle = IntPtr.Zero;
			formatChoose.templateName = null;
			MmResult val = AcmInterop.acmFormatChoose(ref formatChoose);
			selectedFormat = null;
			selectedFormatDescription = null;
			selectedFormatTagDescription = null;
			if ((int)val == 0)
			{
				selectedFormat = WaveFormat.MarshalFromPtr(formatChoose.selectedWaveFormatPointer);
				selectedFormatDescription = formatChoose.formatDescription;
				selectedFormatTagDescription = formatChoose.formatTagDescription;
			}
			Marshal.FreeHGlobal(formatChoose.waveFormatEnumPointer);
			Marshal.FreeHGlobal(formatChoose.selectedWaveFormatPointer);
			if ((int)val != 515 && (int)val != 0)
			{
				throw new MmException(val, "acmFormatChoose");
			}
			return (int)val == 0;
		}

		public static AcmDriver FindByShortName(string shortName)
		{
			foreach (AcmDriver item in EnumerateAcmDrivers())
			{
				if (item.ShortName == shortName)
				{
					return item;
				}
			}
			return null;
		}

		public static IEnumerable<AcmDriver> EnumerateAcmDrivers()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			drivers = new List<AcmDriver>();
			MmException.Try(AcmInterop.acmDriverEnum(DriverEnumCallback, IntPtr.Zero, (AcmDriverEnumFlags)0), "acmDriverEnum");
			return drivers;
		}

		private static bool DriverEnumCallback(IntPtr hAcmDriver, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags)
		{
			drivers.Add(new AcmDriver(hAcmDriver));
			return true;
		}

		private AcmDriver(IntPtr hAcmDriver)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			driverId = hAcmDriver;
			details = default(AcmDriverDetails);
			details.structureSize = Marshal.SizeOf(details);
			MmException.Try(AcmInterop.acmDriverDetails(hAcmDriver, ref details, 0), "acmDriverDetails");
		}

		public override string ToString()
		{
			return LongName;
		}

		public IEnumerable<AcmFormat> GetFormats(AcmFormatTag formatTag)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected I4, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if (driverHandle == IntPtr.Zero)
			{
				throw new InvalidOperationException("Driver must be opened first");
			}
			tempFormatsList = new List<AcmFormat>();
			AcmFormatDetails formatDetails = default(AcmFormatDetails);
			formatDetails.structSize = Marshal.SizeOf(formatDetails);
			formatDetails.waveFormatByteSize = 1024;
			formatDetails.waveFormatPointer = Marshal.AllocHGlobal(formatDetails.waveFormatByteSize);
			formatDetails.formatTag = (int)formatTag.FormatTag;
			MmResult val = AcmInterop.acmFormatEnum(driverHandle, ref formatDetails, AcmFormatEnumCallback, IntPtr.Zero, AcmFormatEnumFlags.None);
			Marshal.FreeHGlobal(formatDetails.waveFormatPointer);
			MmException.Try(val, "acmFormatEnum");
			return tempFormatsList;
		}

		public void Open()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if (driverHandle == IntPtr.Zero)
			{
				MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, DriverId, 0), "acmDriverOpen");
			}
		}

		public void Close()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (driverHandle != IntPtr.Zero)
			{
				MmException.Try(AcmInterop.acmDriverClose(driverHandle, 0), "acmDriverClose");
				driverHandle = IntPtr.Zero;
			}
		}

		private bool AcmFormatTagEnumCallback(IntPtr hAcmDriverId, ref AcmFormatTagDetails formatTagDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags)
		{
			formatTags.Add(new AcmFormatTag(formatTagDetails));
			return true;
		}

		private bool AcmFormatEnumCallback(IntPtr hAcmDriverId, ref AcmFormatDetails formatDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags)
		{
			tempFormatsList.Add(new AcmFormat(formatDetails));
			return true;
		}

		public void Dispose()
		{
			if (driverHandle != IntPtr.Zero)
			{
				Close();
				GC.SuppressFinalize(this);
			}
		}
	}
	internal enum AcmDriverAddFlags
	{
		Local = 0,
		Global = 8,
		Function = 3,
		NotifyWindowHandle = 4
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	internal struct AcmDriverDetails
	{
		public int structureSize;

		public uint fccType;

		public uint fccComp;

		public ushort manufacturerId;

		public ushort productId;

		public uint acmVersion;

		public uint driverVersion;

		public AcmDriverDetailsSupportFlags supportFlags;

		public int formatTagsCount;

		public int filterTagsCount;

		public IntPtr hicon;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		public string shortName;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string longName;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
		public string copyright;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string licensing;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
		public string features;

		private const int ShortNameChars = 32;

		private const int LongNameChars = 128;

		private const int CopyrightChars = 80;

		private const int LicensingChars = 128;

		private const int FeaturesChars = 512;
	}
	[Flags]
	public enum AcmDriverDetailsSupportFlags
	{
		Codec = 1,
		Converter = 2,
		Filter = 4,
		Hardware = 8,
		Async = 0x10,
		Local = 0x40000000,
		Disabled = int.MinValue
	}
	[Flags]
	internal enum AcmDriverEnumFlags
	{
		NoLocal = 0x40000000,
		Disabled = int.MinValue
	}
	public class AcmFormat
	{
		private readonly AcmFormatDetails formatDetails;

		public int FormatIndex => formatDetails.formatIndex;

		public WaveFormatEncoding FormatTag => (WaveFormatEncoding)(ushort)formatDetails.formatTag;

		public AcmDriverDetailsSupportFlags SupportFlags => formatDetails.supportFlags;

		public WaveFormat WaveFormat { get; private set; }

		public int WaveFormatByteSize => formatDetails.waveFormatByteSize;

		public string FormatDescription => formatDetails.formatDescription;

		internal AcmFormat(AcmFormatDetails formatDetails)
		{
			this.formatDetails = formatDetails;
			WaveFormat = WaveFormat.MarshalFromPtr(formatDetails.waveFormatPointer);
		}
	}
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
	internal struct AcmFormatChoose
	{
		public int structureSize;

		public AcmFormatChooseStyleFlags styleFlags;

		public IntPtr ownerWindowHandle;

		public IntPtr selectedWaveFormatPointer;

		public int selectedWaveFormatByteSize;

		[MarshalAs(UnmanagedType.LPTStr)]
		public string title;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)]
		public string formatTagDescription;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string formatDescription;

		[MarshalAs(UnmanagedType.LPTStr)]
		public string name;

		public int nameByteSize;

		public AcmFormatEnumFlags formatEnumFlags;

		public IntPtr waveFormatEnumPointer;

		public IntPtr instanceHandle;

		[MarshalAs(UnmanagedType.LPTStr)]
		public string templateName;

		public IntPtr customData;

		public AcmInterop.AcmFormatChooseHookProc windowCallbackFunction;
	}
	[Flags]
	internal enum AcmFormatChooseStyleFlags
	{
		None = 0,
		ShowHelp = 4,
		EnableHook = 8,
		EnableTemplate = 0x10,
		EnableTemplateHandle = 0x20,
		InitToWfxStruct = 0x40,
		ContextHelp = 0x80
	}
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	internal struct AcmFormatDetails
	{
		public int structSize;

		public int formatIndex;

		public int formatTag;

		public AcmDriverDetailsSupportFlags supportFlags;

		public IntPtr waveFormatPointer;

		public int waveFormatByteSize;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string formatDescription;

		public const int FormatDescriptionChars = 128;
	}
	[Flags]
	public enum AcmFormatEnumFlags
	{
		None = 0,
		Convert = 0x100000,
		Hardware = 0x400000,
		Input = 0x800000,
		Channels = 0x20000,
		SamplesPerSecond = 0x40000,
		Output = 0x1000000,
		Suggest = 0x200000,
		BitsPerSample = 0x80000,
		FormatTag = 0x10000
	}
	[Flags]
	internal enum AcmFormatSuggestFlags
	{
		FormatTag = 0x10000,
		Channels = 0x20000,
		SamplesPerSecond = 0x40000,
		BitsPerSample = 0x80000,
		TypeMask = 0xFF0000
	}
	public class AcmFormatTag
	{
		private AcmFormatTagDetails formatTagDetails;

		public int FormatTagIndex => formatTagDetails.formatTagIndex;

		public WaveFormatEncoding FormatTag => (WaveFormatEncoding)(ushort)formatTagDetails.formatTag;

		public int FormatSize => formatTagDetails.formatSize;

		public AcmDriverDetailsSupportFlags SupportFlags => formatTagDetails.supportFlags;

		public int StandardFormatsCount => formatTagDetails.standardFormatsCount;

		public string FormatDescription => formatTagDetails.formatDescription;

		internal AcmFormatTag(AcmFormatTagDetails formatTagDetails)
		{
			this.formatTagDetails = formatTagDetails;
		}
	}
	internal struct AcmFormatTagDetails
	{
		public int structureSize;

		public int formatTagIndex;

		public int formatTag;

		public int formatSize;

		public AcmDriverDetailsSupportFlags supportFlags;

		public int standardFormatsCount;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)]
		public string formatDescription;

		public const int FormatTagDescriptionChars = 48;
	}
	internal class AcmInterop
	{
		public delegate bool AcmDriverEnumCallback(IntPtr hAcmDriverId, IntPtr instance, AcmDriverDetailsSupportFlags flags);

		public delegate bool AcmFormatEnumCallback(IntPtr hAcmDriverId, ref AcmFormatDetails formatDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags);

		public delegate bool AcmFormatTagEnumCallback(IntPtr hAcmDriverId, ref AcmFormatTagDetails formatTagDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags);

		public delegate bool AcmFormatChooseHookProc(IntPtr windowHandle, int message, IntPtr wParam, IntPtr lParam);

		[DllImport("msacm32.dll")]
		public static extern MmResult acmDriverAdd(out IntPtr driverHandle, IntPtr driverModule, IntPtr driverFunctionAddress, int priority, AcmDriverAddFlags flags);

		[DllImport("msacm32.dll")]
		public static extern MmResult acmDriverRemove(IntPtr driverHandle, int removeFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmDriverClose(IntPtr hAcmDriver, int closeFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmDriverEnum(AcmDriverEnumCallback fnCallback, IntPtr dwInstance, AcmDriverEnumFlags flags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmDriverDetails(IntPtr hAcmDriver, ref AcmDriverDetails driverDetails, int reserved);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmDriverOpen(out IntPtr pAcmDriver, IntPtr hAcmDriverId, int openFlags);

		[DllImport("Msacm32.dll", EntryPoint = "acmFormatChooseW")]
		public static extern MmResult acmFormatChoose(ref AcmFormatChoose formatChoose);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmFormatEnum(IntPtr hAcmDriver, ref AcmFormatDetails formatDetails, AcmFormatEnumCallback callback, IntPtr instance, AcmFormatEnumFlags flags);

		[DllImport("Msacm32.dll", EntryPoint = "acmFormatSuggest")]
		public static extern MmResult acmFormatSuggest2(IntPtr hAcmDriver, IntPtr sourceFormatPointer, IntPtr destFormatPointer, int sizeDestFormat, AcmFormatSuggestFlags suggestFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmFormatTagEnum(IntPtr hAcmDriver, ref AcmFormatTagDetails formatTagDetails, AcmFormatTagEnumCallback callback, IntPtr instance, int reserved);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmMetrics(IntPtr hAcmObject, AcmMetrics metric, out int output);

		[DllImport("Msacm32.dll", EntryPoint = "acmStreamOpen")]
		public static extern MmResult acmStreamOpen2(out IntPtr hAcmStream, IntPtr hAcmDriver, IntPtr sourceFormatPointer, IntPtr destFormatPointer, [In] WaveFilter waveFilter, IntPtr callback, IntPtr instance, AcmStreamOpenFlags openFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamClose(IntPtr hAcmStream, int closeFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamConvert(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, AcmStreamConvertFlags streamConvertFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamPrepareHeader(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, int prepareFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamReset(IntPtr hAcmStream, int resetFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamSize(IntPtr hAcmStream, int inputBufferSize, out int outputBufferSize, AcmStreamSizeFlags flags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamUnprepareHeader(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, int flags);
	}
	public class AcmStream : IDisposable
	{
		private IntPtr streamHandle;

		private IntPtr driverHandle;

		private AcmStreamHeader streamHeader;

		private readonly WaveFormat sourceFormat;

		public byte[] SourceBuffer => streamHeader.SourceBuffer;

		public byte[] DestBuffer => streamHeader.DestBuffer;

		public AcmStream(WaveFormat sourceFormat, WaveFormat destFormat)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				streamHandle = IntPtr.Zero;
				this.sourceFormat = sourceFormat;
				int num = Math.Max(65536, sourceFormat.AverageBytesPerSecond);
				num -= num % sourceFormat.BlockAlign;
				IntPtr intPtr = WaveFormat.MarshalToPtr(sourceFormat);
				IntPtr intPtr2 = WaveFormat.MarshalToPtr(destFormat);
				try
				{
					MmException.Try(AcmInterop.acmStreamOpen2(out streamHandle, IntPtr.Zero, intPtr, intPtr2, null, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen");
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
					Marshal.FreeHGlobal(intPtr2);
				}
				int destBufferLength = SourceToDest(num);
				streamHeader = new AcmStreamHeader(streamHandle, num, destBufferLength);
				driverHandle = IntPtr.Zero;
			}
			catch
			{
				Dispose();
				throw;
			}
		}

		public AcmStream(IntPtr driverId, WaveFormat sourceFormat, WaveFilter waveFilter)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			int num = Math.Max(16384, sourceFormat.AverageBytesPerSecond);
			this.sourceFormat = sourceFormat;
			num -= num % sourceFormat.BlockAlign;
			MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, driverId, 0), "acmDriverOpen");
			IntPtr intPtr = WaveFormat.MarshalToPtr(sourceFormat);
			try
			{
				MmException.Try(AcmInterop.acmStreamOpen2(out streamHandle, driverHandle, intPtr, intPtr, waveFilter, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen");
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
			streamHeader = new AcmStreamHeader(streamHandle, num, SourceToDest(num));
		}

		public int SourceToDest(int source)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (source == 0)
			{
				return 0;
			}
			MmException.Try(AcmInterop.acmStreamSize(streamHandle, source, out var outputBufferSize, AcmStreamSizeFlags.Source), "acmStreamSize");
			return outputBufferSize;
		}

		public int DestToSource(int dest)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (dest == 0)
			{
				return 0;
			}
			MmException.Try(AcmInterop.acmStreamSize(streamHandle, dest, out var outputBufferSize, AcmStreamSizeFlags.Destination), "acmStreamSize");
			return outputBufferSize;
		}

		public static WaveFormat SuggestPcmFormat(WaveFormat compressedFormat)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			WaveFormat val = new WaveFormat(compressedFormat.SampleRate, 16, compressedFormat.Channels);
			IntPtr intPtr = WaveFormat.MarshalToPtr(val);
			IntPtr intPtr2 = WaveFormat.MarshalToPtr(compressedFormat);
			try
			{
				MmResult val2 = AcmInterop.acmFormatSuggest2(IntPtr.Zero, intPtr2, intPtr, Marshal.SizeOf<WaveFormat>(val), AcmFormatSuggestFlags.FormatTag);
				val = WaveFormat.MarshalFromPtr(intPtr);
				MmException.Try(val2, "acmFormatSuggest");
				return val;
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
				Marshal.FreeHGlobal(intPtr2);
			}
		}

		public void Reposition()
		{
			streamHeader.Reposition();
		}

		public int Convert(int bytesToConvert, out int sourceBytesConverted)
		{
			if (bytesToConvert % sourceFormat.BlockAlign != 0)
			{
				bytesToConvert -= bytesToConvert % sourceFormat.BlockAlign;
			}
			return streamHeader.Convert(bytesToConvert, out sourceBytesConverted);
		}

		[Obsolete("Call the version returning sourceBytesConverted instead")]
		public int Convert(int bytesToConvert)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			int sourceBytesConverted;
			int result = Convert(bytesToConvert, out sourceBytesConverted);
			if (sourceBytesConverted != bytesToConvert)
			{
				throw new MmException((MmResult)8, "AcmStreamHeader.Convert didn't convert everything");
			}
			return result;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (disposing && streamHeader != null)
			{
				streamHeader.Dispose();
				streamHeader = null;
			}
			if (streamHandle != IntPtr.Zero)
			{
				MmResult val = AcmInterop.acmStreamClose(streamHandle, 0);
				streamHandle = IntPtr.Zero;
				if ((int)val != 0)
				{
					throw new MmException(val, "acmStreamClose");
				}
			}
			if (driverHandle != IntPtr.Zero)
			{
				AcmInterop.acmDriverClose(driverHandle, 0);
				driverHandle = IntPtr.Zero;
			}
		}

		~AcmStream()
		{
			Dispose(disposing: false);
		}
	}
	internal class AcmStreamHeader : IDisposable
	{
		private AcmStreamHeaderStruct streamHeader;

		private GCHandle hSourceBuffer;

		private GCHandle hDestBuffer;

		private IntPtr streamHandle;

		private bool firstTime;

		private bool disposed;

		public byte[] SourceBuffer { get; private set; }

		public byte[] DestBuffer { get; private set; }

		public AcmStreamHeader(IntPtr streamHandle, int sourceBufferLength, int destBufferLength)
		{
			streamHeader = new AcmStreamHeaderStruct();
			SourceBuffer = new byte[sourceBufferLength];
			hSourceBuffer = GCHandle.Alloc(SourceBuffer, GCHandleType.Pinned);
			DestBuffer = new byte[destBufferLength];
			hDestBuffer = GCHandle.Alloc(DestBuffer, GCHandleType.Pinned);
			this.streamHandle = streamHandle;
			firstTime = true;
		}

		private void Prepare()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			streamHeader.cbStruct = Marshal.SizeOf(streamHeader);
			streamHeader.sourceBufferLength = SourceBuffer.Length;
			streamHeader.sourceBufferPointer = hSourceBuffer.AddrOfPinnedObject();
			streamHeader.destBufferLength = DestBuffer.Length;
			streamHeader.destBufferPointer = hDestBuffer.AddrOfPinnedObject();
			MmException.Try(AcmInterop.acmStreamPrepareHeader(streamHandle, streamHeader, 0), "acmStreamPrepareHeader");
		}

		private void Unprepare()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			streamHeader.sourceBufferLength = SourceBuffer.Length;
			streamHeader.sourceBufferPointer = hSourceBuffer.AddrOfPinnedObject();
			streamHeader.destBufferLength = DestBuffer.Length;
			streamHeader.destBufferPointer = hDestBuffer.AddrOfPinnedObject();
			MmResult val = AcmInterop.acmStreamUnprepareHeader(streamHandle, streamHeader, 0);
			if ((int)val != 0)
			{
				throw new MmException(val, "acmStreamUnprepareHeader");
			}
		}

		public void Reposition()
		{
			firstTime = true;
		}

		public int Convert(int bytesToConvert, out int sourceBytesConverted)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			Prepare();
			try
			{
				streamHeader.sourceBufferLength = bytesToConvert;
				streamHeader.sourceBufferLengthUsed = bytesToConvert;
				AcmStreamConvertFlags streamConvertFlags = (firstTime ? (AcmStreamConvertFlags.BlockAlign | AcmStreamConvertFlags.Start) : AcmStreamConvertFlags.BlockAlign);
				MmException.Try(AcmInterop.acmStreamConvert(streamHandle, streamHeader, streamConvertFlags), "acmStreamConvert");
				firstTime = false;
				sourceBytesConverted = streamHeader.sourceBufferLengthUsed;
			}
			finally
			{
				Unprepare();
			}
			return streamHeader.destBufferLengthUsed;
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposed)
			{
				SourceBuffer = null;
				DestBuffer = null;
				hSourceBuffer.Free();
				hDestBuffer.Free();
			}
			disposed = true;
		}

		~AcmStreamHeader()
		{
			Dispose(disposing: false);
		}
	}
	[Flags]
	internal enum AcmStreamHeaderStatusFlags
	{
		Done = 0x10000,
		Prepared = 0x20000,
		InQueue = 0x100000
	}
	[StructLayout(LayoutKind.Sequential, Size = 128)]
	internal class AcmStreamHeaderStruct
	{
		public int cbStruct;

		public AcmStreamHeaderStatusFlags fdwStatus;

		public IntPtr userData;

		public IntPtr sourceBufferPointer;

		public int sourceBufferLength;

		public int sourceBufferLengthUsed;

		public IntPtr sourceUserData;

		public IntPtr destBufferPointer;

		public int destBufferLength;

		public int destBufferLengthUsed;

		public IntPtr destUserData;
	}
	[Flags]
	internal enum AcmStreamOpenFlags
	{
		Query = 1,
		Async = 2,
		NonRealTime = 4,
		CallbackTypeMask = 0x70000,
		CallbackNull = 0,
		CallbackWindow = 0x10000,
		CallbackTask = 0x20000,
		CallbackFunction = 0x30000,
		CallbackThread = 0x20000,
		CallbackEvent = 0x50000
	}
	internal enum AcmStreamSizeFlags
	{
		Source,
		Destination
	}
	[StructLayout(LayoutKind.Sequential)]
	public class WaveFilter
	{
		public int StructureSize = Marshal.SizeOf(typeof(WaveFilter));

		public int FilterTag;

		public int Filter;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
		public int[] Reserved;
	}
}