/
publish_webrtc.html
819 lines (719 loc) · 27.9 KB
/
publish_webrtc.html
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
<!DOCTYPE html>
<html>
<head>
<title>WebRTC Samples > Publish</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/external/bootstrap4/bootstrap.min.css">
<link rel="stylesheet" href="../css/common.css" />
<link rel="stylesheet" href="../css/samples.css" />
<script src="../js/external/adapter-latest.js"></script>
<script type="text/javascript" src="https://cdn.bitmovin.com/analytics/web/2/bitmovinanalytics.min.js"></script>
</head>
<body>
<div>
<div class="jumbotron">
<div class="col-sm-12 form-group">
<video id="localVideo" autoplay muted controls playsinline></video>
</div>
<div class="form-group col-sm-12 text-left">
<input type="text" class="form-control" id="streamId" name="streamIdTextBox"
placeholder="Type stream ID">
</div>
<div class="col-sm-12 text-right">
<button type="button" id="options" class="btn btn-outline-primary btn-sm">Options</button>
</div>
<div class="form-group col-sm-12 text-left options">
<label class=" mr-2" for="inlineFormCustomSelectPref">Max Video Bitrate(Kbps):</label>
<div class="form-inline">
<input type="text" class="form-control mr-sm-2" id="maxBandwidthTextBox" name="maxBandwidthTextBox"
value="900">
<button type="button" class="btn btn-outline-primary btn-sm" id="max_bandwidth_apply">Apply</button>
</div>
<div class="dropdown-divider"></div>
<legend class="col-form-label video-source-legend">Video Source</legend>
<a id="browser_screen_share_doesnt_support" href="https://caniuse.com/#search=getDisplayMedia">Your
browser doesn't support screen share. You can see supported browsers in this link </a>
<div class="dropdown-divider"></div>
<legend class="col-form-label audio-source-legend">Audio Source</legend>
<legend class="col-form-label microphone-gain-legend">Microphone Gain</legend>
<div class="form-inline"><input type=range id="volume_change_input" min=0 max=1 value=1 step=0.01></div>
<legend class="col-form-label audio-quality-legend">Audio Quality</legend>
<div class="form-check-inline form-inline">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" name="noiseSuppression"
id="noiseSuppression">
<label class="custom-control-label" for="noiseSuppression">Noise Supression</label>
</div>
</div>
<div class="form-check-inline form-inline">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" name="echoCancellation"
id="echoCancellation">
<label class="custom-control-label" for="echoCancellation">Echo Cancellation</label>
</div>
</div>
</div>
<div class="form-group col-sm-12 text-left options">
<label>Data Channel Messages</label>
<div id="all-messages" class="message_area"></div>
<div class="form-row">
<div class="form-group col-sm-8">
<input type="text" class="form-control" id="dataTextbox"
placeholder="Write your message to send players">
</div>
<div class="form-group col-sm-2">
<button type="button" id="send" class="btn btn-outline-primary btn-block">Send</button>
</div>
<div class="form-group col-sm-2">
<button id="send-image-button" type="button" class="btn btn-outline-primary btn-block">
Image
</button>
<input id="file-input" type="file" name="name" accept="image/x-png,image/gif,image/jpeg"
style="display: none" />
</div>
</div>
</div>
<div class="form-group col-sm-12 text-center" id="offlineInfo" >
<div class="form-group col-sm-4 offset-sm-4 text-center" style="margin-bottom: 8px;font-size:1em;">
<a href="" target="_blank"> </a> <!-- this is a place holder to keep the same alignment -->
</div>
<div class="form-group col-sm-4 offset-sm-4 text-center" style="font-size:1.2em">
<span class="badge badge-secondary">Status: Offline</span>
</div>
</div>
<div class="form-group col-sm-12 text-center" id="broadcastingInfo" style="display: none;">
<div class="form-group text-center" style="margin-bottom: 8px;font-size:1em;">
<a href="" id="playlink" target="_blank" data-toggle="tooltip" title="Opens in New Tab">Play with WebRTC</a>
</div>
<div class="form-group text-center" style="font-size:1.2em">
<span class="badge badge-success" >Status: Publishing</span>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary" disabled id="start_publish_button">Start Publishing</button>
<button class="btn btn-primary" disabled id="stop_publish_button">Stop Publishing</button>
</div>
<div class="col-sm-10 offset-sm-1" id="stats_panel">
<div class="row text-muted text-left">
<div class="col-sm-6">
<small>
<div id="average_bit_rate_container">Average Bitrate(Kbps): <span
id="average_bit_rate"></span></div>
<div id="latest_bit_rate_container">Latest Bitrate(Kbps): <span id="latest_bit_rate"></span>
</div>
<div id="packet_lost_container">PacketsLost: <span id="packet_lost_text"></span></div>
<div id="jitter_text_container">Jitter(Secs): <span id="jitter_text"></span></div>
<div>Audio Level: <span id="audio_level_text"></span> <meter id="audio_level_text_container"
high="0.25" max="1" value="0"></meter></div>
</small>
</div>
<div class="col-sm-6">
<small>
<div id="round_trip_time_container">Round Trip Time(Secs): <span
id="round_trip_time"></span></div>
<div id="source_resolution_container">Source WidthxHeight: <span id="source_width"></span> x
<span id="source_height"></span>
</div>
<div id="ongoing_resolution_container">On-going WidthxHeight: <span
id="ongoing_width"></span> x <span id="ongoing_height"></span></div>
<div id="on_going_fps_container">On-going FPS: <span id="on_going_fps"></span></div>
</small>
</div>
</div>
</div>
</div>
<footer class="footer text-left">
<div class="row">
<div class="col-sm-6 text-left"><a target="_parent" href="https://github.com/ant-media/StreamApp/tree/master/src/main/webapp/samples/publish_webrtc.html">View Source on Github</a></div>
<div class="col-sm-6 text-right">
<a href="http://antmedia.io" target="_parent">antmedia.io</a>
</div>
</div>
</footer>
</div>
<script src="../js/external/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="../js/external/popper.min.js" crossorigin="anonymous"></script>
<script src="../js/external/bootstrap.min.js" crossorigin="anonymous"></script>
</body>
<script type="module" lang="javascript">
import { WebRTCAdaptor } from "../js/webrtc_adaptor.js"
import { getUrlParameter } from "../js/fetch.stream.js"
import { SoundMeter } from "../js/soundmeter.js"
import { generateRandomString, getWebSocketURL } from "../js/utility.js"
import {Analytics} from "../js/analytics.js"
var debug = getUrlParameter("debug");
if (debug == null) {
debug = false;
}
function init() {
$('[data-toggle="tooltip"]').tooltip()
var id = getUrlParameter("id");
if (typeof id != "undefined") {
$("#streamId").val(id);
}
else {
id = getUrlParameter("name");
if (typeof id != "undefined") {
$("#streamId").val(id);
}
else {
$("#streamId").val("streamId_" + generateRandomString(9));
}
}
}
$(function () {
init();
});
var max_bandwidth_input = document.getElementById("maxBandwidthTextBox");
var max_bandwidth_apply = document.getElementById("max_bandwidth_apply");
max_bandwidth_apply.addEventListener("click", setBitrateValue, false);
var maxVideoBitrateKbps = 900;
var subscriberId = getUrlParameter("subscriberId");
var subscriberCode = getUrlParameter("subscriberCode");
var streamName = getUrlParameter("streamName");
var mainTrack = getUrlParameter("mainTrack");
var playType = getUrlParameter("play");
var customerId = getUrlParameter("customerId");
var bitmovinKey = getUrlParameter("bitmovinKey");
var applicationName = location.pathname.split('/').filter(Boolean)[0];
var analytics =new Analytics(bitmovinKey);
var playTitle;
if (playType == "hls") {
playTitle = "HLS";
}
else if (playType == "dash") {
playTitle = "Dash";
}
else {
playTitle = "WebRTC";
playType = "webrtc";
}
//TODO: Migrate these methods to Jquery
var start_publish_button = document.getElementById("start_publish_button");
start_publish_button.addEventListener("click", startPublishing, false);
var stop_publish_button = document.getElementById("stop_publish_button");
stop_publish_button.addEventListener("click", stopPublishing, false);
var options = document.getElementById("options");
options.addEventListener("click", toggleOptions, false);
var send = document.getElementById("send");
send.addEventListener("click", sendData, false);
var streamIdBox = document.getElementById("streamId");
var toggleNoiseSuppression = document.getElementById("noiseSuppression");
toggleNoiseSuppression.addEventListener("click", changeAudioConstraints, false);
var toggleEchoCancellation = document.getElementById("echoCancellation");
toggleEchoCancellation.addEventListener("click", changeAudioConstraints, false);
/**
* If publishing stops for any reason, it tries to republish again.
*/
var autoRepublishEnabled = true;
/**
* Timer job that checks the WebRTC connection
*/
var autoRepublishIntervalJob = null;
var streamId;
var token = getUrlParameter("token");
// It should be true
var rtmpForward = getUrlParameter("rtmpForward");
var volume_change_input = document.getElementById("volume_change_input");
volume_change_input.addEventListener("change", changeVolume);
function changeVolume() {
/**
* Change the gain levels on the input selector.
*/
if (document.getElementById('volume_change_input') != null) {
webRTCAdaptor.setVolumeLevel(this.value);
}
}
function setBitrateValue() {
var bitrateBoxValue = max_bandwidth_input.value;
if (bitrateBoxValue == "unlimited" || bitrateBoxValue == NaN) {
maxVideoBitrateKbps = "unlimited"
console.log("input bitrate: " + maxVideoBitrateKbps);
}
else {
var bitrate = parseInt(bitrateBoxValue);
if (bitrate == NaN) {
maxVideoBitrateKbps = 900;
}
else if (bitrate < 100) {
maxVideoBitrateKbps = 100;
}
else {
maxVideoBitrateKbps = bitrate;
}
console.log("input bitrate: " + maxVideoBitrateKbps);
}
// Check stream is publishing
// If it's publishing then call changeBandwidth function
if (start_publish_button.disabled) {
webRTCAdaptor.changeBandwidth(maxVideoBitrateKbps, $("#streamId").val());
}
}
let meterRefresh = null;
const instantMeter = document.querySelector('#audio_level_text_container');
const instantValueDisplay = document.querySelector('#audio_level_text');
function enableAudioLevel() {
webRTCAdaptor.enableAudioLevelForLocalStream((value) => {
instantMeter.value = instantValueDisplay.innerText = value;
}, 200);
};
var file_input = document.getElementById("file-input");
file_input.addEventListener("change", send_image);
var connect_channel_button = document.getElementById("send-image-button");
connect_channel_button.addEventListener("click", () => file_input.click());
function send_image() {
var imageURL = file_input.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var arrayBuffer = this.result;
var bytes = new Uint8Array(arrayBuffer);
var blob = new Blob([bytes.buffer]);
var urlCreator = window.URL || window.webkitURL;
var imageBlobUrl = urlCreator.createObjectURL(blob);
$('<img src =' + imageBlobUrl + ' style="width:100px;"><br>').appendTo($("#all-messages"));
sendBinaryData(arrayBuffer);
};
reader.readAsArrayBuffer(imageURL);
}
function sendBinaryData(data) {
try {
var iceState = webRTCAdaptor.iceConnectionState(streamIdBox.value);
if (
iceState != null &&
iceState != "failed" &&
iceState != "disconnected"
) {
webRTCAdaptor.sendData(streamIdBox.value, data);
} else {
alert("WebRTC connection is not active. Please click start first");
}
} catch (exception) {
console.error(exception);
alert(
"Message cannot be sent. Make sure you've enabled data channel on server web panel"
);
}
}
function handleImageData(data) {
var bytes = new Uint8Array(data);
var blob = new Blob([bytes.buffer]);
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(blob);
$('<img src =' + imageUrl + ' style="width:100px;"><br>').appendTo($("#all-messages"));
}
function startPublishing() {
setBitrateValue();
webRTCAdaptor.bandwidth = maxVideoBitrateKbps;
streamId = streamIdBox.value;
webRTCAdaptor.publish(streamId, token, subscriberId, subscriberCode, streamName, mainTrack);
analytics.analyze(Analytics.publisher,streamId,applicationName,customerId,Analytics.webrtc,"localVideo");
}
function stopPublishing() {
if (autoRepublishIntervalJob != null) {
clearInterval(autoRepublishIntervalJob);
autoRepublishIntervalJob = null;
}
webRTCAdaptor.stop(streamId);
}
function switchVideoMode(chbx) {
//If video device changes manually
if (chbx.value == "screen") {
//webRTCAdaptor.switchDesktopWithMicAudio(streamId);
webRTCAdaptor.switchDesktopCapture(streamId);
}
else if (chbx.value == "screenwithcamera") {
webRTCAdaptor.switchDesktopCaptureWithCamera(streamId);
}
else {
webRTCAdaptor.switchVideoCameraCapture(streamId, chbx.value);
}
}
function switchAudioMode(chbx) {
webRTCAdaptor.switchAudioInputSource(streamId, chbx.value);
}
function getCameraRadioButton(deviceName, deviceId) {
return "<div class=\"form-check form-check-inline\">" +
"<input class=\"form-check-input video-source\" name=\"videoSource\" type=\"radio\" value=\"" + deviceId + "\" id=\"" + deviceId + "\">" +
"<label class=\"form-check-label font-weight-light\" name=\"videoSource\" for=\"" + deviceId + "\" style=\"font-weight:normal\">" +
deviceName +
"</label>" +
"</div>";
}
function getScreenButton() {
return "<div class=\"form-check form-check-inline\">" +
"<input class=\"form-check-input video-source\" name=\"videoSource\" type=\"radio\" value=\"screen\" id=\"screen_share_checkbox\">" +
"<label class=\"form-check-label font-weight-light\" name=\"videoSource\" for=\"screen_share_checkbox\" style=\"font-weight:normal\">" +
"Screen" +
"</label>" +
"</div>"
}
function getScreenWithCamButton() {
return "<div class=\"form-check form-check-inline\">" +
"<input class=\"form-check-input video-source\" name=\"videoSource\" type=\"radio\" value=\"screenwithcamera\" id=\"screen_share_with_camera_checkbox\">" +
"<label class=\"form-check-label font-weight-light\" name=\"videoSource\" for=\"screen_share_with_camera_checkbox\" style=\"font-weight:normal\">" +
"Screen with Camera" +
"</label>" +
"</div>"
}
function getAudioRadioButton(deviceName, deviceId) {
return "<div class=\"form-check form-check-inline\">" +
"<input class=\"form-check-input audio-source\" name=\"audioDeviceSource\" type=\"radio\" value=\"" + deviceId + "\" id=\"" + deviceId + "\">" +
"<label class=\"form-check-label font-weight-light\" name=\"audioDeviceSource\" for=\"" + deviceId + "\" style=\"font-weight:normal\">" +
deviceName +
"</label>" +
"</div>";
}
function toggleOptions() {
$(".options").toggle();
}
function sendData() {
try {
var iceState = webRTCAdaptor.iceConnectionState(streamId);
if (iceState != null && iceState != "failed" && iceState != "disconnected") {
webRTCAdaptor.sendData($("#streamId").val(), $("#dataTextbox").val());
$("#all-messages").append("Sent: " + $("#dataTextbox").val() + "<br>");
$("#dataTextbox").val("");
}
else {
alert("WebRTC publishing is not active. Please click Start Publishing first")
}
}
catch (exception) {
console.error(exception);
alert("Message cannot be sent. Make sure you've enabled data channel on server web panel");
}
}
function checkAndRepublishIfRequired() {
var iceState = webRTCAdaptor.iceConnectionState(streamId);
console.log("Ice state checked = " + iceState);
if (iceState == null || iceState == "failed" || iceState == "disconnected") {
webRTCAdaptor.stop(streamId);
webRTCAdaptor.closePeerConnection(streamId);
webRTCAdaptor.closeWebSocket();
initWebRTCAdaptor(true, autoRepublishEnabled);
}
}
function startAnimation() {
$("#offlineInfo").hide();
$("#broadcastingInfo").show();
$("#playlink").attr("href", "../play.html?id=" + streamId+"&playOrder="+playType);
$("#playlink").text("Play with " + playTitle);
$("#playlink").show();
setTimeout(function () {
var state = webRTCAdaptor.signallingState(streamId);
if (state != null && state != "closed") {
var iceState = webRTCAdaptor.iceConnectionState(streamId);
if (iceState != null && iceState != "failed" && iceState != "disconnected") {
startAnimation();
}
else {
$("#playlink").hide();
$("#broadcastingInfo").hide();
$("#offlineInfo").show();
}
}
else {
$("#playlink").hide();
$("#broadcastingInfo").hide();
$("#offlineInfo").show();
}
}, 200);
}
function changeAudioConstraints() {
var constraint = { audio: {} };
switch (this.name) {
case 'noiseSuppression': {
constraint.audio.noiseSuppression = this.checked;
break;
}
case 'echoCancellation': {
constraint.audio.echoCancellation = this.checked;
break;
}
default: {
break;
}
}
webRTCAdaptor.applyConstraints(constraint);
}
var websocketURL = getWebSocketURL(location, rtmpForward);
var webRTCAdaptor = null;
var selectedRadio = null;
var selectedAudio = null;
function initWebRTCAdaptor(publishImmediately, autoRepublishEnabled) {
webRTCAdaptor = new WebRTCAdaptor({
websocket_url: websocketURL,
localVideoId: "localVideo",
debug: debug,
bandwidth: maxVideoBitrateKbps,
dataChannelEnabled: true,
callback: (info, obj) => {
if (info == "initialized") {
console.log("initialized");
start_publish_button.disabled = false;
stop_publish_button.disabled = true;
if (publishImmediately) {
webRTCAdaptor.publish(streamId, token, subscriberId, subscriberCode, streamName)
}
} else if (info == "publish_started") {
//stream is being published
console.log("publish started");
start_publish_button.disabled = true;
stop_publish_button.disabled = false;
startAnimation();
if (autoRepublishEnabled && autoRepublishIntervalJob == null) {
autoRepublishIntervalJob = setInterval(() => {
checkAndRepublishIfRequired();
}, 3000);
}
webRTCAdaptor.enableStats(obj.streamId);
enableAudioLevel();
} else if (info == "publish_finished") {
//stream is being finished
console.log("publish finished");
start_publish_button.disabled = false;
stop_publish_button.disabled = true;
$("#stats_panel").hide();
}
else if (info == "browser_screen_share_supported") {
$(".video-source").prop("disabled", false);
console.log("browser screen share supported");
browser_screen_share_doesnt_support.style.display = "none";
}
else if (info == "screen_share_stopped") {
//choose the first video source. It may not be correct for all cases.
$(".video-source").first().prop("checked", true);
console.log("screen share stopped");
}
else if (info == "closed") {
//console.log("Connection closed");
if (typeof obj != "undefined") {
console.log("Connecton closed: " + JSON.stringify(obj));
}
}
else if (info == "pong") {
//ping/pong message are sent to and received from server to make the connection alive all the time
//It's especially useful when load balancer or firewalls close the websocket connection due to inactivity
}
else if (info == "refreshConnection") {
checkAndRepublishIfRequired();
}
else if (info == "ice_connection_state_changed") {
console.log("iceConnectionState Changed: ", JSON.stringify(obj));
}
else if (info == "updated_stats") {
//obj is the PeerStats which has fields
//averageOutgoingBitrate - kbits/sec
//currentOutgoingBitrate - kbits/sec
console.log("Average outgoing bitrate " + obj.averageOutgoingBitrate + " kbits/sec"
+ " Current outgoing bitrate: " + obj.currentOutgoingBitrate + " kbits/sec"
+ " video source width: " + obj.resWidth + " video source height: " + obj.resHeight
+ "frame width: " + obj.frameWidth + " frame height: " + obj.frameHeight
+ " video packetLost: " + obj.videoPacketsLost + " audio packetsLost: " + obj.audioPacketsLost
+ " video RTT: " + obj.videoRoundTripTime + " audio RTT: " + obj.audioRoundTripTime
+ " video jitter: " + obj.videoJitter + " audio jitter: " + obj.audioJitter);
analytics.setStats(obj);
$("#average_bit_rate").text(obj.averageOutgoingBitrate);
if (obj.averageOutgoingBitrate > 0) {
$("#average_bit_rate_container").show();
}
else {
$("#average_bit_rate_container").hide();
}
$("#latest_bit_rate").text(obj.currentOutgoingBitrate);
if (obj.currentOutgoingBitrate > 0) {
$("#latest_bit_rate_container").show();
}
else {
$("#latest_bit_rate_container").hide();
}
var packetLost = parseInt(obj.videoPacketsLost) + parseInt(obj.audioPacketsLost);
$("#packet_lost_text").text(packetLost);
if (packetLost > -1) {
$("#packet_lost_container").show();
}
else {
$("#packet_lost_container").hide();
}
var jitter = ((parseFloat(obj.videoJitter) + parseInt(obj.audioJitter)) / 2).toPrecision(3);
$("#jitter_text").text(jitter);
if (jitter > 0) {
$("#jitter_container").show();
}
else {
$("#jitter_container").hide();
}
var rtt = ((parseFloat(obj.videoRoundTripTime) + parseFloat(obj.audioRoundTripTime)) / 2).toPrecision(3);
$("#round_trip_time").text(rtt);
if (rtt > 0) {
$("#round_trip_time_container").show();
}
else {
$("#round_trip_time_container").hide();
}
$("#source_width").text(obj.resWidth);
$("#source_height").text(obj.resHeight);
if (obj.resWidth > 0 && obj.resHeight > 0) {
$("#source_resolution_container").show();
}
else {
$("#source_resolution_container").hide();
}
$("#ongoing_width").text(obj.frameWidth);
$("#ongoing_height").text(obj.frameHeight);
if (obj.frameWidth > 0 && obj.frameHeight > 0) {
$("#ongoing_resolution_container").show();
}
else {
$("#ongoing_resolution_container").hide();
}
$("#on_going_fps").text(obj.currentFPS);
if (obj.currentFPS > 0) {
$("#on_going_fps_container").show();
}
else {
$("#on_going_fps_container").hide();
}
$("#stats_panel").show();
}
else if (info == "data_received") {
var data = obj.data;
if (data instanceof ArrayBuffer) {
handleImageData(data);
}
else {
$("#all-messages").append("Received: " + data + "<br>");
}
}
else if (info == "available_devices") {
var videoHtmlContent = "";
var audioHtmlContent = "";
var devices = new Array();
var i = 0;
var cameraIndex = 0;
var micIndex = 0;
obj.forEach(function (device) {
var label = device.label;
devices.forEach(function (same) {
if (same == device.label) {
i += 1;
label = device.label + " - " + i
}
});
if (device.kind == "videoinput") {
if (typeof label == "undefined" || label == "") {
label = "Cam-" + cameraIndex;
}
cameraIndex++;
videoHtmlContent += getCameraRadioButton(label, device.deviceId);
}
else if (device.kind == "audioinput") {
if (typeof label == "undefined" || label == "") {
label = "Mic-" + micIndex;
}
micIndex++;
audioHtmlContent += getAudioRadioButton(label, device.deviceId);
}
devices.push(device.label)
});
$('[name="videoSource"]').remove();
$('[name="audioDeviceSource"]').remove();
videoHtmlContent += getScreenButton();
videoHtmlContent += getScreenWithCamButton();
$(videoHtmlContent).insertAfter(".video-source-legend");
$(".video-source").first().prop("checked", true);
$(audioHtmlContent).insertAfter(".audio-source-legend");
$(".audio-source").first().prop("checked", true);
if (document.querySelector('input[name="videoSource"]')) {
document.querySelectorAll('input[name="videoSource"]').forEach((elem) => {
elem.addEventListener("change", function (event) {
var item = event.target;
switchVideoMode(item)
selectedRadio = item.value;
});
});
}
if (document.querySelector('input[name="audioDeviceSource"]')) {
document.querySelectorAll('input[name="audioDeviceSource"]').forEach((elem) => {
elem.addEventListener("change", function (event) {
var item = event.target;
switchAudioMode(item)
selectedAudio = item.value;
});
});
}
$(":radio[value=" + selectedRadio + "]").prop("checked", true);
$(":radio[value=" + selectedAudio + "]").prop("checked", true);
}
else if (info == "session_restored") {
start_publish_button.disabled = true;
stop_publish_button.disabled = false;
startAnimation();
console.log(info + "notification received");
}
else {
console.log(info + " notification received");
}
},
callbackError: function (error, message) {
//some of the possible errors, NotFoundError, SecurityError,PermissionDeniedError
console.log("error callback: " + JSON.stringify(error));
var errorMessage = JSON.stringify(error);
if (typeof message != "undefined") {
errorMessage = message;
}
var errorMessage = JSON.stringify(error);
if (error.indexOf("WebSocketNotConnected") != -1) {
errorMessage = "WebSocket Connection is disconnected.";
}
else if (error.indexOf("not_initialized_yet") != -1) {
errorMessage = "Server is getting initialized.";
}
else if (error.indexOf("data_store_not_available") != -1) {
errorMessage = "Data store is not available. It's likely that server is initialized or getting closed";
}
else {
if (error.indexOf("NotFoundError") != -1) {
errorMessage = "Camera or Mic are not found or not allowed in your device";
}
else if (error.indexOf("NotReadableError") != -1 || error.indexOf("TrackStartError") != -1) {
errorMessage = "Camera or Mic are already in use and they cannot be opened. Choose another video/audio source if you have on the page below ";
$(".options").show();
}
else if (error.indexOf("OverconstrainedError") != -1 || error.indexOf("ConstraintNotSatisfiedError") != -1) {
errorMessage = "There is no device found that fits your video and audio constraints. You may change video and audio constraints"
}
else if (error.indexOf("NotAllowedError") != -1 || error.indexOf("PermissionDeniedError") != -1) {
errorMessage = "You are not allowed to access camera and mic.";
}
else if (error.indexOf("TypeError") != -1) {
errorMessage = "Video/Audio is required";
}
else if (error.indexOf("getUserMediaIsNotAllowed") != -1) {
errorMessage = "You are not allowed to reach devices from an insecure origin, please enable ssl";
}
else if (error.indexOf("ScreenSharePermissionDenied") != -1) {
errorMessage = "You are not allowed to access screen share";
$(".video-source").first().prop("checked", true);
}
else if (error.indexOf("UnsecureContext") != -1) {
errorMessage = "Please Install SSL(https). Camera and mic cannot be opened because of unsecure context. ";
}
else {
errorMessage = error
}
alert(errorMessage);
}
console.error(errorMessage);
if (message !== undefined) {
console.error(message);
}
}
});
}
//initialize the WebRTCAdaptor
initWebRTCAdaptor(false, autoRepublishEnabled);
window.webRTCAdaptor = webRTCAdaptor;
</script>
</html>