async Task WritePacketAsync(RtmpPacket packet)
        {
            var header   = packet.Header;
            var streamId = header.StreamId;
            var message  = packet.Body;

            var buffer = GetMessageBytes(header, message);

            header.PacketLength = buffer.Length;

            RtmpHeader previousHeader;

            rtmpHeaders.TryGetValue(streamId, out previousHeader);

            rtmpHeaders[streamId] = header;

            WriteMessageHeaderAsync(header, previousHeader);

            var first = true;

            for (var i = 0; i < header.PacketLength; i += writeChunkSize)
            {
                if (!first)
                {
                    WriteBasicHeaderAsync(ChunkMessageHeaderType.Continuation, header.StreamId);
                }

                var bytesToWrite = i + writeChunkSize > header.PacketLength ? header.PacketLength - i : writeChunkSize;
                writer.WriteAsync(buffer, i, bytesToWrite);
                first = false;
            }

            var chunkSizeMsg = message as ChunkSize;

            if (chunkSizeMsg != null)
            {
                writeChunkSize = chunkSizeMsg.Size;
            }
            await writer.StartWriteAsync();
        }