您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTCUtils.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  2. var Resolutions = require("../../service/RTC/Resolutions");
  3. var currentResolution = null;
  4. function getPreviousResolution(resolution) {
  5. if(!Resolutions[resolution])
  6. return null;
  7. var order = Resolutions[resolution].order;
  8. var res = null;
  9. var resName = null;
  10. for(var i in Resolutions)
  11. {
  12. var tmp = Resolutions[i];
  13. if(res == null || (res.order < tmp.order && tmp.order < order))
  14. {
  15. resName = i;
  16. res = tmp;
  17. }
  18. }
  19. return resName;
  20. }
  21. function setResolutionConstraints(constraints, resolution, isAndroid)
  22. {
  23. if (resolution && !constraints.video || isAndroid) {
  24. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  25. }
  26. if(Resolutions[resolution])
  27. {
  28. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  29. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  30. }
  31. else
  32. {
  33. if (isAndroid) {
  34. constraints.video.mandatory.minWidth = 320;
  35. constraints.video.mandatory.minHeight = 240;
  36. constraints.video.mandatory.maxFrameRate = 15;
  37. }
  38. }
  39. if (constraints.video.mandatory.minWidth)
  40. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  41. if (constraints.video.mandatory.minHeight)
  42. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  43. }
  44. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  45. {
  46. var constraints = {audio: false, video: false};
  47. if (um.indexOf('video') >= 0) {
  48. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  49. }
  50. if (um.indexOf('audio') >= 0) {
  51. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  52. }
  53. if (um.indexOf('screen') >= 0) {
  54. constraints.video = {
  55. mandatory: {
  56. chromeMediaSource: "screen",
  57. googLeakyBucket: true,
  58. maxWidth: window.screen.width,
  59. maxHeight: window.screen.height,
  60. maxFrameRate: 3
  61. },
  62. optional: []
  63. };
  64. }
  65. if (um.indexOf('desktop') >= 0) {
  66. constraints.video = {
  67. mandatory: {
  68. chromeMediaSource: "desktop",
  69. chromeMediaSourceId: desktopStream,
  70. googLeakyBucket: true,
  71. maxWidth: window.screen.width,
  72. maxHeight: window.screen.height,
  73. maxFrameRate: 3
  74. },
  75. optional: []
  76. };
  77. }
  78. if (constraints.audio) {
  79. // if it is good enough for hangouts...
  80. constraints.audio.optional.push(
  81. {googEchoCancellation: true},
  82. {googAutoGainControl: true},
  83. {googNoiseSupression: true},
  84. {googHighpassFilter: true},
  85. {googNoisesuppression2: true},
  86. {googEchoCancellation2: true},
  87. {googAutoGainControl2: true}
  88. );
  89. }
  90. if (constraints.video) {
  91. constraints.video.optional.push(
  92. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  93. );
  94. if (um.indexOf('video') >= 0) {
  95. constraints.video.optional.push(
  96. {googLeakyBucket: true}
  97. );
  98. }
  99. }
  100. if (um.indexOf('video') >= 0) {
  101. setResolutionConstraints(constraints, resolution, isAndroid);
  102. }
  103. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  104. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  105. constraints.video.optional.push({bandwidth: bandwidth});
  106. }
  107. if (fps) { // for some cameras it might be necessary to request 30fps
  108. // so they choose 30fps mjpg over 10fps yuy2
  109. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  110. constraints.video.mandatory.minFrameRate = fps;
  111. }
  112. return constraints;
  113. }
  114. function RTCUtils(RTCService)
  115. {
  116. this.service = RTCService;
  117. if (navigator.mozGetUserMedia) {
  118. console.log('This appears to be Firefox');
  119. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  120. if (version >= 38
  121. && !config.enableSimulcast && config.useBundle && config.useRtcpMux) {
  122. this.peerconnection = mozRTCPeerConnection;
  123. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  124. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  125. this.pc_constraints = {};
  126. this.attachMediaStream = function (element, stream) {
  127. // srcObject is being standardized and FF will eventually
  128. // support that unprefixed. FF also supports the
  129. // "element.src = URL.createObjectURL(...)" combo, but that
  130. // will be deprecated in favour of srcObject.
  131. //
  132. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  133. // https://github.com/webrtc/samples/issues/302
  134. if(!element[0])
  135. return;
  136. element[0].mozSrcObject = stream;
  137. element[0].play();
  138. };
  139. this.getStreamID = function (stream) {
  140. var tracks = stream.getVideoTracks();
  141. if(!tracks || tracks.length == 0)
  142. {
  143. tracks = stream.getAudioTracks();
  144. }
  145. return tracks[0].id.replace(/[\{,\}]/g,"");
  146. };
  147. this.getVideoSrc = function (element) {
  148. if(!element)
  149. return null;
  150. return element.mozSrcObject;
  151. };
  152. this.setVideoSrc = function (element, src) {
  153. if(element)
  154. element.mozSrcObject = src;
  155. };
  156. RTCSessionDescription = mozRTCSessionDescription;
  157. RTCIceCandidate = mozRTCIceCandidate;
  158. } else {
  159. window.location.href = 'unsupported_browser.html';
  160. return;
  161. }
  162. } else if (navigator.webkitGetUserMedia) {
  163. console.log('This appears to be Chrome');
  164. this.peerconnection = webkitRTCPeerConnection;
  165. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  166. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  167. this.attachMediaStream = function (element, stream) {
  168. element.attr('src', webkitURL.createObjectURL(stream));
  169. };
  170. this.getStreamID = function (stream) {
  171. // streams from FF endpoints have the characters '{' and '}'
  172. // that make jQuery choke.
  173. return stream.id.replace(/[\{,\}]/g,"");
  174. };
  175. this.getVideoSrc = function (element) {
  176. if(!element)
  177. return null;
  178. return element.getAttribute("src");
  179. };
  180. this.setVideoSrc = function (element, src) {
  181. if(element)
  182. element.setAttribute("src", src);
  183. };
  184. // DTLS should now be enabled by default but..
  185. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  186. if (navigator.userAgent.indexOf('Android') != -1) {
  187. this.pc_constraints = {}; // disable DTLS on Android
  188. }
  189. if (!webkitMediaStream.prototype.getVideoTracks) {
  190. webkitMediaStream.prototype.getVideoTracks = function () {
  191. return this.videoTracks;
  192. };
  193. }
  194. if (!webkitMediaStream.prototype.getAudioTracks) {
  195. webkitMediaStream.prototype.getAudioTracks = function () {
  196. return this.audioTracks;
  197. };
  198. }
  199. }
  200. else
  201. {
  202. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  203. window.location.href = 'unsupported_browser.html';
  204. return;
  205. }
  206. }
  207. RTCUtils.prototype.getUserMediaWithConstraints = function(
  208. um, success_callback, failure_callback, resolution,bandwidth, fps,
  209. desktopStream)
  210. {
  211. currentResolution = resolution;
  212. // Check if we are running on Android device
  213. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  214. var constraints = getConstraints(
  215. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  216. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  217. var self = this;
  218. try {
  219. if (config.enableSimulcast
  220. && constraints.video
  221. && constraints.video.chromeMediaSource !== 'screen'
  222. && constraints.video.chromeMediaSource !== 'desktop'
  223. && !isAndroid
  224. // We currently do not support FF, as it doesn't have multistream support.
  225. && !isFF) {
  226. APP.simulcast.getUserMedia(constraints, function (stream) {
  227. console.log('onUserMediaSuccess');
  228. self.setAvailableDevices(um, true);
  229. success_callback(stream);
  230. },
  231. function (error) {
  232. console.warn('Failed to get access to local media. Error ', error);
  233. self.setAvailableDevices(um, false);
  234. if (failure_callback) {
  235. failure_callback(error);
  236. }
  237. });
  238. } else {
  239. this.getUserMedia(constraints,
  240. function (stream) {
  241. console.log('onUserMediaSuccess');
  242. self.setAvailableDevices(um, true);
  243. success_callback(stream);
  244. },
  245. function (error) {
  246. self.setAvailableDevices(um, false);
  247. console.warn('Failed to get access to local media. Error ',
  248. error, constraints);
  249. if (failure_callback) {
  250. failure_callback(error);
  251. }
  252. });
  253. }
  254. } catch (e) {
  255. console.error('GUM failed: ', e);
  256. if(failure_callback) {
  257. failure_callback(e);
  258. }
  259. }
  260. };
  261. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  262. var devices = {};
  263. if(um.indexOf("video") != -1)
  264. {
  265. devices.video = available;
  266. }
  267. if(um.indexOf("audio") != -1)
  268. {
  269. devices.audio = available;
  270. }
  271. this.service.setDeviceAvailability(devices);
  272. }
  273. /**
  274. * We ask for audio and video combined stream in order to get permissions and
  275. * not to ask twice.
  276. */
  277. RTCUtils.prototype.obtainAudioAndVideoPermissions = function(devices, callback, usageOptions) {
  278. var self = this;
  279. // Get AV
  280. var successCallback = function (stream) {
  281. if(callback)
  282. callback(stream, usageOptions);
  283. else
  284. self.successCallback(stream, usageOptions);
  285. };
  286. if(!devices)
  287. devices = ['audio', 'video'];
  288. var newDevices = [];
  289. if(usageOptions)
  290. for(var i = 0; i < devices.length; i++)
  291. {
  292. var device = devices[i];
  293. if(usageOptions[device] !== -1)
  294. newDevices.push(device);
  295. }
  296. else
  297. newDevices = devices;
  298. if(newDevices.length === 0)
  299. {
  300. successCallback();
  301. return;
  302. }
  303. if (navigator.mozGetUserMedia) {
  304. // With FF we can't split the stream into audio and video because FF
  305. // doesn't support media stream constructors. So, we need to get the
  306. // audio stream separately from the video stream using two distinct GUM
  307. // calls. Not very user friendly :-( but we don't have many other
  308. // options neither.
  309. //
  310. // Note that we pack those 2 streams in a single object and pass it to
  311. // the successCallback method.
  312. self.getUserMediaWithConstraints(
  313. ['audio'],
  314. function (audioStream) {
  315. self.getUserMediaWithConstraints(
  316. ['video'],
  317. function (videoStream) {
  318. return self.successCallback({
  319. audioStream: audioStream,
  320. videoStream: videoStream
  321. });
  322. },
  323. function (error) {
  324. console.error('failed to obtain video stream - stop',
  325. error);
  326. return self.successCallback(null);
  327. },
  328. config.resolution || '360');
  329. },
  330. function (error) {
  331. console.error('failed to obtain audio stream - stop',
  332. error);
  333. return self.successCallback(null);
  334. }
  335. );
  336. } else {
  337. this.getUserMediaWithConstraints(
  338. newDevices,
  339. function (stream) {
  340. successCallback(stream);
  341. },
  342. function (error) {
  343. self.errorCallback(error);
  344. },
  345. config.resolution || '360');
  346. }
  347. }
  348. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  349. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  350. // an object with two properties: audioStream, videoStream.
  351. if(stream && !navigator.mozGetUserMedia)
  352. console.log('got', stream, stream.getAudioTracks().length,
  353. stream.getVideoTracks().length);
  354. this.handleLocalStream(stream, usageOptions);
  355. };
  356. RTCUtils.prototype.errorCallback = function (error) {
  357. var self = this;
  358. console.error('failed to obtain audio/video stream - trying audio only', error);
  359. var resolution = getPreviousResolution(currentResolution);
  360. if(typeof error == "object" && error.constraintName && error.name
  361. && (error.name == "ConstraintNotSatisfiedError" ||
  362. error.name == "OverconstrainedError") &&
  363. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  364. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  365. && resolution != null)
  366. {
  367. self.getUserMediaWithConstraints(['audio', 'video'],
  368. function (stream) {
  369. return self.successCallback(stream);
  370. }, function (error) {
  371. return self.errorCallback(error);
  372. }, resolution);
  373. }
  374. else
  375. {
  376. self.getUserMediaWithConstraints(
  377. ['audio'],
  378. function (stream) {
  379. return self.successCallback(stream);
  380. },
  381. function (error) {
  382. console.error('failed to obtain audio/video stream - stop',
  383. error);
  384. return self.successCallback(null);
  385. }
  386. );
  387. }
  388. }
  389. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  390. {
  391. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  392. // an object with two properties: audioStream, videoStream.
  393. var audioStream, videoStream;
  394. if(window.webkitMediaStream)
  395. {
  396. audioStream = new webkitMediaStream();
  397. videoStream = new webkitMediaStream();
  398. if(stream) {
  399. var audioTracks = stream.getAudioTracks();
  400. for (var i = 0; i < audioTracks.length; i++) {
  401. audioStream.addTrack(audioTracks[i]);
  402. }
  403. var videoTracks = stream.getVideoTracks();
  404. for (i = 0; i < videoTracks.length; i++) {
  405. videoStream.addTrack(videoTracks[i]);
  406. }
  407. }
  408. }
  409. else
  410. {//firefox
  411. audioStream = stream.audioStream;
  412. videoStream = stream.videoStream;
  413. }
  414. var audioMuted = (usageOptions && usageOptions.audio != 1),
  415. videoMuted = (usageOptions && usageOptions.video != 1);
  416. var audioGUM = (!usageOptions || usageOptions.audio != -1),
  417. videoGUM = (!usageOptions || usageOptions.video != -1);
  418. this.service.createLocalStream(audioStream, "audio", null, null,
  419. audioMuted, audioGUM);
  420. this.service.createLocalStream(videoStream, "video", null, null,
  421. videoMuted, videoGUM);
  422. };
  423. RTCUtils.prototype.createStream = function(stream, isVideo)
  424. {
  425. var newStream = null;
  426. if(window.webkitMediaStream)
  427. {
  428. newStream = new webkitMediaStream();
  429. if(newStream)
  430. {
  431. var tracks = (isVideo? stream.getVideoTracks() : stream.getAudioTracks());
  432. for (i = 0; i < tracks.length; i++) {
  433. newStream.addTrack(tracks[i]);
  434. }
  435. }
  436. }
  437. else
  438. newStream = stream;
  439. return newStream;
  440. };
  441. module.exports = RTCUtils;