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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 getPreviousResolution(resolution) {
  8. if(!Resolutions[resolution])
  9. return null;
  10. var order = Resolutions[resolution].order;
  11. var res = null;
  12. var resName = null;
  13. for(var i in Resolutions) {
  14. var tmp = Resolutions[i];
  15. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  16. resName = i;
  17. res = tmp;
  18. }
  19. }
  20. return resName;
  21. }
  22. function setResolutionConstraints(constraints, resolution) {
  23. var isAndroid = RTCBrowserType.isAndroid();
  24. if (Resolutions[resolution]) {
  25. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  26. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  27. }
  28. else if (isAndroid) {
  29. // FIXME can't remember if the purpose of this was to always request
  30. // low resolution on Android ? if yes it should be moved up front
  31. constraints.video.mandatory.minWidth = 320;
  32. constraints.video.mandatory.minHeight = 240;
  33. constraints.video.mandatory.maxFrameRate = 15;
  34. }
  35. if (constraints.video.mandatory.minWidth)
  36. constraints.video.mandatory.maxWidth =
  37. constraints.video.mandatory.minWidth;
  38. if (constraints.video.mandatory.minHeight)
  39. constraints.video.mandatory.maxHeight =
  40. constraints.video.mandatory.minHeight;
  41. }
  42. function getConstraints(um, resolution, bandwidth, fps, desktopStream) {
  43. var constraints = {audio: false, video: false};
  44. if (um.indexOf('video') >= 0) {
  45. // same behaviour as true
  46. constraints.video = { mandatory: {}, optional: [] };
  47. constraints.video.optional.push({ googLeakyBucket: true });
  48. setResolutionConstraints(constraints, resolution);
  49. }
  50. if (um.indexOf('audio') >= 0) {
  51. if (!RTCBrowserType.isFirefox()) {
  52. // same behaviour as true
  53. constraints.audio = { mandatory: {}, optional: []};
  54. // if it is good enough for hangouts...
  55. constraints.audio.optional.push(
  56. {googEchoCancellation: true},
  57. {googAutoGainControl: true},
  58. {googNoiseSupression: true},
  59. {googHighpassFilter: true},
  60. {googNoisesuppression2: true},
  61. {googEchoCancellation2: true},
  62. {googAutoGainControl2: true}
  63. );
  64. } else {
  65. constraints.audio = true;
  66. }
  67. }
  68. if (um.indexOf('screen') >= 0) {
  69. if (RTCBrowserType.isChrome()) {
  70. constraints.video = {
  71. mandatory: {
  72. chromeMediaSource: "screen",
  73. googLeakyBucket: true,
  74. maxWidth: window.screen.width,
  75. maxHeight: window.screen.height,
  76. maxFrameRate: 3
  77. },
  78. optional: []
  79. };
  80. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  81. constraints.video = {
  82. optional: [
  83. {
  84. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  85. }
  86. ]
  87. };
  88. } else {
  89. console.error(
  90. "'screen' WebRTC media source is supported only in Chrome" +
  91. " and with Temasys plugin");
  92. }
  93. }
  94. if (um.indexOf('desktop') >= 0) {
  95. constraints.video = {
  96. mandatory: {
  97. chromeMediaSource: "desktop",
  98. chromeMediaSourceId: desktopStream,
  99. googLeakyBucket: true,
  100. maxWidth: window.screen.width,
  101. maxHeight: window.screen.height,
  102. maxFrameRate: 3
  103. },
  104. optional: []
  105. };
  106. }
  107. if (bandwidth) {
  108. if (!constraints.video) {
  109. //same behaviour as true
  110. constraints.video = {mandatory: {}, optional: []};
  111. }
  112. constraints.video.optional.push({bandwidth: bandwidth});
  113. }
  114. if (fps) {
  115. // for some cameras it might be necessary to request 30fps
  116. // so they choose 30fps mjpg over 10fps yuy2
  117. if (!constraints.video) {
  118. // same behaviour as true;
  119. constraints.video = {mandatory: {}, optional: []};
  120. }
  121. constraints.video.mandatory.minFrameRate = fps;
  122. }
  123. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  124. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  125. // this later can be a problem with some of the tests
  126. if(RTCBrowserType.isFirefox() && config.firefox_fake_device)
  127. {
  128. constraints.audio = true;
  129. constraints.fake = true;
  130. }
  131. return constraints;
  132. }
  133. function RTCUtils(RTCService, onTemasysPluginReady)
  134. {
  135. var self = this;
  136. this.service = RTCService;
  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': [{'DtlsSrtpKeyAgreement': 'true'}]};
  206. if (RTCBrowserType.isAndroid()) {
  207. this.pc_constraints = {}; // disable DTLS on Android
  208. }
  209. if (!webkitMediaStream.prototype.getVideoTracks) {
  210. webkitMediaStream.prototype.getVideoTracks = function () {
  211. return this.videoTracks;
  212. };
  213. }
  214. if (!webkitMediaStream.prototype.getAudioTracks) {
  215. webkitMediaStream.prototype.getAudioTracks = function () {
  216. return this.audioTracks;
  217. };
  218. }
  219. }
  220. // Detect IE/Safari
  221. else if (RTCBrowserType.isTemasysPluginUsed()) {
  222. //AdapterJS.WebRTCPlugin.setLogLevel(
  223. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  224. AdapterJS.webRTCReady(function (isPlugin) {
  225. self.peerconnection = RTCPeerConnection;
  226. self.getUserMedia = getUserMedia;
  227. self.attachMediaStream = function (elSel, stream) {
  228. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  229. return;
  230. }
  231. attachMediaStream(elSel[0], stream);
  232. };
  233. self.getStreamID = function (stream) {
  234. var id = SDPUtil.filter_special_chars(stream.label);
  235. return id;
  236. };
  237. self.getVideoSrc = function (element) {
  238. if (!element) {
  239. console.warn("Attempt to get video SRC of null element");
  240. return null;
  241. }
  242. var children = element.children;
  243. for (var i = 0; i !== children.length; ++i) {
  244. if (children[i].name === 'streamId') {
  245. return children[i].value;
  246. }
  247. }
  248. //console.info(element.id + " SRC: " + src);
  249. return null;
  250. };
  251. self.setVideoSrc = function (element, src) {
  252. //console.info("Set video src: ", element, src);
  253. if (!src) {
  254. console.warn("Not attaching video stream, 'src' is null");
  255. return;
  256. }
  257. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  258. var stream = AdapterJS.WebRTCPlugin.plugin
  259. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  260. attachMediaStream(element, stream);
  261. };
  262. onTemasysPluginReady(isPlugin);
  263. });
  264. } else {
  265. try {
  266. console.log('Browser does not appear to be WebRTC-capable');
  267. } catch (e) { }
  268. window.location.href = 'unsupported_browser.html';
  269. }
  270. }
  271. RTCUtils.prototype.getUserMediaWithConstraints = function(
  272. um, success_callback, failure_callback, resolution,bandwidth, fps,
  273. desktopStream) {
  274. currentResolution = resolution;
  275. var constraints = getConstraints(
  276. um, resolution, bandwidth, fps, desktopStream);
  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. devices.video = available;
  305. }
  306. if(um.indexOf("audio") != -1) {
  307. devices.audio = available;
  308. }
  309. this.service.setDeviceAvailability(devices);
  310. };
  311. /**
  312. * We ask for audio and video combined stream in order to get permissions and
  313. * not to ask twice.
  314. */
  315. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  316. function(devices, callback, usageOptions)
  317. {
  318. var self = this;
  319. // Get AV
  320. var successCallback = function (stream) {
  321. if(callback)
  322. callback(stream, usageOptions);
  323. else
  324. self.successCallback(stream, usageOptions);
  325. };
  326. if(!devices)
  327. devices = ['audio', 'video'];
  328. var newDevices = [];
  329. if(usageOptions)
  330. for(var i = 0; i < devices.length; i++) {
  331. var device = devices[i];
  332. if(usageOptions[device] === true)
  333. newDevices.push(device);
  334. }
  335. else
  336. newDevices = devices;
  337. if(newDevices.length === 0) {
  338. successCallback();
  339. return;
  340. }
  341. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  342. // With FF/IE we can't split the stream into audio and video because FF
  343. // doesn't support media stream constructors. So, we need to get the
  344. // audio stream separately from the video stream using two distinct GUM
  345. // calls. Not very user friendly :-( but we don't have many other
  346. // options neither.
  347. //
  348. // Note that we pack those 2 streams in a single object and pass it to
  349. // the successCallback method.
  350. var obtainVideo = function (audioStream) {
  351. self.getUserMediaWithConstraints(
  352. ['video'],
  353. function (videoStream) {
  354. return successCallback({
  355. audioStream: audioStream,
  356. videoStream: videoStream
  357. });
  358. },
  359. function (error) {
  360. console.error(
  361. 'failed to obtain video stream - stop', error);
  362. self.errorCallback(error);
  363. },
  364. config.resolution || '360');
  365. };
  366. var obtainAudio = function () {
  367. self.getUserMediaWithConstraints(
  368. ['audio'],
  369. function (audioStream) {
  370. if (newDevices.indexOf('video') !== -1)
  371. obtainVideo(audioStream);
  372. },
  373. function (error) {
  374. console.error(
  375. 'failed to obtain audio stream - stop', error);
  376. self.errorCallback(error);
  377. }
  378. );
  379. };
  380. if (newDevices.indexOf('audio') !== -1) {
  381. obtainAudio();
  382. } else {
  383. obtainVideo(null);
  384. }
  385. } else {
  386. this.getUserMediaWithConstraints(
  387. newDevices,
  388. function (stream) {
  389. successCallback(stream);
  390. },
  391. function (error) {
  392. self.errorCallback(error);
  393. },
  394. config.resolution || '360');
  395. }
  396. };
  397. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  398. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  399. // it's an object with two properties: audioStream, videoStream.
  400. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  401. console.log('got', stream, stream.getAudioTracks().length,
  402. stream.getVideoTracks().length);
  403. this.handleLocalStream(stream, usageOptions);
  404. };
  405. RTCUtils.prototype.errorCallback = function (error) {
  406. var self = this;
  407. console.error('failed to obtain audio/video stream - trying audio only', error);
  408. var resolution = getPreviousResolution(currentResolution);
  409. if(typeof error == "object" && error.constraintName && error.name
  410. && (error.name == "ConstraintNotSatisfiedError" ||
  411. error.name == "OverconstrainedError") &&
  412. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  413. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  414. && resolution != null)
  415. {
  416. self.getUserMediaWithConstraints(['audio', 'video'],
  417. function (stream) {
  418. return self.successCallback(stream);
  419. }, function (error) {
  420. return self.errorCallback(error);
  421. }, resolution);
  422. }
  423. else {
  424. self.getUserMediaWithConstraints(
  425. ['audio'],
  426. function (stream) {
  427. return self.successCallback(stream);
  428. },
  429. function (error) {
  430. console.error('failed to obtain audio/video stream - stop',
  431. error);
  432. return self.successCallback(null);
  433. }
  434. );
  435. }
  436. };
  437. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  438. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  439. // an object with two properties: audioStream, videoStream.
  440. var audioStream, videoStream;
  441. if(window.webkitMediaStream)
  442. {
  443. audioStream = new webkitMediaStream();
  444. videoStream = new webkitMediaStream();
  445. if(stream) {
  446. var audioTracks = stream.getAudioTracks();
  447. for (var i = 0; i < audioTracks.length; i++) {
  448. audioStream.addTrack(audioTracks[i]);
  449. }
  450. var videoTracks = stream.getVideoTracks();
  451. for (i = 0; i < videoTracks.length; i++) {
  452. videoStream.addTrack(videoTracks[i]);
  453. }
  454. }
  455. }
  456. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  457. { // Firefox and Temasys plugin
  458. if (stream && stream.audioStream)
  459. audioStream = stream.audioStream;
  460. else
  461. audioStream = new DummyMediaStream("dummyAudio");
  462. if (stream && stream.videoStream)
  463. videoStream = stream.videoStream;
  464. else
  465. videoStream = new DummyMediaStream("dummyVideo");
  466. }
  467. var audioMuted = (usageOptions && usageOptions.audio === false),
  468. videoMuted = (usageOptions && usageOptions.video === false);
  469. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  470. videoGUM = (!usageOptions || usageOptions.video !== false);
  471. this.service.createLocalStream(audioStream, "audio", null, null,
  472. audioMuted, audioGUM);
  473. this.service.createLocalStream(videoStream, "video", null, 'camera',
  474. videoMuted, videoGUM);
  475. };
  476. function DummyMediaStream(id) {
  477. this.id = id;
  478. this.label = id;
  479. this.stop = function() { };
  480. this.getAudioTracks = function() { return []; };
  481. this.getVideoTracks = function() { return []; };
  482. }
  483. RTCUtils.prototype.createStream = function(stream, isVideo) {
  484. var newStream = null;
  485. if (window.webkitMediaStream) {
  486. newStream = new webkitMediaStream();
  487. if (newStream) {
  488. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  489. for (var i = 0; i < tracks.length; i++) {
  490. newStream.addTrack(tracks[i]);
  491. }
  492. }
  493. }
  494. else {
  495. // FIXME: this is duplicated with 'handleLocalStream' !!!
  496. if (stream) {
  497. newStream = stream;
  498. } else {
  499. newStream =
  500. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  501. }
  502. }
  503. return newStream;
  504. };
  505. module.exports = RTCUtils;