Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

RTCUtils.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. 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 (RTCBrowserType.isAndroid()) {
  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. var constraints = getConstraints(
  268. um, resolution, bandwidth, fps, desktopStream);
  269. console.info("Get media constraints", constraints);
  270. var self = this;
  271. try {
  272. this.getUserMedia(constraints,
  273. function (stream) {
  274. console.log('onUserMediaSuccess');
  275. self.setAvailableDevices(um, true);
  276. success_callback(stream);
  277. },
  278. function (error) {
  279. self.setAvailableDevices(um, false);
  280. console.warn('Failed to get access to local media. Error ',
  281. error, constraints);
  282. if (failure_callback) {
  283. failure_callback(error);
  284. }
  285. });
  286. } catch (e) {
  287. console.error('GUM failed: ', e);
  288. if(failure_callback) {
  289. failure_callback(e);
  290. }
  291. }
  292. };
  293. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  294. var devices = {};
  295. if(um.indexOf("video") != -1) {
  296. devices.video = available;
  297. }
  298. if(um.indexOf("audio") != -1) {
  299. devices.audio = available;
  300. }
  301. this.service.setDeviceAvailability(devices);
  302. };
  303. /**
  304. * We ask for audio and video combined stream in order to get permissions and
  305. * not to ask twice.
  306. */
  307. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  308. function(devices, callback, usageOptions)
  309. {
  310. var self = this;
  311. // Get AV
  312. var successCallback = function (stream) {
  313. if(callback)
  314. callback(stream, usageOptions);
  315. else
  316. self.successCallback(stream, usageOptions);
  317. };
  318. if(!devices)
  319. devices = ['audio', 'video'];
  320. var newDevices = [];
  321. if(usageOptions)
  322. for(var i = 0; i < devices.length; i++) {
  323. var device = devices[i];
  324. if(usageOptions[device] === true)
  325. newDevices.push(device);
  326. }
  327. else
  328. newDevices = devices;
  329. if(newDevices.length === 0) {
  330. successCallback();
  331. return;
  332. }
  333. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  334. // With FF/IE we can't split the stream into audio and video because FF
  335. // doesn't support media stream constructors. So, we need to get the
  336. // audio stream separately from the video stream using two distinct GUM
  337. // calls. Not very user friendly :-( but we don't have many other
  338. // options neither.
  339. //
  340. // Note that we pack those 2 streams in a single object and pass it to
  341. // the successCallback method.
  342. var obtainVideo = function (audioStream) {
  343. self.getUserMediaWithConstraints(
  344. ['video'],
  345. function (videoStream) {
  346. return successCallback({
  347. audioStream: audioStream,
  348. videoStream: videoStream
  349. });
  350. },
  351. function (error) {
  352. console.error(
  353. 'failed to obtain video stream - stop', error);
  354. self.errorCallback(error);
  355. },
  356. config.resolution || '360');
  357. };
  358. var obtainAudio = function () {
  359. self.getUserMediaWithConstraints(
  360. ['audio'],
  361. function (audioStream) {
  362. if (newDevices.indexOf('video') !== -1)
  363. obtainVideo(audioStream);
  364. },
  365. function (error) {
  366. console.error(
  367. 'failed to obtain audio stream - stop', error);
  368. self.errorCallback(error);
  369. }
  370. );
  371. };
  372. if (newDevices.indexOf('audio') !== -1) {
  373. obtainAudio();
  374. } else {
  375. obtainVideo(null);
  376. }
  377. } else {
  378. this.getUserMediaWithConstraints(
  379. newDevices,
  380. function (stream) {
  381. successCallback(stream);
  382. },
  383. function (error) {
  384. self.errorCallback(error);
  385. },
  386. config.resolution || '360');
  387. }
  388. };
  389. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  390. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  391. // it's an object with two properties: audioStream, videoStream.
  392. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  393. console.log('got', stream, stream.getAudioTracks().length,
  394. stream.getVideoTracks().length);
  395. this.handleLocalStream(stream, usageOptions);
  396. };
  397. RTCUtils.prototype.errorCallback = function (error) {
  398. var self = this;
  399. console.error('failed to obtain audio/video stream - trying audio only', error);
  400. var resolution = getPreviousResolution(currentResolution);
  401. if(typeof error == "object" && error.constraintName && error.name
  402. && (error.name == "ConstraintNotSatisfiedError" ||
  403. error.name == "OverconstrainedError") &&
  404. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  405. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  406. && resolution != null)
  407. {
  408. self.getUserMediaWithConstraints(['audio', 'video'],
  409. function (stream) {
  410. return self.successCallback(stream);
  411. }, function (error) {
  412. return self.errorCallback(error);
  413. }, resolution);
  414. }
  415. else {
  416. self.getUserMediaWithConstraints(
  417. ['audio'],
  418. function (stream) {
  419. return self.successCallback(stream);
  420. },
  421. function (error) {
  422. console.error('failed to obtain audio/video stream - stop',
  423. error);
  424. return self.successCallback(null);
  425. }
  426. );
  427. }
  428. };
  429. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  430. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  431. // an object with two properties: audioStream, videoStream.
  432. var audioStream, videoStream;
  433. if(window.webkitMediaStream)
  434. {
  435. audioStream = new webkitMediaStream();
  436. videoStream = new webkitMediaStream();
  437. if(stream) {
  438. var audioTracks = stream.getAudioTracks();
  439. for (var i = 0; i < audioTracks.length; i++) {
  440. audioStream.addTrack(audioTracks[i]);
  441. }
  442. var videoTracks = stream.getVideoTracks();
  443. for (i = 0; i < videoTracks.length; i++) {
  444. videoStream.addTrack(videoTracks[i]);
  445. }
  446. }
  447. }
  448. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  449. { // Firefox and Temasys plugin
  450. if (stream && stream.audioStream)
  451. audioStream = stream.audioStream;
  452. else
  453. audioStream = new DummyMediaStream("dummyAudio");
  454. if (stream && stream.videoStream)
  455. videoStream = stream.videoStream;
  456. else
  457. videoStream = new DummyMediaStream("dummyVideo");
  458. }
  459. var audioMuted = (usageOptions && usageOptions.audio === false),
  460. videoMuted = (usageOptions && usageOptions.video === false);
  461. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  462. videoGUM = (!usageOptions || usageOptions.video !== false);
  463. this.service.createLocalStream(audioStream, "audio", null, null,
  464. audioMuted, audioGUM);
  465. this.service.createLocalStream(videoStream, "video", null, 'camera',
  466. videoMuted, videoGUM);
  467. };
  468. function DummyMediaStream(id) {
  469. this.id = id;
  470. this.label = id;
  471. this.stop = function() { };
  472. this.getAudioTracks = function() { return []; };
  473. this.getVideoTracks = function() { return []; };
  474. }
  475. RTCUtils.prototype.createStream = function(stream, isVideo) {
  476. var newStream = null;
  477. if (window.webkitMediaStream) {
  478. newStream = new webkitMediaStream();
  479. if (newStream) {
  480. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  481. for (var i = 0; i < tracks.length; i++) {
  482. newStream.addTrack(tracks[i]);
  483. }
  484. }
  485. }
  486. else {
  487. // FIXME: this is duplicated with 'handleLocalStream' !!!
  488. if (stream) {
  489. newStream = stream;
  490. } else {
  491. newStream =
  492. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  493. }
  494. }
  495. return newStream;
  496. };
  497. module.exports = RTCUtils;