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

RTCUtils.js 46KB

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