-
Notifications
You must be signed in to change notification settings - Fork 42
/
router.go
937 lines (801 loc) · 27.3 KB
/
router.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
package mediasoup
import (
"sort"
"strings"
"sync"
"sync/atomic"
"github.com/go-logr/logr"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/singleflight"
)
// pipeRouterGroup is a singleflight group to avoid pipe the same routers pair
// at the same time.
var pipeRouterGroup = &singleflight.Group{}
// RouterOptions define options to create a router.
type RouterOptions struct {
// MediaCodecs defines Router media codecs.
MediaCodecs []*RtpCodecCapability `json:"mediaCodecs,omitempty"`
// AppData is custom application data.
AppData interface{} `json:"appData,omitempty"`
}
// PipeToRouterOptions define options to pipe an another router.
type PipeToRouterOptions struct {
// ProducerId is the id of the Producer to consume.
ProducerId string `json:"producerId,omitempty"`
// DataProducerId is the id of the DataProducer to consume.
DataProducerId string `json:"dataProducerId,omitempty"`
// Router is the target Router instance.
Router *Router `json:"router,omitempty"`
// ListenIp is the ip used in the PipeTransport pair. Default '127.0.0.1'.
ListenIp TransportListenIp `json:"listenIp,omitempty"`
// Create a SCTP association. Default false.
EnableSctp bool `json:"enableSctp,omitempty"`
// NumSctpStreams define SCTP streams number.
NumSctpStreams NumSctpStreams `json:"numSctpStreams,omitempty"`
// EnableRtx enable RTX and NACK for RTP retransmission.
EnableRtx bool `json:"enableRtx,omitempty"`
// EnableSrtp enable SRTP.
EnableSrtp bool `json:"enableSrtp,omitempty"`
}
// PipeToRouterResult is the result to piping router.
type PipeToRouterResult struct {
// PipeConsumer is the Consumer created in the current Router.
PipeConsumer *Consumer
// PipeConsumer is the Producer created in the target Router.
PipeProducer *Producer
// PipeDataConsumer is the DataConsumer created in the current Router.
PipeDataConsumer *DataConsumer
// PipeDataProducer is the DataProducer created in the target Router.
PipeDataProducer *DataProducer
}
type routerData struct {
RtpCapabilities RtpCapabilities `json:"rtpCapabilities,omitempty"`
}
type routerParams struct {
// {
// routerId: string;
// };
internal internalData
data routerData
channel *Channel
payloadChannel *PayloadChannel
appData interface{}
}
// Router enables injection, selection and forwarding of media streams through
// Transport instances created on it.
//
// - @emits workerclose
// - @emits @close
type Router struct {
IEventEmitter
logger logr.Logger
internal internalData
data routerData
channel *Channel
payloadChannel *PayloadChannel
closed uint32
appData interface{}
transports sync.Map
producers sync.Map
rtpObservers sync.Map
dataProducers sync.Map
mapRouterPipeTransports sync.Map
observer IEventEmitter
onNewRtpObserver func(observer IRtpObserver)
onNewTransport func(transport ITransport)
onClose func()
}
func newRouter(params routerParams) *Router {
logger := NewLogger("Router")
logger.V(1).Info("constructor()", "internal", params.internal)
return &Router{
IEventEmitter: NewEventEmitter(),
logger: logger,
internal: params.internal,
data: params.data,
channel: params.channel,
payloadChannel: params.payloadChannel,
appData: params.appData,
observer: NewEventEmitter(),
}
}
// Id returns Router id
func (router *Router) Id() string {
return router.internal.RouterId
}
// Closed returns whether the Router is closed.
func (router *Router) Closed() bool {
return atomic.LoadUint32(&router.closed) > 0
}
// RtpCapabilities returns RTC capabilities of the Router.
func (router *Router) RtpCapabilities() RtpCapabilities {
return router.data.RtpCapabilities
}
// AppData returns App custom data.
func (router *Router) AppData() interface{} {
return router.appData
}
// Deprecated
//
// - @emits close
// - @emits newrtpobserver - (observer IRtpObserver)
// - @emits newtransport - (transport ITransport)
func (router *Router) Observer() IEventEmitter {
return router.observer
}
// transportsForTesting returns all transports in map. Just for testing purposes.
func (router *Router) transportsForTesting() map[string]ITransport {
transports := make(map[string]ITransport)
router.transports.Range(func(key, value interface{}) bool {
transports[key.(string)] = value.(ITransport)
return true
})
return transports
}
// Close the Router.
func (router *Router) Close() (err error) {
router.logger.V(1).Info("close()")
if !atomic.CompareAndSwapUint32(&router.closed, 0, 1) {
return
}
reqData := H{"routerId": router.internal.RouterId}
resp := router.channel.Request("worker.closeRouter", router.internal, reqData)
if err = resp.Err(); err != nil {
return
}
router.close()
router.Emit("@close")
return
}
func (router *Router) workerClosed() {
router.logger.V(1).Info("workerClosed()")
if !atomic.CompareAndSwapUint32(&router.closed, 0, 1) {
return
}
router.close()
router.Emit("workerclose")
}
func (router *Router) close() {
// Close every Transport.
router.transports.Range(func(key, value interface{}) bool {
value.(ITransport).routerClosed()
return true
})
router.transports = sync.Map{}
// Clear the Producers map.
router.producers = sync.Map{}
// Close every RtpObserver.
router.rtpObservers.Range(func(key, value interface{}) bool {
value.(IRtpObserver).routerClosed()
return true
})
router.rtpObservers = sync.Map{}
// Clear map of Router/PipeTransports.
router.mapRouterPipeTransports = sync.Map{}
// Emit observer event.
router.observer.SafeEmit("close")
if router.onClose != nil {
router.onClose()
}
}
// Dump Router.
func (router *Router) Dump() (data *RouterDump, err error) {
router.logger.V(1).Info("dump()")
resp := router.channel.Request("router.dump", router.internal)
err = resp.Unmarshal(&data)
return
}
// Producers returns available producers on the router.
func (router *Router) Producers() []*Producer {
router.logger.V(1).Info("Producers()")
producers := make([]*Producer, 0)
router.producers.Range(func(key, value interface{}) bool {
producer, ok := value.(*Producer)
if ok {
producers = append(producers, producer)
}
return true
})
return producers
}
// DataProducers returns available producers on the router.
func (router *Router) DataProducers() []*DataProducer {
router.logger.V(1).Info("DataProducers()")
dataProducers := make([]*DataProducer, 0)
router.dataProducers.Range(func(key, value interface{}) bool {
dataProducer, ok := value.(*DataProducer)
if ok {
dataProducers = append(dataProducers, dataProducer)
}
return true
})
return dataProducers
}
// Transports returns available transports on the router.
func (router *Router) Transports() []ITransport {
router.logger.V(1).Info("Transports()")
transports := make([]ITransport, 0)
router.transports.Range(func(key, value interface{}) bool {
transport, ok := value.(ITransport)
if ok {
transports = append(transports, transport)
}
return true
})
return transports
}
// CreateWebRtcTransport create a WebRtcTransport.
func (router *Router) CreateWebRtcTransport(option WebRtcTransportOptions) (transport *WebRtcTransport, err error) {
options := &WebRtcTransportOptions{
EnableUdp: Bool(true),
InitialAvailableOutgoingBitrate: 600000,
NumSctpStreams: NumSctpStreams{OS: 1024, MIS: 1024},
MaxSctpMessageSize: 262144,
SctpSendBufferSize: 262144,
}
if err = override(options, option); err != nil {
return
}
if len(options.ListenIps) == 0 && options.WebRtcServer == nil {
err = NewTypeError("missing webRtcServer and listenIps (one of them is mandatory)")
return
}
router.logger.V(1).Info("createWebRtcTransport()")
method := "router.createWebRtcTransport"
internal := router.internal
internal.TransportId = uuid.NewString()
reqData := H{
"transportId": internal.TransportId,
"listenIps": options.ListenIps,
"enableUdp": options.EnableUdp,
"enableTcp": options.EnableTcp,
"preferUdp": options.PreferUdp,
"preferTcp": options.PreferTcp,
"initialAvailableOutgoingBitrate": options.InitialAvailableOutgoingBitrate,
"enableSctp": options.EnableSctp,
"numSctpStreams": options.NumSctpStreams,
"maxSctpMessageSize": options.MaxSctpMessageSize,
"sctpSendBufferSize": options.SctpSendBufferSize,
"isDataChannel": true,
}
if options.WebRtcServer != nil {
method = "router.createWebRtcTransportWithServer"
reqData["webRtcServerId"] = option.WebRtcServer.Id()
}
var data *webrtcTransportData
if err = router.channel.Request(method, internal, reqData).Unmarshal(&data); err != nil {
return
}
transport = router.createTransport(internal, data, options.AppData).(*WebRtcTransport)
if options.WebRtcServer != nil {
options.WebRtcServer.handleWebRtcTransport(transport)
}
return
}
// CreatePlainTransport create a PlainTransport.
func (router *Router) CreatePlainTransport(option PlainTransportOptions) (transport *PlainTransport, err error) {
options := &PlainTransportOptions{
RtcpMux: Bool(true),
NumSctpStreams: NumSctpStreams{OS: 1024, MIS: 1024},
MaxSctpMessageSize: 262144,
SctpSendBufferSize: 262144,
SrtpCryptoSuite: AES_CM_128_HMAC_SHA1_80,
}
if err = override(options, option); err != nil {
return
}
router.logger.V(1).Info("createPlainTransport()")
internal := router.internal
internal.TransportId = uuid.NewString()
reqData := H{
"transportId": internal.TransportId,
"listenIp": options.ListenIp,
"rtcpMux": options.RtcpMux,
"comedia": options.Comedia,
"enableSctp": options.EnableSctp,
"numSctpStreams": options.NumSctpStreams,
"maxSctpMessageSize": options.MaxSctpMessageSize,
"sctpSendBufferSize": options.SctpSendBufferSize,
"isDataChannel": false,
"enableSrtp": options.EnableSrtp,
"srtpCryptoSuite": options.SrtpCryptoSuite,
}
resp := router.channel.Request("router.createPlainTransport", internal, reqData)
var data *plainTransportData
if err = resp.Unmarshal(&data); err != nil {
return
}
iTransport := router.createTransport(internal, data, options.AppData)
return iTransport.(*PlainTransport), nil
}
// CreatePipeTransport create a PipeTransport.
func (router *Router) CreatePipeTransport(option PipeTransportOptions) (transport *PipeTransport, err error) {
options := &PipeTransportOptions{
NumSctpStreams: NumSctpStreams{OS: 1024, MIS: 1024},
MaxSctpMessageSize: 268435456,
SctpSendBufferSize: 268435456,
}
if err = override(options, option); err != nil {
return
}
router.logger.V(1).Info("createPipeTransport()")
internal := router.internal
internal.TransportId = uuid.NewString()
reqData := H{
"transportId": internal.TransportId,
"listenIp": options.ListenIp,
"enableSctp": options.EnableSctp,
"numSctpStreams": options.NumSctpStreams,
"maxSctpMessageSize": options.MaxSctpMessageSize,
"sctpSendBufferSize": options.SctpSendBufferSize,
"isDataChannel": false,
"enableRtx": options.EnableRtx,
"enableSrtp": options.EnableSrtp,
}
resp := router.channel.Request("router.createPipeTransport", internal, reqData)
var data *pipeTransortData
if err = resp.Unmarshal(&data); err != nil {
return
}
iTransport := router.createTransport(internal, data, options.AppData)
return iTransport.(*PipeTransport), nil
}
// CreateDirectTransport create a DirectTransport.
func (router *Router) CreateDirectTransport(params ...DirectTransportOptions) (transport *DirectTransport, err error) {
options := &DirectTransportOptions{
MaxMessageSize: 262144,
}
for _, option := range params {
if err = override(options, option); err != nil {
return
}
}
router.logger.V(1).Info("createDirectTransport()")
internal := router.internal
internal.TransportId = uuid.NewString()
reqData := H{
"transportId": internal.TransportId,
"direct": true,
"maxMessageSize": options.MaxMessageSize,
}
resp := router.channel.Request("router.createDirectTransport", internal, reqData)
var data *directTransportData
if err = resp.Unmarshal(&data); err != nil {
return
}
iTransport := router.createTransport(internal, data, options.AppData)
return iTransport.(*DirectTransport), nil
}
// PipeToRouter pipes the given Producer or DataProducer into another Router in same host.
func (router *Router) PipeToRouter(option PipeToRouterOptions) (result *PipeToRouterResult, err error) {
router.logger.V(1).Info("pipeToRouter()")
options := &PipeToRouterOptions{
ListenIp: TransportListenIp{
Ip: "127.0.0.1",
},
EnableSctp: false,
NumSctpStreams: NumSctpStreams{OS: 1024, MIS: 1024},
}
if err = override(options, option); err != nil {
return
}
if len(options.ProducerId) == 0 && len(options.DataProducerId) == 0 {
err = NewTypeError("missing producerId")
return
}
if len(options.ProducerId) > 0 && len(options.DataProducerId) > 0 {
err = NewTypeError("just producerId or dataProducerId can be given")
return
}
if options.Router == nil {
err = NewTypeError("Router not found")
return
}
if options.Router == router {
err = NewTypeError("cannot use this Router as destination'")
return
}
var producer *Producer
var dataProducer *DataProducer
if len(options.ProducerId) > 0 {
if value, ok := router.producers.Load(options.ProducerId); ok {
producer = value.(*Producer)
} else {
err = NewTypeError("Producer not found")
return
}
}
if len(options.DataProducerId) > 0 {
if value, ok := router.dataProducers.Load(options.DataProducerId); ok {
dataProducer = value.(*DataProducer)
} else {
err = NewTypeError("DataProducer not found")
return
}
}
var localPipeTransport, remotePipeTransport *PipeTransport
if value, ok := router.mapRouterPipeTransports.Load(options.Router); ok {
pipeTransportPair := value.([2]*PipeTransport)
localPipeTransport, remotePipeTransport = pipeTransportPair[0], pipeTransportPair[1]
} else {
// Here we may have to create a new PipeTransport pair to connect source and
// destination Routers. We just want to keep a PipeTransport pair for each
// pair of Routers. Since this operation is async, it may happen that two
// simultaneous calls to router1.pipeToRouter({ producerId: xxx, router: router2 })
// would end up generating two pairs of PipeTranports. To prevent that, let's
// use singleflight.
routerPairIds := []string{router.Id(), options.Router.Id()}
sort.Strings(routerPairIds)
key := strings.Join(routerPairIds, "_")
v, err, _ := pipeRouterGroup.Do(key, func() (result interface{}, err error) {
defer func() {
if err != nil {
if localPipeTransport != nil {
localPipeTransport.Close()
}
if remotePipeTransport != nil {
remotePipeTransport.Close()
}
}
}()
option := PipeTransportOptions{
ListenIp: options.ListenIp,
EnableSctp: options.EnableSctp,
NumSctpStreams: options.NumSctpStreams,
EnableRtx: options.EnableRtx,
EnableSrtp: options.EnableSrtp,
}
errgroup := new(errgroup.Group)
errgroup.Go(func() error {
localPipeTransport, err = router.CreatePipeTransport(option)
return err
})
errgroup.Go(func() error {
remotePipeTransport, err = options.Router.CreatePipeTransport(option)
return err
})
if err = errgroup.Wait(); err != nil {
router.logger.Error(err, "pipeToRouter() | error creating PipeTransport pair")
return
}
errgroup.Go(func() error {
return localPipeTransport.Connect(TransportConnectOptions{
Ip: remotePipeTransport.Tuple().LocalIp,
Port: remotePipeTransport.Tuple().LocalPort,
SrtpParameters: remotePipeTransport.SrtpParameters(),
})
})
errgroup.Go(func() error {
return remotePipeTransport.Connect(TransportConnectOptions{
Ip: localPipeTransport.Tuple().LocalIp,
Port: localPipeTransport.Tuple().LocalPort,
SrtpParameters: localPipeTransport.SrtpParameters(),
})
})
if err = errgroup.Wait(); err != nil {
router.logger.Error(err, "pipeToRouter() | error connecting PipeTransport pair")
return
}
return []interface{}{router, [2]*PipeTransport{localPipeTransport, remotePipeTransport}}, nil
})
if err != nil {
return nil, err
}
result := v.([]interface{})
actualRouter := result[0].(*Router)
pipeTransportPair := result[1].([2]*PipeTransport)
// swap local and remote PipeTransport if pipeTransportPair is shared from the other router
if actualRouter != router {
pipeTransportPair[0], pipeTransportPair[1] = pipeTransportPair[1], pipeTransportPair[0]
}
localPipeTransport, remotePipeTransport = router.addPipeTransportPair(options.Router, pipeTransportPair)
}
if producer != nil {
var pipeConsumer *Consumer
var pipeProducer *Producer
defer func() {
if err != nil {
if pipeConsumer != nil {
pipeConsumer.Close()
}
if pipeProducer != nil {
pipeProducer.Close()
}
}
}()
pipeConsumer, err = localPipeTransport.Consume(ConsumerOptions{
ProducerId: options.ProducerId,
})
if err != nil {
router.logger.Error(err, "pipeToRouter() | error creating pipe Consumer")
return
}
pipeProducer, err = remotePipeTransport.Produce(ProducerOptions{
Id: producer.Id(),
Kind: pipeConsumer.Kind(),
RtpParameters: pipeConsumer.RtpParameters(),
Paused: pipeConsumer.ProducerPaused(),
AppData: producer.AppData(),
})
if err != nil {
router.logger.Error(err, "pipeToRouter() | error creating pipe Producer")
return
}
// Ensure that the producer has not been closed in the meanwhile.
if producer.Closed() {
err = NewInvalidStateError("original Producer closed")
router.logger.Error(err, "pipeToRouter() | failed")
return
}
// Ensure that producer.paused has not changed in the meanwhile and, if
// so, sych the pipeProducer.
if pipeProducer.Paused() != producer.Paused() {
if producer.Paused() {
err = pipeProducer.Pause()
} else {
err = pipeProducer.Resume()
}
if err != nil {
router.logger.Error(err, "pipeToRouter() | error pause or resume producer")
return
}
}
// Pipe events from the pipe Consumer to the pipe Producer.
pipeConsumer.Observer().On("close", func() { pipeProducer.Close() })
pipeConsumer.Observer().On("pause", func() { pipeProducer.Pause() })
pipeConsumer.Observer().On("resume", func() { pipeProducer.Resume() })
// Pipe events from the pipe Producer to the pipe Consumer.
pipeProducer.Observer().On("close", func() { pipeConsumer.Close() })
result = &PipeToRouterResult{
PipeConsumer: pipeConsumer,
PipeProducer: pipeProducer,
}
return
}
if dataProducer != nil {
var pipeDataConsumer *DataConsumer
var pipeDataProducer *DataProducer
defer func() {
if err != nil {
if pipeDataConsumer != nil {
pipeDataConsumer.Close()
}
if pipeDataProducer != nil {
pipeDataProducer.Close()
}
}
}()
pipeDataConsumer, err = localPipeTransport.ConsumeData(DataConsumerOptions{
DataProducerId: options.DataProducerId,
})
if err != nil {
router.logger.Error(err, "pipeToRouter() | error creating pipe DataConsumer pair")
return
}
pipeDataProducer, err = remotePipeTransport.ProduceData(DataProducerOptions{
Id: dataProducer.Id(),
SctpStreamParameters: pipeDataConsumer.SctpStreamParameters(),
Label: pipeDataConsumer.Label(),
Protocol: pipeDataConsumer.Protocol(),
AppData: dataProducer.AppData(),
})
if err != nil {
router.logger.Error(err, "pipeToRouter() | error creating pipe DataProducer pair")
return
}
// Ensure that the dataProducer has not been closed in the meanwhile.
if dataProducer.Closed() {
err = NewInvalidStateError("original DataProducer closed")
router.logger.Error(err, "pipeToRouter() | failed")
return
}
// Pipe events from the pipe DataConsumer to the pipe DataProducer.
pipeDataConsumer.Observer().On("close", func() { pipeDataProducer.Close() })
// Pipe events from the pipe DataProducer to the pipe DataConsumer.
pipeDataProducer.Observer().On("close", func() { pipeDataConsumer.Close() })
result = &PipeToRouterResult{
PipeDataConsumer: pipeDataConsumer,
PipeDataProducer: pipeDataProducer,
}
}
return
}
// addPipeTransportPair add PipeTransport pair for the another router
func (router *Router) addPipeTransportPair(anotherRouter *Router, pipeTransportPair [2]*PipeTransport) (*PipeTransport, *PipeTransport) {
if val, loaded := router.mapRouterPipeTransports.LoadOrStore(anotherRouter, pipeTransportPair); loaded {
router.logger.Info("pipeTransport exists, use the old pair", "router", anotherRouter.Id(), "warn", true)
oldPipeTransportPair := val.([2]*PipeTransport)
// close useless pipeTransport pair
for i, transport := range pipeTransportPair {
if transport != oldPipeTransportPair[i] {
transport.Close()
}
}
return oldPipeTransportPair[0], oldPipeTransportPair[1]
}
localPipeTransport, remotePipeTransport := pipeTransportPair[0], pipeTransportPair[1]
localPipeTransport.Observer().On("close", func() {
remotePipeTransport.Close()
router.mapRouterPipeTransports.Delete(anotherRouter)
})
return localPipeTransport, remotePipeTransport
}
// CreateActiveSpeakerObserver create an ActiveSpeakerObserver
func (router *Router) CreateActiveSpeakerObserver(options ...func(*ActiveSpeakerObserverOptions)) (activeSpeakerObserver *ActiveSpeakerObserver, err error) {
router.logger.V(1).Info("createActiveSpeakerObserver()")
o := &ActiveSpeakerObserverOptions{
Interval: 300,
}
for _, option := range options {
option(o)
}
internal := router.internal
internal.RtpObserverId = uuid.NewString()
reqData := H{
"rtpObserverId": internal.RtpObserverId,
"interval": o.Interval,
}
resp := router.channel.Request("router.createActiveSpeakerObserver", internal, reqData)
if err = resp.Err(); err != nil {
return
}
activeSpeakerObserver = newActiveSpeakerObserver(rtpObserverParams{
internal: internal,
channel: router.channel,
payloadChannel: router.payloadChannel,
appData: router.appData,
getProducerById: func(producerId string) *Producer {
if value, ok := router.producers.Load(producerId); ok {
return value.(*Producer)
}
return nil
},
})
router.rtpObservers.Store(activeSpeakerObserver.Id(), activeSpeakerObserver)
activeSpeakerObserver.On("@close", func() {
router.rtpObservers.Delete(activeSpeakerObserver.Id())
})
// Emit observer event.
router.observer.SafeEmit("newrtpobserver", activeSpeakerObserver)
if handler := router.onNewRtpObserver; handler != nil {
handler(activeSpeakerObserver)
}
return
}
// CreateAudioLevelObserver create an AudioLevelObserver.
func (router *Router) CreateAudioLevelObserver(options ...func(o *AudioLevelObserverOptions)) (audioLevelObserver *AudioLevelObserver, err error) {
router.logger.V(1).Info("createAudioLevelObserver()")
o := AudioLevelObserverOptions{
MaxEntries: 1,
Threshold: -80,
Interval: 1000,
}
for _, option := range options {
option(&o)
}
internal := router.internal
internal.RtpObserverId = uuid.NewString()
reqData := H{
"rtpObserverId": internal.RtpObserverId,
"maxEntries": o.MaxEntries,
"threshold": o.Threshold,
"interval": o.Interval,
}
resp := router.channel.Request("router.createAudioLevelObserver", internal, reqData)
if err = resp.Err(); err != nil {
return
}
audioLevelObserver = newAudioLevelObserver(rtpObserverParams{
internal: internal,
channel: router.channel,
payloadChannel: router.payloadChannel,
appData: router.appData,
getProducerById: func(producerId string) *Producer {
if value, ok := router.producers.Load(producerId); ok {
return value.(*Producer)
}
return nil
},
})
router.rtpObservers.Store(audioLevelObserver.Id(), audioLevelObserver)
audioLevelObserver.On("@close", func() {
router.rtpObservers.Delete(audioLevelObserver.Id())
})
// Emit observer event.
router.observer.SafeEmit("newrtpobserver", audioLevelObserver)
if handler := router.onNewRtpObserver; handler != nil {
handler(audioLevelObserver)
}
return
}
// CanConsume check whether the given RTP capabilities can consume the given Producer.
func (router *Router) CanConsume(producerId string, rtpCapabilities RtpCapabilities) bool {
router.logger.V(1).Info("CanConsume()")
value, ok := router.producers.Load(producerId)
if !ok {
router.logger.Error(nil, "canConsume() | Producer is not found", "id", producerId)
return false
}
producer := value.(*Producer)
ok, err := canConsume(producer.ConsumableRtpParameters(), rtpCapabilities)
if err != nil {
router.logger.Error(err, "canConsume() | unexpected error")
}
return ok
}
func (router *Router) OnClose(handler func()) {
router.onClose = handler
}
// OnNewRtpObserver set handler on "newrtpobserver" event
func (router *Router) OnNewRtpObserver(handler func(transport IRtpObserver)) {
router.onNewRtpObserver = handler
}
// OnNewTransport set handler on "newtransport" event
func (router *Router) OnNewTransport(handler func(transport ITransport)) {
router.onNewTransport = handler
}
// createTransport create a Transport interface.
func (router *Router) createTransport(internal internalData, data, appData interface{}) (transport ITransport) {
if appData == nil {
appData = H{}
}
var newTransport func(transportParams) ITransport
switch data.(type) {
case *directTransportData:
newTransport = newDirectTransport
case *plainTransportData:
newTransport = newPlainTransport
case *pipeTransortData:
newTransport = newPipeTransport
case *webrtcTransportData:
newTransport = newWebRtcTransport
}
transport = newTransport(transportParams{
internal: internal,
channel: router.channel,
payloadChannel: router.payloadChannel,
data: data,
appData: appData,
getRouterRtpCapabilities: func() RtpCapabilities {
return router.data.RtpCapabilities
},
getProducerById: func(producerId string) *Producer {
if producer, ok := router.producers.Load(producerId); ok {
return producer.(*Producer)
}
return nil
},
getDataProducerById: func(dataProducerId string) *DataProducer {
if dataProducer, ok := router.dataProducers.Load(dataProducerId); ok {
return dataProducer.(*DataProducer)
}
return nil
},
})
router.transports.Store(transport.Id(), transport)
transport.On("@close", func() {
router.transports.Delete(transport.Id())
})
transport.On("@listenserverclose", func() {
router.transports.Delete(transport.Id())
})
transport.On("@newproducer", func(producer *Producer) {
router.producers.Store(producer.Id(), producer)
})
transport.On("@producerclose", func(producer *Producer) {
router.producers.Delete(producer.Id())
})
transport.On("@newdataproducer", func(dataProducer *DataProducer) {
router.dataProducers.Store(dataProducer.Id(), dataProducer)
})
transport.On("@dataproducerclose", func(dataProducer *DataProducer) {
router.dataProducers.Delete(dataProducer.Id())
})
// Emit observer event.
router.observer.SafeEmit("newtransport", transport)
if handler := router.onNewTransport; handler != nil {
handler(transport)
}
return
}