/
index.js
489 lines (433 loc) · 15 KB
/
index.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
/*!
* Copyright (c) 2015-2020 Cisco Systems, Inc. See LICENSE file.
*/
/* globals navigator */
import bowser from 'bowser';
import LoggerProxy from '../common/logs/logger-proxy';
import {
AUDIO_INPUT,
VIDEO_INPUT,
PEER_CONNECTION_STATE
} from '../constants';
import PeerConnectionManager from '../peer-connection-manager';
import ReconnectionError from '../common/errors/reconnection';
import MediaError from '../common/errors/media';
/**
* MediaDirection
* @typedef {Object} MediaDirection
* @property {boolean} sendAudio
* @property {boolean} receiveAudio
* @property {boolean} sendVideo
* @property {boolean} receiveVideo
* @property {boolean} sendShare
* @property {boolean} receiveShare
*/
/**
* SendOptions
* @typedef {Object} SendOptions
* @property sendAudio
* @property sendVideo
* @property sendShare
* @property {Object} sharePreferences
*/
/**
*
* @public
* @export
* Mimic browser APIs as "the ultimate browser".
* Handles the quirks of each browser.
* Extends and enhances adapter.js, i.e., the "media" file from the web client.
*/
const Media = {};
/**
* @param {boolean} enabled
* @param {MediaStreamTrack} track
* @returns {Boolean}
* @public
*/
Media.setLocalTrack = (enabled, track) => {
if (track) {
track.enabled = !enabled;
return true;
}
return false;
};
/**
* @param {RTCPeerConnection} peerConnection
* @param {Object} meetingProperties
* @param {string} meetingProperties.meetingId
* @param {string} meetingProperties.remoteQualityLevel LOW|MEDIUM|HIGH
* @returns {Promise}
*/
Media.reconnectMedia = (peerConnection, {meetingId, remoteQualityLevel}) => {
if (peerConnection.connectionState === PEER_CONNECTION_STATE.CLOSED ||
peerConnection.connectionState === PEER_CONNECTION_STATE.FAILED) {
return Promise.reject(new ReconnectionError('Reinitiate peerconnection'));
}
return PeerConnectionManager.createOffer(peerConnection, {meetingId, remoteQualityLevel});
};
/**
* format the media array for send
* @param {String} mediaId
* @param {Boolean} audioMuted
* @param {Boolean} videoMuted
* @returns {Array} medias
*/
Media.generateLocalMedias = (mediaId, audioMuted, videoMuted) => {
if (mediaId) {
return [
{
localSdp: JSON.stringify({
audioMuted,
videoMuted
}),
mediaId
}
];
}
return [];
};
/**
* make a browser call to get the media
* @param {SendOptions} options
* @param {Object} config SDK Configuration for meetings plugin
* @returns {Promise}
*/
Media.getLocalMedia = (options, config) => {
const {
sendAudio, sendVideo, sendShare, sharePreferences
} = options;
if (sendAudio || sendVideo) {
return Media.getMedia(sendAudio, sendVideo, config);
}
if (sendShare) {
return Media.getDisplayMedia(
{
sendAudio: false,
sendShare: true,
sharePreferences
},
config
);
}
return Promise.resolve(undefined);
};
/**
* Returns the direction and tracks
* @param {string} trackType type of track (audio/video)
* @param {object} track tracks passed
* @param {boolean} receiveTracks do you want to receive tracks from the remote side
* @returns {Object} returns direction tracks to be added in transceiver
*/
Media.checkTracks = (trackType, track, receiveTracks) => {
const getDirection = (sendTracks, receiveTracks) => {
if (sendTracks && receiveTracks) {
return 'sendrecv';
} if (sendTracks && !receiveTracks) {
return 'sendonly';
} if (!sendTracks && receiveTracks) {
return 'recvonly';
} if (sendTracks && receiveTracks) {
return 'inactive';
}
return 'inactive';
};
if (track) {
return {track, direction: getDirection(!!track, receiveTracks)};
}
return {track: trackType, direction: getDirection(!!track, receiveTracks)};
};
/**
* creates peerconnection and attaches streams
* @param {MediaDirection} mediaProperties
* @param {Object} meetingProperties
* @param {string} meetingProperties.meetingId
* @param {string} meetingProperties.remoteQualityLevel LOW|MEDIUM|HIGH
* @returns {Array} [peerConnection, ]
*/
Media.attachMedia = (mediaProperties, {meetingId, remoteQualityLevel}) => {
const {
mediaDirection, audioTrack, videoTrack, shareTrack, peerConnection
} = mediaProperties;
let result = null;
// Add Transceiver for audio
result = Media.checkTracks('audio', mediaDirection.sendAudio && audioTrack, mediaDirection.receiveAudio);
peerConnection.audioTransceiver = peerConnection.addTransceiver(result.track, {direction: result.direction});
// Add Transceiver for video
result = Media.checkTracks('video', mediaDirection.sendVideo && videoTrack, mediaDirection.receiveVideo);
peerConnection.videoTransceiver = peerConnection.addTransceiver(result.track, {direction: result.direction});
// Add Transceiver for share
result = Media.checkTracks('video', mediaDirection.sendShare && shareTrack, mediaDirection.receiveShare);
peerConnection.shareTransceiver = peerConnection.addTransceiver(result.track, {direction: result.direction});
peerConnection.onnegotiationneeded = (event) => {
LoggerProxy.logger.info(`Media->attachMedia/onnegotiationneeded#PeerConnection: ${event}`);
};
return PeerConnectionManager.createOffer(peerConnection, {meetingId, remoteQualityLevel});
};
/**
* updates all the media streams and creates a new media offer
* @param {MediaDirection} mediaProperties
* @param {Object} meetingProperties
* @param {string} meetingProperties.meetingId
* @param {string} meetingProperties.remoteQualityLevel LOW|MEDIUM|HIGH
* @returns {Promise}
*/
Media.updateMedia = (mediaProperties, {meetingId, remoteQualityLevel}) => {
const {
mediaDirection, audioTrack, videoTrack, shareTrack, peerConnection
} = mediaProperties;
// update audio transceiver
Media.setTrackOnTransceiver(peerConnection.audioTransceiver, {
type: 'audio',
track: audioTrack,
sendTrack: mediaDirection.sendAudio && audioTrack,
receiveTrack: mediaDirection.receiveAudio
});
// update video transceiver
Media.setTrackOnTransceiver(peerConnection.videoTransceiver, {
type: 'video',
track: videoTrack,
sendTrack: mediaDirection.sendVideo && videoTrack,
receiveTrack: mediaDirection.receiveVideo
});
// update content transceiver
Media.setTrackOnTransceiver(peerConnection.shareTransceiver, {
type: 'video',
track: shareTrack,
sendTrack: mediaDirection.sendShare && shareTrack,
receiveTrack: mediaDirection.receiveShare
});
peerConnection.onnegotiationneeded = (event) => {
LoggerProxy.logger.info(`Media->attachMedia/onnegotiationneeded#PeerConnection: ${event}`);
};
return PeerConnectionManager.createOffer(peerConnection, {meetingId, remoteQualityLevel});
};
/**
* @param {RTCRtpTransceiver} transceiver
* @param {Object} options
* @param {MediaStreamTrack} options.track
* @returns {undefined}
*/
Media.setTrackOnTransceiver = (transceiver, options) => {
const {
type, track, sendTrack, receiveTrack
} = options;
try {
const result = Media.checkTracks(type, sendTrack && track, receiveTrack);
transceiver.direction = result.direction;
if (options.track) {
transceiver.sender.replaceTrack(track);
}
}
catch (e) {
throw e;
}
};
/**
* creates a new offer
* @param {Object} meetingProperties
* @param {string} meetingProperties.meetingId
* @param {string} meetingProperties.remoteQualityLevel LOW|MEDIUM|HIGH
* @param {RTCPeerConnection} peerConnection
* @param {RTCRtpTransceiver} transceiver
* @param {Object} options see #Media.setTrackOnTransceiver
* @returns {Promise}
*/
Media.updateTransceiver = ({meetingId, remoteQualityLevel}, peerConnection, transceiver, options) => {
Media.setTrackOnTransceiver(transceiver, options);
return PeerConnectionManager.createOffer(peerConnection, {meetingId, remoteQualityLevel});
};
/**
* generates share streams
* @param {object} options parameter
* @param {Object} options.sendAudio sendAudio: {Boolean} sendAudio constraints
* @param {Object} options.sendShare sendShare: {Boolean} sendShare constraints
* @param {Object} options.sharePreferences sharePreferences: {Object} Share constraints and share constraints
* @param {Object} config SDK Configuration for meetings plugin
* @returns {Object} {streams}
*/
Media.getDisplayMedia = (options, config) => {
const shareConstraints = options.sharePreferences && options.sharePreferences.shareConstraints || {
cursor: 'always',
frameRate: options.sharePreferences && options.sharePreferences.highFrameRate ? config.videoShareFrameRate : config.screenFrameRate,
aspectRatio: config.aspectRatio,
width: options.sharePreferences && options.sharePreferences.highFrameRate ? config.resolution.idealWidth : config.screenResolution.idealWidth,
height: options.sharePreferences && options.sharePreferences.highFrameRate ? config.resolution.idealHeight : config.screenResolution.idealHeight
};
// chrome and webkit based browsers (edge, safari) automatically adjust everything
// and we have noticed higher quality with those browser types
// firefox specifically has some issues with resolution and frame rate decision making
// so we are making it optional and configurable (with defaults) for firefox
// to have higher quality, and for developers to control the values
// eventually we may have to add the same functionality to chrome, OR conversely, get to with firefox
if (bowser.name.toLowerCase() === 'firefox') {
const mediaConfig = {
audio: options.sendAudio,
video: options.sendShare
};
return navigator.mediaDevices.getDisplayMedia({audio: options.sendAudio, video: mediaConfig})
.then((stream) => {
if (options.sendShare && stream.getVideoTracks().length > 0) {
// Firefox has a bug with the spec where changing in the height and width only happens
// after we get the inital tracks
// https://bugzilla.mozilla.org/show_bug.cgi?id=1321221
stream.getVideoTracks()[0].applyConstraints(shareConstraints);
}
return stream;
});
}
return navigator.mediaDevices.getDisplayMedia({audio: options.sendAudio, video: options.sendShare ? shareConstraints : false});
};
/**
* generates audio and video using constraints (often called after getSupportedDevices)
* @param {Object|Boolean} audio gum constraints
* @param {Object|Boolean} video gum constraints
* @param {Object} config SDK Configuration for meetings plugin
* @returns {Object} {streams}
*/
Media.getMedia = (audio, video, config) => {
const defaultWidth = {ideal: config.resolution.idealWidth, max: config.resolution.maxWidth};
const defaultHeight = {ideal: config.resolution.idealHeight, max: config.resolution.maxHeight};
const mediaConfig = {
audio,
video: video ? {
deviceId: video.deviceId ? video.deviceId : undefined,
width: video.width ? video.width : defaultWidth,
height: video.height ? video.height : defaultHeight
} : false,
fake: process.env.NODE_ENV === 'test' // Special case to get fake media for Firefox browser for testing
};
return new Promise((resolve, reject) => {
navigator.mediaDevices
.getUserMedia(mediaConfig)
.then((stream) => {
resolve(stream);
})
.catch((err) => {
reject(
new MediaError('Local Get User Media failed', {
name: err.name,
localMediaFailed: true,
cameraFailed: err === mediaConfig.permissionDenied
})
);
});
});
};
/**
* Checks if the machine has at least one audio or video device (Dont use this for screen share)
* @param {object} [options]
* {
* sendAudio: true/false,
* sendVideo: true/false
* }
* @returns {Object} {
* sendAudio: true/false,
* sendVideo: true/false
*}
*/
Media.getSupportedDevice = ({sendAudio, sendVideo}) =>
Promise.resolve().then(() => {
if (!navigator.mediaDevices || navigator.mediaDevices.enumerateDevices === undefined) {
return {
sendAudio: true,
sendVideo: true
};
}
return navigator.mediaDevices.enumerateDevices().then((devices) => {
const supported = {
audio: devices.filter((device) => device.kind === AUDIO_INPUT).length > 0,
video: devices.filter((device) => device.kind === VIDEO_INPUT).length > 0
};
return {
sendAudio: (supported.audio && sendAudio) || true,
sendVideo: (supported.video && sendVideo) || true
};
});
});
/**
* proxy to browser navigator.mediaDevices.enumerateDevices()
* @returns {Promise}
*/
Media.getDevices = () => {
if (navigator && navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
return navigator.mediaDevices.enumerateDevices();
}
return Promise.reject(new MediaError('enumerateDevices not supported.'));
};
/**
*
* Toggle a specific stream
* noop as of now, does nothing
* @returns {null}
*/
Media.toggleStream = () => {};
/**
* Stop input stream
* @param {MediaTrack} track A media stream
* @returns {null}
*/
Media.stopTracks = (track) => {
if (!track) {
return Promise.resolve();
}
return Promise.resolve().then(() => {
if (track && track.stop) {
try {
track.stop();
}
catch (e) {
LoggerProxy.logger.error(`media/index->stopTracks#Unable to stop the track with state ${track.readyState}, error: ${e}`);
}
}
});
};
/**
*
* Stop input stream
* @param {Stream} stream A media stream
* @returns {null}
*/
Media.stopStream = (stream) => {
if (!stream) {
return Promise.resolve();
}
/*
* To release local media
* 1) Chrome requires all tracks to be stopped (stream.stop got deprecated)
* 2) Firefox requires the stream to be stopped
*/
return Promise.resolve().then(() => {
if (stream.getTracks) {
stream.getTracks().forEach((track) => {
track.stop();
});
}
else if (stream.stop) {
stream.stop();
}
});
};
/**
* generates streams for audio video and share
* @param {object} mediaSetting parameter
* @param {Object} mediaSetting.sendAudio sendAudio: {Boolean} sendAudio constraints
* @param {Object} mediaSetting.sendVideo sendVideo: {Boolean} sendVideo constraints
* @param {Object} mediaSetting.sendShare sendShare: {Boolean} sendShare constraints
* @param {Object} audioVideo parameter
* @param {Object} audioVideo.audio {deviceId: {String}}
* @param {Object} audioVideo.video {deviceId: {String}}
* @param {Object} sharePreferences parameter
* @param {Object} sharePreferences.shareConstraints parameter
* @param {Boolean} sharePreferences.highFrameRate parameter
* @param {Object} config SDK Config
* @returns {Array} [localStream, shareStream]
*/
Media.getUserMedia = (mediaSetting, audioVideo, sharePreferences, config) => Media.getLocalMedia({
sendAudio: mediaSetting.sendAudio ? audioVideo.audio || mediaSetting.sendAudio : false,
sendVideo: mediaSetting.sendVideo ? audioVideo.video || mediaSetting.sendVideo : false
}, config).then((localStream) => Media.getLocalMedia({
sendShare: mediaSetting.sendShare,
sharePreferences
}, config).then((shareStream) => [localStream, shareStream]));
export default Media;