Skip to content

Commit 7377f09

Browse files
authored
Improve message serialization (#16)
1 parent 51ba553 commit 7377f09

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

lib/ex_rtmp/message.ex

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ defmodule ExRTMP.Message do
142142
* `:chunk_size` - The size of each chunk (default: 128)
143143
* `:chunk_stream_id` - The chunk stream id to use (default: 2)
144144
"""
145-
@spec serialize(t(), keyword()) :: iodata()
145+
@spec serialize(t(), keyword()) :: binary()
146146
def serialize(message, opts \\ []) do
147147
chunk_size = Keyword.get(opts, :chunk_size, 128)
148148
chunk_stream_id = Keyword.get(opts, :chunk_stream_id, 2)
@@ -166,14 +166,20 @@ defmodule ExRTMP.Message do
166166
}
167167

168168
2..entries//1
169-
|> Stream.map(fn idx ->
169+
|> Enum.map(fn idx ->
170170
offset = (idx - 1) * chunk_size
171171
size = min(byte_size(payload) - offset, chunk_size)
172172
binary_part(payload, offset, size)
173173
end)
174-
|> Stream.map(&%Chunk{payload: &1, stream_id: chunk_stream_id, fmt: 3})
175-
|> Enum.map(&Chunk.serialize/1)
176-
|> then(&[Chunk.serialize(first_chunk) | &1])
174+
|> chunks_to_binary(chunk_stream_id, Chunk.serialize(first_chunk))
175+
end
176+
177+
defp chunks_to_binary([], _chunk_stream_id, acc), do: acc
178+
179+
# we always use stream id smaller than 63 since we only allow
180+
# one stream per client/session
181+
defp chunks_to_binary([chunk | rest], stream_id, acc) do
182+
chunks_to_binary(rest, stream_id, <<acc::binary, 3::2, stream_id::6, chunk::binary>>)
177183
end
178184

179185
defp parse_payload(%__MODULE__{type: 1, payload: payload} = msg) do

0 commit comments

Comments
 (0)