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

RTCUtils.js 39KB

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