Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RTCUtils.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /* global APP, config, require, attachMediaStream, getUserMedia,
  2. RTCPeerConnection, webkitMediaStream, webkitURL, webkitRTCPeerConnection,
  3. mozRTCIceCandidate, mozRTCSessionDescription, mozRTCPeerConnection */
  4. /* jshint -W101 */
  5. var RTCBrowserType = require("./RTCBrowserType");
  6. var Resolutions = require("../../service/RTC/Resolutions");
  7. var AdapterJS = require("./adapter.screenshare");
  8. var currentResolution = null;
  9. function getPreviousResolution(resolution) {
  10. if(!Resolutions[resolution])
  11. return null;
  12. var order = Resolutions[resolution].order;
  13. var res = null;
  14. var resName = null;
  15. for(var i in Resolutions) {
  16. var tmp = Resolutions[i];
  17. if (!res || (res.order < tmp.order && tmp.order < order)) {
  18. resName = i;
  19. res = tmp;
  20. }
  21. }
  22. return resName;
  23. }
  24. function setResolutionConstraints(constraints, resolution) {
  25. var isAndroid = RTCBrowserType.isAndroid();
  26. if (Resolutions[resolution]) {
  27. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  28. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  29. }
  30. else if (isAndroid) {
  31. // FIXME can't remember if the purpose of this was to always request
  32. // low resolution on Android ? if yes it should be moved up front
  33. constraints.video.mandatory.minWidth = 320;
  34. constraints.video.mandatory.minHeight = 240;
  35. constraints.video.mandatory.maxFrameRate = 15;
  36. }
  37. if (constraints.video.mandatory.minWidth)
  38. constraints.video.mandatory.maxWidth =
  39. constraints.video.mandatory.minWidth;
  40. if (constraints.video.mandatory.minHeight)
  41. constraints.video.mandatory.maxHeight =
  42. constraints.video.mandatory.minHeight;
  43. }
  44. function getConstraints(um, resolution, bandwidth, fps, desktopStream) {
  45. var constraints = {audio: false, video: false};
  46. if (um.indexOf('video') >= 0) {
  47. // same behaviour as true
  48. constraints.video = { mandatory: {}, optional: [] };
  49. constraints.video.optional.push({ googLeakyBucket: true });
  50. setResolutionConstraints(constraints, resolution);
  51. }
  52. if (um.indexOf('audio') >= 0) {
  53. if (!RTCBrowserType.isFirefox()) {
  54. // same behaviour as true
  55. constraints.audio = { mandatory: {}, optional: []};
  56. // if it is good enough for hangouts...
  57. constraints.audio.optional.push(
  58. {googEchoCancellation: true},
  59. {googAutoGainControl: true},
  60. {googNoiseSupression: true},
  61. {googHighpassFilter: true},
  62. {googNoisesuppression2: true},
  63. {googEchoCancellation2: true},
  64. {googAutoGainControl2: true}
  65. );
  66. } else {
  67. constraints.audio = true;
  68. }
  69. }
  70. if (um.indexOf('screen') >= 0) {
  71. if (RTCBrowserType.isChrome()) {
  72. constraints.video = {
  73. mandatory: {
  74. chromeMediaSource: "screen",
  75. googLeakyBucket: true,
  76. maxWidth: window.screen.width,
  77. maxHeight: window.screen.height,
  78. maxFrameRate: 3
  79. },
  80. optional: []
  81. };
  82. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  83. constraints.video = {
  84. optional: [
  85. {
  86. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  87. }
  88. ]
  89. };
  90. } else if (RTCBrowserType.isFirefox()) {
  91. constraints.video = {
  92. mozMediaSource: "window",
  93. mediaSource: "window"
  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. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  131. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  132. // this later can be a problem with some of the tests
  133. if(RTCBrowserType.isFirefox() && config.firefox_fake_device)
  134. {
  135. constraints.audio = true;
  136. constraints.fake = true;
  137. }
  138. return constraints;
  139. }
  140. function RTCUtils(RTCService, onTemasysPluginReady)
  141. {
  142. var self = this;
  143. this.service = RTCService;
  144. if (RTCBrowserType.isFirefox()) {
  145. var FFversion = RTCBrowserType.getFirefoxVersion();
  146. if (FFversion >= 40) {
  147. this.peerconnection = mozRTCPeerConnection;
  148. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  149. this.pc_constraints = {};
  150. this.attachMediaStream = function (element, stream) {
  151. // srcObject is being standardized and FF will eventually
  152. // support that unprefixed. FF also supports the
  153. // "element.src = URL.createObjectURL(...)" combo, but that
  154. // will be deprecated in favour of srcObject.
  155. //
  156. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  157. // https://github.com/webrtc/samples/issues/302
  158. if(!element[0])
  159. return;
  160. element[0].mozSrcObject = stream;
  161. element[0].play();
  162. };
  163. this.getStreamID = function (stream) {
  164. var id = stream.id;
  165. if (!id) {
  166. var tracks = stream.getVideoTracks();
  167. if (!tracks || tracks.length === 0) {
  168. tracks = stream.getAudioTracks();
  169. }
  170. id = tracks[0].id;
  171. }
  172. return APP.xmpp.filter_special_chars(id);
  173. };
  174. this.getVideoSrc = function (element) {
  175. if(!element)
  176. return null;
  177. return element.mozSrcObject;
  178. };
  179. this.setVideoSrc = function (element, src) {
  180. if(element)
  181. element.mozSrcObject = src;
  182. };
  183. window.RTCSessionDescription = mozRTCSessionDescription;
  184. window.RTCIceCandidate = mozRTCIceCandidate;
  185. } else {
  186. console.error(
  187. "Firefox version too old: " + FFversion + ". Required >= 40.");
  188. window.location.href = 'unsupported_browser.html';
  189. return;
  190. }
  191. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  192. this.peerconnection = webkitRTCPeerConnection;
  193. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  194. this.attachMediaStream = function (element, stream) {
  195. element.attr('src', webkitURL.createObjectURL(stream));
  196. };
  197. this.getStreamID = function (stream) {
  198. // streams from FF endpoints have the characters '{' and '}'
  199. // that make jQuery choke.
  200. return APP.xmpp.filter_special_chars(stream.id);
  201. };
  202. this.getVideoSrc = function (element) {
  203. if(!element)
  204. return null;
  205. return element.getAttribute("src");
  206. };
  207. this.setVideoSrc = function (element, src) {
  208. if(element)
  209. element.setAttribute("src", src);
  210. };
  211. // DTLS should now be enabled by default but..
  212. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  213. if (RTCBrowserType.isAndroid()) {
  214. this.pc_constraints = {}; // disable DTLS on Android
  215. }
  216. if (!webkitMediaStream.prototype.getVideoTracks) {
  217. webkitMediaStream.prototype.getVideoTracks = function () {
  218. return this.videoTracks;
  219. };
  220. }
  221. if (!webkitMediaStream.prototype.getAudioTracks) {
  222. webkitMediaStream.prototype.getAudioTracks = function () {
  223. return this.audioTracks;
  224. };
  225. }
  226. }
  227. // Detect IE/Safari
  228. else if (RTCBrowserType.isTemasysPluginUsed()) {
  229. //AdapterJS.WebRTCPlugin.setLogLevel(
  230. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  231. AdapterJS.webRTCReady(function (isPlugin) {
  232. self.peerconnection = RTCPeerConnection;
  233. self.getUserMedia = getUserMedia;
  234. self.attachMediaStream = function (elSel, stream) {
  235. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  236. return;
  237. }
  238. attachMediaStream(elSel[0], stream);
  239. };
  240. self.getStreamID = function (stream) {
  241. return APP.xmpp.filter_special_chars(stream.label);
  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. window.location.href = 'unsupported_browser.html';
  275. }
  276. }
  277. RTCUtils.prototype.getUserMediaWithConstraints = function(
  278. um, success_callback, failure_callback, resolution,bandwidth, fps,
  279. desktopStream) {
  280. currentResolution = resolution;
  281. var constraints = getConstraints(
  282. um, resolution, bandwidth, fps, desktopStream);
  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(um, true);
  290. success_callback(stream);
  291. },
  292. function (error) {
  293. self.setAvailableDevices(um, false);
  294. console.warn('Failed to get access to local media. Error ',
  295. error, constraints);
  296. if (failure_callback) {
  297. failure_callback(error);
  298. }
  299. });
  300. } catch (e) {
  301. console.error('GUM failed: ', e);
  302. if(failure_callback) {
  303. failure_callback(e);
  304. }
  305. }
  306. };
  307. RTCUtils.prototype.setAvailableDevices = function (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. this.service.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. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  322. function(devices, callback, usageOptions)
  323. {
  324. var self = this;
  325. // Get AV
  326. var successCallback = function (stream) {
  327. if(callback)
  328. callback(stream, usageOptions);
  329. else
  330. self.successCallback(stream, usageOptions);
  331. };
  332. if(!devices)
  333. devices = ['audio', 'video'];
  334. var newDevices = [];
  335. if(usageOptions)
  336. for(var i = 0; i < devices.length; i++) {
  337. var device = devices[i];
  338. if(usageOptions[device] === true)
  339. newDevices.push(device);
  340. }
  341. else
  342. newDevices = devices;
  343. if(newDevices.length === 0) {
  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)
  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. self.getUserMediaWithConstraints(
  431. ['audio'],
  432. function (stream) {
  433. return self.successCallback(stream);
  434. },
  435. function (error) {
  436. console.error('failed to obtain audio/video stream - stop',
  437. error);
  438. return self.successCallback(null);
  439. }
  440. );
  441. }
  442. };
  443. RTCUtils.prototype.handleLocalStream = function(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. 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, 'camera',
  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 (var 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 =
  506. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  507. }
  508. }
  509. return newStream;
  510. };
  511. module.exports = RTCUtils;