Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,22 @@ csharp_preserve_single_line_statements = true
csharp_preserve_single_line_blocks = true

# Don't allow single line if/else blocks without braces.
csharp_prefer_braces = true:error
csharp_prefer_braces = true:error

# IDE0007: Use implicit type
dotnet_diagnostic.IDE0007.severity = suggestion

# IDE0019: Use pattern matching
dotnet_diagnostic.IDE0019.severity = suggestion

# IDE0030: Use coalesce expression
dotnet_diagnostic.IDE0030.severity = suggestion

# IDE0031: Use null propagation
dotnet_diagnostic.IDE0031.severity = suggestion

# IDE0078: Use pattern matching
dotnet_diagnostic.IDE0078.severity = suggestion

# IDE0083: Use pattern matching
dotnet_diagnostic.IDE0083.severity = suggestion
4 changes: 3 additions & 1 deletion src/SIPSorcery.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@
<TargetFrameworks>netstandard2.0;netstandard2.1;netcoreapp3.1;net462;net5.0;net6.0;net8.0</TargetFrameworks>
<LangVersion>12.0</LangVersion>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
<NoWarn>$(NoWarn);SYSLIB0050</NoWarn>
<NoWarn>$(NoWarn);SYSLIB0050;CS1591;CS1573;CS1587</NoWarn>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
<WarningsNotAsErrors>$(WarningsNotAsErrors);CS0809;CS0618;CS8632</WarningsNotAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<!-- Disable warning for missing XML doc comments. -->
<NoWarn>$(NoWarn);CS1591;CS1573;CS1587</NoWarn>
Expand Down Expand Up @@ -93,6 +94,7 @@
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<ContinuousIntegrationBuild Condition="'$(CI)' == 'true'">true</ContinuousIntegrationBuild>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

</Project>
12 changes: 5 additions & 7 deletions src/app/Media/Codecs/AudioEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
using System.Collections.Generic;
using System.Linq;
using SIPSorceryMedia.Abstractions;
using SIPSorcery.Sys;
using Concentus.Enums;

namespace SIPSorcery.Media
Expand Down Expand Up @@ -121,16 +122,13 @@ public byte[] EncodeAudio(short[] pcm, AudioFormat format)
}
else if (format.Codec == AudioCodecsEnum.L16)
{
// When netstandard2.1 can be used.
//return MemoryMarshal.Cast<short, byte>(pcm)

// Put on the wire in network byte order (big endian).
return pcm.SelectMany(x => new byte[] { (byte)(x >> 8), (byte)(x) }).ToArray();
return MemoryOperations.ToBigEndianBytes(pcm);
}
else if (format.Codec == AudioCodecsEnum.PCM_S16LE)
{
// Put on the wire as little endian.
return pcm.SelectMany(x => new byte[] { (byte)(x), (byte)(x >> 8) }).ToArray();
return MemoryOperations.ToLittleEndianBytes(pcm);
}
else if (format.Codec == AudioCodecsEnum.OPUS)
{
Expand All @@ -148,7 +146,7 @@ public byte[] EncodeAudio(short[] pcm, AudioFormat format)

byte[] encodedSample = new byte[pcm.Length];
int encodedLength = _opusEncoder.Encode(pcmFloat, pcmFloat.Length / format.ChannelCount, encodedSample, encodedSample.Length);
return encodedSample.Take(encodedLength).ToArray();
return encodedSample.AsSpan(0, encodedLength).ToArray();
}
else
{
Expand All @@ -174,7 +172,7 @@ public short[] DecodeAudio(byte[] encodedSample, AudioFormat format)
short[] decodedPcm = new short[encodedSample.Length * 2];
int decodedSampleCount = _g722Decoder.Decode(_g722DecoderState, decodedPcm, encodedSample, encodedSample.Length);

return decodedPcm.Take(decodedSampleCount).ToArray();
return decodedPcm.AsSpan(0, decodedSampleCount).ToArray();
}
if (format.Codec == AudioCodecsEnum.G729)
{
Expand Down
2 changes: 1 addition & 1 deletion src/app/Media/Codecs/G729Encoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class G729Encoder : Ld8k
* Initialization of the coder.
*/

private byte[] _leftover = new byte[0];
private byte[] _leftover = Array.Empty<byte>();

/**
* Init the Ld8k Coder
Expand Down
2 changes: 1 addition & 1 deletion src/core/SIP/Channels/SIPClientWebSocketChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ private void MonitorReceiveTasks()
if (receiveTask.IsCompleted)
{
logger.LogDebug("Client web socket connection to {ServerUri} received {BytesReceived} bytes.", conn.ServerUri, receiveTask.Result.Count);
//SIPMessageReceived(this, conn.LocalEndPoint, conn.RemoteEndPoint, conn.ReceiveBuffer.Take(receiveTask.Result.Count).ToArray()).Wait();
//SIPMessageReceived(this, conn.LocalEndPoint, conn.RemoteEndPoint, conn.ReceiveBuffer.AsSpan(0, receiveTask.Result.Count).ToArray()).Wait();
ExtractSIPMessages(this, conn, conn.ReceiveBuffer, receiveTask.Result.Count);
conn.ReceiveTask = conn.Client.ReceiveAsync(conn.ReceiveBuffer, m_cts.Token);
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/SIP/Channels/SIPWebSocketChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ protected override void OnError(ErrorEventArgs e)

public void Send(byte[] buffer, int offset, int length)
{
base.Send(buffer.Skip(offset).Take(length).ToArray());
base.Send(buffer.AsSpan(offset, length).ToArray());
}
}

Expand Down
9 changes: 7 additions & 2 deletions src/net/DtlsSrtp/DtlsSrtpTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using Microsoft.Extensions.Logging;
using Org.BouncyCastle.Tls;
using SIPSorcery.Sys;
Expand Down Expand Up @@ -482,11 +483,15 @@ public int GetSendLimit()
return this._sendLimit;
}

public void WriteToRecvStream(byte[] buf)
[Obsolete("Use WriteToRecvStream(ReadOnlySpan<byte>) instead.", false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void WriteToRecvStream(byte[] buf) => WriteToRecvStream(buf.AsSpan());

public void WriteToRecvStream(ReadOnlySpan<byte> buf)
{
if (!_isClosed)
{
_chunks.Add(buf);
_chunks.Add(buf.ToArray());
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/net/HEP/HepPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ public static byte[] GetBytes(SIPEndPoint srcEndPoint, SIPEndPoint dstEndPoint,
Buffer.BlockCopy(BitConverter.GetBytes((ushort)offset), 0, packetBuffer, 4, 2);
}

return packetBuffer.Take(offset).ToArray();
return packetBuffer.AsSpan(0, offset).ToArray();
}
}
}
12 changes: 6 additions & 6 deletions src/net/ICE/RtpIceChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,7 @@ public void AddRemoteCandidate(RTCIceCandidate candidate)
{
OnIceCandidateError?.Invoke(candidate, $"Remote ICE candidate had an invalid port {candidate.port}.");
}
else if(IPAddress.TryParse(candidate.address, out var addrIPv6) &&
else if (IPAddress.TryParse(candidate.address, out var addrIPv6) &&
addrIPv6.AddressFamily == AddressFamily.InterNetworkV6 &&
!Socket.OSSupportsIPv6 &&
NetServices.HasActiveIPv6Address())
Expand Down Expand Up @@ -1123,7 +1123,7 @@ private void CheckIceServers(Object state)
{
if (_activeIceServer == null || _activeIceServer.Error != SocketError.Success)
{
if (_iceServerResolver.IceServers.Count(x => x.Value.Error == SocketError.Success) == 0)
if (!_iceServerResolver.IceServers.Any(x => x.Value.Error == SocketError.Success))
{
logger.LogDebug("RTP ICE Channel all ICE server connection checks failed, stopping ICE servers timer.");
_processIceServersTimer.Dispose();
Expand All @@ -1136,7 +1136,7 @@ private void CheckIceServers(Object state)
.OrderByDescending(x => x.Value._uri.Scheme) // TURN serves take priority.
.FirstOrDefault();

if (!entry.Equals(default(KeyValuePair<STUNUri, IceServer>)))
if (entry.Key is not null && entry.Value is not null)
{
_activeIceServer = entry.Value;
}
Expand Down Expand Up @@ -2168,7 +2168,7 @@ private ChecklistEntry GetChecklistEntryForStunResponse(byte[] transactionID)
/// <returns>If found a matching state object or null if not.</returns>
private IceServer GetIceServerForTransactionID(byte[] transactionID)
{
if (_iceServerResolver.IceServers.Count() == 0)
if (_iceServerResolver.IceServers.Count == 0)
{
return null;
}
Expand All @@ -2180,7 +2180,7 @@ private IceServer GetIceServerForTransactionID(byte[] transactionID)
.Where(x => x.Value.IsTransactionIDMatch(txID))
.SingleOrDefault();

if (!entry.Equals(default(KeyValuePair<STUNUri, IceServer>)))
if (entry.Key is not null && entry.Value is not null)
{
return entry.Value;
}
Expand Down Expand Up @@ -2576,7 +2576,7 @@ private async Task<IPAddress[]> ResolveMdnsName(RTCIceCandidate candidate)
{
if (MdnsResolve != null)
{
logger.LogWarning("RTP ICE channel has both "+ nameof(MdnsGetAddresses) + " and " + nameof(MdnsGetAddresses) + " set. Only " + nameof(MdnsGetAddresses) + " will be used.");
logger.LogWarning("RTP ICE channel has both " + nameof(MdnsGetAddresses) + " and " + nameof(MdnsGetAddresses) + " set. Only " + nameof(MdnsGetAddresses) + " will be used.");
}
return await MdnsGetAddresses(candidate.address).ConfigureAwait(false);
}
Expand Down
73 changes: 45 additions & 28 deletions src/net/RTCP/RTCPBye.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Filename: RTCPBye.cs
//
// Description: RTCP Goodbye packet as defined in RFC3550.
Expand Down Expand Up @@ -27,6 +27,9 @@
//-----------------------------------------------------------------------------

using System;
using System.Buffers.Binary;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using SIPSorcery.Sys;

Expand Down Expand Up @@ -73,7 +76,17 @@ public RTCPBye(uint ssrc, string reason)
/// Create a new RTCP Goodbye packet from a serialised byte array.
/// </summary>
/// <param name="packet">The byte array holding the Goodbye packet.</param>
public RTCPBye(byte[] packet)
[Obsolete("Use RTCPBye(ReadOnlySpan<byte> packet) instead.", false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public RTCPBye(byte[] packet) : this(new ReadOnlySpan<byte>(packet))
{
}

/// <summary>
/// Create a new RTCP Goodbye packet from a serialised byte array.
/// </summary>
/// <param name="packet">The byte array holding the Goodbye packet.</param>
public RTCPBye(ReadOnlySpan<byte> packet)
{
if (packet.Length < MIN_PACKET_SIZE)
{
Expand All @@ -82,56 +95,60 @@ public RTCPBye(byte[] packet)

Header = new RTCPHeader(packet);

if (BitConverter.IsLittleEndian)
{
SSRC = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 4));
}
else
{
SSRC = BitConverter.ToUInt32(packet, 4);
}
SSRC = BinaryPrimitives.ReadUInt32BigEndian(packet.Slice(4));

if (packet.Length > MIN_PACKET_SIZE)
{
int reasonLength = packet[8];

if (packet.Length - MIN_PACKET_SIZE - 1 >= reasonLength)
{
Reason = Encoding.UTF8.GetString(packet, 9, reasonLength);
Reason = Encoding.UTF8.GetString(packet.Slice(9, reasonLength));
}
}
}

public int GetPacketSize() => RTCPHeader.HEADER_BYTES_LENGTH + GetPaddedLength(((Reason is not null) ? Encoding.UTF8.GetByteCount(Reason) : 0));

/// <summary>
/// Gets the raw bytes for the Goodbye packet.
/// </summary>
/// <returns>A byte array.</returns>
public byte[] GetBytes()
{
byte[] reasonBytes = (Reason != null) ? Encoding.UTF8.GetBytes(Reason) : null;
int reasonLength = (reasonBytes != null) ? reasonBytes.Length : 0;
byte[] buffer = new byte[RTCPHeader.HEADER_BYTES_LENGTH + GetPaddedLength(reasonLength)];
Header.SetLength((ushort)(buffer.Length / 4 - 1));
var buffer = new byte[GetPacketSize()];

Buffer.BlockCopy(Header.GetBytes(), 0, buffer, 0, RTCPHeader.HEADER_BYTES_LENGTH);
int payloadIndex = RTCPHeader.HEADER_BYTES_LENGTH;
WriteBytesCore(buffer);

if (BitConverter.IsLittleEndian)
{
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SSRC)), 0, buffer, payloadIndex, 4);
}
else
return buffer;
}

public int WriteBytes(Span<byte> buffer)
{
var size = GetPacketSize();

if (buffer.Length < size)
{
Buffer.BlockCopy(BitConverter.GetBytes(SSRC), 0, buffer, payloadIndex, 4);
throw new ArgumentOutOfRangeException($"The buffer should have at least {size} bytes and had only {buffer.Length}.");
}

if (reasonLength > 0)
WriteBytesCore(buffer.Slice(0, size));

return size;
}

private void WriteBytesCore(Span<byte> buffer)
{
Header.SetLength((ushort)(buffer.Length / 4 - 1));
_ = Header.WriteBytes(buffer);

BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(RTCPHeader.HEADER_BYTES_LENGTH), SSRC);

if (Reason is not null)
{
buffer[payloadIndex + 4] = (byte)reasonLength;
Buffer.BlockCopy(reasonBytes, 0, buffer, payloadIndex + 5, reasonBytes.Length);
buffer[RTCPHeader.HEADER_BYTES_LENGTH + 4] =
(byte)Encoding.UTF8.GetBytes(Reason.AsSpan(), buffer.Slice(RTCPHeader.HEADER_BYTES_LENGTH + 5));
}

return buffer;
}

/// <summary>
Expand Down
Loading