forked from pion/mediadevices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
track.go
572 lines (485 loc) · 16.3 KB
/
track.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package mediadevices
import (
"errors"
"fmt"
"image"
"io"
"strings"
"sync"
"github.com/pion/interceptor"
"github.com/pion/rtcp"
"github.com/google/uuid"
"github.com/pion/mediadevices/pkg/codec"
"github.com/pion/mediadevices/pkg/driver"
"github.com/pion/mediadevices/pkg/io/audio"
"github.com/pion/mediadevices/pkg/io/video"
"github.com/pion/mediadevices/pkg/wave"
"github.com/pion/rtp"
"github.com/pion/webrtc/v3"
)
const (
rtpOutboundMTU = 1200
rtcpInboundMTU = 1500
)
var (
errInvalidDriverType = errors.New("invalid driver type")
errNotFoundPeerConnection = errors.New("failed to find given peer connection")
)
// Source is a generic representation of a media source
type Source interface {
ID() string
Close() error
}
// VideoSource is a specific type of media source that emits a series of video frames
type VideoSource interface {
video.Reader
Source
}
// AudioSource is a specific type of media source that emits a series of audio chunks
type AudioSource interface {
audio.Reader
Source
}
// Track is an interface that represent MediaStreamTrack
// Reference: https://w3c.github.io/mediacapture-main/#mediastreamtrack
type Track interface {
Source
// OnEnded registers a handler to receive an error from the media stream track.
// If the error is already occured before registering, the handler will be
// immediately called.
OnEnded(func(error))
Kind() webrtc.RTPCodecType
// StreamID is the group this track belongs too. This must be unique
StreamID() string
// RID is the RTP Stearm ID for this track. This is only used for Simulcast
RID() string
// Bind binds the current track source to the given peer connection. In Pion/webrtc v3, the bind
// call will happen automatically after the SDP negotiation. Users won't need to call this manually.
Bind(webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, error)
// Unbind is the clean up operation that should be called after Bind. Similar to Bind, unbind will
// be called automatically in Pion/webrtc v3.
Unbind(webrtc.TrackLocalContext) error
// NewRTPReader creates a new reader from the source. The reader will encode the source, and packetize
// the encoded data in RTP format with given mtu size.
//
// Note: `mtu int` will be changed to `mtu uint16` in a future update.
NewRTPReader(codecName string, ssrc uint32, mtu int) (RTPReadCloser, error)
// NewEncodedReader creates a EncodedReadCloser that reads the encoded data in codecName format
NewEncodedReader(codecName string) (EncodedReadCloser, error)
// NewEncodedReader creates a new Go standard io.ReadCloser that reads the encoded data in codecName format
NewEncodedIOReader(codecName string) (io.ReadCloser, error)
}
type baseTrack struct {
Source
err error
onErrorHandler func(error)
errMu sync.Mutex
mu sync.Mutex
endOnce sync.Once
kind MediaDeviceType
selector *CodecSelector
activePeerConnections map[string]chan<- chan<- struct{}
}
func newBaseTrack(source Source, kind MediaDeviceType, selector *CodecSelector) *baseTrack {
return &baseTrack{
Source: source,
kind: kind,
selector: selector,
activePeerConnections: make(map[string]chan<- chan<- struct{}),
}
}
// Kind returns track's kind
func (track *baseTrack) Kind() webrtc.RTPCodecType {
switch track.kind {
case VideoInput:
return webrtc.RTPCodecTypeVideo
case AudioInput:
return webrtc.RTPCodecTypeAudio
default:
panic("invalid track kind: only support VideoInput and AudioInput")
}
}
func (track *baseTrack) StreamID() string {
// TODO: StreamID should be used to group multiple tracks. Should get this information from mediastream instead.
generator, err := uuid.NewRandom()
if err != nil {
panic(err)
}
return generator.String()
}
// RID is only relevant if you wish to use Simulcast
func (track *baseTrack) RID() string {
return ""
}
// OnEnded sets an error handler. When a track has been created and started, if an
// error occurs, handler will get called with the error given to the parameter.
func (track *baseTrack) OnEnded(handler func(error)) {
track.errMu.Lock()
track.onErrorHandler = handler
err := track.err
track.errMu.Unlock()
if err != nil && handler != nil {
// Already errored.
track.endOnce.Do(func() {
handler(err)
})
}
}
// onError is a callback when an error occurs
func (track *baseTrack) onError(err error) {
track.errMu.Lock()
track.err = err
handler := track.onErrorHandler
track.errMu.Unlock()
if handler != nil {
track.endOnce.Do(func() {
handler(err)
})
}
}
func (track *baseTrack) bind(ctx webrtc.TrackLocalContext, specializedTrack Track) (webrtc.RTPCodecParameters, error) {
track.mu.Lock()
defer track.mu.Unlock()
signalCh := make(chan chan<- struct{})
stopRead := make(chan struct{})
track.activePeerConnections[ctx.ID()] = signalCh
var encodedReader RTPReadCloser
var selectedCodec webrtc.RTPCodecParameters
var err error
var errReasons []string
for _, wantedCodec := range ctx.CodecParameters() {
logger.Debugf("trying to build %s rtp reader", wantedCodec.MimeType)
encodedReader, err = specializedTrack.NewRTPReader(wantedCodec.MimeType, uint32(ctx.SSRC()), rtpOutboundMTU)
track.errMu.Lock()
if track.err != nil {
err = track.err
encodedReader = nil
}
track.errMu.Unlock()
if err == nil {
selectedCodec = wantedCodec
break
}
errReasons = append(errReasons, fmt.Sprintf("%s: %s", wantedCodec.MimeType, err))
}
if encodedReader == nil {
return webrtc.RTPCodecParameters{}, errors.New(strings.Join(errReasons, "\n\n"))
}
go func() {
var doneCh chan<- struct{}
writer := ctx.WriteStream()
defer func() {
close(stopRead)
encodedReader.Close()
// When there's another call to unbind, it won't block since we remove the current ctx from active connections
track.removeActivePeerConnection(ctx.ID())
close(signalCh)
if doneCh != nil {
close(doneCh)
}
}()
for {
select {
case doneCh = <-signalCh:
return
default:
}
pkts, _, err := encodedReader.Read()
if err != nil {
// explicitly ignore this error since the higher level should've reported this
return
}
for _, pkt := range pkts {
_, err = writer.WriteRTP(&pkt.Header, pkt.Payload)
if err != nil {
track.onError(err)
return
}
}
}
}()
keyFrameController, ok := encodedReader.Controller().(codec.KeyFrameController)
if ok {
go track.rtcpReadLoop(ctx.RTCPReader(), keyFrameController, stopRead)
}
return selectedCodec, nil
}
func (track *baseTrack) rtcpReadLoop(reader interceptor.RTCPReader, keyFrameController codec.KeyFrameController, stopRead chan struct{}) {
readerBuffer := make([]byte, rtcpInboundMTU)
readLoop:
for {
select {
case <-stopRead:
return
default:
}
readLength, _, err := reader.Read(readerBuffer, interceptor.Attributes{})
if err != nil {
if errors.Is(err, io.EOF) {
return
}
logger.Warnf("failed to read rtcp packet: %s", err)
continue
}
pkts, err := rtcp.Unmarshal(readerBuffer[:readLength])
if err != nil {
logger.Warnf("failed to unmarshal rtcp packet: %s", err)
continue
}
for _, pkt := range pkts {
switch pkt.(type) {
case *rtcp.PictureLossIndication, *rtcp.FullIntraRequest:
if err := keyFrameController.ForceKeyFrame(); err != nil {
logger.Warnf("failed to force key frame: %s", err)
continue readLoop
}
}
}
}
}
func (track *baseTrack) unbind(ctx webrtc.TrackLocalContext) error {
ch := track.removeActivePeerConnection(ctx.ID())
// If there isn't a registered chanel for this ctx, it means it has already been unbound
if ch == nil {
return nil
}
doneCh := make(chan struct{})
ch <- doneCh
<-doneCh
return nil
}
func (track *baseTrack) removeActivePeerConnection(id string) chan<- chan<- struct{} {
track.mu.Lock()
defer track.mu.Unlock()
ch, ok := track.activePeerConnections[id]
if !ok {
return nil
}
delete(track.activePeerConnections, id)
return ch
}
func newTrackFromDriver(d driver.Driver, constraints MediaTrackConstraints, selector *CodecSelector) (Track, error) {
if err := d.Open(); err != nil {
return nil, err
}
switch recorder := d.(type) {
case driver.VideoRecorder:
return newVideoTrackFromDriver(d, recorder, constraints, selector)
case driver.AudioRecorder:
return newAudioTrackFromDriver(d, recorder, constraints, selector)
default:
panic(errInvalidDriverType)
}
}
// VideoTrack is a specific track type that contains video source which allows multiple readers to access, and manipulate.
type VideoTrack struct {
*baseTrack
*video.Broadcaster
shouldCopyFrames bool
}
// NewVideoTrack constructs a new VideoTrack
func NewVideoTrack(source VideoSource, selector *CodecSelector) Track {
return newVideoTrackFromReader(source, source, selector)
}
// ShouldCopyFrames indicates if readers on this track should receive a clopy of the read buffer instead of sharing one.
func (track *VideoTrack) ShouldCopyFrames() bool {
return track.shouldCopyFrames
}
// SetShouldCopyFrames enables frame copy for this track, sending each reader a different read buffer instead of sharing one.
func (track *VideoTrack) SetShouldCopyFrames(shouldCopyFrames bool) {
track.shouldCopyFrames = shouldCopyFrames
}
func newVideoTrackFromReader(source Source, reader video.Reader, selector *CodecSelector) Track {
base := newBaseTrack(source, VideoInput, selector)
wrappedReader := video.ReaderFunc(func() (img image.Image, release func(), err error) {
img, _, err = reader.Read()
if err != nil {
base.onError(err)
}
return img, func() {}, err
})
// TODO: Allow users to configure broadcaster
broadcaster := video.NewBroadcaster(wrappedReader, nil)
return &VideoTrack{
baseTrack: base,
Broadcaster: broadcaster,
}
}
// newVideoTrackFromDriver is an internal video track creation from driver
func newVideoTrackFromDriver(d driver.Driver, recorder driver.VideoRecorder, constraints MediaTrackConstraints, selector *CodecSelector) (Track, error) {
reader, err := recorder.VideoRecord(constraints.selectedMedia)
if err != nil {
return nil, err
}
return newVideoTrackFromReader(d, reader, selector), nil
}
// Transform transforms the underlying source by applying the given fns in serial order
func (track *VideoTrack) Transform(fns ...video.TransformFunc) {
src := track.Broadcaster.Source()
track.Broadcaster.ReplaceSource(video.Merge(fns...)(src))
}
func (track *VideoTrack) Bind(ctx webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, error) {
return track.bind(ctx, track)
}
func (track *VideoTrack) Unbind(ctx webrtc.TrackLocalContext) error {
return track.unbind(ctx)
}
func (track *VideoTrack) newEncodedReader(codecNames ...string) (EncodedReadCloser, *codec.RTPCodec, error) {
reader := track.NewReader(track.shouldCopyFrames)
inputProp, err := detectCurrentVideoProp(track.Broadcaster)
if err != nil {
return nil, nil, err
}
encodedReader, selectedCodec, err := track.selector.selectVideoCodecByNames(reader, inputProp, codecNames...)
if err != nil {
return nil, nil, err
}
sample := newVideoSampler(selectedCodec.ClockRate)
return &encodedReadCloserImpl{
readFn: func() (EncodedBuffer, func(), error) {
data, release, err := encodedReader.Read()
buffer := EncodedBuffer{
Data: data,
Samples: sample(),
}
return buffer, release, err
},
closeFn: encodedReader.Close,
controllerFn: encodedReader.Controller,
}, selectedCodec, nil
}
func (track *VideoTrack) NewEncodedReader(codecName string) (EncodedReadCloser, error) {
reader, _, err := track.newEncodedReader(codecName)
return reader, err
}
func (track *VideoTrack) NewEncodedIOReader(codecName string) (io.ReadCloser, error) {
encodedReader, _, err := track.newEncodedReader(codecName)
if err != nil {
return nil, err
}
return newEncodedIOReadCloserImpl(encodedReader), nil
}
func (track *VideoTrack) NewRTPReader(codecName string, ssrc uint32, mtu int) (RTPReadCloser, error) {
encodedReader, selectedCodec, err := track.newEncodedReader(codecName)
if err != nil {
return nil, err
}
packetizer := rtp.NewPacketizer(uint16(mtu), uint8(selectedCodec.PayloadType), ssrc, selectedCodec.Payloader, rtp.NewRandomSequencer(), selectedCodec.ClockRate)
return &rtpReadCloserImpl{
readFn: func() ([]*rtp.Packet, func(), error) {
encoded, release, err := encodedReader.Read()
if err != nil {
encodedReader.Close()
track.onError(err)
return nil, func() {}, err
}
defer release()
pkts := packetizer.Packetize(encoded.Data, encoded.Samples)
return pkts, release, err
},
closeFn: encodedReader.Close,
controllerFn: encodedReader.Controller,
}, nil
}
// AudioTrack is a specific track type that contains audio source which allows multiple readers to access, and
// manipulate.
type AudioTrack struct {
*baseTrack
*audio.Broadcaster
}
// NewAudioTrack constructs a new AudioTrack
func NewAudioTrack(source AudioSource, selector *CodecSelector) Track {
return newAudioTrackFromReader(source, source, selector)
}
func newAudioTrackFromReader(source Source, reader audio.Reader, selector *CodecSelector) Track {
base := newBaseTrack(source, AudioInput, selector)
wrappedReader := audio.ReaderFunc(func() (chunk wave.Audio, release func(), err error) {
chunk, _, err = reader.Read()
if err != nil {
base.onError(err)
}
return chunk, func() {}, err
})
// TODO: Allow users to configure broadcaster
broadcaster := audio.NewBroadcaster(wrappedReader, nil)
return &AudioTrack{
baseTrack: base,
Broadcaster: broadcaster,
}
}
// newAudioTrackFromDriver is an internal audio track creation from driver
func newAudioTrackFromDriver(d driver.Driver, recorder driver.AudioRecorder, constraints MediaTrackConstraints, selector *CodecSelector) (Track, error) {
reader, err := recorder.AudioRecord(constraints.selectedMedia)
if err != nil {
return nil, err
}
return newAudioTrackFromReader(d, reader, selector), nil
}
// Transform transforms the underlying source by applying the given fns in serial order
func (track *AudioTrack) Transform(fns ...audio.TransformFunc) {
src := track.Broadcaster.Source()
track.Broadcaster.ReplaceSource(audio.Merge(fns...)(src))
}
func (track *AudioTrack) Bind(ctx webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, error) {
return track.bind(ctx, track)
}
func (track *AudioTrack) Unbind(ctx webrtc.TrackLocalContext) error {
return track.unbind(ctx)
}
func (track *AudioTrack) newEncodedReader(codecNames ...string) (EncodedReadCloser, *codec.RTPCodec, error) {
reader := track.NewReader(false)
inputProp, err := detectCurrentAudioProp(track.Broadcaster)
if err != nil {
return nil, nil, err
}
encodedReader, selectedCodec, err := track.selector.selectAudioCodecByNames(reader, inputProp, codecNames...)
if err != nil {
return nil, nil, err
}
sample := newAudioSampler(selectedCodec.ClockRate, selectedCodec.Latency)
return &encodedReadCloserImpl{
readFn: func() (EncodedBuffer, func(), error) {
data, release, err := encodedReader.Read()
buffer := EncodedBuffer{
Data: data,
Samples: sample(),
}
return buffer, release, err
},
closeFn: encodedReader.Close,
controllerFn: encodedReader.Controller,
}, selectedCodec, nil
}
func (track *AudioTrack) NewEncodedReader(codecName string) (EncodedReadCloser, error) {
reader, _, err := track.newEncodedReader(codecName)
return reader, err
}
func (track *AudioTrack) NewEncodedIOReader(codecName string) (io.ReadCloser, error) {
encodedReader, _, err := track.newEncodedReader(codecName)
if err != nil {
return nil, err
}
return newEncodedIOReadCloserImpl(encodedReader), nil
}
func (track *AudioTrack) NewRTPReader(codecName string, ssrc uint32, mtu int) (RTPReadCloser, error) {
encodedReader, selectedCodec, err := track.newEncodedReader(codecName)
if err != nil {
return nil, err
}
packetizer := rtp.NewPacketizer(uint16(mtu), uint8(selectedCodec.PayloadType), ssrc, selectedCodec.Payloader, rtp.NewRandomSequencer(), selectedCodec.ClockRate)
return &rtpReadCloserImpl{
readFn: func() ([]*rtp.Packet, func(), error) {
encoded, release, err := encodedReader.Read()
if err != nil {
encodedReader.Close()
track.onError(err)
return nil, func() {}, err
}
defer release()
pkts := packetizer.Packetize(encoded.Data, encoded.Samples)
return pkts, release, err
},
closeFn: encodedReader.Close,
controllerFn: encodedReader.Controller,
}, nil
}