Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RTCUtils.js 39KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  438. // the browser, its capabilities, etc. and has taken the decision whether to
  439. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  440. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  441. // the specified streams and figure out what we've received based on
  442. // obtainAudioAndVideoPermissions' decision.
  443. if (streams) {
  444. // As mentioned above, certian types of browser (e.g. Chrome) support
  445. // (with a result which meets our requirements expressed bellow) calling
  446. // getUserMedia once for both audio and video.
  447. var audioVideo = streams.audioVideo;
  448. if (audioVideo) {
  449. var audioTracks = audioVideo.getAudioTracks();
  450. if (audioTracks.length) {
  451. audioStream = new webkitMediaStream();
  452. for (var i = 0; i < audioTracks.length; i++) {
  453. audioStream.addTrack(audioTracks[i]);
  454. }
  455. }
  456. var videoTracks = audioVideo.getVideoTracks();
  457. if (videoTracks.length) {
  458. videoStream = new webkitMediaStream();
  459. for (var j = 0; j < videoTracks.length; j++) {
  460. videoStream.addTrack(videoTracks[j]);
  461. }
  462. }
  463. } else {
  464. // On other types of browser (e.g. Firefox) we choose (namely,
  465. // obtainAudioAndVideoPermissions) to call getUsermedia per device
  466. // (type).
  467. audioStream = streams.audio;
  468. videoStream = streams.video;
  469. }
  470. // Again, different choices on different types of browser.
  471. desktopStream = streams.desktopStream || streams.desktop;
  472. }
  473. if (desktopStream) {
  474. res.push({
  475. stream: desktopStream,
  476. track: desktopStream.getVideoTracks()[0],
  477. mediaType: MediaType.VIDEO,
  478. videoType: VideoType.DESKTOP
  479. });
  480. }
  481. if (audioStream) {
  482. res.push({
  483. stream: audioStream,
  484. track: audioStream.getAudioTracks()[0],
  485. mediaType: MediaType.AUDIO,
  486. videoType: null
  487. });
  488. }
  489. if (videoStream) {
  490. res.push({
  491. stream: videoStream,
  492. track: videoStream.getVideoTracks()[0],
  493. mediaType: MediaType.VIDEO,
  494. videoType: VideoType.CAMERA,
  495. resolution: resolution
  496. });
  497. }
  498. return res;
  499. }
  500. /**
  501. * Wraps original attachMediaStream function to set current audio output device
  502. * if this is supported.
  503. * @param {Function} origAttachMediaStream
  504. * @returns {Function}
  505. */
  506. function wrapAttachMediaStream(origAttachMediaStream) {
  507. return function(element, stream) {
  508. var res = origAttachMediaStream.apply(RTCUtils, arguments);
  509. if (RTCUtils.isDeviceChangeAvailable('output') &&
  510. stream.getAudioTracks && stream.getAudioTracks().length) {
  511. element.setSinkId(RTCUtils.getAudioOutputDevice())
  512. .catch(function (ex) {
  513. logger.error('Failed to set audio output on element',
  514. element, ex);
  515. });
  516. }
  517. return res;
  518. }
  519. }
  520. //Options parameter is to pass config options. Currently uses only "useIPv6".
  521. var RTCUtils = {
  522. init: function (options) {
  523. return new Promise(function(resolve, reject) {
  524. if (RTCBrowserType.isFirefox()) {
  525. var FFversion = RTCBrowserType.getFirefoxVersion();
  526. if (FFversion < 40) {
  527. logger.error(
  528. "Firefox version too old: " + FFversion +
  529. ". Required >= 40.");
  530. reject(new Error("Firefox version too old: " + FFversion +
  531. ". Required >= 40."));
  532. return;
  533. }
  534. this.peerconnection = mozRTCPeerConnection;
  535. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  536. this.enumerateDevices = wrapEnumerateDevices(
  537. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  538. );
  539. this.pc_constraints = {};
  540. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  541. // srcObject is being standardized and FF will eventually
  542. // support that unprefixed. FF also supports the
  543. // "element.src = URL.createObjectURL(...)" combo, but that
  544. // will be deprecated in favour of srcObject.
  545. //
  546. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  547. // https://github.com/webrtc/samples/issues/302
  548. if (!element)
  549. return;
  550. element.mozSrcObject = stream;
  551. element.play();
  552. return element;
  553. });
  554. this.getStreamID = function (stream) {
  555. var id = stream.id;
  556. if (!id) {
  557. var tracks = stream.getVideoTracks();
  558. if (!tracks || tracks.length === 0) {
  559. tracks = stream.getAudioTracks();
  560. }
  561. id = tracks[0].id;
  562. }
  563. return SDPUtil.filter_special_chars(id);
  564. };
  565. this.getVideoSrc = function (element) {
  566. if (!element)
  567. return null;
  568. return element.mozSrcObject;
  569. };
  570. this.setVideoSrc = function (element, src) {
  571. if (element)
  572. element.mozSrcObject = src;
  573. };
  574. RTCSessionDescription = mozRTCSessionDescription;
  575. RTCIceCandidate = mozRTCIceCandidate;
  576. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera() || RTCBrowserType.isNWJS()) {
  577. this.peerconnection = webkitRTCPeerConnection;
  578. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  579. if (navigator.mediaDevices) {
  580. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  581. this.enumerateDevices = wrapEnumerateDevices(
  582. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  583. );
  584. } else {
  585. this.getUserMedia = getUserMedia;
  586. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  587. }
  588. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  589. // saves the created url for the stream, so we can reuse it
  590. // and not keep creating urls
  591. if (!stream.jitsiObjectURL) {
  592. stream.jitsiObjectURL
  593. = webkitURL.createObjectURL(stream);
  594. }
  595. element.src = stream.jitsiObjectURL;
  596. return element;
  597. });
  598. this.getStreamID = function (stream) {
  599. // Streams from FF endpoints have the characters '{' and '}'
  600. // that make jQuery choke.
  601. return SDPUtil.filter_special_chars(stream.id);
  602. };
  603. this.getVideoSrc = function (element) {
  604. return element ? element.getAttribute("src") : null;
  605. };
  606. this.setVideoSrc = function (element, src) {
  607. if (element)
  608. element.setAttribute("src", src || '');
  609. };
  610. // DTLS should now be enabled by default but..
  611. this.pc_constraints = {'optional': [
  612. {'DtlsSrtpKeyAgreement': 'true'}
  613. ]};
  614. if (options.useIPv6) {
  615. // https://code.google.com/p/webrtc/issues/detail?id=2828
  616. this.pc_constraints.optional.push({googIPv6: true});
  617. }
  618. if (RTCBrowserType.isAndroid()) {
  619. this.pc_constraints = {}; // disable DTLS on Android
  620. }
  621. if (!webkitMediaStream.prototype.getVideoTracks) {
  622. webkitMediaStream.prototype.getVideoTracks = function () {
  623. return this.videoTracks;
  624. };
  625. }
  626. if (!webkitMediaStream.prototype.getAudioTracks) {
  627. webkitMediaStream.prototype.getAudioTracks = function () {
  628. return this.audioTracks;
  629. };
  630. }
  631. }
  632. // Detect IE/Safari
  633. else if (RTCBrowserType.isTemasysPluginUsed()) {
  634. //AdapterJS.WebRTCPlugin.setLogLevel(
  635. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  636. var self = this;
  637. AdapterJS.webRTCReady(function (isPlugin) {
  638. self.peerconnection = RTCPeerConnection;
  639. self.getUserMedia = window.getUserMedia;
  640. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  641. self.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  642. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  643. return;
  644. }
  645. var isVideoStream = !!stream.getVideoTracks().length;
  646. if (isVideoStream && !$(element).is(':visible')) {
  647. throw new Error('video element must be visible to attach video stream');
  648. }
  649. return attachMediaStream(element, stream);
  650. });
  651. self.getStreamID = function (stream) {
  652. return SDPUtil.filter_special_chars(stream.label);
  653. };
  654. self.getVideoSrc = function (element) {
  655. if (!element) {
  656. logger.warn("Attempt to get video SRC of null element");
  657. return null;
  658. }
  659. var children = element.children;
  660. for (var i = 0; i !== children.length; ++i) {
  661. if (children[i].name === 'streamId') {
  662. return children[i].value;
  663. }
  664. }
  665. //logger.info(element.id + " SRC: " + src);
  666. return null;
  667. };
  668. self.setVideoSrc = function (element, src) {
  669. //logger.info("Set video src: ", element, src);
  670. if (!src) {
  671. attachMediaStream(element, null);
  672. } else {
  673. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  674. var stream
  675. = AdapterJS.WebRTCPlugin.plugin
  676. .getStreamWithId(
  677. AdapterJS.WebRTCPlugin.pageId, src);
  678. attachMediaStream(element, stream);
  679. }
  680. };
  681. onReady(options, self.getUserMediaWithConstraints);
  682. resolve();
  683. });
  684. } else {
  685. try {
  686. logger.error('Browser does not appear to be WebRTC-capable');
  687. } catch (e) {
  688. }
  689. reject('Browser does not appear to be WebRTC-capable');
  690. return;
  691. }
  692. // Call onReady() if Temasys plugin is not used
  693. if (!RTCBrowserType.isTemasysPluginUsed()) {
  694. onReady(options, this.getUserMediaWithConstraints);
  695. resolve();
  696. }
  697. }.bind(this));
  698. },
  699. /**
  700. * @param {string[]} um required user media types
  701. * @param {function} success_callback
  702. * @param {Function} failure_callback
  703. * @param {Object} [options] optional parameters
  704. * @param {string} options.resolution
  705. * @param {number} options.bandwidth
  706. * @param {number} options.fps
  707. * @param {string} options.desktopStream
  708. * @param {string} options.cameraDeviceId
  709. * @param {string} options.micDeviceId
  710. **/
  711. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  712. options = options || {};
  713. var resolution = options.resolution;
  714. var constraints = getConstraints(um, options);
  715. logger.info("Get media constraints", constraints);
  716. try {
  717. this.getUserMedia(constraints,
  718. function (stream) {
  719. logger.log('onUserMediaSuccess');
  720. setAvailableDevices(um, true);
  721. success_callback(stream);
  722. },
  723. function (error) {
  724. setAvailableDevices(um, false);
  725. logger.warn('Failed to get access to local media. Error ',
  726. error, constraints);
  727. if (failure_callback) {
  728. failure_callback(error, resolution);
  729. }
  730. });
  731. } catch (e) {
  732. logger.error('GUM failed: ', e);
  733. if (failure_callback) {
  734. failure_callback(e);
  735. }
  736. }
  737. },
  738. /**
  739. * Creates the local MediaStreams.
  740. * @param {Object} [options] optional parameters
  741. * @param {Array} options.devices the devices that will be requested
  742. * @param {string} options.resolution resolution constraints
  743. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  744. * type: "audio" or "video", videoType: "camera" or "desktop"}
  745. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  746. * @param {string} options.cameraDeviceId
  747. * @param {string} options.micDeviceId
  748. * @returns {*} Promise object that will receive the new JitsiTracks
  749. */
  750. obtainAudioAndVideoPermissions: function (options) {
  751. var self = this;
  752. options = options || {};
  753. return new Promise(function (resolve, reject) {
  754. var successCallback = function (stream) {
  755. resolve(handleLocalStream(stream, options.resolution));
  756. };
  757. options.devices = options.devices || ['audio', 'video'];
  758. if(!screenObtainer.isSupported()
  759. && options.devices.indexOf("desktop") !== -1){
  760. reject(new Error("Desktop sharing is not supported!"));
  761. }
  762. if (RTCBrowserType.isFirefox() ||
  763. RTCBrowserType.isTemasysPluginUsed()) {
  764. var GUM = function (device, s, e) {
  765. this.getUserMediaWithConstraints(device, s, e, options);
  766. };
  767. var deviceGUM = {
  768. "audio": GUM.bind(self, ["audio"]),
  769. "video": GUM.bind(self, ["video"])
  770. };
  771. if(screenObtainer.isSupported()){
  772. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  773. screenObtainer);
  774. }
  775. // With FF/IE we can't split the stream into audio and video because FF
  776. // doesn't support media stream constructors. So, we need to get the
  777. // audio stream separately from the video stream using two distinct GUM
  778. // calls. Not very user friendly :-( but we don't have many other
  779. // options neither.
  780. //
  781. // Note that we pack those 2 streams in a single object and pass it to
  782. // the successCallback method.
  783. obtainDevices({
  784. devices: options.devices,
  785. streams: [],
  786. successCallback: successCallback,
  787. errorCallback: reject,
  788. deviceGUM: deviceGUM
  789. });
  790. } else {
  791. var hasDesktop = options.devices.indexOf('desktop') > -1;
  792. if (hasDesktop) {
  793. options.devices.splice(options.devices.indexOf("desktop"), 1);
  794. }
  795. options.resolution = options.resolution || '360';
  796. if(options.devices.length) {
  797. this.getUserMediaWithConstraints(
  798. options.devices,
  799. function (stream) {
  800. if((options.devices.indexOf("audio") !== -1 &&
  801. !stream.getAudioTracks().length) ||
  802. (options.devices.indexOf("video") !== -1 &&
  803. !stream.getVideoTracks().length))
  804. {
  805. self.stopMediaStream(stream);
  806. reject(JitsiTrackErrors.parseError(
  807. new Error("Unable to get the audio and " +
  808. "video tracks."),
  809. options.devices));
  810. return;
  811. }
  812. if(hasDesktop) {
  813. screenObtainer.obtainStream(
  814. function (desktopStream) {
  815. successCallback({audioVideo: stream,
  816. desktopStream: desktopStream});
  817. }, function (error) {
  818. self.stopMediaStream(stream);
  819. reject(
  820. JitsiTrackErrors.parseError(error,
  821. options.devices));
  822. });
  823. } else {
  824. successCallback({audioVideo: stream});
  825. }
  826. },
  827. function (error) {
  828. reject(JitsiTrackErrors.parseError(error,
  829. options.devices));
  830. },
  831. options);
  832. } else if (hasDesktop) {
  833. screenObtainer.obtainStream(
  834. function (stream) {
  835. successCallback({desktopStream: stream});
  836. }, function (error) {
  837. reject(
  838. JitsiTrackErrors.parseError(error,
  839. ["desktop"]));
  840. });
  841. }
  842. }
  843. }.bind(this));
  844. },
  845. addListener: function (eventType, listener) {
  846. eventEmitter.on(eventType, listener);
  847. },
  848. removeListener: function (eventType, listener) {
  849. eventEmitter.removeListener(eventType, listener);
  850. },
  851. getDeviceAvailability: function () {
  852. return devices;
  853. },
  854. isRTCReady: function () {
  855. return rtcReady;
  856. },
  857. /**
  858. * Checks if its possible to enumerate available cameras/micropones.
  859. * @returns {boolean} true if available, false otherwise.
  860. */
  861. isDeviceListAvailable: function () {
  862. var isEnumerateDevicesAvailable
  863. = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  864. if (isEnumerateDevicesAvailable) {
  865. return true;
  866. }
  867. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  868. },
  869. /**
  870. * Returns true if changing the input (camera / microphone) or output
  871. * (audio) device is supported and false if not.
  872. * @params {string} [deviceType] - type of device to change. Default is
  873. * undefined or 'input', 'output' - for audio output device change.
  874. * @returns {boolean} true if available, false otherwise.
  875. */
  876. isDeviceChangeAvailable: function (deviceType) {
  877. return deviceType === 'output' || deviceType === 'audiooutput'
  878. ? isAudioOutputDeviceChangeAvailable
  879. : RTCBrowserType.isChrome() ||
  880. RTCBrowserType.isFirefox() ||
  881. RTCBrowserType.isOpera() ||
  882. RTCBrowserType.isTemasysPluginUsed()||
  883. RTCBrowserType.isNWJS();
  884. },
  885. /**
  886. * A method to handle stopping of the stream.
  887. * One point to handle the differences in various implementations.
  888. * @param mediaStream MediaStream object to stop.
  889. */
  890. stopMediaStream: function (mediaStream) {
  891. mediaStream.getTracks().forEach(function (track) {
  892. // stop() not supported with IE
  893. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  894. track.stop();
  895. }
  896. });
  897. // leave stop for implementation still using it
  898. if (mediaStream.stop) {
  899. mediaStream.stop();
  900. }
  901. // if we have done createObjectURL, lets clean it
  902. if (mediaStream.jitsiObjectURL) {
  903. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  904. }
  905. },
  906. /**
  907. * Returns whether the desktop sharing is enabled or not.
  908. * @returns {boolean}
  909. */
  910. isDesktopSharingEnabled: function () {
  911. return screenObtainer.isSupported();
  912. },
  913. /**
  914. * Sets current audio output device.
  915. * @param {string} deviceId - id of 'audiooutput' device from
  916. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  917. * device
  918. * @returns {Promise} - resolves when audio output is changed, is rejected
  919. * otherwise
  920. */
  921. setAudioOutputDevice: function (deviceId) {
  922. if (!this.isDeviceChangeAvailable('output')) {
  923. Promise.reject(
  924. new Error('Audio output device change is not supported'));
  925. }
  926. return featureDetectionAudioEl.setSinkId(deviceId)
  927. .then(function() {
  928. audioOutputDeviceId = deviceId;
  929. logger.log('Audio output device set to ' + deviceId);
  930. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  931. deviceId);
  932. });
  933. },
  934. /**
  935. * Returns currently used audio output device id, '' stands for default
  936. * device
  937. * @returns {string}
  938. */
  939. getAudioOutputDevice: function () {
  940. return audioOutputDeviceId;
  941. }
  942. };
  943. module.exports = RTCUtils;