選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

RTCUtils.js 38KB

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