Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTCUtils.js 40KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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(
  738. new JitsiTrackError(error, constraints, um));
  739. }
  740. });
  741. } catch (e) {
  742. logger.error('GUM failed: ', e);
  743. if (failure_callback) {
  744. failure_callback(new JitsiTrackError(e, constraints, um));
  745. }
  746. }
  747. },
  748. /**
  749. * Creates the local MediaStreams.
  750. * @param {Object} [options] optional parameters
  751. * @param {Array} options.devices the devices that will be requested
  752. * @param {string} options.resolution resolution constraints
  753. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  754. * type: "audio" or "video", videoType: "camera" or "desktop"}
  755. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  756. * @param {string} options.cameraDeviceId
  757. * @param {string} options.micDeviceId
  758. * @returns {*} Promise object that will receive the new JitsiTracks
  759. */
  760. obtainAudioAndVideoPermissions: function (options) {
  761. var self = this;
  762. options = options || {};
  763. return new Promise(function (resolve, reject) {
  764. var successCallback = function (stream) {
  765. resolve(handleLocalStream(stream, options.resolution));
  766. };
  767. options.devices = options.devices || ['audio', 'video'];
  768. if(!screenObtainer.isSupported()
  769. && options.devices.indexOf("desktop") !== -1){
  770. reject(new Error("Desktop sharing is not supported!"));
  771. }
  772. if (RTCBrowserType.isFirefox() ||
  773. RTCBrowserType.isTemasysPluginUsed()) {
  774. var GUM = function (device, s, e) {
  775. this.getUserMediaWithConstraints(device, s, e, options);
  776. };
  777. var deviceGUM = {
  778. "audio": GUM.bind(self, ["audio"]),
  779. "video": GUM.bind(self, ["video"])
  780. };
  781. if(screenObtainer.isSupported()){
  782. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  783. screenObtainer);
  784. }
  785. // With FF/IE we can't split the stream into audio and video because FF
  786. // doesn't support media stream constructors. So, we need to get the
  787. // audio stream separately from the video stream using two distinct GUM
  788. // calls. Not very user friendly :-( but we don't have many other
  789. // options neither.
  790. //
  791. // Note that we pack those 2 streams in a single object and pass it to
  792. // the successCallback method.
  793. obtainDevices({
  794. devices: options.devices,
  795. streams: [],
  796. successCallback: successCallback,
  797. errorCallback: reject,
  798. deviceGUM: deviceGUM
  799. });
  800. } else {
  801. var hasDesktop = options.devices.indexOf('desktop') > -1;
  802. if (hasDesktop) {
  803. options.devices.splice(options.devices.indexOf("desktop"), 1);
  804. }
  805. options.resolution = options.resolution || '360';
  806. if(options.devices.length) {
  807. this.getUserMediaWithConstraints(
  808. options.devices,
  809. function (stream) {
  810. if((options.devices.indexOf("audio") !== -1 &&
  811. !stream.getAudioTracks().length) ||
  812. (options.devices.indexOf("video") !== -1 &&
  813. !stream.getVideoTracks().length))
  814. {
  815. self.stopMediaStream(stream);
  816. // We are getting here in case if we requested
  817. // 'audio' or 'video' devices or both, but
  818. // didn't get corresponding MediaStreamTrack in
  819. // response stream. We don't know the reason why
  820. // this happened, so reject with general error.
  821. var devices = [];
  822. if (options.devices.indexOf("audio") !== -1 &&
  823. !stream.getAudioTracks().length) {
  824. devices.push("audio");
  825. }
  826. if (options.devices.indexOf("video") !== -1 &&
  827. !stream.getVideoTracks().length) {
  828. devices.push("video");
  829. }
  830. reject(new JitsiTrackError(
  831. { name: "UnknownError" },
  832. getConstraints(options.devices, options),
  833. devices)
  834. );
  835. return;
  836. }
  837. if(hasDesktop) {
  838. screenObtainer.obtainStream(
  839. function (desktopStream) {
  840. successCallback({audioVideo: stream,
  841. desktopStream: desktopStream});
  842. }, function (error) {
  843. self.stopMediaStream(stream);
  844. reject(error);
  845. });
  846. } else {
  847. successCallback({audioVideo: stream});
  848. }
  849. },
  850. function (error) {
  851. reject(error);
  852. },
  853. options);
  854. } else if (hasDesktop) {
  855. screenObtainer.obtainStream(
  856. function (stream) {
  857. successCallback({desktopStream: stream});
  858. }, function (error) {
  859. reject(error);
  860. });
  861. }
  862. }
  863. }.bind(this));
  864. },
  865. addListener: function (eventType, listener) {
  866. eventEmitter.on(eventType, listener);
  867. },
  868. removeListener: function (eventType, listener) {
  869. eventEmitter.removeListener(eventType, listener);
  870. },
  871. getDeviceAvailability: function () {
  872. return devices;
  873. },
  874. isRTCReady: function () {
  875. return rtcReady;
  876. },
  877. /**
  878. * Checks if its possible to enumerate available cameras/micropones.
  879. * @returns {boolean} true if available, false otherwise.
  880. */
  881. isDeviceListAvailable: function () {
  882. var isEnumerateDevicesAvailable
  883. = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  884. if (isEnumerateDevicesAvailable) {
  885. return true;
  886. }
  887. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  888. },
  889. /**
  890. * Returns true if changing the input (camera / microphone) or output
  891. * (audio) device is supported and false if not.
  892. * @params {string} [deviceType] - type of device to change. Default is
  893. * undefined or 'input', 'output' - for audio output device change.
  894. * @returns {boolean} true if available, false otherwise.
  895. */
  896. isDeviceChangeAvailable: function (deviceType) {
  897. return deviceType === 'output' || deviceType === 'audiooutput'
  898. ? isAudioOutputDeviceChangeAvailable
  899. : RTCBrowserType.isChrome() ||
  900. RTCBrowserType.isFirefox() ||
  901. RTCBrowserType.isOpera() ||
  902. RTCBrowserType.isTemasysPluginUsed()||
  903. RTCBrowserType.isNWJS();
  904. },
  905. /**
  906. * A method to handle stopping of the stream.
  907. * One point to handle the differences in various implementations.
  908. * @param mediaStream MediaStream object to stop.
  909. */
  910. stopMediaStream: function (mediaStream) {
  911. mediaStream.getTracks().forEach(function (track) {
  912. // stop() not supported with IE
  913. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  914. track.stop();
  915. }
  916. });
  917. // leave stop for implementation still using it
  918. if (mediaStream.stop) {
  919. mediaStream.stop();
  920. }
  921. // if we have done createObjectURL, lets clean it
  922. if (mediaStream.jitsiObjectURL) {
  923. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  924. }
  925. },
  926. /**
  927. * Returns whether the desktop sharing is enabled or not.
  928. * @returns {boolean}
  929. */
  930. isDesktopSharingEnabled: function () {
  931. return screenObtainer.isSupported();
  932. },
  933. /**
  934. * Sets current audio output device.
  935. * @param {string} deviceId - id of 'audiooutput' device from
  936. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  937. * device
  938. * @returns {Promise} - resolves when audio output is changed, is rejected
  939. * otherwise
  940. */
  941. setAudioOutputDevice: function (deviceId) {
  942. if (!this.isDeviceChangeAvailable('output')) {
  943. Promise.reject(
  944. new Error('Audio output device change is not supported'));
  945. }
  946. return featureDetectionAudioEl.setSinkId(deviceId)
  947. .then(function() {
  948. audioOutputDeviceId = deviceId;
  949. logger.log('Audio output device set to ' + deviceId);
  950. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  951. deviceId);
  952. });
  953. },
  954. /**
  955. * Returns currently used audio output device id, '' stands for default
  956. * device
  957. * @returns {string}
  958. */
  959. getAudioOutputDevice: function () {
  960. return audioOutputDeviceId;
  961. }
  962. };
  963. module.exports = RTCUtils;