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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 EventEmitter = require("events");
  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. eventEmitter: new EventEmitter(),
  135. init: function (onTemasysPluginReady, options) {
  136. var self = this;
  137. if (RTCBrowserType.isFirefox()) {
  138. var FFversion = RTCBrowserType.getFirefoxVersion();
  139. if (FFversion >= 40) {
  140. this.peerconnection = mozRTCPeerConnection;
  141. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  142. this.pc_constraints = {};
  143. this.attachMediaStream = function (element, stream) {
  144. // srcObject is being standardized and FF will eventually
  145. // support that unprefixed. FF also supports the
  146. // "element.src = URL.createObjectURL(...)" combo, but that
  147. // will be deprecated in favour of srcObject.
  148. //
  149. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  150. // https://github.com/webrtc/samples/issues/302
  151. if (!element[0])
  152. return;
  153. element[0].mozSrcObject = stream;
  154. element[0].play();
  155. };
  156. this.getStreamID = function (stream) {
  157. var id = stream.id;
  158. if (!id) {
  159. var tracks = stream.getVideoTracks();
  160. if (!tracks || tracks.length === 0) {
  161. tracks = stream.getAudioTracks();
  162. }
  163. id = tracks[0].id;
  164. }
  165. return SDPUtil.filter_special_chars(id);
  166. };
  167. this.getVideoSrc = function (element) {
  168. if (!element)
  169. return null;
  170. return element.mozSrcObject;
  171. };
  172. this.setVideoSrc = function (element, src) {
  173. if (element)
  174. element.mozSrcObject = src;
  175. };
  176. RTCSessionDescription = mozRTCSessionDescription;
  177. RTCIceCandidate = mozRTCIceCandidate;
  178. } else {
  179. console.error(
  180. "Firefox version too old: " + FFversion + ". Required >= 40.");
  181. window.location.href = 'unsupported_browser.html';
  182. return;
  183. }
  184. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  185. this.peerconnection = webkitRTCPeerConnection;
  186. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  187. this.attachMediaStream = function (element, stream) {
  188. element.attr('src', webkitURL.createObjectURL(stream));
  189. };
  190. this.getStreamID = function (stream) {
  191. // streams from FF endpoints have the characters '{' and '}'
  192. // that make jQuery choke.
  193. return SDPUtil.filter_special_chars(stream.id);
  194. };
  195. this.getVideoSrc = function (element) {
  196. if (!element)
  197. return null;
  198. return element.getAttribute("src");
  199. };
  200. this.setVideoSrc = function (element, src) {
  201. if (element)
  202. element.setAttribute("src", src);
  203. };
  204. // DTLS should now be enabled by default but..
  205. this.pc_constraints = {'optional': [
  206. {'DtlsSrtpKeyAgreement': 'true'}
  207. ]};
  208. if (options.useIPv6) {
  209. // https://code.google.com/p/webrtc/issues/detail?id=2828
  210. this.pc_constraints.optional.push({googIPv6: true});
  211. }
  212. if (navigator.userAgent.indexOf('Android') != -1) {
  213. this.pc_constraints = {}; // disable DTLS on Android
  214. }
  215. if (!webkitMediaStream.prototype.getVideoTracks) {
  216. webkitMediaStream.prototype.getVideoTracks = function () {
  217. return this.videoTracks;
  218. };
  219. }
  220. if (!webkitMediaStream.prototype.getAudioTracks) {
  221. webkitMediaStream.prototype.getAudioTracks = function () {
  222. return this.audioTracks;
  223. };
  224. }
  225. }
  226. // Detect IE/Safari
  227. else if (RTCBrowserType.isTemasysPluginUsed()) {
  228. //AdapterJS.WebRTCPlugin.setLogLevel(
  229. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  230. AdapterJS.webRTCReady(function (isPlugin) {
  231. self.peerconnection = RTCPeerConnection;
  232. self.getUserMedia = getUserMedia;
  233. self.attachMediaStream = function (elSel, stream) {
  234. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  235. return;
  236. }
  237. attachMediaStream(elSel[0], stream);
  238. };
  239. self.getStreamID = function (stream) {
  240. var id = SDPUtil.filter_special_chars(stream.label);
  241. return id;
  242. };
  243. self.getVideoSrc = function (element) {
  244. if (!element) {
  245. console.warn("Attempt to get video SRC of null element");
  246. return null;
  247. }
  248. var children = element.children;
  249. for (var i = 0; i !== children.length; ++i) {
  250. if (children[i].name === 'streamId') {
  251. return children[i].value;
  252. }
  253. }
  254. //console.info(element.id + " SRC: " + src);
  255. return null;
  256. };
  257. self.setVideoSrc = function (element, src) {
  258. //console.info("Set video src: ", element, src);
  259. if (!src) {
  260. console.warn("Not attaching video stream, 'src' is null");
  261. return;
  262. }
  263. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  264. var stream = AdapterJS.WebRTCPlugin.plugin
  265. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  266. attachMediaStream(element, stream);
  267. };
  268. onTemasysPluginReady(isPlugin);
  269. });
  270. } else {
  271. try {
  272. console.log('Browser does not appear to be WebRTC-capable');
  273. } catch (e) {
  274. }
  275. window.location.href = 'unsupported_browser.html';
  276. }
  277. },
  278. getUserMediaWithConstraints: function (RTC, um, success_callback, failure_callback, resolution, bandwidth, fps, desktopStream) {
  279. // Check if we are running on Android device
  280. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  281. var constraints = getConstraints(
  282. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  283. console.info("Get media constraints", constraints);
  284. var self = this;
  285. try {
  286. this.getUserMedia(constraints,
  287. function (stream) {
  288. console.log('onUserMediaSuccess');
  289. self.setAvailableDevices(RTC, um, true);
  290. success_callback(stream);
  291. },
  292. function (error) {
  293. self.setAvailableDevices(RTC, um, false);
  294. console.warn('Failed to get access to local media. Error ',
  295. error, constraints);
  296. if (failure_callback) {
  297. failure_callback(error, resolution);
  298. }
  299. });
  300. } catch (e) {
  301. console.error('GUM failed: ', e);
  302. if (failure_callback) {
  303. failure_callback(e);
  304. }
  305. }
  306. },
  307. setAvailableDevices: function (RTC, um, available) {
  308. var devices = {};
  309. if (um.indexOf("video") != -1) {
  310. devices.video = available;
  311. }
  312. if (um.indexOf("audio") != -1) {
  313. devices.audio = available;
  314. }
  315. RTC.setDeviceAvailability(devices);
  316. },
  317. /**
  318. * We ask for audio and video combined stream in order to get permissions and
  319. * not to ask twice.
  320. */
  321. obtainAudioAndVideoPermissions: function (RTC, devices, usageOptions, resolution) {
  322. var self = this;
  323. // Get AV
  324. return new Promise(function (resolve, reject) {
  325. var successCallback = function (stream) {
  326. resolve(self.successCallback(RTC , stream, usageOptions));
  327. };
  328. if (!devices)
  329. devices = ['audio', 'video'];
  330. var newDevices = [];
  331. if (usageOptions)
  332. for (var i = 0; i < devices.length; i++) {
  333. var device = devices[i];
  334. if (usageOptions[device] === true)
  335. newDevices.push(device);
  336. }
  337. else
  338. newDevices = devices;
  339. if (newDevices.length === 0) {
  340. successCallback();
  341. return;
  342. }
  343. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  344. // With FF/IE we can't split the stream into audio and video because FF
  345. // doesn't support media stream constructors. So, we need to get the
  346. // audio stream separately from the video stream using two distinct GUM
  347. // calls. Not very user friendly :-( but we don't have many other
  348. // options neither.
  349. //
  350. // Note that we pack those 2 streams in a single object and pass it to
  351. // the successCallback method.
  352. var obtainVideo = function (audioStream) {
  353. self.getUserMediaWithConstraints(
  354. RTC,
  355. ['video'],
  356. function (videoStream) {
  357. return successCallback({
  358. audioStream: audioStream,
  359. videoStream: videoStream
  360. });
  361. },
  362. function (error, resolution) {
  363. console.error(
  364. 'failed to obtain video stream - stop', error);
  365. self.errorCallback(error, resolve, RTC, resolution);
  366. },
  367. config.resolution || '360');
  368. };
  369. var obtainAudio = function () {
  370. self.getUserMediaWithConstraints(
  371. RTC,
  372. ['audio'],
  373. function (audioStream) {
  374. if (newDevices.indexOf('video') !== -1)
  375. obtainVideo(audioStream);
  376. },
  377. function (error) {
  378. console.error(
  379. 'failed to obtain audio stream - stop', error);
  380. self.errorCallback(error, resolve, RTC);
  381. }
  382. );
  383. };
  384. if (newDevices.indexOf('audio') !== -1) {
  385. obtainAudio();
  386. } else {
  387. obtainVideo(null);
  388. }
  389. } else {
  390. this.getUserMediaWithConstraints(
  391. RTC,
  392. newDevices,
  393. function (stream) {
  394. successCallback(stream);
  395. },
  396. function (error, resolution) {
  397. self.errorCallback(error, resolve, RTC, resolution);
  398. },
  399. resolution || '360');
  400. }
  401. }.bind(this));
  402. },
  403. successCallback: function (RTC, stream, usageOptions) {
  404. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  405. // it's an object with two properties: audioStream, videoStream.
  406. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  407. console.log('got', stream, stream.getAudioTracks().length,
  408. stream.getVideoTracks().length);
  409. return this.handleLocalStream(RTC, stream, usageOptions);
  410. },
  411. errorCallback: function (error, resolve, RTC, currentResolution) {
  412. var self = this;
  413. console.error('failed to obtain audio/video stream - trying audio only', error);
  414. var resolution = getPreviousResolution(currentResolution);
  415. if (typeof error == "object" && error.constraintName && error.name
  416. && (error.name == "ConstraintNotSatisfiedError" ||
  417. error.name == "OverconstrainedError") &&
  418. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  419. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  420. && resolution != null) {
  421. self.getUserMediaWithConstraints(RTC, ['audio', 'video'],
  422. function (stream) {
  423. resolve(self.successCallback(RTC, stream));
  424. }, function (error, resolution) {
  425. return self.errorCallback(error, resolve, RTC, resolution);
  426. }, resolution);
  427. }
  428. else {
  429. self.getUserMediaWithConstraints(
  430. RTC,
  431. ['audio'],
  432. function (stream) {
  433. resolve(self.successCallback(RTC, stream));
  434. },
  435. function (error) {
  436. console.error('failed to obtain audio/video stream - stop',
  437. error);
  438. resolve(self.successCallback(RTC, null));
  439. }
  440. );
  441. }
  442. },
  443. handleLocalStream: function (service, stream, usageOptions) {
  444. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  445. // an object with two properties: audioStream, videoStream.
  446. if (window.webkitMediaStream) {
  447. audioStream = new webkitMediaStream();
  448. videoStream = new webkitMediaStream();
  449. if (stream) {
  450. var audioTracks = stream.getAudioTracks();
  451. for (var i = 0; i < audioTracks.length; i++) {
  452. audioStream.addTrack(audioTracks[i]);
  453. }
  454. var videoTracks = stream.getVideoTracks();
  455. for (i = 0; i < videoTracks.length; i++) {
  456. videoStream.addTrack(videoTracks[i]);
  457. }
  458. }
  459. }
  460. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  461. if (stream && stream.audioStream)
  462. audioStream = stream.audioStream;
  463. else
  464. audioStream = new DummyMediaStream("dummyAudio");
  465. if (stream && stream.videoStream)
  466. videoStream = stream.videoStream;
  467. else
  468. videoStream = new DummyMediaStream("dummyVideo");
  469. }
  470. var audioMuted = (usageOptions && usageOptions.audio === false),
  471. videoMuted = (usageOptions && usageOptions.video === false);
  472. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  473. videoGUM = (!usageOptions || usageOptions.video !== false);
  474. return service.createLocalStreams(
  475. [
  476. {stream: audioStream, type: "audio", isMuted: audioMuted, isGUMStream: audioGUM, videoType: null},
  477. {stream: videoStream, type: "video", isMuted: videoMuted, isGUMStream: videoGUM, videoType: "camera"}
  478. ]);
  479. },
  480. createStream: function (stream, isVideo) {
  481. var newStream = null;
  482. if (window.webkitMediaStream) {
  483. newStream = new webkitMediaStream();
  484. if (newStream) {
  485. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  486. for (var i = 0; i < tracks.length; i++) {
  487. newStream.addTrack(tracks[i]);
  488. }
  489. }
  490. }
  491. else {
  492. // FIXME: this is duplicated with 'handleLocalStream' !!!
  493. if (stream) {
  494. newStream = stream;
  495. } else {
  496. newStream =
  497. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  498. }
  499. }
  500. return newStream;
  501. }
  502. }
  503. module.exports = RTCUtils;