-
Notifications
You must be signed in to change notification settings - Fork 36
/
receiver.go
99 lines (85 loc) · 1.6 KB
/
receiver.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package receiver
import (
"bytes"
"io"
"sort"
"sync"
"github.com/fatedier/fft/pkg/stream"
)
type Receiver struct {
fileID uint32
nextFrameID uint32
dst io.Writer
frames []*stream.Frame
framesIDMap map[uint32]struct{}
notifyCh chan struct{}
mu sync.RWMutex
}
func NewReceiver(fileID uint32, dst io.Writer) *Receiver {
return &Receiver{
fileID: fileID,
nextFrameID: 0,
dst: dst,
frames: make([]*stream.Frame, 0),
framesIDMap: make(map[uint32]struct{}),
notifyCh: make(chan struct{}, 1),
}
}
func (r *Receiver) RecvFrame(frame *stream.Frame) {
r.mu.Lock()
if frame.FrameID < r.nextFrameID {
r.mu.Unlock()
return
}
if _, ok := r.framesIDMap[frame.FrameID]; ok {
r.mu.Unlock()
return
}
r.frames = append(r.frames, frame)
r.framesIDMap[frame.FrameID] = struct{}{}
sort.Slice(r.frames, func(i, j int) bool {
return r.frames[i].FrameID < r.frames[j].FrameID
})
r.mu.Unlock()
select {
case r.notifyCh <- struct{}{}:
default:
}
}
func (r *Receiver) Run() {
for {
_, ok := <-r.notifyCh
if !ok {
return
}
buffer := bytes.NewBuffer(nil)
ii := 0
finished := false
r.mu.Lock()
for i, frame := range r.frames {
if r.nextFrameID == frame.FrameID {
ii = i + 1
delete(r.framesIDMap, frame.FrameID)
// it's last frame
if len(frame.Buf) == 0 {
finished = true
break
}
buffer.Write(frame.Buf)
r.nextFrameID++
} else {
ii = i
break
}
}
r.frames = r.frames[ii:]
r.mu.Unlock()
buf := buffer.Bytes()
if len(buf) != 0 {
r.dst.Write(buf)
}
if finished {
break
}
}
}