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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /* global config, require, attachMediaStream, getUserMedia */
  2. var RTCBrowserType = require("./RTCBrowserType");
  3. var Resolutions = require("../../service/RTC/Resolutions");
  4. var AdapterJS = require("./adapter.screenshare");
  5. var SDPUtil = require("../xmpp/SDPUtil");
  6. var currentResolution = null;
  7. function DummyMediaStream(id) {
  8. this.id = id;
  9. this.label = id;
  10. this.stop = function() { };
  11. this.getAudioTracks = function() { return []; };
  12. this.getVideoTracks = function() { return []; };
  13. }
  14. function getPreviousResolution(resolution) {
  15. if(!Resolutions[resolution])
  16. return null;
  17. var order = Resolutions[resolution].order;
  18. var res = null;
  19. var resName = null;
  20. for(var i in Resolutions) {
  21. var tmp = Resolutions[i];
  22. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  23. resName = i;
  24. res = tmp;
  25. }
  26. }
  27. return resName;
  28. }
  29. function setResolutionConstraints(constraints, resolution, isAndroid) {
  30. if (Resolutions[resolution]) {
  31. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  32. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  33. }
  34. else if (isAndroid) {
  35. // FIXME can't remember if the purpose of this was to always request
  36. // low resolution on Android ? if yes it should be moved up front
  37. constraints.video.mandatory.minWidth = 320;
  38. constraints.video.mandatory.minHeight = 240;
  39. constraints.video.mandatory.maxFrameRate = 15;
  40. }
  41. if (constraints.video.mandatory.minWidth)
  42. constraints.video.mandatory.maxWidth =
  43. constraints.video.mandatory.minWidth;
  44. if (constraints.video.mandatory.minHeight)
  45. constraints.video.mandatory.maxHeight =
  46. constraints.video.mandatory.minHeight;
  47. }
  48. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  49. {
  50. var constraints = {audio: false, video: false};
  51. if (um.indexOf('video') >= 0) {
  52. // same behaviour as true
  53. constraints.video = { mandatory: {}, optional: [] };
  54. constraints.video.optional.push({ googLeakyBucket: true });
  55. setResolutionConstraints(constraints, resolution, isAndroid);
  56. }
  57. if (um.indexOf('audio') >= 0) {
  58. if (!RTCBrowserType.isFirefox()) {
  59. // same behaviour as true
  60. constraints.audio = { mandatory: {}, optional: []};
  61. // if it is good enough for hangouts...
  62. constraints.audio.optional.push(
  63. {googEchoCancellation: true},
  64. {googAutoGainControl: true},
  65. {googNoiseSupression: true},
  66. {googHighpassFilter: true},
  67. {googNoisesuppression2: true},
  68. {googEchoCancellation2: true},
  69. {googAutoGainControl2: true}
  70. );
  71. } else {
  72. constraints.audio = true;
  73. }
  74. }
  75. if (um.indexOf('screen') >= 0) {
  76. if (RTCBrowserType.isChrome()) {
  77. constraints.video = {
  78. mandatory: {
  79. chromeMediaSource: "screen",
  80. googLeakyBucket: true,
  81. maxWidth: window.screen.width,
  82. maxHeight: window.screen.height,
  83. maxFrameRate: 3
  84. },
  85. optional: []
  86. };
  87. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  88. constraints.video = {
  89. optional: [
  90. {
  91. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  92. }
  93. ]
  94. };
  95. } else {
  96. console.error(
  97. "'screen' WebRTC media source is supported only in Chrome" +
  98. " and with Temasys plugin");
  99. }
  100. }
  101. if (um.indexOf('desktop') >= 0) {
  102. constraints.video = {
  103. mandatory: {
  104. chromeMediaSource: "desktop",
  105. chromeMediaSourceId: desktopStream,
  106. googLeakyBucket: true,
  107. maxWidth: window.screen.width,
  108. maxHeight: window.screen.height,
  109. maxFrameRate: 3
  110. },
  111. optional: []
  112. };
  113. }
  114. if (bandwidth) {
  115. if (!constraints.video) {
  116. //same behaviour as true
  117. constraints.video = {mandatory: {}, optional: []};
  118. }
  119. constraints.video.optional.push({bandwidth: bandwidth});
  120. }
  121. if (fps) {
  122. // for some cameras it might be necessary to request 30fps
  123. // so they choose 30fps mjpg over 10fps yuy2
  124. if (!constraints.video) {
  125. // same behaviour as true;
  126. constraints.video = {mandatory: {}, optional: []};
  127. }
  128. constraints.video.mandatory.minFrameRate = fps;
  129. }
  130. return constraints;
  131. }
  132. //Options parameter is to pass config options. Currently uses only "useIPv6".
  133. var RTCUtils = {
  134. init: function (onTemasysPluginReady) {
  135. var self = this;
  136. if (RTCBrowserType.isFirefox()) {
  137. var FFversion = RTCBrowserType.getFirefoxVersion();
  138. if (FFversion >= 40) {
  139. this.peerconnection = mozRTCPeerConnection;
  140. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  141. this.pc_constraints = {};
  142. this.attachMediaStream = function (element, stream) {
  143. // srcObject is being standardized and FF will eventually
  144. // support that unprefixed. FF also supports the
  145. // "element.src = URL.createObjectURL(...)" combo, but that
  146. // will be deprecated in favour of srcObject.
  147. //
  148. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  149. // https://github.com/webrtc/samples/issues/302
  150. if (!element[0])
  151. return;
  152. element[0].mozSrcObject = stream;
  153. element[0].play();
  154. };
  155. this.getStreamID = function (stream) {
  156. var id = stream.id;
  157. if (!id) {
  158. var tracks = stream.getVideoTracks();
  159. if (!tracks || tracks.length === 0) {
  160. tracks = stream.getAudioTracks();
  161. }
  162. id = tracks[0].id;
  163. }
  164. return SDPUtil.filter_special_chars(id);
  165. };
  166. this.getVideoSrc = function (element) {
  167. if (!element)
  168. return null;
  169. return element.mozSrcObject;
  170. };
  171. this.setVideoSrc = function (element, src) {
  172. if (element)
  173. element.mozSrcObject = src;
  174. };
  175. RTCSessionDescription = mozRTCSessionDescription;
  176. RTCIceCandidate = mozRTCIceCandidate;
  177. } else {
  178. console.error(
  179. "Firefox version too old: " + FFversion + ". Required >= 40.");
  180. window.location.href = 'unsupported_browser.html';
  181. return;
  182. }
  183. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  184. this.peerconnection = webkitRTCPeerConnection;
  185. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  186. this.attachMediaStream = function (element, stream) {
  187. element.attr('src', webkitURL.createObjectURL(stream));
  188. };
  189. this.getStreamID = function (stream) {
  190. // streams from FF endpoints have the characters '{' and '}'
  191. // that make jQuery choke.
  192. return SDPUtil.filter_special_chars(stream.id);
  193. };
  194. this.getVideoSrc = function (element) {
  195. if (!element)
  196. return null;
  197. return element.getAttribute("src");
  198. };
  199. this.setVideoSrc = function (element, src) {
  200. if (element)
  201. element.setAttribute("src", src);
  202. };
  203. // DTLS should now be enabled by default but..
  204. this.pc_constraints = {'optional': [
  205. {'DtlsSrtpKeyAgreement': 'true'}
  206. ]};
  207. if (this.service.options.useIPv6) {
  208. // https://code.google.com/p/webrtc/issues/detail?id=2828
  209. this.pc_constraints.optional.push({googIPv6: true});
  210. }
  211. if (navigator.userAgent.indexOf('Android') != -1) {
  212. this.pc_constraints = {}; // disable DTLS on Android
  213. }
  214. if (!webkitMediaStream.prototype.getVideoTracks) {
  215. webkitMediaStream.prototype.getVideoTracks = function () {
  216. return this.videoTracks;
  217. };
  218. }
  219. if (!webkitMediaStream.prototype.getAudioTracks) {
  220. webkitMediaStream.prototype.getAudioTracks = function () {
  221. return this.audioTracks;
  222. };
  223. }
  224. }
  225. // Detect IE/Safari
  226. else if (RTCBrowserType.isTemasysPluginUsed()) {
  227. //AdapterJS.WebRTCPlugin.setLogLevel(
  228. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  229. AdapterJS.webRTCReady(function (isPlugin) {
  230. self.peerconnection = RTCPeerConnection;
  231. self.getUserMedia = getUserMedia;
  232. self.attachMediaStream = function (elSel, stream) {
  233. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  234. return;
  235. }
  236. attachMediaStream(elSel[0], stream);
  237. };
  238. self.getStreamID = function (stream) {
  239. var id = SDPUtil.filter_special_chars(stream.label);
  240. return id;
  241. };
  242. self.getVideoSrc = function (element) {
  243. if (!element) {
  244. console.warn("Attempt to get video SRC of null element");
  245. return null;
  246. }
  247. var children = element.children;
  248. for (var i = 0; i !== children.length; ++i) {
  249. if (children[i].name === 'streamId') {
  250. return children[i].value;
  251. }
  252. }
  253. //console.info(element.id + " SRC: " + src);
  254. return null;
  255. };
  256. self.setVideoSrc = function (element, src) {
  257. //console.info("Set video src: ", element, src);
  258. if (!src) {
  259. console.warn("Not attaching video stream, 'src' is null");
  260. return;
  261. }
  262. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  263. var stream = AdapterJS.WebRTCPlugin.plugin
  264. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  265. attachMediaStream(element, stream);
  266. };
  267. onTemasysPluginReady(isPlugin);
  268. });
  269. } else {
  270. try {
  271. console.log('Browser does not appear to be WebRTC-capable');
  272. } catch (e) {
  273. }
  274. window.location.href = 'unsupported_browser.html';
  275. }
  276. },
  277. getUserMediaWithConstraints: function (RTC, um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  278. // Check if we are running on Android device
  279. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  280. var constraints = getConstraints(
  281. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  282. console.info("Get media constraints", constraints);
  283. var self = this;
  284. try {
  285. this.getUserMedia(constraints,
  286. function (stream) {
  287. console.log('onUserMediaSuccess');
  288. self.setAvailableDevices(RTC, um, true);
  289. success_callback(stream);
  290. },
  291. function (error) {
  292. self.setAvailableDevices(RTC, um, false);
  293. console.warn('Failed to get access to local media. Error ',
  294. error, constraints);
  295. if (failure_callback) {
  296. failure_callback(error, resolution);
  297. }
  298. });
  299. } catch (e) {
  300. console.error('GUM failed: ', e);
  301. if (failure_callback) {
  302. failure_callback(e);
  303. }
  304. }
  305. },
  306. setAvailableDevices: function (RTC, um, available) {
  307. var devices = {};
  308. if (um.indexOf("video") != -1) {
  309. devices.video = available;
  310. }
  311. if (um.indexOf("audio") != -1) {
  312. devices.audio = available;
  313. }
  314. RTC.setDeviceAvailability(devices);
  315. },
  316. /**
  317. * We ask for audio and video combined stream in order to get permissions and
  318. * not to ask twice.
  319. */
  320. obtainAudioAndVideoPermissions: function (RTC, devices, usageOptions, resolution) {
  321. var self = this;
  322. // Get AV
  323. return new Promise(function (resolve, reject) {
  324. var successCallback = function (stream) {
  325. resolve(self.successCallback(stream, usageOptions));
  326. };
  327. if (!devices)
  328. devices = ['audio', 'video'];
  329. var newDevices = [];
  330. if (usageOptions)
  331. for (var i = 0; i < devices.length; i++) {
  332. var device = devices[i];
  333. if (usageOptions[device] === true)
  334. newDevices.push(device);
  335. }
  336. else
  337. newDevices = devices;
  338. if (newDevices.length === 0) {
  339. successCallback();
  340. return;
  341. }
  342. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  343. // With FF/IE we can't split the stream into audio and video because FF
  344. // doesn't support media stream constructors. So, we need to get the
  345. // audio stream separately from the video stream using two distinct GUM
  346. // calls. Not very user friendly :-( but we don't have many other
  347. // options neither.
  348. //
  349. // Note that we pack those 2 streams in a single object and pass it to
  350. // the successCallback method.
  351. var obtainVideo = function (audioStream) {
  352. self.getUserMediaWithConstraints(
  353. RTC,
  354. ['video'],
  355. function (videoStream) {
  356. return successCallback({
  357. audioStream: audioStream,
  358. videoStream: videoStream
  359. });
  360. },
  361. function (error, resolution) {
  362. console.error(
  363. 'failed to obtain video stream - stop', error);
  364. self.errorCallback(error, resolve, RTC, resolution);
  365. },
  366. config.resolution || '360');
  367. };
  368. var obtainAudio = function () {
  369. self.getUserMediaWithConstraints(
  370. RTC,
  371. ['audio'],
  372. function (audioStream) {
  373. if (newDevices.indexOf('video') !== -1)
  374. obtainVideo(audioStream);
  375. },
  376. function (error) {
  377. console.error(
  378. 'failed to obtain audio stream - stop', error);
  379. self.errorCallback(error, resolve, RTC);
  380. }
  381. );
  382. };
  383. if (newDevices.indexOf('audio') !== -1) {
  384. obtainAudio();
  385. } else {
  386. obtainVideo(null);
  387. }
  388. } else {
  389. this.getUserMediaWithConstraints(
  390. RTC,
  391. newDevices,
  392. function (stream) {
  393. successCallback(stream);
  394. },
  395. function (error, resolution) {
  396. self.errorCallback(error, resolve, RTC, resolution);
  397. },
  398. resolution || '360');
  399. }
  400. }.bind(this));
  401. },
  402. successCallback: function (stream, usageOptions) {
  403. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  404. // it's an object with two properties: audioStream, videoStream.
  405. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  406. console.log('got', stream, stream.getAudioTracks().length,
  407. stream.getVideoTracks().length);
  408. return this.handleLocalStream(stream, usageOptions);
  409. },
  410. errorCallback: function (error, resolve, RTC, currentResolution) {
  411. var self = this;
  412. console.error('failed to obtain audio/video stream - trying audio only', error);
  413. var resolution = getPreviousResolution(currentResolution);
  414. if (typeof error == "object" && error.constraintName && error.name
  415. && (error.name == "ConstraintNotSatisfiedError" ||
  416. error.name == "OverconstrainedError") &&
  417. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  418. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  419. && resolution != null) {
  420. self.getUserMediaWithConstraints(RTC, ['audio', 'video'],
  421. function (stream) {
  422. resolve(self.successCallback(stream));
  423. }, function (error, resolution) {
  424. return self.errorCallback(error, resolve, RTC, resolution);
  425. }, resolution);
  426. }
  427. else {
  428. self.getUserMediaWithConstraints(
  429. RTC,
  430. ['audio'],
  431. function (stream) {
  432. resolve(self.successCallback(stream));
  433. },
  434. function (error) {
  435. console.error('failed to obtain audio/video stream - stop',
  436. error);
  437. resolve(self.successCallback(null));
  438. }
  439. );
  440. }
  441. },
  442. handleLocalStream: function (stream, usageOptions) {
  443. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  444. // an object with two properties: audioStream, videoStream.
  445. if (window.webkitMediaStream) {
  446. audioStream = new webkitMediaStream();
  447. videoStream = new webkitMediaStream();
  448. if (stream) {
  449. var audioTracks = stream.getAudioTracks();
  450. for (var i = 0; i < audioTracks.length; i++) {
  451. audioStream.addTrack(audioTracks[i]);
  452. }
  453. var videoTracks = stream.getVideoTracks();
  454. for (i = 0; i < videoTracks.length; i++) {
  455. videoStream.addTrack(videoTracks[i]);
  456. }
  457. }
  458. }
  459. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  460. if (stream && stream.audioStream)
  461. audioStream = stream.audioStream;
  462. else
  463. audioStream = new DummyMediaStream("dummyAudio");
  464. if (stream && stream.videoStream)
  465. videoStream = stream.videoStream;
  466. else
  467. videoStream = new DummyMediaStream("dummyVideo");
  468. }
  469. var audioMuted = (usageOptions && usageOptions.audio === false),
  470. videoMuted = (usageOptions && usageOptions.video === false);
  471. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  472. videoGUM = (!usageOptions || usageOptions.video !== false);
  473. return this.service.createLocalStreams(
  474. [
  475. {stream: audioStream, type: "audio", isMuted: audioMuted, isGUMStream: audioGUM, videoType: null},
  476. {stream: videoStream, type: "video", isMuted: videoMuted, isGUMStream: videoGUM, videoType: "camera"}
  477. ]);
  478. },
  479. createStream: function (stream, isVideo) {
  480. var newStream = null;
  481. if (window.webkitMediaStream) {
  482. newStream = new webkitMediaStream();
  483. if (newStream) {
  484. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  485. for (var i = 0; i < tracks.length; i++) {
  486. newStream.addTrack(tracks[i]);
  487. }
  488. }
  489. }
  490. else {
  491. // FIXME: this is duplicated with 'handleLocalStream' !!!
  492. if (stream) {
  493. newStream = stream;
  494. } else {
  495. newStream =
  496. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  497. }
  498. }
  499. return newStream;
  500. }
  501. }
  502. module.exports = RTCUtils;