Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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