You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. /* global config, require, attachMediaStream, getUserMedia,
  2. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  3. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  4. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  5. */
  6. /* jshint -W101 */
  7. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8. var RTCBrowserType = require("./RTCBrowserType");
  9. var Resolutions = require("../../service/RTC/Resolutions");
  10. var RTCEvents = require("../../service/RTC/RTCEvents");
  11. var AdapterJS = require("./adapter.screenshare");
  12. var SDPUtil = require("../xmpp/SDPUtil");
  13. var EventEmitter = require("events");
  14. var screenObtainer = require("./ScreenObtainer");
  15. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  16. var MediaType = require("../../service/RTC/MediaType");
  17. var VideoType = require("../../service/RTC/VideoType");
  18. var GlobalOnErrorHandler = require("../util/GlobalOnErrorHandler");
  19. var eventEmitter = new EventEmitter();
  20. var AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  21. var devices = {
  22. audio: false,
  23. video: false
  24. };
  25. // Currently audio output device change is supported only in Chrome and
  26. // default output always has 'default' device ID
  27. var audioOutputDeviceId = 'default'; // default device
  28. var featureDetectionAudioEl = document.createElement('audio');
  29. var isAudioOutputDeviceChangeAvailable =
  30. typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  31. var currentlyAvailableMediaDevices = [];
  32. var rawEnumerateDevicesWithCallback = navigator.mediaDevices
  33. && navigator.mediaDevices.enumerateDevices
  34. ? function(callback) {
  35. navigator.mediaDevices.enumerateDevices().then(callback, function () {
  36. callback([]);
  37. });
  38. }
  39. : (MediaStreamTrack && MediaStreamTrack.getSources)
  40. ? function (callback) {
  41. MediaStreamTrack.getSources(function (sources) {
  42. callback(sources.map(convertMediaStreamTrackSource));
  43. });
  44. }
  45. : undefined;
  46. // TODO: currently no browser supports 'devicechange' event even in nightly
  47. // builds so no feature/browser detection is used at all. However in future this
  48. // should be changed to some expression. Progress on 'devicechange' event
  49. // implementation for Chrome/Opera/NWJS can be tracked at
  50. // https://bugs.chromium.org/p/chromium/issues/detail?id=388648, for Firefox -
  51. // at https://bugzilla.mozilla.org/show_bug.cgi?id=1152383. More information on
  52. // 'devicechange' event can be found in spec -
  53. // http://w3c.github.io/mediacapture-main/#event-mediadevices-devicechange
  54. // TODO: check MS Edge
  55. var isDeviceChangeEventSupported = false;
  56. var rtcReady = false;
  57. function setResolutionConstraints(constraints, resolution) {
  58. var isAndroid = RTCBrowserType.isAndroid();
  59. if (Resolutions[resolution]) {
  60. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  61. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  62. }
  63. else if (isAndroid) {
  64. // FIXME can't remember if the purpose of this was to always request
  65. // low resolution on Android ? if yes it should be moved up front
  66. constraints.video.mandatory.minWidth = 320;
  67. constraints.video.mandatory.minHeight = 180;
  68. constraints.video.mandatory.maxFrameRate = 15;
  69. }
  70. if (constraints.video.mandatory.minWidth)
  71. constraints.video.mandatory.maxWidth =
  72. constraints.video.mandatory.minWidth;
  73. if (constraints.video.mandatory.minHeight)
  74. constraints.video.mandatory.maxHeight =
  75. constraints.video.mandatory.minHeight;
  76. }
  77. /**
  78. * @param {string[]} um required user media types
  79. *
  80. * @param {Object} [options={}] optional parameters
  81. * @param {string} options.resolution
  82. * @param {number} options.bandwidth
  83. * @param {number} options.fps
  84. * @param {string} options.desktopStream
  85. * @param {string} options.cameraDeviceId
  86. * @param {string} options.micDeviceId
  87. * @param {bool} firefox_fake_device
  88. */
  89. function getConstraints(um, options) {
  90. var constraints = {audio: false, video: false};
  91. if (um.indexOf('video') >= 0) {
  92. // same behaviour as true
  93. constraints.video = { mandatory: {}, optional: [] };
  94. if (options.cameraDeviceId) {
  95. // new style of settings device id (FF only)
  96. constraints.video.deviceId = options.cameraDeviceId;
  97. // old style
  98. constraints.video.optional.push({
  99. sourceId: options.cameraDeviceId
  100. });
  101. }
  102. constraints.video.optional.push({ googLeakyBucket: true });
  103. setResolutionConstraints(constraints, options.resolution);
  104. }
  105. if (um.indexOf('audio') >= 0) {
  106. if (!RTCBrowserType.isFirefox()) {
  107. // same behaviour as true
  108. constraints.audio = { mandatory: {}, optional: []};
  109. if (options.micDeviceId) {
  110. // new style of settings device id (FF only)
  111. constraints.audio.deviceId = options.micDeviceId;
  112. // old style
  113. constraints.audio.optional.push({
  114. sourceId: options.micDeviceId
  115. });
  116. }
  117. // if it is good enough for hangouts...
  118. constraints.audio.optional.push(
  119. {googEchoCancellation: true},
  120. {googAutoGainControl: true},
  121. {googNoiseSupression: true},
  122. {googHighpassFilter: true},
  123. {googNoisesuppression2: true},
  124. {googEchoCancellation2: true},
  125. {googAutoGainControl2: true}
  126. );
  127. } else {
  128. if (options.micDeviceId) {
  129. constraints.audio = {
  130. mandatory: {},
  131. deviceId: options.micDeviceId, // new style
  132. optional: [{
  133. sourceId: options.micDeviceId // old style
  134. }]};
  135. } else {
  136. constraints.audio = true;
  137. }
  138. }
  139. }
  140. if (um.indexOf('screen') >= 0) {
  141. if (RTCBrowserType.isChrome()) {
  142. constraints.video = {
  143. mandatory: {
  144. chromeMediaSource: "screen",
  145. googLeakyBucket: true,
  146. maxWidth: window.screen.width,
  147. maxHeight: window.screen.height,
  148. maxFrameRate: 3
  149. },
  150. optional: []
  151. };
  152. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  153. constraints.video = {
  154. optional: [
  155. {
  156. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  157. }
  158. ]
  159. };
  160. } else if (RTCBrowserType.isFirefox()) {
  161. constraints.video = {
  162. mozMediaSource: "window",
  163. mediaSource: "window"
  164. };
  165. } else {
  166. var errmsg
  167. = "'screen' WebRTC media source is supported only in Chrome"
  168. + " and with Temasys plugin";
  169. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  170. logger.error(errmsg);
  171. }
  172. }
  173. if (um.indexOf('desktop') >= 0) {
  174. constraints.video = {
  175. mandatory: {
  176. chromeMediaSource: "desktop",
  177. chromeMediaSourceId: options.desktopStream,
  178. googLeakyBucket: true,
  179. maxWidth: window.screen.width,
  180. maxHeight: window.screen.height,
  181. maxFrameRate: 3
  182. },
  183. optional: []
  184. };
  185. }
  186. if (options.bandwidth) {
  187. if (!constraints.video) {
  188. //same behaviour as true
  189. constraints.video = {mandatory: {}, optional: []};
  190. }
  191. constraints.video.optional.push({bandwidth: options.bandwidth});
  192. }
  193. if(options.minFps || options.maxFps || options.fps) {
  194. // for some cameras it might be necessary to request 30fps
  195. // so they choose 30fps mjpg over 10fps yuy2
  196. if (!constraints.video) {
  197. // same behaviour as true;
  198. constraints.video = {mandatory: {}, optional: []};
  199. }
  200. if(options.minFps || options.fps) {
  201. options.minFps = options.minFps || options.fps; //Fall back to options.fps for backwards compatibility
  202. constraints.video.mandatory.minFrameRate = options.minFps;
  203. }
  204. if(options.maxFps) {
  205. constraints.video.mandatory.maxFrameRate = options.maxFps;
  206. }
  207. }
  208. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  209. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  210. // this later can be a problem with some of the tests
  211. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  212. {
  213. // seems to be fixed now, removing this experimental fix, as having
  214. // multiple audio tracks brake the tests
  215. //constraints.audio = true;
  216. constraints.fake = true;
  217. }
  218. return constraints;
  219. }
  220. function setAvailableDevices(um, available) {
  221. if (um.indexOf("video") != -1) {
  222. devices.video = available;
  223. }
  224. if (um.indexOf("audio") != -1) {
  225. devices.audio = available;
  226. }
  227. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  228. }
  229. /**
  230. * Checks if new list of available media devices differs from previous one.
  231. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  232. * @returns {boolean} - true if list is different, false otherwise.
  233. */
  234. function compareAvailableMediaDevices(newDevices) {
  235. if (newDevices.length !== currentlyAvailableMediaDevices.length) {
  236. return true;
  237. }
  238. return newDevices.map(mediaDeviceInfoToJSON).sort().join('') !==
  239. currentlyAvailableMediaDevices.map(mediaDeviceInfoToJSON).sort().join('');
  240. function mediaDeviceInfoToJSON(info) {
  241. return JSON.stringify({
  242. kind: info.kind,
  243. deviceId: info.deviceId,
  244. groupId: info.groupId,
  245. label: info.label,
  246. facing: info.facing
  247. });
  248. }
  249. }
  250. /**
  251. * Periodically polls enumerateDevices() method to check if list of media
  252. * devices has changed. This is temporary workaround until 'devicechange' event
  253. * will be supported by browsers.
  254. */
  255. function pollForAvailableMediaDevices() {
  256. // Here we use plain navigator.mediaDevices.enumerateDevices instead of
  257. // wrapped because we just need to know the fact the devices changed, labels
  258. // do not matter. This fixes situation when we have no devices initially,
  259. // and then plug in a new one.
  260. if (rawEnumerateDevicesWithCallback) {
  261. rawEnumerateDevicesWithCallback(function (devices) {
  262. if (compareAvailableMediaDevices(devices)) {
  263. onMediaDevicesListChanged(devices);
  264. }
  265. window.setTimeout(pollForAvailableMediaDevices,
  266. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  267. });
  268. }
  269. }
  270. /**
  271. * Event handler for the 'devicechange' event.
  272. * @param {MediaDeviceInfo[]} devices - list of media devices.
  273. * @emits RTCEvents.DEVICE_LIST_CHANGED
  274. */
  275. function onMediaDevicesListChanged(devices) {
  276. currentlyAvailableMediaDevices = devices.slice(0);
  277. logger.info('list of media devices has changed:', currentlyAvailableMediaDevices);
  278. var videoInputDevices = currentlyAvailableMediaDevices.filter(function (d) {
  279. return d.kind === 'videoinput';
  280. }),
  281. audioInputDevices = currentlyAvailableMediaDevices.filter(function (d) {
  282. return d.kind === 'audioinput';
  283. }),
  284. videoInputDevicesWithEmptyLabels = videoInputDevices.filter(
  285. function (d) {
  286. return d.label === '';
  287. }),
  288. audioInputDevicesWithEmptyLabels = audioInputDevices.filter(
  289. function (d) {
  290. return d.label === '';
  291. });
  292. if (videoInputDevices.length &&
  293. videoInputDevices.length === videoInputDevicesWithEmptyLabels.length) {
  294. setAvailableDevices(['video'], false);
  295. }
  296. if (audioInputDevices.length &&
  297. audioInputDevices.length === audioInputDevicesWithEmptyLabels.length) {
  298. setAvailableDevices(['audio'], false);
  299. }
  300. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, devices);
  301. }
  302. // In case of IE we continue from 'onReady' callback
  303. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  304. // once it is initialized.
  305. function onReady (options, GUM) {
  306. rtcReady = true;
  307. eventEmitter.emit(RTCEvents.RTC_READY, true);
  308. screenObtainer.init(options, GUM);
  309. if (isDeviceChangeEventSupported && RTCUtils.isDeviceListAvailable()) {
  310. navigator.mediaDevices.addEventListener('devicechange', function () {
  311. RTCUtils.enumerateDevices(onMediaDevicesListChanged);
  312. });
  313. } else if (RTCUtils.isDeviceListAvailable()) {
  314. pollForAvailableMediaDevices();
  315. }
  316. }
  317. /**
  318. * Apply function with arguments if function exists.
  319. * Do nothing if function not provided.
  320. * @param {function} [fn] function to apply
  321. * @param {Array} [args=[]] arguments for function
  322. */
  323. function maybeApply(fn, args) {
  324. if (fn) {
  325. fn.apply(null, args || []);
  326. }
  327. }
  328. var getUserMediaStatus = {
  329. initialized: false,
  330. callbacks: []
  331. };
  332. /**
  333. * Wrap `getUserMedia` to allow others to know if it was executed at least
  334. * once or not. Wrapper function uses `getUserMediaStatus` object.
  335. * @param {Function} getUserMedia native function
  336. * @returns {Function} wrapped function
  337. */
  338. function wrapGetUserMedia(getUserMedia) {
  339. return function (constraints, successCallback, errorCallback) {
  340. getUserMedia(constraints, function (stream) {
  341. maybeApply(successCallback, [stream]);
  342. if (!getUserMediaStatus.initialized) {
  343. getUserMediaStatus.initialized = true;
  344. getUserMediaStatus.callbacks.forEach(function (callback) {
  345. callback();
  346. });
  347. getUserMediaStatus.callbacks.length = 0;
  348. }
  349. }, function (error) {
  350. maybeApply(errorCallback, [error]);
  351. });
  352. };
  353. }
  354. /**
  355. * Execute function after getUserMedia was executed at least once.
  356. * @param {Function} callback function to execute after getUserMedia
  357. */
  358. function afterUserMediaInitialized(callback) {
  359. if (getUserMediaStatus.initialized) {
  360. callback();
  361. } else {
  362. getUserMediaStatus.callbacks.push(callback);
  363. }
  364. }
  365. /**
  366. * Wrapper function which makes enumerateDevices to wait
  367. * until someone executes getUserMedia first time.
  368. * @param {Function} enumerateDevices native function
  369. * @returns {Funtion} wrapped function
  370. */
  371. function wrapEnumerateDevices(enumerateDevices) {
  372. return function (callback) {
  373. // enumerate devices only after initial getUserMedia
  374. afterUserMediaInitialized(function () {
  375. enumerateDevices().then(callback, function (err) {
  376. logger.error('cannot enumerate devices: ', err);
  377. callback([]);
  378. });
  379. });
  380. };
  381. }
  382. /**
  383. * Use old MediaStreamTrack to get devices list and
  384. * convert it to enumerateDevices format.
  385. * @param {Function} callback function to call when received devices list.
  386. */
  387. function enumerateDevicesThroughMediaStreamTrack (callback) {
  388. MediaStreamTrack.getSources(function (sources) {
  389. callback(sources.map(convertMediaStreamTrackSource));
  390. });
  391. }
  392. /**
  393. * Converts MediaStreamTrack Source to enumerateDevices format.
  394. * @param {Object} source
  395. */
  396. function convertMediaStreamTrackSource(source) {
  397. var kind = (source.kind || '').toLowerCase();
  398. return {
  399. facing: source.facing || null,
  400. label: source.label,
  401. // theoretically deprecated MediaStreamTrack.getSources should
  402. // not return 'audiooutput' devices but let's handle it in any
  403. // case
  404. kind: kind
  405. ? (kind === 'audiooutput' ? kind : kind + 'input')
  406. : null,
  407. deviceId: source.id,
  408. groupId: source.groupId || null
  409. };
  410. }
  411. function obtainDevices(options) {
  412. if(!options.devices || options.devices.length === 0) {
  413. return options.successCallback(options.streams || {});
  414. }
  415. var device = options.devices.splice(0, 1);
  416. var devices = [];
  417. devices.push(device);
  418. options.deviceGUM[device](function (stream) {
  419. options.streams = options.streams || {};
  420. options.streams[device] = stream;
  421. obtainDevices(options);
  422. },
  423. function (error) {
  424. Object.keys(options.streams).forEach(function(device) {
  425. RTCUtils.stopMediaStream(options.streams[device]);
  426. });
  427. logger.error(
  428. "failed to obtain " + device + " stream - stop", error);
  429. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  430. });
  431. }
  432. /**
  433. * Handles the newly created Media Streams.
  434. * @param streams the new Media Streams
  435. * @param resolution the resolution of the video streams
  436. * @returns {*[]} object that describes the new streams
  437. */
  438. function handleLocalStream(streams, resolution) {
  439. var audioStream, videoStream, desktopStream, res = [];
  440. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  441. // the browser, its capabilities, etc. and has taken the decision whether to
  442. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  443. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  444. // the specified streams and figure out what we've received based on
  445. // obtainAudioAndVideoPermissions' decision.
  446. if (streams) {
  447. // As mentioned above, certian types of browser (e.g. Chrome) support
  448. // (with a result which meets our requirements expressed bellow) calling
  449. // getUserMedia once for both audio and video.
  450. var audioVideo = streams.audioVideo;
  451. if (audioVideo) {
  452. var audioTracks = audioVideo.getAudioTracks();
  453. if (audioTracks.length) {
  454. audioStream = new webkitMediaStream();
  455. for (var i = 0; i < audioTracks.length; i++) {
  456. audioStream.addTrack(audioTracks[i]);
  457. }
  458. }
  459. var videoTracks = audioVideo.getVideoTracks();
  460. if (videoTracks.length) {
  461. videoStream = new webkitMediaStream();
  462. for (var j = 0; j < videoTracks.length; j++) {
  463. videoStream.addTrack(videoTracks[j]);
  464. }
  465. }
  466. } else {
  467. // On other types of browser (e.g. Firefox) we choose (namely,
  468. // obtainAudioAndVideoPermissions) to call getUsermedia per device
  469. // (type).
  470. audioStream = streams.audio;
  471. videoStream = streams.video;
  472. }
  473. // Again, different choices on different types of browser.
  474. desktopStream = streams.desktopStream || streams.desktop;
  475. }
  476. if (desktopStream) {
  477. res.push({
  478. stream: desktopStream,
  479. track: desktopStream.getVideoTracks()[0],
  480. mediaType: MediaType.VIDEO,
  481. videoType: VideoType.DESKTOP
  482. });
  483. }
  484. if (audioStream) {
  485. res.push({
  486. stream: audioStream,
  487. track: audioStream.getAudioTracks()[0],
  488. mediaType: MediaType.AUDIO,
  489. videoType: null
  490. });
  491. }
  492. if (videoStream) {
  493. res.push({
  494. stream: videoStream,
  495. track: videoStream.getVideoTracks()[0],
  496. mediaType: MediaType.VIDEO,
  497. videoType: VideoType.CAMERA,
  498. resolution: resolution
  499. });
  500. }
  501. return res;
  502. }
  503. /**
  504. * Wraps original attachMediaStream function to set current audio output device
  505. * if this is supported.
  506. * @param {Function} origAttachMediaStream
  507. * @returns {Function}
  508. */
  509. function wrapAttachMediaStream(origAttachMediaStream) {
  510. return function(element, stream) {
  511. var res = origAttachMediaStream.apply(RTCUtils, arguments);
  512. if (RTCUtils.isDeviceChangeAvailable('output') &&
  513. stream.getAudioTracks && stream.getAudioTracks().length) {
  514. element.setSinkId(RTCUtils.getAudioOutputDevice())
  515. .catch(function (ex) {
  516. GlobalOnErrorHandler.callUnhandledRejectionHandler(
  517. {promise: this, reason: ex});
  518. logger.error('Failed to set audio output on element',
  519. element, ex);
  520. });
  521. }
  522. return res;
  523. }
  524. }
  525. //Options parameter is to pass config options. Currently uses only "useIPv6".
  526. var RTCUtils = {
  527. init: function (options) {
  528. return new Promise(function(resolve, reject) {
  529. if (RTCBrowserType.isFirefox()) {
  530. var FFversion = RTCBrowserType.getFirefoxVersion();
  531. if (FFversion < 40) {
  532. logger.error(
  533. "Firefox version too old: " + FFversion +
  534. ". Required >= 40.");
  535. reject(new Error("Firefox version too old: " + FFversion +
  536. ". Required >= 40."));
  537. return;
  538. }
  539. this.peerconnection = mozRTCPeerConnection;
  540. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  541. this.enumerateDevices = wrapEnumerateDevices(
  542. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  543. );
  544. this.pc_constraints = {};
  545. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  546. // srcObject is being standardized and FF will eventually
  547. // support that unprefixed. FF also supports the
  548. // "element.src = URL.createObjectURL(...)" combo, but that
  549. // will be deprecated in favour of srcObject.
  550. //
  551. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  552. // https://github.com/webrtc/samples/issues/302
  553. if (!element)
  554. return;
  555. element.mozSrcObject = stream;
  556. element.play();
  557. return element;
  558. });
  559. this.getStreamID = function (stream) {
  560. var id = stream.id;
  561. if (!id) {
  562. var tracks = stream.getVideoTracks();
  563. if (!tracks || tracks.length === 0) {
  564. tracks = stream.getAudioTracks();
  565. }
  566. id = tracks[0].id;
  567. }
  568. return SDPUtil.filter_special_chars(id);
  569. };
  570. this.getVideoSrc = function (element) {
  571. if (!element)
  572. return null;
  573. return element.mozSrcObject;
  574. };
  575. this.setVideoSrc = function (element, src) {
  576. if (element)
  577. element.mozSrcObject = src;
  578. };
  579. RTCSessionDescription = mozRTCSessionDescription;
  580. RTCIceCandidate = mozRTCIceCandidate;
  581. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera() || RTCBrowserType.isNWJS()) {
  582. this.peerconnection = webkitRTCPeerConnection;
  583. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  584. if (navigator.mediaDevices) {
  585. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  586. this.enumerateDevices = wrapEnumerateDevices(
  587. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  588. );
  589. } else {
  590. this.getUserMedia = getUserMedia;
  591. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  592. }
  593. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  594. // saves the created url for the stream, so we can reuse it
  595. // and not keep creating urls
  596. if (!stream.jitsiObjectURL) {
  597. stream.jitsiObjectURL
  598. = webkitURL.createObjectURL(stream);
  599. }
  600. element.src = stream.jitsiObjectURL;
  601. return element;
  602. });
  603. this.getStreamID = function (stream) {
  604. // Streams from FF endpoints have the characters '{' and '}'
  605. // that make jQuery choke.
  606. return SDPUtil.filter_special_chars(stream.id);
  607. };
  608. this.getVideoSrc = function (element) {
  609. return element ? element.getAttribute("src") : null;
  610. };
  611. this.setVideoSrc = function (element, src) {
  612. if (element)
  613. element.setAttribute("src", src || '');
  614. };
  615. // DTLS should now be enabled by default but..
  616. this.pc_constraints = {'optional': [
  617. {'DtlsSrtpKeyAgreement': 'true'}
  618. ]};
  619. if (options.useIPv6) {
  620. // https://code.google.com/p/webrtc/issues/detail?id=2828
  621. this.pc_constraints.optional.push({googIPv6: true});
  622. }
  623. if (RTCBrowserType.isAndroid()) {
  624. this.pc_constraints = {}; // disable DTLS on Android
  625. }
  626. if (!webkitMediaStream.prototype.getVideoTracks) {
  627. webkitMediaStream.prototype.getVideoTracks = function () {
  628. return this.videoTracks;
  629. };
  630. }
  631. if (!webkitMediaStream.prototype.getAudioTracks) {
  632. webkitMediaStream.prototype.getAudioTracks = function () {
  633. return this.audioTracks;
  634. };
  635. }
  636. }
  637. // Detect IE/Safari
  638. else if (RTCBrowserType.isTemasysPluginUsed()) {
  639. //AdapterJS.WebRTCPlugin.setLogLevel(
  640. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  641. var self = this;
  642. AdapterJS.webRTCReady(function (isPlugin) {
  643. self.peerconnection = RTCPeerConnection;
  644. self.getUserMedia = window.getUserMedia;
  645. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  646. self.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  647. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  648. return;
  649. }
  650. var isVideoStream = !!stream.getVideoTracks().length;
  651. if (isVideoStream && !$(element).is(':visible')) {
  652. throw new Error('video element must be visible to attach video stream');
  653. }
  654. return attachMediaStream(element, stream);
  655. });
  656. self.getStreamID = function (stream) {
  657. return SDPUtil.filter_special_chars(stream.label);
  658. };
  659. self.getVideoSrc = function (element) {
  660. if (!element) {
  661. logger.warn("Attempt to get video SRC of null element");
  662. return null;
  663. }
  664. var children = element.children;
  665. for (var i = 0; i !== children.length; ++i) {
  666. if (children[i].name === 'streamId') {
  667. return children[i].value;
  668. }
  669. }
  670. //logger.info(element.id + " SRC: " + src);
  671. return null;
  672. };
  673. self.setVideoSrc = function (element, src) {
  674. //logger.info("Set video src: ", element, src);
  675. if (!src) {
  676. attachMediaStream(element, null);
  677. } else {
  678. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  679. var stream
  680. = AdapterJS.WebRTCPlugin.plugin
  681. .getStreamWithId(
  682. AdapterJS.WebRTCPlugin.pageId, src);
  683. attachMediaStream(element, stream);
  684. }
  685. };
  686. onReady(options, self.getUserMediaWithConstraints);
  687. resolve();
  688. });
  689. } else {
  690. var errmsg = 'Browser does not appear to be WebRTC-capable';
  691. try {
  692. logger.error(errmsg);
  693. } catch (e) {
  694. }
  695. reject(new Error(errmsg));
  696. return;
  697. }
  698. // Call onReady() if Temasys plugin is not used
  699. if (!RTCBrowserType.isTemasysPluginUsed()) {
  700. onReady(options, this.getUserMediaWithConstraints);
  701. resolve();
  702. }
  703. }.bind(this));
  704. },
  705. /**
  706. * @param {string[]} um required user media types
  707. * @param {function} success_callback
  708. * @param {Function} failure_callback
  709. * @param {Object} [options] optional parameters
  710. * @param {string} options.resolution
  711. * @param {number} options.bandwidth
  712. * @param {number} options.fps
  713. * @param {string} options.desktopStream
  714. * @param {string} options.cameraDeviceId
  715. * @param {string} options.micDeviceId
  716. **/
  717. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  718. options = options || {};
  719. var resolution = options.resolution;
  720. var constraints = getConstraints(um, options);
  721. logger.info("Get media constraints", constraints);
  722. try {
  723. this.getUserMedia(constraints,
  724. function (stream) {
  725. logger.log('onUserMediaSuccess');
  726. setAvailableDevices(um, true);
  727. success_callback(stream);
  728. },
  729. function (error) {
  730. setAvailableDevices(um, false);
  731. logger.warn('Failed to get access to local media. Error ',
  732. error, constraints);
  733. if (failure_callback) {
  734. failure_callback(error, resolution);
  735. }
  736. });
  737. } catch (e) {
  738. logger.error('GUM failed: ', e);
  739. if (failure_callback) {
  740. failure_callback(e);
  741. }
  742. }
  743. },
  744. /**
  745. * Creates the local MediaStreams.
  746. * @param {Object} [options] optional parameters
  747. * @param {Array} options.devices the devices that will be requested
  748. * @param {string} options.resolution resolution constraints
  749. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  750. * type: "audio" or "video", videoType: "camera" or "desktop"}
  751. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  752. * @param {string} options.cameraDeviceId
  753. * @param {string} options.micDeviceId
  754. * @returns {*} Promise object that will receive the new JitsiTracks
  755. */
  756. obtainAudioAndVideoPermissions: function (options) {
  757. var self = this;
  758. options = options || {};
  759. return new Promise(function (resolve, reject) {
  760. var successCallback = function (stream) {
  761. resolve(handleLocalStream(stream, options.resolution));
  762. };
  763. options.devices = options.devices || ['audio', 'video'];
  764. if(!screenObtainer.isSupported()
  765. && options.devices.indexOf("desktop") !== -1){
  766. reject(new Error("Desktop sharing is not supported!"));
  767. }
  768. if (RTCBrowserType.isFirefox() ||
  769. RTCBrowserType.isTemasysPluginUsed()) {
  770. var GUM = function (device, s, e) {
  771. this.getUserMediaWithConstraints(device, s, e, options);
  772. };
  773. var deviceGUM = {
  774. "audio": GUM.bind(self, ["audio"]),
  775. "video": GUM.bind(self, ["video"])
  776. };
  777. if(screenObtainer.isSupported()){
  778. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  779. screenObtainer);
  780. }
  781. // With FF/IE we can't split the stream into audio and video because FF
  782. // doesn't support media stream constructors. So, we need to get the
  783. // audio stream separately from the video stream using two distinct GUM
  784. // calls. Not very user friendly :-( but we don't have many other
  785. // options neither.
  786. //
  787. // Note that we pack those 2 streams in a single object and pass it to
  788. // the successCallback method.
  789. obtainDevices({
  790. devices: options.devices,
  791. streams: [],
  792. successCallback: successCallback,
  793. errorCallback: reject,
  794. deviceGUM: deviceGUM
  795. });
  796. } else {
  797. var hasDesktop = options.devices.indexOf('desktop') > -1;
  798. if (hasDesktop) {
  799. options.devices.splice(options.devices.indexOf("desktop"), 1);
  800. }
  801. options.resolution = options.resolution || '360';
  802. if(options.devices.length) {
  803. this.getUserMediaWithConstraints(
  804. options.devices,
  805. function (stream) {
  806. if((options.devices.indexOf("audio") !== -1 &&
  807. !stream.getAudioTracks().length) ||
  808. (options.devices.indexOf("video") !== -1 &&
  809. !stream.getVideoTracks().length))
  810. {
  811. self.stopMediaStream(stream);
  812. reject(JitsiTrackErrors.parseError(
  813. new Error("Unable to get the audio and " +
  814. "video tracks."),
  815. options.devices));
  816. return;
  817. }
  818. if(hasDesktop) {
  819. screenObtainer.obtainStream(
  820. function (desktopStream) {
  821. successCallback({audioVideo: stream,
  822. desktopStream: desktopStream});
  823. }, function (error) {
  824. self.stopMediaStream(stream);
  825. reject(
  826. JitsiTrackErrors.parseError(error,
  827. options.devices));
  828. });
  829. } else {
  830. successCallback({audioVideo: stream});
  831. }
  832. },
  833. function (error) {
  834. reject(JitsiTrackErrors.parseError(error,
  835. options.devices));
  836. },
  837. options);
  838. } else if (hasDesktop) {
  839. screenObtainer.obtainStream(
  840. function (stream) {
  841. successCallback({desktopStream: stream});
  842. }, function (error) {
  843. reject(
  844. JitsiTrackErrors.parseError(error,
  845. ["desktop"]));
  846. });
  847. }
  848. }
  849. }.bind(this));
  850. },
  851. addListener: function (eventType, listener) {
  852. eventEmitter.on(eventType, listener);
  853. },
  854. removeListener: function (eventType, listener) {
  855. eventEmitter.removeListener(eventType, listener);
  856. },
  857. getDeviceAvailability: function () {
  858. return devices;
  859. },
  860. isRTCReady: function () {
  861. return rtcReady;
  862. },
  863. /**
  864. * Checks if its possible to enumerate available cameras/micropones.
  865. * @returns {boolean} true if available, false otherwise.
  866. */
  867. isDeviceListAvailable: function () {
  868. var isEnumerateDevicesAvailable
  869. = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  870. if (isEnumerateDevicesAvailable) {
  871. return true;
  872. }
  873. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  874. },
  875. /**
  876. * Returns true if changing the input (camera / microphone) or output
  877. * (audio) device is supported and false if not.
  878. * @params {string} [deviceType] - type of device to change. Default is
  879. * undefined or 'input', 'output' - for audio output device change.
  880. * @returns {boolean} true if available, false otherwise.
  881. */
  882. isDeviceChangeAvailable: function (deviceType) {
  883. return deviceType === 'output' || deviceType === 'audiooutput'
  884. ? isAudioOutputDeviceChangeAvailable
  885. : RTCBrowserType.isChrome() ||
  886. RTCBrowserType.isFirefox() ||
  887. RTCBrowserType.isOpera() ||
  888. RTCBrowserType.isTemasysPluginUsed()||
  889. RTCBrowserType.isNWJS();
  890. },
  891. /**
  892. * A method to handle stopping of the stream.
  893. * One point to handle the differences in various implementations.
  894. * @param mediaStream MediaStream object to stop.
  895. */
  896. stopMediaStream: function (mediaStream) {
  897. mediaStream.getTracks().forEach(function (track) {
  898. // stop() not supported with IE
  899. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  900. track.stop();
  901. }
  902. });
  903. // leave stop for implementation still using it
  904. if (mediaStream.stop) {
  905. mediaStream.stop();
  906. }
  907. // if we have done createObjectURL, lets clean it
  908. if (mediaStream.jitsiObjectURL) {
  909. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  910. }
  911. },
  912. /**
  913. * Returns whether the desktop sharing is enabled or not.
  914. * @returns {boolean}
  915. */
  916. isDesktopSharingEnabled: function () {
  917. return screenObtainer.isSupported();
  918. },
  919. /**
  920. * Sets current audio output device.
  921. * @param {string} deviceId - id of 'audiooutput' device from
  922. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  923. * device
  924. * @returns {Promise} - resolves when audio output is changed, is rejected
  925. * otherwise
  926. */
  927. setAudioOutputDevice: function (deviceId) {
  928. if (!this.isDeviceChangeAvailable('output')) {
  929. Promise.reject(
  930. new Error('Audio output device change is not supported'));
  931. }
  932. return featureDetectionAudioEl.setSinkId(deviceId)
  933. .then(function() {
  934. audioOutputDeviceId = deviceId;
  935. logger.log('Audio output device set to ' + deviceId);
  936. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  937. deviceId);
  938. });
  939. },
  940. /**
  941. * Returns currently used audio output device id, '' stands for default
  942. * device
  943. * @returns {string}
  944. */
  945. getAudioOutputDevice: function () {
  946. return audioOutputDeviceId;
  947. }
  948. };
  949. module.exports = RTCUtils;