-
Notifications
You must be signed in to change notification settings - Fork 0
/
joinroom.js
404 lines (355 loc) · 12.8 KB
/
joinroom.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
'use strict';
const DailyIframe = require('@daily-co/daily-js');
const { isMobile } = require('./browser');
const $leave = $('#leave-room');
const $room = $('#room');
const $activeParticipant = $('div#active-participant > div.participant.main', $room);
const $activeVideo = $('video', $activeParticipant);
const $participants = $('div#participants', $room);
// The current active Participant in the Room.
let activeParticipant = null;
// The current active speaker, even if they are not
// set as the active participant. This will be used
// in case a participant is unpinned, in which case
// we will replace the tile with the active speaker.
let activeSpeakerId = null;
// Whether the user has selected the active Participant by clicking on
// one of the video thumbnails.
let isActiveParticipantPinned = false;
/**
* Set the active Participant's video.
* @param participant - the active Participant
* @param callObject - the Daily call object instance
*/
function setActiveParticipant(participant, callObject) {
if (activeParticipant) {
const $activeParticipant = $(`div#${activeParticipant.session_id}`, $participants);
$activeParticipant.removeClass('active');
$activeParticipant.removeClass('pinned');
const videoTrack = activeParticipant.tracks.video.persistentTrack;
// Detach any existing VideoTrack of the active Participant.
if (videoTrack) {
const activeVideo = $activeVideo.get(0);
activeVideo.srcObject?.removeTrack(videoTrack);
$activeVideo.css('opacity', '0');
}
// Reset priority back to default
setVideoPriority(activeParticipant.session_id, null, callObject);
}
// Set the new active Participant.
activeParticipant = participant;
const userName = participant.user_name;
const sid = participant.session_id;
const identity = userName ? userName : sid;
const $participant = $(`div#${sid}`, $participants);
$participant.addClass('active');
if (isActiveParticipantPinned) {
$participant.addClass('pinned');
}
// Attach the new active Participant's video.
const track = participant.tracks.video.persistentTrack;
if (track) {
updateTrackIfNeeded($activeVideo.get(0), track);
$activeVideo.css('opacity', '');
}
// Set the new active Participant's identity
$activeParticipant.attr('data-identity', identity);
// Set new active participant's track priority to 'high'
setVideoPriority(activeParticipant.session_id, 'high', callObject);
}
/**
* Set the current active Participant in the Room.
* @param activeParticipant - the participant to feature in active participant view
* @param callObject - the Daily call object instance
*/
function setCurrentActiveParticipant(activeParticipant, callObject) {
const lp = callObject.participants().local;
setActiveParticipant(activeParticipant || lp, callObject);
}
/**
* Set up the Participant's media container.
* @param participant - the Participant whose media container is to be set up
* @param callObject - the Daily call object
*/
function setupParticipantContainer(participant, callObject) {
const sid = participant.session_id;
// Safeguard against duplicate containers
const existingContainer = document.getElementById(sid);
if (existingContainer) return;
const userName = participant.user_name;
const identity = userName ? userName : sid;
// Add a container for the Participant's media.
const $container =
$(`<div class="participant" data-identity="${identity}" id="${sid}">
<audio autoplay ${
participant.local ? 'muted' : ''
} style="opacity: 0"></audio>
<video autoplay muted playsinline style="opacity: 0"></video>
</div>`);
// Toggle the pinning of the active Participant's video.
$container.on('click', () => {
const allParticipants = callObject.participants();
if (activeParticipant.session_id === sid && isActiveParticipantPinned) {
// Unpin the RemoteParticipant and update the current active Participant.
isActiveParticipantPinned = false;
const activeSpeaker = allParticipants[activeSpeakerId];
setCurrentActiveParticipant(activeSpeaker, callObject);
} else {
// Pin the RemoteParticipant as the active Participant.
let p;
if (participant.local) {
p = allParticipants.local;
} else {
p = allParticipants[sid];
}
isActiveParticipantPinned = true;
setActiveParticipant(p, callObject);
}
});
// Add the Participant's container to the DOM.
$participants.append($container);
}
/**
* Set the VideoTrack priority for the given RemoteParticipant. This has no
* effect in Peer-to-Peer Rooms.
* @param sessionId - the ID of the participant whose priority is being set
* @param priority - null | 'low' | 'standard' | 'high'
* @param callObject - the Daily call object
*/
function setVideoPriority(sessionId, priority, callObject) {
let layer = 'inherit';
if (priority === 'high') {
if (isMobile) {
layer = 1;
} else {
layer = 2;
}
}
const receiveSettings = {
[sessionId]: {
video: {
layer
},
},
};
callObject.updateReceiveSettings(receiveSettings)
}
/**
* Attach a Track to the DOM.
* @param track - the Track to attach
* @param participant - the Participant which published the Track
* @param callObject - the Daily call object instance
*/
function attachTrack(track, participant, callObject) {
// Attach the Participant's Track to the thumbnail.
const query = `div#${participant.session_id} > ${track.kind}`;
let $media = $(query, $participants);
if ($media.length === 0) {
setupParticipantContainer(participant, callObject);
$media = $(query, $participants);
}
$media.css('opacity', '');
const media = $media.get(0);
updateTrackIfNeeded(media, track);
// If the attached Track is a VideoTrack that is published by the active
// Participant, then attach it to the main video as well.
if (track.kind === 'video' && participant.session_id === activeParticipant?.session_id) {
updateTrackIfNeeded($activeVideo.get(0), track);
$activeVideo.css('opacity', '');
}
}
// updateTrackIfNeeded() takes an existing video element
// and a new MediaStreamTrack. If the video element contains
// an existing track, it is removed. The new track is attached.
function updateTrackIfNeeded(mediaElement, newTrack) {
const src = mediaElement.srcObject;
if (!src) {
mediaElement.srcObject = new MediaStream([newTrack]);
return;
}
const existingTracks = src.getTracks();
const l = existingTracks.length;
if (l === 0) {
src.addTrack(newTrack);
return;
}
if (l > 1) {
console.warn(`Unexpected count of tracks. Expected 1, got ${l}; only handling the first`);
}
const existingTrack = existingTracks[0];
if (existingTrack.id !== newTrack.id) {
src.removeTrack(existingTrack);
src.addTrack(newTrack);
}
}
/**
* Detach a Track from the DOM.
* @param track - the Track to be detached
* @param participant - the Participant that is publishing the Track
*/
function detachTrack(track, participant) {
// Detach the Participant's Track from the thumbnail.
const $media = $(`div#${participant.session_id} > ${track.kind}`, $participants);
const mediaEl = $media.get(0);
$media.css('opacity', '0');
mediaEl.srcObject.removeTrack(track);
mediaEl.srcObject = null;
// If the detached Track is a VideoTrack that is published by the active
// Participant, then detach it from the main video as well.
if (track.kind === 'video' && participant.session_id === activeParticipant.session_id) {
const activeVideoEl = $activeVideo.get(0);
activeVideoEl.srcObject.removeTrack(track);
activeVideoEl.srcObject = null;
$activeVideo.css('opacity', '0');
}
}
/**
* Handle the Participant's media.
* @param participant - the Participant
* @param callObject - the Daily call object instance
*/
function participantConnected(participant, callObject) {
// Set up the Participant's media container.
setupParticipantContainer(participant, callObject);
}
/**
* Handle a disconnected Participant.
* @param sessionId - the ID of the disconnected participant
* @param callObject - the Daily call object instance
*/
function participantDisconnected(sessionId, callObject) {
// Remove the Participant's media container.
$(`div#${sessionId}`, $participants).remove();
// If this is the currently pinned participant, unpin them
// and set the local participant as active.
if (isActiveParticipantPinned && activeParticipant.session_id === sessionId) {
isActiveParticipantPinned = false;
setCurrentActiveParticipant(null, callObject);
}
}
function removeAllParticipants() {
$participants.empty();
}
/**
* Join a Room.
* @param token - the meeting token used to join a Daily room
* @param connectOptions - the ConnectOptions used to join a Room
*/
async function joinRoom(token, connectOptions) {
// Join to the Room with the given AccessToken and ConnectOptions.
const callObject = DailyIframe.createCallObject({
url: connectOptions.roomURL,
token: token,
dailyConfig: {
userMediaVideoConstraints: connectOptions.userMediaVideoConstraints,
receiveSettings: connectOptions.receiveSettings,
},
audioSource: connectOptions.audioDeviceId,
videoSource: connectOptions.videoDeviceId,
});
callObject
.on('joined-meeting', (ev) => {
const p = ev.participants.local;
// Show local participant as active speaker
// by default.
if (!activeSpeakerId) {
activeSpeakerId = p.session_id;
}
participantConnected(p, callObject);
// Set the current active Participant.
setCurrentActiveParticipant(p, callObject);
})
.on('participant-joined', (ev) => {
const p = ev.participant;
participantConnected(p, callObject);
})
.on('participant-left', (ev) => {
const p = ev.participant;
participantDisconnected(p.session_id, callObject);
})
.on('active-speaker-change', (ev) => {
// Retrieve ID of the current speaker
const sessionId = ev.activeSpeaker.peerId;
// Update the active speaker global
activeSpeakerId = sessionId;
// If active speaker is not pinned, update
// the active speaker tile.
if (!isActiveParticipantPinned) {
// Get all participants in the call
const participants = callObject.participants();
const p = participants[sessionId];
setCurrentActiveParticipant(p, callObject);
}
})
.on('track-started', (ev) => {
const p = ev.participant;
const track = ev.track;
attachTrack(track, p, callObject);
})
.on('track-stopped', (ev) => {
const p = ev.participant;
// If the participant does not exist,
// this must be a user who just left.
// Their departure will be handle in the
// "participant-left" event.
if (!p) return;
const track = ev.track;
detachTrack(track, p);
})
.on('error', (ev) => {
console.error('Fatal error:', ev);
})
.on('nonfatal-error', (ev) => {
console.error('nonfatal-error', ev);
})
// Make the Room available in the JavaScript console for debugging.
window.callObject = callObject;
// Leave the Room when the "Leave Room" button is clicked.
$leave.click(function onLeave() {
$leave.off('click', onLeave);
callObject.leave();
});
callObject.join();
return new Promise((resolve) => {
// Leave the Room when the "beforeunload" event is fired.
window.onbeforeunload = () => {
callObject.leave();
};
if (isMobile) {
// TODO(mmalavalli): investigate why "pagehide" is not working in iOS Safari.
// In iOS Safari, "beforeunload" is not fired, so use "pagehide" instead.
window.onpagehide = () => {
callObject.leave();
};
// On mobile browsers, use "visibilitychange" event to determine when
// the app is backgrounded or foregrounded.
document.onvisibilitychange = async () => {
if (document.visibilityState === 'hidden') {
// When the app is backgrounded, your app can no longer capture
// video frames. So, stop and unpublish the LocalVideoTrack.
callObject.setLocalVideo(false);
} else {
// When the app is foregrounded, your app can now continue to
// capture video frames. So, publish a new LocalVideoTrack.
callObject.setLocalVideo(true);
}
};
}
callObject.on('left-meeting', () => {
// Clear the event handlers on document and window..
window.onbeforeunload = null;
if (isMobile) {
window.onpagehide = null;
document.onvisibilitychange = null;
}
removeAllParticipants();
// Clear the active Participant's video.
$activeVideo.get(0).srcObject = null;
// Clear the Room reference used for debugging from the JavaScript console.
callObject.destroy();
window.callObject = null;
resolve();
});
});
}
module.exports = joinRoom;