diff --git a/Common/Classes/EventArgsEx.cs b/Common/Classes/EventArgsEx.cs index 048d0322..fe023159 100644 --- a/Common/Classes/EventArgsEx.cs +++ b/Common/Classes/EventArgsEx.cs @@ -84,18 +84,17 @@ public static class IEventExtensions { public static bool HasSource(IEvent @event) { - return Object.ReferenceEquals(@event, null).Equals(false) && - Object.ReferenceEquals(@event.Source, null).Equals(false); + return @event is not null && @event.Source is not null; } public static bool IsEnabled(IEvent @event) { - return Object.ReferenceEquals(@event, null).Equals(false) && @event.Enabled; + return @event is not null && @event.Enabled; } public static bool IsNull(IEvent @event) { - return object.ReferenceEquals(@event, null); + return @event is null; } } @@ -110,7 +109,7 @@ internal class Eventbase : IEvent { public Eventbase(Delegate @event, bool enabled = true) { - if (object.ReferenceEquals(@event, null)) throw new ArgumentNullException("@event"); + if (@event is null) throw new ArgumentNullException("@event"); Source = @event; diff --git a/Common/Classes/MemorySegment.cs b/Common/Classes/MemorySegment.cs index 6045d374..e973872c 100644 --- a/Common/Classes/MemorySegment.cs +++ b/Common/Classes/MemorySegment.cs @@ -438,7 +438,7 @@ public bool Equals(MemorySegment other) [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool operator ==(MemorySegment a, MemorySegment b) { - return object.ReferenceEquals(b, null) ? object.ReferenceEquals(a, null) : a.Equals(b); + return b is null ? a is null : a.Equals(b); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -622,7 +622,7 @@ public static int Find(byte[] source, int start, int count, params MemorySegment if (found >= 0) { //If not already set then set it - if(object.ReferenceEquals(first, null)) first = segment; + first ??= segment; //Subtract from needed and if 0 remains break if ((needed -= found) == 0) break; diff --git a/Common/Classes/PacketBase.cs b/Common/Classes/PacketBase.cs index 421b8ee7..e0b6d8b1 100644 --- a/Common/Classes/PacketBase.cs +++ b/Common/Classes/PacketBase.cs @@ -425,7 +425,9 @@ bool IPacket.IsComplete [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] get { - if (object.ReferenceEquals(Completer, null)) return StaticCompleteFrom(null, null).Equals(int.MinValue); + if (Completer is null) + return StaticCompleteFrom(null, null).Equals(int.MinValue); + return Completer(null, null).Equals(int.MinValue); } } diff --git a/Common/Classes/TaggedException.cs b/Common/Classes/TaggedException.cs index 902db615..3fdfda8a 100644 --- a/Common/Classes/TaggedException.cs +++ b/Common/Classes/TaggedException.cs @@ -185,7 +185,8 @@ public TaggedException(T tag, string message, System.Exception innerException, p /// public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { - if (object.ReferenceEquals(null, info)) throw new System.ArgumentNullException(nameof(info)); + if (info is null) throw new System.ArgumentNullException(nameof(info)); + //Add the Tag to the info info.AddValue(TagPropertyString, Tag); //Get all other exception data from base. @@ -232,7 +233,11 @@ public static class TaggedExceptionExtensions /// /// The type related to the exception. /// The which occured. - public static void Raise(this TaggedException exception) { if (exception is not null) throw exception; } + public static void Raise(this TaggedException exception) + { + if (exception is not null) + throw exception; + } /// /// Tries to the given diff --git a/Common/Classes/Transport/TransportClient.cs b/Common/Classes/Transport/TransportClient.cs index 87471bca..c61dbc3d 100644 --- a/Common/Classes/Transport/TransportClient.cs +++ b/Common/Classes/Transport/TransportClient.cs @@ -137,7 +137,7 @@ public virtual void Disconnect() { } public TransportClient(System.Net.NetworkInformation.NetworkInterface networkInterface, bool shouldDispose = true) : base(shouldDispose) { - if (object.ReferenceEquals(networkInterface, null)) throw new System.ArgumentNullException(); + if (networkInterface is null) throw new System.ArgumentNullException(nameof(networkInterface)); NetworkInterface = networkInterface; } diff --git a/Common/Collections/Generic/ConcurrentThesaurus.cs b/Common/Collections/Generic/ConcurrentThesaurus.cs index 4a8649e8..a20decee 100644 --- a/Common/Collections/Generic/ConcurrentThesaurus.cs +++ b/Common/Collections/Generic/ConcurrentThesaurus.cs @@ -38,7 +38,6 @@ The above copyright notice and this permission notice shall be included in all c #region Using Statements -using Media.Common.Extensions.Generic.Dictionary; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -86,8 +85,6 @@ public class ConcurrentThesaurus : ILookup, ICollect readonly ConcurrentDictionary> Dictionary; - System.Collections.ICollection Collection { get { return Dictionary; } } - public int Count { get { return Dictionary.Count; } } public IEnumerable Keys { get { return Dictionary.Keys; } } @@ -328,7 +325,7 @@ void ICollection.CopyTo(TKey[] array, int arrayIndex) int ICollection.Count { - get { return Collection.Count; } + get { return Dictionary.Count; } } bool ICollection.IsReadOnly @@ -352,17 +349,17 @@ IEnumerator IEnumerable.GetEnumerator() public ConcurrentThesaurus(IDictionary> values, IEqualityComparer equalityComparer) { - Dictionary = new ConcurrentDictionary>(values, equalityComparer); + Dictionary = new (values, equalityComparer); } public ConcurrentThesaurus(int capacity, IEqualityComparer equalityComparer) { - Dictionary = new ConcurrentDictionary>(Environment.ProcessorCount, capacity, equalityComparer); + Dictionary = new (Environment.ProcessorCount, capacity, equalityComparer); } public ConcurrentThesaurus(IEqualityComparer equalityComparer) { - Dictionary = new ConcurrentDictionary>(equalityComparer); + Dictionary = new (equalityComparer); } public ConcurrentThesaurus(IDictionary> values) : this(values, EqualityComparer.Default) { } diff --git a/Common/Extensions/EnumerableExtensions.cs b/Common/Extensions/EnumerableExtensions.cs index 472229c1..856343dd 100644 --- a/Common/Extensions/EnumerableExtensions.cs +++ b/Common/Extensions/EnumerableExtensions.cs @@ -43,10 +43,9 @@ public static class EnumerableExtensions [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool SequenceEquals(this System.Collections.IEnumerable left, System.Collections.IEnumerable right) { - if (object.ReferenceEquals(left, null)) return object.ReferenceEquals(right, null); + if (left is null) return right is null; System.Collections.IEnumerator one, two; - System.IDisposable weird = null, strnage = null; try @@ -71,9 +70,8 @@ public static bool SequenceEquals(this System.Collections.IEnumerable left, Syst } finally { - if (object.ReferenceEquals(strnage, null).Equals(false)) strnage.Dispose(); - - if (object.ReferenceEquals(weird, null).Equals(false)) weird.Dispose(); + strnage?.Dispose(); + weird?.Dispose(); } } @@ -81,28 +79,18 @@ public static bool SequenceEquals(this System.Collections.IEnumerable left, Syst [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool SequenceEquals(this System.Collections.Generic.IEnumerable left, System.Collections.Generic.IEnumerable right) { - if (object.ReferenceEquals(left, null)) return object.ReferenceEquals(right, null); + if (left is null) return right is null; - try - { - using (var weird = left.GetEnumerator()) - { - using (var strnage = right.GetEnumerator()) - { - while (weird.MoveNext()) - { - if (strnage.MoveNext().Equals(false) || - weird.Current.Equals(strnage.Current).Equals(false)) return false; - } + using var weird = left.GetEnumerator(); + using var strnage = right.GetEnumerator(); - return true; - } - } - } - catch + while (weird.MoveNext()) { - throw; + if (strnage.MoveNext().Equals(false) || + weird.Current.Equals(strnage.Current).Equals(false)) return false; } + + return true; } } } diff --git a/Common/Extensions/ExceptionExtensions.cs b/Common/Extensions/ExceptionExtensions.cs index cf475c35..32666b92 100644 --- a/Common/Extensions/ExceptionExtensions.cs +++ b/Common/Extensions/ExceptionExtensions.cs @@ -92,7 +92,7 @@ public class ArgumentNullOrDisposedException : System.ArgumentNullException public bool HasDisposed { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - get { return object.ReferenceEquals(null, Disposed).Equals(false); } + get { return Disposed is not null; } } #if DEBUG diff --git a/Common/Extensions/NetworkInterfaceExtensions.cs b/Common/Extensions/NetworkInterfaceExtensions.cs index 332c5433..4a625d12 100644 --- a/Common/Extensions/NetworkInterfaceExtensions.cs +++ b/Common/Extensions/NetworkInterfaceExtensions.cs @@ -125,15 +125,15 @@ public static System.Net.NetworkInformation.NetworkInterface GetNetworkInterface public static System.Net.NetworkInformation.NetworkInterface GetNetworkInterface(System.Net.IPEndPoint localEndPoint) { - if (object.ReferenceEquals(localEndPoint, null)) throw new System.ArgumentNullException("localEndPoint"); + if (localEndPoint is null) throw new System.ArgumentNullException(nameof(localEndPoint)); return GetNetworkInterface(localEndPoint.Address); } public static System.Net.NetworkInformation.NetworkInterface GetNetworkInterface(System.Net.Sockets.Socket socket) { - if (object.ReferenceEquals(socket, null)) throw new System.ArgumentNullException("socket"); - else if (socket.Handle == System.IntPtr.Zero) return null; + if (socket is null) throw new System.ArgumentNullException(nameof(socket)); + else if (socket.Handle == nint.Zero) return null; System.Net.IPEndPoint localEndPoint = socket.IsBound.Equals(false) ? Common.Extensions.IPEndPoint.IPEndPointExtensions.Any : (System.Net.IPEndPoint)socket.LocalEndPoint; @@ -148,7 +148,7 @@ public static System.Net.NetworkInformation.NetworkInterface GetNetworkInterface [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static double GetSpeedInMBytesPerSecond(this System.Net.NetworkInformation.NetworkInterface networkInterface) { - if (object.ReferenceEquals(networkInterface, null)) return 0; + if (networkInterface is null) return 0; long speed = networkInterface.Speed; diff --git a/Common/Extensions/SocketExtensions.cs b/Common/Extensions/SocketExtensions.cs index 977d7b44..811bb1cf 100644 --- a/Common/Extensions/SocketExtensions.cs +++ b/Common/Extensions/SocketExtensions.cs @@ -164,7 +164,7 @@ public static int FindOpenPort(System.Net.Sockets.ProtocolType type, int start = [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public static int ProbeForOpenPort(System.Net.Sockets.ProtocolType type, int start = 30000, bool even = true, System.Net.IPAddress localIp = null) { - if (object.ReferenceEquals(localIp, null)) localIp = GetFirstUnicastIPAddress(System.Net.Sockets.AddressFamily.InterNetwork); // System.Net.IPAddress.Any should give unused ports across all IP's? + localIp ??= GetFirstUnicastIPAddress(System.Net.Sockets.AddressFamily.InterNetwork); // System.Net.IPAddress.Any should give unused ports across all IP's? System.Net.Sockets.Socket working = null; @@ -283,7 +283,7 @@ public static System.Net.IPAddress GetFirstUnicastIPAddress(System.Net.Sockets.A System.Net.IPAddress result = Common.Extensions.NetworkInterface.NetworkInterfaceExtensions.GetFirstUnicastIPAddress(foundInterface, addressFamily); //If the result is not null and the result is not System.Net.IPAddress.None - if (false.Equals(object.ReferenceEquals(result, null)) && false.Equals(Equals(result, System.Net.IPAddress.None))) + if (result is not null && false.Equals(Equals(result, System.Net.IPAddress.None))) { networkInterface = foundInterface; diff --git a/Common/Extensions/StreamExtensions.cs b/Common/Extensions/StreamExtensions.cs index 7d04f73c..b41cb5b3 100644 --- a/Common/Extensions/StreamExtensions.cs +++ b/Common/Extensions/StreamExtensions.cs @@ -1052,19 +1052,16 @@ protected internal override void Dispose(bool disposing) /// The byte to read for /// An optional value indicating if delimit should be present in the result /// The bytes read from the reader - public static byte[] ReadDelimitedValue(this System.IO.Stream stream, byte delimit = Common.ASCII.LineFeed, bool includeDelimit = false) + public static Common.MemorySegment ReadDelimitedValue(this System.IO.Stream stream, byte delimit = Common.ASCII.LineFeed, bool includeDelimit = false) { - //The result of reading from the stream - byte[] result = null; - //Declare a value which will end up in a register on the stack - int register = -1; + int register = -1, count = 0; //Indicate when to terminate reading. bool terminate = false; //Use a MemoryStream as to not lock the reader - using (var buffer = new System.IO.MemoryStream()) + using (var buffer = new System.IO.MemoryStream(128)) { //While data can be read from the stream while (false == terminate) @@ -1080,13 +1077,16 @@ public static byte[] ReadDelimitedValue(this System.IO.Stream stream, byte delim //Write the value read from the reader to the MemoryStream buffer.WriteByte((byte)register); + + //Store count + ++count; } //If terminating then return the array contained in the MemoryStream. - result = buffer.ToArray(); - } + var result = buffer.ToArray(); - //Return the bytes read from the stream - return result; + //Return the bytes read from the stream + return new Common.MemorySegment(result, 0, count); + } } /// @@ -1095,7 +1095,7 @@ public static byte[] ReadDelimitedValue(this System.IO.Stream stream, byte delim /// /// /// - public static void ReadLineFeed(this System.IO.Stream stream, out byte[] result) + public static void ReadLineFeed(this System.IO.Stream stream, out Common.MemorySegment result) { //The length of the array allocated is known and should also be returned... result = Common.Extensions.Stream.StreamExtensions.ReadDelimitedValue(stream, Common.ASCII.LineFeed, true); diff --git a/Common/Extensions/SymbolExtensions.cs b/Common/Extensions/SymbolExtensions.cs index b40d84ee..8b3173c6 100644 --- a/Common/Extensions/SymbolExtensions.cs +++ b/Common/Extensions/SymbolExtensions.cs @@ -74,9 +74,9 @@ static Func MagicMethod(MethodInfo method) where T : class static SymbolExtensions() { //Ensure not already ran. - if (false.Equals(object.ReferenceEquals(TypedConstantExpressionType, null)) - | false.Equals(object.ReferenceEquals(InstanceMethodCallExpressionNType, null)) - | false.Equals(object.ReferenceEquals(TypedConstantExpressionValueProperty, null))) return; + if (false.Equals(TypedConstantExpressionType is null) + | false.Equals(InstanceMethodCallExpressionNType is null) + | false.Equals(TypedConstantExpressionValueProperty is null)) return; //For example //Expression ConstantExpression = () => Common.Binary.Nihil.Equals(null); @@ -112,9 +112,9 @@ static SymbolExtensions() [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static MethodCallExpression CreateMethodCallExpression(MethodInfo method) { - if (object.ReferenceEquals(method,null)) + if (method is null) { - throw new ArgumentNullException("method"); + throw new ArgumentNullException(nameof(method)); } //Return the MethodCallExpression (parameters are included) @@ -215,9 +215,9 @@ public static MemberInfo GetMemberInfo(LambdaExpression expression) { MemberExpression outermostExpression = ((expression.Body as MethodCallExpression).Object as MemberExpression); - if (object.ReferenceEquals(outermostExpression, null)) throw new ArgumentException("Invalid Expression. Should be a MemberExpression"); - - return outermostExpression.Member; + return outermostExpression is null + ? throw new ArgumentException("Invalid Expression. Should be a MemberExpression", nameof(expression)) + : outermostExpression.Member; } /// @@ -261,9 +261,8 @@ public static MethodInfo GetMethodInfo(Expression> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static MethodInfo GetMethodInfo(LambdaExpression expression) { - MethodCallExpression outermostExpression = expression.Body as MethodCallExpression; - - if (object.ReferenceEquals(outermostExpression, null)) throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only."); + if (expression.Body is not MethodCallExpression outermostExpression) + throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only.", nameof(expression)); return outermostExpression.Method; } diff --git a/Common/Extensions/ThreadExtensions.cs b/Common/Extensions/ThreadExtensions.cs index 36faae73..94b37719 100644 --- a/Common/Extensions/ThreadExtensions.cs +++ b/Common/Extensions/ThreadExtensions.cs @@ -53,7 +53,7 @@ public static class ThreadExtensions [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool IsRunning(System.Threading.Thread thread) { - return false.Equals(object.ReferenceEquals(thread, null)) && + return thread is not null && (thread.ThreadState & (System.Threading.ThreadState.Stopped | System.Threading.ThreadState.Unstarted)) == System.Threading.ThreadState.Running; } @@ -89,7 +89,7 @@ public static void AbortAndFree(ref System.Threading.Thread thread, System.Threa public static void AbortAndFree(ref System.Threading.Thread thread, System.TimeSpan timeout, System.Threading.ThreadState state = System.Threading.ThreadState.Stopped) { //If the worker IsAlive and has doesn't have the requested state. - if (false.Equals(object.ReferenceEquals(thread, null)) && + if (thread is not null && false.Equals(thread.ThreadState.HasFlag(state))) { //Attempt to join if not already, todo check flags are compatible in all implementations. @@ -110,7 +110,7 @@ public static bool TryAbortAndFree(ref System.Threading.Thread thread, System.Th try { AbortAndFree(ref thread, state, timeout); } catch { return false; } - return object.ReferenceEquals(thread, null); + return thread is null; } public static bool TryAbortAndFree(ref System.Threading.Thread thread, System.TimeSpan timeout, System.Threading.ThreadState state = System.Threading.ThreadState.Stopped) @@ -118,8 +118,7 @@ public static bool TryAbortAndFree(ref System.Threading.Thread thread, System.Ti try { AbortAndFree(ref thread, timeout, state); } catch { return false; } - return object.ReferenceEquals(thread, null); - } - + return thread is null; + } } } diff --git a/Common/Interfaces/IDisposed.cs b/Common/Interfaces/IDisposed.cs index bb272370..66dbd383 100644 --- a/Common/Interfaces/IDisposed.cs +++ b/Common/Interfaces/IDisposed.cs @@ -68,19 +68,19 @@ public static class IDisposedExtensions [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool IsNullOrDisposed(this IDisposed dispose) { - return object.ReferenceEquals(dispose, null) || dispose.IsDisposed; + return dispose is null || dispose.IsDisposed; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool ShouldDisposed(this IDisposed dispose) { - return false.Equals(object.ReferenceEquals(dispose, null)) && dispose.ShouldDispose; + return dispose is not null && dispose.ShouldDispose; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static void CheckDisposed(this IDisposed dispose) { - if (false.Equals(object.ReferenceEquals(dispose, null)) && dispose.IsDisposed) throw new System.ObjectDisposedException("IDisposedExtensions.CheckDisposed,true"); + if (dispose is not null && dispose.IsDisposed) throw new System.ObjectDisposedException("IDisposedExtensions.CheckDisposed,true"); } //public static void SetShouldDispose(this IDisposed dispose, bool value, bool callDispose = false) diff --git a/Common/Interfaces/ILogging.cs b/Common/Interfaces/ILogging.cs index 252db94a..80419c54 100644 --- a/Common/Interfaces/ILogging.cs +++ b/Common/Interfaces/ILogging.cs @@ -72,7 +72,7 @@ public static void Log(this ILogging log, string message) public static void LogException(this ILogging log, System.Exception exception) { - if (object.ReferenceEquals(exception, null) || IDisposedExtensions.IsNullOrDisposed(log)) return; + if (exception is null || IDisposedExtensions.IsNullOrDisposed(log)) return; log.LogException(exception); } diff --git a/Common/Interfaces/IParser.cs b/Common/Interfaces/IParser.cs index e622cd5e..7a6e9246 100644 --- a/Common/Interfaces/IParser.cs +++ b/Common/Interfaces/IParser.cs @@ -97,7 +97,7 @@ void IParser.OnStateChanged(ref uint state, ref ulong left, ref ulong right) { case Zero: { - ((ICompletable)this).OnCompletion(object.ReferenceEquals(OnRealization, null).Equals(false)); + ((ICompletable)this).OnCompletion(OnRealization is not null); break; } diff --git a/Common/Interfaces/IShareds.cs b/Common/Interfaces/IShareds.cs index 8c553037..b25d7535 100644 --- a/Common/Interfaces/IShareds.cs +++ b/Common/Interfaces/IShareds.cs @@ -58,7 +58,7 @@ public static class ISharedExtensions /// public static bool IsOwned(this IShared shared) { - return object.ReferenceEquals(shared, null).Equals(false) && shared.IsShared.Equals(false); + return shared is not null && shared.IsShared.Equals(false); } } diff --git a/Rtp/RFC3550.cs b/Rtp/RFC3550.cs index a52d2c5f..33633c3f 100644 --- a/Rtp/RFC3550.cs +++ b/Rtp/RFC3550.cs @@ -1336,7 +1336,7 @@ public int CopyTo(byte[] dest, int offset) [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool operator ==(CommonHeaderBits a, CommonHeaderBits b) { - return object.ReferenceEquals(b, null) ? object.ReferenceEquals(a, null) : a.Equals(b); + return b is null ? a is null : a.Equals(b); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] diff --git a/Rtp/Rtcp/RtcpHeader.cs b/Rtp/Rtcp/RtcpHeader.cs index acf23d1d..41e5a764 100644 --- a/Rtp/Rtcp/RtcpHeader.cs +++ b/Rtp/Rtcp/RtcpHeader.cs @@ -613,7 +613,7 @@ public override bool Equals(object obj) public static bool operator ==(RtcpHeader a, RtcpHeader b) { - return object.ReferenceEquals(b, null) ? object.ReferenceEquals(a, null) : a.Equals(b); + return b is null ? a is null : a.Equals(b); } public static bool operator !=(RtcpHeader a, RtcpHeader b) { return (a == b).Equals(false); } diff --git a/Rtp/Rtcp/RtcpPacket.cs b/Rtp/Rtcp/RtcpPacket.cs index 77fa24ac..23bf0c95 100644 --- a/Rtp/Rtcp/RtcpPacket.cs +++ b/Rtp/Rtcp/RtcpPacket.cs @@ -947,15 +947,20 @@ internal protected static void MapDerivedImplementations(AppDomain domain = null /// The result of adding the implemention to the InstanceMap internal static bool TryMapImplementation(byte payloadType, Type implementation) { - Exception any; return payloadType > default(byte) && - object.ReferenceEquals(implementation, null).Equals(false) && - implementation.IsAbstract.Equals(false) && - implementation.IsSubclassOf(RtcpPacketType) - ? Media.Common.Extensions.Generic.Dictionary.DictionaryExtensions.TryAdd(ImplementationMap, payloadType, implementation, out any) : false; + implementation is not null && + implementation.IsAbstract.Equals(false) && + implementation.IsSubclassOf(RtcpPacketType) + ? Media.Common.Extensions.Generic.Dictionary.DictionaryExtensions.TryAdd(ImplementationMap, payloadType, implementation, out _) + : false; } - internal static bool TryUnMapImplementation(byte payloadType, out Type implementation) { implementation = null; Exception any; return payloadType > default(byte) && Media.Common.Extensions.Generic.Dictionary.DictionaryExtensions.TryRemove(ImplementationMap, payloadType, out implementation, out any); } + internal static bool TryUnMapImplementation(byte payloadType, out Type implementation) + { + implementation = null; + return payloadType > default(byte) && + Media.Common.Extensions.Generic.Dictionary.DictionaryExtensions.TryRemove(ImplementationMap, payloadType, out implementation, out _); + } #endregion @@ -1023,7 +1028,7 @@ public override bool Equals(object obj) [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool operator ==(RtcpPacket a, RtcpPacket b) { - return object.ReferenceEquals(b, null) ? object.ReferenceEquals(a, null) : a.Equals(b); + return b is null ? a is null : a.Equals(b); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] diff --git a/Rtp/RtpClient.Constants.cs b/Rtp/RtpClient.Constants.cs index ad1244d8..223a7d8a 100644 --- a/Rtp/RtpClient.Constants.cs +++ b/Rtp/RtpClient.Constants.cs @@ -211,7 +211,7 @@ public static RtpClient FromSessionDescription(Sdp.SessionDescription sessionDes System.Net.NetworkInformation.NetworkInterface localInterface; //If the socket is NOT null and IS BOUND use the localIp of the same address family - if (object.ReferenceEquals(existingSocket, null).Equals(false) && existingSocket.IsBound) + if (existingSocket is not null && existingSocket.IsBound) { //If the socket is IP based if (existingSocket.LocalEndPoint is System.Net.IPEndPoint) diff --git a/Rtp/RtpClient.cs b/Rtp/RtpClient.cs index 9d97603f..f12c98b3 100644 --- a/Rtp/RtpClient.cs +++ b/Rtp/RtpClient.cs @@ -204,21 +204,24 @@ public static TransportContext FromMediaDescription(Sdp.SessionDescription sessi Action configure = null) { //Must have a mediaDescription - if (Common.IDisposedExtensions.IsNullOrDisposed(mediaDescription)) throw new ArgumentNullException("mediaDescription"); + if (Common.IDisposedExtensions.IsNullOrDisposed(mediaDescription)) + throw new ArgumentNullException(nameof(mediaDescription)); //If there is no sdp there must be a local and remoteIp - if (Common.IDisposedExtensions.IsNullOrDisposed(sessionDescription) && (object.ReferenceEquals(localIp, null) || object.ReferenceEquals(remoteIp, null))) throw new InvalidOperationException("Must have a sessionDescription or the localIp and remoteIp cannot be established."); + if (Common.IDisposedExtensions.IsNullOrDisposed(sessionDescription) && + (localIp is null || remoteIp is null)) + throw new InvalidOperationException("Must have a sessionDescription or the localIp and remoteIp cannot be established."); //If no remoteIp was given attempt to parse it from the sdp - if (object.ReferenceEquals(remoteIp, null)) + if (remoteIp is null) { Sdp.SessionDescriptionLine cLine = mediaDescription.ConnectionLine; //Try the sesion level if the media level doesn't have one - if (object.ReferenceEquals(cLine, null)) cLine = sessionDescription.ConnectionLine; + cLine ??= sessionDescription.ConnectionLine; //Attempt to parse the IP, if failed then throw an exception. - if (object.ReferenceEquals(cLine, null) + if (cLine is null || false.Equals(IPAddress.TryParse(new Sdp.Lines.SessionConnectionLine(cLine).Host, out remoteIp))) throw new InvalidOperationException("Cannot determine remoteIp from ConnectionLine"); } @@ -228,7 +231,7 @@ public static TransportContext FromMediaDescription(Sdp.SessionDescription sessi //If no localIp was given determine based on the remoteIp //--When there is no remoteIp this should be done first to determine if the sender is multicasting. - if (object.ReferenceEquals(localIp, null)) localIp = multiCast ? Media.Common.Extensions.Socket.SocketExtensions.GetFirstMulticastIPAddress(remoteIp.AddressFamily) : Media.Common.Extensions.Socket.SocketExtensions.GetFirstUnicastIPAddress(remoteIp.AddressFamily); + localIp ??= multiCast ? Media.Common.Extensions.Socket.SocketExtensions.GetFirstMulticastIPAddress(remoteIp.AddressFamily) : Media.Common.Extensions.Socket.SocketExtensions.GetFirstUnicastIPAddress(remoteIp.AddressFamily); //The localIp and remoteIp should be on the same network otherwise they will need to be mapped or routed. //In most cases this can be mapped. @@ -251,7 +254,7 @@ public static TransportContext FromMediaDescription(Sdp.SessionDescription sessi //To use typed line - if (object.ReferenceEquals(ssrcLine,null).Equals(false)) + if (ssrcLine is not null) { string part = ssrcLine.GetPart(1); @@ -365,7 +368,7 @@ number of senders. When the proportion of senders is greater than Sdp.SessionDescriptionLine rtcpLine = mediaDescription.RtcpLine; - if (object.ReferenceEquals(rtcpLine,null).Equals(false)) + if (rtcpLine is not null) { //Todo... //parts are already present just needs a type to parse out the relevent parts into managed fields.. @@ -389,10 +392,10 @@ number of senders. When the proportion of senders is greater than if (connect) { //Determine if a socket was given or if it will be created. - bool hasSocket = object.ReferenceEquals(existingSocket, null).Equals(false); + bool hasSocket = existingSocket is not null; //If a configuration has been given then set that configuration in the TransportContext. - if (object.ReferenceEquals(configure, null).Equals(false)) tc.ConfigureSocket = configure; + if (configure is not null) tc.ConfigureSocket = configure; //Check for udp if no existing socket was given if (hasSocket.Equals(false) && string.Compare(mediaDescription.MediaProtocol, Media.Rtp.RtpClient.RtpAvpProfileIdentifier, true).Equals(0)) @@ -1330,7 +1333,7 @@ public Sdp.MediaDescription MediaDescription public bool LocalMultiplexing { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - get { return (IDisposedExtensions.IsNullOrDisposed(this) || IsRtcpEnabled.Equals(false) || object.ReferenceEquals(LocalRtp, null)) ? false : LocalRtp.Equals(LocalRtcp); } + get { return (IDisposedExtensions.IsNullOrDisposed(this) || IsRtcpEnabled.Equals(false) || LocalRtp is null) ? false : LocalRtp.Equals(LocalRtcp); } } /// @@ -1339,7 +1342,7 @@ public bool LocalMultiplexing public bool RemoteMultiplexing { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - get { return (IDisposedExtensions.IsNullOrDisposed(this) || IsRtcpEnabled.Equals(false) || object.ReferenceEquals(RemoteRtp, null)) ? false : RemoteRtp.Equals(RemoteRtcp); } + get { return (IDisposedExtensions.IsNullOrDisposed(this) || IsRtcpEnabled.Equals(false) || RemoteRtp is null) ? false : RemoteRtp.Equals(RemoteRtcp); } } /// @@ -2148,10 +2151,10 @@ public void Initialize(Socket rtpSocket, Socket rtcpSocket) { if (IDisposedExtensions.IsNullOrDisposed(this) || IsActive) return; - if (object.ReferenceEquals(rtpSocket, null)) throw new ArgumentNullException(nameof(rtpSocket)); + if (rtpSocket is null) throw new ArgumentNullException(nameof(rtpSocket)); //Maybe should just be set to the rtpSocket? - if (object.ReferenceEquals(rtcpSocket, null)) throw new ArgumentNullException(nameof(rtcpSocket)); + if (rtcpSocket is null) throw new ArgumentNullException(nameof(rtcpSocket)); //RtpBytesRecieved = RtpBytesSent = RtcpBytesRecieved = RtcpBytesSent = 0; @@ -2163,9 +2166,9 @@ public void Initialize(Socket rtpSocket, Socket rtcpSocket) bool punchHole = false.Equals(RtpSocket.ProtocolType == ProtocolType.Tcp) && false.Equals(Media.Common.Extensions.IPAddress.IPAddressExtensions.IsOnIntranet(((IPEndPoint)RtpSocket.RemoteEndPoint).Address)); //Only punch a hole if the remoteIp is not on the LAN by default. - if (object.ReferenceEquals(RemoteRtp, null)) RemoteRtp = RtpSocket.RemoteEndPoint; + RemoteRtp ??= RtpSocket.RemoteEndPoint; - if (object.ReferenceEquals(LocalRtp, null)) + if (LocalRtp is null) { LocalRtp = RtpSocket.LocalEndPoint; @@ -2210,9 +2213,9 @@ public void Initialize(Socket rtpSocket, Socket rtcpSocket) { //Just assign the same end points from the rtp socket. - if (object.ReferenceEquals(LocalRtcp, null)) LocalRtcp = LocalRtp; + LocalRtcp ??= LocalRtp; - if (object.ReferenceEquals(RemoteRtcp, null)) RemoteRtcp = RemoteRtp; + RemoteRtcp ??= RemoteRtp; } } else RtcpSocket = RtpSocket; @@ -3378,7 +3381,7 @@ protected internal void OnOutOfBandData(byte[] data, int offset, int length) InterleavedDataHandler action = OutOfBandData; - if (object.ReferenceEquals(action, null) || data == null || length.Equals(Common.Binary.Zero)) return; + if (action is null || data == null || length.Equals(Common.Binary.Zero)) return; if (m_ThreadEvents) { @@ -3403,7 +3406,7 @@ internal void ParallelOutOfBandData(Media.Common.Classes.PacketBase packet = nul InterleavedDataHandler action = OutOfBandData; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet) || packet.Length.Equals(Common.Binary.LongZero)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet) || packet.Length.Equals(Common.Binary.LongZero)) return; ParallelEnumerable.ForAll(action.GetInvocationList().AsParallel(), (d) => { @@ -3428,7 +3431,7 @@ protected internal void OnRtpPacketReceieved(RtpPacket packet, TransportContext RtpPacketHandler action = RtpPacketReceieved; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet)) return; bool shouldDispose = packet.ShouldDispose; @@ -3469,7 +3472,7 @@ protected internal void OnRtcpPacketReceieved(RtcpPacket packet = null, Transpor RtcpPacketHandler action = RtcpPacketReceieved; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet)) return; bool shouldDispose = packet.ShouldDispose; @@ -3511,7 +3514,7 @@ internal protected void OnRtpFrameChanged(RtpFrame frame = null, TransportContex RtpFrameHandler action = RtpFrameChanged; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(frame) || frame.IsEmpty) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(frame) || frame.IsEmpty) return; bool shouldDispose = frame.ShouldDispose; @@ -3545,7 +3548,7 @@ internal void ParallelRtpFrameChanged(RtpFrame frame = null, TransportContext tc RtpFrameHandler action = RtpFrameChanged; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(frame) || frame.IsEmpty) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(frame) || frame.IsEmpty) return; bool shouldDispose = frame.ShouldDispose; @@ -3572,7 +3575,7 @@ internal void ParallelRtpPacketRecieved(RtpPacket packet = null, TransportContex RtpPacketHandler action = RtpPacketReceieved; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet)) return; //RtpFrameHandler would need the cast up front. ParallelEnumerable.ForAll(action.GetInvocationList().AsParallel(), (d) => @@ -3593,7 +3596,7 @@ internal void ParallelRtpPacketSent(RtpPacket packet = null, TransportContext tc RtpPacketHandler action = RtpPacketSent; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet)) return; //RtpFrameHandler would need the cast up front. ParallelEnumerable.ForAll(action.GetInvocationList().AsParallel(), (d) => @@ -3614,7 +3617,7 @@ internal void ParallelRtcpPacketRecieved(RtcpPacket packet = null, TransportCont RtcpPacketHandler action = RtcpPacketReceieved; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet)) return; //RtpFrameHandler would need the cast up front. ParallelEnumerable.ForAll(action.GetInvocationList().AsParallel(), (d) => @@ -3636,7 +3639,7 @@ internal void ParallelRtcpPacketSent(RtcpPacket packet = null, TransportContext RtcpPacketHandler action = RtcpPacketSent; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet)) return; //RtpFrameHandler would need the cast up front. ParallelEnumerable.ForAll(action.GetInvocationList().AsParallel(), (d) => @@ -3663,7 +3666,7 @@ internal protected void OnRtpPacketSent(RtpPacket packet, TransportContext tc = RtpPacketHandler action = RtpPacketSent; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet) || Common.IDisposedExtensions.IsNullOrDisposed(this)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet) || Common.IDisposedExtensions.IsNullOrDisposed(this)) return; //bool shouldDispose = packet.ShouldDispose; @@ -3699,7 +3702,7 @@ internal protected void OnRtcpPacketSent(RtcpPacket packet, TransportContext tc RtcpPacketHandler action = RtcpPacketSent; - if (object.ReferenceEquals(action, null) || IDisposedExtensions.IsNullOrDisposed(packet)) return; + if (action is null || IDisposedExtensions.IsNullOrDisposed(packet)) return; //bool shouldDispose = packet.ShouldDispose; @@ -3802,7 +3805,7 @@ public bool ThreadEvents //Enable if (m_EventThread == null || EventsStarted.Equals(DateTime.MinValue)) { //Create the event thread - m_EventThread = new Thread(new ThreadStart(HandleEvents), Common.Extensions.Thread.ThreadExtensions.MinimumStackSize) + m_EventThread = new Thread(new ThreadStart(HandleEvents),// Common.Extensions.Thread.ThreadExtensions.MinimumStackSize) { //Assign name Name = "RtpClient-Events-" + InternalId, @@ -3812,7 +3815,7 @@ public bool ThreadEvents //Enable }; //Configure - ConfigureThread(m_EventThread); //should pass name and logging. + ConfigureThread(m_EventThread); //Start thread m_EventThread.Start(); diff --git a/Rtp/RtpFrame.cs b/Rtp/RtpFrame.cs index 845204f9..616dcc54 100644 --- a/Rtp/RtpFrame.cs +++ b/Rtp/RtpFrame.cs @@ -1528,7 +1528,7 @@ public override bool Equals(object obj) [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool operator ==(RtpFrame a, RtpFrame b) { - return object.ReferenceEquals(b, null) ? object.ReferenceEquals(a, null) : a.Equals(b); + return b is null ? a is null : a.Equals(b); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] diff --git a/Rtp/RtpHeader.cs b/Rtp/RtpHeader.cs index 546d9cfe..67775a08 100644 --- a/Rtp/RtpHeader.cs +++ b/Rtp/RtpHeader.cs @@ -613,7 +613,7 @@ public override bool Equals(object obj) public static bool operator ==(RtpHeader a, RtpHeader b) { - return object.ReferenceEquals(b, null) ? object.ReferenceEquals(a, null) : a.Equals(b); + return b is null ? a is null : a.Equals(b); } public static bool operator !=(RtpHeader a, RtpHeader b) { return (a == b).Equals(false); } diff --git a/Rtp/RtpPacket.cs b/Rtp/RtpPacket.cs index fab7fcb5..c5bbf50d 100644 --- a/Rtp/RtpPacket.cs +++ b/Rtp/RtpPacket.cs @@ -962,7 +962,7 @@ public bool IsContiguous() [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public static bool operator ==(RtpPacket a, RtpPacket b) { - return object.ReferenceEquals(b, null) ? object.ReferenceEquals(a, null) : a.Equals(b); + return b is null ? a is null : a.Equals(b); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] diff --git a/RtpTools/RtpDump.cs b/RtpTools/RtpDump.cs index 39f5de94..44040f16 100644 --- a/RtpTools/RtpDump.cs +++ b/RtpTools/RtpDump.cs @@ -70,7 +70,7 @@ public sealed class DumpReader : Common.BaseDisposable, IEnumerable /// Used in non Text format parsing. /// - internal byte[] m_FileIdentifier, m_FileHeader; + internal Common.MemorySegment m_FileIdentifier, m_FileHeader; #endregion @@ -176,7 +176,7 @@ void ReadBinaryFileIdentifier() m_FileIdentifier = Common.Extensions.Stream.StreamExtensions.ReadDelimitedValue(m_Reader.BaseStream); //Get the length of the file header - int length = m_FileIdentifier.Length; + int length = m_FileIdentifier.Count; //strict /.. //Check for Hash, Bang? someone might have wrote something else... @@ -196,7 +196,7 @@ void ReadBinaryFileIdentifier() //rtpplay is not present or if the format was unknown then if (!m_FileIdentifier.Skip(start).Take(count).SequenceEqual(Encoding.ASCII.GetBytes(RtpPlay.RtpPlayFormat)) || - Array.IndexOf(m_FileIdentifier, 0x2f, start + count, m_FileIdentifier.Length - (start + count)) == -1) // start == -1 + Array.IndexOf(m_FileIdentifier.Array, 0x2f, start + count, m_FileIdentifier.Count - (start + count)) == -1) // start == -1 { goto Invalid; } @@ -224,10 +224,10 @@ void ReadBinaryFileHeader() //Read the 16 byte binary header here which contains data redundant of the firstLine. //This will be the last RD_hdr_t in the file. - m_FileHeader = new byte[RtpToolEntry.sizeOf_RD_hdr_t]; + m_FileHeader = new Common.MemorySegment(RtpToolEntry.sizeOf_RD_hdr_t); //Read the 8 byte timeval, 4 byte ip and 2 byte port, if there is padding the next bytes will be 0 otherwise the RD_packet_t starts there. - m_Reader.Read(m_FileHeader, 0, 14); + m_Reader.Read(m_FileHeader.Array, 0, 14); m_StartTime = Media.Ntp.NetworkTimeProtocol.UtcEpoch1970.AddSeconds(BitConverter.Int64BitsToDouble(Common.Binary.Read64(m_FileHeader, 0, Common.Binary.IsLittleEndian))); @@ -237,7 +237,7 @@ void ReadBinaryFileHeader() if (m_Reader.PeekChar() != 0) return; //Read the padding out - m_Reader.Read(m_FileHeader, 14, 2); + m_Reader.Read(m_FileHeader.Array, 14, 2); } /// @@ -275,7 +275,7 @@ internal RtpToolEntry ReadToolEntry() //Only contains data if something goes wrong during parsing, //And would then contain the data consumed while attempting to parse. - byte[] unexpectedData = null; + Common.MemorySegment unexpectedData = null; //This allows certain text items to have a data= token and others to not. //It also allows reading of Rtp in Rtcp only mode @@ -314,11 +314,13 @@ internal RtpToolEntry ReadToolEntry() //If the the format of the entry found was binary if (entry.Format < FileFormat.Text) { - //The unexpected data consists of the supposed fileheader. - if (m_FileIdentifier == null) - { + + //The unexpected data consists of the supposed fileheader. + if (m_FileIdentifier == null) + { //Assign it - m_FileIdentifier = unexpectedData; + m_FileIdentifier = new (unexpectedData); + //Read the following Binary File Header ReadBinaryFileHeader(); @@ -332,7 +334,13 @@ internal RtpToolEntry ReadToolEntry() //Read the entry. return ReadToolEntry(); } - else Media.Common.TaggedExceptionExtensions.RaiseTaggedException(unexpectedData, "Encountered a Binary file header when already parsed the header. The Tag property contains the data unexpected."); + else if (unexpectedData != null) Media.Common.TaggedExceptionExtensions.RaiseTaggedException(unexpectedData, "Encountered a Binary file header when already parsed the header. The Tag property contains the data unexpected."); + } + + //Call determine format so item has the correct format (Header [or Payload]) + if (foundFormat == FileFormat.Unknown) + { + Media.Common.TaggedExceptionExtensions.RaiseTaggedException(entry, "Unknown format"); } else if (unexpectedData != null) Media.Common.TaggedExceptionExtensions.RaiseTaggedException(entry, "Unexpected data found while parsing a Text format. See the Tag property of the InnerException", new Common.TaggedException(unexpectedData)); } @@ -574,7 +582,7 @@ public sealed class DumpWriter : Common.BaseDisposable FileFormat m_Format; //The file header of the Dump being written - byte[] m_FileIdentifier, m_FileHeader; + Common.MemorySegment m_FileIdentifier, m_FileHeader; System.IO.BinaryWriter m_Writer; @@ -734,12 +742,12 @@ public void WriteFileHeader(bool force = false) if(m_FileIdentifier == null) m_FileIdentifier = RtpDumpExtensions.CreateFileIdentifier(m_Source); //Write the file header - m_Writer.Write(m_FileIdentifier, 0, m_FileIdentifier.Length); + m_Writer.Write(m_FileIdentifier.Array, m_FileIdentifier.Offset, m_FileIdentifier.Count); if (m_FileHeader == null) m_FileHeader = RtpDumpExtensions.CreateFileHeader(m_Start, m_Source); //Write the RD_hdr_t - m_Writer.Write(m_FileHeader, 0, m_FileHeader.Length); + m_Writer.Write(m_FileHeader.Array, m_FileHeader.Offset, m_FileHeader.Count); } //We wrote the header... @@ -1006,13 +1014,13 @@ public static class RtpDumpExtensions /// /// The which will be indicated in the header. /// The bytes created - internal static byte[] CreateFileIdentifier(System.Net.IPEndPoint source) + internal static Common.MemorySegment CreateFileIdentifier(System.Net.IPEndPoint source) { //All files must indicate a source address and port if (source == null) throw new ArgumentNullException("source"); //Strings in .Net are encoded in Unicode encoding unless otherwise specified, e.g. in the MicroFramework UTF-8 - return System.Text.Encoding.ASCII.GetBytes(string.Format(FileHeaderFormat, source.Address.ToString(), source.Port.ToString())); + return new(System.Text.Encoding.ASCII.GetBytes(string.Format(FileHeaderFormat, source.Address.ToString(), source.Port.ToString()))); } /// @@ -1020,7 +1028,7 @@ internal static byte[] CreateFileIdentifier(System.Net.IPEndPoint source) /// /// /// - internal static byte[] CreateFileHeader(DateTime timeBase, System.Net.IPEndPoint source) + internal static Common.MemorySegment CreateFileHeader(DateTime timeBase, System.Net.IPEndPoint source) { //All files must indicate a source address and port if (source == null) throw new ArgumentNullException("source"); @@ -1036,7 +1044,7 @@ internal static byte[] CreateFileHeader(DateTime timeBase, System.Net.IPEndPoint Common.Binary.Write16(result, 0, Common.Binary.IsLittleEndian, (short)source.Port); - return result; + return new(result); } } } diff --git a/RtpTools/RtpSend.cs b/RtpTools/RtpSend.cs index a6e640db..c5775b50 100644 --- a/RtpTools/RtpSend.cs +++ b/RtpTools/RtpSend.cs @@ -714,7 +714,7 @@ public static string ToTextualConvention(FileFormat format, Rtp.RtpPacket packet /// The format found while parsing the description. /// Will only contain data if format was unknown, and contains the data encountered in the stream while attempting to parse. /// The item which was created as a result of reading from the stream. - internal static RtpToolEntry ParseText(System.IO.BinaryReader reader, System.Net.IPEndPoint source, ref FileFormat format, out byte[] unexpected) + internal static RtpToolEntry ParseText(System.IO.BinaryReader reader, System.Net.IPEndPoint source, ref FileFormat format, out Common.MemorySegment unexpected) { unexpected = null; @@ -754,9 +754,6 @@ internal static RtpToolEntry ParseText(System.IO.BinaryReader reader, System.Net //Indicates if in a comment bool parsingCommentOrWhitespace = false; - //Contains the data read from the stream until '\n' occurs. - byte[] lineBytes; - //Indicates if the parsing of the entry is complete bool doneParsing = false, formatUnknown = format == FileFormat.Unknown, needAnyToken = true; @@ -789,11 +786,11 @@ internal static RtpToolEntry ParseText(System.IO.BinaryReader reader, System.Net break; } - //Read until '\n' occurs - Common.Extensions.Stream.StreamExtensions.ReadLineFeed(reader.BaseStream, out lineBytes); + //Read until '\n' occurs, //Contains the data read from the stream until '\n' occurs. + Common.Extensions.Stream.StreamExtensions.ReadLineFeed(reader.BaseStream, out var lineBytes); //Keep track of the amount of bytes read - lineBytesLength = lineBytes.Length; + lineBytesLength = lineBytes.Count; //If nothing was read return if (lineBytesLength == 0) return null; @@ -821,7 +818,7 @@ internal static RtpToolEntry ParseText(System.IO.BinaryReader reader, System.Net //Search for '=' - tokenIndex = Array.IndexOf(lineBytes, Common.ASCII.EqualsSign); + tokenIndex = Array.IndexOf(lineBytes.Array, Common.ASCII.EqualsSign); //If not found then this must be a Short entry. if (tokenIndex == -1) @@ -856,7 +853,7 @@ internal static RtpToolEntry ParseText(System.IO.BinaryReader reader, System.Net { //Extract all tokens from the lineBytes - string[] tokens = Encoding.ASCII.GetString(lineBytes).Split((char)Common.ASCII.Space, (char)Common.ASCII.EqualsSign, '(', ')'); + string[] tokens = Encoding.ASCII.GetString(lineBytes.Array, lineBytes.Offset, lineBytesLength).Split((char)Common.ASCII.Space, (char)Common.ASCII.EqualsSign, '(', ')'); //Any hex data will need a length, and we start at offset 0. int dataLen = 0, tokenOffset = 0; diff --git a/RtpTools/RtpToolEntry.cs b/RtpTools/RtpToolEntry.cs index 8fd6c2b1..d0fa573f 100644 --- a/RtpTools/RtpToolEntry.cs +++ b/RtpTools/RtpToolEntry.cs @@ -125,7 +125,7 @@ public static IEnumerable CreatePacketHeader(Common.IPacket packet, int of public const int sizeOf_RD_hdr_t = 16, //Columbia RtpTools don't include this for every packet, only the first. sizeOf_RD_packet_T = 8; - internal static RtpToolEntry CreateShortEntry(DateTime timeBase, System.Net.IPEndPoint source, byte[] memory, int offset = 0, long? fileOffset = null) + internal static RtpToolEntry CreateShortEntry(DateTime timeBase, System.Net.IPEndPoint source, Common.MemorySegment memory, int offset = 0, long? fileOffset = null) { /* Only the header can be restored / represented and indicates a VAT or RTP Packet RTP or vat data in tabular form: [-]time ts [seq], where a - indicates a set marker bit. The sequence number seq is only used for RTP packets. @@ -139,7 +139,7 @@ 844525727.922518 954850177 30670 if (source == null) source = new System.Net.IPEndPoint(0, 0); //Tokenize the entry - string [] entryParts = Encoding.ASCII.GetString(memory, 0, memory.Length - 1).Split((char)Common.ASCII.Space); + string [] entryParts = Encoding.ASCII.GetString(memory.Array, memory.Offset, memory.Count - 1).Split((char)Common.ASCII.Space); int partCount = entryParts.Length; diff --git a/Rtsp/RtspClient.cs b/Rtsp/RtspClient.cs index 8e4390c2..3c14d151 100644 --- a/Rtsp/RtspClient.cs +++ b/Rtsp/RtspClient.cs @@ -5683,7 +5683,7 @@ requested. The server MAY truncate this packet size to the closest //Care should be taken that the SDP is not directing us to connect to some unknown resource.... //Just incase the source datum was not given, only for unicast connections. - if (false.Equals(multicast) && sourceIp.Equals(IPAddress.Any) || sourceIp.Equals(IPAddress.IPv6Any)) sourceIp = ((IPEndPoint)m_RtspSocket.RemoteEndPoint).Address; + if ((false.Equals(multicast) && sourceIp.Equals(IPAddress.Any) || sourceIp.Equals(IPAddress.IPv6Any)) && m_RtspSocket.RemoteEndPoint is IPEndPoint rep) sourceIp = rep.Address; //If multicast was given check the destination address and if was not specified use the sourceIp. if (multicast && (destinationIp.Equals(IPAddress.Any) || destinationIp.Equals(IPAddress.IPv6Any))) destinationIp = sourceIp; diff --git a/RtspServer/Classes/SourceMedia.cs b/RtspServer/Classes/SourceMedia.cs index 113cf8a7..2492ca78 100644 --- a/RtspServer/Classes/SourceMedia.cs +++ b/RtspServer/Classes/SourceMedia.cs @@ -73,7 +73,7 @@ public enum StreamState internal string m_Name; internal Uri m_Source; internal NetworkCredential m_SourceCred; - internal List m_Aliases = new(); + internal HashSet m_Aliases = new (); //internal bool m_Child = false; public virtual Sdp.SessionDescription SessionDescription { get; internal protected set; } @@ -240,7 +240,7 @@ internal void OnFrameDecoded(System.Drawing.Image decoded) { if (DecodeFrames && decoded != null) { - FrameDecoded?.Invoke(this, decoded); + FrameDecoded.Invoke(this, decoded); } } @@ -248,7 +248,7 @@ internal void OnFrameDecoded(byte[] decoded) { if (DecodeFrames && decoded != null) { - DataDecoded?.Invoke(this, decoded); + DataDecoded.Invoke(this, decoded); } } diff --git a/RtspServer/ClientSession.cs b/RtspServer/ClientSession.cs index c9e7181a..709b383c 100644 --- a/RtspServer/ClientSession.cs +++ b/RtspServer/ClientSession.cs @@ -375,34 +375,41 @@ public ClientSession(RtspServer server, Socket rtspSocket, Common.MemorySegment [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void StartReceive() { - //while the socket cannot read in m_SocketPollMicroseconds or less - while (false.Equals(IsDisposed) && - false.Equals(IsDisconnected) && - HasRuningServer && - false.Equals(m_RtspSocket.Poll(m_SocketPollMicroseconds, SelectMode.SelectRead))) + try { - //Wait for the last recieve to complete - //If session is disposed or the socket is shared then jump - if (SharesSocket) goto NotDisconnected; - } + //while the socket cannot read in m_SocketPollMicroseconds or less + while (false.Equals(IsDisposed) && + false.Equals(IsDisconnected) && + HasRuningServer && + false.Equals(m_RtspSocket.Poll(m_SocketPollMicroseconds, SelectMode.SelectRead))) + { + //Wait for the last recieve to complete + //If session is disposed or the socket is shared then jump + if (SharesSocket) goto NotDisconnected; + } - //Ensure not disposed or marked disconnected - if (IsDisposed) return; + //Ensure not disposed or marked disconnected + if (IsDisposed) return; - if(SharesSocket) goto NotDisconnected; + if (SharesSocket) goto NotDisconnected; - if (object.ReferenceEquals(m_RtspSocket, null).Equals(false) && HasRuningServer) - { - if (LastRecieve == null) + if (object.ReferenceEquals(m_RtspSocket, null).Equals(false) && HasRuningServer) { - LastRecieve = new SocketAsyncEventArgs(); - LastRecieve.SetBuffer(m_Buffer.Array, m_Buffer.Offset, m_Buffer.Count); - LastRecieve.UserToken = this; - LastRecieve.Completed += m_Server.ProcessReceive; + if (LastRecieve == null) + { + LastRecieve = new SocketAsyncEventArgs(); + LastRecieve.SetBuffer(m_Buffer.Array, m_Buffer.Offset, m_Buffer.Count); + LastRecieve.UserToken = this; + LastRecieve.Completed += m_Server.ProcessReceive; + } + LastRecieve.RemoteEndPoint = RemoteEndPoint; + if (!m_RtspSocket.ReceiveAsync(LastRecieve)) + ThreadPool.QueueUserWorkItem((o) => m_Server.ProcessReceive(m_Server, LastRecieve)); } - LastRecieve.RemoteEndPoint = RemoteEndPoint; - if (!m_RtspSocket.ReceiveAsync(LastRecieve)) - ThreadPool.QueueUserWorkItem((o) => m_Server.ProcessReceive(m_Server, LastRecieve)); + } + catch (InvalidOperationException) + { + goto NotDisconnected; } NotDisconnected: diff --git a/RtspServer/MediaTypes/RtpAudioSink.cs b/RtspServer/MediaTypes/RtpAudioSink.cs index d760bd72..09c20c77 100644 --- a/RtspServer/MediaTypes/RtpAudioSink.cs +++ b/RtspServer/MediaTypes/RtpAudioSink.cs @@ -285,9 +285,13 @@ public override void Stop() /// public bool Packetize(byte[] data, int offset, int length) { + if (RtpClient == null) return false; + //Get the context for the payloadType so we can increment the timestamps and sequence numbers. var transportContext = RtpClient.GetContextBySourceId(SourceId); + if (transportContext == null) return false; + transportContext.RtpTimestamp += ClockRate; //Create a frame diff --git a/RtspServer/RtspServer.cs b/RtspServer/RtspServer.cs index 154407c5..cfc633e6 100644 --- a/RtspServer/RtspServer.cs +++ b/RtspServer/RtspServer.cs @@ -246,7 +246,7 @@ internal static void ConfigureRtspServerSocket(Socket socket, out int interFrame /// /// The dictionary containing all the clients the server has sessions assocaited with /// - readonly Dictionary m_Sessions = new Dictionary(short.MaxValue); + readonly ConcurrentDictionary m_Sessions = new(); readonly ManualResetEventSlim m_AcceptSignal = new ManualResetEventSlim(false, DefaultReceiveTimeout); @@ -280,7 +280,7 @@ internal IEnumerable Clients [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] get { - return m_Sessions.Values.ToList(); + return m_Sessions.Values; } } @@ -471,7 +471,7 @@ public IEnumerable MediaStreams [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] get { - return m_MediaStreams.Values.ToList(); + return m_MediaStreams.Values; } } @@ -847,32 +847,32 @@ public void DisableUnreliableTransport() #region Session Collection [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - internal bool TryAddSession(ClientSession session) - { - Exception any = null; - - try - { - Common.ILoggingExtensions.Log(Logger, "Adding Client: " + session.Id); - - if (Media.Common.Extensions.Generic.Dictionary.DictionaryExtensions.TryAdd(m_Sessions, session.Id, session, out any)) - { - session.m_Contained = this; - } - - return Object.ReferenceEquals(session.m_Contained, this); - } - catch(Exception ex) - { - any = ex; - - return false; - } - finally - { - Common.ILoggingExtensions.LogException(Logger, any); - } - } + internal bool TryAddSession(ClientSession session) => m_Sessions.TryAdd(session.Id, session); + //{ + // Exception any = null; + + // try + // { + // Common.ILoggingExtensions.Log(Logger, "Adding Client: " + session.Id); + + // if (Media.Common.Extensions.Generic.Dictionary.DictionaryExtensions.TryAdd(m_Sessions, session.Id, session, out any)) + // { + // session.m_Contained = this; + // } + + // return Object.ReferenceEquals(session.m_Contained, this); + // } + // catch(Exception ex) + // { + // any = ex; + + // return false; + // } + // finally + // { + // Common.ILoggingExtensions.LogException(Logger, any); + // } + //} /// /// Disposes and tries to remove the session from the Clients Collection. @@ -881,45 +881,47 @@ internal bool TryAddSession(ClientSession session) /// True if the session was disposed internal bool TryDisposeAndRemoveSession(ClientSession session) { - if (session == null) return false; - - Exception any = null; - try - { - //If the session was not disposed - if (false.Equals(Common.IDisposedExtensions.IsNullOrDisposed(session))) - { - //indicate the session is disposing - Common.ILoggingExtensions.Log(Logger, "Disposing Client: " + session.Id + " @ " + DateTime.UtcNow); - - //Dispose the session - session.Dispose(); - } - - //If the client was already removed indicate this in the logs - if (false.Equals(Media.Common.Extensions.Generic.Dictionary.DictionaryExtensions.TryRemove(m_Sessions, session.Id, out any))) Common.ILoggingExtensions.Log(Logger, "Client Already Removed(" + session.Id + ")"); - - //Indicate success - return true; - } - catch (Exception ex) - { - any = ex; - - //Indicate if a failure occured - return Common.IDisposedExtensions.IsNullOrDisposed(session); - } - finally - { - Common.ILoggingExtensions.LogException(Logger, any); - } + var result = m_Sessions.TryRemove(session.Id, out var localSession); + if (result) localSession.Dispose(); + return result; } + //{ + // if (session == null) return false; + + // Exception any = null; + // try + // { + // //If the session was not disposed + // if (false.Equals(Common.IDisposedExtensions.IsNullOrDisposed(session))) + // { + // //indicate the session is disposing + // Common.ILoggingExtensions.Log(Logger, "Disposing Client: " + session.Id + " @ " + DateTime.UtcNow); + + // //Dispose the session + // session.Dispose(); + // } + + // //If the client was already removed indicate this in the logs + // if (false.Equals(Media.Common.Extensions.Generic.Dictionary.DictionaryExtensions.TryRemove(m_Sessions, session.Id, out any))) Common.ILoggingExtensions.Log(Logger, "Client Already Removed(" + session.Id + ")"); + + // //Indicate success + // return true; + // } + // catch (Exception ex) + // { + // any = ex; + + // //Indicate if a failure occured + // return Common.IDisposedExtensions.IsNullOrDisposed(session); + // } + // finally + // { + // Common.ILoggingExtensions.LogException(Logger, any); + // } + //} [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - internal bool ContainsSession(ClientSession session) - { - return m_Sessions.ContainsKey(session.Id); - } + internal bool ContainsSession(ClientSession session) => m_Sessions.ContainsKey(session.Id); [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] internal ClientSession GetSession(Guid id) @@ -1448,7 +1450,7 @@ internal virtual void MaintainServer(object state = null) if (IsRunning && m_Maintainer != null) m_Maintainer.Change(TimeSpan.FromTicks(RtspClientInactivityTimeout.Ticks >> 2), Media.Common.Extensions.TimeSpan.TimeSpanExtensions.InfiniteTimeSpan); - }), Common.Extensions.Thread.ThreadExtensions.MinimumStackSize) + }))//, Common.Extensions.Thread.ThreadExtensions.MinimumStackSize) { Priority = m_ServerThread.Priority, Name = "Maintenance-" + m_ServerThread.Name, @@ -3578,7 +3580,7 @@ public override void Dispose() Stop(m_LeaveOpen); - foreach (var stream in m_MediaStreams.ToList()) + foreach (var stream in m_MediaStreams) { stream.Value.Dispose();