Debian Codegraph @

html/demos/screensharing.js

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // We import the settings.js file to know which address we should contact
2 // to talk to Janus, and optionally which STUN/TURN servers should be
3 // used as well. Specifically, that file defines the "server" and
4 // "iceServers" properties we'll pass when creating the Janus session.
5
6 /* global iceServers:readonly, Janus:readonly, server:readonly */
7
8 var janus = null;
9 var screentest = null;
10 var opaqueId = "screensharingtest-"+Janus.randomString(12);
11
12 var myusername = null;
13 var myid = null;
14
15 var capture = null;
16 var role = null;
17 var room = null;
18 var source = null;
19
20 var localTracks = {}, localVideos = 0,
21 remoteTracks = {}, remoteVideos = 0;
22
23 $(document).ready(function() {
24 // Initialize the library (all console debuggers enabled)
25 Janus.init({debug: "all", callback: function() {
26 // Use a button to start the demo
27 $('#start').one('click', function() {
28 $(this).attr('disabled', true).unbind('click');
29 // Make sure the browser supports WebRTC
30 if(!Janus.isWebrtcSupported()) {
31 bootbox.alert("No WebRTC support... ");
32 return;
33 }
34 // Create session
35 janus = new Janus(
36 {
37 server: server,
38 iceServers: iceServers,
39 // Should the Janus API require authentication, you can specify either the API secret or user token here too
40 // token: "mytoken",
41 // or
42 // apisecret: "serversecret",
43 success: function() {
44 // Attach to VideoRoom plugin
45 janus.attach(
46 {
47 plugin: "janus.plugin.videoroom",
48 opaqueId: opaqueId,
49 success: function(pluginHandle) {
50 $('#details').remove();
51 screentest = pluginHandle;
52 Janus.log("Plugin attached! (" + screentest.getPlugin() + ", id=" + screentest.getId() + ")");
53 // Prepare the username registration
54 $('#screenmenu').removeClass('hide');
55 $('#createnow').removeClass('hide');
56 $('#create').click(preShareScreen);
57 $('#joinnow').removeClass('hide');
58 $('#join').click(joinScreen);
59 $('#desc').focus();
60 $('#start').removeAttr('disabled').html("Stop")
61 .click(function() {
62 $(this).attr('disabled', true);
63 janus.destroy();
64 });
65 },
66 error: function(error) {
67 Janus.error(" -- Error attaching plugin...", error);
68 bootbox.alert("Error attaching plugin... " + error);
69 },
70 consentDialog: function(on) {
71 Janus.debug("Consent dialog should be " + (on ? "on" : "off") + " now");
72 if(on) {
73 // Darken screen
74 $.blockUI({
75 message: '',
76 baseZ: 3001,
77 css: {
78 border: 'none',
79 padding: '15px',
80 backgroundColor: 'transparent',
81 color: '#aaa'
82 } });
83 } else {
84 // Restore screen
85 $.unblockUI();
86 }
87 },
88 iceState: function(state) {
89 Janus.log("ICE state changed to " + state);
90 },
91 mediaState: function(medium, on, mid) {
92 Janus.log("Janus " + (on ? "started" : "stopped") + " receiving our " + medium + " (mid=" + mid + ")");
93 },
94 webrtcState: function(on) {
95 Janus.log("Janus says our WebRTC PeerConnection is " + (on ? "up" : "down") + " now");
96 $("#screencapture").parent().parent().unblock();
97 if(on) {
98 bootbox.alert("Your screen sharing session just started: pass the <b>" + room + "</b> session identifier to those who want to attend.");
99 } else {
100 bootbox.alert("Your screen sharing session just stopped.", function() {
101 janus.destroy();
102 window.location.reload();
103 });
104 }
105 },
106 slowLink: function(uplink, lost, mid) {
107 Janus.warn("Janus reports problems " + (uplink ? "sending" : "receiving") +
108 " packets on mid " + mid + " (" + lost + " lost packets)");
109 },
110 onmessage: function(msg, jsep) {
111 Janus.debug(" ::: Got a message (publisher) :::", msg);
112 let event = msg["videoroom"];
113 Janus.debug("Event: " + event);
114 if(event) {
115 if(event === "joined") {
116 myid = msg["id"];
117 $('#session').html(room);
118 $('#title').html(escapeXmlTags(msg["description"]));
119 Janus.log("Successfully joined room " + msg["room"] + " with ID " + myid);
120 if(role === "publisher") {
121 // This is our session, publish our stream
122 Janus.debug("Negotiating WebRTC stream for our screen (capture " + capture + ")");
123 // Safari expects a user gesture to share the screen: see issue #2455
124 if(Janus.webRTCAdapter.browserDetails.browser === "safari") {
125 bootbox.alert("Safari requires a user gesture before the screen can be shared: close this dialog to do that. See issue #2455 for more details", function() {
126 screentest.createOffer(
127 {
128 // We want to capture the screen and audio, but sendonly
129 tracks: [
130 { type: 'audio', capture: true, recv: false },
131 { type: 'screen', capture: true, recv: false }
132 ],
133 success: function(jsep) {
134 Janus.debug("Got publisher SDP!", jsep);
135 let publish = { request: "configure", audio: true, video: true };
136 screentest.send({ message: publish, jsep: jsep });
137 },
138 error: function(error) {
139 Janus.error("WebRTC error:", error);
140 bootbox.alert("WebRTC error... " + error.message);
141 }
142 });
143 });
144 } else {
145 // Other browsers should be fine, we try to call getDisplayMedia directly
146 screentest.createOffer(
147 {
148 // We want sendonly audio and screensharing
149 tracks: [
150 { type: 'audio', capture: true, recv: false },
151 { type: 'screen', capture: true, recv: false }
152 ],
153 success: function(jsep) {
154 Janus.debug("Got publisher SDP!", jsep);
155 let publish = { request: "configure", audio: true, video: true };
156 screentest.send({ message: publish, jsep: jsep });
157 },
158 error: function(error) {
159 Janus.error("WebRTC error:", error);
160 bootbox.alert("WebRTC error... " + error.message);
161 }
162 });
163 }
164 } else {
165 // We're just watching a session, any feed to attach to?
166 if(msg["publishers"]) {
167 let list = msg["publishers"];
168 Janus.debug("Got a list of available publishers/feeds:", list);
169 for(let f in list) {
170 if(list[f]["dummy"])
171 continue;
172 let id = list[f]["id"];
173 let display = list[f]["display"];
174 Janus.debug(" >> [" + id + "] " + display);
175 newRemoteFeed(id, display)
176 }
177 }
178 }
179 } else if(event === "event") {
180 // Any feed to attach to?
181 if(role === "listener" && msg["publishers"]) {
182 let list = msg["publishers"];
183 Janus.debug("Got a list of available publishers/feeds:", list);
184 for(let f in list) {
185 if(list[f]["dummy"])
186 continue;
187 let id = list[f]["id"];
188 let display = list[f]["display"];
189 Janus.debug(" >> [" + id + "] " + display);
190 newRemoteFeed(id, display)
191 }
192 } else if(msg["leaving"]) {
193 // One of the publishers has gone away?
194 let leaving = msg["leaving"];
195 Janus.log("Publisher left: " + leaving);
196 if(role === "listener" && msg["leaving"] === source) {
197 bootbox.alert("The screen sharing session is over, the publisher left", function() {
198 window.location.reload();
199 });
200 }
201 } else if(msg["error"]) {
202 bootbox.alert(msg["error"]);
203 }
204 }
205 }
206 if(jsep) {
207 Janus.debug("Handling SDP as well...", jsep);
208 screentest.handleRemoteJsep({ jsep: jsep });
209 }
210 },
211 onlocaltrack: function(track, on) {
212 Janus.debug("Local track " + (on ? "added" : "removed") + ":", track);
213 // We use the track ID as name of the element, but it may contain invalid characters
214 let trackId = track.id.replace(/[{}]/g, "");
215 if(!on) {
216 // Track removed, get rid of the stream and the rendering
217 let stream = localTracks[trackId];
218 if(stream) {
219 try {
220 let tracks = stream.getTracks();
221 for(let i in tracks) {
222 let mst = tracks[i];
223 if(mst)
224 mst.stop();
225 }
226 // eslint-disable-next-line no-unused-vars
227 } catch(e) {}
228 }
229 if(track.kind === "video") {
230 $('#screenvideo' + trackId).remove();
231 localVideos--;
232 if(localVideos === 0) {
233 // No video, at least for now: show a placeholder
234 if($('#screencapture .no-video-container').length === 0) {
235 $('#screencapture').append(
236 '<div class="no-video-container">' +
237 '<i class="fa-solid fa-video fa-xl no-video-icon"></i>' +
238 '<span class="no-video-text">No webcam available</span>' +
239 '</div>');
240 }
241 }
242 }
243 delete localTracks[trackId];
244 return;
245 }
246 // If we're here, a new track was added
247 let stream = localTracks[trackId];
248 if(stream) {
249 // We've been here already
250 return;
251 }
252 $('#screenmenu').addClass('hide');
253 $('#room').removeClass('hide');
254 if(track.kind === "audio") {
255 // We ignore local audio tracks, they'd generate echo anyway
256 if(localVideos === 0) {
257 // No video, at least for now: show a placeholder
258 if($('#screencapture .no-video-container').length === 0) {
259 $('#screencapture').append(
260 '<div class="no-video-container">' +
261 '<i class="fa-solid fa-video fa-xl no-video-icon"></i>' +
262 '<span class="no-video-text">No webcam available</span>' +
263 '</div>');
264 }
265 }
266 } else {
267 // New video track: create a stream out of it
268 localVideos++;
269 $('#screencapture .no-video-container').remove();
270 let stream = new MediaStream([track]);
271 localTracks[trackId] = stream;
272 Janus.log("Created local stream:", stream);
273 $('#screencapture').append('<video class="rounded centered" id="screenvideo' + trackId + '" width=100% autoplay playsinline muted="muted"/>');
274 Janus.attachMediaStream($('#screenvideo' + trackId).get(0), stream);
275 }
276 if(screentest.webrtcStuff.pc.iceConnectionState !== "completed" &&
277 screentest.webrtcStuff.pc.iceConnectionState !== "connected") {
278 $("#screencapture").parent().parent().block({
279 message: '<b>Publishing...</b>',
280 css: {
281 border: 'none',
282 backgroundColor: 'transparent',
283 color: 'white'
284 }
285 });
286 }
287 },
288 // eslint-disable-next-line no-unused-vars
289 onremotetrack: function(track, mid, on) {
290 // The publisher stream is sendonly, we don't expect anything here
291 },
292 oncleanup: function() {
293 Janus.log(" ::: Got a cleanup notification :::");
294 $('#screencapture').empty();
295 $("#screencapture").parent().unblock();
296 $('#room').addClass('hide');
297 localTracks = {};
298 localVideos = 0;
299 }
300 });
301 },
302 error: function(error) {
303 Janus.error(error);
304 bootbox.alert(error, function() {
305 window.location.reload();
306 });
307 },
308 destroyed: function() {
309 window.location.reload();
310 }
311 });
312 });
313 }});
314 });
315
316 // eslint-disable-next-line no-unused-vars
317 function checkEnterShare(field, event) {
318 let theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
319 if(theCode == 13) {
320 preShareScreen();
321 return false;
322 } else {
323 return true;
324 }
325 }
326
327 function preShareScreen() {
328 if(!Janus.isExtensionEnabled()) {
329 bootbox.alert("This browser doesn't support screensharing (getDisplayMedia unavailable)", function() {
330 window.location.reload();
331 });
332 return;
333 }
334 // Create a new room
335 $('#desc').attr('disabled', true);
336 $('#create').attr('disabled', true).unbind('click');
337 $('#roomid').attr('disabled', true);
338 $('#join').attr('disabled', true).unbind('click');
339 if($('#desc').val() === "") {
340 bootbox.alert("Please insert a description for the room");
341 $('#desc').removeAttr('disabled', true);
342 $('#create').removeAttr('disabled', true).click(preShareScreen);
343 $('#roomid').removeAttr('disabled', true);
344 $('#join').removeAttr('disabled', true).click(joinScreen);
345 return;
346 }
347 capture = "screen";
348 shareScreen();
349 }
350
351 function shareScreen() {
352 // Create a new room
353 let desc = $('#desc').val();
354 role = "publisher";
355 let create = {
356 request: "create",
357 description: desc,
358 bitrate: 500000,
359 publishers: 1
360 };
361 screentest.send({ message: create, success: function(result) {
362 if(result["error"]) {
363 bootbox.alert("Couldn't create room: " + result["error"]);
364 return;
365 }
366 let event = result["videoroom"];
367 Janus.debug("Event: " + event);
368 if(event) {
369 // Our own screen sharing session has been created, join it
370 room = result["room"];
371 Janus.log("Screen sharing session created: " + room);
372 myusername = Janus.randomString(12);
373 let register = {
374 request: "join",
375 room: room,
376 ptype: "publisher",
377 display: myusername
378 };
379 screentest.send({ message: register });
380 }
381 }});
382 }
383
384 // eslint-disable-next-line no-unused-vars
385 function checkEnterJoin(field, event) {
386 let theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
387 if(theCode == 13) {
388 joinScreen();
389 return false;
390 } else {
391 return true;
392 }
393 }
394
395 function joinScreen() {
396 // Join an existing screen sharing session
397 $('#desc').attr('disabled', true);
398 $('#create').attr('disabled', true).unbind('click');
399 $('#roomid').attr('disabled', true);
400 $('#join').attr('disabled', true).unbind('click');
401 let roomid = $('#roomid').val();
402 if(isNaN(roomid)) {
403 bootbox.alert("Session identifiers are numeric only");
404 $('#desc').removeAttr('disabled', true);
405 $('#create').removeAttr('disabled', true).click(preShareScreen);
406 $('#roomid').removeAttr('disabled', true);
407 $('#join').removeAttr('disabled', true).click(joinScreen);
408 return;
409 }
410 room = parseInt(roomid);
411 role = "listener";
412 myusername = Janus.randomString(12);
413 let register = {
414 request: "join",
415 room: room,
416 ptype: "publisher",
417 display: myusername
418 };
419 screentest.send({ message: register });
420 }
421
422 function newRemoteFeed(id, display) {
423 // A new feed has been published, create a new plugin handle and attach to it as a listener
424 source = id;
425 let remoteFeed = null;
426 janus.attach(
427 {
428 plugin: "janus.plugin.videoroom",
429 opaqueId: opaqueId,
430 success: function(pluginHandle) {
431 remoteFeed = pluginHandle;
432 remoteFeed.remoteTracks = {};
433 remoteFeed.remoteVideos = 0;
434 Janus.log("Plugin attached! (" + remoteFeed.getPlugin() + ", id=" + remoteFeed.getId() + ")");
435 Janus.log(" -- This is a subscriber");
436 // We wait for the plugin to send us an offer
437 let listen = {
438 request: "join",
439 room: room,
440 ptype: "subscriber",
441 feed: id
442 };
443 remoteFeed.send({ message: listen });
444 },
445 error: function(error) {
446 Janus.error(" -- Error attaching plugin...", error);
447 bootbox.alert("Error attaching plugin... " + error);
448 },
449 iceState: function(state) {
450 Janus.log("ICE state (feed #" + remoteFeed.rfindex + ") changed to " + state);
451 },
452 webrtcState: function(on) {
453 Janus.log("Janus says this WebRTC PeerConnection (feed #" + remoteFeed.rfindex + ") is " + (on ? "up" : "down") + " now");
454 },
455 slowLink: function(uplink, lost, mid) {
456 Janus.warn("Janus reports problems " + (uplink ? "sending" : "receiving") +
457 " packets on mid " + mid + " (" + lost + " lost packets)");
458 },
459 onmessage: function(msg, jsep) {
460 Janus.debug(" ::: Got a message (listener) :::", msg);
461 let event = msg["videoroom"];
462 Janus.debug("Event: " + event);
463 if(event) {
464 if(event === "attached") {
465 // Subscriber created and attached
466 Janus.log("Successfully attached to feed " + id + " (" + display + ") in room " + msg["room"]);
467 $('#screenmenu').addClass('hide');
468 $('#room').removeClass('hide');
469 } else {
470 // What has just happened?
471 }
472 }
473 if(jsep) {
474 Janus.debug("Handling SDP as well...", jsep);
475 // Answer and attach
476 remoteFeed.createAnswer(
477 {
478 jsep: jsep,
479 // We only specify data channels here, as this way in
480 // case they were offered we'll enable them. Since we
481 // don't mention audio or video tracks, we autoaccept them
482 // as recvonly (since we won't capture anything ourselves)
483 tracks: [
484 { type: 'data' }
485 ],
486 success: function(jsep) {
487 Janus.debug("Got SDP!", jsep);
488 let body = { request: "start", room: room };
489 remoteFeed.send({ message: body, jsep: jsep });
490 },
491 error: function(error) {
492 Janus.error("WebRTC error:", error);
493 bootbox.alert("WebRTC error... " + error.message);
494 }
495 });
496 }
497 },
498 // eslint-disable-next-line no-unused-vars
499 onlocaltrack: function(track, on) {
500 // The subscriber stream is recvonly, we don't expect anything here
501 },
502 onremotetrack: function(track, mid, on, metadata) {
503 Janus.debug(
504 "Remote track (mid=" + mid + ") " +
505 (on ? "added" : "removed") +
506 (metadata? " (" + metadata.reason + ") " : "") + ":", track
507 );
508 // Screen sharing tracks are sometimes muted/unmuted by browser
509 // when data is not flowing fast enough; this can make streams blink.
510 // We can ignore these.
511 if(track.kind === "video" && metadata && (metadata.reason === "mute" || metadata.reason === "unmute")) {
512 Janus.log("Ignoring mute/unmute on screen-sharing track.")
513 return
514 }
515 if(!on) {
516 // Track removed, get rid of the stream and the rendering
517 $('#screenvideo' + mid).remove();
518 if(track.kind === "video") {
519 remoteVideos--;
520 if(remoteVideos === 0) {
521 // No video, at least for now: show a placeholder
522 if($('#screencapture .no-video-container').length === 0) {
523 $('#screencapture').append(
524 '<div class="no-video-container">' +
525 '<i class="fa-solid fa-video fa-xl no-video-icon"></i>' +
526 '<span class="no-video-text">No remote video available</span>' +
527 '</div>');
528 }
529 }
530 }
531 delete remoteTracks[mid];
532 return;
533 }
534 // If we're here, a new track was added
535 if(track.kind === "audio") {
536 // New audio track: create a stream out of it, and use a hidden <audio> element
537 let stream = new MediaStream([track]);
538 remoteTracks[mid] = stream;
539 Janus.log("Created remote audio stream:", stream);
540 $('#screencapture').append('<audio class="hide" id="screenvideo' + mid + '" playsinline/>');
541 $('#screenvideo' + mid).get(0).volume = 0;
542 Janus.attachMediaStream($('#screenvideo' + mid).get(0), stream);
543 $('#screenvideo' + mid).get(0).play();
544 $('#screenvideo' + mid).get(0).volume = 1;
545 if(remoteVideos === 0) {
546 // No video, at least for now: show a placeholder
547 if($('#screencapture .no-video-container').length === 0) {
548 $('#screencapture').append(
549 '<div class="no-video-container">' +
550 '<i class="fa-solid fa-video fa-xl no-video-icon"></i>' +
551 '<span class="no-video-text">No remote video available</span>' +
552 '</div>');
553 }
554 }
555 } else {
556 // New video track: create a stream out of it
557 remoteVideos++;
558 $('#screencapture .no-video-container').remove();
559 let stream = new MediaStream([track]);
560 remoteFeed.remoteTracks[mid] = stream;
561 Janus.log("Created remote video stream:", stream);
562 $('#screencapture').append('<video class="rounded centered" id="screenvideo' + mid + '" width=100% playsinline/>');
563 $('#screenvideo' + mid).get(0).volume = 0;
564 Janus.attachMediaStream($('#screenvideo' + mid).get(0), stream);
565 $('#screenvideo' + mid).get(0).play();
566 $('#screenvideo' + mid).get(0).volume = 1;
567 }
568 },
569 oncleanup: function() {
570 Janus.log(" ::: Got a cleanup notification (remote feed " + id + ") :::");
571 $('#waitingvideo').remove();
572 remoteFeed.remoteTracks = {};
573 remoteFeed.remoteVideos = 0;
574 }
575 });
576 }
577
578 // Helper to escape XML tags
579 function escapeXmlTags(value) {
580 if(value) {
581 let escapedValue = value.replace(new RegExp('<', 'g'), '&lt');
582 escapedValue = escapedValue.replace(new RegExp('>', 'g'), '&gt');
583 return escapedValue;
584 }
585 }