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 20KB

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