forked from AgoraIO/Basic-Video-Call
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmeeting.js
More file actions
609 lines (571 loc) · 15.8 KB
/
meeting.js
File metadata and controls
609 lines (571 loc) · 15.8 KB
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
import AgoraRTC from "agora-rtc-sdk";
import "bulma";
import $ from "jquery";
import * as Cookies from "js-cookie";
import { merge } from "lodash";
import "@/assets/css/icons.css";
import "@/assets/global.scss";
import "./meeting.scss";
import ButtonControl from "@/utils/ButtonControl";
import {
isSafari,
isMobileSize,
isChrome,
isFirefox
} from "@/utils/BrowserCheck";
import Notify from "@/utils/Notify";
import Renderer from "@/utils/Render";
import { SHARE_ID, RESOLUTION_ARR, APP_ID, Token } from "@/utils/Settings";
import { logger, log } from "../../utils/Logger";
// eslint-disable-next-line
import Polyfill from "@/utils/Polyfill";
// If display a window to show video info
const DUAL_STREAM_DEBUG = false;
let options = {};
let client = {};
let localStream = {};
let streamList = [];
let shareClient = null;
let shareStream = null;
let mainId;
let mainStream;
const globalLog = logger.init("global", "blue");
const shareLog = logger.init("share", "yellow");
const localLog = logger.init("local", "green");
const optionsInit = () => {
let options = {
videoProfile: Cookies.get("videoProfile").split(",")[0] || "480p_4",
videoProfileLow: Cookies.get("videoProfileLow"),
cameraId: Cookies.get("cameraId"),
microphoneId: Cookies.get("microphoneId"),
channel: Cookies.get("channel") || "test",
transcode: Cookies.get("transcode") || "interop",
attendeeMode: Cookies.get("attendeeMode") || "video",
baseMode: Cookies.get("baseMode") || "avc",
displayMode: 1, // 0 Tile, 1 PIP, 2 screen share
uid: undefined, // In default it is dynamically generated
resolution: undefined
};
let tempProfile = RESOLUTION_ARR[Cookies.get("videoProfile")];
options.resolution = tempProfile[0] / tempProfile[1] || 4 / 3;
options.key = APP_ID;
options.token = Token;
return options;
};
const uiInit = options => {
document.querySelector(
".ag-header-lead span"
).innerHTML = `AgoraWeb v${agoraVersion.slice(1)}`;
Renderer.init("ag-canvas", 9 / 16, 8 / 5);
// Mobile page should remove title and footer
if (isMobileSize()) {
Renderer.enterFullScreen();
}
// Only firefox and chrome support screen sharing
if (!isFirefox() && !isChrome()) {
ButtonControl.disable(".shareScreenBtn");
}
$("#room-name").html(options.channel);
switch (options.attendeeMode) {
case "audio-only":
ButtonControl.hide([".videoControlBtn", ".shareScreenBtn"]);
break;
case "audience":
ButtonControl.hide([
".videoControlBtn",
".audioControlBtn",
".shareScreenBtn"
]);
break;
default:
case "video":
break;
}
};
const clientInit = (client, options) => {
return new Promise((resolve, reject) => {
client.init(options.key, () => {
globalLog("AgoraRTC client initialized");
let lowStreamParam = RESOLUTION_ARR[options.videoProfileLow];
client.join(
options.token,
options.channel,
options.uid,
uid => {
log(uid, "brown", `User ${uid} join channel successfully`);
log(uid, "brown", new Date().toLocaleTimeString());
client.setLowStreamParameter({
width: lowStreamParam[0],
height: lowStreamParam[1],
framerate: lowStreamParam[2],
bitrate: lowStreamParam[3]
});
// Create localstream
resolve(uid);
},
err => {
reject(err);
}
);
});
});
};
/**
*
* @param {*} uid
* @param {*} options global option
* @param {*} config stream config
*/
const streamInit = (uid, options, config) => {
let defaultConfig = {
streamID: uid,
audio: true,
video: true,
screen: false
};
switch (options.attendeeMode) {
case "audio-only":
defaultConfig.video = false;
break;
case "audience":
defaultConfig.video = false;
defaultConfig.audio = false;
break;
default:
case "video":
break;
}
// eslint-disable-next-line
let stream = AgoraRTC.createStream(merge(defaultConfig, config));
stream.setVideoProfile(options.videoProfile);
return stream;
};
const shareEnd = () => {
try {
shareClient && shareClient.unpublish(shareStream);
shareStream && shareStream.close();
shareClient &&
shareClient.leave(
() => {
shareLog("Share client succeed to leave.");
},
() => {
shareLog("Share client failed to leave.");
}
);
} finally {
shareClient = null;
shareStream = null;
}
};
const shareStart = () => {
ButtonControl.disable(".shareScreenBtn");
// eslint-disable-next-line
shareClient = AgoraRTC.createClient({
mode: options.transcode
});
let shareOptions = merge(options, {
uid: SHARE_ID
});
clientInit(shareClient, shareOptions).then(uid => {
let config = {
screen: true,
video: false,
audio: false,
extensionId: "minllpmhdgpndnkomcoccfekfegnlikg",
mediaSource: "application"
};
shareStream = streamInit(uid, shareOptions, config);
shareStream.init(
() => {
ButtonControl.enable(".shareScreenBtn");
shareStream.on("stopScreenSharing", () => {
shareEnd();
shareLog("Stop Screen Sharing at" + new Date());
});
shareClient.publish(shareStream, err => {
shareLog("Publish share stream error: " + err);
shareLog("getUserMedia failed", err);
});
},
err => {
ButtonControl.enable(".shareScreenBtn");
shareLog("getUserMedia failed", err);
shareEnd();
if (isChrome()) {
// If (!chrome.app.isInstalled) {
let msg = `
Please install chrome extension from
<a href="https://chrome.google.com/webstore/detail/minllpmhdgpndnkomcoccfekfegnlikg">Google Webstore</a>
before using sharing screen.
`;
Notify.danger(msg, 5000);
// }
}
}
);
});
};
window.installSuccess = (...args) => {
globalLog(...args);
};
window.installError = (...args) => {
globalLog(...args);
Notify.danger(
"Failed to install the extension, please check the network and console.",
3000
);
};
const removeStream = id => {
streamList.map((item, index) => {
if (item.getId() === id) {
streamList[index].close();
$("#video-item-" + id).remove();
streamList.splice(index, 1);
return 1;
}
return 0;
});
if (streamList.length <= 4 && options.displayMode !== 2) {
ButtonControl.enable(".displayModeBtn");
}
Renderer.customRender(streamList, options.displayMode, mainId);
};
const addStream = (stream, push = false) => {
let id = stream.getId();
// Check for redundant
let redundant = streamList.some(item => {
return item.getId() === id;
});
if (redundant) {
return;
}
// Do push for localStream and unshift for other streams
push ? streamList.push(stream) : streamList.unshift(stream);
if (streamList.length > 4) {
options.displayMode = options.displayMode === 1 ? 0 : options.displayMode;
ButtonControl.disable([".displayModeBtn", ".disableRemoteBtn"]);
}
Renderer.customRender(streamList, options.displayMode, mainId);
};
const getStreamById = id => {
return streamList.filter(item => {
return item.getId() === id;
})[0];
};
const enableDualStream = () => {
client.enableDualStream(
function() {
localLog("Enable dual stream success!");
},
function(e) {
localLog(e);
}
);
};
const setHighStream = (prev, next) => {
if (prev === next) {
return;
}
let prevStream;
let nextStream;
// Get stream by id
for (let stream of streamList) {
let id = stream.getId();
if (id === prev) {
prevStream = stream;
} else if (id === next) {
nextStream = stream;
} else {
// Do nothing
}
}
// Set prev stream to low
prevStream && client.setRemoteVideoStreamType(prevStream, 1);
// Set next stream to high
nextStream && client.setRemoteVideoStreamType(nextStream, 0);
};
/**
* Add callback for client event to control streams
* @param {*} client
* @param {*} streamList
*/
const subscribeStreamEvents = () => {
client.on("stream-added", function(evt) {
let stream = evt.stream;
let id = stream.getId();
localLog("New stream added: " + id);
localLog(new Date().toLocaleTimeString());
localLog("Subscribe ", stream);
if (id === SHARE_ID) {
options.displayMode = 2;
mainId = id;
mainStream = stream;
if (!shareClient) {
ButtonControl.disable(".shareScreenBtn");
}
ButtonControl.disable([".displayModeBtn", ".disableRemoteBtn"]);
}
if (id !== mainId) {
if (options.displayMode === 2) {
client.setRemoteVideoStreamType(stream, 1);
} else {
mainStream && client.setRemoteVideoStreamType(mainStream, 1);
mainStream = stream;
mainId = id;
}
}
client.subscribe(stream, function(err) {
localLog("Subscribe stream failed", err);
});
});
client.on("peer-leave", function(evt) {
let id = evt.uid;
localLog("Peer has left: " + id);
localLog(new Date().toLocaleTimeString());
if (id === SHARE_ID) {
options.displayMode = 0;
if (options.attendeeMode === "video") {
ButtonControl.enable(".shareScreenBtn");
}
ButtonControl.enable([".displayModeBtn", ".disableRemoteBtn"]);
shareEnd();
}
if (id === mainId) {
let next = options.displayMode === 2 ? SHARE_ID : localStream.getId();
setHighStream(mainId, next);
mainId = next;
mainStream = getStreamById(mainId);
}
removeStream(evt.uid);
});
client.on("stream-subscribed", function(evt) {
let stream = evt.stream;
localLog("Got stream-subscribed event");
localLog(new Date().toLocaleTimeString());
localLog("Subscribe remote stream successfully: " + stream.getId());
addStream(stream);
});
client.on("stream-removed", function(evt) {
let stream = evt.stream;
let id = stream.getId();
localLog("Stream removed: " + id);
localLog(new Date().toLocaleTimeString());
if (id === SHARE_ID) {
options.displayMode = 0;
if (options.attendeeMode === "video") {
ButtonControl.enable(".shareScreenBtn");
}
ButtonControl.enable([".displayModeBtn", ".disableRemoteBtn"]);
shareEnd();
}
if (id === mainId) {
let next = options.displayMode === 2 ? SHARE_ID : localStream.getId();
setHighStream(mainId, next);
mainId = next;
mainStream = getStreamById(mainId);
}
removeStream(stream.getId());
});
};
const subscribeMouseEvents = () => {
$(".displayModeBtn").on("click", function(e) {
if (
e.currentTarget.classList.contains("disabled") ||
streamList.length <= 1
) {
return;
}
// 1 refer to pip mode
if (options.displayMode === 1) {
options.displayMode = 0;
ButtonControl.disable(".disableRemoteBtn");
} else if (options.displayMode === 0) {
options.displayMode = 1;
ButtonControl.enable(".disableRemoteBtn");
} else {
// Do nothing when in screen share mode
}
Renderer.customRender(streamList, options.displayMode, mainId);
});
$(".exitBtn").on("click", function() {
try {
shareClient && shareEnd();
client && client.unpublish(localStream);
localStream && localStream.close();
client &&
client.leave(
() => {
localLog("Client succeed to leave.");
},
() => {
localLog("Client failed to leave.");
}
);
} finally {
// Redirect to index
window.location.href = "index.html";
}
});
$(".videoControlBtn").on("click", function() {
$(".videoControlBtn").toggleClass("off");
localStream.isVideoOn()
? localStream.disableVideo()
: localStream.enableVideo();
});
$(".audioControlBtn").on("click", function() {
$(".audioControlBtn").toggleClass("off");
localStream.isAudioOn()
? localStream.disableAudio()
: localStream.enableAudio();
});
$(".shareScreenBtn").on("click", function(e) {
if (e.currentTarget.classList.contains("disabled")) {
return;
}
if (shareClient) {
shareEnd();
} else {
shareStart();
}
});
$(".disableRemoteBtn").on("click", function(e) {
if (
e.currentTarget.classList.contains("disabled") ||
streamList.length <= 1
) {
return;
}
$(".disableRemoteBtn").toggleClass("off");
let list;
let id = localStream.getId();
list = Array.from(
document.querySelectorAll(`.video-item:not(#video-item-${id})`)
);
list.map(item => {
if (item.style.display === "none") {
item.style.display = "block";
return 1;
}
item.style.display = "none";
return 0;
});
});
$(window).resize(function(_) {
if (isMobileSize()) {
Renderer.enterFullScreen();
} else {
Renderer.exitFullScreen();
}
Renderer.customRender(streamList, options.displayMode, mainId);
});
// Dbl click to switch high/low stream
$(".ag-container").dblclick(function(e) {
let dom = e.target;
while (!dom.classList.contains("video-item")) {
dom = dom.parentNode;
if (dom.classList.contains("ag-main")) {
return;
}
}
let id = parseInt(dom.id.split("-")[2], 10);
if (id !== mainId) {
let next = options.displayMode === 2 ? SHARE_ID : id;
// Force to swtich
setHighStream(mainId, next);
mainId = next;
mainStream = getStreamById(mainId);
}
Renderer.customRender(streamList, options.displayMode, mainId);
});
$(document).mousemove(function(_) {
if (global._toolbarToggle) {
clearTimeout(global._toolbarToggle);
}
$(".ag-btn-group").addClass("active");
global._toolbarToggle = setTimeout(function() {
$(".ag-btn-group").removeClass("active");
}, 2500);
});
};
const infoDetectSchedule = () => {
let no = streamList.length;
for (let i = 0; i < no; i++) {
let item = streamList[i];
let id = item.getId();
let box = $(`#video-item-${id} .video-item-box`);
let width;
let height;
let frameRate;
let HighOrLow;
// Whether high or low stream
if (id === mainId) {
HighOrLow = "High";
} else {
HighOrLow = "Low";
}
if (i === no - 1) {
HighOrLow = "local";
}
item.getStats(function(e) {
if (i === no - 1) {
width = e.videoSendResolutionWidth;
height = e.videoSendResolutionHeight;
frameRate = e.videoSendFrameRate;
} else {
width = e.videoReceivedResolutionWidth;
height = e.videoReceivedResolutionHeight;
frameRate = e.videoReceiveFrameRate;
}
let str = `
<p>uid: ${id}</p>
<p>${width}*${height} ${frameRate}fps</p>
<p>${HighOrLow}</p>
`;
box.html(str);
});
}
};
// ------------- start --------------
// ----------------------------------
options = optionsInit();
uiInit(options);
// eslint-disable-next-line
client = AgoraRTC.createClient({
mode: options.transcode
});
subscribeMouseEvents();
subscribeStreamEvents();
clientInit(client, options).then(uid => {
// Use selected device
let config = isSafari()
? {}
: {
cameraId: options.cameraId,
microphoneId: options.microphoneId
};
localStream = streamInit(uid, options, config);
// Enable dual stream
if (options.attendeeMode !== "audience") {
// MainId default to be localStream's ID
mainId = uid;
mainStream = localStream;
}
enableDualStream();
localStream.init(
() => {
if (options.attendeeMode !== "audience") {
addStream(localStream, true);
client.publish(localStream, err => {
localLog("Publish local stream error: " + err);
});
}
},
err => {
localLog("getUserMedia failed", err);
}
);
});
if (DUAL_STREAM_DEBUG) {
setInterval(infoDetectSchedule, 1000);
}