您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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. GlobalOnErrorHandler.callErrorHandler(new Error(
  167. "'screen' WebRTC media source is supported only in Chrome" +
  168. " and with Temasys plugin"));
  169. logger.error(
  170. "'screen' WebRTC media source is supported only in Chrome" +
  171. " and with Temasys plugin");
  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(JitsiTrackErrors.parseError(error, devices));
  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.callUnhandlerRejectionHandler(
  518. {promise: this, reason: ex});
  519. logger.error('Failed to set audio output on element',
  520. element, ex);
  521. });
  522. }
  523. return res;
  524. }
  525. }
  526. //Options parameter is to pass config options. Currently uses only "useIPv6".
  527. var RTCUtils = {
  528. init: function (options) {
  529. return new Promise(function(resolve, reject) {
  530. if (RTCBrowserType.isFirefox()) {
  531. var FFversion = RTCBrowserType.getFirefoxVersion();
  532. if (FFversion < 40) {
  533. logger.error(
  534. "Firefox version too old: " + FFversion +
  535. ". Required >= 40.");
  536. reject(new Error("Firefox version too old: " + FFversion +
  537. ". Required >= 40."));
  538. return;
  539. }
  540. this.peerconnection = mozRTCPeerConnection;
  541. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  542. this.enumerateDevices = wrapEnumerateDevices(
  543. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  544. );
  545. this.pc_constraints = {};
  546. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  547. // srcObject is being standardized and FF will eventually
  548. // support that unprefixed. FF also supports the
  549. // "element.src = URL.createObjectURL(...)" combo, but that
  550. // will be deprecated in favour of srcObject.
  551. //
  552. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  553. // https://github.com/webrtc/samples/issues/302
  554. if (!element)
  555. return;
  556. element.mozSrcObject = stream;
  557. element.play();
  558. return element;
  559. });
  560. this.getStreamID = function (stream) {
  561. var id = stream.id;
  562. if (!id) {
  563. var tracks = stream.getVideoTracks();
  564. if (!tracks || tracks.length === 0) {
  565. tracks = stream.getAudioTracks();
  566. }
  567. id = tracks[0].id;
  568. }
  569. return SDPUtil.filter_special_chars(id);
  570. };
  571. this.getVideoSrc = function (element) {
  572. if (!element)
  573. return null;
  574. return element.mozSrcObject;
  575. };
  576. this.setVideoSrc = function (element, src) {
  577. if (element)
  578. element.mozSrcObject = src;
  579. };
  580. RTCSessionDescription = mozRTCSessionDescription;
  581. RTCIceCandidate = mozRTCIceCandidate;
  582. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera() || RTCBrowserType.isNWJS()) {
  583. this.peerconnection = webkitRTCPeerConnection;
  584. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  585. if (navigator.mediaDevices) {
  586. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  587. this.enumerateDevices = wrapEnumerateDevices(
  588. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  589. );
  590. } else {
  591. this.getUserMedia = getUserMedia;
  592. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  593. }
  594. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  595. // saves the created url for the stream, so we can reuse it
  596. // and not keep creating urls
  597. if (!stream.jitsiObjectURL) {
  598. stream.jitsiObjectURL
  599. = webkitURL.createObjectURL(stream);
  600. }
  601. element.src = stream.jitsiObjectURL;
  602. return element;
  603. });
  604. this.getStreamID = function (stream) {
  605. // Streams from FF endpoints have the characters '{' and '}'
  606. // that make jQuery choke.
  607. return SDPUtil.filter_special_chars(stream.id);
  608. };
  609. this.getVideoSrc = function (element) {
  610. return element ? element.getAttribute("src") : null;
  611. };
  612. this.setVideoSrc = function (element, src) {
  613. if (element)
  614. element.setAttribute("src", src || '');
  615. };
  616. // DTLS should now be enabled by default but..
  617. this.pc_constraints = {'optional': [
  618. {'DtlsSrtpKeyAgreement': 'true'}
  619. ]};
  620. if (options.useIPv6) {
  621. // https://code.google.com/p/webrtc/issues/detail?id=2828
  622. this.pc_constraints.optional.push({googIPv6: true});
  623. }
  624. if (RTCBrowserType.isAndroid()) {
  625. this.pc_constraints = {}; // disable DTLS on Android
  626. }
  627. if (!webkitMediaStream.prototype.getVideoTracks) {
  628. webkitMediaStream.prototype.getVideoTracks = function () {
  629. return this.videoTracks;
  630. };
  631. }
  632. if (!webkitMediaStream.prototype.getAudioTracks) {
  633. webkitMediaStream.prototype.getAudioTracks = function () {
  634. return this.audioTracks;
  635. };
  636. }
  637. }
  638. // Detect IE/Safari
  639. else if (RTCBrowserType.isTemasysPluginUsed()) {
  640. //AdapterJS.WebRTCPlugin.setLogLevel(
  641. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  642. var self = this;
  643. AdapterJS.webRTCReady(function (isPlugin) {
  644. self.peerconnection = RTCPeerConnection;
  645. self.getUserMedia = window.getUserMedia;
  646. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  647. self.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  648. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  649. return;
  650. }
  651. var isVideoStream = !!stream.getVideoTracks().length;
  652. if (isVideoStream && !$(element).is(':visible')) {
  653. throw new Error('video element must be visible to attach video stream');
  654. }
  655. return attachMediaStream(element, stream);
  656. });
  657. self.getStreamID = function (stream) {
  658. return SDPUtil.filter_special_chars(stream.label);
  659. };
  660. self.getVideoSrc = function (element) {
  661. if (!element) {
  662. logger.warn("Attempt to get video SRC of null element");
  663. return null;
  664. }
  665. var children = element.children;
  666. for (var i = 0; i !== children.length; ++i) {
  667. if (children[i].name === 'streamId') {
  668. return children[i].value;
  669. }
  670. }
  671. //logger.info(element.id + " SRC: " + src);
  672. return null;
  673. };
  674. self.setVideoSrc = function (element, src) {
  675. //logger.info("Set video src: ", element, src);
  676. if (!src) {
  677. attachMediaStream(element, null);
  678. } else {
  679. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  680. var stream
  681. = AdapterJS.WebRTCPlugin.plugin
  682. .getStreamWithId(
  683. AdapterJS.WebRTCPlugin.pageId, src);
  684. attachMediaStream(element, stream);
  685. }
  686. };
  687. onReady(options, self.getUserMediaWithConstraints);
  688. resolve();
  689. });
  690. } else {
  691. try {
  692. logger.error(
  693. 'Browser does not appear to be WebRTC-capable');
  694. } catch (e) {
  695. }
  696. reject(
  697. new Error('Browser does not appear to be WebRTC-capable'));
  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;