-
Notifications
You must be signed in to change notification settings - Fork 9
/
clienttracksimulcast.go
442 lines (360 loc) · 12 KB
/
clienttracksimulcast.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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package sfu
import (
"context"
"sync"
"sync/atomic"
"github.com/inlivedev/sfu/pkg/packetmap"
"github.com/pion/rtp"
"github.com/pion/webrtc/v4"
)
type simulcastClientTrack struct {
id string
streamid string
mu sync.RWMutex
client *Client
context context.Context
kind webrtc.RTPCodecType
mimeType string
localTrack *webrtc.TrackLocalStaticRTP
remoteTrack *SimulcastTrack
baseTrack *baseTrack
lastBlankSequenceNumber *atomic.Uint32
sequenceNumber *atomic.Uint32
lastQuality *atomic.Uint32
paddingTS *atomic.Uint32
maxQuality *atomic.Uint32
lastTimestamp *atomic.Uint32
isScreen *atomic.Bool
isEnded *atomic.Bool
packetmapHigh *packetmap.Map
packetmapMid *packetmap.Map
packetmapLow *packetmap.Map
onTrackEndedCallbacks []func()
}
func newSimulcastClientTrack(c *Client, t *SimulcastTrack) *simulcastClientTrack {
track, newTrackErr := webrtc.NewTrackLocalStaticRTP(t.base.codec.RTPCodecCapability, t.base.id, t.base.streamid)
if newTrackErr != nil {
panic(newTrackErr)
}
isScreen := &atomic.Bool{}
isScreen.Store(t.IsScreen())
lastQuality := &atomic.Uint32{}
sequenceNumber := &atomic.Uint32{}
lastTimestamp := &atomic.Uint32{}
ctx, cancel := context.WithCancel(t.context)
ct := &simulcastClientTrack{
mu: sync.RWMutex{},
id: track.ID(),
streamid: track.StreamID(),
context: ctx,
kind: track.Kind(),
mimeType: track.Codec().MimeType,
client: c,
localTrack: track,
remoteTrack: t,
baseTrack: t.base,
sequenceNumber: sequenceNumber,
lastQuality: lastQuality,
paddingTS: &atomic.Uint32{},
maxQuality: &atomic.Uint32{},
lastBlankSequenceNumber: &atomic.Uint32{},
lastTimestamp: lastTimestamp,
isScreen: isScreen,
isEnded: &atomic.Bool{},
onTrackEndedCallbacks: make([]func(), 0),
packetmapHigh: &packetmap.Map{},
packetmapMid: &packetmap.Map{},
packetmapLow: &packetmap.Map{},
}
ct.SetMaxQuality(QualityHigh)
ct.remoteTrack.sendPLI()
t.OnEnded(func() {
ct.onEnded()
cancel()
})
return ct
}
func (t *simulcastClientTrack) Client() *Client {
t.mu.RLock()
defer t.mu.RUnlock()
return t.client
}
func (t *simulcastClientTrack) Context() context.Context {
return t.context
}
func (t *simulcastClientTrack) isFirstKeyframePacket(p *rtp.Packet) bool {
isKeyframe := IsKeyframe(t.mimeType, p)
return isKeyframe && t.lastTimestamp.Load() != p.Timestamp
}
func (t *simulcastClientTrack) send(p *rtp.Packet, quality QualityLevel) {
t.lastTimestamp.Store(p.Timestamp)
t.rewritePacket(p, quality)
// t.client.log.Infof("track: ", t.id, " send packet with quality ", quality, " and sequence number ", p.SequenceNumber)
t.writeRTP(p)
}
func (t *simulcastClientTrack) writeRTP(p *rtp.Packet) {
if err := t.localTrack.WriteRTP(p); err != nil {
t.client.log.Errorf("track: error on write rtp", err)
}
}
func (t *simulcastClientTrack) push(p *rtp.Packet, quality QualityLevel) {
isKeyframe := IsKeyframe(t.mimeType, p)
currentQuality := t.LastQuality()
targetQuality := t.getQuality()
if targetQuality == QualityNone {
// TODO: figure out what to do if the target quality is none
// probably we should send a blank frame
targetQuality = QualityLow
}
if !t.client.bitrateController.Exist(t.ID()) {
// do nothing if the bitrate claim is not exist
return
}
var canSwitch bool
if isKeyframe && quality == targetQuality && currentQuality != targetQuality {
switch quality {
case QualityHigh:
canSwitch = t.packetmapHigh.Drop(p.SequenceNumber, 0)
case QualityMid:
canSwitch = t.packetmapMid.Drop(p.SequenceNumber, 0)
case QualityLow:
canSwitch = t.packetmapLow.Drop(p.SequenceNumber, 0)
}
}
var ok bool
// var newSeqNo uint16
if !canSwitch {
switch quality {
case QualityHigh:
ok, _, _ = t.packetmapHigh.Map(p.SequenceNumber, 0)
if !ok {
return
}
case QualityMid:
ok, _, _ = t.packetmapMid.Map(p.SequenceNumber, 0)
if !ok {
return
}
case QualityLow:
ok, _, _ = t.packetmapLow.Map(p.SequenceNumber, 0)
if !ok {
return
}
}
// p.SequenceNumber = newSeqNo
}
// check if it's a first packet to send
if currentQuality == QualityNone && t.sequenceNumber.Load() == 0 {
// we try to send the low quality first if the track is active and fallback to upper quality if not
if t.remoteTrack.getRemoteTrack(QualityLow) != nil && quality == QualityLow {
t.lastQuality.Store(uint32(QualityLow))
// send PLI to make sure the client will receive the first frame
t.remoteTrack.sendPLI()
} else if t.remoteTrack.getRemoteTrack(QualityMid) != nil && quality == QualityMid {
t.lastQuality.Store(uint32(QualityMid))
// send PLI to make sure the client will receive the first frame
t.remoteTrack.sendPLI()
} else if t.remoteTrack.getRemoteTrack(QualityHigh) != nil && quality == QualityHigh {
t.lastQuality.Store(uint32(QualityHigh))
// send PLI to make sure the client will receive the first frame
t.remoteTrack.sendPLI()
}
t.remoteTrack.onRemoteTrackAdded(func(remote *remoteTrack) {
t.remoteTrack.sendPLI()
})
} else if isKeyframe && canSwitch && quality == targetQuality && t.lastQuality.Load() != uint32(targetQuality) {
// change quality to target quality if it's a keyframe
t.client.log.Tracef("track: %s keyframe %v change quality from %d to %d ", t.id, isKeyframe, t.lastQuality.Load(), targetQuality)
currentQuality = targetQuality
t.lastQuality.Store(uint32(currentQuality))
} else if quality == targetQuality && !isKeyframe && t.lastQuality.Load() != uint32(targetQuality) {
// request PLI to allow us switch quality to target quality
t.client.log.Tracef("track: %s keyframe %v send keyframe and sequence number %d and can switch %v ", t.id, isKeyframe, p.SequenceNumber, canSwitch)
t.remoteTrack.sendPLI()
}
if currentQuality == quality {
t.send(p, quality)
}
}
func (t *simulcastClientTrack) GetRemoteTrack() *remoteTrack {
lastQuality := Uint32ToQualityLevel(t.lastQuality.Load())
// lastQuality := t.lastQuality
switch lastQuality {
case QualityHigh:
return t.remoteTrack.remoteTrackHigh
case QualityMid:
return t.remoteTrack.remoteTrackMid
case QualityLow:
return t.remoteTrack.remoteTrackLow
default:
if t.remoteTrack.isTrackActive(QualityHigh) {
return t.remoteTrack.remoteTrackHigh
}
if t.remoteTrack.isTrackActive(QualityMid) {
return t.remoteTrack.remoteTrackMid
}
if t.remoteTrack.isTrackActive(QualityLow) {
return t.remoteTrack.remoteTrackLow
}
}
return nil
}
func (t *simulcastClientTrack) ID() string {
return t.id
}
func (t *simulcastClientTrack) StreamID() string {
return t.streamid
}
func (t *simulcastClientTrack) Kind() webrtc.RTPCodecType {
return t.kind
}
func (t *simulcastClientTrack) LocalTrack() *webrtc.TrackLocalStaticRTP {
return t.localTrack
}
func (t *simulcastClientTrack) IsScreen() bool {
return t.isScreen.Load()
}
func (t *simulcastClientTrack) SetSourceType(sourceType TrackType) {
t.isScreen.Store(sourceType == TrackTypeScreen)
}
func (t *simulcastClientTrack) LastQuality() QualityLevel {
return Uint32ToQualityLevel(t.lastQuality.Load())
}
func (t *simulcastClientTrack) OnEnded(callback func()) {
t.mu.Lock()
defer t.mu.Unlock()
t.onTrackEndedCallbacks = append(t.onTrackEndedCallbacks, callback)
}
func (t *simulcastClientTrack) onEnded() {
if t.isEnded.Load() {
return
}
for _, callback := range t.onTrackEndedCallbacks {
callback()
}
t.isEnded.Store(true)
}
func (t *simulcastClientTrack) SetMaxQuality(quality QualityLevel) {
t.maxQuality.Store(uint32(quality))
claim := t.Client().bitrateController.GetClaim(t.ID())
if claim != nil {
if claim.Quality() > quality && quality != QualityNone {
claim.SetQuality(quality)
}
}
t.remoteTrack.sendPLI()
}
func (t *simulcastClientTrack) MaxQuality() QualityLevel {
return Uint32ToQualityLevel(t.maxQuality.Load())
}
func (t *simulcastClientTrack) IsSimulcast() bool {
return true
}
func (t *simulcastClientTrack) IsScaleable() bool {
return false
}
func (t *simulcastClientTrack) rewritePacket(p *rtp.Packet, quality QualityLevel) {
t.remoteTrack.mu.RLock()
defer t.remoteTrack.mu.RUnlock()
// make sure the timestamp and sequence number is consistent from the previous packet even it is not the same track
sequenceDelta := uint16(0)
// credit to https://github.com/k0nserv for helping me with this on Pion Slack channel
switch quality {
case QualityHigh:
p.Timestamp = t.remoteTrack.baseTS + ((p.Timestamp - t.remoteTrack.remoteTrackHighBaseTS) - t.remoteTrack.remoteTrackHighBaseTS)
sequenceDelta = t.remoteTrack.highSequence - t.remoteTrack.lastHighSequence
case QualityMid:
p.Timestamp = t.remoteTrack.baseTS + ((p.Timestamp - t.remoteTrack.remoteTrackMidBaseTS) - t.remoteTrack.remoteTrackMidBaseTS)
sequenceDelta = t.remoteTrack.midSequence - t.remoteTrack.lastMidSequence
case QualityLow:
p.Timestamp = t.remoteTrack.baseTS + ((p.Timestamp - t.remoteTrack.remoteTrackLowBaseTS) - t.remoteTrack.remoteTrackLowBaseTS)
sequenceDelta = t.remoteTrack.lowSequence - t.remoteTrack.lastLowSequence
}
t.sequenceNumber.Add(uint32(sequenceDelta))
p.SequenceNumber = uint16(t.sequenceNumber.Load())
}
func (t *simulcastClientTrack) RequestPLI() {
t.remoteTrack.sendPLI()
}
func (t *simulcastClientTrack) getQuality() QualityLevel {
track := t.remoteTrack
claim := t.Client().bitrateController.GetClaim(t.ID())
if claim == nil {
return QualityNone
}
quality := min(claim.Quality(), t.MaxQuality(), Uint32ToQualityLevel(t.client.quality.Load()))
if quality != QualityNone && !track.isTrackActive(quality) {
if quality != QualityLow && track.isTrackActive(QualityLow) {
return QualityLow
}
if quality != QualityMid && track.isTrackActive(QualityMid) {
return QualityMid
}
if quality != QualityHigh && track.isTrackActive(QualityHigh) {
return QualityHigh
}
}
return quality
}
func (t *simulcastClientTrack) ReceiveBitrate() uint32 {
total := uint32(0)
for _, quality := range []QualityLevel{QualityHigh, QualityMid, QualityLow} {
total += t.ReceiveBitrateAtQuality(quality)
}
return total
}
func (t *simulcastClientTrack) SendBitrate() uint32 {
bitrate, err := t.client.stats.GetSenderBitrate(t.ID())
if err != nil {
t.client.log.Errorf("clienttrack: error on get sender", err)
return 0
}
return bitrate
}
func (t *simulcastClientTrack) ReceiveBitrateAtQuality(quality QualityLevel) uint32 {
t.mu.RLock()
defer t.mu.RUnlock()
var remoteTrack *remoteTrack
switch quality {
case QualityHigh:
remoteTrack = t.remoteTrack.remoteTrackHigh
case QualityHighMid:
remoteTrack = t.remoteTrack.remoteTrackHigh
case QualityHighLow:
remoteTrack = t.remoteTrack.remoteTrackHigh
case QualityMid:
remoteTrack = t.remoteTrack.remoteTrackMid
case QualityMidMid:
remoteTrack = t.remoteTrack.remoteTrackMid
case QualityMidLow:
remoteTrack = t.remoteTrack.remoteTrackMid
case QualityLow:
remoteTrack = t.remoteTrack.remoteTrackLow
case QualityLowMid:
remoteTrack = t.remoteTrack.remoteTrackLow
case QualityLowLow:
remoteTrack = t.remoteTrack.remoteTrackLow
}
if remoteTrack == nil {
return 0
}
bitrate, err := t.baseTrack.client.stats.GetReceiverBitrate(remoteTrack.track.ID(), remoteTrack.track.RID())
if err != nil {
t.client.log.Errorf("clienttrack: error on get receiver", err)
return 0
}
switch quality {
case QualityHighMid, QualityMidMid, QualityLowMid:
return bitrate / 2
case QualityHighLow, QualityMidLow, QualityLowLow:
return bitrate / 4
default:
return bitrate
}
}
func (t *simulcastClientTrack) Quality() QualityLevel {
return t.getQuality()
}
func (t *simulcastClientTrack) MimeType() string {
return t.mimeType
}