-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
249 lines (216 loc) · 5.22 KB
/
session.go
File metadata and controls
249 lines (216 loc) · 5.22 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package gem
import (
"bufio"
"context"
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io"
"sync"
"sync/atomic"
"time"
)
const controlOpenTimeout = 5 * time.Second
type CoreSession struct {
transport Transport
cfg Config
sessionID uint64
nextStreamID atomic.Uint32
mu sync.Mutex
videoTx map[uint32]*videoSendState
videoRx map[uint32]*videoReceiveState
videoPipeline *videoPipeline
filePipeline *filePipeline
}
func NewSession(transport Transport, cfg Config) (Session, error) {
return NewCoreSession(transport, cfg)
}
func NewCoreSession(transport Transport, cfg Config) (*CoreSession, error) {
videoPipe, err := newVideoPipeline(cfg.Video)
if err != nil {
return nil, err
}
filePipe, err := newFilePipeline(cfg.File)
if err != nil {
videoPipe.Close()
return nil, err
}
sessionID := cfg.SessionID
if sessionID == 0 {
sessionID, err = randomUint64()
if err != nil {
videoPipe.Close()
filePipe.Close()
return nil, err
}
}
s := &CoreSession{
transport: transport,
cfg: cfg,
sessionID: sessionID,
videoTx: make(map[uint32]*videoSendState),
videoRx: make(map[uint32]*videoReceiveState),
videoPipeline: videoPipe,
filePipeline: filePipe,
}
s.nextStreamID.Store(1)
return s, nil
}
func (s *CoreSession) ID() uint64 {
return s.sessionID
}
func (s *CoreSession) Transport() Transport {
return s.transport
}
func (s *CoreSession) UpdateCompressionGraph(graph []byte) error {
return s.videoPipeline.UpdateGraph(graph)
}
func (s *CoreSession) Close() error {
if err := s.videoPipeline.Close(); err != nil {
_ = s.filePipeline.Close()
_ = s.transport.Close()
return err
}
if err := s.filePipeline.Close(); err != nil {
_ = s.transport.Close()
return err
}
return s.transport.Close()
}
func (s *CoreSession) Run(ctx context.Context, hooks ReceiveHooks) error {
errCh := make(chan error, 2)
var started int
started++
go func() {
errCh <- s.runUniStreamLoop(ctx, hooks)
}()
if s.transport.SupportsDatagrams() {
started++
go func() {
errCh <- s.runDatagramLoop(ctx, hooks)
}()
}
for started > 0 {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errCh:
started--
if err != nil && !errors.Is(err, context.Canceled) {
return err
}
}
}
return nil
}
func (s *CoreSession) runUniStreamLoop(ctx context.Context, hooks ReceiveHooks) error {
for {
stream, err := s.transport.AcceptStream(ctx)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return err
}
go func(reader Stream) {
_ = s.handleUniStream(ctx, reader, hooks)
}(stream)
}
}
func (s *CoreSession) handleUniStream(ctx context.Context, stream Stream, hooks ReceiveHooks) error {
buffered := bufio.NewReader(stream)
header, err := buffered.Peek(17)
if err != nil {
return err
}
if string(header[:4]) != streamMagic {
return fmt.Errorf("unknown stream magic %q", string(header[:4]))
}
switch header[4] {
case streamClassControl:
return s.handleControlStream(buffered)
case streamClassFile:
return s.receiveFileStream(ctx, buffered, hooks)
default:
return fmt.Errorf("unsupported stream class %d", header[4])
}
}
func (s *CoreSession) handleControlStream(reader io.Reader) error {
packet, err := readControlStream(reader)
if err != nil {
return err
}
if packet.SessionID != s.sessionID {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
state, ok := s.videoTx[packet.StreamID]
if !ok {
return nil
}
switch packet.Type {
case controlTypeLossRatio:
lossRatio, err := decodeLossRatioBody(packet.Body)
if err != nil {
return err
}
state.PacketLossRatio = lossRatio
case controlTypeFECFeedback:
body, err := decodeFECFeedbackBody(packet.Body)
if err != nil {
return err
}
if body.FrameIndex <= state.LastFeedbackFrame {
return nil
}
state.Redundancy = adjustRedundancy(state.Redundancy, body, s.cfg.Video.FEC)
state.LastFeedbackFrame = body.FrameIndex
case controlTypeTelemetry:
body, err := decodeTelemetryBody(packet.Body)
if err != nil {
return err
}
if body.FrameIndex <= state.LastTelemetryFrame {
return nil
}
state.Redundancy = adjustRedundancyWithTelemetry(state.Redundancy, body, s.cfg.Video.FEC)
state.Jitter = time.Duration(body.JitterMicros) * time.Microsecond
state.LastTelemetryFrame = body.FrameIndex
case controlTypeStreamFin:
delete(s.videoRx, packet.StreamID)
}
return nil
}
func (s *CoreSession) nextLogicalStreamID() uint32 {
return s.nextStreamID.Add(1) - 1
}
func (s *CoreSession) sendControl(ctx context.Context, packet controlPacket) error {
controlCtx, cancel := context.WithTimeout(ctx, controlOpenTimeout)
defer cancel()
stream, err := s.transport.OpenStream(controlCtx, StreamMetadata{
SessionID: packet.SessionID,
StreamID: packet.StreamID,
Type: StreamTypeControl,
Reliability: ReliabilityReliable,
ContentType: "application/x-gem-control",
Connection: s.transport.ConnectionContext(),
})
if err != nil {
return err
}
defer stream.Close()
return writeControlStream(stream, packet)
}
func randomUint64() (uint64, error) {
var raw [8]byte
if _, err := rand.Read(raw[:]); err != nil {
return 0, err
}
value := binary.LittleEndian.Uint64(raw[:])
if value == 0 {
value = 1
}
return value, nil
}