-
Notifications
You must be signed in to change notification settings - Fork 5
/
rtcSDK.js
1524 lines (1299 loc) · 52.3 KB
/
rtcSDK.js
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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* rtc功能SDK,created by lduoduo
* 注:API目前还在完善中,尚未完成!
* 功能:通过rtc帮助传输媒体流和data数据
* 调用方式:
* 1. 新建实例 var rtc = new rtcSDK()
* 2. 初始化,可以传入媒体流或者data数据,可选
* rtc.init({
* url: 信令服务器地址,必填
* roomId: 房间号码,必填
* debug: false, 是否开启debug,主要针对移动端弹框显示,默认不开启
* mediastream: 媒体流,可选
* data: 自定义data数据,可选
* }).then(supportedListeners=>{
* // 回调返回的supportedListeners是目前SDK支持的事件注册名
* console.log('支持的事件注册列表:',supportedListeners)
* })
* 初始化成功之后,会有属性标志位:inited:true
* 3. 注册回调监听函数
* // 监听远程媒体流
* rtc.on('stream', function (mediastream) {
* console.log(mediastream)
* }.bind(this))
* rtc.on('data', function (data) {
* console.log(data)
* }.bind(this))
* // 连接成功回调
* rtc.on('ready', function (obj) {
* let {status, error, wss} = obj
* status: 连接成功失败的状态
* console.log(obj)
* }.bind(this))
* // 远程断开监听
* rtc.on('stop', function (obj) {
* console.log(obj)
* }.bind(this))
* 4. 可调用的方法
* - rtc.updateStream(stream) // 更新流,用新的流代替旧的流,如果不传参,代表销毁流
* - rtc.sendMessage(data) // 发送文字聊天
* - rtc.sendFile(file) // 发送文件
* - rtc.sendText(data) // 发送自定义纯文本
* - rtc.updateData(data) // 传递自定义数据,目前没有任何限制(已废弃,不推荐使用)
* 5. 本地日志颜色搭配
* - 有活动:黄色
* - 本地信息: 蓝色
* - 远程信息: 绿色
*/
/******************************SDK START************************************ */
// import Logger from './log.js'
require('webrtc-adapter')
require('es6-promise').polyfill();
const sdpTransform = window.sdpTransform = require('sdp-transform')
const support = require('./rtcPolify');
const signal = require('./rtcSignal');
const sdpUtil = require('./rtcSdpUtil');
import RtcStats from './rtcStats';
// 不允许改的属性, rtc当前的状态
const RTC_STATUS = {
'new': '0', // 刚初始化,还未开启
'opened': '1', // 已开启,还未连接
'connected': '2' //双方连接成功
}
// 指定dataChannel数据发送的规则
const RTC_DATA_TYPE = {
'text': '1', // '纯文本数据,默认类型,对端接收只打印不作处理',
'notify': '2', //'通知类数据,场景:发送特殊格式的数据需要提前告知对方注意接收',
'command': '3', //'命令相关,向后扩展白板等',
'message': '4', //'聊天内容',
'other': '5' //'替补类型,暂时无用,未完待续'
}
// 指定dataChannel数据发送的规则的反解析
const RTC_DATA_TYPE_RV = {
1: 'text', // '纯文本数据,默认类型,对端接收只打印不作处理',
2: 'notify', //'通知类数据,场景:发送特殊格式的数据需要提前告知对方注意接收',
3: 'command', //'命令相关,向后扩展白板等',
4: 'message', //'聊天内容',
5: 'other' //'替补类型,暂时无用,未完待续'
}
// 指定dataChannel接收数据后的方法分发
const RTC_DATA_TYPE_FN = {
'text': 'onText', // '纯文本数据, 默认类型, 对端接收只打印不作处理',
'notify': 'onNotify', //'通知类数据,场景:发送特殊格式的数据需要提前告知对方注意接收',
'command': 'onCommand', //'命令相关,向后扩展白板等',
'message': 'onMessage', //'聊天内容',
'other': 'onOther' //'替补类型,暂时无用,未完待续'
}
// 开始构造函数
function rtcSDK() {
this.rtcConnection = null;
// 默认开启的长连接通道
this.dataChannel = null;
// 特殊需求时候开启的别的通道
this.rtcDataChannels = {};
// 待发送的iceoffer
this.ice_offer = [];
// ice交换完毕
this.ice_completed = false;
// 是否是重新连接, 当服务器断开之后进行重连
this.isReconect = false;
// 是否是重新初始化rtc, 当对方离开之后重新初始化
this.isReSetup = false;
this.stream = null;
this.inited = false;
this.wss = null;
// 状态:刚初始化
this.rtcStatus = RTC_STATUS['new'];
this.supportedListeners = {
'ready': '连接成功的回调',
'connected': '点对点webrtc连接成功的回调',
'stream': '收到远端流',
'data': '收到远端datachannel数据',
'stop': '连接断开',
'leave': '对方离开',
'text': '收到纯文本消息',
'message': '收到聊天信息',
'command': '收到指令',
'notify': '收到通知',
'sendFile': '文件发送中的实时状态',
'receiveFile': '文件接收中的实时状态',
'sendBuffer': '发送ArrayBuffer实时状态',
'receiveBuffer': '接收ArrayBuffer实时状态',
'sendBlob': '发送Blob实时状态',
'receiveBlob': '接收Blob实时状态'
}
// 回调监听
this.listeners = {}
this.duoduo_signal = signal
}
rtcSDK.prototype = {
// 临时的远程数据,用于存放接收特殊格式数据,数据接收完毕回传后删除!
remoteTMP: {},
// 注册监听回调事件
on(name, fn) {
this.listeners[name] = fn
},
// 执行回调
emit(name, data) {
this.listeners[name] && this.listeners[name](data)
},
// 初始化入口
init(option = {}) {
// 先校验平台适配情况
if (!support.support) return Promise.reject('当前浏览器不支持WebRTC功能')
let { url, roomId, stream, data, debug } = option
if (!url) return Promise.reject('缺少wss信令地址')
if (!roomId) return Promise.reject('缺少房间号码')
this.tmpStream = stream;
this.data = data;
this.debug = debug || false;
if (this.inited) {
this.updateStream()
return Promise.reject('请勿重复开启rtc连接')
}
this.duoduo_signal.init({ url, roomId });
if (this.isReconect) {
return Promise.resolve()
}
this.duoduo_signal.on('connected', this.connected.bind(this))
this.duoduo_signal.on('start', this.start.bind(this))
this.duoduo_signal.on('leave', this.leave.bind(this))
this.duoduo_signal.on('stop', this.stop.bind(this))
this.duoduo_signal.on('candidate', this.onNewPeer.bind(this))
this.duoduo_signal.on('offer', this.onOffer.bind(this))
this.duoduo_signal.on('answer', this.onAnswer.bind(this))
return Promise.resolve(this.supportedListeners)
},
// 对方离开,清空当前rtc状态,重置
leave(data) {
if (!this.inited) return
this.emit('leave', data)
this.rtcConnection.close();
this.isReSetup = true;
// 重新开启准备工作
this.setup()
},
// 断开连接, 进行销毁工作
stop(data) {
if (!this.inited) return
this.emit('stop', data)
if (this.dataChannel) this.closeChannel(this.dataChannel)
for (let i in this.rtcDataChannels) {
this.closeChannel(this.rtcDataChannels[i])
}
if (this.rtcConnection && this.rtcConnection.signalingState !== 'closed') this.rtcConnection.close()
this.rtcConnection = null
this.dataChannel = null
this.rtcDataChannels = {}
this.duoduo_signal.stop()
let stream = this.stream
if (stream) {
stream.getTracks().forEach(function (track) {
stream.removeTrack(track)
})
}
this.stream = null
this.listeners = {}
this.inited = false
this.isReSetup = false;
this.isReconect = true;
},
connected(option = {}) {
let { status, wss, error } = option
if (status) {
this.setup(wss)
return
}
this.emit('ready', { status: false, error })
},
// 初始化rtc连接,做准备工作
setup(wss) {
let rtcConnection;
this.wss = wss || this.wss;
//Google的STUN服务器:stun:stun.l.google.com:19302 ??
let iceServer = {
"iceServers": [{
"urls": "stun:173.194.202.127:19302"
}]
};
let optional = [{
// DTLS/SRTP is preferred on chrome
// to interop with Firefox
// which supports them by default
DtlsSrtpKeyAgreement: true
},
{
googCpuOveruseDetection: false
}];
rtcConnection = this.rtcConnection = new RTCPeerConnection(iceServer, { optional });
//chrome
// if (navigator.mozGetUserMedia) {
// rtcConnection = this.rtcConnection = new RTCPeerConnection(iceServer);
// } else {
// rtcConnection = this.rtcConnection = new RTCPeerConnection(iceServer, {
// optional: [{
// googCpuOveruseDetection: false
// }, {
// // DTLS/SRTP is preferred on chrome
// // to interop with Firefox
// // which supports them by default
// DtlsSrtpKeyAgreement: true
// }
// ]
// });
// }
logger.info(`${this.getDate()} setup peerconnection`);
/** 初始化成功的标志位 */
this.inited = true;
let stream = this.tmpStream
if (stream) {
// stream.getTracks().forEach((track) => {
// rtcConnection.addTrack(track, stream)
// })
this.updateStream(stream)
// console.log(`${this.getDate()} attach stream:`, stream, stream.getTracks())
}
// 开启datachannel通道
this.dataChannel = rtcConnection.createDataChannel("ldodo", { negotiated: true });
this.onDataChannel(this.dataChannel);
this.initPeerEvent();
this.rtcStatus = RTC_STATUS['opened']
if (this.isReSetup) return
this.emit('ready', { status: true, url: wss })
// 暂时屏蔽
// this.initStats()
},
// 初始化注册peer系列监听事件
initPeerEvent() {
let rtcConnection = this.rtcConnection, that = this;
// 远端流附加了轨道
rtcConnection.ontrack = function (event) {
let track = event.track
logger.log(`${that.getDate()} on remote track`, track);
};
/** 远端流过来了, 新建video标签显示 */
rtcConnection.onaddstream = function (event) {
that.onRemoteStream(event)
};
rtcConnection.onremovestream = function (e) {
logger.warn(`${that.getDate()} on remove stream`, arguments);
}
/** 设置本地sdp触发本地ice */
rtcConnection.onicecandidate = function (event) {
if (event.candidate) {
// 丢掉TCP,只保留UDP
if (/tcp/.test(event.candidate.candidate)) return
console.log(`${that.getDate()} on local ICE: `, event.candidate);
if (that.ice_completed) return
// that.duoduo_signal.send('candidate', event.candidate);
// 先缓存,在sdp_answer回来之后再发ice_offer
if (that.localOffer) {
that.ice_offer.push(event.candidate)
} else {
that.duoduo_signal.send('candidate', event.candidate);
}
} else {
console.log(`${that.getDate()} onicecandidate end`);
}
};
rtcConnection.onnegotiationneeded = function (event) {
console.log(`${that.getDate()} onnegotiationneeded`);
};
/** 对接收方的数据传递设置 */
rtcConnection.ondatachannel = function (e) {
let id = e.channel.id
let label = e.channel.label
logger.log(`${that.getDate()} on remote data channel ${label} ---> ${id}`);
that.rtcDataChannels[label] = e.channel
logger.log(`${that.getDate()} data channel state: ${e.channel.readyState}`);
// 对接收到的通道进行事件注册!
that.onDataChannel(that.rtcDataChannels[label]);
};
rtcConnection.oniceconnectionstatechange = function () {
let state = rtcConnection.iceConnectionState
logger.info(`${that.getDate()} ice connection state change to: ${state}`);
if (state === 'connected') {
logger.log(`${that.getDate()} rtc connect success`)
that.rtcStatus = RTC_STATUS['connected']
that.emit('connected')
// that.rtcStats.start()
}
if(state === 'closed'){
logger.error(`${that.getDate()} rtc connect fail`)
// that.rtcStats.stop()
}
if (that.dataChannel) {
logger.info(`${that.getDate()} data channel state: ${that.dataChannel.readyState}`);
}
};
},
// 初始化stats
initStats() {
this.rtcStats = new RtcStats({ peer: this.rtcConnection, interval: 10000 })
this.rtcStats.on('stats', function (result) {
// console.log(result)
})
},
// stats数据展示
previewGetStatsResult(result) {
console.log(result)
},
// 真正开始连接
start() {
logger.info(`${this.getDate()} 开始连接, 发出链接邀请`);
let rtcConnection = this.rtcConnection
// let that = this
this.createOffer().catch(err => {
console.error(err)
})
},
/***************************************sdp协议的操作 start*************************************** */
// 发起offer呼叫
createOffer() {
// let that = this
let rtcConnection = this.rtcConnection
let config = {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1,
// voiceActivityDetection: false,
// iceRestart: true
};
logger.warn('\r\n-------------------------ldodo: activity start----------------------------\r\n')
return rtcConnection.createOffer(config).then((_offer) => {
this.localOffer = _offer
// 协议更改,统一H264编解码格式
_offer.sdp = sdpUtil.maybePreferVideoReceiveCodec(_offer.sdp, { videoRecvCodec: 'H264' });
// 测试打印sdp!后期删除1
if (this.debug) {
Mt.alert({
title: 'offer',
msg: `<div style="text-align:left;">${sdp(_offer.sdp)}</div>`,
html: true,
confirmBtnMsg: '好'
});
}
_offer = this.formatLocalDescription('local', _offer)
return this.setLocalDescription('offer', _offer).then(() => {
// console.log(`${this.getDate()} setLocalDescription offer:`, rtcConnection.localDescription)
this.duoduo_signal.send('offer', _offer);
return Promise.resolve()
})
}).catch((error) => {
console.error(`${this.getDate()} An error on startPeerConnection:`, error)
let offer = rtcConnection.localDescription
if (!offer) return Promise.reject('no offer');
return this.setLocalDescription('offer', offer).then(() => {
// console.log(`${this.getDate()} still setLocalDescription offer:`, rtcConnection.localDescription)
this.duoduo_signal.send('offer', offer);
return Promise.resolve()
})
})
},
// 回复应答
createAnswer() {
let that = this
let rtcConnection = this.rtcConnection
return rtcConnection.createAnswer().then((_answer) => {
logger.info(`${that.getDate()} create answer:`, _answer)
// 协议更改,统一H264编解码格式
_answer.sdp = sdpUtil.maybePreferVideoReceiveCodec(_answer.sdp, { videoRecvCodec: 'H264' });
// 改动请见:https://stackoverflow.com/questions/34095194/web-rtc-renegotiation-errors
_answer.sdp = _answer.sdp.replace(/a=setup:active/gi, function (item) {
return 'a=setup:passive'
})
// 测试打印sdp!后期删除1
if (that.debug) {
Mt.alert({
title: 'answer',
msg: `<div style="text-align:left;">${sdp(_answer.sdp)}</div>`,
html: true,
confirmBtnMsg: '好'
});
}
// _answer = this.formatLocalDescription('local', _answer)
if (!_answer) return
return that.setLocalDescription('answer', _answer).then(() => {
// console.log(`${that.getDate()} setLocalDescription answer:`, rtcConnection.localDescription)
that.duoduo_signal.send('answer', _answer);
// check remote stream status
that.checkRemoteStreamStatus()
that.checkICE()
return Promise.resolve();
})
})
},
/**
* 格式化sdp, 在create offer之后, 设置之前格式化
* 主要格式化内容:
* @param {any} localRemote remote/local
* @param {any} data sdp内容
* @returns
*/
formatLocalDescription(localRemote, data) {
let sdp_data = data
let type = sdp_data.type
let sdp_diff
// 远程offer,本地answer
if (type == 'offer' && localRemote === 'remote') {
sdp_diff = this.rtcConnection.localDescription
}
// 本地offer,远程answer
if (type === 'offer' && localRemote === 'local') {
sdp_diff = this.rtcConnection.remoteDescription
}
// 本地answer,远程offer
if (type === 'answer' && localRemote === 'local') {
sdp_diff = this.rtcConnection.remoteDescription
}
let sdp_data_parse = sdpTransform.parse(sdp_data.sdp)
let sdp_diff_parse = sdp_diff && sdpTransform.parse(sdp_diff.sdp)
logger.info('更新前 sdp_data', sdp_data.type, sdp_data_parse)
logger.info('更新前 sdp_diff', sdp_diff && sdp_diff.type, sdp_diff_parse)
//test
// if (true) return data
if (!sdp_data_parse.media) return
// 获取音轨和视轨
let stream = this.rtcConnection.getLocalStreams()
stream = stream[0] || new MediaStream()
let audio = stream.getAudioTracks()[0]
let video = stream.getVideoTracks()[0]
let cname = ''
sdp_data_parse.media.forEach((media, index) => {
media.candidates && delete media.candidates
// offer对ssrc做限制,如果没有视频或者音频,删除ssrc属性(firefox无论有无都有ssrc)
if (media.type === 'audio') {
!audio && delete media.ssrcs && delete media.ssrcGroups && delete media.msid
let tmp = media.ssrcs && media.ssrcs.filter((item)=>{
return item.attribute === 'cname'
})
cname = tmp && tmp[0].value
}
if (media.type === 'video') {
!video && delete media.ssrcs && delete media.ssrcGroups && delete media.msid
}
// 添加带宽限制
// b=AS:800
if (!navigator.mozGetUserMedia) {
media.bandwidth = [{
type: 'AS',
limit: 800
}]
} else {
media.bandwidth = [{
type: 'TIAS',
limit: 800
}]
}
// firefox生成的answer里面针对dataChannel会多一行这个,进行删除
if (media.type === 'application') {
delete media.direction
}
// 针对answer的协议做修改,如果对方要求sendrecv,而自己没有流,则应该为inactive
if (type === 'answer' && sdp_diff_parse) {
let direction_diff = sdp_diff_parse.media[index].direction
if (/(sendrecv|recvonly)/.test(direction_diff)) {
if (media.type === 'audio' && !audio) {
media.direction = 'inactive'
}
if (media.type === 'video' && !video) {
media.direction = 'inactive'
}
}
}
// 针对offer的协议做修改, 根据实际流情况添加ssrc
if(type === 'offer' && media.type === "video"){
if(!video || media.ssrcs) return
media.direction = 'sendrecv'
// 添加ssrc
media.ssrcs = []
let ssrcid = sdpUtil.randomSSRC()
media.ssrcs.push({
attribute:'cname',
id:ssrcid,
value: cname
})
media.ssrcs.push({
attribute:'msid',
id:ssrcid,
value: stream.id + ' ' + video.id
})
media.ssrcs.push({
attribute:'mslabel',
id:ssrcid,
value: stream.id
})
media.ssrcs.push({
attribute:'label',
id:ssrcid,
value:video.id
})
// media.ssrcGroups = []
// media.ssrcGroups.push({
// semantics: 'FID',
// ssrcs: ssrcid
// })
}
})
logger.log('更新后 sdp_data', sdp_data_parse)
sdp_data.sdp = sdpTransform.write(sdp_data_parse)
return sdp_data
},
/**
* 设置本地会话内容sdp
*
* @param {any} type offer还是answer
* @param {any} data sdp内容
* @returns {Promise}
*/
setLocalDescription(type, data) {
let rtcConnection = this.rtcConnection
logger.info(`${this.getDate()} setLocalDescription ${type}:\n`, sdpTransform.parse(data.sdp))
logger.info(`\n`, data.sdp)
return rtcConnection.setLocalDescription(new RTCSessionDescription(data))
},
setRemoteDescription(type, data) {
let rtcConnection = this.rtcConnection
logger.log(`${this.getDate()} setRemoteDescription ${type}:\n`, sdpTransform.parse(data.sdp))
logger.log(`\n`, data.sdp)
return rtcConnection.setRemoteDescription(new RTCSessionDescription(data))
},
/** 将对方加入自己的候选者中 */
onNewPeer(candidate) {
// var candidate = data.data;
logger.log(`${this.getDate()} on remote ICE`, candidate)
this.rtcConnection.addIceCandidate(new RTCIceCandidate(candidate));
},
/** 接收链接邀请,发出响应 */
onOffer(offer) {
logger.warn('\r\n-------------------------ldodo: activity start----------------------------\r\n')
logger.log(`${this.getDate()} on remote offer`, offer);
// 协议更改,统一H264编解码格式
offer.sdp = sdpUtil.maybePreferVideoSendCodec(offer.sdp, { videoRecvCodec: 'H264' });
this.setRemoteDescription('offer', offer).then(() => {
return this.createAnswer()
}).catch((error) => {
console.error(`${this.getDate()} onOffer error:`, error)
})
},
/** 接收响应,设置远程的peer session */
onAnswer(answer) {
logger.info(`${this.getDate()} on remote answer`, answer)
// 协议更改,统一H264编解码格式
answer.sdp = sdpUtil.maybePreferVideoSendCodec(answer.sdp, { videoRecvCodec: 'H264' });
this.formatLocalDescription('remote', answer)
// if (!answer) return
this.setRemoteDescription('answer', answer).then(() => {
this.localOffer = null
this.checkICE()
}).catch(function (e) {
console.error(e);
});
},
/***************************************sdp协议的操作 end*************************************** */
/***************************************媒体流的操作 start*************************************** */
updateStream(stream) {
if (!stream) return
if (stream.stream) stream = stream.stream
let rtcConnection = this.rtcConnection
let rtcStream = this.stream
var audioOld, videoOld, audio, video
audio = stream.getAudioTracks()[0]
video = stream.getVideoTracks()[0]
let tmp = rtcConnection.getLocalStreams()
tmp = tmp.length > 0 ? tmp[0] : null
logger.info('当前rtc 流id 和 轨道数目', tmp && tmp.id, (tmp && tmp.getTracks().length))
tmp && tmp.getTracks().forEach(item => {
console.log(' > 轨道id:', `${item.kind}:${item.id}`)
})
// 第一次附加
if (!tmp) {
// rtcStream = new MediaStream()
// rtcConnection.addStream(rtcStream)
this.addAudioTrack(stream)
this.addVideoTrack(stream)
tmp = rtcConnection.getLocalStreams()
tmp = tmp.length > 0 ? tmp[0] : null
logger.info('更新后rtc 流id 和 轨道数目', tmp && tmp.id, (tmp && tmp.getTracks().length))
tmp && tmp.getTracks().forEach(item => {
console.log(' > 轨道id:', `${item.kind} --> ${item.id}`)
})
window.rtcLocalStream = tmp
if (this.rtcStatus === RTC_STATUS['connected']) {
this.createOffer()
}
// window.myRtcStream = this.stream
return
}
// 先取所有轨道
audioOld = rtcStream && rtcStream.getAudioTracks()[0]
videoOld = rtcStream && rtcStream.getVideoTracks()[0]
audio = stream.getAudioTracks()[0]
video = stream.getVideoTracks()[0]
// 新加轨道
if (!audioOld) {
if (audio) {
this.addAudioTrack(stream)
}
}
if (!videoOld) {
if (video) {
this.addVideoTrack(stream)
}
}
// 更新音频轨道
if (audioOld) {
// 移除轨道
if (!audio) {
this.removeAudioTrack()
} else {
// 更新轨道
audio !== audioOld && this.updateAudioTrack(stream)
}
}
// 更新视频轨道
if (videoOld) {
// 移除轨道
if (!video) {
this.removeVideoTrack()
} else {
video !== videoOld && this.updateVideoTrack(stream)
}
}
tmp = rtcConnection.getLocalStreams()
tmp = tmp.length > 0 ? tmp[0] : null
console.log('更新后rtc 流id 和 轨道数目', tmp && tmp.id, (tmp && tmp.getTracks().length))
tmp && tmp.getTracks().forEach(item => {
console.log(' > 轨道id:', `${item.kind} --> ${item.id}`)
})
window.rtcLocalStream = tmp
if (this.rtcStatus === RTC_STATUS['connected']) {
this.createOffer()
}
},
// 移除视频
removeVideoTrack() {
let rtcConnection = this.rtcConnection
let rtcStream = this.stream
if (!rtcStream) return
let videoTrack = rtcStream.getVideoTracks()[0]
let isFirefox = !!navigator.mozGetUserMedia
if (!videoTrack) {
console.warn('removeVideo() | no video track')
return Promise.reject(new Error('no video track'))
}
// videoTrack.stop()
rtcStream.removeTrack(videoTrack)
// New API. 为啥验证不用rtcConnection.removeTrack?, chrome也支持,只不过表现很怪异
if (isFirefox) {
let sender
for (sender of rtcConnection.getSenders()) {
if (sender.track === videoTrack) break
}
rtcConnection.removeTrack(sender)
} else {
// Old API.
// rtcConnection.removeStream(rtcStream)
// rtcConnection.addStream(rtcStream)
}
},
// 添加视频
addVideoTrack(newStream) {
let rtcConnection = this.rtcConnection
let rtcStream = this.stream
let rtcStreamUpdate = rtcStream
let newVideoTrack = newStream.getVideoTracks()[0]
let isFirefox = !!navigator.mozGetUserMedia
if (!newVideoTrack) return
if (!rtcStream) {
rtcStream = new MediaStream()
this.stream = rtcStream
}
rtcStream.addTrack(newVideoTrack)
// New API. 为啥验证不用rtcConnection.addTrack?, chrome也支持,只不过表现很怪异
if (isFirefox) {
rtcConnection.addTrack(newVideoTrack, rtcStream)
} else {
// Old API.
!rtcStreamUpdate && rtcConnection.addStream(rtcStream)
}
},
// 更新视频
updateVideoTrack(newStream) {
let rtcConnection = this.rtcConnection
let rtcStream = this.stream
if (!rtcStream) return
let isFirefox = !!navigator.mozGetUserMedia
// For Chrome (old WenRTC API).
// Replace the track (so new SSRC) and renegotiate.
if (!isFirefox) {
this.removeVideoTrack(true)
return this.addVideoTrack()
}
// For Firefox (modern WebRTC API).
// Avoid renegotiation.
let newVideoTrack = newStream.getVideoTracks()[0]
let oldVideoTrack = rtcStream.getVideoTracks()[0]
let sender
for (sender of rtcConnection.getSenders()) {
if (sender.track === oldVideoTrack) break
}
sender.replaceTrack(newVideoTrack)
rtcStream.removeTrack(oldVideoTrack)
// oldVideoTrack.stop()
rtcStream.addTrack(newVideoTrack)
},
// 移除音频
removeAudioTrack() {
let rtcConnection = this.rtcConnection
let rtcStream = this.stream
let audioTrack = rtcStream.getAudioTracks()[0]
let isFirefox = !!navigator.mozGetUserMedia
if (!audioTrack) {
console.warn('removeAudio() | no audio track')
return Promise.reject(new Error('no audio track'))
}
// audioTrack.stop()
rtcStream.removeTrack(audioTrack)
// New API. 为啥验证不用rtcConnection.removeTrack?, chrome也支持,只不过表现很怪异
if (isFirefox) {
let sender
for (sender of rtcConnection.getSenders()) {
if (sender.track === audioTrack) break
}
rtcConnection.removeTrack(sender)
} else {
// Old API.
// rtcConnection.removeStream(rtcStream)
// rtcConnection.addStream(rtcStream)
}
},
// 添加音频
addAudioTrack(newStream) {
let rtcConnection = this.rtcConnection
let rtcStream = this.stream
let rtcStreamUpdate = rtcStream
let isFirefox = !!navigator.mozGetUserMedia
let newAudioTrack = newStream.getAudioTracks()[0]
if (!newAudioTrack) return
if (!rtcStream) {
rtcStream = new MediaStream()
this.stream = rtcStream
}
rtcStream.addTrack(newAudioTrack)
// New API. 为啥验证不用rtcConnection.addTrack?, chrome也支持,只不过表现很怪异
if (isFirefox) {
rtcConnection.addTrack(newAudioTrack, rtcStream)
} else {
// Old API.
!rtcStreamUpdate && rtcConnection.addStream(rtcStream)
}
},
// 更新音频
updateAudioTrack(newStream) {
let rtcConnection = this.rtcConnection
let rtcStream = this.stream
let isFirefox = !!navigator.mozGetUserMedia
if (!rtcStream) return
// For Chrome (old WenRTC API).
// Replace the track (so new SSRC) and renegotiate.
if (!isFirefox) {
this.removeAudioTrack(true)
return this.addAudioTrack()
}
// For Firefox (modern WebRTC API).
// Avoid renegotiation.
let newAudioTrack = newStream.getAudioTracks()[0]
let oldAudioTrack = rtcStream.getAudioTracks()[0]
let sender
for (sender of rtcConnection.getSenders()) {
if (sender.track === oldAudioTrack) break
}
sender.replaceTrack(newAudioTrack)
rtcStream.removeTrack(oldAudioTrack)
// oldAudioTrack.stop()
rtcStream.addTrack(newAudioTrack)
},
/***************************************媒体流的操作 end*************************************** */
// 远程流监控
onRemoteStream(event) {
let stream = event.stream
window.rtcRemoteStream = stream
if (!stream) return
logger.log(`${this.getDate()} get remote stream`, stream);
stream && stream.getTracks().forEach(item => {
console.log(' > 轨道id:', `${item.kind} --> ${item.id}`)
})
this.emit('stream', stream)
stream.onaddtrack = e => {
logger.log(`${this.getDate()} on add track`, e)
}
stream.onremovetrack = e => {
logger.warn(`${this.getDate()} on remove track`, e)
}
},
// 每当对方sdp协议发生变动,主动检查远程媒体流的状态,该方法用于修复firefox无法获知removeTrack事件
// Hack for Firefox bug:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1347578
checkRemoteStreamStatus() {
},
// 为了保证offer / answer / iceoffer / iceanswer的顺序,这里拎出来处理
checkICE() {