-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
OvenLiveKit.js
777 lines (533 loc) · 20.5 KB
/
OvenLiveKit.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
const OvenLiveKit = {};
const logHeader = 'OvenLiveKit.js :';
const logEventHeader = 'OvenLiveKit.js ====';
// private methods
function sendMessage(webSocket, message) {
if (webSocket) {
webSocket.send(JSON.stringify(message));
}
}
function generateDomainFromUrl(url) {
let result = '';
let match;
if (match = url.match(/^(?:wss?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n\?\=]+)/im)) {
result = match[1];
}
return result;
}
function findIp(string) {
let result = '';
let match;
if (match = string.match(new RegExp('\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b', 'gi'))) {
result = match[0];
}
return result;
}
function checkIOSVersion() {
var agent = window.navigator.userAgent,
start = agent.indexOf('OS ');
if ((agent.indexOf('iPhone') > -1 || agent.indexOf('iPad') > -1) && start > -1) {
return window.Number(agent.substr(start + 3, 3).replace('_', '.'));
}
return 0;
}
function getFormatNumber(sdp, format) {
const lines = sdp.split('\r\n');
let formatNumber = -1;
for (let i = 0; i < lines.length - 1; i++) {
lines[i] = lines[i].toLowerCase();
if (lines[i].indexOf('a=rtpmap') > -1 && lines[i].indexOf(format.toLowerCase()) > -1) {
// parsing "a=rtpmap:100 H264/90000" line
formatNumber = lines[i].split(' ')[0].split(':')[1];
break;
}
}
return formatNumber;
}
function removeFormat(sdp, formatNumber) {
let newLines = [];
let lines = sdp.split('\r\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].indexOf('m=video') === 0) {
newLines.push(lines[i].replace(' ' + formatNumber + '', ''));
} else if (lines[i].indexOf(formatNumber + '') > -1) {
} else {
newLines.push(lines[i]);
}
}
return newLines.join('\r\n')
}
async function getStreamForDeviceCheck() {
// High resolution video constraints makes browser to get maximum resolution of video device.
const constraints = {
audio: { deviceId: undefined },
video: { deviceId: undefined, width: 1920, height: 1080 }
};
return await navigator.mediaDevices.getUserMedia(constraints);
}
async function getDevices() {
return await navigator.mediaDevices.enumerateDevices();
}
function gotDevices(deviceInfos) {
let devices = {
'audioinput': [],
'audiooutput': [],
'videoinput': [],
'other': [],
};
for (let i = 0; i !== deviceInfos.length; ++i) {
const deviceInfo = deviceInfos[i];
let info = {};
info.deviceId = deviceInfo.deviceId;
if (deviceInfo.kind === 'audioinput') {
info.label = deviceInfo.label || `microphone ${devices.audioinput.length + 1}`;
devices.audioinput.push(info);
} else if (deviceInfo.kind === 'audiooutput') {
info.label = deviceInfo.label || `speaker ${devices.audiooutput.length + 1}`;
devices.audiooutput.push(info);
} else if (deviceInfo.kind === 'videoinput') {
info.label = deviceInfo.label || `camera ${devices.videoinput.length + 1}`;
devices.videoinput.push(info);
} else {
info.label = deviceInfo.label || `other ${devices.other.length + 1}`;
devices.other.push(info);
}
}
return devices;
}
function initConfig(instance, options) {
instance.stream = null;
instance.webSocket = null;
instance.peerConnection = null;
instance.connectionConfig = {};
instance.status = 'creating';
instance.videoElement = null;
instance.connectionUrl = null;
if (options && options.callbacks) {
instance.callbacks = options.callbacks;
} else {
instance.callbacks = {};
}
}
function addMethod(instance) {
function errorHandler(error) {
if (instance.callbacks.error) {
instance.callbacks.error(error);
}
}
function getUserMedia(constraints) {
if (!constraints) {
constraints = {
video: {
deviceId: undefined
},
audio: {
deviceId: undefined
}
};
}
console.info(logHeader, 'Requested Constraint To Input Devices', constraints);
return navigator.mediaDevices.getUserMedia(constraints)
.then(function (stream) {
console.info(logHeader, 'Received Media Stream From Input Device', stream);
instance.stream = stream;
let elem = instance.videoElement;
// Attach stream to video element when video element is provided.
if (elem) {
elem.srcObject = stream;
elem.onloadedmetadata = function (e) {
elem.play();
};
}
return new Promise(function (resolve) {
resolve(stream);
});
})
.catch(function (error) {
console.error(logHeader, 'Can\'t Get Media Stream From Input Device', error);
errorHandler(error);
return new Promise(function (resolve, reject) {
reject(error);
});
});
}
function getDisplayMedia(constraints) {
if (!constraints) {
constraints = {};
}
console.info(logHeader, 'Requested Constraint To Display', constraints);
return navigator.mediaDevices.getDisplayMedia(constraints)
.then(function (stream) {
console.info(logHeader, 'Received Media Stream From Display', stream);
instance.stream = stream;
let elem = instance.videoElement;
// Attach stream to video element when video element is provided.
if (elem) {
elem.srcObject = stream;
elem.onloadedmetadata = function (e) {
elem.play();
};
}
return new Promise(function (resolve) {
resolve(stream);
});
})
.catch(function (error) {
console.error(logHeader, 'Can\'t Get Media Stream From Display', error);
errorHandler(error);
return new Promise(function (resolve, reject) {
reject(error);
});
});
}
// From https://webrtchacks.com/limit-webrtc-bandwidth-sdp/
function setBitrateLimit(sdp, media, bitrate) {
let lines = sdp.split('\r\n');
let line = -1;
for (let i = 0; i < lines.length; i++) {
if (lines[i].indexOf('m=' + media) === 0) {
line = i;
break;
}
}
if (line === -1) {
// Could not find the m line for media
return sdp;
}
// Pass the m line
line++;
// Skip i and c lines
while (lines[line].indexOf('i=') === 0 || lines[line].indexOf('c=') === 0) {
line++;
}
// If we're on a b line, replace it
if (lines[line].indexOf('b') === 0) {
lines[line] = 'b=AS:' + bitrate;
return lines.join('\r\n');
}
// Add a new b line
let newLines = lines.slice(0, line)
newLines.push('b=AS:' + bitrate)
newLines = newLines.concat(lines.slice(line, lines.length))
return newLines.join('\r\n')
}
function initWebSocket(connectionUrl) {
if (!connectionUrl) {
errorHandler('connectionUrl is required');
return;
}
instance.connectionUrl = connectionUrl;
let webSocket = null;
try {
webSocket = new WebSocket(connectionUrl);
} catch (error) {
errorHandler(error);
}
instance.webSocket = webSocket;
webSocket.onopen = function () {
// Request offer at the first time.
sendMessage(webSocket, {
command: 'request_offer'
});
};
webSocket.onmessage = function (e) {
let message = JSON.parse(e.data);
if (message.error) {
console.error('webSocket.onmessage', message.error);
errorHandler(message.error);
}
if (message.command === 'offer') {
// OME returns offer. Start create peer connection.
createPeerConnection(
message.id,
message.peer_id,
message.sdp,
message.candidates,
message.ice_servers
);
}
};
webSocket.onerror = function (error) {
console.error('webSocket.onerror', error);
errorHandler(error);
};
webSocket.onclose = function (e) {
if (!instance.removing) {
if (instance.callbacks.connectionClosed) {
instance.callbacks.connectionClosed('websocket', e);
}
}
};
}
function appendFmtp(sdp) {
const fmtpStr = instance.connectionConfig.sdp.appendFmtp;
const lines = sdp.split('\r\n');
const payloads = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].indexOf('m=video') === 0) {
let tokens = lines[i].split(' ')
for (let j = 3; j < tokens.length; j++) {
payloads.push(tokens[j]);
}
break;
}
}
for (let i = 0; i < payloads.length; i++) {
let fmtpLineFound = false;
for (let j = 0; j < lines.length; j++) {
if (lines[j].indexOf('a=fmtp:' + payloads[i]) === 0) {
fmtpLineFound = true;
lines[j] += ';' + fmtpStr;
}
}
if (!fmtpLineFound) {
for (let j = 0; j < lines.length; j++) {
if (lines[j].indexOf('a=rtpmap:' + payloads[i]) === 0) {
lines[j] += '\r\na=fmtp:' + payloads[i] + ' ' + fmtpStr;
}
}
}
}
return lines.join('\r\n')
}
function createPeerConnection(id, peerId, offer, candidates, iceServers) {
let peerConnectionConfig = {};
if (instance.connectionConfig.iceServers) {
// first priority using ice servers from local config.
peerConnectionConfig.iceServers = instance.connectionConfig.iceServers;
if (instance.connectionConfig.iceTransportPolicy) {
peerConnectionConfig.iceTransportPolicy = instance.connectionConfig.iceTransportPolicy;
}
} else if (iceServers) {
// second priority using ice servers from ome and force using TCP
peerConnectionConfig.iceServers = [];
for (let i = 0; i < iceServers.length; i++) {
let iceServer = iceServers[i];
let regIceServer = {};
regIceServer.urls = iceServer.urls;
let hasWebSocketUrl = false;
let webSocketUrl = generateDomainFromUrl(instance.connectionUrl);
for (let j = 0; j < regIceServer.urls.length; j++) {
let serverUrl = regIceServer.urls[j];
if (serverUrl.indexOf(webSocketUrl) > -1) {
hasWebSocketUrl = true;
break;
}
}
if (!hasWebSocketUrl) {
if (regIceServer.urls.length > 0) {
let cloneIceServer = regIceServer.urls[0];
let ip = findIp(cloneIceServer);
if (webSocketUrl && ip) {
regIceServer.urls.push(cloneIceServer.replace(ip, webSocketUrl));
}
}
}
regIceServer.username = iceServer.user_name;
regIceServer.credential = iceServer.credential;
peerConnectionConfig.iceServers.push(regIceServer);
}
peerConnectionConfig.iceTransportPolicy = 'relay';
} else {
// last priority using default ice servers.
if (instance.iceTransportPolicy) {
peerConnectionConfig.iceTransportPolicy = instance.iceTransportPolicy;
}
}
let advancedSetting = {
optional: [
{
googHighStartBitrate: {
exact: !0
}
},
{
googPayloadPadding: {
exact: !0
}
},
{
googScreencastMinBitrate: {
exact: 500
}
},
{
enableDscp: {
exact: true
}
}
]
};
console.info(logHeader, 'Create Peer Connection With Config', peerConnectionConfig);
let peerConnection = new RTCPeerConnection(peerConnectionConfig);
instance.peerConnection = peerConnection;
// set local stream
instance.stream.getTracks().forEach(function (track) {
console.info(logHeader, 'Add Track To Peer Connection', track);
peerConnection.addTrack(track, instance.stream);
});
if (checkIOSVersion() >= 15) {
const formatNumber = getFormatNumber(offer.sdp, 'H264');
if (formatNumber > 0) {
offer.sdp = removeFormat(offer.sdp, formatNumber);
}
}
if (instance.connectionConfig.maxVideoBitrate) {
// if bandwith limit is set. modify sdp from ome to limit acceptable bandwidth of ome
offer.sdp = setBitrateLimit(offer.sdp, 'video', instance.connectionConfig.maxVideoBitrate);
}
if (instance.connectionConfig.sdp && instance.connectionConfig.sdp.appendFmtp) {
offer.sdp = appendFmtp(offer.sdp);
}
peerConnection.setRemoteDescription(new RTCSessionDescription(offer))
.then(function () {
peerConnection.createAnswer()
.then(function (answer) {
console.log(logHeader, 'Answer')
console.log(answer.sdp)
if (checkIOSVersion() >= 15) {
const formatNumber = getFormatNumber(answer.sdp, 'H264');
if (formatNumber > 0) {
answer.sdp = removeFormat(answer.sdp, formatNumber);
}
}
if (instance.connectionConfig.sdp && instance.connectionConfig.sdp.appendFmtp) {
answer.sdp = appendFmtp(answer.sdp);
}
peerConnection.setLocalDescription(answer)
.then(function () {
sendMessage(instance.webSocket, {
id: id,
peer_id: peerId,
command: 'answer',
sdp: answer
});
})
.catch(function (error) {
console.error('peerConnection.setLocalDescription', error);
errorHandler(error);
});
})
.catch(function (error) {
console.error('peerConnection.createAnswer', error);
errorHandler(error);
});
})
.catch(function (error) {
console.error('peerConnection.setRemoteDescription', error);
errorHandler(error);
});
if (candidates) {
addIceCandidate(peerConnection, candidates);
}
peerConnection.onicecandidate = function (e) {
if (e.candidate && e.candidate.candidate) {
console.info(logHeader, 'Candidate Sent', '\n', e.candidate.candidate, '\n', e);
sendMessage(instance.webSocket, {
id: id,
peer_id: peerId,
command: 'candidate',
candidates: [e.candidate]
});
}
};
peerConnection.oniceconnectionstatechange = function (e) {
let state = peerConnection.iceConnectionState;
if (instance.callbacks.iceStateChange) {
console.info(logHeader, 'ICE State', '[' + state + ']');
instance.callbacks.iceStateChange(state);
}
if (state === 'connected') {
if (instance.callbacks.connected) {
console.info(logHeader, 'Iceconnection Connected', e);
instance.callbacks.connected(e);
}
}
if (state === 'failed' || state === 'disconnected' || state === 'closed') {
if (instance.callbacks.connectionClosed) {
console.error(logHeader, 'Iceconnection Closed', e);
instance.callbacks.connectionClosed('ice', e);
}
}
}
}
function addIceCandidate(peerConnection, candidates) {
for (let i = 0; i < candidates.length; i++) {
if (candidates[i] && candidates[i].candidate) {
let basicCandidate = candidates[i];
peerConnection.addIceCandidate(new RTCIceCandidate(basicCandidate))
.then(function () {
})
.catch(function (error) {
console.error('peerConnection.addIceCandidate', error);
errorHandler(error);
});
}
}
}
// instance methods
instance.attachMedia = function (videoElement) {
instance.videoElement = videoElement;
};
instance.getUserMedia = function (constraints) {
return getUserMedia(constraints);
};
instance.getDisplayMedia = function (constraints) {
return getDisplayMedia(constraints);
};
instance.startStreaming = function (connectionUrl, connectionConfig) {
console.info(logEventHeader, 'Start Streaming');
if (connectionConfig) {
instance.connectionConfig = connectionConfig;
}
initWebSocket(connectionUrl);
};
instance.remove = function () {
instance.removing = true;
// first release peer connection with ome
if (instance.peerConnection) {
// remove tracks from peer connection
instance.peerConnection.getSenders().forEach(function (sender) {
instance.peerConnection.removeTrack(sender);
});
instance.peerConnection.close();
instance.peerConnection = null;
delete instance.peerConnection;
}
// release video, audio stream
if (instance.stream) {
instance.stream.getTracks().forEach(track => {
track.stop();
instance.stream.removeTrack(track);
});
if (instance.videoElement) {
instance.videoElement.srcObject = null;
}
instance.stream = null;
delete instance.stream;
}
// release websocket
if (instance.webSocket) {
instance.webSocket.close();
instance.webSocket = null;
delete instance.webSocket;
}
instance.status = 'removed';
console.info(logEventHeader, 'Removed');
};
}
// static methods
OvenLiveKit.create = function (options) {
console.info(logEventHeader, 'Create WebRTC Input v1.0.2');
let instance = {};
instance.removing = false;
initConfig(instance, options);
addMethod(instance);
return instance;
};
OvenLiveKit.getDevices = async function () {
await getStreamForDeviceCheck();
const deviceInfos = await getDevices();
return gotDevices(deviceInfos)
};
export default OvenLiveKit;