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.

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