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.

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