-
Notifications
You must be signed in to change notification settings - Fork 1
/
webrtcmessageassembler.go
64 lines (50 loc) · 1.04 KB
/
webrtcmessageassembler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package wamp_webrtc_go
import (
"bytes"
"sync"
)
type WebRTCMessageAssembler struct {
buffer *bytes.Buffer
sync.Mutex
}
func NewWebRTCMessageAssembler() *WebRTCMessageAssembler {
return &WebRTCMessageAssembler{
buffer: bytes.NewBuffer(nil),
}
}
func (m *WebRTCMessageAssembler) ChunkMessage(message []byte) chan []byte {
m.Lock()
defer m.Unlock()
chunkSize := 16*1024 - 1
totalChunks := (len(message) + chunkSize - 1) / chunkSize
chunks := make(chan []byte)
go func() {
for i := 0; i < totalChunks; i++ {
start := i * chunkSize
end := start + chunkSize
if i == totalChunks-1 {
end = len(message)
}
chunk := message[start:end]
var isFinal byte = 0
if i == totalChunks-1 {
isFinal = 1
}
chunks <- append([]byte{isFinal}, chunk...)
}
close(chunks)
}()
return chunks
}
func (m *WebRTCMessageAssembler) Feed(data []byte) []byte {
m.Lock()
defer m.Unlock()
m.buffer.Write(data[1:])
isFinal := data[0]
if isFinal == 1 {
out := m.buffer.Bytes()
m.buffer.Reset()
return out
}
return nil
}