-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathviewer.js
1188 lines (1058 loc) · 52.8 KB
/
viewer.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
/**
* This file demonstrates the process of starting WebRTC streaming using a KVS Signaling Channel.
*/
const viewer = {};
//globals for DQP metrics and test
const profilingTestLength = 20;
const DQPtestLength = 10; //test time in seconds
let viewerButtonPressed = 0;
let initialDate = 0;
let statStartTime = 0;
let chart = {};
let vTimeStampPrev = 0;
let aTimeStampPrev = 0;
let vBytesPrev = 0;
let vFDroppedPrev = 0;
let aBytesPrev = 0;
let profilingStartTime = 0;
let statStartDate = 0;
let rttSum = 0;
let vjitterSum = 0;
let ajitterSum = 0;
let framerateSum = 0;
let framedropPerSum = 0;
let vBitrateSum = 0;
let aBitrateSum = 0;
let count = 0;
let testAvgRTT = 0;
let testAvgFPS = 0;
let testAvgDropPer = 0;
let testAvgVbitrate = 0;
let testAvgVjitter = 0;
let testAvgAbitrate = 0;
let testAvgAjitter = 0;
let decodedFPSArray = [];
let droppedFramePerArray = [];
let videoBitRateArray = [];
let audioRateArray = [];
let timeArray = [];
let chartHeight = 0;
let signalingSetUpTime = 0;
let timeToSetUpViewerMedia = 0;
let timeToFirstFrameFromOffer = 0;
let timeToFirstFrameFromViewerStart = 0;
let metrics = {
viewer: {
waitTime: {
name: 'viewer-waiting-for-master',
startTime: '',
endTime: '',
tooltip: 'Time duration the viewer was waiting for the master to start (time to start the SDK after the viewer signaling channel was connected)',
color: 'yellow',
},
signaling: {
name: 'signaling-viewer',
startTime: '',
endTime: '',
tooltip: 'Time taken to establish a signaling connection on the viewer-side',
color: '#F44336',
},
setupMediaPlayer: {
name: 'setup-media-player-viewer',
startTime: '',
endTime: '',
tooltip: 'Time taken to setup a media player on the viewer-side by seeking permissions for mic / camera (if needed), fetch tracks from the same and add them to the peer connection',
color: '#9575CD',
},
offAnswerTime: {
name: 'sdp-exchange-viewer',
startTime: '',
endTime: '',
tooltip: 'Time taken to send an offer and receive a response',
color: '#FF6F00',
},
describeChannel: {
name: 'signaling-viewer-describe-channel',
startTime: '',
endTime: '',
tooltip: 'Time taken for the API call to describeSignalingChannel on the viewer',
color: '#EF9A9A',
},
describeMediaStorageConfiguration: {
name: 'signaling-viewer-describe-media-storage-config',
startTime: '',
endTime: '',
tooltip: 'Time taken for the API call to describeSignalingChannel on the viewer',
color: '#EF9A9A',
},
channelEndpoint: {
name: 'signaling-viewer-get-signaling-channel-endpoint',
startTime: '',
endTime: '',
tooltip: 'Time taken for the API call to getSignalingChannelEndpoint on the viewer',
color: '#EF9A9A',
},
iceServerConfig: {
name: 'signaling-viewer-get-ice-server-config',
startTime: '',
endTime: '',
tooltip: 'Time taken for the API call to getIceServerConfig on the viewer',
color: '#EF9A9A',
},
signConnectAsViewer: {
name: 'sign-connect-as-viewer',
startTime: '',
endTime: '',
tooltip: 'Time taken to sign the websocket request via connectAsViewer',
color: '#EF9A9A',
},
connectAsViewer: {
name: 'signaling-connect-as-viewer',
startTime: '',
endTime: '',
tooltip: 'Time taken to open the websocket via connectAsViewer',
color: '#EF9A9A',
},
iceGathering: {
name: 'ice-gathering-viewer',
startTime: '',
endTime: '',
tooltip: 'Time taken to gather all ice candidates on the viewer',
color: '#90CAF9',
},
peerConnection: {
name: 'pc-establishment-viewer',
startTime: '',
endTime: '',
tooltip: 'Time taken to establish the peer connection on the viewer',
color: '#2196F3',
},
ttffAfterPc: {
name: 'ttff-after-pc-viewer',
startTime: '',
endTime: '',
tooltip: 'Time to first frame after the viewer\'s peer connection has been established',
color: '#2196F3',
},
ttff: {
name: 'ttff',
startTime: '',
endTime: '',
tooltip: 'Time to first frame since the viewer button was clicked',
color: '#4CAF50',
},
dataChannel: {
name: 'datachannel-viewer',
startTime: '',
endTime: '',
tooltip: 'Time taken to send a message to the master and receive a response back',
color: '#4CAF50',
}
},
master: {
waitTime: {
name: 'master-waiting-for-viewer',
startTime: '',
endTime: '',
tooltip: 'Time duration the master was waiting for the viewer to start (time to click the button after the master signaling channel was connected)',
color: 'yellow',
},
signaling: {
name: 'signaling-master',
startTime: '',
endTime: '',
tooltip: 'Time taken to establish a signaling connection on the master-side',
color: '#F44336',
},
offAnswerTime: {
name: 'sdp-exchange-master',
startTime: '',
endTime: '',
tooltip: 'Time taken to respond to an offer from the viewer with an answer',
color: '#FF6F00',
},
describeChannel: {
name: 'signaling-master-describe-channel',
startTime: '',
endTime: '',
tooltip: 'Time taken for the API call to desribeSignalingChannel on the master',
color: '#EF9A9A',
},
channelEndpoint: {
name: 'signaling-master-get-signaling-channel-endpoint',
startTime: '',
endTime: '',
tooltip: 'Time taken for the API call to getSignalingChannelEndpoint on the master',
color: '#EF9A9A',
},
iceServerConfig: {
name: 'signaling-master-get-ice-server-config',
startTime: '',
endTime: '',
tooltip: 'Time taken for the API call to getIceServerConfig on the master',
color: '#EF9A9A',
},
getToken: {
name: 'signaling-master-get-token',
startTime: '',
endTime: '',
tooltip: 'Time taken for the getToken call on the master',
color: '#EF9A9A',
},
createChannel: {
name: 'signaling-master-create-channel',
startTime: '',
endTime: '',
tooltip: 'Time taken createChannel API call on the master',
color: '#EF9A9A',
},
connectAsMaster: {
name: 'signaling-master-connect',
startTime: '',
endTime: '',
tooltip: 'Time taken for the signaling connect on the master',
color: '#EF9A9A',
},
iceGathering: {
name: 'ice-gathering-master',
startTime: '',
endTime: '',
tooltip: 'Time taken to gather all ice candidates on the master',
color: '#90CAF9',
},
peerConnection: {
name: 'pc-establishment-master',
startTime: '',
endTime: '',
tooltip: 'Time taken to establish the peer connection on the master',
color: '#2196F3',
},
dataChannel: {
name: 'datachannel-master',
startTime: '',
endTime: '',
tooltip: 'Time taken to send a message to the viewer and receive a response back',
color: '#4CAF50',
},
ttffAfterPc: {
name: 'ttff-after-pc-master',
startTime: '',
endTime: '',
tooltip: 'Time to first frame after the master\'s peer connection has been established',
color: '#2196F3',
}
}
};
let dataChannelLatencyCalcMessage = {
'content': 'Opened data channel by viewer',
'firstMessageFromViewerTs': '',
'firstMessageFromMasterTs': '',
'secondMessageFromViewerTs': '',
'secondMessageFromMasterTs': '',
'lastMessageFromViewerTs': ''
}
async function startViewer(localView, remoteView, formValues, onStatsReport, remoteMessage) {
try {
console.log('[VIEWER] Client id is:', formValues.clientId);
viewerButtonPressed = new Date();
if (formValues.enableProfileTimeline) {
setTimeout(profilingCalculations, profilingTestLength * 1000);
}
viewer.localView = localView;
viewer.remoteView = remoteView;
viewer.remoteView.addEventListener('loadeddata', () => {
metrics.viewer.ttff.endTime = Date.now();
if (formValues.enableProfileTimeline) {
metrics.viewer.ttffAfterPc.endTime = metrics.viewer.ttff.endTime;
metrics.master.ttffAfterPc.endTime = metrics.viewer.ttff.endTime;
// if the ice-gathering on the master side is not complete by the time the metrics are sent, the endTime > startTime
// in order to plot it, we can show it as an ongoing process
if (metrics.master.iceGathering.startTime > metrics.master.iceGathering.endTime) {
metrics.master.iceGathering.endTime = metrics.viewer.ttff.endTime;
}
}
if(formValues.enableDQPmetrics) {
timeToFirstFrameFromOffer = metrics.viewer.ttff.endTime - metrics.viewer.offAnswerTime.startTime;
timeToFirstFrameFromViewerStart = metrics.viewer.ttff.endTime - viewerButtonPressed.getTime();
}
});
if (formValues.enableProfileTimeline) {
metrics.viewer.ttff.startTime = viewerButtonPressed.getTime();
metrics.master.waitTime.endTime = viewerButtonPressed.getTime();
}
if (formValues.enableDQPmetrics) {
console.log('[WebRTC] DQP METRICS TEST STARTED: ', viewerButtonPressed);
let htmlString = '<table><tr><strong><FONT COLOR=RED>Connecting to MASTER...</FONT></strong></tr></table>';
//update the page divs
$('#dqp-test')[0].innerHTML = htmlString;
htmlString = ' ';
$('#webrtc-live-stats')[0].innerHTML = htmlString;
decodedFPSArray = [];
droppedFramePerArray = [];
videoBitRateArray = [];
audioRateArray = [];
timeArray = [];
chart = new Chart('metricsChart', {
type: 'line',
data: {
labels: timeArray,
datasets: [
{
label: 'Decoded FPS',
borderColor: 'blue',
backgroundColor: 'blue',
fill: false,
data: decodedFPSArray,
},
{
label: 'Frames Dropped (%)',
borderColor: 'red',
backgroundColor: 'red',
fill: false,
data: droppedFramePerArray,
},
{
label: 'Video Bitrate (kbps)',
borderColor: 'green',
backgroundColor: 'green',
fill: false,
data: videoBitRateArray,
},
{
label: 'Audio Bitrate (kbps)',
borderColor: 'orange',
backgroundColor: 'orange',
fill: false,
data: audioRateArray,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
},
},
},
});
}
metrics.viewer.signaling.startTime = Date.now();
// Create KVS client
const kinesisVideoClient = new AWS.KinesisVideo({
region: formValues.region,
accessKeyId: formValues.accessKeyId,
secretAccessKey: formValues.secretAccessKey,
sessionToken: formValues.sessionToken,
endpoint: formValues.endpoint,
correctClockSkew: true,
});
// Get signaling channel ARN
metrics.viewer.describeChannel.startTime = Date.now();
const describeSignalingChannelResponse = await kinesisVideoClient
.describeSignalingChannel({
ChannelName: formValues.channelName,
})
.promise();
metrics.viewer.describeChannel.endTime = Date.now();
const channelARN = describeSignalingChannelResponse.ChannelInfo.ChannelARN;
console.log('[VIEWER] Channel ARN:', channelARN);
if (formValues.ingestMedia) {
console.log('[VIEWER] Determining whether this signaling channel is in media ingestion mode.');
metrics.viewer.describeMediaStorageConfiguration.startTime = Date.now();
const mediaStorageConfiguration = await kinesisVideoClient
.describeMediaStorageConfiguration({
ChannelName: formValues.channelName,
})
.promise();
metrics.viewer.describeMediaStorageConfiguration.endTime = Date.now();
if (mediaStorageConfiguration.MediaStorageConfiguration.Status !== 'DISABLED') {
console.error(
'[VIEWER] Media storage and ingestion is ENABLED for this channel. Only the WebRTC Ingestion and Storage peer can join as a viewer.',
);
return;
}
} else {
console.log('[VIEWER] Not using media ingestion feature');
}
// Get signaling channel endpoints
metrics.viewer.channelEndpoint.startTime = Date.now();
const getSignalingChannelEndpointResponse = await kinesisVideoClient
.getSignalingChannelEndpoint({
ChannelARN: channelARN,
SingleMasterChannelEndpointConfiguration: {
Protocols: ['WSS', 'HTTPS'],
Role: KVSWebRTC.Role.VIEWER,
},
})
.promise();
metrics.viewer.channelEndpoint.endTime = Date.now();
const endpointsByProtocol = getSignalingChannelEndpointResponse.ResourceEndpointList.reduce((endpoints, endpoint) => {
endpoints[endpoint.Protocol] = endpoint.ResourceEndpoint;
return endpoints;
}, {});
console.log('[VIEWER] Endpoints:', endpointsByProtocol);
const kinesisVideoSignalingChannelsClient = new AWS.KinesisVideoSignalingChannels({
region: formValues.region,
accessKeyId: formValues.accessKeyId,
secretAccessKey: formValues.secretAccessKey,
sessionToken: formValues.sessionToken,
endpoint: endpointsByProtocol.HTTPS,
correctClockSkew: true,
});
// Get ICE server configuration
metrics.viewer.iceServerConfig.startTime = Date.now();
const getIceServerConfigResponse = await kinesisVideoSignalingChannelsClient
.getIceServerConfig({
ChannelARN: channelARN,
})
.promise();
metrics.viewer.iceServerConfig.endTime = Date.now();
const iceServers = [];
// Don't add stun if user selects TURN only or NAT traversal disabled
if (!formValues.natTraversalDisabled && !formValues.forceTURN) {
iceServers.push({ urls: `stun:stun.kinesisvideo.${formValues.region}.amazonaws.com:443` });
}
// Don't add turn if user selects STUN only or NAT traversal disabled
if (!formValues.natTraversalDisabled && !formValues.forceSTUN) {
getIceServerConfigResponse.IceServerList.forEach(iceServer =>
iceServers.push({
urls: iceServer.Uris,
username: iceServer.Username,
credential: iceServer.Password,
}),
);
}
console.log('[VIEWER] ICE servers:', iceServers);
// Create Signaling Client
viewer.signalingClient = new KVSWebRTC.SignalingClient({
channelARN,
channelEndpoint: endpointsByProtocol.WSS,
clientId: formValues.clientId,
role: KVSWebRTC.Role.VIEWER,
region: formValues.region,
credentials: {
accessKeyId: formValues.accessKeyId,
secretAccessKey: formValues.secretAccessKey,
sessionToken: formValues.sessionToken,
},
requestSigner: {
getSignedURL: async function(signalingEndpoint, queryParams, date) {
const signer = new KVSWebRTC.SigV4RequestSigner(formValues.region, {
accessKeyId: formValues.accessKeyId,
secretAccessKey: formValues.secretAccessKey,
sessionToken: formValues.sessionToken,
});
metrics.viewer.signConnectAsViewer.startTime = Date.now();
console.debug('[VIEWER] Signing the url started at', new Date(metrics.viewer.signConnectAsViewer.startTime));
const retVal = await signer.getSignedURL(signalingEndpoint, queryParams, date);
metrics.viewer.signConnectAsViewer.endTime = Date.now();
console.debug('[VIEWER] Signing the url ended at', new Date(metrics.viewer.signConnectAsViewer.endTime));
console.log('[VIEWER] Time to sign the request:', metrics.viewer.signConnectAsViewer.endTime - metrics.viewer.signConnectAsViewer.startTime, 'ms');
metrics.viewer.connectAsViewer.startTime = Date.now();
console.log('[VIEWER] Connecting to KVS Signaling...');
console.debug('[VIEWER] ConnectAsViewer started at', new Date(metrics.viewer.connectAsViewer.startTime));
return retVal;
},
},
systemClockOffset: kinesisVideoClient.config.systemClockOffset,
});
const resolution = formValues.widescreen
? {
width: { ideal: 1280 },
height: { ideal: 720 },
}
: { width: { ideal: 640 }, height: { ideal: 480 } };
const constraints = {
video: formValues.sendVideo ? resolution : false,
audio: formValues.sendAudio,
};
const configuration = {
iceServers,
iceTransportPolicy: formValues.forceTURN ? 'relay' : 'all',
};
viewer.peerConnection = new RTCPeerConnection(configuration);
if (formValues.enableProfileTimeline) {
viewer.peerConnection.onicegatheringstatechange = (event) => {
if (viewer.peerConnection.iceGatheringState === 'gathering') {
metrics.viewer.iceGathering.startTime = Date.now();
} else if (viewer.peerConnection.iceGatheringState === 'complete') {
metrics.viewer.iceGathering.endTime = Date.now();
}
};
viewer.peerConnection.onconnectionstatechange = (event) => {
if (viewer.peerConnection.connectionState === 'new' || viewer.peerConnection.connectionState === 'connecting') {
metrics.viewer.peerConnection.startTime = Date.now();
}
if (viewer.peerConnection.connectionState === 'connected') {
metrics.viewer.peerConnection.endTime = Date.now();
metrics.viewer.ttffAfterPc.startTime = metrics.viewer.peerConnection.endTime;
}
};
viewer.peerConnection.oniceconnectionstatechange = (event) => {
if (viewer.peerConnection.iceConnectionState === 'connected') {
viewer.peerConnection.getStats().then(stats => {
stats.forEach(report => {
if (report.type === 'candidate-pair') {
activeCandidatePair = report;
}
});
});
}
};
}
if (formValues.openDataChannel) {
const dataChannelObj = viewer.peerConnection.createDataChannel('kvsDataChannel');
viewer.dataChannel = dataChannelObj;
dataChannelObj.onopen = () => {
if (formValues.enableProfileTimeline) {
dataChannelLatencyCalcMessage.firstMessageFromViewerTs = Date.now().toString();
dataChannelObj.send(JSON.stringify(dataChannelLatencyCalcMessage));
} else {
dataChannelObj.send("Opened data channel by viewer");
}
};
// Callback for the data channel created by viewer
let onRemoteDataMessageViewer = (message) => {
remoteMessage.append(`${message.data}\n\n`);
if (formValues.enableProfileTimeline) {
// The datachannel first sends a message of the following format with firstMessageFromViewerTs attached,
// to which the master responds back with the same message attaching firstMessageFromMasterTs.
// In response to this, the viewer sends the same message back with secondMessageFromViewerTs and so on until lastMessageFromViewerTs.
// The viewer is responsible for attaching firstMessageFromViewerTs, secondMessageFromViewerTs, lastMessageFromViewerTs. The master is responsible for firstMessageFromMasterTs and secondMessageFromMasterTs.
// (Master e2e time: secondMessageFromMasterTs - firstMessageFromMasterTs, Viewer e2e time: secondMessageFromViewerTs - firstMessageFromViewerTs)
try {
let dataChannelMessage = JSON.parse(message.data);
if (dataChannelMessage.hasOwnProperty('firstMessageFromViewerTs')) {
if (dataChannelMessage.secondMessageFromViewerTs === '') {
dataChannelMessage.secondMessageFromViewerTs = Date.now().toString();
} else if (dataChannelMessage.lastMessageFromViewerTs === '') {
dataChannelMessage.lastMessageFromViewerTs = Date.now().toString();
metrics.master.dataChannel.startTime = Number(dataChannelMessage.firstMessageFromMasterTs);
metrics.master.dataChannel.endTime = Number(dataChannelMessage.secondMessageFromMasterTs);
metrics.viewer.dataChannel.startTime = Number(dataChannelMessage.firstMessageFromViewerTs);
metrics.viewer.dataChannel.endTime = Number(dataChannelMessage.secondMessageFromViewerTs);
}
dataChannelMessage.content = 'Message from JS viewer';
dataChannelObj.send(JSON.stringify(dataChannelMessage));
} else if (dataChannelMessage.hasOwnProperty('peerConnectionStartTime')) {
metrics.master.peerConnection.startTime = dataChannelMessage.peerConnectionStartTime;
metrics.master.peerConnection.endTime = dataChannelMessage.peerConnectionEndTime;
metrics.master.ttffAfterPc.startTime = metrics.master.peerConnection.endTime;
} else if (dataChannelMessage.hasOwnProperty('signalingStartTime')) {
metrics.master.signaling.startTime = dataChannelMessage.signalingStartTime;
metrics.master.signaling.endTime = dataChannelMessage.signalingEndTime;
if (metrics.viewer.ttff.startTime < metrics.master.signaling.startTime) {
metrics.viewer.ttff.startTime = metrics.master.signaling.startTime;
}
metrics.master.waitTime.startTime = metrics.master.signaling.endTime;
metrics.viewer.waitTime.endTime = metrics.master.signaling.startTime;
metrics.master.offAnswerTime.startTime = dataChannelMessage.offerReceiptTime;
metrics.master.offAnswerTime.endTime = dataChannelMessage.sendAnswerTime;
metrics.master.describeChannel.startTime = dataChannelMessage.describeChannelStartTime;
metrics.master.describeChannel.endTime = dataChannelMessage.describeChannelEndTime;
metrics.master.channelEndpoint.startTime = dataChannelMessage.getSignalingChannelEndpointStartTime;
metrics.master.channelEndpoint.endTime = dataChannelMessage.getSignalingChannelEndpointEndTime;
metrics.master.iceServerConfig.startTime = dataChannelMessage.getIceServerConfigStartTime;
metrics.master.iceServerConfig.endTime = dataChannelMessage.getIceServerConfigEndTime;
metrics.master.getToken.startTime = dataChannelMessage.getTokenStartTime;
metrics.master.getToken.endTime = dataChannelMessage.getTokenEndTime;
metrics.master.createChannel.startTime = dataChannelMessage.createChannelStartTime;
metrics.master.createChannel.endTime = dataChannelMessage.createChannelEndTime;
metrics.master.connectAsMaster.startTime = dataChannelMessage.connectStartTime;
metrics.master.connectAsMaster.endTime = dataChannelMessage.connectEndTime;
} else if (dataChannelMessage.hasOwnProperty('candidateGatheringStartTime')) {
metrics.master.iceGathering.startTime = dataChannelMessage.candidateGatheringStartTime;
metrics.master.iceGathering.endTime = dataChannelMessage.candidateGatheringEndTime;
}
} catch (e) {
console.log("Receiving a non-json message");
}
}
};
dataChannelObj.onmessage = onRemoteDataMessageViewer;
viewer.peerConnection.ondatachannel = event => {
// Callback for the data channel created by master
event.channel.onmessage = onRemoteDataMessageViewer;
};
}
// Poll for connection stats if metrics enabled
if (formValues.enableDQPmetrics) {
// viewer.peerConnectionStatsInterval = setInterval(() => viewer.peerConnection.getStats().then(onStatsReport), 1000);
viewer.peerConnectionStatsInterval = setInterval(() => viewer.peerConnection.getStats().then(stats => calcStats(stats, formValues.clientId)), 1000);
}
if (formValues.enableProfileTimeline) {
profilingStartTime = new Date().getTime();
let headerElement = document.getElementById("timeline-profiling-header");
viewer.profilingInterval = setInterval(() => {
let statRunTime = calcDiffTimestamp2Sec(new Date().getTime(), profilingStartTime);
statRunTime = Number.parseFloat(statRunTime).toFixed(0);
if (statRunTime <= profilingTestLength) {
headerElement.textContent = "Profiling timeline chart available in " + (profilingTestLength - statRunTime);
}
}, 1000);
}
viewer.signalingClient.on('open', async () => {
metrics.viewer.connectAsViewer.endTime = Date.now();
metrics.viewer.signaling.endTime = metrics.viewer.connectAsViewer.endTime;
metrics.viewer.waitTime.startTime = metrics.viewer.signaling.endTime;
console.debug('[VIEWER] ConnectAsViewer ended at', new Date(metrics.viewer.connectAsViewer.endTime));
console.log('[VIEWER] Connected to signaling service');
console.log('[VIEWER] Time to connect to signaling:', metrics.viewer.connectAsViewer.endTime - metrics.viewer.connectAsViewer.startTime, 'ms');
metrics.viewer.setupMediaPlayer.startTime = Date.now();
signalingSetUpTime = metrics.viewer.setupMediaPlayer.startTime - viewerButtonPressed.getTime();
// Get a stream from the webcam, add it to the peer connection, and display it in the local view.
// If no video/audio needed, no need to request for the sources.
// Otherwise, the browser will throw an error saying that either video or audio has to be enabled.
if (formValues.sendVideo || formValues.sendAudio) {
try {
viewer.localStream = await navigator.mediaDevices.getUserMedia(constraints);
viewer.localStream.getTracks().forEach(track => viewer.peerConnection.addTrack(track, viewer.localStream));
localView.srcObject = viewer.localStream;
} catch (e) {
console.error(`[VIEWER] Could not find ${Object.keys(constraints).filter(k => constraints[k])} input device.`, e);
return;
}
}
metrics.viewer.setupMediaPlayer.endTime = Date.now();
timeToSetUpViewerMedia = metrics.viewer.setupMediaPlayer.endTime - metrics.viewer.setupMediaPlayer.startTime;
// Create an SDP offer to send to the master
console.log('[VIEWER] Creating SDP offer');
await viewer.peerConnection.setLocalDescription(
await viewer.peerConnection.createOffer({
offerToReceiveAudio: true,
offerToReceiveVideo: true,
}),
);
// When trickle ICE is enabled, send the offer now and then send ICE candidates as they are generated. Otherwise wait on the ICE candidates.
if (formValues.useTrickleICE) {
console.log('[VIEWER] Sending SDP offer');
console.debug('SDP offer:', viewer.peerConnection.localDescription);
metrics.viewer.offAnswerTime.startTime = Date.now();
viewer.signalingClient.sendSdpOffer(viewer.peerConnection.localDescription);
}
console.log('[VIEWER] Generating ICE candidates');
});
viewer.signalingClient.on('sdpAnswer', async answer => {
// Add the SDP answer to the peer connection
console.log('[VIEWER] Received SDP answer');
console.debug('SDP answer:', answer);
metrics.viewer.offAnswerTime.endTime = Date.now();
await viewer.peerConnection.setRemoteDescription(answer);
});
viewer.signalingClient.on('iceCandidate', candidate => {
// Add the ICE candidate received from the MASTER to the peer connection
console.log('[VIEWER] Received ICE candidate');
console.debug('ICE candidate', candidate);
if (shouldAcceptCandidate(formValues, candidate)) {
viewer.peerConnection.addIceCandidate(candidate);
} else {
console.log('[VIEWER] Not adding candidate from peer.');
}
});
viewer.signalingClient.on('close', () => {
console.log('[VIEWER] Disconnected from signaling channel');
});
viewer.signalingClient.on('error', error => {
console.error('[VIEWER] Signaling client error:', error);
});
// Send any ICE candidates to the other peer
viewer.peerConnection.addEventListener('icecandidate', ({ candidate }) => {
if (candidate) {
console.log('[VIEWER] Generated ICE candidate');
console.debug('ICE candidate:', candidate);
// When trickle ICE is enabled, send the ICE candidates as they are generated.
if (formValues.useTrickleICE) {
if (shouldSendIceCandidate(formValues, candidate)) {
console.log('[VIEWER] Sending ICE candidate');
viewer.signalingClient.sendIceCandidate(candidate);
} else {
console.log('[VIEWER] Not sending ICE candidate');
}
}
} else {
console.log('[VIEWER] All ICE candidates have been generated');
// When trickle ICE is disabled, send the offer now that all the ICE candidates have ben generated.
if (!formValues.useTrickleICE) {
console.log('[VIEWER] Sending SDP offer');
console.debug('SDP offer:', viewer.peerConnection.localDescription);
viewer.signalingClient.sendSdpOffer(viewer.peerConnection.localDescription);
}
}
});
viewer.peerConnection.addEventListener('connectionstatechange', async event => {
printPeerConnectionStateInfo(event, '[VIEWER]');
});
// As remote tracks are received, add them to the remote view
viewer.peerConnection.addEventListener('track', event => {
console.log('[VIEWER] Received remote track');
if (remoteView.srcObject) {
return;
}
viewer.remoteStream = event.streams[0];
remoteView.srcObject = viewer.remoteStream;
//measure the time to first track
if (formValues.enableDQPmetrics && initialDate === 0) {
initialDate = new Date();
}
});
console.log('[VIEWER] Starting viewer connection');
viewer.signalingClient.open();
} catch (e) {
console.error('[VIEWER] Encountered error starting:', e);
}
}
function stopViewer() {
try {
console.log('[VIEWER] Stopping viewer connection');
if (viewer.signalingClient) {
viewer.signalingClient.close();
viewer.signalingClient = null;
}
if (viewer.peerConnection) {
viewer.peerConnection.close();
viewer.peerConnection = null;
}
if (viewer.localStream) {
viewer.localStream.getTracks().forEach(track => track.stop());
viewer.localStream = null;
}
if (viewer.remoteStream) {
viewer.remoteStream.getTracks().forEach(track => track.stop());
viewer.remoteStream = null;
}
if (viewer.peerConnectionStatsInterval) {
clearInterval(viewer.peerConnectionStatsInterval);
viewer.peerConnectionStatsInterval = null;
}
if (viewer.localView) {
viewer.localView.srcObject = null;
}
if (viewer.remoteView) {
viewer.remoteView.srcObject = null;
}
if (viewer.dataChannel) {
viewer.dataChannel = null;
}
if (getFormValues().enableDQPmetrics) {
chart.destroy();
statStartTime = 0;
}
if (getFormValues().enableProfileTimeline) {
let container = document.getElementById('timeline-chart');
let headerElement = document.getElementById("timeline-profiling-header");
container.innerHTML = "";
container.style.height = "0px";
if (viewer.profilingInterval) {
clearInterval(viewer.profilingInterval);
}
headerElement.textContent = "";
}
} catch (e) {
console.error('[VIEWER] Encountered error stopping', e);
}
}
function sendViewerMessage(message) {
if (viewer.dataChannel) {
try {
viewer.dataChannel.send(message);
console.log('[VIEWER] Sent', message, 'to MASTER!');
return true;
} catch (e) {
console.error('[VIEWER] Send DataChannel:', e.toString());
return false;
}
} else {
console.warn('[VIEWER] No DataChannel exists!');
return false;
}
}
function profilingCalculations() {
let headerElement = document.getElementById("timeline-profiling-header");
headerElement.textContent = "Profiling Timeline chart";
google.charts.load('current', {packages:['timeline']});
google.charts.setOnLoadCallback(drawChart);
clearInterval(viewer.profilingInterval);
}
// Functions below support DQP test and metrics
// function to calculate difference between two epoch timestamps and return seconds with large being the most recent and small being the oldest.
function calcDiffTimestamp2Sec(large, small) {
return ((large - small) / 1000).toFixed(2);
}
function calcStats(stats, clientId) {
let rttCurrent = 0;
let videoBitrate = 0;
let videoFramerate = 0;
let videoHeight = 0;
let videoWidth = 0;
let videojitter = 0;
let videoDecodedFrameCount = 0;
let videoDroppedFrameCount = 0;
let curDroppedFrames = 0;
let audioBitrate = 0;
let audiojitter = 0;
let audioSamplesReceived = 0;
let activeCandidatePair = null;
let remoteCandidate = null;
let localCandidate = null;
let remoteCandidateConnectionString = '';
let localCandidateConnectionString = '';
let htmlString = '';
//Loop through each report and find the active pair.
stats.forEach(report => {
if (report.type === 'transport') {
activeCandidatePair = stats.get(report.selectedCandidatePairId);
}
});
// Firefox fix.
if (!activeCandidatePair) {
stats.forEach(report => {
if (report.type === 'candidate-pair' && report.selected) {
activeCandidatePair = report;
}
});
}
// Get the remote candidate connected
if (activeCandidatePair && activeCandidatePair.remoteCandidateId && activeCandidatePair.localCandidateId) {
remoteCandidate = stats.get(activeCandidatePair.remoteCandidateId);
localCandidate = stats.get(activeCandidatePair.localCandidateId);
}
// Capture the IP and port of the remote candidate
if (remoteCandidate) {
remoteCandidateConnectionString = '[' + remoteCandidate.candidateType + '] '
if (remoteCandidate.address && remoteCandidate.port) {
remoteCandidateConnectionString = remoteCandidateConnectionString + remoteCandidate.address + ':' + remoteCandidate.port + ' - ' + remoteCandidate.protocol;
} else if (remoteCandidate.ip && remoteCandidate.port) {
remoteCandidateConnectionString = remoteCandidateConnectionString + remoteCandidate.ip + ':' + remoteCandidate.port + ' - ' + remoteCandidate.protocol;
} else if (remoteCandidate.ipAddress && remoteCandidate.portNumber) {
remoteCandidateConnectionString = remoteCandidateConnectionString + remoteCandidate.ipAddress + ':' + remoteCandidate.portNumber + ' - ' + remoteCandidate.protocol;
}
}
// Capture the IP and port of the local candidate
if (localCandidate) {
localCandidateConnectionString = '[' + localCandidate.candidateType + '] '
if (localCandidate.address && localCandidate.port) {
localCandidateConnectionString = localCandidateConnectionString + localCandidate.address + ':' + localCandidate.port + ' - ' + localCandidate.protocol;
} else if (localCandidate.ip && localCandidate.port) {
localCandidateConnectionString = localCandidateConnectionString + localCandidate.ip + ':' + localCandidate.port + ' - ' + localCandidate.protocol;
} else if (localCandidate.ipAddress && localCandidate.portNumber) {
localCandidateConnectionString = localCandidateConnectionString + localCandidate.ipAddress + ':' + localCandidate.portNumber + ' - ' + localCandidate.protocol;
}
}
if (activeCandidatePair) {
// Get the current RTT the pair.
rttCurrent = activeCandidatePair.currentRoundTripTime;
//Get the video stats.
stats.forEach(report => {
if (report.type === 'inbound-rtp' && report.mediaType === 'video') {
videoFramerate = report.framesPerSecond;
videoHeight = report.frameHeight;
videoWidth = report.frameWidth;
videojitter = report.jitter;
videoDecodedFrameCount = report.framesDecoded;
videoDroppedFrameCount = report.framesDropped;
const bytes = report.bytesReceived;
if (vTimeStampPrev) {
videoBitrate = (8 * (bytes - vBytesPrev)) / (report.timestamp - vTimeStampPrev);
videoBitrate = Math.floor(videoBitrate);
curDroppedFrames = videoDroppedFrameCount - vFDroppedPrev;
}
vBytesPrev = bytes;
vTimeStampPrev = report.timestamp;
vFDroppedPrev = videoDroppedFrameCount;
}
});
//Get the audio stats.
stats.forEach(report => {
if (report.type === 'inbound-rtp' && report.mediaType === 'audio') {
audiojitter = report.jitter;
audioSamplesReceived = report.totalSamplesReceived;
const bytes = report.bytesReceived;
if (aTimeStampPrev) {
audioBitrate = (8 * (bytes - aBytesPrev)) / (report.timestamp - aTimeStampPrev);
audioBitrate = Math.floor(audioBitrate);
}
aBytesPrev = bytes;
aTimeStampPrev = report.timestamp;
}
});
// Only start test and display metrics once something has been decoded
if (videoDecodedFrameCount > 0 || audioSamplesReceived > 0) {
const currentDate = Date.now();
const currentTime = new Date(currentDate).getTime();
//timestamp start of decoded frames
if (statStartTime === 0) {
statStartTime = currentTime;
statStartDate = currentDate;
console.log('[DQP TEST] Measuring stream stats from Master.');
}