public override void Serialize(SerializationContext context) { int bytesNeed = (int)(Messages.Count * 11 + Messages.Sum(m => m.DataLength)); var buffer = _arrayPool.Rent(bytesNeed); try { var span = buffer.AsSpan(0, bytesNeed); int consumed = 0; foreach (var message in Messages) { span[0] = (byte)message.Header.MessageType; span = span.Slice(sizeof(byte)); NetworkBitConverter.TryGetUInt24Bytes((uint)message.Header.MessageLength, span); span = span.Slice(3); NetworkBitConverter.TryGetBytes(message.Header.Timestamp, span); span = span.Slice(4); NetworkBitConverter.TryGetUInt24Bytes((uint)MessageHeader.MessageStreamId, span); span = span.Slice(3); MessageBuffer.AsSpan(consumed, (int)message.Header.MessageLength).CopyTo(span); consumed += (int)message.Header.MessageLength; span = span.Slice((int)message.Header.MessageLength); } context.WriteBuffer.WriteToBuffer(span); } finally { _arrayPool.Return(buffer); } }
public byte[] MultiplexFlv(Message data) { var dataBuffer = new ByteBuffer(); var buffer = new byte[4]; if (data.MessageHeader.MessageLength == 0) { var messageBuffer = new ByteBuffer(); var context = new Networking.Rtmp.Serialization.SerializationContext() { Amf0Writer = _amf0Writer, Amf3Writer = _amf3Writer, WriteBuffer = messageBuffer }; data.Serialize(context); var length = messageBuffer.Length; data.MessageHeader.MessageLength = (uint)length; var bodyBuffer = new byte[length]; messageBuffer.TakeOutMemory(bodyBuffer); dataBuffer.WriteToBuffer((byte)data.MessageHeader.MessageType); NetworkBitConverter.TryGetUInt24Bytes(data.MessageHeader.MessageLength, buffer); dataBuffer.WriteToBuffer(buffer.AsSpan(0, 3)); NetworkBitConverter.TryGetBytes(data.MessageHeader.Timestamp, buffer); dataBuffer.WriteToBuffer(buffer.AsSpan(1, 3)); dataBuffer.WriteToBuffer(buffer.AsSpan(0, 1)); buffer.AsSpan().Clear(); dataBuffer.WriteToBuffer(buffer.AsSpan(0, 3)); dataBuffer.WriteToBuffer(bodyBuffer); } else { dataBuffer.WriteToBuffer((byte)data.MessageHeader.MessageType); NetworkBitConverter.TryGetUInt24Bytes(data.MessageHeader.MessageLength, buffer); dataBuffer.WriteToBuffer(buffer.AsSpan(0, 3)); NetworkBitConverter.TryGetBytes(data.MessageHeader.Timestamp, buffer); dataBuffer.WriteToBuffer(buffer.AsSpan(1, 3)); dataBuffer.WriteToBuffer(buffer.AsSpan(0, 1)); buffer.AsSpan().Clear(); dataBuffer.WriteToBuffer(buffer.AsSpan(0, 3)); var context = new Networking.Rtmp.Serialization.SerializationContext() { Amf0Writer = _amf0Writer, Amf3Writer = _amf3Writer, WriteBuffer = dataBuffer }; data.Serialize(context); } NetworkBitConverter.TryGetBytes((data.MessageHeader.MessageLength + 11), buffer); dataBuffer.WriteToBuffer(buffer); var rawData = new byte[dataBuffer.Length]; dataBuffer.TakeOutMemory(rawData); return(rawData); }