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.

RTCUtils.js 19KB

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