Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RTCUtils.js 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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.warn('Failed to set audio output device for the ' +
  519. 'element. Default audio output device will be used ' +
  520. 'instead',
  521. element, ex);
  522. });
  523. }
  524. return res;
  525. }
  526. }
  527. //Options parameter is to pass config options. Currently uses only "useIPv6".
  528. var RTCUtils = {
  529. init: function (options) {
  530. return new Promise(function(resolve, reject) {
  531. if (RTCBrowserType.isFirefox()) {
  532. var FFversion = RTCBrowserType.getFirefoxVersion();
  533. if (FFversion < 40) {
  534. logger.error(
  535. "Firefox version too old: " + FFversion +
  536. ". Required >= 40.");
  537. reject(new Error("Firefox version too old: " + FFversion +
  538. ". Required >= 40."));
  539. return;
  540. }
  541. this.peerconnection = mozRTCPeerConnection;
  542. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  543. this.enumerateDevices = wrapEnumerateDevices(
  544. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  545. );
  546. this.pc_constraints = {};
  547. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  548. // srcObject is being standardized and FF will eventually
  549. // support that unprefixed. FF also supports the
  550. // "element.src = URL.createObjectURL(...)" combo, but that
  551. // will be deprecated in favour of srcObject.
  552. //
  553. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  554. // https://github.com/webrtc/samples/issues/302
  555. if (!element)
  556. return;
  557. element.mozSrcObject = stream;
  558. element.play();
  559. return element;
  560. });
  561. this.getStreamID = function (stream) {
  562. var id = stream.id;
  563. if (!id) {
  564. var tracks = stream.getVideoTracks();
  565. if (!tracks || tracks.length === 0) {
  566. tracks = stream.getAudioTracks();
  567. }
  568. id = tracks[0].id;
  569. }
  570. return SDPUtil.filter_special_chars(id);
  571. };
  572. this.getVideoSrc = function (element) {
  573. if (!element)
  574. return null;
  575. return element.mozSrcObject;
  576. };
  577. this.setVideoSrc = function (element, src) {
  578. if (element)
  579. element.mozSrcObject = src;
  580. };
  581. RTCSessionDescription = mozRTCSessionDescription;
  582. RTCIceCandidate = mozRTCIceCandidate;
  583. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera() || RTCBrowserType.isNWJS()) {
  584. this.peerconnection = webkitRTCPeerConnection;
  585. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  586. if (navigator.mediaDevices) {
  587. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  588. this.enumerateDevices = wrapEnumerateDevices(
  589. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  590. );
  591. } else {
  592. this.getUserMedia = getUserMedia;
  593. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  594. }
  595. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  596. // saves the created url for the stream, so we can reuse it
  597. // and not keep creating urls
  598. if (!stream.jitsiObjectURL) {
  599. stream.jitsiObjectURL
  600. = webkitURL.createObjectURL(stream);
  601. }
  602. element.src = stream.jitsiObjectURL;
  603. return element;
  604. });
  605. this.getStreamID = function (stream) {
  606. // Streams from FF endpoints have the characters '{' and '}'
  607. // that make jQuery choke.
  608. return SDPUtil.filter_special_chars(stream.id);
  609. };
  610. this.getVideoSrc = function (element) {
  611. return element ? element.getAttribute("src") : null;
  612. };
  613. this.setVideoSrc = function (element, src) {
  614. if (element)
  615. element.setAttribute("src", src || '');
  616. };
  617. // DTLS should now be enabled by default but..
  618. this.pc_constraints = {'optional': [
  619. {'DtlsSrtpKeyAgreement': 'true'}
  620. ]};
  621. if (options.useIPv6) {
  622. // https://code.google.com/p/webrtc/issues/detail?id=2828
  623. this.pc_constraints.optional.push({googIPv6: true});
  624. }
  625. if (RTCBrowserType.isAndroid()) {
  626. this.pc_constraints = {}; // disable DTLS on Android
  627. }
  628. if (!webkitMediaStream.prototype.getVideoTracks) {
  629. webkitMediaStream.prototype.getVideoTracks = function () {
  630. return this.videoTracks;
  631. };
  632. }
  633. if (!webkitMediaStream.prototype.getAudioTracks) {
  634. webkitMediaStream.prototype.getAudioTracks = function () {
  635. return this.audioTracks;
  636. };
  637. }
  638. }
  639. // Detect IE/Safari
  640. else if (RTCBrowserType.isTemasysPluginUsed()) {
  641. //AdapterJS.WebRTCPlugin.setLogLevel(
  642. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  643. var self = this;
  644. AdapterJS.webRTCReady(function (isPlugin) {
  645. self.peerconnection = RTCPeerConnection;
  646. self.getUserMedia = window.getUserMedia;
  647. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  648. self.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  649. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  650. return;
  651. }
  652. var isVideoStream = !!stream.getVideoTracks().length;
  653. if (isVideoStream && !$(element).is(':visible')) {
  654. throw new Error('video element must be visible to attach video stream');
  655. }
  656. return attachMediaStream(element, stream);
  657. });
  658. self.getStreamID = function (stream) {
  659. return SDPUtil.filter_special_chars(stream.label);
  660. };
  661. self.getVideoSrc = function (element) {
  662. if (!element) {
  663. logger.warn("Attempt to get video SRC of null element");
  664. return null;
  665. }
  666. var children = element.children;
  667. for (var i = 0; i !== children.length; ++i) {
  668. if (children[i].name === 'streamId') {
  669. return children[i].value;
  670. }
  671. }
  672. //logger.info(element.id + " SRC: " + src);
  673. return null;
  674. };
  675. self.setVideoSrc = function (element, src) {
  676. //logger.info("Set video src: ", element, src);
  677. if (!src) {
  678. attachMediaStream(element, null);
  679. } else {
  680. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  681. var stream
  682. = AdapterJS.WebRTCPlugin.plugin
  683. .getStreamWithId(
  684. AdapterJS.WebRTCPlugin.pageId, src);
  685. attachMediaStream(element, stream);
  686. }
  687. };
  688. onReady(options, self.getUserMediaWithConstraints);
  689. resolve();
  690. });
  691. } else {
  692. var errmsg = 'Browser does not appear to be WebRTC-capable';
  693. try {
  694. logger.error(errmsg);
  695. } catch (e) {
  696. }
  697. reject(new Error(errmsg));
  698. return;
  699. }
  700. // Call onReady() if Temasys plugin is not used
  701. if (!RTCBrowserType.isTemasysPluginUsed()) {
  702. onReady(options, this.getUserMediaWithConstraints);
  703. resolve();
  704. }
  705. }.bind(this));
  706. },
  707. /**
  708. * @param {string[]} um required user media types
  709. * @param {function} success_callback
  710. * @param {Function} failure_callback
  711. * @param {Object} [options] optional parameters
  712. * @param {string} options.resolution
  713. * @param {number} options.bandwidth
  714. * @param {number} options.fps
  715. * @param {string} options.desktopStream
  716. * @param {string} options.cameraDeviceId
  717. * @param {string} options.micDeviceId
  718. **/
  719. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  720. options = options || {};
  721. var resolution = options.resolution;
  722. var constraints = getConstraints(um, options);
  723. logger.info("Get media constraints", constraints);
  724. try {
  725. this.getUserMedia(constraints,
  726. function (stream) {
  727. logger.log('onUserMediaSuccess');
  728. setAvailableDevices(um, true);
  729. success_callback(stream);
  730. },
  731. function (error) {
  732. setAvailableDevices(um, false);
  733. logger.warn('Failed to get access to local media. Error ',
  734. error, constraints);
  735. if (failure_callback) {
  736. failure_callback(error, resolution);
  737. }
  738. });
  739. } catch (e) {
  740. logger.error('GUM failed: ', e);
  741. if (failure_callback) {
  742. failure_callback(e);
  743. }
  744. }
  745. },
  746. /**
  747. * Creates the local MediaStreams.
  748. * @param {Object} [options] optional parameters
  749. * @param {Array} options.devices the devices that will be requested
  750. * @param {string} options.resolution resolution constraints
  751. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  752. * type: "audio" or "video", videoType: "camera" or "desktop"}
  753. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  754. * @param {string} options.cameraDeviceId
  755. * @param {string} options.micDeviceId
  756. * @returns {*} Promise object that will receive the new JitsiTracks
  757. */
  758. obtainAudioAndVideoPermissions: function (options) {
  759. var self = this;
  760. options = options || {};
  761. return new Promise(function (resolve, reject) {
  762. var successCallback = function (stream) {
  763. resolve(handleLocalStream(stream, options.resolution));
  764. };
  765. options.devices = options.devices || ['audio', 'video'];
  766. if(!screenObtainer.isSupported()
  767. && options.devices.indexOf("desktop") !== -1){
  768. reject(new Error("Desktop sharing is not supported!"));
  769. }
  770. if (RTCBrowserType.isFirefox() ||
  771. RTCBrowserType.isTemasysPluginUsed()) {
  772. var GUM = function (device, s, e) {
  773. this.getUserMediaWithConstraints(device, s, e, options);
  774. };
  775. var deviceGUM = {
  776. "audio": GUM.bind(self, ["audio"]),
  777. "video": GUM.bind(self, ["video"])
  778. };
  779. if(screenObtainer.isSupported()){
  780. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  781. screenObtainer);
  782. }
  783. // With FF/IE we can't split the stream into audio and video because FF
  784. // doesn't support media stream constructors. So, we need to get the
  785. // audio stream separately from the video stream using two distinct GUM
  786. // calls. Not very user friendly :-( but we don't have many other
  787. // options neither.
  788. //
  789. // Note that we pack those 2 streams in a single object and pass it to
  790. // the successCallback method.
  791. obtainDevices({
  792. devices: options.devices,
  793. streams: [],
  794. successCallback: successCallback,
  795. errorCallback: reject,
  796. deviceGUM: deviceGUM
  797. });
  798. } else {
  799. var hasDesktop = options.devices.indexOf('desktop') > -1;
  800. if (hasDesktop) {
  801. options.devices.splice(options.devices.indexOf("desktop"), 1);
  802. }
  803. options.resolution = options.resolution || '360';
  804. if(options.devices.length) {
  805. this.getUserMediaWithConstraints(
  806. options.devices,
  807. function (stream) {
  808. if((options.devices.indexOf("audio") !== -1 &&
  809. !stream.getAudioTracks().length) ||
  810. (options.devices.indexOf("video") !== -1 &&
  811. !stream.getVideoTracks().length))
  812. {
  813. self.stopMediaStream(stream);
  814. reject(JitsiTrackErrors.parseError(
  815. new Error("Unable to get the audio and " +
  816. "video tracks."),
  817. options.devices));
  818. return;
  819. }
  820. if(hasDesktop) {
  821. screenObtainer.obtainStream(
  822. function (desktopStream) {
  823. successCallback({audioVideo: stream,
  824. desktopStream: desktopStream});
  825. }, function (error) {
  826. self.stopMediaStream(stream);
  827. reject(
  828. JitsiTrackErrors.parseError(error,
  829. options.devices));
  830. });
  831. } else {
  832. successCallback({audioVideo: stream});
  833. }
  834. },
  835. function (error) {
  836. reject(JitsiTrackErrors.parseError(error,
  837. options.devices));
  838. },
  839. options);
  840. } else if (hasDesktop) {
  841. screenObtainer.obtainStream(
  842. function (stream) {
  843. successCallback({desktopStream: stream});
  844. }, function (error) {
  845. reject(
  846. JitsiTrackErrors.parseError(error,
  847. ["desktop"]));
  848. });
  849. }
  850. }
  851. }.bind(this));
  852. },
  853. addListener: function (eventType, listener) {
  854. eventEmitter.on(eventType, listener);
  855. },
  856. removeListener: function (eventType, listener) {
  857. eventEmitter.removeListener(eventType, listener);
  858. },
  859. getDeviceAvailability: function () {
  860. return devices;
  861. },
  862. isRTCReady: function () {
  863. return rtcReady;
  864. },
  865. /**
  866. * Checks if its possible to enumerate available cameras/micropones.
  867. * @returns {boolean} true if available, false otherwise.
  868. */
  869. isDeviceListAvailable: function () {
  870. var isEnumerateDevicesAvailable
  871. = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  872. if (isEnumerateDevicesAvailable) {
  873. return true;
  874. }
  875. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  876. },
  877. /**
  878. * Returns true if changing the input (camera / microphone) or output
  879. * (audio) device is supported and false if not.
  880. * @params {string} [deviceType] - type of device to change. Default is
  881. * undefined or 'input', 'output' - for audio output device change.
  882. * @returns {boolean} true if available, false otherwise.
  883. */
  884. isDeviceChangeAvailable: function (deviceType) {
  885. return deviceType === 'output' || deviceType === 'audiooutput'
  886. ? isAudioOutputDeviceChangeAvailable
  887. : RTCBrowserType.isChrome() ||
  888. RTCBrowserType.isFirefox() ||
  889. RTCBrowserType.isOpera() ||
  890. RTCBrowserType.isTemasysPluginUsed()||
  891. RTCBrowserType.isNWJS();
  892. },
  893. /**
  894. * A method to handle stopping of the stream.
  895. * One point to handle the differences in various implementations.
  896. * @param mediaStream MediaStream object to stop.
  897. */
  898. stopMediaStream: function (mediaStream) {
  899. mediaStream.getTracks().forEach(function (track) {
  900. // stop() not supported with IE
  901. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  902. track.stop();
  903. }
  904. });
  905. // leave stop for implementation still using it
  906. if (mediaStream.stop) {
  907. mediaStream.stop();
  908. }
  909. // if we have done createObjectURL, lets clean it
  910. if (mediaStream.jitsiObjectURL) {
  911. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  912. }
  913. },
  914. /**
  915. * Returns whether the desktop sharing is enabled or not.
  916. * @returns {boolean}
  917. */
  918. isDesktopSharingEnabled: function () {
  919. return screenObtainer.isSupported();
  920. },
  921. /**
  922. * Sets current audio output device.
  923. * @param {string} deviceId - id of 'audiooutput' device from
  924. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  925. * device
  926. * @returns {Promise} - resolves when audio output is changed, is rejected
  927. * otherwise
  928. */
  929. setAudioOutputDevice: function (deviceId) {
  930. if (!this.isDeviceChangeAvailable('output')) {
  931. Promise.reject(
  932. new Error('Audio output device change is not supported'));
  933. }
  934. return featureDetectionAudioEl.setSinkId(deviceId)
  935. .then(function() {
  936. audioOutputDeviceId = deviceId;
  937. logger.log('Audio output device set to ' + deviceId);
  938. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  939. deviceId);
  940. });
  941. },
  942. /**
  943. * Returns currently used audio output device id, '' stands for default
  944. * device
  945. * @returns {string}
  946. */
  947. getAudioOutputDevice: function () {
  948. return audioOutputDeviceId;
  949. }
  950. };
  951. module.exports = RTCUtils;